| 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 fileserver |
| 16 | |
| 17 | import ( |
| 18 | "fmt" |
| 19 | "io/fs" |
| 20 | "net/http" |
| 21 | "os" |
| 22 | "path" |
| 23 | "path/filepath" |
| 24 | "runtime" |
| 25 | "strconv" |
| 26 | "strings" |
| 27 | |
| 28 | "github.com/google/cel-go/cel" |
| 29 | "github.com/google/cel-go/common" |
| 30 | "github.com/google/cel-go/common/ast" |
| 31 | "github.com/google/cel-go/common/operators" |
| 32 | "github.com/google/cel-go/common/types" |
| 33 | "github.com/google/cel-go/common/types/ref" |
| 34 | "github.com/google/cel-go/parser" |
| 35 | "go.uber.org/zap" |
| 36 | "go.uber.org/zap/zapcore" |
| 37 | |
| 38 | "github.com/caddyserver/caddy/v2" |
| 39 | "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" |
| 40 | "github.com/caddyserver/caddy/v2/modules/caddyhttp" |
| 41 | ) |
| 42 | |
| 43 | func init() { |
| 44 | caddy.RegisterModule(MatchFile{}) |
| 45 | } |
| 46 | |
| 47 | // MatchFile is an HTTP request matcher that can match |
| 48 | // requests based upon file existence. |
| 49 | // |
| 50 | // Upon matching, three new placeholders will be made |
| 51 | // available: |
| 52 | // |
| 53 | // - `{http.matchers.file.relative}` The root-relative |
| 54 | // path of the file. This is often useful when rewriting |
| 55 | // requests. |
| 56 | // - `{http.matchers.file.absolute}` The absolute path |
| 57 | // of the matched file. |
| 58 | // - `{http.matchers.file.type}` Set to "directory" if |
| 59 | // the matched file is a directory, "file" otherwise. |
| 60 | // - `{http.matchers.file.remainder}` Set to the remainder |
| 61 | // of the path if the path was split by `split_path`. |
| 62 | // |
| 63 | // Even though file matching may depend on the OS path |
| 64 | // separator, the placeholder values always use /. |
| 65 | type MatchFile struct { |
| 66 | // The file system implementation to use. By default, the |
| 67 | // local disk file system will be used. |
| 68 | FileSystem string `json:"fs,omitempty"` |
| 69 | |
| 70 | // The root directory, used for creating absolute |
| 71 | // file paths, and required when working with |
| 72 | // relative paths; if not specified, `{http.vars.root}` |
| 73 | // will be used, if set; otherwise, the current |
| 74 | // directory is assumed. Accepts placeholders. |
| 75 | Root string `json:"root,omitempty"` |
| 76 | |
| 77 | // The list of files to try. Each path here is |
| 78 | // considered related to Root. If nil, the request |
| 79 | // URL's path will be assumed. Files and |
| 80 | // directories are treated distinctly, so to match |
| 81 | // a directory, the filepath MUST end in a forward |
| 82 | // slash `/`. To match a regular file, there must |
| 83 | // be no trailing slash. Accepts placeholders. If |
| 84 | // the policy is "first_exist", then an error may |
| 85 | // be triggered as a fallback by configuring "=" |
| 86 | // followed by a status code number, |
| 87 | // for example "=404". |
| 88 | TryFiles []string `json:"try_files,omitempty"` |
| 89 | |
| 90 | // How to choose a file in TryFiles. Can be: |
| 91 | // |
| 92 | // - first_exist |
| 93 | // - first_exist_fallback |
| 94 | // - smallest_size |
| 95 | // - largest_size |
| 96 | // - most_recently_modified |
| 97 | // |
| 98 | // Default is first_exist. |
| 99 | TryPolicy string `json:"try_policy,omitempty"` |
| 100 | |
| 101 | // A list of delimiters to use to split the path in two |
| 102 | // when trying files. If empty, no splitting will |
| 103 | // occur, and the path will be tried as-is. For each |
| 104 | // split value, the left-hand side of the split, |
| 105 | // including the split value, will be the path tried. |
| 106 | // For example, the path `/remote.php/dav/` using the |
| 107 | // split value `.php` would try the file `/remote.php`. |
| 108 | // Each delimiter must appear at the end of a URI path |
| 109 | // component in order to be used as a split delimiter. |
| 110 | SplitPath []string `json:"split_path,omitempty"` |
| 111 | |
| 112 | fsmap caddy.FileSystems |
| 113 | |
| 114 | logger *zap.Logger |
| 115 | } |
| 116 | |
| 117 | // CaddyModule returns the Caddy module information. |
| 118 | func (MatchFile) CaddyModule() caddy.ModuleInfo { |
| 119 | return caddy.ModuleInfo{ |
| 120 | ID: "http.matchers.file", |
| 121 | New: func() caddy.Module { return new(MatchFile) }, |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | // UnmarshalCaddyfile sets up the matcher from Caddyfile tokens. Syntax: |
| 126 | // |
| 127 | // file <files...> { |
| 128 | // root <path> |
| 129 | // try_files <files...> |
| 130 | // try_policy first_exist|smallest_size|largest_size|most_recently_modified |
| 131 | // } |
| 132 | func (m *MatchFile) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { |
| 133 | // iterate to merge multiple matchers into one |
| 134 | for d.Next() { |
| 135 | m.TryFiles = append(m.TryFiles, d.RemainingArgs()...) |
| 136 | for d.NextBlock(0) { |
| 137 | switch d.Val() { |
| 138 | case "root": |
| 139 | if !d.NextArg() { |
| 140 | return d.ArgErr() |
| 141 | } |
| 142 | m.Root = d.Val() |
| 143 | case "try_files": |
| 144 | m.TryFiles = append(m.TryFiles, d.RemainingArgs()...) |
| 145 | if len(m.TryFiles) == 0 { |
| 146 | return d.ArgErr() |
| 147 | } |
| 148 | case "try_policy": |
| 149 | if !d.NextArg() { |
| 150 | return d.ArgErr() |
| 151 | } |
| 152 | m.TryPolicy = d.Val() |
| 153 | case "split_path": |
| 154 | m.SplitPath = d.RemainingArgs() |
| 155 | if len(m.SplitPath) == 0 { |
| 156 | return d.ArgErr() |
| 157 | } |
| 158 | default: |
| 159 | return d.Errf("unrecognized subdirective: %s", d.Val()) |
| 160 | } |
| 161 | } |
| 162 | } |
| 163 | return nil |
| 164 | } |
| 165 | |
| 166 | // CELLibrary produces options that expose this matcher for use in CEL |
| 167 | // expression matchers. |
| 168 | // |
| 169 | // Example: |
| 170 | // |
| 171 | // expression file() |
| 172 | // expression file({http.request.uri.path}, '/index.php') |
| 173 | // expression file({'root': '/srv', 'try_files': [{http.request.uri.path}, '/index.php'], 'try_policy': 'first_exist', 'split_path': ['.php']}) |
| 174 | func (MatchFile) CELLibrary(ctx caddy.Context) (cel.Library, error) { |
| 175 | requestType := cel.ObjectType("http.Request") |
| 176 | |
| 177 | matcherFactory := func(data ref.Val) (caddyhttp.RequestMatcherWithError, error) { |
| 178 | values, err := caddyhttp.CELValueToMapStrList(data) |
| 179 | if err != nil { |
| 180 | return nil, err |
| 181 | } |
| 182 | |
| 183 | var root string |
| 184 | if len(values["root"]) > 0 { |
| 185 | root = values["root"][0] |
| 186 | } |
| 187 | |
| 188 | var fsName string |
| 189 | if len(values["fs"]) > 0 { |
| 190 | fsName = values["fs"][0] |
| 191 | } |
| 192 | |
| 193 | var try_policy string |
| 194 | if len(values["try_policy"]) > 0 { |
| 195 | try_policy = values["try_policy"][0] |
| 196 | } |
| 197 | |
| 198 | m := MatchFile{ |
| 199 | Root: root, |
| 200 | TryFiles: values["try_files"], |
| 201 | TryPolicy: try_policy, |
| 202 | SplitPath: values["split_path"], |
| 203 | FileSystem: fsName, |
| 204 | } |
| 205 | |
| 206 | err = m.Provision(ctx) |
| 207 | return m, err |
| 208 | } |
| 209 | |
| 210 | envOptions := []cel.EnvOption{ |
| 211 | cel.Macros(parser.NewGlobalVarArgMacro("file", celFileMatcherMacroExpander())), |
| 212 | cel.Function("file", cel.Overload("file_request_map", []*cel.Type{requestType, caddyhttp.CELTypeJSON}, cel.BoolType)), |
| 213 | cel.Function("file_request_map", |
| 214 | cel.Overload("file_request_map", []*cel.Type{requestType, caddyhttp.CELTypeJSON}, cel.BoolType), |
| 215 | cel.SingletonBinaryBinding(caddyhttp.CELMatcherRuntimeFunction("file_request_map", matcherFactory))), |
| 216 | } |
| 217 | |
| 218 | programOptions := []cel.ProgramOption{ |
| 219 | cel.CustomDecorator(caddyhttp.CELMatcherDecorator("file_request_map", matcherFactory)), |
| 220 | } |
| 221 | |
| 222 | return caddyhttp.NewMatcherCELLibrary(envOptions, programOptions), nil |
| 223 | } |
| 224 | |
| 225 | func celFileMatcherMacroExpander() parser.MacroExpander { |
| 226 | return func(eh parser.ExprHelper, target ast.Expr, args []ast.Expr) (ast.Expr, *common.Error) { |
| 227 | if len(args) == 0 { |
| 228 | return eh.NewCall("file", |
| 229 | eh.NewIdent(caddyhttp.CELRequestVarName), |
| 230 | eh.NewMap(), |
| 231 | ), nil |
| 232 | } |
| 233 | if len(args) == 1 { |
| 234 | arg := args[0] |
| 235 | if isCELStringLiteral(arg) || isCELCaddyPlaceholderCall(arg) { |
| 236 | return eh.NewCall("file", |
| 237 | eh.NewIdent(caddyhttp.CELRequestVarName), |
| 238 | eh.NewMap(eh.NewMapEntry( |
| 239 | eh.NewLiteral(types.String("try_files")), |
| 240 | eh.NewList(arg), |
| 241 | false, |
| 242 | )), |
| 243 | ), nil |
| 244 | } |
| 245 | if isCELTryFilesLiteral(arg) { |
| 246 | return eh.NewCall("file", eh.NewIdent(caddyhttp.CELRequestVarName), arg), nil |
| 247 | } |
| 248 | return nil, &common.Error{ |
| 249 | Location: eh.OffsetLocation(arg.ID()), |
| 250 | Message: "matcher requires either a map or string literal argument", |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | for _, arg := range args { |
| 255 | if !isCELStringLiteral(arg) && !isCELCaddyPlaceholderCall(arg) { |
| 256 | return nil, &common.Error{ |
| 257 | Location: eh.OffsetLocation(arg.ID()), |
| 258 | Message: "matcher only supports repeated string literal arguments", |
| 259 | } |
| 260 | } |
| 261 | } |
| 262 | return eh.NewCall("file", |
| 263 | eh.NewIdent(caddyhttp.CELRequestVarName), |
| 264 | eh.NewMap(eh.NewMapEntry( |
| 265 | eh.NewLiteral(types.String("try_files")), |
| 266 | eh.NewList(args...), |
| 267 | false, |
| 268 | )), |
| 269 | ), nil |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | // Provision sets up m's defaults. |
| 274 | func (m *MatchFile) Provision(ctx caddy.Context) error { |
| 275 | m.logger = ctx.Logger() |
| 276 | |
| 277 | m.fsmap = ctx.FileSystems() |
| 278 | |
| 279 | if m.Root == "" { |
| 280 | m.Root = "{http.vars.root}" |
| 281 | } |
| 282 | |
| 283 | if m.FileSystem == "" { |
| 284 | m.FileSystem = "{http.vars.fs}" |
| 285 | } |
| 286 | |
| 287 | // if list of files to try was omitted entirely, assume URL path |
| 288 | // (use placeholder instead of r.URL.Path; see issue #4146) |
| 289 | if m.TryFiles == nil { |
| 290 | m.TryFiles = []string{"{http.request.uri.path}"} |
| 291 | } |
| 292 | return nil |
| 293 | } |
| 294 | |
| 295 | // Validate ensures m has a valid configuration. |
| 296 | func (m MatchFile) Validate() error { |
| 297 | switch m.TryPolicy { |
| 298 | case "", |
| 299 | tryPolicyFirstExist, |
| 300 | tryPolicyFirstExistFallback, |
| 301 | tryPolicyLargestSize, |
| 302 | tryPolicySmallestSize, |
| 303 | tryPolicyMostRecentlyMod: |
| 304 | default: |
| 305 | return fmt.Errorf("unknown try policy %s", m.TryPolicy) |
| 306 | } |
| 307 | return nil |
| 308 | } |
| 309 | |
| 310 | // Match returns true if r matches m. Returns true |
| 311 | // if a file was matched. If so, four placeholders |
| 312 | // will be available: |
| 313 | // - http.matchers.file.relative: Path to file relative to site root |
| 314 | // - http.matchers.file.absolute: Path to file including site root |
| 315 | // - http.matchers.file.type: file or directory |
| 316 | // - http.matchers.file.remainder: Portion remaining after splitting file path (if configured) |
| 317 | func (m MatchFile) Match(r *http.Request) bool { |
| 318 | match, err := m.selectFile(r) |
| 319 | if err != nil { |
| 320 | // nolint:staticcheck |
| 321 | caddyhttp.SetVar(r.Context(), caddyhttp.MatcherErrorVarKey, err) |
| 322 | } |
| 323 | return match |
| 324 | } |
| 325 | |
| 326 | // MatchWithError returns true if r matches m. |
| 327 | func (m MatchFile) MatchWithError(r *http.Request) (bool, error) { |
| 328 | return m.selectFile(r) |
| 329 | } |
| 330 | |
| 331 | // selectFile chooses a file according to m.TryPolicy by appending |
| 332 | // the paths in m.TryFiles to m.Root, with placeholder replacements. |
| 333 | func (m MatchFile) selectFile(r *http.Request) (bool, error) { |
| 334 | repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) |
| 335 | |
| 336 | root := filepath.Clean(repl.ReplaceAll(m.Root, ".")) |
| 337 | |
| 338 | fsName := repl.ReplaceAll(m.FileSystem, "") |
| 339 | |
| 340 | fileSystem, ok := m.fsmap.Get(fsName) |
| 341 | if !ok { |
| 342 | if c := m.logger.Check(zapcore.ErrorLevel, "use of unregistered filesystem"); c != nil { |
| 343 | c.Write(zap.String("fs", fsName)) |
| 344 | } |
| 345 | return false, nil |
| 346 | } |
| 347 | type matchCandidate struct { |
| 348 | fullpath, relative, splitRemainder string |
| 349 | } |
| 350 | |
| 351 | // makeCandidates evaluates placeholders in file and expands any glob expressions |
| 352 | // to build a list of file candidates. Special glob characters are escaped in |
| 353 | // placeholder replacements so globs cannot be expanded from placeholders, and |
| 354 | // globs are not evaluated on Windows because of its path separator character: |
| 355 | // escaping is not supported so we can't safely glob on Windows, or we can't |
| 356 | // support placeholders on Windows (pick one). (Actually, evaluating untrusted |
| 357 | // globs is not the end of the world since the file server will still hide any |
| 358 | // hidden files, it just might lead to unexpected behavior.) |
| 359 | makeCandidates := func(file string) []matchCandidate { |
| 360 | // first, evaluate placeholders in the file pattern |
| 361 | expandedFile, err := repl.ReplaceFunc(file, func(variable string, val any) (any, error) { |
| 362 | if runtime.GOOS == "windows" { |
| 363 | return val, nil |
| 364 | } |
| 365 | switch v := val.(type) { |
| 366 | case string: |
| 367 | return globSafeRepl.Replace(v), nil |
| 368 | case fmt.Stringer: |
| 369 | return globSafeRepl.Replace(v.String()), nil |
| 370 | } |
| 371 | return val, nil |
| 372 | }) |
| 373 | if err != nil { |
| 374 | if c := m.logger.Check(zapcore.ErrorLevel, "evaluating placeholders"); c != nil { |
| 375 | c.Write(zap.Error(err)) |
| 376 | } |
| 377 | |
| 378 | expandedFile = file // "oh well," I guess? |
| 379 | } |
| 380 | |
| 381 | // clean the path and split, if configured -- we must split before |
| 382 | // globbing so that the file system doesn't include the remainder |
| 383 | // ("afterSplit") in the filename; be sure to restore trailing slash |
| 384 | beforeSplit, afterSplit := m.firstSplit(path.Clean(expandedFile)) |
| 385 | if strings.HasSuffix(file, "/") { |
| 386 | beforeSplit += "/" |
| 387 | } |
| 388 | |
| 389 | // create the full path to the file by prepending the site root |
| 390 | fullPattern := caddyhttp.SanitizedPathJoin(root, beforeSplit) |
| 391 | |
| 392 | // expand glob expressions, but not on Windows because Glob() doesn't |
| 393 | // support escaping on Windows due to path separator) |
| 394 | var globResults []string |
| 395 | if runtime.GOOS == "windows" { |
| 396 | globResults = []string{fullPattern} // precious Windows |
| 397 | } else { |
| 398 | globResults, err = fs.Glob(fileSystem, fullPattern) |
| 399 | if err != nil { |
| 400 | if c := m.logger.Check(zapcore.ErrorLevel, "expanding glob"); c != nil { |
| 401 | c.Write(zap.Error(err)) |
| 402 | } |
| 403 | } |
| 404 | } |
| 405 | |
| 406 | // for each glob result, combine all the forms of the path |
| 407 | candidates := make([]matchCandidate, 0, len(globResults)) |
| 408 | for _, result := range globResults { |
| 409 | candidates = append(candidates, matchCandidate{ |
| 410 | fullpath: result, |
| 411 | relative: strings.TrimPrefix(result, root), |
| 412 | splitRemainder: afterSplit, |
| 413 | }) |
| 414 | } |
| 415 | |
| 416 | return candidates |
| 417 | } |
| 418 | |
| 419 | // setPlaceholders creates the placeholders for the matched file |
| 420 | setPlaceholders := func(candidate matchCandidate, isDir bool) { |
| 421 | repl.Set("http.matchers.file.relative", filepath.ToSlash(candidate.relative)) |
| 422 | repl.Set("http.matchers.file.absolute", filepath.ToSlash(candidate.fullpath)) |
| 423 | repl.Set("http.matchers.file.remainder", filepath.ToSlash(candidate.splitRemainder)) |
| 424 | |
| 425 | fileType := "file" |
| 426 | if isDir { |
| 427 | fileType = "directory" |
| 428 | } |
| 429 | repl.Set("http.matchers.file.type", fileType) |
| 430 | } |
| 431 | |
| 432 | // match file according to the configured policy |
| 433 | switch m.TryPolicy { |
| 434 | case "", tryPolicyFirstExist, tryPolicyFirstExistFallback: |
| 435 | maxI := -1 |
| 436 | if m.TryPolicy == tryPolicyFirstExistFallback { |
| 437 | maxI = len(m.TryFiles) - 1 |
| 438 | } |
| 439 | |
| 440 | for i, pattern := range m.TryFiles { |
| 441 | // If the pattern is a status code, emit an error, |
| 442 | // which short-circuits the middleware pipeline and |
| 443 | // writes an HTTP error response. |
| 444 | if err := parseErrorCode(pattern); err != nil { |
| 445 | return false, err |
| 446 | } |
| 447 | |
| 448 | candidates := makeCandidates(pattern) |
| 449 | for _, c := range candidates { |
| 450 | // Skip the IO if using fallback policy and it's the latest item |
| 451 | if i == maxI { |
| 452 | setPlaceholders(c, false) |
| 453 | |
| 454 | return true, nil |
| 455 | } |
| 456 | |
| 457 | if info, exists := m.strictFileExists(fileSystem, c.fullpath); exists { |
| 458 | setPlaceholders(c, info.IsDir()) |
| 459 | return true, nil |
| 460 | } |
| 461 | } |
| 462 | } |
| 463 | |
| 464 | case tryPolicyLargestSize: |
| 465 | var largestSize int64 |
| 466 | var largest matchCandidate |
| 467 | var largestInfo os.FileInfo |
| 468 | for _, pattern := range m.TryFiles { |
| 469 | candidates := makeCandidates(pattern) |
| 470 | for _, c := range candidates { |
| 471 | info, err := fs.Stat(fileSystem, c.fullpath) |
| 472 | if err == nil && info.Size() > largestSize { |
| 473 | largestSize = info.Size() |
| 474 | largest = c |
| 475 | largestInfo = info |
| 476 | } |
| 477 | } |
| 478 | } |
| 479 | if largestInfo == nil { |
| 480 | return false, nil |
| 481 | } |
| 482 | setPlaceholders(largest, largestInfo.IsDir()) |
| 483 | return true, nil |
| 484 | |
| 485 | case tryPolicySmallestSize: |
| 486 | var smallestSize int64 |
| 487 | var smallest matchCandidate |
| 488 | var smallestInfo os.FileInfo |
| 489 | for _, pattern := range m.TryFiles { |
| 490 | candidates := makeCandidates(pattern) |
| 491 | for _, c := range candidates { |
| 492 | info, err := fs.Stat(fileSystem, c.fullpath) |
| 493 | if err == nil && (smallestSize == 0 || info.Size() < smallestSize) { |
| 494 | smallestSize = info.Size() |
| 495 | smallest = c |
| 496 | smallestInfo = info |
| 497 | } |
| 498 | } |
| 499 | } |
| 500 | if smallestInfo == nil { |
| 501 | return false, nil |
| 502 | } |
| 503 | setPlaceholders(smallest, smallestInfo.IsDir()) |
| 504 | return true, nil |
| 505 | |
| 506 | case tryPolicyMostRecentlyMod: |
| 507 | var recent matchCandidate |
| 508 | var recentInfo os.FileInfo |
| 509 | for _, pattern := range m.TryFiles { |
| 510 | candidates := makeCandidates(pattern) |
| 511 | for _, c := range candidates { |
| 512 | info, err := fs.Stat(fileSystem, c.fullpath) |
| 513 | if err == nil && |
| 514 | (recentInfo == nil || info.ModTime().After(recentInfo.ModTime())) { |
| 515 | recent = c |
| 516 | recentInfo = info |
| 517 | } |
| 518 | } |
| 519 | } |
| 520 | if recentInfo == nil { |
| 521 | return false, nil |
| 522 | } |
| 523 | setPlaceholders(recent, recentInfo.IsDir()) |
| 524 | return true, nil |
| 525 | } |
| 526 | |
| 527 | return false, nil |
| 528 | } |
| 529 | |
| 530 | // parseErrorCode checks if the input is a status |
| 531 | // code number, prefixed by "=", and returns an |
| 532 | // error if so. |
| 533 | func parseErrorCode(input string) error { |
| 534 | if len(input) > 1 && input[0] == '=' { |
| 535 | code, err := strconv.Atoi(input[1:]) |
| 536 | if err != nil || code < 100 || code > 999 { |
| 537 | return nil |
| 538 | } |
| 539 | return caddyhttp.Error(code, fmt.Errorf("%s", input[1:])) |
| 540 | } |
| 541 | return nil |
| 542 | } |
| 543 | |
| 544 | // strictFileExists returns true if file exists |
| 545 | // and matches the convention of the given file |
| 546 | // path. If the path ends in a forward slash, |
| 547 | // the file must also be a directory; if it does |
| 548 | // NOT end in a forward slash, the file must NOT |
| 549 | // be a directory. |
| 550 | func (m MatchFile) strictFileExists(fileSystem fs.FS, file string) (os.FileInfo, bool) { |
| 551 | info, err := fs.Stat(fileSystem, file) |
| 552 | if err != nil { |
| 553 | // in reality, this can be any error |
| 554 | // such as permission or even obscure |
| 555 | // ones like "is not a directory" (when |
| 556 | // trying to stat a file within a file); |
| 557 | // in those cases we can't be sure if |
| 558 | // the file exists, so we just treat any |
| 559 | // error as if it does not exist; see |
| 560 | // https://stackoverflow.com/a/12518877/1048862 |
| 561 | return nil, false |
| 562 | } |
| 563 | if strings.HasSuffix(file, separator) { |
| 564 | // by convention, file paths ending |
| 565 | // in a path separator must be a directory |
| 566 | return info, info.IsDir() |
| 567 | } |
| 568 | // by convention, file paths NOT ending |
| 569 | // in a path separator must NOT be a directory |
| 570 | return info, !info.IsDir() |
| 571 | } |
| 572 | |
| 573 | // firstSplit returns the first result where the path |
| 574 | // can be split in two by a value in m.SplitPath. The |
| 575 | // return values are the first piece of the path that |
| 576 | // ends with the split substring and the remainder. |
| 577 | // If the path cannot be split, the path is returned |
| 578 | // as-is (with no remainder). |
| 579 | func (m MatchFile) firstSplit(path string) (splitPart, remainder string) { |
| 580 | for _, split := range m.SplitPath { |
| 581 | if idx := indexFold(path, split); idx > -1 { |
| 582 | pos := idx + len(split) |
| 583 | // skip the split if it's not the final part of the filename |
| 584 | if pos != len(path) && !strings.HasPrefix(path[pos:], "/") { |
| 585 | continue |
| 586 | } |
| 587 | return path[:pos], path[pos:] |
| 588 | } |
| 589 | } |
| 590 | return path, "" |
| 591 | } |
| 592 | |
| 593 | // There is no strings.IndexFold() function like there is strings.EqualFold(), |
| 594 | // but we can use strings.EqualFold() to build our own case-insensitive |
| 595 | // substring search (as of Go 1.14). |
| 596 | func indexFold(haystack, needle string) int { |
| 597 | nlen := len(needle) |
| 598 | for i := 0; i+nlen < len(haystack); i++ { |
| 599 | if strings.EqualFold(haystack[i:i+nlen], needle) { |
| 600 | return i |
| 601 | } |
| 602 | } |
| 603 | return -1 |
| 604 | } |
| 605 | |
| 606 | // isCELTryFilesLiteral returns whether the expression resolves to a map literal containing |
| 607 | // only string keys with or a placeholder call. |
| 608 | func isCELTryFilesLiteral(e ast.Expr) bool { |
| 609 | switch e.Kind() { |
| 610 | case ast.MapKind: |
| 611 | mapExpr := e.AsMap() |
| 612 | for _, entry := range mapExpr.Entries() { |
| 613 | mapKey := entry.AsMapEntry().Key() |
| 614 | mapVal := entry.AsMapEntry().Value() |
| 615 | if !isCELStringLiteral(mapKey) { |
| 616 | return false |
| 617 | } |
| 618 | mapKeyStr := mapKey.AsLiteral().ConvertToType(types.StringType).Value() |
| 619 | switch mapKeyStr { |
| 620 | case "try_files", "split_path": |
| 621 | if !isCELStringListLiteral(mapVal) { |
| 622 | return false |
| 623 | } |
| 624 | case "try_policy", "root": |
| 625 | if !(isCELStringExpr(mapVal)) { |
| 626 | return false |
| 627 | } |
| 628 | default: |
| 629 | return false |
| 630 | } |
| 631 | } |
| 632 | return true |
| 633 | |
| 634 | case ast.UnspecifiedExprKind, ast.CallKind, ast.ComprehensionKind, ast.IdentKind, ast.ListKind, ast.LiteralKind, ast.SelectKind, ast.StructKind: |
| 635 | // appeasing the linter :) |
| 636 | } |
| 637 | return false |
| 638 | } |
| 639 | |
| 640 | // isCELStringExpr indicates whether the expression is a supported string expression |
| 641 | func isCELStringExpr(e ast.Expr) bool { |
| 642 | return isCELStringLiteral(e) || isCELCaddyPlaceholderCall(e) || isCELConcatCall(e) |
| 643 | } |
| 644 | |
| 645 | // isCELStringLiteral returns whether the expression is a CEL string literal. |
| 646 | func isCELStringLiteral(e ast.Expr) bool { |
| 647 | switch e.Kind() { |
| 648 | case ast.LiteralKind: |
| 649 | constant := e.AsLiteral() |
| 650 | switch constant.Type() { |
| 651 | case types.StringType: |
| 652 | return true |
| 653 | } |
| 654 | case ast.UnspecifiedExprKind, ast.CallKind, ast.ComprehensionKind, ast.IdentKind, ast.ListKind, ast.MapKind, ast.SelectKind, ast.StructKind: |
| 655 | // appeasing the linter :) |
| 656 | } |
| 657 | return false |
| 658 | } |
| 659 | |
| 660 | // isCELCaddyPlaceholderCall returns whether the expression is a caddy placeholder call. |
| 661 | func isCELCaddyPlaceholderCall(e ast.Expr) bool { |
| 662 | switch e.Kind() { |
| 663 | case ast.CallKind: |
| 664 | call := e.AsCall() |
| 665 | if call.FunctionName() == caddyhttp.CELPlaceholderFuncName { |
| 666 | return true |
| 667 | } |
| 668 | case ast.UnspecifiedExprKind, ast.ComprehensionKind, ast.IdentKind, ast.ListKind, ast.LiteralKind, ast.MapKind, ast.SelectKind, ast.StructKind: |
| 669 | // appeasing the linter :) |
| 670 | } |
| 671 | return false |
| 672 | } |
| 673 | |
| 674 | // isCELConcatCall tests whether the expression is a concat function (+) with string, placeholder, or |
| 675 | // other concat call arguments. |
| 676 | func isCELConcatCall(e ast.Expr) bool { |
| 677 | switch e.Kind() { |
| 678 | case ast.CallKind: |
| 679 | call := e.AsCall() |
| 680 | if call.Target().Kind() != ast.UnspecifiedExprKind { |
| 681 | return false |
| 682 | } |
| 683 | if call.FunctionName() != operators.Add { |
| 684 | return false |
| 685 | } |
| 686 | for _, arg := range call.Args() { |
| 687 | if !isCELStringExpr(arg) { |
| 688 | return false |
| 689 | } |
| 690 | } |
| 691 | return true |
| 692 | case ast.UnspecifiedExprKind, ast.ComprehensionKind, ast.IdentKind, ast.ListKind, ast.LiteralKind, ast.MapKind, ast.SelectKind, ast.StructKind: |
| 693 | // appeasing the linter :) |
| 694 | } |
| 695 | return false |
| 696 | } |
| 697 | |
| 698 | // isCELStringListLiteral returns whether the expression resolves to a list literal |
| 699 | // containing only string constants or a placeholder call. |
| 700 | func isCELStringListLiteral(e ast.Expr) bool { |
| 701 | switch e.Kind() { |
| 702 | case ast.ListKind: |
| 703 | list := e.AsList() |
| 704 | for _, elem := range list.Elements() { |
| 705 | if !isCELStringExpr(elem) { |
| 706 | return false |
| 707 | } |
| 708 | } |
| 709 | return true |
| 710 | case ast.UnspecifiedExprKind, ast.CallKind, ast.ComprehensionKind, ast.IdentKind, ast.LiteralKind, ast.MapKind, ast.SelectKind, ast.StructKind: |
| 711 | // appeasing the linter :) |
| 712 | } |
| 713 | return false |
| 714 | } |
| 715 | |
| 716 | // globSafeRepl replaces special glob characters with escaped |
| 717 | // equivalents. Note that the filepath godoc states that |
| 718 | // escaping is not done on Windows because of the separator. |
| 719 | var globSafeRepl = strings.NewReplacer( |
| 720 | "*", "\\*", |
| 721 | "[", "\\[", |
| 722 | "?", "\\?", |
| 723 | "\\", "\\\\", |
| 724 | ) |
| 725 | |
| 726 | const ( |
| 727 | tryPolicyFirstExist = "first_exist" |
| 728 | tryPolicyFirstExistFallback = "first_exist_fallback" |
| 729 | tryPolicyLargestSize = "largest_size" |
| 730 | tryPolicySmallestSize = "smallest_size" |
| 731 | tryPolicyMostRecentlyMod = "most_recently_modified" |
| 732 | ) |
| 733 | |
| 734 | // Interface guards |
| 735 | var ( |
| 736 | _ caddy.Validator = (*MatchFile)(nil) |
| 737 | _ caddyhttp.RequestMatcherWithError = (*MatchFile)(nil) |
| 738 | _ caddyhttp.CELLibraryProducer = (*MatchFile)(nil) |
| 739 | ) |