gitee.com/zhaochuninhefei/gmgo@v0.0.31-0.20240209061119-069254a02979/gmhttp/server.go (about) 1 // Copyright 2009 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 server. See RFC 7230 through 7235. 6 7 package gmhttp 8 9 import ( 10 "bufio" 11 "bytes" 12 "context" 13 "errors" 14 "fmt" 15 "io" 16 "log" 17 "math/rand" 18 "net" 19 "net/textproto" 20 "net/url" 21 urlpkg "net/url" 22 "os" 23 "path" 24 "runtime" 25 "sort" 26 "strconv" 27 "strings" 28 "sync" 29 "sync/atomic" 30 "time" 31 32 tls "gitee.com/zhaochuninhefei/gmgo/gmtls" 33 "golang.org/x/net/http/httpguts" 34 ) 35 36 // Errors used by the HTTP server. 37 //goland:noinspection GoUnusedGlobalVariable 38 var ( 39 // ErrBodyNotAllowed is returned by ResponseWriter.Write calls 40 // when the HTTP method or response code does not permit a 41 // body. 42 ErrBodyNotAllowed = errors.New("http: request method or response status code does not allow body") 43 44 // ErrHijacked is returned by ResponseWriter.Write calls when 45 // the underlying connection has been hijacked using the 46 // Hijacker interface. A zero-byte write on a hijacked 47 // connection will return ErrHijacked without any other side 48 // effects. 49 ErrHijacked = errors.New("http: connection has been hijacked") 50 51 // ErrContentLength is returned by ResponseWriter.Write calls 52 // when a Handler set a Content-Length response header with a 53 // declared size and then attempted to write more bytes than 54 // declared. 55 ErrContentLength = errors.New("http: wrote more than the declared Content-Length") 56 57 // Deprecated: ErrWriteAfterFlush is no longer returned by 58 // anything in the net/http package. Callers should not 59 // compare errors against this variable. 60 ErrWriteAfterFlush = errors.New("unused") 61 ) 62 63 // A Handler responds to an HTTP request. 64 // 65 // ServeHTTP should write reply headers and data to the ResponseWriter 66 // and then return. Returning signals that the request is finished; it 67 // is not valid to use the ResponseWriter or read from the 68 // Request.Body after or concurrently with the completion of the 69 // ServeHTTP call. 70 // 71 // Depending on the HTTP client software, HTTP protocol version, and 72 // any intermediaries between the client and the Go server, it may not 73 // be possible to read from the Request.Body after writing to the 74 // ResponseWriter. Cautious handlers should read the Request.Body 75 // first, and then reply. 76 // 77 // Except for reading the body, handlers should not modify the 78 // provided Request. 79 // 80 // If ServeHTTP panics, the server (the caller of ServeHTTP) assumes 81 // that the effect of the panic was isolated to the active request. 82 // It recovers the panic, logs a stack trace to the server error log, 83 // and either closes the network connection or sends an HTTP/2 84 // RST_STREAM, depending on the HTTP protocol. To abort a handler so 85 // the client sees an interrupted response but the server doesn't log 86 // an error, panic with the value ErrAbortHandler. 87 type Handler interface { 88 ServeHTTP(ResponseWriter, *Request) 89 } 90 91 // A ResponseWriter interface is used by an HTTP handler to 92 // construct an HTTP response. 93 // 94 // A ResponseWriter may not be used after the Handler.ServeHTTP method 95 // has returned. 96 type ResponseWriter interface { 97 // Header returns the header map that will be sent by 98 // WriteHeader. The Header map also is the mechanism with which 99 // Handlers can set HTTP trailers. 100 // 101 // Changing the header map after a call to WriteHeader (or 102 // Write) has no effect unless the modified headers are 103 // trailers. 104 // 105 // There are two ways to set Trailers. The preferred way is to 106 // predeclare in the headers which trailers you will later 107 // send by setting the "Trailer" header to the names of the 108 // trailer keys which will come later. In this case, those 109 // keys of the Header map are treated as if they were 110 // trailers. See the example. The second way, for trailer 111 // keys not known to the Handler until after the first Write, 112 // is to prefix the Header map keys with the TrailerPrefix 113 // constant value. See TrailerPrefix. 114 // 115 // To suppress automatic response headers (such as "Date"), set 116 // their value to nil. 117 Header() Header 118 119 // Write writes the data to the connection as part of an HTTP reply. 120 // 121 // If WriteHeader has not yet been called, Write calls 122 // WriteHeader(http.StatusOK) before writing the data. If the Header 123 // does not contain a Content-Type line, Write adds a Content-Type set 124 // to the result of passing the initial 512 bytes of written data to 125 // DetectContentType. Additionally, if the total size of all written 126 // data is under a few KB and there are no Flush calls, the 127 // Content-Length header is added automatically. 128 // 129 // Depending on the HTTP protocol version and the client, calling 130 // Write or WriteHeader may prevent future reads on the 131 // Request.Body. For HTTP/1.x requests, handlers should read any 132 // needed request body data before writing the response. Once the 133 // headers have been flushed (due to either an explicit Flusher.Flush 134 // call or writing enough data to trigger a flush), the request body 135 // may be unavailable. For HTTP/2 requests, the Go HTTP server permits 136 // handlers to continue to read the request body while concurrently 137 // writing the response. However, such behavior may not be supported 138 // by all HTTP/2 clients. Handlers should read before writing if 139 // possible to maximize compatibility. 140 Write([]byte) (int, error) 141 142 // WriteHeader sends an HTTP response header with the provided 143 // status code. 144 // 145 // If WriteHeader is not called explicitly, the first call to Write 146 // will trigger an implicit WriteHeader(http.StatusOK). 147 // Thus explicit calls to WriteHeader are mainly used to 148 // send error codes. 149 // 150 // The provided code must be a valid HTTP 1xx-5xx status code. 151 // Only one header may be written. Go does not currently 152 // support sending user-defined 1xx informational headers, 153 // with the exception of 100-continue response header that the 154 // Server sends automatically when the Request.Body is read. 155 WriteHeader(statusCode int) 156 } 157 158 // The Flusher interface is implemented by ResponseWriters that allow 159 // an HTTP handler to flush buffered data to the client. 160 // 161 // The default HTTP/1.x and HTTP/2 ResponseWriter implementations 162 // support Flusher, but ResponseWriter wrappers may not. Handlers 163 // should always test for this ability at runtime. 164 // 165 // Note that even for ResponseWriters that support Flush, 166 // if the client is connected through an HTTP proxy, 167 // the buffered data may not reach the client until the response 168 // completes. 169 type Flusher interface { 170 // Flush sends any buffered data to the client. 171 Flush() 172 } 173 174 // The Hijacker interface is implemented by ResponseWriters that allow 175 // an HTTP handler to take over the connection. 176 // 177 // The default ResponseWriter for HTTP/1.x connections supports 178 // Hijacker, but HTTP/2 connections intentionally do not. 179 // ResponseWriter wrappers may also not support Hijacker. Handlers 180 // should always test for this ability at runtime. 181 type Hijacker interface { 182 // Hijack lets the caller take over the connection. 183 // After a call to Hijack the HTTP server library 184 // will not do anything else with the connection. 185 // 186 // It becomes the caller's responsibility to manage 187 // and close the connection. 188 // 189 // The returned net.Conn may have read or write deadlines 190 // already set, depending on the configuration of the 191 // Server. It is the caller's responsibility to set 192 // or clear those deadlines as needed. 193 // 194 // The returned bufio.Reader may contain unprocessed buffered 195 // data from the client. 196 // 197 // After a call to Hijack, the original Request.Body must not 198 // be used. The original Request's Context remains valid and 199 // is not canceled until the Request's ServeHTTP method 200 // returns. 201 Hijack() (net.Conn, *bufio.ReadWriter, error) 202 } 203 204 // The CloseNotifier interface is implemented by ResponseWriters which 205 // allow detecting when the underlying connection has gone away. 206 // 207 // This mechanism can be used to cancel long operations on the server 208 // if the client has disconnected before the response is ready. 209 // 210 // ToDeprecated: the CloseNotifier interface predates Go's context package. 211 // New code should use Request.Context instead. 212 type CloseNotifier interface { 213 // CloseNotify returns a channel that receives at most a 214 // single value (true) when the client connection has gone 215 // away. 216 // 217 // CloseNotify may wait to notify until Request.Body has been 218 // fully read. 219 // 220 // After the Handler has returned, there is no guarantee 221 // that the channel receives a value. 222 // 223 // If the protocol is HTTP/1.1 and CloseNotify is called while 224 // processing an idempotent request (such a GET) while 225 // HTTP/1.1 pipelining is in use, the arrival of a subsequent 226 // pipelined request may cause a value to be sent on the 227 // returned channel. In practice HTTP/1.1 pipelining is not 228 // enabled in browsers and not seen often in the wild. If this 229 // is a problem, use HTTP/2 or only use CloseNotify on methods 230 // such as POST. 231 CloseNotify() <-chan bool 232 } 233 234 var ( 235 // ServerContextKey is a context key. It can be used in HTTP 236 // handlers with Context.Value to access the server that 237 // started the handler. The associated value will be of 238 // type *Server. 239 ServerContextKey = &contextKey{"http-server"} 240 241 // LocalAddrContextKey is a context key. It can be used in 242 // HTTP handlers with Context.Value to access the local 243 // address the connection arrived on. 244 // The associated value will be of type net.Addr. 245 LocalAddrContextKey = &contextKey{"local-addr"} 246 ) 247 248 // A conn represents the server side of an HTTP connection. 249 type conn struct { 250 // server is the server on which the connection arrived. 251 // Immutable; never nil. 252 server *Server 253 254 // cancelCtx cancels the connection-level context. 255 cancelCtx context.CancelFunc 256 257 // rwc is the underlying network connection. 258 // This is never wrapped by other types and is the value given out 259 // to CloseNotifier callers. It is usually of type *net.TCPConn or 260 // *tls.Conn. 261 rwc net.Conn 262 263 // remoteAddr is rwc.RemoteAddr().String(). It is not populated synchronously 264 // inside the Listener's Accept goroutine, as some implementations block. 265 // It is populated immediately inside the (*conn).serve goroutine. 266 // This is the value of a Handler's (*Request).RemoteAddr. 267 remoteAddr string 268 269 // tlsState is the TLS connection state when using TLS. 270 // nil means not TLS. 271 tlsState *tls.ConnectionState 272 273 // werr is set to the first write error to rwc. 274 // It is set via checkConnErrorWriter{w}, where bufw writes. 275 werr error 276 277 // r is bufr's read source. It's a wrapper around rwc that provides 278 // io.LimitedReader-style limiting (while reading request headers) 279 // and functionality to support CloseNotifier. See *connReader docs. 280 r *connReader 281 282 // bufr reads from r. 283 bufr *bufio.Reader 284 285 // bufw writes to checkConnErrorWriter{c}, which populates werr on error. 286 bufw *bufio.Writer 287 288 // lastMethod is the method of the most recent request 289 // on this connection, if any. 290 lastMethod string 291 292 curReq atomic.Value // of *response (which has a Request in it) 293 294 curState struct{ atomic uint64 } // packed (unixtime<<8|uint8(ConnState)) 295 296 // mu guards hijackedv 297 mu sync.Mutex 298 299 // hijackedv is whether this connection has been hijacked 300 // by a Handler with the Hijacker interface. 301 // It is guarded by mu. 302 hijackedv bool 303 } 304 305 func (c *conn) hijacked() bool { 306 c.mu.Lock() 307 defer c.mu.Unlock() 308 return c.hijackedv 309 } 310 311 // c.mu must be held. 312 func (c *conn) hijackLocked() (rwc net.Conn, buf *bufio.ReadWriter, err error) { 313 if c.hijackedv { 314 return nil, nil, ErrHijacked 315 } 316 c.r.abortPendingRead() 317 318 c.hijackedv = true 319 rwc = c.rwc 320 _ = rwc.SetDeadline(time.Time{}) 321 322 buf = bufio.NewReadWriter(c.bufr, bufio.NewWriter(rwc)) 323 if c.r.hasByte { 324 if _, err := c.bufr.Peek(c.bufr.Buffered() + 1); err != nil { 325 return nil, nil, fmt.Errorf("unexpected Peek failure reading buffered byte: %v", err) 326 } 327 } 328 c.setState(rwc, StateHijacked, runHooks) 329 return 330 } 331 332 // This should be >= 512 bytes for DetectContentType, 333 // but otherwise it's somewhat arbitrary. 334 const bufferBeforeChunkingSize = 2048 335 336 // chunkWriter writes to a response's conn buffer, and is the writer 337 // wrapped by the response.w buffered writer. 338 // 339 // chunkWriter also is responsible for finalizing the Header, including 340 // conditionally setting the Content-Type and setting a Content-Length 341 // in cases where the handler's final output is smaller than the buffer 342 // size. It also conditionally adds chunk headers, when in chunking mode. 343 // 344 // See the comment above (*response).Write for the entire write flow. 345 type chunkWriter struct { 346 res *response 347 348 // header is either nil or a deep clone of res.handlerHeader 349 // at the time of res.writeHeader, if res.writeHeader is 350 // called and extra buffering is being done to calculate 351 // Content-Type and/or Content-Length. 352 header Header 353 354 // wroteHeader tells whether the header's been written to "the 355 // wire" (or rather: w.conn.buf). this is unlike 356 // (*response).wroteHeader, which tells only whether it was 357 // logically written. 358 wroteHeader bool 359 360 // set by the writeHeader method: 361 chunking bool // using chunked transfer encoding for reply body 362 } 363 364 var ( 365 crlf = []byte("\r\n") 366 colonSpace = []byte(": ") 367 ) 368 369 func (cw *chunkWriter) Write(p []byte) (n int, err error) { 370 if !cw.wroteHeader { 371 cw.writeHeader(p) 372 } 373 if cw.res.req.Method == "HEAD" { 374 // Eat writes. 375 return len(p), nil 376 } 377 if cw.chunking { 378 _, err = fmt.Fprintf(cw.res.conn.bufw, "%x\r\n", len(p)) 379 if err != nil { 380 _ = cw.res.conn.rwc.Close() 381 return 382 } 383 } 384 n, err = cw.res.conn.bufw.Write(p) 385 if cw.chunking && err == nil { 386 _, err = cw.res.conn.bufw.Write(crlf) 387 } 388 if err != nil { 389 _ = cw.res.conn.rwc.Close() 390 } 391 return 392 } 393 394 func (cw *chunkWriter) flush() { 395 if !cw.wroteHeader { 396 cw.writeHeader(nil) 397 } 398 _ = cw.res.conn.bufw.Flush() 399 } 400 401 func (cw *chunkWriter) close() { 402 if !cw.wroteHeader { 403 cw.writeHeader(nil) 404 } 405 if cw.chunking { 406 bw := cw.res.conn.bufw // conn's bufio writer 407 // zero chunk to mark EOF 408 _, _ = bw.WriteString("0\r\n") 409 if trailers := cw.res.finalTrailers(); trailers != nil { 410 _ = trailers.Write(bw) // the writer handles noting errors 411 } 412 // final blank line after the trailers (whether 413 // present or not) 414 _, _ = bw.WriteString("\r\n") 415 } 416 } 417 418 // A response represents the server side of an HTTP response. 419 type response struct { 420 conn *conn 421 req *Request // request for this response 422 reqBody io.ReadCloser 423 cancelCtx context.CancelFunc // when ServeHTTP exits 424 wroteHeader bool // reply header has been (logically) written 425 wroteContinue bool // 100 Continue response was written 426 wants10KeepAlive bool // HTTP/1.0 w/ Connection "keep-alive" 427 wantsClose bool // HTTP request has Connection "close" 428 429 // canWriteContinue is a boolean value accessed as an atomic int32 430 // that says whether or not a 100 Continue header can be written 431 // to the connection. 432 // writeContinueMu must be held while writing the header. 433 // These two fields together synchronize the body reader 434 // (the expectContinueReader, which wants to write 100 Continue) 435 // against the main writer. 436 canWriteContinue atomicBool 437 writeContinueMu sync.Mutex 438 439 w *bufio.Writer // buffers output in chunks to chunkWriter 440 cw chunkWriter 441 442 // handlerHeader is the Header that Handlers get access to, 443 // which may be retained and mutated even after WriteHeader. 444 // handlerHeader is copied into cw.header at WriteHeader 445 // time, and privately mutated thereafter. 446 handlerHeader Header 447 calledHeader bool // handler accessed handlerHeader via Header 448 449 written int64 // number of bytes written in body 450 contentLength int64 // explicitly-declared Content-Length; or -1 451 status int // status code passed to WriteHeader 452 453 // close connection after this reply. set on request and 454 // updated after response from handler if there's a 455 // "Connection: keep-alive" response header and a 456 // Content-Length. 457 closeAfterReply bool 458 459 // requestBodyLimitHit is set by requestTooLarge when 460 // maxBytesReader hits its max size. It is checked in 461 // WriteHeader, to make sure we don't consume the 462 // remaining request body to try to advance to the next HTTP 463 // request. Instead, when this is set, we stop reading 464 // subsequent requests on this connection and stop reading 465 // input from it. 466 requestBodyLimitHit bool 467 468 // trailers are the headers to be sent after the handler 469 // finishes writing the body. This field is initialized from 470 // the Trailer response header when the response header is 471 // written. 472 trailers []string 473 474 handlerDone atomicBool // set true when the handler exits 475 476 // Buffers for Date, Content-Length, and status code 477 dateBuf [len(TimeFormat)]byte 478 clenBuf [10]byte 479 statusBuf [3]byte 480 481 // closeNotifyCh is the channel returned by CloseNotify. 482 // TODO(bradfitz): this is currently (for Go 1.8) always 483 // non-nil. Make this lazily-created again as it used to be? 484 closeNotifyCh chan bool 485 didCloseNotify int32 // atomic (only 0->1 winner should send) 486 } 487 488 // TrailerPrefix is a magic prefix for ResponseWriter.Header map keys 489 // that, if present, signals that the map entry is actually for 490 // the response trailers, and not the response headers. The prefix 491 // is stripped after the ServeHTTP call finishes and the values are 492 // sent in the trailers. 493 // 494 // This mechanism is intended only for trailers that are not known 495 // prior to the headers being written. If the set of trailers is fixed 496 // or known before the header is written, the normal Go trailers mechanism 497 // is preferred: 498 // https://golang.org/pkg/net/http/#ResponseWriter 499 // https://golang.org/pkg/net/http/#example_ResponseWriter_trailers 500 const TrailerPrefix = "Trailer:" 501 502 // finalTrailers is called after the Handler exits and returns a non-nil 503 // value if the Handler set any trailers. 504 func (w *response) finalTrailers() Header { 505 var t Header 506 for k, vv := range w.handlerHeader { 507 if strings.HasPrefix(k, TrailerPrefix) { 508 if t == nil { 509 t = make(Header) 510 } 511 t[strings.TrimPrefix(k, TrailerPrefix)] = vv 512 } 513 } 514 for _, k := range w.trailers { 515 if t == nil { 516 t = make(Header) 517 } 518 for _, v := range w.handlerHeader[k] { 519 t.Add(k, v) 520 } 521 } 522 return t 523 } 524 525 type atomicBool int32 526 527 func (b *atomicBool) isSet() bool { return atomic.LoadInt32((*int32)(b)) != 0 } 528 func (b *atomicBool) setTrue() { atomic.StoreInt32((*int32)(b), 1) } 529 func (b *atomicBool) setFalse() { atomic.StoreInt32((*int32)(b), 0) } 530 531 // declareTrailer is called for each Trailer header when the 532 // response header is written. It notes that a header will need to be 533 // written in the trailers at the end of the response. 534 func (w *response) declareTrailer(k string) { 535 k = CanonicalHeaderKey(k) 536 if !httpguts.ValidTrailerHeader(k) { 537 // Forbidden by RFC 7230, section 4.1.2 538 return 539 } 540 w.trailers = append(w.trailers, k) 541 } 542 543 // requestTooLarge is called by maxBytesReader when too much input has 544 // been read from the client. 545 func (w *response) requestTooLarge() { 546 w.closeAfterReply = true 547 w.requestBodyLimitHit = true 548 if !w.wroteHeader { 549 w.Header().Set("Connection", "close") 550 } 551 } 552 553 // needsSniff reports whether a Content-Type still needs to be sniffed. 554 func (w *response) needsSniff() bool { 555 _, haveType := w.handlerHeader["Content-Type"] 556 return !w.cw.wroteHeader && !haveType && w.written < sniffLen 557 } 558 559 // writerOnly hides an io.Writer value's optional ReadFrom method 560 // from io.Copy. 561 type writerOnly struct { 562 io.Writer 563 } 564 565 // ReadFrom is here to optimize copying from an *os.File regular file 566 // to a *net.TCPConn with sendfile, or from a supported src type such 567 // as a *net.TCPConn on Linux with splice. 568 func (w *response) ReadFrom(src io.Reader) (n int64, err error) { 569 bufp := copyBufPool.Get().(*[]byte) 570 buf := *bufp 571 defer copyBufPool.Put(bufp) 572 573 // Our underlying w.conn.rwc is usually a *TCPConn (with its 574 // own ReadFrom method). If not, just fall back to the normal 575 // copy method. 576 rf, ok := w.conn.rwc.(io.ReaderFrom) 577 if !ok { 578 return io.CopyBuffer(writerOnly{w}, src, buf) 579 } 580 581 // Copy the first sniffLen bytes before switching to ReadFrom. 582 // This ensures we don't start writing the response before the 583 // source is available (see golang.org/issue/5660) and provides 584 // enough bytes to perform Content-Type sniffing when required. 585 if !w.cw.wroteHeader { 586 n0, err := io.CopyBuffer(writerOnly{w}, io.LimitReader(src, sniffLen), buf) 587 n += n0 588 if err != nil || n0 < sniffLen { 589 return n, err 590 } 591 } 592 593 _ = w.w.Flush() // get rid of any previous writes 594 w.cw.flush() // make sure Header is written; flush data to rwc 595 596 // Now that cw has been flushed, its chunking field is guaranteed initialized. 597 if !w.cw.chunking && w.bodyAllowed() { 598 n0, err := rf.ReadFrom(src) 599 n += n0 600 w.written += n0 601 return n, err 602 } 603 604 n0, err := io.CopyBuffer(writerOnly{w}, src, buf) 605 n += n0 606 return n, err 607 } 608 609 // debugServerConnections controls whether all server connections are wrapped 610 // with a verbose logging wrapper. 611 const debugServerConnections = false 612 613 // Create new connection from rwc. 614 func (srv *Server) newConn(rwc net.Conn) *conn { 615 c := &conn{ 616 server: srv, 617 rwc: rwc, 618 } 619 if debugServerConnections { 620 c.rwc = newLoggingConn("server", c.rwc) 621 } 622 return c 623 } 624 625 type readResult struct { 626 _ incomparable 627 n int 628 err error 629 b byte // byte read, if n == 1 630 } 631 632 // connReader is the io.Reader wrapper used by *conn. It combines a 633 // selectively-activated io.LimitedReader (to bound request header 634 // read sizes) with support for selectively keeping an io.Reader.Read 635 // call blocked in a background goroutine to wait for activity and 636 // trigger a CloseNotifier channel. 637 type connReader struct { 638 conn *conn 639 640 mu sync.Mutex // guards following 641 hasByte bool 642 byteBuf [1]byte 643 cond *sync.Cond 644 inRead bool 645 aborted bool // set true before conn.rwc deadline is set to past 646 remain int64 // bytes remaining 647 } 648 649 func (cr *connReader) lock() { 650 cr.mu.Lock() 651 if cr.cond == nil { 652 cr.cond = sync.NewCond(&cr.mu) 653 } 654 } 655 656 func (cr *connReader) unlock() { cr.mu.Unlock() } 657 658 func (cr *connReader) startBackgroundRead() { 659 cr.lock() 660 defer cr.unlock() 661 if cr.inRead { 662 panic("invalid concurrent Body.Read call") 663 } 664 if cr.hasByte { 665 return 666 } 667 cr.inRead = true 668 _ = cr.conn.rwc.SetReadDeadline(time.Time{}) 669 go cr.backgroundRead() 670 } 671 672 func (cr *connReader) backgroundRead() { 673 n, err := cr.conn.rwc.Read(cr.byteBuf[:]) 674 cr.lock() 675 if n == 1 { 676 cr.hasByte = true 677 // We were past the end of the previous request's body already 678 // (since we wouldn't be in a background read otherwise), so 679 // this is a pipelined HTTP request. Prior to Go 1.11 we used to 680 // send on the CloseNotify channel and cancel the context here, 681 // but the behavior was documented as only "may", and we only 682 // did that because that's how CloseNotify accidentally behaved 683 // in very early Go releases prior to context support. Once we 684 // added context support, people used a Handler's 685 // Request.Context() and passed it along. Having that context 686 // cancel on pipelined HTTP requests caused problems. 687 // Fortunately, almost nothing uses HTTP/1.x pipelining. 688 // Unfortunately, apt-get does, or sometimes does. 689 // New Go 1.11 behavior: don't fire CloseNotify or cancel 690 // contexts on pipelined requests. Shouldn't affect people, but 691 // fixes cases like Issue 23921. This does mean that a client 692 // closing their TCP connection after sending a pipelined 693 // request won't cancel the context, but we'll catch that on any 694 // write failure (in checkConnErrorWriter.Write). 695 // If the server never writes, yes, there are still contrived 696 // server & client behaviors where this fails to ever cancel the 697 // context, but that's kinda why HTTP/1.x pipelining died 698 // anyway. 699 } 700 if ne, ok := err.(net.Error); ok && cr.aborted && ne.Timeout() { 701 // Ignore this error. It's the expected error from 702 // another goroutine calling abortPendingRead. 703 } else if err != nil { 704 cr.handleReadError(err) 705 } 706 cr.aborted = false 707 cr.inRead = false 708 cr.unlock() 709 cr.cond.Broadcast() 710 } 711 712 func (cr *connReader) abortPendingRead() { 713 cr.lock() 714 defer cr.unlock() 715 if !cr.inRead { 716 return 717 } 718 cr.aborted = true 719 _ = cr.conn.rwc.SetReadDeadline(aLongTimeAgo) 720 for cr.inRead { 721 cr.cond.Wait() 722 } 723 _ = cr.conn.rwc.SetReadDeadline(time.Time{}) 724 } 725 726 func (cr *connReader) setReadLimit(remain int64) { cr.remain = remain } 727 func (cr *connReader) setInfiniteReadLimit() { cr.remain = maxInt64 } 728 func (cr *connReader) hitReadLimit() bool { return cr.remain <= 0 } 729 730 // handleReadError is called whenever a Read from the client returns a 731 // non-nil error. 732 // 733 // The provided non-nil err is almost always io.EOF or a "use of 734 // closed network connection". In any case, the error is not 735 // particularly interesting, except perhaps for debugging during 736 // development. Any error means the connection is dead and we should 737 // down its context. 738 // 739 // It may be called from multiple goroutines. 740 func (cr *connReader) handleReadError(_ error) { 741 cr.conn.cancelCtx() 742 cr.closeNotify() 743 } 744 745 // may be called from multiple goroutines. 746 func (cr *connReader) closeNotify() { 747 res, _ := cr.conn.curReq.Load().(*response) 748 if res != nil && atomic.CompareAndSwapInt32(&res.didCloseNotify, 0, 1) { 749 res.closeNotifyCh <- true 750 } 751 } 752 753 func (cr *connReader) Read(p []byte) (n int, err error) { 754 cr.lock() 755 if cr.inRead { 756 cr.unlock() 757 if cr.conn.hijacked() { 758 panic("invalid Body.Read call. After hijacked, the original Request must not be used") 759 } 760 panic("invalid concurrent Body.Read call") 761 } 762 if cr.hitReadLimit() { 763 cr.unlock() 764 return 0, io.EOF 765 } 766 if len(p) == 0 { 767 cr.unlock() 768 return 0, nil 769 } 770 if int64(len(p)) > cr.remain { 771 p = p[:cr.remain] 772 } 773 if cr.hasByte { 774 p[0] = cr.byteBuf[0] 775 cr.hasByte = false 776 cr.unlock() 777 return 1, nil 778 } 779 cr.inRead = true 780 cr.unlock() 781 n, err = cr.conn.rwc.Read(p) 782 783 cr.lock() 784 cr.inRead = false 785 if err != nil { 786 cr.handleReadError(err) 787 } 788 cr.remain -= int64(n) 789 cr.unlock() 790 791 cr.cond.Broadcast() 792 return n, err 793 } 794 795 var ( 796 bufioReaderPool sync.Pool 797 bufioWriter2kPool sync.Pool 798 bufioWriter4kPool sync.Pool 799 ) 800 801 var copyBufPool = sync.Pool{ 802 New: func() interface{} { 803 b := make([]byte, 32*1024) 804 return &b 805 }, 806 } 807 808 func bufioWriterPool(size int) *sync.Pool { 809 switch size { 810 case 2 << 10: 811 return &bufioWriter2kPool 812 case 4 << 10: 813 return &bufioWriter4kPool 814 } 815 return nil 816 } 817 818 func newBufioReader(r io.Reader) *bufio.Reader { 819 if v := bufioReaderPool.Get(); v != nil { 820 br := v.(*bufio.Reader) 821 br.Reset(r) 822 return br 823 } 824 // Note: if this reader size is ever changed, update 825 // TestHandlerBodyClose's assumptions. 826 return bufio.NewReader(r) 827 } 828 829 func putBufioReader(br *bufio.Reader) { 830 br.Reset(nil) 831 bufioReaderPool.Put(br) 832 } 833 834 func newBufioWriterSize(w io.Writer, size int) *bufio.Writer { 835 pool := bufioWriterPool(size) 836 if pool != nil { 837 if v := pool.Get(); v != nil { 838 bw := v.(*bufio.Writer) 839 bw.Reset(w) 840 return bw 841 } 842 } 843 return bufio.NewWriterSize(w, size) 844 } 845 846 func putBufioWriter(bw *bufio.Writer) { 847 bw.Reset(nil) 848 if pool := bufioWriterPool(bw.Available()); pool != nil { 849 pool.Put(bw) 850 } 851 } 852 853 // DefaultMaxHeaderBytes is the maximum permitted size of the headers 854 // in an HTTP request. 855 // This can be overridden by setting Server.MaxHeaderBytes. 856 const DefaultMaxHeaderBytes = 1 << 20 // 1 MB 857 858 func (srv *Server) maxHeaderBytes() int { 859 if srv.MaxHeaderBytes > 0 { 860 return srv.MaxHeaderBytes 861 } 862 return DefaultMaxHeaderBytes 863 } 864 865 func (srv *Server) initialReadLimitSize() int64 { 866 return int64(srv.maxHeaderBytes()) + 4096 // bufio slop 867 } 868 869 // wrapper around io.ReadCloser which on first read, sends an 870 // HTTP/1.1 100 Continue header 871 type expectContinueReader struct { 872 resp *response 873 readCloser io.ReadCloser 874 closed atomicBool 875 sawEOF atomicBool 876 } 877 878 func (ecr *expectContinueReader) Read(p []byte) (n int, err error) { 879 if ecr.closed.isSet() { 880 return 0, ErrBodyReadAfterClose 881 } 882 w := ecr.resp 883 if !w.wroteContinue && w.canWriteContinue.isSet() && !w.conn.hijacked() { 884 w.wroteContinue = true 885 w.writeContinueMu.Lock() 886 if w.canWriteContinue.isSet() { 887 _, _ = w.conn.bufw.WriteString("HTTP/1.1 100 Continue\r\n\r\n") 888 _ = w.conn.bufw.Flush() 889 w.canWriteContinue.setFalse() 890 } 891 w.writeContinueMu.Unlock() 892 } 893 n, err = ecr.readCloser.Read(p) 894 if err == io.EOF { 895 ecr.sawEOF.setTrue() 896 } 897 return 898 } 899 900 func (ecr *expectContinueReader) Close() error { 901 ecr.closed.setTrue() 902 return ecr.readCloser.Close() 903 } 904 905 // TimeFormat is the time format to use when generating times in HTTP 906 // headers. It is like time.RFC1123 but hard-codes GMT as the time 907 // zone. The time being formatted must be in UTC for Format to 908 // generate the correct format. 909 // 910 // For parsing this time format, see ParseTime. 911 const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT" 912 913 // appendTime is a non-allocating version of []byte(t.UTC().Format(TimeFormat)) 914 func appendTime(b []byte, t time.Time) []byte { 915 const days = "SunMonTueWedThuFriSat" 916 const months = "JanFebMarAprMayJunJulAugSepOctNovDec" 917 918 t = t.UTC() 919 yy, mm, dd := t.Date() 920 hh, mn, ss := t.Clock() 921 day := days[3*t.Weekday():] 922 mon := months[3*(mm-1):] 923 924 return append(b, 925 day[0], day[1], day[2], ',', ' ', 926 byte('0'+dd/10), byte('0'+dd%10), ' ', 927 mon[0], mon[1], mon[2], ' ', 928 byte('0'+yy/1000), byte('0'+(yy/100)%10), byte('0'+(yy/10)%10), byte('0'+yy%10), ' ', 929 byte('0'+hh/10), byte('0'+hh%10), ':', 930 byte('0'+mn/10), byte('0'+mn%10), ':', 931 byte('0'+ss/10), byte('0'+ss%10), ' ', 932 'G', 'M', 'T') 933 } 934 935 var errTooLarge = errors.New("http: request too large") 936 937 // Read next request from connection. 938 func (c *conn) readRequest(ctx context.Context) (w *response, err error) { 939 if c.hijacked() { 940 return nil, ErrHijacked 941 } 942 943 var ( 944 wholeReqDeadline time.Time // or zero if none 945 hdrDeadline time.Time // or zero if none 946 ) 947 t0 := time.Now() 948 if d := c.server.readHeaderTimeout(); d > 0 { 949 hdrDeadline = t0.Add(d) 950 } 951 if d := c.server.ReadTimeout; d > 0 { 952 wholeReqDeadline = t0.Add(d) 953 } 954 _ = c.rwc.SetReadDeadline(hdrDeadline) 955 if d := c.server.WriteTimeout; d > 0 { 956 defer func() { 957 _ = c.rwc.SetWriteDeadline(time.Now().Add(d)) 958 }() 959 } 960 961 c.r.setReadLimit(c.server.initialReadLimitSize()) 962 if c.lastMethod == "POST" { 963 // RFC 7230 section 3 tolerance for old buggy clients. 964 peek, _ := c.bufr.Peek(4) // ReadRequest will get err below 965 _, _ = c.bufr.Discard(numLeadingCRorLF(peek)) 966 } 967 req, err := readRequest(c.bufr) 968 if err != nil { 969 if c.r.hitReadLimit() { 970 return nil, errTooLarge 971 } 972 return nil, err 973 } 974 975 if !http1ServerSupportsRequest(req) { 976 return nil, statusError{StatusHTTPVersionNotSupported, "unsupported protocol version"} 977 } 978 979 c.lastMethod = req.Method 980 c.r.setInfiniteReadLimit() 981 982 hosts, haveHost := req.Header["Host"] 983 isH2Upgrade := req.isH2Upgrade() 984 if req.ProtoAtLeast(1, 1) && (!haveHost || len(hosts) == 0) && !isH2Upgrade && req.Method != "CONNECT" { 985 return nil, badRequestError("missing required Host header") 986 } 987 if len(hosts) == 1 && !httpguts.ValidHostHeader(hosts[0]) { 988 return nil, badRequestError("malformed Host header") 989 } 990 for k, vv := range req.Header { 991 if !httpguts.ValidHeaderFieldName(k) { 992 return nil, badRequestError("invalid header name") 993 } 994 for _, v := range vv { 995 if !httpguts.ValidHeaderFieldValue(v) { 996 return nil, badRequestError("invalid header value") 997 } 998 } 999 } 1000 delete(req.Header, "Host") 1001 1002 ctx, cancelCtx := context.WithCancel(ctx) 1003 req.ctx = ctx 1004 req.RemoteAddr = c.remoteAddr 1005 req.TLS = c.tlsState 1006 if body, ok := req.Body.(*body); ok { 1007 body.doEarlyClose = true 1008 } 1009 1010 // Adjust the read deadline if necessary. 1011 if !hdrDeadline.Equal(wholeReqDeadline) { 1012 _ = c.rwc.SetReadDeadline(wholeReqDeadline) 1013 } 1014 1015 w = &response{ 1016 conn: c, 1017 cancelCtx: cancelCtx, 1018 req: req, 1019 reqBody: req.Body, 1020 handlerHeader: make(Header), 1021 contentLength: -1, 1022 closeNotifyCh: make(chan bool, 1), 1023 1024 // We populate these ahead of time so we're not 1025 // reading from req.Header after their Handler starts 1026 // and maybe mutates it (Issue 14940) 1027 wants10KeepAlive: req.wantsHttp10KeepAlive(), 1028 wantsClose: req.wantsClose(), 1029 } 1030 if isH2Upgrade { 1031 w.closeAfterReply = true 1032 } 1033 w.cw.res = w 1034 w.w = newBufioWriterSize(&w.cw, bufferBeforeChunkingSize) 1035 return w, nil 1036 } 1037 1038 // http1ServerSupportsRequest reports whether Go's HTTP/1.x server 1039 // supports the given request. 1040 func http1ServerSupportsRequest(req *Request) bool { 1041 if req.ProtoMajor == 1 { 1042 return true 1043 } 1044 // Accept "PRI * HTTP/2.0" upgrade requests, so Handlers can 1045 // wire up their own HTTP/2 upgrades. 1046 if req.ProtoMajor == 2 && req.ProtoMinor == 0 && 1047 req.Method == "PRI" && req.RequestURI == "*" { 1048 return true 1049 } 1050 // Reject HTTP/0.x, and all other HTTP/2+ requests (which 1051 // aren't encoded in ASCII anyway). 1052 return false 1053 } 1054 1055 func (w *response) Header() Header { 1056 if w.cw.header == nil && w.wroteHeader && !w.cw.wroteHeader { 1057 // Accessing the header between logically writing it 1058 // and physically writing it means we need to allocate 1059 // a clone to snapshot the logically written state. 1060 w.cw.header = w.handlerHeader.Clone() 1061 } 1062 w.calledHeader = true 1063 return w.handlerHeader 1064 } 1065 1066 // maxPostHandlerReadBytes is the max number of Request.Body bytes not 1067 // consumed by a handler that the server will read from the client 1068 // in order to keep a connection alive. If there are more bytes than 1069 // this then the server to be paranoid instead sends a "Connection: 1070 // close" response. 1071 // 1072 // This number is approximately what a typical machine's TCP buffer 1073 // size is anyway. (if we have the bytes on the machine, we might as 1074 // well read them) 1075 const maxPostHandlerReadBytes = 256 << 10 1076 1077 func checkWriteHeaderCode(code int) { 1078 // Issue 22880: require valid WriteHeader status codes. 1079 // For now we only enforce that it's three digits. 1080 // In the future we might block things over 599 (600 and above aren't defined 1081 // at https://httpwg.org/specs/rfc7231.html#status.codes) 1082 // and we might block under 200 (once we have more mature 1xx support). 1083 // But for now any three digits. 1084 // 1085 // We used to send "HTTP/1.1 000 0" on the wire in responses but there's 1086 // no equivalent bogus thing we can realistically send in HTTP/2, 1087 // so we'll consistently panic instead and help people find their bugs 1088 // early. (We can't return an error from WriteHeader even if we wanted to.) 1089 if code < 100 || code > 999 { 1090 panic(fmt.Sprintf("invalid WriteHeader code %v", code)) 1091 } 1092 } 1093 1094 // relevantCaller searches the call stack for the first function outside of net/http. 1095 // The purpose of this function is to provide more helpful error messages. 1096 func relevantCaller() runtime.Frame { 1097 pc := make([]uintptr, 16) 1098 n := runtime.Callers(1, pc) 1099 frames := runtime.CallersFrames(pc[:n]) 1100 var frame runtime.Frame 1101 for { 1102 frame, more := frames.Next() 1103 if !strings.HasPrefix(frame.Function, "gitee.com/zhaochuninhefei/gmgo/gmhttp.") { 1104 return frame 1105 } 1106 if !more { 1107 break 1108 } 1109 } 1110 return frame 1111 } 1112 1113 func (w *response) WriteHeader(code int) { 1114 if w.conn.hijacked() { 1115 caller := relevantCaller() 1116 w.conn.server.logf("http: response.WriteHeader on hijacked connection from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line) 1117 return 1118 } 1119 if w.wroteHeader { 1120 caller := relevantCaller() 1121 w.conn.server.logf("http: superfluous response.WriteHeader call from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line) 1122 return 1123 } 1124 checkWriteHeaderCode(code) 1125 w.wroteHeader = true 1126 w.status = code 1127 1128 if w.calledHeader && w.cw.header == nil { 1129 w.cw.header = w.handlerHeader.Clone() 1130 } 1131 1132 if cl := w.handlerHeader.get("Content-Length"); cl != "" { 1133 v, err := strconv.ParseInt(cl, 10, 64) 1134 if err == nil && v >= 0 { 1135 w.contentLength = v 1136 } else { 1137 w.conn.server.logf("http: invalid Content-Length of %q", cl) 1138 w.handlerHeader.Del("Content-Length") 1139 } 1140 } 1141 } 1142 1143 // extraHeader is the set of headers sometimes added by chunkWriter.writeHeader. 1144 // This type is used to avoid extra allocations from cloning and/or populating 1145 // the response Header map and all its 1-element slices. 1146 type extraHeader struct { 1147 contentType string 1148 connection string 1149 transferEncoding string 1150 date []byte // written if not nil 1151 contentLength []byte // written if not nil 1152 } 1153 1154 // Sorted the same as extraHeader.Write's loop. 1155 var extraHeaderKeys = [][]byte{ 1156 []byte("Content-Type"), 1157 []byte("Connection"), 1158 []byte("Transfer-Encoding"), 1159 } 1160 1161 var ( 1162 headerContentLength = []byte("Content-Length: ") 1163 headerDate = []byte("Date: ") 1164 ) 1165 1166 // Write writes the headers described in h to w. 1167 // 1168 // This method has a value receiver, despite the somewhat large size 1169 // of h, because it prevents an allocation. The escape analysis isn't 1170 // smart enough to realize this function doesn't mutate h. 1171 func (h extraHeader) Write(w *bufio.Writer) { 1172 if h.date != nil { 1173 _, _ = w.Write(headerDate) 1174 _, _ = w.Write(h.date) 1175 _, _ = w.Write(crlf) 1176 } 1177 if h.contentLength != nil { 1178 _, _ = w.Write(headerContentLength) 1179 _, _ = w.Write(h.contentLength) 1180 _, _ = w.Write(crlf) 1181 } 1182 for i, v := range []string{h.contentType, h.connection, h.transferEncoding} { 1183 if v != "" { 1184 _, _ = w.Write(extraHeaderKeys[i]) 1185 _, _ = w.Write(colonSpace) 1186 _, _ = w.WriteString(v) 1187 _, _ = w.Write(crlf) 1188 } 1189 } 1190 } 1191 1192 // writeHeader finalizes the header sent to the client and writes it 1193 // to cw.res.conn.bufw. 1194 // 1195 // p is not written by writeHeader, but is the first chunk of the body 1196 // that will be written. It is sniffed for a Content-Type if none is 1197 // set explicitly. It's also used to set the Content-Length, if the 1198 // total body size was small and the handler has already finished 1199 // running. 1200 func (cw *chunkWriter) writeHeader(p []byte) { 1201 if cw.wroteHeader { 1202 return 1203 } 1204 cw.wroteHeader = true 1205 1206 w := cw.res 1207 keepAlivesEnabled := w.conn.server.doKeepAlives() 1208 isHEAD := w.req.Method == "HEAD" 1209 1210 // header is written out to w.conn.buf below. Depending on the 1211 // state of the handler, we either own the map or not. If we 1212 // don't own it, the exclude map is created lazily for 1213 // WriteSubset to remove headers. The setHeader struct holds 1214 // headers we need to add. 1215 header := cw.header 1216 owned := header != nil 1217 if !owned { 1218 header = w.handlerHeader 1219 } 1220 var excludeHeader map[string]bool 1221 delHeader := func(key string) { 1222 if owned { 1223 header.Del(key) 1224 return 1225 } 1226 if _, ok := header[key]; !ok { 1227 return 1228 } 1229 if excludeHeader == nil { 1230 excludeHeader = make(map[string]bool) 1231 } 1232 excludeHeader[key] = true 1233 } 1234 var setHeader extraHeader 1235 1236 // Don't write out the fake "Trailer:foo" keys. See TrailerPrefix. 1237 trailers := false 1238 for k := range cw.header { 1239 if strings.HasPrefix(k, TrailerPrefix) { 1240 if excludeHeader == nil { 1241 excludeHeader = make(map[string]bool) 1242 } 1243 excludeHeader[k] = true 1244 trailers = true 1245 } 1246 } 1247 for _, v := range cw.header["Trailer"] { 1248 trailers = true 1249 foreachHeaderElement(v, cw.res.declareTrailer) 1250 } 1251 1252 te := header.get("Transfer-Encoding") 1253 hasTE := te != "" 1254 1255 // If the handler is done but never sent a Content-Length 1256 // response header and this is our first (and last) write, set 1257 // it, even to zero. This helps HTTP/1.0 clients keep their 1258 // "keep-alive" connections alive. 1259 // Exceptions: 304/204/1xx responses never get Content-Length, and if 1260 // it was a HEAD request, we don't know the difference between 1261 // 0 actual bytes and 0 bytes because the handler noticed it 1262 // was a HEAD request and chose not to write anything. So for 1263 // HEAD, the handler should either write the Content-Length or 1264 // write non-zero bytes. If it's actually 0 bytes and the 1265 // handler never looked at the Request.Method, we just don't 1266 // send a Content-Length header. 1267 // Further, we don't send an automatic Content-Length if they 1268 // set a Transfer-Encoding, because they're generally incompatible. 1269 if w.handlerDone.isSet() && !trailers && !hasTE && bodyAllowedForStatus(w.status) && header.get("Content-Length") == "" && (!isHEAD || len(p) > 0) { 1270 w.contentLength = int64(len(p)) 1271 setHeader.contentLength = strconv.AppendInt(cw.res.clenBuf[:0], int64(len(p)), 10) 1272 } 1273 1274 // If this was an HTTP/1.0 request with keep-alive and we sent a 1275 // Content-Length back, we can make this a keep-alive response ... 1276 if w.wants10KeepAlive && keepAlivesEnabled { 1277 sentLength := header.get("Content-Length") != "" 1278 if sentLength && header.get("Connection") == "keep-alive" { 1279 w.closeAfterReply = false 1280 } 1281 } 1282 1283 // Check for an explicit (and valid) Content-Length header. 1284 hasCL := w.contentLength != -1 1285 1286 if w.wants10KeepAlive && (isHEAD || hasCL || !bodyAllowedForStatus(w.status)) { 1287 _, connectionHeaderSet := header["Connection"] 1288 if !connectionHeaderSet { 1289 setHeader.connection = "keep-alive" 1290 } 1291 } else if !w.req.ProtoAtLeast(1, 1) || w.wantsClose { 1292 w.closeAfterReply = true 1293 } 1294 1295 if header.get("Connection") == "close" || !keepAlivesEnabled { 1296 w.closeAfterReply = true 1297 } 1298 1299 // If the client wanted a 100-continue but we never sent it to 1300 // them (or, more strictly: we never finished reading their 1301 // request body), don't reuse this connection because it's now 1302 // in an unknown state: we might be sending this response at 1303 // the same time the client is now sending its request body 1304 // after a timeout. (Some HTTP clients send Expect: 1305 // 100-continue but knowing that some servers don't support 1306 // it, the clients set a timer and send the body later anyway) 1307 // If we haven't seen EOF, we can't skip over the unread body 1308 // because we don't know if the next bytes on the wire will be 1309 // the body-following-the-timer or the subsequent request. 1310 // See Issue 11549. 1311 if ecr, ok := w.req.Body.(*expectContinueReader); ok && !ecr.sawEOF.isSet() { 1312 w.closeAfterReply = true 1313 } 1314 1315 // Per RFC 2616, we should consume the request body before 1316 // replying, if the handler hasn't already done so. But we 1317 // don't want to do an unbounded amount of reading here for 1318 // DoS reasons, so we only try up to a threshold. 1319 // TODO(bradfitz): where does RFC 2616 say that? See Issue 15527 1320 // about HTTP/1.x Handlers concurrently reading and writing, like 1321 // HTTP/2 handlers can do. Maybe this code should be relaxed? 1322 if w.req.ContentLength != 0 && !w.closeAfterReply { 1323 var discard, tooBig bool 1324 1325 switch bdy := w.req.Body.(type) { 1326 case *expectContinueReader: 1327 if bdy.resp.wroteContinue { 1328 discard = true 1329 } 1330 case *body: 1331 bdy.mu.Lock() 1332 switch { 1333 case bdy.closed: 1334 if !bdy.sawEOF { 1335 // Body was closed in handler with non-EOF error. 1336 w.closeAfterReply = true 1337 } 1338 case bdy.unreadDataSizeLocked() >= maxPostHandlerReadBytes: 1339 tooBig = true 1340 default: 1341 discard = true 1342 } 1343 bdy.mu.Unlock() 1344 default: 1345 discard = true 1346 } 1347 1348 if discard { 1349 _, err := io.CopyN(io.Discard, w.reqBody, maxPostHandlerReadBytes+1) 1350 switch err { 1351 case nil: 1352 // There must be even more data left over. 1353 tooBig = true 1354 case ErrBodyReadAfterClose: 1355 // Body was already consumed and closed. 1356 case io.EOF: 1357 // The remaining body was just consumed, close it. 1358 err = w.reqBody.Close() 1359 if err != nil { 1360 w.closeAfterReply = true 1361 } 1362 default: 1363 // Some other kind of error occurred, like a read timeout, or 1364 // corrupt chunked encoding. In any case, whatever remains 1365 // on the wire must not be parsed as another HTTP request. 1366 w.closeAfterReply = true 1367 } 1368 } 1369 1370 if tooBig { 1371 w.requestTooLarge() 1372 delHeader("Connection") 1373 setHeader.connection = "close" 1374 } 1375 } 1376 1377 code := w.status 1378 if bodyAllowedForStatus(code) { 1379 // If no content type, apply sniffing algorithm to body. 1380 _, haveType := header["Content-Type"] 1381 1382 // If the Content-Encoding was set and is non-blank, 1383 // we shouldn't sniff the body. See Issue 31753. 1384 ce := header.Get("Content-Encoding") 1385 hasCE := len(ce) > 0 1386 if !hasCE && !haveType && !hasTE && len(p) > 0 { 1387 setHeader.contentType = DetectContentType(p) 1388 } 1389 } else { 1390 for _, k := range suppressedHeaders(code) { 1391 delHeader(k) 1392 } 1393 } 1394 1395 if !header.has("Date") { 1396 setHeader.date = appendTime(cw.res.dateBuf[:0], time.Now()) 1397 } 1398 1399 if hasCL && hasTE && te != "identity" { 1400 // TODO: return an error if WriteHeader gets a return parameter 1401 // For now just ignore the Content-Length. 1402 w.conn.server.logf("http: WriteHeader called with both Transfer-Encoding of %q and a Content-Length of %d", 1403 te, w.contentLength) 1404 delHeader("Content-Length") 1405 hasCL = false 1406 } 1407 1408 if w.req.Method == "HEAD" || !bodyAllowedForStatus(code) || code == StatusNoContent { 1409 // Response has no body. 1410 delHeader("Transfer-Encoding") 1411 } else if hasCL { 1412 // Content-Length has been provided, so no chunking is to be done. 1413 delHeader("Transfer-Encoding") 1414 } else if w.req.ProtoAtLeast(1, 1) { 1415 // HTTP/1.1 or greater: Transfer-Encoding has been set to identity, and no 1416 // content-length has been provided. The connection must be closed after the 1417 // reply is written, and no chunking is to be done. This is the setup 1418 // recommended in the Server-Sent Events candidate recommendation 11, 1419 // section 8. 1420 if hasTE && te == "identity" { 1421 cw.chunking = false 1422 w.closeAfterReply = true 1423 delHeader("Transfer-Encoding") 1424 } else { 1425 // HTTP/1.1 or greater: use chunked transfer encoding 1426 // to avoid closing the connection at EOF. 1427 cw.chunking = true 1428 setHeader.transferEncoding = "chunked" 1429 if hasTE && te == "chunked" { 1430 // We will send the chunked Transfer-Encoding header later. 1431 delHeader("Transfer-Encoding") 1432 } 1433 } 1434 } else { 1435 // HTTP version < 1.1: cannot do chunked transfer 1436 // encoding and we don't know the Content-Length so 1437 // signal EOF by closing connection. 1438 w.closeAfterReply = true 1439 delHeader("Transfer-Encoding") // in case already set 1440 } 1441 1442 // Cannot use Content-Length with non-identity Transfer-Encoding. 1443 if cw.chunking { 1444 delHeader("Content-Length") 1445 } 1446 if !w.req.ProtoAtLeast(1, 0) { 1447 return 1448 } 1449 1450 // Only override the Connection header if it is not a successful 1451 // protocol switch response and if KeepAlives are not enabled. 1452 // See https://golang.org/issue/36381. 1453 delConnectionHeader := w.closeAfterReply && 1454 (!keepAlivesEnabled || !hasToken(cw.header.get("Connection"), "close")) && 1455 !isProtocolSwitchResponse(w.status, header) 1456 if delConnectionHeader { 1457 delHeader("Connection") 1458 if w.req.ProtoAtLeast(1, 1) { 1459 setHeader.connection = "close" 1460 } 1461 } 1462 1463 writeStatusLine(w.conn.bufw, w.req.ProtoAtLeast(1, 1), code, w.statusBuf[:]) 1464 _ = cw.header.WriteSubset(w.conn.bufw, excludeHeader) 1465 setHeader.Write(w.conn.bufw) 1466 _, _ = w.conn.bufw.Write(crlf) 1467 } 1468 1469 // foreachHeaderElement splits v according to the "#rule" construction 1470 // in RFC 7230 section 7 and calls fn for each non-empty element. 1471 func foreachHeaderElement(v string, fn func(string)) { 1472 v = textproto.TrimString(v) 1473 if v == "" { 1474 return 1475 } 1476 if !strings.Contains(v, ",") { 1477 fn(v) 1478 return 1479 } 1480 for _, f := range strings.Split(v, ",") { 1481 if f = textproto.TrimString(f); f != "" { 1482 fn(f) 1483 } 1484 } 1485 } 1486 1487 // writeStatusLine writes an HTTP/1.x Status-Line (RFC 7230 Section 3.1.2) 1488 // to bw. is11 is whether the HTTP request is HTTP/1.1. false means HTTP/1.0. 1489 // code is the response status code. 1490 // scratch is an optional scratch buffer. If it has at least capacity 3, it's used. 1491 func writeStatusLine(bw *bufio.Writer, is11 bool, code int, scratch []byte) { 1492 if is11 { 1493 _, _ = bw.WriteString("HTTP/1.1 ") 1494 } else { 1495 _, _ = bw.WriteString("HTTP/1.0 ") 1496 } 1497 if text, ok := statusText[code]; ok { 1498 _, _ = bw.Write(strconv.AppendInt(scratch[:0], int64(code), 10)) 1499 _ = bw.WriteByte(' ') 1500 _, _ = bw.WriteString(text) 1501 _, _ = bw.WriteString("\r\n") 1502 } else { 1503 // don't worry about performance 1504 _, _ = fmt.Fprintf(bw, "%03d status code %d\r\n", code, code) 1505 } 1506 } 1507 1508 // bodyAllowed reports whether a Write is allowed for this response type. 1509 // It's illegal to call this before the header has been flushed. 1510 func (w *response) bodyAllowed() bool { 1511 if !w.wroteHeader { 1512 panic("") 1513 } 1514 return bodyAllowedForStatus(w.status) 1515 } 1516 1517 // The Life Of A Write is like this: 1518 // 1519 // Handler starts. No header has been sent. The handler can either 1520 // write a header, or just start writing. Writing before sending a header 1521 // sends an implicitly empty 200 OK header. 1522 // 1523 // If the handler didn't declare a Content-Length up front, we either 1524 // go into chunking mode or, if the handler finishes running before 1525 // the chunking buffer size, we compute a Content-Length and send that 1526 // in the header instead. 1527 // 1528 // Likewise, if the handler didn't set a Content-Type, we sniff that 1529 // from the initial chunk of output. 1530 // 1531 // The Writers are wired together like: 1532 // 1533 // 1. *response (the ResponseWriter) -> 1534 // 2. (*response).w, a *bufio.Writer of bufferBeforeChunkingSize bytes -> 1535 // 3. chunkWriter.Writer (whose writeHeader finalizes Content-Length/Type) 1536 // and which writes the chunk headers, if needed -> 1537 // 4. conn.bufw, a *bufio.Writer of default (4kB) bytes, writing to -> 1538 // 5. checkConnErrorWriter{c}, which notes any non-nil error on Write 1539 // and populates c.werr with it if so, but otherwise writes to -> 1540 // 6. the rwc, the net.Conn. 1541 // 1542 // TODO(bradfitz): short-circuit some of the buffering when the 1543 // initial header contains both a Content-Type and Content-Length. 1544 // Also short-circuit in (1) when the header's been sent and not in 1545 // chunking mode, writing directly to (4) instead, if (2) has no 1546 // buffered data. More generally, we could short-circuit from (1) to 1547 // (3) even in chunking mode if the write size from (1) is over some 1548 // threshold and nothing is in (2). The answer might be mostly making 1549 // bufferBeforeChunkingSize smaller and having bufio's fast-paths deal 1550 // with this instead. 1551 func (w *response) Write(data []byte) (n int, err error) { 1552 return w.write(len(data), data, "") 1553 } 1554 1555 func (w *response) WriteString(data string) (n int, err error) { 1556 return w.write(len(data), nil, data) 1557 } 1558 1559 // either dataB or dataS is non-zero. 1560 func (w *response) write(lenData int, dataB []byte, dataS string) (n int, err error) { 1561 if w.conn.hijacked() { 1562 if lenData > 0 { 1563 caller := relevantCaller() 1564 w.conn.server.logf("http: response.Write on hijacked connection from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line) 1565 } 1566 return 0, ErrHijacked 1567 } 1568 1569 if w.canWriteContinue.isSet() { 1570 // Body reader wants to write 100 Continue but hasn't yet. 1571 // Tell it not to. The store must be done while holding the lock 1572 // because the lock makes sure that there is not an active write 1573 // this very moment. 1574 w.writeContinueMu.Lock() 1575 w.canWriteContinue.setFalse() 1576 w.writeContinueMu.Unlock() 1577 } 1578 1579 if !w.wroteHeader { 1580 w.WriteHeader(StatusOK) 1581 } 1582 if lenData == 0 { 1583 return 0, nil 1584 } 1585 if !w.bodyAllowed() { 1586 return 0, ErrBodyNotAllowed 1587 } 1588 1589 w.written += int64(lenData) // ignoring errors, for errorKludge 1590 if w.contentLength != -1 && w.written > w.contentLength { 1591 return 0, ErrContentLength 1592 } 1593 if dataB != nil { 1594 return w.w.Write(dataB) 1595 } else { 1596 return w.w.WriteString(dataS) 1597 } 1598 } 1599 1600 func (w *response) finishRequest() { 1601 w.handlerDone.setTrue() 1602 1603 if !w.wroteHeader { 1604 w.WriteHeader(StatusOK) 1605 } 1606 1607 _ = w.w.Flush() 1608 putBufioWriter(w.w) 1609 w.cw.close() 1610 _ = w.conn.bufw.Flush() 1611 1612 w.conn.r.abortPendingRead() 1613 1614 // Close the body (regardless of w.closeAfterReply) so we can 1615 // re-use its bufio.Reader later safely. 1616 _ = w.reqBody.Close() 1617 1618 if w.req.MultipartForm != nil { 1619 _ = w.req.MultipartForm.RemoveAll() 1620 } 1621 } 1622 1623 // shouldReuseConnection reports whether the underlying TCP connection can be reused. 1624 // It must only be called after the handler is done executing. 1625 func (w *response) shouldReuseConnection() bool { 1626 if w.closeAfterReply { 1627 // The request or something set while executing the 1628 // handler indicated we shouldn't reuse this 1629 // connection. 1630 return false 1631 } 1632 1633 if w.req.Method != "HEAD" && w.contentLength != -1 && w.bodyAllowed() && w.contentLength != w.written { 1634 // Did not write enough. Avoid getting out of sync. 1635 return false 1636 } 1637 1638 // There was some error writing to the underlying connection 1639 // during the request, so don't re-use this conn. 1640 if w.conn.werr != nil { 1641 return false 1642 } 1643 1644 if w.closedRequestBodyEarly() { 1645 return false 1646 } 1647 1648 return true 1649 } 1650 1651 func (w *response) closedRequestBodyEarly() bool { 1652 body, ok := w.req.Body.(*body) 1653 return ok && body.didEarlyClose() 1654 } 1655 1656 func (w *response) Flush() { 1657 if !w.wroteHeader { 1658 w.WriteHeader(StatusOK) 1659 } 1660 _ = w.w.Flush() 1661 w.cw.flush() 1662 } 1663 1664 func (c *conn) finalFlush() { 1665 if c.bufr != nil { 1666 // Steal the bufio.Reader (~4KB worth of memory) and its associated 1667 // reader for a future connection. 1668 putBufioReader(c.bufr) 1669 c.bufr = nil 1670 } 1671 1672 if c.bufw != nil { 1673 _ = c.bufw.Flush() 1674 // Steal the bufio.Writer (~4KB worth of memory) and its associated 1675 // writer for a future connection. 1676 putBufioWriter(c.bufw) 1677 c.bufw = nil 1678 } 1679 } 1680 1681 // Close the connection. 1682 func (c *conn) close() { 1683 c.finalFlush() 1684 _ = c.rwc.Close() 1685 } 1686 1687 // rstAvoidanceDelay is the amount of time we sleep after closing the 1688 // write side of a TCP connection before closing the entire socket. 1689 // By sleeping, we increase the chances that the client sees our FIN 1690 // and processes its final data before they process the subsequent RST 1691 // from closing a connection with known unread data. 1692 // This RST seems to occur mostly on BSD systems. (And Windows?) 1693 // This timeout is somewhat arbitrary (~latency around the planet). 1694 const rstAvoidanceDelay = 500 * time.Millisecond 1695 1696 type closeWriter interface { 1697 CloseWrite() error 1698 } 1699 1700 var _ closeWriter = (*net.TCPConn)(nil) 1701 1702 // closeWrite flushes any outstanding data and sends a FIN packet (if 1703 // client is connected via TCP), signalling that we're done. We then 1704 // pause for a bit, hoping the client processes it before any 1705 // subsequent RST. 1706 // 1707 // See https://golang.org/issue/3595 1708 func (c *conn) closeWriteAndWait() { 1709 c.finalFlush() 1710 if tcp, ok := c.rwc.(closeWriter); ok { 1711 _ = tcp.CloseWrite() 1712 } 1713 time.Sleep(rstAvoidanceDelay) 1714 } 1715 1716 // validNextProto reports whether the proto is a valid ALPN protocol name. 1717 // Everything is valid except the empty string and built-in protocol types, 1718 // so that those can't be overridden with alternate implementations. 1719 func validNextProto(proto string) bool { 1720 switch proto { 1721 case "", "http/1.1", "http/1.0": 1722 return false 1723 } 1724 return true 1725 } 1726 1727 const ( 1728 runHooks = true 1729 skipHooks = false 1730 ) 1731 1732 func (c *conn) setState(nc net.Conn, state ConnState, runHook bool) { 1733 srv := c.server 1734 switch state { 1735 case StateNew: 1736 srv.trackConn(c, true) 1737 case StateHijacked, StateClosed: 1738 srv.trackConn(c, false) 1739 } 1740 if state > 0xff || state < 0 { 1741 panic("internal error") 1742 } 1743 packedState := uint64(time.Now().Unix()<<8) | uint64(state) 1744 atomic.StoreUint64(&c.curState.atomic, packedState) 1745 if !runHook { 1746 return 1747 } 1748 if hook := srv.ConnState; hook != nil { 1749 hook(nc, state) 1750 } 1751 } 1752 1753 func (c *conn) getState() (state ConnState, unixSec int64) { 1754 packedState := atomic.LoadUint64(&c.curState.atomic) 1755 return ConnState(packedState & 0xff), int64(packedState >> 8) 1756 } 1757 1758 // badRequestError is a literal string (used by in the server in HTML, 1759 // unescaped) to tell the user why their request was bad. It should 1760 // be plain text without user info or other embedded errors. 1761 func badRequestError(e string) error { return statusError{StatusBadRequest, e} } 1762 1763 // statusError is an error used to respond to a request with an HTTP status. 1764 // The text should be plain text without user info or other embedded errors. 1765 type statusError struct { 1766 code int 1767 text string 1768 } 1769 1770 func (e statusError) Error() string { return StatusText(e.code) + ": " + e.text } 1771 1772 // ErrAbortHandler is a sentinel panic value to abort a handler. 1773 // While any panic from ServeHTTP aborts the response to the client, 1774 // panicking with ErrAbortHandler also suppresses logging of a stack 1775 // trace to the server's error log. 1776 var ErrAbortHandler = errors.New("gitee.com/zhaochuninhefei/gmgo/gmhttp: abort Handler") 1777 1778 // isCommonNetReadError reports whether err is a common error 1779 // encountered during reading a request off the network when the 1780 // client has gone away or had its read fail somehow. This is used to 1781 // determine which logs are interesting enough to log about. 1782 func isCommonNetReadError(err error) bool { 1783 if err == io.EOF { 1784 return true 1785 } 1786 if neterr, ok := err.(net.Error); ok && neterr.Timeout() { 1787 return true 1788 } 1789 if oe, ok := err.(*net.OpError); ok && oe.Op == "read" { 1790 return true 1791 } 1792 return false 1793 } 1794 1795 // Serve a new connection. 1796 func (c *conn) serve(ctx context.Context) { 1797 c.remoteAddr = c.rwc.RemoteAddr().String() 1798 ctx = context.WithValue(ctx, LocalAddrContextKey, c.rwc.LocalAddr()) 1799 defer func() { 1800 if err := recover(); err != nil && err != ErrAbortHandler { 1801 const size = 64 << 10 1802 buf := make([]byte, size) 1803 buf = buf[:runtime.Stack(buf, false)] 1804 c.server.logf("http: panic serving %v: %v\n%s", c.remoteAddr, err, buf) 1805 } 1806 if !c.hijacked() { 1807 c.close() 1808 c.setState(c.rwc, StateClosed, runHooks) 1809 } 1810 }() 1811 1812 if tlsConn, ok := c.rwc.(*tls.Conn); ok { 1813 if d := c.server.ReadTimeout; d > 0 { 1814 _ = c.rwc.SetReadDeadline(time.Now().Add(d)) 1815 } 1816 if d := c.server.WriteTimeout; d > 0 { 1817 _ = c.rwc.SetWriteDeadline(time.Now().Add(d)) 1818 } 1819 if err := tlsConn.HandshakeContext(ctx); err != nil { 1820 // If the handshake failed due to the client not speaking 1821 // TLS, assume they're speaking plaintext HTTP and write a 1822 // 400 response on the TLS conn's underlying net.Conn. 1823 if re, ok := err.(tls.RecordHeaderError); ok && re.Conn != nil && tlsRecordHeaderLooksLikeHTTP(re.RecordHeader) { 1824 _, _ = io.WriteString(re.Conn, "HTTP/1.0 400 Bad Request\r\n\r\nClient sent an HTTP request to an HTTPS server.\n") 1825 _ = re.Conn.Close() 1826 return 1827 } 1828 c.server.logf("http: TLS handshake error from %s: %v", c.rwc.RemoteAddr(), err) 1829 return 1830 } 1831 c.tlsState = new(tls.ConnectionState) 1832 *c.tlsState = tlsConn.ConnectionState() 1833 if proto := c.tlsState.NegotiatedProtocol; validNextProto(proto) { 1834 if fn := c.server.TLSNextProto[proto]; fn != nil { 1835 h := initALPNRequest{ctx, tlsConn, serverHandler{c.server}} 1836 // Mark freshly created HTTP/2 as active and prevent any server state hooks 1837 // from being run on these connections. This prevents closeIdleConns from 1838 // closing such connections. See issue https://golang.org/issue/39776. 1839 c.setState(c.rwc, StateActive, skipHooks) 1840 fn(c.server, tlsConn, h) 1841 } 1842 return 1843 } 1844 } 1845 1846 // HTTP/1.x from here on. 1847 1848 ctx, cancelCtx := context.WithCancel(ctx) 1849 c.cancelCtx = cancelCtx 1850 defer cancelCtx() 1851 1852 c.r = &connReader{conn: c} 1853 c.bufr = newBufioReader(c.r) 1854 c.bufw = newBufioWriterSize(checkConnErrorWriter{c}, 4<<10) 1855 1856 for { 1857 w, err := c.readRequest(ctx) 1858 if c.r.remain != c.server.initialReadLimitSize() { 1859 // If we read any bytes off the wire, we're active. 1860 c.setState(c.rwc, StateActive, runHooks) 1861 } 1862 if err != nil { 1863 const errorHeaders = "\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\n" 1864 1865 switch { 1866 case err == errTooLarge: 1867 // Their HTTP client may or may not be 1868 // able to read this if we're 1869 // responding to them and hanging up 1870 // while they're still writing their 1871 // request. Undefined behavior. 1872 const publicErr = "431 Request Header Fields Too Large" 1873 _, _ = fmt.Fprintf(c.rwc, "HTTP/1.1 "+publicErr+errorHeaders+publicErr) 1874 c.closeWriteAndWait() 1875 return 1876 1877 case isUnsupportedTEError(err): 1878 // Respond as per RFC 7230 Section 3.3.1 which says, 1879 // A server that receives a request message with a 1880 // transfer coding it does not understand SHOULD 1881 // respond with 501 (Unimplemented). 1882 code := StatusNotImplemented 1883 1884 // We purposefully aren't echoing back the transfer-encoding's value, 1885 // so as to mitigate the risk of cross side scripting by an attacker. 1886 _, _ = fmt.Fprintf(c.rwc, "HTTP/1.1 %d %s%sUnsupported transfer encoding", code, StatusText(code), errorHeaders) 1887 return 1888 1889 case isCommonNetReadError(err): 1890 return // don't reply 1891 1892 default: 1893 if v, ok := err.(statusError); ok { 1894 _, _ = fmt.Fprintf(c.rwc, "HTTP/1.1 %d %s: %s%s%d %s: %s", v.code, StatusText(v.code), v.text, errorHeaders, v.code, StatusText(v.code), v.text) 1895 return 1896 } 1897 publicErr := "400 Bad Request" 1898 _, _ = fmt.Fprintf(c.rwc, "HTTP/1.1 "+publicErr+errorHeaders+publicErr) 1899 return 1900 } 1901 } 1902 1903 // Expect 100 Continue support 1904 req := w.req 1905 if req.expectsContinue() { 1906 if req.ProtoAtLeast(1, 1) && req.ContentLength != 0 { 1907 // Wrap the Body reader with one that replies on the connection 1908 req.Body = &expectContinueReader{readCloser: req.Body, resp: w} 1909 w.canWriteContinue.setTrue() 1910 } 1911 } else if req.Header.get("Expect") != "" { 1912 w.sendExpectationFailed() 1913 return 1914 } 1915 1916 c.curReq.Store(w) 1917 1918 if requestBodyRemains(req.Body) { 1919 registerOnHitEOF(req.Body, w.conn.r.startBackgroundRead) 1920 } else { 1921 w.conn.r.startBackgroundRead() 1922 } 1923 1924 // HTTP cannot have multiple simultaneous active requests.[*] 1925 // Until the server replies to this request, it can't read another, 1926 // so we might as well run the handler in this goroutine. 1927 // [*] Not strictly true: HTTP pipelining. We could let them all process 1928 // in parallel even if their responses need to be serialized. 1929 // But we're not going to implement HTTP pipelining because it 1930 // was never deployed in the wild and the answer is HTTP/2. 1931 serverHandler{c.server}.ServeHTTP(w, w.req) 1932 w.cancelCtx() 1933 if c.hijacked() { 1934 return 1935 } 1936 w.finishRequest() 1937 if !w.shouldReuseConnection() { 1938 if w.requestBodyLimitHit || w.closedRequestBodyEarly() { 1939 c.closeWriteAndWait() 1940 } 1941 return 1942 } 1943 c.setState(c.rwc, StateIdle, runHooks) 1944 c.curReq.Store((*response)(nil)) 1945 1946 if !w.conn.server.doKeepAlives() { 1947 // We're in shutdown mode. We might've replied 1948 // to the user without "Connection: close" and 1949 // they might think they can send another 1950 // request, but such is life with HTTP/1.1. 1951 return 1952 } 1953 1954 if d := c.server.idleTimeout(); d != 0 { 1955 _ = c.rwc.SetReadDeadline(time.Now().Add(d)) 1956 if _, err := c.bufr.Peek(4); err != nil { 1957 return 1958 } 1959 } 1960 _ = c.rwc.SetReadDeadline(time.Time{}) 1961 } 1962 } 1963 1964 func (w *response) sendExpectationFailed() { 1965 // TODO(bradfitz): let ServeHTTP handlers handle 1966 // requests with non-standard expectation[s]? Seems 1967 // theoretical at best, and doesn't fit into the 1968 // current ServeHTTP model anyway. We'd need to 1969 // make the ResponseWriter an optional 1970 // "ExpectReplier" interface or something. 1971 // 1972 // For now we'll just obey RFC 7231 5.1.1 which says 1973 // "A server that receives an Expect field-value other 1974 // than 100-continue MAY respond with a 417 (Expectation 1975 // Failed) status code to indicate that the unexpected 1976 // expectation cannot be met." 1977 w.Header().Set("Connection", "close") 1978 w.WriteHeader(StatusExpectationFailed) 1979 w.finishRequest() 1980 } 1981 1982 // Hijack implements the Hijacker.Hijack method. Our response is both a ResponseWriter 1983 // and a Hijacker. 1984 func (w *response) Hijack() (rwc net.Conn, buf *bufio.ReadWriter, err error) { 1985 if w.handlerDone.isSet() { 1986 panic("gitee.com/zhaochuninhefei/gmgo/gmhttp: Hijack called after ServeHTTP finished") 1987 } 1988 if w.wroteHeader { 1989 w.cw.flush() 1990 } 1991 1992 c := w.conn 1993 c.mu.Lock() 1994 defer c.mu.Unlock() 1995 1996 // Release the bufioWriter that writes to the chunk writer, it is not 1997 // used after a connection has been hijacked. 1998 rwc, buf, err = c.hijackLocked() 1999 if err == nil { 2000 putBufioWriter(w.w) 2001 w.w = nil 2002 } 2003 return rwc, buf, err 2004 } 2005 2006 func (w *response) CloseNotify() <-chan bool { 2007 if w.handlerDone.isSet() { 2008 panic("gitee.com/zhaochuninhefei/gmgo/gmhttp: CloseNotify called after ServeHTTP finished") 2009 } 2010 return w.closeNotifyCh 2011 } 2012 2013 func registerOnHitEOF(rc io.ReadCloser, fn func()) { 2014 switch v := rc.(type) { 2015 case *expectContinueReader: 2016 registerOnHitEOF(v.readCloser, fn) 2017 case *body: 2018 v.registerOnHitEOF(fn) 2019 default: 2020 panic("unexpected type " + fmt.Sprintf("%T", rc)) 2021 } 2022 } 2023 2024 // requestBodyRemains reports whether future calls to Read 2025 // on rc might yield more data. 2026 func requestBodyRemains(rc io.ReadCloser) bool { 2027 if rc == NoBody { 2028 return false 2029 } 2030 switch v := rc.(type) { 2031 case *expectContinueReader: 2032 return requestBodyRemains(v.readCloser) 2033 case *body: 2034 return v.bodyRemains() 2035 default: 2036 panic("unexpected type " + fmt.Sprintf("%T", rc)) 2037 } 2038 } 2039 2040 // The HandlerFunc type is an adapter to allow the use of 2041 // ordinary functions as HTTP handlers. If f is a function 2042 // with the appropriate signature, HandlerFunc(f) is a 2043 // Handler that calls f. 2044 type HandlerFunc func(ResponseWriter, *Request) 2045 2046 // ServeHTTP calls f(w, r). 2047 func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) { 2048 f(w, r) 2049 } 2050 2051 // Helper handlers 2052 2053 // Error replies to the request with the specified error message and HTTP code. 2054 // It does not otherwise end the request; the caller should ensure no further 2055 // writes are done to w. 2056 // The error message should be plain text. 2057 func Error(w ResponseWriter, error string, code int) { 2058 w.Header().Set("Content-Type", "text/plain; charset=utf-8") 2059 w.Header().Set("X-Content-Type-Options", "nosniff") 2060 w.WriteHeader(code) 2061 _, _ = fmt.Fprintln(w, error) 2062 } 2063 2064 // NotFound replies to the request with an HTTP 404 not found error. 2065 //goland:noinspection GoUnusedParameter 2066 func NotFound(w ResponseWriter, r *Request) { Error(w, "404 page not found", StatusNotFound) } 2067 2068 // NotFoundHandler returns a simple request handler 2069 // that replies to each request with a ``404 page not found'' reply. 2070 func NotFoundHandler() Handler { return HandlerFunc(NotFound) } 2071 2072 // StripPrefix returns a handler that serves HTTP requests by removing the 2073 // given prefix from the request URL's Path (and RawPath if set) and invoking 2074 // the handler h. StripPrefix handles a request for a path that doesn't begin 2075 // with prefix by replying with an HTTP 404 not found error. The prefix must 2076 // match exactly: if the prefix in the request contains escaped characters 2077 // the reply is also an HTTP 404 not found error. 2078 func StripPrefix(prefix string, h Handler) Handler { 2079 if prefix == "" { 2080 return h 2081 } 2082 return HandlerFunc(func(w ResponseWriter, r *Request) { 2083 p := strings.TrimPrefix(r.URL.Path, prefix) 2084 rp := strings.TrimPrefix(r.URL.RawPath, prefix) 2085 if len(p) < len(r.URL.Path) && (r.URL.RawPath == "" || len(rp) < len(r.URL.RawPath)) { 2086 r2 := new(Request) 2087 *r2 = *r 2088 r2.URL = new(url.URL) 2089 *r2.URL = *r.URL 2090 r2.URL.Path = p 2091 r2.URL.RawPath = rp 2092 h.ServeHTTP(w, r2) 2093 } else { 2094 NotFound(w, r) 2095 } 2096 }) 2097 } 2098 2099 // Redirect replies to the request with a redirect to url, 2100 // which may be a path relative to the request path. 2101 // 2102 // The provided code should be in the 3xx range and is usually 2103 // StatusMovedPermanently, StatusFound or StatusSeeOther. 2104 // 2105 // If the Content-Type header has not been set, Redirect sets it 2106 // to "text/html; charset=utf-8" and writes a small HTML body. 2107 // Setting the Content-Type header to any value, including nil, 2108 // disables that behavior. 2109 func Redirect(w ResponseWriter, r *Request, url string, code int) { 2110 if u, err := urlpkg.Parse(url); err == nil { 2111 // If url was relative, make its path absolute by 2112 // combining with request path. 2113 // The client would probably do this for us, 2114 // but doing it ourselves is more reliable. 2115 // See RFC 7231, section 7.1.2 2116 if u.Scheme == "" && u.Host == "" { 2117 oldpath := r.URL.Path 2118 if oldpath == "" { // should not happen, but avoid a crash if it does 2119 oldpath = "/" 2120 } 2121 2122 // no leading http://server 2123 if url == "" || url[0] != '/' { 2124 // make relative path absolute 2125 olddir, _ := path.Split(oldpath) 2126 url = olddir + url 2127 } 2128 2129 var query string 2130 if i := strings.Index(url, "?"); i != -1 { 2131 url, query = url[:i], url[i:] 2132 } 2133 2134 // clean up but preserve trailing slash 2135 trailing := strings.HasSuffix(url, "/") 2136 url = path.Clean(url) 2137 if trailing && !strings.HasSuffix(url, "/") { 2138 url += "/" 2139 } 2140 url += query 2141 } 2142 } 2143 2144 h := w.Header() 2145 2146 // RFC 7231 notes that a short HTML body is usually included in 2147 // the response because older user agents may not understand 301/307. 2148 // Do it only if the request didn't already have a Content-Type header. 2149 _, hadCT := h["Content-Type"] 2150 2151 h.Set("Location", hexEscapeNonASCII(url)) 2152 if !hadCT && (r.Method == "GET" || r.Method == "HEAD") { 2153 h.Set("Content-Type", "text/html; charset=utf-8") 2154 } 2155 w.WriteHeader(code) 2156 2157 // Shouldn't send the body for POST or HEAD; that leaves GET. 2158 if !hadCT && r.Method == "GET" { 2159 body := "<a href=\"" + htmlEscape(url) + "\">" + statusText[code] + "</a>.\n" 2160 _, _ = fmt.Fprintln(w, body) 2161 } 2162 } 2163 2164 var htmlReplacer = strings.NewReplacer( 2165 "&", "&", 2166 "<", "<", 2167 ">", ">", 2168 // """ is shorter than """. 2169 `"`, """, 2170 // "'" is shorter than "'" and apos was not in HTML until HTML5. 2171 "'", "'", 2172 ) 2173 2174 func htmlEscape(s string) string { 2175 return htmlReplacer.Replace(s) 2176 } 2177 2178 // Redirect to a fixed URL 2179 type redirectHandler struct { 2180 url string 2181 code int 2182 } 2183 2184 func (rh *redirectHandler) ServeHTTP(w ResponseWriter, r *Request) { 2185 Redirect(w, r, rh.url, rh.code) 2186 } 2187 2188 // RedirectHandler returns a request handler that redirects 2189 // each request it receives to the given url using the given 2190 // status code. 2191 // 2192 // The provided code should be in the 3xx range and is usually 2193 // StatusMovedPermanently, StatusFound or StatusSeeOther. 2194 func RedirectHandler(url string, code int) Handler { 2195 return &redirectHandler{url, code} 2196 } 2197 2198 // ServeMux is an HTTP request multiplexer. 2199 // It matches the URL of each incoming request against a list of registered 2200 // patterns and calls the handler for the pattern that 2201 // most closely matches the URL. 2202 // 2203 // Patterns name fixed, rooted paths, like "/favicon.ico", 2204 // or rooted subtrees, like "/images/" (note the trailing slash). 2205 // Longer patterns take precedence over shorter ones, so that 2206 // if there are handlers registered for both "/images/" 2207 // and "/images/thumbnails/", the latter handler will be 2208 // called for paths beginning "/images/thumbnails/" and the 2209 // former will receive requests for any other paths in the 2210 // "/images/" subtree. 2211 // 2212 // Note that since a pattern ending in a slash names a rooted subtree, 2213 // the pattern "/" matches all paths not matched by other registered 2214 // patterns, not just the URL with Path == "/". 2215 // 2216 // If a subtree has been registered and a request is received naming the 2217 // subtree root without its trailing slash, ServeMux redirects that 2218 // request to the subtree root (adding the trailing slash). This behavior can 2219 // be overridden with a separate registration for the path without 2220 // the trailing slash. For example, registering "/images/" causes ServeMux 2221 // to redirect a request for "/images" to "/images/", unless "/images" has 2222 // been registered separately. 2223 // 2224 // Patterns may optionally begin with a host name, restricting matches to 2225 // URLs on that host only. Host-specific patterns take precedence over 2226 // general patterns, so that a handler might register for the two patterns 2227 // "/codesearch" and "codesearch.google.com/" without also taking over 2228 // requests for "http://www.google.com/". 2229 // 2230 // ServeMux also takes care of sanitizing the URL request path and the Host 2231 // header, stripping the port number and redirecting any request containing . or 2232 // .. elements or repeated slashes to an equivalent, cleaner URL. 2233 type ServeMux struct { 2234 mu sync.RWMutex 2235 m map[string]muxEntry 2236 es []muxEntry // slice of entries sorted from longest to shortest. 2237 hosts bool // whether any patterns contain hostnames 2238 } 2239 2240 type muxEntry struct { 2241 h Handler 2242 pattern string 2243 } 2244 2245 // NewServeMux allocates and returns a new ServeMux. 2246 func NewServeMux() *ServeMux { return new(ServeMux) } 2247 2248 // DefaultServeMux is the default ServeMux used by Serve. 2249 var DefaultServeMux = &defaultServeMux 2250 2251 var defaultServeMux ServeMux 2252 2253 // cleanPath returns the canonical path for p, eliminating . and .. elements. 2254 func cleanPath(p string) string { 2255 if p == "" { 2256 return "/" 2257 } 2258 if p[0] != '/' { 2259 p = "/" + p 2260 } 2261 np := path.Clean(p) 2262 // path.Clean removes trailing slash except for root; 2263 // put the trailing slash back if necessary. 2264 if p[len(p)-1] == '/' && np != "/" { 2265 // Fast path for common case of p being the string we want: 2266 if len(p) == len(np)+1 && strings.HasPrefix(p, np) { 2267 np = p 2268 } else { 2269 np += "/" 2270 } 2271 } 2272 return np 2273 } 2274 2275 // stripHostPort returns h without any trailing ":<port>". 2276 func stripHostPort(h string) string { 2277 // If no port on host, return unchanged 2278 if strings.IndexByte(h, ':') == -1 { 2279 return h 2280 } 2281 host, _, err := net.SplitHostPort(h) 2282 if err != nil { 2283 return h // on error, return unchanged 2284 } 2285 return host 2286 } 2287 2288 // Find a handler on a handler map given a path string. 2289 // Most-specific (longest) pattern wins. 2290 func (mux *ServeMux) match(path string) (h Handler, pattern string) { 2291 // Check for exact match first. 2292 v, ok := mux.m[path] 2293 if ok { 2294 return v.h, v.pattern 2295 } 2296 2297 // Check for longest valid match. mux.es contains all patterns 2298 // that end in / sorted from longest to shortest. 2299 for _, e := range mux.es { 2300 if strings.HasPrefix(path, e.pattern) { 2301 return e.h, e.pattern 2302 } 2303 } 2304 return nil, "" 2305 } 2306 2307 // redirectToPathSlash determines if the given path needs appending "/" to it. 2308 // This occurs when a handler for path + "/" was already registered, but 2309 // not for path itself. If the path needs appending to, it creates a new 2310 // URL, setting the path to u.Path + "/" and returning true to indicate so. 2311 func (mux *ServeMux) redirectToPathSlash(host, path string, u *url.URL) (*url.URL, bool) { 2312 mux.mu.RLock() 2313 shouldRedirect := mux.shouldRedirectRLocked(host, path) 2314 mux.mu.RUnlock() 2315 if !shouldRedirect { 2316 return u, false 2317 } 2318 path = path + "/" 2319 u = &url.URL{Path: path, RawQuery: u.RawQuery} 2320 return u, true 2321 } 2322 2323 // shouldRedirectRLocked reports whether the given path and host should be redirected to 2324 // path+"/". This should happen if a handler is registered for path+"/" but 2325 // not path -- see comments at ServeMux. 2326 func (mux *ServeMux) shouldRedirectRLocked(host, path string) bool { 2327 p := []string{path, host + path} 2328 2329 for _, c := range p { 2330 if _, exist := mux.m[c]; exist { 2331 return false 2332 } 2333 } 2334 2335 n := len(path) 2336 if n == 0 { 2337 return false 2338 } 2339 for _, c := range p { 2340 if _, exist := mux.m[c+"/"]; exist { 2341 return path[n-1] != '/' 2342 } 2343 } 2344 2345 return false 2346 } 2347 2348 // Handler returns the handler to use for the given request, 2349 // consulting r.Method, r.Host, and r.URL.Path. It always returns 2350 // a non-nil handler. If the path is not in its canonical form, the 2351 // handler will be an internally-generated handler that redirects 2352 // to the canonical path. If the host contains a port, it is ignored 2353 // when matching handlers. 2354 // 2355 // The path and host are used unchanged for CONNECT requests. 2356 // 2357 // Handler also returns the registered pattern that matches the 2358 // request or, in the case of internally-generated redirects, 2359 // the pattern that will match after following the redirect. 2360 // 2361 // If there is no registered handler that applies to the request, 2362 // Handler returns a ``page not found'' handler and an empty pattern. 2363 func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string) { 2364 2365 // CONNECT requests are not canonicalized. 2366 if r.Method == "CONNECT" { 2367 // If r.URL.Path is /tree and its handler is not registered, 2368 // the /tree -> /tree/ redirect applies to CONNECT requests 2369 // but the path canonicalization does not. 2370 if u, ok := mux.redirectToPathSlash(r.URL.Host, r.URL.Path, r.URL); ok { 2371 return RedirectHandler(u.String(), StatusMovedPermanently), u.Path 2372 } 2373 2374 return mux.handler(r.Host, r.URL.Path) 2375 } 2376 2377 // All other requests have any port stripped and path cleaned 2378 // before passing to mux.handler. 2379 host := stripHostPort(r.Host) 2380 pathCleaned := cleanPath(r.URL.Path) 2381 2382 // If the given path is /tree and its handler is not registered, 2383 // redirect for /tree/. 2384 if u, ok := mux.redirectToPathSlash(host, pathCleaned, r.URL); ok { 2385 return RedirectHandler(u.String(), StatusMovedPermanently), u.Path 2386 } 2387 2388 if pathCleaned != r.URL.Path { 2389 _, pattern = mux.handler(host, pathCleaned) 2390 u := &url.URL{Path: pathCleaned, RawQuery: r.URL.RawQuery} 2391 return RedirectHandler(u.String(), StatusMovedPermanently), pattern 2392 } 2393 2394 return mux.handler(host, r.URL.Path) 2395 } 2396 2397 // handler is the main implementation of Handler. 2398 // The path is known to be in canonical form, except for CONNECT methods. 2399 func (mux *ServeMux) handler(host, path string) (h Handler, pattern string) { 2400 mux.mu.RLock() 2401 defer mux.mu.RUnlock() 2402 2403 // Host-specific pattern takes precedence over generic ones 2404 if mux.hosts { 2405 h, pattern = mux.match(host + path) 2406 } 2407 if h == nil { 2408 h, pattern = mux.match(path) 2409 } 2410 if h == nil { 2411 h, pattern = NotFoundHandler(), "" 2412 } 2413 return 2414 } 2415 2416 // ServeHTTP dispatches the request to the handler whose 2417 // pattern most closely matches the request URL. 2418 func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request) { 2419 if r.RequestURI == "*" { 2420 if r.ProtoAtLeast(1, 1) { 2421 w.Header().Set("Connection", "close") 2422 } 2423 w.WriteHeader(StatusBadRequest) 2424 return 2425 } 2426 h, _ := mux.Handler(r) 2427 h.ServeHTTP(w, r) 2428 } 2429 2430 // Handle registers the handler for the given pattern. 2431 // If a handler already exists for pattern, Handle panics. 2432 func (mux *ServeMux) Handle(pattern string, handler Handler) { 2433 mux.mu.Lock() 2434 defer mux.mu.Unlock() 2435 2436 if pattern == "" { 2437 panic("http: invalid pattern") 2438 } 2439 if handler == nil { 2440 panic("http: nil handler") 2441 } 2442 if _, exist := mux.m[pattern]; exist { 2443 panic("http: multiple registrations for " + pattern) 2444 } 2445 2446 if mux.m == nil { 2447 mux.m = make(map[string]muxEntry) 2448 } 2449 e := muxEntry{h: handler, pattern: pattern} 2450 mux.m[pattern] = e 2451 if pattern[len(pattern)-1] == '/' { 2452 mux.es = appendSorted(mux.es, e) 2453 } 2454 2455 if pattern[0] != '/' { 2456 mux.hosts = true 2457 } 2458 } 2459 2460 func appendSorted(es []muxEntry, e muxEntry) []muxEntry { 2461 n := len(es) 2462 i := sort.Search(n, func(i int) bool { 2463 return len(es[i].pattern) < len(e.pattern) 2464 }) 2465 if i == n { 2466 return append(es, e) 2467 } 2468 // we now know that i points at where we want to insert 2469 es = append(es, muxEntry{}) // try to grow the slice in place, any entry works. 2470 copy(es[i+1:], es[i:]) // Move shorter entries down 2471 es[i] = e 2472 return es 2473 } 2474 2475 // HandleFunc registers the handler function for the given pattern. 2476 func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) { 2477 if handler == nil { 2478 panic("http: nil handler") 2479 } 2480 mux.Handle(pattern, HandlerFunc(handler)) 2481 } 2482 2483 // Handle registers the handler for the given pattern 2484 // in the DefaultServeMux. 2485 // The documentation for ServeMux explains how patterns are matched. 2486 func Handle(pattern string, handler Handler) { DefaultServeMux.Handle(pattern, handler) } 2487 2488 // HandleFunc registers the handler function for the given pattern 2489 // in the DefaultServeMux. 2490 // The documentation for ServeMux explains how patterns are matched. 2491 func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) { 2492 DefaultServeMux.HandleFunc(pattern, handler) 2493 } 2494 2495 // Serve accepts incoming HTTP connections on the listener l, 2496 // creating a new service goroutine for each. The service goroutines 2497 // read requests and then call handler to reply to them. 2498 // 2499 // The handler is typically nil, in which case the DefaultServeMux is used. 2500 // 2501 // HTTP/2 support is only enabled if the Listener returns *tls.Conn 2502 // connections and they were configured with "h2" in the TLS 2503 // Config.NextProtos. 2504 // 2505 // Serve always returns a non-nil error. 2506 func Serve(l net.Listener, handler Handler) error { 2507 srv := &Server{Handler: handler} 2508 return srv.Serve(l) 2509 } 2510 2511 // ServeTLS accepts incoming HTTPS connections on the listener l, 2512 // creating a new service goroutine for each. The service goroutines 2513 // read requests and then call handler to reply to them. 2514 // 2515 // The handler is typically nil, in which case the DefaultServeMux is used. 2516 // 2517 // Additionally, files containing a certificate and matching private key 2518 // for the server must be provided. If the certificate is signed by a 2519 // certificate authority, the certFile should be the concatenation 2520 // of the server's certificate, any intermediates, and the CA's certificate. 2521 // 2522 // ServeTLS always returns a non-nil error. 2523 //goland:noinspection GoUnusedExportedFunction 2524 func ServeTLS(l net.Listener, handler Handler, certFile, keyFile string) error { 2525 srv := &Server{Handler: handler} 2526 return srv.ServeTLS(l, certFile, keyFile) 2527 } 2528 2529 // A Server defines parameters for running an HTTP server. 2530 // The zero value for Server is a valid configuration. 2531 type Server struct { 2532 // Addr optionally specifies the TCP address for the server to listen on, 2533 // in the form "host:port". If empty, ":http" (port 80) is used. 2534 // The service names are defined in RFC 6335 and assigned by IANA. 2535 // See net.Dial for details of the address format. 2536 Addr string 2537 2538 Handler Handler // handler to invoke, http.DefaultServeMux if nil 2539 2540 // TLSConfig optionally provides a TLS configuration for use 2541 // by ServeTLS and ListenAndServeTLS. Note that this value is 2542 // cloned by ServeTLS and ListenAndServeTLS, so it's not 2543 // possible to modify the configuration with methods like 2544 // tls.Config.SetSessionTicketKeys. To use 2545 // SetSessionTicketKeys, use Server.Serve with a TLS Listener 2546 // instead. 2547 TLSConfig *tls.Config 2548 2549 // ReadTimeout is the maximum duration for reading the entire 2550 // request, including the body. A zero or negative value means 2551 // there will be no timeout. 2552 // 2553 // Because ReadTimeout does not let Handlers make per-request 2554 // decisions on each request body's acceptable deadline or 2555 // upload rate, most users will prefer to use 2556 // ReadHeaderTimeout. It is valid to use them both. 2557 ReadTimeout time.Duration 2558 2559 // ReadHeaderTimeout is the amount of time allowed to read 2560 // request headers. The connection's read deadline is reset 2561 // after reading the headers and the Handler can decide what 2562 // is considered too slow for the body. If ReadHeaderTimeout 2563 // is zero, the value of ReadTimeout is used. If both are 2564 // zero, there is no timeout. 2565 ReadHeaderTimeout time.Duration 2566 2567 // WriteTimeout is the maximum duration before timing out 2568 // writes of the response. It is reset whenever a new 2569 // request's header is read. Like ReadTimeout, it does not 2570 // let Handlers make decisions on a per-request basis. 2571 // A zero or negative value means there will be no timeout. 2572 WriteTimeout time.Duration 2573 2574 // IdleTimeout is the maximum amount of time to wait for the 2575 // next request when keep-alives are enabled. If IdleTimeout 2576 // is zero, the value of ReadTimeout is used. If both are 2577 // zero, there is no timeout. 2578 IdleTimeout time.Duration 2579 2580 // MaxHeaderBytes controls the maximum number of bytes the 2581 // server will read parsing the request header's keys and 2582 // values, including the request line. It does not limit the 2583 // size of the request body. 2584 // If zero, DefaultMaxHeaderBytes is used. 2585 MaxHeaderBytes int 2586 2587 // TLSNextProto optionally specifies a function to take over 2588 // ownership of the provided TLS connection when an ALPN 2589 // protocol upgrade has occurred. The map key is the protocol 2590 // name negotiated. The Handler argument should be used to 2591 // handle HTTP requests and will initialize the Request's TLS 2592 // and RemoteAddr if not already set. The connection is 2593 // automatically closed when the function returns. 2594 // If TLSNextProto is not nil, HTTP/2 support is not enabled 2595 // automatically. 2596 TLSNextProto map[string]func(*Server, *tls.Conn, Handler) 2597 2598 // ConnState specifies an optional callback function that is 2599 // called when a client connection changes state. See the 2600 // ConnState type and associated constants for details. 2601 ConnState func(net.Conn, ConnState) 2602 2603 // ErrorLog specifies an optional logger for errors accepting 2604 // connections, unexpected behavior from handlers, and 2605 // underlying FileSystem errors. 2606 // If nil, logging is done via the log package's standard logger. 2607 ErrorLog *log.Logger 2608 2609 // BaseContext optionally specifies a function that returns 2610 // the base context for incoming requests on this server. 2611 // The provided Listener is the specific Listener that's 2612 // about to start accepting requests. 2613 // If BaseContext is nil, the default is context.Background(). 2614 // If non-nil, it must return a non-nil context. 2615 BaseContext func(net.Listener) context.Context 2616 2617 // ConnContext optionally specifies a function that modifies 2618 // the context used for a new connection c. The provided ctx 2619 // is derived from the base context and has a ServerContextKey 2620 // value. 2621 ConnContext func(ctx context.Context, c net.Conn) context.Context 2622 2623 inShutdown atomicBool // true when server is in shutdown 2624 2625 disableKeepAlives int32 // accessed atomically. 2626 nextProtoOnce sync.Once // guards setupHTTP2_* init 2627 nextProtoErr error // result of http2.ConfigureServer if used 2628 2629 mu sync.Mutex 2630 listeners map[*net.Listener]struct{} 2631 activeConn map[*conn]struct{} 2632 doneChan chan struct{} 2633 onShutdown []func() 2634 } 2635 2636 func (srv *Server) getDoneChan() <-chan struct{} { 2637 srv.mu.Lock() 2638 defer srv.mu.Unlock() 2639 return srv.getDoneChanLocked() 2640 } 2641 2642 func (srv *Server) getDoneChanLocked() chan struct{} { 2643 if srv.doneChan == nil { 2644 srv.doneChan = make(chan struct{}) 2645 } 2646 return srv.doneChan 2647 } 2648 2649 func (srv *Server) closeDoneChanLocked() { 2650 ch := srv.getDoneChanLocked() 2651 select { 2652 case <-ch: 2653 // Already closed. Don't close again. 2654 default: 2655 // Safe to close here. We're the only closer, guarded 2656 // by srv.mu. 2657 close(ch) 2658 } 2659 } 2660 2661 // Close immediately closes all active net.Listeners and any 2662 // connections in state StateNew, StateActive, or StateIdle. For a 2663 // graceful shutdown, use Shutdown. 2664 // 2665 // Close does not attempt to close (and does not even know about) 2666 // any hijacked connections, such as WebSockets. 2667 // 2668 // Close returns any error returned from closing the Server's 2669 // underlying Listener(s). 2670 func (srv *Server) Close() error { 2671 srv.inShutdown.setTrue() 2672 srv.mu.Lock() 2673 defer srv.mu.Unlock() 2674 srv.closeDoneChanLocked() 2675 err := srv.closeListenersLocked() 2676 for c := range srv.activeConn { 2677 _ = c.rwc.Close() 2678 delete(srv.activeConn, c) 2679 } 2680 return err 2681 } 2682 2683 // shutdownPollIntervalMax is the max polling interval when checking 2684 // quiescence during Server.Shutdown. Polling starts with a small 2685 // interval and backs off to the max. 2686 // Ideally we could find a solution that doesn't involve polling, 2687 // but which also doesn't have a high runtime cost (and doesn't 2688 // involve any contentious mutexes), but that is left as an 2689 // exercise for the reader. 2690 const shutdownPollIntervalMax = 500 * time.Millisecond 2691 2692 // Shutdown gracefully shuts down the server without interrupting any 2693 // active connections. Shutdown works by first closing all open 2694 // listeners, then closing all idle connections, and then waiting 2695 // indefinitely for connections to return to idle and then shut down. 2696 // If the provided context expires before the shutdown is complete, 2697 // Shutdown returns the context's error, otherwise it returns any 2698 // error returned from closing the Server's underlying Listener(s). 2699 // 2700 // When Shutdown is called, Serve, ListenAndServe, and 2701 // ListenAndServeTLS immediately return ErrServerClosed. Make sure the 2702 // program doesn't exit and waits instead for Shutdown to return. 2703 // 2704 // Shutdown does not attempt to close nor wait for hijacked 2705 // connections such as WebSockets. The caller of Shutdown should 2706 // separately notify such long-lived connections of shutdown and wait 2707 // for them to close, if desired. See RegisterOnShutdown for a way to 2708 // register shutdown notification functions. 2709 // 2710 // Once Shutdown has been called on a server, it may not be reused; 2711 // future calls to methods such as Serve will return ErrServerClosed. 2712 func (srv *Server) Shutdown(ctx context.Context) error { 2713 srv.inShutdown.setTrue() 2714 2715 srv.mu.Lock() 2716 lnerr := srv.closeListenersLocked() 2717 srv.closeDoneChanLocked() 2718 for _, f := range srv.onShutdown { 2719 go f() 2720 } 2721 srv.mu.Unlock() 2722 2723 pollIntervalBase := time.Millisecond 2724 nextPollInterval := func() time.Duration { 2725 // Add 10% jitter. 2726 interval := pollIntervalBase + time.Duration(rand.Intn(int(pollIntervalBase/10))) 2727 // Double and clamp for next time. 2728 pollIntervalBase *= 2 2729 if pollIntervalBase > shutdownPollIntervalMax { 2730 pollIntervalBase = shutdownPollIntervalMax 2731 } 2732 return interval 2733 } 2734 2735 timer := time.NewTimer(nextPollInterval()) 2736 defer timer.Stop() 2737 for { 2738 if srv.closeIdleConns() && srv.numListeners() == 0 { 2739 return lnerr 2740 } 2741 select { 2742 case <-ctx.Done(): 2743 return ctx.Err() 2744 case <-timer.C: 2745 timer.Reset(nextPollInterval()) 2746 } 2747 } 2748 } 2749 2750 // RegisterOnShutdown registers a function to call on Shutdown. 2751 // This can be used to gracefully shutdown connections that have 2752 // undergone ALPN protocol upgrade or that have been hijacked. 2753 // This function should start protocol-specific graceful shutdown, 2754 // but should not wait for shutdown to complete. 2755 func (srv *Server) RegisterOnShutdown(f func()) { 2756 srv.mu.Lock() 2757 srv.onShutdown = append(srv.onShutdown, f) 2758 srv.mu.Unlock() 2759 } 2760 2761 func (srv *Server) numListeners() int { 2762 srv.mu.Lock() 2763 defer srv.mu.Unlock() 2764 return len(srv.listeners) 2765 } 2766 2767 // closeIdleConns closes all idle connections and reports whether the 2768 // server is quiescent. 2769 func (srv *Server) closeIdleConns() bool { 2770 srv.mu.Lock() 2771 defer srv.mu.Unlock() 2772 quiescent := true 2773 for c := range srv.activeConn { 2774 st, unixSec := c.getState() 2775 // Issue 22682: treat StateNew connections as if 2776 // they're idle if we haven't read the first request'srv 2777 // header in over 5 seconds. 2778 if st == StateNew && unixSec < time.Now().Unix()-5 { 2779 st = StateIdle 2780 } 2781 if st != StateIdle || unixSec == 0 { 2782 // Assume unixSec == 0 means it'srv a very new 2783 // connection, without state set yet. 2784 quiescent = false 2785 continue 2786 } 2787 _ = c.rwc.Close() 2788 delete(srv.activeConn, c) 2789 } 2790 return quiescent 2791 } 2792 2793 func (srv *Server) closeListenersLocked() error { 2794 var err error 2795 for ln := range srv.listeners { 2796 if cerr := (*ln).Close(); cerr != nil && err == nil { 2797 err = cerr 2798 } 2799 } 2800 return err 2801 } 2802 2803 // A ConnState represents the state of a client connection to a server. 2804 // It's used by the optional Server.ConnState hook. 2805 type ConnState int 2806 2807 const ( 2808 // StateNew represents a new connection that is expected to 2809 // send a request immediately. Connections begin at this 2810 // state and then transition to either StateActive or 2811 // StateClosed. 2812 StateNew ConnState = iota 2813 2814 // StateActive represents a connection that has read 1 or more 2815 // bytes of a request. The Server.ConnState hook for 2816 // StateActive fires before the request has entered a handler 2817 // and doesn't fire again until the request has been 2818 // handled. After the request is handled, the state 2819 // transitions to StateClosed, StateHijacked, or StateIdle. 2820 // For HTTP/2, StateActive fires on the transition from zero 2821 // to one active request, and only transitions away once all 2822 // active requests are complete. That means that ConnState 2823 // cannot be used to do per-request work; ConnState only notes 2824 // the overall state of the connection. 2825 StateActive 2826 2827 // StateIdle represents a connection that has finished 2828 // handling a request and is in the keep-alive state, waiting 2829 // for a new request. Connections transition from StateIdle 2830 // to either StateActive or StateClosed. 2831 StateIdle 2832 2833 // StateHijacked represents a hijacked connection. 2834 // This is a terminal state. It does not transition to StateClosed. 2835 StateHijacked 2836 2837 // StateClosed represents a closed connection. 2838 // This is a terminal state. Hijacked connections do not 2839 // transition to StateClosed. 2840 StateClosed 2841 ) 2842 2843 var stateName = map[ConnState]string{ 2844 StateNew: "new", 2845 StateActive: "active", 2846 StateIdle: "idle", 2847 StateHijacked: "hijacked", 2848 StateClosed: "closed", 2849 } 2850 2851 func (c ConnState) String() string { 2852 return stateName[c] 2853 } 2854 2855 // serverHandler delegates to either the server's Handler or 2856 // DefaultServeMux and also handles "OPTIONS *" requests. 2857 type serverHandler struct { 2858 srv *Server 2859 } 2860 2861 func (sh serverHandler) ServeHTTP(rw ResponseWriter, req *Request) { 2862 handler := sh.srv.Handler 2863 if handler == nil { 2864 handler = DefaultServeMux 2865 } 2866 if req.RequestURI == "*" && req.Method == "OPTIONS" { 2867 handler = globalOptionsHandler{} 2868 } 2869 2870 if req.URL != nil && strings.Contains(req.URL.RawQuery, ";") { 2871 var allowQuerySemicolonsInUse int32 2872 req = req.WithContext(context.WithValue(req.Context(), silenceSemWarnContextKey, func() { 2873 atomic.StoreInt32(&allowQuerySemicolonsInUse, 1) 2874 })) 2875 defer func() { 2876 if atomic.LoadInt32(&allowQuerySemicolonsInUse) == 0 { 2877 sh.srv.logf("http: URL query contains semicolon, which is no longer a supported separator; parts of the query may be stripped when parsed; see golang.org/issue/25192") 2878 } 2879 }() 2880 } 2881 2882 handler.ServeHTTP(rw, req) 2883 } 2884 2885 var silenceSemWarnContextKey = &contextKey{"silence-semicolons"} 2886 2887 // AllowQuerySemicolons returns a handler that serves requests by converting any 2888 // unescaped semicolons in the URL query to ampersands, and invoking the handler h. 2889 // 2890 // This restores the pre-Go 1.17 behavior of splitting query parameters on both 2891 // semicolons and ampersands. (See golang.org/issue/25192). Note that this 2892 // behavior doesn't match that of many proxies, and the mismatch can lead to 2893 // security issues. 2894 // 2895 // AllowQuerySemicolons should be invoked before Request.ParseForm is called. 2896 func AllowQuerySemicolons(h Handler) Handler { 2897 return HandlerFunc(func(w ResponseWriter, r *Request) { 2898 if silenceSemicolonsWarning, ok := r.Context().Value(silenceSemWarnContextKey).(func()); ok { 2899 silenceSemicolonsWarning() 2900 } 2901 if strings.Contains(r.URL.RawQuery, ";") { 2902 r2 := new(Request) 2903 *r2 = *r 2904 r2.URL = new(url.URL) 2905 *r2.URL = *r.URL 2906 r2.URL.RawQuery = strings.ReplaceAll(r.URL.RawQuery, ";", "&") 2907 h.ServeHTTP(w, r2) 2908 } else { 2909 h.ServeHTTP(w, r) 2910 } 2911 }) 2912 } 2913 2914 // ListenAndServe listens on the TCP network address srv.Addr and then 2915 // calls Serve to handle requests on incoming connections. 2916 // Accepted connections are configured to enable TCP keep-alives. 2917 // 2918 // If srv.Addr is blank, ":http" is used. 2919 // 2920 // ListenAndServe always returns a non-nil error. After Shutdown or Close, 2921 // the returned error is ErrServerClosed. 2922 func (srv *Server) ListenAndServe() error { 2923 if srv.shuttingDown() { 2924 return ErrServerClosed 2925 } 2926 addr := srv.Addr 2927 if addr == "" { 2928 addr = ":http" 2929 } 2930 ln, err := net.Listen("tcp", addr) 2931 if err != nil { 2932 return err 2933 } 2934 return srv.Serve(ln) 2935 } 2936 2937 var testHookServerServe func(*Server, net.Listener) // used if non-nil 2938 2939 // shouldDoServeHTTP2 reports whether Server.Serve should configure 2940 // automatic HTTP/2. (which sets up the srv.TLSNextProto map) 2941 func (srv *Server) shouldConfigureHTTP2ForServe() bool { 2942 if srv.TLSConfig == nil { 2943 // Compatibility with Go 1.6: 2944 // If there's no TLSConfig, it's possible that the user just 2945 // didn't set it on the http.Server, but did pass it to 2946 // tls.NewListener and passed that listener to Serve. 2947 // So we should configure HTTP/2 (to set up srv.TLSNextProto) 2948 // in case the listener returns an "h2" *tls.Conn. 2949 return true 2950 } 2951 // The user specified a TLSConfig on their http.Server. 2952 // In this, case, only configure HTTP/2 if their tls.Config 2953 // explicitly mentions "h2". Otherwise http2.ConfigureServer 2954 // would modify the tls.Config to add it, but they probably already 2955 // passed this tls.Config to tls.NewListener. And if they did, 2956 // it's too late anyway to fix it. It would only be potentially racy. 2957 // See Issue 15908. 2958 return strSliceContains(srv.TLSConfig.NextProtos, http2NextProtoTLS) 2959 } 2960 2961 // ErrServerClosed is returned by the Server's Serve, ServeTLS, ListenAndServe, 2962 // and ListenAndServeTLS methods after a call to Shutdown or Close. 2963 var ErrServerClosed = errors.New("http: Server closed") 2964 2965 // Serve accepts incoming connections on the Listener l, creating a 2966 // new service goroutine for each. The service goroutines read requests and 2967 // then call srv.Handler to reply to them. 2968 // 2969 // HTTP/2 support is only enabled if the Listener returns *tls.Conn 2970 // connections and they were configured with "h2" in the TLS 2971 // Config.NextProtos. 2972 // 2973 // Serve always returns a non-nil error and closes l. 2974 // After Shutdown or Close, the returned error is ErrServerClosed. 2975 func (srv *Server) Serve(l net.Listener) error { 2976 if fn := testHookServerServe; fn != nil { 2977 fn(srv, l) // call hook with unwrapped listener 2978 } 2979 2980 origListener := l 2981 l = &onceCloseListener{Listener: l} 2982 defer func(l net.Listener) { 2983 _ = l.Close() 2984 }(l) 2985 2986 if err := srv.setupHTTP2_Serve(); err != nil { 2987 return err 2988 } 2989 2990 if !srv.trackListener(&l, true) { 2991 return ErrServerClosed 2992 } 2993 defer srv.trackListener(&l, false) 2994 2995 baseCtx := context.Background() 2996 if srv.BaseContext != nil { 2997 baseCtx = srv.BaseContext(origListener) 2998 if baseCtx == nil { 2999 panic("BaseContext returned a nil context") 3000 } 3001 } 3002 3003 var tempDelay time.Duration // how long to sleep on accept failure 3004 3005 ctx := context.WithValue(baseCtx, ServerContextKey, srv) 3006 for { 3007 rw, err := l.Accept() 3008 if err != nil { 3009 select { 3010 case <-srv.getDoneChan(): 3011 return ErrServerClosed 3012 default: 3013 } 3014 if ne, ok := err.(net.Error); ok && ne.Temporary() { 3015 if tempDelay == 0 { 3016 tempDelay = 5 * time.Millisecond 3017 } else { 3018 tempDelay *= 2 3019 } 3020 if max := 1 * time.Second; tempDelay > max { 3021 tempDelay = max 3022 } 3023 srv.logf("http: Accept error: %v; retrying in %v", err, tempDelay) 3024 time.Sleep(tempDelay) 3025 continue 3026 } 3027 return err 3028 } 3029 connCtx := ctx 3030 if cc := srv.ConnContext; cc != nil { 3031 connCtx = cc(connCtx, rw) 3032 if connCtx == nil { 3033 panic("ConnContext returned nil") 3034 } 3035 } 3036 tempDelay = 0 3037 c := srv.newConn(rw) 3038 c.setState(c.rwc, StateNew, runHooks) // before Serve can return 3039 go c.serve(connCtx) 3040 } 3041 } 3042 3043 // ServeTLS accepts incoming connections on the Listener l, creating a 3044 // new service goroutine for each. The service goroutines perform TLS 3045 // setup and then read requests, calling srv.Handler to reply to them. 3046 // 3047 // Files containing a certificate and matching private key for the 3048 // server must be provided if neither the Server's 3049 // TLSConfig.Certificates nor TLSConfig.GetCertificate are populated. 3050 // If the certificate is signed by a certificate authority, the 3051 // certFile should be the concatenation of the server's certificate, 3052 // any intermediates, and the CA's certificate. 3053 // 3054 // ServeTLS always returns a non-nil error. After Shutdown or Close, the 3055 // returned error is ErrServerClosed. 3056 func (srv *Server) ServeTLS(l net.Listener, certFile, keyFile string) error { 3057 // Setup HTTP/2 before srv.Serve, to initialize srv.TLSConfig 3058 // before we clone it and create the TLS Listener. 3059 if err := srv.setupHTTP2_ServeTLS(); err != nil { 3060 return err 3061 } 3062 3063 config := cloneTLSConfig(srv.TLSConfig) 3064 if !strSliceContains(config.NextProtos, "http/1.1") { 3065 config.NextProtos = append(config.NextProtos, "http/1.1") 3066 } 3067 3068 configHasCert := len(config.Certificates) > 0 || config.GetCertificate != nil 3069 if !configHasCert || certFile != "" || keyFile != "" { 3070 var err error 3071 config.Certificates = make([]tls.Certificate, 1) 3072 config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile) 3073 if err != nil { 3074 return err 3075 } 3076 } 3077 3078 tlsListener := tls.NewListener(l, config) 3079 return srv.Serve(tlsListener) 3080 } 3081 3082 // trackListener adds or removes a net.Listener to the set of tracked 3083 // listeners. 3084 // 3085 // We store a pointer to interface in the map set, in case the 3086 // net.Listener is not comparable. This is safe because we only call 3087 // trackListener via Serve and can track+defer untrack the same 3088 // pointer to local variable there. We never need to compare a 3089 // Listener from another caller. 3090 // 3091 // It reports whether the server is still up (not Shutdown or Closed). 3092 func (srv *Server) trackListener(ln *net.Listener, add bool) bool { 3093 srv.mu.Lock() 3094 defer srv.mu.Unlock() 3095 if srv.listeners == nil { 3096 srv.listeners = make(map[*net.Listener]struct{}) 3097 } 3098 if add { 3099 if srv.shuttingDown() { 3100 return false 3101 } 3102 srv.listeners[ln] = struct{}{} 3103 } else { 3104 delete(srv.listeners, ln) 3105 } 3106 return true 3107 } 3108 3109 func (srv *Server) trackConn(c *conn, add bool) { 3110 srv.mu.Lock() 3111 defer srv.mu.Unlock() 3112 if srv.activeConn == nil { 3113 srv.activeConn = make(map[*conn]struct{}) 3114 } 3115 if add { 3116 srv.activeConn[c] = struct{}{} 3117 } else { 3118 delete(srv.activeConn, c) 3119 } 3120 } 3121 3122 func (srv *Server) idleTimeout() time.Duration { 3123 if srv.IdleTimeout != 0 { 3124 return srv.IdleTimeout 3125 } 3126 return srv.ReadTimeout 3127 } 3128 3129 func (srv *Server) readHeaderTimeout() time.Duration { 3130 if srv.ReadHeaderTimeout != 0 { 3131 return srv.ReadHeaderTimeout 3132 } 3133 return srv.ReadTimeout 3134 } 3135 3136 func (srv *Server) doKeepAlives() bool { 3137 return atomic.LoadInt32(&srv.disableKeepAlives) == 0 && !srv.shuttingDown() 3138 } 3139 3140 func (srv *Server) shuttingDown() bool { 3141 return srv.inShutdown.isSet() 3142 } 3143 3144 // SetKeepAlivesEnabled controls whether HTTP keep-alives are enabled. 3145 // By default, keep-alives are always enabled. Only very 3146 // resource-constrained environments or servers in the process of 3147 // shutting down should disable them. 3148 func (srv *Server) SetKeepAlivesEnabled(v bool) { 3149 if v { 3150 atomic.StoreInt32(&srv.disableKeepAlives, 0) 3151 return 3152 } 3153 atomic.StoreInt32(&srv.disableKeepAlives, 1) 3154 3155 // Close idle HTTP/1 conns: 3156 srv.closeIdleConns() 3157 3158 // TODO: Issue 26303: close HTTP/2 conns as soon as they become idle. 3159 } 3160 3161 func (srv *Server) logf(format string, args ...interface{}) { 3162 if srv.ErrorLog != nil { 3163 srv.ErrorLog.Printf(format, args...) 3164 } else { 3165 log.Printf(format, args...) 3166 } 3167 } 3168 3169 // logf prints to the ErrorLog of the *Server associated with request r 3170 // via ServerContextKey. If there's no associated server, or if ErrorLog 3171 // is nil, logging is done via the log package's standard logger. 3172 func logf(r *Request, format string, args ...interface{}) { 3173 s, _ := r.Context().Value(ServerContextKey).(*Server) 3174 if s != nil && s.ErrorLog != nil { 3175 s.ErrorLog.Printf(format, args...) 3176 } else { 3177 log.Printf(format, args...) 3178 } 3179 } 3180 3181 // ListenAndServe listens on the TCP network address addr and then calls 3182 // Serve with handler to handle requests on incoming connections. 3183 // Accepted connections are configured to enable TCP keep-alives. 3184 // 3185 // The handler is typically nil, in which case the DefaultServeMux is used. 3186 // 3187 // ListenAndServe always returns a non-nil error. 3188 func ListenAndServe(addr string, handler Handler) error { 3189 server := &Server{Addr: addr, Handler: handler} 3190 return server.ListenAndServe() 3191 } 3192 3193 // ListenAndServeTLS acts identically to ListenAndServe, except that it 3194 // expects HTTPS connections. Additionally, files containing a certificate and 3195 // matching private key for the server must be provided. If the certificate 3196 // is signed by a certificate authority, the certFile should be the concatenation 3197 // of the server's certificate, any intermediates, and the CA's certificate. 3198 func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error { 3199 server := &Server{Addr: addr, Handler: handler} 3200 return server.ListenAndServeTLS(certFile, keyFile) 3201 } 3202 3203 // ListenAndServeTLS listens on the TCP network address srv.Addr and 3204 // then calls ServeTLS to handle requests on incoming TLS connections. 3205 // Accepted connections are configured to enable TCP keep-alives. 3206 // 3207 // Filenames containing a certificate and matching private key for the 3208 // server must be provided if neither the Server's TLSConfig.Certificates 3209 // nor TLSConfig.GetCertificate are populated. If the certificate is 3210 // signed by a certificate authority, the certFile should be the 3211 // concatenation of the server's certificate, any intermediates, and 3212 // the CA's certificate. 3213 // 3214 // If srv.Addr is blank, ":https" is used. 3215 // 3216 // ListenAndServeTLS always returns a non-nil error. After Shutdown or 3217 // Close, the returned error is ErrServerClosed. 3218 func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error { 3219 if srv.shuttingDown() { 3220 return ErrServerClosed 3221 } 3222 addr := srv.Addr 3223 if addr == "" { 3224 addr = ":https" 3225 } 3226 3227 ln, err := net.Listen("tcp", addr) 3228 if err != nil { 3229 return err 3230 } 3231 3232 defer func(ln net.Listener) { 3233 _ = ln.Close() 3234 }(ln) 3235 3236 return srv.ServeTLS(ln, certFile, keyFile) 3237 } 3238 3239 // setupHTTP2_ServeTLS conditionally configures HTTP/2 on 3240 // srv and reports whether there was an error setting it up. If it is 3241 // not configured for policy reasons, nil is returned. 3242 //goland:noinspection GoSnakeCaseUsage 3243 func (srv *Server) setupHTTP2_ServeTLS() error { 3244 srv.nextProtoOnce.Do(srv.onceSetNextProtoDefaults) 3245 return srv.nextProtoErr 3246 } 3247 3248 // setupHTTP2_Serve is called from (*Server).Serve and conditionally 3249 // configures HTTP/2 on srv using a more conservative policy than 3250 // setupHTTP2_ServeTLS because Serve is called after tls.Listen, 3251 // and may be called concurrently. See shouldConfigureHTTP2ForServe. 3252 // 3253 // The tests named TestTransportAutomaticHTTP2* and 3254 // TestConcurrentServerServe in server_test.go demonstrate some 3255 // of the supported use cases and motivations. 3256 //goland:noinspection GoSnakeCaseUsage 3257 func (srv *Server) setupHTTP2_Serve() error { 3258 srv.nextProtoOnce.Do(srv.onceSetNextProtoDefaults_Serve) 3259 return srv.nextProtoErr 3260 } 3261 3262 //goland:noinspection GoSnakeCaseUsage 3263 func (srv *Server) onceSetNextProtoDefaults_Serve() { 3264 if srv.shouldConfigureHTTP2ForServe() { 3265 srv.onceSetNextProtoDefaults() 3266 } 3267 } 3268 3269 // onceSetNextProtoDefaults configures HTTP/2, if the user hasn't 3270 // configured otherwise. (by setting srv.TLSNextProto non-nil) 3271 // It must only be called via srv.nextProtoOnce (use srv.setupHTTP2_*). 3272 func (srv *Server) onceSetNextProtoDefaults() { 3273 if omitBundledHTTP2 || strings.Contains(os.Getenv("GODEBUG"), "http2server=0") { 3274 return 3275 } 3276 // Enable HTTP/2 by default if the user hasn't otherwise 3277 // configured their TLSNextProto map. 3278 if srv.TLSNextProto == nil { 3279 conf := &http2Server{ 3280 NewWriteScheduler: func() http2WriteScheduler { return http2NewPriorityWriteScheduler(nil) }, 3281 } 3282 srv.nextProtoErr = http2ConfigureServer(srv, conf) 3283 } 3284 } 3285 3286 // TimeoutHandler returns a Handler that runs h with the given time limit. 3287 // 3288 // The new Handler calls h.ServeHTTP to handle each request, but if a 3289 // call runs for longer than its time limit, the handler responds with 3290 // a 503 Service Unavailable error and the given message in its body. 3291 // (If msg is empty, a suitable default message will be sent.) 3292 // After such a timeout, writes by h to its ResponseWriter will return 3293 // ErrHandlerTimeout. 3294 // 3295 // TimeoutHandler supports the Pusher interface but does not support 3296 // the Hijacker or Flusher interfaces. 3297 func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler { 3298 return &timeoutHandler{ 3299 handler: h, 3300 body: msg, 3301 dt: dt, 3302 } 3303 } 3304 3305 // ErrHandlerTimeout is returned on ResponseWriter Write calls 3306 // in handlers which have timed out. 3307 var ErrHandlerTimeout = errors.New("http: Handler timeout") 3308 3309 type timeoutHandler struct { 3310 handler Handler 3311 body string 3312 dt time.Duration 3313 3314 // When set, no context will be created and this context will 3315 // be used instead. 3316 testContext context.Context 3317 } 3318 3319 func (h *timeoutHandler) errorBody() string { 3320 if h.body != "" { 3321 return h.body 3322 } 3323 return "<html><head><title>Timeout</title></head><body><h1>Timeout</h1></body></html>" 3324 } 3325 3326 func (h *timeoutHandler) ServeHTTP(w ResponseWriter, r *Request) { 3327 ctx := h.testContext 3328 if ctx == nil { 3329 var cancelCtx context.CancelFunc 3330 ctx, cancelCtx = context.WithTimeout(r.Context(), h.dt) 3331 defer cancelCtx() 3332 } 3333 r = r.WithContext(ctx) 3334 done := make(chan struct{}) 3335 tw := &timeoutWriter{ 3336 w: w, 3337 h: make(Header), 3338 req: r, 3339 } 3340 panicChan := make(chan interface{}, 1) 3341 go func() { 3342 defer func() { 3343 if p := recover(); p != nil { 3344 panicChan <- p 3345 } 3346 }() 3347 h.handler.ServeHTTP(tw, r) 3348 close(done) 3349 }() 3350 select { 3351 case p := <-panicChan: 3352 panic(p) 3353 case <-done: 3354 tw.mu.Lock() 3355 defer tw.mu.Unlock() 3356 dst := w.Header() 3357 for k, vv := range tw.h { 3358 dst[k] = vv 3359 } 3360 if !tw.wroteHeader { 3361 tw.code = StatusOK 3362 } 3363 w.WriteHeader(tw.code) 3364 _, _ = w.Write(tw.wbuf.Bytes()) 3365 case <-ctx.Done(): 3366 tw.mu.Lock() 3367 defer tw.mu.Unlock() 3368 w.WriteHeader(StatusServiceUnavailable) 3369 _, _ = io.WriteString(w, h.errorBody()) 3370 tw.timedOut = true 3371 } 3372 } 3373 3374 type timeoutWriter struct { 3375 w ResponseWriter 3376 h Header 3377 wbuf bytes.Buffer 3378 req *Request 3379 3380 mu sync.Mutex 3381 timedOut bool 3382 wroteHeader bool 3383 code int 3384 } 3385 3386 var _ Pusher = (*timeoutWriter)(nil) 3387 3388 // Push implements the Pusher interface. 3389 func (tw *timeoutWriter) Push(target string, opts *PushOptions) error { 3390 if pusher, ok := tw.w.(Pusher); ok { 3391 return pusher.Push(target, opts) 3392 } 3393 return ErrNotSupported 3394 } 3395 3396 func (tw *timeoutWriter) Header() Header { return tw.h } 3397 3398 func (tw *timeoutWriter) Write(p []byte) (int, error) { 3399 tw.mu.Lock() 3400 defer tw.mu.Unlock() 3401 if tw.timedOut { 3402 return 0, ErrHandlerTimeout 3403 } 3404 if !tw.wroteHeader { 3405 tw.writeHeaderLocked(StatusOK) 3406 } 3407 return tw.wbuf.Write(p) 3408 } 3409 3410 func (tw *timeoutWriter) writeHeaderLocked(code int) { 3411 checkWriteHeaderCode(code) 3412 3413 switch { 3414 case tw.timedOut: 3415 return 3416 case tw.wroteHeader: 3417 if tw.req != nil { 3418 caller := relevantCaller() 3419 logf(tw.req, "http: superfluous response.WriteHeader call from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line) 3420 } 3421 default: 3422 tw.wroteHeader = true 3423 tw.code = code 3424 } 3425 } 3426 3427 func (tw *timeoutWriter) WriteHeader(code int) { 3428 tw.mu.Lock() 3429 defer tw.mu.Unlock() 3430 tw.writeHeaderLocked(code) 3431 } 3432 3433 // onceCloseListener wraps a net.Listener, protecting it from 3434 // multiple Close calls. 3435 type onceCloseListener struct { 3436 net.Listener 3437 once sync.Once 3438 closeErr error 3439 } 3440 3441 func (oc *onceCloseListener) Close() error { 3442 oc.once.Do(oc.close) 3443 return oc.closeErr 3444 } 3445 3446 func (oc *onceCloseListener) close() { oc.closeErr = oc.Listener.Close() } 3447 3448 // globalOptionsHandler responds to "OPTIONS *" requests. 3449 type globalOptionsHandler struct{} 3450 3451 func (globalOptionsHandler) ServeHTTP(w ResponseWriter, r *Request) { 3452 w.Header().Set("Content-Length", "0") 3453 if r.ContentLength != 0 { 3454 // Read up to 4KB of OPTIONS body (as mentioned in the 3455 // spec as being reserved for future use), but anything 3456 // over that is considered a waste of server resources 3457 // (or an attack) and we abort and close the connection, 3458 // courtesy of MaxBytesReader's EOF behavior. 3459 mb := MaxBytesReader(w, r.Body, 4<<10) 3460 _, _ = io.Copy(io.Discard, mb) 3461 } 3462 } 3463 3464 // initALPNRequest is an HTTP handler that initializes certain 3465 // uninitialized fields in its *Request. Such partially-initialized 3466 // Requests come from ALPN protocol handlers. 3467 type initALPNRequest struct { 3468 ctx context.Context 3469 c *tls.Conn 3470 h serverHandler 3471 } 3472 3473 // BaseContext is an exported but unadvertised http.Handler method 3474 // recognized by x/net/http2 to pass down a context; the TLSNextProto 3475 // API predates context support so we shoehorn through the only 3476 // interface we have available. 3477 func (h initALPNRequest) BaseContext() context.Context { return h.ctx } 3478 3479 func (h initALPNRequest) ServeHTTP(rw ResponseWriter, req *Request) { 3480 if req.TLS == nil { 3481 req.TLS = &tls.ConnectionState{} 3482 *req.TLS = h.c.ConnectionState() 3483 } 3484 if req.Body == nil { 3485 req.Body = NoBody 3486 } 3487 if req.RemoteAddr == "" { 3488 req.RemoteAddr = h.c.RemoteAddr().String() 3489 } 3490 h.h.ServeHTTP(rw, req) 3491 } 3492 3493 // loggingConn is used for debugging. 3494 type loggingConn struct { 3495 name string 3496 net.Conn 3497 } 3498 3499 var ( 3500 uniqNameMu sync.Mutex 3501 uniqNameNext = make(map[string]int) 3502 ) 3503 3504 func newLoggingConn(baseName string, c net.Conn) net.Conn { 3505 uniqNameMu.Lock() 3506 defer uniqNameMu.Unlock() 3507 uniqNameNext[baseName]++ 3508 return &loggingConn{ 3509 name: fmt.Sprintf("%s-%d", baseName, uniqNameNext[baseName]), 3510 Conn: c, 3511 } 3512 } 3513 3514 func (c *loggingConn) Write(p []byte) (n int, err error) { 3515 log.Printf("%s.Write(%d) = ....", c.name, len(p)) 3516 n, err = c.Conn.Write(p) 3517 log.Printf("%s.Write(%d) = %d, %v", c.name, len(p), n, err) 3518 return 3519 } 3520 3521 func (c *loggingConn) Read(p []byte) (n int, err error) { 3522 log.Printf("%s.Read(%d) = ....", c.name, len(p)) 3523 n, err = c.Conn.Read(p) 3524 log.Printf("%s.Read(%d) = %d, %v", c.name, len(p), n, err) 3525 return 3526 } 3527 3528 func (c *loggingConn) Close() (err error) { 3529 log.Printf("%s.Close() = ...", c.name) 3530 err = c.Conn.Close() 3531 log.Printf("%s.Close() = %v", c.name, err) 3532 return 3533 } 3534 3535 // checkConnErrorWriter writes to c.rwc and records any write errors to c.werr. 3536 // It only contains one field (and a pointer field at that), so it 3537 // fits in an interface value without an extra allocation. 3538 type checkConnErrorWriter struct { 3539 c *conn 3540 } 3541 3542 func (w checkConnErrorWriter) Write(p []byte) (n int, err error) { 3543 n, err = w.c.rwc.Write(p) 3544 if err != nil && w.c.werr == nil { 3545 w.c.werr = err 3546 w.c.cancelCtx() 3547 } 3548 return 3549 } 3550 3551 func numLeadingCRorLF(v []byte) (n int) { 3552 for _, b := range v { 3553 if b == '\r' || b == '\n' { 3554 n++ 3555 continue 3556 } 3557 break 3558 } 3559 return 3560 3561 } 3562 3563 func strSliceContains(ss []string, s string) bool { 3564 for _, v := range ss { 3565 if v == s { 3566 return true 3567 } 3568 } 3569 return false 3570 } 3571 3572 // tlsRecordHeaderLooksLikeHTTP reports whether a TLS record header 3573 // looks like it might've been a misdirected plaintext HTTP request. 3574 func tlsRecordHeaderLooksLikeHTTP(hdr [5]byte) bool { 3575 switch string(hdr[:]) { 3576 case "GET /", "HEAD ", "POST ", "PUT /", "OPTIO": 3577 return true 3578 } 3579 return false 3580 }