client.go 6.1 KB

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