client.go 4.1 KB

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