| 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 | "fmt" |
| 20 | "html" |
| 21 | "net/http" |
| 22 | "reflect" |
| 23 | "strconv" |
| 24 | "strings" |
| 25 | "time" |
| 26 | |
| 27 | "github.com/caddyserver/certmagic" |
| 28 | "github.com/mholt/acmez/v3/acme" |
| 29 | "go.uber.org/zap/zapcore" |
| 30 | |
| 31 | "github.com/caddyserver/caddy/v2" |
| 32 | "github.com/caddyserver/caddy/v2/caddyconfig" |
| 33 | "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" |
| 34 | "github.com/caddyserver/caddy/v2/modules/caddyhttp" |
| 35 | "github.com/caddyserver/caddy/v2/modules/caddytls" |
| 36 | ) |
| 37 | |
| 38 | func init() { |
| 39 | RegisterDirective("bind", parseBind) |
| 40 | RegisterDirective("tls", parseTLS) |
| 41 | RegisterHandlerDirective("fs", parseFilesystem) |
| 42 | RegisterDirective("root", parseRoot) |
| 43 | RegisterHandlerDirective("vars", parseVars) |
| 44 | RegisterHandlerDirective("redir", parseRedir) |
| 45 | RegisterHandlerDirective("respond", parseRespond) |
| 46 | RegisterHandlerDirective("abort", parseAbort) |
| 47 | RegisterHandlerDirective("error", parseError) |
| 48 | RegisterHandlerDirective("route", parseRoute) |
| 49 | RegisterHandlerDirective("handle", parseHandle) |
| 50 | RegisterDirective("handle_errors", parseHandleErrors) |
| 51 | RegisterHandlerDirective("invoke", parseInvoke) |
| 52 | RegisterDirective("log", parseLog) |
| 53 | RegisterHandlerDirective("skip_log", parseLogSkip) |
| 54 | RegisterHandlerDirective("log_skip", parseLogSkip) |
| 55 | RegisterHandlerDirective("log_name", parseLogName) |
| 56 | } |
| 57 | |
| 58 | // parseBind parses the bind directive. Syntax: |
| 59 | // |
| 60 | // bind <addresses...> [{ |
| 61 | // protocols [h1|h2|h2c|h3] [...] |
| 62 | // }] |
| 63 | func parseBind(h Helper) ([]ConfigValue, error) { |
| 64 | h.Next() // consume directive name |
| 65 | var addresses, protocols []string |
| 66 | addresses = h.RemainingArgs() |
| 67 | |
| 68 | for h.NextBlock(0) { |
| 69 | switch h.Val() { |
| 70 | case "protocols": |
| 71 | protocols = h.RemainingArgs() |
| 72 | if len(protocols) == 0 { |
| 73 | return nil, h.Errf("protocols requires one or more arguments") |
| 74 | } |
| 75 | default: |
| 76 | return nil, h.Errf("unknown subdirective: %s", h.Val()) |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | return []ConfigValue{{Class: "bind", Value: addressesWithProtocols{ |
| 81 | addresses: addresses, |
| 82 | protocols: protocols, |
| 83 | }}}, nil |
| 84 | } |
| 85 | |
| 86 | // parseTLS parses the tls directive. Syntax: |
| 87 | // |
| 88 | // tls [<email>|internal|force_automate]|[<cert_file> <key_file>] { |
| 89 | // protocols <min> [<max>] |
| 90 | // ciphers <cipher_suites...> |
| 91 | // curves <curves...> |
| 92 | // client_auth { |
| 93 | // mode [request|require|verify_if_given|require_and_verify] |
| 94 | // trust_pool <module_name> [...] |
| 95 | // trusted_leaf_cert <base64_der> |
| 96 | // trusted_leaf_cert_file <filename> |
| 97 | // } |
| 98 | // alpn <values...> |
| 99 | // load <paths...> |
| 100 | // ca <acme_ca_endpoint> |
| 101 | // ca_root <pem_file> |
| 102 | // key_type [ed25519|p256|p384|rsa2048|rsa4096] |
| 103 | // dns [<provider_name> [...]] (required, though, if DNS is not configured as global option) |
| 104 | // propagation_delay <duration> |
| 105 | // propagation_timeout <duration> |
| 106 | // resolvers <dns_servers...> |
| 107 | // dns_ttl <duration> |
| 108 | // dns_challenge_override_domain <domain> |
| 109 | // on_demand |
| 110 | // reuse_private_keys |
| 111 | // force_automate |
| 112 | // eab <key_id> <mac_key> |
| 113 | // issuer <module_name> [...] |
| 114 | // get_certificate <module_name> [...] |
| 115 | // insecure_secrets_log <log_file> |
| 116 | // renewal_window_ratio <ratio> |
| 117 | // } |
| 118 | func parseTLS(h Helper) ([]ConfigValue, error) { |
| 119 | h.Next() // consume directive name |
| 120 | |
| 121 | cp := new(caddytls.ConnectionPolicy) |
| 122 | var fileLoader caddytls.FileLoader |
| 123 | var folderLoader caddytls.FolderLoader |
| 124 | var certSelector caddytls.CustomCertSelectionPolicy |
| 125 | var acmeIssuer *caddytls.ACMEIssuer |
| 126 | var keyType string |
| 127 | var internalIssuer *caddytls.InternalIssuer |
| 128 | var issuers []certmagic.Issuer |
| 129 | var certManagers []certmagic.Manager |
| 130 | var onDemand bool |
| 131 | var reusePrivateKeys bool |
| 132 | var forceAutomate bool |
| 133 | var renewalWindowRatio float64 |
| 134 | |
| 135 | // Track which DNS challenge options are set |
| 136 | var dnsOptionsSet []string |
| 137 | |
| 138 | firstLine := h.RemainingArgs() |
| 139 | switch len(firstLine) { |
| 140 | case 0: |
| 141 | case 1: |
| 142 | if firstLine[0] == "internal" { |
| 143 | internalIssuer = new(caddytls.InternalIssuer) |
| 144 | } else if firstLine[0] == "force_automate" { |
| 145 | forceAutomate = true |
| 146 | } else if !strings.Contains(firstLine[0], "@") { |
| 147 | return nil, h.Err("single argument must either be 'internal', 'force_automate', or an email address") |
| 148 | } else { |
| 149 | acmeIssuer = &caddytls.ACMEIssuer{ |
| 150 | Email: firstLine[0], |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | case 2: |
| 155 | // file certificate loader |
| 156 | certFilename := firstLine[0] |
| 157 | keyFilename := firstLine[1] |
| 158 | |
| 159 | // tag this certificate so if multiple certs match, specifically |
| 160 | // this one that the user has provided will be used, see #2588: |
| 161 | // https://github.com/caddyserver/caddy/issues/2588 ... but we |
| 162 | // must be careful about how we do this; being careless will |
| 163 | // lead to failed handshakes |
| 164 | // |
| 165 | // we need to remember which cert files we've seen, since we |
| 166 | // must load each cert only once; otherwise, they each get a |
| 167 | // different tag... since a cert loaded twice has the same |
| 168 | // bytes, it will overwrite the first one in the cache, and |
| 169 | // only the last cert (and its tag) will survive, so any conn |
| 170 | // policy that is looking for any tag other than the last one |
| 171 | // to be loaded won't find it, and TLS handshakes will fail |
| 172 | // (see end of issue #3004) |
| 173 | // |
| 174 | // tlsCertTags maps certificate filenames to their tag. |
| 175 | // This is used to remember which tag is used for each |
| 176 | // certificate files, since we need to avoid loading |
| 177 | // the same certificate files more than once, overwriting |
| 178 | // previous tags |
| 179 | tlsCertTags, ok := h.State["tlsCertTags"].(map[string]string) |
| 180 | if !ok { |
| 181 | tlsCertTags = make(map[string]string) |
| 182 | h.State["tlsCertTags"] = tlsCertTags |
| 183 | } |
| 184 | |
| 185 | tag, ok := tlsCertTags[certFilename] |
| 186 | if !ok { |
| 187 | // haven't seen this cert file yet, let's give it a tag |
| 188 | // and add a loader for it |
| 189 | tag = fmt.Sprintf("cert%d", len(tlsCertTags)) |
| 190 | fileLoader = append(fileLoader, caddytls.CertKeyFilePair{ |
| 191 | Certificate: certFilename, |
| 192 | Key: keyFilename, |
| 193 | Tags: []string{tag}, |
| 194 | }) |
| 195 | // remember this for next time we see this cert file |
| 196 | tlsCertTags[certFilename] = tag |
| 197 | } |
| 198 | certSelector.AnyTag = append(certSelector.AnyTag, tag) |
| 199 | |
| 200 | default: |
| 201 | return nil, h.ArgErr() |
| 202 | } |
| 203 | |
| 204 | var hasBlock bool |
| 205 | for h.NextBlock(0) { |
| 206 | hasBlock = true |
| 207 | |
| 208 | switch h.Val() { |
| 209 | case "protocols": |
| 210 | args := h.RemainingArgs() |
| 211 | if len(args) == 0 { |
| 212 | return nil, h.Errf("protocols requires one or two arguments") |
| 213 | } |
| 214 | if len(args) > 0 { |
| 215 | if _, ok := caddytls.SupportedProtocols[args[0]]; !ok { |
| 216 | return nil, h.Errf("wrong protocol name or protocol not supported: '%s'", args[0]) |
| 217 | } |
| 218 | cp.ProtocolMin = args[0] |
| 219 | } |
| 220 | if len(args) > 1 { |
| 221 | if _, ok := caddytls.SupportedProtocols[args[1]]; !ok { |
| 222 | return nil, h.Errf("wrong protocol name or protocol not supported: '%s'", args[1]) |
| 223 | } |
| 224 | cp.ProtocolMax = args[1] |
| 225 | } |
| 226 | |
| 227 | case "ciphers": |
| 228 | for h.NextArg() { |
| 229 | if !caddytls.CipherSuiteNameSupported(h.Val()) { |
| 230 | return nil, h.Errf("wrong cipher suite name or cipher suite not supported: '%s'", h.Val()) |
| 231 | } |
| 232 | cp.CipherSuites = append(cp.CipherSuites, h.Val()) |
| 233 | } |
| 234 | |
| 235 | case "curves": |
| 236 | for h.NextArg() { |
| 237 | if _, ok := caddytls.SupportedCurves[h.Val()]; !ok { |
| 238 | return nil, h.Errf("Wrong curve name or curve not supported: '%s'", h.Val()) |
| 239 | } |
| 240 | cp.Curves = append(cp.Curves, h.Val()) |
| 241 | } |
| 242 | |
| 243 | case "client_auth": |
| 244 | cp.ClientAuthentication = &caddytls.ClientAuthentication{} |
| 245 | if err := cp.ClientAuthentication.UnmarshalCaddyfile(h.NewFromNextSegment()); err != nil { |
| 246 | return nil, err |
| 247 | } |
| 248 | case "alpn": |
| 249 | args := h.RemainingArgs() |
| 250 | if len(args) == 0 { |
| 251 | return nil, h.ArgErr() |
| 252 | } |
| 253 | cp.ALPN = args |
| 254 | |
| 255 | case "load": |
| 256 | folderLoader = append(folderLoader, h.RemainingArgs()...) |
| 257 | |
| 258 | case "ca": |
| 259 | arg := h.RemainingArgs() |
| 260 | if len(arg) != 1 { |
| 261 | return nil, h.ArgErr() |
| 262 | } |
| 263 | if acmeIssuer == nil { |
| 264 | acmeIssuer = new(caddytls.ACMEIssuer) |
| 265 | } |
| 266 | acmeIssuer.CA = arg[0] |
| 267 | |
| 268 | case "key_type": |
| 269 | arg := h.RemainingArgs() |
| 270 | if len(arg) != 1 { |
| 271 | return nil, h.ArgErr() |
| 272 | } |
| 273 | keyType = arg[0] |
| 274 | |
| 275 | case "eab": |
| 276 | arg := h.RemainingArgs() |
| 277 | if len(arg) != 2 { |
| 278 | return nil, h.ArgErr() |
| 279 | } |
| 280 | if acmeIssuer == nil { |
| 281 | acmeIssuer = new(caddytls.ACMEIssuer) |
| 282 | } |
| 283 | acmeIssuer.ExternalAccount = &acme.EAB{ |
| 284 | KeyID: arg[0], |
| 285 | MACKey: arg[1], |
| 286 | } |
| 287 | |
| 288 | case "issuer": |
| 289 | if !h.NextArg() { |
| 290 | return nil, h.ArgErr() |
| 291 | } |
| 292 | modName := h.Val() |
| 293 | modID := "tls.issuance." + modName |
| 294 | unm, err := caddyfile.UnmarshalModule(h.Dispenser, modID) |
| 295 | if err != nil { |
| 296 | return nil, err |
| 297 | } |
| 298 | issuer, ok := unm.(certmagic.Issuer) |
| 299 | if !ok { |
| 300 | return nil, h.Errf("module %s (%T) is not a certmagic.Issuer", modID, unm) |
| 301 | } |
| 302 | issuers = append(issuers, issuer) |
| 303 | |
| 304 | case "get_certificate": |
| 305 | if !h.NextArg() { |
| 306 | return nil, h.ArgErr() |
| 307 | } |
| 308 | modName := h.Val() |
| 309 | modID := "tls.get_certificate." + modName |
| 310 | unm, err := caddyfile.UnmarshalModule(h.Dispenser, modID) |
| 311 | if err != nil { |
| 312 | return nil, err |
| 313 | } |
| 314 | certManager, ok := unm.(certmagic.Manager) |
| 315 | if !ok { |
| 316 | return nil, h.Errf("module %s (%T) is not a certmagic.CertificateManager", modID, unm) |
| 317 | } |
| 318 | certManagers = append(certManagers, certManager) |
| 319 | |
| 320 | case "dns": |
| 321 | if acmeIssuer == nil { |
| 322 | acmeIssuer = new(caddytls.ACMEIssuer) |
| 323 | } |
| 324 | if acmeIssuer.Challenges == nil { |
| 325 | acmeIssuer.Challenges = new(caddytls.ChallengesConfig) |
| 326 | } |
| 327 | if acmeIssuer.Challenges.DNS == nil { |
| 328 | acmeIssuer.Challenges.DNS = new(caddytls.DNSChallengeConfig) |
| 329 | } |
| 330 | // DNS provider configuration optional, since it may be configured globally via the TLS app with global options |
| 331 | if h.NextArg() { |
| 332 | provName := h.Val() |
| 333 | modID := "dns.providers." + provName |
| 334 | unm, err := caddyfile.UnmarshalModule(h.Dispenser, modID) |
| 335 | if err != nil { |
| 336 | return nil, err |
| 337 | } |
| 338 | acmeIssuer.Challenges.DNS.ProviderRaw = caddyconfig.JSONModuleObject(unm, "name", provName, h.warnings) |
| 339 | } else if h.Option("dns") == nil { |
| 340 | // if DNS is omitted locally, it needs to be configured globally |
| 341 | return nil, h.ArgErr() |
| 342 | } |
| 343 | |
| 344 | case "resolvers": |
| 345 | args := h.RemainingArgs() |
| 346 | if len(args) == 0 { |
| 347 | return nil, h.ArgErr() |
| 348 | } |
| 349 | if acmeIssuer == nil { |
| 350 | acmeIssuer = new(caddytls.ACMEIssuer) |
| 351 | } |
| 352 | if acmeIssuer.Challenges == nil { |
| 353 | acmeIssuer.Challenges = new(caddytls.ChallengesConfig) |
| 354 | } |
| 355 | if acmeIssuer.Challenges.DNS == nil { |
| 356 | acmeIssuer.Challenges.DNS = new(caddytls.DNSChallengeConfig) |
| 357 | } |
| 358 | dnsOptionsSet = append(dnsOptionsSet, "resolvers") |
| 359 | acmeIssuer.Challenges.DNS.Resolvers = args |
| 360 | |
| 361 | case "propagation_delay": |
| 362 | arg := h.RemainingArgs() |
| 363 | if len(arg) != 1 { |
| 364 | return nil, h.ArgErr() |
| 365 | } |
| 366 | delayStr := arg[0] |
| 367 | delay, err := caddy.ParseDuration(delayStr) |
| 368 | if err != nil { |
| 369 | return nil, h.Errf("invalid propagation_delay duration %s: %v", delayStr, err) |
| 370 | } |
| 371 | if acmeIssuer == nil { |
| 372 | acmeIssuer = new(caddytls.ACMEIssuer) |
| 373 | } |
| 374 | if acmeIssuer.Challenges == nil { |
| 375 | acmeIssuer.Challenges = new(caddytls.ChallengesConfig) |
| 376 | } |
| 377 | if acmeIssuer.Challenges.DNS == nil { |
| 378 | acmeIssuer.Challenges.DNS = new(caddytls.DNSChallengeConfig) |
| 379 | } |
| 380 | dnsOptionsSet = append(dnsOptionsSet, "propagation_delay") |
| 381 | acmeIssuer.Challenges.DNS.PropagationDelay = caddy.Duration(delay) |
| 382 | |
| 383 | case "propagation_timeout": |
| 384 | arg := h.RemainingArgs() |
| 385 | if len(arg) != 1 { |
| 386 | return nil, h.ArgErr() |
| 387 | } |
| 388 | timeoutStr := arg[0] |
| 389 | var timeout time.Duration |
| 390 | if timeoutStr == "-1" { |
| 391 | timeout = time.Duration(-1) |
| 392 | } else { |
| 393 | var err error |
| 394 | timeout, err = caddy.ParseDuration(timeoutStr) |
| 395 | if err != nil { |
| 396 | return nil, h.Errf("invalid propagation_timeout duration %s: %v", timeoutStr, err) |
| 397 | } |
| 398 | } |
| 399 | if acmeIssuer == nil { |
| 400 | acmeIssuer = new(caddytls.ACMEIssuer) |
| 401 | } |
| 402 | if acmeIssuer.Challenges == nil { |
| 403 | acmeIssuer.Challenges = new(caddytls.ChallengesConfig) |
| 404 | } |
| 405 | if acmeIssuer.Challenges.DNS == nil { |
| 406 | acmeIssuer.Challenges.DNS = new(caddytls.DNSChallengeConfig) |
| 407 | } |
| 408 | dnsOptionsSet = append(dnsOptionsSet, "propagation_timeout") |
| 409 | acmeIssuer.Challenges.DNS.PropagationTimeout = caddy.Duration(timeout) |
| 410 | |
| 411 | case "dns_ttl": |
| 412 | arg := h.RemainingArgs() |
| 413 | if len(arg) != 1 { |
| 414 | return nil, h.ArgErr() |
| 415 | } |
| 416 | ttlStr := arg[0] |
| 417 | ttl, err := caddy.ParseDuration(ttlStr) |
| 418 | if err != nil { |
| 419 | return nil, h.Errf("invalid dns_ttl duration %s: %v", ttlStr, err) |
| 420 | } |
| 421 | if acmeIssuer == nil { |
| 422 | acmeIssuer = new(caddytls.ACMEIssuer) |
| 423 | } |
| 424 | if acmeIssuer.Challenges == nil { |
| 425 | acmeIssuer.Challenges = new(caddytls.ChallengesConfig) |
| 426 | } |
| 427 | if acmeIssuer.Challenges.DNS == nil { |
| 428 | acmeIssuer.Challenges.DNS = new(caddytls.DNSChallengeConfig) |
| 429 | } |
| 430 | dnsOptionsSet = append(dnsOptionsSet, "dns_ttl") |
| 431 | acmeIssuer.Challenges.DNS.TTL = caddy.Duration(ttl) |
| 432 | |
| 433 | case "dns_challenge_override_domain": |
| 434 | arg := h.RemainingArgs() |
| 435 | if len(arg) != 1 { |
| 436 | return nil, h.ArgErr() |
| 437 | } |
| 438 | if acmeIssuer == nil { |
| 439 | acmeIssuer = new(caddytls.ACMEIssuer) |
| 440 | } |
| 441 | if acmeIssuer.Challenges == nil { |
| 442 | acmeIssuer.Challenges = new(caddytls.ChallengesConfig) |
| 443 | } |
| 444 | if acmeIssuer.Challenges.DNS == nil { |
| 445 | acmeIssuer.Challenges.DNS = new(caddytls.DNSChallengeConfig) |
| 446 | } |
| 447 | dnsOptionsSet = append(dnsOptionsSet, "dns_challenge_override_domain") |
| 448 | acmeIssuer.Challenges.DNS.OverrideDomain = arg[0] |
| 449 | |
| 450 | case "ca_root": |
| 451 | arg := h.RemainingArgs() |
| 452 | if len(arg) != 1 { |
| 453 | return nil, h.ArgErr() |
| 454 | } |
| 455 | if acmeIssuer == nil { |
| 456 | acmeIssuer = new(caddytls.ACMEIssuer) |
| 457 | } |
| 458 | acmeIssuer.TrustedRootsPEMFiles = append(acmeIssuer.TrustedRootsPEMFiles, arg[0]) |
| 459 | |
| 460 | case "on_demand": |
| 461 | if h.NextArg() { |
| 462 | return nil, h.ArgErr() |
| 463 | } |
| 464 | onDemand = true |
| 465 | |
| 466 | case "reuse_private_keys": |
| 467 | if h.NextArg() { |
| 468 | return nil, h.ArgErr() |
| 469 | } |
| 470 | reusePrivateKeys = true |
| 471 | |
| 472 | case "insecure_secrets_log": |
| 473 | if !h.NextArg() { |
| 474 | return nil, h.ArgErr() |
| 475 | } |
| 476 | cp.InsecureSecretsLog = h.Val() |
| 477 | |
| 478 | case "renewal_window_ratio": |
| 479 | arg := h.RemainingArgs() |
| 480 | if len(arg) != 1 { |
| 481 | return nil, h.ArgErr() |
| 482 | } |
| 483 | ratio, err := strconv.ParseFloat(arg[0], 64) |
| 484 | if err != nil { |
| 485 | return nil, h.Errf("parsing renewal_window_ratio: %v", err) |
| 486 | } |
| 487 | if ratio <= 0 || ratio >= 1 { |
| 488 | return nil, h.Errf("renewal_window_ratio must be between 0 and 1 (exclusive)") |
| 489 | } |
| 490 | renewalWindowRatio = ratio |
| 491 | |
| 492 | default: |
| 493 | return nil, h.Errf("unknown subdirective: %s", h.Val()) |
| 494 | } |
| 495 | } |
| 496 | |
| 497 | // Validate DNS challenge config: any DNS challenge option except "dns" requires a DNS provider |
| 498 | if acmeIssuer != nil && acmeIssuer.Challenges != nil && acmeIssuer.Challenges.DNS != nil { |
| 499 | dnsCfg := acmeIssuer.Challenges.DNS |
| 500 | providerSet := dnsCfg.ProviderRaw != nil || h.Option("dns") != nil || h.Option("acme_dns") != nil |
| 501 | if len(dnsOptionsSet) > 0 && !providerSet { |
| 502 | return nil, h.Errf( |
| 503 | "setting DNS challenge options [%s] requires a DNS provider (set with the 'dns' subdirective or 'acme_dns' global option)", |
| 504 | strings.Join(dnsOptionsSet, ", "), |
| 505 | ) |
| 506 | } |
| 507 | } |
| 508 | |
| 509 | // a naked tls directive is not allowed |
| 510 | if len(firstLine) == 0 && !hasBlock { |
| 511 | return nil, h.ArgErr() |
| 512 | } |
| 513 | |
| 514 | // begin building the final config values |
| 515 | configVals := []ConfigValue{} |
| 516 | |
| 517 | // certificate loaders |
| 518 | if len(fileLoader) > 0 { |
| 519 | configVals = append(configVals, ConfigValue{ |
| 520 | Class: "tls.cert_loader", |
| 521 | Value: fileLoader, |
| 522 | }) |
| 523 | } |
| 524 | if len(folderLoader) > 0 { |
| 525 | configVals = append(configVals, ConfigValue{ |
| 526 | Class: "tls.cert_loader", |
| 527 | Value: folderLoader, |
| 528 | }) |
| 529 | } |
| 530 | |
| 531 | // some tls subdirectives are shortcuts that implicitly configure issuers, and the |
| 532 | // user can also configure issuers explicitly using the issuer subdirective; the |
| 533 | // logic to support both would likely be complex, or at least unintuitive |
| 534 | if len(issuers) > 0 && (acmeIssuer != nil || internalIssuer != nil) { |
| 535 | return nil, h.Err("cannot mix issuer subdirective (explicit issuers) with other issuer-specific subdirectives (implicit issuers)") |
| 536 | } |
| 537 | if acmeIssuer != nil && internalIssuer != nil { |
| 538 | return nil, h.Err("cannot create both ACME and internal certificate issuers") |
| 539 | } |
| 540 | |
| 541 | // now we should either have: explicitly-created issuers, or an implicitly-created |
| 542 | // ACME or internal issuer, or no issuers at all |
| 543 | switch { |
| 544 | case len(issuers) > 0: |
| 545 | for _, issuer := range issuers { |
| 546 | configVals = append(configVals, ConfigValue{ |
| 547 | Class: "tls.cert_issuer", |
| 548 | Value: issuer, |
| 549 | }) |
| 550 | } |
| 551 | |
| 552 | case acmeIssuer != nil: |
| 553 | // implicit ACME issuers (from various subdirectives) should inherit from |
| 554 | // any globally-configured ACME issuer templates, then apply the local |
| 555 | // shortcut settings as overrides. |
| 556 | defaultIssuers := implicitACMEIssuers(h, acmeIssuer) |
| 557 | for _, issuer := range defaultIssuers { |
| 558 | configVals = append(configVals, ConfigValue{ |
| 559 | Class: "tls.cert_issuer", |
| 560 | Value: issuer, |
| 561 | }) |
| 562 | } |
| 563 | |
| 564 | case internalIssuer != nil: |
| 565 | configVals = append(configVals, ConfigValue{ |
| 566 | Class: "tls.cert_issuer", |
| 567 | Value: internalIssuer, |
| 568 | }) |
| 569 | } |
| 570 | |
| 571 | // certificate key type |
| 572 | if keyType != "" { |
| 573 | configVals = append(configVals, ConfigValue{ |
| 574 | Class: "tls.key_type", |
| 575 | Value: keyType, |
| 576 | }) |
| 577 | } |
| 578 | |
| 579 | // on-demand TLS |
| 580 | if onDemand { |
| 581 | configVals = append(configVals, ConfigValue{ |
| 582 | Class: "tls.on_demand", |
| 583 | Value: true, |
| 584 | }) |
| 585 | } |
| 586 | for _, certManager := range certManagers { |
| 587 | configVals = append(configVals, ConfigValue{ |
| 588 | Class: "tls.cert_manager", |
| 589 | Value: certManager, |
| 590 | }) |
| 591 | } |
| 592 | |
| 593 | // reuse private keys TLS |
| 594 | if reusePrivateKeys { |
| 595 | configVals = append(configVals, ConfigValue{ |
| 596 | Class: "tls.reuse_private_keys", |
| 597 | Value: true, |
| 598 | }) |
| 599 | } |
| 600 | |
| 601 | // renewal window ratio |
| 602 | if renewalWindowRatio > 0 { |
| 603 | configVals = append(configVals, ConfigValue{ |
| 604 | Class: "tls.renewal_window_ratio", |
| 605 | Value: renewalWindowRatio, |
| 606 | }) |
| 607 | } |
| 608 | |
| 609 | // if enabled, the names in the site addresses will be |
| 610 | // added to the automation policies |
| 611 | if forceAutomate { |
| 612 | configVals = append(configVals, ConfigValue{ |
| 613 | Class: "tls.force_automate", |
| 614 | Value: true, |
| 615 | }) |
| 616 | } |
| 617 | |
| 618 | // custom certificate selection |
| 619 | if len(certSelector.AnyTag) > 0 { |
| 620 | cp.CertSelection = &certSelector |
| 621 | } |
| 622 | |
| 623 | // connection policy -- always add one, to ensure that TLS |
| 624 | // is enabled, because this directive was used (this is |
| 625 | // needed, for instance, when a site block has a key of |
| 626 | // just ":5000" - i.e. no hostname, and only on-demand TLS |
| 627 | // is enabled) |
| 628 | configVals = append(configVals, ConfigValue{ |
| 629 | Class: "tls.connection_policy", |
| 630 | Value: cp, |
| 631 | }) |
| 632 | |
| 633 | return configVals, nil |
| 634 | } |
| 635 | |
| 636 | // parseRoot parses the root directive. Syntax: |
| 637 | // |
| 638 | // root [<matcher>] <path> |
| 639 | func parseRoot(h Helper) ([]ConfigValue, error) { |
| 640 | h.Next() // consume directive name |
| 641 | |
| 642 | // count the tokens to determine what to do |
| 643 | argsCount := h.CountRemainingArgs() |
| 644 | if argsCount == 0 { |
| 645 | return nil, h.Errf("too few arguments; must have at least a root path") |
| 646 | } |
| 647 | if argsCount > 2 { |
| 648 | return nil, h.Errf("too many arguments; should only be a matcher and a path") |
| 649 | } |
| 650 | |
| 651 | // with only one arg, assume it's a root path with no matcher token |
| 652 | if argsCount == 1 { |
| 653 | if !h.NextArg() { |
| 654 | return nil, h.ArgErr() |
| 655 | } |
| 656 | // store the unmatched root in block state so sibling directives can access it |
| 657 | h.BlockState["root"] = h.Val() |
| 658 | return h.NewRoute(nil, caddyhttp.VarsMiddleware{"root": h.Val()}), nil |
| 659 | } |
| 660 | |
| 661 | // parse the matcher token into a matcher set |
| 662 | userMatcherSet, err := h.ExtractMatcherSet() |
| 663 | if err != nil { |
| 664 | return nil, err |
| 665 | } |
| 666 | h.Next() // consume directive name again, matcher parsing does a reset |
| 667 | |
| 668 | // advance to the root path |
| 669 | if !h.NextArg() { |
| 670 | return nil, h.ArgErr() |
| 671 | } |
| 672 | // store the unmatched root in state so sibling/child directives can access it |
| 673 | if userMatcherSet == nil { |
| 674 | h.BlockState["root"] = h.Val() |
| 675 | } |
| 676 | // make the route with the matcher |
| 677 | return h.NewRoute(userMatcherSet, caddyhttp.VarsMiddleware{"root": h.Val()}), nil |
| 678 | } |
| 679 | |
| 680 | // parseFilesystem parses the fs directive. Syntax: |
| 681 | // |
| 682 | // fs <filesystem> |
| 683 | func parseFilesystem(h Helper) (caddyhttp.MiddlewareHandler, error) { |
| 684 | h.Next() // consume directive name |
| 685 | if !h.NextArg() { |
| 686 | return nil, h.ArgErr() |
| 687 | } |
| 688 | if h.NextArg() { |
| 689 | return nil, h.ArgErr() |
| 690 | } |
| 691 | return caddyhttp.VarsMiddleware{"fs": h.Val()}, nil |
| 692 | } |
| 693 | |
| 694 | // parseVars parses the vars directive. See its UnmarshalCaddyfile method for syntax. |
| 695 | func parseVars(h Helper) (caddyhttp.MiddlewareHandler, error) { |
| 696 | v := new(caddyhttp.VarsMiddleware) |
| 697 | err := v.UnmarshalCaddyfile(h.Dispenser) |
| 698 | return v, err |
| 699 | } |
| 700 | |
| 701 | // parseRedir parses the redir directive. Syntax: |
| 702 | // |
| 703 | // redir [<matcher>] <to> [<code>] |
| 704 | // |
| 705 | // <code> can be "permanent" for 301, "temporary" for 302 (default), |
| 706 | // a placeholder, or any number in the 3xx range or 401. The special |
| 707 | // code "html" can be used to redirect only browser clients (will |
| 708 | // respond with HTTP 200 and no Location header; redirect is performed |
| 709 | // with JS and a meta tag). |
| 710 | func parseRedir(h Helper) (caddyhttp.MiddlewareHandler, error) { |
| 711 | h.Next() // consume directive name |
| 712 | if !h.NextArg() { |
| 713 | return nil, h.ArgErr() |
| 714 | } |
| 715 | to := h.Val() |
| 716 | |
| 717 | var code string |
| 718 | if h.NextArg() { |
| 719 | code = h.Val() |
| 720 | } |
| 721 | |
| 722 | var body string |
| 723 | var hdr http.Header |
| 724 | switch code { |
| 725 | case "permanent": |
| 726 | code = "301" |
| 727 | |
| 728 | case "temporary", "": |
| 729 | code = "302" |
| 730 | |
| 731 | case "html": |
| 732 | // Script tag comes first since that will better imitate a redirect in the browser's |
| 733 | // history, but the meta tag is a fallback for most non-JS clients. |
| 734 | const metaRedir = `<!DOCTYPE html> |
| 735 | <html> |
| 736 | <head> |
| 737 | <title>Redirecting...</title> |
| 738 | <script>window.location.replace("%s");</script> |
| 739 | <meta http-equiv="refresh" content="0; URL='%s'"> |
| 740 | </head> |
| 741 | <body>Redirecting to <a href="%s">%s</a>...</body> |
| 742 | </html> |
| 743 | ` |
| 744 | safeTo := html.EscapeString(to) |
| 745 | body = fmt.Sprintf(metaRedir, safeTo, safeTo, safeTo, safeTo) |
| 746 | hdr = http.Header{"Content-Type": []string{"text/html; charset=utf-8"}} |
| 747 | code = "200" // don't redirect non-browser clients |
| 748 | |
| 749 | default: |
| 750 | // Allow placeholders for the code |
| 751 | if strings.HasPrefix(code, "{") { |
| 752 | break |
| 753 | } |
| 754 | // Try to validate as an integer otherwise |
| 755 | codeInt, err := strconv.Atoi(code) |
| 756 | if err != nil { |
| 757 | return nil, h.Errf("Not a supported redir code type or not valid integer: '%s'", code) |
| 758 | } |
| 759 | // Sometimes, a 401 with Location header is desirable because |
| 760 | // requests made with XHR will "eat" the 3xx redirect; so if |
| 761 | // the intent was to redirect to an auth page, a 3xx won't |
| 762 | // work. Responding with 401 allows JS code to read the |
| 763 | // Location header and do a window.location redirect manually. |
| 764 | // see https://stackoverflow.com/a/2573589/846934 |
| 765 | // see https://github.com/oauth2-proxy/oauth2-proxy/issues/1522 |
| 766 | if codeInt < 300 || (codeInt > 399 && codeInt != 401) { |
| 767 | return nil, h.Errf("Redir code not in the 3xx range or 401: '%v'", codeInt) |
| 768 | } |
| 769 | } |
| 770 | |
| 771 | // don't redirect non-browser clients |
| 772 | if code != "200" { |
| 773 | hdr = http.Header{"Location": []string{to}} |
| 774 | } |
| 775 | |
| 776 | return caddyhttp.StaticResponse{ |
| 777 | StatusCode: caddyhttp.WeakString(code), |
| 778 | Headers: hdr, |
| 779 | Body: body, |
| 780 | }, nil |
| 781 | } |
| 782 | |
| 783 | // parseRespond parses the respond directive. |
| 784 | func parseRespond(h Helper) (caddyhttp.MiddlewareHandler, error) { |
| 785 | sr := new(caddyhttp.StaticResponse) |
| 786 | err := sr.UnmarshalCaddyfile(h.Dispenser) |
| 787 | return sr, err |
| 788 | } |
| 789 | |
| 790 | // parseAbort parses the abort directive. |
| 791 | func parseAbort(h Helper) (caddyhttp.MiddlewareHandler, error) { |
| 792 | h.Next() // consume directive |
| 793 | for h.Next() || h.NextBlock(0) { |
| 794 | return nil, h.ArgErr() |
| 795 | } |
| 796 | return &caddyhttp.StaticResponse{Abort: true}, nil |
| 797 | } |
| 798 | |
| 799 | // parseError parses the error directive. |
| 800 | func parseError(h Helper) (caddyhttp.MiddlewareHandler, error) { |
| 801 | se := new(caddyhttp.StaticError) |
| 802 | err := se.UnmarshalCaddyfile(h.Dispenser) |
| 803 | return se, err |
| 804 | } |
| 805 | |
| 806 | // parseRoute parses the route directive. |
| 807 | func parseRoute(h Helper) (caddyhttp.MiddlewareHandler, error) { |
| 808 | allResults, err := parseSegmentAsConfig(h) |
| 809 | if err != nil { |
| 810 | return nil, err |
| 811 | } |
| 812 | |
| 813 | for _, result := range allResults { |
| 814 | switch result.Value.(type) { |
| 815 | case caddyhttp.Route, caddyhttp.Subroute: |
| 816 | default: |
| 817 | return nil, h.Errf("%s directive returned something other than an HTTP route or subroute: %#v (only handler directives can be used in routes)", result.directive, result.Value) |
| 818 | } |
| 819 | } |
| 820 | |
| 821 | return buildSubroute(allResults, h.groupCounter, false) |
| 822 | } |
| 823 | |
| 824 | func parseHandle(h Helper) (caddyhttp.MiddlewareHandler, error) { |
| 825 | return ParseSegmentAsSubroute(h) |
| 826 | } |
| 827 | |
| 828 | func parseHandleErrors(h Helper) ([]ConfigValue, error) { |
| 829 | h.Next() // consume directive name |
| 830 | |
| 831 | expression := "" |
| 832 | args := h.RemainingArgs() |
| 833 | if len(args) > 0 { |
| 834 | codes := []string{} |
| 835 | for _, val := range args { |
| 836 | if len(val) != 3 { |
| 837 | return nil, h.Errf("bad status value '%s'", val) |
| 838 | } |
| 839 | if strings.HasSuffix(val, "xx") { |
| 840 | val = val[:1] |
| 841 | _, err := strconv.Atoi(val) |
| 842 | if err != nil { |
| 843 | return nil, h.Errf("bad status value '%s': %v", val, err) |
| 844 | } |
| 845 | if expression != "" { |
| 846 | expression += " || " |
| 847 | } |
| 848 | expression += fmt.Sprintf("{http.error.status_code} >= %s00 && {http.error.status_code} <= %s99", val, val) |
| 849 | continue |
| 850 | } |
| 851 | _, err := strconv.Atoi(val) |
| 852 | if err != nil { |
| 853 | return nil, h.Errf("bad status value '%s': %v", val, err) |
| 854 | } |
| 855 | codes = append(codes, val) |
| 856 | } |
| 857 | if len(codes) > 0 { |
| 858 | if expression != "" { |
| 859 | expression += " || " |
| 860 | } |
| 861 | expression += "{http.error.status_code} in [" + strings.Join(codes, ", ") + "]" |
| 862 | } |
| 863 | // Reset cursor position to get ready for ParseSegmentAsSubroute |
| 864 | h.Reset() |
| 865 | h.Next() |
| 866 | h.RemainingArgs() |
| 867 | h.Prev() |
| 868 | } else { |
| 869 | // If no arguments present reset the cursor position to get ready for ParseSegmentAsSubroute |
| 870 | h.Prev() |
| 871 | } |
| 872 | |
| 873 | handler, err := ParseSegmentAsSubroute(h) |
| 874 | if err != nil { |
| 875 | return nil, err |
| 876 | } |
| 877 | subroute, ok := handler.(*caddyhttp.Subroute) |
| 878 | if !ok { |
| 879 | return nil, h.Errf("segment was not parsed as a subroute") |
| 880 | } |
| 881 | |
| 882 | // wrap the subroutes |
| 883 | wrappingRoute := caddyhttp.Route{ |
| 884 | HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject(subroute, "handler", "subroute", nil)}, |
| 885 | } |
| 886 | subroute = &caddyhttp.Subroute{ |
| 887 | Routes: []caddyhttp.Route{wrappingRoute}, |
| 888 | } |
| 889 | if expression != "" { |
| 890 | statusMatcher := caddy.ModuleMap{ |
| 891 | "expression": h.JSON(caddyhttp.MatchExpression{Expr: expression}), |
| 892 | } |
| 893 | subroute.Routes[0].MatcherSetsRaw = []caddy.ModuleMap{statusMatcher} |
| 894 | } |
| 895 | return []ConfigValue{ |
| 896 | { |
| 897 | Class: "error_route", |
| 898 | Value: subroute, |
| 899 | }, |
| 900 | }, nil |
| 901 | } |
| 902 | |
| 903 | // parseInvoke parses the invoke directive. |
| 904 | func parseInvoke(h Helper) (caddyhttp.MiddlewareHandler, error) { |
| 905 | h.Next() // consume directive |
| 906 | if !h.NextArg() { |
| 907 | return nil, h.ArgErr() |
| 908 | } |
| 909 | for h.Next() || h.NextBlock(0) { |
| 910 | return nil, h.ArgErr() |
| 911 | } |
| 912 | |
| 913 | // remember that we're invoking this name |
| 914 | // to populate the server with these named routes |
| 915 | if h.State[namedRouteKey] == nil { |
| 916 | h.State[namedRouteKey] = map[string]struct{}{} |
| 917 | } |
| 918 | h.State[namedRouteKey].(map[string]struct{})[h.Val()] = struct{}{} |
| 919 | |
| 920 | // return the handler |
| 921 | return &caddyhttp.Invoke{Name: h.Val()}, nil |
| 922 | } |
| 923 | |
| 924 | // parseLog parses the log directive. Syntax: |
| 925 | // |
| 926 | // log <logger_name> { |
| 927 | // hostnames <hostnames...> |
| 928 | // output <writer_module> ... |
| 929 | // core <core_module> ... |
| 930 | // format <encoder_module> ... |
| 931 | // level <level> |
| 932 | // } |
| 933 | func parseLog(h Helper) ([]ConfigValue, error) { |
| 934 | return parseLogHelper(h, nil) |
| 935 | } |
| 936 | |
| 937 | // parseLogHelper is used both for the parseLog directive within Server Blocks, |
| 938 | // as well as the global "log" option for configuring loggers at the global |
| 939 | // level. The parseAsGlobalOption parameter is used to distinguish any differing logic |
| 940 | // between the two. |
| 941 | func parseLogHelper(h Helper, globalLogNames map[string]struct{}) ([]ConfigValue, error) { |
| 942 | h.Next() // consume option name |
| 943 | |
| 944 | // When the globalLogNames parameter is passed in, we make |
| 945 | // modifications to the parsing behavior. |
| 946 | parseAsGlobalOption := globalLogNames != nil |
| 947 | |
| 948 | // nolint:prealloc |
| 949 | var configValues []ConfigValue |
| 950 | |
| 951 | // Logic below expects that a name is always present when a |
| 952 | // global option is being parsed; or an optional override |
| 953 | // is supported for access logs. |
| 954 | var logName string |
| 955 | |
| 956 | if parseAsGlobalOption { |
| 957 | if h.NextArg() { |
| 958 | logName = h.Val() |
| 959 | |
| 960 | // Only a single argument is supported. |
| 961 | if h.NextArg() { |
| 962 | return nil, h.ArgErr() |
| 963 | } |
| 964 | } else { |
| 965 | // If there is no log name specified, we |
| 966 | // reference the default logger. See the |
| 967 | // setupNewDefault function in the logging |
| 968 | // package for where this is configured. |
| 969 | logName = caddy.DefaultLoggerName |
| 970 | } |
| 971 | |
| 972 | // Verify this name is unused. |
| 973 | _, used := globalLogNames[logName] |
| 974 | if used { |
| 975 | return nil, h.Err("duplicate global log option for: " + logName) |
| 976 | } |
| 977 | globalLogNames[logName] = struct{}{} |
| 978 | } else { |
| 979 | // An optional override of the logger name can be provided; |
| 980 | // otherwise a default will be used, like "log0", "log1", etc. |
| 981 | if h.NextArg() { |
| 982 | logName = h.Val() |
| 983 | |
| 984 | // Only a single argument is supported. |
| 985 | if h.NextArg() { |
| 986 | return nil, h.ArgErr() |
| 987 | } |
| 988 | } |
| 989 | } |
| 990 | |
| 991 | cl := new(caddy.CustomLog) |
| 992 | |
| 993 | // allow overriding the current site block's hostnames for this logger; |
| 994 | // this is useful for setting up loggers per subdomain in a site block |
| 995 | // with a wildcard domain |
| 996 | customHostnames := []string{} |
| 997 | noHostname := false |
| 998 | for h.NextBlock(0) { |
| 999 | switch h.Val() { |
| 1000 | case "hostnames": |
| 1001 | if parseAsGlobalOption { |
| 1002 | return nil, h.Err("hostnames is not allowed in the log global options") |
| 1003 | } |
| 1004 | args := h.RemainingArgs() |
| 1005 | if len(args) == 0 { |
| 1006 | return nil, h.ArgErr() |
| 1007 | } |
| 1008 | customHostnames = append(customHostnames, args...) |
| 1009 | |
| 1010 | case "output": |
| 1011 | if !h.NextArg() { |
| 1012 | return nil, h.ArgErr() |
| 1013 | } |
| 1014 | moduleName := h.Val() |
| 1015 | |
| 1016 | // can't use the usual caddyfile.Unmarshaler flow with the |
| 1017 | // standard writers because they are in the caddy package |
| 1018 | // (because they are the default) and implementing that |
| 1019 | // interface there would unfortunately create circular import |
| 1020 | var wo caddy.WriterOpener |
| 1021 | switch moduleName { |
| 1022 | case "stdout": |
| 1023 | wo = caddy.StdoutWriter{} |
| 1024 | case "stderr": |
| 1025 | wo = caddy.StderrWriter{} |
| 1026 | case "discard": |
| 1027 | wo = caddy.DiscardWriter{} |
| 1028 | default: |
| 1029 | modID := "caddy.logging.writers." + moduleName |
| 1030 | unm, err := caddyfile.UnmarshalModule(h.Dispenser, modID) |
| 1031 | if err != nil { |
| 1032 | return nil, err |
| 1033 | } |
| 1034 | var ok bool |
| 1035 | wo, ok = unm.(caddy.WriterOpener) |
| 1036 | if !ok { |
| 1037 | return nil, h.Errf("module %s (%T) is not a WriterOpener", modID, unm) |
| 1038 | } |
| 1039 | } |
| 1040 | cl.WriterRaw = caddyconfig.JSONModuleObject(wo, "output", moduleName, h.warnings) |
| 1041 | |
| 1042 | case "sampling": |
| 1043 | d := h.Dispenser.NewFromNextSegment() |
| 1044 | for d.NextArg() { |
| 1045 | // consume any tokens on the same line, if any. |
| 1046 | } |
| 1047 | |
| 1048 | sampling := &caddy.LogSampling{} |
| 1049 | for nesting := d.Nesting(); d.NextBlock(nesting); { |
| 1050 | subdir := d.Val() |
| 1051 | switch subdir { |
| 1052 | case "interval": |
| 1053 | if !d.NextArg() { |
| 1054 | return nil, d.ArgErr() |
| 1055 | } |
| 1056 | interval, err := caddy.ParseDuration(d.Val()) |
| 1057 | if err != nil { |
| 1058 | return nil, d.Errf("failed to parse interval: %v", err) |
| 1059 | } |
| 1060 | sampling.Interval = interval |
| 1061 | case "first": |
| 1062 | if !d.NextArg() { |
| 1063 | return nil, d.ArgErr() |
| 1064 | } |
| 1065 | first, err := strconv.Atoi(d.Val()) |
| 1066 | if err != nil { |
| 1067 | return nil, d.Errf("failed to parse first: %v", err) |
| 1068 | } |
| 1069 | sampling.First = first |
| 1070 | case "thereafter": |
| 1071 | if !d.NextArg() { |
| 1072 | return nil, d.ArgErr() |
| 1073 | } |
| 1074 | thereafter, err := strconv.Atoi(d.Val()) |
| 1075 | if err != nil { |
| 1076 | return nil, d.Errf("failed to parse thereafter: %v", err) |
| 1077 | } |
| 1078 | sampling.Thereafter = thereafter |
| 1079 | default: |
| 1080 | return nil, d.Errf("unrecognized subdirective: %s", subdir) |
| 1081 | } |
| 1082 | } |
| 1083 | |
| 1084 | cl.Sampling = sampling |
| 1085 | |
| 1086 | case "core": |
| 1087 | if !h.NextArg() { |
| 1088 | return nil, h.ArgErr() |
| 1089 | } |
| 1090 | moduleName := h.Val() |
| 1091 | moduleID := "caddy.logging.cores." + moduleName |
| 1092 | unm, err := caddyfile.UnmarshalModule(h.Dispenser, moduleID) |
| 1093 | if err != nil { |
| 1094 | return nil, err |
| 1095 | } |
| 1096 | core, ok := unm.(zapcore.Core) |
| 1097 | if !ok { |
| 1098 | return nil, h.Errf("module %s (%T) is not a zapcore.Core", moduleID, unm) |
| 1099 | } |
| 1100 | cl.CoreRaw = caddyconfig.JSONModuleObject(core, "module", moduleName, h.warnings) |
| 1101 | |
| 1102 | case "format": |
| 1103 | if !h.NextArg() { |
| 1104 | return nil, h.ArgErr() |
| 1105 | } |
| 1106 | moduleName := h.Val() |
| 1107 | moduleID := "caddy.logging.encoders." + moduleName |
| 1108 | unm, err := caddyfile.UnmarshalModule(h.Dispenser, moduleID) |
| 1109 | if err != nil { |
| 1110 | return nil, err |
| 1111 | } |
| 1112 | enc, ok := unm.(zapcore.Encoder) |
| 1113 | if !ok { |
| 1114 | return nil, h.Errf("module %s (%T) is not a zapcore.Encoder", moduleID, unm) |
| 1115 | } |
| 1116 | cl.EncoderRaw = caddyconfig.JSONModuleObject(enc, "format", moduleName, h.warnings) |
| 1117 | |
| 1118 | case "level": |
| 1119 | if !h.NextArg() { |
| 1120 | return nil, h.ArgErr() |
| 1121 | } |
| 1122 | cl.Level = h.Val() |
| 1123 | if h.NextArg() { |
| 1124 | return nil, h.ArgErr() |
| 1125 | } |
| 1126 | |
| 1127 | case "include": |
| 1128 | if !parseAsGlobalOption { |
| 1129 | return nil, h.Err("include is not allowed in the log directive") |
| 1130 | } |
| 1131 | for h.NextArg() { |
| 1132 | cl.Include = append(cl.Include, h.Val()) |
| 1133 | } |
| 1134 | |
| 1135 | case "exclude": |
| 1136 | if !parseAsGlobalOption { |
| 1137 | return nil, h.Err("exclude is not allowed in the log directive") |
| 1138 | } |
| 1139 | for h.NextArg() { |
| 1140 | cl.Exclude = append(cl.Exclude, h.Val()) |
| 1141 | } |
| 1142 | |
| 1143 | case "no_hostname": |
| 1144 | if h.NextArg() { |
| 1145 | return nil, h.ArgErr() |
| 1146 | } |
| 1147 | noHostname = true |
| 1148 | |
| 1149 | default: |
| 1150 | return nil, h.Errf("unrecognized subdirective: %s", h.Val()) |
| 1151 | } |
| 1152 | } |
| 1153 | |
| 1154 | var val namedCustomLog |
| 1155 | val.hostnames = customHostnames |
| 1156 | val.noHostname = noHostname |
| 1157 | isEmptyConfig := reflect.DeepEqual(cl, new(caddy.CustomLog)) |
| 1158 | |
| 1159 | // Skip handling of empty logging configs |
| 1160 | |
| 1161 | if parseAsGlobalOption { |
| 1162 | // Use indicated name for global log options |
| 1163 | val.name = logName |
| 1164 | } else { |
| 1165 | if logName != "" { |
| 1166 | val.name = logName |
| 1167 | } else if !isEmptyConfig { |
| 1168 | // Construct a log name for server log streams |
| 1169 | logCounter, ok := h.State["logCounter"].(int) |
| 1170 | if !ok { |
| 1171 | logCounter = 0 |
| 1172 | } |
| 1173 | val.name = fmt.Sprintf("log%d", logCounter) |
| 1174 | logCounter++ |
| 1175 | h.State["logCounter"] = logCounter |
| 1176 | } |
| 1177 | if val.name != "" { |
| 1178 | cl.Include = []string{"http.log.access." + val.name} |
| 1179 | } |
| 1180 | } |
| 1181 | if !isEmptyConfig { |
| 1182 | val.log = cl |
| 1183 | } |
| 1184 | configValues = append(configValues, ConfigValue{ |
| 1185 | Class: "custom_log", |
| 1186 | Value: val, |
| 1187 | }) |
| 1188 | return configValues, nil |
| 1189 | } |
| 1190 | |
| 1191 | // parseLogSkip parses the log_skip directive. Syntax: |
| 1192 | // |
| 1193 | // log_skip [<matcher>] |
| 1194 | func parseLogSkip(h Helper) (caddyhttp.MiddlewareHandler, error) { |
| 1195 | h.Next() // consume directive name |
| 1196 | |
| 1197 | // "skip_log" is deprecated, replaced by "log_skip" |
| 1198 | if h.Val() == "skip_log" { |
| 1199 | caddy.Log().Named("config.adapter.caddyfile").Warn("the 'skip_log' directive is deprecated, please use 'log_skip' instead!") |
| 1200 | } |
| 1201 | |
| 1202 | if h.NextArg() { |
| 1203 | return nil, h.ArgErr() |
| 1204 | } |
| 1205 | |
| 1206 | if h.NextBlock(0) { |
| 1207 | return nil, h.Err("log_skip directive does not accept blocks") |
| 1208 | } |
| 1209 | |
| 1210 | return caddyhttp.VarsMiddleware{"log_skip": true}, nil |
| 1211 | } |
| 1212 | |
| 1213 | // parseLogName parses the log_name directive. Syntax: |
| 1214 | // |
| 1215 | // log_name <names...> |
| 1216 | func parseLogName(h Helper) (caddyhttp.MiddlewareHandler, error) { |
| 1217 | h.Next() // consume directive name |
| 1218 | return caddyhttp.VarsMiddleware{ |
| 1219 | caddyhttp.AccessLoggerNameVarKey: h.RemainingArgs(), |
| 1220 | }, nil |
| 1221 | } |