client.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. package shadowsocks
  2. import (
  3. "context"
  4. "time"
  5. "v2ray.com/core/app/log"
  6. "v2ray.com/core/common"
  7. "v2ray.com/core/common/buf"
  8. "v2ray.com/core/common/net"
  9. "v2ray.com/core/common/protocol"
  10. "v2ray.com/core/common/retry"
  11. "v2ray.com/core/common/signal"
  12. "v2ray.com/core/proxy"
  13. "v2ray.com/core/transport/internet"
  14. "v2ray.com/core/transport/ray"
  15. )
  16. // Client is a inbound handler for Shadowsocks protocol
  17. type Client struct {
  18. serverPicker protocol.ServerPicker
  19. }
  20. // NewClient create a new Shadowsocks client.
  21. func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) {
  22. serverList := protocol.NewServerList()
  23. for _, rec := range config.Server {
  24. serverList.AddServer(protocol.NewServerSpecFromPB(*rec))
  25. }
  26. if serverList.Size() == 0 {
  27. return nil, newError("0 server")
  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 newError("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 newError("failed to find an available destination").AtWarning().Base(err)
  56. }
  57. log.Trace(newError("tunneling request to ", destination, " via ", server.Destination()))
  58. defer conn.Close()
  59. request := &protocol.RequestHeader{
  60. Version: Version,
  61. Address: destination.Address,
  62. Port: destination.Port,
  63. }
  64. if destination.Network == net.Network_TCP {
  65. request.Command = protocol.RequestCommandTCP
  66. } else {
  67. request.Command = protocol.RequestCommandUDP
  68. }
  69. user := server.PickUser()
  70. rawAccount, err := user.GetTypedAccount()
  71. if err != nil {
  72. return newError("failed to get a valid user account").AtWarning().Base(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, timer := signal.CancelAfterInactivity(ctx, time.Minute*5)
  80. if request.Command == protocol.RequestCommandTCP {
  81. bufferedWriter := buf.NewBufferedWriter(conn)
  82. bodyWriter, err := WriteTCPRequest(request, bufferedWriter)
  83. if err != nil {
  84. return newError("failed to write request").Base(err)
  85. }
  86. if err := bufferedWriter.SetBuffered(false); err != nil {
  87. return err
  88. }
  89. requestDone := signal.ExecuteAsync(func() error {
  90. if err := buf.Copy(outboundRay.OutboundInput(), bodyWriter, buf.UpdateActivity(timer)); 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.Copy(responseReader, outboundRay.OutboundOutput(), buf.UpdateActivity(timer)); err != nil {
  102. return err
  103. }
  104. return nil
  105. })
  106. if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
  107. return newError("connection ends").Base(err)
  108. }
  109. return nil
  110. }
  111. if request.Command == protocol.RequestCommandUDP {
  112. writer := buf.NewSequentialWriter(&UDPWriter{
  113. Writer: conn,
  114. Request: request,
  115. })
  116. requestDone := signal.ExecuteAsync(func() error {
  117. if err := buf.Copy(outboundRay.OutboundInput(), writer, buf.UpdateActivity(timer)); err != nil {
  118. return newError("failed to transport all UDP request").Base(err)
  119. }
  120. return nil
  121. })
  122. responseDone := signal.ExecuteAsync(func() error {
  123. defer outboundRay.OutboundOutput().Close()
  124. reader := &UDPReader{
  125. Reader: conn,
  126. User: user,
  127. }
  128. if err := buf.Copy(reader, outboundRay.OutboundOutput(), buf.UpdateActivity(timer)); err != nil {
  129. return newError("failed to transport all UDP response").Base(err)
  130. }
  131. return nil
  132. })
  133. if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
  134. return newError("connection ends").Base(err)
  135. }
  136. return nil
  137. }
  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. }