github.com/EagleQL/Xray-core@v1.4.3/proxy/shadowsocks/client.go (about)

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