github.com/xmplusdev/xray-core@v1.8.10/proxy/trojan/client.go (about)

     1  package trojan
     2  
     3  import (
     4  	"context"
     5  	"time"
     6  
     7  	"github.com/xmplusdev/xray-core/common"
     8  	"github.com/xmplusdev/xray-core/common/buf"
     9  	"github.com/xmplusdev/xray-core/common/errors"
    10  	"github.com/xmplusdev/xray-core/common/net"
    11  	"github.com/xmplusdev/xray-core/common/protocol"
    12  	"github.com/xmplusdev/xray-core/common/retry"
    13  	"github.com/xmplusdev/xray-core/common/session"
    14  	"github.com/xmplusdev/xray-core/common/signal"
    15  	"github.com/xmplusdev/xray-core/common/task"
    16  	core "github.com/xmplusdev/xray-core/core"
    17  	"github.com/xmplusdev/xray-core/features/policy"
    18  	"github.com/xmplusdev/xray-core/transport"
    19  	"github.com/xmplusdev/xray-core/transport/internet"
    20  	"github.com/xmplusdev/xray-core/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  	outbound.Name = "trojan"
    58  	inbound := session.InboundFromContext(ctx)
    59  	if inbound != nil {
    60  		inbound.SetCanSpliceCopy(3)
    61  	}
    62  	destination := outbound.Target
    63  	network := destination.Network
    64  
    65  	var server *protocol.ServerSpec
    66  	var conn stat.Connection
    67  
    68  	err := retry.ExponentialBackoff(5, 100).On(func() error {
    69  		server = c.serverPicker.PickServer()
    70  		rawConn, err := dialer.Dial(ctx, server.Destination())
    71  		if err != nil {
    72  			return err
    73  		}
    74  
    75  		conn = rawConn
    76  		return nil
    77  	})
    78  	if err != nil {
    79  		return newError("failed to find an available destination").AtWarning().Base(err)
    80  	}
    81  	newError("tunneling request to ", destination, " via ", server.Destination().NetAddr()).WriteToLog(session.ExportIDToError(ctx))
    82  
    83  	defer conn.Close()
    84  
    85  	user := server.PickUser()
    86  	account, ok := user.Account.(*MemoryAccount)
    87  	if !ok {
    88  		return newError("user account is not valid")
    89  	}
    90  
    91  	var newCtx context.Context
    92  	var newCancel context.CancelFunc
    93  	if session.TimeoutOnlyFromContext(ctx) {
    94  		newCtx, newCancel = context.WithCancel(context.Background())
    95  	}
    96  
    97  	sessionPolicy := c.policyManager.ForLevel(user.Level)
    98  	ctx, cancel := context.WithCancel(ctx)
    99  	timer := signal.CancelAfterInactivity(ctx, func() {
   100  		cancel()
   101  		if newCancel != nil {
   102  			newCancel()
   103  		}
   104  	}, sessionPolicy.Timeouts.ConnectionIdle)
   105  
   106  	postRequest := func() error {
   107  		defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
   108  
   109  		bufferWriter := buf.NewBufferedWriter(buf.NewWriter(conn))
   110  
   111  		connWriter := &ConnWriter{
   112  			Writer:  bufferWriter,
   113  			Target:  destination,
   114  			Account: account,
   115  		}
   116  
   117  		var bodyWriter buf.Writer
   118  		if destination.Network == net.Network_UDP {
   119  			bodyWriter = &PacketWriter{Writer: connWriter, Target: destination}
   120  		} else {
   121  			bodyWriter = connWriter
   122  		}
   123  
   124  		// write some request payload to buffer
   125  		if err = buf.CopyOnceTimeout(link.Reader, bodyWriter, time.Millisecond*100); err != nil && err != buf.ErrNotTimeoutReader && err != buf.ErrReadTimeout {
   126  			return newError("failed to write A request payload").Base(err).AtWarning()
   127  		}
   128  
   129  		// Flush; bufferWriter.WriteMultiBufer now is bufferWriter.writer.WriteMultiBuffer
   130  		if err = bufferWriter.SetBuffered(false); err != nil {
   131  			return newError("failed to flush payload").Base(err).AtWarning()
   132  		}
   133  
   134  		// Send header if not sent yet
   135  		if _, err = connWriter.Write([]byte{}); err != nil {
   136  			return err.(*errors.Error).AtWarning()
   137  		}
   138  
   139  		if err = buf.Copy(link.Reader, bodyWriter, buf.UpdateActivity(timer)); err != nil {
   140  			return newError("failed to transfer request payload").Base(err).AtInfo()
   141  		}
   142  
   143  		return nil
   144  	}
   145  
   146  	getResponse := func() error {
   147  		defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
   148  
   149  		var reader buf.Reader
   150  		if network == net.Network_UDP {
   151  			reader = &PacketReader{
   152  				Reader: conn,
   153  			}
   154  		} else {
   155  			reader = buf.NewReader(conn)
   156  		}
   157  		return buf.Copy(reader, link.Writer, buf.UpdateActivity(timer))
   158  	}
   159  
   160  	if newCtx != nil {
   161  		ctx = newCtx
   162  	}
   163  
   164  	responseDoneAndCloseWriter := task.OnSuccess(getResponse, task.Close(link.Writer))
   165  	if err := task.Run(ctx, postRequest, responseDoneAndCloseWriter); err != nil {
   166  		return newError("connection ends").Base(err)
   167  	}
   168  
   169  	return nil
   170  }
   171  
   172  func init() {
   173  	common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
   174  		return NewClient(ctx, config.(*ClientConfig))
   175  	}))
   176  }