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 2616, Section 14.16:
239 // "When an HTTP message includes the content of a single
240 // range (for example, a response to a request for a
241 // single range, or to a request for a set of ranges
242 // that overlap without any holes), this content is
243 // transmitted with a Content-Range header, and a
244 // Content-Length header showing the number of bytes
245 // actually transferred.
247 // A response to a request for a single range MUST NOT
248 // be sent using the multipart/byteranges media type."
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 != "" {
534 if 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 parent
656 // directories. If the provided name is constructed from user input, it
657 // should be sanitized before calling ServeFile. As a precaution, ServeFile
658 // will reject requests where r.URL.Path contains a ".." path element.
660 // As a special case, ServeFile redirects any request where r.URL.Path
661 // ends in "/index.html" to the same path, without the final
662 // "index.html". To avoid such redirects either modify the path or
664 func ServeFile(w ResponseWriter, r *Request, name string) {
665 if containsDotDot(r.URL.Path) {
666 // Too many programs use r.URL.Path to construct the argument to
667 // serveFile. Reject the request under the assumption that happened
668 // here and ".." may not be wanted.
669 // Note that name might not contain "..", for example if code (still
670 // incorrectly) used filepath.Join(myDir, r.URL.Path).
671 Error(w, "invalid URL path", StatusBadRequest)
674 dir, file := filepath.Split(name)
675 serveFile(w, r, Dir(dir), file, false)
678 func containsDotDot(v string) bool {
679 if !strings.Contains(v, "..") {
682 for _, ent := range strings.FieldsFunc(v, isSlashRune) {
690 func isSlashRune(r rune) bool { return r == '/' || r == '\\' }
692 type fileHandler struct {
696 // FileServer returns a handler that serves HTTP requests
697 // with the contents of the file system rooted at root.
699 // To use the operating system's file system implementation,
702 // http.Handle("/", http.FileServer(http.Dir("/tmp")))
704 // As a special case, the returned file server redirects any request
705 // ending in "/index.html" to the same path, without the final
707 func FileServer(root FileSystem) Handler {
708 return &fileHandler{root}
711 func (f *fileHandler) ServeHTTP(w ResponseWriter, r *Request) {
713 if !strings.HasPrefix(upath, "/") {
717 serveFile(w, r, f.root, path.Clean(upath), true)
720 // httpRange specifies the byte range to be sent to the client.
721 type httpRange struct {
725 func (r httpRange) contentRange(size int64) string {
726 return fmt.Sprintf("bytes %d-%d/%d", r.start, r.start+r.length-1, size)
729 func (r httpRange) mimeHeader(contentType string, size int64) textproto.MIMEHeader {
730 return textproto.MIMEHeader{
731 "Content-Range": {r.contentRange(size)},
732 "Content-Type": {contentType},
736 // parseRange parses a Range header string as per RFC 2616.
737 // errNoOverlap is returned if none of the ranges overlap.
738 func parseRange(s string, size int64) ([]httpRange, error) {
740 return nil, nil // header not present
743 if !strings.HasPrefix(s, b) {
744 return nil, errors.New("invalid range")
746 var ranges []httpRange
748 for _, ra := range strings.Split(s[len(b):], ",") {
749 ra = strings.TrimSpace(ra)
753 i := strings.Index(ra, "-")
755 return nil, errors.New("invalid range")
757 start, end := strings.TrimSpace(ra[:i]), strings.TrimSpace(ra[i+1:])
760 // If no start is specified, end specifies the
761 // range start relative to the end of the file.
762 i, err := strconv.ParseInt(end, 10, 64)
764 return nil, errors.New("invalid range")
770 r.length = size - r.start
772 i, err := strconv.ParseInt(start, 10, 64)
773 if err != nil || i < 0 {
774 return nil, errors.New("invalid range")
777 // If the range begins after the size of the content,
778 // then it does not overlap.
784 // If no end is specified, range extends to end of the file.
785 r.length = size - r.start
787 i, err := strconv.ParseInt(end, 10, 64)
788 if err != nil || r.start > i {
789 return nil, errors.New("invalid range")
794 r.length = i - r.start + 1
797 ranges = append(ranges, r)
799 if noOverlap && len(ranges) == 0 {
800 // The specified ranges did not overlap with the content.
801 return nil, errNoOverlap
806 // countingWriter counts how many bytes have been written to it.
807 type countingWriter int64
809 func (w *countingWriter) Write(p []byte) (n int, err error) {
810 *w += countingWriter(len(p))
814 // rangesMIMESize returns the number of bytes it takes to encode the
815 // provided ranges as a multipart response.
816 func rangesMIMESize(ranges []httpRange, contentType string, contentSize int64) (encSize int64) {
818 mw := multipart.NewWriter(&w)
819 for _, ra := range ranges {
820 mw.CreatePart(ra.mimeHeader(contentType, contentSize))
828 func sumRangesSize(ranges []httpRange) (size int64) {
829 for _, ra := range ranges {