client.go 5.8 KB

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