github.com/Uhtred009/v2ray-core-1@v4.31.2+incompatible/proxy/vless/outbound/outbound.go (about) 1 // +build !confonly 2 3 package outbound 4 5 //go:generate go run v2ray.com/core/common/errors/errorgen 6 7 import ( 8 "context" 9 "time" 10 11 "v2ray.com/core" 12 "v2ray.com/core/common" 13 "v2ray.com/core/common/buf" 14 "v2ray.com/core/common/net" 15 "v2ray.com/core/common/platform" 16 "v2ray.com/core/common/protocol" 17 "v2ray.com/core/common/retry" 18 "v2ray.com/core/common/session" 19 "v2ray.com/core/common/signal" 20 "v2ray.com/core/common/task" 21 "v2ray.com/core/features/policy" 22 "v2ray.com/core/proxy/vless" 23 "v2ray.com/core/proxy/vless/encoding" 24 "v2ray.com/core/transport" 25 "v2ray.com/core/transport/internet" 26 "v2ray.com/core/transport/internet/xtls" 27 ) 28 29 var ( 30 xtls_show = false 31 ) 32 33 func init() { 34 common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { 35 return New(ctx, config.(*Config)) 36 })) 37 38 const defaultFlagValue = "NOT_DEFINED_AT_ALL" 39 40 xtlsShow := platform.NewEnvFlag("v2ray.vless.xtls.show").GetValue(func() string { return defaultFlagValue }) 41 if xtlsShow == "true" { 42 xtls_show = true 43 } 44 } 45 46 // Handler is an outbound connection handler for VLess protocol. 47 type Handler struct { 48 serverList *protocol.ServerList 49 serverPicker protocol.ServerPicker 50 policyManager policy.Manager 51 } 52 53 // New creates a new VLess outbound handler. 54 func New(ctx context.Context, config *Config) (*Handler, error) { 55 56 serverList := protocol.NewServerList() 57 for _, rec := range config.Vnext { 58 s, err := protocol.NewServerSpecFromPB(rec) 59 if err != nil { 60 return nil, newError("failed to parse server spec").Base(err).AtError() 61 } 62 serverList.AddServer(s) 63 } 64 65 v := core.MustFromContext(ctx) 66 handler := &Handler{ 67 serverList: serverList, 68 serverPicker: protocol.NewRoundRobinServerPicker(serverList), 69 policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager), 70 } 71 72 return handler, nil 73 } 74 75 // Process implements proxy.Outbound.Process(). 76 func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error { 77 78 var rec *protocol.ServerSpec 79 var conn internet.Connection 80 81 if err := retry.ExponentialBackoff(5, 200).On(func() error { 82 rec = h.serverPicker.PickServer() 83 var err error 84 conn, err = dialer.Dial(ctx, rec.Destination()) 85 if err != nil { 86 return err 87 } 88 return nil 89 }); err != nil { 90 return newError("failed to find an available destination").Base(err).AtWarning() 91 } 92 defer conn.Close() // nolint: errcheck 93 94 iConn := conn 95 if statConn, ok := iConn.(*internet.StatCouterConnection); ok { 96 iConn = statConn.Connection 97 } 98 99 outbound := session.OutboundFromContext(ctx) 100 if outbound == nil || !outbound.Target.IsValid() { 101 return newError("target not specified").AtError() 102 } 103 104 target := outbound.Target 105 newError("tunneling request to ", target, " via ", rec.Destination()).AtInfo().WriteToLog(session.ExportIDToError(ctx)) 106 107 command := protocol.RequestCommandTCP 108 if target.Network == net.Network_UDP { 109 command = protocol.RequestCommandUDP 110 } 111 if target.Address.Family().IsDomain() && target.Address.Domain() == "v1.mux.cool" { 112 command = protocol.RequestCommandMux 113 } 114 115 request := &protocol.RequestHeader{ 116 Version: encoding.Version, 117 User: rec.PickUser(), 118 Command: command, 119 Address: target.Address, 120 Port: target.Port, 121 } 122 123 account := request.User.Account.(*vless.MemoryAccount) 124 125 requestAddons := &encoding.Addons{ 126 Flow: account.Flow, 127 } 128 129 allowUDP443 := false 130 switch requestAddons.Flow { 131 case vless.XRO + "-udp443", vless.XRD + "-udp443": 132 allowUDP443 = true 133 requestAddons.Flow = requestAddons.Flow[:16] 134 fallthrough 135 case vless.XRO, vless.XRD: 136 switch request.Command { 137 case protocol.RequestCommandMux: 138 return newError(requestAddons.Flow + " doesn't support Mux").AtWarning() 139 case protocol.RequestCommandUDP: 140 if !allowUDP443 && request.Port == 443 { 141 return newError(requestAddons.Flow + " stopped UDP/443").AtInfo() 142 } 143 requestAddons.Flow = "" 144 case protocol.RequestCommandTCP: 145 if xtlsConn, ok := iConn.(*xtls.Conn); ok { 146 xtlsConn.RPRX = true 147 xtlsConn.SHOW = xtls_show 148 xtlsConn.MARK = "XTLS" 149 if requestAddons.Flow == vless.XRD { 150 xtlsConn.DirectMode = true 151 } 152 } else { 153 return newError(`failed to use ` + requestAddons.Flow + `, maybe "security" is not "xtls"`).AtWarning() 154 } 155 } 156 default: 157 if _, ok := iConn.(*xtls.Conn); ok { 158 panic(`To avoid misunderstanding, you must fill in VLESS "flow" when using XTLS.`) 159 } 160 } 161 162 sessionPolicy := h.policyManager.ForLevel(request.User.Level) 163 ctx, cancel := context.WithCancel(ctx) 164 timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle) 165 166 clientReader := link.Reader // .(*pipe.Reader) 167 clientWriter := link.Writer // .(*pipe.Writer) 168 169 postRequest := func() error { 170 defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly) 171 172 bufferWriter := buf.NewBufferedWriter(buf.NewWriter(conn)) 173 if err := encoding.EncodeRequestHeader(bufferWriter, request, requestAddons); err != nil { 174 return newError("failed to encode request header").Base(err).AtWarning() 175 } 176 177 // default: serverWriter := bufferWriter 178 serverWriter := encoding.EncodeBodyAddons(bufferWriter, request, requestAddons) 179 if err := buf.CopyOnceTimeout(clientReader, serverWriter, time.Millisecond*100); err != nil && err != buf.ErrNotTimeoutReader && err != buf.ErrReadTimeout { 180 return err // ... 181 } 182 183 // Flush; bufferWriter.WriteMultiBufer now is bufferWriter.writer.WriteMultiBuffer 184 if err := bufferWriter.SetBuffered(false); err != nil { 185 return newError("failed to write A request payload").Base(err).AtWarning() 186 } 187 188 // from clientReader.ReadMultiBuffer to serverWriter.WriteMultiBufer 189 if err := buf.Copy(clientReader, serverWriter, buf.UpdateActivity(timer)); err != nil { 190 return newError("failed to transfer request payload").Base(err).AtInfo() 191 } 192 193 // Indicates the end of request payload. 194 switch requestAddons.Flow { 195 default: 196 197 } 198 199 return nil 200 } 201 202 getResponse := func() error { 203 defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly) 204 205 responseAddons, err := encoding.DecodeResponseHeader(conn, request) 206 if err != nil { 207 return newError("failed to decode response header").Base(err).AtWarning() 208 } 209 210 // default: serverReader := buf.NewReader(conn) 211 serverReader := encoding.DecodeBodyAddons(conn, request, responseAddons) 212 213 // from serverReader.ReadMultiBuffer to clientWriter.WriteMultiBufer 214 if err := buf.Copy(serverReader, clientWriter, buf.UpdateActivity(timer)); err != nil { 215 return newError("failed to transfer response payload").Base(err).AtInfo() 216 } 217 218 return nil 219 } 220 221 if err := task.Run(ctx, postRequest, task.OnSuccess(getResponse, task.Close(clientWriter))); err != nil { 222 return newError("connection ends").Base(err).AtInfo() 223 } 224 225 return nil 226 }