inbound.go 19 KB

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