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 could expose sensitive files and directories. Dir will follow
34 // symlinks pointing out of the directory tree, which can be especially dangerous
35 // if serving from a directory in which users are able to create arbitrary symlinks.
36 // Dir will also allow access to files and directories starting with a period,
37 // which could expose sensitive directories like .git or sensitive files like
38 // .htpasswd. To exclude files with a leading period, remove the files/directories
39 // from the server or create a custom FileSystem implementation.
41 // An empty Dir is treated as ".".
44 // mapDirOpenError maps the provided non-nil error from opening name
45 // to a possibly better non-nil error. In particular, it turns OS-specific errors
46 // about opening files in non-directories into os.ErrNotExist. See Issue 18984.
47 func mapDirOpenError(originalErr error, name string) error {
48 if os.IsNotExist(originalErr) || os.IsPermission(originalErr) {
52 parts := strings.Split(name, string(filepath.Separator))
53 for i := range parts {
57 fi, err := os.Stat(strings.Join(parts[:i+1], string(filepath.Separator)))
68 // Open implements FileSystem using os.Open, opening files for reading rooted
69 // and relative to the directory d.
70 func (d Dir) Open(name string) (File, error) {
71 if filepath.Separator != '/' && strings.ContainsRune(name, filepath.Separator) {
72 return nil, errors.New("http: invalid character in file path")
78 fullName := filepath.Join(dir, filepath.FromSlash(path.Clean("/"+name)))
79 f, err := os.Open(fullName)
81 return nil, mapDirOpenError(err, fullName)
86 // A FileSystem implements access to a collection of named files.
87 // The elements in a file path are separated by slash ('/', U+002F)
88 // characters, regardless of host operating system convention.
89 type FileSystem interface {
90 Open(name string) (File, error)
93 // A File is returned by a FileSystem's Open method and can be
94 // served by the FileServer implementation.
96 // The methods should behave the same as those on an *os.File.
101 Readdir(count int) ([]os.FileInfo, error)
102 Stat() (os.FileInfo, error)
105 func dirList(w ResponseWriter, r *Request, f File) {
106 dirs, err := f.Readdir(-1)
108 logf(r, "http: error reading directory: %v", err)
109 Error(w, "Error reading directory", StatusInternalServerError)
112 sort.Slice(dirs, func(i, j int) bool { return dirs[i].Name() < dirs[j].Name() })
114 w.Header().Set("Content-Type", "text/html; charset=utf-8")
115 fmt.Fprintf(w, "<pre>\n")
116 for _, d := range dirs {
121 // name may contain '?' or '#', which must be escaped to remain
122 // part of the URL path, and not indicate the start of a query
123 // string or fragment.
124 url := url.URL{Path: name}
125 fmt.Fprintf(w, "<a href=\"%s\">%s</a>\n", url.String(), htmlReplacer.Replace(name))
127 fmt.Fprintf(w, "</pre>\n")
130 // ServeContent replies to the request using the content in the
131 // provided ReadSeeker. The main benefit of ServeContent over io.Copy
132 // is that it handles Range requests properly, sets the MIME type, and
133 // handles If-Match, If-Unmodified-Since, If-None-Match, If-Modified-Since,
134 // and If-Range requests.
136 // If the response's Content-Type header is not set, ServeContent
137 // first tries to deduce the type from name's file extension and,
138 // if that fails, falls back to reading the first block of the content
139 // and passing it to DetectContentType.
140 // The name is otherwise unused; in particular it can be empty and is
141 // never sent in the response.
143 // If modtime is not the zero time or Unix epoch, ServeContent
144 // includes it in a Last-Modified header in the response. If the
145 // request includes an If-Modified-Since header, ServeContent uses
146 // modtime to decide whether the content needs to be sent at all.
148 // The content's Seek method must work: ServeContent uses
149 // a seek to the end of the content to determine its size.
151 // If the caller has set w's ETag header formatted per RFC 7232, section 2.3,
152 // ServeContent uses it to handle requests using If-Match, If-None-Match, or If-Range.
154 // Note that *os.File implements the io.ReadSeeker interface.
155 func ServeContent(w ResponseWriter, req *Request, name string, modtime time.Time, content io.ReadSeeker) {
156 sizeFunc := func() (int64, error) {
157 size, err := content.Seek(0, io.SeekEnd)
161 _, err = content.Seek(0, io.SeekStart)
167 serveContent(w, req, name, modtime, sizeFunc, content)
170 // errSeeker is returned by ServeContent's sizeFunc when the content
171 // doesn't seek properly. The underlying Seeker's error text isn't
172 // included in the sizeFunc reply so it's not sent over HTTP to end
174 var errSeeker = errors.New("seeker can't seek")
176 // errNoOverlap is returned by serveContent's parseRange if first-byte-pos of
177 // all of the byte-range-spec values is greater than the content size.
178 var errNoOverlap = errors.New("invalid range: failed to overlap")
180 // if name is empty, filename is unknown. (used for mime type, before sniffing)
181 // if modtime.IsZero(), modtime is unknown.
182 // content must be seeked to the beginning of the file.
183 // The sizeFunc is called at most once. Its error, if any, is sent in the HTTP response.
184 func serveContent(w ResponseWriter, r *Request, name string, modtime time.Time, sizeFunc func() (int64, error), content io.ReadSeeker) {
185 setLastModified(w, modtime)
186 done, rangeReq := checkPreconditions(w, r, modtime)
193 // If Content-Type isn't set, use the file's extension to find it, but
194 // if the Content-Type is unset explicitly, do not sniff the type.
195 ctypes, haveType := w.Header()["Content-Type"]
198 ctype = mime.TypeByExtension(filepath.Ext(name))
200 // read a chunk to decide between utf-8 text and binary
201 var buf [sniffLen]byte
202 n, _ := io.ReadFull(content, buf[:])
203 ctype = DetectContentType(buf[:n])
204 _, err := content.Seek(0, io.SeekStart) // rewind to output whole file
206 Error(w, "seeker can't seek", StatusInternalServerError)
210 w.Header().Set("Content-Type", ctype)
211 } else if len(ctypes) > 0 {
215 size, err := sizeFunc()
217 Error(w, err.Error(), StatusInternalServerError)
221 // handle Content-Range header.
223 var sendContent io.Reader = content
225 ranges, err := parseRange(rangeReq, size)
227 if err == errNoOverlap {
228 w.Header().Set("Content-Range", fmt.Sprintf("bytes */%d", size))
230 Error(w, err.Error(), StatusRequestedRangeNotSatisfiable)
233 if sumRangesSize(ranges) > size {
234 // The total number of bytes in all the ranges
235 // is larger than the size of the file by
236 // itself, so this is probably an attack, or a
237 // dumb client. Ignore the range request.
241 case len(ranges) == 1:
242 // RFC 7233, Section 4.1:
243 // "If a single part is being transferred, the server
244 // generating the 206 response MUST generate a
245 // Content-Range header field, describing what range
246 // of the selected representation is enclosed, and a
247 // payload consisting of the range.
249 // A server MUST NOT generate a multipart response to
250 // a request for a single range, since a client that
251 // does not request multiple parts might not support
252 // multipart responses."
254 if _, err := content.Seek(ra.start, io.SeekStart); err != nil {
255 Error(w, err.Error(), StatusRequestedRangeNotSatisfiable)
259 code = StatusPartialContent
260 w.Header().Set("Content-Range", ra.contentRange(size))
261 case len(ranges) > 1:
262 sendSize = rangesMIMESize(ranges, ctype, size)
263 code = StatusPartialContent
266 mw := multipart.NewWriter(pw)
267 w.Header().Set("Content-Type", "multipart/byteranges; boundary="+mw.Boundary())
269 defer pr.Close() // cause writing goroutine to fail and exit if CopyN doesn't finish.
271 for _, ra := range ranges {
272 part, err := mw.CreatePart(ra.mimeHeader(ctype, size))
274 pw.CloseWithError(err)
277 if _, err := content.Seek(ra.start, io.SeekStart); err != nil {
278 pw.CloseWithError(err)
281 if _, err := io.CopyN(part, content, ra.length); err != nil {
282 pw.CloseWithError(err)
291 w.Header().Set("Accept-Ranges", "bytes")
292 if w.Header().Get("Content-Encoding") == "" {
293 w.Header().Set("Content-Length", strconv.FormatInt(sendSize, 10))
299 if r.Method != "HEAD" {
300 io.CopyN(w, sendContent, sendSize)
304 // scanETag determines if a syntactically valid ETag is present at s. If so,
305 // the ETag and remaining text after consuming ETag is returned. Otherwise,
306 // it returns "", "".
307 func scanETag(s string) (etag string, remain string) {
308 s = textproto.TrimString(s)
310 if strings.HasPrefix(s, "W/") {
313 if len(s[start:]) < 2 || s[start] != '"' {
316 // ETag is either W/"text" or "text".
318 for i := start + 1; i < len(s); i++ {
321 // Character values allowed in ETags.
322 case c == 0x21 || c >= 0x23 && c <= 0x7E || c >= 0x80:
324 return s[:i+1], s[i+1:]
332 // etagStrongMatch reports whether a and b match using strong ETag comparison.
333 // Assumes a and b are valid ETags.
334 func etagStrongMatch(a, b string) bool {
335 return a == b && a != "" && a[0] == '"'
338 // etagWeakMatch reports whether a and b match using weak ETag comparison.
339 // Assumes a and b are valid ETags.
340 func etagWeakMatch(a, b string) bool {
341 return strings.TrimPrefix(a, "W/") == strings.TrimPrefix(b, "W/")
344 // condResult is the result of an HTTP request precondition check.
345 // See https://tools.ietf.org/html/rfc7232 section 3.
349 condNone condResult = iota
354 func checkIfMatch(w ResponseWriter, r *Request) condResult {
355 im := r.Header.Get("If-Match")
360 im = textproto.TrimString(im)
371 etag, remain := scanETag(im)
375 if etagStrongMatch(etag, w.Header().get("Etag")) {
384 func checkIfUnmodifiedSince(r *Request, modtime time.Time) condResult {
385 ius := r.Header.Get("If-Unmodified-Since")
386 if ius == "" || isZeroTime(modtime) {
389 t, err := ParseTime(ius)
394 // The Last-Modified header truncates sub-second precision so
395 // the modtime needs to be truncated too.
396 modtime = modtime.Truncate(time.Second)
397 if modtime.Before(t) || modtime.Equal(t) {
403 func checkIfNoneMatch(w ResponseWriter, r *Request) condResult {
404 inm := r.Header.get("If-None-Match")
410 buf = textproto.TrimString(buf)
420 etag, remain := scanETag(buf)
424 if etagWeakMatch(etag, w.Header().get("Etag")) {
432 func checkIfModifiedSince(r *Request, modtime time.Time) condResult {
433 if r.Method != "GET" && r.Method != "HEAD" {
436 ims := r.Header.Get("If-Modified-Since")
437 if ims == "" || isZeroTime(modtime) {
440 t, err := ParseTime(ims)
444 // The Last-Modified header truncates sub-second precision so
445 // the modtime needs to be truncated too.
446 modtime = modtime.Truncate(time.Second)
447 if modtime.Before(t) || modtime.Equal(t) {
453 func checkIfRange(w ResponseWriter, r *Request, modtime time.Time) condResult {
454 if r.Method != "GET" && r.Method != "HEAD" {
457 ir := r.Header.get("If-Range")
461 etag, _ := scanETag(ir)
463 if etagStrongMatch(etag, w.Header().Get("Etag")) {
469 // The If-Range value is typically the ETag value, but it may also be
470 // the modtime date. See golang.org/issue/8367.
471 if modtime.IsZero() {
474 t, err := ParseTime(ir)
478 if t.Unix() == modtime.Unix() {
484 var unixEpochTime = time.Unix(0, 0)
486 // isZeroTime reports whether t is obviously unspecified (either zero or Unix()=0).
487 func isZeroTime(t time.Time) bool {
488 return t.IsZero() || t.Equal(unixEpochTime)
491 func setLastModified(w ResponseWriter, modtime time.Time) {
492 if !isZeroTime(modtime) {
493 w.Header().Set("Last-Modified", modtime.UTC().Format(TimeFormat))
497 func writeNotModified(w ResponseWriter) {
498 // RFC 7232 section 4.1:
499 // a sender SHOULD NOT generate representation metadata other than the
500 // above listed fields unless said metadata exists for the purpose of
501 // guiding cache updates (e.g., Last-Modified might be useful if the
502 // response does not have an ETag field).
504 delete(h, "Content-Type")
505 delete(h, "Content-Length")
506 if h.Get("Etag") != "" {
507 delete(h, "Last-Modified")
509 w.WriteHeader(StatusNotModified)
512 // checkPreconditions evaluates request preconditions and reports whether a precondition
513 // resulted in sending StatusNotModified or StatusPreconditionFailed.
514 func checkPreconditions(w ResponseWriter, r *Request, modtime time.Time) (done bool, rangeHeader string) {
515 // This function carefully follows RFC 7232 section 6.
516 ch := checkIfMatch(w, r)
518 ch = checkIfUnmodifiedSince(r, modtime)
521 w.WriteHeader(StatusPreconditionFailed)
524 switch checkIfNoneMatch(w, r) {
526 if r.Method == "GET" || r.Method == "HEAD" {
530 w.WriteHeader(StatusPreconditionFailed)
534 if checkIfModifiedSince(r, modtime) == condFalse {
540 rangeHeader = r.Header.get("Range")
541 if rangeHeader != "" && checkIfRange(w, r, modtime) == condFalse {
544 return false, rangeHeader
547 // name is '/'-separated, not filepath.Separator.
548 func serveFile(w ResponseWriter, r *Request, fs FileSystem, name string, redirect bool) {
549 const indexPage = "/index.html"
551 // redirect .../index.html to .../
552 // can't use Redirect() because that would make the path absolute,
553 // which would be a problem running under StripPrefix
554 if strings.HasSuffix(r.URL.Path, indexPage) {
555 localRedirect(w, r, "./")
559 f, err := fs.Open(name)
561 msg, code := toHTTPError(err)
569 msg, code := toHTTPError(err)
575 // redirect to canonical path: / at end of directory url
576 // r.URL.Path always begins with /
579 if url[len(url)-1] != '/' {
580 localRedirect(w, r, path.Base(url)+"/")
584 if url[len(url)-1] == '/' {
585 localRedirect(w, r, "../"+path.Base(url))
593 // redirect if the directory name doesn't end in a slash
594 if url == "" || url[len(url)-1] != '/' {
595 localRedirect(w, r, path.Base(url)+"/")
599 // use contents of index.html for directory, if present
600 index := strings.TrimSuffix(name, "/") + indexPage
601 ff, err := fs.Open(index)
613 // Still a directory? (we didn't find an index.html file)
615 if checkIfModifiedSince(r, d.ModTime()) == condFalse {
619 setLastModified(w, d.ModTime())
624 // serveContent will check modification time
625 sizeFunc := func() (int64, error) { return d.Size(), nil }
626 serveContent(w, r, d.Name(), d.ModTime(), sizeFunc, f)
629 // toHTTPError returns a non-specific HTTP error message and status code
630 // for a given non-nil error value. It's important that toHTTPError does not
631 // actually return err.Error(), since msg and httpStatus are returned to users,
632 // and historically Go's ServeContent always returned just "404 Not Found" for
633 // all errors. We don't want to start leaking information in error messages.
634 func toHTTPError(err error) (msg string, httpStatus int) {
635 if os.IsNotExist(err) {
636 return "404 page not found", StatusNotFound
638 if os.IsPermission(err) {
639 return "403 Forbidden", StatusForbidden
642 return "500 Internal Server Error", StatusInternalServerError
645 // localRedirect gives a Moved Permanently response.
646 // It does not convert relative paths to absolute paths like Redirect does.
647 func localRedirect(w ResponseWriter, r *Request, newPath string) {
648 if q := r.URL.RawQuery; q != "" {
651 w.Header().Set("Location", newPath)
652 w.WriteHeader(StatusMovedPermanently)
655 // ServeFile replies to the request with the contents of the named
656 // file or directory.
658 // If the provided file or directory name is a relative path, it is
659 // interpreted relative to the current directory and may ascend to
660 // parent directories. If the provided name is constructed from user
661 // input, it should be sanitized before calling ServeFile.
663 // As a precaution, ServeFile will reject requests where r.URL.Path
664 // contains a ".." path element; this protects against callers who
665 // might unsafely use filepath.Join on r.URL.Path without sanitizing
666 // it and then use that filepath.Join result as the name argument.
668 // As another special case, ServeFile redirects any request where r.URL.Path
669 // ends in "/index.html" to the same path, without the final
670 // "index.html". To avoid such redirects either modify the path or
673 // Outside of those two special cases, ServeFile does not use
674 // r.URL.Path for selecting the file or directory to serve; only the
675 // file or directory provided in the name argument is used.
676 func ServeFile(w ResponseWriter, r *Request, name string) {
677 if containsDotDot(r.URL.Path) {
678 // Too many programs use r.URL.Path to construct the argument to
679 // serveFile. Reject the request under the assumption that happened
680 // here and ".." may not be wanted.
681 // Note that name might not contain "..", for example if code (still
682 // incorrectly) used filepath.Join(myDir, r.URL.Path).
683 Error(w, "invalid URL path", StatusBadRequest)
686 dir, file := filepath.Split(name)
687 serveFile(w, r, Dir(dir), file, false)
690 func containsDotDot(v string) bool {
691 if !strings.Contains(v, "..") {
694 for _, ent := range strings.FieldsFunc(v, isSlashRune) {
702 func isSlashRune(r rune) bool { return r == '/' || r == '\\' }
704 type fileHandler struct {
708 // FileServer returns a handler that serves HTTP requests
709 // with the contents of the file system rooted at root.
711 // To use the operating system's file system implementation,
714 // http.Handle("/", http.FileServer(http.Dir("/tmp")))
716 // As a special case, the returned file server redirects any request
717 // ending in "/index.html" to the same path, without the final
719 func FileServer(root FileSystem) Handler {
720 return &fileHandler{root}
723 func (f *fileHandler) ServeHTTP(w ResponseWriter, r *Request) {
725 if !strings.HasPrefix(upath, "/") {
729 serveFile(w, r, f.root, path.Clean(upath), true)
732 // httpRange specifies the byte range to be sent to the client.
733 type httpRange struct {
737 func (r httpRange) contentRange(size int64) string {
738 return fmt.Sprintf("bytes %d-%d/%d", r.start, r.start+r.length-1, size)
741 func (r httpRange) mimeHeader(contentType string, size int64) textproto.MIMEHeader {
742 return textproto.MIMEHeader{
743 "Content-Range": {r.contentRange(size)},
744 "Content-Type": {contentType},
748 // parseRange parses a Range header string as per RFC 7233.
749 // errNoOverlap is returned if none of the ranges overlap.
750 func parseRange(s string, size int64) ([]httpRange, error) {
752 return nil, nil // header not present
755 if !strings.HasPrefix(s, b) {
756 return nil, errors.New("invalid range")
758 var ranges []httpRange
760 for _, ra := range strings.Split(s[len(b):], ",") {
761 ra = textproto.TrimString(ra)
765 i := strings.Index(ra, "-")
767 return nil, errors.New("invalid range")
769 start, end := textproto.TrimString(ra[:i]), textproto.TrimString(ra[i+1:])
772 // If no start is specified, end specifies the
773 // range start relative to the end of the file.
774 i, err := strconv.ParseInt(end, 10, 64)
776 return nil, errors.New("invalid range")
782 r.length = size - r.start
784 i, err := strconv.ParseInt(start, 10, 64)
785 if err != nil || i < 0 {
786 return nil, errors.New("invalid range")
789 // If the range begins after the size of the content,
790 // then it does not overlap.
796 // If no end is specified, range extends to end of the file.
797 r.length = size - r.start
799 i, err := strconv.ParseInt(end, 10, 64)
800 if err != nil || r.start > i {
801 return nil, errors.New("invalid range")
806 r.length = i - r.start + 1
809 ranges = append(ranges, r)
811 if noOverlap && len(ranges) == 0 {
812 // The specified ranges did not overlap with the content.
813 return nil, errNoOverlap
818 // countingWriter counts how many bytes have been written to it.
819 type countingWriter int64
821 func (w *countingWriter) Write(p []byte) (n int, err error) {
822 *w += countingWriter(len(p))
826 // rangesMIMESize returns the number of bytes it takes to encode the
827 // provided ranges as a multipart response.
828 func rangesMIMESize(ranges []httpRange, contentType string, contentSize int64) (encSize int64) {
830 mw := multipart.NewWriter(&w)
831 for _, ra := range ranges {
832 mw.CreatePart(ra.mimeHeader(contentType, contentSize))
840 func sumRangesSize(ranges []httpRange) (size int64) {
841 for _, ra := range ranges {