]> Cypherpunks.ru repositories - gostls13.git/blob - src/net/http/fs.go
[dev.boringcrypto] all: merge master into dev.boringcrypto
[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 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                 }
415                 if buf[0] == '*' {
416                         return condFalse
417                 }
418                 etag, remain := scanETag(buf)
419                 if etag == "" {
420                         break
421                 }
422                 if etagWeakMatch(etag, w.Header().get("Etag")) {
423                         return condFalse
424                 }
425                 buf = remain
426         }
427         return condTrue
428 }
429
430 func checkIfModifiedSince(r *Request, modtime time.Time) condResult {
431         if r.Method != "GET" && r.Method != "HEAD" {
432                 return condNone
433         }
434         ims := r.Header.Get("If-Modified-Since")
435         if ims == "" || isZeroTime(modtime) {
436                 return condNone
437         }
438         t, err := ParseTime(ims)
439         if err != nil {
440                 return condNone
441         }
442         // The Last-Modified header truncates sub-second precision so
443         // the modtime needs to be truncated too.
444         modtime = modtime.Truncate(time.Second)
445         if modtime.Before(t) || modtime.Equal(t) {
446                 return condFalse
447         }
448         return condTrue
449 }
450
451 func checkIfRange(w ResponseWriter, r *Request, modtime time.Time) condResult {
452         if r.Method != "GET" && r.Method != "HEAD" {
453                 return condNone
454         }
455         ir := r.Header.get("If-Range")
456         if ir == "" {
457                 return condNone
458         }
459         etag, _ := scanETag(ir)
460         if etag != "" {
461                 if etagStrongMatch(etag, w.Header().Get("Etag")) {
462                         return condTrue
463                 } else {
464                         return condFalse
465                 }
466         }
467         // The If-Range value is typically the ETag value, but it may also be
468         // the modtime date. See golang.org/issue/8367.
469         if modtime.IsZero() {
470                 return condFalse
471         }
472         t, err := ParseTime(ir)
473         if err != nil {
474                 return condFalse
475         }
476         if t.Unix() == modtime.Unix() {
477                 return condTrue
478         }
479         return condFalse
480 }
481
482 var unixEpochTime = time.Unix(0, 0)
483
484 // isZeroTime reports whether t is obviously unspecified (either zero or Unix()=0).
485 func isZeroTime(t time.Time) bool {
486         return t.IsZero() || t.Equal(unixEpochTime)
487 }
488
489 func setLastModified(w ResponseWriter, modtime time.Time) {
490         if !isZeroTime(modtime) {
491                 w.Header().Set("Last-Modified", modtime.UTC().Format(TimeFormat))
492         }
493 }
494
495 func writeNotModified(w ResponseWriter) {
496         // RFC 7232 section 4.1:
497         // a sender SHOULD NOT generate representation metadata other than the
498         // above listed fields unless said metadata exists for the purpose of
499         // guiding cache updates (e.g., Last-Modified might be useful if the
500         // response does not have an ETag field).
501         h := w.Header()
502         delete(h, "Content-Type")
503         delete(h, "Content-Length")
504         if h.Get("Etag") != "" {
505                 delete(h, "Last-Modified")
506         }
507         w.WriteHeader(StatusNotModified)
508 }
509
510 // checkPreconditions evaluates request preconditions and reports whether a precondition
511 // resulted in sending StatusNotModified or StatusPreconditionFailed.
512 func checkPreconditions(w ResponseWriter, r *Request, modtime time.Time) (done bool, rangeHeader string) {
513         // This function carefully follows RFC 7232 section 6.
514         ch := checkIfMatch(w, r)
515         if ch == condNone {
516                 ch = checkIfUnmodifiedSince(r, modtime)
517         }
518         if ch == condFalse {
519                 w.WriteHeader(StatusPreconditionFailed)
520                 return true, ""
521         }
522         switch checkIfNoneMatch(w, r) {
523         case condFalse:
524                 if r.Method == "GET" || r.Method == "HEAD" {
525                         writeNotModified(w)
526                         return true, ""
527                 } else {
528                         w.WriteHeader(StatusPreconditionFailed)
529                         return true, ""
530                 }
531         case condNone:
532                 if checkIfModifiedSince(r, modtime) == condFalse {
533                         writeNotModified(w)
534                         return true, ""
535                 }
536         }
537
538         rangeHeader = r.Header.get("Range")
539         if rangeHeader != "" && checkIfRange(w, r, modtime) == condFalse {
540                 rangeHeader = ""
541         }
542         return false, rangeHeader
543 }
544
545 // name is '/'-separated, not filepath.Separator.
546 func serveFile(w ResponseWriter, r *Request, fs FileSystem, name string, redirect bool) {
547         const indexPage = "/index.html"
548
549         // redirect .../index.html to .../
550         // can't use Redirect() because that would make the path absolute,
551         // which would be a problem running under StripPrefix
552         if strings.HasSuffix(r.URL.Path, indexPage) {
553                 localRedirect(w, r, "./")
554                 return
555         }
556
557         f, err := fs.Open(name)
558         if err != nil {
559                 msg, code := toHTTPError(err)
560                 Error(w, msg, code)
561                 return
562         }
563         defer f.Close()
564
565         d, err := f.Stat()
566         if err != nil {
567                 msg, code := toHTTPError(err)
568                 Error(w, msg, code)
569                 return
570         }
571
572         if redirect {
573                 // redirect to canonical path: / at end of directory url
574                 // r.URL.Path always begins with /
575                 url := r.URL.Path
576                 if d.IsDir() {
577                         if url[len(url)-1] != '/' {
578                                 localRedirect(w, r, path.Base(url)+"/")
579                                 return
580                         }
581                 } else {
582                         if url[len(url)-1] == '/' {
583                                 localRedirect(w, r, "../"+path.Base(url))
584                                 return
585                         }
586                 }
587         }
588
589         if d.IsDir() {
590                 url := r.URL.Path
591                 // redirect if the directory name doesn't end in a slash
592                 if url == "" || url[len(url)-1] != '/' {
593                         localRedirect(w, r, path.Base(url)+"/")
594                         return
595                 }
596
597                 // use contents of index.html for directory, if present
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                 setLastModified(w, d.ModTime())
618                 dirList(w, r, 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
658 // parent directories. If the provided name is constructed from user
659 // input, it should be sanitized before calling ServeFile.
660 //
661 // As a precaution, ServeFile will reject requests where r.URL.Path
662 // contains a ".." path element; this protects against callers who
663 // might unsafely use filepath.Join on r.URL.Path without sanitizing
664 // it and then use that filepath.Join result as the name argument.
665 //
666 // As another special case, ServeFile redirects any request where r.URL.Path
667 // ends in "/index.html" to the same path, without the final
668 // "index.html". To avoid such redirects either modify the path or
669 // use ServeContent.
670 //
671 // Outside of those two special cases, ServeFile does not use
672 // r.URL.Path for selecting the file or directory to serve; only the
673 // file or directory provided in the name argument is used.
674 func ServeFile(w ResponseWriter, r *Request, name string) {
675         if containsDotDot(r.URL.Path) {
676                 // Too many programs use r.URL.Path to construct the argument to
677                 // serveFile. Reject the request under the assumption that happened
678                 // here and ".." may not be wanted.
679                 // Note that name might not contain "..", for example if code (still
680                 // incorrectly) used filepath.Join(myDir, r.URL.Path).
681                 Error(w, "invalid URL path", StatusBadRequest)
682                 return
683         }
684         dir, file := filepath.Split(name)
685         serveFile(w, r, Dir(dir), file, false)
686 }
687
688 func containsDotDot(v string) bool {
689         if !strings.Contains(v, "..") {
690                 return false
691         }
692         for _, ent := range strings.FieldsFunc(v, isSlashRune) {
693                 if ent == ".." {
694                         return true
695                 }
696         }
697         return false
698 }
699
700 func isSlashRune(r rune) bool { return r == '/' || r == '\\' }
701
702 type fileHandler struct {
703         root FileSystem
704 }
705
706 // FileServer returns a handler that serves HTTP requests
707 // with the contents of the file system rooted at root.
708 //
709 // To use the operating system's file system implementation,
710 // use http.Dir:
711 //
712 //     http.Handle("/", http.FileServer(http.Dir("/tmp")))
713 //
714 // As a special case, the returned file server redirects any request
715 // ending in "/index.html" to the same path, without the final
716 // "index.html".
717 func FileServer(root FileSystem) Handler {
718         return &fileHandler{root}
719 }
720
721 func (f *fileHandler) ServeHTTP(w ResponseWriter, r *Request) {
722         upath := r.URL.Path
723         if !strings.HasPrefix(upath, "/") {
724                 upath = "/" + upath
725                 r.URL.Path = upath
726         }
727         serveFile(w, r, f.root, path.Clean(upath), true)
728 }
729
730 // httpRange specifies the byte range to be sent to the client.
731 type httpRange struct {
732         start, length int64
733 }
734
735 func (r httpRange) contentRange(size int64) string {
736         return fmt.Sprintf("bytes %d-%d/%d", r.start, r.start+r.length-1, size)
737 }
738
739 func (r httpRange) mimeHeader(contentType string, size int64) textproto.MIMEHeader {
740         return textproto.MIMEHeader{
741                 "Content-Range": {r.contentRange(size)},
742                 "Content-Type":  {contentType},
743         }
744 }
745
746 // parseRange parses a Range header string as per RFC 7233.
747 // errNoOverlap is returned if none of the ranges overlap.
748 func parseRange(s string, size int64) ([]httpRange, error) {
749         if s == "" {
750                 return nil, nil // header not present
751         }
752         const b = "bytes="
753         if !strings.HasPrefix(s, b) {
754                 return nil, errors.New("invalid range")
755         }
756         var ranges []httpRange
757         noOverlap := false
758         for _, ra := range strings.Split(s[len(b):], ",") {
759                 ra = textproto.TrimString(ra)
760                 if ra == "" {
761                         continue
762                 }
763                 i := strings.Index(ra, "-")
764                 if i < 0 {
765                         return nil, errors.New("invalid range")
766                 }
767                 start, end := textproto.TrimString(ra[:i]), textproto.TrimString(ra[i+1:])
768                 var r httpRange
769                 if start == "" {
770                         // If no start is specified, end specifies the
771                         // range start relative to the end of the file.
772                         i, err := strconv.ParseInt(end, 10, 64)
773                         if err != nil {
774                                 return nil, errors.New("invalid range")
775                         }
776                         if i > size {
777                                 i = size
778                         }
779                         r.start = size - i
780                         r.length = size - r.start
781                 } else {
782                         i, err := strconv.ParseInt(start, 10, 64)
783                         if err != nil || i < 0 {
784                                 return nil, errors.New("invalid range")
785                         }
786                         if i >= size {
787                                 // If the range begins after the size of the content,
788                                 // then it does not overlap.
789                                 noOverlap = true
790                                 continue
791                         }
792                         r.start = i
793                         if end == "" {
794                                 // If no end is specified, range extends to end of the file.
795                                 r.length = size - r.start
796                         } else {
797                                 i, err := strconv.ParseInt(end, 10, 64)
798                                 if err != nil || r.start > i {
799                                         return nil, errors.New("invalid range")
800                                 }
801                                 if i >= size {
802                                         i = size - 1
803                                 }
804                                 r.length = i - r.start + 1
805                         }
806                 }
807                 ranges = append(ranges, r)
808         }
809         if noOverlap && len(ranges) == 0 {
810                 // The specified ranges did not overlap with the content.
811                 return nil, errNoOverlap
812         }
813         return ranges, nil
814 }
815
816 // countingWriter counts how many bytes have been written to it.
817 type countingWriter int64
818
819 func (w *countingWriter) Write(p []byte) (n int, err error) {
820         *w += countingWriter(len(p))
821         return len(p), nil
822 }
823
824 // rangesMIMESize returns the number of bytes it takes to encode the
825 // provided ranges as a multipart response.
826 func rangesMIMESize(ranges []httpRange, contentType string, contentSize int64) (encSize int64) {
827         var w countingWriter
828         mw := multipart.NewWriter(&w)
829         for _, ra := range ranges {
830                 mw.CreatePart(ra.mimeHeader(contentType, contentSize))
831                 encSize += ra.length
832         }
833         mw.Close()
834         encSize += int64(w)
835         return
836 }
837
838 func sumRangesSize(ranges []httpRange) (size int64) {
839         for _, ra := range ranges {
840                 size += ra.length
841         }
842         return
843 }