client.go 5.0 KB

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