client.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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. mergedInput := buf.NewMergingReader(outboundRay.OutboundInput())
  92. if err := buf.PipeUntilEOF(timer, mergedInput, 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. return newError("connection ends").Base(err)
  110. }
  111. return nil
  112. }
  113. if request.Command == protocol.RequestCommandUDP {
  114. writer := &UDPWriter{
  115. Writer: conn,
  116. Request: request,
  117. }
  118. requestDone := signal.ExecuteAsync(func() error {
  119. if err := buf.PipeUntilEOF(timer, outboundRay.OutboundInput(), writer); err != nil {
  120. return newError("failed to transport all UDP request").Base(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. return newError("failed to transport all UDP response").Base(err)
  132. }
  133. return nil
  134. })
  135. if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
  136. return newError("connection ends").Base(err)
  137. }
  138. return nil
  139. }
  140. runtime.KeepAlive(timer)
  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. }