summaryrefslogtreecommitdiff
path: root/http/static.go
blob: bfcb87c2fd3f842d4910a02284d994437f0ae446 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package http

import (
	"net/http"
	"strings"
	"path"
	"github.com/sirupsen/logrus"
	"os"
	"path/filepath"
)

var (
	forbiddenFiles = []string{".php", ".htaccess"}
)

// staticServer serves static files
type staticServer struct {
	root http.Dir
}

// serve attempts to serve static file and returns true in case of success, will return false in case if file not
// found, not allowed or on read error.
func (svr *staticServer) serve(w http.ResponseWriter, r *http.Request) bool {
	fpath := r.URL.Path
	if !strings.HasPrefix(fpath, "/") {
		fpath = "/" + fpath
	}
	fpath = path.Clean(fpath)

	if svr.forbidden(fpath) {
		logrus.Warningf("attempt to access forbidden file %s", fpath) // todo: better logs
		return false
	}

	f, err := svr.root.Open(fpath)
	if err != nil {
		if !os.IsNotExist(err) {
			logrus.Error(err) //todo: rr or access error
		}

		return false
	}
	defer f.Close()

	d, err := f.Stat()
	if err != nil {
		logrus.Error(err) //todo: rr or access error
		return false
	}

	if d.IsDir() {
		// do not serve directories
		return false
	}

	http.ServeContent(w, r, d.Name(), d.ModTime(), f)
	return true
}

// forbidden returns true if file has forbidden extension.
func (svr *staticServer) forbidden(path string) bool {
	ext := strings.ToLower(filepath.Ext(path))
	for _, exl := range forbiddenFiles {
		if ext == exl {
			return true
		}
	}

	return false
}