Debian Codegraph @

modules/caddyhttp/fileserver/caddyfile.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 "path/filepath"
19 "strconv"
20 "strings"
21
22 "github.com/caddyserver/caddy/v2"
23 "github.com/caddyserver/caddy/v2/caddyconfig"
24 "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
25 "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile"
26 "github.com/caddyserver/caddy/v2/modules/caddyhttp"
27 "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode"
28 "github.com/caddyserver/caddy/v2/modules/caddyhttp/rewrite"
29 )
30
31 func init() {
32 httpcaddyfile.RegisterHandlerDirective("file_server", parseCaddyfile)
33 httpcaddyfile.RegisterDirective("try_files", parseTryFiles)
34 }
35
36 // parseCaddyfile parses the file_server directive.
37 // See UnmarshalCaddyfile for the syntax.
38 func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) {
39 fsrv := new(FileServer)
40 err := fsrv.UnmarshalCaddyfile(h.Dispenser)
41 if err != nil {
42 return fsrv, err
43 }
44 err = fsrv.FinalizeUnmarshalCaddyfile(h)
45 if err != nil {
46 return nil, err
47 }
48 return fsrv, err
49 }
50
51 // UnmarshalCaddyfile parses the file_server directive. It enables
52 // the static file server and configures it with this syntax:
53 //
54 // file_server [<matcher>] [browse] {
55 // fs <filesystem>
56 // root <path>
57 // hide <files...>
58 // index <files...>
59 // browse [<template_file>]
60 // precompressed <formats...>
61 // status <status>
62 // disable_canonical_uris
63 // }
64 //
65 // The FinalizeUnmarshalCaddyfile method should be called after this
66 // to finalize setup of hidden Caddyfiles.
67 func (fsrv *FileServer) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
68 d.Next() // consume directive name
69
70 args := d.RemainingArgs()
71 switch len(args) {
72 case 0:
73 case 1:
74 if args[0] != "browse" {
75 return d.ArgErr()
76 }
77 fsrv.Browse = new(Browse)
78 default:
79 return d.ArgErr()
80 }
81
82 for nesting := d.Nesting(); d.NextBlock(nesting); {
83 switch d.Val() {
84 case "fs":
85 if !d.NextArg() {
86 return d.ArgErr()
87 }
88 if fsrv.FileSystem != "" {
89 return d.Err("file system already specified")
90 }
91 fsrv.FileSystem = d.Val()
92
93 case "hide":
94 fsrv.Hide = d.RemainingArgs()
95 if len(fsrv.Hide) == 0 {
96 return d.ArgErr()
97 }
98
99 case "index":
100 fsrv.IndexNames = d.RemainingArgs()
101 if len(fsrv.IndexNames) == 0 {
102 return d.ArgErr()
103 }
104
105 case "root":
106 if !d.Args(&fsrv.Root) {
107 return d.ArgErr()
108 }
109
110 case "browse":
111 if fsrv.Browse != nil {
112 return d.Err("browsing is already configured")
113 }
114 fsrv.Browse = new(Browse)
115 d.Args(&fsrv.Browse.TemplateFile)
116 for nesting := d.Nesting(); d.NextBlock(nesting); {
117 switch d.Val() {
118 case "reveal_symlinks":
119 if fsrv.Browse.RevealSymlinks {
120 return d.Err("Symlinks path reveal is already enabled")
121 }
122 fsrv.Browse.RevealSymlinks = true
123 case "sort":
124 for d.NextArg() {
125 dVal := d.Val()
126 switch dVal {
127 case sortByName, sortByNameDirFirst, sortBySize, sortByTime, sortOrderAsc, sortOrderDesc:
128 fsrv.Browse.SortOptions = append(fsrv.Browse.SortOptions, dVal)
129 default:
130 return d.Errf("unknown sort option '%s'", dVal)
131 }
132 }
133 case "file_limit":
134 fileLimit := d.RemainingArgs()
135 if len(fileLimit) != 1 {
136 return d.Err("file_limit should have an integer value")
137 }
138 val, _ := strconv.Atoi(fileLimit[0])
139 if fsrv.Browse.FileLimit != 0 {
140 return d.Err("file_limit is already enabled")
141 }
142 fsrv.Browse.FileLimit = val
143 default:
144 return d.Errf("unknown subdirective '%s'", d.Val())
145 }
146 }
147
148 case "precompressed":
149 fsrv.PrecompressedOrder = d.RemainingArgs()
150 if len(fsrv.PrecompressedOrder) == 0 {
151 fsrv.PrecompressedOrder = []string{"br", "zstd", "gzip"}
152 }
153
154 for _, format := range fsrv.PrecompressedOrder {
155 modID := "http.precompressed." + format
156 mod, err := caddy.GetModule(modID)
157 if err != nil {
158 return d.Errf("getting module named '%s': %v", modID, err)
159 }
160 inst := mod.New()
161 precompress, ok := inst.(encode.Precompressed)
162 if !ok {
163 return d.Errf("module %s is not a precompressor; is %T", modID, inst)
164 }
165 if fsrv.PrecompressedRaw == nil {
166 fsrv.PrecompressedRaw = make(caddy.ModuleMap)
167 }
168 fsrv.PrecompressedRaw[format] = caddyconfig.JSON(precompress, nil)
169 }
170
171 case "status":
172 if !d.NextArg() {
173 return d.ArgErr()
174 }
175 fsrv.StatusCode = caddyhttp.WeakString(d.Val())
176
177 case "disable_canonical_uris":
178 if d.NextArg() {
179 return d.ArgErr()
180 }
181 falseBool := false
182 fsrv.CanonicalURIs = &falseBool
183
184 case "pass_thru":
185 if d.NextArg() {
186 return d.ArgErr()
187 }
188 fsrv.PassThru = true
189
190 case "etag_file_extensions":
191 etagFileExtensions := d.RemainingArgs()
192 if len(etagFileExtensions) == 0 {
193 return d.ArgErr()
194 }
195 fsrv.EtagFileExtensions = etagFileExtensions
196
197 default:
198 return d.Errf("unknown subdirective '%s'", d.Val())
199 }
200 }
201
202 return nil
203 }
204
205 // FinalizeUnmarshalCaddyfile finalizes the Caddyfile parsing which
206 // requires having an httpcaddyfile.Helper to function, to setup hidden Caddyfiles.
207 func (fsrv *FileServer) FinalizeUnmarshalCaddyfile(h httpcaddyfile.Helper) error {
208 // Hide the Caddyfile (and any imported Caddyfiles).
209 // This needs to be done in here instead of UnmarshalCaddyfile
210 // because UnmarshalCaddyfile only has access to the dispenser
211 // and not the helper, and only the helper has access to the
212 // Caddyfiles function.
213 if configFiles := h.Caddyfiles(); len(configFiles) > 0 {
214 for _, file := range configFiles {
215 file = filepath.Clean(file)
216 if !fileHidden(file, fsrv.Hide) {
217 // if there's no path separator, the file server module will hide all
218 // files by that name, rather than a specific one; but we want to hide
219 // only this specific file, so ensure there's always a path separator
220 if !strings.Contains(file, separator) {
221 file = "." + separator + file
222 }
223 fsrv.Hide = append(fsrv.Hide, file)
224 }
225 }
226 }
227 return nil
228 }
229
230 // parseTryFiles parses the try_files directive. It combines a file matcher
231 // with a rewrite directive, so this is not a standard handler directive.
232 // A try_files directive has this syntax (notice no matcher tokens accepted):
233 //
234 // try_files <files...> {
235 // policy first_exist|smallest_size|largest_size|most_recently_modified
236 // }
237 //
238 // and is basically shorthand for:
239 //
240 // @try_files file {
241 // try_files <files...>
242 // policy first_exist|smallest_size|largest_size|most_recently_modified
243 // }
244 // rewrite @try_files {http.matchers.file.relative}
245 //
246 // This directive rewrites request paths only, preserving any other part
247 // of the URI, unless the part is explicitly given in the file list. For
248 // example, if any of the files in the list have a query string:
249 //
250 // try_files {path} index.php?{query}&p={path}
251 //
252 // then the query string will not be treated as part of the file name; and
253 // if that file matches, the given query string will replace any query string
254 // that already exists on the request URI.
255 func parseTryFiles(h httpcaddyfile.Helper) ([]httpcaddyfile.ConfigValue, error) {
256 if !h.Next() {
257 return nil, h.ArgErr()
258 }
259
260 tryFiles := h.RemainingArgs()
261 if len(tryFiles) == 0 {
262 return nil, h.ArgErr()
263 }
264
265 // parse out the optional try policy
266 var tryPolicy string
267 for h.NextBlock(0) {
268 switch h.Val() {
269 case "policy":
270 if tryPolicy != "" {
271 return nil, h.Err("try policy already configured")
272 }
273 if !h.NextArg() {
274 return nil, h.ArgErr()
275 }
276 tryPolicy = h.Val()
277
278 switch tryPolicy {
279 case tryPolicyFirstExist, tryPolicyFirstExistFallback, tryPolicyLargestSize, tryPolicySmallestSize, tryPolicyMostRecentlyMod:
280 default:
281 return nil, h.Errf("unrecognized try policy: %s", tryPolicy)
282 }
283 }
284 }
285
286 // makeRoute returns a route that tries the files listed in try
287 // and then rewrites to the matched file; userQueryString is
288 // appended to the rewrite rule.
289 makeRoute := func(try []string, userQueryString string) []httpcaddyfile.ConfigValue {
290 handler := rewrite.Rewrite{
291 URI: "{http.matchers.file.relative}" + userQueryString,
292 }
293 matcherSet := caddy.ModuleMap{
294 "file": h.JSON(MatchFile{TryFiles: try, TryPolicy: tryPolicy}),
295 }
296 return h.NewRoute(matcherSet, handler)
297 }
298
299 var result []httpcaddyfile.ConfigValue
300
301 // if there are query strings in the list, we have to split into
302 // a separate route for each item with a query string, because
303 // the rewrite is different for that item
304 try := make([]string, 0, len(tryFiles))
305 for _, item := range tryFiles {
306 if idx := strings.Index(item, "?"); idx >= 0 {
307 if len(try) > 0 {
308 result = append(result, makeRoute(try, "")...)
309 try = []string{}
310 }
311 result = append(result, makeRoute([]string{item[:idx]}, item[idx:])...)
312 continue
313 }
314 // accumulate consecutive non-query-string parameters
315 try = append(try, item)
316 }
317 if len(try) > 0 {
318 result = append(result, makeRoute(try, "")...)
319 }
320
321 // ensure that multiple routes (possible if rewrite targets
322 // have query strings, for example) are grouped together
323 // so only the first matching rewrite is performed (#2891)
324 h.GroupRoutes(result)
325
326 return result, nil
327 }
328
329 var _ caddyfile.Unmarshaler = (*FileServer)(nil)