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

     1  package shadowsocks
     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/policy"
    17  	"github.com/xtls/xray-core/transport"
    18  	"github.com/xtls/xray-core/transport/internet"
    19  	"github.com/xtls/xray-core/transport/internet/stat"
    20  )
    21  
    22  // Client is a inbound handler for Shadowsocks protocol
    23  type Client struct {
    24  	serverPicker  protocol.ServerPicker
    25  	policyManager policy.Manager
    26  }
    27  
    28  // NewClient create a new Shadowsocks client.
    29  func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) {
    30  	serverList := protocol.NewServerList()
    31  	for _, rec := range config.Server {
    32  		s, err := protocol.NewServerSpecFromPB(rec)
    33  		if err != nil {
    34  			return nil, newError("failed to parse server spec").Base(err)
    35  		}
    36  		serverList.AddServer(s)
    37  	}
    38  	if serverList.Size() == 0 {
    39  		return nil, newError("0 server")
    40  	}
    41  
    42  	v := core.MustFromContext(ctx)
    43  	client := &Client{
    44  		serverPicker:  protocol.NewRoundRobinServerPicker(serverList),
    45  		policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
    46  	}
    47  	return client, nil
    48  }
    49  
    50  // Process implements OutboundHandler.Process().
    51  func (c *Client) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
    52  	outbounds := session.OutboundsFromContext(ctx)
    53  	ob := outbounds[len(outbounds) - 1]
    54  	if !ob.Target.IsValid() {
    55  		return newError("target not specified")
    56  	}
    57  	ob.Name = "shadowsocks"
    58  	ob.CanSpliceCopy = 3
    59  	destination := ob.Target
    60  	network := destination.Network
    61  
    62  	var server *protocol.ServerSpec
    63  	var conn stat.Connection
    64  
    65  	err := retry.ExponentialBackoff(5, 100).On(func() error {
    66  		server = c.serverPicker.PickServer()
    67  		dest := server.Destination()
    68  		dest.Network = network
    69  		rawConn, err := dialer.Dial(ctx, dest)
    70  		if err != nil {
    71  			return err
    72  		}
    73  		conn = rawConn
    74  
    75  		return nil
    76  	})
    77  	if err != nil {
    78  		return newError("failed to find an available destination").AtWarning().Base(err)
    79  	}
    80  	newError("tunneling request to ", destination, " via ", network, ":", server.Destination().NetAddr()).WriteToLog(session.ExportIDToError(ctx))
    81  
    82  	defer conn.Close()
    83  
    84  	request := &protocol.RequestHeader{
    85  		Version: Version,
    86  		Address: destination.Address,
    87  		Port:    destination.Port,
    88  	}
    89  	if destination.Network == net.Network_TCP {
    90  		request.Command = protocol.RequestCommandTCP
    91  	} else {
    92  		request.Command = protocol.RequestCommandUDP
    93  	}
    94  
    95  	user := server.PickUser()
    96  	_, ok := user.Account.(*MemoryAccount)
    97  	if !ok {
    98  		return newError("user account is not valid")
    99  	}
   100  	request.User = user
   101  
   102  	var newCtx context.Context
   103  	var newCancel context.CancelFunc
   104  	if session.TimeoutOnlyFromContext(ctx) {
   105  		newCtx, newCancel = context.WithCancel(context.Background())
   106  	}
   107  
   108  	sessionPolicy := c.policyManager.ForLevel(user.Level)
   109  	ctx, cancel := context.WithCancel(ctx)
   110  	timer := signal.CancelAfterInactivity(ctx, func() {
   111  		cancel()
   112  		if newCancel != nil {
   113  			newCancel()
   114  		}
   115  	}, sessionPolicy.Timeouts.ConnectionIdle)
   116  
   117  	if newCtx != nil {
   118  		ctx = newCtx
   119  	}
   120  
   121  	if request.Command == protocol.RequestCommandTCP {
   122  		requestDone := func() error {
   123  			defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
   124  			bufferedWriter := buf.NewBufferedWriter(buf.NewWriter(conn))
   125  			bodyWriter, err := WriteTCPRequest(request, bufferedWriter)
   126  			if err != nil {
   127  				return newError("failed to write request").Base(err)
   128  			}
   129  
   130  			if err = buf.CopyOnceTimeout(link.Reader, bodyWriter, time.Millisecond*100); err != nil && err != buf.ErrNotTimeoutReader && err != buf.ErrReadTimeout {
   131  				return newError("failed to write A request payload").Base(err).AtWarning()
   132  			}
   133  
   134  			if err := bufferedWriter.SetBuffered(false); err != nil {
   135  				return err
   136  			}
   137  
   138  			return buf.Copy(link.Reader, bodyWriter, buf.UpdateActivity(timer))
   139  		}
   140  
   141  		responseDone := func() error {
   142  			defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
   143  
   144  			responseReader, err := ReadTCPResponse(user, conn)
   145  			if err != nil {
   146  				return err
   147  			}
   148  
   149  			return buf.Copy(responseReader, link.Writer, buf.UpdateActivity(timer))
   150  		}
   151  
   152  		responseDoneAndCloseWriter := task.OnSuccess(responseDone, task.Close(link.Writer))
   153  		if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil {
   154  			return newError("connection ends").Base(err)
   155  		}
   156  
   157  		return nil
   158  	}
   159  
   160  	if request.Command == protocol.RequestCommandUDP {
   161  
   162  		requestDone := func() error {
   163  			defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
   164  
   165  			writer := &UDPWriter{
   166  				Writer:  conn,
   167  				Request: request,
   168  			}
   169  
   170  			if err := buf.Copy(link.Reader, writer, buf.UpdateActivity(timer)); err != nil {
   171  				return newError("failed to transport all UDP request").Base(err)
   172  			}
   173  			return nil
   174  		}
   175  
   176  		responseDone := func() error {
   177  			defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
   178  
   179  			reader := &UDPReader{
   180  				Reader: conn,
   181  				User:   user,
   182  			}
   183  
   184  			if err := buf.Copy(reader, link.Writer, buf.UpdateActivity(timer)); err != nil {
   185  				return newError("failed to transport all UDP response").Base(err)
   186  			}
   187  			return nil
   188  		}
   189  
   190  		responseDoneAndCloseWriter := task.OnSuccess(responseDone, task.Close(link.Writer))
   191  		if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil {
   192  			return newError("connection ends").Base(err)
   193  		}
   194  
   195  		return nil
   196  	}
   197  
   198  	return nil
   199  }
   200  
   201  func init() {
   202  	common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
   203  		return NewClient(ctx, config.(*ClientConfig))
   204  	}))
   205  }