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

     1  package trojan
     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/errors"
    10  	"github.com/moqsien/xraycore/common/net"
    11  	"github.com/moqsien/xraycore/common/protocol"
    12  	"github.com/moqsien/xraycore/common/retry"
    13  	"github.com/moqsien/xraycore/common/session"
    14  	"github.com/moqsien/xraycore/common/signal"
    15  	"github.com/moqsien/xraycore/common/task"
    16  	core "github.com/moqsien/xraycore/core"
    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 inbound handler for trojan protocol
    24  type Client struct {
    25  	serverPicker  protocol.ServerPicker
    26  	policyManager policy.Manager
    27  }
    28  
    29  // NewClient create a new trojan client.
    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 parse server spec").Base(err)
    36  		}
    37  		serverList.AddServer(s)
    38  	}
    39  	if serverList.Size() == 0 {
    40  		return nil, newError("0 server")
    41  	}
    42  
    43  	v := core.MustFromContext(ctx)
    44  	client := &Client{
    45  		serverPicker:  protocol.NewRoundRobinServerPicker(serverList),
    46  		policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
    47  	}
    48  	return client, nil
    49  }
    50  
    51  // Process implements OutboundHandler.Process().
    52  func (c *Client) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
    53  	outbound := session.OutboundFromContext(ctx)
    54  	if outbound == nil || !outbound.Target.IsValid() {
    55  		return newError("target not specified")
    56  	}
    57  	destination := outbound.Target
    58  	network := destination.Network
    59  
    60  	var server *protocol.ServerSpec
    61  	var conn stat.Connection
    62  
    63  	err := retry.ExponentialBackoff(5, 100).On(func() error {
    64  		server = c.serverPicker.PickServer()
    65  		rawConn, err := dialer.Dial(ctx, server.Destination())
    66  		if err != nil {
    67  			return err
    68  		}
    69  
    70  		conn = rawConn
    71  		return nil
    72  	})
    73  	if err != nil {
    74  		return newError("failed to find an available destination").AtWarning().Base(err)
    75  	}
    76  	newError("tunneling request to ", destination, " via ", server.Destination().NetAddr()).WriteToLog(session.ExportIDToError(ctx))
    77  
    78  	defer conn.Close()
    79  
    80  	user := server.PickUser()
    81  	account, ok := user.Account.(*MemoryAccount)
    82  	if !ok {
    83  		return newError("user account is not valid")
    84  	}
    85  
    86  	var newCtx context.Context
    87  	var newCancel context.CancelFunc
    88  	if session.TimeoutOnlyFromContext(ctx) {
    89  		newCtx, newCancel = context.WithCancel(context.Background())
    90  	}
    91  
    92  	sessionPolicy := c.policyManager.ForLevel(user.Level)
    93  	ctx, cancel := context.WithCancel(ctx)
    94  	timer := signal.CancelAfterInactivity(ctx, func() {
    95  		cancel()
    96  		if newCancel != nil {
    97  			newCancel()
    98  		}
    99  	}, sessionPolicy.Timeouts.ConnectionIdle)
   100  
   101  	postRequest := func() error {
   102  		defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
   103  
   104  		bufferWriter := buf.NewBufferedWriter(buf.NewWriter(conn))
   105  
   106  		connWriter := &ConnWriter{
   107  			Writer:  bufferWriter,
   108  			Target:  destination,
   109  			Account: account,
   110  		}
   111  
   112  		var bodyWriter buf.Writer
   113  		if destination.Network == net.Network_UDP {
   114  			bodyWriter = &PacketWriter{Writer: connWriter, Target: destination}
   115  		} else {
   116  			bodyWriter = connWriter
   117  		}
   118  
   119  		// write some request payload to buffer
   120  		if err = buf.CopyOnceTimeout(link.Reader, bodyWriter, time.Millisecond*100); err != nil && err != buf.ErrNotTimeoutReader && err != buf.ErrReadTimeout {
   121  			return newError("failed to write A request payload").Base(err).AtWarning()
   122  		}
   123  
   124  		// Flush; bufferWriter.WriteMultiBufer now is bufferWriter.writer.WriteMultiBuffer
   125  		if err = bufferWriter.SetBuffered(false); err != nil {
   126  			return newError("failed to flush payload").Base(err).AtWarning()
   127  		}
   128  
   129  		// Send header if not sent yet
   130  		if _, err = connWriter.Write([]byte{}); err != nil {
   131  			return err.(*errors.Error).AtWarning()
   132  		}
   133  
   134  		if err = buf.Copy(link.Reader, bodyWriter, buf.UpdateActivity(timer)); err != nil {
   135  			return newError("failed to transfer request payload").Base(err).AtInfo()
   136  		}
   137  
   138  		return nil
   139  	}
   140  
   141  	getResponse := func() error {
   142  		defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
   143  
   144  		var reader buf.Reader
   145  		if network == net.Network_UDP {
   146  			reader = &PacketReader{
   147  				Reader: conn,
   148  			}
   149  		} else {
   150  			reader = buf.NewReader(conn)
   151  		}
   152  		return buf.Copy(reader, link.Writer, buf.UpdateActivity(timer))
   153  	}
   154  
   155  	if newCtx != nil {
   156  		ctx = newCtx
   157  	}
   158  
   159  	responseDoneAndCloseWriter := task.OnSuccess(getResponse, task.Close(link.Writer))
   160  	if err := task.Run(ctx, postRequest, responseDoneAndCloseWriter); err != nil {
   161  		return newError("connection ends").Base(err)
   162  	}
   163  
   164  	return nil
   165  }
   166  
   167  func init() {
   168  	common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
   169  		return NewClient(ctx, config.(*ClientConfig))
   170  	}))
   171  }