...
Run Format

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

Documentation: net/http/httputil

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

View as plain text