Debian Codegraph @

modules/caddyhttp/fileserver/browsetplcontext.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 "context"
19 "io/fs"
20 "net/url"
21 "os"
22 "path"
23 "slices"
24 "sort"
25 "strconv"
26 "strings"
27 "time"
28
29 "github.com/dustin/go-humanize"
30 "go.uber.org/zap"
31 "go.uber.org/zap/zapcore"
32
33 "github.com/caddyserver/caddy/v2"
34 "github.com/caddyserver/caddy/v2/modules/caddyhttp"
35 )
36
37 func (fsrv *FileServer) directoryListing(ctx context.Context, fileSystem fs.FS, parentModTime time.Time, entries []fs.DirEntry, canGoUp bool, root, urlPath string, repl *caddy.Replacer) *browseTemplateContext {
38 filesToHide := fsrv.transformHidePaths(repl)
39
40 name, _ := url.PathUnescape(urlPath)
41
42 tplCtx := &browseTemplateContext{
43 Name: path.Base(name),
44 Path: urlPath,
45 CanGoUp: canGoUp,
46 lastModified: parentModTime,
47 }
48
49 for _, entry := range entries {
50 if err := ctx.Err(); err != nil {
51 break
52 }
53
54 name := entry.Name()
55
56 if fileHidden(name, filesToHide) {
57 continue
58 }
59
60 info, err := entry.Info()
61 if err != nil {
62 if c := fsrv.logger.Check(zapcore.ErrorLevel, "could not get info about directory entry"); c != nil {
63 c.Write(zap.String("name", entry.Name()), zap.String("root", root))
64 }
65 continue
66 }
67
68 // keep track of the most recently modified item in the listing
69 modTime := info.ModTime()
70 if tplCtx.lastModified.IsZero() || modTime.After(tplCtx.lastModified) {
71 tplCtx.lastModified = modTime
72 }
73
74 isDir := entry.IsDir() || fsrv.isSymlinkTargetDir(fileSystem, info, root, urlPath)
75
76 // add the slash after the escape of path to avoid escaping the slash as well
77 if isDir {
78 name += "/"
79 tplCtx.NumDirs++
80 } else {
81 tplCtx.NumFiles++
82 }
83
84 size := info.Size()
85
86 if !isDir {
87 // increase the total by the symlink's size, not the target's size,
88 // by incrementing before we follow the symlink
89 tplCtx.TotalFileSize += size
90 }
91
92 fileIsSymlink := isSymlink(info)
93 symlinkPath := ""
94 if fileIsSymlink {
95 path := caddyhttp.SanitizedPathJoin(root, path.Join(urlPath, info.Name()))
96 fileInfo, err := fs.Stat(fileSystem, path)
97 if err == nil {
98 size = fileInfo.Size()
99 }
100
101 if fsrv.Browse.RevealSymlinks {
102 symLinkTarget, err := os.Readlink(path)
103 if err == nil {
104 symlinkPath = symLinkTarget
105 }
106 }
107
108 // An error most likely means the symlink target doesn't exist,
109 // which isn't entirely unusual and shouldn't fail the listing.
110 // In this case, just use the size of the symlink itself, which
111 // was already set above.
112 }
113
114 if !isDir {
115 // increase the total including the symlink target's size
116 tplCtx.TotalFileSizeFollowingSymlinks += size
117 }
118
119 u := url.URL{Path: "./" + name} // prepend with "./" to fix paths with ':' in the name
120
121 tplCtx.Items = append(tplCtx.Items, fileInfo{
122 IsDir: isDir,
123 IsSymlink: fileIsSymlink,
124 Name: name,
125 Size: size,
126 URL: u.String(),
127 ModTime: modTime.UTC(),
128 Mode: info.Mode(),
129 Tpl: tplCtx, // a reference up to the template context is useful
130 SymlinkPath: symlinkPath,
131 })
132 }
133
134 // this time is used for the Last-Modified header and comparing If-Modified-Since from client
135 // both are expected to be in UTC, so we convert to UTC here
136 // see: https://github.com/caddyserver/caddy/issues/6828
137 tplCtx.lastModified = tplCtx.lastModified.UTC()
138 return tplCtx
139 }
140
141 // browseTemplateContext provides the template context for directory listings.
142 type browseTemplateContext struct {
143 // The name of the directory (the last element of the path).
144 Name string `json:"name"`
145
146 // The full path of the request.
147 Path string `json:"path"`
148
149 // Whether the parent directory is browsable.
150 CanGoUp bool `json:"can_go_up"`
151
152 // The items (files and folders) in the path.
153 Items []fileInfo `json:"items,omitempty"`
154
155 // If ≠0 then Items starting from that many elements.
156 Offset int `json:"offset,omitempty"`
157
158 // If ≠0 then Items have been limited to that many elements.
159 Limit int `json:"limit,omitempty"`
160
161 // The number of directories in the listing.
162 NumDirs int `json:"num_dirs"`
163
164 // The number of files (items that aren't directories) in the listing.
165 NumFiles int `json:"num_files"`
166
167 // The total size of all files in the listing. Only includes the
168 // size of the files themselves, not the size of symlink targets
169 // (i.e. the calculation of this value does not follow symlinks).
170 TotalFileSize int64 `json:"total_file_size"`
171
172 // The total size of all files in the listing, including the
173 // size of the files targeted by symlinks.
174 TotalFileSizeFollowingSymlinks int64 `json:"total_file_size_following_symlinks"`
175
176 // Sort column used
177 Sort string `json:"sort,omitempty"`
178
179 // Sorting order
180 Order string `json:"order,omitempty"`
181
182 // Display format (list or grid)
183 Layout string `json:"layout,omitempty"`
184
185 // The most recent file modification date in the listing.
186 // Used for HTTP header purposes.
187 lastModified time.Time
188 }
189
190 // Breadcrumbs returns l.Path where every element maps
191 // the link to the text to display.
192 func (l browseTemplateContext) Breadcrumbs() []crumb {
193 if len(l.Path) == 0 {
194 return []crumb{}
195 }
196
197 // skip trailing slash
198 lpath := l.Path
199 if lpath[len(lpath)-1] == '/' {
200 lpath = lpath[:len(lpath)-1]
201 }
202 parts := strings.Split(lpath, "/")
203 result := make([]crumb, len(parts))
204 for i, p := range parts {
205 if i == 0 && p == "" {
206 p = "/"
207 }
208 // the directory name could include an encoded slash in its path,
209 // so the item name should be unescaped in the loop rather than unescaping the
210 // entire path outside the loop.
211 p, _ = url.PathUnescape(p)
212 lnk := strings.Repeat("../", len(parts)-i-1)
213 result[i] = crumb{Link: lnk, Text: p}
214 }
215
216 return result
217 }
218
219 func (l *browseTemplateContext) applySortAndLimit(sortParam, orderParam, limitParam string, offsetParam string) {
220 l.Sort = sortParam
221 l.Order = orderParam
222
223 if l.Order == "desc" {
224 switch l.Sort {
225 case sortByName:
226 sort.Sort(sort.Reverse(byName(*l)))
227 case sortByNameDirFirst:
228 sort.Sort(sort.Reverse(byNameDirFirst(*l)))
229 case sortBySize:
230 sort.Sort(sort.Reverse(bySize(*l)))
231 case sortByTime:
232 sort.Sort(sort.Reverse(byTime(*l)))
233 }
234 } else {
235 switch l.Sort {
236 case sortByName:
237 sort.Sort(byName(*l))
238 case sortByNameDirFirst:
239 sort.Sort(byNameDirFirst(*l))
240 case sortBySize:
241 sort.Sort(bySize(*l))
242 case sortByTime:
243 sort.Sort(byTime(*l))
244 }
245 }
246
247 if offsetParam != "" {
248 offset, _ := strconv.Atoi(offsetParam)
249 if offset > 0 && offset <= len(l.Items) {
250 l.Items = l.Items[offset:]
251 l.Offset = offset
252 }
253 }
254
255 if limitParam != "" {
256 limit, _ := strconv.Atoi(limitParam)
257
258 if limit > 0 && limit <= len(l.Items) {
259 l.Items = l.Items[:limit]
260 l.Limit = limit
261 }
262 }
263 }
264
265 // crumb represents part of a breadcrumb menu,
266 // pairing a link with the text to display.
267 type crumb struct {
268 Link, Text string
269 }
270
271 // fileInfo contains serializable information
272 // about a file or directory.
273 type fileInfo struct {
274 Name string `json:"name"`
275 Size int64 `json:"size"`
276 URL string `json:"url"`
277 ModTime time.Time `json:"mod_time"`
278 Mode os.FileMode `json:"mode"`
279 IsDir bool `json:"is_dir"`
280 IsSymlink bool `json:"is_symlink"`
281 SymlinkPath string `json:"symlink_path,omitempty"`
282
283 // a pointer to the template context is useful inside nested templates
284 Tpl *browseTemplateContext `json:"-"`
285 }
286
287 // HasExt returns true if the filename has any of the given suffixes, case-insensitive.
288 func (fi fileInfo) HasExt(exts ...string) bool {
289 return slices.ContainsFunc(exts, func(ext string) bool {
290 return strings.HasSuffix(strings.ToLower(fi.Name), strings.ToLower(ext))
291 })
292 }
293
294 // HumanSize returns the size of the file as a
295 // human-readable string in IEC format (i.e.
296 // power of 2 or base 1024).
297 func (fi fileInfo) HumanSize() string {
298 return humanize.IBytes(uint64(fi.Size))
299 }
300
301 // HumanTotalFileSize returns the total size of all files
302 // in the listing as a human-readable string in IEC format
303 // (i.e. power of 2 or base 1024).
304 func (btc browseTemplateContext) HumanTotalFileSize() string {
305 return humanize.IBytes(uint64(btc.TotalFileSize))
306 }
307
308 // HumanTotalFileSizeFollowingSymlinks is the same as HumanTotalFileSize
309 // except the returned value reflects the size of symlink targets.
310 func (btc browseTemplateContext) HumanTotalFileSizeFollowingSymlinks() string {
311 return humanize.IBytes(uint64(btc.TotalFileSizeFollowingSymlinks))
312 }
313
314 // HumanModTime returns the modified time of the file
315 // as a human-readable string given by format.
316 func (fi fileInfo) HumanModTime(format string) string {
317 return fi.ModTime.Format(format)
318 }
319
320 type (
321 byName browseTemplateContext
322 byNameDirFirst browseTemplateContext
323 bySize browseTemplateContext
324 byTime browseTemplateContext
325 )
326
327 func (l byName) Len() int { return len(l.Items) }
328 func (l byName) Swap(i, j int) { l.Items[i], l.Items[j] = l.Items[j], l.Items[i] }
329
330 func (l byName) Less(i, j int) bool {
331 return strings.ToLower(l.Items[i].Name) < strings.ToLower(l.Items[j].Name)
332 }
333
334 func (l byNameDirFirst) Len() int { return len(l.Items) }
335 func (l byNameDirFirst) Swap(i, j int) { l.Items[i], l.Items[j] = l.Items[j], l.Items[i] }
336
337 func (l byNameDirFirst) Less(i, j int) bool {
338 // sort by name if both are dir or file
339 if l.Items[i].IsDir == l.Items[j].IsDir {
340 return strings.ToLower(l.Items[i].Name) < strings.ToLower(l.Items[j].Name)
341 }
342 // sort dir ahead of file
343 return l.Items[i].IsDir
344 }
345
346 func (l bySize) Len() int { return len(l.Items) }
347 func (l bySize) Swap(i, j int) { l.Items[i], l.Items[j] = l.Items[j], l.Items[i] }
348
349 func (l bySize) Less(i, j int) bool {
350 const directoryOffset = -1 << 31 // = -math.MinInt32
351
352 iSize, jSize := l.Items[i].Size, l.Items[j].Size
353
354 // directory sizes depend on the file system; to
355 // provide a consistent experience, put them up front
356 // and sort them by name
357 if l.Items[i].IsDir {
358 iSize = directoryOffset
359 }
360 if l.Items[j].IsDir {
361 jSize = directoryOffset
362 }
363 if l.Items[i].IsDir && l.Items[j].IsDir {
364 return strings.ToLower(l.Items[i].Name) < strings.ToLower(l.Items[j].Name)
365 }
366
367 return iSize < jSize
368 }
369
370 func (l byTime) Len() int { return len(l.Items) }
371 func (l byTime) Swap(i, j int) { l.Items[i], l.Items[j] = l.Items[j], l.Items[i] }
372 func (l byTime) Less(i, j int) bool { return l.Items[i].ModTime.Before(l.Items[j].ModTime) }
373
374 const (
375 sortByName = "name"
376 sortByNameDirFirst = "namedirfirst"
377 sortBySize = "size"
378 sortByTime = "time"
379
380 sortOrderAsc = "asc"
381 sortOrderDesc = "desc"
382 )