client.go 4.6 KB

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