client.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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/policy"
  17. "github.com/v2fly/v2ray-core/v4/transport"
  18. "github.com/v2fly/v2ray-core/v4/transport/internet"
  19. )
  20. // Client is a Socks5 client.
  21. type Client struct {
  22. serverPicker protocol.ServerPicker
  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. serverList := protocol.NewServerList()
  28. for _, rec := range config.Server {
  29. s, err := protocol.NewServerSpecFromPB(rec)
  30. if err != nil {
  31. return nil, newError("failed to get server spec").Base(err)
  32. }
  33. serverList.AddServer(s)
  34. }
  35. if serverList.Size() == 0 {
  36. return nil, newError("0 target server")
  37. }
  38. v := core.MustFromContext(ctx)
  39. return &Client{
  40. serverPicker: protocol.NewRoundRobinServerPicker(serverList),
  41. policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
  42. }, nil
  43. }
  44. // Process implements proxy.Outbound.Process.
  45. func (c *Client) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
  46. outbound := session.OutboundFromContext(ctx)
  47. if outbound == nil || !outbound.Target.IsValid() {
  48. return newError("target not specified.")
  49. }
  50. // Destination of the inner request.
  51. destination := outbound.Target
  52. // Outbound server.
  53. var server *protocol.ServerSpec
  54. // Outbound server's destination.
  55. var dest net.Destination
  56. // Connection to the outbound server.
  57. var conn internet.Connection
  58. if err := retry.ExponentialBackoff(5, 100).On(func() error {
  59. server = c.serverPicker.PickServer()
  60. dest = server.Destination()
  61. rawConn, err := dialer.Dial(ctx, dest)
  62. if err != nil {
  63. return err
  64. }
  65. conn = rawConn
  66. return nil
  67. }); err != nil {
  68. return newError("failed to find an available destination").Base(err)
  69. }
  70. defer func() {
  71. if err := conn.Close(); err != nil {
  72. newError("failed to closed connection").Base(err).WriteToLog(session.ExportIDToError(ctx))
  73. }
  74. }()
  75. p := c.policyManager.ForLevel(0)
  76. request := &protocol.RequestHeader{
  77. Version: socks5Version,
  78. Command: protocol.RequestCommandTCP,
  79. Address: destination.Address,
  80. Port: destination.Port,
  81. }
  82. if destination.Network == net.Network_UDP {
  83. request.Command = protocol.RequestCommandUDP
  84. }
  85. user := server.PickUser()
  86. if user != nil {
  87. request.User = user
  88. p = c.policyManager.ForLevel(user.Level)
  89. }
  90. if err := conn.SetDeadline(time.Now().Add(p.Timeouts.Handshake)); err != nil {
  91. newError("failed to set deadline for handshake").Base(err).WriteToLog(session.ExportIDToError(ctx))
  92. }
  93. udpRequest, err := ClientHandshake(request, conn, conn)
  94. if err != nil {
  95. return newError("failed to establish connection to server").AtWarning().Base(err)
  96. }
  97. if udpRequest != nil {
  98. if udpRequest.Address == net.AnyIP || udpRequest.Address == net.AnyIPv6 {
  99. udpRequest.Address = dest.Address
  100. }
  101. }
  102. if err := conn.SetDeadline(time.Time{}); err != nil {
  103. newError("failed to clear deadline after handshake").Base(err).WriteToLog(session.ExportIDToError(ctx))
  104. }
  105. ctx, cancel := context.WithCancel(ctx)
  106. timer := signal.CancelAfterInactivity(ctx, cancel, p.Timeouts.ConnectionIdle)
  107. var requestFunc func() error
  108. var responseFunc func() error
  109. if request.Command == protocol.RequestCommandTCP {
  110. requestFunc = func() error {
  111. defer timer.SetTimeout(p.Timeouts.DownlinkOnly)
  112. return buf.Copy(link.Reader, buf.NewWriter(conn), buf.UpdateActivity(timer))
  113. }
  114. responseFunc = func() error {
  115. defer timer.SetTimeout(p.Timeouts.UplinkOnly)
  116. return buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer))
  117. }
  118. } else if request.Command == protocol.RequestCommandUDP {
  119. udpConn, err := dialer.Dial(ctx, udpRequest.Destination())
  120. if err != nil {
  121. return newError("failed to create UDP connection").Base(err)
  122. }
  123. defer udpConn.Close()
  124. requestFunc = func() error {
  125. defer timer.SetTimeout(p.Timeouts.DownlinkOnly)
  126. return buf.Copy(link.Reader, &buf.SequentialWriter{Writer: NewUDPWriter(request, udpConn)}, buf.UpdateActivity(timer))
  127. }
  128. responseFunc = func() error {
  129. defer timer.SetTimeout(p.Timeouts.UplinkOnly)
  130. reader := &UDPReader{reader: udpConn}
  131. return buf.Copy(reader, link.Writer, buf.UpdateActivity(timer))
  132. }
  133. }
  134. responseDonePost := task.OnSuccess(responseFunc, task.Close(link.Writer))
  135. if err := task.Run(ctx, requestFunc, responseDonePost); err != nil {
  136. return newError("connection ends").Base(err)
  137. }
  138. return nil
  139. }
  140. func init() {
  141. common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  142. return NewClient(ctx, config.(*ClientConfig))
  143. }))
  144. }