client.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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.FromContext(ctx)
  31. if v == nil {
  32. return nil, newError("V is not in context")
  33. }
  34. return &Client{
  35. serverPicker: protocol.NewRoundRobinServerPicker(serverList),
  36. policyManager: v.PolicyManager(),
  37. }, nil
  38. }
  39. // Process implements proxy.Outbound.Process.
  40. func (c *Client) Process(ctx context.Context, ray ray.OutboundRay, dialer proxy.Dialer) error {
  41. destination, ok := proxy.TargetFromContext(ctx)
  42. if !ok {
  43. return newError("target not specified.")
  44. }
  45. var server *protocol.ServerSpec
  46. var conn internet.Connection
  47. err := retry.ExponentialBackoff(5, 100).On(func() error {
  48. server = c.serverPicker.PickServer()
  49. dest := server.Destination()
  50. rawConn, err := dialer.Dial(ctx, dest)
  51. if err != nil {
  52. return err
  53. }
  54. conn = rawConn
  55. return nil
  56. })
  57. if err != nil {
  58. return newError("failed to find an available destination").Base(err)
  59. }
  60. defer conn.Close()
  61. p := c.policyManager.ForLevel(0)
  62. request := &protocol.RequestHeader{
  63. Version: socks5Version,
  64. Command: protocol.RequestCommandTCP,
  65. Address: destination.Address,
  66. Port: destination.Port,
  67. }
  68. if destination.Network == net.Network_UDP {
  69. request.Command = protocol.RequestCommandUDP
  70. }
  71. user := server.PickUser()
  72. if user != nil {
  73. request.User = user
  74. p = c.policyManager.ForLevel(user.Level)
  75. }
  76. if err := conn.SetDeadline(time.Now().Add(p.Timeouts.Handshake)); err != nil {
  77. newError("failed to set deadline for handshake").Base(err).WriteToLog()
  78. }
  79. udpRequest, err := ClientHandshake(request, conn, conn)
  80. if err != nil {
  81. return newError("failed to establish connection to server").AtWarning().Base(err)
  82. }
  83. if err := conn.SetDeadline(time.Time{}); err != nil {
  84. newError("failed to clear deadline after handshake").Base(err).WriteToLog()
  85. }
  86. ctx, cancel := context.WithCancel(ctx)
  87. timer := signal.CancelAfterInactivity(ctx, cancel, p.Timeouts.ConnectionIdle)
  88. var requestFunc func() error
  89. var responseFunc func() error
  90. if request.Command == protocol.RequestCommandTCP {
  91. requestFunc = func() error {
  92. defer timer.SetTimeout(p.Timeouts.DownlinkOnly)
  93. return buf.Copy(ray.OutboundInput(), buf.NewWriter(conn), buf.UpdateActivity(timer))
  94. }
  95. responseFunc = func() error {
  96. defer timer.SetTimeout(p.Timeouts.UplinkOnly)
  97. return buf.Copy(buf.NewReader(conn), ray.OutboundOutput(), buf.UpdateActivity(timer))
  98. }
  99. } else if request.Command == protocol.RequestCommandUDP {
  100. udpConn, err := dialer.Dial(ctx, udpRequest.Destination())
  101. if err != nil {
  102. return newError("failed to create UDP connection").Base(err)
  103. }
  104. defer udpConn.Close()
  105. requestFunc = func() error {
  106. defer timer.SetTimeout(p.Timeouts.DownlinkOnly)
  107. return buf.Copy(ray.OutboundInput(), buf.NewSequentialWriter(NewUDPWriter(request, udpConn)), buf.UpdateActivity(timer))
  108. }
  109. responseFunc = func() error {
  110. defer timer.SetTimeout(p.Timeouts.UplinkOnly)
  111. reader := &UDPReader{reader: udpConn}
  112. return buf.Copy(reader, ray.OutboundOutput(), buf.UpdateActivity(timer))
  113. }
  114. }
  115. requestDone := signal.ExecuteAsync(requestFunc)
  116. responseDone := signal.ExecuteAsync(responseFunc)
  117. if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
  118. return newError("connection ends").Base(err)
  119. }
  120. return nil
  121. }
  122. func init() {
  123. common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  124. return NewClient(ctx, config.(*ClientConfig))
  125. }))
  126. }