golang.org/toolchain@v0.0.1-go1.9rc2.windows-amd64/src/net/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  	"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  func (d Dir) Open(name string) (File, error) {
    67  	if filepath.Separator != '/' && strings.ContainsRune(name, filepath.Separator) {
    68  		return nil, errors.New("http: invalid character in file path")
    69  	}
    70  	dir := string(d)
    71  	if dir == "" {
    72  		dir = "."
    73  	}
    74  	fullName := filepath.Join(dir, filepath.FromSlash(path.Clean("/"+name)))
    75  	f, err := os.Open(fullName)
    76  	if err != nil {
    77  		return nil, mapDirOpenError(err, fullName)
    78  	}
    79  	return f, nil
    80  }
    81  
    82  // A FileSystem implements access to a collection of named files.
    83  // The elements in a file path are separated by slash ('/', U+002F)
    84  // characters, regardless of host operating system convention.
    85  type FileSystem interface {
    86  	Open(name string) (File, error)
    87  }
    88  
    89  // A File is returned by a FileSystem's Open method and can be
    90  // served by the FileServer implementation.
    91  //
    92  // The methods should behave the same as those on an *os.File.
    93  type File interface {
    94  	io.Closer
    95  	io.Reader
    96  	io.Seeker
    97  	Readdir(count int) ([]os.FileInfo, error)
    98  	Stat() (os.FileInfo, error)
    99  }
   100  
   101  func dirList(w ResponseWriter, f File) {
   102  	dirs, err := f.Readdir(-1)
   103  	if err != nil {
   104  		// TODO: log err.Error() to the Server.ErrorLog, once it's possible
   105  		// for a handler to get at its Server via the ResponseWriter. See
   106  		// Issue 12438.
   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 2616, Section 14.16:
   241  			// "When an HTTP message includes the content of a single
   242  			// range (for example, a response to a request for a
   243  			// single range, or to a request for a set of ranges
   244  			// that overlap without any holes), this content is
   245  			// transmitted with a Content-Range header, and a
   246  			// Content-Length header showing the number of bytes
   247  			// actually transferred.
   248  			// ...
   249  			// A response to a request for a single range MUST NOT
   250  			// be sent using the multipart/byteranges media type."
   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 string(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  	if t, err := ParseTime(ius); err == nil {
   388  		// The Date-Modified header truncates sub-second precision, so
   389  		// use mtime < t+1s instead of mtime <= t to check for unmodified.
   390  		if modtime.Before(t.Add(1 * time.Second)) {
   391  			return condTrue
   392  		}
   393  		return condFalse
   394  	}
   395  	return condNone
   396  }
   397  
   398  func checkIfNoneMatch(w ResponseWriter, r *Request) condResult {
   399  	inm := r.Header.get("If-None-Match")
   400  	if inm == "" {
   401  		return condNone
   402  	}
   403  	buf := inm
   404  	for {
   405  		buf = textproto.TrimString(buf)
   406  		if len(buf) == 0 {
   407  			break
   408  		}
   409  		if buf[0] == ',' {
   410  			buf = buf[1:]
   411  		}
   412  		if buf[0] == '*' {
   413  			return condFalse
   414  		}
   415  		etag, remain := scanETag(buf)
   416  		if etag == "" {
   417  			break
   418  		}
   419  		if etagWeakMatch(etag, w.Header().get("Etag")) {
   420  			return condFalse
   421  		}
   422  		buf = remain
   423  	}
   424  	return condTrue
   425  }
   426  
   427  func checkIfModifiedSince(r *Request, modtime time.Time) condResult {
   428  	if r.Method != "GET" && r.Method != "HEAD" {
   429  		return condNone
   430  	}
   431  	ims := r.Header.Get("If-Modified-Since")
   432  	if ims == "" || isZeroTime(modtime) {
   433  		return condNone
   434  	}
   435  	t, err := ParseTime(ims)
   436  	if err != nil {
   437  		return condNone
   438  	}
   439  	// The Date-Modified header truncates sub-second precision, so
   440  	// use mtime < t+1s instead of mtime <= t to check for unmodified.
   441  	if modtime.Before(t.Add(1 * time.Second)) {
   442  		return condFalse
   443  	}
   444  	return condTrue
   445  }
   446  
   447  func checkIfRange(w ResponseWriter, r *Request, modtime time.Time) condResult {
   448  	if r.Method != "GET" {
   449  		return condNone
   450  	}
   451  	ir := r.Header.get("If-Range")
   452  	if ir == "" {
   453  		return condNone
   454  	}
   455  	etag, _ := scanETag(ir)
   456  	if etag != "" {
   457  		if etagStrongMatch(etag, w.Header().Get("Etag")) {
   458  			return condTrue
   459  		} else {
   460  			return condFalse
   461  		}
   462  	}
   463  	// The If-Range value is typically the ETag value, but it may also be
   464  	// the modtime date. See golang.org/issue/8367.
   465  	if modtime.IsZero() {
   466  		return condFalse
   467  	}
   468  	t, err := ParseTime(ir)
   469  	if err != nil {
   470  		return condFalse
   471  	}
   472  	if t.Unix() == modtime.Unix() {
   473  		return condTrue
   474  	}
   475  	return condFalse
   476  }
   477  
   478  var unixEpochTime = time.Unix(0, 0)
   479  
   480  // isZeroTime reports whether t is obviously unspecified (either zero or Unix()=0).
   481  func isZeroTime(t time.Time) bool {
   482  	return t.IsZero() || t.Equal(unixEpochTime)
   483  }
   484  
   485  func setLastModified(w ResponseWriter, modtime time.Time) {
   486  	if !isZeroTime(modtime) {
   487  		w.Header().Set("Last-Modified", modtime.UTC().Format(TimeFormat))
   488  	}
   489  }
   490  
   491  func writeNotModified(w ResponseWriter) {
   492  	// RFC 7232 section 4.1:
   493  	// a sender SHOULD NOT generate representation metadata other than the
   494  	// above listed fields unless said metadata exists for the purpose of
   495  	// guiding cache updates (e.g., Last-Modified might be useful if the
   496  	// response does not have an ETag field).
   497  	h := w.Header()
   498  	delete(h, "Content-Type")
   499  	delete(h, "Content-Length")
   500  	if h.Get("Etag") != "" {
   501  		delete(h, "Last-Modified")
   502  	}
   503  	w.WriteHeader(StatusNotModified)
   504  }
   505  
   506  // checkPreconditions evaluates request preconditions and reports whether a precondition
   507  // resulted in sending StatusNotModified or StatusPreconditionFailed.
   508  func checkPreconditions(w ResponseWriter, r *Request, modtime time.Time) (done bool, rangeHeader string) {
   509  	// This function carefully follows RFC 7232 section 6.
   510  	ch := checkIfMatch(w, r)
   511  	if ch == condNone {
   512  		ch = checkIfUnmodifiedSince(r, modtime)
   513  	}
   514  	if ch == condFalse {
   515  		w.WriteHeader(StatusPreconditionFailed)
   516  		return true, ""
   517  	}
   518  	switch checkIfNoneMatch(w, r) {
   519  	case condFalse:
   520  		if r.Method == "GET" || r.Method == "HEAD" {
   521  			writeNotModified(w)
   522  			return true, ""
   523  		} else {
   524  			w.WriteHeader(StatusPreconditionFailed)
   525  			return true, ""
   526  		}
   527  	case condNone:
   528  		if checkIfModifiedSince(r, modtime) == condFalse {
   529  			writeNotModified(w)
   530  			return true, ""
   531  		}
   532  	}
   533  
   534  	rangeHeader = r.Header.get("Range")
   535  	if rangeHeader != "" {
   536  		if checkIfRange(w, r, modtime) == condFalse {
   537  			rangeHeader = ""
   538  		}
   539  	}
   540  	return false, rangeHeader
   541  }
   542  
   543  // name is '/'-separated, not filepath.Separator.
   544  func serveFile(w ResponseWriter, r *Request, fs FileSystem, name string, redirect bool) {
   545  	const indexPage = "/index.html"
   546  
   547  	// redirect .../index.html to .../
   548  	// can't use Redirect() because that would make the path absolute,
   549  	// which would be a problem running under StripPrefix
   550  	if strings.HasSuffix(r.URL.Path, indexPage) {
   551  		localRedirect(w, r, "./")
   552  		return
   553  	}
   554  
   555  	f, err := fs.Open(name)
   556  	if err != nil {
   557  		msg, code := toHTTPError(err)
   558  		Error(w, msg, code)
   559  		return
   560  	}
   561  	defer f.Close()
   562  
   563  	d, err := f.Stat()
   564  	if err != nil {
   565  		msg, code := toHTTPError(err)
   566  		Error(w, msg, code)
   567  		return
   568  	}
   569  
   570  	if redirect {
   571  		// redirect to canonical path: / at end of directory url
   572  		// r.URL.Path always begins with /
   573  		url := r.URL.Path
   574  		if d.IsDir() {
   575  			if url[len(url)-1] != '/' {
   576  				localRedirect(w, r, path.Base(url)+"/")
   577  				return
   578  			}
   579  		} else {
   580  			if url[len(url)-1] == '/' {
   581  				localRedirect(w, r, "../"+path.Base(url))
   582  				return
   583  			}
   584  		}
   585  	}
   586  
   587  	// redirect if the directory name doesn't end in a slash
   588  	if d.IsDir() {
   589  		url := r.URL.Path
   590  		if url[len(url)-1] != '/' {
   591  			localRedirect(w, r, path.Base(url)+"/")
   592  			return
   593  		}
   594  	}
   595  
   596  	// use contents of index.html for directory, if present
   597  	if d.IsDir() {
   598  		index := strings.TrimSuffix(name, "/") + indexPage
   599  		ff, err := fs.Open(index)
   600  		if err == nil {
   601  			defer ff.Close()
   602  			dd, err := ff.Stat()
   603  			if err == nil {
   604  				name = index
   605  				d = dd
   606  				f = ff
   607  			}
   608  		}
   609  	}
   610  
   611  	// Still a directory? (we didn't find an index.html file)
   612  	if d.IsDir() {
   613  		if checkIfModifiedSince(r, d.ModTime()) == condFalse {
   614  			writeNotModified(w)
   615  			return
   616  		}
   617  		w.Header().Set("Last-Modified", d.ModTime().UTC().Format(TimeFormat))
   618  		dirList(w, f)
   619  		return
   620  	}
   621  
   622  	// serveContent will check modification time
   623  	sizeFunc := func() (int64, error) { return d.Size(), nil }
   624  	serveContent(w, r, d.Name(), d.ModTime(), sizeFunc, f)
   625  }
   626  
   627  // toHTTPError returns a non-specific HTTP error message and status code
   628  // for a given non-nil error value. It's important that toHTTPError does not
   629  // actually return err.Error(), since msg and httpStatus are returned to users,
   630  // and historically Go's ServeContent always returned just "404 Not Found" for
   631  // all errors. We don't want to start leaking information in error messages.
   632  func toHTTPError(err error) (msg string, httpStatus int) {
   633  	if os.IsNotExist(err) {
   634  		return "404 page not found", StatusNotFound
   635  	}
   636  	if os.IsPermission(err) {
   637  		return "403 Forbidden", StatusForbidden
   638  	}
   639  	// Default:
   640  	return "500 Internal Server Error", StatusInternalServerError
   641  }
   642  
   643  // localRedirect gives a Moved Permanently response.
   644  // It does not convert relative paths to absolute paths like Redirect does.
   645  func localRedirect(w ResponseWriter, r *Request, newPath string) {
   646  	if q := r.URL.RawQuery; q != "" {
   647  		newPath += "?" + q
   648  	}
   649  	w.Header().Set("Location", newPath)
   650  	w.WriteHeader(StatusMovedPermanently)
   651  }
   652  
   653  // ServeFile replies to the request with the contents of the named
   654  // file or directory.
   655  //
   656  // If the provided file or directory name is a relative path, it is
   657  // interpreted relative to the current directory and may ascend to parent
   658  // directories. If the provided name is constructed from user input, it
   659  // should be sanitized before calling ServeFile. As a precaution, ServeFile
   660  // will reject requests where r.URL.Path contains a ".." path element.
   661  //
   662  // As a special case, ServeFile redirects any request where r.URL.Path
   663  // ends in "/index.html" to the same path, without the final
   664  // "index.html". To avoid such redirects either modify the path or
   665  // use ServeContent.
   666  func ServeFile(w ResponseWriter, r *Request, name string) {
   667  	if containsDotDot(r.URL.Path) {
   668  		// Too many programs use r.URL.Path to construct the argument to
   669  		// serveFile. Reject the request under the assumption that happened
   670  		// here and ".." may not be wanted.
   671  		// Note that name might not contain "..", for example if code (still
   672  		// incorrectly) used filepath.Join(myDir, r.URL.Path).
   673  		Error(w, "invalid URL path", StatusBadRequest)
   674  		return
   675  	}
   676  	dir, file := filepath.Split(name)
   677  	serveFile(w, r, Dir(dir), file, false)
   678  }
   679  
   680  func containsDotDot(v string) bool {
   681  	if !strings.Contains(v, "..") {
   682  		return false
   683  	}
   684  	for _, ent := range strings.FieldsFunc(v, isSlashRune) {
   685  		if ent == ".." {
   686  			return true
   687  		}
   688  	}
   689  	return false
   690  }
   691  
   692  func isSlashRune(r rune) bool { return r == '/' || r == '\\' }
   693  
   694  type fileHandler struct {
   695  	root FileSystem
   696  }
   697  
   698  // FileServer returns a handler that serves HTTP requests
   699  // with the contents of the file system rooted at root.
   700  //
   701  // To use the operating system's file system implementation,
   702  // use http.Dir:
   703  //
   704  //     http.Handle("/", http.FileServer(http.Dir("/tmp")))
   705  //
   706  // As a special case, the returned file server redirects any request
   707  // ending in "/index.html" to the same path, without the final
   708  // "index.html".
   709  func FileServer(root FileSystem) Handler {
   710  	return &fileHandler{root}
   711  }
   712  
   713  func (f *fileHandler) ServeHTTP(w ResponseWriter, r *Request) {
   714  	upath := r.URL.Path
   715  	if !strings.HasPrefix(upath, "/") {
   716  		upath = "/" + upath
   717  		r.URL.Path = upath
   718  	}
   719  	serveFile(w, r, f.root, path.Clean(upath), true)
   720  }
   721  
   722  // httpRange specifies the byte range to be sent to the client.
   723  type httpRange struct {
   724  	start, length int64
   725  }
   726  
   727  func (r httpRange) contentRange(size int64) string {
   728  	return fmt.Sprintf("bytes %d-%d/%d", r.start, r.start+r.length-1, size)
   729  }
   730  
   731  func (r httpRange) mimeHeader(contentType string, size int64) textproto.MIMEHeader {
   732  	return textproto.MIMEHeader{
   733  		"Content-Range": {r.contentRange(size)},
   734  		"Content-Type":  {contentType},
   735  	}
   736  }
   737  
   738  // parseRange parses a Range header string as per RFC 2616.
   739  // errNoOverlap is returned if none of the ranges overlap.
   740  func parseRange(s string, size int64) ([]httpRange, error) {
   741  	if s == "" {
   742  		return nil, nil // header not present
   743  	}
   744  	const b = "bytes="
   745  	if !strings.HasPrefix(s, b) {
   746  		return nil, errors.New("invalid range")
   747  	}
   748  	var ranges []httpRange
   749  	noOverlap := false
   750  	for _, ra := range strings.Split(s[len(b):], ",") {
   751  		ra = strings.TrimSpace(ra)
   752  		if ra == "" {
   753  			continue
   754  		}
   755  		i := strings.Index(ra, "-")
   756  		if i < 0 {
   757  			return nil, errors.New("invalid range")
   758  		}
   759  		start, end := strings.TrimSpace(ra[:i]), strings.TrimSpace(ra[i+1:])
   760  		var r httpRange
   761  		if start == "" {
   762  			// If no start is specified, end specifies the
   763  			// range start relative to the end of the file.
   764  			i, err := strconv.ParseInt(end, 10, 64)
   765  			if err != nil {
   766  				return nil, errors.New("invalid range")
   767  			}
   768  			if i > size {
   769  				i = size
   770  			}
   771  			r.start = size - i
   772  			r.length = size - r.start
   773  		} else {
   774  			i, err := strconv.ParseInt(start, 10, 64)
   775  			if err != nil || i < 0 {
   776  				return nil, errors.New("invalid range")
   777  			}
   778  			if i >= size {
   779  				// If the range begins after the size of the content,
   780  				// then it does not overlap.
   781  				noOverlap = true
   782  				continue
   783  			}
   784  			r.start = i
   785  			if end == "" {
   786  				// If no end is specified, range extends to end of the file.
   787  				r.length = size - r.start
   788  			} else {
   789  				i, err := strconv.ParseInt(end, 10, 64)
   790  				if err != nil || r.start > i {
   791  					return nil, errors.New("invalid range")
   792  				}
   793  				if i >= size {
   794  					i = size - 1
   795  				}
   796  				r.length = i - r.start + 1
   797  			}
   798  		}
   799  		ranges = append(ranges, r)
   800  	}
   801  	if noOverlap && len(ranges) == 0 {
   802  		// The specified ranges did not overlap with the content.
   803  		return nil, errNoOverlap
   804  	}
   805  	return ranges, nil
   806  }
   807  
   808  // countingWriter counts how many bytes have been written to it.
   809  type countingWriter int64
   810  
   811  func (w *countingWriter) Write(p []byte) (n int, err error) {
   812  	*w += countingWriter(len(p))
   813  	return len(p), nil
   814  }
   815  
   816  // rangesMIMESize returns the number of bytes it takes to encode the
   817  // provided ranges as a multipart response.
   818  func rangesMIMESize(ranges []httpRange, contentType string, contentSize int64) (encSize int64) {
   819  	var w countingWriter
   820  	mw := multipart.NewWriter(&w)
   821  	for _, ra := range ranges {
   822  		mw.CreatePart(ra.mimeHeader(contentType, contentSize))
   823  		encSize += ra.length
   824  	}
   825  	mw.Close()
   826  	encSize += int64(w)
   827  	return
   828  }
   829  
   830  func sumRangesSize(ranges []httpRange) (size int64) {
   831  	for _, ra := range ranges {
   832  		size += ra.length
   833  	}
   834  	return
   835  }