client.go 5.0 KB

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