client.go 4.6 KB

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