inbound.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. package inbound
  2. //go:generate go run github.com/xtls/xray-core/common/errors/errorgen
  3. import (
  4. "bytes"
  5. "context"
  6. gotls "crypto/tls"
  7. "io"
  8. "reflect"
  9. "strconv"
  10. "strings"
  11. "syscall"
  12. "time"
  13. "unsafe"
  14. "github.com/pires/go-proxyproto"
  15. "github.com/xtls/xray-core/common"
  16. "github.com/xtls/xray-core/common/buf"
  17. "github.com/xtls/xray-core/common/errors"
  18. "github.com/xtls/xray-core/common/log"
  19. "github.com/xtls/xray-core/common/net"
  20. "github.com/xtls/xray-core/common/platform"
  21. "github.com/xtls/xray-core/common/protocol"
  22. "github.com/xtls/xray-core/common/retry"
  23. "github.com/xtls/xray-core/common/session"
  24. "github.com/xtls/xray-core/common/signal"
  25. "github.com/xtls/xray-core/common/task"
  26. "github.com/xtls/xray-core/core"
  27. "github.com/xtls/xray-core/features/dns"
  28. feature_inbound "github.com/xtls/xray-core/features/inbound"
  29. "github.com/xtls/xray-core/features/policy"
  30. "github.com/xtls/xray-core/features/routing"
  31. "github.com/xtls/xray-core/features/stats"
  32. "github.com/xtls/xray-core/proxy/vless"
  33. "github.com/xtls/xray-core/proxy/vless/encoding"
  34. "github.com/xtls/xray-core/transport/internet/reality"
  35. "github.com/xtls/xray-core/transport/internet/stat"
  36. "github.com/xtls/xray-core/transport/internet/tls"
  37. "github.com/xtls/xray-core/transport/internet/xtls"
  38. )
  39. var xtls_show = false
  40. func init() {
  41. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  42. var dc dns.Client
  43. if err := core.RequireFeatures(ctx, func(d dns.Client) error {
  44. dc = d
  45. return nil
  46. }); err != nil {
  47. return nil, err
  48. }
  49. return New(ctx, config.(*Config), dc)
  50. }))
  51. const defaultFlagValue = "NOT_DEFINED_AT_ALL"
  52. xtlsShow := platform.NewEnvFlag("xray.vless.xtls.show").GetValue(func() string { return defaultFlagValue })
  53. if xtlsShow == "true" {
  54. xtls_show = true
  55. }
  56. }
  57. // Handler is an inbound connection handler that handles messages in VLess protocol.
  58. type Handler struct {
  59. inboundHandlerManager feature_inbound.Manager
  60. policyManager policy.Manager
  61. validator *vless.Validator
  62. dns dns.Client
  63. fallbacks map[string]map[string]map[string]*Fallback // or nil
  64. // regexps map[string]*regexp.Regexp // or nil
  65. }
  66. // New creates a new VLess inbound handler.
  67. func New(ctx context.Context, config *Config, dc dns.Client) (*Handler, error) {
  68. v := core.MustFromContext(ctx)
  69. handler := &Handler{
  70. inboundHandlerManager: v.GetFeature(feature_inbound.ManagerType()).(feature_inbound.Manager),
  71. policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
  72. validator: new(vless.Validator),
  73. dns: dc,
  74. }
  75. for _, user := range config.Clients {
  76. u, err := user.ToMemoryUser()
  77. if err != nil {
  78. return nil, newError("failed to get VLESS user").Base(err).AtError()
  79. }
  80. if err := handler.AddUser(ctx, u); err != nil {
  81. return nil, newError("failed to initiate user").Base(err).AtError()
  82. }
  83. }
  84. if config.Fallbacks != nil {
  85. handler.fallbacks = make(map[string]map[string]map[string]*Fallback)
  86. // handler.regexps = make(map[string]*regexp.Regexp)
  87. for _, fb := range config.Fallbacks {
  88. if handler.fallbacks[fb.Name] == nil {
  89. handler.fallbacks[fb.Name] = make(map[string]map[string]*Fallback)
  90. }
  91. if handler.fallbacks[fb.Name][fb.Alpn] == nil {
  92. handler.fallbacks[fb.Name][fb.Alpn] = make(map[string]*Fallback)
  93. }
  94. handler.fallbacks[fb.Name][fb.Alpn][fb.Path] = fb
  95. /*
  96. if fb.Path != "" {
  97. if r, err := regexp.Compile(fb.Path); err != nil {
  98. return nil, newError("invalid path regexp").Base(err).AtError()
  99. } else {
  100. handler.regexps[fb.Path] = r
  101. }
  102. }
  103. */
  104. }
  105. if handler.fallbacks[""] != nil {
  106. for name, apfb := range handler.fallbacks {
  107. if name != "" {
  108. for alpn := range handler.fallbacks[""] {
  109. if apfb[alpn] == nil {
  110. apfb[alpn] = make(map[string]*Fallback)
  111. }
  112. }
  113. }
  114. }
  115. }
  116. for _, apfb := range handler.fallbacks {
  117. if apfb[""] != nil {
  118. for alpn, pfb := range apfb {
  119. if alpn != "" { // && alpn != "h2" {
  120. for path, fb := range apfb[""] {
  121. if pfb[path] == nil {
  122. pfb[path] = fb
  123. }
  124. }
  125. }
  126. }
  127. }
  128. }
  129. if handler.fallbacks[""] != nil {
  130. for name, apfb := range handler.fallbacks {
  131. if name != "" {
  132. for alpn, pfb := range handler.fallbacks[""] {
  133. for path, fb := range pfb {
  134. if apfb[alpn][path] == nil {
  135. apfb[alpn][path] = fb
  136. }
  137. }
  138. }
  139. }
  140. }
  141. }
  142. }
  143. return handler, nil
  144. }
  145. func isMuxAndNotXUDP(request *protocol.RequestHeader, first *buf.Buffer) bool {
  146. if request.Command != protocol.RequestCommandMux {
  147. return false
  148. }
  149. if first.Len() < 7 {
  150. return true
  151. }
  152. firstBytes := first.Bytes()
  153. return !(firstBytes[2] == 0 && // ID high
  154. firstBytes[3] == 0 && // ID low
  155. firstBytes[6] == 2) // Network type: UDP
  156. }
  157. // Close implements common.Closable.Close().
  158. func (h *Handler) Close() error {
  159. return errors.Combine(common.Close(h.validator))
  160. }
  161. // AddUser implements proxy.UserManager.AddUser().
  162. func (h *Handler) AddUser(ctx context.Context, u *protocol.MemoryUser) error {
  163. return h.validator.Add(u)
  164. }
  165. // RemoveUser implements proxy.UserManager.RemoveUser().
  166. func (h *Handler) RemoveUser(ctx context.Context, e string) error {
  167. return h.validator.Del(e)
  168. }
  169. // Network implements proxy.Inbound.Network().
  170. func (*Handler) Network() []net.Network {
  171. return []net.Network{net.Network_TCP, net.Network_UNIX}
  172. }
  173. // Process implements proxy.Inbound.Process().
  174. func (h *Handler) Process(ctx context.Context, network net.Network, connection stat.Connection, dispatcher routing.Dispatcher) error {
  175. sid := session.ExportIDToError(ctx)
  176. iConn := connection
  177. statConn, ok := iConn.(*stat.CounterConnection)
  178. if ok {
  179. iConn = statConn.Connection
  180. }
  181. sessionPolicy := h.policyManager.ForLevel(0)
  182. if err := connection.SetReadDeadline(time.Now().Add(sessionPolicy.Timeouts.Handshake)); err != nil {
  183. return newError("unable to set read deadline").Base(err).AtWarning()
  184. }
  185. first := buf.FromBytes(make([]byte, buf.Size))
  186. first.Clear()
  187. firstLen, _ := first.ReadFrom(connection)
  188. newError("firstLen = ", firstLen).AtInfo().WriteToLog(sid)
  189. reader := &buf.BufferedReader{
  190. Reader: buf.NewReader(connection),
  191. Buffer: buf.MultiBuffer{first},
  192. }
  193. var request *protocol.RequestHeader
  194. var requestAddons *encoding.Addons
  195. var err error
  196. napfb := h.fallbacks
  197. isfb := napfb != nil
  198. if isfb && firstLen < 18 {
  199. err = newError("fallback directly")
  200. } else {
  201. request, requestAddons, isfb, err = encoding.DecodeRequestHeader(isfb, first, reader, h.validator)
  202. }
  203. if err != nil {
  204. if isfb {
  205. if err := connection.SetReadDeadline(time.Time{}); err != nil {
  206. newError("unable to set back read deadline").Base(err).AtWarning().WriteToLog(sid)
  207. }
  208. newError("fallback starts").Base(err).AtInfo().WriteToLog(sid)
  209. name := ""
  210. alpn := ""
  211. if tlsConn, ok := iConn.(*tls.Conn); ok {
  212. cs := tlsConn.ConnectionState()
  213. name = cs.ServerName
  214. alpn = cs.NegotiatedProtocol
  215. newError("realName = " + name).AtInfo().WriteToLog(sid)
  216. newError("realAlpn = " + alpn).AtInfo().WriteToLog(sid)
  217. } else if xtlsConn, ok := iConn.(*xtls.Conn); ok {
  218. cs := xtlsConn.ConnectionState()
  219. name = cs.ServerName
  220. alpn = cs.NegotiatedProtocol
  221. newError("realName = " + name).AtInfo().WriteToLog(sid)
  222. newError("realAlpn = " + alpn).AtInfo().WriteToLog(sid)
  223. } else if realityConn, ok := iConn.(*reality.Conn); ok {
  224. cs := realityConn.ConnectionState()
  225. name = cs.ServerName
  226. alpn = cs.NegotiatedProtocol
  227. newError("realName = " + name).AtInfo().WriteToLog(sid)
  228. newError("realAlpn = " + alpn).AtInfo().WriteToLog(sid)
  229. }
  230. name = strings.ToLower(name)
  231. alpn = strings.ToLower(alpn)
  232. if len(napfb) > 1 || napfb[""] == nil {
  233. if name != "" && napfb[name] == nil {
  234. match := ""
  235. for n := range napfb {
  236. if n != "" && strings.Contains(name, n) && len(n) > len(match) {
  237. match = n
  238. }
  239. }
  240. name = match
  241. }
  242. }
  243. if napfb[name] == nil {
  244. name = ""
  245. }
  246. apfb := napfb[name]
  247. if apfb == nil {
  248. return newError(`failed to find the default "name" config`).AtWarning()
  249. }
  250. if apfb[alpn] == nil {
  251. alpn = ""
  252. }
  253. pfb := apfb[alpn]
  254. if pfb == nil {
  255. return newError(`failed to find the default "alpn" config`).AtWarning()
  256. }
  257. path := ""
  258. if len(pfb) > 1 || pfb[""] == nil {
  259. /*
  260. if lines := bytes.Split(firstBytes, []byte{'\r', '\n'}); len(lines) > 1 {
  261. if s := bytes.Split(lines[0], []byte{' '}); len(s) == 3 {
  262. if len(s[0]) < 8 && len(s[1]) > 0 && len(s[2]) == 8 {
  263. newError("realPath = " + string(s[1])).AtInfo().WriteToLog(sid)
  264. for _, fb := range pfb {
  265. if fb.Path != "" && h.regexps[fb.Path].Match(s[1]) {
  266. path = fb.Path
  267. break
  268. }
  269. }
  270. }
  271. }
  272. }
  273. */
  274. if firstLen >= 18 && first.Byte(4) != '*' { // not h2c
  275. firstBytes := first.Bytes()
  276. for i := 4; i <= 8; i++ { // 5 -> 9
  277. if firstBytes[i] == '/' && firstBytes[i-1] == ' ' {
  278. search := len(firstBytes)
  279. if search > 64 {
  280. search = 64 // up to about 60
  281. }
  282. for j := i + 1; j < search; j++ {
  283. k := firstBytes[j]
  284. if k == '\r' || k == '\n' { // avoid logging \r or \n
  285. break
  286. }
  287. if k == '?' || k == ' ' {
  288. path = string(firstBytes[i:j])
  289. newError("realPath = " + path).AtInfo().WriteToLog(sid)
  290. if pfb[path] == nil {
  291. path = ""
  292. }
  293. break
  294. }
  295. }
  296. break
  297. }
  298. }
  299. }
  300. }
  301. fb := pfb[path]
  302. if fb == nil {
  303. return newError(`failed to find the default "path" config`).AtWarning()
  304. }
  305. ctx, cancel := context.WithCancel(ctx)
  306. timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
  307. ctx = policy.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer)
  308. var conn net.Conn
  309. if err := retry.ExponentialBackoff(5, 100).On(func() error {
  310. var dialer net.Dialer
  311. conn, err = dialer.DialContext(ctx, fb.Type, fb.Dest)
  312. if err != nil {
  313. return err
  314. }
  315. return nil
  316. }); err != nil {
  317. return newError("failed to dial to " + fb.Dest).Base(err).AtWarning()
  318. }
  319. defer conn.Close()
  320. serverReader := buf.NewReader(conn)
  321. serverWriter := buf.NewWriter(conn)
  322. postRequest := func() error {
  323. defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
  324. if fb.Xver != 0 {
  325. ipType := 4
  326. remoteAddr, remotePort, err := net.SplitHostPort(connection.RemoteAddr().String())
  327. if err != nil {
  328. ipType = 0
  329. }
  330. localAddr, localPort, err := net.SplitHostPort(connection.LocalAddr().String())
  331. if err != nil {
  332. ipType = 0
  333. }
  334. if ipType == 4 {
  335. for i := 0; i < len(remoteAddr); i++ {
  336. if remoteAddr[i] == ':' {
  337. ipType = 6
  338. break
  339. }
  340. }
  341. }
  342. pro := buf.New()
  343. defer pro.Release()
  344. switch fb.Xver {
  345. case 1:
  346. if ipType == 0 {
  347. pro.Write([]byte("PROXY UNKNOWN\r\n"))
  348. break
  349. }
  350. if ipType == 4 {
  351. pro.Write([]byte("PROXY TCP4 " + remoteAddr + " " + localAddr + " " + remotePort + " " + localPort + "\r\n"))
  352. } else {
  353. pro.Write([]byte("PROXY TCP6 " + remoteAddr + " " + localAddr + " " + remotePort + " " + localPort + "\r\n"))
  354. }
  355. case 2:
  356. pro.Write([]byte("\x0D\x0A\x0D\x0A\x00\x0D\x0A\x51\x55\x49\x54\x0A")) // signature
  357. if ipType == 0 {
  358. pro.Write([]byte("\x20\x00\x00\x00")) // v2 + LOCAL + UNSPEC + UNSPEC + 0 bytes
  359. break
  360. }
  361. if ipType == 4 {
  362. pro.Write([]byte("\x21\x11\x00\x0C")) // v2 + PROXY + AF_INET + STREAM + 12 bytes
  363. pro.Write(net.ParseIP(remoteAddr).To4())
  364. pro.Write(net.ParseIP(localAddr).To4())
  365. } else {
  366. pro.Write([]byte("\x21\x21\x00\x24")) // v2 + PROXY + AF_INET6 + STREAM + 36 bytes
  367. pro.Write(net.ParseIP(remoteAddr).To16())
  368. pro.Write(net.ParseIP(localAddr).To16())
  369. }
  370. p1, _ := strconv.ParseUint(remotePort, 10, 16)
  371. p2, _ := strconv.ParseUint(localPort, 10, 16)
  372. pro.Write([]byte{byte(p1 >> 8), byte(p1), byte(p2 >> 8), byte(p2)})
  373. }
  374. if err := serverWriter.WriteMultiBuffer(buf.MultiBuffer{pro}); err != nil {
  375. return newError("failed to set PROXY protocol v", fb.Xver).Base(err).AtWarning()
  376. }
  377. }
  378. if err := buf.Copy(reader, serverWriter, buf.UpdateActivity(timer)); err != nil {
  379. return newError("failed to fallback request payload").Base(err).AtInfo()
  380. }
  381. return nil
  382. }
  383. writer := buf.NewWriter(connection)
  384. getResponse := func() error {
  385. defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
  386. if err := buf.Copy(serverReader, writer, buf.UpdateActivity(timer)); err != nil {
  387. return newError("failed to deliver response payload").Base(err).AtInfo()
  388. }
  389. return nil
  390. }
  391. if err := task.Run(ctx, task.OnSuccess(postRequest, task.Close(serverWriter)), task.OnSuccess(getResponse, task.Close(writer))); err != nil {
  392. common.Interrupt(serverReader)
  393. common.Interrupt(serverWriter)
  394. return newError("fallback ends").Base(err).AtInfo()
  395. }
  396. return nil
  397. }
  398. if errors.Cause(err) != io.EOF {
  399. log.Record(&log.AccessMessage{
  400. From: connection.RemoteAddr(),
  401. To: "",
  402. Status: log.AccessRejected,
  403. Reason: err,
  404. })
  405. err = newError("invalid request from ", connection.RemoteAddr()).Base(err).AtInfo()
  406. }
  407. return err
  408. }
  409. if err := connection.SetReadDeadline(time.Time{}); err != nil {
  410. newError("unable to set back read deadline").Base(err).AtWarning().WriteToLog(sid)
  411. }
  412. newError("received request for ", request.Destination()).AtInfo().WriteToLog(sid)
  413. inbound := session.InboundFromContext(ctx)
  414. if inbound == nil {
  415. panic("no inbound metadata")
  416. }
  417. inbound.User = request.User
  418. account := request.User.Account.(*vless.MemoryAccount)
  419. responseAddons := &encoding.Addons{
  420. // Flow: requestAddons.Flow,
  421. }
  422. var netConn net.Conn
  423. var rawConn syscall.RawConn
  424. var input *bytes.Reader
  425. var rawInput *bytes.Buffer
  426. allowNoneFlow := false
  427. accountFlow := account.Flow
  428. flows := strings.Split(account.Flow, ",")
  429. for _, f := range flows {
  430. t := strings.TrimSpace(f)
  431. if t == "none" {
  432. allowNoneFlow = true
  433. } else {
  434. accountFlow = t
  435. }
  436. }
  437. switch requestAddons.Flow {
  438. case vless.XRO, vless.XRD, vless.XRV:
  439. if accountFlow == requestAddons.Flow {
  440. switch request.Command {
  441. case protocol.RequestCommandMux:
  442. return newError(requestAddons.Flow + " doesn't support Mux").AtWarning()
  443. case protocol.RequestCommandUDP:
  444. return newError(requestAddons.Flow + " doesn't support UDP").AtWarning()
  445. case protocol.RequestCommandTCP:
  446. if requestAddons.Flow == vless.XRV {
  447. var t reflect.Type
  448. var p uintptr
  449. if tlsConn, ok := iConn.(*tls.Conn); ok {
  450. if tlsConn.ConnectionState().Version != gotls.VersionTLS13 {
  451. return newError(`failed to use `+requestAddons.Flow+`, found outer tls version `, tlsConn.ConnectionState().Version).AtWarning()
  452. }
  453. netConn = tlsConn.NetConn()
  454. t = reflect.TypeOf(tlsConn.Conn).Elem()
  455. p = uintptr(unsafe.Pointer(tlsConn.Conn))
  456. } else if realityConn, ok := iConn.(*reality.Conn); ok {
  457. netConn = realityConn.NetConn()
  458. t = reflect.TypeOf(realityConn.Conn).Elem()
  459. p = uintptr(unsafe.Pointer(realityConn.Conn))
  460. } else if _, ok := iConn.(*tls.UConn); ok {
  461. return newError("XTLS only supports UTLS fingerprint for the outbound.").AtWarning()
  462. } else if _, ok := iConn.(*xtls.Conn); ok {
  463. return newError(`failed to use ` + requestAddons.Flow + `, vision "security" must be "tls" or "reality"`).AtWarning()
  464. } else {
  465. return newError("XTLS only supports TCP, mKCP and DomainSocket for now.").AtWarning()
  466. }
  467. if pc, ok := netConn.(*proxyproto.Conn); ok {
  468. netConn = pc.Raw()
  469. // 8192 > 4096, there is no need to process pc's bufReader
  470. }
  471. if sc, ok := netConn.(syscall.Conn); ok {
  472. rawConn, _ = sc.SyscallConn()
  473. }
  474. i, _ := t.FieldByName("input")
  475. r, _ := t.FieldByName("rawInput")
  476. input = (*bytes.Reader)(unsafe.Pointer(p + i.Offset))
  477. rawInput = (*bytes.Buffer)(unsafe.Pointer(p + r.Offset))
  478. } else if xtlsConn, ok := iConn.(*xtls.Conn); ok {
  479. xtlsConn.RPRX = true
  480. xtlsConn.SHOW = xtls_show
  481. xtlsConn.MARK = "XTLS"
  482. if requestAddons.Flow == vless.XRD {
  483. xtlsConn.DirectMode = true
  484. if sc, ok := xtlsConn.NetConn().(syscall.Conn); ok {
  485. rawConn, _ = sc.SyscallConn()
  486. }
  487. }
  488. } else {
  489. return newError(`failed to use ` + requestAddons.Flow + `, maybe "security" is not "xtls"`).AtWarning()
  490. }
  491. }
  492. } else {
  493. return newError(account.ID.String() + " is not able to use " + requestAddons.Flow).AtWarning()
  494. }
  495. case "", "none":
  496. if accountFlow == vless.XRV && !allowNoneFlow && (request.Command == protocol.RequestCommandTCP || isMuxAndNotXUDP(request, first)) {
  497. return newError(account.ID.String() + " is not able to use " + vless.XRV +
  498. ". Note the pure tls proxy has certain tls in tls characters. Append \",none\" in flow to suppress").AtWarning()
  499. }
  500. default:
  501. return newError("unknown request flow " + requestAddons.Flow).AtWarning()
  502. }
  503. if request.Command != protocol.RequestCommandMux {
  504. ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
  505. From: connection.RemoteAddr(),
  506. To: request.Destination(),
  507. Status: log.AccessAccepted,
  508. Reason: "",
  509. Email: request.User.Email,
  510. })
  511. }
  512. sessionPolicy = h.policyManager.ForLevel(request.User.Level)
  513. ctx, cancel := context.WithCancel(ctx)
  514. timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
  515. ctx = policy.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer)
  516. link, err := dispatcher.Dispatch(ctx, request.Destination())
  517. if err != nil {
  518. return newError("failed to dispatch request to ", request.Destination()).Base(err).AtWarning()
  519. }
  520. serverReader := link.Reader // .(*pipe.Reader)
  521. serverWriter := link.Writer // .(*pipe.Writer)
  522. enableXtls := false
  523. isTLS12orAbove := false
  524. isTLS := false
  525. var cipher uint16 = 0
  526. var remainingServerHello int32 = -1
  527. numberOfPacketToFilter := 8
  528. postRequest := func() error {
  529. defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
  530. // default: clientReader := reader
  531. clientReader := encoding.DecodeBodyAddons(reader, request, requestAddons)
  532. var err error
  533. if rawConn != nil {
  534. var counter stats.Counter
  535. if statConn != nil {
  536. counter = statConn.ReadCounter
  537. }
  538. // TODO enable splice
  539. ctx = session.ContextWithInbound(ctx, nil)
  540. if requestAddons.Flow == vless.XRV {
  541. err = encoding.XtlsRead(clientReader, serverWriter, timer, netConn, rawConn, input, rawInput, counter, ctx, account.ID.Bytes(),
  542. &numberOfPacketToFilter, &enableXtls, &isTLS12orAbove, &isTLS, &cipher, &remainingServerHello)
  543. } else {
  544. err = encoding.ReadV(clientReader, serverWriter, timer, iConn.(*xtls.Conn), rawConn, counter, ctx)
  545. }
  546. } else {
  547. // from clientReader.ReadMultiBuffer to serverWriter.WriteMultiBufer
  548. err = buf.Copy(clientReader, serverWriter, buf.UpdateActivity(timer))
  549. }
  550. if err != nil {
  551. return newError("failed to transfer request payload").Base(err).AtInfo()
  552. }
  553. return nil
  554. }
  555. getResponse := func() error {
  556. defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
  557. bufferWriter := buf.NewBufferedWriter(buf.NewWriter(connection))
  558. if err := encoding.EncodeResponseHeader(bufferWriter, request, responseAddons); err != nil {
  559. return newError("failed to encode response header").Base(err).AtWarning()
  560. }
  561. // default: clientWriter := bufferWriter
  562. clientWriter := encoding.EncodeBodyAddons(bufferWriter, request, responseAddons)
  563. userUUID := account.ID.Bytes()
  564. multiBuffer, err1 := serverReader.ReadMultiBuffer()
  565. if err1 != nil {
  566. return err1 // ...
  567. }
  568. if requestAddons.Flow == vless.XRV {
  569. encoding.XtlsFilterTls(multiBuffer, &numberOfPacketToFilter, &enableXtls, &isTLS12orAbove, &isTLS, &cipher, &remainingServerHello, ctx)
  570. multiBuffer = encoding.ReshapeMultiBuffer(ctx, multiBuffer)
  571. for i, b := range multiBuffer {
  572. multiBuffer[i] = encoding.XtlsPadding(b, encoding.CommandPaddingContinue, &userUUID, isTLS, ctx)
  573. }
  574. }
  575. if err := clientWriter.WriteMultiBuffer(multiBuffer); err != nil {
  576. return err // ...
  577. }
  578. // Flush; bufferWriter.WriteMultiBufer now is bufferWriter.writer.WriteMultiBuffer
  579. if err := bufferWriter.SetBuffered(false); err != nil {
  580. return newError("failed to write A response payload").Base(err).AtWarning()
  581. }
  582. var err error
  583. if rawConn != nil && requestAddons.Flow == vless.XRV {
  584. var counter stats.Counter
  585. if statConn != nil {
  586. counter = statConn.WriteCounter
  587. }
  588. err = encoding.XtlsWrite(serverReader, clientWriter, timer, netConn, counter, ctx, &numberOfPacketToFilter,
  589. &enableXtls, &isTLS12orAbove, &isTLS, &cipher, &remainingServerHello)
  590. } else {
  591. // from serverReader.ReadMultiBuffer to clientWriter.WriteMultiBufer
  592. err = buf.Copy(serverReader, clientWriter, buf.UpdateActivity(timer))
  593. }
  594. if err != nil {
  595. return newError("failed to transfer response payload").Base(err).AtInfo()
  596. }
  597. // Indicates the end of response payload.
  598. switch responseAddons.Flow {
  599. default:
  600. }
  601. return nil
  602. }
  603. if err := task.Run(ctx, task.OnSuccess(postRequest, task.Close(serverWriter)), getResponse); err != nil {
  604. common.Interrupt(serverReader)
  605. common.Interrupt(serverWriter)
  606. return newError("connection ends").Base(err).AtInfo()
  607. }
  608. return nil
  609. }