client.go 4.6 KB

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