client.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. package shadowsocks
  2. import (
  3. "context"
  4. "v2ray.com/core/common/session"
  5. "v2ray.com/core/common/task"
  6. "v2ray.com/core"
  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. )
  16. // Client is a inbound handler for Shadowsocks protocol
  17. type Client struct {
  18. serverPicker protocol.ServerPicker
  19. v *core.Instance
  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. s, err := protocol.NewServerSpecFromPB(*rec)
  26. if err != nil {
  27. return nil, newError("failed to parse server spec").Base(err)
  28. }
  29. serverList.AddServer(s)
  30. }
  31. if serverList.Size() == 0 {
  32. return nil, newError("0 server")
  33. }
  34. client := &Client{
  35. serverPicker: protocol.NewRoundRobinServerPicker(serverList),
  36. v: core.MustFromContext(ctx),
  37. }
  38. return client, nil
  39. }
  40. // Process implements OutboundHandler.Process().
  41. func (c *Client) Process(ctx context.Context, link *core.Link, dialer proxy.Dialer) error {
  42. outbound := session.OutboundFromContext(ctx)
  43. if outbound == nil || !outbound.Target.IsValid() {
  44. return newError("target not specified")
  45. }
  46. destination := outbound.Target
  47. network := destination.Network
  48. var server *protocol.ServerSpec
  49. var conn internet.Connection
  50. err := retry.ExponentialBackoff(5, 100).On(func() error {
  51. server = c.serverPicker.PickServer()
  52. dest := server.Destination()
  53. dest.Network = network
  54. rawConn, err := dialer.Dial(ctx, dest)
  55. if err != nil {
  56. return err
  57. }
  58. conn = rawConn
  59. return nil
  60. })
  61. if err != nil {
  62. return newError("failed to find an available destination").AtWarning().Base(err)
  63. }
  64. newError("tunneling request to ", destination, " via ", server.Destination()).WriteToLog(session.ExportIDToError(ctx))
  65. defer conn.Close()
  66. request := &protocol.RequestHeader{
  67. Version: Version,
  68. Address: destination.Address,
  69. Port: destination.Port,
  70. }
  71. if destination.Network == net.Network_TCP {
  72. request.Command = protocol.RequestCommandTCP
  73. } else {
  74. request.Command = protocol.RequestCommandUDP
  75. }
  76. user := server.PickUser()
  77. account, ok := user.Account.(*MemoryAccount)
  78. if !ok {
  79. return newError("user account is not valid")
  80. }
  81. request.User = user
  82. if account.OneTimeAuth == Account_Auto || account.OneTimeAuth == Account_Enabled {
  83. request.Option |= RequestOptionOneTimeAuth
  84. }
  85. sessionPolicy := c.v.PolicyManager().ForLevel(user.Level)
  86. ctx, cancel := context.WithCancel(ctx)
  87. timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
  88. if request.Command == protocol.RequestCommandTCP {
  89. bufferedWriter := buf.NewBufferedWriter(buf.NewWriter(conn))
  90. bodyWriter, err := WriteTCPRequest(request, bufferedWriter)
  91. if err != nil {
  92. return newError("failed to write request").Base(err)
  93. }
  94. if err := bufferedWriter.SetBuffered(false); err != nil {
  95. return err
  96. }
  97. requestDone := func() error {
  98. defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
  99. return buf.Copy(link.Reader, bodyWriter, buf.UpdateActivity(timer))
  100. }
  101. responseDone := func() error {
  102. defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
  103. responseReader, err := ReadTCPResponse(user, conn)
  104. if err != nil {
  105. return err
  106. }
  107. return buf.Copy(responseReader, link.Writer, buf.UpdateActivity(timer))
  108. }
  109. var responseDoneAndCloseWriter = task.Single(responseDone, task.OnSuccess(task.Close(link.Writer)))
  110. if err := task.Run(task.WithContext(ctx), task.Parallel(requestDone, responseDoneAndCloseWriter))(); err != nil {
  111. return newError("connection ends").Base(err)
  112. }
  113. return nil
  114. }
  115. if request.Command == protocol.RequestCommandUDP {
  116. writer := &buf.SequentialWriter{Writer: &UDPWriter{
  117. Writer: conn,
  118. Request: request,
  119. }}
  120. requestDone := func() error {
  121. defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
  122. if err := buf.Copy(link.Reader, writer, buf.UpdateActivity(timer)); err != nil {
  123. return newError("failed to transport all UDP request").Base(err)
  124. }
  125. return nil
  126. }
  127. responseDone := func() error {
  128. defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
  129. reader := &UDPReader{
  130. Reader: conn,
  131. User: user,
  132. }
  133. if err := buf.Copy(reader, link.Writer, buf.UpdateActivity(timer)); err != nil {
  134. return newError("failed to transport all UDP response").Base(err)
  135. }
  136. return nil
  137. }
  138. var responseDoneAndCloseWriter = task.Single(responseDone, task.OnSuccess(task.Close(link.Writer)))
  139. if err := task.Run(task.WithContext(ctx), task.Parallel(requestDone, responseDoneAndCloseWriter))(); err != nil {
  140. return newError("connection ends").Base(err)
  141. }
  142. return nil
  143. }
  144. return nil
  145. }
  146. func init() {
  147. common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  148. return NewClient(ctx, config.(*ClientConfig))
  149. }))
  150. }