github.com/ck00004/CobaltStrikeParser-Go@v1.0.14/lib/http/fs.go (about)

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