client.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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/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. }
  21. // NewClient create a new Shadowsocks client.
  22. func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) {
  23. serverList := protocol.NewServerList()
  24. for _, rec := range config.Server {
  25. serverList.AddServer(protocol.NewServerSpecFromPB(*rec))
  26. }
  27. if serverList.Size() == 0 {
  28. return nil, newError("0 server")
  29. }
  30. client := &Client{
  31. serverPicker: protocol.NewRoundRobinServerPicker(serverList),
  32. }
  33. return client, nil
  34. }
  35. // Process implements OutboundHandler.Process().
  36. func (v *Client) Process(ctx context.Context, outboundRay ray.OutboundRay, dialer proxy.Dialer) error {
  37. destination, ok := proxy.TargetFromContext(ctx)
  38. if !ok {
  39. return newError("target not specified")
  40. }
  41. network := destination.Network
  42. var server *protocol.ServerSpec
  43. var conn internet.Connection
  44. err := retry.ExponentialBackoff(5, 100).On(func() error {
  45. server = v.serverPicker.PickServer()
  46. dest := server.Destination()
  47. dest.Network = network
  48. rawConn, err := dialer.Dial(ctx, dest)
  49. if err != nil {
  50. return err
  51. }
  52. conn = rawConn
  53. return nil
  54. })
  55. if err != nil {
  56. return newError("failed to find an available destination").AtWarning().Base(err)
  57. }
  58. log.Trace(newError("tunneling request to ", destination, " via ", server.Destination()))
  59. defer conn.Close()
  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. return newError("failed to get a valid user account").AtWarning().Base(err)
  74. }
  75. account := rawAccount.(*ShadowsocksAccount)
  76. request.User = user
  77. if account.OneTimeAuth == Account_Auto || account.OneTimeAuth == Account_Enabled {
  78. request.Option |= RequestOptionOneTimeAuth
  79. }
  80. ctx, timer := signal.CancelAfterInactivity(ctx, time.Minute*2)
  81. if request.Command == protocol.RequestCommandTCP {
  82. bufferedWriter := buf.NewBufferedWriter(conn)
  83. bodyWriter, err := WriteTCPRequest(request, bufferedWriter)
  84. if err != nil {
  85. return newError("failed to write request").Base(err)
  86. }
  87. if err := bufferedWriter.SetBuffered(false); err != nil {
  88. return err
  89. }
  90. requestDone := signal.ExecuteAsync(func() error {
  91. if err := buf.Copy(timer, outboundRay.OutboundInput(), bodyWriter); err != nil {
  92. return err
  93. }
  94. return nil
  95. })
  96. responseDone := signal.ExecuteAsync(func() error {
  97. defer outboundRay.OutboundOutput().Close()
  98. responseReader, err := ReadTCPResponse(user, conn)
  99. if err != nil {
  100. return err
  101. }
  102. if err := buf.Copy(timer, responseReader, outboundRay.OutboundOutput()); err != nil {
  103. return err
  104. }
  105. return nil
  106. })
  107. if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
  108. return newError("connection ends").Base(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.Copy(timer, outboundRay.OutboundInput(), writer); err != nil {
  119. return newError("failed to transport all UDP request").Base(err)
  120. }
  121. return nil
  122. })
  123. responseDone := signal.ExecuteAsync(func() error {
  124. defer outboundRay.OutboundOutput().Close()
  125. reader := &UDPReader{
  126. Reader: conn,
  127. User: user,
  128. }
  129. if err := buf.Copy(timer, reader, outboundRay.OutboundOutput()); err != nil {
  130. return newError("failed to transport all UDP response").Base(err)
  131. }
  132. return nil
  133. })
  134. if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
  135. return newError("connection ends").Base(err)
  136. }
  137. return nil
  138. }
  139. runtime.KeepAlive(timer)
  140. return nil
  141. }
  142. func init() {
  143. common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  144. return NewClient(ctx, config.(*ClientConfig))
  145. }))
  146. }