-
Notifications
You must be signed in to change notification settings - Fork 13
/
hashfs.go
215 lines (183 loc) · 5.42 KB
/
hashfs.go
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
package hashfs
import (
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"path"
"regexp"
"strconv"
"strings"
"sync"
)
// Ensure file system implements interface.
var _ fs.FS = (*FS)(nil)
// FS represents an fs.FS file system that can optionally use content addressable
// hashes in the filename. This allows the caller to aggressively cache the
// data since the filename will change if the data changes.
type FS struct {
fsys fs.FS
mu sync.RWMutex
m map[string]string // lookup (path to hash path)
r map[string][2]string // reverse lookup (hash path to path)
}
func NewFS(fsys fs.FS) *FS {
return &FS{
fsys: fsys,
m: make(map[string]string),
r: make(map[string][2]string),
}
}
// Open returns a reference to the named file.
// If name is a hash name then the underlying file is used.
func (fsys *FS) Open(name string) (fs.File, error) {
f, _, err := fsys.open(name)
return f, err
}
func (fsys *FS) open(name string) (_ fs.File, hash string, err error) {
// Parse filename to see if it contains a hash.
// If so, check if hash name matches.
base, hash := fsys.ParseName(name)
if hash != "" && fsys.HashName(base) == name {
name = base
}
f, err := fsys.fsys.Open(name)
return f, hash, err
}
// HashName returns the hash name for a path, if exists.
// Otherwise returns the original path.
func (fsys *FS) HashName(name string) string {
// Lookup cached formatted name, if exists.
fsys.mu.RLock()
if s := fsys.m[name]; s != "" {
fsys.mu.RUnlock()
return s
}
fsys.mu.RUnlock()
// Read file contents. Return original filename if we receive an error.
buf, err := fs.ReadFile(fsys.fsys, name)
if err != nil {
return name
}
// Compute hash and build filename.
hash := sha256.Sum256(buf)
hashhex := hex.EncodeToString(hash[:])
hashname := FormatName(name, hashhex)
// Store in lookups.
fsys.mu.Lock()
fsys.m[name] = hashname
fsys.r[hashname] = [2]string{name, hashhex}
fsys.mu.Unlock()
return hashname
}
// FormatName returns a hash name that inserts hash before the filename's
// extension. If no extension exists on filename then the hash is appended.
// Returns blank string the original filename if hash is blank. Returns a blank
// string if the filename is blank.
func FormatName(filename, hash string) string {
if filename == "" {
return ""
} else if hash == "" {
return filename
}
dir, base := path.Split(filename)
if i := strings.Index(base, "."); i != -1 {
return path.Join(dir, fmt.Sprintf("%s-%s%s", base[:i], hash, base[i:]))
}
return path.Join(dir, fmt.Sprintf("%s-%s", base, hash))
}
// ParseName splits formatted hash filename into its base & hash components.
func (fsys *FS) ParseName(filename string) (base, hash string) {
fsys.mu.RLock()
defer fsys.mu.RUnlock()
if hashed, ok := fsys.r[filename]; ok {
return hashed[0], hashed[1]
}
return ParseName(filename)
}
// ParseName splits formatted hash filename into its base & hash components.
func ParseName(filename string) (base, hash string) {
if filename == "" {
return "", ""
}
dir, base := path.Split(filename)
// Extract pre-hash & extension.
pre, ext := base, ""
if i := strings.Index(base, "."); i != -1 {
pre = base[:i]
ext = base[i:]
}
// If prehash doesn't contain the hash, then exit.
if !hashSuffixRegex.MatchString(pre) {
return filename, ""
}
return path.Join(dir, pre[:len(pre)-65]+ext), pre[len(pre)-64:]
}
var hashSuffixRegex = regexp.MustCompile(`-[0-9a-f]{64}`)
// FileServer returns an http.Handler for serving FS files. It provides a
// simplified implementation of http.FileServer which is used to aggressively
// cache files on the client since the file hash is in the filename.
//
// Because FileServer is focused on small known path files, several features
// of http.FileServer have been removed including canonicalizing directories,
// defaulting index.html pages, precondition checks, & content range headers.
func FileServer(fsys fs.FS) http.Handler {
hfsys, ok := fsys.(*FS)
if !ok {
hfsys = NewFS(fsys)
}
return &fsHandler{fsys: hfsys}
}
type fsHandler struct {
fsys *FS
}
func (h *fsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Clean up filename based on URL path.
filename := r.URL.Path
if filename == "/" {
filename = "."
} else {
filename = strings.TrimPrefix(filename, "/")
}
filename = path.Clean(filename)
// Read file from attached file system.
f, hash, err := h.fsys.open(filename)
if errors.Is(err, fs.ErrNotExist) {
http.Error(w, "404 page not found", http.StatusNotFound)
return
} else if err != nil {
http.Error(w, "500 Internal Server Error", http.StatusInternalServerError)
return
}
defer f.Close()
// Fetch file info. Disallow directories from being displayed.
fi, err := f.Stat()
if err != nil {
http.Error(w, "500 Internal Server Error", http.StatusInternalServerError)
return
} else if fi.IsDir() {
http.Error(w, "403 Forbidden", http.StatusForbidden)
return
}
// Cache the file aggressively if the file contains a hash.
if hash != "" {
w.Header().Set("Cache-Control", `public, max-age=31536000`)
w.Header().Set("ETag", "\""+hash+"\"")
}
// Flush header and write content.
switch f := f.(type) {
case io.ReadSeeker:
http.ServeContent(w, r, filename, fi.ModTime(), f.(io.ReadSeeker))
default:
// Set content length.
w.Header().Set("Content-Length", strconv.FormatInt(fi.Size(), 10))
// Flush header and write content.
w.WriteHeader(http.StatusOK)
if r.Method != "HEAD" {
io.Copy(w, f)
}
}
}