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

View as plain text