github.com/megatontech/mynoteforgo@v0.0.0-20200507084910-5d0c6ea6e890/源码/net/http/httputil/reverseproxy.go (about) 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 dst = mlw 393 } 394 } 395 396 var buf []byte 397 if p.BufferPool != nil { 398 buf = p.BufferPool.Get() 399 defer p.BufferPool.Put(buf) 400 } 401 _, err := p.copyBuffer(dst, src, buf) 402 return err 403 } 404 405 // copyBuffer returns any write errors or non-EOF read errors, and the amount 406 // of bytes written. 407 func (p *ReverseProxy) copyBuffer(dst io.Writer, src io.Reader, buf []byte) (int64, error) { 408 if len(buf) == 0 { 409 buf = make([]byte, 32*1024) 410 } 411 var written int64 412 for { 413 nr, rerr := src.Read(buf) 414 if rerr != nil && rerr != io.EOF && rerr != context.Canceled { 415 p.logf("httputil: ReverseProxy read error during body copy: %v", rerr) 416 } 417 if nr > 0 { 418 nw, werr := dst.Write(buf[:nr]) 419 if nw > 0 { 420 written += int64(nw) 421 } 422 if werr != nil { 423 return written, werr 424 } 425 if nr != nw { 426 return written, io.ErrShortWrite 427 } 428 } 429 if rerr != nil { 430 if rerr == io.EOF { 431 rerr = nil 432 } 433 return written, rerr 434 } 435 } 436 } 437 438 func (p *ReverseProxy) logf(format string, args ...interface{}) { 439 if p.ErrorLog != nil { 440 p.ErrorLog.Printf(format, args...) 441 } else { 442 log.Printf(format, args...) 443 } 444 } 445 446 type writeFlusher interface { 447 io.Writer 448 http.Flusher 449 } 450 451 type maxLatencyWriter struct { 452 dst writeFlusher 453 latency time.Duration // non-zero; negative means to flush immediately 454 455 mu sync.Mutex // protects t, flushPending, and dst.Flush 456 t *time.Timer 457 flushPending bool 458 } 459 460 func (m *maxLatencyWriter) Write(p []byte) (n int, err error) { 461 m.mu.Lock() 462 defer m.mu.Unlock() 463 n, err = m.dst.Write(p) 464 if m.latency < 0 { 465 m.dst.Flush() 466 return 467 } 468 if m.flushPending { 469 return 470 } 471 if m.t == nil { 472 m.t = time.AfterFunc(m.latency, m.delayedFlush) 473 } else { 474 m.t.Reset(m.latency) 475 } 476 m.flushPending = true 477 return 478 } 479 480 func (m *maxLatencyWriter) delayedFlush() { 481 m.mu.Lock() 482 defer m.mu.Unlock() 483 if !m.flushPending { // if stop was called but AfterFunc already started this goroutine 484 return 485 } 486 m.dst.Flush() 487 m.flushPending = false 488 } 489 490 func (m *maxLatencyWriter) stop() { 491 m.mu.Lock() 492 defer m.mu.Unlock() 493 m.flushPending = false 494 if m.t != nil { 495 m.t.Stop() 496 } 497 } 498 499 func upgradeType(h http.Header) string { 500 if !httpguts.HeaderValuesContainsToken(h["Connection"], "Upgrade") { 501 return "" 502 } 503 return strings.ToLower(h.Get("Upgrade")) 504 } 505 506 func (p *ReverseProxy) handleUpgradeResponse(rw http.ResponseWriter, req *http.Request, res *http.Response) { 507 reqUpType := upgradeType(req.Header) 508 resUpType := upgradeType(res.Header) 509 if reqUpType != resUpType { 510 p.getErrorHandler()(rw, req, fmt.Errorf("backend tried to switch protocol %q when %q was requested", resUpType, reqUpType)) 511 return 512 } 513 514 copyHeader(res.Header, rw.Header()) 515 516 hj, ok := rw.(http.Hijacker) 517 if !ok { 518 p.getErrorHandler()(rw, req, fmt.Errorf("can't switch protocols using non-Hijacker ResponseWriter type %T", rw)) 519 return 520 } 521 backConn, ok := res.Body.(io.ReadWriteCloser) 522 if !ok { 523 p.getErrorHandler()(rw, req, fmt.Errorf("internal error: 101 switching protocols response with non-writable body")) 524 return 525 } 526 defer backConn.Close() 527 conn, brw, err := hj.Hijack() 528 if err != nil { 529 p.getErrorHandler()(rw, req, fmt.Errorf("Hijack failed on protocol switch: %v", err)) 530 return 531 } 532 defer conn.Close() 533 res.Body = nil // so res.Write only writes the headers; we have res.Body in backConn above 534 if err := res.Write(brw); err != nil { 535 p.getErrorHandler()(rw, req, fmt.Errorf("response write: %v", err)) 536 return 537 } 538 if err := brw.Flush(); err != nil { 539 p.getErrorHandler()(rw, req, fmt.Errorf("response flush: %v", err)) 540 return 541 } 542 errc := make(chan error, 1) 543 spc := switchProtocolCopier{user: conn, backend: backConn} 544 go spc.copyToBackend(errc) 545 go spc.copyFromBackend(errc) 546 <-errc 547 return 548 } 549 550 // switchProtocolCopier exists so goroutines proxying data back and 551 // forth have nice names in stacks. 552 type switchProtocolCopier struct { 553 user, backend io.ReadWriter 554 } 555 556 func (c switchProtocolCopier) copyFromBackend(errc chan<- error) { 557 _, err := io.Copy(c.user, c.backend) 558 errc <- err 559 } 560 561 func (c switchProtocolCopier) copyToBackend(errc chan<- error) { 562 _, err := io.Copy(c.backend, c.user) 563 errc <- err 564 }