github.com/twelsh-aw/go/src@v0.0.0-20230516233729-a56fe86a7c81/net/http/serve_test.go (about) 1 // Copyright 2010 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 // End-to-end serving tests 6 7 package http_test 8 9 import ( 10 "bufio" 11 "bytes" 12 "compress/gzip" 13 "compress/zlib" 14 "context" 15 "crypto/tls" 16 "encoding/json" 17 "errors" 18 "fmt" 19 "internal/testenv" 20 "io" 21 "log" 22 "math/rand" 23 "mime/multipart" 24 "net" 25 . "net/http" 26 "net/http/httptest" 27 "net/http/httptrace" 28 "net/http/httputil" 29 "net/http/internal" 30 "net/http/internal/testcert" 31 "net/url" 32 "os" 33 "os/exec" 34 "path/filepath" 35 "reflect" 36 "regexp" 37 "runtime" 38 "strconv" 39 "strings" 40 "sync" 41 "sync/atomic" 42 "syscall" 43 "testing" 44 "time" 45 ) 46 47 type dummyAddr string 48 type oneConnListener struct { 49 conn net.Conn 50 } 51 52 func (l *oneConnListener) Accept() (c net.Conn, err error) { 53 c = l.conn 54 if c == nil { 55 err = io.EOF 56 return 57 } 58 err = nil 59 l.conn = nil 60 return 61 } 62 63 func (l *oneConnListener) Close() error { 64 return nil 65 } 66 67 func (l *oneConnListener) Addr() net.Addr { 68 return dummyAddr("test-address") 69 } 70 71 func (a dummyAddr) Network() string { 72 return string(a) 73 } 74 75 func (a dummyAddr) String() string { 76 return string(a) 77 } 78 79 type noopConn struct{} 80 81 func (noopConn) LocalAddr() net.Addr { return dummyAddr("local-addr") } 82 func (noopConn) RemoteAddr() net.Addr { return dummyAddr("remote-addr") } 83 func (noopConn) SetDeadline(t time.Time) error { return nil } 84 func (noopConn) SetReadDeadline(t time.Time) error { return nil } 85 func (noopConn) SetWriteDeadline(t time.Time) error { return nil } 86 87 type rwTestConn struct { 88 io.Reader 89 io.Writer 90 noopConn 91 92 closeFunc func() error // called if non-nil 93 closec chan bool // else, if non-nil, send value to it on close 94 } 95 96 func (c *rwTestConn) Close() error { 97 if c.closeFunc != nil { 98 return c.closeFunc() 99 } 100 select { 101 case c.closec <- true: 102 default: 103 } 104 return nil 105 } 106 107 type testConn struct { 108 readMu sync.Mutex // for TestHandlerBodyClose 109 readBuf bytes.Buffer 110 writeBuf bytes.Buffer 111 closec chan bool // if non-nil, send value to it on close 112 noopConn 113 } 114 115 func (c *testConn) Read(b []byte) (int, error) { 116 c.readMu.Lock() 117 defer c.readMu.Unlock() 118 return c.readBuf.Read(b) 119 } 120 121 func (c *testConn) Write(b []byte) (int, error) { 122 return c.writeBuf.Write(b) 123 } 124 125 func (c *testConn) Close() error { 126 select { 127 case c.closec <- true: 128 default: 129 } 130 return nil 131 } 132 133 // reqBytes treats req as a request (with \n delimiters) and returns it with \r\n delimiters, 134 // ending in \r\n\r\n 135 func reqBytes(req string) []byte { 136 return []byte(strings.ReplaceAll(strings.TrimSpace(req), "\n", "\r\n") + "\r\n\r\n") 137 } 138 139 type handlerTest struct { 140 logbuf bytes.Buffer 141 handler Handler 142 } 143 144 func newHandlerTest(h Handler) handlerTest { 145 return handlerTest{handler: h} 146 } 147 148 func (ht *handlerTest) rawResponse(req string) string { 149 reqb := reqBytes(req) 150 var output strings.Builder 151 conn := &rwTestConn{ 152 Reader: bytes.NewReader(reqb), 153 Writer: &output, 154 closec: make(chan bool, 1), 155 } 156 ln := &oneConnListener{conn: conn} 157 srv := &Server{ 158 ErrorLog: log.New(&ht.logbuf, "", 0), 159 Handler: ht.handler, 160 } 161 go srv.Serve(ln) 162 <-conn.closec 163 return output.String() 164 } 165 166 func TestConsumingBodyOnNextConn(t *testing.T) { 167 t.Parallel() 168 defer afterTest(t) 169 conn := new(testConn) 170 for i := 0; i < 2; i++ { 171 conn.readBuf.Write([]byte( 172 "POST / HTTP/1.1\r\n" + 173 "Host: test\r\n" + 174 "Content-Length: 11\r\n" + 175 "\r\n" + 176 "foo=1&bar=1")) 177 } 178 179 reqNum := 0 180 ch := make(chan *Request) 181 servech := make(chan error) 182 listener := &oneConnListener{conn} 183 handler := func(res ResponseWriter, req *Request) { 184 reqNum++ 185 ch <- req 186 } 187 188 go func() { 189 servech <- Serve(listener, HandlerFunc(handler)) 190 }() 191 192 var req *Request 193 req = <-ch 194 if req == nil { 195 t.Fatal("Got nil first request.") 196 } 197 if req.Method != "POST" { 198 t.Errorf("For request #1's method, got %q; expected %q", 199 req.Method, "POST") 200 } 201 202 req = <-ch 203 if req == nil { 204 t.Fatal("Got nil first request.") 205 } 206 if req.Method != "POST" { 207 t.Errorf("For request #2's method, got %q; expected %q", 208 req.Method, "POST") 209 } 210 211 if serveerr := <-servech; serveerr != io.EOF { 212 t.Errorf("Serve returned %q; expected EOF", serveerr) 213 } 214 } 215 216 type stringHandler string 217 218 func (s stringHandler) ServeHTTP(w ResponseWriter, r *Request) { 219 w.Header().Set("Result", string(s)) 220 } 221 222 var handlers = []struct { 223 pattern string 224 msg string 225 }{ 226 {"/", "Default"}, 227 {"/someDir/", "someDir"}, 228 {"/#/", "hash"}, 229 {"someHost.com/someDir/", "someHost.com/someDir"}, 230 } 231 232 var vtests = []struct { 233 url string 234 expected string 235 }{ 236 {"http://localhost/someDir/apage", "someDir"}, 237 {"http://localhost/%23/apage", "hash"}, 238 {"http://localhost/otherDir/apage", "Default"}, 239 {"http://someHost.com/someDir/apage", "someHost.com/someDir"}, 240 {"http://otherHost.com/someDir/apage", "someDir"}, 241 {"http://otherHost.com/aDir/apage", "Default"}, 242 // redirections for trees 243 {"http://localhost/someDir", "/someDir/"}, 244 {"http://localhost/%23", "/%23/"}, 245 {"http://someHost.com/someDir", "/someDir/"}, 246 } 247 248 func TestHostHandlers(t *testing.T) { run(t, testHostHandlers, []testMode{http1Mode}) } 249 func testHostHandlers(t *testing.T, mode testMode) { 250 mux := NewServeMux() 251 for _, h := range handlers { 252 mux.Handle(h.pattern, stringHandler(h.msg)) 253 } 254 ts := newClientServerTest(t, mode, mux).ts 255 256 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 257 if err != nil { 258 t.Fatal(err) 259 } 260 defer conn.Close() 261 cc := httputil.NewClientConn(conn, nil) 262 for _, vt := range vtests { 263 var r *Response 264 var req Request 265 if req.URL, err = url.Parse(vt.url); err != nil { 266 t.Errorf("cannot parse url: %v", err) 267 continue 268 } 269 if err := cc.Write(&req); err != nil { 270 t.Errorf("writing request: %v", err) 271 continue 272 } 273 r, err := cc.Read(&req) 274 if err != nil { 275 t.Errorf("reading response: %v", err) 276 continue 277 } 278 switch r.StatusCode { 279 case StatusOK: 280 s := r.Header.Get("Result") 281 if s != vt.expected { 282 t.Errorf("Get(%q) = %q, want %q", vt.url, s, vt.expected) 283 } 284 case StatusMovedPermanently: 285 s := r.Header.Get("Location") 286 if s != vt.expected { 287 t.Errorf("Get(%q) = %q, want %q", vt.url, s, vt.expected) 288 } 289 default: 290 t.Errorf("Get(%q) unhandled status code %d", vt.url, r.StatusCode) 291 } 292 } 293 } 294 295 var serveMuxRegister = []struct { 296 pattern string 297 h Handler 298 }{ 299 {"/dir/", serve(200)}, 300 {"/search", serve(201)}, 301 {"codesearch.google.com/search", serve(202)}, 302 {"codesearch.google.com/", serve(203)}, 303 {"example.com/", HandlerFunc(checkQueryStringHandler)}, 304 } 305 306 // serve returns a handler that sends a response with the given code. 307 func serve(code int) HandlerFunc { 308 return func(w ResponseWriter, r *Request) { 309 w.WriteHeader(code) 310 } 311 } 312 313 // checkQueryStringHandler checks if r.URL.RawQuery has the same value 314 // as the URL excluding the scheme and the query string and sends 200 315 // response code if it is, 500 otherwise. 316 func checkQueryStringHandler(w ResponseWriter, r *Request) { 317 u := *r.URL 318 u.Scheme = "http" 319 u.Host = r.Host 320 u.RawQuery = "" 321 if "http://"+r.URL.RawQuery == u.String() { 322 w.WriteHeader(200) 323 } else { 324 w.WriteHeader(500) 325 } 326 } 327 328 var serveMuxTests = []struct { 329 method string 330 host string 331 path string 332 code int 333 pattern string 334 }{ 335 {"GET", "google.com", "/", 404, ""}, 336 {"GET", "google.com", "/dir", 301, "/dir/"}, 337 {"GET", "google.com", "/dir/", 200, "/dir/"}, 338 {"GET", "google.com", "/dir/file", 200, "/dir/"}, 339 {"GET", "google.com", "/search", 201, "/search"}, 340 {"GET", "google.com", "/search/", 404, ""}, 341 {"GET", "google.com", "/search/foo", 404, ""}, 342 {"GET", "codesearch.google.com", "/search", 202, "codesearch.google.com/search"}, 343 {"GET", "codesearch.google.com", "/search/", 203, "codesearch.google.com/"}, 344 {"GET", "codesearch.google.com", "/search/foo", 203, "codesearch.google.com/"}, 345 {"GET", "codesearch.google.com", "/", 203, "codesearch.google.com/"}, 346 {"GET", "codesearch.google.com:443", "/", 203, "codesearch.google.com/"}, 347 {"GET", "images.google.com", "/search", 201, "/search"}, 348 {"GET", "images.google.com", "/search/", 404, ""}, 349 {"GET", "images.google.com", "/search/foo", 404, ""}, 350 {"GET", "google.com", "/../search", 301, "/search"}, 351 {"GET", "google.com", "/dir/..", 301, ""}, 352 {"GET", "google.com", "/dir/..", 301, ""}, 353 {"GET", "google.com", "/dir/./file", 301, "/dir/"}, 354 355 // The /foo -> /foo/ redirect applies to CONNECT requests 356 // but the path canonicalization does not. 357 {"CONNECT", "google.com", "/dir", 301, "/dir/"}, 358 {"CONNECT", "google.com", "/../search", 404, ""}, 359 {"CONNECT", "google.com", "/dir/..", 200, "/dir/"}, 360 {"CONNECT", "google.com", "/dir/..", 200, "/dir/"}, 361 {"CONNECT", "google.com", "/dir/./file", 200, "/dir/"}, 362 } 363 364 func TestServeMuxHandler(t *testing.T) { 365 setParallel(t) 366 mux := NewServeMux() 367 for _, e := range serveMuxRegister { 368 mux.Handle(e.pattern, e.h) 369 } 370 371 for _, tt := range serveMuxTests { 372 r := &Request{ 373 Method: tt.method, 374 Host: tt.host, 375 URL: &url.URL{ 376 Path: tt.path, 377 }, 378 } 379 h, pattern := mux.Handler(r) 380 rr := httptest.NewRecorder() 381 h.ServeHTTP(rr, r) 382 if pattern != tt.pattern || rr.Code != tt.code { 383 t.Errorf("%s %s %s = %d, %q, want %d, %q", tt.method, tt.host, tt.path, rr.Code, pattern, tt.code, tt.pattern) 384 } 385 } 386 } 387 388 // Issue 24297 389 func TestServeMuxHandleFuncWithNilHandler(t *testing.T) { 390 setParallel(t) 391 defer func() { 392 if err := recover(); err == nil { 393 t.Error("expected call to mux.HandleFunc to panic") 394 } 395 }() 396 mux := NewServeMux() 397 mux.HandleFunc("/", nil) 398 } 399 400 var serveMuxTests2 = []struct { 401 method string 402 host string 403 url string 404 code int 405 redirOk bool 406 }{ 407 {"GET", "google.com", "/", 404, false}, 408 {"GET", "example.com", "/test/?example.com/test/", 200, false}, 409 {"GET", "example.com", "test/?example.com/test/", 200, true}, 410 } 411 412 // TestServeMuxHandlerRedirects tests that automatic redirects generated by 413 // mux.Handler() shouldn't clear the request's query string. 414 func TestServeMuxHandlerRedirects(t *testing.T) { 415 setParallel(t) 416 mux := NewServeMux() 417 for _, e := range serveMuxRegister { 418 mux.Handle(e.pattern, e.h) 419 } 420 421 for _, tt := range serveMuxTests2 { 422 tries := 1 // expect at most 1 redirection if redirOk is true. 423 turl := tt.url 424 for { 425 u, e := url.Parse(turl) 426 if e != nil { 427 t.Fatal(e) 428 } 429 r := &Request{ 430 Method: tt.method, 431 Host: tt.host, 432 URL: u, 433 } 434 h, _ := mux.Handler(r) 435 rr := httptest.NewRecorder() 436 h.ServeHTTP(rr, r) 437 if rr.Code != 301 { 438 if rr.Code != tt.code { 439 t.Errorf("%s %s %s = %d, want %d", tt.method, tt.host, tt.url, rr.Code, tt.code) 440 } 441 break 442 } 443 if !tt.redirOk { 444 t.Errorf("%s %s %s, unexpected redirect", tt.method, tt.host, tt.url) 445 break 446 } 447 turl = rr.HeaderMap.Get("Location") 448 tries-- 449 } 450 if tries < 0 { 451 t.Errorf("%s %s %s, too many redirects", tt.method, tt.host, tt.url) 452 } 453 } 454 } 455 456 // Tests for https://golang.org/issue/900 457 func TestMuxRedirectLeadingSlashes(t *testing.T) { 458 setParallel(t) 459 paths := []string{"//foo.txt", "///foo.txt", "/../../foo.txt"} 460 for _, path := range paths { 461 req, err := ReadRequest(bufio.NewReader(strings.NewReader("GET " + path + " HTTP/1.1\r\nHost: test\r\n\r\n"))) 462 if err != nil { 463 t.Errorf("%s", err) 464 } 465 mux := NewServeMux() 466 resp := httptest.NewRecorder() 467 468 mux.ServeHTTP(resp, req) 469 470 if loc, expected := resp.Header().Get("Location"), "/foo.txt"; loc != expected { 471 t.Errorf("Expected Location header set to %q; got %q", expected, loc) 472 return 473 } 474 475 if code, expected := resp.Code, StatusMovedPermanently; code != expected { 476 t.Errorf("Expected response code of StatusMovedPermanently; got %d", code) 477 return 478 } 479 } 480 } 481 482 // Test that the special cased "/route" redirect 483 // implicitly created by a registered "/route/" 484 // properly sets the query string in the redirect URL. 485 // See Issue 17841. 486 func TestServeWithSlashRedirectKeepsQueryString(t *testing.T) { 487 run(t, testServeWithSlashRedirectKeepsQueryString, []testMode{http1Mode}) 488 } 489 func testServeWithSlashRedirectKeepsQueryString(t *testing.T, mode testMode) { 490 writeBackQuery := func(w ResponseWriter, r *Request) { 491 fmt.Fprintf(w, "%s", r.URL.RawQuery) 492 } 493 494 mux := NewServeMux() 495 mux.HandleFunc("/testOne", writeBackQuery) 496 mux.HandleFunc("/testTwo/", writeBackQuery) 497 mux.HandleFunc("/testThree", writeBackQuery) 498 mux.HandleFunc("/testThree/", func(w ResponseWriter, r *Request) { 499 fmt.Fprintf(w, "%s:bar", r.URL.RawQuery) 500 }) 501 502 ts := newClientServerTest(t, mode, mux).ts 503 504 tests := [...]struct { 505 path string 506 method string 507 want string 508 statusOk bool 509 }{ 510 0: {"/testOne?this=that", "GET", "this=that", true}, 511 1: {"/testTwo?foo=bar", "GET", "foo=bar", true}, 512 2: {"/testTwo?a=1&b=2&a=3", "GET", "a=1&b=2&a=3", true}, 513 3: {"/testTwo?", "GET", "", true}, 514 4: {"/testThree?foo", "GET", "foo", true}, 515 5: {"/testThree/?foo", "GET", "foo:bar", true}, 516 6: {"/testThree?foo", "CONNECT", "foo", true}, 517 7: {"/testThree/?foo", "CONNECT", "foo:bar", true}, 518 519 // canonicalization or not 520 8: {"/testOne/foo/..?foo", "GET", "foo", true}, 521 9: {"/testOne/foo/..?foo", "CONNECT", "404 page not found\n", false}, 522 } 523 524 for i, tt := range tests { 525 req, _ := NewRequest(tt.method, ts.URL+tt.path, nil) 526 res, err := ts.Client().Do(req) 527 if err != nil { 528 continue 529 } 530 slurp, _ := io.ReadAll(res.Body) 531 res.Body.Close() 532 if !tt.statusOk { 533 if got, want := res.StatusCode, 404; got != want { 534 t.Errorf("#%d: Status = %d; want = %d", i, got, want) 535 } 536 } 537 if got, want := string(slurp), tt.want; got != want { 538 t.Errorf("#%d: Body = %q; want = %q", i, got, want) 539 } 540 } 541 } 542 543 func TestServeWithSlashRedirectForHostPatterns(t *testing.T) { 544 setParallel(t) 545 546 mux := NewServeMux() 547 mux.Handle("example.com/pkg/foo/", stringHandler("example.com/pkg/foo/")) 548 mux.Handle("example.com/pkg/bar", stringHandler("example.com/pkg/bar")) 549 mux.Handle("example.com/pkg/bar/", stringHandler("example.com/pkg/bar/")) 550 mux.Handle("example.com:3000/pkg/connect/", stringHandler("example.com:3000/pkg/connect/")) 551 mux.Handle("example.com:9000/", stringHandler("example.com:9000/")) 552 mux.Handle("/pkg/baz/", stringHandler("/pkg/baz/")) 553 554 tests := []struct { 555 method string 556 url string 557 code int 558 loc string 559 want string 560 }{ 561 {"GET", "http://example.com/", 404, "", ""}, 562 {"GET", "http://example.com/pkg/foo", 301, "/pkg/foo/", ""}, 563 {"GET", "http://example.com/pkg/bar", 200, "", "example.com/pkg/bar"}, 564 {"GET", "http://example.com/pkg/bar/", 200, "", "example.com/pkg/bar/"}, 565 {"GET", "http://example.com/pkg/baz", 301, "/pkg/baz/", ""}, 566 {"GET", "http://example.com:3000/pkg/foo", 301, "/pkg/foo/", ""}, 567 {"CONNECT", "http://example.com/", 404, "", ""}, 568 {"CONNECT", "http://example.com:3000/", 404, "", ""}, 569 {"CONNECT", "http://example.com:9000/", 200, "", "example.com:9000/"}, 570 {"CONNECT", "http://example.com/pkg/foo", 301, "/pkg/foo/", ""}, 571 {"CONNECT", "http://example.com:3000/pkg/foo", 404, "", ""}, 572 {"CONNECT", "http://example.com:3000/pkg/baz", 301, "/pkg/baz/", ""}, 573 {"CONNECT", "http://example.com:3000/pkg/connect", 301, "/pkg/connect/", ""}, 574 } 575 576 for i, tt := range tests { 577 req, _ := NewRequest(tt.method, tt.url, nil) 578 w := httptest.NewRecorder() 579 mux.ServeHTTP(w, req) 580 581 if got, want := w.Code, tt.code; got != want { 582 t.Errorf("#%d: Status = %d; want = %d", i, got, want) 583 } 584 585 if tt.code == 301 { 586 if got, want := w.HeaderMap.Get("Location"), tt.loc; got != want { 587 t.Errorf("#%d: Location = %q; want = %q", i, got, want) 588 } 589 } else { 590 if got, want := w.HeaderMap.Get("Result"), tt.want; got != want { 591 t.Errorf("#%d: Result = %q; want = %q", i, got, want) 592 } 593 } 594 } 595 } 596 597 func TestShouldRedirectConcurrency(t *testing.T) { run(t, testShouldRedirectConcurrency) } 598 func testShouldRedirectConcurrency(t *testing.T, mode testMode) { 599 mux := NewServeMux() 600 newClientServerTest(t, mode, mux) 601 mux.HandleFunc("/", func(w ResponseWriter, r *Request) {}) 602 } 603 604 func BenchmarkServeMux(b *testing.B) { benchmarkServeMux(b, true) } 605 func BenchmarkServeMux_SkipServe(b *testing.B) { benchmarkServeMux(b, false) } 606 func benchmarkServeMux(b *testing.B, runHandler bool) { 607 type test struct { 608 path string 609 code int 610 req *Request 611 } 612 613 // Build example handlers and requests 614 var tests []test 615 endpoints := []string{"search", "dir", "file", "change", "count", "s"} 616 for _, e := range endpoints { 617 for i := 200; i < 230; i++ { 618 p := fmt.Sprintf("/%s/%d/", e, i) 619 tests = append(tests, test{ 620 path: p, 621 code: i, 622 req: &Request{Method: "GET", Host: "localhost", URL: &url.URL{Path: p}}, 623 }) 624 } 625 } 626 mux := NewServeMux() 627 for _, tt := range tests { 628 mux.Handle(tt.path, serve(tt.code)) 629 } 630 631 rw := httptest.NewRecorder() 632 b.ReportAllocs() 633 b.ResetTimer() 634 for i := 0; i < b.N; i++ { 635 for _, tt := range tests { 636 *rw = httptest.ResponseRecorder{} 637 h, pattern := mux.Handler(tt.req) 638 if runHandler { 639 h.ServeHTTP(rw, tt.req) 640 if pattern != tt.path || rw.Code != tt.code { 641 b.Fatalf("got %d, %q, want %d, %q", rw.Code, pattern, tt.code, tt.path) 642 } 643 } 644 } 645 } 646 } 647 648 func TestServerTimeouts(t *testing.T) { run(t, testServerTimeouts, []testMode{http1Mode}) } 649 func testServerTimeouts(t *testing.T, mode testMode) { 650 // Try three times, with increasing timeouts. 651 tries := []time.Duration{250 * time.Millisecond, 500 * time.Millisecond, 1 * time.Second} 652 for i, timeout := range tries { 653 err := testServerTimeoutsWithTimeout(t, timeout, mode) 654 if err == nil { 655 return 656 } 657 t.Logf("failed at %v: %v", timeout, err) 658 if i != len(tries)-1 { 659 t.Logf("retrying at %v ...", tries[i+1]) 660 } 661 } 662 t.Fatal("all attempts failed") 663 } 664 665 func testServerTimeoutsWithTimeout(t *testing.T, timeout time.Duration, mode testMode) error { 666 reqNum := 0 667 ts := newClientServerTest(t, mode, HandlerFunc(func(res ResponseWriter, req *Request) { 668 reqNum++ 669 fmt.Fprintf(res, "req=%d", reqNum) 670 }), func(ts *httptest.Server) { 671 ts.Config.ReadTimeout = timeout 672 ts.Config.WriteTimeout = timeout 673 }).ts 674 675 // Hit the HTTP server successfully. 676 c := ts.Client() 677 r, err := c.Get(ts.URL) 678 if err != nil { 679 return fmt.Errorf("http Get #1: %v", err) 680 } 681 got, err := io.ReadAll(r.Body) 682 expected := "req=1" 683 if string(got) != expected || err != nil { 684 return fmt.Errorf("Unexpected response for request #1; got %q ,%v; expected %q, nil", 685 string(got), err, expected) 686 } 687 688 // Slow client that should timeout. 689 t1 := time.Now() 690 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 691 if err != nil { 692 return fmt.Errorf("Dial: %v", err) 693 } 694 buf := make([]byte, 1) 695 n, err := conn.Read(buf) 696 conn.Close() 697 latency := time.Since(t1) 698 if n != 0 || err != io.EOF { 699 return fmt.Errorf("Read = %v, %v, wanted %v, %v", n, err, 0, io.EOF) 700 } 701 minLatency := timeout / 5 * 4 702 if latency < minLatency { 703 return fmt.Errorf("got EOF after %s, want >= %s", latency, minLatency) 704 } 705 706 // Hit the HTTP server successfully again, verifying that the 707 // previous slow connection didn't run our handler. (that we 708 // get "req=2", not "req=3") 709 r, err = c.Get(ts.URL) 710 if err != nil { 711 return fmt.Errorf("http Get #2: %v", err) 712 } 713 got, err = io.ReadAll(r.Body) 714 r.Body.Close() 715 expected = "req=2" 716 if string(got) != expected || err != nil { 717 return fmt.Errorf("Get #2 got %q, %v, want %q, nil", string(got), err, expected) 718 } 719 720 if !testing.Short() { 721 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 722 if err != nil { 723 return fmt.Errorf("long Dial: %v", err) 724 } 725 defer conn.Close() 726 go io.Copy(io.Discard, conn) 727 for i := 0; i < 5; i++ { 728 _, err := conn.Write([]byte("GET / HTTP/1.1\r\nHost: foo\r\n\r\n")) 729 if err != nil { 730 return fmt.Errorf("on write %d: %v", i, err) 731 } 732 time.Sleep(timeout / 2) 733 } 734 } 735 return nil 736 } 737 738 func TestServerReadTimeout(t *testing.T) { run(t, testServerReadTimeout) } 739 func testServerReadTimeout(t *testing.T, mode testMode) { 740 respBody := "response body" 741 for timeout := 5 * time.Millisecond; ; timeout *= 2 { 742 cst := newClientServerTest(t, mode, HandlerFunc(func(res ResponseWriter, req *Request) { 743 _, err := io.Copy(io.Discard, req.Body) 744 if !errors.Is(err, os.ErrDeadlineExceeded) { 745 t.Errorf("server timed out reading request body: got err %v; want os.ErrDeadlineExceeded", err) 746 } 747 res.Write([]byte(respBody)) 748 }), func(ts *httptest.Server) { 749 ts.Config.ReadHeaderTimeout = -1 // don't time out while reading headers 750 ts.Config.ReadTimeout = timeout 751 }) 752 pr, pw := io.Pipe() 753 res, err := cst.c.Post(cst.ts.URL, "text/apocryphal", pr) 754 if err != nil { 755 t.Logf("Get error, retrying: %v", err) 756 cst.close() 757 continue 758 } 759 defer res.Body.Close() 760 got, err := io.ReadAll(res.Body) 761 if string(got) != respBody || err != nil { 762 t.Errorf("client read response body: %q, %v; want %q, nil", string(got), err, respBody) 763 } 764 pw.Close() 765 break 766 } 767 } 768 769 func TestServerWriteTimeout(t *testing.T) { run(t, testServerWriteTimeout) } 770 func testServerWriteTimeout(t *testing.T, mode testMode) { 771 for timeout := 5 * time.Millisecond; ; timeout *= 2 { 772 errc := make(chan error, 2) 773 cst := newClientServerTest(t, mode, HandlerFunc(func(res ResponseWriter, req *Request) { 774 errc <- nil 775 _, err := io.Copy(res, neverEnding('a')) 776 errc <- err 777 }), func(ts *httptest.Server) { 778 ts.Config.WriteTimeout = timeout 779 }) 780 res, err := cst.c.Get(cst.ts.URL) 781 if err != nil { 782 // Probably caused by the write timeout expiring before the handler runs. 783 t.Logf("Get error, retrying: %v", err) 784 cst.close() 785 continue 786 } 787 defer res.Body.Close() 788 _, err = io.Copy(io.Discard, res.Body) 789 if err == nil { 790 t.Errorf("client reading from truncated request body: got nil error, want non-nil") 791 } 792 select { 793 case <-errc: 794 err = <-errc // io.Copy error 795 if !errors.Is(err, os.ErrDeadlineExceeded) { 796 t.Errorf("server timed out writing request body: got err %v; want os.ErrDeadlineExceeded", err) 797 } 798 return 799 default: 800 // The write timeout expired before the handler started. 801 t.Logf("handler didn't run, retrying") 802 cst.close() 803 } 804 } 805 } 806 807 // Test that the HTTP/2 server handles Server.WriteTimeout (Issue 18437) 808 func TestWriteDeadlineExtendedOnNewRequest(t *testing.T) { 809 run(t, testWriteDeadlineExtendedOnNewRequest) 810 } 811 func testWriteDeadlineExtendedOnNewRequest(t *testing.T, mode testMode) { 812 if testing.Short() { 813 t.Skip("skipping in short mode") 814 } 815 ts := newClientServerTest(t, mode, HandlerFunc(func(res ResponseWriter, req *Request) {}), 816 func(ts *httptest.Server) { 817 ts.Config.WriteTimeout = 250 * time.Millisecond 818 }, 819 ).ts 820 821 c := ts.Client() 822 823 for i := 1; i <= 3; i++ { 824 req, err := NewRequest("GET", ts.URL, nil) 825 if err != nil { 826 t.Fatal(err) 827 } 828 829 r, err := c.Do(req) 830 if err != nil { 831 t.Fatalf("http2 Get #%d: %v", i, err) 832 } 833 r.Body.Close() 834 time.Sleep(ts.Config.WriteTimeout / 2) 835 } 836 } 837 838 // tryTimeouts runs testFunc with increasing timeouts. Test passes on first success, 839 // and fails if all timeouts fail. 840 func tryTimeouts(t *testing.T, testFunc func(timeout time.Duration) error) { 841 tries := []time.Duration{250 * time.Millisecond, 500 * time.Millisecond, 1 * time.Second} 842 for i, timeout := range tries { 843 err := testFunc(timeout) 844 if err == nil { 845 return 846 } 847 t.Logf("failed at %v: %v", timeout, err) 848 if i != len(tries)-1 { 849 t.Logf("retrying at %v ...", tries[i+1]) 850 } 851 } 852 t.Fatal("all attempts failed") 853 } 854 855 // Test that the HTTP/2 server RSTs stream on slow write. 856 func TestWriteDeadlineEnforcedPerStream(t *testing.T) { 857 if testing.Short() { 858 t.Skip("skipping in short mode") 859 } 860 setParallel(t) 861 run(t, func(t *testing.T, mode testMode) { 862 tryTimeouts(t, func(timeout time.Duration) error { 863 return testWriteDeadlineEnforcedPerStream(t, mode, timeout) 864 }) 865 }) 866 } 867 868 func testWriteDeadlineEnforcedPerStream(t *testing.T, mode testMode, timeout time.Duration) error { 869 reqNum := 0 870 ts := newClientServerTest(t, mode, HandlerFunc(func(res ResponseWriter, req *Request) { 871 reqNum++ 872 if reqNum == 1 { 873 return // first request succeeds 874 } 875 time.Sleep(timeout) // second request times out 876 }), func(ts *httptest.Server) { 877 ts.Config.WriteTimeout = timeout / 2 878 }).ts 879 880 c := ts.Client() 881 882 req, err := NewRequest("GET", ts.URL, nil) 883 if err != nil { 884 return fmt.Errorf("NewRequest: %v", err) 885 } 886 r, err := c.Do(req) 887 if err != nil { 888 return fmt.Errorf("Get #1: %v", err) 889 } 890 r.Body.Close() 891 892 req, err = NewRequest("GET", ts.URL, nil) 893 if err != nil { 894 return fmt.Errorf("NewRequest: %v", err) 895 } 896 r, err = c.Do(req) 897 if err == nil { 898 r.Body.Close() 899 return fmt.Errorf("Get #2 expected error, got nil") 900 } 901 if mode == http2Mode { 902 expected := "stream ID 3; INTERNAL_ERROR" // client IDs are odd, second stream should be 3 903 if !strings.Contains(err.Error(), expected) { 904 return fmt.Errorf("http2 Get #2: expected error to contain %q, got %q", expected, err) 905 } 906 } 907 return nil 908 } 909 910 // Test that the HTTP/2 server does not send RST when WriteDeadline not set. 911 func TestNoWriteDeadline(t *testing.T) { 912 if testing.Short() { 913 t.Skip("skipping in short mode") 914 } 915 setParallel(t) 916 defer afterTest(t) 917 run(t, func(t *testing.T, mode testMode) { 918 tryTimeouts(t, func(timeout time.Duration) error { 919 return testNoWriteDeadline(t, mode, timeout) 920 }) 921 }) 922 } 923 924 func testNoWriteDeadline(t *testing.T, mode testMode, timeout time.Duration) error { 925 reqNum := 0 926 ts := newClientServerTest(t, mode, HandlerFunc(func(res ResponseWriter, req *Request) { 927 reqNum++ 928 if reqNum == 1 { 929 return // first request succeeds 930 } 931 time.Sleep(timeout) // second request timesout 932 })).ts 933 934 c := ts.Client() 935 936 for i := 0; i < 2; i++ { 937 req, err := NewRequest("GET", ts.URL, nil) 938 if err != nil { 939 return fmt.Errorf("NewRequest: %v", err) 940 } 941 r, err := c.Do(req) 942 if err != nil { 943 return fmt.Errorf("Get #%d: %v", i, err) 944 } 945 r.Body.Close() 946 } 947 return nil 948 } 949 950 // golang.org/issue/4741 -- setting only a write timeout that triggers 951 // shouldn't cause a handler to block forever on reads (next HTTP 952 // request) that will never happen. 953 func TestOnlyWriteTimeout(t *testing.T) { run(t, testOnlyWriteTimeout, []testMode{http1Mode}) } 954 func testOnlyWriteTimeout(t *testing.T, mode testMode) { 955 var ( 956 mu sync.RWMutex 957 conn net.Conn 958 ) 959 var afterTimeoutErrc = make(chan error, 1) 960 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, req *Request) { 961 buf := make([]byte, 512<<10) 962 _, err := w.Write(buf) 963 if err != nil { 964 t.Errorf("handler Write error: %v", err) 965 return 966 } 967 mu.RLock() 968 defer mu.RUnlock() 969 if conn == nil { 970 t.Error("no established connection found") 971 return 972 } 973 conn.SetWriteDeadline(time.Now().Add(-30 * time.Second)) 974 _, err = w.Write(buf) 975 afterTimeoutErrc <- err 976 }), func(ts *httptest.Server) { 977 ts.Listener = trackLastConnListener{ts.Listener, &mu, &conn} 978 }).ts 979 980 c := ts.Client() 981 982 err := func() error { 983 res, err := c.Get(ts.URL) 984 if err != nil { 985 return err 986 } 987 _, err = io.Copy(io.Discard, res.Body) 988 res.Body.Close() 989 return err 990 }() 991 if err == nil { 992 t.Errorf("expected an error copying body from Get request") 993 } 994 995 if err := <-afterTimeoutErrc; err == nil { 996 t.Error("expected write error after timeout") 997 } 998 } 999 1000 // trackLastConnListener tracks the last net.Conn that was accepted. 1001 type trackLastConnListener struct { 1002 net.Listener 1003 1004 mu *sync.RWMutex 1005 last *net.Conn // destination 1006 } 1007 1008 func (l trackLastConnListener) Accept() (c net.Conn, err error) { 1009 c, err = l.Listener.Accept() 1010 if err == nil { 1011 l.mu.Lock() 1012 *l.last = c 1013 l.mu.Unlock() 1014 } 1015 return 1016 } 1017 1018 // TestIdentityResponse verifies that a handler can unset 1019 func TestIdentityResponse(t *testing.T) { run(t, testIdentityResponse) } 1020 func testIdentityResponse(t *testing.T, mode testMode) { 1021 if mode == http2Mode { 1022 t.Skip("https://go.dev/issue/56019") 1023 } 1024 1025 handler := HandlerFunc(func(rw ResponseWriter, req *Request) { 1026 rw.Header().Set("Content-Length", "3") 1027 rw.Header().Set("Transfer-Encoding", req.FormValue("te")) 1028 switch { 1029 case req.FormValue("overwrite") == "1": 1030 _, err := rw.Write([]byte("foo TOO LONG")) 1031 if err != ErrContentLength { 1032 t.Errorf("expected ErrContentLength; got %v", err) 1033 } 1034 case req.FormValue("underwrite") == "1": 1035 rw.Header().Set("Content-Length", "500") 1036 rw.Write([]byte("too short")) 1037 default: 1038 rw.Write([]byte("foo")) 1039 } 1040 }) 1041 1042 ts := newClientServerTest(t, mode, handler).ts 1043 c := ts.Client() 1044 1045 // Note: this relies on the assumption (which is true) that 1046 // Get sends HTTP/1.1 or greater requests. Otherwise the 1047 // server wouldn't have the choice to send back chunked 1048 // responses. 1049 for _, te := range []string{"", "identity"} { 1050 url := ts.URL + "/?te=" + te 1051 res, err := c.Get(url) 1052 if err != nil { 1053 t.Fatalf("error with Get of %s: %v", url, err) 1054 } 1055 if cl, expected := res.ContentLength, int64(3); cl != expected { 1056 t.Errorf("for %s expected res.ContentLength of %d; got %d", url, expected, cl) 1057 } 1058 if cl, expected := res.Header.Get("Content-Length"), "3"; cl != expected { 1059 t.Errorf("for %s expected Content-Length header of %q; got %q", url, expected, cl) 1060 } 1061 if tl, expected := len(res.TransferEncoding), 0; tl != expected { 1062 t.Errorf("for %s expected len(res.TransferEncoding) of %d; got %d (%v)", 1063 url, expected, tl, res.TransferEncoding) 1064 } 1065 res.Body.Close() 1066 } 1067 1068 // Verify that ErrContentLength is returned 1069 url := ts.URL + "/?overwrite=1" 1070 res, err := c.Get(url) 1071 if err != nil { 1072 t.Fatalf("error with Get of %s: %v", url, err) 1073 } 1074 res.Body.Close() 1075 1076 if mode != http1Mode { 1077 return 1078 } 1079 1080 // Verify that the connection is closed when the declared Content-Length 1081 // is larger than what the handler wrote. 1082 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 1083 if err != nil { 1084 t.Fatalf("error dialing: %v", err) 1085 } 1086 _, err = conn.Write([]byte("GET /?underwrite=1 HTTP/1.1\r\nHost: foo\r\n\r\n")) 1087 if err != nil { 1088 t.Fatalf("error writing: %v", err) 1089 } 1090 1091 // The ReadAll will hang for a failing test. 1092 got, _ := io.ReadAll(conn) 1093 expectedSuffix := "\r\n\r\ntoo short" 1094 if !strings.HasSuffix(string(got), expectedSuffix) { 1095 t.Errorf("Expected output to end with %q; got response body %q", 1096 expectedSuffix, string(got)) 1097 } 1098 } 1099 1100 func testTCPConnectionCloses(t *testing.T, req string, h Handler) { 1101 setParallel(t) 1102 s := newClientServerTest(t, http1Mode, h).ts 1103 1104 conn, err := net.Dial("tcp", s.Listener.Addr().String()) 1105 if err != nil { 1106 t.Fatal("dial error:", err) 1107 } 1108 defer conn.Close() 1109 1110 _, err = fmt.Fprint(conn, req) 1111 if err != nil { 1112 t.Fatal("print error:", err) 1113 } 1114 1115 r := bufio.NewReader(conn) 1116 res, err := ReadResponse(r, &Request{Method: "GET"}) 1117 if err != nil { 1118 t.Fatal("ReadResponse error:", err) 1119 } 1120 1121 _, err = io.ReadAll(r) 1122 if err != nil { 1123 t.Fatal("read error:", err) 1124 } 1125 1126 if !res.Close { 1127 t.Errorf("Response.Close = false; want true") 1128 } 1129 } 1130 1131 func testTCPConnectionStaysOpen(t *testing.T, req string, handler Handler) { 1132 setParallel(t) 1133 ts := newClientServerTest(t, http1Mode, handler).ts 1134 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 1135 if err != nil { 1136 t.Fatal(err) 1137 } 1138 defer conn.Close() 1139 br := bufio.NewReader(conn) 1140 for i := 0; i < 2; i++ { 1141 if _, err := io.WriteString(conn, req); err != nil { 1142 t.Fatal(err) 1143 } 1144 res, err := ReadResponse(br, nil) 1145 if err != nil { 1146 t.Fatalf("res %d: %v", i+1, err) 1147 } 1148 if _, err := io.Copy(io.Discard, res.Body); err != nil { 1149 t.Fatalf("res %d body copy: %v", i+1, err) 1150 } 1151 res.Body.Close() 1152 } 1153 } 1154 1155 // TestServeHTTP10Close verifies that HTTP/1.0 requests won't be kept alive. 1156 func TestServeHTTP10Close(t *testing.T) { 1157 testTCPConnectionCloses(t, "GET / HTTP/1.0\r\n\r\n", HandlerFunc(func(w ResponseWriter, r *Request) { 1158 ServeFile(w, r, "testdata/file") 1159 })) 1160 } 1161 1162 // TestClientCanClose verifies that clients can also force a connection to close. 1163 func TestClientCanClose(t *testing.T) { 1164 testTCPConnectionCloses(t, "GET / HTTP/1.1\r\nHost: foo\r\nConnection: close\r\n\r\n", HandlerFunc(func(w ResponseWriter, r *Request) { 1165 // Nothing. 1166 })) 1167 } 1168 1169 // TestHandlersCanSetConnectionClose verifies that handlers can force a connection to close, 1170 // even for HTTP/1.1 requests. 1171 func TestHandlersCanSetConnectionClose11(t *testing.T) { 1172 testTCPConnectionCloses(t, "GET / HTTP/1.1\r\nHost: foo\r\n\r\n\r\n", HandlerFunc(func(w ResponseWriter, r *Request) { 1173 w.Header().Set("Connection", "close") 1174 })) 1175 } 1176 1177 func TestHandlersCanSetConnectionClose10(t *testing.T) { 1178 testTCPConnectionCloses(t, "GET / HTTP/1.0\r\nConnection: keep-alive\r\n\r\n", HandlerFunc(func(w ResponseWriter, r *Request) { 1179 w.Header().Set("Connection", "close") 1180 })) 1181 } 1182 1183 func TestHTTP2UpgradeClosesConnection(t *testing.T) { 1184 testTCPConnectionCloses(t, "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n", HandlerFunc(func(w ResponseWriter, r *Request) { 1185 // Nothing. (if not hijacked, the server should close the connection 1186 // afterwards) 1187 })) 1188 } 1189 1190 func send204(w ResponseWriter, r *Request) { w.WriteHeader(204) } 1191 func send304(w ResponseWriter, r *Request) { w.WriteHeader(304) } 1192 1193 // Issue 15647: 204 responses can't have bodies, so HTTP/1.0 keep-alive conns should stay open. 1194 func TestHTTP10KeepAlive204Response(t *testing.T) { 1195 testTCPConnectionStaysOpen(t, "GET / HTTP/1.0\r\nConnection: keep-alive\r\n\r\n", HandlerFunc(send204)) 1196 } 1197 1198 func TestHTTP11KeepAlive204Response(t *testing.T) { 1199 testTCPConnectionStaysOpen(t, "GET / HTTP/1.1\r\nHost: foo\r\n\r\n", HandlerFunc(send204)) 1200 } 1201 1202 func TestHTTP10KeepAlive304Response(t *testing.T) { 1203 testTCPConnectionStaysOpen(t, 1204 "GET / HTTP/1.0\r\nConnection: keep-alive\r\nIf-Modified-Since: Mon, 02 Jan 2006 15:04:05 GMT\r\n\r\n", 1205 HandlerFunc(send304)) 1206 } 1207 1208 // Issue 15703 1209 func TestKeepAliveFinalChunkWithEOF(t *testing.T) { run(t, testKeepAliveFinalChunkWithEOF) } 1210 func testKeepAliveFinalChunkWithEOF(t *testing.T, mode testMode) { 1211 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 1212 w.(Flusher).Flush() // force chunked encoding 1213 w.Write([]byte("{\"Addr\": \"" + r.RemoteAddr + "\"}")) 1214 })) 1215 type data struct { 1216 Addr string 1217 } 1218 var addrs [2]data 1219 for i := range addrs { 1220 res, err := cst.c.Get(cst.ts.URL) 1221 if err != nil { 1222 t.Fatal(err) 1223 } 1224 if err := json.NewDecoder(res.Body).Decode(&addrs[i]); err != nil { 1225 t.Fatal(err) 1226 } 1227 if addrs[i].Addr == "" { 1228 t.Fatal("no address") 1229 } 1230 res.Body.Close() 1231 } 1232 if addrs[0] != addrs[1] { 1233 t.Fatalf("connection not reused") 1234 } 1235 } 1236 1237 func TestSetsRemoteAddr(t *testing.T) { run(t, testSetsRemoteAddr) } 1238 func testSetsRemoteAddr(t *testing.T, mode testMode) { 1239 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 1240 fmt.Fprintf(w, "%s", r.RemoteAddr) 1241 })) 1242 1243 res, err := cst.c.Get(cst.ts.URL) 1244 if err != nil { 1245 t.Fatalf("Get error: %v", err) 1246 } 1247 body, err := io.ReadAll(res.Body) 1248 if err != nil { 1249 t.Fatalf("ReadAll error: %v", err) 1250 } 1251 ip := string(body) 1252 if !strings.HasPrefix(ip, "127.0.0.1:") && !strings.HasPrefix(ip, "[::1]:") { 1253 t.Fatalf("Expected local addr; got %q", ip) 1254 } 1255 } 1256 1257 type blockingRemoteAddrListener struct { 1258 net.Listener 1259 conns chan<- net.Conn 1260 } 1261 1262 func (l *blockingRemoteAddrListener) Accept() (net.Conn, error) { 1263 c, err := l.Listener.Accept() 1264 if err != nil { 1265 return nil, err 1266 } 1267 brac := &blockingRemoteAddrConn{ 1268 Conn: c, 1269 addrs: make(chan net.Addr, 1), 1270 } 1271 l.conns <- brac 1272 return brac, nil 1273 } 1274 1275 type blockingRemoteAddrConn struct { 1276 net.Conn 1277 addrs chan net.Addr 1278 } 1279 1280 func (c *blockingRemoteAddrConn) RemoteAddr() net.Addr { 1281 return <-c.addrs 1282 } 1283 1284 // Issue 12943 1285 func TestServerAllowsBlockingRemoteAddr(t *testing.T) { 1286 run(t, testServerAllowsBlockingRemoteAddr, []testMode{http1Mode}) 1287 } 1288 func testServerAllowsBlockingRemoteAddr(t *testing.T, mode testMode) { 1289 conns := make(chan net.Conn) 1290 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 1291 fmt.Fprintf(w, "RA:%s", r.RemoteAddr) 1292 }), func(ts *httptest.Server) { 1293 ts.Listener = &blockingRemoteAddrListener{ 1294 Listener: ts.Listener, 1295 conns: conns, 1296 } 1297 }).ts 1298 1299 c := ts.Client() 1300 // Force separate connection for each: 1301 c.Transport.(*Transport).DisableKeepAlives = true 1302 1303 fetch := func(num int, response chan<- string) { 1304 resp, err := c.Get(ts.URL) 1305 if err != nil { 1306 t.Errorf("Request %d: %v", num, err) 1307 response <- "" 1308 return 1309 } 1310 defer resp.Body.Close() 1311 body, err := io.ReadAll(resp.Body) 1312 if err != nil { 1313 t.Errorf("Request %d: %v", num, err) 1314 response <- "" 1315 return 1316 } 1317 response <- string(body) 1318 } 1319 1320 // Start a request. The server will block on getting conn.RemoteAddr. 1321 response1c := make(chan string, 1) 1322 go fetch(1, response1c) 1323 1324 // Wait for the server to accept it; grab the connection. 1325 conn1 := <-conns 1326 1327 // Start another request and grab its connection 1328 response2c := make(chan string, 1) 1329 go fetch(2, response2c) 1330 conn2 := <-conns 1331 1332 // Send a response on connection 2. 1333 conn2.(*blockingRemoteAddrConn).addrs <- &net.TCPAddr{ 1334 IP: net.ParseIP("12.12.12.12"), Port: 12} 1335 1336 // ... and see it 1337 response2 := <-response2c 1338 if g, e := response2, "RA:12.12.12.12:12"; g != e { 1339 t.Fatalf("response 2 addr = %q; want %q", g, e) 1340 } 1341 1342 // Finish the first response. 1343 conn1.(*blockingRemoteAddrConn).addrs <- &net.TCPAddr{ 1344 IP: net.ParseIP("21.21.21.21"), Port: 21} 1345 1346 // ... and see it 1347 response1 := <-response1c 1348 if g, e := response1, "RA:21.21.21.21:21"; g != e { 1349 t.Fatalf("response 1 addr = %q; want %q", g, e) 1350 } 1351 } 1352 1353 // TestHeadResponses verifies that all MIME type sniffing and Content-Length 1354 // counting of GET requests also happens on HEAD requests. 1355 func TestHeadResponses(t *testing.T) { run(t, testHeadResponses) } 1356 func testHeadResponses(t *testing.T, mode testMode) { 1357 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 1358 _, err := w.Write([]byte("<html>")) 1359 if err != nil { 1360 t.Errorf("ResponseWriter.Write: %v", err) 1361 } 1362 1363 // Also exercise the ReaderFrom path 1364 _, err = io.Copy(w, strings.NewReader("789a")) 1365 if err != nil { 1366 t.Errorf("Copy(ResponseWriter, ...): %v", err) 1367 } 1368 })) 1369 res, err := cst.c.Head(cst.ts.URL) 1370 if err != nil { 1371 t.Error(err) 1372 } 1373 if len(res.TransferEncoding) > 0 { 1374 t.Errorf("expected no TransferEncoding; got %v", res.TransferEncoding) 1375 } 1376 if ct := res.Header.Get("Content-Type"); ct != "text/html; charset=utf-8" { 1377 t.Errorf("Content-Type: %q; want text/html; charset=utf-8", ct) 1378 } 1379 if v := res.ContentLength; v != 10 { 1380 t.Errorf("Content-Length: %d; want 10", v) 1381 } 1382 body, err := io.ReadAll(res.Body) 1383 if err != nil { 1384 t.Error(err) 1385 } 1386 if len(body) > 0 { 1387 t.Errorf("got unexpected body %q", string(body)) 1388 } 1389 } 1390 1391 func TestTLSHandshakeTimeout(t *testing.T) { 1392 run(t, testTLSHandshakeTimeout, []testMode{https1Mode, http2Mode}) 1393 } 1394 func testTLSHandshakeTimeout(t *testing.T, mode testMode) { 1395 errc := make(chanWriter, 10) // but only expecting 1 1396 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {}), 1397 func(ts *httptest.Server) { 1398 ts.Config.ReadTimeout = 250 * time.Millisecond 1399 ts.Config.ErrorLog = log.New(errc, "", 0) 1400 }, 1401 ).ts 1402 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 1403 if err != nil { 1404 t.Fatalf("Dial: %v", err) 1405 } 1406 defer conn.Close() 1407 1408 var buf [1]byte 1409 n, err := conn.Read(buf[:]) 1410 if err == nil || n != 0 { 1411 t.Errorf("Read = %d, %v; want an error and no bytes", n, err) 1412 } 1413 1414 v := <-errc 1415 if !strings.Contains(v, "timeout") && !strings.Contains(v, "TLS handshake") { 1416 t.Errorf("expected a TLS handshake timeout error; got %q", v) 1417 } 1418 } 1419 1420 func TestTLSServer(t *testing.T) { run(t, testTLSServer, []testMode{https1Mode, http2Mode}) } 1421 func testTLSServer(t *testing.T, mode testMode) { 1422 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 1423 if r.TLS != nil { 1424 w.Header().Set("X-TLS-Set", "true") 1425 if r.TLS.HandshakeComplete { 1426 w.Header().Set("X-TLS-HandshakeComplete", "true") 1427 } 1428 } 1429 }), func(ts *httptest.Server) { 1430 ts.Config.ErrorLog = log.New(io.Discard, "", 0) 1431 }).ts 1432 1433 // Connect an idle TCP connection to this server before we run 1434 // our real tests. This idle connection used to block forever 1435 // in the TLS handshake, preventing future connections from 1436 // being accepted. It may prevent future accidental blocking 1437 // in newConn. 1438 idleConn, err := net.Dial("tcp", ts.Listener.Addr().String()) 1439 if err != nil { 1440 t.Fatalf("Dial: %v", err) 1441 } 1442 defer idleConn.Close() 1443 1444 if !strings.HasPrefix(ts.URL, "https://") { 1445 t.Errorf("expected test TLS server to start with https://, got %q", ts.URL) 1446 return 1447 } 1448 client := ts.Client() 1449 res, err := client.Get(ts.URL) 1450 if err != nil { 1451 t.Error(err) 1452 return 1453 } 1454 if res == nil { 1455 t.Errorf("got nil Response") 1456 return 1457 } 1458 defer res.Body.Close() 1459 if res.Header.Get("X-TLS-Set") != "true" { 1460 t.Errorf("expected X-TLS-Set response header") 1461 return 1462 } 1463 if res.Header.Get("X-TLS-HandshakeComplete") != "true" { 1464 t.Errorf("expected X-TLS-HandshakeComplete header") 1465 } 1466 } 1467 1468 func TestServeTLS(t *testing.T) { 1469 CondSkipHTTP2(t) 1470 // Not parallel: uses global test hooks. 1471 defer afterTest(t) 1472 defer SetTestHookServerServe(nil) 1473 1474 cert, err := tls.X509KeyPair(testcert.LocalhostCert, testcert.LocalhostKey) 1475 if err != nil { 1476 t.Fatal(err) 1477 } 1478 tlsConf := &tls.Config{ 1479 Certificates: []tls.Certificate{cert}, 1480 } 1481 1482 ln := newLocalListener(t) 1483 defer ln.Close() 1484 addr := ln.Addr().String() 1485 1486 serving := make(chan bool, 1) 1487 SetTestHookServerServe(func(s *Server, ln net.Listener) { 1488 serving <- true 1489 }) 1490 handler := HandlerFunc(func(w ResponseWriter, r *Request) {}) 1491 s := &Server{ 1492 Addr: addr, 1493 TLSConfig: tlsConf, 1494 Handler: handler, 1495 } 1496 errc := make(chan error, 1) 1497 go func() { errc <- s.ServeTLS(ln, "", "") }() 1498 select { 1499 case err := <-errc: 1500 t.Fatalf("ServeTLS: %v", err) 1501 case <-serving: 1502 } 1503 1504 c, err := tls.Dial("tcp", ln.Addr().String(), &tls.Config{ 1505 InsecureSkipVerify: true, 1506 NextProtos: []string{"h2", "http/1.1"}, 1507 }) 1508 if err != nil { 1509 t.Fatal(err) 1510 } 1511 defer c.Close() 1512 if got, want := c.ConnectionState().NegotiatedProtocol, "h2"; got != want { 1513 t.Errorf("NegotiatedProtocol = %q; want %q", got, want) 1514 } 1515 if got, want := c.ConnectionState().NegotiatedProtocolIsMutual, true; got != want { 1516 t.Errorf("NegotiatedProtocolIsMutual = %v; want %v", got, want) 1517 } 1518 } 1519 1520 // Test that the HTTPS server nicely rejects plaintext HTTP/1.x requests. 1521 func TestTLSServerRejectHTTPRequests(t *testing.T) { 1522 run(t, testTLSServerRejectHTTPRequests, []testMode{https1Mode, http2Mode}) 1523 } 1524 func testTLSServerRejectHTTPRequests(t *testing.T, mode testMode) { 1525 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 1526 t.Error("unexpected HTTPS request") 1527 }), func(ts *httptest.Server) { 1528 var errBuf bytes.Buffer 1529 ts.Config.ErrorLog = log.New(&errBuf, "", 0) 1530 }).ts 1531 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 1532 if err != nil { 1533 t.Fatal(err) 1534 } 1535 defer conn.Close() 1536 io.WriteString(conn, "GET / HTTP/1.1\r\nHost: foo\r\n\r\n") 1537 slurp, err := io.ReadAll(conn) 1538 if err != nil { 1539 t.Fatal(err) 1540 } 1541 const wantPrefix = "HTTP/1.0 400 Bad Request\r\n" 1542 if !strings.HasPrefix(string(slurp), wantPrefix) { 1543 t.Errorf("response = %q; wanted prefix %q", slurp, wantPrefix) 1544 } 1545 } 1546 1547 // Issue 15908 1548 func TestAutomaticHTTP2_Serve_NoTLSConfig(t *testing.T) { 1549 testAutomaticHTTP2_Serve(t, nil, true) 1550 } 1551 1552 func TestAutomaticHTTP2_Serve_NonH2TLSConfig(t *testing.T) { 1553 testAutomaticHTTP2_Serve(t, &tls.Config{}, false) 1554 } 1555 1556 func TestAutomaticHTTP2_Serve_H2TLSConfig(t *testing.T) { 1557 testAutomaticHTTP2_Serve(t, &tls.Config{NextProtos: []string{"h2"}}, true) 1558 } 1559 1560 func testAutomaticHTTP2_Serve(t *testing.T, tlsConf *tls.Config, wantH2 bool) { 1561 setParallel(t) 1562 defer afterTest(t) 1563 ln := newLocalListener(t) 1564 ln.Close() // immediately (not a defer!) 1565 var s Server 1566 s.TLSConfig = tlsConf 1567 if err := s.Serve(ln); err == nil { 1568 t.Fatal("expected an error") 1569 } 1570 gotH2 := s.TLSNextProto["h2"] != nil 1571 if gotH2 != wantH2 { 1572 t.Errorf("http2 configured = %v; want %v", gotH2, wantH2) 1573 } 1574 } 1575 1576 func TestAutomaticHTTP2_Serve_WithTLSConfig(t *testing.T) { 1577 setParallel(t) 1578 defer afterTest(t) 1579 ln := newLocalListener(t) 1580 ln.Close() // immediately (not a defer!) 1581 var s Server 1582 // Set the TLSConfig. In reality, this would be the 1583 // *tls.Config given to tls.NewListener. 1584 s.TLSConfig = &tls.Config{ 1585 NextProtos: []string{"h2"}, 1586 } 1587 if err := s.Serve(ln); err == nil { 1588 t.Fatal("expected an error") 1589 } 1590 on := s.TLSNextProto["h2"] != nil 1591 if !on { 1592 t.Errorf("http2 wasn't automatically enabled") 1593 } 1594 } 1595 1596 func TestAutomaticHTTP2_ListenAndServe(t *testing.T) { 1597 cert, err := tls.X509KeyPair(testcert.LocalhostCert, testcert.LocalhostKey) 1598 if err != nil { 1599 t.Fatal(err) 1600 } 1601 testAutomaticHTTP2_ListenAndServe(t, &tls.Config{ 1602 Certificates: []tls.Certificate{cert}, 1603 }) 1604 } 1605 1606 func TestAutomaticHTTP2_ListenAndServe_GetCertificate(t *testing.T) { 1607 cert, err := tls.X509KeyPair(testcert.LocalhostCert, testcert.LocalhostKey) 1608 if err != nil { 1609 t.Fatal(err) 1610 } 1611 testAutomaticHTTP2_ListenAndServe(t, &tls.Config{ 1612 GetCertificate: func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) { 1613 return &cert, nil 1614 }, 1615 }) 1616 } 1617 1618 func testAutomaticHTTP2_ListenAndServe(t *testing.T, tlsConf *tls.Config) { 1619 CondSkipHTTP2(t) 1620 // Not parallel: uses global test hooks. 1621 defer afterTest(t) 1622 defer SetTestHookServerServe(nil) 1623 var ok bool 1624 var s *Server 1625 const maxTries = 5 1626 var ln net.Listener 1627 Try: 1628 for try := 0; try < maxTries; try++ { 1629 ln = newLocalListener(t) 1630 addr := ln.Addr().String() 1631 ln.Close() 1632 t.Logf("Got %v", addr) 1633 lnc := make(chan net.Listener, 1) 1634 SetTestHookServerServe(func(s *Server, ln net.Listener) { 1635 lnc <- ln 1636 }) 1637 s = &Server{ 1638 Addr: addr, 1639 TLSConfig: tlsConf, 1640 } 1641 errc := make(chan error, 1) 1642 go func() { errc <- s.ListenAndServeTLS("", "") }() 1643 select { 1644 case err := <-errc: 1645 t.Logf("On try #%v: %v", try+1, err) 1646 continue 1647 case ln = <-lnc: 1648 ok = true 1649 t.Logf("Listening on %v", ln.Addr().String()) 1650 break Try 1651 } 1652 } 1653 if !ok { 1654 t.Fatalf("Failed to start up after %d tries", maxTries) 1655 } 1656 defer ln.Close() 1657 c, err := tls.Dial("tcp", ln.Addr().String(), &tls.Config{ 1658 InsecureSkipVerify: true, 1659 NextProtos: []string{"h2", "http/1.1"}, 1660 }) 1661 if err != nil { 1662 t.Fatal(err) 1663 } 1664 defer c.Close() 1665 if got, want := c.ConnectionState().NegotiatedProtocol, "h2"; got != want { 1666 t.Errorf("NegotiatedProtocol = %q; want %q", got, want) 1667 } 1668 if got, want := c.ConnectionState().NegotiatedProtocolIsMutual, true; got != want { 1669 t.Errorf("NegotiatedProtocolIsMutual = %v; want %v", got, want) 1670 } 1671 } 1672 1673 type serverExpectTest struct { 1674 contentLength int // of request body 1675 chunked bool 1676 expectation string // e.g. "100-continue" 1677 readBody bool // whether handler should read the body (if false, sends StatusUnauthorized) 1678 expectedResponse string // expected substring in first line of http response 1679 } 1680 1681 func expectTest(contentLength int, expectation string, readBody bool, expectedResponse string) serverExpectTest { 1682 return serverExpectTest{ 1683 contentLength: contentLength, 1684 expectation: expectation, 1685 readBody: readBody, 1686 expectedResponse: expectedResponse, 1687 } 1688 } 1689 1690 var serverExpectTests = []serverExpectTest{ 1691 // Normal 100-continues, case-insensitive. 1692 expectTest(100, "100-continue", true, "100 Continue"), 1693 expectTest(100, "100-cOntInUE", true, "100 Continue"), 1694 1695 // No 100-continue. 1696 expectTest(100, "", true, "200 OK"), 1697 1698 // 100-continue but requesting client to deny us, 1699 // so it never reads the body. 1700 expectTest(100, "100-continue", false, "401 Unauthorized"), 1701 // Likewise without 100-continue: 1702 expectTest(100, "", false, "401 Unauthorized"), 1703 1704 // Non-standard expectations are failures 1705 expectTest(0, "a-pony", false, "417 Expectation Failed"), 1706 1707 // Expect-100 requested but no body (is apparently okay: Issue 7625) 1708 expectTest(0, "100-continue", true, "200 OK"), 1709 // Expect-100 requested but handler doesn't read the body 1710 expectTest(0, "100-continue", false, "401 Unauthorized"), 1711 // Expect-100 continue with no body, but a chunked body. 1712 { 1713 expectation: "100-continue", 1714 readBody: true, 1715 chunked: true, 1716 expectedResponse: "100 Continue", 1717 }, 1718 } 1719 1720 // Tests that the server responds to the "Expect" request header 1721 // correctly. 1722 func TestServerExpect(t *testing.T) { run(t, testServerExpect, []testMode{http1Mode}) } 1723 func testServerExpect(t *testing.T, mode testMode) { 1724 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 1725 // Note using r.FormValue("readbody") because for POST 1726 // requests that would read from r.Body, which we only 1727 // conditionally want to do. 1728 if strings.Contains(r.URL.RawQuery, "readbody=true") { 1729 io.ReadAll(r.Body) 1730 w.Write([]byte("Hi")) 1731 } else { 1732 w.WriteHeader(StatusUnauthorized) 1733 } 1734 })).ts 1735 1736 runTest := func(test serverExpectTest) { 1737 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 1738 if err != nil { 1739 t.Fatalf("Dial: %v", err) 1740 } 1741 defer conn.Close() 1742 1743 // Only send the body immediately if we're acting like an HTTP client 1744 // that doesn't send 100-continue expectations. 1745 writeBody := test.contentLength != 0 && strings.ToLower(test.expectation) != "100-continue" 1746 1747 wg := sync.WaitGroup{} 1748 wg.Add(1) 1749 defer wg.Wait() 1750 1751 go func() { 1752 defer wg.Done() 1753 1754 contentLen := fmt.Sprintf("Content-Length: %d", test.contentLength) 1755 if test.chunked { 1756 contentLen = "Transfer-Encoding: chunked" 1757 } 1758 _, err := fmt.Fprintf(conn, "POST /?readbody=%v HTTP/1.1\r\n"+ 1759 "Connection: close\r\n"+ 1760 "%s\r\n"+ 1761 "Expect: %s\r\nHost: foo\r\n\r\n", 1762 test.readBody, contentLen, test.expectation) 1763 if err != nil { 1764 t.Errorf("On test %#v, error writing request headers: %v", test, err) 1765 return 1766 } 1767 if writeBody { 1768 var targ io.WriteCloser = struct { 1769 io.Writer 1770 io.Closer 1771 }{ 1772 conn, 1773 io.NopCloser(nil), 1774 } 1775 if test.chunked { 1776 targ = httputil.NewChunkedWriter(conn) 1777 } 1778 body := strings.Repeat("A", test.contentLength) 1779 _, err = fmt.Fprint(targ, body) 1780 if err == nil { 1781 err = targ.Close() 1782 } 1783 if err != nil { 1784 if !test.readBody { 1785 // Server likely already hung up on us. 1786 // See larger comment below. 1787 t.Logf("On test %#v, acceptable error writing request body: %v", test, err) 1788 return 1789 } 1790 t.Errorf("On test %#v, error writing request body: %v", test, err) 1791 } 1792 } 1793 }() 1794 bufr := bufio.NewReader(conn) 1795 line, err := bufr.ReadString('\n') 1796 if err != nil { 1797 if writeBody && !test.readBody { 1798 // This is an acceptable failure due to a possible TCP race: 1799 // We were still writing data and the server hung up on us. A TCP 1800 // implementation may send a RST if our request body data was known 1801 // to be lost, which may trigger our reads to fail. 1802 // See RFC 1122 page 88. 1803 t.Logf("On test %#v, acceptable error from ReadString: %v", test, err) 1804 return 1805 } 1806 t.Fatalf("On test %#v, ReadString: %v", test, err) 1807 } 1808 if !strings.Contains(line, test.expectedResponse) { 1809 t.Errorf("On test %#v, got first line = %q; want %q", test, line, test.expectedResponse) 1810 } 1811 } 1812 1813 for _, test := range serverExpectTests { 1814 runTest(test) 1815 } 1816 } 1817 1818 // Under a ~256KB (maxPostHandlerReadBytes) threshold, the server 1819 // should consume client request bodies that a handler didn't read. 1820 func TestServerUnreadRequestBodyLittle(t *testing.T) { 1821 setParallel(t) 1822 defer afterTest(t) 1823 conn := new(testConn) 1824 body := strings.Repeat("x", 100<<10) 1825 conn.readBuf.Write([]byte(fmt.Sprintf( 1826 "POST / HTTP/1.1\r\n"+ 1827 "Host: test\r\n"+ 1828 "Content-Length: %d\r\n"+ 1829 "\r\n", len(body)))) 1830 conn.readBuf.Write([]byte(body)) 1831 1832 done := make(chan bool) 1833 1834 readBufLen := func() int { 1835 conn.readMu.Lock() 1836 defer conn.readMu.Unlock() 1837 return conn.readBuf.Len() 1838 } 1839 1840 ls := &oneConnListener{conn} 1841 go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) { 1842 defer close(done) 1843 if bufLen := readBufLen(); bufLen < len(body)/2 { 1844 t.Errorf("on request, read buffer length is %d; expected about 100 KB", bufLen) 1845 } 1846 rw.WriteHeader(200) 1847 rw.(Flusher).Flush() 1848 if g, e := readBufLen(), 0; g != e { 1849 t.Errorf("after WriteHeader, read buffer length is %d; want %d", g, e) 1850 } 1851 if c := rw.Header().Get("Connection"); c != "" { 1852 t.Errorf(`Connection header = %q; want ""`, c) 1853 } 1854 })) 1855 <-done 1856 } 1857 1858 // Over a ~256KB (maxPostHandlerReadBytes) threshold, the server 1859 // should ignore client request bodies that a handler didn't read 1860 // and close the connection. 1861 func TestServerUnreadRequestBodyLarge(t *testing.T) { 1862 setParallel(t) 1863 if testing.Short() && testenv.Builder() == "" { 1864 t.Log("skipping in short mode") 1865 } 1866 conn := new(testConn) 1867 body := strings.Repeat("x", 1<<20) 1868 conn.readBuf.Write([]byte(fmt.Sprintf( 1869 "POST / HTTP/1.1\r\n"+ 1870 "Host: test\r\n"+ 1871 "Content-Length: %d\r\n"+ 1872 "\r\n", len(body)))) 1873 conn.readBuf.Write([]byte(body)) 1874 conn.closec = make(chan bool, 1) 1875 1876 ls := &oneConnListener{conn} 1877 go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) { 1878 if conn.readBuf.Len() < len(body)/2 { 1879 t.Errorf("on request, read buffer length is %d; expected about 1MB", conn.readBuf.Len()) 1880 } 1881 rw.WriteHeader(200) 1882 rw.(Flusher).Flush() 1883 if conn.readBuf.Len() < len(body)/2 { 1884 t.Errorf("post-WriteHeader, read buffer length is %d; expected about 1MB", conn.readBuf.Len()) 1885 } 1886 })) 1887 <-conn.closec 1888 1889 if res := conn.writeBuf.String(); !strings.Contains(res, "Connection: close") { 1890 t.Errorf("Expected a Connection: close header; got response: %s", res) 1891 } 1892 } 1893 1894 type handlerBodyCloseTest struct { 1895 bodySize int 1896 bodyChunked bool 1897 reqConnClose bool 1898 1899 wantEOFSearch bool // should Handler's Body.Close do Reads, looking for EOF? 1900 wantNextReq bool // should it find the next request on the same conn? 1901 } 1902 1903 func (t handlerBodyCloseTest) connectionHeader() string { 1904 if t.reqConnClose { 1905 return "Connection: close\r\n" 1906 } 1907 return "" 1908 } 1909 1910 var handlerBodyCloseTests = [...]handlerBodyCloseTest{ 1911 // Small enough to slurp past to the next request + 1912 // has Content-Length. 1913 0: { 1914 bodySize: 20 << 10, 1915 bodyChunked: false, 1916 reqConnClose: false, 1917 wantEOFSearch: true, 1918 wantNextReq: true, 1919 }, 1920 1921 // Small enough to slurp past to the next request + 1922 // is chunked. 1923 1: { 1924 bodySize: 20 << 10, 1925 bodyChunked: true, 1926 reqConnClose: false, 1927 wantEOFSearch: true, 1928 wantNextReq: true, 1929 }, 1930 1931 // Small enough to slurp past to the next request + 1932 // has Content-Length + 1933 // declares Connection: close (so pointless to read more). 1934 2: { 1935 bodySize: 20 << 10, 1936 bodyChunked: false, 1937 reqConnClose: true, 1938 wantEOFSearch: false, 1939 wantNextReq: false, 1940 }, 1941 1942 // Small enough to slurp past to the next request + 1943 // declares Connection: close, 1944 // but chunked, so it might have trailers. 1945 // TODO: maybe skip this search if no trailers were declared 1946 // in the headers. 1947 3: { 1948 bodySize: 20 << 10, 1949 bodyChunked: true, 1950 reqConnClose: true, 1951 wantEOFSearch: true, 1952 wantNextReq: false, 1953 }, 1954 1955 // Big with Content-Length, so give up immediately if we know it's too big. 1956 4: { 1957 bodySize: 1 << 20, 1958 bodyChunked: false, // has a Content-Length 1959 reqConnClose: false, 1960 wantEOFSearch: false, 1961 wantNextReq: false, 1962 }, 1963 1964 // Big chunked, so read a bit before giving up. 1965 5: { 1966 bodySize: 1 << 20, 1967 bodyChunked: true, 1968 reqConnClose: false, 1969 wantEOFSearch: true, 1970 wantNextReq: false, 1971 }, 1972 1973 // Big with Connection: close, but chunked, so search for trailers. 1974 // TODO: maybe skip this search if no trailers were declared 1975 // in the headers. 1976 6: { 1977 bodySize: 1 << 20, 1978 bodyChunked: true, 1979 reqConnClose: true, 1980 wantEOFSearch: true, 1981 wantNextReq: false, 1982 }, 1983 1984 // Big with Connection: close, so don't do any reads on Close. 1985 // With Content-Length. 1986 7: { 1987 bodySize: 1 << 20, 1988 bodyChunked: false, 1989 reqConnClose: true, 1990 wantEOFSearch: false, 1991 wantNextReq: false, 1992 }, 1993 } 1994 1995 func TestHandlerBodyClose(t *testing.T) { 1996 setParallel(t) 1997 if testing.Short() && testenv.Builder() == "" { 1998 t.Skip("skipping in -short mode") 1999 } 2000 for i, tt := range handlerBodyCloseTests { 2001 testHandlerBodyClose(t, i, tt) 2002 } 2003 } 2004 2005 func testHandlerBodyClose(t *testing.T, i int, tt handlerBodyCloseTest) { 2006 conn := new(testConn) 2007 body := strings.Repeat("x", tt.bodySize) 2008 if tt.bodyChunked { 2009 conn.readBuf.WriteString("POST / HTTP/1.1\r\n" + 2010 "Host: test\r\n" + 2011 tt.connectionHeader() + 2012 "Transfer-Encoding: chunked\r\n" + 2013 "\r\n") 2014 cw := internal.NewChunkedWriter(&conn.readBuf) 2015 io.WriteString(cw, body) 2016 cw.Close() 2017 conn.readBuf.WriteString("\r\n") 2018 } else { 2019 conn.readBuf.Write([]byte(fmt.Sprintf( 2020 "POST / HTTP/1.1\r\n"+ 2021 "Host: test\r\n"+ 2022 tt.connectionHeader()+ 2023 "Content-Length: %d\r\n"+ 2024 "\r\n", len(body)))) 2025 conn.readBuf.Write([]byte(body)) 2026 } 2027 if !tt.reqConnClose { 2028 conn.readBuf.WriteString("GET / HTTP/1.1\r\nHost: test\r\n\r\n") 2029 } 2030 conn.closec = make(chan bool, 1) 2031 2032 readBufLen := func() int { 2033 conn.readMu.Lock() 2034 defer conn.readMu.Unlock() 2035 return conn.readBuf.Len() 2036 } 2037 2038 ls := &oneConnListener{conn} 2039 var numReqs int 2040 var size0, size1 int 2041 go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) { 2042 numReqs++ 2043 if numReqs == 1 { 2044 size0 = readBufLen() 2045 req.Body.Close() 2046 size1 = readBufLen() 2047 } 2048 })) 2049 <-conn.closec 2050 if numReqs < 1 || numReqs > 2 { 2051 t.Fatalf("%d. bug in test. unexpected number of requests = %d", i, numReqs) 2052 } 2053 didSearch := size0 != size1 2054 if didSearch != tt.wantEOFSearch { 2055 t.Errorf("%d. did EOF search = %v; want %v (size went from %d to %d)", i, didSearch, !didSearch, size0, size1) 2056 } 2057 if tt.wantNextReq && numReqs != 2 { 2058 t.Errorf("%d. numReq = %d; want 2", i, numReqs) 2059 } 2060 } 2061 2062 // testHandlerBodyConsumer represents a function injected into a test handler to 2063 // vary work done on a request Body. 2064 type testHandlerBodyConsumer struct { 2065 name string 2066 f func(io.ReadCloser) 2067 } 2068 2069 var testHandlerBodyConsumers = []testHandlerBodyConsumer{ 2070 {"nil", func(io.ReadCloser) {}}, 2071 {"close", func(r io.ReadCloser) { r.Close() }}, 2072 {"discard", func(r io.ReadCloser) { io.Copy(io.Discard, r) }}, 2073 } 2074 2075 func TestRequestBodyReadErrorClosesConnection(t *testing.T) { 2076 setParallel(t) 2077 defer afterTest(t) 2078 for _, handler := range testHandlerBodyConsumers { 2079 conn := new(testConn) 2080 conn.readBuf.WriteString("POST /public HTTP/1.1\r\n" + 2081 "Host: test\r\n" + 2082 "Transfer-Encoding: chunked\r\n" + 2083 "\r\n" + 2084 "hax\r\n" + // Invalid chunked encoding 2085 "GET /secret HTTP/1.1\r\n" + 2086 "Host: test\r\n" + 2087 "\r\n") 2088 2089 conn.closec = make(chan bool, 1) 2090 ls := &oneConnListener{conn} 2091 var numReqs int 2092 go Serve(ls, HandlerFunc(func(_ ResponseWriter, req *Request) { 2093 numReqs++ 2094 if strings.Contains(req.URL.Path, "secret") { 2095 t.Error("Request for /secret encountered, should not have happened.") 2096 } 2097 handler.f(req.Body) 2098 })) 2099 <-conn.closec 2100 if numReqs != 1 { 2101 t.Errorf("Handler %v: got %d reqs; want 1", handler.name, numReqs) 2102 } 2103 } 2104 } 2105 2106 func TestInvalidTrailerClosesConnection(t *testing.T) { 2107 setParallel(t) 2108 defer afterTest(t) 2109 for _, handler := range testHandlerBodyConsumers { 2110 conn := new(testConn) 2111 conn.readBuf.WriteString("POST /public HTTP/1.1\r\n" + 2112 "Host: test\r\n" + 2113 "Trailer: hack\r\n" + 2114 "Transfer-Encoding: chunked\r\n" + 2115 "\r\n" + 2116 "3\r\n" + 2117 "hax\r\n" + 2118 "0\r\n" + 2119 "I'm not a valid trailer\r\n" + 2120 "GET /secret HTTP/1.1\r\n" + 2121 "Host: test\r\n" + 2122 "\r\n") 2123 2124 conn.closec = make(chan bool, 1) 2125 ln := &oneConnListener{conn} 2126 var numReqs int 2127 go Serve(ln, HandlerFunc(func(_ ResponseWriter, req *Request) { 2128 numReqs++ 2129 if strings.Contains(req.URL.Path, "secret") { 2130 t.Errorf("Handler %s, Request for /secret encountered, should not have happened.", handler.name) 2131 } 2132 handler.f(req.Body) 2133 })) 2134 <-conn.closec 2135 if numReqs != 1 { 2136 t.Errorf("Handler %s: got %d reqs; want 1", handler.name, numReqs) 2137 } 2138 } 2139 } 2140 2141 // slowTestConn is a net.Conn that provides a means to simulate parts of a 2142 // request being received piecemeal. Deadlines can be set and enforced in both 2143 // Read and Write. 2144 type slowTestConn struct { 2145 // over multiple calls to Read, time.Durations are slept, strings are read. 2146 script []any 2147 closec chan bool 2148 2149 mu sync.Mutex // guards rd/wd 2150 rd, wd time.Time // read, write deadline 2151 noopConn 2152 } 2153 2154 func (c *slowTestConn) SetDeadline(t time.Time) error { 2155 c.SetReadDeadline(t) 2156 c.SetWriteDeadline(t) 2157 return nil 2158 } 2159 2160 func (c *slowTestConn) SetReadDeadline(t time.Time) error { 2161 c.mu.Lock() 2162 defer c.mu.Unlock() 2163 c.rd = t 2164 return nil 2165 } 2166 2167 func (c *slowTestConn) SetWriteDeadline(t time.Time) error { 2168 c.mu.Lock() 2169 defer c.mu.Unlock() 2170 c.wd = t 2171 return nil 2172 } 2173 2174 func (c *slowTestConn) Read(b []byte) (n int, err error) { 2175 c.mu.Lock() 2176 defer c.mu.Unlock() 2177 restart: 2178 if !c.rd.IsZero() && time.Now().After(c.rd) { 2179 return 0, syscall.ETIMEDOUT 2180 } 2181 if len(c.script) == 0 { 2182 return 0, io.EOF 2183 } 2184 2185 switch cue := c.script[0].(type) { 2186 case time.Duration: 2187 if !c.rd.IsZero() { 2188 // If the deadline falls in the middle of our sleep window, deduct 2189 // part of the sleep, then return a timeout. 2190 if remaining := time.Until(c.rd); remaining < cue { 2191 c.script[0] = cue - remaining 2192 time.Sleep(remaining) 2193 return 0, syscall.ETIMEDOUT 2194 } 2195 } 2196 c.script = c.script[1:] 2197 time.Sleep(cue) 2198 goto restart 2199 2200 case string: 2201 n = copy(b, cue) 2202 // If cue is too big for the buffer, leave the end for the next Read. 2203 if len(cue) > n { 2204 c.script[0] = cue[n:] 2205 } else { 2206 c.script = c.script[1:] 2207 } 2208 2209 default: 2210 panic("unknown cue in slowTestConn script") 2211 } 2212 2213 return 2214 } 2215 2216 func (c *slowTestConn) Close() error { 2217 select { 2218 case c.closec <- true: 2219 default: 2220 } 2221 return nil 2222 } 2223 2224 func (c *slowTestConn) Write(b []byte) (int, error) { 2225 if !c.wd.IsZero() && time.Now().After(c.wd) { 2226 return 0, syscall.ETIMEDOUT 2227 } 2228 return len(b), nil 2229 } 2230 2231 func TestRequestBodyTimeoutClosesConnection(t *testing.T) { 2232 if testing.Short() { 2233 t.Skip("skipping in -short mode") 2234 } 2235 defer afterTest(t) 2236 for _, handler := range testHandlerBodyConsumers { 2237 conn := &slowTestConn{ 2238 script: []any{ 2239 "POST /public HTTP/1.1\r\n" + 2240 "Host: test\r\n" + 2241 "Content-Length: 10000\r\n" + 2242 "\r\n", 2243 "foo bar baz", 2244 600 * time.Millisecond, // Request deadline should hit here 2245 "GET /secret HTTP/1.1\r\n" + 2246 "Host: test\r\n" + 2247 "\r\n", 2248 }, 2249 closec: make(chan bool, 1), 2250 } 2251 ls := &oneConnListener{conn} 2252 2253 var numReqs int 2254 s := Server{ 2255 Handler: HandlerFunc(func(_ ResponseWriter, req *Request) { 2256 numReqs++ 2257 if strings.Contains(req.URL.Path, "secret") { 2258 t.Error("Request for /secret encountered, should not have happened.") 2259 } 2260 handler.f(req.Body) 2261 }), 2262 ReadTimeout: 400 * time.Millisecond, 2263 } 2264 go s.Serve(ls) 2265 <-conn.closec 2266 2267 if numReqs != 1 { 2268 t.Errorf("Handler %v: got %d reqs; want 1", handler.name, numReqs) 2269 } 2270 } 2271 } 2272 2273 // cancelableTimeoutContext overwrites the error message to DeadlineExceeded 2274 type cancelableTimeoutContext struct { 2275 context.Context 2276 } 2277 2278 func (c cancelableTimeoutContext) Err() error { 2279 if c.Context.Err() != nil { 2280 return context.DeadlineExceeded 2281 } 2282 return nil 2283 } 2284 2285 func TestTimeoutHandler(t *testing.T) { run(t, testTimeoutHandler) } 2286 func testTimeoutHandler(t *testing.T, mode testMode) { 2287 sendHi := make(chan bool, 1) 2288 writeErrors := make(chan error, 1) 2289 sayHi := HandlerFunc(func(w ResponseWriter, r *Request) { 2290 <-sendHi 2291 _, werr := w.Write([]byte("hi")) 2292 writeErrors <- werr 2293 }) 2294 ctx, cancel := context.WithCancel(context.Background()) 2295 h := NewTestTimeoutHandler(sayHi, cancelableTimeoutContext{ctx}) 2296 cst := newClientServerTest(t, mode, h) 2297 2298 // Succeed without timing out: 2299 sendHi <- true 2300 res, err := cst.c.Get(cst.ts.URL) 2301 if err != nil { 2302 t.Error(err) 2303 } 2304 if g, e := res.StatusCode, StatusOK; g != e { 2305 t.Errorf("got res.StatusCode %d; expected %d", g, e) 2306 } 2307 body, _ := io.ReadAll(res.Body) 2308 if g, e := string(body), "hi"; g != e { 2309 t.Errorf("got body %q; expected %q", g, e) 2310 } 2311 if g := <-writeErrors; g != nil { 2312 t.Errorf("got unexpected Write error on first request: %v", g) 2313 } 2314 2315 // Times out: 2316 cancel() 2317 2318 res, err = cst.c.Get(cst.ts.URL) 2319 if err != nil { 2320 t.Error(err) 2321 } 2322 if g, e := res.StatusCode, StatusServiceUnavailable; g != e { 2323 t.Errorf("got res.StatusCode %d; expected %d", g, e) 2324 } 2325 body, _ = io.ReadAll(res.Body) 2326 if !strings.Contains(string(body), "<title>Timeout</title>") { 2327 t.Errorf("expected timeout body; got %q", string(body)) 2328 } 2329 if g, w := res.Header.Get("Content-Type"), "text/html; charset=utf-8"; g != w { 2330 t.Errorf("response content-type = %q; want %q", g, w) 2331 } 2332 2333 // Now make the previously-timed out handler speak again, 2334 // which verifies the panic is handled: 2335 sendHi <- true 2336 if g, e := <-writeErrors, ErrHandlerTimeout; g != e { 2337 t.Errorf("expected Write error of %v; got %v", e, g) 2338 } 2339 } 2340 2341 // See issues 8209 and 8414. 2342 func TestTimeoutHandlerRace(t *testing.T) { run(t, testTimeoutHandlerRace) } 2343 func testTimeoutHandlerRace(t *testing.T, mode testMode) { 2344 delayHi := HandlerFunc(func(w ResponseWriter, r *Request) { 2345 ms, _ := strconv.Atoi(r.URL.Path[1:]) 2346 if ms == 0 { 2347 ms = 1 2348 } 2349 for i := 0; i < ms; i++ { 2350 w.Write([]byte("hi")) 2351 time.Sleep(time.Millisecond) 2352 } 2353 }) 2354 2355 ts := newClientServerTest(t, mode, TimeoutHandler(delayHi, 20*time.Millisecond, "")).ts 2356 2357 c := ts.Client() 2358 2359 var wg sync.WaitGroup 2360 gate := make(chan bool, 10) 2361 n := 50 2362 if testing.Short() { 2363 n = 10 2364 gate = make(chan bool, 3) 2365 } 2366 for i := 0; i < n; i++ { 2367 gate <- true 2368 wg.Add(1) 2369 go func() { 2370 defer wg.Done() 2371 defer func() { <-gate }() 2372 res, err := c.Get(fmt.Sprintf("%s/%d", ts.URL, rand.Intn(50))) 2373 if err == nil { 2374 io.Copy(io.Discard, res.Body) 2375 res.Body.Close() 2376 } 2377 }() 2378 } 2379 wg.Wait() 2380 } 2381 2382 // See issues 8209 and 8414. 2383 // Both issues involved panics in the implementation of TimeoutHandler. 2384 func TestTimeoutHandlerRaceHeader(t *testing.T) { run(t, testTimeoutHandlerRaceHeader) } 2385 func testTimeoutHandlerRaceHeader(t *testing.T, mode testMode) { 2386 delay204 := HandlerFunc(func(w ResponseWriter, r *Request) { 2387 w.WriteHeader(204) 2388 }) 2389 2390 ts := newClientServerTest(t, mode, TimeoutHandler(delay204, time.Nanosecond, "")).ts 2391 2392 var wg sync.WaitGroup 2393 gate := make(chan bool, 50) 2394 n := 500 2395 if testing.Short() { 2396 n = 10 2397 } 2398 2399 c := ts.Client() 2400 for i := 0; i < n; i++ { 2401 gate <- true 2402 wg.Add(1) 2403 go func() { 2404 defer wg.Done() 2405 defer func() { <-gate }() 2406 res, err := c.Get(ts.URL) 2407 if err != nil { 2408 // We see ECONNRESET from the connection occasionally, 2409 // and that's OK: this test is checking that the server does not panic. 2410 t.Log(err) 2411 return 2412 } 2413 defer res.Body.Close() 2414 io.Copy(io.Discard, res.Body) 2415 }() 2416 } 2417 wg.Wait() 2418 } 2419 2420 // Issue 9162 2421 func TestTimeoutHandlerRaceHeaderTimeout(t *testing.T) { run(t, testTimeoutHandlerRaceHeaderTimeout) } 2422 func testTimeoutHandlerRaceHeaderTimeout(t *testing.T, mode testMode) { 2423 sendHi := make(chan bool, 1) 2424 writeErrors := make(chan error, 1) 2425 sayHi := HandlerFunc(func(w ResponseWriter, r *Request) { 2426 w.Header().Set("Content-Type", "text/plain") 2427 <-sendHi 2428 _, werr := w.Write([]byte("hi")) 2429 writeErrors <- werr 2430 }) 2431 ctx, cancel := context.WithCancel(context.Background()) 2432 h := NewTestTimeoutHandler(sayHi, cancelableTimeoutContext{ctx}) 2433 cst := newClientServerTest(t, mode, h) 2434 2435 // Succeed without timing out: 2436 sendHi <- true 2437 res, err := cst.c.Get(cst.ts.URL) 2438 if err != nil { 2439 t.Error(err) 2440 } 2441 if g, e := res.StatusCode, StatusOK; g != e { 2442 t.Errorf("got res.StatusCode %d; expected %d", g, e) 2443 } 2444 body, _ := io.ReadAll(res.Body) 2445 if g, e := string(body), "hi"; g != e { 2446 t.Errorf("got body %q; expected %q", g, e) 2447 } 2448 if g := <-writeErrors; g != nil { 2449 t.Errorf("got unexpected Write error on first request: %v", g) 2450 } 2451 2452 // Times out: 2453 cancel() 2454 2455 res, err = cst.c.Get(cst.ts.URL) 2456 if err != nil { 2457 t.Error(err) 2458 } 2459 if g, e := res.StatusCode, StatusServiceUnavailable; g != e { 2460 t.Errorf("got res.StatusCode %d; expected %d", g, e) 2461 } 2462 body, _ = io.ReadAll(res.Body) 2463 if !strings.Contains(string(body), "<title>Timeout</title>") { 2464 t.Errorf("expected timeout body; got %q", string(body)) 2465 } 2466 2467 // Now make the previously-timed out handler speak again, 2468 // which verifies the panic is handled: 2469 sendHi <- true 2470 if g, e := <-writeErrors, ErrHandlerTimeout; g != e { 2471 t.Errorf("expected Write error of %v; got %v", e, g) 2472 } 2473 } 2474 2475 // Issue 14568. 2476 func TestTimeoutHandlerStartTimerWhenServing(t *testing.T) { 2477 run(t, testTimeoutHandlerStartTimerWhenServing) 2478 } 2479 func testTimeoutHandlerStartTimerWhenServing(t *testing.T, mode testMode) { 2480 if testing.Short() { 2481 t.Skip("skipping sleeping test in -short mode") 2482 } 2483 var handler HandlerFunc = func(w ResponseWriter, _ *Request) { 2484 w.WriteHeader(StatusNoContent) 2485 } 2486 timeout := 300 * time.Millisecond 2487 ts := newClientServerTest(t, mode, TimeoutHandler(handler, timeout, "")).ts 2488 defer ts.Close() 2489 2490 c := ts.Client() 2491 2492 // Issue was caused by the timeout handler starting the timer when 2493 // was created, not when the request. So wait for more than the timeout 2494 // to ensure that's not the case. 2495 time.Sleep(2 * timeout) 2496 res, err := c.Get(ts.URL) 2497 if err != nil { 2498 t.Fatal(err) 2499 } 2500 defer res.Body.Close() 2501 if res.StatusCode != StatusNoContent { 2502 t.Errorf("got res.StatusCode %d, want %v", res.StatusCode, StatusNoContent) 2503 } 2504 } 2505 2506 func TestTimeoutHandlerContextCanceled(t *testing.T) { run(t, testTimeoutHandlerContextCanceled) } 2507 func testTimeoutHandlerContextCanceled(t *testing.T, mode testMode) { 2508 writeErrors := make(chan error, 1) 2509 sayHi := HandlerFunc(func(w ResponseWriter, r *Request) { 2510 w.Header().Set("Content-Type", "text/plain") 2511 var err error 2512 // The request context has already been canceled, but 2513 // retry the write for a while to give the timeout handler 2514 // a chance to notice. 2515 for i := 0; i < 100; i++ { 2516 _, err = w.Write([]byte("a")) 2517 if err != nil { 2518 break 2519 } 2520 time.Sleep(1 * time.Millisecond) 2521 } 2522 writeErrors <- err 2523 }) 2524 ctx, cancel := context.WithCancel(context.Background()) 2525 cancel() 2526 h := NewTestTimeoutHandler(sayHi, ctx) 2527 cst := newClientServerTest(t, mode, h) 2528 defer cst.close() 2529 2530 res, err := cst.c.Get(cst.ts.URL) 2531 if err != nil { 2532 t.Error(err) 2533 } 2534 if g, e := res.StatusCode, StatusServiceUnavailable; g != e { 2535 t.Errorf("got res.StatusCode %d; expected %d", g, e) 2536 } 2537 body, _ := io.ReadAll(res.Body) 2538 if g, e := string(body), ""; g != e { 2539 t.Errorf("got body %q; expected %q", g, e) 2540 } 2541 if g, e := <-writeErrors, context.Canceled; g != e { 2542 t.Errorf("got unexpected Write in handler: %v, want %g", g, e) 2543 } 2544 } 2545 2546 // https://golang.org/issue/15948 2547 func TestTimeoutHandlerEmptyResponse(t *testing.T) { run(t, testTimeoutHandlerEmptyResponse) } 2548 func testTimeoutHandlerEmptyResponse(t *testing.T, mode testMode) { 2549 var handler HandlerFunc = func(w ResponseWriter, _ *Request) { 2550 // No response. 2551 } 2552 timeout := 300 * time.Millisecond 2553 ts := newClientServerTest(t, mode, TimeoutHandler(handler, timeout, "")).ts 2554 2555 c := ts.Client() 2556 2557 res, err := c.Get(ts.URL) 2558 if err != nil { 2559 t.Fatal(err) 2560 } 2561 defer res.Body.Close() 2562 if res.StatusCode != StatusOK { 2563 t.Errorf("got res.StatusCode %d, want %v", res.StatusCode, StatusOK) 2564 } 2565 } 2566 2567 // https://golang.org/issues/22084 2568 func TestTimeoutHandlerPanicRecovery(t *testing.T) { 2569 wrapper := func(h Handler) Handler { 2570 return TimeoutHandler(h, time.Second, "") 2571 } 2572 run(t, func(t *testing.T, mode testMode) { 2573 testHandlerPanic(t, false, mode, wrapper, "intentional death for testing") 2574 }, testNotParallel) 2575 } 2576 2577 func TestRedirectBadPath(t *testing.T) { 2578 // This used to crash. It's not valid input (bad path), but it 2579 // shouldn't crash. 2580 rr := httptest.NewRecorder() 2581 req := &Request{ 2582 Method: "GET", 2583 URL: &url.URL{ 2584 Scheme: "http", 2585 Path: "not-empty-but-no-leading-slash", // bogus 2586 }, 2587 } 2588 Redirect(rr, req, "", 304) 2589 if rr.Code != 304 { 2590 t.Errorf("Code = %d; want 304", rr.Code) 2591 } 2592 } 2593 2594 // Test different URL formats and schemes 2595 func TestRedirect(t *testing.T) { 2596 req, _ := NewRequest("GET", "http://example.com/qux/", nil) 2597 2598 var tests = []struct { 2599 in string 2600 want string 2601 }{ 2602 // normal http 2603 {"http://foobar.com/baz", "http://foobar.com/baz"}, 2604 // normal https 2605 {"https://foobar.com/baz", "https://foobar.com/baz"}, 2606 // custom scheme 2607 {"test://foobar.com/baz", "test://foobar.com/baz"}, 2608 // schemeless 2609 {"//foobar.com/baz", "//foobar.com/baz"}, 2610 // relative to the root 2611 {"/foobar.com/baz", "/foobar.com/baz"}, 2612 // relative to the current path 2613 {"foobar.com/baz", "/qux/foobar.com/baz"}, 2614 // relative to the current path (+ going upwards) 2615 {"../quux/foobar.com/baz", "/quux/foobar.com/baz"}, 2616 // incorrect number of slashes 2617 {"///foobar.com/baz", "/foobar.com/baz"}, 2618 2619 // Verifies we don't path.Clean() on the wrong parts in redirects: 2620 {"/foo?next=http://bar.com/", "/foo?next=http://bar.com/"}, 2621 {"http://localhost:8080/_ah/login?continue=http://localhost:8080/", 2622 "http://localhost:8080/_ah/login?continue=http://localhost:8080/"}, 2623 2624 {"/фубар", "/%d1%84%d1%83%d0%b1%d0%b0%d1%80"}, 2625 {"http://foo.com/фубар", "http://foo.com/%d1%84%d1%83%d0%b1%d0%b0%d1%80"}, 2626 } 2627 2628 for _, tt := range tests { 2629 rec := httptest.NewRecorder() 2630 Redirect(rec, req, tt.in, 302) 2631 if got, want := rec.Code, 302; got != want { 2632 t.Errorf("Redirect(%q) generated status code %v; want %v", tt.in, got, want) 2633 } 2634 if got := rec.Header().Get("Location"); got != tt.want { 2635 t.Errorf("Redirect(%q) generated Location header %q; want %q", tt.in, got, tt.want) 2636 } 2637 } 2638 } 2639 2640 // Test that Redirect sets Content-Type header for GET and HEAD requests 2641 // and writes a short HTML body, unless the request already has a Content-Type header. 2642 func TestRedirectContentTypeAndBody(t *testing.T) { 2643 type ctHeader struct { 2644 Values []string 2645 } 2646 2647 var tests = []struct { 2648 method string 2649 ct *ctHeader // Optional Content-Type header to set. 2650 wantCT string 2651 wantBody string 2652 }{ 2653 {MethodGet, nil, "text/html; charset=utf-8", "<a href=\"/foo\">Found</a>.\n\n"}, 2654 {MethodHead, nil, "text/html; charset=utf-8", ""}, 2655 {MethodPost, nil, "", ""}, 2656 {MethodDelete, nil, "", ""}, 2657 {"foo", nil, "", ""}, 2658 {MethodGet, &ctHeader{[]string{"application/test"}}, "application/test", ""}, 2659 {MethodGet, &ctHeader{[]string{}}, "", ""}, 2660 {MethodGet, &ctHeader{nil}, "", ""}, 2661 } 2662 for _, tt := range tests { 2663 req := httptest.NewRequest(tt.method, "http://example.com/qux/", nil) 2664 rec := httptest.NewRecorder() 2665 if tt.ct != nil { 2666 rec.Header()["Content-Type"] = tt.ct.Values 2667 } 2668 Redirect(rec, req, "/foo", 302) 2669 if got, want := rec.Code, 302; got != want { 2670 t.Errorf("Redirect(%q, %#v) generated status code %v; want %v", tt.method, tt.ct, got, want) 2671 } 2672 if got, want := rec.Header().Get("Content-Type"), tt.wantCT; got != want { 2673 t.Errorf("Redirect(%q, %#v) generated Content-Type header %q; want %q", tt.method, tt.ct, got, want) 2674 } 2675 resp := rec.Result() 2676 body, err := io.ReadAll(resp.Body) 2677 if err != nil { 2678 t.Fatal(err) 2679 } 2680 if got, want := string(body), tt.wantBody; got != want { 2681 t.Errorf("Redirect(%q, %#v) generated Body %q; want %q", tt.method, tt.ct, got, want) 2682 } 2683 } 2684 } 2685 2686 // TestZeroLengthPostAndResponse exercises an optimization done by the Transport: 2687 // when there is no body (either because the method doesn't permit a body, or an 2688 // explicit Content-Length of zero is present), then the transport can re-use the 2689 // connection immediately. But when it re-uses the connection, it typically closes 2690 // the previous request's body, which is not optimal for zero-lengthed bodies, 2691 // as the client would then see http.ErrBodyReadAfterClose and not 0, io.EOF. 2692 func TestZeroLengthPostAndResponse(t *testing.T) { run(t, testZeroLengthPostAndResponse) } 2693 2694 func testZeroLengthPostAndResponse(t *testing.T, mode testMode) { 2695 cst := newClientServerTest(t, mode, HandlerFunc(func(rw ResponseWriter, r *Request) { 2696 all, err := io.ReadAll(r.Body) 2697 if err != nil { 2698 t.Fatalf("handler ReadAll: %v", err) 2699 } 2700 if len(all) != 0 { 2701 t.Errorf("handler got %d bytes; expected 0", len(all)) 2702 } 2703 rw.Header().Set("Content-Length", "0") 2704 })) 2705 2706 req, err := NewRequest("POST", cst.ts.URL, strings.NewReader("")) 2707 if err != nil { 2708 t.Fatal(err) 2709 } 2710 req.ContentLength = 0 2711 2712 var resp [5]*Response 2713 for i := range resp { 2714 resp[i], err = cst.c.Do(req) 2715 if err != nil { 2716 t.Fatalf("client post #%d: %v", i, err) 2717 } 2718 } 2719 2720 for i := range resp { 2721 all, err := io.ReadAll(resp[i].Body) 2722 if err != nil { 2723 t.Fatalf("req #%d: client ReadAll: %v", i, err) 2724 } 2725 if len(all) != 0 { 2726 t.Errorf("req #%d: client got %d bytes; expected 0", i, len(all)) 2727 } 2728 } 2729 } 2730 2731 func TestHandlerPanicNil(t *testing.T) { 2732 run(t, func(t *testing.T, mode testMode) { 2733 testHandlerPanic(t, false, mode, nil, nil) 2734 }, testNotParallel) 2735 } 2736 2737 func TestHandlerPanic(t *testing.T) { 2738 run(t, func(t *testing.T, mode testMode) { 2739 testHandlerPanic(t, false, mode, nil, "intentional death for testing") 2740 }, testNotParallel) 2741 } 2742 2743 func TestHandlerPanicWithHijack(t *testing.T) { 2744 // Only testing HTTP/1, and our http2 server doesn't support hijacking. 2745 run(t, func(t *testing.T, mode testMode) { 2746 testHandlerPanic(t, true, mode, nil, "intentional death for testing") 2747 }, []testMode{http1Mode}) 2748 } 2749 2750 func testHandlerPanic(t *testing.T, withHijack bool, mode testMode, wrapper func(Handler) Handler, panicValue any) { 2751 // Direct log output to a pipe. 2752 // 2753 // We read from the pipe to verify that the handler actually caught the panic 2754 // and logged something. 2755 // 2756 // We use a pipe rather than a buffer, because when testing connection hijacking 2757 // server shutdown doesn't wait for the hijacking handler to return, so the 2758 // log may occur after the server has shut down. 2759 pr, pw := io.Pipe() 2760 defer pw.Close() 2761 2762 var handler Handler = HandlerFunc(func(w ResponseWriter, r *Request) { 2763 if withHijack { 2764 rwc, _, err := w.(Hijacker).Hijack() 2765 if err != nil { 2766 t.Logf("unexpected error: %v", err) 2767 } 2768 defer rwc.Close() 2769 } 2770 panic(panicValue) 2771 }) 2772 if wrapper != nil { 2773 handler = wrapper(handler) 2774 } 2775 cst := newClientServerTest(t, mode, handler, func(ts *httptest.Server) { 2776 ts.Config.ErrorLog = log.New(pw, "", 0) 2777 }) 2778 2779 // Do a blocking read on the log output pipe. 2780 done := make(chan bool, 1) 2781 go func() { 2782 buf := make([]byte, 4<<10) 2783 _, err := pr.Read(buf) 2784 pr.Close() 2785 if err != nil && err != io.EOF { 2786 t.Error(err) 2787 } 2788 done <- true 2789 }() 2790 2791 _, err := cst.c.Get(cst.ts.URL) 2792 if err == nil { 2793 t.Logf("expected an error") 2794 } 2795 2796 if panicValue == nil { 2797 return 2798 } 2799 2800 <-done 2801 } 2802 2803 type terrorWriter struct{ t *testing.T } 2804 2805 func (w terrorWriter) Write(p []byte) (int, error) { 2806 w.t.Errorf("%s", p) 2807 return len(p), nil 2808 } 2809 2810 // Issue 16456: allow writing 0 bytes on hijacked conn to test hijack 2811 // without any log spam. 2812 func TestServerWriteHijackZeroBytes(t *testing.T) { 2813 run(t, testServerWriteHijackZeroBytes, []testMode{http1Mode}) 2814 } 2815 func testServerWriteHijackZeroBytes(t *testing.T, mode testMode) { 2816 done := make(chan struct{}) 2817 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 2818 defer close(done) 2819 w.(Flusher).Flush() 2820 conn, _, err := w.(Hijacker).Hijack() 2821 if err != nil { 2822 t.Errorf("Hijack: %v", err) 2823 return 2824 } 2825 defer conn.Close() 2826 _, err = w.Write(nil) 2827 if err != ErrHijacked { 2828 t.Errorf("Write error = %v; want ErrHijacked", err) 2829 } 2830 }), func(ts *httptest.Server) { 2831 ts.Config.ErrorLog = log.New(terrorWriter{t}, "Unexpected write: ", 0) 2832 }).ts 2833 2834 c := ts.Client() 2835 res, err := c.Get(ts.URL) 2836 if err != nil { 2837 t.Fatal(err) 2838 } 2839 res.Body.Close() 2840 <-done 2841 } 2842 2843 func TestServerNoDate(t *testing.T) { 2844 run(t, func(t *testing.T, mode testMode) { 2845 testServerNoHeader(t, mode, "Date") 2846 }) 2847 } 2848 2849 func TestServerContentType(t *testing.T) { 2850 run(t, func(t *testing.T, mode testMode) { 2851 testServerNoHeader(t, mode, "Content-Type") 2852 }) 2853 } 2854 2855 func testServerNoHeader(t *testing.T, mode testMode, header string) { 2856 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 2857 w.Header()[header] = nil 2858 io.WriteString(w, "<html>foo</html>") // non-empty 2859 })) 2860 res, err := cst.c.Get(cst.ts.URL) 2861 if err != nil { 2862 t.Fatal(err) 2863 } 2864 res.Body.Close() 2865 if got, ok := res.Header[header]; ok { 2866 t.Fatalf("Expected no %s header; got %q", header, got) 2867 } 2868 } 2869 2870 func TestStripPrefix(t *testing.T) { run(t, testStripPrefix) } 2871 func testStripPrefix(t *testing.T, mode testMode) { 2872 h := HandlerFunc(func(w ResponseWriter, r *Request) { 2873 w.Header().Set("X-Path", r.URL.Path) 2874 w.Header().Set("X-RawPath", r.URL.RawPath) 2875 }) 2876 ts := newClientServerTest(t, mode, StripPrefix("/foo/bar", h)).ts 2877 2878 c := ts.Client() 2879 2880 cases := []struct { 2881 reqPath string 2882 path string // If empty we want a 404. 2883 rawPath string 2884 }{ 2885 {"/foo/bar/qux", "/qux", ""}, 2886 {"/foo/bar%2Fqux", "/qux", "%2Fqux"}, 2887 {"/foo%2Fbar/qux", "", ""}, // Escaped prefix does not match. 2888 {"/bar", "", ""}, // No prefix match. 2889 } 2890 for _, tc := range cases { 2891 t.Run(tc.reqPath, func(t *testing.T) { 2892 res, err := c.Get(ts.URL + tc.reqPath) 2893 if err != nil { 2894 t.Fatal(err) 2895 } 2896 res.Body.Close() 2897 if tc.path == "" { 2898 if res.StatusCode != StatusNotFound { 2899 t.Errorf("got %q, want 404 Not Found", res.Status) 2900 } 2901 return 2902 } 2903 if res.StatusCode != StatusOK { 2904 t.Fatalf("got %q, want 200 OK", res.Status) 2905 } 2906 if g, w := res.Header.Get("X-Path"), tc.path; g != w { 2907 t.Errorf("got Path %q, want %q", g, w) 2908 } 2909 if g, w := res.Header.Get("X-RawPath"), tc.rawPath; g != w { 2910 t.Errorf("got RawPath %q, want %q", g, w) 2911 } 2912 }) 2913 } 2914 } 2915 2916 // https://golang.org/issue/18952. 2917 func TestStripPrefixNotModifyRequest(t *testing.T) { 2918 h := StripPrefix("/foo", NotFoundHandler()) 2919 req := httptest.NewRequest("GET", "/foo/bar", nil) 2920 h.ServeHTTP(httptest.NewRecorder(), req) 2921 if req.URL.Path != "/foo/bar" { 2922 t.Errorf("StripPrefix should not modify the provided Request, but it did") 2923 } 2924 } 2925 2926 func TestRequestLimit(t *testing.T) { run(t, testRequestLimit) } 2927 func testRequestLimit(t *testing.T, mode testMode) { 2928 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 2929 t.Fatalf("didn't expect to get request in Handler") 2930 }), optQuietLog) 2931 req, _ := NewRequest("GET", cst.ts.URL, nil) 2932 var bytesPerHeader = len("header12345: val12345\r\n") 2933 for i := 0; i < ((DefaultMaxHeaderBytes+4096)/bytesPerHeader)+1; i++ { 2934 req.Header.Set(fmt.Sprintf("header%05d", i), fmt.Sprintf("val%05d", i)) 2935 } 2936 res, err := cst.c.Do(req) 2937 if res != nil { 2938 defer res.Body.Close() 2939 } 2940 if mode == http2Mode { 2941 // In HTTP/2, the result depends on a race. If the client has received the 2942 // server's SETTINGS before RoundTrip starts sending the request, then RoundTrip 2943 // will fail with an error. Otherwise, the client should receive a 431 from the 2944 // server. 2945 if err == nil && res.StatusCode != 431 { 2946 t.Fatalf("expected 431 response status; got: %d %s", res.StatusCode, res.Status) 2947 } 2948 } else { 2949 // In HTTP/1, we expect a 431 from the server. 2950 // Some HTTP clients may fail on this undefined behavior (server replying and 2951 // closing the connection while the request is still being written), but 2952 // we do support it (at least currently), so we expect a response below. 2953 if err != nil { 2954 t.Fatalf("Do: %v", err) 2955 } 2956 if res.StatusCode != 431 { 2957 t.Fatalf("expected 431 response status; got: %d %s", res.StatusCode, res.Status) 2958 } 2959 } 2960 } 2961 2962 type neverEnding byte 2963 2964 func (b neverEnding) Read(p []byte) (n int, err error) { 2965 for i := range p { 2966 p[i] = byte(b) 2967 } 2968 return len(p), nil 2969 } 2970 2971 type countReader struct { 2972 r io.Reader 2973 n *int64 2974 } 2975 2976 func (cr countReader) Read(p []byte) (n int, err error) { 2977 n, err = cr.r.Read(p) 2978 atomic.AddInt64(cr.n, int64(n)) 2979 return 2980 } 2981 2982 func TestRequestBodyLimit(t *testing.T) { run(t, testRequestBodyLimit) } 2983 func testRequestBodyLimit(t *testing.T, mode testMode) { 2984 const limit = 1 << 20 2985 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 2986 r.Body = MaxBytesReader(w, r.Body, limit) 2987 n, err := io.Copy(io.Discard, r.Body) 2988 if err == nil { 2989 t.Errorf("expected error from io.Copy") 2990 } 2991 if n != limit { 2992 t.Errorf("io.Copy = %d, want %d", n, limit) 2993 } 2994 mbErr, ok := err.(*MaxBytesError) 2995 if !ok { 2996 t.Errorf("expected MaxBytesError, got %T", err) 2997 } 2998 if mbErr.Limit != limit { 2999 t.Errorf("MaxBytesError.Limit = %d, want %d", mbErr.Limit, limit) 3000 } 3001 })) 3002 3003 nWritten := new(int64) 3004 req, _ := NewRequest("POST", cst.ts.URL, io.LimitReader(countReader{neverEnding('a'), nWritten}, limit*200)) 3005 3006 // Send the POST, but don't care it succeeds or not. The 3007 // remote side is going to reply and then close the TCP 3008 // connection, and HTTP doesn't really define if that's 3009 // allowed or not. Some HTTP clients will get the response 3010 // and some (like ours, currently) will complain that the 3011 // request write failed, without reading the response. 3012 // 3013 // But that's okay, since what we're really testing is that 3014 // the remote side hung up on us before we wrote too much. 3015 _, _ = cst.c.Do(req) 3016 3017 if atomic.LoadInt64(nWritten) > limit*100 { 3018 t.Errorf("handler restricted the request body to %d bytes, but client managed to write %d", 3019 limit, nWritten) 3020 } 3021 } 3022 3023 // TestClientWriteShutdown tests that if the client shuts down the write 3024 // side of their TCP connection, the server doesn't send a 400 Bad Request. 3025 func TestClientWriteShutdown(t *testing.T) { run(t, testClientWriteShutdown) } 3026 func testClientWriteShutdown(t *testing.T, mode testMode) { 3027 if runtime.GOOS == "plan9" { 3028 t.Skip("skipping test; see https://golang.org/issue/17906") 3029 } 3030 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {})).ts 3031 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 3032 if err != nil { 3033 t.Fatalf("Dial: %v", err) 3034 } 3035 err = conn.(*net.TCPConn).CloseWrite() 3036 if err != nil { 3037 t.Fatalf("CloseWrite: %v", err) 3038 } 3039 3040 bs, err := io.ReadAll(conn) 3041 if err != nil { 3042 t.Errorf("ReadAll: %v", err) 3043 } 3044 got := string(bs) 3045 if got != "" { 3046 t.Errorf("read %q from server; want nothing", got) 3047 } 3048 } 3049 3050 // Tests that chunked server responses that write 1 byte at a time are 3051 // buffered before chunk headers are added, not after chunk headers. 3052 func TestServerBufferedChunking(t *testing.T) { 3053 conn := new(testConn) 3054 conn.readBuf.Write([]byte("GET / HTTP/1.1\r\nHost: foo\r\n\r\n")) 3055 conn.closec = make(chan bool, 1) 3056 ls := &oneConnListener{conn} 3057 go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) { 3058 rw.(Flusher).Flush() // force the Header to be sent, in chunking mode, not counting the length 3059 rw.Write([]byte{'x'}) 3060 rw.Write([]byte{'y'}) 3061 rw.Write([]byte{'z'}) 3062 })) 3063 <-conn.closec 3064 if !bytes.HasSuffix(conn.writeBuf.Bytes(), []byte("\r\n\r\n3\r\nxyz\r\n0\r\n\r\n")) { 3065 t.Errorf("response didn't end with a single 3 byte 'xyz' chunk; got:\n%q", 3066 conn.writeBuf.Bytes()) 3067 } 3068 } 3069 3070 // Tests that the server flushes its response headers out when it's 3071 // ignoring the response body and waits a bit before forcefully 3072 // closing the TCP connection, causing the client to get a RST. 3073 // See https://golang.org/issue/3595 3074 func TestServerGracefulClose(t *testing.T) { 3075 run(t, testServerGracefulClose, []testMode{http1Mode}) 3076 } 3077 func testServerGracefulClose(t *testing.T, mode testMode) { 3078 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 3079 Error(w, "bye", StatusUnauthorized) 3080 })).ts 3081 3082 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 3083 if err != nil { 3084 t.Fatal(err) 3085 } 3086 defer conn.Close() 3087 const bodySize = 5 << 20 3088 req := []byte(fmt.Sprintf("POST / HTTP/1.1\r\nHost: foo.com\r\nContent-Length: %d\r\n\r\n", bodySize)) 3089 for i := 0; i < bodySize; i++ { 3090 req = append(req, 'x') 3091 } 3092 writeErr := make(chan error) 3093 go func() { 3094 _, err := conn.Write(req) 3095 writeErr <- err 3096 }() 3097 br := bufio.NewReader(conn) 3098 lineNum := 0 3099 for { 3100 line, err := br.ReadString('\n') 3101 if err == io.EOF { 3102 break 3103 } 3104 if err != nil { 3105 t.Fatalf("ReadLine: %v", err) 3106 } 3107 lineNum++ 3108 if lineNum == 1 && !strings.Contains(line, "401 Unauthorized") { 3109 t.Errorf("Response line = %q; want a 401", line) 3110 } 3111 } 3112 // Wait for write to finish. This is a broken pipe on both 3113 // Darwin and Linux, but checking this isn't the point of 3114 // the test. 3115 <-writeErr 3116 } 3117 3118 func TestCaseSensitiveMethod(t *testing.T) { run(t, testCaseSensitiveMethod) } 3119 func testCaseSensitiveMethod(t *testing.T, mode testMode) { 3120 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 3121 if r.Method != "get" { 3122 t.Errorf(`Got method %q; want "get"`, r.Method) 3123 } 3124 })) 3125 defer cst.close() 3126 req, _ := NewRequest("get", cst.ts.URL, nil) 3127 res, err := cst.c.Do(req) 3128 if err != nil { 3129 t.Error(err) 3130 return 3131 } 3132 3133 res.Body.Close() 3134 } 3135 3136 // TestContentLengthZero tests that for both an HTTP/1.0 and HTTP/1.1 3137 // request (both keep-alive), when a Handler never writes any 3138 // response, the net/http package adds a "Content-Length: 0" response 3139 // header. 3140 func TestContentLengthZero(t *testing.T) { 3141 run(t, testContentLengthZero, []testMode{http1Mode}) 3142 } 3143 func testContentLengthZero(t *testing.T, mode testMode) { 3144 ts := newClientServerTest(t, mode, HandlerFunc(func(rw ResponseWriter, req *Request) {})).ts 3145 3146 for _, version := range []string{"HTTP/1.0", "HTTP/1.1"} { 3147 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 3148 if err != nil { 3149 t.Fatalf("error dialing: %v", err) 3150 } 3151 _, err = fmt.Fprintf(conn, "GET / %v\r\nConnection: keep-alive\r\nHost: foo\r\n\r\n", version) 3152 if err != nil { 3153 t.Fatalf("error writing: %v", err) 3154 } 3155 req, _ := NewRequest("GET", "/", nil) 3156 res, err := ReadResponse(bufio.NewReader(conn), req) 3157 if err != nil { 3158 t.Fatalf("error reading response: %v", err) 3159 } 3160 if te := res.TransferEncoding; len(te) > 0 { 3161 t.Errorf("For version %q, Transfer-Encoding = %q; want none", version, te) 3162 } 3163 if cl := res.ContentLength; cl != 0 { 3164 t.Errorf("For version %q, Content-Length = %v; want 0", version, cl) 3165 } 3166 conn.Close() 3167 } 3168 } 3169 3170 func TestCloseNotifier(t *testing.T) { 3171 run(t, testCloseNotifier, []testMode{http1Mode}) 3172 } 3173 func testCloseNotifier(t *testing.T, mode testMode) { 3174 gotReq := make(chan bool, 1) 3175 sawClose := make(chan bool, 1) 3176 ts := newClientServerTest(t, mode, HandlerFunc(func(rw ResponseWriter, req *Request) { 3177 gotReq <- true 3178 cc := rw.(CloseNotifier).CloseNotify() 3179 <-cc 3180 sawClose <- true 3181 })).ts 3182 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 3183 if err != nil { 3184 t.Fatalf("error dialing: %v", err) 3185 } 3186 diec := make(chan bool) 3187 go func() { 3188 _, err = fmt.Fprintf(conn, "GET / HTTP/1.1\r\nConnection: keep-alive\r\nHost: foo\r\n\r\n") 3189 if err != nil { 3190 t.Error(err) 3191 return 3192 } 3193 <-diec 3194 conn.Close() 3195 }() 3196 For: 3197 for { 3198 select { 3199 case <-gotReq: 3200 diec <- true 3201 case <-sawClose: 3202 break For 3203 } 3204 } 3205 ts.Close() 3206 } 3207 3208 // Tests that a pipelined request does not cause the first request's 3209 // Handler's CloseNotify channel to fire. 3210 // 3211 // Issue 13165 (where it used to deadlock), but behavior changed in Issue 23921. 3212 func TestCloseNotifierPipelined(t *testing.T) { 3213 run(t, testCloseNotifierPipelined, []testMode{http1Mode}) 3214 } 3215 func testCloseNotifierPipelined(t *testing.T, mode testMode) { 3216 gotReq := make(chan bool, 2) 3217 sawClose := make(chan bool, 2) 3218 ts := newClientServerTest(t, mode, HandlerFunc(func(rw ResponseWriter, req *Request) { 3219 gotReq <- true 3220 cc := rw.(CloseNotifier).CloseNotify() 3221 select { 3222 case <-cc: 3223 t.Error("unexpected CloseNotify") 3224 case <-time.After(100 * time.Millisecond): 3225 } 3226 sawClose <- true 3227 })).ts 3228 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 3229 if err != nil { 3230 t.Fatalf("error dialing: %v", err) 3231 } 3232 diec := make(chan bool, 1) 3233 defer close(diec) 3234 go func() { 3235 const req = "GET / HTTP/1.1\r\nConnection: keep-alive\r\nHost: foo\r\n\r\n" 3236 _, err = io.WriteString(conn, req+req) // two requests 3237 if err != nil { 3238 t.Error(err) 3239 return 3240 } 3241 <-diec 3242 conn.Close() 3243 }() 3244 reqs := 0 3245 closes := 0 3246 for { 3247 select { 3248 case <-gotReq: 3249 reqs++ 3250 if reqs > 2 { 3251 t.Fatal("too many requests") 3252 } 3253 case <-sawClose: 3254 closes++ 3255 if closes > 1 { 3256 return 3257 } 3258 } 3259 } 3260 } 3261 3262 func TestCloseNotifierChanLeak(t *testing.T) { 3263 defer afterTest(t) 3264 req := reqBytes("GET / HTTP/1.0\nHost: golang.org") 3265 for i := 0; i < 20; i++ { 3266 var output bytes.Buffer 3267 conn := &rwTestConn{ 3268 Reader: bytes.NewReader(req), 3269 Writer: &output, 3270 closec: make(chan bool, 1), 3271 } 3272 ln := &oneConnListener{conn: conn} 3273 handler := HandlerFunc(func(rw ResponseWriter, r *Request) { 3274 // Ignore the return value and never read from 3275 // it, testing that we don't leak goroutines 3276 // on the sending side: 3277 _ = rw.(CloseNotifier).CloseNotify() 3278 }) 3279 go Serve(ln, handler) 3280 <-conn.closec 3281 } 3282 } 3283 3284 // Tests that we can use CloseNotifier in one request, and later call Hijack 3285 // on a second request on the same connection. 3286 // 3287 // It also tests that the connReader stitches together its background 3288 // 1-byte read for CloseNotifier when CloseNotifier doesn't fire with 3289 // the rest of the second HTTP later. 3290 // 3291 // Issue 9763. 3292 // HTTP/1-only test. (http2 doesn't have Hijack) 3293 func TestHijackAfterCloseNotifier(t *testing.T) { 3294 run(t, testHijackAfterCloseNotifier, []testMode{http1Mode}) 3295 } 3296 func testHijackAfterCloseNotifier(t *testing.T, mode testMode) { 3297 script := make(chan string, 2) 3298 script <- "closenotify" 3299 script <- "hijack" 3300 close(script) 3301 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 3302 plan := <-script 3303 switch plan { 3304 default: 3305 panic("bogus plan; too many requests") 3306 case "closenotify": 3307 w.(CloseNotifier).CloseNotify() // discard result 3308 w.Header().Set("X-Addr", r.RemoteAddr) 3309 case "hijack": 3310 c, _, err := w.(Hijacker).Hijack() 3311 if err != nil { 3312 t.Errorf("Hijack in Handler: %v", err) 3313 return 3314 } 3315 if _, ok := c.(*net.TCPConn); !ok { 3316 // Verify it's not wrapped in some type. 3317 // Not strictly a go1 compat issue, but in practice it probably is. 3318 t.Errorf("type of hijacked conn is %T; want *net.TCPConn", c) 3319 } 3320 fmt.Fprintf(c, "HTTP/1.0 200 OK\r\nX-Addr: %v\r\nContent-Length: 0\r\n\r\n", r.RemoteAddr) 3321 c.Close() 3322 return 3323 } 3324 })).ts 3325 res1, err := ts.Client().Get(ts.URL) 3326 if err != nil { 3327 log.Fatal(err) 3328 } 3329 res2, err := ts.Client().Get(ts.URL) 3330 if err != nil { 3331 log.Fatal(err) 3332 } 3333 addr1 := res1.Header.Get("X-Addr") 3334 addr2 := res2.Header.Get("X-Addr") 3335 if addr1 == "" || addr1 != addr2 { 3336 t.Errorf("addr1, addr2 = %q, %q; want same", addr1, addr2) 3337 } 3338 } 3339 3340 func TestHijackBeforeRequestBodyRead(t *testing.T) { 3341 run(t, testHijackBeforeRequestBodyRead, []testMode{http1Mode}) 3342 } 3343 func testHijackBeforeRequestBodyRead(t *testing.T, mode testMode) { 3344 var requestBody = bytes.Repeat([]byte("a"), 1<<20) 3345 bodyOkay := make(chan bool, 1) 3346 gotCloseNotify := make(chan bool, 1) 3347 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 3348 defer close(bodyOkay) // caller will read false if nothing else 3349 3350 reqBody := r.Body 3351 r.Body = nil // to test that server.go doesn't use this value. 3352 3353 gone := w.(CloseNotifier).CloseNotify() 3354 slurp, err := io.ReadAll(reqBody) 3355 if err != nil { 3356 t.Errorf("Body read: %v", err) 3357 return 3358 } 3359 if len(slurp) != len(requestBody) { 3360 t.Errorf("Backend read %d request body bytes; want %d", len(slurp), len(requestBody)) 3361 return 3362 } 3363 if !bytes.Equal(slurp, requestBody) { 3364 t.Error("Backend read wrong request body.") // 1MB; omitting details 3365 return 3366 } 3367 bodyOkay <- true 3368 <-gone 3369 gotCloseNotify <- true 3370 })).ts 3371 3372 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 3373 if err != nil { 3374 t.Fatal(err) 3375 } 3376 defer conn.Close() 3377 3378 fmt.Fprintf(conn, "POST / HTTP/1.1\r\nHost: foo\r\nContent-Length: %d\r\n\r\n%s", 3379 len(requestBody), requestBody) 3380 if !<-bodyOkay { 3381 // already failed. 3382 return 3383 } 3384 conn.Close() 3385 <-gotCloseNotify 3386 } 3387 3388 func TestOptions(t *testing.T) { run(t, testOptions, []testMode{http1Mode}) } 3389 func testOptions(t *testing.T, mode testMode) { 3390 uric := make(chan string, 2) // only expect 1, but leave space for 2 3391 mux := NewServeMux() 3392 mux.HandleFunc("/", func(w ResponseWriter, r *Request) { 3393 uric <- r.RequestURI 3394 }) 3395 ts := newClientServerTest(t, mode, mux).ts 3396 3397 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 3398 if err != nil { 3399 t.Fatal(err) 3400 } 3401 defer conn.Close() 3402 3403 // An OPTIONS * request should succeed. 3404 _, err = conn.Write([]byte("OPTIONS * HTTP/1.1\r\nHost: foo.com\r\n\r\n")) 3405 if err != nil { 3406 t.Fatal(err) 3407 } 3408 br := bufio.NewReader(conn) 3409 res, err := ReadResponse(br, &Request{Method: "OPTIONS"}) 3410 if err != nil { 3411 t.Fatal(err) 3412 } 3413 if res.StatusCode != 200 { 3414 t.Errorf("Got non-200 response to OPTIONS *: %#v", res) 3415 } 3416 3417 // A GET * request on a ServeMux should fail. 3418 _, err = conn.Write([]byte("GET * HTTP/1.1\r\nHost: foo.com\r\n\r\n")) 3419 if err != nil { 3420 t.Fatal(err) 3421 } 3422 res, err = ReadResponse(br, &Request{Method: "GET"}) 3423 if err != nil { 3424 t.Fatal(err) 3425 } 3426 if res.StatusCode != 400 { 3427 t.Errorf("Got non-400 response to GET *: %#v", res) 3428 } 3429 3430 res, err = Get(ts.URL + "/second") 3431 if err != nil { 3432 t.Fatal(err) 3433 } 3434 res.Body.Close() 3435 if got := <-uric; got != "/second" { 3436 t.Errorf("Handler saw request for %q; want /second", got) 3437 } 3438 } 3439 3440 func TestOptionsHandler(t *testing.T) { run(t, testOptionsHandler, []testMode{http1Mode}) } 3441 func testOptionsHandler(t *testing.T, mode testMode) { 3442 rc := make(chan *Request, 1) 3443 3444 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 3445 rc <- r 3446 }), func(ts *httptest.Server) { 3447 ts.Config.DisableGeneralOptionsHandler = true 3448 }).ts 3449 3450 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 3451 if err != nil { 3452 t.Fatal(err) 3453 } 3454 defer conn.Close() 3455 3456 _, err = conn.Write([]byte("OPTIONS * HTTP/1.1\r\nHost: foo.com\r\n\r\n")) 3457 if err != nil { 3458 t.Fatal(err) 3459 } 3460 3461 if got := <-rc; got.Method != "OPTIONS" || got.RequestURI != "*" { 3462 t.Errorf("Expected OPTIONS * request, got %v", got) 3463 } 3464 } 3465 3466 // Tests regarding the ordering of Write, WriteHeader, Header, and 3467 // Flush calls. In Go 1.0, rw.WriteHeader immediately flushed the 3468 // (*response).header to the wire. In Go 1.1, the actual wire flush is 3469 // delayed, so we could maybe tack on a Content-Length and better 3470 // Content-Type after we see more (or all) of the output. To preserve 3471 // compatibility with Go 1, we need to be careful to track which 3472 // headers were live at the time of WriteHeader, so we write the same 3473 // ones, even if the handler modifies them (~erroneously) after the 3474 // first Write. 3475 func TestHeaderToWire(t *testing.T) { 3476 tests := []struct { 3477 name string 3478 handler func(ResponseWriter, *Request) 3479 check func(got, logs string) error 3480 }{ 3481 { 3482 name: "write without Header", 3483 handler: func(rw ResponseWriter, r *Request) { 3484 rw.Write([]byte("hello world")) 3485 }, 3486 check: func(got, logs string) error { 3487 if !strings.Contains(got, "Content-Length:") { 3488 return errors.New("no content-length") 3489 } 3490 if !strings.Contains(got, "Content-Type: text/plain") { 3491 return errors.New("no content-type") 3492 } 3493 return nil 3494 }, 3495 }, 3496 { 3497 name: "Header mutation before write", 3498 handler: func(rw ResponseWriter, r *Request) { 3499 h := rw.Header() 3500 h.Set("Content-Type", "some/type") 3501 rw.Write([]byte("hello world")) 3502 h.Set("Too-Late", "bogus") 3503 }, 3504 check: func(got, logs string) error { 3505 if !strings.Contains(got, "Content-Length:") { 3506 return errors.New("no content-length") 3507 } 3508 if !strings.Contains(got, "Content-Type: some/type") { 3509 return errors.New("wrong content-type") 3510 } 3511 if strings.Contains(got, "Too-Late") { 3512 return errors.New("don't want too-late header") 3513 } 3514 return nil 3515 }, 3516 }, 3517 { 3518 name: "write then useless Header mutation", 3519 handler: func(rw ResponseWriter, r *Request) { 3520 rw.Write([]byte("hello world")) 3521 rw.Header().Set("Too-Late", "Write already wrote headers") 3522 }, 3523 check: func(got, logs string) error { 3524 if strings.Contains(got, "Too-Late") { 3525 return errors.New("header appeared from after WriteHeader") 3526 } 3527 return nil 3528 }, 3529 }, 3530 { 3531 name: "flush then write", 3532 handler: func(rw ResponseWriter, r *Request) { 3533 rw.(Flusher).Flush() 3534 rw.Write([]byte("post-flush")) 3535 rw.Header().Set("Too-Late", "Write already wrote headers") 3536 }, 3537 check: func(got, logs string) error { 3538 if !strings.Contains(got, "Transfer-Encoding: chunked") { 3539 return errors.New("not chunked") 3540 } 3541 if strings.Contains(got, "Too-Late") { 3542 return errors.New("header appeared from after WriteHeader") 3543 } 3544 return nil 3545 }, 3546 }, 3547 { 3548 name: "header then flush", 3549 handler: func(rw ResponseWriter, r *Request) { 3550 rw.Header().Set("Content-Type", "some/type") 3551 rw.(Flusher).Flush() 3552 rw.Write([]byte("post-flush")) 3553 rw.Header().Set("Too-Late", "Write already wrote headers") 3554 }, 3555 check: func(got, logs string) error { 3556 if !strings.Contains(got, "Transfer-Encoding: chunked") { 3557 return errors.New("not chunked") 3558 } 3559 if strings.Contains(got, "Too-Late") { 3560 return errors.New("header appeared from after WriteHeader") 3561 } 3562 if !strings.Contains(got, "Content-Type: some/type") { 3563 return errors.New("wrong content-type") 3564 } 3565 return nil 3566 }, 3567 }, 3568 { 3569 name: "sniff-on-first-write content-type", 3570 handler: func(rw ResponseWriter, r *Request) { 3571 rw.Write([]byte("<html><head></head><body>some html</body></html>")) 3572 rw.Header().Set("Content-Type", "x/wrong") 3573 }, 3574 check: func(got, logs string) error { 3575 if !strings.Contains(got, "Content-Type: text/html") { 3576 return errors.New("wrong content-type; want html") 3577 } 3578 return nil 3579 }, 3580 }, 3581 { 3582 name: "explicit content-type wins", 3583 handler: func(rw ResponseWriter, r *Request) { 3584 rw.Header().Set("Content-Type", "some/type") 3585 rw.Write([]byte("<html><head></head><body>some html</body></html>")) 3586 }, 3587 check: func(got, logs string) error { 3588 if !strings.Contains(got, "Content-Type: some/type") { 3589 return errors.New("wrong content-type; want html") 3590 } 3591 return nil 3592 }, 3593 }, 3594 { 3595 name: "empty handler", 3596 handler: func(rw ResponseWriter, r *Request) { 3597 }, 3598 check: func(got, logs string) error { 3599 if !strings.Contains(got, "Content-Length: 0") { 3600 return errors.New("want 0 content-length") 3601 } 3602 return nil 3603 }, 3604 }, 3605 { 3606 name: "only Header, no write", 3607 handler: func(rw ResponseWriter, r *Request) { 3608 rw.Header().Set("Some-Header", "some-value") 3609 }, 3610 check: func(got, logs string) error { 3611 if !strings.Contains(got, "Some-Header") { 3612 return errors.New("didn't get header") 3613 } 3614 return nil 3615 }, 3616 }, 3617 { 3618 name: "WriteHeader call", 3619 handler: func(rw ResponseWriter, r *Request) { 3620 rw.WriteHeader(404) 3621 rw.Header().Set("Too-Late", "some-value") 3622 }, 3623 check: func(got, logs string) error { 3624 if !strings.Contains(got, "404") { 3625 return errors.New("wrong status") 3626 } 3627 if strings.Contains(got, "Too-Late") { 3628 return errors.New("shouldn't have seen Too-Late") 3629 } 3630 return nil 3631 }, 3632 }, 3633 } 3634 for _, tc := range tests { 3635 ht := newHandlerTest(HandlerFunc(tc.handler)) 3636 got := ht.rawResponse("GET / HTTP/1.1\nHost: golang.org") 3637 logs := ht.logbuf.String() 3638 if err := tc.check(got, logs); err != nil { 3639 t.Errorf("%s: %v\nGot response:\n%s\n\n%s", tc.name, err, got, logs) 3640 } 3641 } 3642 } 3643 3644 type errorListener struct { 3645 errs []error 3646 } 3647 3648 func (l *errorListener) Accept() (c net.Conn, err error) { 3649 if len(l.errs) == 0 { 3650 return nil, io.EOF 3651 } 3652 err = l.errs[0] 3653 l.errs = l.errs[1:] 3654 return 3655 } 3656 3657 func (l *errorListener) Close() error { 3658 return nil 3659 } 3660 3661 func (l *errorListener) Addr() net.Addr { 3662 return dummyAddr("test-address") 3663 } 3664 3665 func TestAcceptMaxFds(t *testing.T) { 3666 setParallel(t) 3667 3668 ln := &errorListener{[]error{ 3669 &net.OpError{ 3670 Op: "accept", 3671 Err: syscall.EMFILE, 3672 }}} 3673 server := &Server{ 3674 Handler: HandlerFunc(HandlerFunc(func(ResponseWriter, *Request) {})), 3675 ErrorLog: log.New(io.Discard, "", 0), // noisy otherwise 3676 } 3677 err := server.Serve(ln) 3678 if err != io.EOF { 3679 t.Errorf("got error %v, want EOF", err) 3680 } 3681 } 3682 3683 func TestWriteAfterHijack(t *testing.T) { 3684 req := reqBytes("GET / HTTP/1.1\nHost: golang.org") 3685 var buf strings.Builder 3686 wrotec := make(chan bool, 1) 3687 conn := &rwTestConn{ 3688 Reader: bytes.NewReader(req), 3689 Writer: &buf, 3690 closec: make(chan bool, 1), 3691 } 3692 handler := HandlerFunc(func(rw ResponseWriter, r *Request) { 3693 conn, bufrw, err := rw.(Hijacker).Hijack() 3694 if err != nil { 3695 t.Error(err) 3696 return 3697 } 3698 go func() { 3699 bufrw.Write([]byte("[hijack-to-bufw]")) 3700 bufrw.Flush() 3701 conn.Write([]byte("[hijack-to-conn]")) 3702 conn.Close() 3703 wrotec <- true 3704 }() 3705 }) 3706 ln := &oneConnListener{conn: conn} 3707 go Serve(ln, handler) 3708 <-conn.closec 3709 <-wrotec 3710 if g, w := buf.String(), "[hijack-to-bufw][hijack-to-conn]"; g != w { 3711 t.Errorf("wrote %q; want %q", g, w) 3712 } 3713 } 3714 3715 func TestDoubleHijack(t *testing.T) { 3716 req := reqBytes("GET / HTTP/1.1\nHost: golang.org") 3717 var buf bytes.Buffer 3718 conn := &rwTestConn{ 3719 Reader: bytes.NewReader(req), 3720 Writer: &buf, 3721 closec: make(chan bool, 1), 3722 } 3723 handler := HandlerFunc(func(rw ResponseWriter, r *Request) { 3724 conn, _, err := rw.(Hijacker).Hijack() 3725 if err != nil { 3726 t.Error(err) 3727 return 3728 } 3729 _, _, err = rw.(Hijacker).Hijack() 3730 if err == nil { 3731 t.Errorf("got err = nil; want err != nil") 3732 } 3733 conn.Close() 3734 }) 3735 ln := &oneConnListener{conn: conn} 3736 go Serve(ln, handler) 3737 <-conn.closec 3738 } 3739 3740 // https://golang.org/issue/5955 3741 // Note that this does not test the "request too large" 3742 // exit path from the http server. This is intentional; 3743 // not sending Connection: close is just a minor wire 3744 // optimization and is pointless if dealing with a 3745 // badly behaved client. 3746 func TestHTTP10ConnectionHeader(t *testing.T) { 3747 run(t, testHTTP10ConnectionHeader, []testMode{http1Mode}) 3748 } 3749 func testHTTP10ConnectionHeader(t *testing.T, mode testMode) { 3750 mux := NewServeMux() 3751 mux.Handle("/", HandlerFunc(func(ResponseWriter, *Request) {})) 3752 ts := newClientServerTest(t, mode, mux).ts 3753 3754 // net/http uses HTTP/1.1 for requests, so write requests manually 3755 tests := []struct { 3756 req string // raw http request 3757 expect []string // expected Connection header(s) 3758 }{ 3759 { 3760 req: "GET / HTTP/1.0\r\n\r\n", 3761 expect: nil, 3762 }, 3763 { 3764 req: "OPTIONS * HTTP/1.0\r\n\r\n", 3765 expect: nil, 3766 }, 3767 { 3768 req: "GET / HTTP/1.0\r\nConnection: keep-alive\r\n\r\n", 3769 expect: []string{"keep-alive"}, 3770 }, 3771 } 3772 3773 for _, tt := range tests { 3774 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 3775 if err != nil { 3776 t.Fatal("dial err:", err) 3777 } 3778 3779 _, err = fmt.Fprint(conn, tt.req) 3780 if err != nil { 3781 t.Fatal("conn write err:", err) 3782 } 3783 3784 resp, err := ReadResponse(bufio.NewReader(conn), &Request{Method: "GET"}) 3785 if err != nil { 3786 t.Fatal("ReadResponse err:", err) 3787 } 3788 conn.Close() 3789 resp.Body.Close() 3790 3791 got := resp.Header["Connection"] 3792 if !reflect.DeepEqual(got, tt.expect) { 3793 t.Errorf("wrong Connection headers for request %q. Got %q expect %q", tt.req, got, tt.expect) 3794 } 3795 } 3796 } 3797 3798 // See golang.org/issue/5660 3799 func TestServerReaderFromOrder(t *testing.T) { run(t, testServerReaderFromOrder) } 3800 func testServerReaderFromOrder(t *testing.T, mode testMode) { 3801 pr, pw := io.Pipe() 3802 const size = 3 << 20 3803 cst := newClientServerTest(t, mode, HandlerFunc(func(rw ResponseWriter, req *Request) { 3804 rw.Header().Set("Content-Type", "text/plain") // prevent sniffing path 3805 done := make(chan bool) 3806 go func() { 3807 io.Copy(rw, pr) 3808 close(done) 3809 }() 3810 time.Sleep(25 * time.Millisecond) // give Copy a chance to break things 3811 n, err := io.Copy(io.Discard, req.Body) 3812 if err != nil { 3813 t.Errorf("handler Copy: %v", err) 3814 return 3815 } 3816 if n != size { 3817 t.Errorf("handler Copy = %d; want %d", n, size) 3818 } 3819 pw.Write([]byte("hi")) 3820 pw.Close() 3821 <-done 3822 })) 3823 3824 req, err := NewRequest("POST", cst.ts.URL, io.LimitReader(neverEnding('a'), size)) 3825 if err != nil { 3826 t.Fatal(err) 3827 } 3828 res, err := cst.c.Do(req) 3829 if err != nil { 3830 t.Fatal(err) 3831 } 3832 all, err := io.ReadAll(res.Body) 3833 if err != nil { 3834 t.Fatal(err) 3835 } 3836 res.Body.Close() 3837 if string(all) != "hi" { 3838 t.Errorf("Body = %q; want hi", all) 3839 } 3840 } 3841 3842 // Issue 6157, Issue 6685 3843 func TestCodesPreventingContentTypeAndBody(t *testing.T) { 3844 for _, code := range []int{StatusNotModified, StatusNoContent} { 3845 ht := newHandlerTest(HandlerFunc(func(w ResponseWriter, r *Request) { 3846 if r.URL.Path == "/header" { 3847 w.Header().Set("Content-Length", "123") 3848 } 3849 w.WriteHeader(code) 3850 if r.URL.Path == "/more" { 3851 w.Write([]byte("stuff")) 3852 } 3853 })) 3854 for _, req := range []string{ 3855 "GET / HTTP/1.0", 3856 "GET /header HTTP/1.0", 3857 "GET /more HTTP/1.0", 3858 "GET / HTTP/1.1\nHost: foo", 3859 "GET /header HTTP/1.1\nHost: foo", 3860 "GET /more HTTP/1.1\nHost: foo", 3861 } { 3862 got := ht.rawResponse(req) 3863 wantStatus := fmt.Sprintf("%d %s", code, StatusText(code)) 3864 if !strings.Contains(got, wantStatus) { 3865 t.Errorf("Code %d: Wanted %q Modified for %q: %s", code, wantStatus, req, got) 3866 } else if strings.Contains(got, "Content-Length") { 3867 t.Errorf("Code %d: Got a Content-Length from %q: %s", code, req, got) 3868 } else if strings.Contains(got, "stuff") { 3869 t.Errorf("Code %d: Response contains a body from %q: %s", code, req, got) 3870 } 3871 } 3872 } 3873 } 3874 3875 func TestContentTypeOkayOn204(t *testing.T) { 3876 ht := newHandlerTest(HandlerFunc(func(w ResponseWriter, r *Request) { 3877 w.Header().Set("Content-Length", "123") // suppressed 3878 w.Header().Set("Content-Type", "foo/bar") 3879 w.WriteHeader(204) 3880 })) 3881 got := ht.rawResponse("GET / HTTP/1.1\nHost: foo") 3882 if !strings.Contains(got, "Content-Type: foo/bar") { 3883 t.Errorf("Response = %q; want Content-Type: foo/bar", got) 3884 } 3885 if strings.Contains(got, "Content-Length: 123") { 3886 t.Errorf("Response = %q; don't want a Content-Length", got) 3887 } 3888 } 3889 3890 // Issue 6995 3891 // A server Handler can receive a Request, and then turn around and 3892 // give a copy of that Request.Body out to the Transport (e.g. any 3893 // proxy). So then two people own that Request.Body (both the server 3894 // and the http client), and both think they can close it on failure. 3895 // Therefore, all incoming server requests Bodies need to be thread-safe. 3896 func TestTransportAndServerSharedBodyRace(t *testing.T) { 3897 run(t, testTransportAndServerSharedBodyRace) 3898 } 3899 func testTransportAndServerSharedBodyRace(t *testing.T, mode testMode) { 3900 const bodySize = 1 << 20 3901 3902 // errorf is like t.Errorf, but also writes to println. When 3903 // this test fails, it hangs. This helps debugging and I've 3904 // added this enough times "temporarily". It now gets added 3905 // full time. 3906 errorf := func(format string, args ...any) { 3907 v := fmt.Sprintf(format, args...) 3908 println(v) 3909 t.Error(v) 3910 } 3911 3912 unblockBackend := make(chan bool) 3913 backend := newClientServerTest(t, mode, HandlerFunc(func(rw ResponseWriter, req *Request) { 3914 gone := rw.(CloseNotifier).CloseNotify() 3915 didCopy := make(chan any) 3916 go func() { 3917 n, err := io.CopyN(rw, req.Body, bodySize) 3918 didCopy <- []any{n, err} 3919 }() 3920 isGone := false 3921 Loop: 3922 for { 3923 select { 3924 case <-didCopy: 3925 break Loop 3926 case <-gone: 3927 isGone = true 3928 case <-time.After(time.Second): 3929 println("1 second passes in backend, proxygone=", isGone) 3930 } 3931 } 3932 <-unblockBackend 3933 })) 3934 defer backend.close() 3935 3936 backendRespc := make(chan *Response, 1) 3937 var proxy *clientServerTest 3938 proxy = newClientServerTest(t, mode, HandlerFunc(func(rw ResponseWriter, req *Request) { 3939 req2, _ := NewRequest("POST", backend.ts.URL, req.Body) 3940 req2.ContentLength = bodySize 3941 cancel := make(chan struct{}) 3942 req2.Cancel = cancel 3943 3944 bresp, err := proxy.c.Do(req2) 3945 if err != nil { 3946 errorf("Proxy outbound request: %v", err) 3947 return 3948 } 3949 _, err = io.CopyN(io.Discard, bresp.Body, bodySize/2) 3950 if err != nil { 3951 errorf("Proxy copy error: %v", err) 3952 return 3953 } 3954 backendRespc <- bresp // to close later 3955 3956 // Try to cause a race: Both the Transport and the proxy handler's Server 3957 // will try to read/close req.Body (aka req2.Body) 3958 if mode == http2Mode { 3959 close(cancel) 3960 } else { 3961 proxy.c.Transport.(*Transport).CancelRequest(req2) 3962 } 3963 rw.Write([]byte("OK")) 3964 })) 3965 defer proxy.close() 3966 3967 defer close(unblockBackend) 3968 req, _ := NewRequest("POST", proxy.ts.URL, io.LimitReader(neverEnding('a'), bodySize)) 3969 res, err := proxy.c.Do(req) 3970 if err != nil { 3971 t.Fatalf("Original request: %v", err) 3972 } 3973 3974 // Cleanup, so we don't leak goroutines. 3975 res.Body.Close() 3976 select { 3977 case res := <-backendRespc: 3978 res.Body.Close() 3979 default: 3980 // We failed earlier. (e.g. on proxy.c.Do(req2)) 3981 } 3982 } 3983 3984 // Test that a hanging Request.Body.Read from another goroutine can't 3985 // cause the Handler goroutine's Request.Body.Close to block. 3986 // See issue 7121. 3987 func TestRequestBodyCloseDoesntBlock(t *testing.T) { 3988 run(t, testRequestBodyCloseDoesntBlock, []testMode{http1Mode}) 3989 } 3990 func testRequestBodyCloseDoesntBlock(t *testing.T, mode testMode) { 3991 if testing.Short() { 3992 t.Skip("skipping in -short mode") 3993 } 3994 3995 readErrCh := make(chan error, 1) 3996 errCh := make(chan error, 2) 3997 3998 server := newClientServerTest(t, mode, HandlerFunc(func(rw ResponseWriter, req *Request) { 3999 go func(body io.Reader) { 4000 _, err := body.Read(make([]byte, 100)) 4001 readErrCh <- err 4002 }(req.Body) 4003 time.Sleep(500 * time.Millisecond) 4004 })).ts 4005 4006 closeConn := make(chan bool) 4007 defer close(closeConn) 4008 go func() { 4009 conn, err := net.Dial("tcp", server.Listener.Addr().String()) 4010 if err != nil { 4011 errCh <- err 4012 return 4013 } 4014 defer conn.Close() 4015 _, err = conn.Write([]byte("POST / HTTP/1.1\r\nConnection: close\r\nHost: foo\r\nContent-Length: 100000\r\n\r\n")) 4016 if err != nil { 4017 errCh <- err 4018 return 4019 } 4020 // And now just block, making the server block on our 4021 // 100000 bytes of body that will never arrive. 4022 <-closeConn 4023 }() 4024 select { 4025 case err := <-readErrCh: 4026 if err == nil { 4027 t.Error("Read was nil. Expected error.") 4028 } 4029 case err := <-errCh: 4030 t.Error(err) 4031 } 4032 } 4033 4034 // test that ResponseWriter implements io.StringWriter. 4035 func TestResponseWriterWriteString(t *testing.T) { 4036 okc := make(chan bool, 1) 4037 ht := newHandlerTest(HandlerFunc(func(w ResponseWriter, r *Request) { 4038 _, ok := w.(io.StringWriter) 4039 okc <- ok 4040 })) 4041 ht.rawResponse("GET / HTTP/1.0") 4042 select { 4043 case ok := <-okc: 4044 if !ok { 4045 t.Error("ResponseWriter did not implement io.StringWriter") 4046 } 4047 default: 4048 t.Error("handler was never called") 4049 } 4050 } 4051 4052 func TestAppendTime(t *testing.T) { 4053 var b [len(TimeFormat)]byte 4054 t1 := time.Date(2013, 9, 21, 15, 41, 0, 0, time.FixedZone("CEST", 2*60*60)) 4055 res := ExportAppendTime(b[:0], t1) 4056 t2, err := ParseTime(string(res)) 4057 if err != nil { 4058 t.Fatalf("Error parsing time: %s", err) 4059 } 4060 if !t1.Equal(t2) { 4061 t.Fatalf("Times differ; expected: %v, got %v (%s)", t1, t2, string(res)) 4062 } 4063 } 4064 4065 func TestServerConnState(t *testing.T) { run(t, testServerConnState, []testMode{http1Mode}) } 4066 func testServerConnState(t *testing.T, mode testMode) { 4067 handler := map[string]func(w ResponseWriter, r *Request){ 4068 "/": func(w ResponseWriter, r *Request) { 4069 fmt.Fprintf(w, "Hello.") 4070 }, 4071 "/close": func(w ResponseWriter, r *Request) { 4072 w.Header().Set("Connection", "close") 4073 fmt.Fprintf(w, "Hello.") 4074 }, 4075 "/hijack": func(w ResponseWriter, r *Request) { 4076 c, _, _ := w.(Hijacker).Hijack() 4077 c.Write([]byte("HTTP/1.0 200 OK\r\nConnection: close\r\n\r\nHello.")) 4078 c.Close() 4079 }, 4080 "/hijack-panic": func(w ResponseWriter, r *Request) { 4081 c, _, _ := w.(Hijacker).Hijack() 4082 c.Write([]byte("HTTP/1.0 200 OK\r\nConnection: close\r\n\r\nHello.")) 4083 c.Close() 4084 panic("intentional panic") 4085 }, 4086 } 4087 4088 // A stateLog is a log of states over the lifetime of a connection. 4089 type stateLog struct { 4090 active net.Conn // The connection for which the log is recorded; set to the first connection seen in StateNew. 4091 got []ConnState 4092 want []ConnState 4093 complete chan<- struct{} // If non-nil, closed when either 'got' is equal to 'want', or 'got' is no longer a prefix of 'want'. 4094 } 4095 activeLog := make(chan *stateLog, 1) 4096 4097 // wantLog invokes doRequests, then waits for the resulting connection to 4098 // either pass through the sequence of states in want or enter a state outside 4099 // of that sequence. 4100 wantLog := func(doRequests func(), want ...ConnState) { 4101 t.Helper() 4102 complete := make(chan struct{}) 4103 activeLog <- &stateLog{want: want, complete: complete} 4104 4105 doRequests() 4106 4107 <-complete 4108 sl := <-activeLog 4109 if !reflect.DeepEqual(sl.got, sl.want) { 4110 t.Errorf("Request(s) produced unexpected state sequence.\nGot: %v\nWant: %v", sl.got, sl.want) 4111 } 4112 // Don't return sl to activeLog: we don't expect any further states after 4113 // this point, and want to keep the ConnState callback blocked until the 4114 // next call to wantLog. 4115 } 4116 4117 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 4118 handler[r.URL.Path](w, r) 4119 }), func(ts *httptest.Server) { 4120 ts.Config.ErrorLog = log.New(io.Discard, "", 0) 4121 ts.Config.ConnState = func(c net.Conn, state ConnState) { 4122 if c == nil { 4123 t.Errorf("nil conn seen in state %s", state) 4124 return 4125 } 4126 sl := <-activeLog 4127 if sl.active == nil && state == StateNew { 4128 sl.active = c 4129 } else if sl.active != c { 4130 t.Errorf("unexpected conn in state %s", state) 4131 activeLog <- sl 4132 return 4133 } 4134 sl.got = append(sl.got, state) 4135 if sl.complete != nil && (len(sl.got) >= len(sl.want) || !reflect.DeepEqual(sl.got, sl.want[:len(sl.got)])) { 4136 close(sl.complete) 4137 sl.complete = nil 4138 } 4139 activeLog <- sl 4140 } 4141 }).ts 4142 defer func() { 4143 activeLog <- &stateLog{} // If the test failed, allow any remaining ConnState callbacks to complete. 4144 ts.Close() 4145 }() 4146 4147 c := ts.Client() 4148 4149 mustGet := func(url string, headers ...string) { 4150 t.Helper() 4151 req, err := NewRequest("GET", url, nil) 4152 if err != nil { 4153 t.Fatal(err) 4154 } 4155 for len(headers) > 0 { 4156 req.Header.Add(headers[0], headers[1]) 4157 headers = headers[2:] 4158 } 4159 res, err := c.Do(req) 4160 if err != nil { 4161 t.Errorf("Error fetching %s: %v", url, err) 4162 return 4163 } 4164 _, err = io.ReadAll(res.Body) 4165 defer res.Body.Close() 4166 if err != nil { 4167 t.Errorf("Error reading %s: %v", url, err) 4168 } 4169 } 4170 4171 wantLog(func() { 4172 mustGet(ts.URL + "/") 4173 mustGet(ts.URL + "/close") 4174 }, StateNew, StateActive, StateIdle, StateActive, StateClosed) 4175 4176 wantLog(func() { 4177 mustGet(ts.URL + "/") 4178 mustGet(ts.URL+"/", "Connection", "close") 4179 }, StateNew, StateActive, StateIdle, StateActive, StateClosed) 4180 4181 wantLog(func() { 4182 mustGet(ts.URL + "/hijack") 4183 }, StateNew, StateActive, StateHijacked) 4184 4185 wantLog(func() { 4186 mustGet(ts.URL + "/hijack-panic") 4187 }, StateNew, StateActive, StateHijacked) 4188 4189 wantLog(func() { 4190 c, err := net.Dial("tcp", ts.Listener.Addr().String()) 4191 if err != nil { 4192 t.Fatal(err) 4193 } 4194 c.Close() 4195 }, StateNew, StateClosed) 4196 4197 wantLog(func() { 4198 c, err := net.Dial("tcp", ts.Listener.Addr().String()) 4199 if err != nil { 4200 t.Fatal(err) 4201 } 4202 if _, err := io.WriteString(c, "BOGUS REQUEST\r\n\r\n"); err != nil { 4203 t.Fatal(err) 4204 } 4205 c.Read(make([]byte, 1)) // block until server hangs up on us 4206 c.Close() 4207 }, StateNew, StateActive, StateClosed) 4208 4209 wantLog(func() { 4210 c, err := net.Dial("tcp", ts.Listener.Addr().String()) 4211 if err != nil { 4212 t.Fatal(err) 4213 } 4214 if _, err := io.WriteString(c, "GET / HTTP/1.1\r\nHost: foo\r\n\r\n"); err != nil { 4215 t.Fatal(err) 4216 } 4217 res, err := ReadResponse(bufio.NewReader(c), nil) 4218 if err != nil { 4219 t.Fatal(err) 4220 } 4221 if _, err := io.Copy(io.Discard, res.Body); err != nil { 4222 t.Fatal(err) 4223 } 4224 c.Close() 4225 }, StateNew, StateActive, StateIdle, StateClosed) 4226 } 4227 4228 func TestServerKeepAlivesEnabledResultClose(t *testing.T) { 4229 run(t, testServerKeepAlivesEnabledResultClose, []testMode{http1Mode}) 4230 } 4231 func testServerKeepAlivesEnabledResultClose(t *testing.T, mode testMode) { 4232 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 4233 }), func(ts *httptest.Server) { 4234 ts.Config.SetKeepAlivesEnabled(false) 4235 }).ts 4236 res, err := ts.Client().Get(ts.URL) 4237 if err != nil { 4238 t.Fatal(err) 4239 } 4240 defer res.Body.Close() 4241 if !res.Close { 4242 t.Errorf("Body.Close == false; want true") 4243 } 4244 } 4245 4246 // golang.org/issue/7856 4247 func TestServerEmptyBodyRace(t *testing.T) { run(t, testServerEmptyBodyRace) } 4248 func testServerEmptyBodyRace(t *testing.T, mode testMode) { 4249 var n int32 4250 cst := newClientServerTest(t, mode, HandlerFunc(func(rw ResponseWriter, req *Request) { 4251 atomic.AddInt32(&n, 1) 4252 }), optQuietLog) 4253 var wg sync.WaitGroup 4254 const reqs = 20 4255 for i := 0; i < reqs; i++ { 4256 wg.Add(1) 4257 go func() { 4258 defer wg.Done() 4259 res, err := cst.c.Get(cst.ts.URL) 4260 if err != nil { 4261 // Try to deflake spurious "connection reset by peer" under load. 4262 // See golang.org/issue/22540. 4263 time.Sleep(10 * time.Millisecond) 4264 res, err = cst.c.Get(cst.ts.URL) 4265 if err != nil { 4266 t.Error(err) 4267 return 4268 } 4269 } 4270 defer res.Body.Close() 4271 _, err = io.Copy(io.Discard, res.Body) 4272 if err != nil { 4273 t.Error(err) 4274 return 4275 } 4276 }() 4277 } 4278 wg.Wait() 4279 if got := atomic.LoadInt32(&n); got != reqs { 4280 t.Errorf("handler ran %d times; want %d", got, reqs) 4281 } 4282 } 4283 4284 func TestServerConnStateNew(t *testing.T) { 4285 sawNew := false // if the test is buggy, we'll race on this variable. 4286 srv := &Server{ 4287 ConnState: func(c net.Conn, state ConnState) { 4288 if state == StateNew { 4289 sawNew = true // testing that this write isn't racy 4290 } 4291 }, 4292 Handler: HandlerFunc(func(w ResponseWriter, r *Request) {}), // irrelevant 4293 } 4294 srv.Serve(&oneConnListener{ 4295 conn: &rwTestConn{ 4296 Reader: strings.NewReader("GET / HTTP/1.1\r\nHost: foo\r\n\r\n"), 4297 Writer: io.Discard, 4298 }, 4299 }) 4300 if !sawNew { // testing that this read isn't racy 4301 t.Error("StateNew not seen") 4302 } 4303 } 4304 4305 type closeWriteTestConn struct { 4306 rwTestConn 4307 didCloseWrite bool 4308 } 4309 4310 func (c *closeWriteTestConn) CloseWrite() error { 4311 c.didCloseWrite = true 4312 return nil 4313 } 4314 4315 func TestCloseWrite(t *testing.T) { 4316 setParallel(t) 4317 var srv Server 4318 var testConn closeWriteTestConn 4319 c := ExportServerNewConn(&srv, &testConn) 4320 ExportCloseWriteAndWait(c) 4321 if !testConn.didCloseWrite { 4322 t.Error("didn't see CloseWrite call") 4323 } 4324 } 4325 4326 // This verifies that a handler can Flush and then Hijack. 4327 // 4328 // A similar test crashed once during development, but it was only 4329 // testing this tangentially and temporarily until another TODO was 4330 // fixed. 4331 // 4332 // So add an explicit test for this. 4333 func TestServerFlushAndHijack(t *testing.T) { run(t, testServerFlushAndHijack, []testMode{http1Mode}) } 4334 func testServerFlushAndHijack(t *testing.T, mode testMode) { 4335 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 4336 io.WriteString(w, "Hello, ") 4337 w.(Flusher).Flush() 4338 conn, buf, _ := w.(Hijacker).Hijack() 4339 buf.WriteString("6\r\nworld!\r\n0\r\n\r\n") 4340 if err := buf.Flush(); err != nil { 4341 t.Error(err) 4342 } 4343 if err := conn.Close(); err != nil { 4344 t.Error(err) 4345 } 4346 })).ts 4347 res, err := Get(ts.URL) 4348 if err != nil { 4349 t.Fatal(err) 4350 } 4351 defer res.Body.Close() 4352 all, err := io.ReadAll(res.Body) 4353 if err != nil { 4354 t.Fatal(err) 4355 } 4356 if want := "Hello, world!"; string(all) != want { 4357 t.Errorf("Got %q; want %q", all, want) 4358 } 4359 } 4360 4361 // golang.org/issue/8534 -- the Server shouldn't reuse a connection 4362 // for keep-alive after it's seen any Write error (e.g. a timeout) on 4363 // that net.Conn. 4364 // 4365 // To test, verify we don't timeout or see fewer unique client 4366 // addresses (== unique connections) than requests. 4367 func TestServerKeepAliveAfterWriteError(t *testing.T) { 4368 run(t, testServerKeepAliveAfterWriteError, []testMode{http1Mode}) 4369 } 4370 func testServerKeepAliveAfterWriteError(t *testing.T, mode testMode) { 4371 if testing.Short() { 4372 t.Skip("skipping in -short mode") 4373 } 4374 const numReq = 3 4375 addrc := make(chan string, numReq) 4376 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 4377 addrc <- r.RemoteAddr 4378 time.Sleep(500 * time.Millisecond) 4379 w.(Flusher).Flush() 4380 }), func(ts *httptest.Server) { 4381 ts.Config.WriteTimeout = 250 * time.Millisecond 4382 }).ts 4383 4384 errc := make(chan error, numReq) 4385 go func() { 4386 defer close(errc) 4387 for i := 0; i < numReq; i++ { 4388 res, err := Get(ts.URL) 4389 if res != nil { 4390 res.Body.Close() 4391 } 4392 errc <- err 4393 } 4394 }() 4395 4396 addrSeen := map[string]bool{} 4397 numOkay := 0 4398 for { 4399 select { 4400 case v := <-addrc: 4401 addrSeen[v] = true 4402 case err, ok := <-errc: 4403 if !ok { 4404 if len(addrSeen) != numReq { 4405 t.Errorf("saw %d unique client addresses; want %d", len(addrSeen), numReq) 4406 } 4407 if numOkay != 0 { 4408 t.Errorf("got %d successful client requests; want 0", numOkay) 4409 } 4410 return 4411 } 4412 if err == nil { 4413 numOkay++ 4414 } 4415 } 4416 } 4417 } 4418 4419 // Issue 9987: shouldn't add automatic Content-Length (or 4420 // Content-Type) if a Transfer-Encoding was set by the handler. 4421 func TestNoContentLengthIfTransferEncoding(t *testing.T) { 4422 run(t, testNoContentLengthIfTransferEncoding, []testMode{http1Mode}) 4423 } 4424 func testNoContentLengthIfTransferEncoding(t *testing.T, mode testMode) { 4425 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 4426 w.Header().Set("Transfer-Encoding", "foo") 4427 io.WriteString(w, "<html>") 4428 })).ts 4429 c, err := net.Dial("tcp", ts.Listener.Addr().String()) 4430 if err != nil { 4431 t.Fatalf("Dial: %v", err) 4432 } 4433 defer c.Close() 4434 if _, err := io.WriteString(c, "GET / HTTP/1.1\r\nHost: foo\r\n\r\n"); err != nil { 4435 t.Fatal(err) 4436 } 4437 bs := bufio.NewScanner(c) 4438 var got strings.Builder 4439 for bs.Scan() { 4440 if strings.TrimSpace(bs.Text()) == "" { 4441 break 4442 } 4443 got.WriteString(bs.Text()) 4444 got.WriteByte('\n') 4445 } 4446 if err := bs.Err(); err != nil { 4447 t.Fatal(err) 4448 } 4449 if strings.Contains(got.String(), "Content-Length") { 4450 t.Errorf("Unexpected Content-Length in response headers: %s", got.String()) 4451 } 4452 if strings.Contains(got.String(), "Content-Type") { 4453 t.Errorf("Unexpected Content-Type in response headers: %s", got.String()) 4454 } 4455 } 4456 4457 // tolerate extra CRLF(s) before Request-Line on subsequent requests on a conn 4458 // Issue 10876. 4459 func TestTolerateCRLFBeforeRequestLine(t *testing.T) { 4460 req := []byte("POST / HTTP/1.1\r\nHost: golang.org\r\nContent-Length: 3\r\n\r\nABC" + 4461 "\r\n\r\n" + // <-- this stuff is bogus, but we'll ignore it 4462 "GET / HTTP/1.1\r\nHost: golang.org\r\n\r\n") 4463 var buf bytes.Buffer 4464 conn := &rwTestConn{ 4465 Reader: bytes.NewReader(req), 4466 Writer: &buf, 4467 closec: make(chan bool, 1), 4468 } 4469 ln := &oneConnListener{conn: conn} 4470 numReq := 0 4471 go Serve(ln, HandlerFunc(func(rw ResponseWriter, r *Request) { 4472 numReq++ 4473 })) 4474 <-conn.closec 4475 if numReq != 2 { 4476 t.Errorf("num requests = %d; want 2", numReq) 4477 t.Logf("Res: %s", buf.Bytes()) 4478 } 4479 } 4480 4481 func TestIssue13893_Expect100(t *testing.T) { 4482 // test that the Server doesn't filter out Expect headers. 4483 req := reqBytes(`PUT /readbody HTTP/1.1 4484 User-Agent: PycURL/7.22.0 4485 Host: 127.0.0.1:9000 4486 Accept: */* 4487 Expect: 100-continue 4488 Content-Length: 10 4489 4490 HelloWorld 4491 4492 `) 4493 var buf bytes.Buffer 4494 conn := &rwTestConn{ 4495 Reader: bytes.NewReader(req), 4496 Writer: &buf, 4497 closec: make(chan bool, 1), 4498 } 4499 ln := &oneConnListener{conn: conn} 4500 go Serve(ln, HandlerFunc(func(w ResponseWriter, r *Request) { 4501 if _, ok := r.Header["Expect"]; !ok { 4502 t.Error("Expect header should not be filtered out") 4503 } 4504 })) 4505 <-conn.closec 4506 } 4507 4508 func TestIssue11549_Expect100(t *testing.T) { 4509 req := reqBytes(`PUT /readbody HTTP/1.1 4510 User-Agent: PycURL/7.22.0 4511 Host: 127.0.0.1:9000 4512 Accept: */* 4513 Expect: 100-continue 4514 Content-Length: 10 4515 4516 HelloWorldPUT /noreadbody HTTP/1.1 4517 User-Agent: PycURL/7.22.0 4518 Host: 127.0.0.1:9000 4519 Accept: */* 4520 Expect: 100-continue 4521 Content-Length: 10 4522 4523 GET /should-be-ignored HTTP/1.1 4524 Host: foo 4525 4526 `) 4527 var buf strings.Builder 4528 conn := &rwTestConn{ 4529 Reader: bytes.NewReader(req), 4530 Writer: &buf, 4531 closec: make(chan bool, 1), 4532 } 4533 ln := &oneConnListener{conn: conn} 4534 numReq := 0 4535 go Serve(ln, HandlerFunc(func(w ResponseWriter, r *Request) { 4536 numReq++ 4537 if r.URL.Path == "/readbody" { 4538 io.ReadAll(r.Body) 4539 } 4540 io.WriteString(w, "Hello world!") 4541 })) 4542 <-conn.closec 4543 if numReq != 2 { 4544 t.Errorf("num requests = %d; want 2", numReq) 4545 } 4546 if !strings.Contains(buf.String(), "Connection: close\r\n") { 4547 t.Errorf("expected 'Connection: close' in response; got: %s", buf.String()) 4548 } 4549 } 4550 4551 // If a Handler finishes and there's an unread request body, 4552 // verify the server try to do implicit read on it before replying. 4553 func TestHandlerFinishSkipBigContentLengthRead(t *testing.T) { 4554 setParallel(t) 4555 conn := &testConn{closec: make(chan bool)} 4556 conn.readBuf.Write([]byte(fmt.Sprintf( 4557 "POST / HTTP/1.1\r\n" + 4558 "Host: test\r\n" + 4559 "Content-Length: 9999999999\r\n" + 4560 "\r\n" + strings.Repeat("a", 1<<20)))) 4561 4562 ls := &oneConnListener{conn} 4563 var inHandlerLen int 4564 go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) { 4565 inHandlerLen = conn.readBuf.Len() 4566 rw.WriteHeader(404) 4567 })) 4568 <-conn.closec 4569 afterHandlerLen := conn.readBuf.Len() 4570 4571 if afterHandlerLen != inHandlerLen { 4572 t.Errorf("unexpected implicit read. Read buffer went from %d -> %d", inHandlerLen, afterHandlerLen) 4573 } 4574 } 4575 4576 func TestHandlerSetsBodyNil(t *testing.T) { run(t, testHandlerSetsBodyNil) } 4577 func testHandlerSetsBodyNil(t *testing.T, mode testMode) { 4578 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 4579 r.Body = nil 4580 fmt.Fprintf(w, "%v", r.RemoteAddr) 4581 })) 4582 get := func() string { 4583 res, err := cst.c.Get(cst.ts.URL) 4584 if err != nil { 4585 t.Fatal(err) 4586 } 4587 defer res.Body.Close() 4588 slurp, err := io.ReadAll(res.Body) 4589 if err != nil { 4590 t.Fatal(err) 4591 } 4592 return string(slurp) 4593 } 4594 a, b := get(), get() 4595 if a != b { 4596 t.Errorf("Failed to reuse connections between requests: %v vs %v", a, b) 4597 } 4598 } 4599 4600 // Test that we validate the Host header. 4601 // Issue 11206 (invalid bytes in Host) and 13624 (Host present in HTTP/1.1) 4602 func TestServerValidatesHostHeader(t *testing.T) { 4603 tests := []struct { 4604 proto string 4605 host string 4606 want int 4607 }{ 4608 {"HTTP/0.9", "", 505}, 4609 4610 {"HTTP/1.1", "", 400}, 4611 {"HTTP/1.1", "Host: \r\n", 200}, 4612 {"HTTP/1.1", "Host: 1.2.3.4\r\n", 200}, 4613 {"HTTP/1.1", "Host: foo.com\r\n", 200}, 4614 {"HTTP/1.1", "Host: foo-bar_baz.com\r\n", 200}, 4615 {"HTTP/1.1", "Host: foo.com:80\r\n", 200}, 4616 {"HTTP/1.1", "Host: ::1\r\n", 200}, 4617 {"HTTP/1.1", "Host: [::1]\r\n", 200}, // questionable without port, but accept it 4618 {"HTTP/1.1", "Host: [::1]:80\r\n", 200}, 4619 {"HTTP/1.1", "Host: [::1%25en0]:80\r\n", 200}, 4620 {"HTTP/1.1", "Host: 1.2.3.4\r\n", 200}, 4621 {"HTTP/1.1", "Host: \x06\r\n", 400}, 4622 {"HTTP/1.1", "Host: \xff\r\n", 400}, 4623 {"HTTP/1.1", "Host: {\r\n", 400}, 4624 {"HTTP/1.1", "Host: }\r\n", 400}, 4625 {"HTTP/1.1", "Host: first\r\nHost: second\r\n", 400}, 4626 4627 // HTTP/1.0 can lack a host header, but if present 4628 // must play by the rules too: 4629 {"HTTP/1.0", "", 200}, 4630 {"HTTP/1.0", "Host: first\r\nHost: second\r\n", 400}, 4631 {"HTTP/1.0", "Host: \xff\r\n", 400}, 4632 4633 // Make an exception for HTTP upgrade requests: 4634 {"PRI * HTTP/2.0", "", 200}, 4635 4636 // Also an exception for CONNECT requests: (Issue 18215) 4637 {"CONNECT golang.org:443 HTTP/1.1", "", 200}, 4638 4639 // But not other HTTP/2 stuff: 4640 {"PRI / HTTP/2.0", "", 505}, 4641 {"GET / HTTP/2.0", "", 505}, 4642 {"GET / HTTP/3.0", "", 505}, 4643 } 4644 for _, tt := range tests { 4645 conn := &testConn{closec: make(chan bool, 1)} 4646 methodTarget := "GET / " 4647 if !strings.HasPrefix(tt.proto, "HTTP/") { 4648 methodTarget = "" 4649 } 4650 io.WriteString(&conn.readBuf, methodTarget+tt.proto+"\r\n"+tt.host+"\r\n") 4651 4652 ln := &oneConnListener{conn} 4653 srv := Server{ 4654 ErrorLog: quietLog, 4655 Handler: HandlerFunc(func(ResponseWriter, *Request) {}), 4656 } 4657 go srv.Serve(ln) 4658 <-conn.closec 4659 res, err := ReadResponse(bufio.NewReader(&conn.writeBuf), nil) 4660 if err != nil { 4661 t.Errorf("For %s %q, ReadResponse: %v", tt.proto, tt.host, res) 4662 continue 4663 } 4664 if res.StatusCode != tt.want { 4665 t.Errorf("For %s %q, Status = %d; want %d", tt.proto, tt.host, res.StatusCode, tt.want) 4666 } 4667 } 4668 } 4669 4670 func TestServerHandlersCanHandleH2PRI(t *testing.T) { 4671 run(t, testServerHandlersCanHandleH2PRI, []testMode{http1Mode}) 4672 } 4673 func testServerHandlersCanHandleH2PRI(t *testing.T, mode testMode) { 4674 const upgradeResponse = "upgrade here" 4675 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 4676 conn, br, err := w.(Hijacker).Hijack() 4677 if err != nil { 4678 t.Error(err) 4679 return 4680 } 4681 defer conn.Close() 4682 if r.Method != "PRI" || r.RequestURI != "*" { 4683 t.Errorf("Got method/target %q %q; want PRI *", r.Method, r.RequestURI) 4684 return 4685 } 4686 if !r.Close { 4687 t.Errorf("Request.Close = true; want false") 4688 } 4689 const want = "SM\r\n\r\n" 4690 buf := make([]byte, len(want)) 4691 n, err := io.ReadFull(br, buf) 4692 if err != nil || string(buf[:n]) != want { 4693 t.Errorf("Read = %v, %v (%q), want %q", n, err, buf[:n], want) 4694 return 4695 } 4696 io.WriteString(conn, upgradeResponse) 4697 })).ts 4698 4699 c, err := net.Dial("tcp", ts.Listener.Addr().String()) 4700 if err != nil { 4701 t.Fatalf("Dial: %v", err) 4702 } 4703 defer c.Close() 4704 io.WriteString(c, "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n") 4705 slurp, err := io.ReadAll(c) 4706 if err != nil { 4707 t.Fatal(err) 4708 } 4709 if string(slurp) != upgradeResponse { 4710 t.Errorf("Handler response = %q; want %q", slurp, upgradeResponse) 4711 } 4712 } 4713 4714 // Test that we validate the valid bytes in HTTP/1 headers. 4715 // Issue 11207. 4716 func TestServerValidatesHeaders(t *testing.T) { 4717 setParallel(t) 4718 tests := []struct { 4719 header string 4720 want int 4721 }{ 4722 {"", 200}, 4723 {"Foo: bar\r\n", 200}, 4724 {"X-Foo: bar\r\n", 200}, 4725 {"Foo: a space\r\n", 200}, 4726 4727 {"A space: foo\r\n", 400}, // space in header 4728 {"foo\xffbar: foo\r\n", 400}, // binary in header 4729 {"foo\x00bar: foo\r\n", 400}, // binary in header 4730 {"Foo: " + strings.Repeat("x", 1<<21) + "\r\n", 431}, // header too large 4731 // Spaces between the header key and colon are not allowed. 4732 // See RFC 7230, Section 3.2.4. 4733 {"Foo : bar\r\n", 400}, 4734 {"Foo\t: bar\r\n", 400}, 4735 4736 {"foo: foo foo\r\n", 200}, // LWS space is okay 4737 {"foo: foo\tfoo\r\n", 200}, // LWS tab is okay 4738 {"foo: foo\x00foo\r\n", 400}, // CTL 0x00 in value is bad 4739 {"foo: foo\x7ffoo\r\n", 400}, // CTL 0x7f in value is bad 4740 {"foo: foo\xfffoo\r\n", 200}, // non-ASCII high octets in value are fine 4741 } 4742 for _, tt := range tests { 4743 conn := &testConn{closec: make(chan bool, 1)} 4744 io.WriteString(&conn.readBuf, "GET / HTTP/1.1\r\nHost: foo\r\n"+tt.header+"\r\n") 4745 4746 ln := &oneConnListener{conn} 4747 srv := Server{ 4748 ErrorLog: quietLog, 4749 Handler: HandlerFunc(func(ResponseWriter, *Request) {}), 4750 } 4751 go srv.Serve(ln) 4752 <-conn.closec 4753 res, err := ReadResponse(bufio.NewReader(&conn.writeBuf), nil) 4754 if err != nil { 4755 t.Errorf("For %q, ReadResponse: %v", tt.header, res) 4756 continue 4757 } 4758 if res.StatusCode != tt.want { 4759 t.Errorf("For %q, Status = %d; want %d", tt.header, res.StatusCode, tt.want) 4760 } 4761 } 4762 } 4763 4764 func TestServerRequestContextCancel_ServeHTTPDone(t *testing.T) { 4765 run(t, testServerRequestContextCancel_ServeHTTPDone) 4766 } 4767 func testServerRequestContextCancel_ServeHTTPDone(t *testing.T, mode testMode) { 4768 ctxc := make(chan context.Context, 1) 4769 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 4770 ctx := r.Context() 4771 select { 4772 case <-ctx.Done(): 4773 t.Error("should not be Done in ServeHTTP") 4774 default: 4775 } 4776 ctxc <- ctx 4777 })) 4778 res, err := cst.c.Get(cst.ts.URL) 4779 if err != nil { 4780 t.Fatal(err) 4781 } 4782 res.Body.Close() 4783 ctx := <-ctxc 4784 select { 4785 case <-ctx.Done(): 4786 default: 4787 t.Error("context should be done after ServeHTTP completes") 4788 } 4789 } 4790 4791 // Tests that the Request.Context available to the Handler is canceled 4792 // if the peer closes their TCP connection. This requires that the server 4793 // is always blocked in a Read call so it notices the EOF from the client. 4794 // See issues 15927 and 15224. 4795 func TestServerRequestContextCancel_ConnClose(t *testing.T) { 4796 run(t, testServerRequestContextCancel_ConnClose, []testMode{http1Mode}) 4797 } 4798 func testServerRequestContextCancel_ConnClose(t *testing.T, mode testMode) { 4799 inHandler := make(chan struct{}) 4800 handlerDone := make(chan struct{}) 4801 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 4802 close(inHandler) 4803 <-r.Context().Done() 4804 close(handlerDone) 4805 })).ts 4806 c, err := net.Dial("tcp", ts.Listener.Addr().String()) 4807 if err != nil { 4808 t.Fatal(err) 4809 } 4810 defer c.Close() 4811 io.WriteString(c, "GET / HTTP/1.1\r\nHost: foo\r\n\r\n") 4812 <-inHandler 4813 c.Close() // this should trigger the context being done 4814 <-handlerDone 4815 } 4816 4817 func TestServerContext_ServerContextKey(t *testing.T) { 4818 run(t, testServerContext_ServerContextKey) 4819 } 4820 func testServerContext_ServerContextKey(t *testing.T, mode testMode) { 4821 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 4822 ctx := r.Context() 4823 got := ctx.Value(ServerContextKey) 4824 if _, ok := got.(*Server); !ok { 4825 t.Errorf("context value = %T; want *http.Server", got) 4826 } 4827 })) 4828 res, err := cst.c.Get(cst.ts.URL) 4829 if err != nil { 4830 t.Fatal(err) 4831 } 4832 res.Body.Close() 4833 } 4834 4835 func TestServerContext_LocalAddrContextKey(t *testing.T) { 4836 run(t, testServerContext_LocalAddrContextKey) 4837 } 4838 func testServerContext_LocalAddrContextKey(t *testing.T, mode testMode) { 4839 ch := make(chan any, 1) 4840 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 4841 ch <- r.Context().Value(LocalAddrContextKey) 4842 })) 4843 if _, err := cst.c.Head(cst.ts.URL); err != nil { 4844 t.Fatal(err) 4845 } 4846 4847 host := cst.ts.Listener.Addr().String() 4848 got := <-ch 4849 if addr, ok := got.(net.Addr); !ok { 4850 t.Errorf("local addr value = %T; want net.Addr", got) 4851 } else if fmt.Sprint(addr) != host { 4852 t.Errorf("local addr = %v; want %v", addr, host) 4853 } 4854 } 4855 4856 // https://golang.org/issue/15960 4857 func TestHandlerSetTransferEncodingChunked(t *testing.T) { 4858 setParallel(t) 4859 defer afterTest(t) 4860 ht := newHandlerTest(HandlerFunc(func(w ResponseWriter, r *Request) { 4861 w.Header().Set("Transfer-Encoding", "chunked") 4862 w.Write([]byte("hello")) 4863 })) 4864 resp := ht.rawResponse("GET / HTTP/1.1\nHost: foo") 4865 const hdr = "Transfer-Encoding: chunked" 4866 if n := strings.Count(resp, hdr); n != 1 { 4867 t.Errorf("want 1 occurrence of %q in response, got %v\nresponse: %v", hdr, n, resp) 4868 } 4869 } 4870 4871 // https://golang.org/issue/16063 4872 func TestHandlerSetTransferEncodingGzip(t *testing.T) { 4873 setParallel(t) 4874 defer afterTest(t) 4875 ht := newHandlerTest(HandlerFunc(func(w ResponseWriter, r *Request) { 4876 w.Header().Set("Transfer-Encoding", "gzip") 4877 gz := gzip.NewWriter(w) 4878 gz.Write([]byte("hello")) 4879 gz.Close() 4880 })) 4881 resp := ht.rawResponse("GET / HTTP/1.1\nHost: foo") 4882 for _, v := range []string{"gzip", "chunked"} { 4883 hdr := "Transfer-Encoding: " + v 4884 if n := strings.Count(resp, hdr); n != 1 { 4885 t.Errorf("want 1 occurrence of %q in response, got %v\nresponse: %v", hdr, n, resp) 4886 } 4887 } 4888 } 4889 4890 func BenchmarkClientServer(b *testing.B) { 4891 run(b, benchmarkClientServer, []testMode{http1Mode, https1Mode, http2Mode}) 4892 } 4893 func benchmarkClientServer(b *testing.B, mode testMode) { 4894 b.ReportAllocs() 4895 b.StopTimer() 4896 ts := newClientServerTest(b, mode, HandlerFunc(func(rw ResponseWriter, r *Request) { 4897 fmt.Fprintf(rw, "Hello world.\n") 4898 })).ts 4899 b.StartTimer() 4900 4901 c := ts.Client() 4902 for i := 0; i < b.N; i++ { 4903 res, err := c.Get(ts.URL) 4904 if err != nil { 4905 b.Fatal("Get:", err) 4906 } 4907 all, err := io.ReadAll(res.Body) 4908 res.Body.Close() 4909 if err != nil { 4910 b.Fatal("ReadAll:", err) 4911 } 4912 body := string(all) 4913 if body != "Hello world.\n" { 4914 b.Fatal("Got body:", body) 4915 } 4916 } 4917 4918 b.StopTimer() 4919 } 4920 4921 func BenchmarkClientServerParallel(b *testing.B) { 4922 for _, parallelism := range []int{4, 64} { 4923 b.Run(fmt.Sprint(parallelism), func(b *testing.B) { 4924 run(b, func(b *testing.B, mode testMode) { 4925 benchmarkClientServerParallel(b, parallelism, mode) 4926 }, []testMode{http1Mode, https1Mode, http2Mode}) 4927 }) 4928 } 4929 } 4930 4931 func benchmarkClientServerParallel(b *testing.B, parallelism int, mode testMode) { 4932 b.ReportAllocs() 4933 ts := newClientServerTest(b, mode, HandlerFunc(func(rw ResponseWriter, r *Request) { 4934 fmt.Fprintf(rw, "Hello world.\n") 4935 })).ts 4936 b.ResetTimer() 4937 b.SetParallelism(parallelism) 4938 b.RunParallel(func(pb *testing.PB) { 4939 c := ts.Client() 4940 for pb.Next() { 4941 res, err := c.Get(ts.URL) 4942 if err != nil { 4943 b.Logf("Get: %v", err) 4944 continue 4945 } 4946 all, err := io.ReadAll(res.Body) 4947 res.Body.Close() 4948 if err != nil { 4949 b.Logf("ReadAll: %v", err) 4950 continue 4951 } 4952 body := string(all) 4953 if body != "Hello world.\n" { 4954 panic("Got body: " + body) 4955 } 4956 } 4957 }) 4958 } 4959 4960 // A benchmark for profiling the server without the HTTP client code. 4961 // The client code runs in a subprocess. 4962 // 4963 // For use like: 4964 // 4965 // $ go test -c 4966 // $ ./http.test -test.run=XX -test.bench=BenchmarkServer -test.benchtime=15s -test.cpuprofile=http.prof 4967 // $ go tool pprof http.test http.prof 4968 // (pprof) web 4969 func BenchmarkServer(b *testing.B) { 4970 b.ReportAllocs() 4971 // Child process mode; 4972 if url := os.Getenv("TEST_BENCH_SERVER_URL"); url != "" { 4973 n, err := strconv.Atoi(os.Getenv("TEST_BENCH_CLIENT_N")) 4974 if err != nil { 4975 panic(err) 4976 } 4977 for i := 0; i < n; i++ { 4978 res, err := Get(url) 4979 if err != nil { 4980 log.Panicf("Get: %v", err) 4981 } 4982 all, err := io.ReadAll(res.Body) 4983 res.Body.Close() 4984 if err != nil { 4985 log.Panicf("ReadAll: %v", err) 4986 } 4987 body := string(all) 4988 if body != "Hello world.\n" { 4989 log.Panicf("Got body: %q", body) 4990 } 4991 } 4992 os.Exit(0) 4993 return 4994 } 4995 4996 var res = []byte("Hello world.\n") 4997 b.StopTimer() 4998 ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, r *Request) { 4999 rw.Header().Set("Content-Type", "text/html; charset=utf-8") 5000 rw.Write(res) 5001 })) 5002 defer ts.Close() 5003 b.StartTimer() 5004 5005 cmd := exec.Command(os.Args[0], "-test.run=XXXX", "-test.bench=BenchmarkServer$") 5006 cmd.Env = append([]string{ 5007 fmt.Sprintf("TEST_BENCH_CLIENT_N=%d", b.N), 5008 fmt.Sprintf("TEST_BENCH_SERVER_URL=%s", ts.URL), 5009 }, os.Environ()...) 5010 out, err := cmd.CombinedOutput() 5011 if err != nil { 5012 b.Errorf("Test failure: %v, with output: %s", err, out) 5013 } 5014 } 5015 5016 // getNoBody wraps Get but closes any Response.Body before returning the response. 5017 func getNoBody(urlStr string) (*Response, error) { 5018 res, err := Get(urlStr) 5019 if err != nil { 5020 return nil, err 5021 } 5022 res.Body.Close() 5023 return res, nil 5024 } 5025 5026 // A benchmark for profiling the client without the HTTP server code. 5027 // The server code runs in a subprocess. 5028 func BenchmarkClient(b *testing.B) { 5029 b.ReportAllocs() 5030 b.StopTimer() 5031 defer afterTest(b) 5032 5033 var data = []byte("Hello world.\n") 5034 if server := os.Getenv("TEST_BENCH_SERVER"); server != "" { 5035 // Server process mode. 5036 port := os.Getenv("TEST_BENCH_SERVER_PORT") // can be set by user 5037 if port == "" { 5038 port = "0" 5039 } 5040 ln, err := net.Listen("tcp", "localhost:"+port) 5041 if err != nil { 5042 fmt.Fprintln(os.Stderr, err.Error()) 5043 os.Exit(1) 5044 } 5045 fmt.Println(ln.Addr().String()) 5046 HandleFunc("/", func(w ResponseWriter, r *Request) { 5047 r.ParseForm() 5048 if r.Form.Get("stop") != "" { 5049 os.Exit(0) 5050 } 5051 w.Header().Set("Content-Type", "text/html; charset=utf-8") 5052 w.Write(data) 5053 }) 5054 var srv Server 5055 log.Fatal(srv.Serve(ln)) 5056 } 5057 5058 // Start server process. 5059 ctx, cancel := context.WithCancel(context.Background()) 5060 cmd := testenv.CommandContext(b, ctx, os.Args[0], "-test.run=XXXX", "-test.bench=BenchmarkClient$") 5061 cmd.Env = append(cmd.Environ(), "TEST_BENCH_SERVER=yes") 5062 cmd.Stderr = os.Stderr 5063 stdout, err := cmd.StdoutPipe() 5064 if err != nil { 5065 b.Fatal(err) 5066 } 5067 if err := cmd.Start(); err != nil { 5068 b.Fatalf("subprocess failed to start: %v", err) 5069 } 5070 5071 done := make(chan error, 1) 5072 go func() { 5073 done <- cmd.Wait() 5074 close(done) 5075 }() 5076 defer func() { 5077 cancel() 5078 <-done 5079 }() 5080 5081 // Wait for the server in the child process to respond and tell us 5082 // its listening address, once it's started listening: 5083 bs := bufio.NewScanner(stdout) 5084 if !bs.Scan() { 5085 b.Fatalf("failed to read listening URL from child: %v", bs.Err()) 5086 } 5087 url := "http://" + strings.TrimSpace(bs.Text()) + "/" 5088 if _, err := getNoBody(url); err != nil { 5089 b.Fatalf("initial probe of child process failed: %v", err) 5090 } 5091 5092 // Do b.N requests to the server. 5093 b.StartTimer() 5094 for i := 0; i < b.N; i++ { 5095 res, err := Get(url) 5096 if err != nil { 5097 b.Fatalf("Get: %v", err) 5098 } 5099 body, err := io.ReadAll(res.Body) 5100 res.Body.Close() 5101 if err != nil { 5102 b.Fatalf("ReadAll: %v", err) 5103 } 5104 if !bytes.Equal(body, data) { 5105 b.Fatalf("Got body: %q", body) 5106 } 5107 } 5108 b.StopTimer() 5109 5110 // Instruct server process to stop. 5111 getNoBody(url + "?stop=yes") 5112 if err := <-done; err != nil { 5113 b.Fatalf("subprocess failed: %v", err) 5114 } 5115 } 5116 5117 func BenchmarkServerFakeConnNoKeepAlive(b *testing.B) { 5118 b.ReportAllocs() 5119 req := reqBytes(`GET / HTTP/1.0 5120 Host: golang.org 5121 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 5122 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17 5123 Accept-Encoding: gzip,deflate,sdch 5124 Accept-Language: en-US,en;q=0.8 5125 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 5126 `) 5127 res := []byte("Hello world!\n") 5128 5129 conn := &testConn{ 5130 // testConn.Close will not push into the channel 5131 // if it's full. 5132 closec: make(chan bool, 1), 5133 } 5134 handler := HandlerFunc(func(rw ResponseWriter, r *Request) { 5135 rw.Header().Set("Content-Type", "text/html; charset=utf-8") 5136 rw.Write(res) 5137 }) 5138 ln := new(oneConnListener) 5139 for i := 0; i < b.N; i++ { 5140 conn.readBuf.Reset() 5141 conn.writeBuf.Reset() 5142 conn.readBuf.Write(req) 5143 ln.conn = conn 5144 Serve(ln, handler) 5145 <-conn.closec 5146 } 5147 } 5148 5149 // repeatReader reads content count times, then EOFs. 5150 type repeatReader struct { 5151 content []byte 5152 count int 5153 off int 5154 } 5155 5156 func (r *repeatReader) Read(p []byte) (n int, err error) { 5157 if r.count <= 0 { 5158 return 0, io.EOF 5159 } 5160 n = copy(p, r.content[r.off:]) 5161 r.off += n 5162 if r.off == len(r.content) { 5163 r.count-- 5164 r.off = 0 5165 } 5166 return 5167 } 5168 5169 func BenchmarkServerFakeConnWithKeepAlive(b *testing.B) { 5170 b.ReportAllocs() 5171 5172 req := reqBytes(`GET / HTTP/1.1 5173 Host: golang.org 5174 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 5175 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17 5176 Accept-Encoding: gzip,deflate,sdch 5177 Accept-Language: en-US,en;q=0.8 5178 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 5179 `) 5180 res := []byte("Hello world!\n") 5181 5182 conn := &rwTestConn{ 5183 Reader: &repeatReader{content: req, count: b.N}, 5184 Writer: io.Discard, 5185 closec: make(chan bool, 1), 5186 } 5187 handled := 0 5188 handler := HandlerFunc(func(rw ResponseWriter, r *Request) { 5189 handled++ 5190 rw.Header().Set("Content-Type", "text/html; charset=utf-8") 5191 rw.Write(res) 5192 }) 5193 ln := &oneConnListener{conn: conn} 5194 go Serve(ln, handler) 5195 <-conn.closec 5196 if b.N != handled { 5197 b.Errorf("b.N=%d but handled %d", b.N, handled) 5198 } 5199 } 5200 5201 // same as above, but representing the most simple possible request 5202 // and handler. Notably: the handler does not call rw.Header(). 5203 func BenchmarkServerFakeConnWithKeepAliveLite(b *testing.B) { 5204 b.ReportAllocs() 5205 5206 req := reqBytes(`GET / HTTP/1.1 5207 Host: golang.org 5208 `) 5209 res := []byte("Hello world!\n") 5210 5211 conn := &rwTestConn{ 5212 Reader: &repeatReader{content: req, count: b.N}, 5213 Writer: io.Discard, 5214 closec: make(chan bool, 1), 5215 } 5216 handled := 0 5217 handler := HandlerFunc(func(rw ResponseWriter, r *Request) { 5218 handled++ 5219 rw.Write(res) 5220 }) 5221 ln := &oneConnListener{conn: conn} 5222 go Serve(ln, handler) 5223 <-conn.closec 5224 if b.N != handled { 5225 b.Errorf("b.N=%d but handled %d", b.N, handled) 5226 } 5227 } 5228 5229 const someResponse = "<html>some response</html>" 5230 5231 // A Response that's just no bigger than 2KB, the buffer-before-chunking threshold. 5232 var response = bytes.Repeat([]byte(someResponse), 2<<10/len(someResponse)) 5233 5234 // Both Content-Type and Content-Length set. Should be no buffering. 5235 func BenchmarkServerHandlerTypeLen(b *testing.B) { 5236 benchmarkHandler(b, HandlerFunc(func(w ResponseWriter, r *Request) { 5237 w.Header().Set("Content-Type", "text/html") 5238 w.Header().Set("Content-Length", strconv.Itoa(len(response))) 5239 w.Write(response) 5240 })) 5241 } 5242 5243 // A Content-Type is set, but no length. No sniffing, but will count the Content-Length. 5244 func BenchmarkServerHandlerNoLen(b *testing.B) { 5245 benchmarkHandler(b, HandlerFunc(func(w ResponseWriter, r *Request) { 5246 w.Header().Set("Content-Type", "text/html") 5247 w.Write(response) 5248 })) 5249 } 5250 5251 // A Content-Length is set, but the Content-Type will be sniffed. 5252 func BenchmarkServerHandlerNoType(b *testing.B) { 5253 benchmarkHandler(b, HandlerFunc(func(w ResponseWriter, r *Request) { 5254 w.Header().Set("Content-Length", strconv.Itoa(len(response))) 5255 w.Write(response) 5256 })) 5257 } 5258 5259 // Neither a Content-Type or Content-Length, so sniffed and counted. 5260 func BenchmarkServerHandlerNoHeader(b *testing.B) { 5261 benchmarkHandler(b, HandlerFunc(func(w ResponseWriter, r *Request) { 5262 w.Write(response) 5263 })) 5264 } 5265 5266 func benchmarkHandler(b *testing.B, h Handler) { 5267 b.ReportAllocs() 5268 req := reqBytes(`GET / HTTP/1.1 5269 Host: golang.org 5270 `) 5271 conn := &rwTestConn{ 5272 Reader: &repeatReader{content: req, count: b.N}, 5273 Writer: io.Discard, 5274 closec: make(chan bool, 1), 5275 } 5276 handled := 0 5277 handler := HandlerFunc(func(rw ResponseWriter, r *Request) { 5278 handled++ 5279 h.ServeHTTP(rw, r) 5280 }) 5281 ln := &oneConnListener{conn: conn} 5282 go Serve(ln, handler) 5283 <-conn.closec 5284 if b.N != handled { 5285 b.Errorf("b.N=%d but handled %d", b.N, handled) 5286 } 5287 } 5288 5289 func BenchmarkServerHijack(b *testing.B) { 5290 b.ReportAllocs() 5291 req := reqBytes(`GET / HTTP/1.1 5292 Host: golang.org 5293 `) 5294 h := HandlerFunc(func(w ResponseWriter, r *Request) { 5295 conn, _, err := w.(Hijacker).Hijack() 5296 if err != nil { 5297 panic(err) 5298 } 5299 conn.Close() 5300 }) 5301 conn := &rwTestConn{ 5302 Writer: io.Discard, 5303 closec: make(chan bool, 1), 5304 } 5305 ln := &oneConnListener{conn: conn} 5306 for i := 0; i < b.N; i++ { 5307 conn.Reader = bytes.NewReader(req) 5308 ln.conn = conn 5309 Serve(ln, h) 5310 <-conn.closec 5311 } 5312 } 5313 5314 func BenchmarkCloseNotifier(b *testing.B) { run(b, benchmarkCloseNotifier, []testMode{http1Mode}) } 5315 func benchmarkCloseNotifier(b *testing.B, mode testMode) { 5316 b.ReportAllocs() 5317 b.StopTimer() 5318 sawClose := make(chan bool) 5319 ts := newClientServerTest(b, mode, HandlerFunc(func(rw ResponseWriter, req *Request) { 5320 <-rw.(CloseNotifier).CloseNotify() 5321 sawClose <- true 5322 })).ts 5323 b.StartTimer() 5324 for i := 0; i < b.N; i++ { 5325 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 5326 if err != nil { 5327 b.Fatalf("error dialing: %v", err) 5328 } 5329 _, err = fmt.Fprintf(conn, "GET / HTTP/1.1\r\nConnection: keep-alive\r\nHost: foo\r\n\r\n") 5330 if err != nil { 5331 b.Fatal(err) 5332 } 5333 conn.Close() 5334 <-sawClose 5335 } 5336 b.StopTimer() 5337 } 5338 5339 // Verify this doesn't race (Issue 16505) 5340 func TestConcurrentServerServe(t *testing.T) { 5341 setParallel(t) 5342 for i := 0; i < 100; i++ { 5343 ln1 := &oneConnListener{conn: nil} 5344 ln2 := &oneConnListener{conn: nil} 5345 srv := Server{} 5346 go func() { srv.Serve(ln1) }() 5347 go func() { srv.Serve(ln2) }() 5348 } 5349 } 5350 5351 func TestServerIdleTimeout(t *testing.T) { run(t, testServerIdleTimeout, []testMode{http1Mode}) } 5352 func testServerIdleTimeout(t *testing.T, mode testMode) { 5353 if testing.Short() { 5354 t.Skip("skipping in short mode") 5355 } 5356 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 5357 io.Copy(io.Discard, r.Body) 5358 io.WriteString(w, r.RemoteAddr) 5359 }), func(ts *httptest.Server) { 5360 ts.Config.ReadHeaderTimeout = 1 * time.Second 5361 ts.Config.IdleTimeout = 2 * time.Second 5362 }).ts 5363 c := ts.Client() 5364 5365 get := func() string { 5366 res, err := c.Get(ts.URL) 5367 if err != nil { 5368 t.Fatal(err) 5369 } 5370 defer res.Body.Close() 5371 slurp, err := io.ReadAll(res.Body) 5372 if err != nil { 5373 t.Fatal(err) 5374 } 5375 return string(slurp) 5376 } 5377 5378 a1, a2 := get(), get() 5379 if a1 != a2 { 5380 t.Fatalf("did requests on different connections") 5381 } 5382 time.Sleep(3 * time.Second) 5383 a3 := get() 5384 if a2 == a3 { 5385 t.Fatal("request three unexpectedly on same connection") 5386 } 5387 5388 // And test that ReadHeaderTimeout still works: 5389 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 5390 if err != nil { 5391 t.Fatal(err) 5392 } 5393 defer conn.Close() 5394 conn.Write([]byte("GET / HTTP/1.1\r\nHost: foo.com\r\n")) 5395 time.Sleep(2 * time.Second) 5396 if _, err := io.CopyN(io.Discard, conn, 1); err == nil { 5397 t.Fatal("copy byte succeeded; want err") 5398 } 5399 } 5400 5401 func get(t *testing.T, c *Client, url string) string { 5402 res, err := c.Get(url) 5403 if err != nil { 5404 t.Fatal(err) 5405 } 5406 defer res.Body.Close() 5407 slurp, err := io.ReadAll(res.Body) 5408 if err != nil { 5409 t.Fatal(err) 5410 } 5411 return string(slurp) 5412 } 5413 5414 // Tests that calls to Server.SetKeepAlivesEnabled(false) closes any 5415 // currently-open connections. 5416 func TestServerSetKeepAlivesEnabledClosesConns(t *testing.T) { 5417 run(t, testServerSetKeepAlivesEnabledClosesConns, []testMode{http1Mode}) 5418 } 5419 func testServerSetKeepAlivesEnabledClosesConns(t *testing.T, mode testMode) { 5420 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 5421 io.WriteString(w, r.RemoteAddr) 5422 })).ts 5423 5424 c := ts.Client() 5425 tr := c.Transport.(*Transport) 5426 5427 get := func() string { return get(t, c, ts.URL) } 5428 5429 a1, a2 := get(), get() 5430 if a1 == a2 { 5431 t.Logf("made two requests from a single conn %q (as expected)", a1) 5432 } else { 5433 t.Errorf("server reported requests from %q and %q; expected same connection", a1, a2) 5434 } 5435 5436 // The two requests should have used the same connection, 5437 // and there should not have been a second connection that 5438 // was created by racing dial against reuse. 5439 // (The first get was completed when the second get started.) 5440 if conns := tr.IdleConnStrsForTesting(); len(conns) != 1 { 5441 t.Errorf("found %d idle conns (%q); want 1", len(conns), conns) 5442 } 5443 5444 // SetKeepAlivesEnabled should discard idle conns. 5445 ts.Config.SetKeepAlivesEnabled(false) 5446 5447 waitCondition(t, 10*time.Millisecond, func(d time.Duration) bool { 5448 if conns := tr.IdleConnStrsForTesting(); len(conns) > 0 { 5449 if d > 0 { 5450 t.Logf("idle conns %v after SetKeepAlivesEnabled called = %q; waiting for empty", d, conns) 5451 } 5452 return false 5453 } 5454 return true 5455 }) 5456 5457 // If we make a third request it should use a new connection, but in general 5458 // we have no way to verify that: the new connection could happen to reuse the 5459 // exact same ports from the previous connection. 5460 } 5461 5462 func TestServerShutdown(t *testing.T) { run(t, testServerShutdown) } 5463 func testServerShutdown(t *testing.T, mode testMode) { 5464 var cst *clientServerTest 5465 5466 var once sync.Once 5467 statesRes := make(chan map[ConnState]int, 1) 5468 shutdownRes := make(chan error, 1) 5469 gotOnShutdown := make(chan struct{}) 5470 handler := HandlerFunc(func(w ResponseWriter, r *Request) { 5471 first := false 5472 once.Do(func() { 5473 statesRes <- cst.ts.Config.ExportAllConnsByState() 5474 go func() { 5475 shutdownRes <- cst.ts.Config.Shutdown(context.Background()) 5476 }() 5477 first = true 5478 }) 5479 5480 if first { 5481 // Shutdown is graceful, so it should not interrupt this in-flight response 5482 // but should reject new requests. (Since this request is still in flight, 5483 // the server's port should not be reused for another server yet.) 5484 <-gotOnShutdown 5485 // TODO(#59038): The HTTP/2 server empirically does not always reject new 5486 // requests. As a workaround, loop until we see a failure. 5487 for !t.Failed() { 5488 res, err := cst.c.Get(cst.ts.URL) 5489 if err != nil { 5490 break 5491 } 5492 out, _ := io.ReadAll(res.Body) 5493 res.Body.Close() 5494 if mode == http2Mode { 5495 t.Logf("%v: unexpected success (%q). Listener should be closed before OnShutdown is called.", cst.ts.URL, out) 5496 t.Logf("Retrying to work around https://go.dev/issue/59038.") 5497 continue 5498 } 5499 t.Errorf("%v: unexpected success (%q). Listener should be closed before OnShutdown is called.", cst.ts.URL, out) 5500 } 5501 } 5502 5503 io.WriteString(w, r.RemoteAddr) 5504 }) 5505 5506 cst = newClientServerTest(t, mode, handler, func(srv *httptest.Server) { 5507 srv.Config.RegisterOnShutdown(func() { close(gotOnShutdown) }) 5508 }) 5509 5510 out := get(t, cst.c, cst.ts.URL) // calls t.Fail on failure 5511 t.Logf("%v: %q", cst.ts.URL, out) 5512 5513 if err := <-shutdownRes; err != nil { 5514 t.Fatalf("Shutdown: %v", err) 5515 } 5516 <-gotOnShutdown // Will hang if RegisterOnShutdown is broken. 5517 5518 if states := <-statesRes; states[StateActive] != 1 { 5519 t.Errorf("connection in wrong state, %v", states) 5520 } 5521 } 5522 5523 func TestServerShutdownStateNew(t *testing.T) { run(t, testServerShutdownStateNew) } 5524 func testServerShutdownStateNew(t *testing.T, mode testMode) { 5525 if testing.Short() { 5526 t.Skip("test takes 5-6 seconds; skipping in short mode") 5527 } 5528 5529 var connAccepted sync.WaitGroup 5530 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 5531 // nothing. 5532 }), func(ts *httptest.Server) { 5533 ts.Config.ConnState = func(conn net.Conn, state ConnState) { 5534 if state == StateNew { 5535 connAccepted.Done() 5536 } 5537 } 5538 }).ts 5539 5540 // Start a connection but never write to it. 5541 connAccepted.Add(1) 5542 c, err := net.Dial("tcp", ts.Listener.Addr().String()) 5543 if err != nil { 5544 t.Fatal(err) 5545 } 5546 defer c.Close() 5547 5548 // Wait for the connection to be accepted by the server. Otherwise, if 5549 // Shutdown happens to run first, the server will be closed when 5550 // encountering the connection, in which case it will be rejected 5551 // immediately. 5552 connAccepted.Wait() 5553 5554 shutdownRes := make(chan error, 1) 5555 go func() { 5556 shutdownRes <- ts.Config.Shutdown(context.Background()) 5557 }() 5558 readRes := make(chan error, 1) 5559 go func() { 5560 _, err := c.Read([]byte{0}) 5561 readRes <- err 5562 }() 5563 5564 // TODO(#59037): This timeout is hard-coded in closeIdleConnections. 5565 // It is undocumented, and some users may find it surprising. 5566 // Either document it, or switch to a less surprising behavior. 5567 const expectTimeout = 5 * time.Second 5568 5569 t0 := time.Now() 5570 select { 5571 case got := <-shutdownRes: 5572 d := time.Since(t0) 5573 if got != nil { 5574 t.Fatalf("shutdown error after %v: %v", d, err) 5575 } 5576 if d < expectTimeout/2 { 5577 t.Errorf("shutdown too soon after %v", d) 5578 } 5579 case <-time.After(expectTimeout * 3 / 2): 5580 t.Fatalf("timeout waiting for shutdown") 5581 } 5582 5583 // Wait for c.Read to unblock; should be already done at this point, 5584 // or within a few milliseconds. 5585 if err := <-readRes; err == nil { 5586 t.Error("expected error from Read") 5587 } 5588 } 5589 5590 // Issue 17878: tests that we can call Close twice. 5591 func TestServerCloseDeadlock(t *testing.T) { 5592 var s Server 5593 s.Close() 5594 s.Close() 5595 } 5596 5597 // Issue 17717: tests that Server.SetKeepAlivesEnabled is respected by 5598 // both HTTP/1 and HTTP/2. 5599 func TestServerKeepAlivesEnabled(t *testing.T) { run(t, testServerKeepAlivesEnabled, testNotParallel) } 5600 func testServerKeepAlivesEnabled(t *testing.T, mode testMode) { 5601 if mode == http2Mode { 5602 restore := ExportSetH2GoawayTimeout(10 * time.Millisecond) 5603 defer restore() 5604 } 5605 // Not parallel: messes with global variable. (http2goAwayTimeout) 5606 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {})) 5607 defer cst.close() 5608 srv := cst.ts.Config 5609 srv.SetKeepAlivesEnabled(false) 5610 for try := 0; try < 2; try++ { 5611 waitCondition(t, 10*time.Millisecond, func(d time.Duration) bool { 5612 if !srv.ExportAllConnsIdle() { 5613 if d > 0 { 5614 t.Logf("test server still has active conns after %v", d) 5615 } 5616 return false 5617 } 5618 return true 5619 }) 5620 conns := 0 5621 var info httptrace.GotConnInfo 5622 ctx := httptrace.WithClientTrace(context.Background(), &httptrace.ClientTrace{ 5623 GotConn: func(v httptrace.GotConnInfo) { 5624 conns++ 5625 info = v 5626 }, 5627 }) 5628 req, err := NewRequestWithContext(ctx, "GET", cst.ts.URL, nil) 5629 if err != nil { 5630 t.Fatal(err) 5631 } 5632 res, err := cst.c.Do(req) 5633 if err != nil { 5634 t.Fatal(err) 5635 } 5636 res.Body.Close() 5637 if conns != 1 { 5638 t.Fatalf("request %v: got %v conns, want 1", try, conns) 5639 } 5640 if info.Reused || info.WasIdle { 5641 t.Fatalf("request %v: Reused=%v (want false), WasIdle=%v (want false)", try, info.Reused, info.WasIdle) 5642 } 5643 } 5644 } 5645 5646 // Issue 18447: test that the Server's ReadTimeout is stopped while 5647 // the server's doing its 1-byte background read between requests, 5648 // waiting for the connection to maybe close. 5649 func TestServerCancelsReadTimeoutWhenIdle(t *testing.T) { run(t, testServerCancelsReadTimeoutWhenIdle) } 5650 func testServerCancelsReadTimeoutWhenIdle(t *testing.T, mode testMode) { 5651 runTimeSensitiveTest(t, []time.Duration{ 5652 10 * time.Millisecond, 5653 50 * time.Millisecond, 5654 250 * time.Millisecond, 5655 time.Second, 5656 2 * time.Second, 5657 }, func(t *testing.T, timeout time.Duration) error { 5658 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 5659 select { 5660 case <-time.After(2 * timeout): 5661 fmt.Fprint(w, "ok") 5662 case <-r.Context().Done(): 5663 fmt.Fprint(w, r.Context().Err()) 5664 } 5665 }), func(ts *httptest.Server) { 5666 ts.Config.ReadTimeout = timeout 5667 }).ts 5668 5669 c := ts.Client() 5670 5671 res, err := c.Get(ts.URL) 5672 if err != nil { 5673 return fmt.Errorf("Get: %v", err) 5674 } 5675 slurp, err := io.ReadAll(res.Body) 5676 res.Body.Close() 5677 if err != nil { 5678 return fmt.Errorf("Body ReadAll: %v", err) 5679 } 5680 if string(slurp) != "ok" { 5681 return fmt.Errorf("got: %q, want ok", slurp) 5682 } 5683 return nil 5684 }) 5685 } 5686 5687 // Issue 54784: test that the Server's ReadHeaderTimeout only starts once the 5688 // beginning of a request has been received, rather than including time the 5689 // connection spent idle. 5690 func TestServerCancelsReadHeaderTimeoutWhenIdle(t *testing.T) { 5691 run(t, testServerCancelsReadHeaderTimeoutWhenIdle, []testMode{http1Mode}) 5692 } 5693 func testServerCancelsReadHeaderTimeoutWhenIdle(t *testing.T, mode testMode) { 5694 runTimeSensitiveTest(t, []time.Duration{ 5695 10 * time.Millisecond, 5696 50 * time.Millisecond, 5697 250 * time.Millisecond, 5698 time.Second, 5699 2 * time.Second, 5700 }, func(t *testing.T, timeout time.Duration) error { 5701 ts := newClientServerTest(t, mode, serve(200), func(ts *httptest.Server) { 5702 ts.Config.ReadHeaderTimeout = timeout 5703 ts.Config.IdleTimeout = 0 // disable idle timeout 5704 }).ts 5705 5706 // rather than using an http.Client, create a single connection, so that 5707 // we can ensure this connection is not closed. 5708 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 5709 if err != nil { 5710 t.Fatalf("dial failed: %v", err) 5711 } 5712 br := bufio.NewReader(conn) 5713 defer conn.Close() 5714 5715 if _, err := conn.Write([]byte("GET / HTTP/1.1\r\nHost: e.com\r\n\r\n")); err != nil { 5716 return fmt.Errorf("writing first request failed: %v", err) 5717 } 5718 5719 if _, err := ReadResponse(br, nil); err != nil { 5720 return fmt.Errorf("first response (before timeout) failed: %v", err) 5721 } 5722 5723 // wait for longer than the server's ReadHeaderTimeout, and then send 5724 // another request 5725 time.Sleep(timeout * 3 / 2) 5726 5727 if _, err := conn.Write([]byte("GET / HTTP/1.1\r\nHost: e.com\r\n\r\n")); err != nil { 5728 return fmt.Errorf("writing second request failed: %v", err) 5729 } 5730 5731 if _, err := ReadResponse(br, nil); err != nil { 5732 return fmt.Errorf("second response (after timeout) failed: %v", err) 5733 } 5734 5735 return nil 5736 }) 5737 } 5738 5739 // runTimeSensitiveTest runs test with the provided durations until one passes. 5740 // If they all fail, t.Fatal is called with the last one's duration and error value. 5741 func runTimeSensitiveTest(t *testing.T, durations []time.Duration, test func(t *testing.T, d time.Duration) error) { 5742 for i, d := range durations { 5743 err := test(t, d) 5744 if err == nil { 5745 return 5746 } 5747 if i == len(durations)-1 { 5748 t.Fatalf("failed with duration %v: %v", d, err) 5749 } 5750 } 5751 } 5752 5753 // Issue 18535: test that the Server doesn't try to do a background 5754 // read if it's already done one. 5755 func TestServerDuplicateBackgroundRead(t *testing.T) { 5756 run(t, testServerDuplicateBackgroundRead, []testMode{http1Mode}) 5757 } 5758 func testServerDuplicateBackgroundRead(t *testing.T, mode testMode) { 5759 if runtime.GOOS == "netbsd" && runtime.GOARCH == "arm" { 5760 testenv.SkipFlaky(t, 24826) 5761 } 5762 5763 goroutines := 5 5764 requests := 2000 5765 if testing.Short() { 5766 goroutines = 3 5767 requests = 100 5768 } 5769 5770 hts := newClientServerTest(t, mode, HandlerFunc(NotFound)).ts 5771 5772 reqBytes := []byte("GET / HTTP/1.1\r\nHost: e.com\r\n\r\n") 5773 5774 var wg sync.WaitGroup 5775 for i := 0; i < goroutines; i++ { 5776 wg.Add(1) 5777 go func() { 5778 defer wg.Done() 5779 cn, err := net.Dial("tcp", hts.Listener.Addr().String()) 5780 if err != nil { 5781 t.Error(err) 5782 return 5783 } 5784 defer cn.Close() 5785 5786 wg.Add(1) 5787 go func() { 5788 defer wg.Done() 5789 io.Copy(io.Discard, cn) 5790 }() 5791 5792 for j := 0; j < requests; j++ { 5793 if t.Failed() { 5794 return 5795 } 5796 _, err := cn.Write(reqBytes) 5797 if err != nil { 5798 t.Error(err) 5799 return 5800 } 5801 } 5802 }() 5803 } 5804 wg.Wait() 5805 } 5806 5807 // Test that the bufio.Reader returned by Hijack includes any buffered 5808 // byte (from the Server's backgroundRead) in its buffer. We want the 5809 // Handler code to be able to tell that a byte is available via 5810 // bufio.Reader.Buffered(), without resorting to Reading it 5811 // (potentially blocking) to get at it. 5812 func TestServerHijackGetsBackgroundByte(t *testing.T) { 5813 run(t, testServerHijackGetsBackgroundByte, []testMode{http1Mode}) 5814 } 5815 func testServerHijackGetsBackgroundByte(t *testing.T, mode testMode) { 5816 if runtime.GOOS == "plan9" { 5817 t.Skip("skipping test; see https://golang.org/issue/18657") 5818 } 5819 done := make(chan struct{}) 5820 inHandler := make(chan bool, 1) 5821 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 5822 defer close(done) 5823 5824 // Tell the client to send more data after the GET request. 5825 inHandler <- true 5826 5827 conn, buf, err := w.(Hijacker).Hijack() 5828 if err != nil { 5829 t.Error(err) 5830 return 5831 } 5832 defer conn.Close() 5833 5834 peek, err := buf.Reader.Peek(3) 5835 if string(peek) != "foo" || err != nil { 5836 t.Errorf("Peek = %q, %v; want foo, nil", peek, err) 5837 } 5838 5839 select { 5840 case <-r.Context().Done(): 5841 t.Error("context unexpectedly canceled") 5842 default: 5843 } 5844 })).ts 5845 5846 cn, err := net.Dial("tcp", ts.Listener.Addr().String()) 5847 if err != nil { 5848 t.Fatal(err) 5849 } 5850 defer cn.Close() 5851 if _, err := cn.Write([]byte("GET / HTTP/1.1\r\nHost: e.com\r\n\r\n")); err != nil { 5852 t.Fatal(err) 5853 } 5854 <-inHandler 5855 if _, err := cn.Write([]byte("foo")); err != nil { 5856 t.Fatal(err) 5857 } 5858 5859 if err := cn.(*net.TCPConn).CloseWrite(); err != nil { 5860 t.Fatal(err) 5861 } 5862 <-done 5863 } 5864 5865 // Like TestServerHijackGetsBackgroundByte above but sending a 5866 // immediate 1MB of data to the server to fill up the server's 4KB 5867 // buffer. 5868 func TestServerHijackGetsBackgroundByte_big(t *testing.T) { 5869 run(t, testServerHijackGetsBackgroundByte_big, []testMode{http1Mode}) 5870 } 5871 func testServerHijackGetsBackgroundByte_big(t *testing.T, mode testMode) { 5872 if runtime.GOOS == "plan9" { 5873 t.Skip("skipping test; see https://golang.org/issue/18657") 5874 } 5875 done := make(chan struct{}) 5876 const size = 8 << 10 5877 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 5878 defer close(done) 5879 5880 conn, buf, err := w.(Hijacker).Hijack() 5881 if err != nil { 5882 t.Error(err) 5883 return 5884 } 5885 defer conn.Close() 5886 slurp, err := io.ReadAll(buf.Reader) 5887 if err != nil { 5888 t.Errorf("Copy: %v", err) 5889 } 5890 allX := true 5891 for _, v := range slurp { 5892 if v != 'x' { 5893 allX = false 5894 } 5895 } 5896 if len(slurp) != size { 5897 t.Errorf("read %d; want %d", len(slurp), size) 5898 } else if !allX { 5899 t.Errorf("read %q; want %d 'x'", slurp, size) 5900 } 5901 })).ts 5902 5903 cn, err := net.Dial("tcp", ts.Listener.Addr().String()) 5904 if err != nil { 5905 t.Fatal(err) 5906 } 5907 defer cn.Close() 5908 if _, err := fmt.Fprintf(cn, "GET / HTTP/1.1\r\nHost: e.com\r\n\r\n%s", 5909 strings.Repeat("x", size)); err != nil { 5910 t.Fatal(err) 5911 } 5912 if err := cn.(*net.TCPConn).CloseWrite(); err != nil { 5913 t.Fatal(err) 5914 } 5915 5916 <-done 5917 } 5918 5919 // Issue 18319: test that the Server validates the request method. 5920 func TestServerValidatesMethod(t *testing.T) { 5921 tests := []struct { 5922 method string 5923 want int 5924 }{ 5925 {"GET", 200}, 5926 {"GE(T", 400}, 5927 } 5928 for _, tt := range tests { 5929 conn := &testConn{closec: make(chan bool, 1)} 5930 io.WriteString(&conn.readBuf, tt.method+" / HTTP/1.1\r\nHost: foo.example\r\n\r\n") 5931 5932 ln := &oneConnListener{conn} 5933 go Serve(ln, serve(200)) 5934 <-conn.closec 5935 res, err := ReadResponse(bufio.NewReader(&conn.writeBuf), nil) 5936 if err != nil { 5937 t.Errorf("For %s, ReadResponse: %v", tt.method, res) 5938 continue 5939 } 5940 if res.StatusCode != tt.want { 5941 t.Errorf("For %s, Status = %d; want %d", tt.method, res.StatusCode, tt.want) 5942 } 5943 } 5944 } 5945 5946 // Listener for TestServerListenNotComparableListener. 5947 type eofListenerNotComparable []int 5948 5949 func (eofListenerNotComparable) Accept() (net.Conn, error) { return nil, io.EOF } 5950 func (eofListenerNotComparable) Addr() net.Addr { return nil } 5951 func (eofListenerNotComparable) Close() error { return nil } 5952 5953 // Issue 24812: don't crash on non-comparable Listener 5954 func TestServerListenNotComparableListener(t *testing.T) { 5955 var s Server 5956 s.Serve(make(eofListenerNotComparable, 1)) // used to panic 5957 } 5958 5959 // countCloseListener is a Listener wrapper that counts the number of Close calls. 5960 type countCloseListener struct { 5961 net.Listener 5962 closes int32 // atomic 5963 } 5964 5965 func (p *countCloseListener) Close() error { 5966 var err error 5967 if n := atomic.AddInt32(&p.closes, 1); n == 1 && p.Listener != nil { 5968 err = p.Listener.Close() 5969 } 5970 return err 5971 } 5972 5973 // Issue 24803: don't call Listener.Close on Server.Shutdown. 5974 func TestServerCloseListenerOnce(t *testing.T) { 5975 setParallel(t) 5976 defer afterTest(t) 5977 5978 ln := newLocalListener(t) 5979 defer ln.Close() 5980 5981 cl := &countCloseListener{Listener: ln} 5982 server := &Server{} 5983 sdone := make(chan bool, 1) 5984 5985 go func() { 5986 server.Serve(cl) 5987 sdone <- true 5988 }() 5989 time.Sleep(10 * time.Millisecond) 5990 server.Shutdown(context.Background()) 5991 ln.Close() 5992 <-sdone 5993 5994 nclose := atomic.LoadInt32(&cl.closes) 5995 if nclose != 1 { 5996 t.Errorf("Close calls = %v; want 1", nclose) 5997 } 5998 } 5999 6000 // Issue 20239: don't block in Serve if Shutdown is called first. 6001 func TestServerShutdownThenServe(t *testing.T) { 6002 var srv Server 6003 cl := &countCloseListener{Listener: nil} 6004 srv.Shutdown(context.Background()) 6005 got := srv.Serve(cl) 6006 if got != ErrServerClosed { 6007 t.Errorf("Serve err = %v; want ErrServerClosed", got) 6008 } 6009 nclose := atomic.LoadInt32(&cl.closes) 6010 if nclose != 1 { 6011 t.Errorf("Close calls = %v; want 1", nclose) 6012 } 6013 } 6014 6015 // Issue 23351: document and test behavior of ServeMux with ports 6016 func TestStripPortFromHost(t *testing.T) { 6017 mux := NewServeMux() 6018 6019 mux.HandleFunc("example.com/", func(w ResponseWriter, r *Request) { 6020 fmt.Fprintf(w, "OK") 6021 }) 6022 mux.HandleFunc("example.com:9000/", func(w ResponseWriter, r *Request) { 6023 fmt.Fprintf(w, "uh-oh!") 6024 }) 6025 6026 req := httptest.NewRequest("GET", "http://example.com:9000/", nil) 6027 rw := httptest.NewRecorder() 6028 6029 mux.ServeHTTP(rw, req) 6030 6031 response := rw.Body.String() 6032 if response != "OK" { 6033 t.Errorf("Response gotten was %q", response) 6034 } 6035 } 6036 6037 func TestServerContexts(t *testing.T) { run(t, testServerContexts) } 6038 func testServerContexts(t *testing.T, mode testMode) { 6039 type baseKey struct{} 6040 type connKey struct{} 6041 ch := make(chan context.Context, 1) 6042 ts := newClientServerTest(t, mode, HandlerFunc(func(rw ResponseWriter, r *Request) { 6043 ch <- r.Context() 6044 }), func(ts *httptest.Server) { 6045 ts.Config.BaseContext = func(ln net.Listener) context.Context { 6046 if strings.Contains(reflect.TypeOf(ln).String(), "onceClose") { 6047 t.Errorf("unexpected onceClose listener type %T", ln) 6048 } 6049 return context.WithValue(context.Background(), baseKey{}, "base") 6050 } 6051 ts.Config.ConnContext = func(ctx context.Context, c net.Conn) context.Context { 6052 if got, want := ctx.Value(baseKey{}), "base"; got != want { 6053 t.Errorf("in ConnContext, base context key = %#v; want %q", got, want) 6054 } 6055 return context.WithValue(ctx, connKey{}, "conn") 6056 } 6057 }).ts 6058 res, err := ts.Client().Get(ts.URL) 6059 if err != nil { 6060 t.Fatal(err) 6061 } 6062 res.Body.Close() 6063 ctx := <-ch 6064 if got, want := ctx.Value(baseKey{}), "base"; got != want { 6065 t.Errorf("base context key = %#v; want %q", got, want) 6066 } 6067 if got, want := ctx.Value(connKey{}), "conn"; got != want { 6068 t.Errorf("conn context key = %#v; want %q", got, want) 6069 } 6070 } 6071 6072 // Issue 35750: check ConnContext not modifying context for other connections 6073 func TestConnContextNotModifyingAllContexts(t *testing.T) { 6074 run(t, testConnContextNotModifyingAllContexts) 6075 } 6076 func testConnContextNotModifyingAllContexts(t *testing.T, mode testMode) { 6077 type connKey struct{} 6078 ts := newClientServerTest(t, mode, HandlerFunc(func(rw ResponseWriter, r *Request) { 6079 rw.Header().Set("Connection", "close") 6080 }), func(ts *httptest.Server) { 6081 ts.Config.ConnContext = func(ctx context.Context, c net.Conn) context.Context { 6082 if got := ctx.Value(connKey{}); got != nil { 6083 t.Errorf("in ConnContext, unexpected context key = %#v", got) 6084 } 6085 return context.WithValue(ctx, connKey{}, "conn") 6086 } 6087 }).ts 6088 6089 var res *Response 6090 var err error 6091 6092 res, err = ts.Client().Get(ts.URL) 6093 if err != nil { 6094 t.Fatal(err) 6095 } 6096 res.Body.Close() 6097 6098 res, err = ts.Client().Get(ts.URL) 6099 if err != nil { 6100 t.Fatal(err) 6101 } 6102 res.Body.Close() 6103 } 6104 6105 // Issue 30710: ensure that as per the spec, a server responds 6106 // with 501 Not Implemented for unsupported transfer-encodings. 6107 func TestUnsupportedTransferEncodingsReturn501(t *testing.T) { 6108 run(t, testUnsupportedTransferEncodingsReturn501, []testMode{http1Mode}) 6109 } 6110 func testUnsupportedTransferEncodingsReturn501(t *testing.T, mode testMode) { 6111 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 6112 w.Write([]byte("Hello, World!")) 6113 })).ts 6114 6115 serverURL, err := url.Parse(cst.URL) 6116 if err != nil { 6117 t.Fatalf("Failed to parse server URL: %v", err) 6118 } 6119 6120 unsupportedTEs := []string{ 6121 "fugazi", 6122 "foo-bar", 6123 "unknown", 6124 `" chunked"`, 6125 } 6126 6127 for _, badTE := range unsupportedTEs { 6128 http1ReqBody := fmt.Sprintf(""+ 6129 "POST / HTTP/1.1\r\nConnection: close\r\n"+ 6130 "Host: localhost\r\nTransfer-Encoding: %s\r\n\r\n", badTE) 6131 6132 gotBody, err := fetchWireResponse(serverURL.Host, []byte(http1ReqBody)) 6133 if err != nil { 6134 t.Errorf("%q. unexpected error: %v", badTE, err) 6135 continue 6136 } 6137 6138 wantBody := fmt.Sprintf("" + 6139 "HTTP/1.1 501 Not Implemented\r\nContent-Type: text/plain; charset=utf-8\r\n" + 6140 "Connection: close\r\n\r\nUnsupported transfer encoding") 6141 6142 if string(gotBody) != wantBody { 6143 t.Errorf("%q. body\ngot\n%q\nwant\n%q", badTE, gotBody, wantBody) 6144 } 6145 } 6146 } 6147 6148 // Issue 31753: don't sniff when Content-Encoding is set 6149 func TestContentEncodingNoSniffing(t *testing.T) { run(t, testContentEncodingNoSniffing) } 6150 func testContentEncodingNoSniffing(t *testing.T, mode testMode) { 6151 type setting struct { 6152 name string 6153 body []byte 6154 6155 // setting contentEncoding as an interface instead of a string 6156 // directly, so as to differentiate between 3 states: 6157 // unset, empty string "" and set string "foo/bar". 6158 contentEncoding any 6159 wantContentType string 6160 } 6161 6162 settings := []*setting{ 6163 { 6164 name: "gzip content-encoding, gzipped", // don't sniff. 6165 contentEncoding: "application/gzip", 6166 wantContentType: "", 6167 body: func() []byte { 6168 buf := new(bytes.Buffer) 6169 gzw := gzip.NewWriter(buf) 6170 gzw.Write([]byte("doctype html><p>Hello</p>")) 6171 gzw.Close() 6172 return buf.Bytes() 6173 }(), 6174 }, 6175 { 6176 name: "zlib content-encoding, zlibbed", // don't sniff. 6177 contentEncoding: "application/zlib", 6178 wantContentType: "", 6179 body: func() []byte { 6180 buf := new(bytes.Buffer) 6181 zw := zlib.NewWriter(buf) 6182 zw.Write([]byte("doctype html><p>Hello</p>")) 6183 zw.Close() 6184 return buf.Bytes() 6185 }(), 6186 }, 6187 { 6188 name: "no content-encoding", // must sniff. 6189 wantContentType: "application/x-gzip", 6190 body: func() []byte { 6191 buf := new(bytes.Buffer) 6192 gzw := gzip.NewWriter(buf) 6193 gzw.Write([]byte("doctype html><p>Hello</p>")) 6194 gzw.Close() 6195 return buf.Bytes() 6196 }(), 6197 }, 6198 { 6199 name: "phony content-encoding", // don't sniff. 6200 contentEncoding: "foo/bar", 6201 body: []byte("doctype html><p>Hello</p>"), 6202 }, 6203 { 6204 name: "empty but set content-encoding", 6205 contentEncoding: "", 6206 wantContentType: "audio/mpeg", 6207 body: []byte("ID3"), 6208 }, 6209 } 6210 6211 for _, tt := range settings { 6212 t.Run(tt.name, func(t *testing.T) { 6213 cst := newClientServerTest(t, mode, HandlerFunc(func(rw ResponseWriter, r *Request) { 6214 if tt.contentEncoding != nil { 6215 rw.Header().Set("Content-Encoding", tt.contentEncoding.(string)) 6216 } 6217 rw.Write(tt.body) 6218 })) 6219 6220 res, err := cst.c.Get(cst.ts.URL) 6221 if err != nil { 6222 t.Fatalf("Failed to fetch URL: %v", err) 6223 } 6224 defer res.Body.Close() 6225 6226 if g, w := res.Header.Get("Content-Encoding"), tt.contentEncoding; g != w { 6227 if w != nil { // The case where contentEncoding was set explicitly. 6228 t.Errorf("Content-Encoding mismatch\n\tgot: %q\n\twant: %q", g, w) 6229 } else if g != "" { // "" should be the equivalent when the contentEncoding is unset. 6230 t.Errorf("Unexpected Content-Encoding %q", g) 6231 } 6232 } 6233 6234 if g, w := res.Header.Get("Content-Type"), tt.wantContentType; g != w { 6235 t.Errorf("Content-Type mismatch\n\tgot: %q\n\twant: %q", g, w) 6236 } 6237 }) 6238 } 6239 } 6240 6241 // Issue 30803: ensure that TimeoutHandler logs spurious 6242 // WriteHeader calls, for consistency with other Handlers. 6243 func TestTimeoutHandlerSuperfluousLogs(t *testing.T) { 6244 run(t, testTimeoutHandlerSuperfluousLogs, []testMode{http1Mode}) 6245 } 6246 func testTimeoutHandlerSuperfluousLogs(t *testing.T, mode testMode) { 6247 if testing.Short() { 6248 t.Skip("skipping in short mode") 6249 } 6250 6251 pc, curFile, _, _ := runtime.Caller(0) 6252 curFileBaseName := filepath.Base(curFile) 6253 testFuncName := runtime.FuncForPC(pc).Name() 6254 6255 timeoutMsg := "timed out here!" 6256 6257 tests := []struct { 6258 name string 6259 mustTimeout bool 6260 wantResp string 6261 }{ 6262 { 6263 name: "return before timeout", 6264 wantResp: "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n", 6265 }, 6266 { 6267 name: "return after timeout", 6268 mustTimeout: true, 6269 wantResp: fmt.Sprintf("HTTP/1.1 503 Service Unavailable\r\nContent-Length: %d\r\n\r\n%s", 6270 len(timeoutMsg), timeoutMsg), 6271 }, 6272 } 6273 6274 for _, tt := range tests { 6275 tt := tt 6276 t.Run(tt.name, func(t *testing.T) { 6277 exitHandler := make(chan bool, 1) 6278 defer close(exitHandler) 6279 lastLine := make(chan int, 1) 6280 6281 sh := HandlerFunc(func(w ResponseWriter, r *Request) { 6282 w.WriteHeader(404) 6283 w.WriteHeader(404) 6284 w.WriteHeader(404) 6285 w.WriteHeader(404) 6286 _, _, line, _ := runtime.Caller(0) 6287 lastLine <- line 6288 <-exitHandler 6289 }) 6290 6291 if !tt.mustTimeout { 6292 exitHandler <- true 6293 } 6294 6295 logBuf := new(strings.Builder) 6296 srvLog := log.New(logBuf, "", 0) 6297 // When expecting to timeout, we'll keep the duration short. 6298 dur := 20 * time.Millisecond 6299 if !tt.mustTimeout { 6300 // Otherwise, make it arbitrarily long to reduce the risk of flakes. 6301 dur = 10 * time.Second 6302 } 6303 th := TimeoutHandler(sh, dur, timeoutMsg) 6304 cst := newClientServerTest(t, mode, th, optWithServerLog(srvLog)) 6305 defer cst.close() 6306 6307 res, err := cst.c.Get(cst.ts.URL) 6308 if err != nil { 6309 t.Fatalf("Unexpected error: %v", err) 6310 } 6311 6312 // Deliberately removing the "Date" header since it is highly ephemeral 6313 // and will cause failure if we try to match it exactly. 6314 res.Header.Del("Date") 6315 res.Header.Del("Content-Type") 6316 6317 // Match the response. 6318 blob, _ := httputil.DumpResponse(res, true) 6319 if g, w := string(blob), tt.wantResp; g != w { 6320 t.Errorf("Response mismatch\nGot\n%q\n\nWant\n%q", g, w) 6321 } 6322 6323 // Given 4 w.WriteHeader calls, only the first one is valid 6324 // and the rest should be reported as the 3 spurious logs. 6325 logEntries := strings.Split(strings.TrimSpace(logBuf.String()), "\n") 6326 if g, w := len(logEntries), 3; g != w { 6327 blob, _ := json.MarshalIndent(logEntries, "", " ") 6328 t.Fatalf("Server logs count mismatch\ngot %d, want %d\n\nGot\n%s\n", g, w, blob) 6329 } 6330 6331 lastSpuriousLine := <-lastLine 6332 firstSpuriousLine := lastSpuriousLine - 3 6333 // Now ensure that the regexes match exactly. 6334 // "http: superfluous response.WriteHeader call from <fn>.func\d.\d (<curFile>:lastSpuriousLine-[1, 3]" 6335 for i, logEntry := range logEntries { 6336 wantLine := firstSpuriousLine + i 6337 pat := fmt.Sprintf("^http: superfluous response.WriteHeader call from %s.func\\d+.\\d+ \\(%s:%d\\)$", 6338 testFuncName, curFileBaseName, wantLine) 6339 re := regexp.MustCompile(pat) 6340 if !re.MatchString(logEntry) { 6341 t.Errorf("Log entry mismatch\n\t%s\ndoes not match\n\t%s", logEntry, pat) 6342 } 6343 } 6344 }) 6345 } 6346 } 6347 6348 // fetchWireResponse is a helper for dialing to host, 6349 // sending http1ReqBody as the payload and retrieving 6350 // the response as it was sent on the wire. 6351 func fetchWireResponse(host string, http1ReqBody []byte) ([]byte, error) { 6352 conn, err := net.Dial("tcp", host) 6353 if err != nil { 6354 return nil, err 6355 } 6356 defer conn.Close() 6357 6358 if _, err := conn.Write(http1ReqBody); err != nil { 6359 return nil, err 6360 } 6361 return io.ReadAll(conn) 6362 } 6363 6364 func BenchmarkResponseStatusLine(b *testing.B) { 6365 b.ReportAllocs() 6366 b.RunParallel(func(pb *testing.PB) { 6367 bw := bufio.NewWriter(io.Discard) 6368 var buf3 [3]byte 6369 for pb.Next() { 6370 Export_writeStatusLine(bw, true, 200, buf3[:]) 6371 } 6372 }) 6373 } 6374 6375 func TestDisableKeepAliveUpgrade(t *testing.T) { 6376 run(t, testDisableKeepAliveUpgrade, []testMode{http1Mode}) 6377 } 6378 func testDisableKeepAliveUpgrade(t *testing.T, mode testMode) { 6379 if testing.Short() { 6380 t.Skip("skipping in short mode") 6381 } 6382 6383 s := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 6384 w.Header().Set("Connection", "Upgrade") 6385 w.Header().Set("Upgrade", "someProto") 6386 w.WriteHeader(StatusSwitchingProtocols) 6387 c, buf, err := w.(Hijacker).Hijack() 6388 if err != nil { 6389 return 6390 } 6391 defer c.Close() 6392 6393 // Copy from the *bufio.ReadWriter, which may contain buffered data. 6394 // Copy to the net.Conn, to avoid buffering the output. 6395 io.Copy(c, buf) 6396 }), func(ts *httptest.Server) { 6397 ts.Config.SetKeepAlivesEnabled(false) 6398 }).ts 6399 6400 cl := s.Client() 6401 cl.Transport.(*Transport).DisableKeepAlives = true 6402 6403 resp, err := cl.Get(s.URL) 6404 if err != nil { 6405 t.Fatalf("failed to perform request: %v", err) 6406 } 6407 defer resp.Body.Close() 6408 6409 if resp.StatusCode != StatusSwitchingProtocols { 6410 t.Fatalf("unexpected status code: %v", resp.StatusCode) 6411 } 6412 6413 rwc, ok := resp.Body.(io.ReadWriteCloser) 6414 if !ok { 6415 t.Fatalf("Response.Body is not an io.ReadWriteCloser: %T", resp.Body) 6416 } 6417 6418 _, err = rwc.Write([]byte("hello")) 6419 if err != nil { 6420 t.Fatalf("failed to write to body: %v", err) 6421 } 6422 6423 b := make([]byte, 5) 6424 _, err = io.ReadFull(rwc, b) 6425 if err != nil { 6426 t.Fatalf("failed to read from body: %v", err) 6427 } 6428 6429 if string(b) != "hello" { 6430 t.Fatalf("unexpected value read from body:\ngot: %q\nwant: %q", b, "hello") 6431 } 6432 } 6433 6434 type tlogWriter struct{ t *testing.T } 6435 6436 func (w tlogWriter) Write(p []byte) (int, error) { 6437 w.t.Log(string(p)) 6438 return len(p), nil 6439 } 6440 6441 func TestWriteHeaderSwitchingProtocols(t *testing.T) { 6442 run(t, testWriteHeaderSwitchingProtocols, []testMode{http1Mode}) 6443 } 6444 func testWriteHeaderSwitchingProtocols(t *testing.T, mode testMode) { 6445 const wantBody = "want" 6446 const wantUpgrade = "someProto" 6447 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 6448 w.Header().Set("Connection", "Upgrade") 6449 w.Header().Set("Upgrade", wantUpgrade) 6450 w.WriteHeader(StatusSwitchingProtocols) 6451 NewResponseController(w).Flush() 6452 6453 // Writing headers or the body after sending a 101 header should fail. 6454 w.WriteHeader(200) 6455 if _, err := w.Write([]byte("x")); err == nil { 6456 t.Errorf("Write to body after 101 Switching Protocols unexpectedly succeeded") 6457 } 6458 6459 c, _, err := NewResponseController(w).Hijack() 6460 if err != nil { 6461 t.Errorf("Hijack: %v", err) 6462 return 6463 } 6464 defer c.Close() 6465 if _, err := c.Write([]byte(wantBody)); err != nil { 6466 t.Errorf("Write to hijacked body: %v", err) 6467 } 6468 }), func(ts *httptest.Server) { 6469 // Don't spam log with warning about superfluous WriteHeader call. 6470 ts.Config.ErrorLog = log.New(tlogWriter{t}, "log: ", 0) 6471 }).ts 6472 6473 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 6474 if err != nil { 6475 t.Fatalf("net.Dial: %v", err) 6476 } 6477 _, err = conn.Write([]byte("GET / HTTP/1.1\r\nHost: foo\r\n\r\n")) 6478 if err != nil { 6479 t.Fatalf("conn.Write: %v", err) 6480 } 6481 defer conn.Close() 6482 6483 r := bufio.NewReader(conn) 6484 res, err := ReadResponse(r, &Request{Method: "GET"}) 6485 if err != nil { 6486 t.Fatal("ReadResponse error:", err) 6487 } 6488 if res.StatusCode != StatusSwitchingProtocols { 6489 t.Errorf("Response StatusCode=%v, want 101", res.StatusCode) 6490 } 6491 if got := res.Header.Get("Upgrade"); got != wantUpgrade { 6492 t.Errorf("Response Upgrade header = %q, want %q", got, wantUpgrade) 6493 } 6494 body, err := io.ReadAll(r) 6495 if err != nil { 6496 t.Error(err) 6497 } 6498 if string(body) != wantBody { 6499 t.Errorf("Response body = %q, want %q", string(body), wantBody) 6500 } 6501 } 6502 6503 func TestMuxRedirectRelative(t *testing.T) { 6504 setParallel(t) 6505 req, err := ReadRequest(bufio.NewReader(strings.NewReader("GET http://example.com HTTP/1.1\r\nHost: test\r\n\r\n"))) 6506 if err != nil { 6507 t.Errorf("%s", err) 6508 } 6509 mux := NewServeMux() 6510 resp := httptest.NewRecorder() 6511 mux.ServeHTTP(resp, req) 6512 if got, want := resp.Header().Get("Location"), "/"; got != want { 6513 t.Errorf("Location header expected %q; got %q", want, got) 6514 } 6515 if got, want := resp.Code, StatusMovedPermanently; got != want { 6516 t.Errorf("Expected response code %d; got %d", want, got) 6517 } 6518 } 6519 6520 // TestQuerySemicolon tests the behavior of semicolons in queries. See Issue 25192. 6521 func TestQuerySemicolon(t *testing.T) { 6522 t.Cleanup(func() { afterTest(t) }) 6523 6524 tests := []struct { 6525 query string 6526 xNoSemicolons string 6527 xWithSemicolons string 6528 expectParseFormErr bool 6529 }{ 6530 {"?a=1;x=bad&x=good", "good", "bad", true}, 6531 {"?a=1;b=bad&x=good", "good", "good", true}, 6532 {"?a=1%3Bx=bad&x=good%3B", "good;", "good;", false}, 6533 {"?a=1;x=good;x=bad", "", "good", true}, 6534 } 6535 6536 run(t, func(t *testing.T, mode testMode) { 6537 for _, tt := range tests { 6538 t.Run(tt.query+"/allow=false", func(t *testing.T) { 6539 allowSemicolons := false 6540 testQuerySemicolon(t, mode, tt.query, tt.xNoSemicolons, allowSemicolons, tt.expectParseFormErr) 6541 }) 6542 t.Run(tt.query+"/allow=true", func(t *testing.T) { 6543 allowSemicolons, expectParseFormErr := true, false 6544 testQuerySemicolon(t, mode, tt.query, tt.xWithSemicolons, allowSemicolons, expectParseFormErr) 6545 }) 6546 } 6547 }) 6548 } 6549 6550 func testQuerySemicolon(t *testing.T, mode testMode, query string, wantX string, allowSemicolons, expectParseFormErr bool) { 6551 writeBackX := func(w ResponseWriter, r *Request) { 6552 x := r.URL.Query().Get("x") 6553 if expectParseFormErr { 6554 if err := r.ParseForm(); err == nil || !strings.Contains(err.Error(), "semicolon") { 6555 t.Errorf("expected error mentioning semicolons from ParseForm, got %v", err) 6556 } 6557 } else { 6558 if err := r.ParseForm(); err != nil { 6559 t.Errorf("expected no error from ParseForm, got %v", err) 6560 } 6561 } 6562 if got := r.FormValue("x"); x != got { 6563 t.Errorf("got %q from FormValue, want %q", got, x) 6564 } 6565 fmt.Fprintf(w, "%s", x) 6566 } 6567 6568 h := Handler(HandlerFunc(writeBackX)) 6569 if allowSemicolons { 6570 h = AllowQuerySemicolons(h) 6571 } 6572 6573 logBuf := &strings.Builder{} 6574 ts := newClientServerTest(t, mode, h, func(ts *httptest.Server) { 6575 ts.Config.ErrorLog = log.New(logBuf, "", 0) 6576 }).ts 6577 6578 req, _ := NewRequest("GET", ts.URL+query, nil) 6579 res, err := ts.Client().Do(req) 6580 if err != nil { 6581 t.Fatal(err) 6582 } 6583 slurp, _ := io.ReadAll(res.Body) 6584 res.Body.Close() 6585 if got, want := res.StatusCode, 200; got != want { 6586 t.Errorf("Status = %d; want = %d", got, want) 6587 } 6588 if got, want := string(slurp), wantX; got != want { 6589 t.Errorf("Body = %q; want = %q", got, want) 6590 } 6591 } 6592 6593 func TestMaxBytesHandler(t *testing.T) { 6594 setParallel(t) 6595 defer afterTest(t) 6596 6597 for _, maxSize := range []int64{100, 1_000, 1_000_000} { 6598 for _, requestSize := range []int64{100, 1_000, 1_000_000} { 6599 t.Run(fmt.Sprintf("max size %d request size %d", maxSize, requestSize), 6600 func(t *testing.T) { 6601 run(t, func(t *testing.T, mode testMode) { 6602 testMaxBytesHandler(t, mode, maxSize, requestSize) 6603 }) 6604 }) 6605 } 6606 } 6607 } 6608 6609 func testMaxBytesHandler(t *testing.T, mode testMode, maxSize, requestSize int64) { 6610 var ( 6611 handlerN int64 6612 handlerErr error 6613 ) 6614 echo := HandlerFunc(func(w ResponseWriter, r *Request) { 6615 var buf bytes.Buffer 6616 handlerN, handlerErr = io.Copy(&buf, r.Body) 6617 io.Copy(w, &buf) 6618 }) 6619 6620 ts := newClientServerTest(t, mode, MaxBytesHandler(echo, maxSize)).ts 6621 defer ts.Close() 6622 6623 c := ts.Client() 6624 6625 body := strings.Repeat("a", int(requestSize)) 6626 var wg sync.WaitGroup 6627 defer wg.Wait() 6628 getBody := func() (io.ReadCloser, error) { 6629 wg.Add(1) 6630 body := &wgReadCloser{ 6631 Reader: strings.NewReader(body), 6632 wg: &wg, 6633 } 6634 return body, nil 6635 } 6636 reqBody, _ := getBody() 6637 req, err := NewRequest("POST", ts.URL, reqBody) 6638 if err != nil { 6639 reqBody.Close() 6640 t.Fatal(err) 6641 } 6642 req.ContentLength = int64(len(body)) 6643 req.GetBody = getBody 6644 req.Header.Set("Content-Type", "text/plain") 6645 6646 var buf strings.Builder 6647 res, err := c.Do(req) 6648 if err != nil { 6649 t.Errorf("unexpected connection error: %v", err) 6650 } else { 6651 _, err = io.Copy(&buf, res.Body) 6652 res.Body.Close() 6653 if err != nil { 6654 t.Errorf("unexpected read error: %v", err) 6655 } 6656 } 6657 if handlerN > maxSize { 6658 t.Errorf("expected max request body %d; got %d", maxSize, handlerN) 6659 } 6660 if requestSize > maxSize && handlerErr == nil { 6661 t.Error("expected error on handler side; got nil") 6662 } 6663 if requestSize <= maxSize { 6664 if handlerErr != nil { 6665 t.Errorf("%d expected nil error on handler side; got %v", requestSize, handlerErr) 6666 } 6667 if handlerN != requestSize { 6668 t.Errorf("expected request of size %d; got %d", requestSize, handlerN) 6669 } 6670 } 6671 if buf.Len() != int(handlerN) { 6672 t.Errorf("expected echo of size %d; got %d", handlerN, buf.Len()) 6673 } 6674 } 6675 6676 func TestEarlyHints(t *testing.T) { 6677 ht := newHandlerTest(HandlerFunc(func(w ResponseWriter, r *Request) { 6678 h := w.Header() 6679 h.Add("Link", "</style.css>; rel=preload; as=style") 6680 h.Add("Link", "</script.js>; rel=preload; as=script") 6681 w.WriteHeader(StatusEarlyHints) 6682 6683 h.Add("Link", "</foo.js>; rel=preload; as=script") 6684 w.WriteHeader(StatusEarlyHints) 6685 6686 w.Write([]byte("stuff")) 6687 })) 6688 6689 got := ht.rawResponse("GET / HTTP/1.1\nHost: golang.org") 6690 expected := "HTTP/1.1 103 Early Hints\r\nLink: </style.css>; rel=preload; as=style\r\nLink: </script.js>; rel=preload; as=script\r\n\r\nHTTP/1.1 103 Early Hints\r\nLink: </style.css>; rel=preload; as=style\r\nLink: </script.js>; rel=preload; as=script\r\nLink: </foo.js>; rel=preload; as=script\r\n\r\nHTTP/1.1 200 OK\r\nLink: </style.css>; rel=preload; as=style\r\nLink: </script.js>; rel=preload; as=script\r\nLink: </foo.js>; rel=preload; as=script\r\nDate: " // dynamic content expected 6691 if !strings.Contains(got, expected) { 6692 t.Errorf("unexpected response; got %q; should start by %q", got, expected) 6693 } 6694 } 6695 func TestProcessing(t *testing.T) { 6696 ht := newHandlerTest(HandlerFunc(func(w ResponseWriter, r *Request) { 6697 w.WriteHeader(StatusProcessing) 6698 w.Write([]byte("stuff")) 6699 })) 6700 6701 got := ht.rawResponse("GET / HTTP/1.1\nHost: golang.org") 6702 expected := "HTTP/1.1 102 Processing\r\n\r\nHTTP/1.1 200 OK\r\nDate: " // dynamic content expected 6703 if !strings.Contains(got, expected) { 6704 t.Errorf("unexpected response; got %q; should start by %q", got, expected) 6705 } 6706 } 6707 6708 func TestParseFormCleanup(t *testing.T) { run(t, testParseFormCleanup) } 6709 func testParseFormCleanup(t *testing.T, mode testMode) { 6710 if mode == http2Mode { 6711 t.Skip("https://go.dev/issue/20253") 6712 } 6713 6714 const maxMemory = 1024 6715 const key = "file" 6716 6717 if runtime.GOOS == "windows" { 6718 // Windows sometimes refuses to remove a file that was just closed. 6719 t.Skip("https://go.dev/issue/25965") 6720 } 6721 6722 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 6723 r.ParseMultipartForm(maxMemory) 6724 f, _, err := r.FormFile(key) 6725 if err != nil { 6726 t.Errorf("r.FormFile(%q) = %v", key, err) 6727 return 6728 } 6729 of, ok := f.(*os.File) 6730 if !ok { 6731 t.Errorf("r.FormFile(%q) returned type %T, want *os.File", key, f) 6732 return 6733 } 6734 w.Write([]byte(of.Name())) 6735 })) 6736 6737 fBuf := new(bytes.Buffer) 6738 mw := multipart.NewWriter(fBuf) 6739 mf, err := mw.CreateFormFile(key, "myfile.txt") 6740 if err != nil { 6741 t.Fatal(err) 6742 } 6743 if _, err := mf.Write(bytes.Repeat([]byte("A"), maxMemory*2)); err != nil { 6744 t.Fatal(err) 6745 } 6746 if err := mw.Close(); err != nil { 6747 t.Fatal(err) 6748 } 6749 req, err := NewRequest("POST", cst.ts.URL, fBuf) 6750 if err != nil { 6751 t.Fatal(err) 6752 } 6753 req.Header.Set("Content-Type", mw.FormDataContentType()) 6754 res, err := cst.c.Do(req) 6755 if err != nil { 6756 t.Fatal(err) 6757 } 6758 defer res.Body.Close() 6759 fname, err := io.ReadAll(res.Body) 6760 if err != nil { 6761 t.Fatal(err) 6762 } 6763 cst.close() 6764 if _, err := os.Stat(string(fname)); !errors.Is(err, os.ErrNotExist) { 6765 t.Errorf("file %q exists after HTTP handler returned", string(fname)) 6766 } 6767 } 6768 6769 func TestHeadBody(t *testing.T) { 6770 const identityMode = false 6771 const chunkedMode = true 6772 run(t, func(t *testing.T, mode testMode) { 6773 t.Run("identity", func(t *testing.T) { testHeadBody(t, mode, identityMode, "HEAD") }) 6774 t.Run("chunked", func(t *testing.T) { testHeadBody(t, mode, chunkedMode, "HEAD") }) 6775 }) 6776 } 6777 6778 func TestGetBody(t *testing.T) { 6779 const identityMode = false 6780 const chunkedMode = true 6781 run(t, func(t *testing.T, mode testMode) { 6782 t.Run("identity", func(t *testing.T) { testHeadBody(t, mode, identityMode, "GET") }) 6783 t.Run("chunked", func(t *testing.T) { testHeadBody(t, mode, chunkedMode, "GET") }) 6784 }) 6785 } 6786 6787 func testHeadBody(t *testing.T, mode testMode, chunked bool, method string) { 6788 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { 6789 b, err := io.ReadAll(r.Body) 6790 if err != nil { 6791 t.Errorf("server reading body: %v", err) 6792 return 6793 } 6794 w.Header().Set("X-Request-Body", string(b)) 6795 w.Header().Set("Content-Length", "0") 6796 })) 6797 defer cst.close() 6798 for _, reqBody := range []string{ 6799 "", 6800 "", 6801 "request_body", 6802 "", 6803 } { 6804 var bodyReader io.Reader 6805 if reqBody != "" { 6806 bodyReader = strings.NewReader(reqBody) 6807 if chunked { 6808 bodyReader = bufio.NewReader(bodyReader) 6809 } 6810 } 6811 req, err := NewRequest(method, cst.ts.URL, bodyReader) 6812 if err != nil { 6813 t.Fatal(err) 6814 } 6815 res, err := cst.c.Do(req) 6816 if err != nil { 6817 t.Fatal(err) 6818 } 6819 res.Body.Close() 6820 if got, want := res.StatusCode, 200; got != want { 6821 t.Errorf("%v request with %d-byte body: StatusCode = %v, want %v", method, len(reqBody), got, want) 6822 } 6823 if got, want := res.Header.Get("X-Request-Body"), reqBody; got != want { 6824 t.Errorf("%v request with %d-byte body: handler read body %q, want %q", method, len(reqBody), got, want) 6825 } 6826 } 6827 }