github.com/guyezi/gofrontend@v0.0.0-20200228202240-7a62a49e62c0/libgo/go/net/http/fs_test.go (about) 1 // Copyright 2010 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package http_test 6 7 import ( 8 "bufio" 9 "bytes" 10 "errors" 11 "fmt" 12 "io" 13 "io/ioutil" 14 "mime" 15 "mime/multipart" 16 "net" 17 . "net/http" 18 "net/http/httptest" 19 "net/url" 20 "os" 21 "os/exec" 22 "path" 23 "path/filepath" 24 "reflect" 25 "regexp" 26 "runtime" 27 "strings" 28 "testing" 29 "time" 30 ) 31 32 const ( 33 testFile = "testdata/file" 34 testFileLen = 11 35 ) 36 37 type wantRange struct { 38 start, end int64 // range [start,end) 39 } 40 41 var ServeFileRangeTests = []struct { 42 r string 43 code int 44 ranges []wantRange 45 }{ 46 {r: "", code: StatusOK}, 47 {r: "bytes=0-4", code: StatusPartialContent, ranges: []wantRange{{0, 5}}}, 48 {r: "bytes=2-", code: StatusPartialContent, ranges: []wantRange{{2, testFileLen}}}, 49 {r: "bytes=-5", code: StatusPartialContent, ranges: []wantRange{{testFileLen - 5, testFileLen}}}, 50 {r: "bytes=3-7", code: StatusPartialContent, ranges: []wantRange{{3, 8}}}, 51 {r: "bytes=0-0,-2", code: StatusPartialContent, ranges: []wantRange{{0, 1}, {testFileLen - 2, testFileLen}}}, 52 {r: "bytes=0-1,5-8", code: StatusPartialContent, ranges: []wantRange{{0, 2}, {5, 9}}}, 53 {r: "bytes=0-1,5-", code: StatusPartialContent, ranges: []wantRange{{0, 2}, {5, testFileLen}}}, 54 {r: "bytes=5-1000", code: StatusPartialContent, ranges: []wantRange{{5, testFileLen}}}, 55 {r: "bytes=0-,1-,2-,3-,4-", code: StatusOK}, // ignore wasteful range request 56 {r: "bytes=0-9", code: StatusPartialContent, ranges: []wantRange{{0, testFileLen - 1}}}, 57 {r: "bytes=0-10", code: StatusPartialContent, ranges: []wantRange{{0, testFileLen}}}, 58 {r: "bytes=0-11", code: StatusPartialContent, ranges: []wantRange{{0, testFileLen}}}, 59 {r: "bytes=10-11", code: StatusPartialContent, ranges: []wantRange{{testFileLen - 1, testFileLen}}}, 60 {r: "bytes=10-", code: StatusPartialContent, ranges: []wantRange{{testFileLen - 1, testFileLen}}}, 61 {r: "bytes=11-", code: StatusRequestedRangeNotSatisfiable}, 62 {r: "bytes=11-12", code: StatusRequestedRangeNotSatisfiable}, 63 {r: "bytes=12-12", code: StatusRequestedRangeNotSatisfiable}, 64 {r: "bytes=11-100", code: StatusRequestedRangeNotSatisfiable}, 65 {r: "bytes=12-100", code: StatusRequestedRangeNotSatisfiable}, 66 {r: "bytes=100-", code: StatusRequestedRangeNotSatisfiable}, 67 {r: "bytes=100-1000", code: StatusRequestedRangeNotSatisfiable}, 68 } 69 70 func TestServeFile(t *testing.T) { 71 setParallel(t) 72 defer afterTest(t) 73 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 74 ServeFile(w, r, "testdata/file") 75 })) 76 defer ts.Close() 77 c := ts.Client() 78 79 var err error 80 81 file, err := ioutil.ReadFile(testFile) 82 if err != nil { 83 t.Fatal("reading file:", err) 84 } 85 86 // set up the Request (re-used for all tests) 87 var req Request 88 req.Header = make(Header) 89 if req.URL, err = url.Parse(ts.URL); err != nil { 90 t.Fatal("ParseURL:", err) 91 } 92 req.Method = "GET" 93 94 // straight GET 95 _, body := getBody(t, "straight get", req, c) 96 if !bytes.Equal(body, file) { 97 t.Fatalf("body mismatch: got %q, want %q", body, file) 98 } 99 100 // Range tests 101 Cases: 102 for _, rt := range ServeFileRangeTests { 103 if rt.r != "" { 104 req.Header.Set("Range", rt.r) 105 } 106 resp, body := getBody(t, fmt.Sprintf("range test %q", rt.r), req, c) 107 if resp.StatusCode != rt.code { 108 t.Errorf("range=%q: StatusCode=%d, want %d", rt.r, resp.StatusCode, rt.code) 109 } 110 if rt.code == StatusRequestedRangeNotSatisfiable { 111 continue 112 } 113 wantContentRange := "" 114 if len(rt.ranges) == 1 { 115 rng := rt.ranges[0] 116 wantContentRange = fmt.Sprintf("bytes %d-%d/%d", rng.start, rng.end-1, testFileLen) 117 } 118 cr := resp.Header.Get("Content-Range") 119 if cr != wantContentRange { 120 t.Errorf("range=%q: Content-Range = %q, want %q", rt.r, cr, wantContentRange) 121 } 122 ct := resp.Header.Get("Content-Type") 123 if len(rt.ranges) == 1 { 124 rng := rt.ranges[0] 125 wantBody := file[rng.start:rng.end] 126 if !bytes.Equal(body, wantBody) { 127 t.Errorf("range=%q: body = %q, want %q", rt.r, body, wantBody) 128 } 129 if strings.HasPrefix(ct, "multipart/byteranges") { 130 t.Errorf("range=%q content-type = %q; unexpected multipart/byteranges", rt.r, ct) 131 } 132 } 133 if len(rt.ranges) > 1 { 134 typ, params, err := mime.ParseMediaType(ct) 135 if err != nil { 136 t.Errorf("range=%q content-type = %q; %v", rt.r, ct, err) 137 continue 138 } 139 if typ != "multipart/byteranges" { 140 t.Errorf("range=%q content-type = %q; want multipart/byteranges", rt.r, typ) 141 continue 142 } 143 if params["boundary"] == "" { 144 t.Errorf("range=%q content-type = %q; lacks boundary", rt.r, ct) 145 continue 146 } 147 if g, w := resp.ContentLength, int64(len(body)); g != w { 148 t.Errorf("range=%q Content-Length = %d; want %d", rt.r, g, w) 149 continue 150 } 151 mr := multipart.NewReader(bytes.NewReader(body), params["boundary"]) 152 for ri, rng := range rt.ranges { 153 part, err := mr.NextPart() 154 if err != nil { 155 t.Errorf("range=%q, reading part index %d: %v", rt.r, ri, err) 156 continue Cases 157 } 158 wantContentRange = fmt.Sprintf("bytes %d-%d/%d", rng.start, rng.end-1, testFileLen) 159 if g, w := part.Header.Get("Content-Range"), wantContentRange; g != w { 160 t.Errorf("range=%q: part Content-Range = %q; want %q", rt.r, g, w) 161 } 162 body, err := ioutil.ReadAll(part) 163 if err != nil { 164 t.Errorf("range=%q, reading part index %d body: %v", rt.r, ri, err) 165 continue Cases 166 } 167 wantBody := file[rng.start:rng.end] 168 if !bytes.Equal(body, wantBody) { 169 t.Errorf("range=%q: body = %q, want %q", rt.r, body, wantBody) 170 } 171 } 172 _, err = mr.NextPart() 173 if err != io.EOF { 174 t.Errorf("range=%q; expected final error io.EOF; got %v", rt.r, err) 175 } 176 } 177 } 178 } 179 180 func TestServeFile_DotDot(t *testing.T) { 181 tests := []struct { 182 req string 183 wantStatus int 184 }{ 185 {"/testdata/file", 200}, 186 {"/../file", 400}, 187 {"/..", 400}, 188 {"/../", 400}, 189 {"/../foo", 400}, 190 {"/..\\foo", 400}, 191 {"/file/a", 200}, 192 {"/file/a..", 200}, 193 {"/file/a/..", 400}, 194 {"/file/a\\..", 400}, 195 } 196 for _, tt := range tests { 197 req, err := ReadRequest(bufio.NewReader(strings.NewReader("GET " + tt.req + " HTTP/1.1\r\nHost: foo\r\n\r\n"))) 198 if err != nil { 199 t.Errorf("bad request %q: %v", tt.req, err) 200 continue 201 } 202 rec := httptest.NewRecorder() 203 ServeFile(rec, req, "testdata/file") 204 if rec.Code != tt.wantStatus { 205 t.Errorf("for request %q, status = %d; want %d", tt.req, rec.Code, tt.wantStatus) 206 } 207 } 208 } 209 210 // Tests that this doesn't panic. (Issue 30165) 211 func TestServeFileDirPanicEmptyPath(t *testing.T) { 212 rec := httptest.NewRecorder() 213 req := httptest.NewRequest("GET", "/", nil) 214 req.URL.Path = "" 215 ServeFile(rec, req, "testdata") 216 res := rec.Result() 217 if res.StatusCode != 301 { 218 t.Errorf("code = %v; want 301", res.Status) 219 } 220 } 221 222 var fsRedirectTestData = []struct { 223 original, redirect string 224 }{ 225 {"/test/index.html", "/test/"}, 226 {"/test/testdata", "/test/testdata/"}, 227 {"/test/testdata/file/", "/test/testdata/file"}, 228 } 229 230 func TestFSRedirect(t *testing.T) { 231 defer afterTest(t) 232 ts := httptest.NewServer(StripPrefix("/test", FileServer(Dir(".")))) 233 defer ts.Close() 234 235 for _, data := range fsRedirectTestData { 236 res, err := Get(ts.URL + data.original) 237 if err != nil { 238 t.Fatal(err) 239 } 240 res.Body.Close() 241 if g, e := res.Request.URL.Path, data.redirect; g != e { 242 t.Errorf("redirect from %s: got %s, want %s", data.original, g, e) 243 } 244 } 245 } 246 247 type testFileSystem struct { 248 open func(name string) (File, error) 249 } 250 251 func (fs *testFileSystem) Open(name string) (File, error) { 252 return fs.open(name) 253 } 254 255 func TestFileServerCleans(t *testing.T) { 256 defer afterTest(t) 257 ch := make(chan string, 1) 258 fs := FileServer(&testFileSystem{func(name string) (File, error) { 259 ch <- name 260 return nil, errors.New("file does not exist") 261 }}) 262 tests := []struct { 263 reqPath, openArg string 264 }{ 265 {"/foo.txt", "/foo.txt"}, 266 {"//foo.txt", "/foo.txt"}, 267 {"/../foo.txt", "/foo.txt"}, 268 } 269 req, _ := NewRequest("GET", "http://example.com", nil) 270 for n, test := range tests { 271 rec := httptest.NewRecorder() 272 req.URL.Path = test.reqPath 273 fs.ServeHTTP(rec, req) 274 if got := <-ch; got != test.openArg { 275 t.Errorf("test %d: got %q, want %q", n, got, test.openArg) 276 } 277 } 278 } 279 280 func TestFileServerEscapesNames(t *testing.T) { 281 defer afterTest(t) 282 const dirListPrefix = "<pre>\n" 283 const dirListSuffix = "\n</pre>\n" 284 tests := []struct { 285 name, escaped string 286 }{ 287 {`simple_name`, `<a href="simple_name">simple_name</a>`}, 288 {`"'<>&`, `<a href="%22%27%3C%3E&">"'<>&</a>`}, 289 {`?foo=bar#baz`, `<a href="%3Ffoo=bar%23baz">?foo=bar#baz</a>`}, 290 {`<combo>?foo`, `<a href="%3Ccombo%3E%3Ffoo"><combo>?foo</a>`}, 291 {`foo:bar`, `<a href="./foo:bar">foo:bar</a>`}, 292 } 293 294 // We put each test file in its own directory in the fakeFS so we can look at it in isolation. 295 fs := make(fakeFS) 296 for i, test := range tests { 297 testFile := &fakeFileInfo{basename: test.name} 298 fs[fmt.Sprintf("/%d", i)] = &fakeFileInfo{ 299 dir: true, 300 modtime: time.Unix(1000000000, 0).UTC(), 301 ents: []*fakeFileInfo{testFile}, 302 } 303 fs[fmt.Sprintf("/%d/%s", i, test.name)] = testFile 304 } 305 306 ts := httptest.NewServer(FileServer(&fs)) 307 defer ts.Close() 308 for i, test := range tests { 309 url := fmt.Sprintf("%s/%d", ts.URL, i) 310 res, err := Get(url) 311 if err != nil { 312 t.Fatalf("test %q: Get: %v", test.name, err) 313 } 314 b, err := ioutil.ReadAll(res.Body) 315 if err != nil { 316 t.Fatalf("test %q: read Body: %v", test.name, err) 317 } 318 s := string(b) 319 if !strings.HasPrefix(s, dirListPrefix) || !strings.HasSuffix(s, dirListSuffix) { 320 t.Errorf("test %q: listing dir, full output is %q, want prefix %q and suffix %q", test.name, s, dirListPrefix, dirListSuffix) 321 } 322 if trimmed := strings.TrimSuffix(strings.TrimPrefix(s, dirListPrefix), dirListSuffix); trimmed != test.escaped { 323 t.Errorf("test %q: listing dir, filename escaped to %q, want %q", test.name, trimmed, test.escaped) 324 } 325 res.Body.Close() 326 } 327 } 328 329 func TestFileServerSortsNames(t *testing.T) { 330 defer afterTest(t) 331 const contents = "I am a fake file" 332 dirMod := time.Unix(123, 0).UTC() 333 fileMod := time.Unix(1000000000, 0).UTC() 334 fs := fakeFS{ 335 "/": &fakeFileInfo{ 336 dir: true, 337 modtime: dirMod, 338 ents: []*fakeFileInfo{ 339 { 340 basename: "b", 341 modtime: fileMod, 342 contents: contents, 343 }, 344 { 345 basename: "a", 346 modtime: fileMod, 347 contents: contents, 348 }, 349 }, 350 }, 351 } 352 353 ts := httptest.NewServer(FileServer(&fs)) 354 defer ts.Close() 355 356 res, err := Get(ts.URL) 357 if err != nil { 358 t.Fatalf("Get: %v", err) 359 } 360 defer res.Body.Close() 361 362 b, err := ioutil.ReadAll(res.Body) 363 if err != nil { 364 t.Fatalf("read Body: %v", err) 365 } 366 s := string(b) 367 if !strings.Contains(s, "<a href=\"a\">a</a>\n<a href=\"b\">b</a>") { 368 t.Errorf("output appears to be unsorted:\n%s", s) 369 } 370 } 371 372 func mustRemoveAll(dir string) { 373 err := os.RemoveAll(dir) 374 if err != nil { 375 panic(err) 376 } 377 } 378 379 func TestFileServerImplicitLeadingSlash(t *testing.T) { 380 defer afterTest(t) 381 tempDir, err := ioutil.TempDir("", "") 382 if err != nil { 383 t.Fatalf("TempDir: %v", err) 384 } 385 defer mustRemoveAll(tempDir) 386 if err := ioutil.WriteFile(filepath.Join(tempDir, "foo.txt"), []byte("Hello world"), 0644); err != nil { 387 t.Fatalf("WriteFile: %v", err) 388 } 389 ts := httptest.NewServer(StripPrefix("/bar/", FileServer(Dir(tempDir)))) 390 defer ts.Close() 391 get := func(suffix string) string { 392 res, err := Get(ts.URL + suffix) 393 if err != nil { 394 t.Fatalf("Get %s: %v", suffix, err) 395 } 396 b, err := ioutil.ReadAll(res.Body) 397 if err != nil { 398 t.Fatalf("ReadAll %s: %v", suffix, err) 399 } 400 res.Body.Close() 401 return string(b) 402 } 403 if s := get("/bar/"); !strings.Contains(s, ">foo.txt<") { 404 t.Logf("expected a directory listing with foo.txt, got %q", s) 405 } 406 if s := get("/bar/foo.txt"); s != "Hello world" { 407 t.Logf("expected %q, got %q", "Hello world", s) 408 } 409 } 410 411 func TestDirJoin(t *testing.T) { 412 if runtime.GOOS == "windows" { 413 t.Skip("skipping test on windows") 414 } 415 wfi, err := os.Stat("/etc/hosts") 416 if err != nil { 417 t.Skip("skipping test; no /etc/hosts file") 418 } 419 test := func(d Dir, name string) { 420 f, err := d.Open(name) 421 if err != nil { 422 t.Fatalf("open of %s: %v", name, err) 423 } 424 defer f.Close() 425 gfi, err := f.Stat() 426 if err != nil { 427 t.Fatalf("stat of %s: %v", name, err) 428 } 429 if !os.SameFile(gfi, wfi) { 430 t.Errorf("%s got different file", name) 431 } 432 } 433 test(Dir("/etc/"), "/hosts") 434 test(Dir("/etc/"), "hosts") 435 test(Dir("/etc/"), "../../../../hosts") 436 test(Dir("/etc"), "/hosts") 437 test(Dir("/etc"), "hosts") 438 test(Dir("/etc"), "../../../../hosts") 439 440 // Not really directories, but since we use this trick in 441 // ServeFile, test it: 442 test(Dir("/etc/hosts"), "") 443 test(Dir("/etc/hosts"), "/") 444 test(Dir("/etc/hosts"), "../") 445 } 446 447 func TestEmptyDirOpenCWD(t *testing.T) { 448 test := func(d Dir) { 449 name := "fs_test.go" 450 f, err := d.Open(name) 451 if err != nil { 452 t.Fatalf("open of %s: %v", name, err) 453 } 454 defer f.Close() 455 } 456 test(Dir("")) 457 test(Dir(".")) 458 test(Dir("./")) 459 } 460 461 func TestServeFileContentType(t *testing.T) { 462 defer afterTest(t) 463 const ctype = "icecream/chocolate" 464 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 465 switch r.FormValue("override") { 466 case "1": 467 w.Header().Set("Content-Type", ctype) 468 case "2": 469 // Explicitly inhibit sniffing. 470 w.Header()["Content-Type"] = []string{} 471 } 472 ServeFile(w, r, "testdata/file") 473 })) 474 defer ts.Close() 475 get := func(override string, want []string) { 476 resp, err := Get(ts.URL + "?override=" + override) 477 if err != nil { 478 t.Fatal(err) 479 } 480 if h := resp.Header["Content-Type"]; !reflect.DeepEqual(h, want) { 481 t.Errorf("Content-Type mismatch: got %v, want %v", h, want) 482 } 483 resp.Body.Close() 484 } 485 get("0", []string{"text/plain; charset=utf-8"}) 486 get("1", []string{ctype}) 487 get("2", nil) 488 } 489 490 func TestServeFileMimeType(t *testing.T) { 491 defer afterTest(t) 492 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 493 ServeFile(w, r, "testdata/style.css") 494 })) 495 defer ts.Close() 496 resp, err := Get(ts.URL) 497 if err != nil { 498 t.Fatal(err) 499 } 500 resp.Body.Close() 501 want := "text/css; charset=utf-8" 502 if h := resp.Header.Get("Content-Type"); h != want { 503 t.Errorf("Content-Type mismatch: got %q, want %q", h, want) 504 } 505 } 506 507 func TestServeFileFromCWD(t *testing.T) { 508 defer afterTest(t) 509 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 510 ServeFile(w, r, "fs_test.go") 511 })) 512 defer ts.Close() 513 r, err := Get(ts.URL) 514 if err != nil { 515 t.Fatal(err) 516 } 517 r.Body.Close() 518 if r.StatusCode != 200 { 519 t.Fatalf("expected 200 OK, got %s", r.Status) 520 } 521 } 522 523 // Issue 13996 524 func TestServeDirWithoutTrailingSlash(t *testing.T) { 525 e := "/testdata/" 526 defer afterTest(t) 527 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 528 ServeFile(w, r, ".") 529 })) 530 defer ts.Close() 531 r, err := Get(ts.URL + "/testdata") 532 if err != nil { 533 t.Fatal(err) 534 } 535 r.Body.Close() 536 if g := r.Request.URL.Path; g != e { 537 t.Errorf("got %s, want %s", g, e) 538 } 539 } 540 541 // Tests that ServeFile doesn't add a Content-Length if a Content-Encoding is 542 // specified. 543 func TestServeFileWithContentEncoding_h1(t *testing.T) { testServeFileWithContentEncoding(t, h1Mode) } 544 func TestServeFileWithContentEncoding_h2(t *testing.T) { testServeFileWithContentEncoding(t, h2Mode) } 545 func testServeFileWithContentEncoding(t *testing.T, h2 bool) { 546 defer afterTest(t) 547 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) { 548 w.Header().Set("Content-Encoding", "foo") 549 ServeFile(w, r, "testdata/file") 550 551 // Because the testdata is so small, it would fit in 552 // both the h1 and h2 Server's write buffers. For h1, 553 // sendfile is used, though, forcing a header flush at 554 // the io.Copy. http2 doesn't do a header flush so 555 // buffers all 11 bytes and then adds its own 556 // Content-Length. To prevent the Server's 557 // Content-Length and test ServeFile only, flush here. 558 w.(Flusher).Flush() 559 })) 560 defer cst.close() 561 resp, err := cst.c.Get(cst.ts.URL) 562 if err != nil { 563 t.Fatal(err) 564 } 565 resp.Body.Close() 566 if g, e := resp.ContentLength, int64(-1); g != e { 567 t.Errorf("Content-Length mismatch: got %d, want %d", g, e) 568 } 569 } 570 571 func TestServeIndexHtml(t *testing.T) { 572 defer afterTest(t) 573 const want = "index.html says hello\n" 574 ts := httptest.NewServer(FileServer(Dir("."))) 575 defer ts.Close() 576 577 for _, path := range []string{"/testdata/", "/testdata/index.html"} { 578 res, err := Get(ts.URL + path) 579 if err != nil { 580 t.Fatal(err) 581 } 582 b, err := ioutil.ReadAll(res.Body) 583 if err != nil { 584 t.Fatal("reading Body:", err) 585 } 586 if s := string(b); s != want { 587 t.Errorf("for path %q got %q, want %q", path, s, want) 588 } 589 res.Body.Close() 590 } 591 } 592 593 func TestFileServerZeroByte(t *testing.T) { 594 defer afterTest(t) 595 ts := httptest.NewServer(FileServer(Dir("."))) 596 defer ts.Close() 597 598 c, err := net.Dial("tcp", ts.Listener.Addr().String()) 599 if err != nil { 600 t.Fatal(err) 601 } 602 defer c.Close() 603 _, err = fmt.Fprintf(c, "GET /..\x00 HTTP/1.0\r\n\r\n") 604 if err != nil { 605 t.Fatal(err) 606 } 607 var got bytes.Buffer 608 bufr := bufio.NewReader(io.TeeReader(c, &got)) 609 res, err := ReadResponse(bufr, nil) 610 if err != nil { 611 t.Fatal("ReadResponse: ", err) 612 } 613 if res.StatusCode == 200 { 614 t.Errorf("got status 200; want an error. Body is:\n%s", got.Bytes()) 615 } 616 } 617 618 type fakeFileInfo struct { 619 dir bool 620 basename string 621 modtime time.Time 622 ents []*fakeFileInfo 623 contents string 624 err error 625 } 626 627 func (f *fakeFileInfo) Name() string { return f.basename } 628 func (f *fakeFileInfo) Sys() interface{} { return nil } 629 func (f *fakeFileInfo) ModTime() time.Time { return f.modtime } 630 func (f *fakeFileInfo) IsDir() bool { return f.dir } 631 func (f *fakeFileInfo) Size() int64 { return int64(len(f.contents)) } 632 func (f *fakeFileInfo) Mode() os.FileMode { 633 if f.dir { 634 return 0755 | os.ModeDir 635 } 636 return 0644 637 } 638 639 type fakeFile struct { 640 io.ReadSeeker 641 fi *fakeFileInfo 642 path string // as opened 643 entpos int 644 } 645 646 func (f *fakeFile) Close() error { return nil } 647 func (f *fakeFile) Stat() (os.FileInfo, error) { return f.fi, nil } 648 func (f *fakeFile) Readdir(count int) ([]os.FileInfo, error) { 649 if !f.fi.dir { 650 return nil, os.ErrInvalid 651 } 652 var fis []os.FileInfo 653 654 limit := f.entpos + count 655 if count <= 0 || limit > len(f.fi.ents) { 656 limit = len(f.fi.ents) 657 } 658 for ; f.entpos < limit; f.entpos++ { 659 fis = append(fis, f.fi.ents[f.entpos]) 660 } 661 662 if len(fis) == 0 && count > 0 { 663 return fis, io.EOF 664 } else { 665 return fis, nil 666 } 667 } 668 669 type fakeFS map[string]*fakeFileInfo 670 671 func (fs fakeFS) Open(name string) (File, error) { 672 name = path.Clean(name) 673 f, ok := fs[name] 674 if !ok { 675 return nil, os.ErrNotExist 676 } 677 if f.err != nil { 678 return nil, f.err 679 } 680 return &fakeFile{ReadSeeker: strings.NewReader(f.contents), fi: f, path: name}, nil 681 } 682 683 func TestDirectoryIfNotModified(t *testing.T) { 684 defer afterTest(t) 685 const indexContents = "I am a fake index.html file" 686 fileMod := time.Unix(1000000000, 0).UTC() 687 fileModStr := fileMod.Format(TimeFormat) 688 dirMod := time.Unix(123, 0).UTC() 689 indexFile := &fakeFileInfo{ 690 basename: "index.html", 691 modtime: fileMod, 692 contents: indexContents, 693 } 694 fs := fakeFS{ 695 "/": &fakeFileInfo{ 696 dir: true, 697 modtime: dirMod, 698 ents: []*fakeFileInfo{indexFile}, 699 }, 700 "/index.html": indexFile, 701 } 702 703 ts := httptest.NewServer(FileServer(fs)) 704 defer ts.Close() 705 706 res, err := Get(ts.URL) 707 if err != nil { 708 t.Fatal(err) 709 } 710 b, err := ioutil.ReadAll(res.Body) 711 if err != nil { 712 t.Fatal(err) 713 } 714 if string(b) != indexContents { 715 t.Fatalf("Got body %q; want %q", b, indexContents) 716 } 717 res.Body.Close() 718 719 lastMod := res.Header.Get("Last-Modified") 720 if lastMod != fileModStr { 721 t.Fatalf("initial Last-Modified = %q; want %q", lastMod, fileModStr) 722 } 723 724 req, _ := NewRequest("GET", ts.URL, nil) 725 req.Header.Set("If-Modified-Since", lastMod) 726 727 c := ts.Client() 728 res, err = c.Do(req) 729 if err != nil { 730 t.Fatal(err) 731 } 732 if res.StatusCode != 304 { 733 t.Fatalf("Code after If-Modified-Since request = %v; want 304", res.StatusCode) 734 } 735 res.Body.Close() 736 737 // Advance the index.html file's modtime, but not the directory's. 738 indexFile.modtime = indexFile.modtime.Add(1 * time.Hour) 739 740 res, err = c.Do(req) 741 if err != nil { 742 t.Fatal(err) 743 } 744 if res.StatusCode != 200 { 745 t.Fatalf("Code after second If-Modified-Since request = %v; want 200; res is %#v", res.StatusCode, res) 746 } 747 res.Body.Close() 748 } 749 750 func mustStat(t *testing.T, fileName string) os.FileInfo { 751 fi, err := os.Stat(fileName) 752 if err != nil { 753 t.Fatal(err) 754 } 755 return fi 756 } 757 758 func TestServeContent(t *testing.T) { 759 defer afterTest(t) 760 type serveParam struct { 761 name string 762 modtime time.Time 763 content io.ReadSeeker 764 contentType string 765 etag string 766 } 767 servec := make(chan serveParam, 1) 768 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 769 p := <-servec 770 if p.etag != "" { 771 w.Header().Set("ETag", p.etag) 772 } 773 if p.contentType != "" { 774 w.Header().Set("Content-Type", p.contentType) 775 } 776 ServeContent(w, r, p.name, p.modtime, p.content) 777 })) 778 defer ts.Close() 779 780 type testCase struct { 781 // One of file or content must be set: 782 file string 783 content io.ReadSeeker 784 785 modtime time.Time 786 serveETag string // optional 787 serveContentType string // optional 788 reqHeader map[string]string 789 wantLastMod string 790 wantContentType string 791 wantContentRange string 792 wantStatus int 793 } 794 htmlModTime := mustStat(t, "testdata/index.html").ModTime() 795 tests := map[string]testCase{ 796 "no_last_modified": { 797 file: "testdata/style.css", 798 wantContentType: "text/css; charset=utf-8", 799 wantStatus: 200, 800 }, 801 "with_last_modified": { 802 file: "testdata/index.html", 803 wantContentType: "text/html; charset=utf-8", 804 modtime: htmlModTime, 805 wantLastMod: htmlModTime.UTC().Format(TimeFormat), 806 wantStatus: 200, 807 }, 808 "not_modified_modtime": { 809 file: "testdata/style.css", 810 serveETag: `"foo"`, // Last-Modified sent only when no ETag 811 modtime: htmlModTime, 812 reqHeader: map[string]string{ 813 "If-Modified-Since": htmlModTime.UTC().Format(TimeFormat), 814 }, 815 wantStatus: 304, 816 }, 817 "not_modified_modtime_with_contenttype": { 818 file: "testdata/style.css", 819 serveContentType: "text/css", // explicit content type 820 serveETag: `"foo"`, // Last-Modified sent only when no ETag 821 modtime: htmlModTime, 822 reqHeader: map[string]string{ 823 "If-Modified-Since": htmlModTime.UTC().Format(TimeFormat), 824 }, 825 wantStatus: 304, 826 }, 827 "not_modified_etag": { 828 file: "testdata/style.css", 829 serveETag: `"foo"`, 830 reqHeader: map[string]string{ 831 "If-None-Match": `"foo"`, 832 }, 833 wantStatus: 304, 834 }, 835 "not_modified_etag_no_seek": { 836 content: panicOnSeek{nil}, // should never be called 837 serveETag: `W/"foo"`, // If-None-Match uses weak ETag comparison 838 reqHeader: map[string]string{ 839 "If-None-Match": `"baz", W/"foo"`, 840 }, 841 wantStatus: 304, 842 }, 843 "if_none_match_mismatch": { 844 file: "testdata/style.css", 845 serveETag: `"foo"`, 846 reqHeader: map[string]string{ 847 "If-None-Match": `"Foo"`, 848 }, 849 wantStatus: 200, 850 wantContentType: "text/css; charset=utf-8", 851 }, 852 "range_good": { 853 file: "testdata/style.css", 854 serveETag: `"A"`, 855 reqHeader: map[string]string{ 856 "Range": "bytes=0-4", 857 }, 858 wantStatus: StatusPartialContent, 859 wantContentType: "text/css; charset=utf-8", 860 wantContentRange: "bytes 0-4/8", 861 }, 862 "range_match": { 863 file: "testdata/style.css", 864 serveETag: `"A"`, 865 reqHeader: map[string]string{ 866 "Range": "bytes=0-4", 867 "If-Range": `"A"`, 868 }, 869 wantStatus: StatusPartialContent, 870 wantContentType: "text/css; charset=utf-8", 871 wantContentRange: "bytes 0-4/8", 872 }, 873 "range_match_weak_etag": { 874 file: "testdata/style.css", 875 serveETag: `W/"A"`, 876 reqHeader: map[string]string{ 877 "Range": "bytes=0-4", 878 "If-Range": `W/"A"`, 879 }, 880 wantStatus: 200, 881 wantContentType: "text/css; charset=utf-8", 882 }, 883 "range_no_overlap": { 884 file: "testdata/style.css", 885 serveETag: `"A"`, 886 reqHeader: map[string]string{ 887 "Range": "bytes=10-20", 888 }, 889 wantStatus: StatusRequestedRangeNotSatisfiable, 890 wantContentType: "text/plain; charset=utf-8", 891 wantContentRange: "bytes */8", 892 }, 893 // An If-Range resource for entity "A", but entity "B" is now current. 894 // The Range request should be ignored. 895 "range_no_match": { 896 file: "testdata/style.css", 897 serveETag: `"A"`, 898 reqHeader: map[string]string{ 899 "Range": "bytes=0-4", 900 "If-Range": `"B"`, 901 }, 902 wantStatus: 200, 903 wantContentType: "text/css; charset=utf-8", 904 }, 905 "range_with_modtime": { 906 file: "testdata/style.css", 907 modtime: time.Date(2014, 6, 25, 17, 12, 18, 0 /* nanos */, time.UTC), 908 reqHeader: map[string]string{ 909 "Range": "bytes=0-4", 910 "If-Range": "Wed, 25 Jun 2014 17:12:18 GMT", 911 }, 912 wantStatus: StatusPartialContent, 913 wantContentType: "text/css; charset=utf-8", 914 wantContentRange: "bytes 0-4/8", 915 wantLastMod: "Wed, 25 Jun 2014 17:12:18 GMT", 916 }, 917 "range_with_modtime_mismatch": { 918 file: "testdata/style.css", 919 modtime: time.Date(2014, 6, 25, 17, 12, 18, 0 /* nanos */, time.UTC), 920 reqHeader: map[string]string{ 921 "Range": "bytes=0-4", 922 "If-Range": "Wed, 25 Jun 2014 17:12:19 GMT", 923 }, 924 wantStatus: StatusOK, 925 wantContentType: "text/css; charset=utf-8", 926 wantLastMod: "Wed, 25 Jun 2014 17:12:18 GMT", 927 }, 928 "range_with_modtime_nanos": { 929 file: "testdata/style.css", 930 modtime: time.Date(2014, 6, 25, 17, 12, 18, 123 /* nanos */, time.UTC), 931 reqHeader: map[string]string{ 932 "Range": "bytes=0-4", 933 "If-Range": "Wed, 25 Jun 2014 17:12:18 GMT", 934 }, 935 wantStatus: StatusPartialContent, 936 wantContentType: "text/css; charset=utf-8", 937 wantContentRange: "bytes 0-4/8", 938 wantLastMod: "Wed, 25 Jun 2014 17:12:18 GMT", 939 }, 940 "unix_zero_modtime": { 941 content: strings.NewReader("<html>foo"), 942 modtime: time.Unix(0, 0), 943 wantStatus: StatusOK, 944 wantContentType: "text/html; charset=utf-8", 945 }, 946 "ifmatch_matches": { 947 file: "testdata/style.css", 948 serveETag: `"A"`, 949 reqHeader: map[string]string{ 950 "If-Match": `"Z", "A"`, 951 }, 952 wantStatus: 200, 953 wantContentType: "text/css; charset=utf-8", 954 }, 955 "ifmatch_star": { 956 file: "testdata/style.css", 957 serveETag: `"A"`, 958 reqHeader: map[string]string{ 959 "If-Match": `*`, 960 }, 961 wantStatus: 200, 962 wantContentType: "text/css; charset=utf-8", 963 }, 964 "ifmatch_failed": { 965 file: "testdata/style.css", 966 serveETag: `"A"`, 967 reqHeader: map[string]string{ 968 "If-Match": `"B"`, 969 }, 970 wantStatus: 412, 971 }, 972 "ifmatch_fails_on_weak_etag": { 973 file: "testdata/style.css", 974 serveETag: `W/"A"`, 975 reqHeader: map[string]string{ 976 "If-Match": `W/"A"`, 977 }, 978 wantStatus: 412, 979 }, 980 "if_unmodified_since_true": { 981 file: "testdata/style.css", 982 modtime: htmlModTime, 983 reqHeader: map[string]string{ 984 "If-Unmodified-Since": htmlModTime.UTC().Format(TimeFormat), 985 }, 986 wantStatus: 200, 987 wantContentType: "text/css; charset=utf-8", 988 wantLastMod: htmlModTime.UTC().Format(TimeFormat), 989 }, 990 "if_unmodified_since_false": { 991 file: "testdata/style.css", 992 modtime: htmlModTime, 993 reqHeader: map[string]string{ 994 "If-Unmodified-Since": htmlModTime.Add(-2 * time.Second).UTC().Format(TimeFormat), 995 }, 996 wantStatus: 412, 997 wantLastMod: htmlModTime.UTC().Format(TimeFormat), 998 }, 999 } 1000 for testName, tt := range tests { 1001 var content io.ReadSeeker 1002 if tt.file != "" { 1003 f, err := os.Open(tt.file) 1004 if err != nil { 1005 t.Fatalf("test %q: %v", testName, err) 1006 } 1007 defer f.Close() 1008 content = f 1009 } else { 1010 content = tt.content 1011 } 1012 for _, method := range []string{"GET", "HEAD"} { 1013 //restore content in case it is consumed by previous method 1014 if content, ok := content.(*strings.Reader); ok { 1015 content.Seek(0, io.SeekStart) 1016 } 1017 1018 servec <- serveParam{ 1019 name: filepath.Base(tt.file), 1020 content: content, 1021 modtime: tt.modtime, 1022 etag: tt.serveETag, 1023 contentType: tt.serveContentType, 1024 } 1025 req, err := NewRequest(method, ts.URL, nil) 1026 if err != nil { 1027 t.Fatal(err) 1028 } 1029 for k, v := range tt.reqHeader { 1030 req.Header.Set(k, v) 1031 } 1032 1033 c := ts.Client() 1034 res, err := c.Do(req) 1035 if err != nil { 1036 t.Fatal(err) 1037 } 1038 io.Copy(ioutil.Discard, res.Body) 1039 res.Body.Close() 1040 if res.StatusCode != tt.wantStatus { 1041 t.Errorf("test %q using %q: got status = %d; want %d", testName, method, res.StatusCode, tt.wantStatus) 1042 } 1043 if g, e := res.Header.Get("Content-Type"), tt.wantContentType; g != e { 1044 t.Errorf("test %q using %q: got content-type = %q, want %q", testName, method, g, e) 1045 } 1046 if g, e := res.Header.Get("Content-Range"), tt.wantContentRange; g != e { 1047 t.Errorf("test %q using %q: got content-range = %q, want %q", testName, method, g, e) 1048 } 1049 if g, e := res.Header.Get("Last-Modified"), tt.wantLastMod; g != e { 1050 t.Errorf("test %q using %q: got last-modified = %q, want %q", testName, method, g, e) 1051 } 1052 } 1053 } 1054 } 1055 1056 // Issue 12991 1057 func TestServerFileStatError(t *testing.T) { 1058 rec := httptest.NewRecorder() 1059 r, _ := NewRequest("GET", "http://foo/", nil) 1060 redirect := false 1061 name := "file.txt" 1062 fs := issue12991FS{} 1063 ExportServeFile(rec, r, fs, name, redirect) 1064 if body := rec.Body.String(); !strings.Contains(body, "403") || !strings.Contains(body, "Forbidden") { 1065 t.Errorf("wanted 403 forbidden message; got: %s", body) 1066 } 1067 } 1068 1069 type issue12991FS struct{} 1070 1071 func (issue12991FS) Open(string) (File, error) { return issue12991File{}, nil } 1072 1073 type issue12991File struct{ File } 1074 1075 func (issue12991File) Stat() (os.FileInfo, error) { return nil, os.ErrPermission } 1076 func (issue12991File) Close() error { return nil } 1077 1078 func TestServeContentErrorMessages(t *testing.T) { 1079 defer afterTest(t) 1080 fs := fakeFS{ 1081 "/500": &fakeFileInfo{ 1082 err: errors.New("random error"), 1083 }, 1084 "/403": &fakeFileInfo{ 1085 err: &os.PathError{Err: os.ErrPermission}, 1086 }, 1087 } 1088 ts := httptest.NewServer(FileServer(fs)) 1089 defer ts.Close() 1090 c := ts.Client() 1091 for _, code := range []int{403, 404, 500} { 1092 res, err := c.Get(fmt.Sprintf("%s/%d", ts.URL, code)) 1093 if err != nil { 1094 t.Errorf("Error fetching /%d: %v", code, err) 1095 continue 1096 } 1097 if res.StatusCode != code { 1098 t.Errorf("For /%d, status code = %d; want %d", code, res.StatusCode, code) 1099 } 1100 res.Body.Close() 1101 } 1102 } 1103 1104 // verifies that sendfile is being used on Linux 1105 func TestLinuxSendfile(t *testing.T) { 1106 setParallel(t) 1107 defer afterTest(t) 1108 if runtime.GOOS != "linux" { 1109 t.Skip("skipping; linux-only test") 1110 } 1111 if _, err := exec.LookPath("strace"); err != nil { 1112 t.Skip("skipping; strace not found in path") 1113 } 1114 1115 ln, err := net.Listen("tcp", "127.0.0.1:0") 1116 if err != nil { 1117 t.Fatal(err) 1118 } 1119 lnf, err := ln.(*net.TCPListener).File() 1120 if err != nil { 1121 t.Fatal(err) 1122 } 1123 defer ln.Close() 1124 1125 // Attempt to run strace, and skip on failure - this test requires SYS_PTRACE. 1126 if err := exec.Command("strace", "-f", "-q", os.Args[0], "-test.run=^$").Run(); err != nil { 1127 t.Skipf("skipping; failed to run strace: %v", err) 1128 } 1129 1130 var buf bytes.Buffer 1131 child := exec.Command("strace", "-f", "-q", os.Args[0], "-test.run=TestLinuxSendfileChild") 1132 child.ExtraFiles = append(child.ExtraFiles, lnf) 1133 child.Env = append([]string{"GO_WANT_HELPER_PROCESS=1"}, os.Environ()...) 1134 child.Stdout = &buf 1135 child.Stderr = &buf 1136 if err := child.Start(); err != nil { 1137 t.Skipf("skipping; failed to start straced child: %v", err) 1138 } 1139 1140 res, err := Get(fmt.Sprintf("http://%s/", ln.Addr())) 1141 if err != nil { 1142 t.Fatalf("http client error: %v", err) 1143 } 1144 _, err = io.Copy(ioutil.Discard, res.Body) 1145 if err != nil { 1146 t.Fatalf("client body read error: %v", err) 1147 } 1148 res.Body.Close() 1149 1150 // Force child to exit cleanly. 1151 Post(fmt.Sprintf("http://%s/quit", ln.Addr()), "", nil) 1152 child.Wait() 1153 1154 rx := regexp.MustCompile(`\b(n64:)?sendfile(64)?\(`) 1155 out := buf.String() 1156 if !rx.MatchString(out) { 1157 t.Errorf("no sendfile system call found in:\n%s", out) 1158 } 1159 } 1160 1161 func getBody(t *testing.T, testName string, req Request, client *Client) (*Response, []byte) { 1162 r, err := client.Do(&req) 1163 if err != nil { 1164 t.Fatalf("%s: for URL %q, send error: %v", testName, req.URL.String(), err) 1165 } 1166 b, err := ioutil.ReadAll(r.Body) 1167 if err != nil { 1168 t.Fatalf("%s: for URL %q, reading body: %v", testName, req.URL.String(), err) 1169 } 1170 return r, b 1171 } 1172 1173 // TestLinuxSendfileChild isn't a real test. It's used as a helper process 1174 // for TestLinuxSendfile. 1175 func TestLinuxSendfileChild(*testing.T) { 1176 if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" { 1177 return 1178 } 1179 defer os.Exit(0) 1180 fd3 := os.NewFile(3, "ephemeral-port-listener") 1181 ln, err := net.FileListener(fd3) 1182 if err != nil { 1183 panic(err) 1184 } 1185 mux := NewServeMux() 1186 mux.Handle("/", FileServer(Dir("testdata"))) 1187 mux.HandleFunc("/quit", func(ResponseWriter, *Request) { 1188 os.Exit(0) 1189 }) 1190 s := &Server{Handler: mux} 1191 err = s.Serve(ln) 1192 if err != nil { 1193 panic(err) 1194 } 1195 } 1196 1197 // Issue 18984: tests that requests for paths beyond files return not-found errors 1198 func TestFileServerNotDirError(t *testing.T) { 1199 defer afterTest(t) 1200 ts := httptest.NewServer(FileServer(Dir("testdata"))) 1201 defer ts.Close() 1202 1203 res, err := Get(ts.URL + "/index.html/not-a-file") 1204 if err != nil { 1205 t.Fatal(err) 1206 } 1207 res.Body.Close() 1208 if res.StatusCode != 404 { 1209 t.Errorf("StatusCode = %v; want 404", res.StatusCode) 1210 } 1211 1212 test := func(name string, dir Dir) { 1213 t.Run(name, func(t *testing.T) { 1214 _, err = dir.Open("/index.html/not-a-file") 1215 if err == nil { 1216 t.Fatal("err == nil; want != nil") 1217 } 1218 if !os.IsNotExist(err) { 1219 t.Errorf("err = %v; os.IsNotExist(err) = %v; want true", err, os.IsNotExist(err)) 1220 } 1221 1222 _, err = dir.Open("/index.html/not-a-dir/not-a-file") 1223 if err == nil { 1224 t.Fatal("err == nil; want != nil") 1225 } 1226 if !os.IsNotExist(err) { 1227 t.Errorf("err = %v; os.IsNotExist(err) = %v; want true", err, os.IsNotExist(err)) 1228 } 1229 }) 1230 } 1231 1232 absPath, err := filepath.Abs("testdata") 1233 if err != nil { 1234 t.Fatal("get abs path:", err) 1235 } 1236 1237 test("RelativePath", Dir("testdata")) 1238 test("AbsolutePath", Dir(absPath)) 1239 } 1240 1241 func TestFileServerCleanPath(t *testing.T) { 1242 tests := []struct { 1243 path string 1244 wantCode int 1245 wantOpen []string 1246 }{ 1247 {"/", 200, []string{"/", "/index.html"}}, 1248 {"/dir", 301, []string{"/dir"}}, 1249 {"/dir/", 200, []string{"/dir", "/dir/index.html"}}, 1250 } 1251 for _, tt := range tests { 1252 var log []string 1253 rr := httptest.NewRecorder() 1254 req, _ := NewRequest("GET", "http://foo.localhost"+tt.path, nil) 1255 FileServer(fileServerCleanPathDir{&log}).ServeHTTP(rr, req) 1256 if !reflect.DeepEqual(log, tt.wantOpen) { 1257 t.Logf("For %s: Opens = %q; want %q", tt.path, log, tt.wantOpen) 1258 } 1259 if rr.Code != tt.wantCode { 1260 t.Logf("For %s: Response code = %d; want %d", tt.path, rr.Code, tt.wantCode) 1261 } 1262 } 1263 } 1264 1265 type fileServerCleanPathDir struct { 1266 log *[]string 1267 } 1268 1269 func (d fileServerCleanPathDir) Open(path string) (File, error) { 1270 *(d.log) = append(*(d.log), path) 1271 if path == "/" || path == "/dir" || path == "/dir/" { 1272 // Just return back something that's a directory. 1273 return Dir(".").Open(".") 1274 } 1275 return nil, os.ErrNotExist 1276 } 1277 1278 type panicOnSeek struct{ io.ReadSeeker } 1279 1280 func Test_scanETag(t *testing.T) { 1281 tests := []struct { 1282 in string 1283 wantETag string 1284 wantRemain string 1285 }{ 1286 {`W/"etag-1"`, `W/"etag-1"`, ""}, 1287 {`"etag-2"`, `"etag-2"`, ""}, 1288 {`"etag-1", "etag-2"`, `"etag-1"`, `, "etag-2"`}, 1289 {"", "", ""}, 1290 {"W/", "", ""}, 1291 {`W/"truc`, "", ""}, 1292 {`w/"case-sensitive"`, "", ""}, 1293 {`"spaced etag"`, "", ""}, 1294 } 1295 for _, test := range tests { 1296 etag, remain := ExportScanETag(test.in) 1297 if etag != test.wantETag || remain != test.wantRemain { 1298 t.Errorf("scanETag(%q)=%q %q, want %q %q", test.in, etag, remain, test.wantETag, test.wantRemain) 1299 } 1300 } 1301 }