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