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

View as plain text