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