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