]> Cypherpunks.ru repositories - gostls13.git/blob - src/net/http/fs.go
net/http: redirect if the URL path is a dir & doesn't end in a slash
[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 // An empty Dir is treated as ".".
34 type Dir string
35
36 func (d Dir) Open(name string) (File, error) {
37         if filepath.Separator != '/' && strings.ContainsRune(name, filepath.Separator) ||
38                 strings.Contains(name, "\x00") {
39                 return nil, errors.New("http: invalid character in file path")
40         }
41         dir := string(d)
42         if dir == "" {
43                 dir = "."
44         }
45         f, err := os.Open(filepath.Join(dir, filepath.FromSlash(path.Clean("/"+name))))
46         if err != nil {
47                 return nil, err
48         }
49         return f, nil
50 }
51
52 // A FileSystem implements access to a collection of named files.
53 // The elements in a file path are separated by slash ('/', U+002F)
54 // characters, regardless of host operating system convention.
55 type FileSystem interface {
56         Open(name string) (File, error)
57 }
58
59 // A File is returned by a FileSystem's Open method and can be
60 // served by the FileServer implementation.
61 //
62 // The methods should behave the same as those on an *os.File.
63 type File interface {
64         io.Closer
65         io.Reader
66         io.Seeker
67         Readdir(count int) ([]os.FileInfo, error)
68         Stat() (os.FileInfo, error)
69 }
70
71 func dirList(w ResponseWriter, f File) {
72         dirs, err := f.Readdir(-1)
73         if err != nil {
74                 // TODO: log err.Error() to the Server.ErrorLog, once it's possible
75                 // for a handler to get at its Server via the ResponseWriter. See
76                 // Issue 12438.
77                 Error(w, "Error reading directory", StatusInternalServerError)
78                 return
79         }
80         sort.Sort(byName(dirs))
81
82         w.Header().Set("Content-Type", "text/html; charset=utf-8")
83         fmt.Fprintf(w, "<pre>\n")
84         for _, d := range dirs {
85                 name := d.Name()
86                 if d.IsDir() {
87                         name += "/"
88                 }
89                 // name may contain '?' or '#', which must be escaped to remain
90                 // part of the URL path, and not indicate the start of a query
91                 // string or fragment.
92                 url := url.URL{Path: name}
93                 fmt.Fprintf(w, "<a href=\"%s\">%s</a>\n", url.String(), htmlReplacer.Replace(name))
94         }
95         fmt.Fprintf(w, "</pre>\n")
96 }
97
98 // ServeContent replies to the request using the content in the
99 // provided ReadSeeker. The main benefit of ServeContent over io.Copy
100 // is that it handles Range requests properly, sets the MIME type, and
101 // handles If-Modified-Since requests.
102 //
103 // If the response's Content-Type header is not set, ServeContent
104 // first tries to deduce the type from name's file extension and,
105 // if that fails, falls back to reading the first block of the content
106 // and passing it to DetectContentType.
107 // The name is otherwise unused; in particular it can be empty and is
108 // never sent in the response.
109 //
110 // If modtime is not the zero time or Unix epoch, ServeContent
111 // includes it in a Last-Modified header in the response. If the
112 // request includes an If-Modified-Since header, ServeContent uses
113 // modtime to decide whether the content needs to be sent at all.
114 //
115 // The content's Seek method must work: ServeContent uses
116 // a seek to the end of the content to determine its size.
117 //
118 // If the caller has set w's ETag header, ServeContent uses it to
119 // handle requests using If-Range and If-None-Match.
120 //
121 // Note that *os.File implements the io.ReadSeeker interface.
122 func ServeContent(w ResponseWriter, req *Request, name string, modtime time.Time, content io.ReadSeeker) {
123         sizeFunc := func() (int64, error) {
124                 size, err := content.Seek(0, os.SEEK_END)
125                 if err != nil {
126                         return 0, errSeeker
127                 }
128                 _, err = content.Seek(0, os.SEEK_SET)
129                 if err != nil {
130                         return 0, errSeeker
131                 }
132                 return size, nil
133         }
134         serveContent(w, req, name, modtime, sizeFunc, content)
135 }
136
137 // errSeeker is returned by ServeContent's sizeFunc when the content
138 // doesn't seek properly. The underlying Seeker's error text isn't
139 // included in the sizeFunc reply so it's not sent over HTTP to end
140 // users.
141 var errSeeker = errors.New("seeker can't seek")
142
143 // if name is empty, filename is unknown. (used for mime type, before sniffing)
144 // if modtime.IsZero(), modtime is unknown.
145 // content must be seeked to the beginning of the file.
146 // The sizeFunc is called at most once. Its error, if any, is sent in the HTTP response.
147 func serveContent(w ResponseWriter, r *Request, name string, modtime time.Time, sizeFunc func() (int64, error), content io.ReadSeeker) {
148         if checkLastModified(w, r, modtime) {
149                 return
150         }
151         rangeReq, done := checkETag(w, r, modtime)
152         if done {
153                 return
154         }
155
156         code := StatusOK
157
158         // If Content-Type isn't set, use the file's extension to find it, but
159         // if the Content-Type is unset explicitly, do not sniff the type.
160         ctypes, haveType := w.Header()["Content-Type"]
161         var ctype string
162         if !haveType {
163                 ctype = mime.TypeByExtension(filepath.Ext(name))
164                 if ctype == "" {
165                         // read a chunk to decide between utf-8 text and binary
166                         var buf [sniffLen]byte
167                         n, _ := io.ReadFull(content, buf[:])
168                         ctype = DetectContentType(buf[:n])
169                         _, err := content.Seek(0, os.SEEK_SET) // rewind to output whole file
170                         if err != nil {
171                                 Error(w, "seeker can't seek", StatusInternalServerError)
172                                 return
173                         }
174                 }
175                 w.Header().Set("Content-Type", ctype)
176         } else if len(ctypes) > 0 {
177                 ctype = ctypes[0]
178         }
179
180         size, err := sizeFunc()
181         if err != nil {
182                 Error(w, err.Error(), StatusInternalServerError)
183                 return
184         }
185
186         // handle Content-Range header.
187         sendSize := size
188         var sendContent io.Reader = content
189         if size >= 0 {
190                 ranges, err := parseRange(rangeReq, size)
191                 if err != nil {
192                         Error(w, err.Error(), StatusRequestedRangeNotSatisfiable)
193                         return
194                 }
195                 if sumRangesSize(ranges) > size {
196                         // The total number of bytes in all the ranges
197                         // is larger than the size of the file by
198                         // itself, so this is probably an attack, or a
199                         // dumb client. Ignore the range request.
200                         ranges = nil
201                 }
202                 switch {
203                 case len(ranges) == 1:
204                         // RFC 2616, Section 14.16:
205                         // "When an HTTP message includes the content of a single
206                         // range (for example, a response to a request for a
207                         // single range, or to a request for a set of ranges
208                         // that overlap without any holes), this content is
209                         // transmitted with a Content-Range header, and a
210                         // Content-Length header showing the number of bytes
211                         // actually transferred.
212                         // ...
213                         // A response to a request for a single range MUST NOT
214                         // be sent using the multipart/byteranges media type."
215                         ra := ranges[0]
216                         if _, err := content.Seek(ra.start, os.SEEK_SET); err != nil {
217                                 Error(w, err.Error(), StatusRequestedRangeNotSatisfiable)
218                                 return
219                         }
220                         sendSize = ra.length
221                         code = StatusPartialContent
222                         w.Header().Set("Content-Range", ra.contentRange(size))
223                 case len(ranges) > 1:
224                         sendSize = rangesMIMESize(ranges, ctype, size)
225                         code = StatusPartialContent
226
227                         pr, pw := io.Pipe()
228                         mw := multipart.NewWriter(pw)
229                         w.Header().Set("Content-Type", "multipart/byteranges; boundary="+mw.Boundary())
230                         sendContent = pr
231                         defer pr.Close() // cause writing goroutine to fail and exit if CopyN doesn't finish.
232                         go func() {
233                                 for _, ra := range ranges {
234                                         part, err := mw.CreatePart(ra.mimeHeader(ctype, size))
235                                         if err != nil {
236                                                 pw.CloseWithError(err)
237                                                 return
238                                         }
239                                         if _, err := content.Seek(ra.start, os.SEEK_SET); err != nil {
240                                                 pw.CloseWithError(err)
241                                                 return
242                                         }
243                                         if _, err := io.CopyN(part, content, ra.length); err != nil {
244                                                 pw.CloseWithError(err)
245                                                 return
246                                         }
247                                 }
248                                 mw.Close()
249                                 pw.Close()
250                         }()
251                 }
252
253                 w.Header().Set("Accept-Ranges", "bytes")
254                 if w.Header().Get("Content-Encoding") == "" {
255                         w.Header().Set("Content-Length", strconv.FormatInt(sendSize, 10))
256                 }
257         }
258
259         w.WriteHeader(code)
260
261         if r.Method != "HEAD" {
262                 io.CopyN(w, sendContent, sendSize)
263         }
264 }
265
266 var unixEpochTime = time.Unix(0, 0)
267
268 // modtime is the modification time of the resource to be served, or IsZero().
269 // return value is whether this request is now complete.
270 func checkLastModified(w ResponseWriter, r *Request, modtime time.Time) bool {
271         if modtime.IsZero() || modtime.Equal(unixEpochTime) {
272                 // If the file doesn't have a modtime (IsZero), or the modtime
273                 // is obviously garbage (Unix time == 0), then ignore modtimes
274                 // and don't process the If-Modified-Since header.
275                 return false
276         }
277
278         // The Date-Modified header truncates sub-second precision, so
279         // use mtime < t+1s instead of mtime <= t to check for unmodified.
280         if t, err := time.Parse(TimeFormat, r.Header.Get("If-Modified-Since")); err == nil && modtime.Before(t.Add(1*time.Second)) {
281                 h := w.Header()
282                 delete(h, "Content-Type")
283                 delete(h, "Content-Length")
284                 w.WriteHeader(StatusNotModified)
285                 return true
286         }
287         w.Header().Set("Last-Modified", modtime.UTC().Format(TimeFormat))
288         return false
289 }
290
291 // checkETag implements If-None-Match and If-Range checks.
292 //
293 // The ETag or modtime must have been previously set in the
294 // ResponseWriter's headers. The modtime is only compared at second
295 // granularity and may be the zero value to mean unknown.
296 //
297 // The return value is the effective request "Range" header to use and
298 // whether this request is now considered done.
299 func checkETag(w ResponseWriter, r *Request, modtime time.Time) (rangeReq string, done bool) {
300         etag := w.Header().get("Etag")
301         rangeReq = r.Header.get("Range")
302
303         // Invalidate the range request if the entity doesn't match the one
304         // the client was expecting.
305         // "If-Range: version" means "ignore the Range: header unless version matches the
306         // current file."
307         // We only support ETag versions.
308         // The caller must have set the ETag on the response already.
309         if ir := r.Header.get("If-Range"); ir != "" && ir != etag {
310                 // The If-Range value is typically the ETag value, but it may also be
311                 // the modtime date. See golang.org/issue/8367.
312                 timeMatches := false
313                 if !modtime.IsZero() {
314                         if t, err := ParseTime(ir); err == nil && t.Unix() == modtime.Unix() {
315                                 timeMatches = true
316                         }
317                 }
318                 if !timeMatches {
319                         rangeReq = ""
320                 }
321         }
322
323         if inm := r.Header.get("If-None-Match"); inm != "" {
324                 // Must know ETag.
325                 if etag == "" {
326                         return rangeReq, false
327                 }
328
329                 // TODO(bradfitz): non-GET/HEAD requests require more work:
330                 // sending a different status code on matches, and
331                 // also can't use weak cache validators (those with a "W/
332                 // prefix).  But most users of ServeContent will be using
333                 // it on GET or HEAD, so only support those for now.
334                 if r.Method != "GET" && r.Method != "HEAD" {
335                         return rangeReq, false
336                 }
337
338                 // TODO(bradfitz): deal with comma-separated or multiple-valued
339                 // list of If-None-match values. For now just handle the common
340                 // case of a single item.
341                 if inm == etag || inm == "*" {
342                         h := w.Header()
343                         delete(h, "Content-Type")
344                         delete(h, "Content-Length")
345                         w.WriteHeader(StatusNotModified)
346                         return "", true
347                 }
348         }
349         return rangeReq, false
350 }
351
352 // name is '/'-separated, not filepath.Separator.
353 func serveFile(w ResponseWriter, r *Request, fs FileSystem, name string, redirect bool) {
354         const indexPage = "/index.html"
355
356         // redirect .../index.html to .../
357         // can't use Redirect() because that would make the path absolute,
358         // which would be a problem running under StripPrefix
359         if strings.HasSuffix(r.URL.Path, indexPage) {
360                 localRedirect(w, r, "./")
361                 return
362         }
363
364         f, err := fs.Open(name)
365         if err != nil {
366                 msg, code := toHTTPError(err)
367                 Error(w, msg, code)
368                 return
369         }
370         defer f.Close()
371
372         d, err := f.Stat()
373         if err != nil {
374                 msg, code := toHTTPError(err)
375                 Error(w, msg, code)
376                 return
377         }
378
379         if redirect {
380                 // redirect to canonical path: / at end of directory url
381                 // r.URL.Path always begins with /
382                 url := r.URL.Path
383                 if d.IsDir() {
384                         if url[len(url)-1] != '/' {
385                                 localRedirect(w, r, path.Base(url)+"/")
386                                 return
387                         }
388                 } else {
389                         if url[len(url)-1] == '/' {
390                                 localRedirect(w, r, "../"+path.Base(url))
391                                 return
392                         }
393                 }
394         }
395
396         // redirect if the directory name doesn't end in a slash
397         if d.IsDir() {
398                 url := r.URL.Path
399                 if url[len(url)-1] != '/' {
400                         localRedirect(w, r, path.Base(url)+"/")
401                         return
402                 }
403         }
404
405         // use contents of index.html for directory, if present
406         if d.IsDir() {
407                 index := strings.TrimSuffix(name, "/") + indexPage
408                 ff, err := fs.Open(index)
409                 if err == nil {
410                         defer ff.Close()
411                         dd, err := ff.Stat()
412                         if err == nil {
413                                 name = index
414                                 d = dd
415                                 f = ff
416                         }
417                 }
418         }
419
420         // Still a directory? (we didn't find an index.html file)
421         if d.IsDir() {
422                 if checkLastModified(w, r, d.ModTime()) {
423                         return
424                 }
425                 dirList(w, f)
426                 return
427         }
428
429         // serveContent will check modification time
430         sizeFunc := func() (int64, error) { return d.Size(), nil }
431         serveContent(w, r, d.Name(), d.ModTime(), sizeFunc, f)
432 }
433
434 // toHTTPError returns a non-specific HTTP error message and status code
435 // for a given non-nil error value. It's important that toHTTPError does not
436 // actually return err.Error(), since msg and httpStatus are returned to users,
437 // and historically Go's ServeContent always returned just "404 Not Found" for
438 // all errors. We don't want to start leaking information in error messages.
439 func toHTTPError(err error) (msg string, httpStatus int) {
440         if os.IsNotExist(err) {
441                 return "404 page not found", StatusNotFound
442         }
443         if os.IsPermission(err) {
444                 return "403 Forbidden", StatusForbidden
445         }
446         // Default:
447         return "500 Internal Server Error", StatusInternalServerError
448 }
449
450 // localRedirect gives a Moved Permanently response.
451 // It does not convert relative paths to absolute paths like Redirect does.
452 func localRedirect(w ResponseWriter, r *Request, newPath string) {
453         if q := r.URL.RawQuery; q != "" {
454                 newPath += "?" + q
455         }
456         w.Header().Set("Location", newPath)
457         w.WriteHeader(StatusMovedPermanently)
458 }
459
460 // ServeFile replies to the request with the contents of the named
461 // file or directory.
462 //
463 // If the provided file or directory name is a relative path, it is
464 // interpreted relative to the current directory and may ascend to parent
465 // directories. If the provided name is constructed from user input, it
466 // should be sanitized before calling ServeFile. As a precaution, ServeFile
467 // will reject requests where r.URL.Path contains a ".." path element.
468 //
469 // As a special case, ServeFile redirects any request where r.URL.Path
470 // ends in "/index.html" to the same path, without the final
471 // "index.html". To avoid such redirects either modify the path or
472 // use ServeContent.
473 func ServeFile(w ResponseWriter, r *Request, name string) {
474         if containsDotDot(r.URL.Path) {
475                 // Too many programs use r.URL.Path to construct the argument to
476                 // serveFile. Reject the request under the assumption that happened
477                 // here and ".." may not be wanted.
478                 // Note that name might not contain "..", for example if code (still
479                 // incorrectly) used filepath.Join(myDir, r.URL.Path).
480                 Error(w, "invalid URL path", StatusBadRequest)
481                 return
482         }
483         dir, file := filepath.Split(name)
484         serveFile(w, r, Dir(dir), file, false)
485 }
486
487 func containsDotDot(v string) bool {
488         if !strings.Contains(v, "..") {
489                 return false
490         }
491         for _, ent := range strings.FieldsFunc(v, isSlashRune) {
492                 if ent == ".." {
493                         return true
494                 }
495         }
496         return false
497 }
498
499 func isSlashRune(r rune) bool { return r == '/' || r == '\\' }
500
501 type fileHandler struct {
502         root FileSystem
503 }
504
505 // FileServer returns a handler that serves HTTP requests
506 // with the contents of the file system rooted at root.
507 //
508 // To use the operating system's file system implementation,
509 // use http.Dir:
510 //
511 //     http.Handle("/", http.FileServer(http.Dir("/tmp")))
512 //
513 // As a special case, the returned file server redirects any request
514 // ending in "/index.html" to the same path, without the final
515 // "index.html".
516 func FileServer(root FileSystem) Handler {
517         return &fileHandler{root}
518 }
519
520 func (f *fileHandler) ServeHTTP(w ResponseWriter, r *Request) {
521         upath := r.URL.Path
522         if !strings.HasPrefix(upath, "/") {
523                 upath = "/" + upath
524                 r.URL.Path = upath
525         }
526         serveFile(w, r, f.root, path.Clean(upath), true)
527 }
528
529 // httpRange specifies the byte range to be sent to the client.
530 type httpRange struct {
531         start, length int64
532 }
533
534 func (r httpRange) contentRange(size int64) string {
535         return fmt.Sprintf("bytes %d-%d/%d", r.start, r.start+r.length-1, size)
536 }
537
538 func (r httpRange) mimeHeader(contentType string, size int64) textproto.MIMEHeader {
539         return textproto.MIMEHeader{
540                 "Content-Range": {r.contentRange(size)},
541                 "Content-Type":  {contentType},
542         }
543 }
544
545 // parseRange parses a Range header string as per RFC 2616.
546 func parseRange(s string, size int64) ([]httpRange, error) {
547         if s == "" {
548                 return nil, nil // header not present
549         }
550         const b = "bytes="
551         if !strings.HasPrefix(s, b) {
552                 return nil, errors.New("invalid range")
553         }
554         var ranges []httpRange
555         for _, ra := range strings.Split(s[len(b):], ",") {
556                 ra = strings.TrimSpace(ra)
557                 if ra == "" {
558                         continue
559                 }
560                 i := strings.Index(ra, "-")
561                 if i < 0 {
562                         return nil, errors.New("invalid range")
563                 }
564                 start, end := strings.TrimSpace(ra[:i]), strings.TrimSpace(ra[i+1:])
565                 var r httpRange
566                 if start == "" {
567                         // If no start is specified, end specifies the
568                         // range start relative to the end of the file.
569                         i, err := strconv.ParseInt(end, 10, 64)
570                         if err != nil {
571                                 return nil, errors.New("invalid range")
572                         }
573                         if i > size {
574                                 i = size
575                         }
576                         r.start = size - i
577                         r.length = size - r.start
578                 } else {
579                         i, err := strconv.ParseInt(start, 10, 64)
580                         if err != nil || i >= size || i < 0 {
581                                 return nil, errors.New("invalid range")
582                         }
583                         r.start = i
584                         if end == "" {
585                                 // If no end is specified, range extends to end of the file.
586                                 r.length = size - r.start
587                         } else {
588                                 i, err := strconv.ParseInt(end, 10, 64)
589                                 if err != nil || r.start > i {
590                                         return nil, errors.New("invalid range")
591                                 }
592                                 if i >= size {
593                                         i = size - 1
594                                 }
595                                 r.length = i - r.start + 1
596                         }
597                 }
598                 ranges = append(ranges, r)
599         }
600         return ranges, nil
601 }
602
603 // countingWriter counts how many bytes have been written to it.
604 type countingWriter int64
605
606 func (w *countingWriter) Write(p []byte) (n int, err error) {
607         *w += countingWriter(len(p))
608         return len(p), nil
609 }
610
611 // rangesMIMESize returns the number of bytes it takes to encode the
612 // provided ranges as a multipart response.
613 func rangesMIMESize(ranges []httpRange, contentType string, contentSize int64) (encSize int64) {
614         var w countingWriter
615         mw := multipart.NewWriter(&w)
616         for _, ra := range ranges {
617                 mw.CreatePart(ra.mimeHeader(contentType, contentSize))
618                 encSize += ra.length
619         }
620         mw.Close()
621         encSize += int64(w)
622         return
623 }
624
625 func sumRangesSize(ranges []httpRange) (size int64) {
626         for _, ra := range ranges {
627                 size += ra.length
628         }
629         return
630 }
631
632 type byName []os.FileInfo
633
634 func (s byName) Len() int           { return len(s) }
635 func (s byName) Less(i, j int) bool { return s[i].Name() < s[j].Name() }
636 func (s byName) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }