github.com/xraypb/xray-core@v1.6.6/proxy/vless/outbound/outbound.go (about) 1 package outbound 2 3 //go:generate go run github.com/xraypb/xray-core/common/errors/errorgen 4 5 import ( 6 "context" 7 "syscall" 8 9 "github.com/xraypb/xray-core/common" 10 "github.com/xraypb/xray-core/common/buf" 11 "github.com/xraypb/xray-core/common/net" 12 "github.com/xraypb/xray-core/common/platform" 13 "github.com/xraypb/xray-core/common/protocol" 14 "github.com/xraypb/xray-core/common/retry" 15 "github.com/xraypb/xray-core/common/session" 16 "github.com/xraypb/xray-core/common/signal" 17 "github.com/xraypb/xray-core/common/task" 18 "github.com/xraypb/xray-core/common/xudp" 19 core "github.com/xraypb/xray-core/core" 20 "github.com/xraypb/xray-core/features/policy" 21 "github.com/xraypb/xray-core/features/stats" 22 "github.com/xraypb/xray-core/proxy/vless" 23 "github.com/xraypb/xray-core/proxy/vless/encoding" 24 "github.com/xraypb/xray-core/transport" 25 "github.com/xraypb/xray-core/transport/internet" 26 "github.com/xraypb/xray-core/transport/internet/stat" 27 "github.com/xraypb/xray-core/transport/internet/tls" 28 "github.com/xraypb/xray-core/transport/internet/xtls" 29 ) 30 31 var xtls_show = false 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("xray.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 cone bool 52 } 53 54 // New creates a new VLess outbound handler. 55 func New(ctx context.Context, config *Config) (*Handler, error) { 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 cone: ctx.Value("cone").(bool), 71 } 72 73 return handler, nil 74 } 75 76 // Process implements proxy.Outbound.Process(). 77 func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error { 78 var rec *protocol.ServerSpec 79 var conn stat.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() 93 94 iConn := conn 95 statConn, ok := iConn.(*stat.CounterConnection) 96 if ok { 97 iConn = statConn.Connection 98 } 99 100 outbound := session.OutboundFromContext(ctx) 101 if outbound == nil || !outbound.Target.IsValid() { 102 return newError("target not specified").AtError() 103 } 104 105 target := outbound.Target 106 newError("tunneling request to ", target, " via ", rec.Destination().NetAddr()).AtInfo().WriteToLog(session.ExportIDToError(ctx)) 107 108 command := protocol.RequestCommandTCP 109 if target.Network == net.Network_UDP { 110 command = protocol.RequestCommandUDP 111 } 112 if target.Address.Family().IsDomain() && target.Address.Domain() == "v1.mux.cool" { 113 command = protocol.RequestCommandMux 114 } 115 116 request := &protocol.RequestHeader{ 117 Version: encoding.Version, 118 User: rec.PickUser(), 119 Command: command, 120 Address: target.Address, 121 Port: target.Port, 122 } 123 124 account := request.User.Account.(*vless.MemoryAccount) 125 126 requestAddons := &encoding.Addons{ 127 Flow: account.Flow, 128 } 129 130 var netConn net.Conn 131 var rawConn syscall.RawConn 132 allowUDP443 := false 133 switch requestAddons.Flow { 134 case vless.XRO + "-udp443", vless.XRD + "-udp443", vless.XRS + "-udp443", vless.XRV + "-udp443": 135 allowUDP443 = true 136 requestAddons.Flow = requestAddons.Flow[:16] 137 fallthrough 138 case vless.XRO, vless.XRD, vless.XRS, vless.XRV: 139 switch request.Command { 140 case protocol.RequestCommandMux: 141 return newError(requestAddons.Flow + " doesn't support Mux").AtWarning() 142 case protocol.RequestCommandUDP: 143 if !allowUDP443 && request.Port == 443 { 144 return newError(requestAddons.Flow + " stopped UDP/443").AtInfo() 145 } 146 requestAddons.Flow = "" 147 case protocol.RequestCommandTCP: 148 if requestAddons.Flow == vless.XRV { 149 if tlsConn, ok := iConn.(*tls.Conn); ok { 150 netConn = tlsConn.NetConn() 151 if sc, ok := netConn.(syscall.Conn); ok { 152 rawConn, _ = sc.SyscallConn() 153 } 154 } else if utlsConn, ok := iConn.(*tls.UConn); ok { 155 netConn = utlsConn.Conn.NetConn() 156 if sc, ok := netConn.(syscall.Conn); ok { 157 rawConn, _ = sc.SyscallConn() 158 } 159 } else if _, ok := iConn.(*xtls.Conn); ok { 160 return newError(`failed to use ` + requestAddons.Flow + `, vision "security" must be "tls"`).AtWarning() 161 } else { 162 return newError("XTLS only supports TCP, mKCP and DomainSocket for now.").AtWarning() 163 } 164 } else if xtlsConn, ok := iConn.(*xtls.Conn); ok { 165 xtlsConn.RPRX = true 166 xtlsConn.SHOW = xtls_show 167 xtlsConn.MARK = "XTLS" 168 if requestAddons.Flow == vless.XRS { 169 requestAddons.Flow = vless.XRD 170 } 171 if requestAddons.Flow == vless.XRD { 172 xtlsConn.DirectMode = true 173 if sc, ok := xtlsConn.NetConn().(syscall.Conn); ok { 174 rawConn, _ = sc.SyscallConn() 175 } 176 } 177 } else { 178 return newError(`failed to use ` + requestAddons.Flow + `, maybe "security" is not "xtls"`).AtWarning() 179 } 180 } 181 default: 182 if _, ok := iConn.(*xtls.Conn); ok { 183 panic(`To avoid misunderstanding, you must fill in VLESS "flow" when using XTLS.`) 184 } 185 } 186 187 sessionPolicy := h.policyManager.ForLevel(request.User.Level) 188 ctx, cancel := context.WithCancel(ctx) 189 timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle) 190 191 clientReader := link.Reader // .(*pipe.Reader) 192 clientWriter := link.Writer // .(*pipe.Writer) 193 enableXtls := false 194 isTLS12orAbove := false 195 isTLS := false 196 var cipher uint16 = 0 197 var remainingServerHello int32 = -1 198 numberOfPacketToFilter := 8 199 200 if request.Command == protocol.RequestCommandUDP && h.cone && request.Port != 53 && request.Port != 443 { 201 request.Command = protocol.RequestCommandMux 202 request.Address = net.DomainAddress("v1.mux.cool") 203 request.Port = net.Port(666) 204 } 205 206 postRequest := func() error { 207 defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly) 208 209 bufferWriter := buf.NewBufferedWriter(buf.NewWriter(conn)) 210 if err := encoding.EncodeRequestHeader(bufferWriter, request, requestAddons); err != nil { 211 return newError("failed to encode request header").Base(err).AtWarning() 212 } 213 214 // default: serverWriter := bufferWriter 215 serverWriter := encoding.EncodeBodyAddons(bufferWriter, request, requestAddons) 216 if request.Command == protocol.RequestCommandMux && request.Port == 666 { 217 serverWriter = xudp.NewPacketWriter(serverWriter, target) 218 } 219 userUUID := account.ID.Bytes() 220 multiBuffer, err1 := clientReader.ReadMultiBuffer() 221 if err1 != nil { 222 return err1 // ... 223 } 224 if requestAddons.Flow == vless.XRV { 225 encoding.XtlsFilterTls(multiBuffer, &numberOfPacketToFilter, &enableXtls, &isTLS12orAbove, &isTLS, &cipher, &remainingServerHello, ctx) 226 if isTLS { 227 for i, b := range multiBuffer { 228 multiBuffer[i] = encoding.XtlsPadding(b, 0x00, &userUUID, ctx) 229 } 230 } 231 } 232 if err := serverWriter.WriteMultiBuffer(multiBuffer); err != nil { 233 return err // ... 234 } 235 // Flush; bufferWriter.WriteMultiBufer now is bufferWriter.writer.WriteMultiBuffer 236 if err := bufferWriter.SetBuffered(false); err != nil { 237 return newError("failed to write A request payload").Base(err).AtWarning() 238 } 239 240 var err error 241 if rawConn != nil && requestAddons.Flow == vless.XRV { 242 var counter stats.Counter 243 if statConn != nil { 244 counter = statConn.WriteCounter 245 } 246 err = encoding.XtlsWrite(clientReader, serverWriter, timer, netConn, counter, ctx, &userUUID, &numberOfPacketToFilter, 247 &enableXtls, &isTLS12orAbove, &isTLS, &cipher, &remainingServerHello) 248 } else { 249 // from clientReader.ReadMultiBuffer to serverWriter.WriteMultiBufer 250 err = buf.Copy(clientReader, serverWriter, buf.UpdateActivity(timer)) 251 } 252 if err != nil { 253 return newError("failed to transfer request payload").Base(err).AtInfo() 254 } 255 256 // Indicates the end of request payload. 257 switch requestAddons.Flow { 258 default: 259 } 260 return nil 261 } 262 263 getResponse := func() error { 264 defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly) 265 266 responseAddons, err := encoding.DecodeResponseHeader(conn, request) 267 if err != nil { 268 return newError("failed to decode response header").Base(err).AtInfo() 269 } 270 271 // default: serverReader := buf.NewReader(conn) 272 serverReader := encoding.DecodeBodyAddons(conn, request, responseAddons) 273 if request.Command == protocol.RequestCommandMux && request.Port == 666 { 274 serverReader = xudp.NewPacketReader(conn) 275 } 276 277 if rawConn != nil { 278 var counter stats.Counter 279 if statConn != nil { 280 counter = statConn.ReadCounter 281 } 282 if requestAddons.Flow == vless.XRV { 283 err = encoding.XtlsRead(serverReader, clientWriter, timer, netConn, rawConn, counter, ctx, account.ID.Bytes(), 284 &numberOfPacketToFilter, &enableXtls, &isTLS12orAbove, &isTLS, &cipher, &remainingServerHello) 285 } else { 286 if requestAddons.Flow != vless.XRS { 287 ctx = session.ContextWithInbound(ctx, nil) 288 } 289 err = encoding.ReadV(serverReader, clientWriter, timer, iConn.(*xtls.Conn), rawConn, counter, ctx) 290 } 291 } else { 292 // from serverReader.ReadMultiBuffer to clientWriter.WriteMultiBufer 293 err = buf.Copy(serverReader, clientWriter, buf.UpdateActivity(timer)) 294 } 295 296 if err != nil { 297 return newError("failed to transfer response payload").Base(err).AtInfo() 298 } 299 300 return nil 301 } 302 303 if err := task.Run(ctx, postRequest, task.OnSuccess(getResponse, task.Close(clientWriter))); err != nil { 304 return newError("connection ends").Base(err).AtInfo() 305 } 306 307 return nil 308 }