client.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. package socks
  2. import (
  3. "context"
  4. "runtime"
  5. "time"
  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. }
  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. return &Client{
  30. serverPicker: protocol.NewRoundRobinServerPicker(serverList),
  31. }, nil
  32. }
  33. // Process implements proxy.Outbound.Process.
  34. func (c *Client) Process(ctx context.Context, ray ray.OutboundRay, dialer proxy.Dialer) error {
  35. destination, ok := proxy.TargetFromContext(ctx)
  36. if !ok {
  37. return newError("target not specified.")
  38. }
  39. var server *protocol.ServerSpec
  40. var conn internet.Connection
  41. err := retry.ExponentialBackoff(5, 100).On(func() error {
  42. server = c.serverPicker.PickServer()
  43. dest := server.Destination()
  44. rawConn, err := dialer.Dial(ctx, dest)
  45. if err != nil {
  46. return err
  47. }
  48. conn = rawConn
  49. return nil
  50. })
  51. if err != nil {
  52. return newError("failed to find an available destination").Base(err)
  53. }
  54. defer conn.Close()
  55. request := &protocol.RequestHeader{
  56. Version: socks5Version,
  57. Command: protocol.RequestCommandTCP,
  58. Address: destination.Address,
  59. Port: destination.Port,
  60. }
  61. if destination.Network == net.Network_UDP {
  62. request.Command = protocol.RequestCommandUDP
  63. }
  64. user := server.PickUser()
  65. if user != nil {
  66. request.User = user
  67. }
  68. udpRequest, err := ClientHandshake(request, conn, conn)
  69. if err != nil {
  70. return newError("failed to establish connection to server").AtWarning().Base(err)
  71. }
  72. ctx, timer := signal.CancelAfterInactivity(ctx, time.Minute*2)
  73. var requestFunc func() error
  74. var responseFunc func() error
  75. if request.Command == protocol.RequestCommandTCP {
  76. requestFunc = func() error {
  77. return buf.PipeUntilEOF(timer, ray.OutboundInput(), buf.NewWriter(conn))
  78. }
  79. responseFunc = func() error {
  80. defer ray.OutboundOutput().Close()
  81. return buf.PipeUntilEOF(timer, buf.NewReader(conn), ray.OutboundOutput())
  82. }
  83. } else if request.Command == protocol.RequestCommandUDP {
  84. udpConn, err := dialer.Dial(ctx, udpRequest.Destination())
  85. if err != nil {
  86. return newError("failed to create UDP connection").Base(err)
  87. }
  88. defer udpConn.Close()
  89. requestFunc = func() error {
  90. return buf.PipeUntilEOF(timer, ray.OutboundInput(), &UDPWriter{request: request, writer: udpConn})
  91. }
  92. responseFunc = func() error {
  93. defer ray.OutboundOutput().Close()
  94. reader := &UDPReader{reader: udpConn}
  95. return buf.PipeUntilEOF(timer, reader, ray.OutboundOutput())
  96. }
  97. }
  98. requestDone := signal.ExecuteAsync(requestFunc)
  99. responseDone := signal.ExecuteAsync(responseFunc)
  100. if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
  101. return newError("connection ends").Base(err)
  102. }
  103. runtime.KeepAlive(timer)
  104. return nil
  105. }
  106. func init() {
  107. common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  108. return NewClient(ctx, config.(*ClientConfig))
  109. }))
  110. }