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