client.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. package shadowsocks
  2. import (
  3. "context"
  4. "runtime"
  5. "time"
  6. "v2ray.com/core/app/log"
  7. "v2ray.com/core/common"
  8. "v2ray.com/core/common/buf"
  9. "v2ray.com/core/common/errors"
  10. "v2ray.com/core/common/net"
  11. "v2ray.com/core/common/protocol"
  12. "v2ray.com/core/common/retry"
  13. "v2ray.com/core/common/signal"
  14. "v2ray.com/core/proxy"
  15. "v2ray.com/core/transport/internet"
  16. "v2ray.com/core/transport/ray"
  17. )
  18. // Client is a inbound handler for Shadowsocks protocol
  19. type Client struct {
  20. serverPicker protocol.ServerPicker
  21. }
  22. // NewClient create a new Shadowsocks client.
  23. func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) {
  24. serverList := protocol.NewServerList()
  25. for _, rec := range config.Server {
  26. serverList.AddServer(protocol.NewServerSpecFromPB(*rec))
  27. }
  28. client := &Client{
  29. serverPicker: protocol.NewRoundRobinServerPicker(serverList),
  30. }
  31. return client, nil
  32. }
  33. // Process implements OutboundHandler.Process().
  34. func (v *Client) Process(ctx context.Context, outboundRay ray.OutboundRay, dialer proxy.Dialer) error {
  35. destination, ok := proxy.TargetFromContext(ctx)
  36. if !ok {
  37. return errors.New("target not specified").Path("Proxy", "Shadowsocks", "Client")
  38. }
  39. network := destination.Network
  40. var server *protocol.ServerSpec
  41. var conn internet.Connection
  42. err := retry.ExponentialBackoff(5, 100).On(func() error {
  43. server = v.serverPicker.PickServer()
  44. dest := server.Destination()
  45. dest.Network = network
  46. rawConn, err := dialer.Dial(ctx, dest)
  47. if err != nil {
  48. return err
  49. }
  50. conn = rawConn
  51. return nil
  52. })
  53. if err != nil {
  54. return errors.New("failed to find an available destination").AtWarning().Base(err).Path("Proxy", "Shadowsocks", "Client")
  55. }
  56. log.Trace(errors.New("tunneling request to ", destination, " via ", server.Destination()).Path("Proxy", "Shadowsocks", "Client"))
  57. defer conn.Close()
  58. request := &protocol.RequestHeader{
  59. Version: Version,
  60. Address: destination.Address,
  61. Port: destination.Port,
  62. }
  63. if destination.Network == net.Network_TCP {
  64. request.Command = protocol.RequestCommandTCP
  65. } else {
  66. request.Command = protocol.RequestCommandUDP
  67. }
  68. user := server.PickUser()
  69. rawAccount, err := user.GetTypedAccount()
  70. if err != nil {
  71. return errors.New("failed to get a valid user account").AtWarning().Base(err).Path("Proxy", "Shadowsocks", "Client")
  72. }
  73. account := rawAccount.(*ShadowsocksAccount)
  74. request.User = user
  75. if account.OneTimeAuth == Account_Auto || account.OneTimeAuth == Account_Enabled {
  76. request.Option |= RequestOptionOneTimeAuth
  77. }
  78. ctx, timer := signal.CancelAfterInactivity(ctx, time.Minute*2)
  79. if request.Command == protocol.RequestCommandTCP {
  80. bufferedWriter := buf.NewBufferedWriter(conn)
  81. bodyWriter, err := WriteTCPRequest(request, bufferedWriter)
  82. if err != nil {
  83. return errors.New("failed to write request").Base(err).Path("Proxy", "Shadowsocks", "Client")
  84. }
  85. if err := bufferedWriter.SetBuffered(false); err != nil {
  86. return err
  87. }
  88. requestDone := signal.ExecuteAsync(func() error {
  89. mergedInput := buf.NewMergingReader(outboundRay.OutboundInput())
  90. if err := buf.PipeUntilEOF(timer, mergedInput, bodyWriter); err != nil {
  91. return err
  92. }
  93. return nil
  94. })
  95. responseDone := signal.ExecuteAsync(func() error {
  96. defer outboundRay.OutboundOutput().Close()
  97. responseReader, err := ReadTCPResponse(user, conn)
  98. if err != nil {
  99. return err
  100. }
  101. if err := buf.PipeUntilEOF(timer, responseReader, outboundRay.OutboundOutput()); err != nil {
  102. return err
  103. }
  104. return nil
  105. })
  106. if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
  107. return errors.New("connection ends").Base(err).Path("Proxy", "Shadowsocks", "Client")
  108. }
  109. return nil
  110. }
  111. if request.Command == protocol.RequestCommandUDP {
  112. writer := &UDPWriter{
  113. Writer: conn,
  114. Request: request,
  115. }
  116. requestDone := signal.ExecuteAsync(func() error {
  117. if err := buf.PipeUntilEOF(timer, outboundRay.OutboundInput(), writer); err != nil {
  118. return errors.New("failed to transport all UDP request").Base(err).Path("Proxy", "Shadowsocks", "Client")
  119. }
  120. return nil
  121. })
  122. responseDone := signal.ExecuteAsync(func() error {
  123. defer outboundRay.OutboundOutput().Close()
  124. reader := &UDPReader{
  125. Reader: conn,
  126. User: user,
  127. }
  128. if err := buf.PipeUntilEOF(timer, reader, outboundRay.OutboundOutput()); err != nil {
  129. return errors.New("failed to transport all UDP response").Base(err).Path("Proxy", "Shadowsocks", "Client")
  130. }
  131. return nil
  132. })
  133. if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
  134. return errors.New("connection ends").Base(err).Path("Proxy", "Shadowsocks", "Client")
  135. }
  136. return nil
  137. }
  138. runtime.KeepAlive(timer)
  139. return nil
  140. }
  141. func init() {
  142. common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  143. return NewClient(ctx, config.(*ClientConfig))
  144. }))
  145. }