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

View as plain text