github.com/v2fly/v2ray-core/v4@v4.45.2/proxy/trojan/client.go (about)

     1  //go:build !confonly
     2  // +build !confonly
     3  
     4  package trojan
     5  
     6  import (
     7  	"context"
     8  	"time"
     9  
    10  	core "github.com/v2fly/v2ray-core/v4"
    11  	"github.com/v2fly/v2ray-core/v4/common"
    12  	"github.com/v2fly/v2ray-core/v4/common/buf"
    13  	"github.com/v2fly/v2ray-core/v4/common/net"
    14  	"github.com/v2fly/v2ray-core/v4/common/protocol"
    15  	"github.com/v2fly/v2ray-core/v4/common/retry"
    16  	"github.com/v2fly/v2ray-core/v4/common/session"
    17  	"github.com/v2fly/v2ray-core/v4/common/signal"
    18  	"github.com/v2fly/v2ray-core/v4/common/task"
    19  	"github.com/v2fly/v2ray-core/v4/features/policy"
    20  	"github.com/v2fly/v2ray-core/v4/transport"
    21  	"github.com/v2fly/v2ray-core/v4/transport/internet"
    22  )
    23  
    24  // Client is a inbound handler for trojan protocol
    25  type Client struct {
    26  	serverPicker  protocol.ServerPicker
    27  	policyManager policy.Manager
    28  }
    29  
    30  // NewClient create a new trojan client.
    31  func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) {
    32  	serverList := protocol.NewServerList()
    33  	for _, rec := range config.Server {
    34  		s, err := protocol.NewServerSpecFromPB(rec)
    35  		if err != nil {
    36  			return nil, newError("failed to parse server spec").Base(err)
    37  		}
    38  		serverList.AddServer(s)
    39  	}
    40  	if serverList.Size() == 0 {
    41  		return nil, newError("0 server")
    42  	}
    43  
    44  	v := core.MustFromContext(ctx)
    45  	client := &Client{
    46  		serverPicker:  protocol.NewRoundRobinServerPicker(serverList),
    47  		policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
    48  	}
    49  	return client, nil
    50  }
    51  
    52  // Process implements OutboundHandler.Process().
    53  func (c *Client) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
    54  	outbound := session.OutboundFromContext(ctx)
    55  	if outbound == nil || !outbound.Target.IsValid() {
    56  		return newError("target not specified")
    57  	}
    58  	destination := outbound.Target
    59  	network := destination.Network
    60  
    61  	var server *protocol.ServerSpec
    62  	var conn internet.Connection
    63  
    64  	err := retry.ExponentialBackoff(5, 100).On(func() error {
    65  		server = c.serverPicker.PickServer()
    66  		rawConn, err := dialer.Dial(ctx, server.Destination())
    67  		if err != nil {
    68  			return err
    69  		}
    70  
    71  		conn = rawConn
    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 ", server.Destination()).WriteToLog(session.ExportIDToError(ctx))
    78  
    79  	defer conn.Close()
    80  
    81  	user := server.PickUser()
    82  	account, ok := user.Account.(*MemoryAccount)
    83  	if !ok {
    84  		return newError("user account is not valid")
    85  	}
    86  
    87  	sessionPolicy := c.policyManager.ForLevel(user.Level)
    88  	ctx, cancel := context.WithCancel(ctx)
    89  	timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
    90  
    91  	postRequest := func() error {
    92  		defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
    93  
    94  		var bodyWriter buf.Writer
    95  		bufferWriter := buf.NewBufferedWriter(buf.NewWriter(conn))
    96  		connWriter := &ConnWriter{Writer: bufferWriter, Target: destination, Account: account}
    97  
    98  		if destination.Network == net.Network_UDP {
    99  			bodyWriter = &PacketWriter{Writer: connWriter, Target: destination}
   100  		} else {
   101  			bodyWriter = connWriter
   102  		}
   103  
   104  		// write some request payload to buffer
   105  		if err = buf.CopyOnceTimeout(link.Reader, bodyWriter, time.Millisecond*100); err != nil && err != buf.ErrNotTimeoutReader && err != buf.ErrReadTimeout {
   106  			return newError("failed to write A request payload").Base(err).AtWarning()
   107  		}
   108  
   109  		// Flush; bufferWriter.WriteMultiBufer now is bufferWriter.writer.WriteMultiBuffer
   110  		if err = bufferWriter.SetBuffered(false); err != nil {
   111  			return newError("failed to flush payload").Base(err).AtWarning()
   112  		}
   113  
   114  		if err = buf.Copy(link.Reader, bodyWriter, buf.UpdateActivity(timer)); err != nil {
   115  			return newError("failed to transfer request payload").Base(err).AtInfo()
   116  		}
   117  
   118  		return nil
   119  	}
   120  
   121  	getResponse := func() error {
   122  		defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
   123  
   124  		var reader buf.Reader
   125  		if network == net.Network_UDP {
   126  			reader = &PacketReader{
   127  				Reader: conn,
   128  			}
   129  		} else {
   130  			reader = buf.NewReader(conn)
   131  		}
   132  		return buf.Copy(reader, link.Writer, buf.UpdateActivity(timer))
   133  	}
   134  
   135  	responseDoneAndCloseWriter := task.OnSuccess(getResponse, task.Close(link.Writer))
   136  	if err := task.Run(ctx, postRequest, responseDoneAndCloseWriter); err != nil {
   137  		return newError("connection ends").Base(err)
   138  	}
   139  
   140  	return nil
   141  }
   142  
   143  func init() {
   144  	common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
   145  		return NewClient(ctx, config.(*ClientConfig))
   146  	}))
   147  }