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