Debian Codegraph @

modules/caddyhttp/fileserver/browse.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 "context"
20 _ "embed"
21 "encoding/json"
22 "errors"
23 "fmt"
24 "io"
25 "io/fs"
26 "net/http"
27 "os"
28 "path"
29 "strings"
30 "sync"
31 "text/tabwriter"
32 "text/template"
33 "time"
34
35 "go.uber.org/zap"
36 "go.uber.org/zap/zapcore"
37
38 "github.com/caddyserver/caddy/v2"
39 "github.com/caddyserver/caddy/v2/modules/caddyhttp"
40 "github.com/caddyserver/caddy/v2/modules/caddyhttp/templates"
41 )
42
43 // BrowseTemplate is the default template document to use for
44 // file listings. By default, its default value is an embedded
45 // document. You can override this value at program start, or
46 // if you are running Caddy via config, you can specify a
47 // custom template_file in the browse configuration.
48 //
49 //go:embed browse.html
50 var BrowseTemplate string
51
52 // Browse configures directory browsing.
53 type Browse struct {
54 // Filename of the template to use instead of the embedded browse template.
55 TemplateFile string `json:"template_file,omitempty"`
56
57 // Determines whether or not targets of symlinks should be revealed.
58 RevealSymlinks bool `json:"reveal_symlinks,omitempty"`
59
60 // Override the default sort.
61 // It includes the following options:
62 // - sort_by: name(default), namedirfirst, size, time
63 // - order: asc(default), desc
64 // eg.:
65 // - `sort time desc` will sort by time in descending order
66 // - `sort size` will sort by size in ascending order
67 // The first option must be `sort_by` and the second option must be `order` (if exists).
68 SortOptions []string `json:"sort,omitempty"`
69
70 // FileLimit limits the number of up to n DirEntry values in directory order.
71 FileLimit int `json:"file_limit,omitempty"`
72 }
73
74 const (
75 defaultDirEntryLimit = 10000
76 )
77
78 func (fsrv *FileServer) serveBrowse(fileSystem fs.FS, root, dirPath string, w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
79 if c := fsrv.logger.Check(zapcore.DebugLevel, "browse enabled; listing directory contents"); c != nil {
80 c.Write(zap.String("path", dirPath), zap.String("root", root))
81 }
82
83 // Navigation on the client-side gets messed up if the
84 // URL doesn't end in a trailing slash because hrefs to
85 // "b/c" at path "/a" end up going to "/b/c" instead
86 // of "/a/b/c" - so we have to redirect in this case
87 // so that the path is "/a/" and the client constructs
88 // relative hrefs "b/c" to be "/a/b/c".
89 //
90 // Only redirect if the last element of the path (the filename) was not
91 // rewritten; if the admin wanted to rewrite to the canonical path, they
92 // would have, and we have to be very careful not to introduce unwanted
93 // redirects and especially redirect loops! (Redirecting using the
94 // original URI is necessary because that's the URI the browser knows,
95 // we don't want to redirect from internally-rewritten URIs.)
96 // See https://github.com/caddyserver/caddy/issues/4205.
97 // We also redirect if the path is empty, because this implies the path
98 // prefix was fully stripped away by a `handle_path` handler for example.
99 // See https://github.com/caddyserver/caddy/issues/4466.
100 origReq := r.Context().Value(caddyhttp.OriginalRequestCtxKey).(http.Request)
101 if r.URL.Path == "" || path.Base(origReq.URL.Path) == path.Base(r.URL.Path) {
102 if !strings.HasSuffix(origReq.URL.Path, "/") {
103 if c := fsrv.logger.Check(zapcore.DebugLevel, "redirecting to trailing slash to preserve hrefs"); c != nil {
104 c.Write(zap.String("request_path", r.URL.Path))
105 }
106 return redirect(w, r, origReq.URL.Path+"/")
107 }
108 }
109
110 dir, err := fsrv.openFile(fileSystem, dirPath, w)
111 if err != nil {
112 return err
113 }
114 defer dir.Close()
115
116 repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
117
118 // TODO: not entirely sure if path.Clean() is necessary here but seems like a safe plan (i.e. /%2e%2e%2f) - someone could verify this
119 listing, err := fsrv.loadDirectoryContents(r.Context(), fileSystem, dir.(fs.ReadDirFile), root, path.Clean(r.URL.EscapedPath()), repl)
120 switch {
121 case errors.Is(err, fs.ErrPermission):
122 return caddyhttp.Error(http.StatusForbidden, err)
123 case errors.Is(err, fs.ErrNotExist):
124 return fsrv.notFound(w, r, next)
125 case err != nil:
126 return caddyhttp.Error(http.StatusInternalServerError, err)
127 }
128
129 w.Header().Add("Vary", "Accept, Accept-Encoding")
130
131 // speed up browser/client experience and caching by supporting If-Modified-Since
132 if ifModSinceStr := r.Header.Get("If-Modified-Since"); ifModSinceStr != "" {
133 // basically a copy of stdlib file server's handling of If-Modified-Since
134 ifModSince, err := http.ParseTime(ifModSinceStr)
135 if err == nil && listing.lastModified.Truncate(time.Second).Compare(ifModSince) <= 0 {
136 w.WriteHeader(http.StatusNotModified)
137 return nil
138 }
139 }
140
141 fsrv.browseApplyQueryParams(w, r, listing)
142
143 buf := bufPool.Get().(*bytes.Buffer)
144 buf.Reset()
145 defer bufPool.Put(buf)
146
147 acceptHeader := strings.ToLower(strings.Join(r.Header["Accept"], ","))
148 w.Header().Set("Last-Modified", listing.lastModified.Format(http.TimeFormat))
149
150 switch {
151 case strings.Contains(acceptHeader, "application/json"):
152 if err := json.NewEncoder(buf).Encode(listing.Items); err != nil {
153 return caddyhttp.Error(http.StatusInternalServerError, err)
154 }
155 w.Header().Set("Content-Type", "application/json; charset=utf-8")
156
157 case strings.Contains(acceptHeader, "text/plain"):
158 writer := tabwriter.NewWriter(buf, 0, 8, 1, '\t', tabwriter.AlignRight)
159
160 // Header on top
161 if _, err := fmt.Fprintln(writer, "Name\tSize\tModified"); err != nil {
162 return caddyhttp.Error(http.StatusInternalServerError, err)
163 }
164
165 // Lines to separate the header
166 if _, err := fmt.Fprintln(writer, "----\t----\t--------"); err != nil {
167 return caddyhttp.Error(http.StatusInternalServerError, err)
168 }
169
170 // Actual files
171 for _, item := range listing.Items {
172 //nolint:gosec // not sure how this could be XSS unless you lose control of the file system (like aren't sanitizing) and client ignores Content-Type of text/plain
173 if _, err := fmt.Fprintf(writer, "%s\t%s\t%s\n",
174 item.Name, item.HumanSize(), item.HumanModTime("January 2, 2006 at 15:04:05"),
175 ); err != nil {
176 return caddyhttp.Error(http.StatusInternalServerError, err)
177 }
178 }
179
180 if err := writer.Flush(); err != nil {
181 return caddyhttp.Error(http.StatusInternalServerError, err)
182 }
183
184 w.Header().Set("Content-Type", "text/plain; charset=utf-8")
185
186 default:
187 var fs http.FileSystem
188 if fsrv.Root != "" {
189 fs = http.Dir(repl.ReplaceAll(fsrv.Root, "."))
190 }
191
192 tplCtx := &templateContext{
193 TemplateContext: templates.TemplateContext{
194 Root: fs,
195 Req: r,
196 RespHeader: templates.WrappedHeader{Header: w.Header()},
197 },
198 browseTemplateContext: listing,
199 }
200
201 tpl, err := fsrv.makeBrowseTemplate(tplCtx)
202 if err != nil {
203 return fmt.Errorf("parsing browse template: %v", err)
204 }
205 if err := tpl.Execute(buf, tplCtx); err != nil {
206 return caddyhttp.Error(http.StatusInternalServerError, err)
207 }
208 w.Header().Set("Content-Type", "text/html; charset=utf-8")
209 }
210
211 _, _ = buf.WriteTo(w)
212
213 return nil
214 }
215
216 func (fsrv *FileServer) loadDirectoryContents(ctx context.Context, fileSystem fs.FS, dir fs.ReadDirFile, root, urlPath string, repl *caddy.Replacer) (*browseTemplateContext, error) {
217 // modTime for the directory itself
218 stat, err := dir.Stat()
219 if err != nil {
220 return nil, err
221 }
222 dirLimit := defaultDirEntryLimit
223 if fsrv.Browse.FileLimit != 0 {
224 dirLimit = fsrv.Browse.FileLimit
225 }
226 files, err := dir.ReadDir(dirLimit)
227 if err != nil && err != io.EOF {
228 return nil, err
229 }
230
231 // user can presumably browse "up" to parent folder if path is longer than "/"
232 canGoUp := len(urlPath) > 1
233
234 return fsrv.directoryListing(ctx, fileSystem, stat.ModTime(), files, canGoUp, root, urlPath, repl), nil
235 }
236
237 // browseApplyQueryParams applies query parameters to the listing.
238 // It mutates the listing and may set cookies.
239 func (fsrv *FileServer) browseApplyQueryParams(w http.ResponseWriter, r *http.Request, listing *browseTemplateContext) {
240 var orderParam, sortParam string
241
242 // The configs in Caddyfile have lower priority than Query params,
243 // so put it at first.
244 for idx, item := range fsrv.Browse.SortOptions {
245 // Only `sort` & `order`, 2 params are allowed
246 if idx >= 2 {
247 break
248 }
249 switch item {
250 case sortByName, sortByNameDirFirst, sortBySize, sortByTime:
251 sortParam = item
252 case sortOrderAsc, sortOrderDesc:
253 orderParam = item
254 }
255 }
256
257 layoutParam := r.URL.Query().Get("layout")
258 limitParam := r.URL.Query().Get("limit")
259 offsetParam := r.URL.Query().Get("offset")
260 sortParamTmp := r.URL.Query().Get("sort")
261 if sortParamTmp != "" {
262 sortParam = sortParamTmp
263 }
264 orderParamTmp := r.URL.Query().Get("order")
265 if orderParamTmp != "" {
266 orderParam = orderParamTmp
267 }
268
269 switch layoutParam {
270 case "list", "grid", "":
271 listing.Layout = layoutParam
272 default:
273 listing.Layout = "list"
274 }
275
276 // figure out what to sort by
277 switch sortParam {
278 case "":
279 sortParam = sortByNameDirFirst
280 if sortCookie, sortErr := r.Cookie("sort"); sortErr == nil {
281 sortParam = sortCookie.Value
282 }
283 case sortByName, sortByNameDirFirst, sortBySize, sortByTime:
284 http.SetCookie(w, &http.Cookie{ //nolint:gosec // Secure depends on whether the request itself used TLS
285 Name: "sort",
286 Value: sortParam,
287 Secure: r.TLS != nil,
288 HttpOnly: true,
289 SameSite: http.SameSiteLaxMode,
290 })
291 }
292
293 // then figure out the order
294 switch orderParam {
295 case "":
296 orderParam = sortOrderAsc
297 if orderCookie, orderErr := r.Cookie("order"); orderErr == nil {
298 orderParam = orderCookie.Value
299 }
300 case sortOrderAsc, sortOrderDesc:
301 http.SetCookie(w, &http.Cookie{ //nolint:gosec // Secure depends on whether the request itself used TLS
302 Name: "order",
303 Value: orderParam,
304 Secure: r.TLS != nil,
305 HttpOnly: true,
306 SameSite: http.SameSiteLaxMode,
307 })
308 }
309
310 // finally, apply the sorting and limiting
311 listing.applySortAndLimit(sortParam, orderParam, limitParam, offsetParam)
312 }
313
314 // makeBrowseTemplate creates the template to be used for directory listings.
315 func (fsrv *FileServer) makeBrowseTemplate(tplCtx *templateContext) (*template.Template, error) {
316 var tpl *template.Template
317 var err error
318
319 if fsrv.Browse.TemplateFile != "" {
320 tpl = tplCtx.NewTemplate(path.Base(fsrv.Browse.TemplateFile))
321 tpl, err = tpl.ParseFiles(fsrv.Browse.TemplateFile)
322 if err != nil {
323 return nil, fmt.Errorf("parsing browse template file: %v", err)
324 }
325 } else {
326 tpl = tplCtx.NewTemplate("default_listing")
327 tpl, err = tpl.Parse(BrowseTemplate)
328 if err != nil {
329 return nil, fmt.Errorf("parsing default browse template: %v", err)
330 }
331 }
332
333 return tpl, nil
334 }
335
336 // isSymlinkTargetDir returns true if f's symbolic link target
337 // is a directory.
338 func (fsrv *FileServer) isSymlinkTargetDir(fileSystem fs.FS, f fs.FileInfo, root, urlPath string) bool {
339 if !isSymlink(f) {
340 return false
341 }
342 target := caddyhttp.SanitizedPathJoin(root, path.Join(urlPath, f.Name()))
343 targetInfo, err := fs.Stat(fileSystem, target)
344 if err != nil {
345 return false
346 }
347 return targetInfo.IsDir()
348 }
349
350 // isSymlink return true if f is a symbolic link.
351 func isSymlink(f fs.FileInfo) bool {
352 return f.Mode()&os.ModeSymlink != 0
353 }
354
355 // templateContext powers the context used when evaluating the browse template.
356 // It combines browse-specific features with the standard templates handler
357 // features.
358 type templateContext struct {
359 templates.TemplateContext
360 *browseTemplateContext
361 }
362
363 // bufPool is used to increase the efficiency of file listings.
364 var bufPool = sync.Pool{
365 New: func() any {
366 return new(bytes.Buffer)
367 },
368 }