caddy/caddyhttp/staticfiles/fileserver.go
Mateusz Gajewski 54c63002cc Feature #1282 - Support serving statically compressed .gz and .br files (#1289)
* Feature #1282 - Support pre-gzipped files

* Fix broken test cases

* Support brotli encoding as well

* Fix for #1276 - support integers and floats as metadata in markdown (#1278)

* Fix for #1276

* Use strconv.Format

* Use map[string]interface{} as variables

* One more file

* Always run all tests before commit

* Get rid of DocFlags

* Fix syntax in caddy.conf

* Update to Go 1.7.4

* Add send_timeout property to fastcgi directive.

* Convert rwc field on FCGIClient from type io.ReadWriteCloser to net.Conn.
* Return HTTP 504 to the client when a timeout occurs.
* In Handler.ServeHTTP(), close the connection before returning an HTTP
502/504.
* Refactor tests and add coverage.

* Return HTTP 504 when FastCGI connect times out.

* test: add unit test for #1283 (#1288)

* After review fixes

* Limit the number of restarts with systemd

* Prevent fd leak

* Prevent fd leak

* Refactor loops

* gofmt
2016-12-19 09:51:09 -07:00

233 lines
5.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package staticfiles
import (
"fmt"
"math/rand"
"net/http"
"os"
"path"
"path/filepath"
"runtime"
"strconv"
"strings"
)
// FileServer implements a production-ready file server
// and is the 'default' handler for all requests to Caddy.
// It simply loads and serves the URI requested. FileServer
// is adapted from the one in net/http by the Go authors.
// Significant modifications have been made.
//
// Original license:
//
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
type FileServer struct {
// Jailed disk access
Root http.FileSystem
// List of files to treat as "Not Found"
Hide []string
}
// ServeHTTP serves static files for r according to fs's configuration.
func (fs FileServer) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
// r.URL.Path has already been cleaned by Caddy.
if r.URL.Path == "" {
r.URL.Path = "/"
}
return fs.serveFile(w, r, r.URL.Path)
}
// serveFile writes the specified file to the HTTP response.
// name is '/'-separated, not filepath.Separator.
func (fs FileServer) serveFile(w http.ResponseWriter, r *http.Request, name string) (int, error) {
location := name
// Prevent absolute path access on Windows.
// TODO remove when stdlib http.Dir fixes this.
if runtime.GOOS == "windows" {
if filepath.IsAbs(name[1:]) {
return http.StatusNotFound, nil
}
}
f, err := fs.Root.Open(name)
if err != nil {
if os.IsNotExist(err) {
return http.StatusNotFound, nil
} else if os.IsPermission(err) {
return http.StatusForbidden, err
}
// Likely the server is under load and ran out of file descriptors
backoff := int(3 + rand.Int31()%3) // 35 seconds to prevent a stampede
w.Header().Set("Retry-After", strconv.Itoa(backoff))
return http.StatusServiceUnavailable, err
}
defer f.Close()
d, err := f.Stat()
if err != nil {
if os.IsNotExist(err) {
return http.StatusNotFound, nil
} else if os.IsPermission(err) {
return http.StatusForbidden, err
}
// Return a different status code than above so as to distinguish these cases
return http.StatusInternalServerError, err
}
// redirect to canonical path
url := r.URL.Path
if d.IsDir() {
// Ensure / at end of directory url
if !strings.HasSuffix(url, "/") {
Redirect(w, r, path.Base(url)+"/", http.StatusMovedPermanently)
return http.StatusMovedPermanently, nil
}
} else {
// Ensure no / at end of file url
if strings.HasSuffix(url, "/") {
Redirect(w, r, "../"+path.Base(url), http.StatusMovedPermanently)
return http.StatusMovedPermanently, nil
}
}
// use contents of an index file, if present, for directory
if d.IsDir() {
for _, indexPage := range IndexPages {
index := strings.TrimSuffix(name, "/") + "/" + indexPage
ff, err := fs.Root.Open(index)
if err != nil {
continue
}
// this defer does not leak fds because previous iterations
// of the loop must have had an err, so nothing to close
defer ff.Close()
dd, err := ff.Stat()
if err != nil {
ff.Close()
continue
}
// Close previous file - release fd immediately
f.Close()
d = dd
f = ff
location = index
break
}
}
// Still a directory? (we didn't find an index file)
// Return 404 to hide the fact that the folder exists
if d.IsDir() {
return http.StatusNotFound, nil
}
if fs.IsHidden(d) {
return http.StatusNotFound, nil
}
filename := d.Name()
for _, encoding := range staticEncodingPriority {
if !strings.Contains(r.Header.Get("Accept-Encoding"), encoding) {
continue
}
encodedFile, err := fs.Root.Open(location + staticEncoding[encoding])
if err != nil {
continue
}
encodedFileInfo, err := encodedFile.Stat()
if err != nil {
encodedFile.Close()
continue
}
// Close previous file - release fd
f.Close()
// Stat is needed for generating valid ETag
d = encodedFileInfo
// Encoded file will be served
f = encodedFile
w.Header().Add("Vary", "Accept-Encoding")
w.Header().Set("Content-Encoding", encoding)
defer f.Close()
break
}
// Experimental ETag header
e := fmt.Sprintf(`W/"%x-%x"`, d.ModTime().Unix(), d.Size())
w.Header().Set("ETag", e)
// Note: Errors generated by ServeContent are written immediately
// to the response. This usually only happens if seeking fails (rare).
http.ServeContent(w, r, filename, d.ModTime(), f)
return http.StatusOK, nil
}
// IsHidden checks if file with FileInfo d is on hide list.
func (fs FileServer) IsHidden(d os.FileInfo) bool {
// If the file is supposed to be hidden, return a 404
for _, hiddenPath := range fs.Hide {
// Check if the served file is exactly the hidden file.
if hFile, err := fs.Root.Open(hiddenPath); err == nil {
fs, _ := hFile.Stat()
hFile.Close()
if os.SameFile(d, fs) {
return true
}
}
}
return false
}
// Redirect sends an HTTP redirect to the client but will preserve
// the query string for the new path. Based on http.localRedirect
// from the Go standard library.
func Redirect(w http.ResponseWriter, r *http.Request, newPath string, statusCode int) {
if q := r.URL.RawQuery; q != "" {
newPath += "?" + q
}
http.Redirect(w, r, newPath, statusCode)
}
// IndexPages is a list of pages that may be understood as
// the "index" files to directories.
var IndexPages = []string{
"index.html",
"index.htm",
"index.txt",
"default.html",
"default.htm",
"default.txt",
}
// staticEncoding is a map of content-encoding to a file extension.
// If client accepts given encoding (via Accept-Encoding header) and compressed file with given extensions exists
// it will be served to the client instead of original one.
var staticEncoding = map[string]string{
"gzip": ".gz",
"br": ".br",
}
// staticEncodingPriority is a list of preferred static encodings (most efficient compression to least one).
var staticEncodingPriority = []string{
"br",
"gzip",
}