github.com/xtls/xray-core@v1.8.12-0.20240518155711-3168d27b0bdb/proxy/socks/client.go (about)

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