github.com/moqsien/xraycore@v1.8.5/proxy/socks/client.go (about)

     1  package socks
     2  
     3  import (
     4  	"context"
     5  	"time"
     6  
     7  	"github.com/moqsien/xraycore/common"
     8  	"github.com/moqsien/xraycore/common/buf"
     9  	"github.com/moqsien/xraycore/common/net"
    10  	"github.com/moqsien/xraycore/common/protocol"
    11  	"github.com/moqsien/xraycore/common/retry"
    12  	"github.com/moqsien/xraycore/common/session"
    13  	"github.com/moqsien/xraycore/common/signal"
    14  	"github.com/moqsien/xraycore/common/task"
    15  	"github.com/moqsien/xraycore/core"
    16  	"github.com/moqsien/xraycore/features/dns"
    17  	"github.com/moqsien/xraycore/features/policy"
    18  	"github.com/moqsien/xraycore/transport"
    19  	"github.com/moqsien/xraycore/transport/internet"
    20  	"github.com/moqsien/xraycore/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  	outbound := session.OutboundFromContext(ctx)
    61  	if outbound == nil || !outbound.Target.IsValid() {
    62  		return newError("target not specified.")
    63  	}
    64  	// Destination of the inner request.
    65  	destination := outbound.Target
    66  
    67  	// Outbound server.
    68  	var server *protocol.ServerSpec
    69  	// Outbound server's destination.
    70  	var dest net.Destination
    71  	// Connection to the outbound server.
    72  	var conn stat.Connection
    73  
    74  	if err := retry.ExponentialBackoff(5, 100).On(func() error {
    75  		server = c.serverPicker.PickServer()
    76  		dest = server.Destination()
    77  		rawConn, err := dialer.Dial(ctx, dest)
    78  		if err != nil {
    79  			return err
    80  		}
    81  		conn = rawConn
    82  
    83  		return nil
    84  	}); err != nil {
    85  		return newError("failed to find an available destination").Base(err)
    86  	}
    87  
    88  	defer func() {
    89  		if err := conn.Close(); err != nil {
    90  			newError("failed to closed connection").Base(err).WriteToLog(session.ExportIDToError(ctx))
    91  		}
    92  	}()
    93  
    94  	p := c.policyManager.ForLevel(0)
    95  
    96  	request := &protocol.RequestHeader{
    97  		Version: socks5Version,
    98  		Command: protocol.RequestCommandTCP,
    99  		Address: destination.Address,
   100  		Port:    destination.Port,
   101  	}
   102  
   103  	switch c.version {
   104  	case Version_SOCKS4:
   105  		if request.Address.Family().IsDomain() {
   106  			ips, err := c.dns.LookupIP(request.Address.Domain(), dns.IPOption{
   107  				IPv4Enable: true,
   108  			})
   109  			if err != nil {
   110  				return err
   111  			} else if len(ips) == 0 {
   112  				return dns.ErrEmptyResponse
   113  			}
   114  			request.Address = net.IPAddress(ips[0])
   115  		}
   116  		fallthrough
   117  	case Version_SOCKS4A:
   118  		request.Version = socks4Version
   119  
   120  		if destination.Network == net.Network_UDP {
   121  			return newError("udp is not supported in socks4")
   122  		} else if destination.Address.Family().IsIPv6() {
   123  			return newError("ipv6 is not supported in socks4")
   124  		}
   125  	}
   126  
   127  	if destination.Network == net.Network_UDP {
   128  		request.Command = protocol.RequestCommandUDP
   129  	}
   130  
   131  	user := server.PickUser()
   132  	if user != nil {
   133  		request.User = user
   134  		p = c.policyManager.ForLevel(user.Level)
   135  	}
   136  
   137  	if err := conn.SetDeadline(time.Now().Add(p.Timeouts.Handshake)); err != nil {
   138  		newError("failed to set deadline for handshake").Base(err).WriteToLog(session.ExportIDToError(ctx))
   139  	}
   140  	udpRequest, err := ClientHandshake(request, conn, conn)
   141  	if err != nil {
   142  		return newError("failed to establish connection to server").AtWarning().Base(err)
   143  	}
   144  	if udpRequest != nil {
   145  		if udpRequest.Address == net.AnyIP || udpRequest.Address == net.AnyIPv6 {
   146  			udpRequest.Address = dest.Address
   147  		}
   148  	}
   149  
   150  	if err := conn.SetDeadline(time.Time{}); err != nil {
   151  		newError("failed to clear deadline after handshake").Base(err).WriteToLog(session.ExportIDToError(ctx))
   152  	}
   153  
   154  	var newCtx context.Context
   155  	var newCancel context.CancelFunc
   156  	if session.TimeoutOnlyFromContext(ctx) {
   157  		newCtx, newCancel = context.WithCancel(context.Background())
   158  	}
   159  
   160  	ctx, cancel := context.WithCancel(ctx)
   161  	timer := signal.CancelAfterInactivity(ctx, func() {
   162  		cancel()
   163  		if newCancel != nil {
   164  			newCancel()
   165  		}
   166  	}, p.Timeouts.ConnectionIdle)
   167  
   168  	var requestFunc func() error
   169  	var responseFunc func() error
   170  	if request.Command == protocol.RequestCommandTCP {
   171  		requestFunc = func() error {
   172  			defer timer.SetTimeout(p.Timeouts.DownlinkOnly)
   173  			return buf.Copy(link.Reader, buf.NewWriter(conn), buf.UpdateActivity(timer))
   174  		}
   175  		responseFunc = func() error {
   176  			defer timer.SetTimeout(p.Timeouts.UplinkOnly)
   177  			return buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer))
   178  		}
   179  	} else if request.Command == protocol.RequestCommandUDP {
   180  		udpConn, err := dialer.Dial(ctx, udpRequest.Destination())
   181  		if err != nil {
   182  			return newError("failed to create UDP connection").Base(err)
   183  		}
   184  		defer udpConn.Close()
   185  		requestFunc = func() error {
   186  			defer timer.SetTimeout(p.Timeouts.DownlinkOnly)
   187  			writer := &UDPWriter{Writer: udpConn, Request: request}
   188  			return buf.Copy(link.Reader, writer, buf.UpdateActivity(timer))
   189  		}
   190  		responseFunc = func() error {
   191  			defer timer.SetTimeout(p.Timeouts.UplinkOnly)
   192  			reader := &UDPReader{Reader: udpConn}
   193  			return buf.Copy(reader, link.Writer, buf.UpdateActivity(timer))
   194  		}
   195  	}
   196  
   197  	if newCtx != nil {
   198  		ctx = newCtx
   199  	}
   200  
   201  	responseDonePost := task.OnSuccess(responseFunc, task.Close(link.Writer))
   202  	if err := task.Run(ctx, requestFunc, responseDonePost); err != nil {
   203  		return newError("connection ends").Base(err)
   204  	}
   205  
   206  	return nil
   207  }
   208  
   209  func init() {
   210  	common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
   211  		return NewClient(ctx, config.(*ClientConfig))
   212  	}))
   213  }