Debian Codegraph @

modules/caddyhttp/fileserver/staticfiles.go

raw symbols SCIP
1 // Copyright 2015 Matthew Holt and The Caddy Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package fileserver
16
17 import (
18 "bytes"
19 "errors"
20 "fmt"
21 "io"
22 "io/fs"
23 weakrand "math/rand/v2"
24 "mime"
25 "net/http"
26 "os"
27 "path"
28 "path/filepath"
29 "runtime"
30 "strconv"
31 "strings"
32 "time"
33
34 "go.uber.org/zap"
35 "go.uber.org/zap/zapcore"
36
37 "github.com/caddyserver/caddy/v2"
38 "github.com/caddyserver/caddy/v2/modules/caddyhttp"
39 "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode"
40 )
41
42 func init() {
43 caddy.RegisterModule(FileServer{})
44 }
45
46 // FileServer implements a handler that serves static files.
47 //
48 // The path of the file to serve is constructed by joining the site root
49 // and the sanitized request path. Any and all files within the root and
50 // links with targets outside the site root may therefore be accessed.
51 // For example, with a site root of `/www`, requests to `/foo/bar.txt`
52 // will serve the file at `/www/foo/bar.txt`.
53 //
54 // The request path is sanitized using the Go standard library's
55 // path.Clean() function (https://pkg.go.dev/path#Clean) before being
56 // joined to the root. Request paths must be valid and well-formed.
57 //
58 // For requests that access directories instead of regular files,
59 // Caddy will attempt to serve an index file if present. For example,
60 // a request to `/dir/` will attempt to serve `/dir/index.html` if
61 // it exists. The index file names to try are configurable. If a
62 // requested directory does not have an index file, Caddy writes a
63 // 404 response. Alternatively, file browsing can be enabled with
64 // the "browse" parameter which shows a list of files when directories
65 // are requested if no index file is present. If "browse" is enabled,
66 // Caddy may serve a JSON array of the directory listing when the `Accept`
67 // header mentions `application/json` with the following structure:
68 //
69 // [{
70 // "name": "",
71 // "size": 0,
72 // "url": "",
73 // "mod_time": "",
74 // "mode": 0,
75 // "is_dir": false,
76 // "is_symlink": false
77 // }]
78 //
79 // with the `url` being relative to the request path and `mod_time` in the RFC 3339 format
80 // with sub-second precision. For any other value for the `Accept` header, the
81 // respective browse template is executed with `Content-Type: text/html`.
82 //
83 // By default, this handler will canonicalize URIs so that requests to
84 // directories end with a slash, but requests to regular files do not.
85 // This is enforced with HTTP redirects automatically and can be disabled.
86 // Canonicalization redirects are not issued, however, if a URI rewrite
87 // modified the last component of the path (the filename).
88 //
89 // This handler sets the Etag and Last-Modified headers for static files.
90 // It does not perform MIME sniffing to determine Content-Type based on
91 // contents, but does use the extension (if known); see the Go docs for
92 // details: https://pkg.go.dev/mime#TypeByExtension
93 //
94 // The file server properly handles requests with If-Match,
95 // If-Unmodified-Since, If-Modified-Since, If-None-Match, Range, and
96 // If-Range headers. It includes the file's modification time in the
97 // Last-Modified header of the response.
98 type FileServer struct {
99 // The file system implementation to use. By default, Caddy uses the local
100 // disk file system.
101 //
102 // if a non default filesystem is used, it must be first be registered in the globals section.
103 FileSystem string `json:"fs,omitempty"`
104
105 // The path to the root of the site. Default is `{http.vars.root}` if set,
106 // or current working directory otherwise. This should be a trusted value.
107 //
108 // Note that a site root is not a sandbox. Although the file server does
109 // sanitize the request URI to prevent directory traversal, files (including
110 // links) within the site root may be directly accessed based on the request
111 // path. Files and folders within the root should be secure and trustworthy.
112 Root string `json:"root,omitempty"`
113
114 // A list of files or folders to hide; the file server will pretend as if
115 // they don't exist. Accepts globular patterns like `*.ext` or `/foo/*/bar`
116 // as well as placeholders. Because site roots can be dynamic, this list
117 // uses file system paths, not request paths. To clarify, the base of
118 // relative paths is the current working directory, NOT the site root.
119 //
120 // Entries without a path separator (`/` or `\` depending on OS) will match
121 // any file or directory of that name regardless of its path. To hide only a
122 // specific file with a name that may not be unique, always use a path
123 // separator. For example, to hide all files or folder trees named "hidden",
124 // put "hidden" in the list. To hide only ./hidden, put "./hidden" in the list.
125 //
126 // When possible, all paths are resolved to their absolute form before
127 // comparisons are made. For maximum clarity and explicitness, use complete,
128 // absolute paths; or, for greater portability, use relative paths instead.
129 //
130 // Note that hide comparisons are case-sensitive. On case-insensitive
131 // filesystems, requests with different path casing may still resolve to the
132 // same file or directory on disk, so hide should not be treated as a
133 // security boundary for sensitive paths.
134 Hide []string `json:"hide,omitempty"`
135
136 // The names of files to try as index files if a folder is requested.
137 // Default: index.html, index.txt.
138 IndexNames []string `json:"index_names,omitempty"`
139
140 // Enables file listings if a directory was requested and no index
141 // file is present.
142 Browse *Browse `json:"browse,omitempty"`
143
144 // Use redirects to enforce trailing slashes for directories, or to
145 // remove trailing slash from URIs for files. Default is true.
146 //
147 // Canonicalization will not happen if the last element of the request's
148 // path (the filename) is changed in an internal rewrite, to avoid
149 // clobbering the explicit rewrite with implicit behavior.
150 CanonicalURIs *bool `json:"canonical_uris,omitempty"`
151
152 // Override the status code written when successfully serving a file.
153 // Particularly useful when explicitly serving a file as display for
154 // an error, like a 404 page. A placeholder may be used. By default,
155 // the status code will typically be 200, or 206 for partial content.
156 StatusCode caddyhttp.WeakString `json:"status_code,omitempty"`
157
158 // If pass-thru mode is enabled and a requested file is not found,
159 // it will invoke the next handler in the chain instead of returning
160 // a 404 error. By default, this is false (disabled).
161 PassThru bool `json:"pass_thru,omitempty"`
162
163 // Selection of encoders to use to check for precompressed files.
164 PrecompressedRaw caddy.ModuleMap `json:"precompressed,omitempty" caddy:"namespace=http.precompressed"`
165
166 // If the client has no strong preference (q-factor), choose these encodings in order.
167 // If no order specified here, the first encoding from the Accept-Encoding header
168 // that both client and server support is used
169 PrecompressedOrder []string `json:"precompressed_order,omitempty"`
170 precompressors map[string]encode.Precompressed
171
172 // List of file extensions to try to read Etags from.
173 // If set, file Etags will be read from sidecar files
174 // with any of these suffixes, instead of generating
175 // our own Etag.
176 // Keep in mind that the Etag values in the files have to be quoted as per RFC7232.
177 // See https://datatracker.ietf.org/doc/html/rfc7232#section-2.3 for a few examples.
178 EtagFileExtensions []string `json:"etag_file_extensions,omitempty"`
179
180 fsmap caddy.FileSystems
181
182 logger *zap.Logger
183 }
184
185 // CaddyModule returns the Caddy module information.
186 func (FileServer) CaddyModule() caddy.ModuleInfo {
187 return caddy.ModuleInfo{
188 ID: "http.handlers.file_server",
189 New: func() caddy.Module { return new(FileServer) },
190 }
191 }
192
193 // Provision sets up the static files responder.
194 func (fsrv *FileServer) Provision(ctx caddy.Context) error {
195 fsrv.logger = ctx.Logger()
196
197 fsrv.fsmap = ctx.FileSystems()
198
199 if fsrv.FileSystem == "" {
200 fsrv.FileSystem = "{http.vars.fs}"
201 }
202
203 if fsrv.Root == "" {
204 fsrv.Root = "{http.vars.root}"
205 }
206
207 if fsrv.IndexNames == nil {
208 fsrv.IndexNames = defaultIndexNames
209 }
210
211 // for hide paths that are static (i.e. no placeholders), we can transform them into
212 // absolute paths before the server starts for very slight performance improvement
213 for i, h := range fsrv.Hide {
214 if !strings.Contains(h, "{") && strings.Contains(h, separator) {
215 if abs, err := caddy.FastAbs(h); err == nil {
216 fsrv.Hide[i] = abs
217 }
218 }
219 }
220
221 // support precompressed sidecar files
222 mods, err := ctx.LoadModule(fsrv, "PrecompressedRaw")
223 if err != nil {
224 return fmt.Errorf("loading encoder modules: %v", err)
225 }
226 for modName, modIface := range mods.(map[string]any) {
227 p, ok := modIface.(encode.Precompressed)
228 if !ok {
229 return fmt.Errorf("module %s is not precompressor", modName)
230 }
231 ae := p.AcceptEncoding()
232 if ae == "" {
233 return fmt.Errorf("precompressor does not specify an Accept-Encoding value")
234 }
235 suffix := p.Suffix()
236 if suffix == "" {
237 return fmt.Errorf("precompressor does not specify a Suffix value")
238 }
239 if _, ok := fsrv.precompressors[ae]; ok {
240 return fmt.Errorf("precompressor already added: %s", ae)
241 }
242 if fsrv.precompressors == nil {
243 fsrv.precompressors = make(map[string]encode.Precompressed)
244 }
245 fsrv.precompressors[ae] = p
246 }
247
248 if fsrv.Browse != nil {
249 // check sort options
250 for idx, sortOption := range fsrv.Browse.SortOptions {
251 switch idx {
252 case 0:
253 if sortOption != sortByName && sortOption != sortByNameDirFirst && sortOption != sortBySize && sortOption != sortByTime {
254 return fmt.Errorf("the first option must be one of the following: %s, %s, %s, %s, but got %s", sortByName, sortByNameDirFirst, sortBySize, sortByTime, sortOption)
255 }
256 case 1:
257 if sortOption != sortOrderAsc && sortOption != sortOrderDesc {
258 return fmt.Errorf("the second option must be one of the following: %s, %s, but got %s", sortOrderAsc, sortOrderDesc, sortOption)
259 }
260 default:
261 return fmt.Errorf("only max 2 sort options are allowed, but got %d", idx+1)
262 }
263 }
264 }
265
266 return nil
267 }
268
269 func (fsrv *FileServer) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
270 repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
271
272 if runtime.GOOS == "windows" {
273 // reject paths with Alternate Data Streams (ADS)
274 if strings.Contains(r.URL.Path, ":") {
275 return caddyhttp.Error(http.StatusBadRequest, fmt.Errorf("illegal ADS path"))
276 }
277 // reject paths with "8.3" short names
278 trimmedPath := strings.TrimRight(r.URL.Path, ". ") // Windows ignores trailing dots and spaces, sigh
279 if len(path.Base(trimmedPath)) <= 12 && strings.Contains(trimmedPath, "~") {
280 return caddyhttp.Error(http.StatusBadRequest, fmt.Errorf("illegal short name"))
281 }
282 // both of those could bypass file hiding or possibly leak information even if the file is not hidden
283 }
284
285 filesToHide := fsrv.transformHidePaths(repl)
286
287 root := repl.ReplaceAll(fsrv.Root, ".")
288 fsName := repl.ReplaceAll(fsrv.FileSystem, "")
289
290 fileSystem, ok := fsrv.fsmap.Get(fsName)
291 if !ok {
292 return caddyhttp.Error(http.StatusNotFound, fmt.Errorf("filesystem not found"))
293 }
294
295 // remove any trailing `/` as it breaks fs.ValidPath() in the stdlib
296 filename := strings.TrimSuffix(caddyhttp.SanitizedPathJoin(root, r.URL.Path), "/")
297
298 if c := fsrv.logger.Check(zapcore.DebugLevel, "sanitized path join"); c != nil {
299 c.Write(
300 zap.String("site_root", root),
301 zap.String("fs", fsName),
302 zap.String("request_path", r.URL.Path),
303 zap.String("result", filename),
304 )
305 }
306
307 // get information about the file
308 info, err := fs.Stat(fileSystem, filename)
309 if err != nil {
310 err = fsrv.mapDirOpenError(fileSystem, err, filename)
311 if errors.Is(err, fs.ErrNotExist) {
312 return fsrv.notFound(w, r, next)
313 } else if errors.Is(err, fs.ErrInvalid) {
314 return caddyhttp.Error(http.StatusBadRequest, err)
315 } else if errors.Is(err, fs.ErrPermission) {
316 return caddyhttp.Error(http.StatusForbidden, err)
317 }
318 return caddyhttp.Error(http.StatusInternalServerError, err)
319 }
320
321 // if the request mapped to a directory, see if
322 // there is an index file we can serve
323 var implicitIndexFile bool
324 if info.IsDir() && len(fsrv.IndexNames) > 0 {
325 for _, indexPage := range fsrv.IndexNames {
326 indexPage := repl.ReplaceAll(indexPage, "")
327 indexPath := caddyhttp.SanitizedPathJoin(filename, indexPage)
328 if fileHidden(indexPath, filesToHide) {
329 // pretend this file doesn't exist
330 if c := fsrv.logger.Check(zapcore.DebugLevel, "hiding index file"); c != nil {
331 c.Write(
332 zap.String("filename", indexPath),
333 zap.Strings("files_to_hide", filesToHide),
334 )
335 }
336 continue
337 }
338
339 indexInfo, err := fs.Stat(fileSystem, indexPath)
340 if err != nil {
341 continue
342 }
343
344 // don't rewrite the request path to append
345 // the index file, because we might need to
346 // do a canonical-URL redirect below based
347 // on the URL as-is
348
349 // we've chosen to use this index file,
350 // so replace the last file info and path
351 // with that of the index file
352 info = indexInfo
353 filename = indexPath
354 implicitIndexFile = true
355 if c := fsrv.logger.Check(zapcore.DebugLevel, "located index file"); c != nil {
356 c.Write(zap.String("filename", filename))
357 }
358 break
359 }
360 }
361
362 // if still referencing a directory, delegate
363 // to browse or return an error
364 if info.IsDir() {
365 if c := fsrv.logger.Check(zapcore.DebugLevel, "no index file in directory"); c != nil {
366 c.Write(
367 zap.String("path", filename),
368 zap.Strings("index_filenames", fsrv.IndexNames),
369 )
370 }
371 if fsrv.Browse != nil && !fileHidden(filename, filesToHide) {
372 return fsrv.serveBrowse(fileSystem, root, filename, w, r, next)
373 }
374 return fsrv.notFound(w, r, next)
375 }
376
377 // one last check to ensure the file isn't hidden (we might
378 // have changed the filename from when we last checked)
379 if fileHidden(filename, filesToHide) {
380 if c := fsrv.logger.Check(zapcore.DebugLevel, "hiding file"); c != nil {
381 c.Write(
382 zap.String("filename", filename),
383 zap.Strings("files_to_hide", filesToHide),
384 )
385 }
386 return fsrv.notFound(w, r, next)
387 }
388
389 // if URL canonicalization is enabled, we need to enforce trailing
390 // slash convention: if a directory, trailing slash; if a file, no
391 // trailing slash - not enforcing this can break relative hrefs
392 // in HTML (see https://github.com/caddyserver/caddy/issues/2741)
393 if fsrv.CanonicalURIs == nil || *fsrv.CanonicalURIs {
394 // Only redirect if the last element of the path (the filename) was not
395 // rewritten; if the admin wanted to rewrite to the canonical path, they
396 // would have, and we have to be very careful not to introduce unwanted
397 // redirects and especially redirect loops!
398 // See https://github.com/caddyserver/caddy/issues/4205.
399 origReq := r.Context().Value(caddyhttp.OriginalRequestCtxKey).(http.Request)
400 if path.Base(origReq.URL.Path) == path.Base(r.URL.Path) {
401 if implicitIndexFile && !strings.HasSuffix(origReq.URL.Path, "/") {
402 to := origReq.URL.Path + "/"
403 if c := fsrv.logger.Check(zapcore.DebugLevel, "redirecting to canonical URI (adding trailing slash for directory"); c != nil {
404 c.Write(
405 zap.String("from_path", origReq.URL.Path),
406 zap.String("to_path", to),
407 )
408 }
409 return redirect(w, r, to)
410 } else if !implicitIndexFile && strings.HasSuffix(origReq.URL.Path, "/") {
411 to := origReq.URL.Path[:len(origReq.URL.Path)-1]
412 if c := fsrv.logger.Check(zapcore.DebugLevel, "redirecting to canonical URI (removing trailing slash for file"); c != nil {
413 c.Write(
414 zap.String("from_path", origReq.URL.Path),
415 zap.String("to_path", to),
416 )
417 }
418 return redirect(w, r, to)
419 }
420 }
421 }
422
423 var file fs.File
424 respHeader := w.Header()
425
426 // etag is usually unset, but if the user knows what they're doing, let them override it
427 etag := respHeader.Get("Etag")
428
429 // static file responses are often compressed, either on-the-fly
430 // or with precompressed sidecar files; in any case, the headers
431 // should contain "Vary: Accept-Encoding" even when not compressed
432 // so caches can craft a reliable key (according to REDbot results)
433 // see #5849
434 respHeader.Add("Vary", "Accept-Encoding")
435
436 // check for precompressed files
437 for _, ae := range encode.AcceptedEncodings(r, fsrv.PrecompressedOrder) {
438 precompress, ok := fsrv.precompressors[ae]
439 if !ok {
440 continue
441 }
442 compressedFilename := filename + precompress.Suffix()
443 compressedInfo, err := fs.Stat(fileSystem, compressedFilename)
444 if err != nil || compressedInfo.IsDir() {
445 if c := fsrv.logger.Check(zapcore.DebugLevel, "precompressed file not accessible"); c != nil {
446 c.Write(zap.String("filename", compressedFilename), zap.Error(err))
447 }
448 continue
449 }
450 if c := fsrv.logger.Check(zapcore.DebugLevel, "opening compressed sidecar file"); c != nil {
451 c.Write(zap.String("filename", compressedFilename), zap.Error(err))
452 }
453 file, err = fsrv.openFile(fileSystem, compressedFilename, w)
454 if err != nil {
455 if c := fsrv.logger.Check(zapcore.WarnLevel, "opening precompressed file failed"); c != nil {
456 c.Write(zap.String("filename", compressedFilename), zap.Error(err))
457 }
458 if caddyErr, ok := err.(caddyhttp.HandlerError); ok && caddyErr.StatusCode == http.StatusServiceUnavailable {
459 return err
460 }
461 file = nil
462 continue
463 }
464 defer file.Close()
465 respHeader.Set("Content-Encoding", ae)
466
467 // stdlib won't set Content-Length for non-range requests if Content-Encoding is set.
468 // see: https://github.com/caddyserver/caddy/issues/7040
469 // Setting the Range header manually will result in 206 Partial Content.
470 // see: https://github.com/caddyserver/caddy/issues/7250
471 if r.Header.Get("Range") == "" {
472 respHeader.Set("Content-Length", strconv.FormatInt(compressedInfo.Size(), 10))
473 }
474
475 // try to get the etag from pre computed files if an etag suffix list was provided
476 if etag == "" && fsrv.EtagFileExtensions != nil {
477 etag, err = fsrv.getEtagFromFile(fileSystem, compressedFilename)
478 if err != nil {
479 return err
480 }
481 }
482
483 // don't assign info = compressedInfo because sidecars are kind
484 // of transparent; however we do need to set the Etag:
485 // https://caddy.community/t/gzipped-sidecar-file-wrong-same-etag/16793
486 if etag == "" {
487 etag = calculateEtag(compressedInfo)
488 }
489
490 break
491 }
492
493 // no precompressed file found, use the actual file
494 if file == nil {
495 if c := fsrv.logger.Check(zapcore.DebugLevel, "opening file"); c != nil {
496 c.Write(zap.String("filename", filename))
497 }
498
499 // open the file
500 file, err = fsrv.openFile(fileSystem, filename, w)
501 if err != nil {
502 if herr, ok := err.(caddyhttp.HandlerError); ok &&
503 herr.StatusCode == http.StatusNotFound {
504 return fsrv.notFound(w, r, next)
505 }
506 return err // error is already structured
507 }
508 defer file.Close()
509 // try to get the etag from pre computed files if an etag suffix list was provided
510 if etag == "" && fsrv.EtagFileExtensions != nil {
511 etag, err = fsrv.getEtagFromFile(fileSystem, filename)
512 if err != nil {
513 return err
514 }
515 }
516 if etag == "" {
517 etag = calculateEtag(info)
518 }
519 }
520
521 // at this point, we're serving a file; Go std lib supports only
522 // GET and HEAD, which is sensible for a static file server - reject
523 // any other methods (see issue #5166)
524 if r.Method != http.MethodGet && r.Method != http.MethodHead {
525 // if we're in an error context, then it doesn't make sense
526 // to repeat the error; just continue because we're probably
527 // trying to write an error page response (see issue #5703)
528 if _, ok := r.Context().Value(caddyhttp.ErrorCtxKey).(error); !ok {
529 respHeader.Add("Allow", "GET, HEAD")
530 return caddyhttp.Error(http.StatusMethodNotAllowed, nil)
531 }
532 }
533
534 // set the Etag - note that a conditional If-None-Match request is handled
535 // by http.ServeContent below, which checks against this Etag value
536 if etag != "" {
537 respHeader.Set("Etag", etag)
538 }
539
540 if respHeader.Get("Content-Type") == "" {
541 mtyp := mime.TypeByExtension(filepath.Ext(filename))
542 if mtyp == "" {
543 // do not allow Go to sniff the content-type; see https://www.youtube.com/watch?v=8t8JYpt0egE
544 respHeader["Content-Type"] = nil
545 } else {
546 respHeader.Set("Content-Type", mtyp)
547 }
548 }
549
550 var statusCodeOverride int
551
552 // if this handler exists in an error context (i.e. is part of a
553 // handler chain that is supposed to handle a previous error),
554 // we should set status code to the one from the error instead
555 // of letting http.ServeContent set the default (usually 200)
556 if reqErr, ok := r.Context().Value(caddyhttp.ErrorCtxKey).(error); ok {
557 statusCodeOverride = http.StatusInternalServerError
558 if handlerErr, ok := reqErr.(caddyhttp.HandlerError); ok {
559 if handlerErr.StatusCode > 0 {
560 statusCodeOverride = handlerErr.StatusCode
561 }
562 }
563 }
564
565 // if a status code override is configured, run the replacer on it
566 if codeStr := fsrv.StatusCode.String(); codeStr != "" {
567 statusCodeOverride, err = strconv.Atoi(repl.ReplaceAll(codeStr, ""))
568 if err != nil {
569 return caddyhttp.Error(http.StatusInternalServerError, err)
570 }
571 }
572
573 // if we do have an override from the previous two parts, then
574 // we wrap the response writer to intercept the WriteHeader call
575 if statusCodeOverride > 0 {
576 w = statusOverrideResponseWriter{ResponseWriter: w, code: statusCodeOverride}
577 }
578
579 // let the standard library do what it does best; note, however,
580 // that errors generated by ServeContent are written immediately
581 // to the response, so we cannot handle them (but errors there
582 // are rare)
583 //
584 // There are a few file modification times that aren't useful
585 // to send in Last-Modified headers, but the golang http library only
586 // omits Last-Modified headers for the Unix epoch time. So, force
587 // the modification time to the epoch time if it's not useful.
588 zeroTime := time.Time{}
589 modTime := info.ModTime()
590 if !usefulModTime(modTime) {
591 modTime = zeroTime
592 }
593 http.ServeContent(w, r, info.Name(), modTime, file.(io.ReadSeeker))
594
595 return nil
596 }
597
598 // openFile opens the file at the given filename. If there was an error,
599 // the response is configured to inform the client how to best handle it
600 // and a well-described handler error is returned (do not wrap the
601 // returned error value).
602 func (fsrv *FileServer) openFile(fileSystem fs.FS, filename string, w http.ResponseWriter) (fs.File, error) {
603 file, err := fileSystem.Open(filename)
604 if err != nil {
605 err = fsrv.mapDirOpenError(fileSystem, err, filename)
606 if errors.Is(err, fs.ErrNotExist) {
607 if c := fsrv.logger.Check(zapcore.DebugLevel, "file not found"); c != nil {
608 c.Write(zap.String("filename", filename), zap.Error(err))
609 }
610 return nil, caddyhttp.Error(http.StatusNotFound, err)
611 } else if errors.Is(err, fs.ErrPermission) {
612 if c := fsrv.logger.Check(zapcore.DebugLevel, "permission denied"); c != nil {
613 c.Write(zap.String("filename", filename), zap.Error(err))
614 }
615 return nil, caddyhttp.Error(http.StatusForbidden, err)
616 }
617 // maybe the server is under load and ran out of file descriptors?
618 // have client wait arbitrary seconds to help prevent a stampede
619 //nolint:gosec
620 backoff := weakrand.IntN(maxBackoff-minBackoff) + minBackoff
621 w.Header().Set("Retry-After", strconv.Itoa(backoff))
622 if c := fsrv.logger.Check(zapcore.DebugLevel, "retry after backoff"); c != nil {
623 c.Write(zap.String("filename", filename), zap.Int("backoff", backoff), zap.Error(err))
624 }
625 return nil, caddyhttp.Error(http.StatusServiceUnavailable, err)
626 }
627 return file, nil
628 }
629
630 // mapDirOpenError maps the provided non-nil error from opening name
631 // to a possibly better non-nil error. In particular, it turns OS-specific errors
632 // about opening files in non-directories into os.ErrNotExist. See golang/go#18984.
633 // Adapted from the Go standard library; originally written by Nathaniel Caza.
634 // https://go-review.googlesource.com/c/go/+/36635/
635 // https://go-review.googlesource.com/c/go/+/36804/
636 func (fsrv *FileServer) mapDirOpenError(fileSystem fs.FS, originalErr error, name string) error {
637 if errors.Is(originalErr, fs.ErrNotExist) || errors.Is(originalErr, fs.ErrPermission) {
638 return originalErr
639 }
640
641 var pathErr *fs.PathError
642 if errors.As(originalErr, &pathErr) {
643 return fs.ErrInvalid
644 }
645
646 parts := strings.Split(name, separator)
647 for i := range parts {
648 if parts[i] == "" {
649 continue
650 }
651 fi, err := fs.Stat(fileSystem, strings.Join(parts[:i+1], separator))
652 if err != nil {
653 return originalErr
654 }
655 if !fi.IsDir() {
656 return fs.ErrNotExist
657 }
658 }
659
660 return originalErr
661 }
662
663 // transformHidePaths performs replacements for all the elements of fsrv.Hide and
664 // makes them absolute paths (if they contain a path separator), then returns a
665 // new list of the transformed values.
666 func (fsrv *FileServer) transformHidePaths(repl *caddy.Replacer) []string {
667 hide := make([]string, len(fsrv.Hide))
668 for i := range fsrv.Hide {
669 hide[i] = repl.ReplaceAll(fsrv.Hide[i], "")
670 if strings.Contains(hide[i], separator) {
671 abs, err := caddy.FastAbs(hide[i])
672 if err == nil {
673 hide[i] = abs
674 }
675 }
676 }
677 return hide
678 }
679
680 // fileHidden returns true if filename is hidden according to the hide list.
681 // filename must be a relative or absolute file system path, not a request
682 // URI path. It is expected that all the paths in the hide list are absolute
683 // paths or are singular filenames (without a path separator).
684 func fileHidden(filename string, hide []string) bool {
685 if len(hide) == 0 {
686 return false
687 }
688
689 // all path comparisons use the complete absolute path if possible
690 filenameAbs, err := caddy.FastAbs(filename)
691 if err == nil {
692 filename = filenameAbs
693 }
694
695 var components []string
696
697 for _, h := range hide {
698 if !strings.Contains(h, separator) {
699 // if there is no separator in h, then we assume the user
700 // wants to hide any files or folders that match that
701 // name; thus we have to compare against each component
702 // of the filename, e.g. hiding "bar" would hide "/bar"
703 // as well as "/foo/bar/baz" but not "/barstool".
704 if len(components) == 0 {
705 components = strings.Split(filename, separator)
706 }
707 for _, c := range components {
708 if hidden, _ := filepath.Match(h, c); hidden {
709 return true
710 }
711 }
712 } else if after, ok := strings.CutPrefix(filename, h); ok {
713 // if there is a separator in h, and filename is exactly
714 // prefixed with h, then we can do a prefix match so that
715 // "/foo" matches "/foo/bar" but not "/foobar".
716 withoutPrefix := after
717 if strings.HasPrefix(withoutPrefix, separator) {
718 return true
719 }
720 }
721
722 // in the general case, a glob match will suffice
723 if hidden, _ := filepath.Match(h, filename); hidden {
724 return true
725 }
726 }
727
728 return false
729 }
730
731 // notFound returns a 404 error or, if pass-thru is enabled,
732 // it calls the next handler in the chain.
733 func (fsrv *FileServer) notFound(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
734 if fsrv.PassThru {
735 return next.ServeHTTP(w, r)
736 }
737 return caddyhttp.Error(http.StatusNotFound, nil)
738 }
739
740 // Indicates whether a file's modification time is useful for validator
741 // generation purposes (i.e. inclusion in ETag and Last-Modified headers).
742 // See issues #5548 and #7730.
743 func usefulModTime(modTime time.Time) bool {
744 mtimeunix := modTime.Unix()
745 return mtimeunix != 0 && mtimeunix != 1
746 }
747
748 // calculateEtag computes an entity tag using a strong validator
749 // without consuming the contents of the file. It requires the
750 // file info contain the correct size and modification time.
751 // It strives to implement the semantics regarding ETags as defined
752 // by RFC 9110 section 8.8.3 and 8.8.1. See
753 // https://www.rfc-editor.org/rfc/rfc9110.html#section-8.8.3.
754 //
755 // As our implementation uses file modification timestamp and size,
756 // note the following from RFC 9110 section 8.8.1: "A representation's
757 // modification time, if defined with only one-second resolution,
758 // might be a weak validator if it is possible for the representation to
759 // be modified twice during a single second and retrieved between those
760 // modifications." The ext4 file system, which underpins the vast majority
761 // of Caddy deployments, stores mod times with millisecond precision,
762 // which we consider precise enough to qualify as a strong validator.
763 func calculateEtag(d os.FileInfo) string {
764 mtime := d.ModTime()
765 if !usefulModTime(mtime) {
766 return ""
767 }
768 var sb strings.Builder
769 sb.WriteRune('"')
770 sb.WriteString(strconv.FormatInt(mtime.UnixNano(), 36))
771 sb.WriteString(strconv.FormatInt(d.Size(), 36))
772 sb.WriteRune('"')
773 return sb.String()
774 }
775
776 // Finds the first corresponding etag file for a given file in the file system and return its content
777 func (fsrv *FileServer) getEtagFromFile(fileSystem fs.FS, filename string) (string, error) {
778 for _, suffix := range fsrv.EtagFileExtensions {
779 etagFilename := filename + suffix
780 etag, err := fs.ReadFile(fileSystem, etagFilename)
781 if errors.Is(err, fs.ErrNotExist) {
782 continue
783 }
784 if err != nil {
785 return "", fmt.Errorf("cannot read etag from file %s: %v", etagFilename, err)
786 }
787
788 // Etags should not contain newline characters
789 etag = bytes.ReplaceAll(etag, []byte("\n"), []byte{})
790
791 return string(etag), nil
792 }
793 return "", nil
794 }
795
796 // redirect performs a redirect to a given path. The 'toPath' parameter
797 // MUST be solely a path, and MUST NOT include a query.
798 func redirect(w http.ResponseWriter, r *http.Request, toPath string) error {
799 for strings.HasPrefix(toPath, "//") {
800 // prevent path-based open redirects
801 toPath = strings.TrimPrefix(toPath, "/")
802 }
803 // preserve the query string if present
804 if r.URL.RawQuery != "" {
805 toPath += "?" + r.URL.RawQuery
806 }
807 http.Redirect(w, r, toPath, http.StatusPermanentRedirect) //nolint:gosec // toPath is a same-origin path and leading // is stripped above
808 return nil
809 }
810
811 // statusOverrideResponseWriter intercepts WriteHeader calls
812 // to instead write the HTTP status code we want instead
813 // of the one http.ServeContent will use by default (usually 200)
814 type statusOverrideResponseWriter struct {
815 http.ResponseWriter
816 code int
817 }
818
819 // WriteHeader intercepts calls by the stdlib to WriteHeader
820 // to instead write the HTTP status code we want.
821 func (wr statusOverrideResponseWriter) WriteHeader(int) {
822 wr.ResponseWriter.WriteHeader(wr.code)
823 }
824
825 // Unwrap returns the underlying ResponseWriter, necessary for
826 // http.ResponseController to work correctly.
827 func (wr statusOverrideResponseWriter) Unwrap() http.ResponseWriter {
828 return wr.ResponseWriter
829 }
830
831 var defaultIndexNames = []string{"index.html", "index.txt"}
832
833 const (
834 minBackoff, maxBackoff = 2, 5
835 separator = string(filepath.Separator)
836 )
837
838 // Interface guards
839 var (
840 _ caddy.Provisioner = (*FileServer)(nil)
841 _ caddyhttp.MiddlewareHandler = (*FileServer)(nil)
842 )