| 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 caddyhttp |
| 16 | |
| 17 | import ( |
| 18 | "encoding/json" |
| 19 | "errors" |
| 20 | "fmt" |
| 21 | "net" |
| 22 | "net/http" |
| 23 | "net/textproto" |
| 24 | "net/url" |
| 25 | "path" |
| 26 | "regexp" |
| 27 | "runtime" |
| 28 | "slices" |
| 29 | "sort" |
| 30 | "strconv" |
| 31 | "strings" |
| 32 | |
| 33 | "github.com/google/cel-go/cel" |
| 34 | "github.com/google/cel-go/common/types" |
| 35 | "github.com/google/cel-go/common/types/ref" |
| 36 | "golang.org/x/net/idna" |
| 37 | |
| 38 | "github.com/caddyserver/caddy/v2" |
| 39 | "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" |
| 40 | ) |
| 41 | |
| 42 | type ( |
| 43 | // MatchHost matches requests by the Host value (case-insensitive). |
| 44 | // |
| 45 | // When used in a top-level HTTP route, |
| 46 | // [qualifying domain names](/docs/automatic-https#hostname-requirements) |
| 47 | // may trigger [automatic HTTPS](/docs/automatic-https), which automatically |
| 48 | // provisions and renews certificates for you. Before doing this, you |
| 49 | // should ensure that DNS records for these domains are properly configured, |
| 50 | // especially A/AAAA pointed at your server. |
| 51 | // |
| 52 | // Automatic HTTPS can be |
| 53 | // [customized or disabled](/docs/modules/http#servers/automatic_https). |
| 54 | // |
| 55 | // Wildcards (`*`) may be used to represent exactly one label of the |
| 56 | // hostname, in accordance with RFC 1034 (because host matchers are also |
| 57 | // used for automatic HTTPS which influences TLS certificates). Thus, |
| 58 | // a host of `*` matches hosts like `localhost` or `internal` but not |
| 59 | // `example.com`. To catch all hosts, omit the host matcher entirely. |
| 60 | // |
| 61 | // The wildcard can be useful for matching all subdomains, for example: |
| 62 | // `*.example.com` matches `foo.example.com` but not `foo.bar.example.com`. |
| 63 | // |
| 64 | // Duplicate entries will return an error. |
| 65 | MatchHost []string |
| 66 | |
| 67 | // MatchPath case-insensitively matches requests by the URI's path. Path |
| 68 | // matching is exact, not prefix-based, giving you more control and clarity |
| 69 | // over matching. Wildcards (`*`) may be used: |
| 70 | // |
| 71 | // - At the end only, for a prefix match (`/prefix/*`) |
| 72 | // - At the beginning only, for a suffix match (`*.suffix`) |
| 73 | // - On both sides only, for a substring match (`*/contains/*`) |
| 74 | // - In the middle, for a globular match (`/accounts/*/info`) |
| 75 | // |
| 76 | // Slashes are significant; i.e. `/foo*` matches `/foo`, `/foo/`, `/foo/bar`, |
| 77 | // and `/foobar`; but `/foo/*` does not match `/foo` or `/foobar`. Valid |
| 78 | // paths start with a slash `/`. |
| 79 | // |
| 80 | // Because there are, in general, multiple possible escaped forms of any |
| 81 | // path, path matchers operate in unescaped space; that is, path matchers |
| 82 | // should be written in their unescaped form to prevent ambiguities and |
| 83 | // possible security issues, as all request paths will be normalized to |
| 84 | // their unescaped forms before matcher evaluation. |
| 85 | // |
| 86 | // However, escape sequences in a match pattern are supported; they are |
| 87 | // compared with the request's raw/escaped path for those bytes only. |
| 88 | // In other words, a matcher of `/foo%2Fbar` will match a request path |
| 89 | // of precisely `/foo%2Fbar`, but not `/foo/bar`. It follows that matching |
| 90 | // the literal percent sign (%) in normalized space can be done using the |
| 91 | // escaped form, `%25`. |
| 92 | // |
| 93 | // Even though wildcards (`*`) operate in the normalized space, the special |
| 94 | // escaped wildcard (`%*`), which is not a valid escape sequence, may be |
| 95 | // used in place of a span that should NOT be decoded; that is, `/bands/%*` |
| 96 | // will match `/bands/AC%2fDC` whereas `/bands/*` will not. |
| 97 | // |
| 98 | // Even though path matching is done in normalized space, the special |
| 99 | // wildcard `%*` may be used in place of a span that should NOT be decoded; |
| 100 | // that is, `/bands/%*/` will match `/bands/AC%2fDC/` whereas `/bands/*/` |
| 101 | // will not. |
| 102 | // |
| 103 | // This matcher is fast, so it does not support regular expressions or |
| 104 | // capture groups. For slower but more powerful matching, use the |
| 105 | // path_regexp matcher. (Note that due to the special treatment of |
| 106 | // escape sequences in matcher patterns, they may perform slightly slower |
| 107 | // in high-traffic environments.) |
| 108 | MatchPath []string |
| 109 | |
| 110 | // MatchPathRE matches requests by a regular expression on the URI's path. |
| 111 | // Path matching is performed in the unescaped (decoded) form of the path. |
| 112 | // |
| 113 | // Upon a match, it adds placeholders to the request: `{http.regexp.name.capture_group}` |
| 114 | // where `name` is the regular expression's name, and `capture_group` is either |
| 115 | // the named or positional capture group from the expression itself. If no name |
| 116 | // is given, then the placeholder omits the name: `{http.regexp.capture_group}` |
| 117 | // (potentially leading to collisions). |
| 118 | MatchPathRE struct{ MatchRegexp } |
| 119 | |
| 120 | // MatchMethod matches requests by the method. |
| 121 | MatchMethod []string |
| 122 | |
| 123 | // MatchQuery matches requests by the URI's query string. It takes a JSON object |
| 124 | // keyed by the query keys, with an array of string values to match for that key. |
| 125 | // Query key matches are exact, but wildcards may be used for value matches. Both |
| 126 | // keys and values may be placeholders. |
| 127 | // |
| 128 | // An example of the structure to match `?key=value&topic=api&query=something` is: |
| 129 | // |
| 130 | // ```json |
| 131 | // { |
| 132 | // "key": ["value"], |
| 133 | // "topic": ["api"], |
| 134 | // "query": ["*"] |
| 135 | // } |
| 136 | // ``` |
| 137 | // |
| 138 | // Invalid query strings, including those with bad escapings or illegal characters |
| 139 | // like semicolons, will fail to parse and thus fail to match. |
| 140 | // |
| 141 | // **NOTE:** Notice that query string values are arrays, not singular values. This is |
| 142 | // because repeated keys are valid in query strings, and each one may have a |
| 143 | // different value. This matcher will match for a key if any one of its configured |
| 144 | // values is assigned in the query string. Backend applications relying on query |
| 145 | // strings MUST take into consideration that query string values are arrays and can |
| 146 | // have multiple values. |
| 147 | MatchQuery url.Values |
| 148 | |
| 149 | // MatchHeader matches requests by header fields. The key is the field |
| 150 | // name and the array is the list of field values. It performs fast, |
| 151 | // exact string comparisons of the field values. Fast prefix, suffix, |
| 152 | // and substring matches can also be done by suffixing, prefixing, or |
| 153 | // surrounding the value with the wildcard `*` character, respectively. |
| 154 | // If a list is null, the header must not exist. If the list is empty, |
| 155 | // the field must simply exist, regardless of its value. |
| 156 | // |
| 157 | // **NOTE:** Notice that header values are arrays, not singular values. This is |
| 158 | // because repeated fields are valid in headers, and each one may have a |
| 159 | // different value. This matcher will match for a field if any one of its configured |
| 160 | // values matches in the header. Backend applications relying on headers MUST take |
| 161 | // into consideration that header field values are arrays and can have multiple |
| 162 | // values. |
| 163 | MatchHeader http.Header |
| 164 | |
| 165 | // MatchHeaderRE matches requests by a regular expression on header fields. |
| 166 | // |
| 167 | // Upon a match, it adds placeholders to the request: `{http.regexp.name.capture_group}` |
| 168 | // where `name` is the regular expression's name, and `capture_group` is either |
| 169 | // the named or positional capture group from the expression itself. If no name |
| 170 | // is given, then the placeholder omits the name: `{http.regexp.capture_group}` |
| 171 | // (potentially leading to collisions). |
| 172 | MatchHeaderRE map[string]*MatchRegexp |
| 173 | |
| 174 | // MatchProtocol matches requests by protocol. Recognized values are |
| 175 | // "http", "https", and "grpc" for broad protocol matches, or specific |
| 176 | // HTTP versions can be specified like so: "http/1", "http/1.1", |
| 177 | // "http/2", "http/3", or minimum versions: "http/2+", etc. |
| 178 | MatchProtocol string |
| 179 | |
| 180 | // MatchTLS matches HTTP requests based on the underlying |
| 181 | // TLS connection state. If this matcher is specified but |
| 182 | // the request did not come over TLS, it will never match. |
| 183 | // If this matcher is specified but is empty and the request |
| 184 | // did come in over TLS, it will always match. |
| 185 | MatchTLS struct { |
| 186 | // Matches if the TLS handshake has completed. QUIC 0-RTT early |
| 187 | // data may arrive before the handshake completes. Generally, it |
| 188 | // is unsafe to replay these requests if they are not idempotent; |
| 189 | // additionally, the remote IP of early data packets can more |
| 190 | // easily be spoofed. It is conventional to respond with HTTP 425 |
| 191 | // Too Early if the request cannot risk being processed in this |
| 192 | // state. |
| 193 | HandshakeComplete *bool `json:"handshake_complete,omitempty"` |
| 194 | } |
| 195 | |
| 196 | // MatchNot matches requests by negating the results of its matcher |
| 197 | // sets. A single "not" matcher takes one or more matcher sets. Each |
| 198 | // matcher set is OR'ed; in other words, if any matcher set returns |
| 199 | // true, the final result of the "not" matcher is false. Individual |
| 200 | // matchers within a set work the same (i.e. different matchers in |
| 201 | // the same set are AND'ed). |
| 202 | // |
| 203 | // NOTE: The generated docs which describe the structure of this |
| 204 | // module are wrong because of how this type unmarshals JSON in a |
| 205 | // custom way. The correct structure is: |
| 206 | // |
| 207 | // ```json |
| 208 | // [ |
| 209 | // {}, |
| 210 | // {} |
| 211 | // ] |
| 212 | // ``` |
| 213 | // |
| 214 | // where each of the array elements is a matcher set, i.e. an |
| 215 | // object keyed by matcher name. |
| 216 | MatchNot struct { |
| 217 | MatcherSetsRaw []caddy.ModuleMap `json:"-" caddy:"namespace=http.matchers"` |
| 218 | MatcherSets []MatcherSet `json:"-"` |
| 219 | } |
| 220 | ) |
| 221 | |
| 222 | func init() { |
| 223 | caddy.RegisterModule(MatchHost{}) |
| 224 | caddy.RegisterModule(MatchPath{}) |
| 225 | caddy.RegisterModule(MatchPathRE{}) |
| 226 | caddy.RegisterModule(MatchMethod{}) |
| 227 | caddy.RegisterModule(MatchQuery{}) |
| 228 | caddy.RegisterModule(MatchHeader{}) |
| 229 | caddy.RegisterModule(MatchHeaderRE{}) |
| 230 | caddy.RegisterModule(new(MatchProtocol)) |
| 231 | caddy.RegisterModule(MatchTLS{}) |
| 232 | caddy.RegisterModule(MatchNot{}) |
| 233 | } |
| 234 | |
| 235 | // CaddyModule returns the Caddy module information. |
| 236 | func (MatchHost) CaddyModule() caddy.ModuleInfo { |
| 237 | return caddy.ModuleInfo{ |
| 238 | ID: "http.matchers.host", |
| 239 | New: func() caddy.Module { return new(MatchHost) }, |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | // UnmarshalCaddyfile implements caddyfile.Unmarshaler. |
| 244 | func (m *MatchHost) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { |
| 245 | // iterate to merge multiple matchers into one |
| 246 | for d.Next() { |
| 247 | *m = append(*m, d.RemainingArgs()...) |
| 248 | if d.NextBlock(0) { |
| 249 | return d.Err("malformed host matcher: blocks are not supported") |
| 250 | } |
| 251 | } |
| 252 | return nil |
| 253 | } |
| 254 | |
| 255 | // Provision sets up and validates m, including making it more efficient for large lists. |
| 256 | func (m MatchHost) Provision(_ caddy.Context) error { |
| 257 | // check for duplicates; they are nonsensical and reduce efficiency |
| 258 | // (we could just remove them, but the user should know their config is erroneous) |
| 259 | seen := make(map[string]int, len(m)) |
| 260 | for i, host := range m { |
| 261 | asciiHost, err := idna.ToASCII(host) |
| 262 | if err != nil { |
| 263 | return fmt.Errorf("converting hostname '%s' to ASCII: %v", host, err) |
| 264 | } |
| 265 | normalizedHost := strings.ToLower(asciiHost) |
| 266 | if firstI, ok := seen[normalizedHost]; ok { |
| 267 | return fmt.Errorf("host at index %d is repeated at index %d: %s", firstI, i, host) |
| 268 | } |
| 269 | // Normalize exact hosts for standardized comparison in large-list fastpath later on. |
| 270 | // Keep wildcards/placeholders untouched. |
| 271 | if m.fuzzy(asciiHost) { |
| 272 | m[i] = asciiHost |
| 273 | } else { |
| 274 | m[i] = normalizedHost |
| 275 | } |
| 276 | seen[normalizedHost] = i |
| 277 | } |
| 278 | |
| 279 | if m.large() { |
| 280 | // sort the slice lexicographically, grouping "fuzzy" entries (wildcards and placeholders) |
| 281 | // at the front of the list; this allows us to use binary search for exact matches, which |
| 282 | // we have seen from experience is the most common kind of value in large lists; and any |
| 283 | // other kinds of values (wildcards and placeholders) are grouped in front so the linear |
| 284 | // search should find a match fairly quickly |
| 285 | sort.Slice(m, func(i, j int) bool { |
| 286 | iInexact, jInexact := m.fuzzy(m[i]), m.fuzzy(m[j]) |
| 287 | if iInexact && !jInexact { |
| 288 | return true |
| 289 | } |
| 290 | if !iInexact && jInexact { |
| 291 | return false |
| 292 | } |
| 293 | return m[i] < m[j] |
| 294 | }) |
| 295 | } |
| 296 | |
| 297 | return nil |
| 298 | } |
| 299 | |
| 300 | // Match returns true if r matches m. |
| 301 | func (m MatchHost) Match(r *http.Request) bool { |
| 302 | match, _ := m.MatchWithError(r) |
| 303 | return match |
| 304 | } |
| 305 | |
| 306 | // MatchWithError returns true if r matches m. |
| 307 | func (m MatchHost) MatchWithError(r *http.Request) (bool, error) { |
| 308 | reqHost, _, err := net.SplitHostPort(r.Host) |
| 309 | if err != nil { |
| 310 | // OK; probably didn't have a port |
| 311 | reqHost = r.Host |
| 312 | |
| 313 | // make sure we strip the brackets from IPv6 addresses |
| 314 | reqHost = strings.TrimPrefix(reqHost, "[") |
| 315 | reqHost = strings.TrimSuffix(reqHost, "]") |
| 316 | } |
| 317 | |
| 318 | if m.large() { |
| 319 | reqHostLower := strings.ToLower(reqHost) |
| 320 | // fast path: locate exact match using binary search (about 100-1000x faster for large lists) |
| 321 | pos := sort.Search(len(m), func(i int) bool { |
| 322 | if m.fuzzy(m[i]) { |
| 323 | return false |
| 324 | } |
| 325 | return m[i] >= reqHostLower |
| 326 | }) |
| 327 | if pos < len(m) && m[pos] == reqHostLower { |
| 328 | return true, nil |
| 329 | } |
| 330 | } |
| 331 | |
| 332 | repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) |
| 333 | |
| 334 | outer: |
| 335 | for _, host := range m { |
| 336 | // fast path: if matcher is large, we already know we don't have an exact |
| 337 | // match, so we're only looking for fuzzy match now, which should be at the |
| 338 | // front of the list; if we have reached a value that is not fuzzy, there |
| 339 | // will be no match and we can short-circuit for efficiency |
| 340 | if m.large() && !m.fuzzy(host) { |
| 341 | break |
| 342 | } |
| 343 | |
| 344 | host = repl.ReplaceAll(host, "") |
| 345 | if strings.Contains(host, "*") { |
| 346 | patternParts := strings.Split(host, ".") |
| 347 | incomingParts := strings.Split(reqHost, ".") |
| 348 | if len(patternParts) != len(incomingParts) { |
| 349 | continue |
| 350 | } |
| 351 | for i := range patternParts { |
| 352 | if patternParts[i] == "*" { |
| 353 | continue |
| 354 | } |
| 355 | if !strings.EqualFold(patternParts[i], incomingParts[i]) { |
| 356 | continue outer |
| 357 | } |
| 358 | } |
| 359 | return true, nil |
| 360 | } else if strings.EqualFold(reqHost, host) { |
| 361 | return true, nil |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | return false, nil |
| 366 | } |
| 367 | |
| 368 | // CELLibrary produces options that expose this matcher for use in CEL |
| 369 | // expression matchers. |
| 370 | // |
| 371 | // Example: |
| 372 | // |
| 373 | // expression host('localhost') |
| 374 | func (MatchHost) CELLibrary(ctx caddy.Context) (cel.Library, error) { |
| 375 | return CELMatcherImpl( |
| 376 | "host", |
| 377 | "host_match_request_list", |
| 378 | []*cel.Type{cel.ListType(cel.StringType)}, |
| 379 | func(data ref.Val) (RequestMatcherWithError, error) { |
| 380 | refStringList := stringSliceType |
| 381 | strList, err := data.ConvertToNative(refStringList) |
| 382 | if err != nil { |
| 383 | return nil, err |
| 384 | } |
| 385 | matcher := MatchHost(strList.([]string)) |
| 386 | err = matcher.Provision(ctx) |
| 387 | return matcher, err |
| 388 | }, |
| 389 | ) |
| 390 | } |
| 391 | |
| 392 | // fuzzy returns true if the given hostname h is not a specific |
| 393 | // hostname, e.g. has placeholders or wildcards. |
| 394 | func (MatchHost) fuzzy(h string) bool { return strings.ContainsAny(h, "{*") } |
| 395 | |
| 396 | // large returns true if m is considered to be large. Optimizing |
| 397 | // the matcher for smaller lists has diminishing returns. |
| 398 | // See related benchmark function in test file to conduct experiments. |
| 399 | func (m MatchHost) large() bool { return len(m) > 100 } |
| 400 | |
| 401 | // CaddyModule returns the Caddy module information. |
| 402 | func (MatchPath) CaddyModule() caddy.ModuleInfo { |
| 403 | return caddy.ModuleInfo{ |
| 404 | ID: "http.matchers.path", |
| 405 | New: func() caddy.Module { return new(MatchPath) }, |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | // Provision lower-cases the paths in m to ensure case-insensitive matching. |
| 410 | func (m MatchPath) Provision(_ caddy.Context) error { |
| 411 | for i := range m { |
| 412 | if m[i] == "*" && i > 0 { |
| 413 | // will always match, so just put it first |
| 414 | m[0] = m[i] |
| 415 | break |
| 416 | } |
| 417 | m[i] = strings.ToLower(m[i]) |
| 418 | } |
| 419 | return nil |
| 420 | } |
| 421 | |
| 422 | // Match returns true if r matches m. |
| 423 | func (m MatchPath) Match(r *http.Request) bool { |
| 424 | match, _ := m.MatchWithError(r) |
| 425 | return match |
| 426 | } |
| 427 | |
| 428 | // MatchWithError returns true if r matches m. |
| 429 | func (m MatchPath) MatchWithError(r *http.Request) (bool, error) { |
| 430 | // Even though RFC 9110 says that path matching is case-sensitive |
| 431 | // (https://www.rfc-editor.org/rfc/rfc9110.html#section-4.2.3), |
| 432 | // we do case-insensitive matching to mitigate security issues |
| 433 | // related to differences between operating systems, applications, |
| 434 | // etc; if case-sensitive matching is needed, the regex matcher |
| 435 | // can be used instead. |
| 436 | reqPath := strings.ToLower(r.URL.Path) |
| 437 | |
| 438 | if runtime.GOOS == "windows" { // issue #5613 |
| 439 | // Windows treats backslashes as path separators and |
| 440 | // ignores trailing dots and spaces when accessing files |
| 441 | // (sigh), potentially causing a security risk (cry) if |
| 442 | // protected files are not matched as intended. |
| 443 | reqPath = strings.ReplaceAll(reqPath, `\`, "/") |
| 444 | reqPath = strings.TrimRight(reqPath, ". ") |
| 445 | } |
| 446 | |
| 447 | repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) |
| 448 | |
| 449 | for _, matchPattern := range m { |
| 450 | matchPattern = repl.ReplaceAll(matchPattern, "") |
| 451 | |
| 452 | // special case: whole path is wildcard; this is unnecessary |
| 453 | // as it matches all requests, which is the same as no matcher |
| 454 | if matchPattern == "*" { |
| 455 | return true, nil |
| 456 | } |
| 457 | |
| 458 | // Clean the path, merge doubled slashes, etc. |
| 459 | // This ensures maliciously crafted requests can't bypass |
| 460 | // the path matcher. See #4407. Good security posture |
| 461 | // requires that we should do all we can to reduce any |
| 462 | // funny-looking paths into "normalized" forms such that |
| 463 | // weird variants can't sneak by. |
| 464 | // |
| 465 | // How we clean the path depends on the kind of pattern: |
| 466 | // we either merge slashes or we don't. If the pattern |
| 467 | // has double slashes, we preserve them in the path. |
| 468 | // |
| 469 | // TODO: Despite the fact that the *vast* majority of path |
| 470 | // matchers have only 1 pattern, a possible optimization is |
| 471 | // to remember the cleaned form of the path for future |
| 472 | // iterations; it's just that the way we clean depends on |
| 473 | // the kind of pattern. |
| 474 | |
| 475 | mergeSlashes := !strings.Contains(matchPattern, "//") |
| 476 | |
| 477 | // if '%' appears in the match pattern, we interpret that to mean |
| 478 | // the intent is to compare that part of the path in raw/escaped |
| 479 | // space; i.e. "%40"=="%40", not "@", and "%2F"=="%2F", not "/" |
| 480 | if strings.Contains(matchPattern, "%") { |
| 481 | escapedPath := r.URL.EscapedPath() |
| 482 | if runtime.GOOS == "windows" { |
| 483 | escapedPath = windowsEscapedPathSeparatorRepl.Replace(escapedPath) |
| 484 | matchPattern = windowsEscapedPathSeparatorRepl.Replace(matchPattern) |
| 485 | } |
| 486 | reqPathForPattern := CleanPath(escapedPath, mergeSlashes) |
| 487 | if m.matchPatternWithEscapeSequence(reqPathForPattern, matchPattern) { |
| 488 | return true, nil |
| 489 | } |
| 490 | |
| 491 | // doing prefix/suffix/substring matches doesn't make sense |
| 492 | continue |
| 493 | } |
| 494 | |
| 495 | reqPathForPattern := CleanPath(reqPath, mergeSlashes) |
| 496 | |
| 497 | // for substring, prefix, and suffix matching, only perform those |
| 498 | // special, fast matches if they are the only wildcards in the pattern; |
| 499 | // otherwise we assume a globular match if any * appears in the middle |
| 500 | |
| 501 | // special case: first and last characters are wildcard, |
| 502 | // treat it as a fast substring match |
| 503 | if strings.Count(matchPattern, "*") == 2 && |
| 504 | strings.HasPrefix(matchPattern, "*") && |
| 505 | strings.HasSuffix(matchPattern, "*") { |
| 506 | if strings.Contains(reqPathForPattern, matchPattern[1:len(matchPattern)-1]) { |
| 507 | return true, nil |
| 508 | } |
| 509 | continue |
| 510 | } |
| 511 | |
| 512 | // only perform prefix/suffix match if it is the only wildcard... |
| 513 | // I think that is more correct most of the time |
| 514 | if strings.Count(matchPattern, "*") == 1 { |
| 515 | // special case: first character is a wildcard, |
| 516 | // treat it as a fast suffix match |
| 517 | if strings.HasPrefix(matchPattern, "*") { |
| 518 | if strings.HasSuffix(reqPathForPattern, matchPattern[1:]) { |
| 519 | return true, nil |
| 520 | } |
| 521 | continue |
| 522 | } |
| 523 | |
| 524 | // special case: last character is a wildcard, |
| 525 | // treat it as a fast prefix match |
| 526 | if strings.HasSuffix(matchPattern, "*") { |
| 527 | if strings.HasPrefix(reqPathForPattern, matchPattern[:len(matchPattern)-1]) { |
| 528 | return true, nil |
| 529 | } |
| 530 | continue |
| 531 | } |
| 532 | } |
| 533 | |
| 534 | // at last, use globular matching, which also is exact matching |
| 535 | // if there are no glob/wildcard chars; we ignore the error here |
| 536 | // because we can't handle it anyway |
| 537 | matches, _ := path.Match(matchPattern, reqPathForPattern) |
| 538 | if matches { |
| 539 | return true, nil |
| 540 | } |
| 541 | } |
| 542 | return false, nil |
| 543 | } |
| 544 | |
| 545 | func (MatchPath) matchPatternWithEscapeSequence(escapedPath, matchPath string) bool { |
| 546 | escapedPath = strings.ToLower(escapedPath) |
| 547 | // We would just compare the pattern against r.URL.Path, |
| 548 | // but the pattern contains %, indicating that we should |
| 549 | // compare at least some part of the path in raw/escaped |
| 550 | // space, not normalized space; so we build the string we |
| 551 | // will compare against by adding the normalized parts |
| 552 | // of the path, then switching to the escaped parts where |
| 553 | // the pattern hints to us wherever % is present. |
| 554 | var sb strings.Builder |
| 555 | |
| 556 | // iterate the pattern and escaped path in lock-step; |
| 557 | // increment iPattern every time we consume a char from the pattern, |
| 558 | // increment iPath every time we consume a char from the path; |
| 559 | // iPattern and iPath are our cursors/iterator positions for each string |
| 560 | var iPattern, iPath int |
| 561 | for { |
| 562 | if iPattern >= len(matchPath) || iPath >= len(escapedPath) { |
| 563 | break |
| 564 | } |
| 565 | // get the next character from the request path |
| 566 | |
| 567 | pathCh := string(escapedPath[iPath]) |
| 568 | var escapedPathCh string |
| 569 | |
| 570 | // normalize (decode) escape sequences |
| 571 | if pathCh == "%" && len(escapedPath) >= iPath+3 { |
| 572 | // hold onto this in case we find out the intent is to match in escaped space here; |
| 573 | // we lowercase it even though technically the spec says: "For consistency, URI |
| 574 | // producers and normalizers should use uppercase hexadecimal digits for all percent- |
| 575 | // encodings" (RFC 3986 section 2.1) - we lowercased the matcher pattern earlier in |
| 576 | // provisioning so we do the same here to gain case-insensitivity in equivalence; |
| 577 | // besides, this string is never shown visibly |
| 578 | escapedPathCh = strings.ToLower(escapedPath[iPath : iPath+3]) |
| 579 | |
| 580 | var err error |
| 581 | pathCh, err = url.PathUnescape(escapedPathCh) |
| 582 | if err != nil { |
| 583 | // should be impossible unless EscapedPath() is giving us an invalid sequence! |
| 584 | return false |
| 585 | } |
| 586 | iPath += 2 // escape sequence is 2 bytes longer than normal char |
| 587 | } |
| 588 | |
| 589 | // now get the next character from the pattern |
| 590 | |
| 591 | normalize := true |
| 592 | switch matchPath[iPattern] { |
| 593 | case '%': |
| 594 | // escape sequence |
| 595 | |
| 596 | // if not a wildcard ("%*"), compare literally; consume next two bytes of pattern |
| 597 | if len(matchPath) >= iPattern+3 && matchPath[iPattern+1] != '*' { |
| 598 | sb.WriteString(escapedPathCh) |
| 599 | iPath++ |
| 600 | iPattern += 2 |
| 601 | break |
| 602 | } |
| 603 | |
| 604 | // escaped wildcard sequence; consume next byte only ('*') |
| 605 | iPattern++ |
| 606 | normalize = false |
| 607 | |
| 608 | fallthrough |
| 609 | case '*': |
| 610 | // wildcard, so consume until next matching character |
| 611 | remaining := escapedPath[iPath:] |
| 612 | until := len(escapedPath) - iPath // go until end of string... |
| 613 | if iPattern < len(matchPath)-1 { // ...unless the * is not at the end |
| 614 | nextCh := matchPath[iPattern+1] |
| 615 | until = strings.IndexByte(remaining, nextCh) |
| 616 | if until == -1 { |
| 617 | // terminating char of wildcard span not found, so definitely no match |
| 618 | return false |
| 619 | } |
| 620 | } |
| 621 | if until == 0 { |
| 622 | // empty span; nothing to add on this iteration |
| 623 | break |
| 624 | } |
| 625 | next := remaining[:until] |
| 626 | if normalize { |
| 627 | var err error |
| 628 | next, err = url.PathUnescape(next) |
| 629 | if err != nil { |
| 630 | return false // should be impossible anyway |
| 631 | } |
| 632 | } |
| 633 | sb.WriteString(next) |
| 634 | iPath += until |
| 635 | default: |
| 636 | sb.WriteString(pathCh) |
| 637 | iPath++ |
| 638 | } |
| 639 | |
| 640 | iPattern++ |
| 641 | } |
| 642 | |
| 643 | // we can now treat rawpath globs (%*) as regular globs (*) |
| 644 | matchPath = strings.ReplaceAll(matchPath, "%*", "*") |
| 645 | |
| 646 | // ignore error here because we can't handle it anyway |
| 647 | matches, _ := path.Match(matchPath, strings.ToLower(sb.String())) |
| 648 | return matches |
| 649 | } |
| 650 | |
| 651 | // windowsEscapedPathSeparatorRepl normalizes Windows backslash separators |
| 652 | // while preserving escaped-path matching semantics. |
| 653 | var windowsEscapedPathSeparatorRepl = strings.NewReplacer( |
| 654 | `\`, "%2f", |
| 655 | "%5c", "%2f", |
| 656 | "%5C", "%2f", |
| 657 | ) |
| 658 | |
| 659 | // CELLibrary produces options that expose this matcher for use in CEL |
| 660 | // expression matchers. |
| 661 | // |
| 662 | // Example: |
| 663 | // |
| 664 | // expression path('*substring*', '*suffix') |
| 665 | func (MatchPath) CELLibrary(ctx caddy.Context) (cel.Library, error) { |
| 666 | return CELMatcherImpl( |
| 667 | // name of the macro, this is the function name that users see when writing expressions. |
| 668 | "path", |
| 669 | // name of the function that the macro will be rewritten to call. |
| 670 | "path_match_request_list", |
| 671 | // internal data type of the MatchPath value. |
| 672 | []*cel.Type{cel.ListType(cel.StringType)}, |
| 673 | // function to convert a constant list of strings to a MatchPath instance. |
| 674 | func(data ref.Val) (RequestMatcherWithError, error) { |
| 675 | refStringList := stringSliceType |
| 676 | strList, err := data.ConvertToNative(refStringList) |
| 677 | if err != nil { |
| 678 | return nil, err |
| 679 | } |
| 680 | matcher := MatchPath(strList.([]string)) |
| 681 | err = matcher.Provision(ctx) |
| 682 | return matcher, err |
| 683 | }, |
| 684 | ) |
| 685 | } |
| 686 | |
| 687 | // UnmarshalCaddyfile implements caddyfile.Unmarshaler. |
| 688 | func (m *MatchPath) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { |
| 689 | // iterate to merge multiple matchers into one |
| 690 | for d.Next() { |
| 691 | *m = append(*m, d.RemainingArgs()...) |
| 692 | if d.NextBlock(0) { |
| 693 | return d.Err("malformed path matcher: blocks are not supported") |
| 694 | } |
| 695 | } |
| 696 | return nil |
| 697 | } |
| 698 | |
| 699 | // CaddyModule returns the Caddy module information. |
| 700 | func (MatchPathRE) CaddyModule() caddy.ModuleInfo { |
| 701 | return caddy.ModuleInfo{ |
| 702 | ID: "http.matchers.path_regexp", |
| 703 | New: func() caddy.Module { return new(MatchPathRE) }, |
| 704 | } |
| 705 | } |
| 706 | |
| 707 | // Match returns true if r matches m. |
| 708 | func (m MatchPathRE) Match(r *http.Request) bool { |
| 709 | match, _ := m.MatchWithError(r) |
| 710 | return match |
| 711 | } |
| 712 | |
| 713 | // MatchWithError returns true if r matches m. |
| 714 | func (m MatchPathRE) MatchWithError(r *http.Request) (bool, error) { |
| 715 | repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) |
| 716 | |
| 717 | // Clean the path, merges doubled slashes, etc. |
| 718 | // This ensures maliciously crafted requests can't bypass |
| 719 | // the path matcher. See #4407 |
| 720 | cleanedPath := cleanPath(r.URL.Path) |
| 721 | |
| 722 | return m.MatchRegexp.Match(cleanedPath, repl), nil |
| 723 | } |
| 724 | |
| 725 | // CELLibrary produces options that expose this matcher for use in CEL |
| 726 | // expression matchers. |
| 727 | // |
| 728 | // Example: |
| 729 | // |
| 730 | // expression path_regexp('^/bar') |
| 731 | func (MatchPathRE) CELLibrary(ctx caddy.Context) (cel.Library, error) { |
| 732 | unnamedPattern, err := CELMatcherImpl( |
| 733 | "path_regexp", |
| 734 | "path_regexp_request_string", |
| 735 | []*cel.Type{cel.StringType}, |
| 736 | func(data ref.Val) (RequestMatcherWithError, error) { |
| 737 | pattern := data.(types.String) |
| 738 | matcher := MatchPathRE{MatchRegexp{ |
| 739 | Name: ctx.Value(MatcherNameCtxKey).(string), |
| 740 | Pattern: string(pattern), |
| 741 | }} |
| 742 | err := matcher.Provision(ctx) |
| 743 | return matcher, err |
| 744 | }, |
| 745 | ) |
| 746 | if err != nil { |
| 747 | return nil, err |
| 748 | } |
| 749 | namedPattern, err := CELMatcherImpl( |
| 750 | "path_regexp", |
| 751 | "path_regexp_request_string_string", |
| 752 | []*cel.Type{cel.StringType, cel.StringType}, |
| 753 | func(data ref.Val) (RequestMatcherWithError, error) { |
| 754 | refStringList := stringSliceType |
| 755 | params, err := data.ConvertToNative(refStringList) |
| 756 | if err != nil { |
| 757 | return nil, err |
| 758 | } |
| 759 | strParams := params.([]string) |
| 760 | name := strParams[0] |
| 761 | if name == "" { |
| 762 | name = ctx.Value(MatcherNameCtxKey).(string) |
| 763 | } |
| 764 | matcher := MatchPathRE{MatchRegexp{ |
| 765 | Name: name, |
| 766 | Pattern: strParams[1], |
| 767 | }} |
| 768 | err = matcher.Provision(ctx) |
| 769 | return matcher, err |
| 770 | }, |
| 771 | ) |
| 772 | if err != nil { |
| 773 | return nil, err |
| 774 | } |
| 775 | envOpts := append(unnamedPattern.CompileOptions(), namedPattern.CompileOptions()...) |
| 776 | prgOpts := append(unnamedPattern.ProgramOptions(), namedPattern.ProgramOptions()...) |
| 777 | return NewMatcherCELLibrary(envOpts, prgOpts), nil |
| 778 | } |
| 779 | |
| 780 | // CaddyModule returns the Caddy module information. |
| 781 | func (MatchMethod) CaddyModule() caddy.ModuleInfo { |
| 782 | return caddy.ModuleInfo{ |
| 783 | ID: "http.matchers.method", |
| 784 | New: func() caddy.Module { return new(MatchMethod) }, |
| 785 | } |
| 786 | } |
| 787 | |
| 788 | // UnmarshalCaddyfile implements caddyfile.Unmarshaler. |
| 789 | func (m *MatchMethod) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { |
| 790 | // iterate to merge multiple matchers into one |
| 791 | for d.Next() { |
| 792 | *m = append(*m, d.RemainingArgs()...) |
| 793 | if d.NextBlock(0) { |
| 794 | return d.Err("malformed method matcher: blocks are not supported") |
| 795 | } |
| 796 | } |
| 797 | return nil |
| 798 | } |
| 799 | |
| 800 | // Match returns true if r matches m. |
| 801 | func (m MatchMethod) Match(r *http.Request) bool { |
| 802 | match, _ := m.MatchWithError(r) |
| 803 | return match |
| 804 | } |
| 805 | |
| 806 | // MatchWithError returns true if r matches m. |
| 807 | func (m MatchMethod) MatchWithError(r *http.Request) (bool, error) { |
| 808 | return slices.Contains(m, r.Method), nil |
| 809 | } |
| 810 | |
| 811 | // CELLibrary produces options that expose this matcher for use in CEL |
| 812 | // expression matchers. |
| 813 | // |
| 814 | // Example: |
| 815 | // |
| 816 | // expression method('PUT', 'POST') |
| 817 | func (MatchMethod) CELLibrary(_ caddy.Context) (cel.Library, error) { |
| 818 | return CELMatcherImpl( |
| 819 | "method", |
| 820 | "method_request_list", |
| 821 | []*cel.Type{cel.ListType(cel.StringType)}, |
| 822 | func(data ref.Val) (RequestMatcherWithError, error) { |
| 823 | refStringList := stringSliceType |
| 824 | strList, err := data.ConvertToNative(refStringList) |
| 825 | if err != nil { |
| 826 | return nil, err |
| 827 | } |
| 828 | return MatchMethod(strList.([]string)), nil |
| 829 | }, |
| 830 | ) |
| 831 | } |
| 832 | |
| 833 | // CaddyModule returns the Caddy module information. |
| 834 | func (MatchQuery) CaddyModule() caddy.ModuleInfo { |
| 835 | return caddy.ModuleInfo{ |
| 836 | ID: "http.matchers.query", |
| 837 | New: func() caddy.Module { return new(MatchQuery) }, |
| 838 | } |
| 839 | } |
| 840 | |
| 841 | // UnmarshalCaddyfile implements caddyfile.Unmarshaler. |
| 842 | func (m *MatchQuery) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { |
| 843 | if *m == nil { |
| 844 | *m = make(map[string][]string) |
| 845 | } |
| 846 | // iterate to merge multiple matchers into one |
| 847 | for d.Next() { |
| 848 | for _, query := range d.RemainingArgs() { |
| 849 | if query == "" { |
| 850 | continue |
| 851 | } |
| 852 | before, after, found := strings.Cut(query, "=") |
| 853 | if !found { |
| 854 | return d.Errf("malformed query matcher token: %s; must be in param=val format", d.Val()) |
| 855 | } |
| 856 | url.Values(*m).Add(before, after) |
| 857 | } |
| 858 | if d.NextBlock(0) { |
| 859 | return d.Err("malformed query matcher: blocks are not supported") |
| 860 | } |
| 861 | } |
| 862 | return nil |
| 863 | } |
| 864 | |
| 865 | // Match returns true if r matches m. An empty m matches an empty query string. |
| 866 | func (m MatchQuery) Match(r *http.Request) bool { |
| 867 | match, _ := m.MatchWithError(r) |
| 868 | return match |
| 869 | } |
| 870 | |
| 871 | // MatchWithError returns true if r matches m. |
| 872 | // An empty m matches an empty query string. |
| 873 | func (m MatchQuery) MatchWithError(r *http.Request) (bool, error) { |
| 874 | // If no query keys are configured, this only |
| 875 | // matches an empty query string. |
| 876 | if len(m) == 0 { |
| 877 | return len(r.URL.Query()) == 0, nil |
| 878 | } |
| 879 | |
| 880 | repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) |
| 881 | |
| 882 | // parse query string just once, for efficiency |
| 883 | parsed, err := url.ParseQuery(r.URL.RawQuery) |
| 884 | if err != nil { |
| 885 | // Illegal query string. Likely bad escape sequence or unescaped literals. |
| 886 | // Note that semicolons in query string have a controversial history. Summaries: |
| 887 | // - https://github.com/golang/go/issues/50034 |
| 888 | // - https://github.com/golang/go/issues/25192 |
| 889 | // Despite the URL WHATWG spec mandating the use of & separators for query strings, |
| 890 | // every URL parser implementation is different, and Filippo Valsorda rightly wrote: |
| 891 | // "Relying on parser alignment for security is doomed." Overall conclusion is that |
| 892 | // splitting on & and rejecting ; in key=value pairs is safer than accepting raw ;. |
| 893 | // We regard the Go team's decision as sound and thus reject malformed query strings. |
| 894 | return false, nil |
| 895 | } |
| 896 | |
| 897 | // Count the amount of matched keys, to ensure we AND |
| 898 | // between all configured query keys; all keys must |
| 899 | // match at least one value. |
| 900 | matchedKeys := 0 |
| 901 | for param, vals := range m { |
| 902 | param = repl.ReplaceAll(param, "") |
| 903 | paramVal, found := parsed[param] |
| 904 | if !found { |
| 905 | return false, nil |
| 906 | } |
| 907 | for _, v := range vals { |
| 908 | v = repl.ReplaceAll(v, "") |
| 909 | if slices.Contains(paramVal, v) || v == "*" { |
| 910 | matchedKeys++ |
| 911 | break |
| 912 | } |
| 913 | } |
| 914 | } |
| 915 | return matchedKeys == len(m), nil |
| 916 | } |
| 917 | |
| 918 | // CELLibrary produces options that expose this matcher for use in CEL |
| 919 | // expression matchers. |
| 920 | // |
| 921 | // Example: |
| 922 | // |
| 923 | // expression query({'sort': 'asc'}) || query({'foo': ['*bar*', 'baz']}) |
| 924 | func (MatchQuery) CELLibrary(_ caddy.Context) (cel.Library, error) { |
| 925 | return CELMatcherImpl( |
| 926 | "query", |
| 927 | "query_matcher_request_map", |
| 928 | []*cel.Type{CELTypeJSON}, |
| 929 | func(data ref.Val) (RequestMatcherWithError, error) { |
| 930 | mapStrListStr, err := CELValueToMapStrList(data) |
| 931 | if err != nil { |
| 932 | return nil, err |
| 933 | } |
| 934 | return MatchQuery(url.Values(mapStrListStr)), nil |
| 935 | }, |
| 936 | ) |
| 937 | } |
| 938 | |
| 939 | // CaddyModule returns the Caddy module information. |
| 940 | func (MatchHeader) CaddyModule() caddy.ModuleInfo { |
| 941 | return caddy.ModuleInfo{ |
| 942 | ID: "http.matchers.header", |
| 943 | New: func() caddy.Module { return new(MatchHeader) }, |
| 944 | } |
| 945 | } |
| 946 | |
| 947 | // UnmarshalCaddyfile implements caddyfile.Unmarshaler. |
| 948 | func (m *MatchHeader) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { |
| 949 | if *m == nil { |
| 950 | *m = make(map[string][]string) |
| 951 | } |
| 952 | // iterate to merge multiple matchers into one |
| 953 | for d.Next() { |
| 954 | var field, val string |
| 955 | if !d.Args(&field) { |
| 956 | return d.Errf("malformed header matcher: expected field") |
| 957 | } |
| 958 | |
| 959 | if strings.HasPrefix(field, "!") { |
| 960 | if len(field) == 1 { |
| 961 | return d.Errf("malformed header matcher: must have field name following ! character") |
| 962 | } |
| 963 | |
| 964 | field = field[1:] |
| 965 | headers := *m |
| 966 | headers[field] = nil |
| 967 | m = &headers |
| 968 | if d.NextArg() { |
| 969 | return d.Errf("malformed header matcher: null matching headers cannot have a field value") |
| 970 | } |
| 971 | } else { |
| 972 | if !d.NextArg() { |
| 973 | return d.Errf("malformed header matcher: expected both field and value") |
| 974 | } |
| 975 | |
| 976 | // If multiple header matchers with the same header field are defined, |
| 977 | // we want to add the existing to the list of headers (will be OR'ed) |
| 978 | val = d.Val() |
| 979 | http.Header(*m).Add(field, val) |
| 980 | } |
| 981 | |
| 982 | if d.NextBlock(0) { |
| 983 | return d.Err("malformed header matcher: blocks are not supported") |
| 984 | } |
| 985 | } |
| 986 | return nil |
| 987 | } |
| 988 | |
| 989 | // Match returns true if r matches m. |
| 990 | func (m MatchHeader) Match(r *http.Request) bool { |
| 991 | match, _ := m.MatchWithError(r) |
| 992 | return match |
| 993 | } |
| 994 | |
| 995 | // MatchWithError returns true if r matches m. |
| 996 | func (m MatchHeader) MatchWithError(r *http.Request) (bool, error) { |
| 997 | repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) |
| 998 | return matchHeaders(r.Header, http.Header(m), r.Host, r.TransferEncoding, repl), nil |
| 999 | } |
| 1000 | |
| 1001 | // CELLibrary produces options that expose this matcher for use in CEL |
| 1002 | // expression matchers. |
| 1003 | // |
| 1004 | // Example: |
| 1005 | // |
| 1006 | // expression header({'content-type': 'image/png'}) |
| 1007 | // expression header({'foo': ['bar', 'baz']}) // match bar or baz |
| 1008 | func (MatchHeader) CELLibrary(_ caddy.Context) (cel.Library, error) { |
| 1009 | return CELMatcherImpl( |
| 1010 | "header", |
| 1011 | "header_matcher_request_map", |
| 1012 | []*cel.Type{CELTypeJSON}, |
| 1013 | func(data ref.Val) (RequestMatcherWithError, error) { |
| 1014 | mapStrListStr, err := CELValueToMapStrList(data) |
| 1015 | if err != nil { |
| 1016 | return nil, err |
| 1017 | } |
| 1018 | return MatchHeader(http.Header(mapStrListStr)), nil |
| 1019 | }, |
| 1020 | ) |
| 1021 | } |
| 1022 | |
| 1023 | // getHeaderFieldVals returns the field values for the given fieldName from input. |
| 1024 | // The host parameter should be obtained from the http.Request.Host field, and the |
| 1025 | // transferEncoding from http.Request.TransferEncoding, since net/http removes them |
| 1026 | // from the header map. |
| 1027 | func getHeaderFieldVals(input http.Header, fieldName, host string, transferEncoding []string) []string { |
| 1028 | fieldName = textproto.CanonicalMIMEHeaderKey(fieldName) |
| 1029 | if fieldName == "Host" && host != "" { |
| 1030 | return []string{host} |
| 1031 | } |
| 1032 | if fieldName == "Transfer-Encoding" && input[fieldName] == nil { |
| 1033 | return transferEncoding |
| 1034 | } |
| 1035 | return input[fieldName] |
| 1036 | } |
| 1037 | |
| 1038 | // matchHeaders returns true if input matches the criteria in against without regex. |
| 1039 | // The host parameter should be obtained from the http.Request.Host field since |
| 1040 | // net/http removes it from the header map. |
| 1041 | func matchHeaders(input, against http.Header, host string, transferEncoding []string, repl *caddy.Replacer) bool { |
| 1042 | for field, allowedFieldVals := range against { |
| 1043 | actualFieldVals := getHeaderFieldVals(input, field, host, transferEncoding) |
| 1044 | if allowedFieldVals != nil && len(allowedFieldVals) == 0 && actualFieldVals != nil { |
| 1045 | // a non-nil but empty list of allowed values means |
| 1046 | // match if the header field exists at all |
| 1047 | continue |
| 1048 | } |
| 1049 | if allowedFieldVals == nil && actualFieldVals == nil { |
| 1050 | // a nil list means match if the header does not exist at all |
| 1051 | continue |
| 1052 | } |
| 1053 | var match bool |
| 1054 | fieldVals: |
| 1055 | for _, actualFieldVal := range actualFieldVals { |
| 1056 | for _, allowedFieldVal := range allowedFieldVals { |
| 1057 | if repl != nil { |
| 1058 | allowedFieldVal = repl.ReplaceAll(allowedFieldVal, "") |
| 1059 | } |
| 1060 | switch { |
| 1061 | case allowedFieldVal == "*": |
| 1062 | match = true |
| 1063 | case strings.HasPrefix(allowedFieldVal, "*") && strings.HasSuffix(allowedFieldVal, "*"): |
| 1064 | match = strings.Contains(actualFieldVal, allowedFieldVal[1:len(allowedFieldVal)-1]) |
| 1065 | case strings.HasPrefix(allowedFieldVal, "*"): |
| 1066 | match = strings.HasSuffix(actualFieldVal, allowedFieldVal[1:]) |
| 1067 | case strings.HasSuffix(allowedFieldVal, "*"): |
| 1068 | match = strings.HasPrefix(actualFieldVal, allowedFieldVal[:len(allowedFieldVal)-1]) |
| 1069 | default: |
| 1070 | match = actualFieldVal == allowedFieldVal |
| 1071 | } |
| 1072 | if match { |
| 1073 | break fieldVals |
| 1074 | } |
| 1075 | } |
| 1076 | } |
| 1077 | if !match { |
| 1078 | return false |
| 1079 | } |
| 1080 | } |
| 1081 | return true |
| 1082 | } |
| 1083 | |
| 1084 | // CaddyModule returns the Caddy module information. |
| 1085 | func (MatchHeaderRE) CaddyModule() caddy.ModuleInfo { |
| 1086 | return caddy.ModuleInfo{ |
| 1087 | ID: "http.matchers.header_regexp", |
| 1088 | New: func() caddy.Module { return new(MatchHeaderRE) }, |
| 1089 | } |
| 1090 | } |
| 1091 | |
| 1092 | // UnmarshalCaddyfile implements caddyfile.Unmarshaler. |
| 1093 | func (m *MatchHeaderRE) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { |
| 1094 | if *m == nil { |
| 1095 | *m = make(map[string]*MatchRegexp) |
| 1096 | } |
| 1097 | // iterate to merge multiple matchers into one |
| 1098 | for d.Next() { |
| 1099 | var first, second, third string |
| 1100 | if !d.Args(&first, &second) { |
| 1101 | return d.ArgErr() |
| 1102 | } |
| 1103 | |
| 1104 | var name, field, val string |
| 1105 | if d.Args(&third) { |
| 1106 | name = first |
| 1107 | field = second |
| 1108 | val = third |
| 1109 | } else { |
| 1110 | field = first |
| 1111 | val = second |
| 1112 | } |
| 1113 | |
| 1114 | // Default to the named matcher's name, if no regexp name is provided |
| 1115 | if name == "" { |
| 1116 | name = d.GetContextString(caddyfile.MatcherNameCtxKey) |
| 1117 | } |
| 1118 | |
| 1119 | // If there's already a pattern for this field |
| 1120 | // then we would end up overwriting the old one |
| 1121 | if (*m)[field] != nil { |
| 1122 | return d.Errf("header_regexp matcher can only be used once per named matcher, per header field: %s", field) |
| 1123 | } |
| 1124 | |
| 1125 | (*m)[field] = &MatchRegexp{Pattern: val, Name: name} |
| 1126 | |
| 1127 | if d.NextBlock(0) { |
| 1128 | return d.Err("malformed header_regexp matcher: blocks are not supported") |
| 1129 | } |
| 1130 | } |
| 1131 | return nil |
| 1132 | } |
| 1133 | |
| 1134 | // Match returns true if r matches m. |
| 1135 | func (m MatchHeaderRE) Match(r *http.Request) bool { |
| 1136 | match, _ := m.MatchWithError(r) |
| 1137 | return match |
| 1138 | } |
| 1139 | |
| 1140 | // MatchWithError returns true if r matches m. |
| 1141 | func (m MatchHeaderRE) MatchWithError(r *http.Request) (bool, error) { |
| 1142 | for field, rm := range m { |
| 1143 | actualFieldVals := getHeaderFieldVals(r.Header, field, r.Host, r.TransferEncoding) |
| 1144 | match := false |
| 1145 | fieldVal: |
| 1146 | for _, actualFieldVal := range actualFieldVals { |
| 1147 | repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) |
| 1148 | if rm.Match(actualFieldVal, repl) { |
| 1149 | match = true |
| 1150 | break fieldVal |
| 1151 | } |
| 1152 | } |
| 1153 | if !match { |
| 1154 | return false, nil |
| 1155 | } |
| 1156 | } |
| 1157 | return true, nil |
| 1158 | } |
| 1159 | |
| 1160 | // Provision compiles m's regular expressions. |
| 1161 | func (m MatchHeaderRE) Provision(ctx caddy.Context) error { |
| 1162 | for _, rm := range m { |
| 1163 | err := rm.Provision(ctx) |
| 1164 | if err != nil { |
| 1165 | return err |
| 1166 | } |
| 1167 | } |
| 1168 | return nil |
| 1169 | } |
| 1170 | |
| 1171 | // Validate validates m's regular expressions. |
| 1172 | func (m MatchHeaderRE) Validate() error { |
| 1173 | for _, rm := range m { |
| 1174 | err := rm.Validate() |
| 1175 | if err != nil { |
| 1176 | return err |
| 1177 | } |
| 1178 | } |
| 1179 | return nil |
| 1180 | } |
| 1181 | |
| 1182 | // CELLibrary produces options that expose this matcher for use in CEL |
| 1183 | // expression matchers. |
| 1184 | // |
| 1185 | // Example: |
| 1186 | // |
| 1187 | // expression header_regexp('foo', 'Field', 'fo+') |
| 1188 | func (MatchHeaderRE) CELLibrary(ctx caddy.Context) (cel.Library, error) { |
| 1189 | unnamedPattern, err := CELMatcherImpl( |
| 1190 | "header_regexp", |
| 1191 | "header_regexp_request_string_string", |
| 1192 | []*cel.Type{cel.StringType, cel.StringType}, |
| 1193 | func(data ref.Val) (RequestMatcherWithError, error) { |
| 1194 | refStringList := stringSliceType |
| 1195 | params, err := data.ConvertToNative(refStringList) |
| 1196 | if err != nil { |
| 1197 | return nil, err |
| 1198 | } |
| 1199 | strParams := params.([]string) |
| 1200 | matcher := MatchHeaderRE{} |
| 1201 | matcher[strParams[0]] = &MatchRegexp{ |
| 1202 | Pattern: strParams[1], |
| 1203 | Name: ctx.Value(MatcherNameCtxKey).(string), |
| 1204 | } |
| 1205 | err = matcher.Provision(ctx) |
| 1206 | return matcher, err |
| 1207 | }, |
| 1208 | ) |
| 1209 | if err != nil { |
| 1210 | return nil, err |
| 1211 | } |
| 1212 | namedPattern, err := CELMatcherImpl( |
| 1213 | "header_regexp", |
| 1214 | "header_regexp_request_string_string_string", |
| 1215 | []*cel.Type{cel.StringType, cel.StringType, cel.StringType}, |
| 1216 | func(data ref.Val) (RequestMatcherWithError, error) { |
| 1217 | refStringList := stringSliceType |
| 1218 | params, err := data.ConvertToNative(refStringList) |
| 1219 | if err != nil { |
| 1220 | return nil, err |
| 1221 | } |
| 1222 | strParams := params.([]string) |
| 1223 | name := strParams[0] |
| 1224 | if name == "" { |
| 1225 | name = ctx.Value(MatcherNameCtxKey).(string) |
| 1226 | } |
| 1227 | matcher := MatchHeaderRE{} |
| 1228 | matcher[strParams[1]] = &MatchRegexp{ |
| 1229 | Pattern: strParams[2], |
| 1230 | Name: name, |
| 1231 | } |
| 1232 | err = matcher.Provision(ctx) |
| 1233 | return matcher, err |
| 1234 | }, |
| 1235 | ) |
| 1236 | if err != nil { |
| 1237 | return nil, err |
| 1238 | } |
| 1239 | envOpts := append(unnamedPattern.CompileOptions(), namedPattern.CompileOptions()...) |
| 1240 | prgOpts := append(unnamedPattern.ProgramOptions(), namedPattern.ProgramOptions()...) |
| 1241 | return NewMatcherCELLibrary(envOpts, prgOpts), nil |
| 1242 | } |
| 1243 | |
| 1244 | // CaddyModule returns the Caddy module information. |
| 1245 | func (MatchProtocol) CaddyModule() caddy.ModuleInfo { |
| 1246 | return caddy.ModuleInfo{ |
| 1247 | ID: "http.matchers.protocol", |
| 1248 | New: func() caddy.Module { return new(MatchProtocol) }, |
| 1249 | } |
| 1250 | } |
| 1251 | |
| 1252 | // Match returns true if r matches m. |
| 1253 | func (m MatchProtocol) Match(r *http.Request) bool { |
| 1254 | match, _ := m.MatchWithError(r) |
| 1255 | return match |
| 1256 | } |
| 1257 | |
| 1258 | // MatchWithError returns true if r matches m. |
| 1259 | func (m MatchProtocol) MatchWithError(r *http.Request) (bool, error) { |
| 1260 | switch string(m) { |
| 1261 | case "grpc": |
| 1262 | return strings.HasPrefix(r.Header.Get("content-type"), "application/grpc"), nil |
| 1263 | case "https": |
| 1264 | return r.TLS != nil, nil |
| 1265 | case "http": |
| 1266 | return r.TLS == nil, nil |
| 1267 | case "http/1.0": |
| 1268 | return r.ProtoMajor == 1 && r.ProtoMinor == 0, nil |
| 1269 | case "http/1.0+": |
| 1270 | return r.ProtoAtLeast(1, 0), nil |
| 1271 | case "http/1.1": |
| 1272 | return r.ProtoMajor == 1 && r.ProtoMinor == 1, nil |
| 1273 | case "http/1.1+": |
| 1274 | return r.ProtoAtLeast(1, 1), nil |
| 1275 | case "http/2": |
| 1276 | return r.ProtoMajor == 2, nil |
| 1277 | case "http/2+": |
| 1278 | return r.ProtoAtLeast(2, 0), nil |
| 1279 | case "http/3": |
| 1280 | return r.ProtoMajor == 3, nil |
| 1281 | case "http/3+": |
| 1282 | return r.ProtoAtLeast(3, 0), nil |
| 1283 | } |
| 1284 | return false, nil |
| 1285 | } |
| 1286 | |
| 1287 | // UnmarshalCaddyfile implements caddyfile.Unmarshaler. |
| 1288 | func (m *MatchProtocol) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { |
| 1289 | // iterate to merge multiple matchers into one |
| 1290 | for d.Next() { |
| 1291 | var proto string |
| 1292 | if !d.Args(&proto) { |
| 1293 | return d.Err("expected exactly one protocol") |
| 1294 | } |
| 1295 | *m = MatchProtocol(proto) |
| 1296 | } |
| 1297 | return nil |
| 1298 | } |
| 1299 | |
| 1300 | // CELLibrary produces options that expose this matcher for use in CEL |
| 1301 | // expression matchers. |
| 1302 | // |
| 1303 | // Example: |
| 1304 | // |
| 1305 | // expression protocol('https') |
| 1306 | func (MatchProtocol) CELLibrary(_ caddy.Context) (cel.Library, error) { |
| 1307 | return CELMatcherImpl( |
| 1308 | "protocol", |
| 1309 | "protocol_request_string", |
| 1310 | []*cel.Type{cel.StringType}, |
| 1311 | func(data ref.Val) (RequestMatcherWithError, error) { |
| 1312 | protocolStr, ok := data.(types.String) |
| 1313 | if !ok { |
| 1314 | return nil, errors.New("protocol argument was not a string") |
| 1315 | } |
| 1316 | return MatchProtocol(strings.ToLower(string(protocolStr))), nil |
| 1317 | }, |
| 1318 | ) |
| 1319 | } |
| 1320 | |
| 1321 | // CaddyModule returns the Caddy module information. |
| 1322 | func (MatchTLS) CaddyModule() caddy.ModuleInfo { |
| 1323 | return caddy.ModuleInfo{ |
| 1324 | ID: "http.matchers.tls", |
| 1325 | New: func() caddy.Module { return new(MatchTLS) }, |
| 1326 | } |
| 1327 | } |
| 1328 | |
| 1329 | // Match returns true if r matches m. |
| 1330 | func (m MatchTLS) Match(r *http.Request) bool { |
| 1331 | match, _ := m.MatchWithError(r) |
| 1332 | return match |
| 1333 | } |
| 1334 | |
| 1335 | // MatchWithError returns true if r matches m. |
| 1336 | func (m MatchTLS) MatchWithError(r *http.Request) (bool, error) { |
| 1337 | if r.TLS == nil { |
| 1338 | return false, nil |
| 1339 | } |
| 1340 | if m.HandshakeComplete != nil { |
| 1341 | if (!*m.HandshakeComplete && r.TLS.HandshakeComplete) || |
| 1342 | (*m.HandshakeComplete && !r.TLS.HandshakeComplete) { |
| 1343 | return false, nil |
| 1344 | } |
| 1345 | } |
| 1346 | return true, nil |
| 1347 | } |
| 1348 | |
| 1349 | // UnmarshalCaddyfile parses Caddyfile tokens for this matcher. Syntax: |
| 1350 | // |
| 1351 | // ... tls [early_data] |
| 1352 | // |
| 1353 | // EXPERIMENTAL SYNTAX: Subject to change. |
| 1354 | func (m *MatchTLS) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { |
| 1355 | // iterate to merge multiple matchers into one |
| 1356 | for d.Next() { |
| 1357 | if d.NextArg() { |
| 1358 | switch d.Val() { |
| 1359 | case "early_data": |
| 1360 | var false bool |
| 1361 | m.HandshakeComplete = &false |
| 1362 | default: |
| 1363 | return d.Errf("unrecognized option '%s'", d.Val()) |
| 1364 | } |
| 1365 | } |
| 1366 | if d.NextArg() { |
| 1367 | return d.ArgErr() |
| 1368 | } |
| 1369 | if d.NextBlock(0) { |
| 1370 | return d.Err("malformed tls matcher: blocks are not supported yet") |
| 1371 | } |
| 1372 | } |
| 1373 | return nil |
| 1374 | } |
| 1375 | |
| 1376 | // CaddyModule returns the Caddy module information. |
| 1377 | func (MatchNot) CaddyModule() caddy.ModuleInfo { |
| 1378 | return caddy.ModuleInfo{ |
| 1379 | ID: "http.matchers.not", |
| 1380 | New: func() caddy.Module { return new(MatchNot) }, |
| 1381 | } |
| 1382 | } |
| 1383 | |
| 1384 | // UnmarshalCaddyfile implements caddyfile.Unmarshaler. |
| 1385 | func (m *MatchNot) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { |
| 1386 | // iterate to merge multiple matchers into one |
| 1387 | for d.Next() { |
| 1388 | matcherSet, err := ParseCaddyfileNestedMatcherSet(d) |
| 1389 | if err != nil { |
| 1390 | return err |
| 1391 | } |
| 1392 | m.MatcherSetsRaw = append(m.MatcherSetsRaw, matcherSet) |
| 1393 | } |
| 1394 | return nil |
| 1395 | } |
| 1396 | |
| 1397 | // UnmarshalJSON satisfies json.Unmarshaler. It puts the JSON |
| 1398 | // bytes directly into m's MatcherSetsRaw field. |
| 1399 | func (m *MatchNot) UnmarshalJSON(data []byte) error { |
| 1400 | return json.Unmarshal(data, &m.MatcherSetsRaw) |
| 1401 | } |
| 1402 | |
| 1403 | // MarshalJSON satisfies json.Marshaler by marshaling |
| 1404 | // m's raw matcher sets. |
| 1405 | func (m MatchNot) MarshalJSON() ([]byte, error) { |
| 1406 | return json.Marshal(m.MatcherSetsRaw) |
| 1407 | } |
| 1408 | |
| 1409 | // Provision loads the matcher modules to be negated. |
| 1410 | func (m *MatchNot) Provision(ctx caddy.Context) error { |
| 1411 | matcherSets, err := ctx.LoadModule(m, "MatcherSetsRaw") |
| 1412 | if err != nil { |
| 1413 | return fmt.Errorf("loading matcher sets: %v", err) |
| 1414 | } |
| 1415 | for _, modMap := range matcherSets.([]map[string]any) { |
| 1416 | var ms MatcherSet |
| 1417 | for _, modIface := range modMap { |
| 1418 | if mod, ok := modIface.(RequestMatcherWithError); ok { |
| 1419 | ms = append(ms, mod) |
| 1420 | continue |
| 1421 | } |
| 1422 | if mod, ok := modIface.(RequestMatcher); ok { |
| 1423 | ms = append(ms, mod) |
| 1424 | continue |
| 1425 | } |
| 1426 | return fmt.Errorf("module is not a request matcher: %T", modIface) |
| 1427 | } |
| 1428 | m.MatcherSets = append(m.MatcherSets, ms) |
| 1429 | } |
| 1430 | return nil |
| 1431 | } |
| 1432 | |
| 1433 | // Match returns true if r matches m. Since this matcher negates |
| 1434 | // the embedded matchers, false is returned if any of its matcher |
| 1435 | // sets return true. |
| 1436 | func (m MatchNot) Match(r *http.Request) bool { |
| 1437 | match, _ := m.MatchWithError(r) |
| 1438 | return match |
| 1439 | } |
| 1440 | |
| 1441 | // MatchWithError returns true if r matches m. Since this matcher |
| 1442 | // negates the embedded matchers, false is returned if any of its |
| 1443 | // matcher sets return true. |
| 1444 | func (m MatchNot) MatchWithError(r *http.Request) (bool, error) { |
| 1445 | for _, ms := range m.MatcherSets { |
| 1446 | matches, err := ms.MatchWithError(r) |
| 1447 | if err != nil { |
| 1448 | return false, err |
| 1449 | } |
| 1450 | if matches { |
| 1451 | return false, nil |
| 1452 | } |
| 1453 | } |
| 1454 | return true, nil |
| 1455 | } |
| 1456 | |
| 1457 | // MatchRegexp is an embedable type for matching |
| 1458 | // using regular expressions. It adds placeholders |
| 1459 | // to the request's replacer. |
| 1460 | type MatchRegexp struct { |
| 1461 | // A unique name for this regular expression. Optional, |
| 1462 | // but useful to prevent overwriting captures from other |
| 1463 | // regexp matchers. |
| 1464 | Name string `json:"name,omitempty"` |
| 1465 | |
| 1466 | // The regular expression to evaluate, in RE2 syntax, |
| 1467 | // which is the same general syntax used by Go, Perl, |
| 1468 | // and Python. For details, see |
| 1469 | // [Go's regexp package](https://golang.org/pkg/regexp/). |
| 1470 | // Captures are accessible via placeholders. Unnamed |
| 1471 | // capture groups are exposed as their numeric, 1-based |
| 1472 | // index, while named capture groups are available by |
| 1473 | // the capture group name. |
| 1474 | Pattern string `json:"pattern"` |
| 1475 | |
| 1476 | compiled *regexp.Regexp |
| 1477 | } |
| 1478 | |
| 1479 | // Provision compiles the regular expression. |
| 1480 | func (mre *MatchRegexp) Provision(caddy.Context) error { |
| 1481 | re, err := regexp.Compile(mre.Pattern) |
| 1482 | if err != nil { |
| 1483 | return fmt.Errorf("compiling matcher regexp %s: %v", mre.Pattern, err) |
| 1484 | } |
| 1485 | mre.compiled = re |
| 1486 | return nil |
| 1487 | } |
| 1488 | |
| 1489 | // Validate ensures mre is set up correctly. |
| 1490 | func (mre *MatchRegexp) Validate() error { |
| 1491 | if mre.Name != "" && !wordRE.MatchString(mre.Name) { |
| 1492 | return fmt.Errorf("invalid regexp name (must contain only word characters): %s", mre.Name) |
| 1493 | } |
| 1494 | return nil |
| 1495 | } |
| 1496 | |
| 1497 | // Match returns true if input matches the compiled regular |
| 1498 | // expression in mre. It sets values on the replacer repl |
| 1499 | // associated with capture groups, using the given scope |
| 1500 | // (namespace). |
| 1501 | func (mre *MatchRegexp) Match(input string, repl *caddy.Replacer) bool { |
| 1502 | matches := mre.compiled.FindStringSubmatch(input) |
| 1503 | if matches == nil { |
| 1504 | return false |
| 1505 | } |
| 1506 | |
| 1507 | // save all capture groups, first by index |
| 1508 | for i, match := range matches { |
| 1509 | keySuffix := "." + strconv.Itoa(i) |
| 1510 | if mre.Name != "" { |
| 1511 | repl.Set(regexpPlaceholderPrefix+"."+mre.Name+keySuffix, match) |
| 1512 | } |
| 1513 | repl.Set(regexpPlaceholderPrefix+keySuffix, match) |
| 1514 | } |
| 1515 | |
| 1516 | // then by name |
| 1517 | for i, name := range mre.compiled.SubexpNames() { |
| 1518 | // skip the first element (the full match), and empty names |
| 1519 | if i == 0 || name == "" { |
| 1520 | continue |
| 1521 | } |
| 1522 | |
| 1523 | keySuffix := "." + name |
| 1524 | if mre.Name != "" { |
| 1525 | repl.Set(regexpPlaceholderPrefix+"."+mre.Name+keySuffix, matches[i]) |
| 1526 | } |
| 1527 | repl.Set(regexpPlaceholderPrefix+keySuffix, matches[i]) |
| 1528 | } |
| 1529 | |
| 1530 | return true |
| 1531 | } |
| 1532 | |
| 1533 | // UnmarshalCaddyfile implements caddyfile.Unmarshaler. |
| 1534 | func (mre *MatchRegexp) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { |
| 1535 | // iterate to merge multiple matchers into one |
| 1536 | for d.Next() { |
| 1537 | // If this is the second iteration of the loop |
| 1538 | // then there's more than one path_regexp matcher |
| 1539 | // and we would end up overwriting the old one |
| 1540 | if mre.Pattern != "" { |
| 1541 | return d.Err("regular expression can only be used once per named matcher") |
| 1542 | } |
| 1543 | |
| 1544 | args := d.RemainingArgs() |
| 1545 | switch len(args) { |
| 1546 | case 1: |
| 1547 | mre.Pattern = args[0] |
| 1548 | case 2: |
| 1549 | mre.Name = args[0] |
| 1550 | mre.Pattern = args[1] |
| 1551 | default: |
| 1552 | return d.ArgErr() |
| 1553 | } |
| 1554 | |
| 1555 | // Default to the named matcher's name, if no regexp name is provided |
| 1556 | if mre.Name == "" { |
| 1557 | mre.Name = d.GetContextString(caddyfile.MatcherNameCtxKey) |
| 1558 | } |
| 1559 | |
| 1560 | if d.NextBlock(0) { |
| 1561 | return d.Err("malformed path_regexp matcher: blocks are not supported") |
| 1562 | } |
| 1563 | } |
| 1564 | return nil |
| 1565 | } |
| 1566 | |
| 1567 | // ParseCaddyfileNestedMatcherSet parses the Caddyfile tokens for a nested |
| 1568 | // matcher set, and returns its raw module map value. |
| 1569 | func ParseCaddyfileNestedMatcherSet(d *caddyfile.Dispenser) (caddy.ModuleMap, error) { |
| 1570 | matcherMap := make(map[string]any) |
| 1571 | |
| 1572 | // in case there are multiple instances of the same matcher, concatenate |
| 1573 | // their tokens (we expect that UnmarshalCaddyfile should be able to |
| 1574 | // handle more than one segment); otherwise, we'd overwrite other |
| 1575 | // instances of the matcher in this set |
| 1576 | tokensByMatcherName := make(map[string][]caddyfile.Token) |
| 1577 | for nesting := d.Nesting(); d.NextArg() || d.NextBlock(nesting); { |
| 1578 | // if the token is quoted (backtick), treat it as a shorthand |
| 1579 | // for an expression matcher, same as @named matcher parsing |
| 1580 | if d.Token().Quoted() { |
| 1581 | expressionToken := d.Token().Clone() |
| 1582 | expressionToken.Text = "expression" |
| 1583 | tokensByMatcherName["expression"] = append(tokensByMatcherName["expression"], expressionToken, d.Token()) |
| 1584 | continue |
| 1585 | } |
| 1586 | matcherName := d.Val() |
| 1587 | tokensByMatcherName[matcherName] = append(tokensByMatcherName[matcherName], d.NextSegment()...) |
| 1588 | } |
| 1589 | |
| 1590 | for matcherName, tokens := range tokensByMatcherName { |
| 1591 | mod, err := caddy.GetModule("http.matchers." + matcherName) |
| 1592 | if err != nil { |
| 1593 | return nil, d.Errf("getting matcher module '%s': %v", matcherName, err) |
| 1594 | } |
| 1595 | unm, ok := mod.New().(caddyfile.Unmarshaler) |
| 1596 | if !ok { |
| 1597 | return nil, d.Errf("matcher module '%s' is not a Caddyfile unmarshaler", matcherName) |
| 1598 | } |
| 1599 | err = unm.UnmarshalCaddyfile(caddyfile.NewDispenser(tokens)) |
| 1600 | if err != nil { |
| 1601 | return nil, err |
| 1602 | } |
| 1603 | if rm, ok := unm.(RequestMatcherWithError); ok { |
| 1604 | matcherMap[matcherName] = rm |
| 1605 | continue |
| 1606 | } |
| 1607 | if rm, ok := unm.(RequestMatcher); ok { |
| 1608 | matcherMap[matcherName] = rm |
| 1609 | continue |
| 1610 | } |
| 1611 | return nil, fmt.Errorf("matcher module '%s' is not a request matcher", matcherName) |
| 1612 | } |
| 1613 | |
| 1614 | // we should now have a functional matcher, but we also |
| 1615 | // need to be able to marshal as JSON, otherwise config |
| 1616 | // adaptation will be missing the matchers! |
| 1617 | matcherSet := make(caddy.ModuleMap) |
| 1618 | for name, matcher := range matcherMap { |
| 1619 | jsonBytes, err := json.Marshal(matcher) |
| 1620 | if err != nil { |
| 1621 | return nil, fmt.Errorf("marshaling %T matcher: %v", matcher, err) |
| 1622 | } |
| 1623 | matcherSet[name] = jsonBytes |
| 1624 | } |
| 1625 | |
| 1626 | return matcherSet, nil |
| 1627 | } |
| 1628 | |
| 1629 | var wordRE = regexp.MustCompile(`\w+`) |
| 1630 | |
| 1631 | const regexpPlaceholderPrefix = "http.regexp" |
| 1632 | |
| 1633 | // MatcherErrorVarKey is the key used for the variable that |
| 1634 | // holds an optional error emitted from a request matcher, |
| 1635 | // to short-circuit the handler chain, since matchers cannot |
| 1636 | // return errors via the RequestMatcher interface. |
| 1637 | // |
| 1638 | // Deprecated: Matchers should implement RequestMatcherWithError |
| 1639 | // which can return an error directly, instead of smuggling it |
| 1640 | // through the vars map. |
| 1641 | const MatcherErrorVarKey = "matchers.error" |
| 1642 | |
| 1643 | // Interface guards |
| 1644 | var ( |
| 1645 | _ RequestMatcherWithError = (*MatchHost)(nil) |
| 1646 | _ caddy.Provisioner = (*MatchHost)(nil) |
| 1647 | _ RequestMatcherWithError = (*MatchPath)(nil) |
| 1648 | _ RequestMatcherWithError = (*MatchPathRE)(nil) |
| 1649 | _ caddy.Provisioner = (*MatchPathRE)(nil) |
| 1650 | _ RequestMatcherWithError = (*MatchMethod)(nil) |
| 1651 | _ RequestMatcherWithError = (*MatchQuery)(nil) |
| 1652 | _ RequestMatcherWithError = (*MatchHeader)(nil) |
| 1653 | _ RequestMatcherWithError = (*MatchHeaderRE)(nil) |
| 1654 | _ caddy.Provisioner = (*MatchHeaderRE)(nil) |
| 1655 | _ RequestMatcherWithError = (*MatchProtocol)(nil) |
| 1656 | _ RequestMatcherWithError = (*MatchNot)(nil) |
| 1657 | _ caddy.Provisioner = (*MatchNot)(nil) |
| 1658 | _ caddy.Provisioner = (*MatchRegexp)(nil) |
| 1659 | |
| 1660 | _ caddyfile.Unmarshaler = (*MatchHost)(nil) |
| 1661 | _ caddyfile.Unmarshaler = (*MatchPath)(nil) |
| 1662 | _ caddyfile.Unmarshaler = (*MatchPathRE)(nil) |
| 1663 | _ caddyfile.Unmarshaler = (*MatchMethod)(nil) |
| 1664 | _ caddyfile.Unmarshaler = (*MatchQuery)(nil) |
| 1665 | _ caddyfile.Unmarshaler = (*MatchHeader)(nil) |
| 1666 | _ caddyfile.Unmarshaler = (*MatchHeaderRE)(nil) |
| 1667 | _ caddyfile.Unmarshaler = (*MatchProtocol)(nil) |
| 1668 | _ caddyfile.Unmarshaler = (*VarsMatcher)(nil) |
| 1669 | _ caddyfile.Unmarshaler = (*MatchVarsRE)(nil) |
| 1670 | |
| 1671 | _ CELLibraryProducer = (*MatchHost)(nil) |
| 1672 | _ CELLibraryProducer = (*MatchPath)(nil) |
| 1673 | _ CELLibraryProducer = (*MatchPathRE)(nil) |
| 1674 | _ CELLibraryProducer = (*MatchMethod)(nil) |
| 1675 | _ CELLibraryProducer = (*MatchQuery)(nil) |
| 1676 | _ CELLibraryProducer = (*MatchHeader)(nil) |
| 1677 | _ CELLibraryProducer = (*MatchHeaderRE)(nil) |
| 1678 | _ CELLibraryProducer = (*MatchProtocol)(nil) |
| 1679 | _ CELLibraryProducer = (*VarsMatcher)(nil) |
| 1680 | _ CELLibraryProducer = (*MatchVarsRE)(nil) |
| 1681 | |
| 1682 | _ json.Marshaler = (*MatchNot)(nil) |
| 1683 | _ json.Unmarshaler = (*MatchNot)(nil) |
| 1684 | ) |