client.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. package socks
  2. import (
  3. "context"
  4. "time"
  5. "v2ray.com/core"
  6. "v2ray.com/core/common"
  7. "v2ray.com/core/common/buf"
  8. "v2ray.com/core/common/net"
  9. "v2ray.com/core/common/protocol"
  10. "v2ray.com/core/common/retry"
  11. "v2ray.com/core/common/signal"
  12. "v2ray.com/core/proxy"
  13. "v2ray.com/core/transport/internet"
  14. )
  15. // Client is a Socks5 client.
  16. type Client struct {
  17. serverPicker protocol.ServerPicker
  18. policyManager core.PolicyManager
  19. }
  20. // NewClient create a new Socks5 client based on the given config.
  21. func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) {
  22. serverList := protocol.NewServerList()
  23. for _, rec := range config.Server {
  24. serverList.AddServer(protocol.NewServerSpecFromPB(*rec))
  25. }
  26. if serverList.Size() == 0 {
  27. return nil, newError("0 target server")
  28. }
  29. v := core.MustFromContext(ctx)
  30. return &Client{
  31. serverPicker: protocol.NewRoundRobinServerPicker(serverList),
  32. policyManager: v.PolicyManager(),
  33. }, nil
  34. }
  35. // Process implements proxy.Outbound.Process.
  36. func (c *Client) Process(ctx context.Context, link *core.Link, dialer proxy.Dialer) error {
  37. destination, ok := proxy.TargetFromContext(ctx)
  38. if !ok {
  39. return newError("target not specified.")
  40. }
  41. var server *protocol.ServerSpec
  42. var conn internet.Connection
  43. if err := retry.ExponentialBackoff(5, 100).On(func() error {
  44. server = c.serverPicker.PickServer()
  45. dest := server.Destination()
  46. rawConn, err := dialer.Dial(ctx, dest)
  47. if err != nil {
  48. return err
  49. }
  50. conn = rawConn
  51. return nil
  52. }); err != nil {
  53. return newError("failed to find an available destination").Base(err)
  54. }
  55. defer func() {
  56. if err := conn.Close(); err != nil {
  57. newError("failed to closed connection").Base(err).WithContext(ctx).WriteToLog()
  58. }
  59. }()
  60. p := c.policyManager.ForLevel(0)
  61. request := &protocol.RequestHeader{
  62. Version: socks5Version,
  63. Command: protocol.RequestCommandTCP,
  64. Address: destination.Address,
  65. Port: destination.Port,
  66. }
  67. if destination.Network == net.Network_UDP {
  68. request.Command = protocol.RequestCommandUDP
  69. }
  70. user := server.PickUser()
  71. if user != nil {
  72. request.User = user
  73. p = c.policyManager.ForLevel(user.Level)
  74. }
  75. if err := conn.SetDeadline(time.Now().Add(p.Timeouts.Handshake)); err != nil {
  76. newError("failed to set deadline for handshake").Base(err).WithContext(ctx).WriteToLog()
  77. }
  78. udpRequest, err := ClientHandshake(request, conn, conn)
  79. if err != nil {
  80. return newError("failed to establish connection to server").AtWarning().Base(err)
  81. }
  82. if err := conn.SetDeadline(time.Time{}); err != nil {
  83. newError("failed to clear deadline after handshake").Base(err).WithContext(ctx).WriteToLog()
  84. }
  85. ctx, cancel := context.WithCancel(ctx)
  86. timer := signal.CancelAfterInactivity(ctx, cancel, p.Timeouts.ConnectionIdle)
  87. var requestFunc func() error
  88. var responseFunc func() error
  89. if request.Command == protocol.RequestCommandTCP {
  90. requestFunc = func() error {
  91. defer timer.SetTimeout(p.Timeouts.DownlinkOnly)
  92. return buf.Copy(link.Reader, buf.NewWriter(conn), buf.UpdateActivity(timer))
  93. }
  94. responseFunc = func() error {
  95. defer timer.SetTimeout(p.Timeouts.UplinkOnly)
  96. return buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer))
  97. }
  98. } else if request.Command == protocol.RequestCommandUDP {
  99. udpConn, err := dialer.Dial(ctx, udpRequest.Destination())
  100. if err != nil {
  101. return newError("failed to create UDP connection").Base(err)
  102. }
  103. defer udpConn.Close()
  104. requestFunc = func() error {
  105. defer timer.SetTimeout(p.Timeouts.DownlinkOnly)
  106. return buf.Copy(link.Reader, buf.NewSequentialWriter(NewUDPWriter(request, udpConn)), buf.UpdateActivity(timer))
  107. }
  108. responseFunc = func() error {
  109. defer timer.SetTimeout(p.Timeouts.UplinkOnly)
  110. reader := &UDPReader{reader: udpConn}
  111. return buf.Copy(reader, link.Writer, buf.UpdateActivity(timer))
  112. }
  113. }
  114. if err := signal.ExecuteParallel(ctx, requestFunc, responseFunc); err != nil {
  115. return newError("connection ends").Base(err)
  116. }
  117. return nil
  118. }
  119. func init() {
  120. common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  121. return NewClient(ctx, config.(*ClientConfig))
  122. }))
  123. }