github.com/Uhtred009/v2ray-core-1@v4.31.2+incompatible/proxy/socks/client.go (about)

     1  // +build !confonly
     2  
     3  package socks
     4  
     5  import (
     6  	"context"
     7  	"time"
     8  
     9  	"v2ray.com/core"
    10  	"v2ray.com/core/common"
    11  	"v2ray.com/core/common/buf"
    12  	"v2ray.com/core/common/net"
    13  	"v2ray.com/core/common/protocol"
    14  	"v2ray.com/core/common/retry"
    15  	"v2ray.com/core/common/session"
    16  	"v2ray.com/core/common/signal"
    17  	"v2ray.com/core/common/task"
    18  	"v2ray.com/core/features/policy"
    19  	"v2ray.com/core/transport"
    20  	"v2ray.com/core/transport/internet"
    21  )
    22  
    23  // Client is a Socks5 client.
    24  type Client struct {
    25  	serverPicker  protocol.ServerPicker
    26  	policyManager policy.Manager
    27  }
    28  
    29  // NewClient create a new Socks5 client based on the given config.
    30  func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) {
    31  	serverList := protocol.NewServerList()
    32  	for _, rec := range config.Server {
    33  		s, err := protocol.NewServerSpecFromPB(rec)
    34  		if err != nil {
    35  			return nil, newError("failed to get server spec").Base(err)
    36  		}
    37  		serverList.AddServer(s)
    38  	}
    39  	if serverList.Size() == 0 {
    40  		return nil, newError("0 target server")
    41  	}
    42  
    43  	v := core.MustFromContext(ctx)
    44  	return &Client{
    45  		serverPicker:  protocol.NewRoundRobinServerPicker(serverList),
    46  		policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
    47  	}, nil
    48  }
    49  
    50  // Process implements proxy.Outbound.Process.
    51  func (c *Client) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
    52  	outbound := session.OutboundFromContext(ctx)
    53  	if outbound == nil || !outbound.Target.IsValid() {
    54  		return newError("target not specified.")
    55  	}
    56  	destination := outbound.Target
    57  
    58  	var server *protocol.ServerSpec
    59  	var conn internet.Connection
    60  
    61  	if err := retry.ExponentialBackoff(5, 100).On(func() error {
    62  		server = c.serverPicker.PickServer()
    63  		dest := server.Destination()
    64  		rawConn, err := dialer.Dial(ctx, dest)
    65  		if err != nil {
    66  			return err
    67  		}
    68  		conn = rawConn
    69  
    70  		return nil
    71  	}); err != nil {
    72  		return newError("failed to find an available destination").Base(err)
    73  	}
    74  
    75  	defer func() {
    76  		if err := conn.Close(); err != nil {
    77  			newError("failed to closed connection").Base(err).WriteToLog(session.ExportIDToError(ctx))
    78  		}
    79  	}()
    80  
    81  	p := c.policyManager.ForLevel(0)
    82  
    83  	request := &protocol.RequestHeader{
    84  		Version: socks5Version,
    85  		Command: protocol.RequestCommandTCP,
    86  		Address: destination.Address,
    87  		Port:    destination.Port,
    88  	}
    89  	if destination.Network == net.Network_UDP {
    90  		request.Command = protocol.RequestCommandUDP
    91  	}
    92  
    93  	user := server.PickUser()
    94  	if user != nil {
    95  		request.User = user
    96  		p = c.policyManager.ForLevel(user.Level)
    97  	}
    98  
    99  	if err := conn.SetDeadline(time.Now().Add(p.Timeouts.Handshake)); err != nil {
   100  		newError("failed to set deadline for handshake").Base(err).WriteToLog(session.ExportIDToError(ctx))
   101  	}
   102  	udpRequest, err := ClientHandshake(request, conn, conn)
   103  	if err != nil {
   104  		return newError("failed to establish connection to server").AtWarning().Base(err)
   105  	}
   106  
   107  	if err := conn.SetDeadline(time.Time{}); err != nil {
   108  		newError("failed to clear deadline after handshake").Base(err).WriteToLog(session.ExportIDToError(ctx))
   109  	}
   110  
   111  	ctx, cancel := context.WithCancel(ctx)
   112  	timer := signal.CancelAfterInactivity(ctx, cancel, p.Timeouts.ConnectionIdle)
   113  
   114  	var requestFunc func() error
   115  	var responseFunc func() error
   116  	if request.Command == protocol.RequestCommandTCP {
   117  		requestFunc = func() error {
   118  			defer timer.SetTimeout(p.Timeouts.DownlinkOnly)
   119  			return buf.Copy(link.Reader, buf.NewWriter(conn), buf.UpdateActivity(timer))
   120  		}
   121  		responseFunc = func() error {
   122  			defer timer.SetTimeout(p.Timeouts.UplinkOnly)
   123  			return buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer))
   124  		}
   125  	} else if request.Command == protocol.RequestCommandUDP {
   126  		udpConn, err := dialer.Dial(ctx, udpRequest.Destination())
   127  		if err != nil {
   128  			return newError("failed to create UDP connection").Base(err)
   129  		}
   130  		defer udpConn.Close() // nolint: errcheck
   131  		requestFunc = func() error {
   132  			defer timer.SetTimeout(p.Timeouts.DownlinkOnly)
   133  			return buf.Copy(link.Reader, &buf.SequentialWriter{Writer: NewUDPWriter(request, udpConn)}, buf.UpdateActivity(timer))
   134  		}
   135  		responseFunc = func() error {
   136  			defer timer.SetTimeout(p.Timeouts.UplinkOnly)
   137  			reader := &UDPReader{reader: udpConn}
   138  			return buf.Copy(reader, link.Writer, buf.UpdateActivity(timer))
   139  		}
   140  	}
   141  
   142  	var responseDonePost = task.OnSuccess(responseFunc, task.Close(link.Writer))
   143  	if err := task.Run(ctx, requestFunc, responseDonePost); err != nil {
   144  		return newError("connection ends").Base(err)
   145  	}
   146  
   147  	return nil
   148  }
   149  
   150  func init() {
   151  	common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
   152  		return NewClient(ctx, config.(*ClientConfig))
   153  	}))
   154  }