Debian Codegraph @

src/net/http/serve_test.go

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