client.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. package shadowsocks
  2. import (
  3. "context"
  4. "time"
  5. "runtime"
  6. "v2ray.com/core/common"
  7. "v2ray.com/core/common/buf"
  8. "v2ray.com/core/common/bufio"
  9. "v2ray.com/core/app/log"
  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) error {
  35. destination := proxy.DestinationFromContext(ctx)
  36. network := destination.Network
  37. var server *protocol.ServerSpec
  38. var conn internet.Connection
  39. dialer := proxy.DialerFromContext(ctx)
  40. err := retry.ExponentialBackoff(5, 100).On(func() error {
  41. server = v.serverPicker.PickServer()
  42. dest := server.Destination()
  43. dest.Network = network
  44. rawConn, err := dialer.Dial(ctx, dest)
  45. if err != nil {
  46. return err
  47. }
  48. conn = rawConn
  49. return nil
  50. })
  51. if err != nil {
  52. log.Warning("Shadowsocks|Client: Failed to find an available destination:", err)
  53. return err
  54. }
  55. log.Info("Shadowsocks|Client: Tunneling request to ", destination, " via ", server.Destination())
  56. defer conn.Close()
  57. conn.SetReusable(false)
  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. log.Warning("Shadowsocks|Client: Failed to get a valid user account: ", err)
  72. return err
  73. }
  74. account := rawAccount.(*ShadowsocksAccount)
  75. request.User = user
  76. if account.OneTimeAuth == Account_Auto || account.OneTimeAuth == Account_Enabled {
  77. request.Option |= RequestOptionOneTimeAuth
  78. }
  79. ctx, cancel := context.WithCancel(ctx)
  80. timer := signal.CancelAfterInactivity(ctx, cancel, time.Minute*2)
  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 err
  87. }
  88. bufferedWriter.SetBuffered(false)
  89. requestDone := signal.ExecuteAsync(func() error {
  90. if err := buf.PipeUntilEOF(timer, outboundRay.OutboundInput(), 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. log.Info("Shadowsocks|Client: Connection ends with ", err)
  108. return err
  109. }
  110. return nil
  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(timer, outboundRay.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. responseDone := signal.ExecuteAsync(func() error {
  125. defer outboundRay.OutboundOutput().Close()
  126. reader := &UDPReader{
  127. Reader: conn,
  128. User: user,
  129. }
  130. if err := buf.PipeUntilEOF(timer, reader, outboundRay.OutboundOutput()); err != nil {
  131. log.Info("Shadowsocks|Client: Failed to transport all UDP response: ", err)
  132. return err
  133. }
  134. return nil
  135. })
  136. if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
  137. log.Info("Shadowsocks|Client: Connection ends with ", err)
  138. return err
  139. }
  140. return nil
  141. }
  142. runtime.KeepAlive(timer)
  143. return nil
  144. }
  145. func init() {
  146. common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  147. return NewClient(ctx, config.(*ClientConfig))
  148. }))
  149. }