Debian Codegraph @

caddyconfig/httpcaddyfile/options.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 "slices"
19 "strconv"
20
21 "github.com/caddyserver/certmagic"
22 "github.com/libdns/libdns"
23 "github.com/mholt/acmez/v3/acme"
24
25 "github.com/caddyserver/caddy/v2"
26 "github.com/caddyserver/caddy/v2/caddyconfig"
27 "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
28 "github.com/caddyserver/caddy/v2/modules/caddyhttp"
29 "github.com/caddyserver/caddy/v2/modules/caddytls"
30 )
31
32 func init() {
33 RegisterGlobalOption("debug", parseOptTrue)
34 RegisterGlobalOption("http_port", parseOptHTTPPort)
35 RegisterGlobalOption("https_port", parseOptHTTPSPort)
36 RegisterGlobalOption("default_bind", parseOptDefaultBind)
37 RegisterGlobalOption("grace_period", parseOptDuration)
38 RegisterGlobalOption("shutdown_delay", parseOptDuration)
39 RegisterGlobalOption("default_sni", parseOptSingleString)
40 RegisterGlobalOption("fallback_sni", parseOptSingleString)
41 RegisterGlobalOption("order", parseOptOrder)
42 RegisterGlobalOption("storage", parseOptStorage)
43 RegisterGlobalOption("storage_check", parseStorageCheck)
44 RegisterGlobalOption("storage_clean_interval", parseStorageCleanInterval)
45 RegisterGlobalOption("renew_interval", parseOptDuration)
46 RegisterGlobalOption("ocsp_interval", parseOptDuration)
47 RegisterGlobalOption("acme_ca", parseOptSingleString)
48 RegisterGlobalOption("acme_ca_root", parseOptSingleString)
49 RegisterGlobalOption("acme_dns", parseOptDNS)
50 RegisterGlobalOption("acme_eab", parseOptACMEEAB)
51 RegisterGlobalOption("cert_issuer", parseOptCertIssuer)
52 RegisterGlobalOption("skip_install_trust", parseOptTrue)
53 RegisterGlobalOption("email", parseOptSingleString)
54 RegisterGlobalOption("admin", parseOptAdmin)
55 RegisterGlobalOption("on_demand_tls", parseOptOnDemand)
56 RegisterGlobalOption("local_certs", parseOptTrue)
57 RegisterGlobalOption("key_type", parseOptSingleString)
58 RegisterGlobalOption("auto_https", parseOptAutoHTTPS)
59 RegisterGlobalOption("metrics", parseMetricsOptions)
60 RegisterGlobalOption("servers", parseServerOptions)
61 RegisterGlobalOption("ocsp_stapling", parseOCSPStaplingOptions)
62 RegisterGlobalOption("cert_lifetime", parseOptDuration)
63 RegisterGlobalOption("log", parseLogOptions)
64 RegisterGlobalOption("preferred_chains", parseOptPreferredChains)
65 RegisterGlobalOption("persist_config", parseOptPersistConfig)
66 RegisterGlobalOption("dns", parseOptDNS)
67 RegisterGlobalOption("tls_resolvers", parseOptTLSResolvers)
68 RegisterGlobalOption("ech", parseOptECH)
69 RegisterGlobalOption("renewal_window_ratio", parseOptRenewalWindowRatio)
70 }
71
72 func parseOptTrue(d *caddyfile.Dispenser, _ any) (any, error) { return true, nil }
73
74 func parseOptHTTPPort(d *caddyfile.Dispenser, _ any) (any, error) {
75 d.Next() // consume option name
76 var httpPort int
77 var httpPortStr string
78 if !d.AllArgs(&httpPortStr) {
79 return 0, d.ArgErr()
80 }
81 var err error
82 httpPort, err = strconv.Atoi(httpPortStr)
83 if err != nil {
84 return 0, d.Errf("converting port '%s' to integer value: %v", httpPortStr, err)
85 }
86 return httpPort, nil
87 }
88
89 func parseOptHTTPSPort(d *caddyfile.Dispenser, _ any) (any, error) {
90 d.Next() // consume option name
91 var httpsPort int
92 var httpsPortStr string
93 if !d.AllArgs(&httpsPortStr) {
94 return 0, d.ArgErr()
95 }
96 var err error
97 httpsPort, err = strconv.Atoi(httpsPortStr)
98 if err != nil {
99 return 0, d.Errf("converting port '%s' to integer value: %v", httpsPortStr, err)
100 }
101 return httpsPort, nil
102 }
103
104 func parseOptOrder(d *caddyfile.Dispenser, _ any) (any, error) {
105 d.Next() // consume option name
106
107 // get directive name
108 if !d.Next() {
109 return nil, d.ArgErr()
110 }
111 dirName := d.Val()
112 if _, ok := registeredDirectives[dirName]; !ok {
113 return nil, d.Errf("%s is not a registered directive", dirName)
114 }
115
116 // get positional token
117 if !d.Next() {
118 return nil, d.ArgErr()
119 }
120 pos := Positional(d.Val())
121
122 // if directive already had an order, drop it
123 newOrder := slices.DeleteFunc(directiveOrder, func(d string) bool {
124 return d == dirName
125 })
126
127 // act on the positional; if it's First or Last, we're done right away
128 switch pos {
129 case First:
130 newOrder = append([]string{dirName}, newOrder...)
131 if d.NextArg() {
132 return nil, d.ArgErr()
133 }
134 directiveOrder = newOrder
135 return newOrder, nil
136
137 case Last:
138 newOrder = append(newOrder, dirName)
139 if d.NextArg() {
140 return nil, d.ArgErr()
141 }
142 directiveOrder = newOrder
143 return newOrder, nil
144
145 // if it's Before or After, continue
146 case Before:
147 case After:
148
149 default:
150 return nil, d.Errf("unknown positional '%s'", pos)
151 }
152
153 // get name of other directive
154 if !d.NextArg() {
155 return nil, d.ArgErr()
156 }
157 otherDir := d.Val()
158 if d.NextArg() {
159 return nil, d.ArgErr()
160 }
161
162 // get the position of the target directive
163 targetIndex := slices.Index(newOrder, otherDir)
164 if targetIndex == -1 {
165 return nil, d.Errf("directive '%s' not found", otherDir)
166 }
167 // if we're inserting after, we need to increment the index to go after
168 if pos == After {
169 targetIndex++
170 }
171 // insert the directive into the new order
172 newOrder = slices.Insert(newOrder, targetIndex, dirName)
173
174 directiveOrder = newOrder
175
176 return newOrder, nil
177 }
178
179 func parseOptStorage(d *caddyfile.Dispenser, _ any) (any, error) {
180 if !d.Next() { // consume option name
181 return nil, d.ArgErr()
182 }
183 if !d.Next() { // get storage module name
184 return nil, d.ArgErr()
185 }
186 modID := "caddy.storage." + d.Val()
187 unm, err := caddyfile.UnmarshalModule(d, modID)
188 if err != nil {
189 return nil, err
190 }
191 storage, ok := unm.(caddy.StorageConverter)
192 if !ok {
193 return nil, d.Errf("module %s is not a caddy.StorageConverter", modID)
194 }
195 return storage, nil
196 }
197
198 func parseStorageCheck(d *caddyfile.Dispenser, _ any) (any, error) {
199 d.Next() // consume option name
200 if !d.Next() {
201 return "", d.ArgErr()
202 }
203 val := d.Val()
204 if d.Next() {
205 return "", d.ArgErr()
206 }
207 if val != "off" {
208 return "", d.Errf("storage_check must be 'off'")
209 }
210 return val, nil
211 }
212
213 func parseStorageCleanInterval(d *caddyfile.Dispenser, _ any) (any, error) {
214 d.Next() // consume option name
215 if !d.Next() {
216 return "", d.ArgErr()
217 }
218 val := d.Val()
219 if d.Next() {
220 return "", d.ArgErr()
221 }
222 if val == "off" {
223 return false, nil
224 }
225 dur, err := caddy.ParseDuration(d.Val())
226 if err != nil {
227 return nil, d.Errf("failed to parse storage_clean_interval, must be a duration or 'off' %w", err)
228 }
229 return caddy.Duration(dur), nil
230 }
231
232 func parseOptDuration(d *caddyfile.Dispenser, _ any) (any, error) {
233 if !d.Next() { // consume option name
234 return nil, d.ArgErr()
235 }
236 if !d.Next() { // get duration value
237 return nil, d.ArgErr()
238 }
239 dur, err := caddy.ParseDuration(d.Val())
240 if err != nil {
241 return nil, err
242 }
243 return caddy.Duration(dur), nil
244 }
245
246 func parseOptACMEEAB(d *caddyfile.Dispenser, _ any) (any, error) {
247 eab := new(acme.EAB)
248 d.Next() // consume option name
249 if d.NextArg() {
250 return nil, d.ArgErr()
251 }
252 for d.NextBlock(0) {
253 switch d.Val() {
254 case "key_id":
255 if !d.NextArg() {
256 return nil, d.ArgErr()
257 }
258 eab.KeyID = d.Val()
259
260 case "mac_key":
261 if !d.NextArg() {
262 return nil, d.ArgErr()
263 }
264 eab.MACKey = d.Val()
265
266 default:
267 return nil, d.Errf("unrecognized parameter '%s'", d.Val())
268 }
269 }
270 return eab, nil
271 }
272
273 func parseOptCertIssuer(d *caddyfile.Dispenser, existing any) (any, error) {
274 d.Next() // consume option name
275
276 var issuers []certmagic.Issuer
277 if existing != nil {
278 issuers = existing.([]certmagic.Issuer)
279 }
280
281 // get issuer module name
282 if !d.Next() {
283 return nil, d.ArgErr()
284 }
285 modID := "tls.issuance." + d.Val()
286 unm, err := caddyfile.UnmarshalModule(d, modID)
287 if err != nil {
288 return nil, err
289 }
290 iss, ok := unm.(certmagic.Issuer)
291 if !ok {
292 return nil, d.Errf("module %s (%T) is not a certmagic.Issuer", modID, unm)
293 }
294 issuers = append(issuers, iss)
295 return issuers, nil
296 }
297
298 func parseOptSingleString(d *caddyfile.Dispenser, _ any) (any, error) {
299 d.Next() // consume option name
300 if !d.Next() {
301 return "", d.ArgErr()
302 }
303 val := d.Val()
304 if d.Next() {
305 return "", d.ArgErr()
306 }
307 return val, nil
308 }
309
310 func parseOptTLSResolvers(d *caddyfile.Dispenser, _ any) (any, error) {
311 d.Next() // consume option name
312 resolvers := d.RemainingArgs()
313 if len(resolvers) == 0 {
314 return nil, d.ArgErr()
315 }
316 return resolvers, nil
317 }
318
319 func parseOptDefaultBind(d *caddyfile.Dispenser, _ any) (any, error) {
320 d.Next() // consume option name
321
322 var addresses, protocols []string
323 addresses = d.RemainingArgs()
324
325 if len(addresses) == 0 {
326 addresses = append(addresses, "")
327 }
328
329 for d.NextBlock(0) {
330 switch d.Val() {
331 case "protocols":
332 protocols = d.RemainingArgs()
333 if len(protocols) == 0 {
334 return nil, d.Errf("protocols requires one or more arguments")
335 }
336 default:
337 return nil, d.Errf("unknown subdirective: %s", d.Val())
338 }
339 }
340
341 return []ConfigValue{{Class: "bind", Value: addressesWithProtocols{
342 addresses: addresses,
343 protocols: protocols,
344 }}}, nil
345 }
346
347 func parseOptAdmin(d *caddyfile.Dispenser, _ any) (any, error) {
348 d.Next() // consume option name
349
350 adminCfg := new(caddy.AdminConfig)
351 if d.NextArg() {
352 listenAddress := d.Val()
353 if listenAddress == "off" {
354 adminCfg.Disabled = true
355 if d.Next() { // Do not accept any remaining options including block
356 return nil, d.Err("No more option is allowed after turning off admin config")
357 }
358 } else {
359 adminCfg.Listen = listenAddress
360 if d.NextArg() { // At most 1 arg is allowed
361 return nil, d.ArgErr()
362 }
363 }
364 }
365 for d.NextBlock(0) {
366 switch d.Val() {
367 case "enforce_origin":
368 adminCfg.EnforceOrigin = true
369
370 case "origins":
371 adminCfg.Origins = d.RemainingArgs()
372
373 default:
374 return nil, d.Errf("unrecognized parameter '%s'", d.Val())
375 }
376 }
377 if adminCfg.Listen == "" && !adminCfg.Disabled {
378 adminCfg.Listen = caddy.DefaultAdminListen
379 }
380 return adminCfg, nil
381 }
382
383 func parseOptOnDemand(d *caddyfile.Dispenser, _ any) (any, error) {
384 d.Next() // consume option name
385 if d.NextArg() {
386 return nil, d.ArgErr()
387 }
388
389 var ond *caddytls.OnDemandConfig
390
391 for nesting := d.Nesting(); d.NextBlock(nesting); {
392 switch d.Val() {
393 case "ask":
394 if !d.NextArg() {
395 return nil, d.ArgErr()
396 }
397 if ond == nil {
398 ond = new(caddytls.OnDemandConfig)
399 }
400 if ond.PermissionRaw != nil {
401 return nil, d.Err("on-demand TLS permission module (or 'ask') already specified")
402 }
403 perm := caddytls.PermissionByHTTP{Endpoint: d.Val()}
404 ond.PermissionRaw = caddyconfig.JSONModuleObject(perm, "module", "http", nil)
405
406 case "permission":
407 if !d.NextArg() {
408 return nil, d.ArgErr()
409 }
410 if ond == nil {
411 ond = new(caddytls.OnDemandConfig)
412 }
413 if ond.PermissionRaw != nil {
414 return nil, d.Err("on-demand TLS permission module (or 'ask') already specified")
415 }
416 modName := d.Val()
417 modID := "tls.permission." + modName
418 unm, err := caddyfile.UnmarshalModule(d, modID)
419 if err != nil {
420 return nil, err
421 }
422 perm, ok := unm.(caddytls.OnDemandPermission)
423 if !ok {
424 return nil, d.Errf("module %s (%T) is not an on-demand TLS permission module", modID, unm)
425 }
426 ond.PermissionRaw = caddyconfig.JSONModuleObject(perm, "module", modName, nil)
427
428 case "interval":
429 return nil, d.Errf("the on_demand_tls 'interval' option is no longer supported, remove it from your config")
430
431 case "burst":
432 return nil, d.Errf("the on_demand_tls 'burst' option is no longer supported, remove it from your config")
433
434 default:
435 return nil, d.Errf("unrecognized parameter '%s'", d.Val())
436 }
437 }
438 if ond == nil {
439 return nil, d.Err("expected at least one config parameter for on_demand_tls")
440 }
441 return ond, nil
442 }
443
444 func parseOptPersistConfig(d *caddyfile.Dispenser, _ any) (any, error) {
445 d.Next() // consume option name
446 if !d.Next() {
447 return "", d.ArgErr()
448 }
449 val := d.Val()
450 if d.Next() {
451 return "", d.ArgErr()
452 }
453 if val != "off" {
454 return "", d.Errf("persist_config must be 'off'")
455 }
456 return val, nil
457 }
458
459 func parseOptAutoHTTPS(d *caddyfile.Dispenser, _ any) (any, error) {
460 d.Next() // consume option name
461 val := d.RemainingArgs()
462 if len(val) == 0 {
463 return "", d.ArgErr()
464 }
465 for _, v := range val {
466 switch v {
467 case "off":
468 case "disable_redirects":
469 case "disable_certs":
470 case "ignore_loaded_certs":
471 default:
472 return "", d.Errf("auto_https must be one of 'off', 'disable_redirects', 'disable_certs', or 'ignore_loaded_certs'")
473 }
474 }
475 return val, nil
476 }
477
478 func unmarshalCaddyfileMetricsOptions(d *caddyfile.Dispenser) (any, error) {
479 d.Next() // consume option name
480 metrics := new(caddyhttp.Metrics)
481 for d.NextBlock(0) {
482 switch d.Val() {
483 case "per_host":
484 metrics.PerHost = true
485 case "observe_catchall_hosts":
486 metrics.ObserveCatchallHosts = true
487 case "otlp":
488 metrics.OTLP = true
489 default:
490 return nil, d.Errf("unrecognized servers option '%s'", d.Val())
491 }
492 }
493 return metrics, nil
494 }
495
496 func parseMetricsOptions(d *caddyfile.Dispenser, _ any) (any, error) {
497 return unmarshalCaddyfileMetricsOptions(d)
498 }
499
500 func parseServerOptions(d *caddyfile.Dispenser, _ any) (any, error) {
501 return unmarshalCaddyfileServerOptions(d)
502 }
503
504 func parseOCSPStaplingOptions(d *caddyfile.Dispenser, _ any) (any, error) {
505 d.Next() // consume option name
506 var val string
507 if !d.AllArgs(&val) {
508 return nil, d.ArgErr()
509 }
510 if val != "off" {
511 return nil, d.Errf("invalid argument '%s'", val)
512 }
513 return certmagic.OCSPConfig{
514 DisableStapling: val == "off",
515 }, nil
516 }
517
518 // parseLogOptions parses the global log option. Syntax:
519 //
520 // log [name] {
521 // output <writer_module> ...
522 // format <encoder_module> ...
523 // level <level>
524 // include <namespaces...>
525 // exclude <namespaces...>
526 // }
527 //
528 // When the name argument is unspecified, this directive modifies the default
529 // logger.
530 func parseLogOptions(d *caddyfile.Dispenser, existingVal any) (any, error) {
531 currentNames := make(map[string]struct{})
532 if existingVal != nil {
533 innerVals, ok := existingVal.([]ConfigValue)
534 if !ok {
535 return nil, d.Errf("existing log values of unexpected type: %T", existingVal)
536 }
537 for _, rawVal := range innerVals {
538 val, ok := rawVal.Value.(namedCustomLog)
539 if !ok {
540 return nil, d.Errf("existing log value of unexpected type: %T", existingVal)
541 }
542 currentNames[val.name] = struct{}{}
543 }
544 }
545
546 var warnings []caddyconfig.Warning
547 // Call out the same parser that handles server-specific log configuration.
548 configValues, err := parseLogHelper(
549 Helper{
550 Dispenser: d,
551 warnings: &warnings,
552 },
553 currentNames,
554 )
555 if err != nil {
556 return nil, err
557 }
558 if len(warnings) > 0 {
559 return nil, d.Errf("warnings found in parsing global log options: %+v", warnings)
560 }
561
562 return configValues, nil
563 }
564
565 func parseOptPreferredChains(d *caddyfile.Dispenser, _ any) (any, error) {
566 d.Next()
567 return caddytls.ParseCaddyfilePreferredChainsOptions(d)
568 }
569
570 func parseOptDNS(d *caddyfile.Dispenser, _ any) (any, error) {
571 d.Next() // consume option name
572 optName := d.Val()
573
574 // get DNS module name
575 if !d.Next() {
576 // this is allowed if this is the "acme_dns" option since it may refer to the globally-configured "dns" option's value
577 if optName == "acme_dns" {
578 return nil, nil
579 }
580 return nil, d.ArgErr()
581 }
582 modID := "dns.providers." + d.Val()
583 unm, err := caddyfile.UnmarshalModule(d, modID)
584 if err != nil {
585 return nil, err
586 }
587 switch unm.(type) {
588 case libdns.RecordGetter,
589 libdns.RecordSetter,
590 libdns.RecordAppender,
591 libdns.RecordDeleter:
592 default:
593 return nil, d.Errf("module %s (%T) is not a libdns provider", modID, unm)
594 }
595 return unm, nil
596 }
597
598 func parseOptECH(d *caddyfile.Dispenser, _ any) (any, error) {
599 d.Next() // consume option name
600
601 ech := new(caddytls.ECH)
602
603 publicNames := d.RemainingArgs()
604 for _, publicName := range publicNames {
605 ech.Configs = append(ech.Configs, caddytls.ECHConfiguration{
606 PublicName: publicName,
607 })
608 }
609 if len(ech.Configs) == 0 {
610 return nil, d.ArgErr()
611 }
612
613 for nesting := d.Nesting(); d.NextBlock(nesting); {
614 switch d.Val() {
615 case "dns":
616 if !d.Next() {
617 return nil, d.ArgErr()
618 }
619 providerName := d.Val()
620 modID := "dns.providers." + providerName
621 unm, err := caddyfile.UnmarshalModule(d, modID)
622 if err != nil {
623 return nil, err
624 }
625 ech.Publication = append(ech.Publication, &caddytls.ECHPublication{
626 Configs: publicNames,
627 PublishersRaw: caddy.ModuleMap{
628 "dns": caddyconfig.JSON(caddytls.ECHDNSPublisher{
629 ProviderRaw: caddyconfig.JSONModuleObject(unm, "name", providerName, nil),
630 }, nil),
631 },
632 })
633 default:
634 return nil, d.Errf("ech: unrecognized subdirective '%s'", d.Val())
635 }
636 }
637
638 return ech, nil
639 }
640
641 func parseOptRenewalWindowRatio(d *caddyfile.Dispenser, _ any) (any, error) {
642 d.Next() // consume option name
643 if !d.Next() {
644 return 0, d.ArgErr()
645 }
646 val := d.Val()
647 ratio, err := strconv.ParseFloat(val, 64)
648 if err != nil {
649 return 0, d.Errf("parsing renewal_window_ratio: %v", err)
650 }
651 if ratio <= 0 || ratio >= 1 {
652 return 0, d.Errf("renewal_window_ratio must be between 0 and 1 (exclusive)")
653 }
654 if d.Next() {
655 return 0, d.ArgErr()
656 }
657 return ratio, nil
658 }