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