github.com/imannamdari/v2ray-core/v5@v5.0.5/proxy/trojan/client.go (about) 1 package trojan 2 3 import ( 4 "context" 5 6 core "github.com/imannamdari/v2ray-core/v5" 7 "github.com/imannamdari/v2ray-core/v5/common" 8 "github.com/imannamdari/v2ray-core/v5/common/buf" 9 "github.com/imannamdari/v2ray-core/v5/common/net" 10 "github.com/imannamdari/v2ray-core/v5/common/net/packetaddr" 11 "github.com/imannamdari/v2ray-core/v5/common/protocol" 12 "github.com/imannamdari/v2ray-core/v5/common/retry" 13 "github.com/imannamdari/v2ray-core/v5/common/session" 14 "github.com/imannamdari/v2ray-core/v5/common/signal" 15 "github.com/imannamdari/v2ray-core/v5/common/task" 16 "github.com/imannamdari/v2ray-core/v5/features/policy" 17 "github.com/imannamdari/v2ray-core/v5/proxy" 18 "github.com/imannamdari/v2ray-core/v5/transport" 19 "github.com/imannamdari/v2ray-core/v5/transport/internet" 20 "github.com/imannamdari/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 _, 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[:], 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 if err = buf.CopyOnceTimeout(link.Reader, bodyWriter, proxy.FirstPayloadTimeout); err != nil && err != buf.ErrNotTimeoutReader && err != buf.ErrReadTimeout { 150 return newError("failed to write a request payload").Base(err).AtWarning() 151 } 152 153 // Flush; bufferWriter.WriteMultiBuffer now is bufferWriter.writer.WriteMultiBuffer 154 if err = bufferWriter.SetBuffered(false); err != nil { 155 return newError("failed to flush payload").Base(err).AtWarning() 156 } 157 158 if err = buf.Copy(link.Reader, bodyWriter, buf.UpdateActivity(timer)); err != nil { 159 return newError("failed to transfer request payload").Base(err).AtInfo() 160 } 161 162 return nil 163 } 164 165 getResponse := func() error { 166 defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly) 167 168 var reader buf.Reader 169 if network == net.Network_UDP { 170 reader = &PacketReader{ 171 Reader: conn, 172 } 173 } else { 174 reader = buf.NewReader(conn) 175 } 176 return buf.Copy(reader, link.Writer, buf.UpdateActivity(timer)) 177 } 178 179 responseDoneAndCloseWriter := task.OnSuccess(getResponse, task.Close(link.Writer)) 180 if err := task.Run(ctx, postRequest, responseDoneAndCloseWriter); err != nil { 181 return newError("connection ends").Base(err) 182 } 183 184 return nil 185 } 186 187 func init() { 188 common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { 189 return NewClient(ctx, config.(*ClientConfig)) 190 })) 191 }