inbound.go 19 KB

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