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 // Open implements FileSystem using os.Open, opening files for reading rooted
67 // and relative to the directory d.
68 func (d Dir) Open(name string) (File, error) {
69 if filepath.Separator != '/' && strings.ContainsRune(name, filepath.Separator) {
70 return nil, errors.New("http: invalid character in file path")
76 fullName := filepath.Join(dir, filepath.FromSlash(path.Clean("/"+name)))
77 f, err := os.Open(fullName)
79 return nil, mapDirOpenError(err, fullName)
84 // A FileSystem implements access to a collection of named files.
85 // The elements in a file path are separated by slash ('/', U+002F)
86 // characters, regardless of host operating system convention.
87 type FileSystem interface {
88 Open(name string) (File, error)
91 // A File is returned by a FileSystem's Open method and can be
92 // served by the FileServer implementation.
94 // The methods should behave the same as those on an *os.File.
99 Readdir(count int) ([]os.FileInfo, error)
100 Stat() (os.FileInfo, error)
103 func dirList(w ResponseWriter, r *Request, f File) {
104 dirs, err := f.Readdir(-1)
106 logf(r, "http: error reading directory: %v", err)
107 Error(w, "Error reading directory", StatusInternalServerError)
110 sort.Slice(dirs, func(i, j int) bool { return dirs[i].Name() < dirs[j].Name() })
112 w.Header().Set("Content-Type", "text/html; charset=utf-8")
113 fmt.Fprintf(w, "<pre>\n")
114 for _, d := range dirs {
119 // name may contain '?' or '#', which must be escaped to remain
120 // part of the URL path, and not indicate the start of a query
121 // string or fragment.
122 url := url.URL{Path: name}
123 fmt.Fprintf(w, "<a href=\"%s\">%s</a>\n", url.String(), htmlReplacer.Replace(name))
125 fmt.Fprintf(w, "</pre>\n")
128 // ServeContent replies to the request using the content in the
129 // provided ReadSeeker. The main benefit of ServeContent over io.Copy
130 // is that it handles Range requests properly, sets the MIME type, and
131 // handles If-Match, If-Unmodified-Since, If-None-Match, If-Modified-Since,
132 // and If-Range requests.
134 // If the response's Content-Type header is not set, ServeContent
135 // first tries to deduce the type from name's file extension and,
136 // if that fails, falls back to reading the first block of the content
137 // and passing it to DetectContentType.
138 // The name is otherwise unused; in particular it can be empty and is
139 // never sent in the response.
141 // If modtime is not the zero time or Unix epoch, ServeContent
142 // includes it in a Last-Modified header in the response. If the
143 // request includes an If-Modified-Since header, ServeContent uses
144 // modtime to decide whether the content needs to be sent at all.
146 // The content's Seek method must work: ServeContent uses
147 // a seek to the end of the content to determine its size.
149 // If the caller has set w's ETag header formatted per RFC 7232, section 2.3,
150 // ServeContent uses it to handle requests using If-Match, If-None-Match, or If-Range.
152 // Note that *os.File implements the io.ReadSeeker interface.
153 func ServeContent(w ResponseWriter, req *Request, name string, modtime time.Time, content io.ReadSeeker) {
154 sizeFunc := func() (int64, error) {
155 size, err := content.Seek(0, io.SeekEnd)
159 _, err = content.Seek(0, io.SeekStart)
165 serveContent(w, req, name, modtime, sizeFunc, content)
168 // errSeeker is returned by ServeContent's sizeFunc when the content
169 // doesn't seek properly. The underlying Seeker's error text isn't
170 // included in the sizeFunc reply so it's not sent over HTTP to end
172 var errSeeker = errors.New("seeker can't seek")
174 // errNoOverlap is returned by serveContent's parseRange if first-byte-pos of
175 // all of the byte-range-spec values is greater than the content size.
176 var errNoOverlap = errors.New("invalid range: failed to overlap")
178 // if name is empty, filename is unknown. (used for mime type, before sniffing)
179 // if modtime.IsZero(), modtime is unknown.
180 // content must be seeked to the beginning of the file.
181 // The sizeFunc is called at most once. Its error, if any, is sent in the HTTP response.
182 func serveContent(w ResponseWriter, r *Request, name string, modtime time.Time, sizeFunc func() (int64, error), content io.ReadSeeker) {
183 setLastModified(w, modtime)
184 done, rangeReq := checkPreconditions(w, r, modtime)
191 // If Content-Type isn't set, use the file's extension to find it, but
192 // if the Content-Type is unset explicitly, do not sniff the type.
193 ctypes, haveType := w.Header()["Content-Type"]
196 ctype = mime.TypeByExtension(filepath.Ext(name))
198 // read a chunk to decide between utf-8 text and binary
199 var buf [sniffLen]byte
200 n, _ := io.ReadFull(content, buf[:])
201 ctype = DetectContentType(buf[:n])
202 _, err := content.Seek(0, io.SeekStart) // rewind to output whole file
204 Error(w, "seeker can't seek", StatusInternalServerError)
208 w.Header().Set("Content-Type", ctype)
209 } else if len(ctypes) > 0 {
213 size, err := sizeFunc()
215 Error(w, err.Error(), StatusInternalServerError)
219 // handle Content-Range header.
221 var sendContent io.Reader = content
223 ranges, err := parseRange(rangeReq, size)
225 if err == errNoOverlap {
226 w.Header().Set("Content-Range", fmt.Sprintf("bytes */%d", size))
228 Error(w, err.Error(), StatusRequestedRangeNotSatisfiable)
231 if sumRangesSize(ranges) > size {
232 // The total number of bytes in all the ranges
233 // is larger than the size of the file by
234 // itself, so this is probably an attack, or a
235 // dumb client. Ignore the range request.
239 case len(ranges) == 1:
240 // RFC 7233, Section 4.1:
241 // "If a single part is being transferred, the server
242 // generating the 206 response MUST generate a
243 // Content-Range header field, describing what range
244 // of the selected representation is enclosed, and a
245 // payload consisting of the range.
247 // A server MUST NOT generate a multipart response to
248 // a request for a single range, since a client that
249 // does not request multiple parts might not support
250 // multipart responses."
252 if _, err := content.Seek(ra.start, io.SeekStart); err != nil {
253 Error(w, err.Error(), StatusRequestedRangeNotSatisfiable)
257 code = StatusPartialContent
258 w.Header().Set("Content-Range", ra.contentRange(size))
259 case len(ranges) > 1:
260 sendSize = rangesMIMESize(ranges, ctype, size)
261 code = StatusPartialContent
264 mw := multipart.NewWriter(pw)
265 w.Header().Set("Content-Type", "multipart/byteranges; boundary="+mw.Boundary())
267 defer pr.Close() // cause writing goroutine to fail and exit if CopyN doesn't finish.
269 for _, ra := range ranges {
270 part, err := mw.CreatePart(ra.mimeHeader(ctype, size))
272 pw.CloseWithError(err)
275 if _, err := content.Seek(ra.start, io.SeekStart); err != nil {
276 pw.CloseWithError(err)
279 if _, err := io.CopyN(part, content, ra.length); err != nil {
280 pw.CloseWithError(err)
289 w.Header().Set("Accept-Ranges", "bytes")
290 if w.Header().Get("Content-Encoding") == "" {
291 w.Header().Set("Content-Length", strconv.FormatInt(sendSize, 10))
297 if r.Method != "HEAD" {
298 io.CopyN(w, sendContent, sendSize)
302 // scanETag determines if a syntactically valid ETag is present at s. If so,
303 // the ETag and remaining text after consuming ETag is returned. Otherwise,
304 // it returns "", "".
305 func scanETag(s string) (etag string, remain string) {
306 s = textproto.TrimString(s)
308 if strings.HasPrefix(s, "W/") {
311 if len(s[start:]) < 2 || s[start] != '"' {
314 // ETag is either W/"text" or "text".
316 for i := start + 1; i < len(s); i++ {
319 // Character values allowed in ETags.
320 case c == 0x21 || c >= 0x23 && c <= 0x7E || c >= 0x80:
322 return s[:i+1], s[i+1:]
330 // etagStrongMatch reports whether a and b match using strong ETag comparison.
331 // Assumes a and b are valid ETags.
332 func etagStrongMatch(a, b string) bool {
333 return a == b && a != "" && a[0] == '"'
336 // etagWeakMatch reports whether a and b match using weak ETag comparison.
337 // Assumes a and b are valid ETags.
338 func etagWeakMatch(a, b string) bool {
339 return strings.TrimPrefix(a, "W/") == strings.TrimPrefix(b, "W/")
342 // condResult is the result of an HTTP request precondition check.
343 // See https://tools.ietf.org/html/rfc7232 section 3.
347 condNone condResult = iota
352 func checkIfMatch(w ResponseWriter, r *Request) condResult {
353 im := r.Header.Get("If-Match")
358 im = textproto.TrimString(im)
369 etag, remain := scanETag(im)
373 if etagStrongMatch(etag, w.Header().get("Etag")) {
382 func checkIfUnmodifiedSince(r *Request, modtime time.Time) condResult {
383 ius := r.Header.Get("If-Unmodified-Since")
384 if ius == "" || isZeroTime(modtime) {
387 if t, err := ParseTime(ius); err == nil {
388 // The Date-Modified header truncates sub-second precision, so
389 // use mtime < t+1s instead of mtime <= t to check for unmodified.
390 if modtime.Before(t.Add(1 * time.Second)) {
398 func checkIfNoneMatch(w ResponseWriter, r *Request) condResult {
399 inm := r.Header.get("If-None-Match")
405 buf = textproto.TrimString(buf)
415 etag, remain := scanETag(buf)
419 if etagWeakMatch(etag, w.Header().get("Etag")) {
427 func checkIfModifiedSince(r *Request, modtime time.Time) condResult {
428 if r.Method != "GET" && r.Method != "HEAD" {
431 ims := r.Header.Get("If-Modified-Since")
432 if ims == "" || isZeroTime(modtime) {
435 t, err := ParseTime(ims)
439 // The Date-Modified header truncates sub-second precision, so
440 // use mtime < t+1s instead of mtime <= t to check for unmodified.
441 if modtime.Before(t.Add(1 * time.Second)) {
447 func checkIfRange(w ResponseWriter, r *Request, modtime time.Time) condResult {
448 if r.Method != "GET" && r.Method != "HEAD" {
451 ir := r.Header.get("If-Range")
455 etag, _ := scanETag(ir)
457 if etagStrongMatch(etag, w.Header().Get("Etag")) {
463 // The If-Range value is typically the ETag value, but it may also be
464 // the modtime date. See golang.org/issue/8367.
465 if modtime.IsZero() {
468 t, err := ParseTime(ir)
472 if t.Unix() == modtime.Unix() {
478 var unixEpochTime = time.Unix(0, 0)
480 // isZeroTime reports whether t is obviously unspecified (either zero or Unix()=0).
481 func isZeroTime(t time.Time) bool {
482 return t.IsZero() || t.Equal(unixEpochTime)
485 func setLastModified(w ResponseWriter, modtime time.Time) {
486 if !isZeroTime(modtime) {
487 w.Header().Set("Last-Modified", modtime.UTC().Format(TimeFormat))
491 func writeNotModified(w ResponseWriter) {
492 // RFC 7232 section 4.1:
493 // a sender SHOULD NOT generate representation metadata other than the
494 // above listed fields unless said metadata exists for the purpose of
495 // guiding cache updates (e.g., Last-Modified might be useful if the
496 // response does not have an ETag field).
498 delete(h, "Content-Type")
499 delete(h, "Content-Length")
500 if h.Get("Etag") != "" {
501 delete(h, "Last-Modified")
503 w.WriteHeader(StatusNotModified)
506 // checkPreconditions evaluates request preconditions and reports whether a precondition
507 // resulted in sending StatusNotModified or StatusPreconditionFailed.
508 func checkPreconditions(w ResponseWriter, r *Request, modtime time.Time) (done bool, rangeHeader string) {
509 // This function carefully follows RFC 7232 section 6.
510 ch := checkIfMatch(w, r)
512 ch = checkIfUnmodifiedSince(r, modtime)
515 w.WriteHeader(StatusPreconditionFailed)
518 switch checkIfNoneMatch(w, r) {
520 if r.Method == "GET" || r.Method == "HEAD" {
524 w.WriteHeader(StatusPreconditionFailed)
528 if checkIfModifiedSince(r, modtime) == condFalse {
534 rangeHeader = r.Header.get("Range")
535 if rangeHeader != "" && checkIfRange(w, r, modtime) == condFalse {
538 return false, rangeHeader
541 // name is '/'-separated, not filepath.Separator.
542 func serveFile(w ResponseWriter, r *Request, fs FileSystem, name string, redirect bool) {
543 const indexPage = "/index.html"
545 // redirect .../index.html to .../
546 // can't use Redirect() because that would make the path absolute,
547 // which would be a problem running under StripPrefix
548 if strings.HasSuffix(r.URL.Path, indexPage) {
549 localRedirect(w, r, "./")
553 f, err := fs.Open(name)
555 msg, code := toHTTPError(err)
563 msg, code := toHTTPError(err)
569 // redirect to canonical path: / at end of directory url
570 // r.URL.Path always begins with /
573 if url[len(url)-1] != '/' {
574 localRedirect(w, r, path.Base(url)+"/")
578 if url[len(url)-1] == '/' {
579 localRedirect(w, r, "../"+path.Base(url))
585 // redirect if the directory name doesn't end in a slash
588 if url[len(url)-1] != '/' {
589 localRedirect(w, r, path.Base(url)+"/")
594 // use contents of index.html for directory, if present
596 index := strings.TrimSuffix(name, "/") + indexPage
597 ff, err := fs.Open(index)
609 // Still a directory? (we didn't find an index.html file)
611 if checkIfModifiedSince(r, d.ModTime()) == condFalse {
615 w.Header().Set("Last-Modified", d.ModTime().UTC().Format(TimeFormat))
620 // serveContent will check modification time
621 sizeFunc := func() (int64, error) { return d.Size(), nil }
622 serveContent(w, r, d.Name(), d.ModTime(), sizeFunc, f)
625 // toHTTPError returns a non-specific HTTP error message and status code
626 // for a given non-nil error value. It's important that toHTTPError does not
627 // actually return err.Error(), since msg and httpStatus are returned to users,
628 // and historically Go's ServeContent always returned just "404 Not Found" for
629 // all errors. We don't want to start leaking information in error messages.
630 func toHTTPError(err error) (msg string, httpStatus int) {
631 if os.IsNotExist(err) {
632 return "404 page not found", StatusNotFound
634 if os.IsPermission(err) {
635 return "403 Forbidden", StatusForbidden
638 return "500 Internal Server Error", StatusInternalServerError
641 // localRedirect gives a Moved Permanently response.
642 // It does not convert relative paths to absolute paths like Redirect does.
643 func localRedirect(w ResponseWriter, r *Request, newPath string) {
644 if q := r.URL.RawQuery; q != "" {
647 w.Header().Set("Location", newPath)
648 w.WriteHeader(StatusMovedPermanently)
651 // ServeFile replies to the request with the contents of the named
652 // file or directory.
654 // If the provided file or directory name is a relative path, it is
655 // interpreted relative to the current directory and may ascend to
656 // parent directories. If the provided name is constructed from user
657 // input, it should be sanitized before calling ServeFile.
659 // As a precaution, ServeFile will reject requests where r.URL.Path
660 // contains a ".." path element; this protects against callers who
661 // might unsafely use filepath.Join on r.URL.Path without sanitizing
662 // it and then use that filepath.Join result as the name argument.
664 // As another special case, ServeFile redirects any request where r.URL.Path
665 // ends in "/index.html" to the same path, without the final
666 // "index.html". To avoid such redirects either modify the path or
669 // Outside of those two special cases, ServeFile does not use
670 // r.URL.Path for selecting the file or directory to serve; only the
671 // file or directory provided in the name argument is used.
672 func ServeFile(w ResponseWriter, r *Request, name string) {
673 if containsDotDot(r.URL.Path) {
674 // Too many programs use r.URL.Path to construct the argument to
675 // serveFile. Reject the request under the assumption that happened
676 // here and ".." may not be wanted.
677 // Note that name might not contain "..", for example if code (still
678 // incorrectly) used filepath.Join(myDir, r.URL.Path).
679 Error(w, "invalid URL path", StatusBadRequest)
682 dir, file := filepath.Split(name)
683 serveFile(w, r, Dir(dir), file, false)
686 func containsDotDot(v string) bool {
687 if !strings.Contains(v, "..") {
690 for _, ent := range strings.FieldsFunc(v, isSlashRune) {
698 func isSlashRune(r rune) bool { return r == '/' || r == '\\' }
700 type fileHandler struct {
704 // FileServer returns a handler that serves HTTP requests
705 // with the contents of the file system rooted at root.
707 // To use the operating system's file system implementation,
710 // http.Handle("/", http.FileServer(http.Dir("/tmp")))
712 // As a special case, the returned file server redirects any request
713 // ending in "/index.html" to the same path, without the final
715 func FileServer(root FileSystem) Handler {
716 return &fileHandler{root}
719 func (f *fileHandler) ServeHTTP(w ResponseWriter, r *Request) {
721 if !strings.HasPrefix(upath, "/") {
725 serveFile(w, r, f.root, path.Clean(upath), true)
728 // httpRange specifies the byte range to be sent to the client.
729 type httpRange struct {
733 func (r httpRange) contentRange(size int64) string {
734 return fmt.Sprintf("bytes %d-%d/%d", r.start, r.start+r.length-1, size)
737 func (r httpRange) mimeHeader(contentType string, size int64) textproto.MIMEHeader {
738 return textproto.MIMEHeader{
739 "Content-Range": {r.contentRange(size)},
740 "Content-Type": {contentType},
744 // parseRange parses a Range header string as per RFC 7233.
745 // errNoOverlap is returned if none of the ranges overlap.
746 func parseRange(s string, size int64) ([]httpRange, error) {
748 return nil, nil // header not present
751 if !strings.HasPrefix(s, b) {
752 return nil, errors.New("invalid range")
754 var ranges []httpRange
756 for _, ra := range strings.Split(s[len(b):], ",") {
757 ra = strings.TrimSpace(ra)
761 i := strings.Index(ra, "-")
763 return nil, errors.New("invalid range")
765 start, end := strings.TrimSpace(ra[:i]), strings.TrimSpace(ra[i+1:])
768 // If no start is specified, end specifies the
769 // range start relative to the end of the file.
770 i, err := strconv.ParseInt(end, 10, 64)
772 return nil, errors.New("invalid range")
778 r.length = size - r.start
780 i, err := strconv.ParseInt(start, 10, 64)
781 if err != nil || i < 0 {
782 return nil, errors.New("invalid range")
785 // If the range begins after the size of the content,
786 // then it does not overlap.
792 // If no end is specified, range extends to end of the file.
793 r.length = size - r.start
795 i, err := strconv.ParseInt(end, 10, 64)
796 if err != nil || r.start > i {
797 return nil, errors.New("invalid range")
802 r.length = i - r.start + 1
805 ranges = append(ranges, r)
807 if noOverlap && len(ranges) == 0 {
808 // The specified ranges did not overlap with the content.
809 return nil, errNoOverlap
814 // countingWriter counts how many bytes have been written to it.
815 type countingWriter int64
817 func (w *countingWriter) Write(p []byte) (n int, err error) {
818 *w += countingWriter(len(p))
822 // rangesMIMESize returns the number of bytes it takes to encode the
823 // provided ranges as a multipart response.
824 func rangesMIMESize(ranges []httpRange, contentType string, contentSize int64) (encSize int64) {
826 mw := multipart.NewWriter(&w)
827 for _, ra := range ranges {
828 mw.CreatePart(ra.mimeHeader(contentType, contentSize))
836 func sumRangesSize(ranges []httpRange) (size int64) {
837 for _, ra := range ranges {