client.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. package shadowsocks
  2. import (
  3. "context"
  4. "runtime"
  5. "time"
  6. "v2ray.com/core/app/log"
  7. "v2ray.com/core/common"
  8. "v2ray.com/core/common/buf"
  9. "v2ray.com/core/common/bufio"
  10. "v2ray.com/core/common/errors"
  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. return errors.Base(err).Message("Shadowsocks|Client: Failed to find an available destination.")
  56. }
  57. log.Info("Shadowsocks|Client: Tunneling request to ", destination, " via ", server.Destination())
  58. defer conn.Close()
  59. conn.SetReusable(false)
  60. request := &protocol.RequestHeader{
  61. Version: Version,
  62. Address: destination.Address,
  63. Port: destination.Port,
  64. }
  65. if destination.Network == net.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 err
  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. ctx, cancel := context.WithCancel(ctx)
  82. timer := signal.CancelAfterInactivity(ctx, cancel, time.Minute*2)
  83. if request.Command == protocol.RequestCommandTCP {
  84. bufferedWriter := bufio.NewWriter(conn)
  85. bodyWriter, err := WriteTCPRequest(request, bufferedWriter)
  86. if err != nil {
  87. log.Info("Shadowsocks|Client: Failed to write request: ", err)
  88. return err
  89. }
  90. bufferedWriter.SetBuffered(false)
  91. requestDone := signal.ExecuteAsync(func() error {
  92. if err := buf.PipeUntilEOF(timer, outboundRay.OutboundInput(), bodyWriter); err != nil {
  93. return err
  94. }
  95. return nil
  96. })
  97. responseDone := signal.ExecuteAsync(func() error {
  98. defer outboundRay.OutboundOutput().Close()
  99. responseReader, err := ReadTCPResponse(user, conn)
  100. if err != nil {
  101. return err
  102. }
  103. if err := buf.PipeUntilEOF(timer, responseReader, outboundRay.OutboundOutput()); err != nil {
  104. return err
  105. }
  106. return nil
  107. })
  108. if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
  109. log.Info("Shadowsocks|Client: Connection ends with ", err)
  110. return err
  111. }
  112. return nil
  113. }
  114. if request.Command == protocol.RequestCommandUDP {
  115. writer := &UDPWriter{
  116. Writer: conn,
  117. Request: request,
  118. }
  119. requestDone := signal.ExecuteAsync(func() error {
  120. if err := buf.PipeUntilEOF(timer, outboundRay.OutboundInput(), writer); err != nil {
  121. log.Info("Shadowsocks|Client: Failed to transport all UDP request: ", err)
  122. return err
  123. }
  124. return nil
  125. })
  126. responseDone := signal.ExecuteAsync(func() error {
  127. defer outboundRay.OutboundOutput().Close()
  128. reader := &UDPReader{
  129. Reader: conn,
  130. User: user,
  131. }
  132. if err := buf.PipeUntilEOF(timer, reader, outboundRay.OutboundOutput()); err != nil {
  133. log.Info("Shadowsocks|Client: Failed to transport all UDP response: ", err)
  134. return err
  135. }
  136. return nil
  137. })
  138. if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
  139. log.Info("Shadowsocks|Client: Connection ends with ", err)
  140. return err
  141. }
  142. return nil
  143. }
  144. runtime.KeepAlive(timer)
  145. return nil
  146. }
  147. func init() {
  148. common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  149. return NewClient(ctx, config.(*ClientConfig))
  150. }))
  151. }