inbound.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  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. "time"
  12. "unsafe"
  13. "golang.org/x/net/http2"
  14. "golang.org/x/net/http2/hpack"
  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/proxy"
  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, errors.New("failed to get VLESS user").Base(err).AtError()
  71. }
  72. if err := handler.AddUser(ctx, u); err != nil {
  73. return nil, errors.New("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, errors.New("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. iConn := connection
  168. if statConn, ok := iConn.(*stat.CounterConnection); ok {
  169. iConn = statConn.Connection
  170. }
  171. sessionPolicy := h.policyManager.ForLevel(0)
  172. if err := connection.SetReadDeadline(time.Now().Add(sessionPolicy.Timeouts.Handshake)); err != nil {
  173. return errors.New("unable to set read deadline").Base(err).AtWarning()
  174. }
  175. first := buf.FromBytes(make([]byte, buf.Size))
  176. first.Clear()
  177. firstLen, _ := first.ReadFrom(connection)
  178. errors.LogInfo(ctx, "firstLen = ", firstLen)
  179. reader := &buf.BufferedReader{
  180. Reader: buf.NewReader(connection),
  181. Buffer: buf.MultiBuffer{first},
  182. }
  183. var request *protocol.RequestHeader
  184. var requestAddons *encoding.Addons
  185. var err error
  186. napfb := h.fallbacks
  187. isfb := napfb != nil
  188. if isfb && firstLen < 18 {
  189. err = errors.New("fallback directly")
  190. } else {
  191. request, requestAddons, isfb, err = encoding.DecodeRequestHeader(isfb, first, reader, h.validator)
  192. }
  193. if err != nil {
  194. if isfb {
  195. if err := connection.SetReadDeadline(time.Time{}); err != nil {
  196. errors.LogWarningInner(ctx, err, "unable to set back read deadline")
  197. }
  198. errors.LogInfoInner(ctx, err, "fallback starts")
  199. name := ""
  200. alpn := ""
  201. if tlsConn, ok := iConn.(*tls.Conn); ok {
  202. cs := tlsConn.ConnectionState()
  203. name = cs.ServerName
  204. alpn = cs.NegotiatedProtocol
  205. errors.LogInfo(ctx, "realName = "+name)
  206. errors.LogInfo(ctx, "realAlpn = "+alpn)
  207. } else if realityConn, ok := iConn.(*reality.Conn); ok {
  208. cs := realityConn.ConnectionState()
  209. name = cs.ServerName
  210. alpn = cs.NegotiatedProtocol
  211. errors.LogInfo(ctx, "realName = "+name)
  212. errors.LogInfo(ctx, "realAlpn = "+alpn)
  213. }
  214. name = strings.ToLower(name)
  215. alpn = strings.ToLower(alpn)
  216. if len(napfb) > 1 || napfb[""] == nil {
  217. if name != "" && napfb[name] == nil {
  218. match := ""
  219. for n := range napfb {
  220. if n != "" && strings.Contains(name, n) && len(n) > len(match) {
  221. match = n
  222. }
  223. }
  224. name = match
  225. }
  226. }
  227. if napfb[name] == nil {
  228. name = ""
  229. }
  230. apfb := napfb[name]
  231. if apfb == nil {
  232. return errors.New(`failed to find the default "name" config`).AtWarning()
  233. }
  234. if apfb[alpn] == nil {
  235. alpn = ""
  236. }
  237. pfb := apfb[alpn]
  238. if pfb == nil {
  239. return errors.New(`failed to find the default "alpn" config`).AtWarning()
  240. }
  241. path := ""
  242. if len(pfb) > 1 || pfb[""] == nil {
  243. /*
  244. if lines := bytes.Split(firstBytes, []byte{'\r', '\n'}); len(lines) > 1 {
  245. if s := bytes.Split(lines[0], []byte{' '}); len(s) == 3 {
  246. if len(s[0]) < 8 && len(s[1]) > 0 && len(s[2]) == 8 {
  247. errors.New("realPath = " + string(s[1])).AtInfo().WriteToLog(sid)
  248. for _, fb := range pfb {
  249. if fb.Path != "" && h.regexps[fb.Path].Match(s[1]) {
  250. path = fb.Path
  251. break
  252. }
  253. }
  254. }
  255. }
  256. }
  257. */
  258. if firstLen >= 18 && first.Byte(4) != '*' { // not h2c
  259. firstBytes := first.Bytes()
  260. for i := 4; i <= 8; i++ { // 5 -> 9
  261. if firstBytes[i] == '/' && firstBytes[i-1] == ' ' {
  262. search := len(firstBytes)
  263. if search > 64 {
  264. search = 64 // up to about 60
  265. }
  266. for j := i + 1; j < search; j++ {
  267. k := firstBytes[j]
  268. if k == '\r' || k == '\n' { // avoid logging \r or \n
  269. break
  270. }
  271. if k == '?' || k == ' ' {
  272. path = string(firstBytes[i:j])
  273. errors.LogInfo(ctx, "realPath = "+path)
  274. if pfb[path] == nil {
  275. path = ""
  276. }
  277. break
  278. }
  279. }
  280. break
  281. }
  282. }
  283. } else if firstLen >= 18 && first.Byte(4) == '*' { // process h2c
  284. h2path := extractPathFromH2Request(connection)
  285. if h2path != "" {
  286. path = h2path
  287. errors.LogInfo(ctx, "realPath = "+path)
  288. }
  289. }
  290. }
  291. fb := prefixMatch(pfb, path)
  292. if fb == nil {
  293. return errors.New(`failed to find the default "path" config`).AtWarning()
  294. }
  295. ctx, cancel := context.WithCancel(ctx)
  296. timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
  297. ctx = policy.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer)
  298. var conn net.Conn
  299. if err := retry.ExponentialBackoff(5, 100).On(func() error {
  300. var dialer net.Dialer
  301. conn, err = dialer.DialContext(ctx, fb.Type, fb.Dest)
  302. if err != nil {
  303. return err
  304. }
  305. return nil
  306. }); err != nil {
  307. return errors.New("failed to dial to " + fb.Dest).Base(err).AtWarning()
  308. }
  309. defer conn.Close()
  310. serverReader := buf.NewReader(conn)
  311. serverWriter := buf.NewWriter(conn)
  312. postRequest := func() error {
  313. defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
  314. if fb.Xver != 0 {
  315. ipType := 4
  316. remoteAddr, remotePort, err := net.SplitHostPort(connection.RemoteAddr().String())
  317. if err != nil {
  318. ipType = 0
  319. }
  320. localAddr, localPort, err := net.SplitHostPort(connection.LocalAddr().String())
  321. if err != nil {
  322. ipType = 0
  323. }
  324. if ipType == 4 {
  325. for i := 0; i < len(remoteAddr); i++ {
  326. if remoteAddr[i] == ':' {
  327. ipType = 6
  328. break
  329. }
  330. }
  331. }
  332. pro := buf.New()
  333. defer pro.Release()
  334. switch fb.Xver {
  335. case 1:
  336. if ipType == 0 {
  337. pro.Write([]byte("PROXY UNKNOWN\r\n"))
  338. break
  339. }
  340. if ipType == 4 {
  341. pro.Write([]byte("PROXY TCP4 " + remoteAddr + " " + localAddr + " " + remotePort + " " + localPort + "\r\n"))
  342. } else {
  343. pro.Write([]byte("PROXY TCP6 " + remoteAddr + " " + localAddr + " " + remotePort + " " + localPort + "\r\n"))
  344. }
  345. case 2:
  346. pro.Write([]byte("\x0D\x0A\x0D\x0A\x00\x0D\x0A\x51\x55\x49\x54\x0A")) // signature
  347. if ipType == 0 {
  348. pro.Write([]byte("\x20\x00\x00\x00")) // v2 + LOCAL + UNSPEC + UNSPEC + 0 bytes
  349. break
  350. }
  351. if ipType == 4 {
  352. pro.Write([]byte("\x21\x11\x00\x0C")) // v2 + PROXY + AF_INET + STREAM + 12 bytes
  353. pro.Write(net.ParseIP(remoteAddr).To4())
  354. pro.Write(net.ParseIP(localAddr).To4())
  355. } else {
  356. pro.Write([]byte("\x21\x21\x00\x24")) // v2 + PROXY + AF_INET6 + STREAM + 36 bytes
  357. pro.Write(net.ParseIP(remoteAddr).To16())
  358. pro.Write(net.ParseIP(localAddr).To16())
  359. }
  360. p1, _ := strconv.ParseUint(remotePort, 10, 16)
  361. p2, _ := strconv.ParseUint(localPort, 10, 16)
  362. pro.Write([]byte{byte(p1 >> 8), byte(p1), byte(p2 >> 8), byte(p2)})
  363. }
  364. if err := serverWriter.WriteMultiBuffer(buf.MultiBuffer{pro}); err != nil {
  365. return errors.New("failed to set PROXY protocol v", fb.Xver).Base(err).AtWarning()
  366. }
  367. }
  368. if err := buf.Copy(reader, serverWriter, buf.UpdateActivity(timer)); err != nil {
  369. return errors.New("failed to fallback request payload").Base(err).AtInfo()
  370. }
  371. return nil
  372. }
  373. writer := buf.NewWriter(connection)
  374. getResponse := func() error {
  375. defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
  376. if err := buf.Copy(serverReader, writer, buf.UpdateActivity(timer)); err != nil {
  377. return errors.New("failed to deliver response payload").Base(err).AtInfo()
  378. }
  379. return nil
  380. }
  381. if err := task.Run(ctx, task.OnSuccess(postRequest, task.Close(serverWriter)), task.OnSuccess(getResponse, task.Close(writer))); err != nil {
  382. common.Interrupt(serverReader)
  383. common.Interrupt(serverWriter)
  384. return errors.New("fallback ends").Base(err).AtInfo()
  385. }
  386. return nil
  387. }
  388. if errors.Cause(err) != io.EOF {
  389. log.Record(&log.AccessMessage{
  390. From: connection.RemoteAddr(),
  391. To: "",
  392. Status: log.AccessRejected,
  393. Reason: err,
  394. })
  395. err = errors.New("invalid request from ", connection.RemoteAddr()).Base(err).AtInfo()
  396. }
  397. return err
  398. }
  399. if err := connection.SetReadDeadline(time.Time{}); err != nil {
  400. errors.LogWarningInner(ctx, err, "unable to set back read deadline")
  401. }
  402. errors.LogInfo(ctx, "received request for ", request.Destination())
  403. inbound := session.InboundFromContext(ctx)
  404. if inbound == nil {
  405. panic("no inbound metadata")
  406. }
  407. inbound.Name = "vless"
  408. inbound.User = request.User
  409. account := request.User.Account.(*vless.MemoryAccount)
  410. responseAddons := &encoding.Addons{
  411. // Flow: requestAddons.Flow,
  412. }
  413. var input *bytes.Reader
  414. var rawInput *bytes.Buffer
  415. switch requestAddons.Flow {
  416. case vless.XRV:
  417. if account.Flow == requestAddons.Flow {
  418. inbound.CanSpliceCopy = 2
  419. switch request.Command {
  420. case protocol.RequestCommandUDP:
  421. return errors.New(requestAddons.Flow + " doesn't support UDP").AtWarning()
  422. case protocol.RequestCommandMux:
  423. fallthrough // we will break Mux connections that contain TCP requests
  424. case protocol.RequestCommandTCP:
  425. var t reflect.Type
  426. var p uintptr
  427. if tlsConn, ok := iConn.(*tls.Conn); ok {
  428. if tlsConn.ConnectionState().Version != gotls.VersionTLS13 {
  429. return errors.New(`failed to use `+requestAddons.Flow+`, found outer tls version `, tlsConn.ConnectionState().Version).AtWarning()
  430. }
  431. t = reflect.TypeOf(tlsConn.Conn).Elem()
  432. p = uintptr(unsafe.Pointer(tlsConn.Conn))
  433. } else if realityConn, ok := iConn.(*reality.Conn); ok {
  434. t = reflect.TypeOf(realityConn.Conn).Elem()
  435. p = uintptr(unsafe.Pointer(realityConn.Conn))
  436. } else {
  437. return errors.New("XTLS only supports TLS and REALITY directly for now.").AtWarning()
  438. }
  439. i, _ := t.FieldByName("input")
  440. r, _ := t.FieldByName("rawInput")
  441. input = (*bytes.Reader)(unsafe.Pointer(p + i.Offset))
  442. rawInput = (*bytes.Buffer)(unsafe.Pointer(p + r.Offset))
  443. }
  444. } else {
  445. return errors.New(account.ID.String() + " is not able to use " + requestAddons.Flow).AtWarning()
  446. }
  447. case "":
  448. inbound.CanSpliceCopy = 3
  449. if account.Flow == vless.XRV && (request.Command == protocol.RequestCommandTCP || isMuxAndNotXUDP(request, first)) {
  450. return errors.New(account.ID.String() + " is not able to use \"\". Note that the pure TLS proxy has certain TLS in TLS characters.").AtWarning()
  451. }
  452. default:
  453. return errors.New("unknown request flow " + requestAddons.Flow).AtWarning()
  454. }
  455. if request.Command != protocol.RequestCommandMux {
  456. ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
  457. From: connection.RemoteAddr(),
  458. To: request.Destination(),
  459. Status: log.AccessAccepted,
  460. Reason: "",
  461. Email: request.User.Email,
  462. })
  463. } else if account.Flow == vless.XRV {
  464. ctx = session.ContextWithAllowedNetwork(ctx, net.Network_UDP)
  465. }
  466. sessionPolicy = h.policyManager.ForLevel(request.User.Level)
  467. ctx, cancel := context.WithCancel(ctx)
  468. timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
  469. inbound.Timer = timer
  470. ctx = policy.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer)
  471. link, err := dispatcher.Dispatch(ctx, request.Destination())
  472. if err != nil {
  473. return errors.New("failed to dispatch request to ", request.Destination()).Base(err).AtWarning()
  474. }
  475. serverReader := link.Reader // .(*pipe.Reader)
  476. serverWriter := link.Writer // .(*pipe.Writer)
  477. trafficState := proxy.NewTrafficState(account.ID.Bytes())
  478. postRequest := func() error {
  479. defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
  480. // default: clientReader := reader
  481. clientReader := encoding.DecodeBodyAddons(reader, request, requestAddons)
  482. var err error
  483. if requestAddons.Flow == vless.XRV {
  484. ctx1 := session.ContextWithInbound(ctx, nil) // TODO enable splice
  485. clientReader = proxy.NewVisionReader(clientReader, trafficState, ctx1)
  486. err = encoding.XtlsRead(clientReader, serverWriter, timer, connection, input, rawInput, trafficState, nil, ctx1)
  487. } else {
  488. // from clientReader.ReadMultiBuffer to serverWriter.WriteMultiBufer
  489. err = buf.Copy(clientReader, serverWriter, buf.UpdateActivity(timer))
  490. }
  491. if err != nil {
  492. return errors.New("failed to transfer request payload").Base(err).AtInfo()
  493. }
  494. return nil
  495. }
  496. getResponse := func() error {
  497. defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
  498. bufferWriter := buf.NewBufferedWriter(buf.NewWriter(connection))
  499. if err := encoding.EncodeResponseHeader(bufferWriter, request, responseAddons); err != nil {
  500. return errors.New("failed to encode response header").Base(err).AtWarning()
  501. }
  502. // default: clientWriter := bufferWriter
  503. clientWriter := encoding.EncodeBodyAddons(bufferWriter, request, requestAddons, trafficState, ctx)
  504. multiBuffer, err1 := serverReader.ReadMultiBuffer()
  505. if err1 != nil {
  506. return err1 // ...
  507. }
  508. if err := clientWriter.WriteMultiBuffer(multiBuffer); err != nil {
  509. return err // ...
  510. }
  511. // Flush; bufferWriter.WriteMultiBufer now is bufferWriter.writer.WriteMultiBuffer
  512. if err := bufferWriter.SetBuffered(false); err != nil {
  513. return errors.New("failed to write A response payload").Base(err).AtWarning()
  514. }
  515. var err error
  516. if requestAddons.Flow == vless.XRV {
  517. err = encoding.XtlsWrite(serverReader, clientWriter, timer, connection, trafficState, nil, ctx)
  518. } else {
  519. // from serverReader.ReadMultiBuffer to clientWriter.WriteMultiBufer
  520. err = buf.Copy(serverReader, clientWriter, buf.UpdateActivity(timer))
  521. }
  522. if err != nil {
  523. return errors.New("failed to transfer response payload").Base(err).AtInfo()
  524. }
  525. // Indicates the end of response payload.
  526. switch responseAddons.Flow {
  527. default:
  528. }
  529. return nil
  530. }
  531. if err := task.Run(ctx, task.OnSuccess(postRequest, task.Close(serverWriter)), getResponse); err != nil {
  532. common.Interrupt(serverReader)
  533. common.Interrupt(serverWriter)
  534. return errors.New("connection ends").Base(err).AtInfo()
  535. }
  536. return nil
  537. }
  538. // Get path form http2
  539. func extractPathFromH2Request(conn stat.Connection) string {
  540. framer := http2.NewFramer(io.Discard, conn)
  541. for {
  542. frame, err := framer.ReadFrame()
  543. if err != nil {
  544. return ""
  545. }
  546. // find headers frame
  547. if f, ok := frame.(*http2.HeadersFrame); ok {
  548. decoder := hpack.NewDecoder(4096, func(hf hpack.HeaderField) {})
  549. headerBlock := f.HeaderBlockFragment()
  550. hf, err := decoder.DecodeFull(headerBlock)
  551. if err != nil {
  552. return ""
  553. }
  554. path := func(headers []hpack.HeaderField) string {
  555. for _, header := range headers {
  556. if header.Name == ":path" {
  557. return header.Value
  558. }
  559. }
  560. return ""
  561. }
  562. return path(hf)
  563. }
  564. }
  565. }
  566. func prefixMatch(pfb map[string]*Fallback, path string) *Fallback {
  567. for {
  568. if val, exists := pfb[path]; exists {
  569. return val
  570. }
  571. if path == "/" {
  572. break
  573. }
  574. path = strings.TrimSuffix(path, "/")
  575. if idx := strings.LastIndex(path, "/"); idx != -1 {
  576. path = path[:idx]
  577. } else {
  578. break
  579. }
  580. }
  581. return nil
  582. }