client.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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/net"
  8. "github.com/xtls/xray-core/common/protocol"
  9. "github.com/xtls/xray-core/common/retry"
  10. "github.com/xtls/xray-core/common/session"
  11. "github.com/xtls/xray-core/common/signal"
  12. "github.com/xtls/xray-core/common/task"
  13. "github.com/xtls/xray-core/core"
  14. "github.com/xtls/xray-core/features/dns"
  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. version Version
  25. dns dns.Client
  26. }
  27. // NewClient create a new Socks5 client based on the given config.
  28. func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) {
  29. serverList := protocol.NewServerList()
  30. for _, rec := range config.Server {
  31. s, err := protocol.NewServerSpecFromPB(rec)
  32. if err != nil {
  33. return nil, newError("failed to get server spec").Base(err)
  34. }
  35. serverList.AddServer(s)
  36. }
  37. if serverList.Size() == 0 {
  38. return nil, newError("0 target server")
  39. }
  40. v := core.MustFromContext(ctx)
  41. c := &Client{
  42. serverPicker: protocol.NewRoundRobinServerPicker(serverList),
  43. policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
  44. version: config.Version,
  45. }
  46. if config.Version == Version_SOCKS4 {
  47. c.dns = v.GetFeature(dns.ClientType()).(dns.Client)
  48. }
  49. return c, nil
  50. }
  51. // Process implements proxy.Outbound.Process.
  52. func (c *Client) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
  53. outbound := session.OutboundFromContext(ctx)
  54. if outbound == nil || !outbound.Target.IsValid() {
  55. return newError("target not specified.")
  56. }
  57. outbound.Name = "socks"
  58. inbound := session.InboundFromContext(ctx)
  59. if inbound != nil {
  60. inbound.SetCanSpliceCopy(2)
  61. }
  62. // Destination of the inner request.
  63. destination := outbound.Target
  64. // Outbound server.
  65. var server *protocol.ServerSpec
  66. // Outbound server's destination.
  67. var dest net.Destination
  68. // Connection to the outbound server.
  69. var conn stat.Connection
  70. if err := retry.ExponentialBackoff(5, 100).On(func() error {
  71. server = c.serverPicker.PickServer()
  72. dest = server.Destination()
  73. rawConn, err := dialer.Dial(ctx, dest)
  74. if err != nil {
  75. return err
  76. }
  77. conn = rawConn
  78. return nil
  79. }); err != nil {
  80. return newError("failed to find an available destination").Base(err)
  81. }
  82. defer func() {
  83. if err := conn.Close(); err != nil {
  84. newError("failed to closed connection").Base(err).WriteToLog(session.ExportIDToError(ctx))
  85. }
  86. }()
  87. p := c.policyManager.ForLevel(0)
  88. request := &protocol.RequestHeader{
  89. Version: socks5Version,
  90. Command: protocol.RequestCommandTCP,
  91. Address: destination.Address,
  92. Port: destination.Port,
  93. }
  94. switch c.version {
  95. case Version_SOCKS4:
  96. if request.Address.Family().IsDomain() {
  97. ips, err := c.dns.LookupIP(request.Address.Domain(), dns.IPOption{
  98. IPv4Enable: true,
  99. })
  100. if err != nil {
  101. return err
  102. } else if len(ips) == 0 {
  103. return dns.ErrEmptyResponse
  104. }
  105. request.Address = net.IPAddress(ips[0])
  106. }
  107. fallthrough
  108. case Version_SOCKS4A:
  109. request.Version = socks4Version
  110. if destination.Network == net.Network_UDP {
  111. return newError("udp is not supported in socks4")
  112. } else if destination.Address.Family().IsIPv6() {
  113. return newError("ipv6 is not supported in socks4")
  114. }
  115. }
  116. if destination.Network == net.Network_UDP {
  117. request.Command = protocol.RequestCommandUDP
  118. }
  119. user := server.PickUser()
  120. if user != nil {
  121. request.User = user
  122. p = c.policyManager.ForLevel(user.Level)
  123. }
  124. if err := conn.SetDeadline(time.Now().Add(p.Timeouts.Handshake)); err != nil {
  125. newError("failed to set deadline for handshake").Base(err).WriteToLog(session.ExportIDToError(ctx))
  126. }
  127. udpRequest, err := ClientHandshake(request, conn, conn)
  128. if err != nil {
  129. return newError("failed to establish connection to server").AtWarning().Base(err)
  130. }
  131. if udpRequest != nil {
  132. if udpRequest.Address == net.AnyIP || udpRequest.Address == net.AnyIPv6 {
  133. udpRequest.Address = dest.Address
  134. }
  135. }
  136. if err := conn.SetDeadline(time.Time{}); err != nil {
  137. newError("failed to clear deadline after handshake").Base(err).WriteToLog(session.ExportIDToError(ctx))
  138. }
  139. var newCtx context.Context
  140. var newCancel context.CancelFunc
  141. if session.TimeoutOnlyFromContext(ctx) {
  142. newCtx, newCancel = context.WithCancel(context.Background())
  143. }
  144. ctx, cancel := context.WithCancel(ctx)
  145. timer := signal.CancelAfterInactivity(ctx, func() {
  146. cancel()
  147. if newCancel != nil {
  148. newCancel()
  149. }
  150. }, p.Timeouts.ConnectionIdle)
  151. var requestFunc func() error
  152. var responseFunc func() error
  153. if request.Command == protocol.RequestCommandTCP {
  154. requestFunc = func() error {
  155. defer timer.SetTimeout(p.Timeouts.DownlinkOnly)
  156. return buf.Copy(link.Reader, buf.NewWriter(conn), buf.UpdateActivity(timer))
  157. }
  158. responseFunc = func() error {
  159. defer timer.SetTimeout(p.Timeouts.UplinkOnly)
  160. return buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer))
  161. }
  162. } else if request.Command == protocol.RequestCommandUDP {
  163. udpConn, err := dialer.Dial(ctx, udpRequest.Destination())
  164. if err != nil {
  165. return newError("failed to create UDP connection").Base(err)
  166. }
  167. defer udpConn.Close()
  168. requestFunc = func() error {
  169. defer timer.SetTimeout(p.Timeouts.DownlinkOnly)
  170. writer := &UDPWriter{Writer: udpConn, Request: request}
  171. return buf.Copy(link.Reader, writer, buf.UpdateActivity(timer))
  172. }
  173. responseFunc = func() error {
  174. defer timer.SetTimeout(p.Timeouts.UplinkOnly)
  175. reader := &UDPReader{Reader: udpConn}
  176. return buf.Copy(reader, link.Writer, buf.UpdateActivity(timer))
  177. }
  178. }
  179. if newCtx != nil {
  180. ctx = newCtx
  181. }
  182. responseDonePost := task.OnSuccess(responseFunc, task.Close(link.Writer))
  183. if err := task.Run(ctx, requestFunc, responseDonePost); err != nil {
  184. return newError("connection ends").Base(err)
  185. }
  186. return nil
  187. }
  188. func init() {
  189. common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  190. return NewClient(ctx, config.(*ClientConfig))
  191. }))
  192. }