Debian Codegraph @

src/net/http/httputil/reverseproxy.go

raw
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
5 // HTTP reverse proxy handler
6
7 package httputil
8
9 import (
10 "context"
11 "errors"
12 "fmt"
13 "internal/godebug"
14 "io"
15 "log"
16 "mime"
17 "net"
18 "net/http"
19 "net/http/httptrace"
20 "net/http/internal/ascii"
21 "net/textproto"
22 "net/url"
23 "strings"
24 "sync"
25 "time"
26
27 "golang.org/x/net/http/httpguts"
28 )
29
30 // A ProxyRequest contains a request to be rewritten by a [ReverseProxy].
31 type ProxyRequest struct {
32 // In is the request received by the proxy.
33 // The Rewrite function must not modify In.
34 In *http.Request
35
36 // Out is the request which will be sent by the proxy.
37 // The Rewrite function may modify or replace this request.
38 // Hop-by-hop headers are removed from this request
39 // before Rewrite is called.
40 Out *http.Request
41 }
42
43 // SetURL routes the outbound request to the scheme, host, and base path
44 // provided in target. If the target's path is "/base" and the incoming
45 // request was for "/dir", the target request will be for "/base/dir".
46 // To route requests without joining the incoming path,
47 // set r.Out.URL directly.
48 //
49 // SetURL rewrites the outbound Host header to match the target's host.
50 // To preserve the inbound request's Host header (the default behavior
51 // of [NewSingleHostReverseProxy]):
52 //
53 // rewriteFunc := func(r *httputil.ProxyRequest) {
54 // r.SetURL(url)
55 // r.Out.Host = r.In.Host
56 // }
57 func (r *ProxyRequest) SetURL(target *url.URL) {
58 rewriteRequestURL(r.Out, target)
59 r.Out.Host = ""
60 }
61
62 // SetXForwarded sets the X-Forwarded-For, X-Forwarded-Host, and
63 // X-Forwarded-Proto headers of the outbound request.
64 //
65 // - The X-Forwarded-For header is set to the client IP address.
66 // - The X-Forwarded-Host header is set to the host name requested
67 // by the client.
68 // - The X-Forwarded-Proto header is set to "http" or "https", depending
69 // on whether the inbound request was made on a TLS-enabled connection.
70 //
71 // If the outbound request contains an existing X-Forwarded-For header,
72 // SetXForwarded appends the client IP address to it. To append to the
73 // inbound request's X-Forwarded-For header (the default behavior of
74 // [ReverseProxy] when using a Director function), copy the header
75 // from the inbound request before calling SetXForwarded:
76 //
77 // rewriteFunc := func(r *httputil.ProxyRequest) {
78 // r.Out.Header["X-Forwarded-For"] = r.In.Header["X-Forwarded-For"]
79 // r.SetXForwarded()
80 // }
81 func (r *ProxyRequest) SetXForwarded() {
82 clientIP, _, err := net.SplitHostPort(r.In.RemoteAddr)
83 if err == nil {
84 prior := r.Out.Header["X-Forwarded-For"]
85 if len(prior) > 0 {
86 clientIP = strings.Join(prior, ", ") + ", " + clientIP
87 }
88 r.Out.Header.Set("X-Forwarded-For", clientIP)
89 } else {
90 r.Out.Header.Del("X-Forwarded-For")
91 }
92 r.Out.Header.Set("X-Forwarded-Host", r.In.Host)
93 if r.In.TLS == nil {
94 r.Out.Header.Set("X-Forwarded-Proto", "http")
95 } else {
96 r.Out.Header.Set("X-Forwarded-Proto", "https")
97 }
98 }
99
100 // ReverseProxy is an HTTP Handler that takes an incoming request and
101 // sends it to another server, proxying the response back to the
102 // client.
103 //
104 // 1xx responses are forwarded to the client if the underlying
105 // transport supports ClientTrace.Got1xxResponse.
106 //
107 // Hop-by-hop headers (see RFC 9110, section 7.6.1), including
108 // Connection, Proxy-Connection, Keep-Alive, Proxy-Authenticate,
109 // Proxy-Authorization, TE, Trailer, Transfer-Encoding, and Upgrade,
110 // are removed from client requests and backend responses.
111 // The Rewrite function may be used to add hop-by-hop headers to the request,
112 // and the ModifyResponse function may be used to remove them from the response.
113 type ReverseProxy struct {
114 // Rewrite must be a function which modifies
115 // the request into a new request to be sent
116 // using Transport. Its response is then copied
117 // back to the original client unmodified.
118 // Rewrite must not access the provided ProxyRequest
119 // or its contents after returning.
120 //
121 // The Forwarded, X-Forwarded, X-Forwarded-Host,
122 // and X-Forwarded-Proto headers are removed from the
123 // outbound request before Rewrite is called. See also
124 // the ProxyRequest.SetXForwarded method.
125 //
126 // Unparsable query parameters are removed from the
127 // outbound request before Rewrite is called.
128 // The Rewrite function may copy the inbound URL's
129 // RawQuery to the outbound URL to preserve the original
130 // parameter string. Note that this can lead to security
131 // issues if the proxy's interpretation of query parameters
132 // does not match that of the downstream server.
133 //
134 // At most one of Rewrite or Director may be set.
135 Rewrite func(*ProxyRequest)
136
137 // Director is a function which modifies
138 // the request into a new request to be sent
139 // using Transport. Its response is then copied
140 // back to the original client unmodified.
141 // Director must not access the provided Request
142 // after returning.
143 //
144 // By default, the X-Forwarded-For header is set to the
145 // value of the client IP address. If an X-Forwarded-For
146 // header already exists, the client IP is appended to the
147 // existing values. As a special case, if the header
148 // exists in the Request.Header map but has a nil value
149 // (such as when set by the Director func), the X-Forwarded-For
150 // header is not modified.
151 //
152 // To prevent IP spoofing, be sure to delete any pre-existing
153 // X-Forwarded-For header coming from the client or
154 // an untrusted proxy.
155 //
156 // Hop-by-hop headers are removed from the request after
157 // Director returns, which can remove headers added by
158 // Director. Use a Rewrite function instead to ensure
159 // modifications to the request are preserved.
160 //
161 // Unparsable query parameters are removed from the outbound
162 // request if Request.Form is set after Director returns.
163 //
164 // At most one of Rewrite or Director may be set.
165 Director func(*http.Request)
166
167 // The transport used to perform proxy requests.
168 // If nil, http.DefaultTransport is used.
169 Transport http.RoundTripper
170
171 // FlushInterval specifies the flush interval
172 // to flush to the client while copying the
173 // response body.
174 // If zero, no periodic flushing is done.
175 // A negative value means to flush immediately
176 // after each write to the client.
177 // The FlushInterval is ignored when ReverseProxy
178 // recognizes a response as a streaming response, or
179 // if its ContentLength is -1; for such responses, writes
180 // are flushed to the client immediately.
181 FlushInterval time.Duration
182
183 // ErrorLog specifies an optional logger for errors
184 // that occur when attempting to proxy the request.
185 // If nil, logging is done via the log package's standard logger.
186 ErrorLog *log.Logger
187
188 // BufferPool optionally specifies a buffer pool to
189 // get byte slices for use by io.CopyBuffer when
190 // copying HTTP response bodies.
191 BufferPool BufferPool
192
193 // ModifyResponse is an optional function that modifies the
194 // Response from the backend. It is called if the backend
195 // returns a response at all, with any HTTP status code.
196 // If the backend is unreachable, the optional ErrorHandler is
197 // called without any call to ModifyResponse.
198 //
199 // Hop-by-hop headers are removed from the response before
200 // calling ModifyResponse. ModifyResponse may need to remove
201 // additional headers to fit its deployment model, such as Alt-Svc.
202 //
203 // If ModifyResponse returns an error, ErrorHandler is called
204 // with its error value. If ErrorHandler is nil, its default
205 // implementation is used.
206 ModifyResponse func(*http.Response) error
207
208 // ErrorHandler is an optional function that handles errors
209 // reaching the backend or errors from ModifyResponse.
210 //
211 // If nil, the default is to log the provided error and return
212 // a 502 Status Bad Gateway response.
213 ErrorHandler func(http.ResponseWriter, *http.Request, error)
214 }
215
216 // A BufferPool is an interface for getting and returning temporary
217 // byte slices for use by [io.CopyBuffer].
218 type BufferPool interface {
219 Get() []byte
220 Put([]byte)
221 }
222
223 func singleJoiningSlash(a, b string) string {
224 aslash := strings.HasSuffix(a, "/")
225 bslash := strings.HasPrefix(b, "/")
226 switch {
227 case aslash && bslash:
228 return a + b[1:]
229 case !aslash && !bslash:
230 return a + "/" + b
231 }
232 return a + b
233 }
234
235 func joinURLPath(a, b *url.URL) (path, rawpath string) {
236 if a.RawPath == "" && b.RawPath == "" {
237 return singleJoiningSlash(a.Path, b.Path), ""
238 }
239 // Same as singleJoiningSlash, but uses EscapedPath to determine
240 // whether a slash should be added
241 apath := a.EscapedPath()
242 bpath := b.EscapedPath()
243
244 aslash := strings.HasSuffix(apath, "/")
245 bslash := strings.HasPrefix(bpath, "/")
246
247 switch {
248 case aslash && bslash:
249 return a.Path + b.Path[1:], apath + bpath[1:]
250 case !aslash && !bslash:
251 return a.Path + "/" + b.Path, apath + "/" + bpath
252 }
253 return a.Path + b.Path, apath + bpath
254 }
255
256 // NewSingleHostReverseProxy returns a new [ReverseProxy] that routes
257 // URLs to the scheme, host, and base path provided in target. If the
258 // target's path is "/base" and the incoming request was for "/dir",
259 // the target request will be for /base/dir.
260 //
261 // NewSingleHostReverseProxy does not rewrite the Host header.
262 //
263 // To customize the ReverseProxy behavior beyond what
264 // NewSingleHostReverseProxy provides, use ReverseProxy directly
265 // with a Rewrite function. The ProxyRequest SetURL method
266 // may be used to route the outbound request. (Note that SetURL,
267 // unlike NewSingleHostReverseProxy, rewrites the Host header
268 // of the outbound request by default.)
269 //
270 // proxy := &ReverseProxy{
271 // Rewrite: func(r *ProxyRequest) {
272 // r.SetURL(target)
273 // r.Out.Host = r.In.Host // if desired
274 // },
275 // }
276 func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy {
277 director := func(req *http.Request) {
278 rewriteRequestURL(req, target)
279 }
280 return &ReverseProxy{Director: director}
281 }
282
283 func rewriteRequestURL(req *http.Request, target *url.URL) {
284 targetQuery := target.RawQuery
285 req.URL.Scheme = target.Scheme
286 req.URL.Host = target.Host
287 req.URL.Path, req.URL.RawPath = joinURLPath(target, req.URL)
288 if targetQuery == "" || req.URL.RawQuery == "" {
289 req.URL.RawQuery = targetQuery + req.URL.RawQuery
290 } else {
291 req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
292 }
293 }
294
295 func copyHeader(dst, src http.Header) {
296 for k, vv := range src {
297 for _, v := range vv {
298 dst.Add(k, v)
299 }
300 }
301 }
302
303 // Hop-by-hop headers. These are removed when sent to the backend.
304 // As of RFC 7230, hop-by-hop headers are required to appear in the
305 // Connection header field. These are the headers defined by the
306 // obsoleted RFC 2616 (section 13.5.1) and are used for backward
307 // compatibility.
308 var hopHeaders = []string{
309 "Connection",
310 "Proxy-Connection", // non-standard but still sent by libcurl and rejected by e.g. google
311 "Keep-Alive",
312 "Proxy-Authenticate",
313 "Proxy-Authorization",
314 "Te", // canonicalized version of "TE"
315 "Trailer", // not Trailers per URL above; https://www.rfc-editor.org/errata_search.php?eid=4522
316 "Transfer-Encoding",
317 "Upgrade",
318 }
319
320 func (p *ReverseProxy) defaultErrorHandler(rw http.ResponseWriter, req *http.Request, err error) {
321 p.logf("http: proxy error: %v", err)
322 rw.WriteHeader(http.StatusBadGateway)
323 }
324
325 func (p *ReverseProxy) getErrorHandler() func(http.ResponseWriter, *http.Request, error) {
326 if p.ErrorHandler != nil {
327 return p.ErrorHandler
328 }
329 return p.defaultErrorHandler
330 }
331
332 // modifyResponse conditionally runs the optional ModifyResponse hook
333 // and reports whether the request should proceed.
334 func (p *ReverseProxy) modifyResponse(rw http.ResponseWriter, res *http.Response, req *http.Request) bool {
335 if p.ModifyResponse == nil {
336 return true
337 }
338 if err := p.ModifyResponse(res); err != nil {
339 res.Body.Close()
340 p.getErrorHandler()(rw, req, err)
341 return false
342 }
343 return true
344 }
345
346 func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
347 transport := p.Transport
348 if transport == nil {
349 transport = http.DefaultTransport
350 }
351
352 ctx := req.Context()
353 if ctx.Done() != nil {
354 // CloseNotifier predates context.Context, and has been
355 // entirely superseded by it. If the request contains
356 // a Context that carries a cancellation signal, don't
357 // bother spinning up a goroutine to watch the CloseNotify
358 // channel (if any).
359 //
360 // If the request Context has a nil Done channel (which
361 // means it is either context.Background, or a custom
362 // Context implementation with no cancellation signal),
363 // then consult the CloseNotifier if available.
364 } else if cn, ok := rw.(http.CloseNotifier); ok {
365 var cancel context.CancelFunc
366 ctx, cancel = context.WithCancel(ctx)
367 defer cancel()
368 notifyChan := cn.CloseNotify()
369 go func() {
370 select {
371 case <-notifyChan:
372 cancel()
373 case <-ctx.Done():
374 }
375 }()
376 }
377
378 outreq := req.Clone(ctx)
379 if req.ContentLength == 0 {
380 outreq.Body = nil // Issue 16036: nil Body for http.Transport retries
381 }
382 if outreq.Body != nil {
383 // Reading from the request body after returning from a handler is not
384 // allowed, and the RoundTrip goroutine that reads the Body can outlive
385 // this handler. This can lead to a crash if the handler panics (see
386 // Issue 46866). Although calling Close doesn't guarantee there isn't
387 // any Read in flight after the handle returns, in practice it's safe to
388 // read after closing it.
389 defer outreq.Body.Close()
390 }
391 if outreq.Header == nil {
392 outreq.Header = make(http.Header) // Issue 33142: historical behavior was to always allocate
393 }
394
395 if (p.Director != nil) == (p.Rewrite != nil) {
396 p.getErrorHandler()(rw, req, errors.New("ReverseProxy must have exactly one of Director or Rewrite set"))
397 return
398 }
399
400 if p.Director != nil {
401 p.Director(outreq)
402 if outreq.Form != nil {
403 outreq.URL.RawQuery = cleanQueryParams(outreq.URL.RawQuery)
404 }
405 }
406 outreq.Close = false
407
408 reqUpType := upgradeType(outreq.Header)
409 if !ascii.IsPrint(reqUpType) {
410 p.getErrorHandler()(rw, req, fmt.Errorf("client tried to switch to invalid protocol %q", reqUpType))
411 return
412 }
413 removeHopByHopHeaders(outreq.Header)
414
415 // Issue 21096: tell backend applications that care about trailer support
416 // that we support trailers. (We do, but we don't go out of our way to
417 // advertise that unless the incoming client request thought it was worth
418 // mentioning.) Note that we look at req.Header, not outreq.Header, since
419 // the latter has passed through removeHopByHopHeaders.
420 if httpguts.HeaderValuesContainsToken(req.Header["Te"], "trailers") {
421 outreq.Header.Set("Te", "trailers")
422 }
423
424 // After stripping all the hop-by-hop connection headers above, add back any
425 // necessary for protocol upgrades, such as for websockets.
426 if reqUpType != "" {
427 outreq.Header.Set("Connection", "Upgrade")
428 outreq.Header.Set("Upgrade", reqUpType)
429 }
430
431 if p.Rewrite != nil {
432 // Strip client-provided forwarding headers.
433 // The Rewrite func may use SetXForwarded to set new values
434 // for these or copy the previous values from the inbound request.
435 outreq.Header.Del("Forwarded")
436 outreq.Header.Del("X-Forwarded-For")
437 outreq.Header.Del("X-Forwarded-Host")
438 outreq.Header.Del("X-Forwarded-Proto")
439
440 // Remove unparsable query parameters from the outbound request.
441 outreq.URL.RawQuery = cleanQueryParams(outreq.URL.RawQuery)
442
443 pr := &ProxyRequest{
444 In: req,
445 Out: outreq,
446 }
447 p.Rewrite(pr)
448 outreq = pr.Out
449 } else {
450 if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
451 // If we aren't the first proxy retain prior
452 // X-Forwarded-For information as a comma+space
453 // separated list and fold multiple headers into one.
454 prior, ok := outreq.Header["X-Forwarded-For"]
455 omit := ok && prior == nil // Issue 38079: nil now means don't populate the header
456 if len(prior) > 0 {
457 clientIP = strings.Join(prior, ", ") + ", " + clientIP
458 }
459 if !omit {
460 outreq.Header.Set("X-Forwarded-For", clientIP)
461 }
462 }
463 }
464
465 if _, ok := outreq.Header["User-Agent"]; !ok {
466 // If the outbound request doesn't have a User-Agent header set,
467 // don't send the default Go HTTP client User-Agent.
468 outreq.Header.Set("User-Agent", "")
469 }
470
471 var (
472 roundTripMutex sync.Mutex
473 roundTripDone bool
474 )
475 trace := &httptrace.ClientTrace{
476 Got1xxResponse: func(code int, header textproto.MIMEHeader) error {
477 roundTripMutex.Lock()
478 defer roundTripMutex.Unlock()
479 if roundTripDone {
480 // If RoundTrip has returned, don't try to further modify
481 // the ResponseWriter's header map.
482 return nil
483 }
484 h := rw.Header()
485 copyHeader(h, http.Header(header))
486 rw.WriteHeader(code)
487
488 // Clear headers, it's not automatically done by ResponseWriter.WriteHeader() for 1xx responses
489 clear(h)
490 return nil
491 },
492 }
493 outreq = outreq.WithContext(httptrace.WithClientTrace(outreq.Context(), trace))
494
495 res, err := transport.RoundTrip(outreq)
496 roundTripMutex.Lock()
497 roundTripDone = true
498 roundTripMutex.Unlock()
499 if err != nil {
500 p.getErrorHandler()(rw, outreq, err)
501 return
502 }
503
504 // Deal with 101 Switching Protocols responses: (WebSocket, h2c, etc)
505 if res.StatusCode == http.StatusSwitchingProtocols {
506 if !p.modifyResponse(rw, res, outreq) {
507 return
508 }
509 p.handleUpgradeResponse(rw, outreq, res)
510 return
511 }
512
513 removeHopByHopHeaders(res.Header)
514
515 if !p.modifyResponse(rw, res, outreq) {
516 return
517 }
518
519 copyHeader(rw.Header(), res.Header)
520
521 // The "Trailer" header isn't included in the Transport's response,
522 // at least for *http.Transport. Build it up from Trailer.
523 announcedTrailers := len(res.Trailer)
524 if announcedTrailers > 0 {
525 trailerKeys := make([]string, 0, len(res.Trailer))
526 for k := range res.Trailer {
527 trailerKeys = append(trailerKeys, k)
528 }
529 rw.Header().Add("Trailer", strings.Join(trailerKeys, ", "))
530 }
531
532 rw.WriteHeader(res.StatusCode)
533
534 err = p.copyResponse(rw, res.Body, p.flushInterval(res))
535 if err != nil {
536 defer res.Body.Close()
537 // Since we're streaming the response, if we run into an error all we can do
538 // is abort the request. Issue 23643: ReverseProxy should use ErrAbortHandler
539 // on read error while copying body.
540 if !shouldPanicOnCopyError(req) {
541 p.logf("suppressing panic for copyResponse error in test; copy error: %v", err)
542 return
543 }
544 panic(http.ErrAbortHandler)
545 }
546 res.Body.Close() // close now, instead of defer, to populate res.Trailer
547
548 if len(res.Trailer) > 0 {
549 // Force chunking if we saw a response trailer.
550 // This prevents net/http from calculating the length for short
551 // bodies and adding a Content-Length.
552 http.NewResponseController(rw).Flush()
553 }
554
555 if len(res.Trailer) == announcedTrailers {
556 copyHeader(rw.Header(), res.Trailer)
557 return
558 }
559
560 for k, vv := range res.Trailer {
561 k = http.TrailerPrefix + k
562 for _, v := range vv {
563 rw.Header().Add(k, v)
564 }
565 }
566 }
567
568 var inOurTests bool // whether we're in our own tests
569
570 // shouldPanicOnCopyError reports whether the reverse proxy should
571 // panic with http.ErrAbortHandler. This is the right thing to do by
572 // default, but Go 1.10 and earlier did not, so existing unit tests
573 // weren't expecting panics. Only panic in our own tests, or when
574 // running under the HTTP server.
575 func shouldPanicOnCopyError(req *http.Request) bool {
576 if inOurTests {
577 // Our tests know to handle this panic.
578 return true
579 }
580 if req.Context().Value(http.ServerContextKey) != nil {
581 // We seem to be running under an HTTP server, so
582 // it'll recover the panic.
583 return true
584 }
585 // Otherwise act like Go 1.10 and earlier to not break
586 // existing tests.
587 return false
588 }
589
590 // removeHopByHopHeaders removes hop-by-hop headers.
591 func removeHopByHopHeaders(h http.Header) {
592 // RFC 7230, section 6.1: Remove headers listed in the "Connection" header.
593 for _, f := range h["Connection"] {
594 for sf := range strings.SplitSeq(f, ",") {
595 if sf = textproto.TrimString(sf); sf != "" {
596 h.Del(sf)
597 }
598 }
599 }
600 // RFC 2616, section 13.5.1: Remove a set of known hop-by-hop headers.
601 // This behavior is superseded by the RFC 7230 Connection header, but
602 // preserve it for backwards compatibility.
603 for _, f := range hopHeaders {
604 h.Del(f)
605 }
606 }
607
608 // flushInterval returns the p.FlushInterval value, conditionally
609 // overriding its value for a specific request/response.
610 func (p *ReverseProxy) flushInterval(res *http.Response) time.Duration {
611 resCT := res.Header.Get("Content-Type")
612
613 // For Server-Sent Events responses, flush immediately.
614 // The MIME type is defined in https://www.w3.org/TR/eventsource/#text-event-stream
615 if baseCT, _, _ := mime.ParseMediaType(resCT); baseCT == "text/event-stream" {
616 return -1 // negative means immediately
617 }
618
619 // We might have the case of streaming for which Content-Length might be unset.
620 if res.ContentLength == -1 {
621 return -1
622 }
623
624 return p.FlushInterval
625 }
626
627 func (p *ReverseProxy) copyResponse(dst http.ResponseWriter, src io.Reader, flushInterval time.Duration) error {
628 var w io.Writer = dst
629
630 if flushInterval != 0 {
631 mlw := &maxLatencyWriter{
632 dst: dst,
633 flush: http.NewResponseController(dst).Flush,
634 latency: flushInterval,
635 }
636 defer mlw.stop()
637
638 // set up initial timer so headers get flushed even if body writes are delayed
639 mlw.flushPending = true
640 mlw.t = time.AfterFunc(flushInterval, mlw.delayedFlush)
641
642 w = mlw
643 }
644
645 var buf []byte
646 if p.BufferPool != nil {
647 buf = p.BufferPool.Get()
648 defer p.BufferPool.Put(buf)
649 }
650 _, err := p.copyBuffer(w, src, buf)
651 return err
652 }
653
654 // copyBuffer returns any write errors or non-EOF read errors, and the amount
655 // of bytes written.
656 func (p *ReverseProxy) copyBuffer(dst io.Writer, src io.Reader, buf []byte) (int64, error) {
657 if len(buf) == 0 {
658 buf = make([]byte, 32*1024)
659 }
660 var written int64
661 for {
662 nr, rerr := src.Read(buf)
663 if rerr != nil && rerr != io.EOF && rerr != context.Canceled {
664 p.logf("httputil: ReverseProxy read error during body copy: %v", rerr)
665 }
666 if nr > 0 {
667 nw, werr := dst.Write(buf[:nr])
668 if nw > 0 {
669 written += int64(nw)
670 }
671 if werr != nil {
672 return written, werr
673 }
674 if nr != nw {
675 return written, io.ErrShortWrite
676 }
677 }
678 if rerr != nil {
679 if rerr == io.EOF {
680 rerr = nil
681 }
682 return written, rerr
683 }
684 }
685 }
686
687 func (p *ReverseProxy) logf(format string, args ...any) {
688 if p.ErrorLog != nil {
689 p.ErrorLog.Printf(format, args...)
690 } else {
691 log.Printf(format, args...)
692 }
693 }
694
695 type maxLatencyWriter struct {
696 dst io.Writer
697 flush func() error
698 latency time.Duration // non-zero; negative means to flush immediately
699
700 mu sync.Mutex // protects t, flushPending, and dst.Flush
701 t *time.Timer
702 flushPending bool
703 }
704
705 func (m *maxLatencyWriter) Write(p []byte) (n int, err error) {
706 m.mu.Lock()
707 defer m.mu.Unlock()
708 n, err = m.dst.Write(p)
709 if m.latency < 0 {
710 m.flush()
711 return
712 }
713 if m.flushPending {
714 return
715 }
716 if m.t == nil {
717 m.t = time.AfterFunc(m.latency, m.delayedFlush)
718 } else {
719 m.t.Reset(m.latency)
720 }
721 m.flushPending = true
722 return
723 }
724
725 func (m *maxLatencyWriter) delayedFlush() {
726 m.mu.Lock()
727 defer m.mu.Unlock()
728 if !m.flushPending { // if stop was called but AfterFunc already started this goroutine
729 return
730 }
731 m.flush()
732 m.flushPending = false
733 }
734
735 func (m *maxLatencyWriter) stop() {
736 m.mu.Lock()
737 defer m.mu.Unlock()
738 m.flushPending = false
739 if m.t != nil {
740 m.t.Stop()
741 }
742 }
743
744 func upgradeType(h http.Header) string {
745 if !httpguts.HeaderValuesContainsToken(h["Connection"], "Upgrade") {
746 return ""
747 }
748 return h.Get("Upgrade")
749 }
750
751 func (p *ReverseProxy) handleUpgradeResponse(rw http.ResponseWriter, req *http.Request, res *http.Response) {
752 reqUpType := upgradeType(req.Header)
753 resUpType := upgradeType(res.Header)
754 if !ascii.IsPrint(resUpType) { // We know reqUpType is ASCII, it's checked by the caller.
755 p.getErrorHandler()(rw, req, fmt.Errorf("backend tried to switch to invalid protocol %q", resUpType))
756 return
757 }
758 if !ascii.EqualFold(reqUpType, resUpType) {
759 p.getErrorHandler()(rw, req, fmt.Errorf("backend tried to switch protocol %q when %q was requested", resUpType, reqUpType))
760 return
761 }
762
763 backConn, ok := res.Body.(io.ReadWriteCloser)
764 if !ok {
765 p.getErrorHandler()(rw, req, fmt.Errorf("internal error: 101 switching protocols response with non-writable body"))
766 return
767 }
768
769 rc := http.NewResponseController(rw)
770 conn, brw, hijackErr := rc.Hijack()
771 if errors.Is(hijackErr, http.ErrNotSupported) {
772 p.getErrorHandler()(rw, req, fmt.Errorf("can't switch protocols using non-Hijacker ResponseWriter type %T", rw))
773 return
774 }
775
776 backConnCloseCh := make(chan bool)
777 go func() {
778 // Ensure that the cancellation of a request closes the backend.
779 // See issue https://golang.org/issue/35559.
780 select {
781 case <-req.Context().Done():
782 case <-backConnCloseCh:
783 }
784 backConn.Close()
785 }()
786 defer close(backConnCloseCh)
787
788 if hijackErr != nil {
789 p.getErrorHandler()(rw, req, fmt.Errorf("Hijack failed on protocol switch: %v", hijackErr))
790 return
791 }
792 defer conn.Close()
793
794 copyHeader(rw.Header(), res.Header)
795
796 res.Header = rw.Header()
797 res.Body = nil // so res.Write only writes the headers; we have res.Body in backConn above
798 if err := res.Write(brw); err != nil {
799 p.getErrorHandler()(rw, req, fmt.Errorf("response write: %v", err))
800 return
801 }
802 if err := brw.Flush(); err != nil {
803 p.getErrorHandler()(rw, req, fmt.Errorf("response flush: %v", err))
804 return
805 }
806 errc := make(chan error, 1)
807 spc := switchProtocolCopier{user: conn, backend: backConn}
808 go spc.copyToBackend(errc)
809 go spc.copyFromBackend(errc)
810
811 // Wait until both copy functions have sent on the error channel,
812 // or until one fails.
813 err := <-errc
814 if err == nil {
815 err = <-errc
816 }
817 }
818
819 var errCopyDone = errors.New("hijacked connection copy complete")
820
821 // switchProtocolCopier exists so goroutines proxying data back and
822 // forth have nice names in stacks.
823 type switchProtocolCopier struct {
824 user, backend io.ReadWriter
825 }
826
827 func (c switchProtocolCopier) copyFromBackend(errc chan<- error) {
828 if _, err := io.Copy(c.user, c.backend); err != nil {
829 errc <- err
830 return
831 }
832
833 // backend conn has reached EOF so propogate close write to user conn
834 if wc, ok := c.user.(interface{ CloseWrite() error }); ok {
835 errc <- wc.CloseWrite()
836 return
837 }
838
839 errc <- errCopyDone
840 }
841
842 func (c switchProtocolCopier) copyToBackend(errc chan<- error) {
843 if _, err := io.Copy(c.backend, c.user); err != nil {
844 errc <- err
845 return
846 }
847
848 // user conn has reached EOF so propogate close write to backend conn
849 if wc, ok := c.backend.(interface{ CloseWrite() error }); ok {
850 errc <- wc.CloseWrite()
851 return
852 }
853
854 errc <- errCopyDone
855 }
856
857 var urlmaxqueryparams = godebug.New("urlmaxqueryparams")
858
859 // Keep this in sync with net/url.
860 const defaultMaxParams = 10000
861
862 func cleanQueryParams(s string) string {
863 reencode := func(s string) string {
864 v, _ := url.ParseQuery(s)
865 return v.Encode()
866 }
867 if urlmaxqueryparams.Value() != "" {
868 // Always reencode when a non-default urlmaxqueryparams is set.
869 return reencode(s)
870 }
871 if numParams := strings.Count(s, "&") + 1; numParams > defaultMaxParams {
872 // Too many query parameters.
873 return reencode(s)
874 }
875 for i := 0; i < len(s); {
876 switch s[i] {
877 case ';':
878 return reencode(s)
879 case '%':
880 if i+2 >= len(s) || !ishex(s[i+1]) || !ishex(s[i+2]) {
881 return reencode(s)
882 }
883 i += 3
884 default:
885 i++
886 }
887 }
888 return s
889 }
890
891 func ishex(c byte) bool {
892 switch {
893 case '0' <= c && c <= '9':
894 return true
895 case 'a' <= c && c <= 'f':
896 return true
897 case 'A' <= c && c <= 'F':
898 return true
899 }
900 return false
901 }