github.com/Kolosok86/http@v0.1.2/fs.go (about) 1 // Copyright 2009 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // HTTP file system request handler 6 7 package http 8 9 import ( 10 "errors" 11 "fmt" 12 "io" 13 "io/fs" 14 "mime" 15 "net/url" 16 "os" 17 "path" 18 "path/filepath" 19 "sort" 20 "strconv" 21 "strings" 22 "time" 23 24 "github.com/Kolosok86/http/internal/multipart" 25 "github.com/Kolosok86/http/textproto" 26 ) 27 28 // A Dir implements FileSystem using the native file system restricted to a 29 // specific directory tree. 30 // 31 // While the FileSystem.Open method takes '/'-separated paths, a Dir's string 32 // value is a filename on the native file system, not a URL, so it is separated 33 // by filepath.Separator, which isn't necessarily '/'. 34 // 35 // Note that Dir could expose sensitive files and directories. Dir will follow 36 // symlinks pointing out of the directory tree, which can be especially dangerous 37 // if serving from a directory in which users are able to create arbitrary symlinks. 38 // Dir will also allow access to files and directories starting with a period, 39 // which could expose sensitive directories like .git or sensitive files like 40 // .htpasswd. To exclude files with a leading period, remove the files/directories 41 // from the server or create a custom FileSystem implementation. 42 // 43 // An empty Dir is treated as ".". 44 type Dir string 45 46 // mapOpenError maps the provided non-nil error from opening name 47 // to a possibly better non-nil error. In particular, it turns OS-specific errors 48 // about opening files in non-directories into fs.ErrNotExist. See Issues 18984 and 49552. 49 func mapOpenError(originalErr error, name string, sep rune, stat func(string) (fs.FileInfo, error)) error { 50 if errors.Is(originalErr, fs.ErrNotExist) || errors.Is(originalErr, fs.ErrPermission) { 51 return originalErr 52 } 53 54 parts := strings.Split(name, string(sep)) 55 for i := range parts { 56 if parts[i] == "" { 57 continue 58 } 59 fi, err := stat(strings.Join(parts[:i+1], string(sep))) 60 if err != nil { 61 return originalErr 62 } 63 if !fi.IsDir() { 64 return fs.ErrNotExist 65 } 66 } 67 return originalErr 68 } 69 70 // Open implements FileSystem using os.Open, opening files for reading rooted 71 // and relative to the directory d. 72 func (d Dir) Open(name string) (File, error) { 73 if filepath.Separator != '/' && strings.ContainsRune(name, filepath.Separator) { 74 return nil, errors.New("http: invalid character in file path") 75 } 76 dir := string(d) 77 if dir == "" { 78 dir = "." 79 } 80 fullName := filepath.Join(dir, filepath.FromSlash(path.Clean("/"+name))) 81 f, err := os.Open(fullName) 82 if err != nil { 83 return nil, mapOpenError(err, fullName, filepath.Separator, os.Stat) 84 } 85 return f, nil 86 } 87 88 // A FileSystem implements access to a collection of named files. 89 // The elements in a file path are separated by slash ('/', U+002F) 90 // characters, regardless of host operating system convention. 91 // See the FileServer function to convert a FileSystem to a Handler. 92 // 93 // This interface predates the fs.FS interface, which can be used instead: 94 // the FS adapter function converts an fs.FS to a FileSystem. 95 type FileSystem interface { 96 Open(name string) (File, error) 97 } 98 99 // A File is returned by a FileSystem's Open method and can be 100 // served by the FileServer implementation. 101 // 102 // The methods should behave the same as those on an *os.File. 103 type File interface { 104 io.Closer 105 io.Reader 106 io.Seeker 107 Readdir(count int) ([]fs.FileInfo, error) 108 Stat() (fs.FileInfo, error) 109 } 110 111 type anyDirs interface { 112 len() int 113 name(i int) string 114 isDir(i int) bool 115 } 116 117 type fileInfoDirs []fs.FileInfo 118 119 func (d fileInfoDirs) len() int { return len(d) } 120 func (d fileInfoDirs) isDir(i int) bool { return d[i].IsDir() } 121 func (d fileInfoDirs) name(i int) string { return d[i].Name() } 122 123 type dirEntryDirs []fs.DirEntry 124 125 func (d dirEntryDirs) len() int { return len(d) } 126 func (d dirEntryDirs) isDir(i int) bool { return d[i].IsDir() } 127 func (d dirEntryDirs) name(i int) string { return d[i].Name() } 128 129 func dirList(w ResponseWriter, r *Request, f File) { 130 // Prefer to use ReadDir instead of Readdir, 131 // because the former doesn't require calling 132 // Stat on every entry of a directory on Unix. 133 var dirs anyDirs 134 var err error 135 if d, ok := f.(fs.ReadDirFile); ok { 136 var list dirEntryDirs 137 list, err = d.ReadDir(-1) 138 dirs = list 139 } else { 140 var list fileInfoDirs 141 list, err = f.Readdir(-1) 142 dirs = list 143 } 144 145 if err != nil { 146 logf(r, "http: error reading directory: %v", err) 147 Error(w, "Error reading directory", StatusInternalServerError) 148 return 149 } 150 sort.Slice(dirs, func(i, j int) bool { return dirs.name(i) < dirs.name(j) }) 151 152 w.Header().Set("Content-Type", "text/html; charset=utf-8") 153 fmt.Fprintf(w, "<pre>\n") 154 for i, n := 0, dirs.len(); i < n; i++ { 155 name := dirs.name(i) 156 if dirs.isDir(i) { 157 name += "/" 158 } 159 // name may contain '?' or '#', which must be escaped to remain 160 // part of the URL path, and not indicate the start of a query 161 // string or fragment. 162 url := url.URL{Path: name} 163 fmt.Fprintf(w, "<a href=\"%s\">%s</a>\n", url.String(), htmlReplacer.Replace(name)) 164 } 165 fmt.Fprintf(w, "</pre>\n") 166 } 167 168 // ServeContent replies to the request using the content in the 169 // provided ReadSeeker. The main benefit of ServeContent over io.Copy 170 // is that it handles Range requests properly, sets the MIME type, and 171 // handles If-Match, If-Unmodified-Since, If-None-Match, If-Modified-Since, 172 // and If-Range requests. 173 // 174 // If the response's Content-Type header is not set, ServeContent 175 // first tries to deduce the type from name's file extension and, 176 // if that fails, falls back to reading the first block of the content 177 // and passing it to DetectContentType. 178 // The name is otherwise unused; in particular it can be empty and is 179 // never sent in the response. 180 // 181 // If modtime is not the zero time or Unix epoch, ServeContent 182 // includes it in a Last-Modified header in the response. If the 183 // request includes an If-Modified-Since header, ServeContent uses 184 // modtime to decide whether the content needs to be sent at all. 185 // 186 // The content's Seek method must work: ServeContent uses 187 // a seek to the end of the content to determine its size. 188 // 189 // If the caller has set w's ETag header formatted per RFC 7232, section 2.3, 190 // ServeContent uses it to handle requests using If-Match, If-None-Match, or If-Range. 191 // 192 // Note that *os.File implements the io.ReadSeeker interface. 193 func ServeContent(w ResponseWriter, req *Request, name string, modtime time.Time, content io.ReadSeeker) { 194 sizeFunc := func() (int64, error) { 195 size, err := content.Seek(0, io.SeekEnd) 196 if err != nil { 197 return 0, errSeeker 198 } 199 _, err = content.Seek(0, io.SeekStart) 200 if err != nil { 201 return 0, errSeeker 202 } 203 return size, nil 204 } 205 serveContent(w, req, name, modtime, sizeFunc, content) 206 } 207 208 // errSeeker is returned by ServeContent's sizeFunc when the content 209 // doesn't seek properly. The underlying Seeker's error text isn't 210 // included in the sizeFunc reply so it's not sent over HTTP to end 211 // users. 212 var errSeeker = errors.New("seeker can't seek") 213 214 // errNoOverlap is returned by serveContent's parseRange if first-byte-pos of 215 // all of the byte-range-spec Values is greater than the content size. 216 var errNoOverlap = errors.New("invalid range: failed to overlap") 217 218 // if name is empty, filename is unknown. (used for mime type, before sniffing) 219 // if modtime.IsZero(), modtime is unknown. 220 // content must be seeked to the beginning of the file. 221 // The sizeFunc is called at most once. Its error, if any, is sent in the HTTP response. 222 func serveContent(w ResponseWriter, r *Request, name string, modtime time.Time, sizeFunc func() (int64, error), content io.ReadSeeker) { 223 setLastModified(w, modtime) 224 done, rangeReq := checkPreconditions(w, r, modtime) 225 if done { 226 return 227 } 228 229 code := StatusOK 230 231 // If Content-Type isn't set, use the file's extension to find it, but 232 // if the Content-Type is unset explicitly, do not sniff the type. 233 ctypes, haveType := w.Header()["Content-Type"] 234 var ctype string 235 if !haveType { 236 ctype = mime.TypeByExtension(filepath.Ext(name)) 237 if ctype == "" { 238 // read a chunk to decide between utf-8 text and binary 239 var buf [sniffLen]byte 240 n, _ := io.ReadFull(content, buf[:]) 241 ctype = DetectContentType(buf[:n]) 242 _, err := content.Seek(0, io.SeekStart) // rewind to output whole file 243 if err != nil { 244 Error(w, "seeker can't seek", StatusInternalServerError) 245 return 246 } 247 } 248 w.Header().Set("Content-Type", ctype) 249 } else if len(ctypes) > 0 { 250 ctype = ctypes[0] 251 } 252 253 size, err := sizeFunc() 254 if err != nil { 255 Error(w, err.Error(), StatusInternalServerError) 256 return 257 } 258 if size < 0 { 259 // Should never happen but just to be sure 260 Error(w, "negative content size computed", StatusInternalServerError) 261 return 262 } 263 264 // handle Content-Range header. 265 sendSize := size 266 var sendContent io.Reader = content 267 ranges, err := parseRange(rangeReq, size) 268 switch err { 269 case nil: 270 case errNoOverlap: 271 if size == 0 { 272 // Some clients add a Range header to all requests to 273 // limit the size of the response. If the file is empty, 274 // ignore the range header and respond with a 200 rather 275 // than a 416. 276 ranges = nil 277 break 278 } 279 w.Header().Set("Content-Range", fmt.Sprintf("bytes */%d", size)) 280 fallthrough 281 default: 282 Error(w, err.Error(), StatusRequestedRangeNotSatisfiable) 283 return 284 } 285 286 if sumRangesSize(ranges) > size { 287 // The total number of bytes in all the ranges 288 // is larger than the size of the file by 289 // itself, so this is probably an attack, or a 290 // dumb client. Ignore the range request. 291 ranges = nil 292 } 293 switch { 294 case len(ranges) == 1: 295 // RFC 7233, Section 4.1: 296 // "If a single part is being transferred, the server 297 // generating the 206 response MUST generate a 298 // Content-Range header field, describing what range 299 // of the selected representation is enclosed, and a 300 // payload consisting of the range. 301 // ... 302 // A server MUST NOT generate a multipart response to 303 // a request for a single range, since a client that 304 // does not request multiple parts might not support 305 // multipart responses." 306 ra := ranges[0] 307 if _, err := content.Seek(ra.start, io.SeekStart); err != nil { 308 Error(w, err.Error(), StatusRequestedRangeNotSatisfiable) 309 return 310 } 311 sendSize = ra.length 312 code = StatusPartialContent 313 w.Header().Set("Content-Range", ra.contentRange(size)) 314 case len(ranges) > 1: 315 sendSize = rangesMIMESize(ranges, ctype, size) 316 code = StatusPartialContent 317 318 pr, pw := io.Pipe() 319 mw := multipart.NewWriter(pw) 320 w.Header().Set("Content-Type", "multipart/byteranges; boundary="+mw.Boundary()) 321 sendContent = pr 322 defer pr.Close() // cause writing goroutine to fail and exit if CopyN doesn't finish. 323 go func() { 324 for _, ra := range ranges { 325 part, err := mw.CreatePart(ra.mimeHeader(ctype, size)) 326 if err != nil { 327 pw.CloseWithError(err) 328 return 329 } 330 if _, err := content.Seek(ra.start, io.SeekStart); err != nil { 331 pw.CloseWithError(err) 332 return 333 } 334 if _, err := io.CopyN(part, content, ra.length); err != nil { 335 pw.CloseWithError(err) 336 return 337 } 338 } 339 mw.Close() 340 pw.Close() 341 }() 342 } 343 344 w.Header().Set("Accept-Ranges", "bytes") 345 if w.Header().Get("Content-Encoding") == "" { 346 w.Header().Set("Content-Length", strconv.FormatInt(sendSize, 10)) 347 } 348 349 w.WriteHeader(code) 350 351 if r.Method != "HEAD" { 352 io.CopyN(w, sendContent, sendSize) 353 } 354 } 355 356 // scanETag determines if a syntactically valid ETag is present at s. If so, 357 // the ETag and remaining text after consuming ETag is returned. Otherwise, 358 // it returns "", "". 359 func scanETag(s string) (etag string, remain string) { 360 s = textproto.TrimString(s) 361 start := 0 362 if strings.HasPrefix(s, "W/") { 363 start = 2 364 } 365 if len(s[start:]) < 2 || s[start] != '"' { 366 return "", "" 367 } 368 // ETag is either W/"text" or "text". 369 // See RFC 7232 2.3. 370 for i := start + 1; i < len(s); i++ { 371 c := s[i] 372 switch { 373 // Character Values allowed in ETags. 374 case c == 0x21 || c >= 0x23 && c <= 0x7E || c >= 0x80: 375 case c == '"': 376 return s[:i+1], s[i+1:] 377 default: 378 return "", "" 379 } 380 } 381 return "", "" 382 } 383 384 // etagStrongMatch reports whether a and b match using strong ETag comparison. 385 // Assumes a and b are valid ETags. 386 func etagStrongMatch(a, b string) bool { 387 return a == b && a != "" && a[0] == '"' 388 } 389 390 // etagWeakMatch reports whether a and b match using weak ETag comparison. 391 // Assumes a and b are valid ETags. 392 func etagWeakMatch(a, b string) bool { 393 return strings.TrimPrefix(a, "W/") == strings.TrimPrefix(b, "W/") 394 } 395 396 // condResult is the result of an HTTP request precondition check. 397 // See https://tools.ietf.org/html/rfc7232 section 3. 398 type condResult int 399 400 const ( 401 condNone condResult = iota 402 condTrue 403 condFalse 404 ) 405 406 func checkIfMatch(w ResponseWriter, r *Request) condResult { 407 im := r.Header.Get("If-Match") 408 if im == "" { 409 return condNone 410 } 411 for { 412 im = textproto.TrimString(im) 413 if len(im) == 0 { 414 break 415 } 416 if im[0] == ',' { 417 im = im[1:] 418 continue 419 } 420 if im[0] == '*' { 421 return condTrue 422 } 423 etag, remain := scanETag(im) 424 if etag == "" { 425 break 426 } 427 if etagStrongMatch(etag, w.Header().get("Etag")) { 428 return condTrue 429 } 430 im = remain 431 } 432 433 return condFalse 434 } 435 436 func checkIfUnmodifiedSince(r *Request, modtime time.Time) condResult { 437 ius := r.Header.Get("If-Unmodified-Since") 438 if ius == "" || isZeroTime(modtime) { 439 return condNone 440 } 441 t, err := ParseTime(ius) 442 if err != nil { 443 return condNone 444 } 445 446 // The Last-Modified header truncates sub-second precision so 447 // the modtime needs to be truncated too. 448 modtime = modtime.Truncate(time.Second) 449 if ret := modtime.Compare(t); ret <= 0 { 450 return condTrue 451 } 452 return condFalse 453 } 454 455 func checkIfNoneMatch(w ResponseWriter, r *Request) condResult { 456 inm := r.Header.get("If-None-Match") 457 if inm == "" { 458 return condNone 459 } 460 buf := inm 461 for { 462 buf = textproto.TrimString(buf) 463 if len(buf) == 0 { 464 break 465 } 466 if buf[0] == ',' { 467 buf = buf[1:] 468 continue 469 } 470 if buf[0] == '*' { 471 return condFalse 472 } 473 etag, remain := scanETag(buf) 474 if etag == "" { 475 break 476 } 477 if etagWeakMatch(etag, w.Header().get("Etag")) { 478 return condFalse 479 } 480 buf = remain 481 } 482 return condTrue 483 } 484 485 func checkIfModifiedSince(r *Request, modtime time.Time) condResult { 486 if r.Method != "GET" && r.Method != "HEAD" { 487 return condNone 488 } 489 ims := r.Header.Get("If-Modified-Since") 490 if ims == "" || isZeroTime(modtime) { 491 return condNone 492 } 493 t, err := ParseTime(ims) 494 if err != nil { 495 return condNone 496 } 497 // The Last-Modified header truncates sub-second precision so 498 // the modtime needs to be truncated too. 499 modtime = modtime.Truncate(time.Second) 500 if ret := modtime.Compare(t); ret <= 0 { 501 return condFalse 502 } 503 return condTrue 504 } 505 506 func checkIfRange(w ResponseWriter, r *Request, modtime time.Time) condResult { 507 if r.Method != "GET" && r.Method != "HEAD" { 508 return condNone 509 } 510 ir := r.Header.get("If-Range") 511 if ir == "" { 512 return condNone 513 } 514 etag, _ := scanETag(ir) 515 if etag != "" { 516 if etagStrongMatch(etag, w.Header().Get("Etag")) { 517 return condTrue 518 } else { 519 return condFalse 520 } 521 } 522 // The If-Range value is typically the ETag value, but it may also be 523 // the modtime date. See golang.org/issue/8367. 524 if modtime.IsZero() { 525 return condFalse 526 } 527 t, err := ParseTime(ir) 528 if err != nil { 529 return condFalse 530 } 531 if t.Unix() == modtime.Unix() { 532 return condTrue 533 } 534 return condFalse 535 } 536 537 var unixEpochTime = time.Unix(0, 0) 538 539 // isZeroTime reports whether t is obviously unspecified (either zero or Unix()=0). 540 func isZeroTime(t time.Time) bool { 541 return t.IsZero() || t.Equal(unixEpochTime) 542 } 543 544 func setLastModified(w ResponseWriter, modtime time.Time) { 545 if !isZeroTime(modtime) { 546 w.Header().Set("Last-Modified", modtime.UTC().Format(TimeFormat)) 547 } 548 } 549 550 func writeNotModified(w ResponseWriter) { 551 // RFC 7232 section 4.1: 552 // a sender SHOULD NOT generate representation metadata other than the 553 // above listed fields unless said metadata exists for the purpose of 554 // guiding cache updates (e.g., Last-Modified might be useful if the 555 // response does not have an ETag field). 556 h := w.Header() 557 delete(h, "Content-Type") 558 delete(h, "Content-Length") 559 delete(h, "Content-Encoding") 560 if h.Get("Etag") != "" { 561 delete(h, "Last-Modified") 562 } 563 w.WriteHeader(StatusNotModified) 564 } 565 566 // checkPreconditions evaluates request preconditions and reports whether a precondition 567 // resulted in sending StatusNotModified or StatusPreconditionFailed. 568 func checkPreconditions(w ResponseWriter, r *Request, modtime time.Time) (done bool, rangeHeader string) { 569 // This function carefully follows RFC 7232 section 6. 570 ch := checkIfMatch(w, r) 571 if ch == condNone { 572 ch = checkIfUnmodifiedSince(r, modtime) 573 } 574 if ch == condFalse { 575 w.WriteHeader(StatusPreconditionFailed) 576 return true, "" 577 } 578 switch checkIfNoneMatch(w, r) { 579 case condFalse: 580 if r.Method == "GET" || r.Method == "HEAD" { 581 writeNotModified(w) 582 return true, "" 583 } else { 584 w.WriteHeader(StatusPreconditionFailed) 585 return true, "" 586 } 587 case condNone: 588 if checkIfModifiedSince(r, modtime) == condFalse { 589 writeNotModified(w) 590 return true, "" 591 } 592 } 593 594 rangeHeader = r.Header.get("Range") 595 if rangeHeader != "" && checkIfRange(w, r, modtime) == condFalse { 596 rangeHeader = "" 597 } 598 return false, rangeHeader 599 } 600 601 // name is '/'-separated, not filepath.Separator. 602 func serveFile(w ResponseWriter, r *Request, fs FileSystem, name string, redirect bool) { 603 const indexPage = "/index.html" 604 605 // redirect .../index.html to .../ 606 // can't use Redirect() because that would make the path absolute, 607 // which would be a problem running under StripPrefix 608 if strings.HasSuffix(r.URL.Path, indexPage) { 609 localRedirect(w, r, "./") 610 return 611 } 612 613 f, err := fs.Open(name) 614 if err != nil { 615 msg, code := toHTTPError(err) 616 Error(w, msg, code) 617 return 618 } 619 defer f.Close() 620 621 d, err := f.Stat() 622 if err != nil { 623 msg, code := toHTTPError(err) 624 Error(w, msg, code) 625 return 626 } 627 628 if redirect { 629 // redirect to canonical path: / at end of directory url 630 // r.URL.Path always begins with / 631 url := r.URL.Path 632 if d.IsDir() { 633 if url[len(url)-1] != '/' { 634 localRedirect(w, r, path.Base(url)+"/") 635 return 636 } 637 } else { 638 if url[len(url)-1] == '/' { 639 localRedirect(w, r, "../"+path.Base(url)) 640 return 641 } 642 } 643 } 644 645 if d.IsDir() { 646 url := r.URL.Path 647 // redirect if the directory name doesn't end in a slash 648 if url == "" || url[len(url)-1] != '/' { 649 localRedirect(w, r, path.Base(url)+"/") 650 return 651 } 652 653 // use contents of index.html for directory, if present 654 index := strings.TrimSuffix(name, "/") + indexPage 655 ff, err := fs.Open(index) 656 if err == nil { 657 defer ff.Close() 658 dd, err := ff.Stat() 659 if err == nil { 660 d = dd 661 f = ff 662 } 663 } 664 } 665 666 // Still a directory? (we didn't find an index.html file) 667 if d.IsDir() { 668 if checkIfModifiedSince(r, d.ModTime()) == condFalse { 669 writeNotModified(w) 670 return 671 } 672 setLastModified(w, d.ModTime()) 673 dirList(w, r, f) 674 return 675 } 676 677 // serveContent will check modification time 678 sizeFunc := func() (int64, error) { return d.Size(), nil } 679 serveContent(w, r, d.Name(), d.ModTime(), sizeFunc, f) 680 } 681 682 // toHTTPError returns a non-specific HTTP error message and status code 683 // for a given non-nil error value. It's important that toHTTPError does not 684 // actually return err.Error(), since msg and httpStatus are returned to users, 685 // and historically Go's ServeContent always returned just "404 Not Found" for 686 // all errors. We don't want to start leaking information in error messages. 687 func toHTTPError(err error) (msg string, httpStatus int) { 688 if errors.Is(err, fs.ErrNotExist) { 689 return "404 page not found", StatusNotFound 690 } 691 if errors.Is(err, fs.ErrPermission) { 692 return "403 Forbidden", StatusForbidden 693 } 694 // Default: 695 return "500 Internal Server Error", StatusInternalServerError 696 } 697 698 // localRedirect gives a Moved Permanently response. 699 // It does not convert relative paths to absolute paths like Redirect does. 700 func localRedirect(w ResponseWriter, r *Request, newPath string) { 701 if q := r.URL.RawQuery; q != "" { 702 newPath += "?" + q 703 } 704 w.Header().Set("Location", newPath) 705 w.WriteHeader(StatusMovedPermanently) 706 } 707 708 // ServeFile replies to the request with the contents of the named 709 // file or directory. 710 // 711 // If the provided file or directory name is a relative path, it is 712 // interpreted relative to the current directory and may ascend to 713 // parent directories. If the provided name is constructed from user 714 // input, it should be sanitized before calling ServeFile. 715 // 716 // As a precaution, ServeFile will reject requests where r.URL.Path 717 // contains a ".." path element; this protects against callers who 718 // might unsafely use filepath.Join on r.URL.Path without sanitizing 719 // it and then use that filepath.Join result as the name argument. 720 // 721 // As another special case, ServeFile redirects any request where r.URL.Path 722 // ends in "/index.html" to the same path, without the final 723 // "index.html". To avoid such redirects either modify the path or 724 // use ServeContent. 725 // 726 // Outside of those two special cases, ServeFile does not use 727 // r.URL.Path for selecting the file or directory to serve; only the 728 // file or directory provided in the name argument is used. 729 func ServeFile(w ResponseWriter, r *Request, name string) { 730 if containsDotDot(r.URL.Path) { 731 // Too many programs use r.URL.Path to construct the argument to 732 // serveFile. Reject the request under the assumption that happened 733 // here and ".." may not be wanted. 734 // Note that name might not contain "..", for example if code (still 735 // incorrectly) used filepath.Join(myDir, r.URL.Path). 736 Error(w, "invalid URL path", StatusBadRequest) 737 return 738 } 739 dir, file := filepath.Split(name) 740 serveFile(w, r, Dir(dir), file, false) 741 } 742 743 func containsDotDot(v string) bool { 744 if !strings.Contains(v, "..") { 745 return false 746 } 747 for _, ent := range strings.FieldsFunc(v, isSlashRune) { 748 if ent == ".." { 749 return true 750 } 751 } 752 return false 753 } 754 755 func isSlashRune(r rune) bool { return r == '/' || r == '\\' } 756 757 type fileHandler struct { 758 root FileSystem 759 } 760 761 type ioFS struct { 762 fsys fs.FS 763 } 764 765 type ioFile struct { 766 file fs.File 767 } 768 769 func (f ioFS) Open(name string) (File, error) { 770 if name == "/" { 771 name = "." 772 } else { 773 name = strings.TrimPrefix(name, "/") 774 } 775 file, err := f.fsys.Open(name) 776 if err != nil { 777 return nil, mapOpenError(err, name, '/', func(path string) (fs.FileInfo, error) { 778 return fs.Stat(f.fsys, path) 779 }) 780 } 781 return ioFile{file}, nil 782 } 783 784 func (f ioFile) Close() error { return f.file.Close() } 785 func (f ioFile) Read(b []byte) (int, error) { return f.file.Read(b) } 786 func (f ioFile) Stat() (fs.FileInfo, error) { return f.file.Stat() } 787 788 var errMissingSeek = errors.New("io.File missing Seek method") 789 var errMissingReadDir = errors.New("io.File directory missing ReadDir method") 790 791 func (f ioFile) Seek(offset int64, whence int) (int64, error) { 792 s, ok := f.file.(io.Seeker) 793 if !ok { 794 return 0, errMissingSeek 795 } 796 return s.Seek(offset, whence) 797 } 798 799 func (f ioFile) ReadDir(count int) ([]fs.DirEntry, error) { 800 d, ok := f.file.(fs.ReadDirFile) 801 if !ok { 802 return nil, errMissingReadDir 803 } 804 return d.ReadDir(count) 805 } 806 807 func (f ioFile) Readdir(count int) ([]fs.FileInfo, error) { 808 d, ok := f.file.(fs.ReadDirFile) 809 if !ok { 810 return nil, errMissingReadDir 811 } 812 var list []fs.FileInfo 813 for { 814 dirs, err := d.ReadDir(count - len(list)) 815 for _, dir := range dirs { 816 info, err := dir.Info() 817 if err != nil { 818 // Pretend it doesn't exist, like (*os.File).Readdir does. 819 continue 820 } 821 list = append(list, info) 822 } 823 if err != nil { 824 return list, err 825 } 826 if count < 0 || len(list) >= count { 827 break 828 } 829 } 830 return list, nil 831 } 832 833 // FS converts fsys to a FileSystem implementation, 834 // for use with FileServer and NewFileTransport. 835 // The files provided by fsys must implement io.Seeker. 836 func FS(fsys fs.FS) FileSystem { 837 return ioFS{fsys} 838 } 839 840 // FileServer returns a handler that serves HTTP requests 841 // with the contents of the file system rooted at root. 842 // 843 // As a special case, the returned file server redirects any request 844 // ending in "/index.html" to the same path, without the final 845 // "index.html". 846 // 847 // To use the operating system's file system implementation, 848 // use http.Dir: 849 // 850 // http.Handle("/", http.FileServer(http.Dir("/tmp"))) 851 // 852 // To use an fs.FS implementation, use http.FS to convert it: 853 // 854 // http.Handle("/", http.FileServer(http.FS(fsys))) 855 func FileServer(root FileSystem) Handler { 856 return &fileHandler{root} 857 } 858 859 func (f *fileHandler) ServeHTTP(w ResponseWriter, r *Request) { 860 const options = MethodOptions + ", " + MethodGet + ", " + MethodHead 861 862 switch r.Method { 863 case MethodGet, MethodHead: 864 if !strings.HasPrefix(r.URL.Path, "/") { 865 r.URL.Path = "/" + r.URL.Path 866 } 867 serveFile(w, r, f.root, path.Clean(r.URL.Path), true) 868 869 case MethodOptions: 870 w.Header().Set("Allow", options) 871 872 default: 873 w.Header().Set("Allow", options) 874 Error(w, "read-only", StatusMethodNotAllowed) 875 } 876 } 877 878 // httpRange specifies the byte range to be sent to the client. 879 type httpRange struct { 880 start, length int64 881 } 882 883 func (r httpRange) contentRange(size int64) string { 884 return fmt.Sprintf("bytes %d-%d/%d", r.start, r.start+r.length-1, size) 885 } 886 887 func (r httpRange) mimeHeader(contentType string, size int64) textproto.MIMEHeader { 888 return textproto.MIMEHeader{ 889 "Content-Range": {r.contentRange(size)}, 890 "Content-Type": {contentType}, 891 } 892 } 893 894 // parseRange parses a Range header string as per RFC 7233. 895 // errNoOverlap is returned if none of the ranges overlap. 896 func parseRange(s string, size int64) ([]httpRange, error) { 897 if s == "" { 898 return nil, nil // header not present 899 } 900 const b = "bytes=" 901 if !strings.HasPrefix(s, b) { 902 return nil, errors.New("invalid range") 903 } 904 var ranges []httpRange 905 noOverlap := false 906 for _, ra := range strings.Split(s[len(b):], ",") { 907 ra = textproto.TrimString(ra) 908 if ra == "" { 909 continue 910 } 911 start, end, ok := strings.Cut(ra, "-") 912 if !ok { 913 return nil, errors.New("invalid range") 914 } 915 start, end = textproto.TrimString(start), textproto.TrimString(end) 916 var r httpRange 917 if start == "" { 918 // If no start is specified, end specifies the 919 // range start relative to the end of the file, 920 // and we are dealing with <suffix-length> 921 // which has to be a non-negative integer as per 922 // RFC 7233 Section 2.1 "Byte-Ranges". 923 if end == "" || end[0] == '-' { 924 return nil, errors.New("invalid range") 925 } 926 i, err := strconv.ParseInt(end, 10, 64) 927 if i < 0 || err != nil { 928 return nil, errors.New("invalid range") 929 } 930 if i > size { 931 i = size 932 } 933 r.start = size - i 934 r.length = size - r.start 935 } else { 936 i, err := strconv.ParseInt(start, 10, 64) 937 if err != nil || i < 0 { 938 return nil, errors.New("invalid range") 939 } 940 if i >= size { 941 // If the range begins after the size of the content, 942 // then it does not overlap. 943 noOverlap = true 944 continue 945 } 946 r.start = i 947 if end == "" { 948 // If no end is specified, range extends to end of the file. 949 r.length = size - r.start 950 } else { 951 i, err := strconv.ParseInt(end, 10, 64) 952 if err != nil || r.start > i { 953 return nil, errors.New("invalid range") 954 } 955 if i >= size { 956 i = size - 1 957 } 958 r.length = i - r.start + 1 959 } 960 } 961 ranges = append(ranges, r) 962 } 963 if noOverlap && len(ranges) == 0 { 964 // The specified ranges did not overlap with the content. 965 return nil, errNoOverlap 966 } 967 return ranges, nil 968 } 969 970 // countingWriter counts how many bytes have been written to it. 971 type countingWriter int64 972 973 func (w *countingWriter) Write(p []byte) (n int, err error) { 974 *w += countingWriter(len(p)) 975 return len(p), nil 976 } 977 978 // rangesMIMESize returns the number of bytes it takes to encode the 979 // provided ranges as a multipart response. 980 func rangesMIMESize(ranges []httpRange, contentType string, contentSize int64) (encSize int64) { 981 var w countingWriter 982 mw := multipart.NewWriter(&w) 983 for _, ra := range ranges { 984 mw.CreatePart(ra.mimeHeader(contentType, contentSize)) 985 encSize += ra.length 986 } 987 mw.Close() 988 encSize += int64(w) 989 return 990 } 991 992 func sumRangesSize(ranges []httpRange) (size int64) { 993 for _, ra := range ranges { 994 size += ra.length 995 } 996 return 997 }