client.go 6.1 KB

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