Debian Codegraph @

caddyconfig/httpcaddyfile/httptype.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 "cmp"
19 "encoding/json"
20 "fmt"
21 "net"
22 "reflect"
23 "slices"
24 "sort"
25 "strconv"
26 "strings"
27
28 "go.uber.org/zap"
29
30 "github.com/caddyserver/caddy/v2"
31 "github.com/caddyserver/caddy/v2/caddyconfig"
32 "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
33 "github.com/caddyserver/caddy/v2/modules/caddyhttp"
34 "github.com/caddyserver/caddy/v2/modules/caddypki"
35 "github.com/caddyserver/caddy/v2/modules/caddytls"
36 )
37
38 func init() {
39 caddyconfig.RegisterAdapter("caddyfile", caddyfile.Adapter{ServerType: ServerType{}})
40 }
41
42 // App represents the configuration for a non-standard
43 // Caddy app module (e.g. third-party plugin) which was
44 // parsed from a global options block.
45 type App struct {
46 // The JSON key for the app being configured
47 Name string
48
49 // The raw app config as JSON
50 Value json.RawMessage
51 }
52
53 // ServerType can set up a config from an HTTP Caddyfile.
54 type ServerType struct{}
55
56 // Setup makes a config from the tokens.
57 func (st ServerType) Setup(
58 inputServerBlocks []caddyfile.ServerBlock,
59 options map[string]any,
60 ) (*caddy.Config, []caddyconfig.Warning, error) {
61 var warnings []caddyconfig.Warning
62 gc := counter{new(int)}
63 state := make(map[string]any)
64
65 // load all the server blocks and associate them with a "pile" of config values
66 originalServerBlocks := make([]serverBlock, 0, len(inputServerBlocks))
67 for _, sblock := range inputServerBlocks {
68 for j, k := range sblock.Keys {
69 if j == 0 && strings.HasPrefix(k.Text, "@") {
70 return nil, warnings, fmt.Errorf("%s:%d: cannot define a matcher outside of a site block: '%s'", k.File, k.Line, k.Text)
71 }
72 if _, ok := registeredDirectives[k.Text]; ok {
73 return nil, warnings, fmt.Errorf("%s:%d: parsed '%s' as a site address, but it is a known directive; directives must appear in a site block", k.File, k.Line, k.Text)
74 }
75 }
76 originalServerBlocks = append(originalServerBlocks, serverBlock{
77 block: sblock,
78 pile: make(map[string][]ConfigValue),
79 })
80 }
81
82 // apply any global options
83 var err error
84 originalServerBlocks, err = st.evaluateGlobalOptionsBlock(originalServerBlocks, options)
85 if err != nil {
86 return nil, warnings, err
87 }
88
89 // this will replace both static and user-defined placeholder shorthands
90 // with actual identifiers used by Caddy
91 replacer := NewShorthandReplacer()
92
93 originalServerBlocks, err = st.extractNamedRoutes(originalServerBlocks, options, &warnings, replacer)
94 if err != nil {
95 return nil, warnings, err
96 }
97
98 for _, sb := range originalServerBlocks {
99 for i := range sb.block.Segments {
100 replacer.ApplyToSegment(&sb.block.Segments[i])
101 }
102
103 if len(sb.block.Keys) == 0 {
104 return nil, warnings, fmt.Errorf("server block without any key is global configuration, and if used, it must be first")
105 }
106
107 // extract matcher definitions
108 matcherDefs := make(map[string]caddy.ModuleMap)
109 for _, segment := range sb.block.Segments {
110 if dir := segment.Directive(); strings.HasPrefix(dir, matcherPrefix) {
111 d := caddyfile.NewDispenser(segment)
112 err := parseMatcherDefinitions(d, matcherDefs)
113 if err != nil {
114 return nil, warnings, err
115 }
116 }
117 }
118
119 // evaluate each directive ("segment") in this block
120 for _, segment := range sb.block.Segments {
121 dir := segment.Directive()
122
123 if strings.HasPrefix(dir, matcherPrefix) {
124 // matcher definitions were pre-processed
125 continue
126 }
127
128 dirFunc, ok := registeredDirectives[dir]
129 if !ok {
130 tkn := segment[0]
131 message := "%s:%d: unrecognized directive: %s"
132 if !sb.block.HasBraces {
133 message += "\nDid you mean to define a second site? If so, you must use curly braces around each site to separate their configurations."
134 }
135 return nil, warnings, fmt.Errorf(message, tkn.File, tkn.Line, dir)
136 }
137
138 h := Helper{
139 Dispenser: caddyfile.NewDispenser(segment),
140 options: options,
141 warnings: &warnings,
142 matcherDefs: matcherDefs,
143 parentBlock: sb.block,
144 groupCounter: gc,
145 State: state,
146 BlockState: state,
147 }
148
149 results, err := dirFunc(h)
150 if err != nil {
151 return nil, warnings, fmt.Errorf("parsing caddyfile tokens for '%s': %v", dir, err)
152 }
153
154 dir = normalizeDirectiveName(dir)
155
156 for _, result := range results {
157 result.directive = dir
158 sb.pile[result.Class] = append(sb.pile[result.Class], result)
159 }
160
161 // specially handle named routes that were pulled out from
162 // the invoke directive, which could be nested anywhere within
163 // some subroutes in this directive; we add them to the pile
164 // for this server block
165 if state[namedRouteKey] != nil {
166 for name := range state[namedRouteKey].(map[string]struct{}) {
167 result := ConfigValue{Class: namedRouteKey, Value: name}
168 sb.pile[result.Class] = append(sb.pile[result.Class], result)
169 }
170 state[namedRouteKey] = nil
171 }
172 }
173 }
174
175 // map
176 sbmap, err := st.mapAddressToProtocolToServerBlocks(originalServerBlocks, options)
177 if err != nil {
178 return nil, warnings, err
179 }
180
181 // reduce
182 pairings := st.consolidateAddrMappings(sbmap)
183
184 // each pairing of listener addresses to list of server
185 // blocks is basically a server definition
186 servers, err := st.serversFromPairings(pairings, options, &warnings, gc)
187 if err != nil {
188 return nil, warnings, err
189 }
190
191 // hoist the metrics config from per-server to global
192 metrics, _ := options["metrics"].(*caddyhttp.Metrics)
193 for _, s := range servers {
194 if s.Metrics != nil {
195 metrics = cmp.Or(metrics, &caddyhttp.Metrics{})
196 metrics = &caddyhttp.Metrics{
197 PerHost: metrics.PerHost || s.Metrics.PerHost,
198 }
199 s.Metrics = nil // we don't need it anymore
200 }
201 }
202
203 // now that each server is configured, make the HTTP app
204 httpApp := caddyhttp.App{
205 HTTPPort: tryInt(options["http_port"], &warnings),
206 HTTPSPort: tryInt(options["https_port"], &warnings),
207 GracePeriod: tryDuration(options["grace_period"], &warnings),
208 ShutdownDelay: tryDuration(options["shutdown_delay"], &warnings),
209 Metrics: metrics,
210 Servers: servers,
211 }
212
213 // then make the TLS app
214 tlsApp, warnings, err := st.buildTLSApp(pairings, options, warnings)
215 if err != nil {
216 return nil, warnings, err
217 }
218
219 // then make the PKI app
220 pkiApp, warnings, err := st.buildPKIApp(pairings, options, warnings)
221 if err != nil {
222 return nil, warnings, err
223 }
224
225 // extract any custom logs, and enforce configured levels
226 var customLogs []namedCustomLog
227 var hasDefaultLog bool
228 addCustomLog := func(ncl namedCustomLog) {
229 if ncl.name == "" {
230 return
231 }
232 if ncl.name == caddy.DefaultLoggerName {
233 hasDefaultLog = true
234 }
235 if _, ok := options["debug"]; ok && ncl.log != nil && ncl.log.Level == "" {
236 ncl.log.Level = zap.DebugLevel.CapitalString()
237 }
238 customLogs = append(customLogs, ncl)
239 }
240
241 // Apply global log options, when set
242 if options["log"] != nil {
243 for _, logValue := range options["log"].([]ConfigValue) {
244 addCustomLog(logValue.Value.(namedCustomLog))
245 }
246 }
247
248 if !hasDefaultLog {
249 // if the default log was not customized, ensure we
250 // configure it with any applicable options
251 if _, ok := options["debug"]; ok {
252 customLogs = append(customLogs, namedCustomLog{
253 name: caddy.DefaultLoggerName,
254 log: &caddy.CustomLog{
255 BaseLog: caddy.BaseLog{Level: zap.DebugLevel.CapitalString()},
256 },
257 })
258 }
259 }
260
261 // Apply server-specific log options
262 for _, p := range pairings {
263 for _, sb := range p.serverBlocks {
264 for _, clVal := range sb.pile["custom_log"] {
265 addCustomLog(clVal.Value.(namedCustomLog))
266 }
267 }
268 }
269
270 // annnd the top-level config, then we're done!
271 cfg := &caddy.Config{AppsRaw: make(caddy.ModuleMap)}
272
273 // loop through the configured options, and if any of
274 // them are an httpcaddyfile App, then we insert them
275 // into the config as raw Caddy apps
276 for _, opt := range options {
277 if app, ok := opt.(App); ok {
278 cfg.AppsRaw[app.Name] = app.Value
279 }
280 }
281
282 // insert the standard Caddy apps into the config
283 if len(httpApp.Servers) > 0 {
284 cfg.AppsRaw["http"] = caddyconfig.JSON(httpApp, &warnings)
285 }
286 if !reflect.DeepEqual(tlsApp, &caddytls.TLS{CertificatesRaw: make(caddy.ModuleMap)}) {
287 cfg.AppsRaw["tls"] = caddyconfig.JSON(tlsApp, &warnings)
288 }
289 if !reflect.DeepEqual(pkiApp, &caddypki.PKI{CAs: make(map[string]*caddypki.CA)}) {
290 cfg.AppsRaw["pki"] = caddyconfig.JSON(pkiApp, &warnings)
291 }
292 if filesystems, ok := options["filesystem"].(caddy.Module); ok {
293 cfg.AppsRaw["caddy.filesystems"] = caddyconfig.JSON(
294 filesystems,
295 &warnings)
296 }
297
298 if storageCvtr, ok := options["storage"].(caddy.StorageConverter); ok {
299 cfg.StorageRaw = caddyconfig.JSONModuleObject(storageCvtr,
300 "module",
301 storageCvtr.(caddy.Module).CaddyModule().ID.Name(),
302 &warnings)
303 }
304 if adminConfig, ok := options["admin"].(*caddy.AdminConfig); ok && adminConfig != nil {
305 cfg.Admin = adminConfig
306 }
307 if pc, ok := options["persist_config"].(string); ok && pc == "off" {
308 if cfg.Admin == nil {
309 cfg.Admin = new(caddy.AdminConfig)
310 }
311 if cfg.Admin.Config == nil {
312 cfg.Admin.Config = new(caddy.ConfigSettings)
313 }
314 cfg.Admin.Config.Persist = new(bool)
315 }
316
317 if len(customLogs) > 0 {
318 if cfg.Logging == nil {
319 cfg.Logging = &caddy.Logging{
320 Logs: make(map[string]*caddy.CustomLog),
321 }
322 }
323
324 // Add the default log first if defined, so that it doesn't
325 // accidentally get re-created below due to the Exclude logic
326 for _, ncl := range customLogs {
327 if ncl.name == caddy.DefaultLoggerName && ncl.log != nil {
328 cfg.Logging.Logs[caddy.DefaultLoggerName] = ncl.log
329 break
330 }
331 }
332
333 // Add the rest of the custom logs
334 for _, ncl := range customLogs {
335 if ncl.log == nil || ncl.name == caddy.DefaultLoggerName {
336 continue
337 }
338 if ncl.name != "" {
339 cfg.Logging.Logs[ncl.name] = ncl.log
340 }
341 // most users seem to prefer not writing access logs
342 // to the default log when they are directed to a
343 // file or have any other special customization
344 if ncl.name != caddy.DefaultLoggerName && len(ncl.log.Include) > 0 {
345 defaultLog, ok := cfg.Logging.Logs[caddy.DefaultLoggerName]
346 if !ok {
347 defaultLog = new(caddy.CustomLog)
348 cfg.Logging.Logs[caddy.DefaultLoggerName] = defaultLog
349 }
350 defaultLog.Exclude = append(defaultLog.Exclude, ncl.log.Include...)
351
352 // avoid duplicates by sorting + compacting
353 sort.Strings(defaultLog.Exclude)
354 defaultLog.Exclude = slices.Compact(defaultLog.Exclude)
355 }
356 }
357 // we may have not actually added anything, so remove if empty
358 if len(cfg.Logging.Logs) == 0 {
359 cfg.Logging = nil
360 }
361 }
362
363 return cfg, warnings, nil
364 }
365
366 // evaluateGlobalOptionsBlock evaluates the global options block,
367 // which is expected to be the first server block if it has zero
368 // keys. It returns the updated list of server blocks with the
369 // global options block removed, and updates options accordingly.
370 func (ServerType) evaluateGlobalOptionsBlock(serverBlocks []serverBlock, options map[string]any) ([]serverBlock, error) {
371 if len(serverBlocks) == 0 || len(serverBlocks[0].block.Keys) > 0 {
372 return serverBlocks, nil
373 }
374
375 for _, segment := range serverBlocks[0].block.Segments {
376 opt := segment.Directive()
377 var val any
378 var err error
379 disp := caddyfile.NewDispenser(segment)
380
381 optFunc, ok := registeredGlobalOptions[opt]
382 if !ok {
383 tkn := segment[0]
384 return nil, fmt.Errorf("%s:%d: unrecognized global option: %s", tkn.File, tkn.Line, opt)
385 }
386
387 val, err = optFunc(disp, options[opt])
388 if err != nil {
389 return nil, fmt.Errorf("parsing caddyfile tokens for '%s': %v", opt, err)
390 }
391
392 // As a special case, fold multiple "servers" options together
393 // in an array instead of overwriting a possible existing value
394 if opt == "servers" {
395 existingOpts, ok := options[opt].([]serverOptions)
396 if !ok {
397 existingOpts = []serverOptions{}
398 }
399 serverOpts, ok := val.(serverOptions)
400 if !ok {
401 return nil, fmt.Errorf("unexpected type from 'servers' global options: %T", val)
402 }
403 options[opt] = append(existingOpts, serverOpts)
404 continue
405 }
406 // Additionally, fold multiple "log" options together into an
407 // array so that multiple loggers can be configured.
408 if opt == "log" {
409 existingOpts, ok := options[opt].([]ConfigValue)
410 if !ok {
411 existingOpts = []ConfigValue{}
412 }
413 logOpts, ok := val.([]ConfigValue)
414 if !ok {
415 return nil, fmt.Errorf("unexpected type from 'log' global options: %T", val)
416 }
417 options[opt] = append(existingOpts, logOpts...)
418 continue
419 }
420 // Also fold multiple "default_bind" options together into an
421 // array so that server blocks can have multiple binds by default.
422 if opt == "default_bind" {
423 existingOpts, ok := options[opt].([]ConfigValue)
424 if !ok {
425 existingOpts = []ConfigValue{}
426 }
427 defaultBindOpts, ok := val.([]ConfigValue)
428 if !ok {
429 return nil, fmt.Errorf("unexpected type from 'default_bind' global options: %T", val)
430 }
431 options[opt] = append(existingOpts, defaultBindOpts...)
432 continue
433 }
434
435 options[opt] = val
436 }
437
438 // If we got "servers" options, we'll sort them by their listener address
439 if serverOpts, ok := options["servers"].([]serverOptions); ok {
440 sort.Slice(serverOpts, func(i, j int) bool {
441 return len(serverOpts[i].ListenerAddress) > len(serverOpts[j].ListenerAddress)
442 })
443
444 // Reject the config if there are duplicate listener address
445 seen := make(map[string]bool)
446 for _, entry := range serverOpts {
447 if _, alreadySeen := seen[entry.ListenerAddress]; alreadySeen {
448 return nil, fmt.Errorf("cannot have 'servers' global options with duplicate listener addresses: %s", entry.ListenerAddress)
449 }
450 seen[entry.ListenerAddress] = true
451 }
452 }
453
454 return serverBlocks[1:], nil
455 }
456
457 // extractNamedRoutes pulls out any named route server blocks
458 // so they don't get parsed as sites, and stores them in options
459 // for later.
460 func (ServerType) extractNamedRoutes(
461 serverBlocks []serverBlock,
462 options map[string]any,
463 warnings *[]caddyconfig.Warning,
464 replacer ShorthandReplacer,
465 ) ([]serverBlock, error) {
466 namedRoutes := map[string]*caddyhttp.Route{}
467
468 gc := counter{new(int)}
469 state := make(map[string]any)
470
471 // copy the server blocks so we can
472 // splice out the named route ones
473 filtered := append([]serverBlock{}, serverBlocks...)
474 index := -1
475
476 for _, sb := range serverBlocks {
477 index++
478 if !sb.block.IsNamedRoute {
479 continue
480 }
481
482 // splice out this block, because we know it's not a real server
483 filtered = append(filtered[:index], filtered[index+1:]...)
484 index--
485
486 if len(sb.block.Segments) == 0 {
487 continue
488 }
489
490 wholeSegment := caddyfile.Segment{}
491 for i := range sb.block.Segments {
492 // replace user-defined placeholder shorthands in extracted named routes
493 replacer.ApplyToSegment(&sb.block.Segments[i])
494
495 // zip up all the segments since ParseSegmentAsSubroute
496 // was designed to take a directive+
497 wholeSegment = append(wholeSegment, sb.block.Segments[i]...)
498 }
499
500 h := Helper{
501 Dispenser: caddyfile.NewDispenser(wholeSegment),
502 options: options,
503 warnings: warnings,
504 matcherDefs: nil,
505 parentBlock: sb.block,
506 groupCounter: gc,
507 State: state,
508 BlockState: state,
509 }
510
511 handler, err := ParseSegmentAsSubroute(h)
512 if err != nil {
513 return nil, err
514 }
515 subroute := handler.(*caddyhttp.Subroute)
516 route := caddyhttp.Route{}
517
518 if len(subroute.Routes) == 1 && len(subroute.Routes[0].MatcherSetsRaw) == 0 {
519 // if there's only one route with no matcher, then we can simplify
520 route.HandlersRaw = append(route.HandlersRaw, subroute.Routes[0].HandlersRaw[0])
521 } else {
522 // otherwise we need the whole subroute
523 route.HandlersRaw = []json.RawMessage{caddyconfig.JSONModuleObject(handler, "handler", subroute.CaddyModule().ID.Name(), h.warnings)}
524 }
525
526 namedRoutes[sb.block.GetKeysText()[0]] = &route
527 }
528 options["named_routes"] = namedRoutes
529
530 return filtered, nil
531 }
532
533 // serversFromPairings creates the servers for each pairing of addresses
534 // to server blocks. Each pairing is essentially a server definition.
535 func (st *ServerType) serversFromPairings(
536 pairings []sbAddrAssociation,
537 options map[string]any,
538 warnings *[]caddyconfig.Warning,
539 groupCounter counter,
540 ) (map[string]*caddyhttp.Server, error) {
541 servers := make(map[string]*caddyhttp.Server)
542 defaultSNI := tryString(options["default_sni"], warnings)
543 fallbackSNI := tryString(options["fallback_sni"], warnings)
544
545 httpPort := strconv.Itoa(caddyhttp.DefaultHTTPPort)
546 if hp, ok := options["http_port"].(int); ok {
547 httpPort = strconv.Itoa(hp)
548 }
549 httpsPort := strconv.Itoa(caddyhttp.DefaultHTTPSPort)
550 if hsp, ok := options["https_port"].(int); ok {
551 httpsPort = strconv.Itoa(hsp)
552 }
553 autoHTTPS := []string{}
554 if ah, ok := options["auto_https"].([]string); ok {
555 autoHTTPS = ah
556 }
557
558 for i, p := range pairings {
559 // detect ambiguous site definitions: server blocks which
560 // have the same host bound to the same interface (listener
561 // address), otherwise their routes will improperly be added
562 // to the same server (see issue #4635)
563 for j, sblock1 := range p.serverBlocks {
564 for _, key := range sblock1.block.GetKeysText() {
565 for k, sblock2 := range p.serverBlocks {
566 if k == j {
567 continue
568 }
569 if slices.Contains(sblock2.block.GetKeysText(), key) {
570 return nil, fmt.Errorf("ambiguous site definition: %s", key)
571 }
572 }
573 }
574 }
575
576 var (
577 addresses []string
578 protocols [][]string
579 )
580
581 for _, addressWithProtocols := range p.addressesWithProtocols {
582 addresses = append(addresses, addressWithProtocols.address)
583 protocols = append(protocols, addressWithProtocols.protocols)
584 }
585
586 srv := &caddyhttp.Server{
587 Listen: addresses,
588 ListenProtocols: protocols,
589 }
590
591 // remove srv.ListenProtocols[j] if it only contains the default protocols
592 for j, lnProtocols := range srv.ListenProtocols {
593 srv.ListenProtocols[j] = nil
594 for _, lnProtocol := range lnProtocols {
595 if lnProtocol != "" {
596 srv.ListenProtocols[j] = lnProtocols
597 break
598 }
599 }
600 }
601
602 // remove srv.ListenProtocols if it only contains the default protocols for all listen addresses
603 listenProtocols := srv.ListenProtocols
604 srv.ListenProtocols = nil
605 for _, lnProtocols := range listenProtocols {
606 if lnProtocols != nil {
607 srv.ListenProtocols = listenProtocols
608 break
609 }
610 }
611
612 // handle the auto_https global option
613 for _, val := range autoHTTPS {
614 switch val {
615 case "off":
616 if srv.AutoHTTPS == nil {
617 srv.AutoHTTPS = new(caddyhttp.AutoHTTPSConfig)
618 }
619 srv.AutoHTTPS.Disabled = true
620
621 case "disable_redirects":
622 if srv.AutoHTTPS == nil {
623 srv.AutoHTTPS = new(caddyhttp.AutoHTTPSConfig)
624 }
625 srv.AutoHTTPS.DisableRedir = true
626
627 case "disable_certs":
628 if srv.AutoHTTPS == nil {
629 srv.AutoHTTPS = new(caddyhttp.AutoHTTPSConfig)
630 }
631 srv.AutoHTTPS.DisableCerts = true
632
633 case "ignore_loaded_certs":
634 if srv.AutoHTTPS == nil {
635 srv.AutoHTTPS = new(caddyhttp.AutoHTTPSConfig)
636 }
637 srv.AutoHTTPS.IgnoreLoadedCerts = true
638 }
639 }
640
641 // Using paths in site addresses is deprecated
642 // See ParseAddress() where parsing should later reject paths
643 // See https://github.com/caddyserver/caddy/pull/4728 for a full explanation
644 for _, sblock := range p.serverBlocks {
645 for _, addr := range sblock.parsedKeys {
646 if addr.Path != "" {
647 caddy.Log().Named("caddyfile").Warn("Using a path in a site address is deprecated; please use the 'handle' directive instead", zap.String("address", addr.String()))
648 }
649 }
650 }
651
652 // sort server blocks by their keys; this is important because
653 // only the first matching site should be evaluated, and we should
654 // attempt to match most specific site first (host and path), in
655 // case their matchers overlap; we do this somewhat naively by
656 // descending sort by length of host then path
657 sort.SliceStable(p.serverBlocks, func(i, j int) bool {
658 // TODO: we could pre-process the specificities for efficiency,
659 // but I don't expect many blocks will have THAT many keys...
660 var iLongestPath, jLongestPath string
661 var iLongestHost, jLongestHost string
662 var iWildcardHost, jWildcardHost bool
663 for _, addr := range p.serverBlocks[i].parsedKeys {
664 if strings.Contains(addr.Host, "*") || addr.Host == "" {
665 iWildcardHost = true
666 }
667 if specificity(addr.Host) > specificity(iLongestHost) {
668 iLongestHost = addr.Host
669 }
670 if specificity(addr.Path) > specificity(iLongestPath) {
671 iLongestPath = addr.Path
672 }
673 }
674 for _, addr := range p.serverBlocks[j].parsedKeys {
675 if strings.Contains(addr.Host, "*") || addr.Host == "" {
676 jWildcardHost = true
677 }
678 if specificity(addr.Host) > specificity(jLongestHost) {
679 jLongestHost = addr.Host
680 }
681 if specificity(addr.Path) > specificity(jLongestPath) {
682 jLongestPath = addr.Path
683 }
684 }
685 // catch-all blocks (blocks with no hostname) should always go
686 // last, even after blocks with wildcard hosts
687 if specificity(iLongestHost) == 0 {
688 return false
689 }
690 if specificity(jLongestHost) == 0 {
691 return true
692 }
693 if iWildcardHost != jWildcardHost {
694 // site blocks that have a key with a wildcard in the hostname
695 // must always be less specific than blocks without one; see
696 // https://github.com/caddyserver/caddy/issues/3410
697 return jWildcardHost && !iWildcardHost
698 }
699 if specificity(iLongestHost) == specificity(jLongestHost) {
700 return len(iLongestPath) > len(jLongestPath)
701 }
702 return specificity(iLongestHost) > specificity(jLongestHost)
703 })
704
705 var hasCatchAllTLSConnPolicy, addressQualifiesForTLS bool
706 autoHTTPSWillAddConnPolicy := srv.AutoHTTPS == nil || !srv.AutoHTTPS.Disabled
707
708 // if needed, the ServerLogConfig is initialized beforehand so
709 // that all server blocks can populate it with data, even when not
710 // coming with a log directive
711 for _, sblock := range p.serverBlocks {
712 if len(sblock.pile["custom_log"]) != 0 {
713 srv.Logs = new(caddyhttp.ServerLogConfig)
714 break
715 }
716 }
717
718 // add named routes to the server if 'invoke' was used inside of it
719 configuredNamedRoutes := options["named_routes"].(map[string]*caddyhttp.Route)
720 for _, sblock := range p.serverBlocks {
721 if len(sblock.pile[namedRouteKey]) == 0 {
722 continue
723 }
724 for _, value := range sblock.pile[namedRouteKey] {
725 if srv.NamedRoutes == nil {
726 srv.NamedRoutes = map[string]*caddyhttp.Route{}
727 }
728 name := value.Value.(string)
729 if configuredNamedRoutes[name] == nil {
730 return nil, fmt.Errorf("cannot invoke named route '%s', which was not defined", name)
731 }
732 srv.NamedRoutes[name] = configuredNamedRoutes[name]
733 }
734 }
735
736 // create a subroute for each site in the server block
737 for _, sblock := range p.serverBlocks {
738 matcherSetsEnc, err := st.compileEncodedMatcherSets(sblock)
739 if err != nil {
740 return nil, fmt.Errorf("server block %v: compiling matcher sets: %v", sblock.block.Keys, err)
741 }
742
743 hosts := sblock.hostsFromKeys(false)
744
745 // emit warnings if user put unspecified IP addresses; they probably want the bind directive
746 for _, h := range hosts {
747 if h == "0.0.0.0" || h == "::" {
748 caddy.Log().Named("caddyfile").Warn("Site block has an unspecified IP address which only matches requests having that Host header; you probably want the 'bind' directive to configure the socket", zap.String("address", h))
749 }
750 }
751
752 // collect hosts that are forced to be automated
753 forceAutomatedNames := make(map[string]struct{})
754 if _, ok := sblock.pile["tls.force_automate"]; ok {
755 for _, host := range hosts {
756 forceAutomatedNames[host] = struct{}{}
757 }
758 }
759
760 // tls: connection policies
761 if cpVals, ok := sblock.pile["tls.connection_policy"]; ok {
762 // tls connection policies
763 for _, cpVal := range cpVals {
764 cp := cpVal.Value.(*caddytls.ConnectionPolicy)
765
766 // make sure the policy covers all hostnames from the block
767 for _, h := range hosts {
768 if h == defaultSNI {
769 hosts = append(hosts, "")
770 cp.DefaultSNI = defaultSNI
771 break
772 }
773 if h == fallbackSNI {
774 hosts = append(hosts, "")
775 cp.FallbackSNI = fallbackSNI
776 break
777 }
778 }
779
780 if len(hosts) > 0 {
781 slices.Sort(hosts) // for deterministic JSON output
782 cp.MatchersRaw = caddy.ModuleMap{
783 "sni": caddyconfig.JSON(hosts, warnings), // make sure to match all hosts, not just auto-HTTPS-qualified ones
784 }
785 } else {
786 cp.DefaultSNI = defaultSNI
787 cp.FallbackSNI = fallbackSNI
788 }
789
790 // only append this policy if it actually changes something,
791 // or if the configuration explicitly automates certs for
792 // these names (this is necessary to hoist a connection policy
793 // above one that may manually load a wildcard cert that would
794 // otherwise clobber the automated one; the code that appends
795 // policies that manually load certs comes later, so they're
796 // lower in the list)
797 if !cp.SettingsEmpty() || mapContains(forceAutomatedNames, hosts) {
798 srv.TLSConnPolicies = append(srv.TLSConnPolicies, cp)
799 hasCatchAllTLSConnPolicy = len(hosts) == 0
800 }
801 }
802 }
803
804 for _, addr := range sblock.parsedKeys {
805 // if server only uses HTTP port, auto-HTTPS will not apply
806 if listenersUseAnyPortOtherThan(srv.Listen, httpPort) {
807 // exclude any hosts that were defined explicitly with "http://"
808 // in the key from automated cert management (issue #2998)
809 if addr.Scheme == "http" && addr.Host != "" {
810 if srv.AutoHTTPS == nil {
811 srv.AutoHTTPS = new(caddyhttp.AutoHTTPSConfig)
812 }
813 if !slices.Contains(srv.AutoHTTPS.Skip, addr.Host) {
814 srv.AutoHTTPS.Skip = append(srv.AutoHTTPS.Skip, addr.Host)
815 }
816 }
817 }
818
819 // If TLS is specified as directive, it will also result in 1 or more connection policy being created
820 // Thus, catch-all address with non-standard port, e.g. :8443, can have TLS enabled without
821 // specifying prefix "https://"
822 // Second part of the condition is to allow creating TLS conn policy even though `auto_https` has been disabled
823 // ensuring compatibility with behavior described in below link
824 // https://caddy.community/t/making-sense-of-auto-https-and-why-disabling-it-still-serves-https-instead-of-http/9761
825 createdTLSConnPolicies, ok := sblock.pile["tls.connection_policy"]
826 hasTLSEnabled := (ok && len(createdTLSConnPolicies) > 0) ||
827 (addr.Host != "" && (srv.AutoHTTPS == nil || !slices.Contains(srv.AutoHTTPS.Skip, addr.Host)))
828
829 // we'll need to remember if the address qualifies for auto-HTTPS, so we
830 // can add a TLS conn policy if necessary
831 if addr.Scheme == "https" ||
832 (addr.Scheme != "http" && addr.Port != httpPort && hasTLSEnabled) {
833 addressQualifiesForTLS = true
834 }
835
836 // predict whether auto-HTTPS will add the conn policy for us; if so, we
837 // may not need to add one for this server
838 autoHTTPSWillAddConnPolicy = autoHTTPSWillAddConnPolicy &&
839 (addr.Port == httpsPort || (addr.Port != httpPort && addr.Host != ""))
840 }
841
842 // Look for any config values that provide listener wrappers on the server block
843 for _, listenerConfig := range sblock.pile["listener_wrapper"] {
844 listenerWrapper, ok := listenerConfig.Value.(caddy.ListenerWrapper)
845 if !ok {
846 return nil, fmt.Errorf("config for a listener wrapper did not provide a value that implements caddy.ListenerWrapper")
847 }
848 jsonListenerWrapper := caddyconfig.JSONModuleObject(
849 listenerWrapper,
850 "wrapper",
851 listenerWrapper.(caddy.Module).CaddyModule().ID.Name(),
852 warnings)
853 srv.ListenerWrappersRaw = append(srv.ListenerWrappersRaw, jsonListenerWrapper)
854 }
855
856 // Look for any config values that provide packet conn wrappers on the server block
857 for _, listenerConfig := range sblock.pile["packet_conn_wrapper"] {
858 packetConnWrapper, ok := listenerConfig.Value.(caddy.PacketConnWrapper)
859 if !ok {
860 return nil, fmt.Errorf("config for a packet conn wrapper did not provide a value that implements caddy.PacketConnWrapper")
861 }
862 jsonPacketConnWrapper := caddyconfig.JSONModuleObject(
863 packetConnWrapper,
864 "wrapper",
865 packetConnWrapper.(caddy.Module).CaddyModule().ID.Name(),
866 warnings)
867 srv.PacketConnWrappersRaw = append(srv.PacketConnWrappersRaw, jsonPacketConnWrapper)
868 }
869
870 // set up each handler directive, making sure to honor directive order
871 dirRoutes := sblock.pile["route"]
872 siteSubroute, err := buildSubroute(dirRoutes, groupCounter, true)
873 if err != nil {
874 return nil, err
875 }
876
877 // add the site block's route(s) to the server
878 srv.Routes = appendSubrouteToRouteList(srv.Routes, siteSubroute, matcherSetsEnc, p, warnings)
879
880 // if error routes are defined, add those too
881 if errorSubrouteVals, ok := sblock.pile["error_route"]; ok {
882 if srv.Errors == nil {
883 srv.Errors = new(caddyhttp.HTTPErrorConfig)
884 }
885 sort.SliceStable(errorSubrouteVals, func(i, j int) bool {
886 sri, srj := errorSubrouteVals[i].Value.(*caddyhttp.Subroute), errorSubrouteVals[j].Value.(*caddyhttp.Subroute)
887 if len(sri.Routes[0].MatcherSetsRaw) == 0 && len(srj.Routes[0].MatcherSetsRaw) != 0 {
888 return false
889 }
890 return true
891 })
892 errorsSubroute := &caddyhttp.Subroute{}
893 for _, val := range errorSubrouteVals {
894 sr := val.Value.(*caddyhttp.Subroute)
895 errorsSubroute.Routes = append(errorsSubroute.Routes, sr.Routes...)
896 }
897 srv.Errors.Routes = appendSubrouteToRouteList(srv.Errors.Routes, errorsSubroute, matcherSetsEnc, p, warnings)
898 }
899
900 // add log associations
901 // see https://github.com/caddyserver/caddy/issues/3310
902 sblockLogHosts := sblock.hostsFromKeys(true)
903 for _, cval := range sblock.pile["custom_log"] {
904 ncl := cval.Value.(namedCustomLog)
905
906 // if `no_hostname` is set, then this logger will not
907 // be associated with any of the site block's hostnames,
908 // and only be usable via the `log_name` directive
909 // or the `access_logger_names` variable
910 if ncl.noHostname {
911 continue
912 }
913
914 if sblock.hasHostCatchAllKey() && len(ncl.hostnames) == 0 {
915 // all requests for hosts not able to be listed should use
916 // this log because it's a catch-all-hosts server block
917 srv.Logs.DefaultLoggerName = ncl.name
918 } else if len(ncl.hostnames) > 0 {
919 // if the logger overrides the hostnames, map that to the logger name
920 for _, h := range ncl.hostnames {
921 if srv.Logs.LoggerNames == nil {
922 srv.Logs.LoggerNames = make(map[string]caddyhttp.StringArray)
923 }
924 srv.Logs.LoggerNames[h] = append(srv.Logs.LoggerNames[h], ncl.name)
925 }
926 } else {
927 // otherwise, map each host to the logger name
928 for _, h := range sblockLogHosts {
929 // strip the port from the host, if any
930 host, _, err := net.SplitHostPort(h)
931 if err != nil {
932 host = h
933 }
934 if srv.Logs.LoggerNames == nil {
935 srv.Logs.LoggerNames = make(map[string]caddyhttp.StringArray)
936 }
937 srv.Logs.LoggerNames[host] = append(srv.Logs.LoggerNames[host], ncl.name)
938 }
939 }
940 }
941 if srv.Logs != nil && len(sblock.pile["custom_log"]) == 0 {
942 // server has access logs enabled, but this server block does not
943 // enable access logs; therefore, all hosts of this server block
944 // should not be access-logged
945 if len(hosts) == 0 {
946 // if the server block has a catch-all-hosts key, then we should
947 // not log reqs to any host unless it appears in the map
948 srv.Logs.SkipUnmappedHosts = true
949 }
950 srv.Logs.SkipHosts = append(srv.Logs.SkipHosts, sblockLogHosts...)
951 }
952 }
953
954 // sort for deterministic JSON output
955 if srv.Logs != nil {
956 slices.Sort(srv.Logs.SkipHosts)
957 }
958
959 // a server cannot (natively) serve both HTTP and HTTPS at the
960 // same time, so make sure the configuration isn't in conflict
961 err := detectConflictingSchemes(srv, p.serverBlocks, options)
962 if err != nil {
963 return nil, err
964 }
965
966 // a catch-all TLS conn policy is necessary to ensure TLS can
967 // be offered to all hostnames of the server; even though only
968 // one policy is needed to enable TLS for the server, that
969 // policy might apply to only certain TLS handshakes; but when
970 // using the Caddyfile, user would expect all handshakes to at
971 // least have a matching connection policy, so here we append a
972 // catch-all/default policy if there isn't one already (it's
973 // important that it goes at the end) - see issue #3004:
974 // https://github.com/caddyserver/caddy/issues/3004
975 // TODO: maybe a smarter way to handle this might be to just make the
976 // auto-HTTPS logic at provision-time detect if there is any connection
977 // policy missing for any HTTPS-enabled hosts, if so, add it... maybe?
978 if addressQualifiesForTLS &&
979 !hasCatchAllTLSConnPolicy &&
980 (len(srv.TLSConnPolicies) > 0 || !autoHTTPSWillAddConnPolicy || defaultSNI != "" || fallbackSNI != "") {
981 srv.TLSConnPolicies = append(srv.TLSConnPolicies, &caddytls.ConnectionPolicy{
982 DefaultSNI: defaultSNI,
983 FallbackSNI: fallbackSNI,
984 })
985 }
986
987 // tidy things up a bit
988 srv.TLSConnPolicies, err = consolidateConnPolicies(srv.TLSConnPolicies)
989 if err != nil {
990 return nil, fmt.Errorf("consolidating TLS connection policies for server %d: %v", i, err)
991 }
992 srv.Routes = consolidateRoutes(srv.Routes)
993
994 servers[fmt.Sprintf("srv%d", i)] = srv
995 }
996
997 if err := applyServerOptions(servers, options, warnings); err != nil {
998 return nil, fmt.Errorf("applying global server options: %v", err)
999 }
1000
1001 return servers, nil
1002 }
1003
1004 func detectConflictingSchemes(srv *caddyhttp.Server, serverBlocks []serverBlock, options map[string]any) error {
1005 httpPort := strconv.Itoa(caddyhttp.DefaultHTTPPort)
1006 if hp, ok := options["http_port"].(int); ok {
1007 httpPort = strconv.Itoa(hp)
1008 }
1009 httpsPort := strconv.Itoa(caddyhttp.DefaultHTTPSPort)
1010 if hsp, ok := options["https_port"].(int); ok {
1011 httpsPort = strconv.Itoa(hsp)
1012 }
1013
1014 var httpOrHTTPS string
1015 checkAndSetHTTP := func(addr Address) error {
1016 if httpOrHTTPS == "HTTPS" {
1017 errMsg := fmt.Errorf("server listening on %v is configured for HTTPS and cannot natively multiplex HTTP and HTTPS: %s",
1018 srv.Listen, addr.Original)
1019 if addr.Scheme == "" && addr.Host == "" {
1020 errMsg = fmt.Errorf("%s (try specifying https:// in the address)", errMsg)
1021 }
1022 return errMsg
1023 }
1024 if len(srv.TLSConnPolicies) > 0 {
1025 // any connection policies created for an HTTP server
1026 // is a logical conflict, as it would enable HTTPS
1027 return fmt.Errorf("server listening on %v is HTTP, but attempts to configure TLS connection policies", srv.Listen)
1028 }
1029 httpOrHTTPS = "HTTP"
1030 return nil
1031 }
1032 checkAndSetHTTPS := func(addr Address) error {
1033 if httpOrHTTPS == "HTTP" {
1034 return fmt.Errorf("server listening on %v is configured for HTTP and cannot natively multiplex HTTP and HTTPS: %s",
1035 srv.Listen, addr.Original)
1036 }
1037 httpOrHTTPS = "HTTPS"
1038 return nil
1039 }
1040
1041 for _, sblock := range serverBlocks {
1042 for _, addr := range sblock.parsedKeys {
1043 if addr.Scheme == "http" || addr.Port == httpPort {
1044 if err := checkAndSetHTTP(addr); err != nil {
1045 return err
1046 }
1047 } else if addr.Scheme == "https" || addr.Port == httpsPort || len(srv.TLSConnPolicies) > 0 {
1048 if err := checkAndSetHTTPS(addr); err != nil {
1049 return err
1050 }
1051 } else if addr.Host == "" {
1052 if err := checkAndSetHTTP(addr); err != nil {
1053 return err
1054 }
1055 }
1056 }
1057 }
1058
1059 return nil
1060 }
1061
1062 // consolidateConnPolicies sorts any catch-all policy to the end, removes empty TLS connection
1063 // policies, and combines equivalent ones for a cleaner overall output.
1064 func consolidateConnPolicies(cps caddytls.ConnectionPolicies) (caddytls.ConnectionPolicies, error) {
1065 // catch-all policies (those without any matcher) should be at the
1066 // end, otherwise it nullifies any more specific policies
1067 sort.SliceStable(cps, func(i, j int) bool {
1068 return cps[j].MatchersRaw == nil && cps[i].MatchersRaw != nil
1069 })
1070
1071 for i := 0; i < len(cps); i++ {
1072 // compare it to the others
1073 for j := 0; j < len(cps); j++ {
1074 if j == i {
1075 continue
1076 }
1077
1078 // if they're exactly equal in every way, just keep one of them
1079 if reflect.DeepEqual(cps[i], cps[j]) {
1080 cps = slices.Delete(cps, j, j+1)
1081 i--
1082 break
1083 }
1084
1085 // as a special case, if there are adjacent TLS conn policies that are identical except
1086 // by their matchers, and the matchers are specifically just ServerName ("sni") matchers
1087 // (by far the most common), we can combine them into a single policy
1088 if i == j-1 && len(cps[i].MatchersRaw) == 1 && len(cps[j].MatchersRaw) == 1 {
1089 if iSNIMatcherJSON, ok := cps[i].MatchersRaw["sni"]; ok {
1090 if jSNIMatcherJSON, ok := cps[j].MatchersRaw["sni"]; ok {
1091 // position of policies and the matcher criteria check out; if settings are
1092 // the same, then we can combine the policies; we have to unmarshal and
1093 // remarshal the matchers though
1094 if cps[i].SettingsEqual(*cps[j]) {
1095 var iSNIMatcher caddytls.MatchServerName
1096 if err := json.Unmarshal(iSNIMatcherJSON, &iSNIMatcher); err == nil {
1097 var jSNIMatcher caddytls.MatchServerName
1098 if err := json.Unmarshal(jSNIMatcherJSON, &jSNIMatcher); err == nil {
1099 iSNIMatcher = append(iSNIMatcher, jSNIMatcher...)
1100 cps[i].MatchersRaw["sni"], err = json.Marshal(iSNIMatcher)
1101 if err != nil {
1102 return nil, fmt.Errorf("recombining SNI matchers: %v", err)
1103 }
1104 cps = slices.Delete(cps, j, j+1)
1105 i--
1106 break
1107 }
1108 }
1109 }
1110 }
1111 }
1112 }
1113
1114 // if they have the same matcher, try to reconcile each field: either they must
1115 // be identical, or we have to be able to combine them safely
1116 if reflect.DeepEqual(cps[i].MatchersRaw, cps[j].MatchersRaw) {
1117 if len(cps[i].ALPN) > 0 &&
1118 len(cps[j].ALPN) > 0 &&
1119 !reflect.DeepEqual(cps[i].ALPN, cps[j].ALPN) {
1120 return nil, fmt.Errorf("two policies with same match criteria have conflicting ALPN: %v vs. %v",
1121 cps[i].ALPN, cps[j].ALPN)
1122 }
1123 if len(cps[i].CipherSuites) > 0 &&
1124 len(cps[j].CipherSuites) > 0 &&
1125 !reflect.DeepEqual(cps[i].CipherSuites, cps[j].CipherSuites) {
1126 return nil, fmt.Errorf("two policies with same match criteria have conflicting cipher suites: %v vs. %v",
1127 cps[i].CipherSuites, cps[j].CipherSuites)
1128 }
1129 if cps[i].ClientAuthentication == nil &&
1130 cps[j].ClientAuthentication != nil &&
1131 !reflect.DeepEqual(cps[i].ClientAuthentication, cps[j].ClientAuthentication) {
1132 return nil, fmt.Errorf("two policies with same match criteria have conflicting client auth configuration: %+v vs. %+v",
1133 cps[i].ClientAuthentication, cps[j].ClientAuthentication)
1134 }
1135 if len(cps[i].Curves) > 0 &&
1136 len(cps[j].Curves) > 0 &&
1137 !reflect.DeepEqual(cps[i].Curves, cps[j].Curves) {
1138 return nil, fmt.Errorf("two policies with same match criteria have conflicting curves: %v vs. %v",
1139 cps[i].Curves, cps[j].Curves)
1140 }
1141 if cps[i].DefaultSNI != "" &&
1142 cps[j].DefaultSNI != "" &&
1143 cps[i].DefaultSNI != cps[j].DefaultSNI {
1144 return nil, fmt.Errorf("two policies with same match criteria have conflicting default SNI: %s vs. %s",
1145 cps[i].DefaultSNI, cps[j].DefaultSNI)
1146 }
1147 if cps[i].FallbackSNI != "" &&
1148 cps[j].FallbackSNI != "" &&
1149 cps[i].FallbackSNI != cps[j].FallbackSNI {
1150 return nil, fmt.Errorf("two policies with same match criteria have conflicting fallback SNI: %s vs. %s",
1151 cps[i].FallbackSNI, cps[j].FallbackSNI)
1152 }
1153 if cps[i].ProtocolMin != "" &&
1154 cps[j].ProtocolMin != "" &&
1155 cps[i].ProtocolMin != cps[j].ProtocolMin {
1156 return nil, fmt.Errorf("two policies with same match criteria have conflicting min protocol: %s vs. %s",
1157 cps[i].ProtocolMin, cps[j].ProtocolMin)
1158 }
1159 if cps[i].ProtocolMax != "" &&
1160 cps[j].ProtocolMax != "" &&
1161 cps[i].ProtocolMax != cps[j].ProtocolMax {
1162 return nil, fmt.Errorf("two policies with same match criteria have conflicting max protocol: %s vs. %s",
1163 cps[i].ProtocolMax, cps[j].ProtocolMax)
1164 }
1165 if cps[i].CertSelection != nil && cps[j].CertSelection != nil {
1166 // merging fields other than AnyTag is not implemented
1167 if !reflect.DeepEqual(cps[i].CertSelection.SerialNumber, cps[j].CertSelection.SerialNumber) ||
1168 !reflect.DeepEqual(cps[i].CertSelection.SubjectOrganization, cps[j].CertSelection.SubjectOrganization) ||
1169 cps[i].CertSelection.PublicKeyAlgorithm != cps[j].CertSelection.PublicKeyAlgorithm ||
1170 !reflect.DeepEqual(cps[i].CertSelection.AllTags, cps[j].CertSelection.AllTags) {
1171 return nil, fmt.Errorf("two policies with same match criteria have conflicting cert selections: %+v vs. %+v",
1172 cps[i].CertSelection, cps[j].CertSelection)
1173 }
1174 }
1175
1176 // by now we've decided that we can merge the two -- we'll keep i and drop j
1177
1178 if len(cps[i].ALPN) == 0 && len(cps[j].ALPN) > 0 {
1179 cps[i].ALPN = cps[j].ALPN
1180 }
1181 if len(cps[i].CipherSuites) == 0 && len(cps[j].CipherSuites) > 0 {
1182 cps[i].CipherSuites = cps[j].CipherSuites
1183 }
1184 if cps[i].ClientAuthentication == nil && cps[j].ClientAuthentication != nil {
1185 cps[i].ClientAuthentication = cps[j].ClientAuthentication
1186 }
1187 if len(cps[i].Curves) == 0 && len(cps[j].Curves) > 0 {
1188 cps[i].Curves = cps[j].Curves
1189 }
1190 if cps[i].DefaultSNI == "" && cps[j].DefaultSNI != "" {
1191 cps[i].DefaultSNI = cps[j].DefaultSNI
1192 }
1193 if cps[i].FallbackSNI == "" && cps[j].FallbackSNI != "" {
1194 cps[i].FallbackSNI = cps[j].FallbackSNI
1195 }
1196 if cps[i].ProtocolMin == "" && cps[j].ProtocolMin != "" {
1197 cps[i].ProtocolMin = cps[j].ProtocolMin
1198 }
1199 if cps[i].ProtocolMax == "" && cps[j].ProtocolMax != "" {
1200 cps[i].ProtocolMax = cps[j].ProtocolMax
1201 }
1202
1203 if cps[i].CertSelection == nil && cps[j].CertSelection != nil {
1204 // if j is the only one with a policy, move it over to i
1205 cps[i].CertSelection = cps[j].CertSelection
1206 } else if cps[i].CertSelection != nil && cps[j].CertSelection != nil {
1207 // if both have one, then combine AnyTag
1208 for _, tag := range cps[j].CertSelection.AnyTag {
1209 if !slices.Contains(cps[i].CertSelection.AnyTag, tag) {
1210 cps[i].CertSelection.AnyTag = append(cps[i].CertSelection.AnyTag, tag)
1211 }
1212 }
1213 }
1214
1215 cps = slices.Delete(cps, j, j+1)
1216 i--
1217 break
1218 }
1219 }
1220 }
1221
1222 return cps, nil
1223 }
1224
1225 // appendSubrouteToRouteList appends the routes in subroute
1226 // to the routeList, optionally qualified by matchers.
1227 func appendSubrouteToRouteList(routeList caddyhttp.RouteList,
1228 subroute *caddyhttp.Subroute,
1229 matcherSetsEnc []caddy.ModuleMap,
1230 p sbAddrAssociation,
1231 warnings *[]caddyconfig.Warning,
1232 ) caddyhttp.RouteList {
1233 // nothing to do if... there's nothing to do
1234 if len(matcherSetsEnc) == 0 && len(subroute.Routes) == 0 && subroute.Errors == nil {
1235 return routeList
1236 }
1237
1238 // No need to wrap the handlers in a subroute if this is the only server block
1239 // and there is no matcher for it (doing so would produce unnecessarily nested
1240 // JSON), *unless* there is a host matcher within this site block; if so, then
1241 // we still need to wrap in a subroute because otherwise the host matcher from
1242 // the inside of the site block would be a top-level host matcher, which is
1243 // subject to auto-HTTPS (cert management), and using a host matcher within
1244 // a site block is a valid, common pattern for excluding domains from cert
1245 // management, leading to unexpected behavior; see issue #5124.
1246 wrapInSubroute := true
1247 if len(matcherSetsEnc) == 0 && len(p.serverBlocks) == 1 {
1248 var hasHostMatcher bool
1249 outer:
1250 for _, route := range subroute.Routes {
1251 for _, ms := range route.MatcherSetsRaw {
1252 for matcherName := range ms {
1253 if matcherName == "host" {
1254 hasHostMatcher = true
1255 break outer
1256 }
1257 }
1258 }
1259 }
1260 wrapInSubroute = hasHostMatcher
1261 }
1262
1263 if wrapInSubroute {
1264 route := caddyhttp.Route{
1265 // the semantics of a site block in the Caddyfile dictate
1266 // that only the first matching one is evaluated, since
1267 // site blocks do not cascade nor inherit
1268 Terminal: true,
1269 }
1270 if len(matcherSetsEnc) > 0 {
1271 route.MatcherSetsRaw = matcherSetsEnc
1272 }
1273 if len(subroute.Routes) > 0 || subroute.Errors != nil {
1274 route.HandlersRaw = []json.RawMessage{
1275 caddyconfig.JSONModuleObject(subroute, "handler", "subroute", warnings),
1276 }
1277 }
1278 if len(route.MatcherSetsRaw) > 0 || len(route.HandlersRaw) > 0 {
1279 routeList = append(routeList, route)
1280 }
1281 } else {
1282 routeList = append(routeList, subroute.Routes...)
1283 }
1284
1285 return routeList
1286 }
1287
1288 // buildSubroute turns the config values, which are expected to be routes
1289 // into a clean and orderly subroute that has all the routes within it.
1290 func buildSubroute(routes []ConfigValue, groupCounter counter, needsSorting bool) (*caddyhttp.Subroute, error) {
1291 if needsSorting {
1292 for _, val := range routes {
1293 if !slices.Contains(directiveOrder, val.directive) {
1294 return nil, fmt.Errorf("directive '%s' is not an ordered HTTP handler, so it cannot be used here - try placing within a route block or using the order global option", val.directive)
1295 }
1296 }
1297
1298 sortRoutes(routes)
1299 }
1300
1301 subroute := new(caddyhttp.Subroute)
1302
1303 // some directives are mutually exclusive (only first matching
1304 // instance should be evaluated); this is done by putting their
1305 // routes in the same group
1306 mutuallyExclusiveDirs := map[string]*struct {
1307 count int
1308 groupName string
1309 }{
1310 // as a special case, group rewrite directives so that they are mutually exclusive;
1311 // this means that only the first matching rewrite will be evaluated, and that's
1312 // probably a good thing, since there should never be a need to do more than one
1313 // rewrite (I think?), and cascading rewrites smell bad... imagine these rewrites:
1314 // rewrite /docs/json/* /docs/json/index.html
1315 // rewrite /docs/* /docs/index.html
1316 // (We use this on the Caddy website, or at least we did once.) The first rewrite's
1317 // result is also matched by the second rewrite, making the first rewrite pointless.
1318 // See issue #2959.
1319 "rewrite": {},
1320
1321 // handle blocks are also mutually exclusive by definition
1322 "handle": {},
1323
1324 // root just sets a variable, so if it was not mutually exclusive, intersecting
1325 // root directives would overwrite previously-matched ones; they should not cascade
1326 "root": {},
1327 }
1328
1329 // we need to deterministically loop over each of these directives
1330 // in order to keep the group numbers consistent
1331 keys := make([]string, 0, len(mutuallyExclusiveDirs))
1332 for k := range mutuallyExclusiveDirs {
1333 keys = append(keys, k)
1334 }
1335 sort.Strings(keys)
1336
1337 for _, meDir := range keys {
1338 info := mutuallyExclusiveDirs[meDir]
1339
1340 // see how many instances of the directive there are
1341 for _, r := range routes {
1342 if r.directive == meDir {
1343 info.count++
1344 if info.count > 1 {
1345 break
1346 }
1347 }
1348 }
1349 // if there is more than one, put them in a group
1350 // (special case: "rewrite" directive must always be in
1351 // its own group--even if there is only one--because we
1352 // do not want a rewrite to be consolidated into other
1353 // adjacent routes that happen to have the same matcher,
1354 // see caddyserver/caddy#3108 - because the implied
1355 // intent of rewrite is to do an internal redirect,
1356 // we can't assume that the request will continue to
1357 // match the same matcher; anyway, giving a route a
1358 // unique group name should keep it from consolidating)
1359 if info.count > 1 || meDir == "rewrite" {
1360 info.groupName = groupCounter.nextGroup()
1361 }
1362 }
1363
1364 // add all the routes piled in from directives
1365 for _, r := range routes {
1366 // put this route into a group if it is mutually exclusive
1367 if info, ok := mutuallyExclusiveDirs[r.directive]; ok {
1368 route := r.Value.(caddyhttp.Route)
1369 route.Group = info.groupName
1370 r.Value = route
1371 }
1372
1373 switch route := r.Value.(type) {
1374 case caddyhttp.Subroute:
1375 // if a route-class config value is actually a Subroute handler
1376 // with nothing but a list of routes, then it is the intention
1377 // of the directive to keep these handlers together and in this
1378 // same order, but not necessarily in a subroute (if it wanted
1379 // to keep them in a subroute, the directive would have returned
1380 // a route with a Subroute as its handler); this is useful to
1381 // keep multiple handlers/routes together and in the same order
1382 // so that the sorting procedure we did above doesn't reorder them
1383 if route.Errors != nil {
1384 // if error handlers are also set, this is confusing; it's
1385 // probably supposed to be wrapped in a Route and encoded
1386 // as a regular handler route... programmer error.
1387 panic("found subroute with more than just routes; perhaps it should have been wrapped in a route?")
1388 }
1389 subroute.Routes = append(subroute.Routes, route.Routes...)
1390 case caddyhttp.Route:
1391 subroute.Routes = append(subroute.Routes, route)
1392 }
1393 }
1394
1395 subroute.Routes = consolidateRoutes(subroute.Routes)
1396
1397 return subroute, nil
1398 }
1399
1400 // normalizeDirectiveName ensures directives that should be sorted
1401 // at the same level are named the same before sorting happens.
1402 func normalizeDirectiveName(directive string) string {
1403 // As a special case, we want "handle_path" to be sorted
1404 // at the same level as "handle", so we force them to use
1405 // the same directive name after their parsing is complete.
1406 // See https://github.com/caddyserver/caddy/issues/3675#issuecomment-678042377
1407 if directive == "handle_path" {
1408 directive = "handle"
1409 }
1410 return directive
1411 }
1412
1413 // consolidateRoutes combines routes with the same properties
1414 // (same matchers, same Terminal and Group settings) for a
1415 // cleaner overall output.
1416 func consolidateRoutes(routes caddyhttp.RouteList) caddyhttp.RouteList {
1417 for i := 0; i < len(routes)-1; i++ {
1418 if reflect.DeepEqual(routes[i].MatcherSetsRaw, routes[i+1].MatcherSetsRaw) &&
1419 routes[i].Terminal == routes[i+1].Terminal &&
1420 routes[i].Group == routes[i+1].Group {
1421 // keep the handlers in the same order, then splice out repetitive route
1422 routes[i].HandlersRaw = append(routes[i].HandlersRaw, routes[i+1].HandlersRaw...)
1423 routes = append(routes[:i+1], routes[i+2:]...)
1424 i--
1425 }
1426 }
1427 return routes
1428 }
1429
1430 func matcherSetFromMatcherToken(
1431 tkn caddyfile.Token,
1432 matcherDefs map[string]caddy.ModuleMap,
1433 warnings *[]caddyconfig.Warning,
1434 ) (caddy.ModuleMap, bool, error) {
1435 // matcher tokens can be wildcards, simple path matchers,
1436 // or refer to a pre-defined matcher by some name
1437 if tkn.Text == "*" {
1438 // match all requests == no matchers, so nothing to do
1439 return nil, true, nil
1440 }
1441
1442 // convenient way to specify a single path match
1443 if strings.HasPrefix(tkn.Text, "/") {
1444 return caddy.ModuleMap{
1445 "path": caddyconfig.JSON(caddyhttp.MatchPath{tkn.Text}, warnings),
1446 }, true, nil
1447 }
1448
1449 // pre-defined matcher
1450 if strings.HasPrefix(tkn.Text, matcherPrefix) {
1451 m, ok := matcherDefs[tkn.Text]
1452 if !ok {
1453 return nil, false, fmt.Errorf("unrecognized matcher name: %+v", tkn.Text)
1454 }
1455 return m, true, nil
1456 }
1457
1458 return nil, false, nil
1459 }
1460
1461 func (st *ServerType) compileEncodedMatcherSets(sblock serverBlock) ([]caddy.ModuleMap, error) {
1462 type hostPathPair struct {
1463 hostm caddyhttp.MatchHost
1464 pathm caddyhttp.MatchPath
1465 }
1466
1467 // keep routes with common host and path matchers together
1468 var matcherPairs []*hostPathPair
1469
1470 var catchAllHosts bool
1471 for _, addr := range sblock.parsedKeys {
1472 // choose a matcher pair that should be shared by this
1473 // server block; if none exists yet, create one
1474 var chosenMatcherPair *hostPathPair
1475 for _, mp := range matcherPairs {
1476 if (len(mp.pathm) == 0 && addr.Path == "") ||
1477 (len(mp.pathm) == 1 && mp.pathm[0] == addr.Path) {
1478 chosenMatcherPair = mp
1479 break
1480 }
1481 }
1482 if chosenMatcherPair == nil {
1483 chosenMatcherPair = new(hostPathPair)
1484 if addr.Path != "" {
1485 chosenMatcherPair.pathm = []string{addr.Path}
1486 }
1487 matcherPairs = append(matcherPairs, chosenMatcherPair)
1488 }
1489
1490 // if one of the keys has no host (i.e. is a catch-all for
1491 // any hostname), then we need to null out the host matcher
1492 // entirely so that it matches all hosts
1493 if addr.Host == "" && !catchAllHosts {
1494 chosenMatcherPair.hostm = nil
1495 catchAllHosts = true
1496 }
1497 if catchAllHosts {
1498 continue
1499 }
1500
1501 // add this server block's keys to the matcher
1502 // pair if it doesn't already exist
1503 if addr.Host != "" && !slices.Contains(chosenMatcherPair.hostm, addr.Host) {
1504 chosenMatcherPair.hostm = append(chosenMatcherPair.hostm, addr.Host)
1505 }
1506 }
1507
1508 // iterate each pairing of host and path matchers and
1509 // put them into a map for JSON encoding
1510 var matcherSets []map[string]caddyhttp.RequestMatcherWithError
1511 for _, mp := range matcherPairs {
1512 matcherSet := make(map[string]caddyhttp.RequestMatcherWithError)
1513 if len(mp.hostm) > 0 {
1514 matcherSet["host"] = mp.hostm
1515 }
1516 if len(mp.pathm) > 0 {
1517 matcherSet["path"] = mp.pathm
1518 }
1519 if len(matcherSet) > 0 {
1520 matcherSets = append(matcherSets, matcherSet)
1521 }
1522 }
1523
1524 // finally, encode each of the matcher sets
1525 matcherSetsEnc := make([]caddy.ModuleMap, 0, len(matcherSets))
1526 for _, ms := range matcherSets {
1527 msEncoded, err := encodeMatcherSet(ms)
1528 if err != nil {
1529 return nil, fmt.Errorf("server block %v: %v", sblock.block.Keys, err)
1530 }
1531 matcherSetsEnc = append(matcherSetsEnc, msEncoded)
1532 }
1533
1534 return matcherSetsEnc, nil
1535 }
1536
1537 func parseMatcherDefinitions(d *caddyfile.Dispenser, matchers map[string]caddy.ModuleMap) error {
1538 d.Next() // advance to the first token
1539
1540 // this is the "name" for "named matchers"
1541 definitionName := d.Val()
1542
1543 if _, ok := matchers[definitionName]; ok {
1544 return fmt.Errorf("matcher is defined more than once: %s", definitionName)
1545 }
1546 matchers[definitionName] = make(caddy.ModuleMap)
1547
1548 // given a matcher name and the tokens following it, parse
1549 // the tokens as a matcher module and record it
1550 makeMatcher := func(matcherName string, tokens []caddyfile.Token) error {
1551 // create a new dispenser from the tokens
1552 dispenser := caddyfile.NewDispenser(tokens)
1553
1554 // set the matcher name (without @) in the dispenser context so
1555 // that matcher modules can access it to use it as their name
1556 // (e.g. regexp matchers which use the name for capture groups)
1557 dispenser.SetContext(caddyfile.MatcherNameCtxKey, definitionName[1:])
1558
1559 mod, err := caddy.GetModule("http.matchers." + matcherName)
1560 if err != nil {
1561 return fmt.Errorf("getting matcher module '%s': %v", matcherName, err)
1562 }
1563 unm, ok := mod.New().(caddyfile.Unmarshaler)
1564 if !ok {
1565 return fmt.Errorf("matcher module '%s' is not a Caddyfile unmarshaler", matcherName)
1566 }
1567 err = unm.UnmarshalCaddyfile(dispenser)
1568 if err != nil {
1569 return err
1570 }
1571
1572 if rm, ok := unm.(caddyhttp.RequestMatcherWithError); ok {
1573 matchers[definitionName][matcherName] = caddyconfig.JSON(rm, nil)
1574 return nil
1575 }
1576 // nolint:staticcheck
1577 if rm, ok := unm.(caddyhttp.RequestMatcher); ok {
1578 matchers[definitionName][matcherName] = caddyconfig.JSON(rm, nil)
1579 return nil
1580 }
1581 return fmt.Errorf("matcher module '%s' is not a request matcher", matcherName)
1582 }
1583
1584 // if the next token is quoted, we can assume it's not a matcher name
1585 // and that it's probably an 'expression' matcher
1586 if d.NextArg() {
1587 if d.Token().Quoted() {
1588 // since it was missing the matcher name, we insert a token
1589 // in front of the expression token itself; we use Clone() to
1590 // make the new token to keep the same the import location as
1591 // the next token, if this is within a snippet or imported file.
1592 // see https://github.com/caddyserver/caddy/issues/6287
1593 expressionToken := d.Token().Clone()
1594 expressionToken.Text = "expression"
1595 err := makeMatcher("expression", []caddyfile.Token{expressionToken, d.Token()})
1596 if err != nil {
1597 return err
1598 }
1599 return nil
1600 }
1601
1602 // if it wasn't quoted, then we need to rewind after calling
1603 // d.NextArg() so the below properly grabs the matcher name
1604 d.Prev()
1605 }
1606
1607 // in case there are multiple instances of the same matcher, concatenate
1608 // their tokens (we expect that UnmarshalCaddyfile should be able to
1609 // handle more than one segment); otherwise, we'd overwrite other
1610 // instances of the matcher in this set
1611 tokensByMatcherName := make(map[string][]caddyfile.Token)
1612 for nesting := d.Nesting(); d.NextArg() || d.NextBlock(nesting); {
1613 matcherName := d.Val()
1614 tokensByMatcherName[matcherName] = append(tokensByMatcherName[matcherName], d.NextSegment()...)
1615 }
1616 for matcherName, tokens := range tokensByMatcherName {
1617 err := makeMatcher(matcherName, tokens)
1618 if err != nil {
1619 return err
1620 }
1621 }
1622 return nil
1623 }
1624
1625 func encodeMatcherSet(matchers map[string]caddyhttp.RequestMatcherWithError) (caddy.ModuleMap, error) {
1626 msEncoded := make(caddy.ModuleMap)
1627 for matcherName, val := range matchers {
1628 jsonBytes, err := json.Marshal(val)
1629 if err != nil {
1630 return nil, fmt.Errorf("marshaling matcher set %#v: %v", matchers, err)
1631 }
1632 msEncoded[matcherName] = jsonBytes
1633 }
1634 return msEncoded, nil
1635 }
1636
1637 // WasReplacedPlaceholderShorthand checks if a token string was
1638 // likely a replaced shorthand of the known Caddyfile placeholder
1639 // replacement outputs. Useful to prevent some user-defined map
1640 // output destinations from overlapping with one of the
1641 // predefined shorthands.
1642 func WasReplacedPlaceholderShorthand(token string) string {
1643 prev := ""
1644 for i, item := range placeholderShorthands() {
1645 // only look at every 2nd item, which is the replacement
1646 if i%2 == 0 {
1647 prev = item
1648 continue
1649 }
1650 if strings.Trim(token, "{}") == strings.Trim(item, "{}") {
1651 // we return the original shorthand so it
1652 // can be used for an error message
1653 return prev
1654 }
1655 }
1656 return ""
1657 }
1658
1659 // tryInt tries to convert val to an integer. If it fails,
1660 // it downgrades the error to a warning and returns 0.
1661 func tryInt(val any, warnings *[]caddyconfig.Warning) int {
1662 intVal, ok := val.(int)
1663 if val != nil && !ok && warnings != nil {
1664 *warnings = append(*warnings, caddyconfig.Warning{Message: "not an integer type"})
1665 }
1666 return intVal
1667 }
1668
1669 func tryString(val any, warnings *[]caddyconfig.Warning) string {
1670 stringVal, ok := val.(string)
1671 if val != nil && !ok && warnings != nil {
1672 *warnings = append(*warnings, caddyconfig.Warning{Message: "not a string type"})
1673 }
1674 return stringVal
1675 }
1676
1677 func tryDuration(val any, warnings *[]caddyconfig.Warning) caddy.Duration {
1678 durationVal, ok := val.(caddy.Duration)
1679 if val != nil && !ok && warnings != nil {
1680 *warnings = append(*warnings, caddyconfig.Warning{Message: "not a duration type"})
1681 }
1682 return durationVal
1683 }
1684
1685 // listenersUseAnyPortOtherThan returns true if there are any
1686 // listeners in addresses that use a port which is not otherPort.
1687 // Mostly borrowed from unexported method in caddyhttp package.
1688 func listenersUseAnyPortOtherThan(addresses []string, otherPort string) bool {
1689 otherPortInt, err := strconv.Atoi(otherPort)
1690 if err != nil {
1691 return false
1692 }
1693 for _, lnAddr := range addresses {
1694 laddrs, err := caddy.ParseNetworkAddress(lnAddr)
1695 if err != nil {
1696 continue
1697 }
1698 if uint(otherPortInt) > laddrs.EndPort || uint(otherPortInt) < laddrs.StartPort {
1699 return true
1700 }
1701 }
1702 return false
1703 }
1704
1705 func mapContains[K comparable, V any](m map[K]V, keys []K) bool {
1706 if len(m) == 0 || len(keys) == 0 {
1707 return false
1708 }
1709 for _, key := range keys {
1710 if _, ok := m[key]; ok {
1711 return true
1712 }
1713 }
1714 return false
1715 }
1716
1717 // specificity returns len(s) minus any wildcards (*) and
1718 // placeholders ({...}). Basically, it's a length count
1719 // that penalizes the use of wildcards and placeholders.
1720 // This is useful for comparing hostnames and paths.
1721 // However, wildcards in paths are not a sure answer to
1722 // the question of specificity. For example,
1723 // '*.example.com' is clearly less specific than
1724 // 'a.example.com', but is '/a' more or less specific
1725 // than '/a*'?
1726 func specificity(s string) int {
1727 l := len(s) - strings.Count(s, "*")
1728 for len(s) > 0 {
1729 start := strings.Index(s, "{")
1730 if start < 0 {
1731 return l
1732 }
1733 end := strings.Index(s[start:], "}") + start + 1
1734 if end <= start {
1735 return l
1736 }
1737 l -= end - start
1738 s = s[end:]
1739 }
1740 return l
1741 }
1742
1743 type counter struct {
1744 n *int
1745 }
1746
1747 func (c counter) nextGroup() string {
1748 name := fmt.Sprintf("group%d", *c.n)
1749 *c.n++
1750 return name
1751 }
1752
1753 type namedCustomLog struct {
1754 name string
1755 hostnames []string
1756 log *caddy.CustomLog
1757 noHostname bool
1758 }
1759
1760 // addressWithProtocols associates a listen address with
1761 // the protocols to serve it with
1762 type addressWithProtocols struct {
1763 address string
1764 protocols []string
1765 }
1766
1767 // sbAddrAssociation is a mapping from a list of
1768 // addresses with protocols, and a list of server
1769 // blocks that are served on those addresses.
1770 type sbAddrAssociation struct {
1771 addressesWithProtocols []addressWithProtocols
1772 serverBlocks []serverBlock
1773 }
1774
1775 const (
1776 matcherPrefix = "@"
1777 namedRouteKey = "named_route"
1778 )
1779
1780 // Interface guard
1781 var _ caddyfile.ServerType = (*ServerType)(nil)