Debian Codegraph @

caddyconfig/httpcaddyfile/directives.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 httpcaddyfile
16
17 import (
18 "encoding/json"
19 "maps"
20 "net"
21 "slices"
22 "sort"
23 "strconv"
24 "strings"
25
26 "github.com/caddyserver/caddy/v2"
27 "github.com/caddyserver/caddy/v2/caddyconfig"
28 "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
29 "github.com/caddyserver/caddy/v2/modules/caddyhttp"
30 )
31
32 // defaultDirectiveOrder specifies the default order
33 // to apply directives in HTTP routes. This must only
34 // consist of directives that are included in Caddy's
35 // standard distribution.
36 //
37 // e.g. The 'root' directive goes near the start in
38 // case rewrites or redirects depend on existence of
39 // files, i.e. the file matcher, which must know the
40 // root first.
41 //
42 // e.g. The 'header' directive goes before 'redir' so
43 // that headers can be manipulated before doing redirects.
44 //
45 // e.g. The 'respond' directive is near the end because it
46 // writes a response and terminates the middleware chain.
47 var defaultDirectiveOrder = []string{
48 "tracing",
49
50 // set variables that may be used by other directives
51 "map",
52 "vars",
53 "fs",
54 "root",
55 "log_append",
56 "skip_log", // TODO: deprecated, renamed to log_skip
57 "log_skip",
58 "log_name",
59
60 "header",
61 "copy_response_headers", // only in reverse_proxy's handle_response
62 "request_body",
63
64 "redir",
65
66 // incoming request manipulation
67 "method",
68 "rewrite",
69 "uri",
70 "try_files",
71
72 // middleware handlers; some wrap responses
73 "basicauth", // TODO: deprecated, renamed to basic_auth
74 "basic_auth",
75 "forward_auth",
76 "request_header",
77 "encode",
78 "push",
79 "intercept",
80 "templates",
81
82 // special routing & dispatching directives
83 "invoke",
84 "handle",
85 "handle_path",
86 "route",
87
88 // handlers that typically respond to requests
89 "abort",
90 "error",
91 "copy_response", // only in reverse_proxy's handle_response
92 "respond",
93 "metrics",
94 "reverse_proxy",
95 "php_fastcgi",
96 "file_server",
97 "acme_server",
98 }
99
100 // directiveOrder specifies the order to apply directives
101 // in HTTP routes, after being modified by either the
102 // plugins or by the user via the "order" global option.
103 var directiveOrder = defaultDirectiveOrder
104
105 // RegisterDirective registers a unique directive dir with an
106 // associated unmarshaling (setup) function. When directive dir
107 // is encountered in a Caddyfile, setupFunc will be called to
108 // unmarshal its tokens.
109 func RegisterDirective(dir string, setupFunc UnmarshalFunc) {
110 if _, ok := registeredDirectives[dir]; ok {
111 panic("directive " + dir + " already registered")
112 }
113 registeredDirectives[dir] = setupFunc
114 }
115
116 // RegisterHandlerDirective is like RegisterDirective, but for
117 // directives which specifically output only an HTTP handler.
118 // Directives registered with this function will always have
119 // an optional matcher token as the first argument.
120 func RegisterHandlerDirective(dir string, setupFunc UnmarshalHandlerFunc) {
121 RegisterDirective(dir, func(h Helper) ([]ConfigValue, error) {
122 if !h.Next() {
123 return nil, h.ArgErr()
124 }
125
126 matcherSet, err := h.ExtractMatcherSet()
127 if err != nil {
128 return nil, err
129 }
130
131 val, err := setupFunc(h)
132 if err != nil {
133 return nil, err
134 }
135
136 return h.NewRoute(matcherSet, val), nil
137 })
138 }
139
140 // RegisterDirectiveOrder registers the default order for a
141 // directive from a plugin.
142 //
143 // This is useful when a plugin has a well-understood place
144 // it should run in the middleware pipeline, and it allows
145 // users to avoid having to define the order themselves.
146 //
147 // The directive dir may be placed in the position relative
148 // to ('before' or 'after') a directive included in Caddy's
149 // standard distribution. It cannot be relative to another
150 // plugin's directive.
151 //
152 // EXPERIMENTAL: This API may change or be removed.
153 func RegisterDirectiveOrder(dir string, position Positional, standardDir string) {
154 // check if directive was already ordered
155 if slices.Contains(directiveOrder, dir) {
156 panic("directive '" + dir + "' already ordered")
157 }
158
159 if position != Before && position != After {
160 panic("the 2nd argument must be either 'before' or 'after', got '" + position + "'")
161 }
162
163 // check if directive exists in standard distribution, since
164 // we can't allow plugins to depend on one another; we can't
165 // guarantee the order that plugins are loaded in.
166 foundStandardDir := slices.Contains(defaultDirectiveOrder, standardDir)
167 if !foundStandardDir {
168 panic("the 3rd argument '" + standardDir + "' must be a directive that exists in the standard distribution of Caddy")
169 }
170
171 // insert directive into proper position
172 newOrder := directiveOrder
173 for i, d := range newOrder {
174 if d != standardDir {
175 continue
176 }
177 switch position {
178 case Before:
179 newOrder = append(newOrder[:i], append([]string{dir}, newOrder[i:]...)...)
180 case After:
181 newOrder = append(newOrder[:i+1], append([]string{dir}, newOrder[i+1:]...)...)
182 case First, Last:
183 }
184 break
185 }
186 directiveOrder = newOrder
187 }
188
189 // RegisterGlobalOption registers a unique global option opt with
190 // an associated unmarshaling (setup) function. When the global
191 // option opt is encountered in a Caddyfile, setupFunc will be
192 // called to unmarshal its tokens.
193 func RegisterGlobalOption(opt string, setupFunc UnmarshalGlobalFunc) {
194 if _, ok := registeredGlobalOptions[opt]; ok {
195 panic("global option " + opt + " already registered")
196 }
197 registeredGlobalOptions[opt] = setupFunc
198 }
199
200 // Helper is a type which helps setup a value from
201 // Caddyfile tokens.
202 type Helper struct {
203 *caddyfile.Dispenser
204 // State stores intermediate variables during caddyfile adaptation.
205 State map[string]any
206 // BlockState stores intermediate variables scoped to the current block.
207 // It propagates down, but unlike state not back up from child to parent.
208 BlockState map[string]any
209 options map[string]any
210 warnings *[]caddyconfig.Warning
211 matcherDefs map[string]caddy.ModuleMap
212 parentBlock caddyfile.ServerBlock
213 groupCounter counter
214 }
215
216 // Option gets the option keyed by name.
217 func (h Helper) Option(name string) any {
218 return h.options[name]
219 }
220
221 // Caddyfiles returns the list of config files from
222 // which tokens in the current server block were loaded.
223 func (h Helper) Caddyfiles() []string {
224 // first obtain set of names of files involved
225 // in this server block, without duplicates
226 files := make(map[string]struct{})
227 for _, segment := range h.parentBlock.Segments {
228 for _, token := range segment {
229 files[token.File] = struct{}{}
230 }
231 }
232 // then convert the set into a slice
233 filesSlice := make([]string, 0, len(files))
234 for file := range files {
235 filesSlice = append(filesSlice, file)
236 }
237 sort.Strings(filesSlice)
238 return filesSlice
239 }
240
241 // JSON converts val into JSON. Any errors are added to warnings.
242 func (h Helper) JSON(val any) json.RawMessage {
243 return caddyconfig.JSON(val, h.warnings)
244 }
245
246 // MatcherToken assumes the next argument token is (possibly) a matcher,
247 // and if so, returns the matcher set along with a true value. If the next
248 // token is not a matcher, nil and false is returned. Note that a true
249 // value may be returned with a nil matcher set if it is a catch-all.
250 func (h Helper) MatcherToken() (caddy.ModuleMap, bool, error) {
251 if !h.NextArg() {
252 return nil, false, nil
253 }
254 return matcherSetFromMatcherToken(h.Dispenser.Token(), h.matcherDefs, h.warnings)
255 }
256
257 // ExtractMatcherSet is like MatcherToken, except this is a higher-level
258 // method that returns the matcher set described by the matcher token,
259 // or nil if there is none, and deletes the matcher token from the
260 // dispenser and resets it as if this look-ahead never happened. Useful
261 // when wrapping a route (one or more handlers) in a user-defined matcher.
262 func (h Helper) ExtractMatcherSet() (caddy.ModuleMap, error) {
263 matcherSet, hasMatcher, err := h.MatcherToken()
264 if err != nil {
265 return nil, err
266 }
267 if hasMatcher {
268 // strip matcher token; we don't need to
269 // use the return value here because a
270 // new dispenser should have been made
271 // solely for this directive's tokens,
272 // with no other uses of same slice
273 h.Dispenser.Delete()
274 }
275 h.Dispenser.Reset() // pretend this lookahead never happened
276 return matcherSet, nil
277 }
278
279 // NewRoute returns config values relevant to creating a new HTTP route.
280 func (h Helper) NewRoute(matcherSet caddy.ModuleMap,
281 handler caddyhttp.MiddlewareHandler,
282 ) []ConfigValue {
283 mod, err := caddy.GetModule(caddy.GetModuleID(handler))
284 if err != nil {
285 *h.warnings = append(*h.warnings, caddyconfig.Warning{
286 File: h.File(),
287 Line: h.Line(),
288 Message: err.Error(),
289 })
290 return nil
291 }
292 var matcherSetsRaw []caddy.ModuleMap
293 if matcherSet != nil {
294 matcherSetsRaw = append(matcherSetsRaw, matcherSet)
295 }
296 return []ConfigValue{
297 {
298 Class: "route",
299 Value: caddyhttp.Route{
300 MatcherSetsRaw: matcherSetsRaw,
301 HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject(handler, "handler", mod.ID.Name(), h.warnings)},
302 },
303 },
304 }
305 }
306
307 // GroupRoutes adds the routes (caddyhttp.Route type) in vals to the
308 // same group, if there is more than one route in vals.
309 func (h Helper) GroupRoutes(vals []ConfigValue) {
310 // ensure there's at least two routes; group of one is pointless
311 var count int
312 for _, v := range vals {
313 if _, ok := v.Value.(caddyhttp.Route); ok {
314 count++
315 if count > 1 {
316 break
317 }
318 }
319 }
320 if count < 2 {
321 return
322 }
323
324 // now that we know the group will have some effect, do it
325 groupName := h.groupCounter.nextGroup()
326 for i := range vals {
327 if route, ok := vals[i].Value.(caddyhttp.Route); ok {
328 route.Group = groupName
329 vals[i].Value = route
330 }
331 }
332 }
333
334 // WithDispenser returns a new instance based on d. All others Helper
335 // fields are copied, so typically maps are shared with this new instance.
336 func (h Helper) WithDispenser(d *caddyfile.Dispenser) Helper {
337 h.Dispenser = d
338 return h
339 }
340
341 // ParseSegmentAsSubroute parses the segment such that its subdirectives
342 // are themselves treated as directives, from which a subroute is built
343 // and returned.
344 func ParseSegmentAsSubroute(h Helper) (caddyhttp.MiddlewareHandler, error) {
345 allResults, err := parseSegmentAsConfig(h)
346 if err != nil {
347 return nil, err
348 }
349
350 return buildSubroute(allResults, h.groupCounter, true)
351 }
352
353 // parseSegmentAsConfig parses the segment such that its subdirectives
354 // are themselves treated as directives, including named matcher definitions,
355 // and the raw Config structs are returned.
356 func parseSegmentAsConfig(h Helper) ([]ConfigValue, error) {
357 var allResults []ConfigValue
358
359 for h.Next() {
360 // don't allow non-matcher args on the first line
361 if h.NextArg() {
362 return nil, h.ArgErr()
363 }
364
365 // slice the linear list of tokens into top-level segments
366 var segments []caddyfile.Segment
367 for nesting := h.Nesting(); h.NextBlock(nesting); {
368 segments = append(segments, h.NextSegment())
369 }
370
371 // copy existing matcher definitions so we can augment
372 // new ones that are defined only in this scope
373 matcherDefs := make(map[string]caddy.ModuleMap, len(h.matcherDefs))
374 maps.Copy(matcherDefs, h.matcherDefs)
375
376 // find and extract any embedded matcher definitions in this scope
377 for i := 0; i < len(segments); i++ {
378 seg := segments[i]
379 if strings.HasPrefix(seg.Directive(), matcherPrefix) {
380 // parse, then add the matcher to matcherDefs
381 err := parseMatcherDefinitions(caddyfile.NewDispenser(seg), matcherDefs)
382 if err != nil {
383 return nil, err
384 }
385 // remove the matcher segment (consumed), then step back the loop
386 segments = append(segments[:i], segments[i+1:]...)
387 i--
388 }
389 }
390
391 // clone BlockState once for the entire block so sibling directives
392 // can share state, but changes don't leak to the parent scope
393 subBlockState := make(map[string]any, len(h.BlockState))
394 maps.Copy(subBlockState, h.BlockState)
395
396 // with matchers ready to go, evaluate each directive's segment
397 for _, seg := range segments {
398 dir := seg.Directive()
399 dirFunc, ok := registeredDirectives[dir]
400 if !ok {
401 return nil, h.Errf("unrecognized directive: %s - are you sure your Caddyfile structure (nesting and braces) is correct?", dir)
402 }
403
404 subHelper := h
405 subHelper.Dispenser = caddyfile.NewDispenser(seg)
406 subHelper.matcherDefs = matcherDefs
407 subHelper.BlockState = subBlockState
408
409 results, err := dirFunc(subHelper)
410 if err != nil {
411 return nil, h.Errf("parsing caddyfile tokens for '%s': %v", dir, err)
412 }
413
414 dir = normalizeDirectiveName(dir)
415
416 for _, result := range results {
417 result.directive = dir
418 allResults = append(allResults, result)
419 }
420 }
421 }
422
423 return allResults, nil
424 }
425
426 // ConfigValue represents a value to be added to the final
427 // configuration, or a value to be consulted when building
428 // the final configuration.
429 type ConfigValue struct {
430 // The kind of value this is. As the config is
431 // being built, the adapter will look in the
432 // "pile" for values belonging to a certain
433 // class when it is setting up a certain part
434 // of the config. The associated value will be
435 // type-asserted and placed accordingly.
436 Class string
437
438 // The value to be used when building the config.
439 // Generally its type is associated with the
440 // name of the Class.
441 Value any
442
443 directive string
444 }
445
446 func sortRoutes(routes []ConfigValue) {
447 dirPositions := make(map[string]int)
448 for i, dir := range directiveOrder {
449 dirPositions[dir] = i
450 }
451
452 sort.SliceStable(routes, func(i, j int) bool {
453 // if the directives are different, just use the established directive order
454 iDir, jDir := routes[i].directive, routes[j].directive
455 if iDir != jDir {
456 return dirPositions[iDir] < dirPositions[jDir]
457 }
458
459 // directives are the same; sub-sort by path matcher length if there's
460 // only one matcher set and one path (this is a very common case and
461 // usually -- but not always -- helpful/expected, oh well; user can
462 // always take manual control of order using handler or route blocks)
463 iRoute, ok := routes[i].Value.(caddyhttp.Route)
464 if !ok {
465 return false
466 }
467 jRoute, ok := routes[j].Value.(caddyhttp.Route)
468 if !ok {
469 return false
470 }
471
472 // decode the path matchers if there is just one matcher set
473 var iPM, jPM caddyhttp.MatchPath
474 if len(iRoute.MatcherSetsRaw) == 1 {
475 _ = json.Unmarshal(iRoute.MatcherSetsRaw[0]["path"], &iPM)
476 }
477 if len(jRoute.MatcherSetsRaw) == 1 {
478 _ = json.Unmarshal(jRoute.MatcherSetsRaw[0]["path"], &jPM)
479 }
480
481 // if there is only one path in the path matcher, sort by longer path
482 // (more specific) first; missing path matchers or multi-matchers are
483 // treated as zero-length paths
484 var iPathLen, jPathLen int
485 if len(iPM) == 1 {
486 iPathLen = len(iPM[0])
487 }
488 if len(jPM) == 1 {
489 jPathLen = len(jPM[0])
490 }
491
492 sortByPath := func() bool {
493 // we can only confidently compare path lengths if both
494 // directives have a single path to match (issue #5037)
495 if iPathLen > 0 && jPathLen > 0 {
496 // trim the trailing wildcard if there is one
497 iPathTrimmed := strings.TrimSuffix(iPM[0], "*")
498 jPathTrimmed := strings.TrimSuffix(jPM[0], "*")
499
500 // if both paths are the same except for a trailing wildcard,
501 // sort by the shorter path first (which is more specific)
502 if iPathTrimmed == jPathTrimmed {
503 return iPathLen < jPathLen
504 }
505
506 // we use the trimmed length to compare the paths
507 // https://github.com/caddyserver/caddy/issues/7012#issuecomment-2870142195
508 // credit to https://github.com/Hellio404
509 // for sorts with many items, mixing matchers w/ and w/o wildcards will confuse the sort and result in incorrect orders
510 iPathLen = len(iPathTrimmed)
511 jPathLen = len(jPathTrimmed)
512
513 // if both paths have the same length, sort lexically
514 // https://github.com/caddyserver/caddy/pull/7015#issuecomment-2871993588
515 if iPathLen == jPathLen {
516 return iPathTrimmed < jPathTrimmed
517 }
518
519 // sort most-specific (longest) path first
520 return iPathLen > jPathLen
521 }
522
523 // if both directives don't have a single path to compare,
524 // sort whichever one has a matcher first; if both have
525 // a matcher, sort equally (stable sort preserves order)
526 return len(iRoute.MatcherSetsRaw) > 0 && len(jRoute.MatcherSetsRaw) == 0
527 }()
528
529 // some directives involve setting values which can overwrite
530 // each other, so it makes most sense to reverse the order so
531 // that the least-specific matcher is first, allowing the last
532 // matching one to win
533 if iDir == "vars" {
534 return !sortByPath
535 }
536
537 // everything else is most-specific matcher first
538 return sortByPath
539 })
540 }
541
542 // serverBlock pairs a Caddyfile server block with
543 // a "pile" of config values, keyed by class name,
544 // as well as its parsed keys for convenience.
545 type serverBlock struct {
546 block caddyfile.ServerBlock
547 pile map[string][]ConfigValue // config values obtained from directives
548 parsedKeys []Address
549 }
550
551 // hostsFromKeys returns a list of all the non-empty hostnames found in
552 // the keys of the server block sb. If logger mode is false, a key with
553 // an empty hostname portion will return an empty slice, since that
554 // server block is interpreted to effectively match all hosts. An empty
555 // string is never added to the slice.
556 //
557 // If loggerMode is true, then the non-standard ports of keys will be
558 // joined to the hostnames. This is to effectively match the Host
559 // header of requests that come in for that key.
560 //
561 // The resulting slice is not sorted but will never have duplicates.
562 func (sb serverBlock) hostsFromKeys(loggerMode bool) []string {
563 // ensure each entry in our list is unique
564 hostMap := make(map[string]struct{})
565 for _, addr := range sb.parsedKeys {
566 if addr.Host == "" {
567 if !loggerMode {
568 // server block contains a key like ":443", i.e. the host portion
569 // is empty / catch-all, which means to match all hosts
570 return []string{}
571 }
572 // never append an empty string
573 continue
574 }
575 if loggerMode &&
576 addr.Port != "" &&
577 addr.Port != strconv.Itoa(caddyhttp.DefaultHTTPPort) &&
578 addr.Port != strconv.Itoa(caddyhttp.DefaultHTTPSPort) {
579 hostMap[net.JoinHostPort(addr.Host, addr.Port)] = struct{}{}
580 } else {
581 hostMap[addr.Host] = struct{}{}
582 }
583 }
584
585 // convert map to slice
586 sblockHosts := make([]string, 0, len(hostMap))
587 for host := range hostMap {
588 sblockHosts = append(sblockHosts, host)
589 }
590
591 return sblockHosts
592 }
593
594 func (sb serverBlock) hostsFromKeysNotHTTP(httpPort string) []string {
595 // ensure each entry in our list is unique
596 hostMap := make(map[string]struct{})
597 for _, addr := range sb.parsedKeys {
598 if addr.Host == "" {
599 continue
600 }
601 if addr.Scheme != "http" && addr.Port != httpPort {
602 hostMap[addr.Host] = struct{}{}
603 }
604 }
605
606 // convert map to slice
607 sblockHosts := make([]string, 0, len(hostMap))
608 for host := range hostMap {
609 sblockHosts = append(sblockHosts, host)
610 }
611
612 return sblockHosts
613 }
614
615 // hasHostCatchAllKey returns true if sb has a key that
616 // omits a host portion, i.e. it "catches all" hosts.
617 func (sb serverBlock) hasHostCatchAllKey() bool {
618 return slices.ContainsFunc(sb.parsedKeys, func(addr Address) bool {
619 return addr.Host == ""
620 })
621 }
622
623 // isAllHTTP returns true if all sb keys explicitly specify
624 // the http:// scheme
625 func (sb serverBlock) isAllHTTP() bool {
626 return !slices.ContainsFunc(sb.parsedKeys, func(addr Address) bool {
627 return addr.Scheme != "http"
628 })
629 }
630
631 // Positional are the supported modes for ordering directives.
632 type Positional string
633
634 const (
635 Before Positional = "before"
636 After Positional = "after"
637 First Positional = "first"
638 Last Positional = "last"
639 )
640
641 type (
642 // UnmarshalFunc is a function which can unmarshal Caddyfile
643 // tokens into zero or more config values using a Helper type.
644 // These are passed in a call to RegisterDirective.
645 UnmarshalFunc func(h Helper) ([]ConfigValue, error)
646
647 // UnmarshalHandlerFunc is like UnmarshalFunc, except the
648 // output of the unmarshaling is an HTTP handler. This
649 // function does not need to deal with HTTP request matching
650 // which is abstracted away. Since writing HTTP handlers
651 // with Caddyfile support is very common, this is a more
652 // convenient way to add a handler to the chain since a lot
653 // of the details common to HTTP handlers are taken care of
654 // for you. These are passed to a call to
655 // RegisterHandlerDirective.
656 UnmarshalHandlerFunc func(h Helper) (caddyhttp.MiddlewareHandler, error)
657
658 // UnmarshalGlobalFunc is a function which can unmarshal Caddyfile
659 // tokens from a global option. It is passed the tokens to parse and
660 // existing value from the previous instance of this global option
661 // (if any). It returns the value to associate with this global option.
662 UnmarshalGlobalFunc func(d *caddyfile.Dispenser, existingVal any) (any, error)
663 )
664
665 var registeredDirectives = make(map[string]UnmarshalFunc)
666
667 var registeredGlobalOptions = make(map[string]UnmarshalGlobalFunc)