github.com/v2fly/v2ray-core/v5@v5.16.2-0.20240507031116-8191faa6e095/proxy/trojan/client.go (about)

     1  package trojan
     2  
     3  import (
     4  	"context"
     5  
     6  	core "github.com/v2fly/v2ray-core/v5"
     7  	"github.com/v2fly/v2ray-core/v5/common"
     8  	"github.com/v2fly/v2ray-core/v5/common/buf"
     9  	"github.com/v2fly/v2ray-core/v5/common/net"
    10  	"github.com/v2fly/v2ray-core/v5/common/net/packetaddr"
    11  	"github.com/v2fly/v2ray-core/v5/common/protocol"
    12  	"github.com/v2fly/v2ray-core/v5/common/retry"
    13  	"github.com/v2fly/v2ray-core/v5/common/session"
    14  	"github.com/v2fly/v2ray-core/v5/common/signal"
    15  	"github.com/v2fly/v2ray-core/v5/common/task"
    16  	"github.com/v2fly/v2ray-core/v5/features/policy"
    17  	"github.com/v2fly/v2ray-core/v5/proxy"
    18  	"github.com/v2fly/v2ray-core/v5/transport"
    19  	"github.com/v2fly/v2ray-core/v5/transport/internet"
    20  	"github.com/v2fly/v2ray-core/v5/transport/internet/udp"
    21  )
    22  
    23  // Client is an 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 internet.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  	sessionPolicy := c.policyManager.ForLevel(user.Level)
    87  	ctx, cancel := context.WithCancel(ctx)
    88  	timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
    89  
    90  	if packetConn, err := packetaddr.ToPacketAddrConn(link, destination); err == nil {
    91  		postRequest := func() error {
    92  			defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
    93  
    94  			var buffer [2048]byte
    95  			n, addr, err := packetConn.ReadFrom(buffer[:])
    96  			if err != nil {
    97  				return newError("failed to read a packet").Base(err)
    98  			}
    99  			dest := net.DestinationFromAddr(addr)
   100  
   101  			bufferWriter := buf.NewBufferedWriter(buf.NewWriter(conn))
   102  			connWriter := &ConnWriter{Writer: bufferWriter, Target: dest, Account: account}
   103  			packetWriter := &PacketWriter{Writer: connWriter, Target: dest}
   104  
   105  			// write some request payload to buffer
   106  			if _, err := packetWriter.WriteTo(buffer[:n], addr); err != nil {
   107  				return newError("failed to write a request payload").Base(err)
   108  			}
   109  
   110  			// Flush; bufferWriter.WriteMultiBuffer now is bufferWriter.writer.WriteMultiBuffer
   111  			if err = bufferWriter.SetBuffered(false); err != nil {
   112  				return newError("failed to flush payload").Base(err).AtWarning()
   113  			}
   114  
   115  			return udp.CopyPacketConn(packetWriter, packetConn, udp.UpdateActivity(timer))
   116  		}
   117  
   118  		getResponse := func() error {
   119  			defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
   120  
   121  			packetReader := &PacketReader{Reader: conn}
   122  			packetConnectionReader := &PacketConnectionReader{reader: packetReader}
   123  
   124  			return udp.CopyPacketConn(packetConn, packetConnectionReader, udp.UpdateActivity(timer))
   125  		}
   126  
   127  		responseDoneAndCloseWriter := task.OnSuccess(getResponse, task.Close(link.Writer))
   128  		if err := task.Run(ctx, postRequest, responseDoneAndCloseWriter); err != nil {
   129  			return newError("connection ends").Base(err)
   130  		}
   131  
   132  		return nil
   133  	}
   134  
   135  	postRequest := func() error {
   136  		defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
   137  
   138  		var bodyWriter buf.Writer
   139  		bufferWriter := buf.NewBufferedWriter(buf.NewWriter(conn))
   140  		connWriter := &ConnWriter{Writer: bufferWriter, Target: destination, Account: account}
   141  
   142  		if destination.Network == net.Network_UDP {
   143  			bodyWriter = &PacketWriter{Writer: connWriter, Target: destination}
   144  		} else {
   145  			bodyWriter = connWriter
   146  		}
   147  
   148  		// write some request payload to buffer
   149  		err = buf.CopyOnceTimeout(link.Reader, bodyWriter, proxy.FirstPayloadTimeout)
   150  		switch err {
   151  		case buf.ErrNotTimeoutReader, buf.ErrReadTimeout:
   152  			if err := connWriter.WriteHeader(); err != nil {
   153  				return newError("failed to write request header").Base(err).AtWarning()
   154  			}
   155  		case nil:
   156  		default:
   157  			return newError("failed to write a request payload").Base(err).AtWarning()
   158  		}
   159  
   160  		// Flush; bufferWriter.WriteMultiBuffer now is bufferWriter.writer.WriteMultiBuffer
   161  		if err = bufferWriter.SetBuffered(false); err != nil {
   162  			return newError("failed to flush payload").Base(err).AtWarning()
   163  		}
   164  
   165  		if err = buf.Copy(link.Reader, bodyWriter, buf.UpdateActivity(timer)); err != nil {
   166  			return newError("failed to transfer request payload").Base(err).AtInfo()
   167  		}
   168  
   169  		return nil
   170  	}
   171  
   172  	getResponse := func() error {
   173  		defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
   174  
   175  		var reader buf.Reader
   176  		if network == net.Network_UDP {
   177  			reader = &PacketReader{
   178  				Reader: conn,
   179  			}
   180  		} else {
   181  			reader = buf.NewReader(conn)
   182  		}
   183  		return buf.Copy(reader, link.Writer, buf.UpdateActivity(timer))
   184  	}
   185  
   186  	responseDoneAndCloseWriter := task.OnSuccess(getResponse, task.Close(link.Writer))
   187  	if err := task.Run(ctx, postRequest, responseDoneAndCloseWriter); err != nil {
   188  		return newError("connection ends").Base(err)
   189  	}
   190  
   191  	return nil
   192  }
   193  
   194  func init() {
   195  	common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
   196  		return NewClient(ctx, config.(*ClientConfig))
   197  	}))
   198  }