client.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. package shadowsocks
  2. import (
  3. "context"
  4. "v2ray.com/core"
  5. "v2ray.com/core/common"
  6. "v2ray.com/core/common/buf"
  7. "v2ray.com/core/common/functions"
  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. )
  15. // Client is a inbound handler for Shadowsocks protocol
  16. type Client struct {
  17. serverPicker protocol.ServerPicker
  18. v *core.Instance
  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. v: core.MustFromContext(ctx),
  32. }
  33. return client, nil
  34. }
  35. // Process implements OutboundHandler.Process().
  36. func (c *Client) Process(ctx context.Context, link *core.Link, 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 = c.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. newError("tunneling request to ", destination, " via ", server.Destination()).WithContext(ctx).WriteToLog()
  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.(*MemoryAccount)
  76. request.User = user
  77. if account.OneTimeAuth == Account_Auto || account.OneTimeAuth == Account_Enabled {
  78. request.Option |= RequestOptionOneTimeAuth
  79. }
  80. sessionPolicy := c.v.PolicyManager().ForLevel(user.Level)
  81. ctx, cancel := context.WithCancel(ctx)
  82. timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
  83. if request.Command == protocol.RequestCommandTCP {
  84. bufferedWriter := buf.NewBufferedWriter(buf.NewWriter(conn))
  85. bodyWriter, err := WriteTCPRequest(request, bufferedWriter)
  86. if err != nil {
  87. return newError("failed to write request").Base(err)
  88. }
  89. if err := bufferedWriter.SetBuffered(false); err != nil {
  90. return err
  91. }
  92. requestDone := func() error {
  93. defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
  94. return buf.Copy(link.Reader, bodyWriter, buf.UpdateActivity(timer))
  95. }
  96. responseDone := func() error {
  97. defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
  98. responseReader, err := ReadTCPResponse(user, conn)
  99. if err != nil {
  100. return err
  101. }
  102. return buf.Copy(responseReader, link.Writer, buf.UpdateActivity(timer))
  103. }
  104. if err := signal.ExecuteParallel(ctx, requestDone, responseDone); err != nil {
  105. return newError("connection ends").Base(err)
  106. }
  107. return nil
  108. }
  109. if request.Command == protocol.RequestCommandUDP {
  110. writer := buf.NewSequentialWriter(&UDPWriter{
  111. Writer: conn,
  112. Request: request,
  113. })
  114. requestDone := func() error {
  115. defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
  116. if err := buf.Copy(link.Reader, writer, buf.UpdateActivity(timer)); err != nil {
  117. return newError("failed to transport all UDP request").Base(err)
  118. }
  119. return nil
  120. }
  121. responseDone := func() error {
  122. defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
  123. reader := &UDPReader{
  124. Reader: conn,
  125. User: user,
  126. }
  127. if err := buf.Copy(reader, link.Writer, buf.UpdateActivity(timer)); err != nil {
  128. return newError("failed to transport all UDP response").Base(err)
  129. }
  130. return nil
  131. }
  132. if err := signal.ExecuteParallel(ctx, requestDone, functions.OnSuccess(responseDone, functions.Close(link.Writer))); err != nil {
  133. return newError("connection ends").Base(err)
  134. }
  135. return nil
  136. }
  137. return nil
  138. }
  139. func init() {
  140. common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  141. return NewClient(ctx, config.(*ClientConfig))
  142. }))
  143. }