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

     1  package shadowsocks
     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/policy"
    17  	"github.com/moqsien/xraycore/transport"
    18  	"github.com/moqsien/xraycore/transport/internet"
    19  	"github.com/moqsien/xraycore/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  	outbound := session.OutboundFromContext(ctx)
    53  	if outbound == nil || !outbound.Target.IsValid() {
    54  		return newError("target not specified")
    55  	}
    56  	destination := outbound.Target
    57  	network := destination.Network
    58  
    59  	var server *protocol.ServerSpec
    60  	var conn stat.Connection
    61  
    62  	err := retry.ExponentialBackoff(5, 100).On(func() error {
    63  		server = c.serverPicker.PickServer()
    64  		dest := server.Destination()
    65  		dest.Network = network
    66  		rawConn, err := dialer.Dial(ctx, dest)
    67  		if err != nil {
    68  			return err
    69  		}
    70  		conn = rawConn
    71  
    72  		return nil
    73  	})
    74  	if err != nil {
    75  		return newError("failed to find an available destination").AtWarning().Base(err)
    76  	}
    77  	newError("tunneling request to ", destination, " via ", network, ":", server.Destination().NetAddr()).WriteToLog(session.ExportIDToError(ctx))
    78  
    79  	defer conn.Close()
    80  
    81  	request := &protocol.RequestHeader{
    82  		Version: Version,
    83  		Address: destination.Address,
    84  		Port:    destination.Port,
    85  	}
    86  	if destination.Network == net.Network_TCP {
    87  		request.Command = protocol.RequestCommandTCP
    88  	} else {
    89  		request.Command = protocol.RequestCommandUDP
    90  	}
    91  
    92  	user := server.PickUser()
    93  	_, ok := user.Account.(*MemoryAccount)
    94  	if !ok {
    95  		return newError("user account is not valid")
    96  	}
    97  	request.User = user
    98  
    99  	var newCtx context.Context
   100  	var newCancel context.CancelFunc
   101  	if session.TimeoutOnlyFromContext(ctx) {
   102  		newCtx, newCancel = context.WithCancel(context.Background())
   103  	}
   104  
   105  	sessionPolicy := c.policyManager.ForLevel(user.Level)
   106  	ctx, cancel := context.WithCancel(ctx)
   107  	timer := signal.CancelAfterInactivity(ctx, func() {
   108  		cancel()
   109  		if newCancel != nil {
   110  			newCancel()
   111  		}
   112  	}, sessionPolicy.Timeouts.ConnectionIdle)
   113  
   114  	if newCtx != nil {
   115  		ctx = newCtx
   116  	}
   117  
   118  	if request.Command == protocol.RequestCommandTCP {
   119  		requestDone := func() error {
   120  			defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
   121  			bufferedWriter := buf.NewBufferedWriter(buf.NewWriter(conn))
   122  			bodyWriter, err := WriteTCPRequest(request, bufferedWriter)
   123  			if err != nil {
   124  				return newError("failed to write request").Base(err)
   125  			}
   126  
   127  			if err = buf.CopyOnceTimeout(link.Reader, bodyWriter, time.Millisecond*100); err != nil && err != buf.ErrNotTimeoutReader && err != buf.ErrReadTimeout {
   128  				return newError("failed to write A request payload").Base(err).AtWarning()
   129  			}
   130  
   131  			if err := bufferedWriter.SetBuffered(false); err != nil {
   132  				return err
   133  			}
   134  
   135  			return buf.Copy(link.Reader, bodyWriter, buf.UpdateActivity(timer))
   136  		}
   137  
   138  		responseDone := func() error {
   139  			defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
   140  
   141  			responseReader, err := ReadTCPResponse(user, conn)
   142  			if err != nil {
   143  				return err
   144  			}
   145  
   146  			return buf.Copy(responseReader, link.Writer, buf.UpdateActivity(timer))
   147  		}
   148  
   149  		responseDoneAndCloseWriter := task.OnSuccess(responseDone, task.Close(link.Writer))
   150  		if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil {
   151  			return newError("connection ends").Base(err)
   152  		}
   153  
   154  		return nil
   155  	}
   156  
   157  	if request.Command == protocol.RequestCommandUDP {
   158  
   159  		requestDone := func() error {
   160  			defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
   161  
   162  			writer := &UDPWriter{
   163  				Writer:  conn,
   164  				Request: request,
   165  			}
   166  
   167  			if err := buf.Copy(link.Reader, writer, buf.UpdateActivity(timer)); err != nil {
   168  				return newError("failed to transport all UDP request").Base(err)
   169  			}
   170  			return nil
   171  		}
   172  
   173  		responseDone := func() error {
   174  			defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
   175  
   176  			reader := &UDPReader{
   177  				Reader: conn,
   178  				User:   user,
   179  			}
   180  
   181  			if err := buf.Copy(reader, link.Writer, buf.UpdateActivity(timer)); err != nil {
   182  				return newError("failed to transport all UDP response").Base(err)
   183  			}
   184  			return nil
   185  		}
   186  
   187  		responseDoneAndCloseWriter := task.OnSuccess(responseDone, task.Close(link.Writer))
   188  		if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil {
   189  			return newError("connection ends").Base(err)
   190  		}
   191  
   192  		return nil
   193  	}
   194  
   195  	return nil
   196  }
   197  
   198  func init() {
   199  	common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
   200  		return NewClient(ctx, config.(*ClientConfig))
   201  	}))
   202  }