@marcel91200 / caddy Mirror · read-only
Fork 0

Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS

Mirrored from https://github.com/Slazee/caddy.git

Synced Nov 11, 01:00 UTC

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