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.
5 // HTTP file system request handler
27 // A Dir implements FileSystem using the native file system restricted to a
28 // specific directory tree.
30 // While the FileSystem.Open method takes '/'-separated paths, a Dir's string
31 // value is a filename on the native file system, not a URL, so it is separated
32 // by filepath.Separator, which isn't necessarily '/'.
34 // Note that Dir could expose sensitive files and directories. Dir will follow
35 // symlinks pointing out of the directory tree, which can be especially dangerous
36 // if serving from a directory in which users are able to create arbitrary symlinks.
37 // Dir will also allow access to files and directories starting with a period,
38 // which could expose sensitive directories like .git or sensitive files like
39 // .htpasswd. To exclude files with a leading period, remove the files/directories
40 // from the server or create a custom FileSystem implementation.
42 // An empty Dir is treated as ".".
45 // mapOpenError maps the provided non-nil error from opening name
46 // to a possibly better non-nil error. In particular, it turns OS-specific errors
47 // about opening files in non-directories into fs.ErrNotExist. See Issues 18984 and 49552.
48 func mapOpenError(originalErr error, name string, sep rune, stat func(string) (fs.FileInfo, error)) error {
49 if errors.Is(originalErr, fs.ErrNotExist) || errors.Is(originalErr, fs.ErrPermission) {
53 parts := strings.Split(name, string(sep))
54 for i := range parts {
58 fi, err := stat(strings.Join(parts[:i+1], string(sep)))
69 // Open implements FileSystem using os.Open, opening files for reading rooted
70 // and relative to the directory d.
71 func (d Dir) Open(name string) (File, error) {
72 if filepath.Separator != '/' && strings.ContainsRune(name, filepath.Separator) {
73 return nil, errors.New("http: invalid character in file path")
79 fullName := filepath.Join(dir, filepath.FromSlash(path.Clean("/"+name)))
80 f, err := os.Open(fullName)
82 return nil, mapOpenError(err, fullName, filepath.Separator, os.Stat)
87 // A FileSystem implements access to a collection of named files.
88 // The elements in a file path are separated by slash ('/', U+002F)
89 // characters, regardless of host operating system convention.
90 // See the FileServer function to convert a FileSystem to a Handler.
92 // This interface predates the fs.FS interface, which can be used instead:
93 // the FS adapter function converts an fs.FS to a FileSystem.
94 type FileSystem interface {
95 Open(name string) (File, error)
98 // A File is returned by a FileSystem's Open method and can be
99 // served by the FileServer implementation.
101 // The methods should behave the same as those on an *os.File.
102 type File interface {
106 Readdir(count int) ([]fs.FileInfo, error)
107 Stat() (fs.FileInfo, error)
110 type anyDirs interface {
116 type fileInfoDirs []fs.FileInfo
118 func (d fileInfoDirs) len() int { return len(d) }
119 func (d fileInfoDirs) isDir(i int) bool { return d[i].IsDir() }
120 func (d fileInfoDirs) name(i int) string { return d[i].Name() }
122 type dirEntryDirs []fs.DirEntry
124 func (d dirEntryDirs) len() int { return len(d) }
125 func (d dirEntryDirs) isDir(i int) bool { return d[i].IsDir() }
126 func (d dirEntryDirs) name(i int) string { return d[i].Name() }
128 func dirList(w ResponseWriter, r *Request, f File) {
129 // Prefer to use ReadDir instead of Readdir,
130 // because the former doesn't require calling
131 // Stat on every entry of a directory on Unix.
134 if d, ok := f.(fs.ReadDirFile); ok {
135 var list dirEntryDirs
136 list, err = d.ReadDir(-1)
139 var list fileInfoDirs
140 list, err = f.Readdir(-1)
145 logf(r, "http: error reading directory: %v", err)
146 Error(w, "Error reading directory", StatusInternalServerError)
149 sort.Slice(dirs, func(i, j int) bool { return dirs.name(i) < dirs.name(j) })
151 w.Header().Set("Content-Type", "text/html; charset=utf-8")
152 fmt.Fprintf(w, "<pre>\n")
153 for i, n := 0, dirs.len(); i < n; i++ {
158 // name may contain '?' or '#', which must be escaped to remain
159 // part of the URL path, and not indicate the start of a query
160 // string or fragment.
161 url := url.URL{Path: name}
162 fmt.Fprintf(w, "<a href=\"%s\">%s</a>\n", url.String(), htmlReplacer.Replace(name))
164 fmt.Fprintf(w, "</pre>\n")
167 // ServeContent replies to the request using the content in the
168 // provided ReadSeeker. The main benefit of ServeContent over io.Copy
169 // is that it handles Range requests properly, sets the MIME type, and
170 // handles If-Match, If-Unmodified-Since, If-None-Match, If-Modified-Since,
171 // and If-Range requests.
173 // If the response's Content-Type header is not set, ServeContent
174 // first tries to deduce the type from name's file extension and,
175 // if that fails, falls back to reading the first block of the content
176 // and passing it to DetectContentType.
177 // The name is otherwise unused; in particular it can be empty and is
178 // never sent in the response.
180 // If modtime is not the zero time or Unix epoch, ServeContent
181 // includes it in a Last-Modified header in the response. If the
182 // request includes an If-Modified-Since header, ServeContent uses
183 // modtime to decide whether the content needs to be sent at all.
185 // The content's Seek method must work: ServeContent uses
186 // a seek to the end of the content to determine its size.
188 // If the caller has set w's ETag header formatted per RFC 7232, section 2.3,
189 // ServeContent uses it to handle requests using If-Match, If-None-Match, or If-Range.
191 // Note that *os.File implements the io.ReadSeeker interface.
192 func ServeContent(w ResponseWriter, req *Request, name string, modtime time.Time, content io.ReadSeeker) {
193 sizeFunc := func() (int64, error) {
194 size, err := content.Seek(0, io.SeekEnd)
198 _, err = content.Seek(0, io.SeekStart)
204 serveContent(w, req, name, modtime, sizeFunc, content)
207 // errSeeker is returned by ServeContent's sizeFunc when the content
208 // doesn't seek properly. The underlying Seeker's error text isn't
209 // included in the sizeFunc reply so it's not sent over HTTP to end
211 var errSeeker = errors.New("seeker can't seek")
213 // errNoOverlap is returned by serveContent's parseRange if first-byte-pos of
214 // all of the byte-range-spec values is greater than the content size.
215 var errNoOverlap = errors.New("invalid range: failed to overlap")
217 // if name is empty, filename is unknown. (used for mime type, before sniffing)
218 // if modtime.IsZero(), modtime is unknown.
219 // content must be seeked to the beginning of the file.
220 // The sizeFunc is called at most once. Its error, if any, is sent in the HTTP response.
221 func serveContent(w ResponseWriter, r *Request, name string, modtime time.Time, sizeFunc func() (int64, error), content io.ReadSeeker) {
222 setLastModified(w, modtime)
223 done, rangeReq := checkPreconditions(w, r, modtime)
230 // If Content-Type isn't set, use the file's extension to find it, but
231 // if the Content-Type is unset explicitly, do not sniff the type.
232 ctypes, haveType := w.Header()["Content-Type"]
235 ctype = mime.TypeByExtension(filepath.Ext(name))
237 // read a chunk to decide between utf-8 text and binary
238 var buf [sniffLen]byte
239 n, _ := io.ReadFull(content, buf[:])
240 ctype = DetectContentType(buf[:n])
241 _, err := content.Seek(0, io.SeekStart) // rewind to output whole file
243 Error(w, "seeker can't seek", StatusInternalServerError)
247 w.Header().Set("Content-Type", ctype)
248 } else if len(ctypes) > 0 {
252 size, err := sizeFunc()
254 Error(w, err.Error(), StatusInternalServerError)
258 // handle Content-Range header.
260 var sendContent io.Reader = content
262 ranges, err := parseRange(rangeReq, size)
264 if err == errNoOverlap {
265 w.Header().Set("Content-Range", fmt.Sprintf("bytes */%d", size))
267 Error(w, err.Error(), StatusRequestedRangeNotSatisfiable)
270 if sumRangesSize(ranges) > size {
271 // The total number of bytes in all the ranges
272 // is larger than the size of the file by
273 // itself, so this is probably an attack, or a
274 // dumb client. Ignore the range request.
278 case len(ranges) == 1:
279 // RFC 7233, Section 4.1:
280 // "If a single part is being transferred, the server
281 // generating the 206 response MUST generate a
282 // Content-Range header field, describing what range
283 // of the selected representation is enclosed, and a
284 // payload consisting of the range.
286 // A server MUST NOT generate a multipart response to
287 // a request for a single range, since a client that
288 // does not request multiple parts might not support
289 // multipart responses."
291 if _, err := content.Seek(ra.start, io.SeekStart); err != nil {
292 Error(w, err.Error(), StatusRequestedRangeNotSatisfiable)
296 code = StatusPartialContent
297 w.Header().Set("Content-Range", ra.contentRange(size))
298 case len(ranges) > 1:
299 sendSize = rangesMIMESize(ranges, ctype, size)
300 code = StatusPartialContent
303 mw := multipart.NewWriter(pw)
304 w.Header().Set("Content-Type", "multipart/byteranges; boundary="+mw.Boundary())
306 defer pr.Close() // cause writing goroutine to fail and exit if CopyN doesn't finish.
308 for _, ra := range ranges {
309 part, err := mw.CreatePart(ra.mimeHeader(ctype, size))
311 pw.CloseWithError(err)
314 if _, err := content.Seek(ra.start, io.SeekStart); err != nil {
315 pw.CloseWithError(err)
318 if _, err := io.CopyN(part, content, ra.length); err != nil {
319 pw.CloseWithError(err)
328 w.Header().Set("Accept-Ranges", "bytes")
329 if w.Header().Get("Content-Encoding") == "" {
330 w.Header().Set("Content-Length", strconv.FormatInt(sendSize, 10))
336 if r.Method != "HEAD" {
337 io.CopyN(w, sendContent, sendSize)
341 // scanETag determines if a syntactically valid ETag is present at s. If so,
342 // the ETag and remaining text after consuming ETag is returned. Otherwise,
343 // it returns "", "".
344 func scanETag(s string) (etag string, remain string) {
345 s = textproto.TrimString(s)
347 if strings.HasPrefix(s, "W/") {
350 if len(s[start:]) < 2 || s[start] != '"' {
353 // ETag is either W/"text" or "text".
355 for i := start + 1; i < len(s); i++ {
358 // Character values allowed in ETags.
359 case c == 0x21 || c >= 0x23 && c <= 0x7E || c >= 0x80:
361 return s[:i+1], s[i+1:]
369 // etagStrongMatch reports whether a and b match using strong ETag comparison.
370 // Assumes a and b are valid ETags.
371 func etagStrongMatch(a, b string) bool {
372 return a == b && a != "" && a[0] == '"'
375 // etagWeakMatch reports whether a and b match using weak ETag comparison.
376 // Assumes a and b are valid ETags.
377 func etagWeakMatch(a, b string) bool {
378 return strings.TrimPrefix(a, "W/") == strings.TrimPrefix(b, "W/")
381 // condResult is the result of an HTTP request precondition check.
382 // See https://tools.ietf.org/html/rfc7232 section 3.
386 condNone condResult = iota
391 func checkIfMatch(w ResponseWriter, r *Request) condResult {
392 im := r.Header.Get("If-Match")
397 im = textproto.TrimString(im)
408 etag, remain := scanETag(im)
412 if etagStrongMatch(etag, w.Header().get("Etag")) {
421 func checkIfUnmodifiedSince(r *Request, modtime time.Time) condResult {
422 ius := r.Header.Get("If-Unmodified-Since")
423 if ius == "" || isZeroTime(modtime) {
426 t, err := ParseTime(ius)
431 // The Last-Modified header truncates sub-second precision so
432 // the modtime needs to be truncated too.
433 modtime = modtime.Truncate(time.Second)
434 if modtime.Before(t) || modtime.Equal(t) {
440 func checkIfNoneMatch(w ResponseWriter, r *Request) condResult {
441 inm := r.Header.get("If-None-Match")
447 buf = textproto.TrimString(buf)
458 etag, remain := scanETag(buf)
462 if etagWeakMatch(etag, w.Header().get("Etag")) {
470 func checkIfModifiedSince(r *Request, modtime time.Time) condResult {
471 if r.Method != "GET" && r.Method != "HEAD" {
474 ims := r.Header.Get("If-Modified-Since")
475 if ims == "" || isZeroTime(modtime) {
478 t, err := ParseTime(ims)
482 // The Last-Modified header truncates sub-second precision so
483 // the modtime needs to be truncated too.
484 modtime = modtime.Truncate(time.Second)
485 if modtime.Before(t) || modtime.Equal(t) {
491 func checkIfRange(w ResponseWriter, r *Request, modtime time.Time) condResult {
492 if r.Method != "GET" && r.Method != "HEAD" {
495 ir := r.Header.get("If-Range")
499 etag, _ := scanETag(ir)
501 if etagStrongMatch(etag, w.Header().Get("Etag")) {
507 // The If-Range value is typically the ETag value, but it may also be
508 // the modtime date. See golang.org/issue/8367.
509 if modtime.IsZero() {
512 t, err := ParseTime(ir)
516 if t.Unix() == modtime.Unix() {
522 var unixEpochTime = time.Unix(0, 0)
524 // isZeroTime reports whether t is obviously unspecified (either zero or Unix()=0).
525 func isZeroTime(t time.Time) bool {
526 return t.IsZero() || t.Equal(unixEpochTime)
529 func setLastModified(w ResponseWriter, modtime time.Time) {
530 if !isZeroTime(modtime) {
531 w.Header().Set("Last-Modified", modtime.UTC().Format(TimeFormat))
535 func writeNotModified(w ResponseWriter) {
536 // RFC 7232 section 4.1:
537 // a sender SHOULD NOT generate representation metadata other than the
538 // above listed fields unless said metadata exists for the purpose of
539 // guiding cache updates (e.g., Last-Modified might be useful if the
540 // response does not have an ETag field).
542 delete(h, "Content-Type")
543 delete(h, "Content-Length")
544 if h.Get("Etag") != "" {
545 delete(h, "Last-Modified")
547 w.WriteHeader(StatusNotModified)
550 // checkPreconditions evaluates request preconditions and reports whether a precondition
551 // resulted in sending StatusNotModified or StatusPreconditionFailed.
552 func checkPreconditions(w ResponseWriter, r *Request, modtime time.Time) (done bool, rangeHeader string) {
553 // This function carefully follows RFC 7232 section 6.
554 ch := checkIfMatch(w, r)
556 ch = checkIfUnmodifiedSince(r, modtime)
559 w.WriteHeader(StatusPreconditionFailed)
562 switch checkIfNoneMatch(w, r) {
564 if r.Method == "GET" || r.Method == "HEAD" {
568 w.WriteHeader(StatusPreconditionFailed)
572 if checkIfModifiedSince(r, modtime) == condFalse {
578 rangeHeader = r.Header.get("Range")
579 if rangeHeader != "" && checkIfRange(w, r, modtime) == condFalse {
582 return false, rangeHeader
585 // name is '/'-separated, not filepath.Separator.
586 func serveFile(w ResponseWriter, r *Request, fs FileSystem, name string, redirect bool) {
587 const indexPage = "/index.html"
589 // redirect .../index.html to .../
590 // can't use Redirect() because that would make the path absolute,
591 // which would be a problem running under StripPrefix
592 if strings.HasSuffix(r.URL.Path, indexPage) {
593 localRedirect(w, r, "./")
597 f, err := fs.Open(name)
599 msg, code := toHTTPError(err)
607 msg, code := toHTTPError(err)
613 // redirect to canonical path: / at end of directory url
614 // r.URL.Path always begins with /
617 if url[len(url)-1] != '/' {
618 localRedirect(w, r, path.Base(url)+"/")
622 if url[len(url)-1] == '/' {
623 localRedirect(w, r, "../"+path.Base(url))
631 // redirect if the directory name doesn't end in a slash
632 if url == "" || url[len(url)-1] != '/' {
633 localRedirect(w, r, path.Base(url)+"/")
637 // use contents of index.html for directory, if present
638 index := strings.TrimSuffix(name, "/") + indexPage
639 ff, err := fs.Open(index)
651 // Still a directory? (we didn't find an index.html file)
653 if checkIfModifiedSince(r, d.ModTime()) == condFalse {
657 setLastModified(w, d.ModTime())
662 // serveContent will check modification time
663 sizeFunc := func() (int64, error) { return d.Size(), nil }
664 serveContent(w, r, d.Name(), d.ModTime(), sizeFunc, f)
667 // toHTTPError returns a non-specific HTTP error message and status code
668 // for a given non-nil error value. It's important that toHTTPError does not
669 // actually return err.Error(), since msg and httpStatus are returned to users,
670 // and historically Go's ServeContent always returned just "404 Not Found" for
671 // all errors. We don't want to start leaking information in error messages.
672 func toHTTPError(err error) (msg string, httpStatus int) {
673 if errors.Is(err, fs.ErrNotExist) {
674 return "404 page not found", StatusNotFound
676 if errors.Is(err, fs.ErrPermission) {
677 return "403 Forbidden", StatusForbidden
680 return "500 Internal Server Error", StatusInternalServerError
683 // localRedirect gives a Moved Permanently response.
684 // It does not convert relative paths to absolute paths like Redirect does.
685 func localRedirect(w ResponseWriter, r *Request, newPath string) {
686 if q := r.URL.RawQuery; q != "" {
689 w.Header().Set("Location", newPath)
690 w.WriteHeader(StatusMovedPermanently)
693 // ServeFile replies to the request with the contents of the named
694 // file or directory.
696 // If the provided file or directory name is a relative path, it is
697 // interpreted relative to the current directory and may ascend to
698 // parent directories. If the provided name is constructed from user
699 // input, it should be sanitized before calling ServeFile.
701 // As a precaution, ServeFile will reject requests where r.URL.Path
702 // contains a ".." path element; this protects against callers who
703 // might unsafely use filepath.Join on r.URL.Path without sanitizing
704 // it and then use that filepath.Join result as the name argument.
706 // As another special case, ServeFile redirects any request where r.URL.Path
707 // ends in "/index.html" to the same path, without the final
708 // "index.html". To avoid such redirects either modify the path or
711 // Outside of those two special cases, ServeFile does not use
712 // r.URL.Path for selecting the file or directory to serve; only the
713 // file or directory provided in the name argument is used.
714 func ServeFile(w ResponseWriter, r *Request, name string) {
715 if containsDotDot(r.URL.Path) {
716 // Too many programs use r.URL.Path to construct the argument to
717 // serveFile. Reject the request under the assumption that happened
718 // here and ".." may not be wanted.
719 // Note that name might not contain "..", for example if code (still
720 // incorrectly) used filepath.Join(myDir, r.URL.Path).
721 Error(w, "invalid URL path", StatusBadRequest)
724 dir, file := filepath.Split(name)
725 serveFile(w, r, Dir(dir), file, false)
728 func containsDotDot(v string) bool {
729 if !strings.Contains(v, "..") {
732 for _, ent := range strings.FieldsFunc(v, isSlashRune) {
740 func isSlashRune(r rune) bool { return r == '/' || r == '\\' }
742 type fileHandler struct {
754 func (f ioFS) Open(name string) (File, error) {
758 name = strings.TrimPrefix(name, "/")
760 file, err := f.fsys.Open(name)
762 return nil, mapOpenError(err, name, '/', func(path string) (fs.FileInfo, error) {
763 return fs.Stat(f.fsys, path)
766 return ioFile{file}, nil
769 func (f ioFile) Close() error { return f.file.Close() }
770 func (f ioFile) Read(b []byte) (int, error) { return f.file.Read(b) }
771 func (f ioFile) Stat() (fs.FileInfo, error) { return f.file.Stat() }
773 var errMissingSeek = errors.New("io.File missing Seek method")
774 var errMissingReadDir = errors.New("io.File directory missing ReadDir method")
776 func (f ioFile) Seek(offset int64, whence int) (int64, error) {
777 s, ok := f.file.(io.Seeker)
779 return 0, errMissingSeek
781 return s.Seek(offset, whence)
784 func (f ioFile) ReadDir(count int) ([]fs.DirEntry, error) {
785 d, ok := f.file.(fs.ReadDirFile)
787 return nil, errMissingReadDir
789 return d.ReadDir(count)
792 func (f ioFile) Readdir(count int) ([]fs.FileInfo, error) {
793 d, ok := f.file.(fs.ReadDirFile)
795 return nil, errMissingReadDir
797 var list []fs.FileInfo
799 dirs, err := d.ReadDir(count - len(list))
800 for _, dir := range dirs {
801 info, err := dir.Info()
803 // Pretend it doesn't exist, like (*os.File).Readdir does.
806 list = append(list, info)
811 if count < 0 || len(list) >= count {
818 // FS converts fsys to a FileSystem implementation,
819 // for use with FileServer and NewFileTransport.
820 func FS(fsys fs.FS) FileSystem {
824 // FileServer returns a handler that serves HTTP requests
825 // with the contents of the file system rooted at root.
827 // As a special case, the returned file server redirects any request
828 // ending in "/index.html" to the same path, without the final
831 // To use the operating system's file system implementation,
834 // http.Handle("/", http.FileServer(http.Dir("/tmp")))
836 // To use an fs.FS implementation, use http.FS to convert it:
838 // http.Handle("/", http.FileServer(http.FS(fsys)))
839 func FileServer(root FileSystem) Handler {
840 return &fileHandler{root}
843 func (f *fileHandler) ServeHTTP(w ResponseWriter, r *Request) {
845 if !strings.HasPrefix(upath, "/") {
849 serveFile(w, r, f.root, path.Clean(upath), true)
852 // httpRange specifies the byte range to be sent to the client.
853 type httpRange struct {
857 func (r httpRange) contentRange(size int64) string {
858 return fmt.Sprintf("bytes %d-%d/%d", r.start, r.start+r.length-1, size)
861 func (r httpRange) mimeHeader(contentType string, size int64) textproto.MIMEHeader {
862 return textproto.MIMEHeader{
863 "Content-Range": {r.contentRange(size)},
864 "Content-Type": {contentType},
868 // parseRange parses a Range header string as per RFC 7233.
869 // errNoOverlap is returned if none of the ranges overlap.
870 func parseRange(s string, size int64) ([]httpRange, error) {
872 return nil, nil // header not present
875 if !strings.HasPrefix(s, b) {
876 return nil, errors.New("invalid range")
878 var ranges []httpRange
880 for _, ra := range strings.Split(s[len(b):], ",") {
881 ra = textproto.TrimString(ra)
885 start, end, ok := strings.Cut(ra, "-")
887 return nil, errors.New("invalid range")
889 start, end = textproto.TrimString(start), textproto.TrimString(end)
892 // If no start is specified, end specifies the
893 // range start relative to the end of the file,
894 // and we are dealing with <suffix-length>
895 // which has to be a non-negative integer as per
896 // RFC 7233 Section 2.1 "Byte-Ranges".
897 if end == "" || end[0] == '-' {
898 return nil, errors.New("invalid range")
900 i, err := strconv.ParseInt(end, 10, 64)
901 if i < 0 || err != nil {
902 return nil, errors.New("invalid range")
908 r.length = size - r.start
910 i, err := strconv.ParseInt(start, 10, 64)
911 if err != nil || i < 0 {
912 return nil, errors.New("invalid range")
915 // If the range begins after the size of the content,
916 // then it does not overlap.
922 // If no end is specified, range extends to end of the file.
923 r.length = size - r.start
925 i, err := strconv.ParseInt(end, 10, 64)
926 if err != nil || r.start > i {
927 return nil, errors.New("invalid range")
932 r.length = i - r.start + 1
935 ranges = append(ranges, r)
937 if noOverlap && len(ranges) == 0 {
938 // The specified ranges did not overlap with the content.
939 return nil, errNoOverlap
944 // countingWriter counts how many bytes have been written to it.
945 type countingWriter int64
947 func (w *countingWriter) Write(p []byte) (n int, err error) {
948 *w += countingWriter(len(p))
952 // rangesMIMESize returns the number of bytes it takes to encode the
953 // provided ranges as a multipart response.
954 func rangesMIMESize(ranges []httpRange, contentType string, contentSize int64) (encSize int64) {
956 mw := multipart.NewWriter(&w)
957 for _, ra := range ranges {
958 mw.CreatePart(ra.mimeHeader(contentType, contentSize))
966 func sumRangesSize(ranges []httpRange) (size int64) {
967 for _, ra := range ranges {