github.com/imannamdari/v2ray-core/v5@v5.0.5/proxy/socks/client.go (about)

     1  package socks
     2  
     3  import (
     4  	"context"
     5  	"time"
     6  
     7  	core "github.com/imannamdari/v2ray-core/v5"
     8  	"github.com/imannamdari/v2ray-core/v5/common"
     9  	"github.com/imannamdari/v2ray-core/v5/common/buf"
    10  	"github.com/imannamdari/v2ray-core/v5/common/net"
    11  	"github.com/imannamdari/v2ray-core/v5/common/net/packetaddr"
    12  	"github.com/imannamdari/v2ray-core/v5/common/protocol"
    13  	"github.com/imannamdari/v2ray-core/v5/common/retry"
    14  	"github.com/imannamdari/v2ray-core/v5/common/session"
    15  	"github.com/imannamdari/v2ray-core/v5/common/signal"
    16  	"github.com/imannamdari/v2ray-core/v5/common/task"
    17  	"github.com/imannamdari/v2ray-core/v5/features/dns"
    18  	"github.com/imannamdari/v2ray-core/v5/features/policy"
    19  	"github.com/imannamdari/v2ray-core/v5/transport"
    20  	"github.com/imannamdari/v2ray-core/v5/transport/internet"
    21  	"github.com/imannamdari/v2ray-core/v5/transport/internet/udp"
    22  )
    23  
    24  // Client is a Socks5 client.
    25  type Client struct {
    26  	serverPicker  protocol.ServerPicker
    27  	policyManager policy.Manager
    28  	version       Version
    29  	dns           dns.Client
    30  }
    31  
    32  // NewClient create a new Socks5 client based on the given config.
    33  func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) {
    34  	serverList := protocol.NewServerList()
    35  	for _, rec := range config.Server {
    36  		s, err := protocol.NewServerSpecFromPB(rec)
    37  		if err != nil {
    38  			return nil, newError("failed to get server spec").Base(err)
    39  		}
    40  		serverList.AddServer(s)
    41  	}
    42  	if serverList.Size() == 0 {
    43  		return nil, newError("0 target server")
    44  	}
    45  
    46  	v := core.MustFromContext(ctx)
    47  	c := &Client{
    48  		serverPicker:  protocol.NewRoundRobinServerPicker(serverList),
    49  		policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
    50  		version:       config.Version,
    51  	}
    52  	if config.Version == Version_SOCKS4 {
    53  		c.dns = v.GetFeature(dns.ClientType()).(dns.Client)
    54  	}
    55  
    56  	return c, nil
    57  }
    58  
    59  // Process implements proxy.Outbound.Process.
    60  func (c *Client) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
    61  	outbound := session.OutboundFromContext(ctx)
    62  	if outbound == nil || !outbound.Target.IsValid() {
    63  		return newError("target not specified.")
    64  	}
    65  	// Destination of the inner request.
    66  	destination := outbound.Target
    67  
    68  	// Outbound server.
    69  	var server *protocol.ServerSpec
    70  	// Outbound server's destination.
    71  	var dest net.Destination
    72  	// Connection to the outbound server.
    73  	var conn internet.Connection
    74  
    75  	if err := retry.ExponentialBackoff(5, 100).On(func() error {
    76  		server = c.serverPicker.PickServer()
    77  		dest = server.Destination()
    78  		rawConn, err := dialer.Dial(ctx, dest)
    79  		if err != nil {
    80  			return err
    81  		}
    82  		conn = rawConn
    83  
    84  		return nil
    85  	}); err != nil {
    86  		return newError("failed to find an available destination").Base(err)
    87  	}
    88  
    89  	defer func() {
    90  		if err := conn.Close(); err != nil {
    91  			newError("failed to closed connection").Base(err).WriteToLog(session.ExportIDToError(ctx))
    92  		}
    93  	}()
    94  
    95  	p := c.policyManager.ForLevel(0)
    96  
    97  	request := &protocol.RequestHeader{
    98  		Version: socks5Version,
    99  		Command: protocol.RequestCommandTCP,
   100  		Address: destination.Address,
   101  		Port:    destination.Port,
   102  	}
   103  
   104  	switch c.version {
   105  	case Version_SOCKS4:
   106  		if request.Address.Family().IsDomain() {
   107  			ips, err := dns.LookupIPWithOption(c.dns, request.Address.Domain(), dns.IPOption{IPv4Enable: true, IPv6Enable: false, FakeEnable: false})
   108  			if err != nil {
   109  				return err
   110  			} else if len(ips) == 0 {
   111  				return dns.ErrEmptyResponse
   112  			}
   113  			request.Address = net.IPAddress(ips[0])
   114  		}
   115  		fallthrough
   116  	case Version_SOCKS4A:
   117  		request.Version = socks4Version
   118  
   119  		if destination.Network == net.Network_UDP {
   120  			return newError("udp is not supported in socks4")
   121  		} else if destination.Address.Family().IsIPv6() {
   122  			return newError("ipv6 is not supported in socks4")
   123  		}
   124  	}
   125  
   126  	if destination.Network == net.Network_UDP {
   127  		request.Command = protocol.RequestCommandUDP
   128  	}
   129  
   130  	user := server.PickUser()
   131  	if user != nil {
   132  		request.User = user
   133  		p = c.policyManager.ForLevel(user.Level)
   134  	}
   135  
   136  	if err := conn.SetDeadline(time.Now().Add(p.Timeouts.Handshake)); err != nil {
   137  		newError("failed to set deadline for handshake").Base(err).WriteToLog(session.ExportIDToError(ctx))
   138  	}
   139  
   140  	var udpRequest *protocol.RequestHeader
   141  	var err error
   142  	if request.Version == socks4Version {
   143  		err = ClientHandshake4(request, conn, conn)
   144  		if err != nil {
   145  			return newError("failed to establish connection to server").AtWarning().Base(err)
   146  		}
   147  	} else {
   148  		udpRequest, err = ClientHandshake(request, conn, conn)
   149  		if err != nil {
   150  			return newError("failed to establish connection to server").AtWarning().Base(err)
   151  		}
   152  	}
   153  
   154  	if udpRequest != nil {
   155  		if udpRequest.Address == net.AnyIP || udpRequest.Address == net.AnyIPv6 {
   156  			udpRequest.Address = dest.Address
   157  		}
   158  	}
   159  
   160  	if err := conn.SetDeadline(time.Time{}); err != nil {
   161  		newError("failed to clear deadline after handshake").Base(err).WriteToLog(session.ExportIDToError(ctx))
   162  	}
   163  
   164  	ctx, cancel := context.WithCancel(ctx)
   165  	timer := signal.CancelAfterInactivity(ctx, cancel, p.Timeouts.ConnectionIdle)
   166  
   167  	if packetConn, err := packetaddr.ToPacketAddrConn(link, destination); err == nil {
   168  		udpConn, err := dialer.Dial(ctx, udpRequest.Destination())
   169  		if err != nil {
   170  			return newError("failed to create UDP connection").Base(err)
   171  		}
   172  		defer udpConn.Close()
   173  
   174  		requestDone := func() error {
   175  			protocolWriter := NewUDPWriter(request, udpConn)
   176  			return udp.CopyPacketConn(protocolWriter, packetConn, udp.UpdateActivity(timer))
   177  		}
   178  		responseDone := func() error {
   179  			protocolReader := &UDPReader{
   180  				reader: udpConn,
   181  			}
   182  			return udp.CopyPacketConn(packetConn, protocolReader, udp.UpdateActivity(timer))
   183  		}
   184  		responseDoneAndCloseWriter := task.OnSuccess(responseDone, task.Close(link.Writer))
   185  		if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil {
   186  			return newError("connection ends").Base(err)
   187  		}
   188  		return nil
   189  	}
   190  
   191  	var requestFunc func() error
   192  	var responseFunc func() error
   193  	if request.Command == protocol.RequestCommandTCP {
   194  		requestFunc = func() error {
   195  			defer timer.SetTimeout(p.Timeouts.DownlinkOnly)
   196  			return buf.Copy(link.Reader, buf.NewWriter(conn), buf.UpdateActivity(timer))
   197  		}
   198  		responseFunc = func() error {
   199  			defer timer.SetTimeout(p.Timeouts.UplinkOnly)
   200  			return buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer))
   201  		}
   202  	} else if request.Command == protocol.RequestCommandUDP {
   203  		udpConn, err := dialer.Dial(ctx, udpRequest.Destination())
   204  		if err != nil {
   205  			return newError("failed to create UDP connection").Base(err)
   206  		}
   207  		defer udpConn.Close()
   208  		requestFunc = func() error {
   209  			defer timer.SetTimeout(p.Timeouts.DownlinkOnly)
   210  			return buf.Copy(link.Reader, &buf.SequentialWriter{Writer: NewUDPWriter(request, udpConn)}, buf.UpdateActivity(timer))
   211  		}
   212  		responseFunc = func() error {
   213  			defer timer.SetTimeout(p.Timeouts.UplinkOnly)
   214  			reader := &UDPReader{reader: udpConn}
   215  			return buf.Copy(reader, link.Writer, buf.UpdateActivity(timer))
   216  		}
   217  	}
   218  
   219  	responseDonePost := task.OnSuccess(responseFunc, task.Close(link.Writer))
   220  	if err := task.Run(ctx, requestFunc, responseDonePost); err != nil {
   221  		return newError("connection ends").Base(err)
   222  	}
   223  
   224  	return nil
   225  }
   226  
   227  func init() {
   228  	common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
   229  		return NewClient(ctx, config.(*ClientConfig))
   230  	}))
   231  }