reverseproxy.go 16 KB

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