reverseproxy.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. // Copyright 2011 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // HTTP reverse proxy handler
  5. package vhost
  6. import (
  7. "context"
  8. "fmt"
  9. "io"
  10. "log"
  11. "net"
  12. "net/http"
  13. "net/textproto"
  14. "net/url"
  15. "strings"
  16. "sync"
  17. "time"
  18. "golang.org/x/net/http/httpguts"
  19. )
  20. // ReverseProxy is an HTTP Handler that takes an incoming request and
  21. // sends it to another server, proxying the response back to the
  22. // client.
  23. //
  24. // ReverseProxy by default sets the client IP as the value of the
  25. // X-Forwarded-For header.
  26. //
  27. // If an X-Forwarded-For header already exists, the client IP is
  28. // appended to the existing values. As a special case, if the header
  29. // exists in the Request.Header map but has a nil value (such as when
  30. // set by the Director func), the X-Forwarded-For header is
  31. // not modified.
  32. //
  33. // To prevent IP spoofing, be sure to delete any pre-existing
  34. // X-Forwarded-For header coming from the client or
  35. // an untrusted proxy.
  36. type ReverseProxy struct {
  37. // Director must be a function which modifies
  38. // the request into a new request to be sent
  39. // using Transport. Its response is then copied
  40. // back to the original client unmodified.
  41. // Director must not access the provided Request
  42. // after returning.
  43. Director func(*http.Request)
  44. // The transport used to perform proxy requests.
  45. // If nil, http.DefaultTransport is used.
  46. Transport http.RoundTripper
  47. // FlushInterval specifies the flush interval
  48. // to flush to the client while copying the
  49. // response body.
  50. // If zero, no periodic flushing is done.
  51. // A negative value means to flush immediately
  52. // after each write to the client.
  53. // The FlushInterval is ignored when ReverseProxy
  54. // recognizes a response as a streaming response, or
  55. // if its ContentLength is -1; for such responses, writes
  56. // are flushed to the client immediately.
  57. FlushInterval time.Duration
  58. // ErrorLog specifies an optional logger for errors
  59. // that occur when attempting to proxy the request.
  60. // If nil, logging is done via the log package's standard logger.
  61. ErrorLog *log.Logger
  62. // BufferPool optionally specifies a buffer pool to
  63. // get byte slices for use by io.CopyBuffer when
  64. // copying HTTP response bodies.
  65. BufferPool BufferPool
  66. // ModifyResponse is an optional function that modifies the
  67. // Response from the backend. It is called if the backend
  68. // returns a response at all, with any HTTP status code.
  69. // If the backend is unreachable, the optional ErrorHandler is
  70. // called without any call to ModifyResponse.
  71. //
  72. // If ModifyResponse returns an error, ErrorHandler is called
  73. // with its error value. If ErrorHandler is nil, its default
  74. // implementation is used.
  75. ModifyResponse func(*http.Response) error
  76. // ErrorHandler is an optional function that handles errors
  77. // reaching the backend or errors from ModifyResponse.
  78. //
  79. // If nil, the default is to log the provided error and return
  80. // a 502 Status Bad Gateway response.
  81. ErrorHandler func(http.ResponseWriter, *http.Request, error)
  82. }
  83. // A BufferPool is an interface for getting and returning temporary
  84. // byte slices for use by io.CopyBuffer.
  85. type BufferPool interface {
  86. Get() []byte
  87. Put([]byte)
  88. }
  89. func singleJoiningSlash(a, b string) string {
  90. aslash := strings.HasSuffix(a, "/")
  91. bslash := strings.HasPrefix(b, "/")
  92. switch {
  93. case aslash && bslash:
  94. return a + b[1:]
  95. case !aslash && !bslash:
  96. return a + "/" + b
  97. }
  98. return a + b
  99. }
  100. func joinURLPath(a, b *url.URL) (path, rawpath string) {
  101. if a.RawPath == "" && b.RawPath == "" {
  102. return singleJoiningSlash(a.Path, b.Path), ""
  103. }
  104. // Same as singleJoiningSlash, but uses EscapedPath to determine
  105. // whether a slash should be added
  106. apath := a.EscapedPath()
  107. bpath := b.EscapedPath()
  108. aslash := strings.HasSuffix(apath, "/")
  109. bslash := strings.HasPrefix(bpath, "/")
  110. switch {
  111. case aslash && bslash:
  112. return a.Path + b.Path[1:], apath + bpath[1:]
  113. case !aslash && !bslash:
  114. return a.Path + "/" + b.Path, apath + "/" + bpath
  115. }
  116. return a.Path + b.Path, apath + bpath
  117. }
  118. // NewSingleHostReverseProxy returns a new ReverseProxy that routes
  119. // URLs to the scheme, host, and base path provided in target. If the
  120. // target's path is "/base" and the incoming request was for "/dir",
  121. // the target request will be for /base/dir.
  122. // NewSingleHostReverseProxy does not rewrite the Host header.
  123. // To rewrite Host headers, use ReverseProxy directly with a custom
  124. // Director policy.
  125. func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy {
  126. targetQuery := target.RawQuery
  127. director := func(req *http.Request) {
  128. req.URL.Scheme = target.Scheme
  129. req.URL.Host = target.Host
  130. req.URL.Path, req.URL.RawPath = joinURLPath(target, req.URL)
  131. if targetQuery == "" || req.URL.RawQuery == "" {
  132. req.URL.RawQuery = targetQuery + req.URL.RawQuery
  133. } else {
  134. req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
  135. }
  136. if _, ok := req.Header["User-Agent"]; !ok {
  137. // explicitly disable User-Agent so it's not set to default value
  138. req.Header.Set("User-Agent", "")
  139. }
  140. }
  141. return &ReverseProxy{Director: director}
  142. }
  143. func copyHeader(dst, src http.Header) {
  144. for k, vv := range src {
  145. for _, v := range vv {
  146. dst.Add(k, v)
  147. }
  148. }
  149. }
  150. // Hop-by-hop headers. These are removed when sent to the backend.
  151. // As of RFC 7230, hop-by-hop headers are required to appear in the
  152. // Connection header field. These are the headers defined by the
  153. // obsoleted RFC 2616 (section 13.5.1) and are used for backward
  154. // compatibility.
  155. var hopHeaders = []string{
  156. "Connection",
  157. "Proxy-Connection", // non-standard but still sent by libcurl and rejected by e.g. google
  158. "Keep-Alive",
  159. "Proxy-Authenticate",
  160. "Proxy-Authorization",
  161. "Te", // canonicalized version of "TE"
  162. "Trailer", // not Trailers per URL above; https://www.rfc-editor.org/errata_search.php?eid=4522
  163. "Transfer-Encoding",
  164. "Upgrade",
  165. }
  166. func (p *ReverseProxy) defaultErrorHandler(rw http.ResponseWriter, req *http.Request, err error) {
  167. p.logf("http: proxy error: %v", err)
  168. rw.WriteHeader(http.StatusBadGateway)
  169. }
  170. func (p *ReverseProxy) getErrorHandler() func(http.ResponseWriter, *http.Request, error) {
  171. if p.ErrorHandler != nil {
  172. return p.ErrorHandler
  173. }
  174. return p.defaultErrorHandler
  175. }
  176. // modifyResponse conditionally runs the optional ModifyResponse hook
  177. // and reports whether the request should proceed.
  178. func (p *ReverseProxy) modifyResponse(rw http.ResponseWriter, res *http.Response, req *http.Request) bool {
  179. if p.ModifyResponse == nil {
  180. return true
  181. }
  182. if err := p.ModifyResponse(res); err != nil {
  183. res.Body.Close()
  184. p.getErrorHandler()(rw, req, err)
  185. return false
  186. }
  187. return true
  188. }
  189. func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
  190. transport := p.Transport
  191. if transport == nil {
  192. transport = http.DefaultTransport
  193. }
  194. ctx := req.Context()
  195. if cn, ok := rw.(http.CloseNotifier); ok {
  196. var cancel context.CancelFunc
  197. ctx, cancel = context.WithCancel(ctx)
  198. defer cancel()
  199. notifyChan := cn.CloseNotify()
  200. go func() {
  201. select {
  202. case <-notifyChan:
  203. cancel()
  204. case <-ctx.Done():
  205. }
  206. }()
  207. }
  208. outreq := req.Clone(ctx)
  209. if req.ContentLength == 0 {
  210. outreq.Body = nil // Issue 16036: nil Body for http.Transport retries
  211. }
  212. if outreq.Header == nil {
  213. outreq.Header = make(http.Header) // Issue 33142: historical behavior was to always allocate
  214. }
  215. // =============================
  216. // Modified for frp
  217. outreq = outreq.Clone(context.WithValue(outreq.Context(), RouteInfoURL, req.URL.Path))
  218. outreq = outreq.Clone(context.WithValue(outreq.Context(), RouteInfoHost, req.Host))
  219. outreq = outreq.Clone(context.WithValue(outreq.Context(), RouteInfoRemote, req.RemoteAddr))
  220. // =============================
  221. p.Director(outreq)
  222. outreq.Close = false
  223. reqUpType := upgradeType(outreq.Header)
  224. removeConnectionHeaders(outreq.Header)
  225. // Remove hop-by-hop headers to the backend. Especially
  226. // important is "Connection" because we want a persistent
  227. // connection, regardless of what the client sent to us.
  228. for _, h := range hopHeaders {
  229. hv := outreq.Header.Get(h)
  230. if hv == "" {
  231. continue
  232. }
  233. if h == "Te" && hv == "trailers" {
  234. // Issue 21096: tell backend applications that
  235. // care about trailer support that we support
  236. // trailers. (We do, but we don't go out of
  237. // our way to advertise that unless the
  238. // incoming client request thought it was
  239. // worth mentioning)
  240. continue
  241. }
  242. outreq.Header.Del(h)
  243. }
  244. // After stripping all the hop-by-hop connection headers above, add back any
  245. // necessary for protocol upgrades, such as for websockets.
  246. if reqUpType != "" {
  247. outreq.Header.Set("Connection", "Upgrade")
  248. outreq.Header.Set("Upgrade", reqUpType)
  249. }
  250. if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
  251. // If we aren't the first proxy retain prior
  252. // X-Forwarded-For information as a comma+space
  253. // separated list and fold multiple headers into one.
  254. prior, ok := outreq.Header["X-Forwarded-For"]
  255. omit := ok && prior == nil // Issue 38079: nil now means don't populate the header
  256. if len(prior) > 0 {
  257. clientIP = strings.Join(prior, ", ") + ", " + clientIP
  258. }
  259. if !omit {
  260. outreq.Header.Set("X-Forwarded-For", clientIP)
  261. }
  262. }
  263. res, err := transport.RoundTrip(outreq)
  264. if err != nil {
  265. p.getErrorHandler()(rw, outreq, err)
  266. return
  267. }
  268. // Deal with 101 Switching Protocols responses: (WebSocket, h2c, etc)
  269. if res.StatusCode == http.StatusSwitchingProtocols {
  270. if !p.modifyResponse(rw, res, outreq) {
  271. return
  272. }
  273. p.handleUpgradeResponse(rw, outreq, res)
  274. return
  275. }
  276. removeConnectionHeaders(res.Header)
  277. for _, h := range hopHeaders {
  278. res.Header.Del(h)
  279. }
  280. if !p.modifyResponse(rw, res, outreq) {
  281. return
  282. }
  283. copyHeader(rw.Header(), res.Header)
  284. // The "Trailer" header isn't included in the Transport's response,
  285. // at least for *http.Transport. Build it up from Trailer.
  286. announcedTrailers := len(res.Trailer)
  287. if announcedTrailers > 0 {
  288. trailerKeys := make([]string, 0, len(res.Trailer))
  289. for k := range res.Trailer {
  290. trailerKeys = append(trailerKeys, k)
  291. }
  292. rw.Header().Add("Trailer", strings.Join(trailerKeys, ", "))
  293. }
  294. rw.WriteHeader(res.StatusCode)
  295. err = p.copyResponse(rw, res.Body, p.flushInterval(res))
  296. if err != nil {
  297. defer res.Body.Close()
  298. // Since we're streaming the response, if we run into an error all we can do
  299. // is abort the request. Issue 23643: ReverseProxy should use ErrAbortHandler
  300. // on read error while copying body.
  301. if !shouldPanicOnCopyError(req) {
  302. p.logf("suppressing panic for copyResponse error in test; copy error: %v", err)
  303. return
  304. }
  305. panic(http.ErrAbortHandler)
  306. }
  307. res.Body.Close() // close now, instead of defer, to populate res.Trailer
  308. if len(res.Trailer) > 0 {
  309. // Force chunking if we saw a response trailer.
  310. // This prevents net/http from calculating the length for short
  311. // bodies and adding a Content-Length.
  312. if fl, ok := rw.(http.Flusher); ok {
  313. fl.Flush()
  314. }
  315. }
  316. if len(res.Trailer) == announcedTrailers {
  317. copyHeader(rw.Header(), res.Trailer)
  318. return
  319. }
  320. for k, vv := range res.Trailer {
  321. k = http.TrailerPrefix + k
  322. for _, v := range vv {
  323. rw.Header().Add(k, v)
  324. }
  325. }
  326. }
  327. var inOurTests bool // whether we're in our own tests
  328. // shouldPanicOnCopyError reports whether the reverse proxy should
  329. // panic with http.ErrAbortHandler. This is the right thing to do by
  330. // default, but Go 1.10 and earlier did not, so existing unit tests
  331. // weren't expecting panics. Only panic in our own tests, or when
  332. // running under the HTTP server.
  333. func shouldPanicOnCopyError(req *http.Request) bool {
  334. if inOurTests {
  335. // Our tests know to handle this panic.
  336. return true
  337. }
  338. if req.Context().Value(http.ServerContextKey) != nil {
  339. // We seem to be running under an HTTP server, so
  340. // it'll recover the panic.
  341. return true
  342. }
  343. // Otherwise act like Go 1.10 and earlier to not break
  344. // existing tests.
  345. return false
  346. }
  347. // removeConnectionHeaders removes hop-by-hop headers listed in the "Connection" header of h.
  348. // See RFC 7230, section 6.1
  349. func removeConnectionHeaders(h http.Header) {
  350. for _, f := range h["Connection"] {
  351. for _, sf := range strings.Split(f, ",") {
  352. if sf = textproto.TrimString(sf); sf != "" {
  353. h.Del(sf)
  354. }
  355. }
  356. }
  357. }
  358. // flushInterval returns the p.FlushInterval value, conditionally
  359. // overriding its value for a specific request/response.
  360. func (p *ReverseProxy) flushInterval(res *http.Response) time.Duration {
  361. resCT := res.Header.Get("Content-Type")
  362. // For Server-Sent Events responses, flush immediately.
  363. // The MIME type is defined in https://www.w3.org/TR/eventsource/#text-event-stream
  364. if resCT == "text/event-stream" {
  365. return -1 // negative means immediately
  366. }
  367. // We might have the case of streaming for which Content-Length might be unset.
  368. if res.ContentLength == -1 {
  369. return -1
  370. }
  371. return p.FlushInterval
  372. }
  373. func (p *ReverseProxy) copyResponse(dst io.Writer, src io.Reader, flushInterval time.Duration) error {
  374. if flushInterval != 0 {
  375. if wf, ok := dst.(writeFlusher); ok {
  376. mlw := &maxLatencyWriter{
  377. dst: wf,
  378. latency: flushInterval,
  379. }
  380. defer mlw.stop()
  381. // set up initial timer so headers get flushed even if body writes are delayed
  382. mlw.flushPending = true
  383. mlw.t = time.AfterFunc(flushInterval, mlw.delayedFlush)
  384. dst = mlw
  385. }
  386. }
  387. var buf []byte
  388. if p.BufferPool != nil {
  389. buf = p.BufferPool.Get()
  390. defer p.BufferPool.Put(buf)
  391. }
  392. _, err := p.copyBuffer(dst, src, buf)
  393. return err
  394. }
  395. // copyBuffer returns any write errors or non-EOF read errors, and the amount
  396. // of bytes written.
  397. func (p *ReverseProxy) copyBuffer(dst io.Writer, src io.Reader, buf []byte) (int64, error) {
  398. if len(buf) == 0 {
  399. buf = make([]byte, 32*1024)
  400. }
  401. var written int64
  402. for {
  403. nr, rerr := src.Read(buf)
  404. if rerr != nil && rerr != io.EOF && rerr != context.Canceled {
  405. p.logf("httputil: ReverseProxy read error during body copy: %v", rerr)
  406. }
  407. if nr > 0 {
  408. nw, werr := dst.Write(buf[:nr])
  409. if nw > 0 {
  410. written += int64(nw)
  411. }
  412. if werr != nil {
  413. return written, werr
  414. }
  415. if nr != nw {
  416. return written, io.ErrShortWrite
  417. }
  418. }
  419. if rerr != nil {
  420. if rerr == io.EOF {
  421. rerr = nil
  422. }
  423. return written, rerr
  424. }
  425. }
  426. }
  427. func (p *ReverseProxy) logf(format string, args ...interface{}) {
  428. if p.ErrorLog != nil {
  429. p.ErrorLog.Printf(format, args...)
  430. } else {
  431. log.Printf(format, args...)
  432. }
  433. }
  434. type writeFlusher interface {
  435. io.Writer
  436. http.Flusher
  437. }
  438. type maxLatencyWriter struct {
  439. dst writeFlusher
  440. latency time.Duration // non-zero; negative means to flush immediately
  441. mu sync.Mutex // protects t, flushPending, and dst.Flush
  442. t *time.Timer
  443. flushPending bool
  444. }
  445. func (m *maxLatencyWriter) Write(p []byte) (n int, err error) {
  446. m.mu.Lock()
  447. defer m.mu.Unlock()
  448. n, err = m.dst.Write(p)
  449. if m.latency < 0 {
  450. m.dst.Flush()
  451. return
  452. }
  453. if m.flushPending {
  454. return
  455. }
  456. if m.t == nil {
  457. m.t = time.AfterFunc(m.latency, m.delayedFlush)
  458. } else {
  459. m.t.Reset(m.latency)
  460. }
  461. m.flushPending = true
  462. return
  463. }
  464. func (m *maxLatencyWriter) delayedFlush() {
  465. m.mu.Lock()
  466. defer m.mu.Unlock()
  467. if !m.flushPending { // if stop was called but AfterFunc already started this goroutine
  468. return
  469. }
  470. m.dst.Flush()
  471. m.flushPending = false
  472. }
  473. func (m *maxLatencyWriter) stop() {
  474. m.mu.Lock()
  475. defer m.mu.Unlock()
  476. m.flushPending = false
  477. if m.t != nil {
  478. m.t.Stop()
  479. }
  480. }
  481. func upgradeType(h http.Header) string {
  482. if !httpguts.HeaderValuesContainsToken(h["Connection"], "Upgrade") {
  483. return ""
  484. }
  485. return strings.ToLower(h.Get("Upgrade"))
  486. }
  487. func (p *ReverseProxy) handleUpgradeResponse(rw http.ResponseWriter, req *http.Request, res *http.Response) {
  488. reqUpType := upgradeType(req.Header)
  489. resUpType := upgradeType(res.Header)
  490. if reqUpType != resUpType {
  491. p.getErrorHandler()(rw, req, fmt.Errorf("backend tried to switch protocol %q when %q was requested", resUpType, reqUpType))
  492. return
  493. }
  494. hj, ok := rw.(http.Hijacker)
  495. if !ok {
  496. p.getErrorHandler()(rw, req, fmt.Errorf("can't switch protocols using non-Hijacker ResponseWriter type %T", rw))
  497. return
  498. }
  499. backConn, ok := res.Body.(io.ReadWriteCloser)
  500. if !ok {
  501. p.getErrorHandler()(rw, req, fmt.Errorf("internal error: 101 switching protocols response with non-writable body"))
  502. return
  503. }
  504. backConnCloseCh := make(chan bool)
  505. go func() {
  506. // Ensure that the cancelation of a request closes the backend.
  507. // See issue https://golang.org/issue/35559.
  508. select {
  509. case <-req.Context().Done():
  510. case <-backConnCloseCh:
  511. }
  512. backConn.Close()
  513. }()
  514. defer close(backConnCloseCh)
  515. conn, brw, err := hj.Hijack()
  516. if err != nil {
  517. p.getErrorHandler()(rw, req, fmt.Errorf("Hijack failed on protocol switch: %v", err))
  518. return
  519. }
  520. defer conn.Close()
  521. copyHeader(rw.Header(), res.Header)
  522. res.Header = rw.Header()
  523. res.Body = nil // so res.Write only writes the headers; we have res.Body in backConn above
  524. if err := res.Write(brw); err != nil {
  525. p.getErrorHandler()(rw, req, fmt.Errorf("response write: %v", err))
  526. return
  527. }
  528. if err := brw.Flush(); err != nil {
  529. p.getErrorHandler()(rw, req, fmt.Errorf("response flush: %v", err))
  530. return
  531. }
  532. errc := make(chan error, 1)
  533. spc := switchProtocolCopier{user: conn, backend: backConn}
  534. go spc.copyToBackend(errc)
  535. go spc.copyFromBackend(errc)
  536. <-errc
  537. return
  538. }
  539. // switchProtocolCopier exists so goroutines proxying data back and
  540. // forth have nice names in stacks.
  541. type switchProtocolCopier struct {
  542. user, backend io.ReadWriter
  543. }
  544. func (c switchProtocolCopier) copyFromBackend(errc chan<- error) {
  545. _, err := io.Copy(c.user, c.backend)
  546. errc <- err
  547. }
  548. func (c switchProtocolCopier) copyToBackend(errc chan<- error) {
  549. _, err := io.Copy(c.backend, c.user)
  550. errc <- err
  551. }