client.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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. outbounds := session.OutboundsFromContext(ctx)
  54. ob := outbounds[len(outbounds) - 1]
  55. if !ob.Target.IsValid() {
  56. return newError("target not specified.")
  57. }
  58. ob.Name = "socks"
  59. ob.CanSpliceCopy = 2
  60. // Destination of the inner request.
  61. destination := ob.Target
  62. // Outbound server.
  63. var server *protocol.ServerSpec
  64. // Outbound server's destination.
  65. var dest net.Destination
  66. // Connection to the outbound server.
  67. var conn stat.Connection
  68. if err := retry.ExponentialBackoff(5, 100).On(func() error {
  69. server = c.serverPicker.PickServer()
  70. dest = server.Destination()
  71. rawConn, err := dialer.Dial(ctx, dest)
  72. if err != nil {
  73. return err
  74. }
  75. conn = rawConn
  76. return nil
  77. }); err != nil {
  78. return newError("failed to find an available destination").Base(err)
  79. }
  80. defer func() {
  81. if err := conn.Close(); err != nil {
  82. newError("failed to closed connection").Base(err).WriteToLog(session.ExportIDToError(ctx))
  83. }
  84. }()
  85. p := c.policyManager.ForLevel(0)
  86. request := &protocol.RequestHeader{
  87. Version: socks5Version,
  88. Command: protocol.RequestCommandTCP,
  89. Address: destination.Address,
  90. Port: destination.Port,
  91. }
  92. switch c.version {
  93. case Version_SOCKS4:
  94. if request.Address.Family().IsDomain() {
  95. ips, err := c.dns.LookupIP(request.Address.Domain(), dns.IPOption{
  96. IPv4Enable: true,
  97. })
  98. if err != nil {
  99. return err
  100. } else if len(ips) == 0 {
  101. return dns.ErrEmptyResponse
  102. }
  103. request.Address = net.IPAddress(ips[0])
  104. }
  105. fallthrough
  106. case Version_SOCKS4A:
  107. request.Version = socks4Version
  108. if destination.Network == net.Network_UDP {
  109. return newError("udp is not supported in socks4")
  110. } else if destination.Address.Family().IsIPv6() {
  111. return newError("ipv6 is not supported in socks4")
  112. }
  113. }
  114. if destination.Network == net.Network_UDP {
  115. request.Command = protocol.RequestCommandUDP
  116. }
  117. user := server.PickUser()
  118. if user != nil {
  119. request.User = user
  120. p = c.policyManager.ForLevel(user.Level)
  121. }
  122. if err := conn.SetDeadline(time.Now().Add(p.Timeouts.Handshake)); err != nil {
  123. newError("failed to set deadline for handshake").Base(err).WriteToLog(session.ExportIDToError(ctx))
  124. }
  125. udpRequest, err := ClientHandshake(request, conn, conn)
  126. if err != nil {
  127. return newError("failed to establish connection to server").AtWarning().Base(err)
  128. }
  129. if udpRequest != nil {
  130. if udpRequest.Address == net.AnyIP || udpRequest.Address == net.AnyIPv6 {
  131. udpRequest.Address = dest.Address
  132. }
  133. }
  134. if err := conn.SetDeadline(time.Time{}); err != nil {
  135. newError("failed to clear deadline after handshake").Base(err).WriteToLog(session.ExportIDToError(ctx))
  136. }
  137. var newCtx context.Context
  138. var newCancel context.CancelFunc
  139. if session.TimeoutOnlyFromContext(ctx) {
  140. newCtx, newCancel = context.WithCancel(context.Background())
  141. }
  142. ctx, cancel := context.WithCancel(ctx)
  143. timer := signal.CancelAfterInactivity(ctx, func() {
  144. cancel()
  145. if newCancel != nil {
  146. newCancel()
  147. }
  148. }, p.Timeouts.ConnectionIdle)
  149. var requestFunc func() error
  150. var responseFunc func() error
  151. if request.Command == protocol.RequestCommandTCP {
  152. requestFunc = func() error {
  153. defer timer.SetTimeout(p.Timeouts.DownlinkOnly)
  154. return buf.Copy(link.Reader, buf.NewWriter(conn), buf.UpdateActivity(timer))
  155. }
  156. responseFunc = func() error {
  157. defer timer.SetTimeout(p.Timeouts.UplinkOnly)
  158. return buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer))
  159. }
  160. } else if request.Command == protocol.RequestCommandUDP {
  161. udpConn, err := dialer.Dial(ctx, udpRequest.Destination())
  162. if err != nil {
  163. return newError("failed to create UDP connection").Base(err)
  164. }
  165. defer udpConn.Close()
  166. requestFunc = func() error {
  167. defer timer.SetTimeout(p.Timeouts.DownlinkOnly)
  168. writer := &UDPWriter{Writer: udpConn, Request: request}
  169. return buf.Copy(link.Reader, writer, buf.UpdateActivity(timer))
  170. }
  171. responseFunc = func() error {
  172. defer timer.SetTimeout(p.Timeouts.UplinkOnly)
  173. reader := &UDPReader{Reader: udpConn}
  174. return buf.Copy(reader, link.Writer, buf.UpdateActivity(timer))
  175. }
  176. }
  177. if newCtx != nil {
  178. ctx = newCtx
  179. }
  180. responseDonePost := task.OnSuccess(responseFunc, task.Close(link.Writer))
  181. if err := task.Run(ctx, requestFunc, responseDonePost); err != nil {
  182. return newError("connection ends").Base(err)
  183. }
  184. return nil
  185. }
  186. func init() {
  187. common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  188. return NewClient(ctx, config.(*ClientConfig))
  189. }))
  190. }