Source file src/net/http/fs.go

     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.
     4  
     5  // HTTP file system request handler
     6  
     7  package http
     8  
     9  import (
    10  	"errors"
    11  	"fmt"
    12  	"io"
    13  	"io/fs"
    14  	"mime"
    15  	"mime/multipart"
    16  	"net/textproto"
    17  	"net/url"
    18  	"os"
    19  	"path"
    20  	"path/filepath"
    21  	"sort"
    22  	"strconv"
    23  	"strings"
    24  	"time"
    25  )
    26  
    27  // A Dir implements [FileSystem] using the native file system restricted to a
    28  // specific directory tree.
    29  //
    30  // While the [FileSystem.Open] method takes '/'-separated paths, a Dir's string
    31  // value is a directory path on the native file system, not a URL, so it is separated
    32  // by [filepath.Separator], which isn't necessarily '/'.
    33  //
    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.
    41  //
    42  // An empty Dir is treated as ".".
    43  type Dir string
    44  
    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) {
    50  		return originalErr
    51  	}
    52  
    53  	parts := strings.Split(name, string(sep))
    54  	for i := range parts {
    55  		if parts[i] == "" {
    56  			continue
    57  		}
    58  		fi, err := stat(strings.Join(parts[:i+1], string(sep)))
    59  		if err != nil {
    60  			return originalErr
    61  		}
    62  		if !fi.IsDir() {
    63  			return fs.ErrNotExist
    64  		}
    65  	}
    66  	return originalErr
    67  }
    68  
    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  	path := path.Clean("/" + name)[1:]
    73  	if path == "" {
    74  		path = "."
    75  	}
    76  	path, err := filepath.Localize(path)
    77  	if err != nil {
    78  		return nil, errors.New("http: invalid or unsafe file path")
    79  	}
    80  	dir := string(d)
    81  	if dir == "" {
    82  		dir = "."
    83  	}
    84  	fullName := filepath.Join(dir, path)
    85  	f, err := os.Open(fullName)
    86  	if err != nil {
    87  		return nil, mapOpenError(err, fullName, filepath.Separator, os.Stat)
    88  	}
    89  	return f, nil
    90  }
    91  
    92  // A FileSystem implements access to a collection of named files.
    93  // The elements in a file path are separated by slash ('/', U+002F)
    94  // characters, regardless of host operating system convention.
    95  // See the [FileServer] function to convert a FileSystem to a [Handler].
    96  //
    97  // This interface predates the [fs.FS] interface, which can be used instead:
    98  // the [FS] adapter function converts an fs.FS to a FileSystem.
    99  type FileSystem interface {
   100  	Open(name string) (File, error)
   101  }
   102  
   103  // A File is returned by a [FileSystem]'s Open method and can be
   104  // served by the [FileServer] implementation.
   105  //
   106  // The methods should behave the same as those on an [*os.File].
   107  type File interface {
   108  	io.Closer
   109  	io.Reader
   110  	io.Seeker
   111  	Readdir(count int) ([]fs.FileInfo, error)
   112  	Stat() (fs.FileInfo, error)
   113  }
   114  
   115  type anyDirs interface {
   116  	len() int
   117  	name(i int) string
   118  	isDir(i int) bool
   119  }
   120  
   121  type fileInfoDirs []fs.FileInfo
   122  
   123  func (d fileInfoDirs) len() int          { return len(d) }
   124  func (d fileInfoDirs) isDir(i int) bool  { return d[i].IsDir() }
   125  func (d fileInfoDirs) name(i int) string { return d[i].Name() }
   126  
   127  type dirEntryDirs []fs.DirEntry
   128  
   129  func (d dirEntryDirs) len() int          { return len(d) }
   130  func (d dirEntryDirs) isDir(i int) bool  { return d[i].IsDir() }
   131  func (d dirEntryDirs) name(i int) string { return d[i].Name() }
   132  
   133  func dirList(w ResponseWriter, r *Request, f File) {
   134  	// Prefer to use ReadDir instead of Readdir,
   135  	// because the former doesn't require calling
   136  	// Stat on every entry of a directory on Unix.
   137  	var dirs anyDirs
   138  	var err error
   139  	if d, ok := f.(fs.ReadDirFile); ok {
   140  		var list dirEntryDirs
   141  		list, err = d.ReadDir(-1)
   142  		dirs = list
   143  	} else {
   144  		var list fileInfoDirs
   145  		list, err = f.Readdir(-1)
   146  		dirs = list
   147  	}
   148  
   149  	if err != nil {
   150  		logf(r, "http: error reading directory: %v", err)
   151  		Error(w, "Error reading directory", StatusInternalServerError)
   152  		return
   153  	}
   154  	sort.Slice(dirs, func(i, j int) bool { return dirs.name(i) < dirs.name(j) })
   155  
   156  	w.Header().Set("Content-Type", "text/html; charset=utf-8")
   157  	fmt.Fprintf(w, "<!doctype html>\n")
   158  	fmt.Fprintf(w, "<meta name=\"viewport\" content=\"width=device-width\">\n")
   159  	fmt.Fprintf(w, "<pre>\n")
   160  	for i, n := 0, dirs.len(); i < n; i++ {
   161  		name := dirs.name(i)
   162  		if dirs.isDir(i) {
   163  			name += "/"
   164  		}
   165  		// name may contain '?' or '#', which must be escaped to remain
   166  		// part of the URL path, and not indicate the start of a query
   167  		// string or fragment.
   168  		url := url.URL{Path: name}
   169  		fmt.Fprintf(w, "<a href=\"%s\">%s</a>\n", url.String(), htmlReplacer.Replace(name))
   170  	}
   171  	fmt.Fprintf(w, "</pre>\n")
   172  }
   173  
   174  // ServeContent replies to the request using the content in the
   175  // provided ReadSeeker. The main benefit of ServeContent over [io.Copy]
   176  // is that it handles Range requests properly, sets the MIME type, and
   177  // handles If-Match, If-Unmodified-Since, If-None-Match, If-Modified-Since,
   178  // and If-Range requests.
   179  //
   180  // If the response's Content-Type header is not set, ServeContent
   181  // first tries to deduce the type from name's file extension and,
   182  // if that fails, falls back to reading the first block of the content
   183  // and passing it to [DetectContentType].
   184  // The name is otherwise unused; in particular it can be empty and is
   185  // never sent in the response.
   186  //
   187  // If modtime is not the zero time or Unix epoch, ServeContent
   188  // includes it in a Last-Modified header in the response. If the
   189  // request includes an If-Modified-Since header, ServeContent uses
   190  // modtime to decide whether the content needs to be sent at all.
   191  //
   192  // The content's Seek method must work: ServeContent uses
   193  // a seek to the end of the content to determine its size.
   194  //
   195  // If the caller has set w's ETag header formatted per RFC 7232, section 2.3,
   196  // ServeContent uses it to handle requests using If-Match, If-None-Match, or If-Range.
   197  //
   198  // Note that [*os.File] implements the [io.ReadSeeker] interface.
   199  func ServeContent(w ResponseWriter, req *Request, name string, modtime time.Time, content io.ReadSeeker) {
   200  	sizeFunc := func() (int64, error) {
   201  		size, err := content.Seek(0, io.SeekEnd)
   202  		if err != nil {
   203  			return 0, errSeeker
   204  		}
   205  		_, err = content.Seek(0, io.SeekStart)
   206  		if err != nil {
   207  			return 0, errSeeker
   208  		}
   209  		return size, nil
   210  	}
   211  	serveContent(w, req, name, modtime, sizeFunc, content)
   212  }
   213  
   214  // errSeeker is returned by ServeContent's sizeFunc when the content
   215  // doesn't seek properly. The underlying Seeker's error text isn't
   216  // included in the sizeFunc reply so it's not sent over HTTP to end
   217  // users.
   218  var errSeeker = errors.New("seeker can't seek")
   219  
   220  // errNoOverlap is returned by serveContent's parseRange if first-byte-pos of
   221  // all of the byte-range-spec values is greater than the content size.
   222  var errNoOverlap = errors.New("invalid range: failed to overlap")
   223  
   224  // if name is empty, filename is unknown. (used for mime type, before sniffing)
   225  // if modtime.IsZero(), modtime is unknown.
   226  // content must be seeked to the beginning of the file.
   227  // The sizeFunc is called at most once. Its error, if any, is sent in the HTTP response.
   228  func serveContent(w ResponseWriter, r *Request, name string, modtime time.Time, sizeFunc func() (int64, error), content io.ReadSeeker) {
   229  	setLastModified(w, modtime)
   230  	done, rangeReq := checkPreconditions(w, r, modtime)
   231  	if done {
   232  		return
   233  	}
   234  
   235  	code := StatusOK
   236  
   237  	// If Content-Type isn't set, use the file's extension to find it, but
   238  	// if the Content-Type is unset explicitly, do not sniff the type.
   239  	ctypes, haveType := w.Header()["Content-Type"]
   240  	var ctype string
   241  	if !haveType {
   242  		ctype = mime.TypeByExtension(filepath.Ext(name))
   243  		if ctype == "" {
   244  			// read a chunk to decide between utf-8 text and binary
   245  			var buf [sniffLen]byte
   246  			n, _ := io.ReadFull(content, buf[:])
   247  			ctype = DetectContentType(buf[:n])
   248  			_, err := content.Seek(0, io.SeekStart) // rewind to output whole file
   249  			if err != nil {
   250  				Error(w, "seeker can't seek", StatusInternalServerError)
   251  				return
   252  			}
   253  		}
   254  		w.Header().Set("Content-Type", ctype)
   255  	} else if len(ctypes) > 0 {
   256  		ctype = ctypes[0]
   257  	}
   258  
   259  	size, err := sizeFunc()
   260  	if err != nil {
   261  		Error(w, err.Error(), StatusInternalServerError)
   262  		return
   263  	}
   264  	if size < 0 {
   265  		// Should never happen but just to be sure
   266  		Error(w, "negative content size computed", StatusInternalServerError)
   267  		return
   268  	}
   269  
   270  	// handle Content-Range header.
   271  	sendSize := size
   272  	var sendContent io.Reader = content
   273  	ranges, err := parseRange(rangeReq, size)
   274  	switch err {
   275  	case nil:
   276  	case errNoOverlap:
   277  		if size == 0 {
   278  			// Some clients add a Range header to all requests to
   279  			// limit the size of the response. If the file is empty,
   280  			// ignore the range header and respond with a 200 rather
   281  			// than a 416.
   282  			ranges = nil
   283  			break
   284  		}
   285  		w.Header().Set("Content-Range", fmt.Sprintf("bytes */%d", size))
   286  		fallthrough
   287  	default:
   288  		Error(w, err.Error(), StatusRequestedRangeNotSatisfiable)
   289  		return
   290  	}
   291  
   292  	if sumRangesSize(ranges) > size {
   293  		// The total number of bytes in all the ranges
   294  		// is larger than the size of the file by
   295  		// itself, so this is probably an attack, or a
   296  		// dumb client. Ignore the range request.
   297  		ranges = nil
   298  	}
   299  	switch {
   300  	case len(ranges) == 1:
   301  		// RFC 7233, Section 4.1:
   302  		// "If a single part is being transferred, the server
   303  		// generating the 206 response MUST generate a
   304  		// Content-Range header field, describing what range
   305  		// of the selected representation is enclosed, and a
   306  		// payload consisting of the range.
   307  		// ...
   308  		// A server MUST NOT generate a multipart response to
   309  		// a request for a single range, since a client that
   310  		// does not request multiple parts might not support
   311  		// multipart responses."
   312  		ra := ranges[0]
   313  		if _, err := content.Seek(ra.start, io.SeekStart); err != nil {
   314  			Error(w, err.Error(), StatusRequestedRangeNotSatisfiable)
   315  			return
   316  		}
   317  		sendSize = ra.length
   318  		code = StatusPartialContent
   319  		w.Header().Set("Content-Range", ra.contentRange(size))
   320  	case len(ranges) > 1:
   321  		sendSize = rangesMIMESize(ranges, ctype, size)
   322  		code = StatusPartialContent
   323  
   324  		pr, pw := io.Pipe()
   325  		mw := multipart.NewWriter(pw)
   326  		w.Header().Set("Content-Type", "multipart/byteranges; boundary="+mw.Boundary())
   327  		sendContent = pr
   328  		defer pr.Close() // cause writing goroutine to fail and exit if CopyN doesn't finish.
   329  		go func() {
   330  			for _, ra := range ranges {
   331  				part, err := mw.CreatePart(ra.mimeHeader(ctype, size))
   332  				if err != nil {
   333  					pw.CloseWithError(err)
   334  					return
   335  				}
   336  				if _, err := content.Seek(ra.start, io.SeekStart); err != nil {
   337  					pw.CloseWithError(err)
   338  					return
   339  				}
   340  				if _, err := io.CopyN(part, content, ra.length); err != nil {
   341  					pw.CloseWithError(err)
   342  					return
   343  				}
   344  			}
   345  			mw.Close()
   346  			pw.Close()
   347  		}()
   348  	}
   349  
   350  	w.Header().Set("Accept-Ranges", "bytes")
   351  
   352  	// We should be able to unconditionally set the Content-Length here.
   353  	//
   354  	// However, there is a pattern observed in the wild that this breaks:
   355  	// The user wraps the ResponseWriter in one which gzips data written to it,
   356  	// and sets "Content-Encoding: gzip".
   357  	//
   358  	// The user shouldn't be doing this; the serveContent path here depends
   359  	// on serving seekable data with a known length. If you want to compress
   360  	// on the fly, then you shouldn't be using ServeFile/ServeContent, or
   361  	// you should compress the entire file up-front and provide a seekable
   362  	// view of the compressed data.
   363  	//
   364  	// However, since we've observed this pattern in the wild, and since
   365  	// setting Content-Length here breaks code that mostly-works today,
   366  	// skip setting Content-Length if the user set Content-Encoding.
   367  	//
   368  	// If this is a range request, always set Content-Length.
   369  	// If the user isn't changing the bytes sent in the ResponseWrite,
   370  	// the Content-Length will be correct.
   371  	// If the user is changing the bytes sent, then the range request wasn't
   372  	// going to work properly anyway and we aren't worse off.
   373  	//
   374  	// A possible future improvement on this might be to look at the type
   375  	// of the ResponseWriter, and always set Content-Length if it's one
   376  	// that we recognize.
   377  	if len(ranges) > 0 || w.Header().Get("Content-Encoding") == "" {
   378  		w.Header().Set("Content-Length", strconv.FormatInt(sendSize, 10))
   379  	}
   380  	w.WriteHeader(code)
   381  
   382  	if r.Method != "HEAD" {
   383  		io.CopyN(w, sendContent, sendSize)
   384  	}
   385  }
   386  
   387  // scanETag determines if a syntactically valid ETag is present at s. If so,
   388  // the ETag and remaining text after consuming ETag is returned. Otherwise,
   389  // it returns "", "".
   390  func scanETag(s string) (etag string, remain string) {
   391  	s = textproto.TrimString(s)
   392  	start := 0
   393  	if strings.HasPrefix(s, "W/") {
   394  		start = 2
   395  	}
   396  	if len(s[start:]) < 2 || s[start] != '"' {
   397  		return "", ""
   398  	}
   399  	// ETag is either W/"text" or "text".
   400  	// See RFC 7232 2.3.
   401  	for i := start + 1; i < len(s); i++ {
   402  		c := s[i]
   403  		switch {
   404  		// Character values allowed in ETags.
   405  		case c == 0x21 || c >= 0x23 && c <= 0x7E || c >= 0x80:
   406  		case c == '"':
   407  			return s[:i+1], s[i+1:]
   408  		default:
   409  			return "", ""
   410  		}
   411  	}
   412  	return "", ""
   413  }
   414  
   415  // etagStrongMatch reports whether a and b match using strong ETag comparison.
   416  // Assumes a and b are valid ETags.
   417  func etagStrongMatch(a, b string) bool {
   418  	return a == b && a != "" && a[0] == '"'
   419  }
   420  
   421  // etagWeakMatch reports whether a and b match using weak ETag comparison.
   422  // Assumes a and b are valid ETags.
   423  func etagWeakMatch(a, b string) bool {
   424  	return strings.TrimPrefix(a, "W/") == strings.TrimPrefix(b, "W/")
   425  }
   426  
   427  // condResult is the result of an HTTP request precondition check.
   428  // See https://tools.ietf.org/html/rfc7232 section 3.
   429  type condResult int
   430  
   431  const (
   432  	condNone condResult = iota
   433  	condTrue
   434  	condFalse
   435  )
   436  
   437  func checkIfMatch(w ResponseWriter, r *Request) condResult {
   438  	im := r.Header.Get("If-Match")
   439  	if im == "" {
   440  		return condNone
   441  	}
   442  	for {
   443  		im = textproto.TrimString(im)
   444  		if len(im) == 0 {
   445  			break
   446  		}
   447  		if im[0] == ',' {
   448  			im = im[1:]
   449  			continue
   450  		}
   451  		if im[0] == '*' {
   452  			return condTrue
   453  		}
   454  		etag, remain := scanETag(im)
   455  		if etag == "" {
   456  			break
   457  		}
   458  		if etagStrongMatch(etag, w.Header().get("Etag")) {
   459  			return condTrue
   460  		}
   461  		im = remain
   462  	}
   463  
   464  	return condFalse
   465  }
   466  
   467  func checkIfUnmodifiedSince(r *Request, modtime time.Time) condResult {
   468  	ius := r.Header.Get("If-Unmodified-Since")
   469  	if ius == "" || isZeroTime(modtime) {
   470  		return condNone
   471  	}
   472  	t, err := ParseTime(ius)
   473  	if err != nil {
   474  		return condNone
   475  	}
   476  
   477  	// The Last-Modified header truncates sub-second precision so
   478  	// the modtime needs to be truncated too.
   479  	modtime = modtime.Truncate(time.Second)
   480  	if ret := modtime.Compare(t); ret <= 0 {
   481  		return condTrue
   482  	}
   483  	return condFalse
   484  }
   485  
   486  func checkIfNoneMatch(w ResponseWriter, r *Request) condResult {
   487  	inm := r.Header.get("If-None-Match")
   488  	if inm == "" {
   489  		return condNone
   490  	}
   491  	buf := inm
   492  	for {
   493  		buf = textproto.TrimString(buf)
   494  		if len(buf) == 0 {
   495  			break
   496  		}
   497  		if buf[0] == ',' {
   498  			buf = buf[1:]
   499  			continue
   500  		}
   501  		if buf[0] == '*' {
   502  			return condFalse
   503  		}
   504  		etag, remain := scanETag(buf)
   505  		if etag == "" {
   506  			break
   507  		}
   508  		if etagWeakMatch(etag, w.Header().get("Etag")) {
   509  			return condFalse
   510  		}
   511  		buf = remain
   512  	}
   513  	return condTrue
   514  }
   515  
   516  func checkIfModifiedSince(r *Request, modtime time.Time) condResult {
   517  	if r.Method != "GET" && r.Method != "HEAD" {
   518  		return condNone
   519  	}
   520  	ims := r.Header.Get("If-Modified-Since")
   521  	if ims == "" || isZeroTime(modtime) {
   522  		return condNone
   523  	}
   524  	t, err := ParseTime(ims)
   525  	if err != nil {
   526  		return condNone
   527  	}
   528  	// The Last-Modified header truncates sub-second precision so
   529  	// the modtime needs to be truncated too.
   530  	modtime = modtime.Truncate(time.Second)
   531  	if ret := modtime.Compare(t); ret <= 0 {
   532  		return condFalse
   533  	}
   534  	return condTrue
   535  }
   536  
   537  func checkIfRange(w ResponseWriter, r *Request, modtime time.Time) condResult {
   538  	if r.Method != "GET" && r.Method != "HEAD" {
   539  		return condNone
   540  	}
   541  	ir := r.Header.get("If-Range")
   542  	if ir == "" {
   543  		return condNone
   544  	}
   545  	etag, _ := scanETag(ir)
   546  	if etag != "" {
   547  		if etagStrongMatch(etag, w.Header().Get("Etag")) {
   548  			return condTrue
   549  		} else {
   550  			return condFalse
   551  		}
   552  	}
   553  	// The If-Range value is typically the ETag value, but it may also be
   554  	// the modtime date. See golang.org/issue/8367.
   555  	if modtime.IsZero() {
   556  		return condFalse
   557  	}
   558  	t, err := ParseTime(ir)
   559  	if err != nil {
   560  		return condFalse
   561  	}
   562  	if t.Unix() == modtime.Unix() {
   563  		return condTrue
   564  	}
   565  	return condFalse
   566  }
   567  
   568  var unixEpochTime = time.Unix(0, 0)
   569  
   570  // isZeroTime reports whether t is obviously unspecified (either zero or Unix()=0).
   571  func isZeroTime(t time.Time) bool {
   572  	return t.IsZero() || t.Equal(unixEpochTime)
   573  }
   574  
   575  func setLastModified(w ResponseWriter, modtime time.Time) {
   576  	if !isZeroTime(modtime) {
   577  		w.Header().Set("Last-Modified", modtime.UTC().Format(TimeFormat))
   578  	}
   579  }
   580  
   581  func writeNotModified(w ResponseWriter) {
   582  	// RFC 7232 section 4.1:
   583  	// a sender SHOULD NOT generate representation metadata other than the
   584  	// above listed fields unless said metadata exists for the purpose of
   585  	// guiding cache updates (e.g., Last-Modified might be useful if the
   586  	// response does not have an ETag field).
   587  	h := w.Header()
   588  	delete(h, "Content-Type")
   589  	delete(h, "Content-Length")
   590  	delete(h, "Content-Encoding")
   591  	if h.Get("Etag") != "" {
   592  		delete(h, "Last-Modified")
   593  	}
   594  	w.WriteHeader(StatusNotModified)
   595  }
   596  
   597  // checkPreconditions evaluates request preconditions and reports whether a precondition
   598  // resulted in sending StatusNotModified or StatusPreconditionFailed.
   599  func checkPreconditions(w ResponseWriter, r *Request, modtime time.Time) (done bool, rangeHeader string) {
   600  	// This function carefully follows RFC 7232 section 6.
   601  	ch := checkIfMatch(w, r)
   602  	if ch == condNone {
   603  		ch = checkIfUnmodifiedSince(r, modtime)
   604  	}
   605  	if ch == condFalse {
   606  		w.WriteHeader(StatusPreconditionFailed)
   607  		return true, ""
   608  	}
   609  	switch checkIfNoneMatch(w, r) {
   610  	case condFalse:
   611  		if r.Method == "GET" || r.Method == "HEAD" {
   612  			writeNotModified(w)
   613  			return true, ""
   614  		} else {
   615  			w.WriteHeader(StatusPreconditionFailed)
   616  			return true, ""
   617  		}
   618  	case condNone:
   619  		if checkIfModifiedSince(r, modtime) == condFalse {
   620  			writeNotModified(w)
   621  			return true, ""
   622  		}
   623  	}
   624  
   625  	rangeHeader = r.Header.get("Range")
   626  	if rangeHeader != "" && checkIfRange(w, r, modtime) == condFalse {
   627  		rangeHeader = ""
   628  	}
   629  	return false, rangeHeader
   630  }
   631  
   632  // name is '/'-separated, not filepath.Separator.
   633  func serveFile(w ResponseWriter, r *Request, fs FileSystem, name string, redirect bool) {
   634  	const indexPage = "/index.html"
   635  
   636  	// redirect .../index.html to .../
   637  	// can't use Redirect() because that would make the path absolute,
   638  	// which would be a problem running under StripPrefix
   639  	if strings.HasSuffix(r.URL.Path, indexPage) {
   640  		localRedirect(w, r, "./")
   641  		return
   642  	}
   643  
   644  	f, err := fs.Open(name)
   645  	if err != nil {
   646  		msg, code := toHTTPError(err)
   647  		Error(w, msg, code)
   648  		return
   649  	}
   650  	defer f.Close()
   651  
   652  	d, err := f.Stat()
   653  	if err != nil {
   654  		msg, code := toHTTPError(err)
   655  		Error(w, msg, code)
   656  		return
   657  	}
   658  
   659  	if redirect {
   660  		// redirect to canonical path: / at end of directory url
   661  		// r.URL.Path always begins with /
   662  		url := r.URL.Path
   663  		if d.IsDir() {
   664  			if url[len(url)-1] != '/' {
   665  				localRedirect(w, r, path.Base(url)+"/")
   666  				return
   667  			}
   668  		} else if url[len(url)-1] == '/' {
   669  			base := path.Base(url)
   670  			if base == "/" || base == "." {
   671  				// The FileSystem maps a path like "/" or "/./" to a file instead of a directory.
   672  				msg := "http: attempting to traverse a non-directory"
   673  				Error(w, msg, StatusInternalServerError)
   674  				return
   675  			}
   676  			localRedirect(w, r, "../"+base)
   677  			return
   678  		}
   679  	}
   680  
   681  	if d.IsDir() {
   682  		url := r.URL.Path
   683  		// redirect if the directory name doesn't end in a slash
   684  		if url == "" || url[len(url)-1] != '/' {
   685  			localRedirect(w, r, path.Base(url)+"/")
   686  			return
   687  		}
   688  
   689  		// use contents of index.html for directory, if present
   690  		index := strings.TrimSuffix(name, "/") + indexPage
   691  		ff, err := fs.Open(index)
   692  		if err == nil {
   693  			defer ff.Close()
   694  			dd, err := ff.Stat()
   695  			if err == nil {
   696  				d = dd
   697  				f = ff
   698  			}
   699  		}
   700  	}
   701  
   702  	// Still a directory? (we didn't find an index.html file)
   703  	if d.IsDir() {
   704  		if checkIfModifiedSince(r, d.ModTime()) == condFalse {
   705  			writeNotModified(w)
   706  			return
   707  		}
   708  		setLastModified(w, d.ModTime())
   709  		dirList(w, r, f)
   710  		return
   711  	}
   712  
   713  	// serveContent will check modification time
   714  	sizeFunc := func() (int64, error) { return d.Size(), nil }
   715  	serveContent(w, r, d.Name(), d.ModTime(), sizeFunc, f)
   716  }
   717  
   718  // toHTTPError returns a non-specific HTTP error message and status code
   719  // for a given non-nil error value. It's important that toHTTPError does not
   720  // actually return err.Error(), since msg and httpStatus are returned to users,
   721  // and historically Go's ServeContent always returned just "404 Not Found" for
   722  // all errors. We don't want to start leaking information in error messages.
   723  func toHTTPError(err error) (msg string, httpStatus int) {
   724  	if errors.Is(err, fs.ErrNotExist) {
   725  		return "404 page not found", StatusNotFound
   726  	}
   727  	if errors.Is(err, fs.ErrPermission) {
   728  		return "403 Forbidden", StatusForbidden
   729  	}
   730  	// Default:
   731  	return "500 Internal Server Error", StatusInternalServerError
   732  }
   733  
   734  // localRedirect gives a Moved Permanently response.
   735  // It does not convert relative paths to absolute paths like Redirect does.
   736  func localRedirect(w ResponseWriter, r *Request, newPath string) {
   737  	if q := r.URL.RawQuery; q != "" {
   738  		newPath += "?" + q
   739  	}
   740  	w.Header().Set("Location", newPath)
   741  	w.WriteHeader(StatusMovedPermanently)
   742  }
   743  
   744  // ServeFile replies to the request with the contents of the named
   745  // file or directory.
   746  //
   747  // If the provided file or directory name is a relative path, it is
   748  // interpreted relative to the current directory and may ascend to
   749  // parent directories. If the provided name is constructed from user
   750  // input, it should be sanitized before calling [ServeFile].
   751  //
   752  // As a precaution, ServeFile will reject requests where r.URL.Path
   753  // contains a ".." path element; this protects against callers who
   754  // might unsafely use [filepath.Join] on r.URL.Path without sanitizing
   755  // it and then use that filepath.Join result as the name argument.
   756  //
   757  // As another special case, ServeFile redirects any request where r.URL.Path
   758  // ends in "/index.html" to the same path, without the final
   759  // "index.html". To avoid such redirects either modify the path or
   760  // use [ServeContent].
   761  //
   762  // Outside of those two special cases, ServeFile does not use
   763  // r.URL.Path for selecting the file or directory to serve; only the
   764  // file or directory provided in the name argument is used.
   765  func ServeFile(w ResponseWriter, r *Request, name string) {
   766  	if containsDotDot(r.URL.Path) {
   767  		// Too many programs use r.URL.Path to construct the argument to
   768  		// serveFile. Reject the request under the assumption that happened
   769  		// here and ".." may not be wanted.
   770  		// Note that name might not contain "..", for example if code (still
   771  		// incorrectly) used filepath.Join(myDir, r.URL.Path).
   772  		Error(w, "invalid URL path", StatusBadRequest)
   773  		return
   774  	}
   775  	dir, file := filepath.Split(name)
   776  	serveFile(w, r, Dir(dir), file, false)
   777  }
   778  
   779  // ServeFileFS replies to the request with the contents
   780  // of the named file or directory from the file system fsys.
   781  //
   782  // If the provided name is constructed from user input, it should be
   783  // sanitized before calling [ServeFileFS].
   784  //
   785  // As a precaution, ServeFileFS will reject requests where r.URL.Path
   786  // contains a ".." path element; this protects against callers who
   787  // might unsafely use [filepath.Join] on r.URL.Path without sanitizing
   788  // it and then use that filepath.Join result as the name argument.
   789  //
   790  // As another special case, ServeFileFS redirects any request where r.URL.Path
   791  // ends in "/index.html" to the same path, without the final
   792  // "index.html". To avoid such redirects either modify the path or
   793  // use [ServeContent].
   794  //
   795  // Outside of those two special cases, ServeFileFS does not use
   796  // r.URL.Path for selecting the file or directory to serve; only the
   797  // file or directory provided in the name argument is used.
   798  func ServeFileFS(w ResponseWriter, r *Request, fsys fs.FS, name string) {
   799  	if containsDotDot(r.URL.Path) {
   800  		// Too many programs use r.URL.Path to construct the argument to
   801  		// serveFile. Reject the request under the assumption that happened
   802  		// here and ".." may not be wanted.
   803  		// Note that name might not contain "..", for example if code (still
   804  		// incorrectly) used filepath.Join(myDir, r.URL.Path).
   805  		Error(w, "invalid URL path", StatusBadRequest)
   806  		return
   807  	}
   808  	serveFile(w, r, FS(fsys), name, false)
   809  }
   810  
   811  func containsDotDot(v string) bool {
   812  	if !strings.Contains(v, "..") {
   813  		return false
   814  	}
   815  	for _, ent := range strings.FieldsFunc(v, isSlashRune) {
   816  		if ent == ".." {
   817  			return true
   818  		}
   819  	}
   820  	return false
   821  }
   822  
   823  func isSlashRune(r rune) bool { return r == '/' || r == '\\' }
   824  
   825  type fileHandler struct {
   826  	root FileSystem
   827  }
   828  
   829  type ioFS struct {
   830  	fsys fs.FS
   831  }
   832  
   833  type ioFile struct {
   834  	file fs.File
   835  }
   836  
   837  func (f ioFS) Open(name string) (File, error) {
   838  	if name == "/" {
   839  		name = "."
   840  	} else {
   841  		name = strings.TrimPrefix(name, "/")
   842  	}
   843  	file, err := f.fsys.Open(name)
   844  	if err != nil {
   845  		return nil, mapOpenError(err, name, '/', func(path string) (fs.FileInfo, error) {
   846  			return fs.Stat(f.fsys, path)
   847  		})
   848  	}
   849  	return ioFile{file}, nil
   850  }
   851  
   852  func (f ioFile) Close() error               { return f.file.Close() }
   853  func (f ioFile) Read(b []byte) (int, error) { return f.file.Read(b) }
   854  func (f ioFile) Stat() (fs.FileInfo, error) { return f.file.Stat() }
   855  
   856  var errMissingSeek = errors.New("io.File missing Seek method")
   857  var errMissingReadDir = errors.New("io.File directory missing ReadDir method")
   858  
   859  func (f ioFile) Seek(offset int64, whence int) (int64, error) {
   860  	s, ok := f.file.(io.Seeker)
   861  	if !ok {
   862  		return 0, errMissingSeek
   863  	}
   864  	return s.Seek(offset, whence)
   865  }
   866  
   867  func (f ioFile) ReadDir(count int) ([]fs.DirEntry, error) {
   868  	d, ok := f.file.(fs.ReadDirFile)
   869  	if !ok {
   870  		return nil, errMissingReadDir
   871  	}
   872  	return d.ReadDir(count)
   873  }
   874  
   875  func (f ioFile) Readdir(count int) ([]fs.FileInfo, error) {
   876  	d, ok := f.file.(fs.ReadDirFile)
   877  	if !ok {
   878  		return nil, errMissingReadDir
   879  	}
   880  	var list []fs.FileInfo
   881  	for {
   882  		dirs, err := d.ReadDir(count - len(list))
   883  		for _, dir := range dirs {
   884  			info, err := dir.Info()
   885  			if err != nil {
   886  				// Pretend it doesn't exist, like (*os.File).Readdir does.
   887  				continue
   888  			}
   889  			list = append(list, info)
   890  		}
   891  		if err != nil {
   892  			return list, err
   893  		}
   894  		if count < 0 || len(list) >= count {
   895  			break
   896  		}
   897  	}
   898  	return list, nil
   899  }
   900  
   901  // FS converts fsys to a [FileSystem] implementation,
   902  // for use with [FileServer] and [NewFileTransport].
   903  // The files provided by fsys must implement [io.Seeker].
   904  func FS(fsys fs.FS) FileSystem {
   905  	return ioFS{fsys}
   906  }
   907  
   908  // FileServer returns a handler that serves HTTP requests
   909  // with the contents of the file system rooted at root.
   910  //
   911  // As a special case, the returned file server redirects any request
   912  // ending in "/index.html" to the same path, without the final
   913  // "index.html".
   914  //
   915  // To use the operating system's file system implementation,
   916  // use [http.Dir]:
   917  //
   918  //	http.Handle("/", http.FileServer(http.Dir("/tmp")))
   919  //
   920  // To use an [fs.FS] implementation, use [http.FileServerFS] instead.
   921  func FileServer(root FileSystem) Handler {
   922  	return &fileHandler{root}
   923  }
   924  
   925  // FileServerFS returns a handler that serves HTTP requests
   926  // with the contents of the file system fsys.
   927  //
   928  // As a special case, the returned file server redirects any request
   929  // ending in "/index.html" to the same path, without the final
   930  // "index.html".
   931  //
   932  //	http.Handle("/", http.FileServerFS(fsys))
   933  func FileServerFS(root fs.FS) Handler {
   934  	return FileServer(FS(root))
   935  }
   936  
   937  func (f *fileHandler) ServeHTTP(w ResponseWriter, r *Request) {
   938  	upath := r.URL.Path
   939  	if !strings.HasPrefix(upath, "/") {
   940  		upath = "/" + upath
   941  		r.URL.Path = upath
   942  	}
   943  	serveFile(w, r, f.root, path.Clean(upath), true)
   944  }
   945  
   946  // httpRange specifies the byte range to be sent to the client.
   947  type httpRange struct {
   948  	start, length int64
   949  }
   950  
   951  func (r httpRange) contentRange(size int64) string {
   952  	return fmt.Sprintf("bytes %d-%d/%d", r.start, r.start+r.length-1, size)
   953  }
   954  
   955  func (r httpRange) mimeHeader(contentType string, size int64) textproto.MIMEHeader {
   956  	return textproto.MIMEHeader{
   957  		"Content-Range": {r.contentRange(size)},
   958  		"Content-Type":  {contentType},
   959  	}
   960  }
   961  
   962  // parseRange parses a Range header string as per RFC 7233.
   963  // errNoOverlap is returned if none of the ranges overlap.
   964  func parseRange(s string, size int64) ([]httpRange, error) {
   965  	if s == "" {
   966  		return nil, nil // header not present
   967  	}
   968  	const b = "bytes="
   969  	if !strings.HasPrefix(s, b) {
   970  		return nil, errors.New("invalid range")
   971  	}
   972  	var ranges []httpRange
   973  	noOverlap := false
   974  	for _, ra := range strings.Split(s[len(b):], ",") {
   975  		ra = textproto.TrimString(ra)
   976  		if ra == "" {
   977  			continue
   978  		}
   979  		start, end, ok := strings.Cut(ra, "-")
   980  		if !ok {
   981  			return nil, errors.New("invalid range")
   982  		}
   983  		start, end = textproto.TrimString(start), textproto.TrimString(end)
   984  		var r httpRange
   985  		if start == "" {
   986  			// If no start is specified, end specifies the
   987  			// range start relative to the end of the file,
   988  			// and we are dealing with <suffix-length>
   989  			// which has to be a non-negative integer as per
   990  			// RFC 7233 Section 2.1 "Byte-Ranges".
   991  			if end == "" || end[0] == '-' {
   992  				return nil, errors.New("invalid range")
   993  			}
   994  			i, err := strconv.ParseInt(end, 10, 64)
   995  			if i < 0 || err != nil {
   996  				return nil, errors.New("invalid range")
   997  			}
   998  			if i > size {
   999  				i = size
  1000  			}
  1001  			r.start = size - i
  1002  			r.length = size - r.start
  1003  		} else {
  1004  			i, err := strconv.ParseInt(start, 10, 64)
  1005  			if err != nil || i < 0 {
  1006  				return nil, errors.New("invalid range")
  1007  			}
  1008  			if i >= size {
  1009  				// If the range begins after the size of the content,
  1010  				// then it does not overlap.
  1011  				noOverlap = true
  1012  				continue
  1013  			}
  1014  			r.start = i
  1015  			if end == "" {
  1016  				// If no end is specified, range extends to end of the file.
  1017  				r.length = size - r.start
  1018  			} else {
  1019  				i, err := strconv.ParseInt(end, 10, 64)
  1020  				if err != nil || r.start > i {
  1021  					return nil, errors.New("invalid range")
  1022  				}
  1023  				if i >= size {
  1024  					i = size - 1
  1025  				}
  1026  				r.length = i - r.start + 1
  1027  			}
  1028  		}
  1029  		ranges = append(ranges, r)
  1030  	}
  1031  	if noOverlap && len(ranges) == 0 {
  1032  		// The specified ranges did not overlap with the content.
  1033  		return nil, errNoOverlap
  1034  	}
  1035  	return ranges, nil
  1036  }
  1037  
  1038  // countingWriter counts how many bytes have been written to it.
  1039  type countingWriter int64
  1040  
  1041  func (w *countingWriter) Write(p []byte) (n int, err error) {
  1042  	*w += countingWriter(len(p))
  1043  	return len(p), nil
  1044  }
  1045  
  1046  // rangesMIMESize returns the number of bytes it takes to encode the
  1047  // provided ranges as a multipart response.
  1048  func rangesMIMESize(ranges []httpRange, contentType string, contentSize int64) (encSize int64) {
  1049  	var w countingWriter
  1050  	mw := multipart.NewWriter(&w)
  1051  	for _, ra := range ranges {
  1052  		mw.CreatePart(ra.mimeHeader(contentType, contentSize))
  1053  		encSize += ra.length
  1054  	}
  1055  	mw.Close()
  1056  	encSize += int64(w)
  1057  	return
  1058  }
  1059  
  1060  func sumRangesSize(ranges []httpRange) (size int64) {
  1061  	for _, ra := range ranges {
  1062  		size += ra.length
  1063  	}
  1064  	return
  1065  }
  1066  

View as plain text