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