client.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. package socks
  2. import (
  3. "context"
  4. "time"
  5. "github.com/xtls/xray-core/common"
  6. "github.com/xtls/xray-core/common/buf"
  7. "github.com/xtls/xray-core/common/errors"
  8. "github.com/xtls/xray-core/common/net"
  9. "github.com/xtls/xray-core/common/protocol"
  10. "github.com/xtls/xray-core/common/retry"
  11. "github.com/xtls/xray-core/common/session"
  12. "github.com/xtls/xray-core/common/signal"
  13. "github.com/xtls/xray-core/common/task"
  14. "github.com/xtls/xray-core/core"
  15. "github.com/xtls/xray-core/features/policy"
  16. "github.com/xtls/xray-core/transport"
  17. "github.com/xtls/xray-core/transport/internet"
  18. "github.com/xtls/xray-core/transport/internet/stat"
  19. )
  20. // Client is a Socks5 client.
  21. type Client struct {
  22. serverPicker protocol.ServerPicker
  23. policyManager policy.Manager
  24. }
  25. // NewClient create a new Socks5 client based on the given config.
  26. func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) {
  27. serverList := protocol.NewServerList()
  28. for _, rec := range config.Server {
  29. s, err := protocol.NewServerSpecFromPB(rec)
  30. if err != nil {
  31. return nil, errors.New("failed to get server spec").Base(err)
  32. }
  33. serverList.AddServer(s)
  34. }
  35. if serverList.Size() == 0 {
  36. return nil, errors.New("0 target server")
  37. }
  38. v := core.MustFromContext(ctx)
  39. c := &Client{
  40. serverPicker: protocol.NewRoundRobinServerPicker(serverList),
  41. policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
  42. }
  43. return c, nil
  44. }
  45. // Process implements proxy.Outbound.Process.
  46. func (c *Client) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
  47. outbounds := session.OutboundsFromContext(ctx)
  48. ob := outbounds[len(outbounds)-1]
  49. if !ob.Target.IsValid() {
  50. return errors.New("target not specified.")
  51. }
  52. ob.Name = "socks"
  53. ob.CanSpliceCopy = 2
  54. // Destination of the inner request.
  55. destination := ob.Target
  56. // Outbound server.
  57. var server *protocol.ServerSpec
  58. // Outbound server's destination.
  59. var dest net.Destination
  60. // Connection to the outbound server.
  61. var conn stat.Connection
  62. if err := retry.ExponentialBackoff(5, 100).On(func() error {
  63. server = c.serverPicker.PickServer()
  64. dest = server.Destination()
  65. rawConn, err := dialer.Dial(ctx, dest)
  66. if err != nil {
  67. return err
  68. }
  69. conn = rawConn
  70. return nil
  71. }); err != nil {
  72. return errors.New("failed to find an available destination").Base(err)
  73. }
  74. defer func() {
  75. if err := conn.Close(); err != nil {
  76. errors.LogInfoInner(ctx, err, "failed to closed connection")
  77. }
  78. }()
  79. p := c.policyManager.ForLevel(0)
  80. request := &protocol.RequestHeader{
  81. Version: socks5Version,
  82. Command: protocol.RequestCommandTCP,
  83. Address: destination.Address,
  84. Port: destination.Port,
  85. }
  86. if destination.Network == net.Network_UDP {
  87. request.Command = protocol.RequestCommandUDP
  88. }
  89. user := server.PickUser()
  90. if user != nil {
  91. request.User = user
  92. p = c.policyManager.ForLevel(user.Level)
  93. }
  94. if err := conn.SetDeadline(time.Now().Add(p.Timeouts.Handshake)); err != nil {
  95. errors.LogInfoInner(ctx, err, "failed to set deadline for handshake")
  96. }
  97. udpRequest, err := ClientHandshake(request, conn, conn)
  98. if err != nil {
  99. return errors.New("failed to establish connection to server").AtWarning().Base(err)
  100. }
  101. if udpRequest != nil {
  102. if udpRequest.Address == net.AnyIP || udpRequest.Address == net.AnyIPv6 {
  103. udpRequest.Address = dest.Address
  104. }
  105. }
  106. if err := conn.SetDeadline(time.Time{}); err != nil {
  107. errors.LogInfoInner(ctx, err, "failed to clear deadline after handshake")
  108. }
  109. var newCtx context.Context
  110. var newCancel context.CancelFunc
  111. if session.TimeoutOnlyFromContext(ctx) {
  112. newCtx, newCancel = context.WithCancel(context.Background())
  113. }
  114. ctx, cancel := context.WithCancel(ctx)
  115. timer := signal.CancelAfterInactivity(ctx, func() {
  116. cancel()
  117. if newCancel != nil {
  118. newCancel()
  119. }
  120. }, p.Timeouts.ConnectionIdle)
  121. var requestFunc func() error
  122. var responseFunc func() error
  123. if request.Command == protocol.RequestCommandTCP {
  124. requestFunc = func() error {
  125. defer timer.SetTimeout(p.Timeouts.DownlinkOnly)
  126. return buf.Copy(link.Reader, buf.NewWriter(conn), buf.UpdateActivity(timer))
  127. }
  128. responseFunc = func() error {
  129. defer timer.SetTimeout(p.Timeouts.UplinkOnly)
  130. return buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer))
  131. }
  132. } else if request.Command == protocol.RequestCommandUDP {
  133. udpConn, err := dialer.Dial(ctx, udpRequest.Destination())
  134. if err != nil {
  135. return errors.New("failed to create UDP connection").Base(err)
  136. }
  137. defer udpConn.Close()
  138. requestFunc = func() error {
  139. defer timer.SetTimeout(p.Timeouts.DownlinkOnly)
  140. writer := &UDPWriter{Writer: udpConn, Request: request}
  141. return buf.Copy(link.Reader, writer, buf.UpdateActivity(timer))
  142. }
  143. responseFunc = func() error {
  144. defer timer.SetTimeout(p.Timeouts.UplinkOnly)
  145. reader := &UDPReader{Reader: udpConn}
  146. return buf.Copy(reader, link.Writer, buf.UpdateActivity(timer))
  147. }
  148. }
  149. if newCtx != nil {
  150. ctx = newCtx
  151. }
  152. responseDonePost := task.OnSuccess(responseFunc, task.Close(link.Writer))
  153. if err := task.Run(ctx, requestFunc, responseDonePost); err != nil {
  154. return errors.New("connection ends").Base(err)
  155. }
  156. return nil
  157. }
  158. func init() {
  159. common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  160. return NewClient(ctx, config.(*ClientConfig))
  161. }))
  162. }