Black Lives Matter. Support the Equal Justice Initiative.

Source file src/net/http/fs.go

Documentation: net/http

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

View as plain text