client.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  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. client := &Client{
  28. serverPicker: protocol.NewRoundRobinServerPicker(serverList),
  29. }
  30. return client, nil
  31. }
  32. // Process implements OutboundHandler.Process().
  33. func (v *Client) Process(ctx context.Context, outboundRay ray.OutboundRay, dialer proxy.Dialer) error {
  34. destination, ok := proxy.TargetFromContext(ctx)
  35. if !ok {
  36. return newError("target not specified")
  37. }
  38. network := destination.Network
  39. var server *protocol.ServerSpec
  40. var conn internet.Connection
  41. err := retry.ExponentialBackoff(5, 100).On(func() error {
  42. server = v.serverPicker.PickServer()
  43. dest := server.Destination()
  44. dest.Network = network
  45. rawConn, err := dialer.Dial(ctx, dest)
  46. if err != nil {
  47. return err
  48. }
  49. conn = rawConn
  50. return nil
  51. })
  52. if err != nil {
  53. return newError("failed to find an available destination").AtWarning().Base(err)
  54. }
  55. log.Trace(newError("tunneling request to ", destination, " via ", server.Destination()))
  56. defer conn.Close()
  57. request := &protocol.RequestHeader{
  58. Version: Version,
  59. Address: destination.Address,
  60. Port: destination.Port,
  61. }
  62. if destination.Network == net.Network_TCP {
  63. request.Command = protocol.RequestCommandTCP
  64. } else {
  65. request.Command = protocol.RequestCommandUDP
  66. }
  67. user := server.PickUser()
  68. rawAccount, err := user.GetTypedAccount()
  69. if err != nil {
  70. return newError("failed to get a valid user account").AtWarning().Base(err)
  71. }
  72. account := rawAccount.(*ShadowsocksAccount)
  73. request.User = user
  74. if account.OneTimeAuth == Account_Auto || account.OneTimeAuth == Account_Enabled {
  75. request.Option |= RequestOptionOneTimeAuth
  76. }
  77. ctx, timer := signal.CancelAfterInactivity(ctx, time.Minute*2)
  78. if request.Command == protocol.RequestCommandTCP {
  79. bufferedWriter := buf.NewBufferedWriter(conn)
  80. bodyWriter, err := WriteTCPRequest(request, bufferedWriter)
  81. if err != nil {
  82. return newError("failed to write request").Base(err)
  83. }
  84. if err := bufferedWriter.SetBuffered(false); err != nil {
  85. return err
  86. }
  87. requestDone := signal.ExecuteAsync(func() error {
  88. mergedInput := buf.NewMergingReader(outboundRay.OutboundInput())
  89. if err := buf.PipeUntilEOF(timer, mergedInput, bodyWriter); err != nil {
  90. return err
  91. }
  92. return nil
  93. })
  94. responseDone := signal.ExecuteAsync(func() error {
  95. defer outboundRay.OutboundOutput().Close()
  96. responseReader, err := ReadTCPResponse(user, conn)
  97. if err != nil {
  98. return err
  99. }
  100. if err := buf.PipeUntilEOF(timer, responseReader, outboundRay.OutboundOutput()); err != nil {
  101. return err
  102. }
  103. return nil
  104. })
  105. if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
  106. return newError("connection ends").Base(err)
  107. }
  108. return nil
  109. }
  110. if request.Command == protocol.RequestCommandUDP {
  111. writer := &UDPWriter{
  112. Writer: conn,
  113. Request: request,
  114. }
  115. requestDone := signal.ExecuteAsync(func() error {
  116. if err := buf.PipeUntilEOF(timer, outboundRay.OutboundInput(), writer); err != nil {
  117. return newError("failed to transport all UDP request").Base(err)
  118. }
  119. return nil
  120. })
  121. responseDone := signal.ExecuteAsync(func() error {
  122. defer outboundRay.OutboundOutput().Close()
  123. reader := &UDPReader{
  124. Reader: conn,
  125. User: user,
  126. }
  127. if err := buf.PipeUntilEOF(timer, reader, outboundRay.OutboundOutput()); err != nil {
  128. return newError("failed to transport all UDP response").Base(err)
  129. }
  130. return nil
  131. })
  132. if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
  133. return newError("connection ends").Base(err)
  134. }
  135. return nil
  136. }
  137. runtime.KeepAlive(timer)
  138. return nil
  139. }
  140. func init() {
  141. common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  142. return NewClient(ctx, config.(*ClientConfig))
  143. }))
  144. }