client.go 6.1 KB

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