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
26 // A Dir implements FileSystem using the native file system restricted to a
27 // specific directory tree.
29 // While the FileSystem.Open method takes '/'-separated paths, a Dir's string
30 // value is a filename on the native file system, not a URL, so it is separated
31 // by filepath.Separator, which isn't necessarily '/'.
33 // Note that Dir will allow access to files and directories starting with a
34 // period, which could expose sensitive directories like a .git directory or
35 // sensitive files like .htpasswd. To exclude files with a leading period,
36 // remove the files/directories from the server or create a custom FileSystem
39 // An empty Dir is treated as ".".
42 // mapDirOpenError maps the provided non-nil error from opening name
43 // to a possibly better non-nil error. In particular, it turns OS-specific errors
44 // about opening files in non-directories into os.ErrNotExist. See Issue 18984.
45 func mapDirOpenError(originalErr error, name string) error {
46 if os.IsNotExist(originalErr) || os.IsPermission(originalErr) {
50 parts := strings.Split(name, string(filepath.Separator))
51 for i := range parts {
55 fi, err := os.Stat(strings.Join(parts[:i+1], string(filepath.Separator)))
66 func (d Dir) Open(name string) (File, error) {
67 if filepath.Separator != '/' && strings.ContainsRune(name, filepath.Separator) {
68 return nil, errors.New("http: invalid character in file path")
74 fullName := filepath.Join(dir, filepath.FromSlash(path.Clean("/"+name)))
75 f, err := os.Open(fullName)
77 return nil, mapDirOpenError(err, fullName)
82 // A FileSystem implements access to a collection of named files.
83 // The elements in a file path are separated by slash ('/', U+002F)
84 // characters, regardless of host operating system convention.
85 type FileSystem interface {
86 Open(name string) (File, error)
89 // A File is returned by a FileSystem's Open method and can be
90 // served by the FileServer implementation.
92 // The methods should behave the same as those on an *os.File.
97 Readdir(count int) ([]os.FileInfo, error)
98 Stat() (os.FileInfo, error)
101 func dirList(w ResponseWriter, r *Request, f File) {
102 dirs, err := f.Readdir(-1)
104 logf(r, "http: error reading directory: %v", err)
105 Error(w, "Error reading directory", StatusInternalServerError)
108 sort.Slice(dirs, func(i, j int) bool { return dirs[i].Name() < dirs[j].Name() })
110 w.Header().Set("Content-Type", "text/html; charset=utf-8")
111 fmt.Fprintf(w, "<pre>\n")
112 for _, d := range dirs {
117 // name may contain '?' or '#', which must be escaped to remain
118 // part of the URL path, and not indicate the start of a query
119 // string or fragment.
120 url := url.URL{Path: name}
121 fmt.Fprintf(w, "<a href=\"%s\">%s</a>\n", url.String(), htmlReplacer.Replace(name))
123 fmt.Fprintf(w, "</pre>\n")
126 // ServeContent replies to the request using the content in the
127 // provided ReadSeeker. The main benefit of ServeContent over io.Copy
128 // is that it handles Range requests properly, sets the MIME type, and
129 // handles If-Match, If-Unmodified-Since, If-None-Match, If-Modified-Since,
130 // and If-Range requests.
132 // If the response's Content-Type header is not set, ServeContent
133 // first tries to deduce the type from name's file extension and,
134 // if that fails, falls back to reading the first block of the content
135 // and passing it to DetectContentType.
136 // The name is otherwise unused; in particular it can be empty and is
137 // never sent in the response.
139 // If modtime is not the zero time or Unix epoch, ServeContent
140 // includes it in a Last-Modified header in the response. If the
141 // request includes an If-Modified-Since header, ServeContent uses
142 // modtime to decide whether the content needs to be sent at all.
144 // The content's Seek method must work: ServeContent uses
145 // a seek to the end of the content to determine its size.
147 // If the caller has set w's ETag header formatted per RFC 7232, section 2.3,
148 // ServeContent uses it to handle requests using If-Match, If-None-Match, or If-Range.
150 // Note that *os.File implements the io.ReadSeeker interface.
151 func ServeContent(w ResponseWriter, req *Request, name string, modtime time.Time, content io.ReadSeeker) {
152 sizeFunc := func() (int64, error) {
153 size, err := content.Seek(0, io.SeekEnd)
157 _, err = content.Seek(0, io.SeekStart)
163 serveContent(w, req, name, modtime, sizeFunc, content)
166 // errSeeker is returned by ServeContent's sizeFunc when the content
167 // doesn't seek properly. The underlying Seeker's error text isn't
168 // included in the sizeFunc reply so it's not sent over HTTP to end
170 var errSeeker = errors.New("seeker can't seek")
172 // errNoOverlap is returned by serveContent's parseRange if first-byte-pos of
173 // all of the byte-range-spec values is greater than the content size.
174 var errNoOverlap = errors.New("invalid range: failed to overlap")
176 // if name is empty, filename is unknown. (used for mime type, before sniffing)
177 // if modtime.IsZero(), modtime is unknown.
178 // content must be seeked to the beginning of the file.
179 // The sizeFunc is called at most once. Its error, if any, is sent in the HTTP response.
180 func serveContent(w ResponseWriter, r *Request, name string, modtime time.Time, sizeFunc func() (int64, error), content io.ReadSeeker) {
181 setLastModified(w, modtime)
182 done, rangeReq := checkPreconditions(w, r, modtime)
189 // If Content-Type isn't set, use the file's extension to find it, but
190 // if the Content-Type is unset explicitly, do not sniff the type.
191 ctypes, haveType := w.Header()["Content-Type"]
194 ctype = mime.TypeByExtension(filepath.Ext(name))
196 // read a chunk to decide between utf-8 text and binary
197 var buf [sniffLen]byte
198 n, _ := io.ReadFull(content, buf[:])
199 ctype = DetectContentType(buf[:n])
200 _, err := content.Seek(0, io.SeekStart) // rewind to output whole file
202 Error(w, "seeker can't seek", StatusInternalServerError)
206 w.Header().Set("Content-Type", ctype)
207 } else if len(ctypes) > 0 {
211 size, err := sizeFunc()
213 Error(w, err.Error(), StatusInternalServerError)
217 // handle Content-Range header.
219 var sendContent io.Reader = content
221 ranges, err := parseRange(rangeReq, size)
223 if err == errNoOverlap {
224 w.Header().Set("Content-Range", fmt.Sprintf("bytes */%d", size))
226 Error(w, err.Error(), StatusRequestedRangeNotSatisfiable)
229 if sumRangesSize(ranges) > size {
230 // The total number of bytes in all the ranges
231 // is larger than the size of the file by
232 // itself, so this is probably an attack, or a
233 // dumb client. Ignore the range request.
237 case len(ranges) == 1:
238 // RFC 7233, Section 4.1:
239 // "If a single part is being transferred, the server
240 // generating the 206 response MUST generate a
241 // Content-Range header field, describing what range
242 // of the selected representation is enclosed, and a
243 // payload consisting of the range.
245 // A server MUST NOT generate a multipart response to
246 // a request for a single range, since a client that
247 // does not request multiple parts might not support
248 // multipart responses."
250 if _, err := content.Seek(ra.start, io.SeekStart); err != nil {
251 Error(w, err.Error(), StatusRequestedRangeNotSatisfiable)
255 code = StatusPartialContent
256 w.Header().Set("Content-Range", ra.contentRange(size))
257 case len(ranges) > 1:
258 sendSize = rangesMIMESize(ranges, ctype, size)
259 code = StatusPartialContent
262 mw := multipart.NewWriter(pw)
263 w.Header().Set("Content-Type", "multipart/byteranges; boundary="+mw.Boundary())
265 defer pr.Close() // cause writing goroutine to fail and exit if CopyN doesn't finish.
267 for _, ra := range ranges {
268 part, err := mw.CreatePart(ra.mimeHeader(ctype, size))
270 pw.CloseWithError(err)
273 if _, err := content.Seek(ra.start, io.SeekStart); err != nil {
274 pw.CloseWithError(err)
277 if _, err := io.CopyN(part, content, ra.length); err != nil {
278 pw.CloseWithError(err)
287 w.Header().Set("Accept-Ranges", "bytes")
288 if w.Header().Get("Content-Encoding") == "" {
289 w.Header().Set("Content-Length", strconv.FormatInt(sendSize, 10))
295 if r.Method != "HEAD" {
296 io.CopyN(w, sendContent, sendSize)
300 // scanETag determines if a syntactically valid ETag is present at s. If so,
301 // the ETag and remaining text after consuming ETag is returned. Otherwise,
302 // it returns "", "".
303 func scanETag(s string) (etag string, remain string) {
304 s = textproto.TrimString(s)
306 if strings.HasPrefix(s, "W/") {
309 if len(s[start:]) < 2 || s[start] != '"' {
312 // ETag is either W/"text" or "text".
314 for i := start + 1; i < len(s); i++ {
317 // Character values allowed in ETags.
318 case c == 0x21 || c >= 0x23 && c <= 0x7E || c >= 0x80:
320 return s[:i+1], s[i+1:]
328 // etagStrongMatch reports whether a and b match using strong ETag comparison.
329 // Assumes a and b are valid ETags.
330 func etagStrongMatch(a, b string) bool {
331 return a == b && a != "" && a[0] == '"'
334 // etagWeakMatch reports whether a and b match using weak ETag comparison.
335 // Assumes a and b are valid ETags.
336 func etagWeakMatch(a, b string) bool {
337 return strings.TrimPrefix(a, "W/") == strings.TrimPrefix(b, "W/")
340 // condResult is the result of an HTTP request precondition check.
341 // See https://tools.ietf.org/html/rfc7232 section 3.
345 condNone condResult = iota
350 func checkIfMatch(w ResponseWriter, r *Request) condResult {
351 im := r.Header.Get("If-Match")
356 im = textproto.TrimString(im)
367 etag, remain := scanETag(im)
371 if etagStrongMatch(etag, w.Header().get("Etag")) {
380 func checkIfUnmodifiedSince(r *Request, modtime time.Time) condResult {
381 ius := r.Header.Get("If-Unmodified-Since")
382 if ius == "" || isZeroTime(modtime) {
385 if t, err := ParseTime(ius); err == nil {
386 // The Date-Modified header truncates sub-second precision, so
387 // use mtime < t+1s instead of mtime <= t to check for unmodified.
388 if modtime.Before(t.Add(1 * time.Second)) {
396 func checkIfNoneMatch(w ResponseWriter, r *Request) condResult {
397 inm := r.Header.get("If-None-Match")
403 buf = textproto.TrimString(buf)
413 etag, remain := scanETag(buf)
417 if etagWeakMatch(etag, w.Header().get("Etag")) {
425 func checkIfModifiedSince(r *Request, modtime time.Time) condResult {
426 if r.Method != "GET" && r.Method != "HEAD" {
429 ims := r.Header.Get("If-Modified-Since")
430 if ims == "" || isZeroTime(modtime) {
433 t, err := ParseTime(ims)
437 // The Date-Modified header truncates sub-second precision, so
438 // use mtime < t+1s instead of mtime <= t to check for unmodified.
439 if modtime.Before(t.Add(1 * time.Second)) {
445 func checkIfRange(w ResponseWriter, r *Request, modtime time.Time) condResult {
446 if r.Method != "GET" && r.Method != "HEAD" {
449 ir := r.Header.get("If-Range")
453 etag, _ := scanETag(ir)
455 if etagStrongMatch(etag, w.Header().Get("Etag")) {
461 // The If-Range value is typically the ETag value, but it may also be
462 // the modtime date. See golang.org/issue/8367.
463 if modtime.IsZero() {
466 t, err := ParseTime(ir)
470 if t.Unix() == modtime.Unix() {
476 var unixEpochTime = time.Unix(0, 0)
478 // isZeroTime reports whether t is obviously unspecified (either zero or Unix()=0).
479 func isZeroTime(t time.Time) bool {
480 return t.IsZero() || t.Equal(unixEpochTime)
483 func setLastModified(w ResponseWriter, modtime time.Time) {
484 if !isZeroTime(modtime) {
485 w.Header().Set("Last-Modified", modtime.UTC().Format(TimeFormat))
489 func writeNotModified(w ResponseWriter) {
490 // RFC 7232 section 4.1:
491 // a sender SHOULD NOT generate representation metadata other than the
492 // above listed fields unless said metadata exists for the purpose of
493 // guiding cache updates (e.g., Last-Modified might be useful if the
494 // response does not have an ETag field).
496 delete(h, "Content-Type")
497 delete(h, "Content-Length")
498 if h.Get("Etag") != "" {
499 delete(h, "Last-Modified")
501 w.WriteHeader(StatusNotModified)
504 // checkPreconditions evaluates request preconditions and reports whether a precondition
505 // resulted in sending StatusNotModified or StatusPreconditionFailed.
506 func checkPreconditions(w ResponseWriter, r *Request, modtime time.Time) (done bool, rangeHeader string) {
507 // This function carefully follows RFC 7232 section 6.
508 ch := checkIfMatch(w, r)
510 ch = checkIfUnmodifiedSince(r, modtime)
513 w.WriteHeader(StatusPreconditionFailed)
516 switch checkIfNoneMatch(w, r) {
518 if r.Method == "GET" || r.Method == "HEAD" {
522 w.WriteHeader(StatusPreconditionFailed)
526 if checkIfModifiedSince(r, modtime) == condFalse {
532 rangeHeader = r.Header.get("Range")
533 if rangeHeader != "" && checkIfRange(w, r, modtime) == condFalse {
536 return false, rangeHeader
539 // name is '/'-separated, not filepath.Separator.
540 func serveFile(w ResponseWriter, r *Request, fs FileSystem, name string, redirect bool) {
541 const indexPage = "/index.html"
543 // redirect .../index.html to .../
544 // can't use Redirect() because that would make the path absolute,
545 // which would be a problem running under StripPrefix
546 if strings.HasSuffix(r.URL.Path, indexPage) {
547 localRedirect(w, r, "./")
551 f, err := fs.Open(name)
553 msg, code := toHTTPError(err)
561 msg, code := toHTTPError(err)
567 // redirect to canonical path: / at end of directory url
568 // r.URL.Path always begins with /
571 if url[len(url)-1] != '/' {
572 localRedirect(w, r, path.Base(url)+"/")
576 if url[len(url)-1] == '/' {
577 localRedirect(w, r, "../"+path.Base(url))
583 // redirect if the directory name doesn't end in a slash
586 if url[len(url)-1] != '/' {
587 localRedirect(w, r, path.Base(url)+"/")
592 // use contents of index.html for directory, if present
594 index := strings.TrimSuffix(name, "/") + indexPage
595 ff, err := fs.Open(index)
607 // Still a directory? (we didn't find an index.html file)
609 if checkIfModifiedSince(r, d.ModTime()) == condFalse {
613 w.Header().Set("Last-Modified", d.ModTime().UTC().Format(TimeFormat))
618 // serveContent will check modification time
619 sizeFunc := func() (int64, error) { return d.Size(), nil }
620 serveContent(w, r, d.Name(), d.ModTime(), sizeFunc, f)
623 // toHTTPError returns a non-specific HTTP error message and status code
624 // for a given non-nil error value. It's important that toHTTPError does not
625 // actually return err.Error(), since msg and httpStatus are returned to users,
626 // and historically Go's ServeContent always returned just "404 Not Found" for
627 // all errors. We don't want to start leaking information in error messages.
628 func toHTTPError(err error) (msg string, httpStatus int) {
629 if os.IsNotExist(err) {
630 return "404 page not found", StatusNotFound
632 if os.IsPermission(err) {
633 return "403 Forbidden", StatusForbidden
636 return "500 Internal Server Error", StatusInternalServerError
639 // localRedirect gives a Moved Permanently response.
640 // It does not convert relative paths to absolute paths like Redirect does.
641 func localRedirect(w ResponseWriter, r *Request, newPath string) {
642 if q := r.URL.RawQuery; q != "" {
645 w.Header().Set("Location", newPath)
646 w.WriteHeader(StatusMovedPermanently)
649 // ServeFile replies to the request with the contents of the named
650 // file or directory.
652 // If the provided file or directory name is a relative path, it is
653 // interpreted relative to the current directory and may ascend to
654 // parent directories. If the provided name is constructed from user
655 // input, it should be sanitized before calling ServeFile.
657 // As a precaution, ServeFile will reject requests where r.URL.Path
658 // contains a ".." path element; this protects against callers who
659 // might unsafely use filepath.Join on r.URL.Path without sanitizing
660 // it and then use that filepath.Join result as the name argument.
662 // As another special case, ServeFile redirects any request where r.URL.Path
663 // ends in "/index.html" to the same path, without the final
664 // "index.html". To avoid such redirects either modify the path or
667 // Outside of those two special cases, ServeFile does not use
668 // r.URL.Path for selecting the file or directory to serve; only the
669 // file or directory provided in the name argument is used.
670 func ServeFile(w ResponseWriter, r *Request, name string) {
671 if containsDotDot(r.URL.Path) {
672 // Too many programs use r.URL.Path to construct the argument to
673 // serveFile. Reject the request under the assumption that happened
674 // here and ".." may not be wanted.
675 // Note that name might not contain "..", for example if code (still
676 // incorrectly) used filepath.Join(myDir, r.URL.Path).
677 Error(w, "invalid URL path", StatusBadRequest)
680 dir, file := filepath.Split(name)
681 serveFile(w, r, Dir(dir), file, false)
684 func containsDotDot(v string) bool {
685 if !strings.Contains(v, "..") {
688 for _, ent := range strings.FieldsFunc(v, isSlashRune) {
696 func isSlashRune(r rune) bool { return r == '/' || r == '\\' }
698 type fileHandler struct {
702 // FileServer returns a handler that serves HTTP requests
703 // with the contents of the file system rooted at root.
705 // To use the operating system's file system implementation,
708 // http.Handle("/", http.FileServer(http.Dir("/tmp")))
710 // As a special case, the returned file server redirects any request
711 // ending in "/index.html" to the same path, without the final
713 func FileServer(root FileSystem) Handler {
714 return &fileHandler{root}
717 func (f *fileHandler) ServeHTTP(w ResponseWriter, r *Request) {
719 if !strings.HasPrefix(upath, "/") {
723 serveFile(w, r, f.root, path.Clean(upath), true)
726 // httpRange specifies the byte range to be sent to the client.
727 type httpRange struct {
731 func (r httpRange) contentRange(size int64) string {
732 return fmt.Sprintf("bytes %d-%d/%d", r.start, r.start+r.length-1, size)
735 func (r httpRange) mimeHeader(contentType string, size int64) textproto.MIMEHeader {
736 return textproto.MIMEHeader{
737 "Content-Range": {r.contentRange(size)},
738 "Content-Type": {contentType},
742 // parseRange parses a Range header string as per RFC 7233.
743 // errNoOverlap is returned if none of the ranges overlap.
744 func parseRange(s string, size int64) ([]httpRange, error) {
746 return nil, nil // header not present
749 if !strings.HasPrefix(s, b) {
750 return nil, errors.New("invalid range")
752 var ranges []httpRange
754 for _, ra := range strings.Split(s[len(b):], ",") {
755 ra = strings.TrimSpace(ra)
759 i := strings.Index(ra, "-")
761 return nil, errors.New("invalid range")
763 start, end := strings.TrimSpace(ra[:i]), strings.TrimSpace(ra[i+1:])
766 // If no start is specified, end specifies the
767 // range start relative to the end of the file.
768 i, err := strconv.ParseInt(end, 10, 64)
770 return nil, errors.New("invalid range")
776 r.length = size - r.start
778 i, err := strconv.ParseInt(start, 10, 64)
779 if err != nil || i < 0 {
780 return nil, errors.New("invalid range")
783 // If the range begins after the size of the content,
784 // then it does not overlap.
790 // If no end is specified, range extends to end of the file.
791 r.length = size - r.start
793 i, err := strconv.ParseInt(end, 10, 64)
794 if err != nil || r.start > i {
795 return nil, errors.New("invalid range")
800 r.length = i - r.start + 1
803 ranges = append(ranges, r)
805 if noOverlap && len(ranges) == 0 {
806 // The specified ranges did not overlap with the content.
807 return nil, errNoOverlap
812 // countingWriter counts how many bytes have been written to it.
813 type countingWriter int64
815 func (w *countingWriter) Write(p []byte) (n int, err error) {
816 *w += countingWriter(len(p))
820 // rangesMIMESize returns the number of bytes it takes to encode the
821 // provided ranges as a multipart response.
822 func rangesMIMESize(ranges []httpRange, contentType string, contentSize int64) (encSize int64) {
824 mw := multipart.NewWriter(&w)
825 for _, ra := range ranges {
826 mw.CreatePart(ra.mimeHeader(contentType, contentSize))
834 func sumRangesSize(ranges []httpRange) (size int64) {
835 for _, ra := range ranges {