client.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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. defer conn.Close()
  55. conn.SetReusable(false)
  56. request := &protocol.RequestHeader{
  57. Version: Version,
  58. Address: destination.Address,
  59. Port: destination.Port,
  60. }
  61. if destination.Network == net.Network_TCP {
  62. request.Command = protocol.RequestCommandTCP
  63. } else {
  64. request.Command = protocol.RequestCommandUDP
  65. }
  66. user := server.PickUser()
  67. rawAccount, err := user.GetTypedAccount()
  68. if err != nil {
  69. log.Warning("Shadowsocks|Client: Failed to get a valid user account: ", err)
  70. return err
  71. }
  72. account := rawAccount.(*ShadowsocksAccount)
  73. request.User = user
  74. if account.OneTimeAuth == Account_Auto || account.OneTimeAuth == Account_Enabled {
  75. request.Option |= RequestOptionOneTimeAuth
  76. }
  77. if request.Command == protocol.RequestCommandTCP {
  78. bufferedWriter := bufio.NewWriter(conn)
  79. bodyWriter, err := WriteTCPRequest(request, bufferedWriter)
  80. if err != nil {
  81. log.Info("Shadowsocks|Client: Failed to write request: ", err)
  82. return err
  83. }
  84. bufferedWriter.SetBuffered(false)
  85. requestDone := signal.ExecuteAsync(func() error {
  86. if err := buf.PipeUntilEOF(outboundRay.OutboundInput(), bodyWriter); err != nil {
  87. return err
  88. }
  89. return nil
  90. })
  91. responseDone := signal.ExecuteAsync(func() error {
  92. defer outboundRay.OutboundOutput().Close()
  93. responseReader, err := ReadTCPResponse(user, conn)
  94. if err != nil {
  95. return err
  96. }
  97. if err := buf.PipeUntilEOF(responseReader, outboundRay.OutboundOutput()); err != nil {
  98. return err
  99. }
  100. return nil
  101. })
  102. if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
  103. log.Info("Shadowsocks|Client: Connection ends with ", err)
  104. outboundRay.OutboundInput().CloseError()
  105. outboundRay.OutboundOutput().CloseError()
  106. return err
  107. }
  108. return nil
  109. }
  110. if request.Command == protocol.RequestCommandUDP {
  111. writer := &UDPWriter{
  112. Writer: conn,
  113. Request: request,
  114. }
  115. requestDone := signal.ExecuteAsync(func() error {
  116. if err := buf.PipeUntilEOF(outboundRay.OutboundInput(), writer); err != nil {
  117. log.Info("Shadowsocks|Client: Failed to transport all UDP request: ", err)
  118. return err
  119. }
  120. return nil
  121. })
  122. timedReader := net.NewTimeOutReader(16, conn)
  123. responseDone := signal.ExecuteAsync(func() error {
  124. defer outboundRay.OutboundOutput().Close()
  125. reader := &UDPReader{
  126. Reader: timedReader,
  127. User: user,
  128. }
  129. if err := buf.PipeUntilEOF(reader, outboundRay.OutboundOutput()); err != nil {
  130. log.Info("Shadowsocks|Client: Failed to transport all UDP response: ", err)
  131. return err
  132. }
  133. return nil
  134. })
  135. if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
  136. log.Info("Shadowsocks|Client: Connection ends with ", err)
  137. return err
  138. }
  139. return nil
  140. }
  141. return nil
  142. }
  143. func init() {
  144. common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  145. return NewClient(ctx, config.(*ClientConfig))
  146. }))
  147. }