Source file src/net/http/httputil/reverseproxy.go

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

View as plain text