Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions BOT_DISCLOSURE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
I am just a bot. You are interacting with a bot.
10 changes: 6 additions & 4 deletions modules/caddyhttp/fileserver/matcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -446,11 +446,13 @@ func (m MatchFile) selectFile(r *http.Request) (bool, error) {
}
fullPattern := caddyhttp.SanitizedPathJoin(globRoot, beforeSplit)

// expand glob expressions, but not on Windows because Glob() doesn't
// support escaping on Windows due to path separator)
// Expand glob expressions, but not on Windows because Glob() doesn't
// support escaping on Windows due to path separator. Skip Glob on any
// platform when the pattern has no meta characters: Glob would stat the
// file, and strictFileExists stats it again.
var globResults []string
if runtime.GOOS == "windows" {
globResults = []string{fullPattern} // precious Windows
if runtime.GOOS == "windows" || !strings.ContainsAny(fullPattern, `*?[\`) {
globResults = []string{fullPattern}
} else {
globResults, err = fs.Glob(fileSystem, fullPattern)
if err != nil {
Expand Down
46 changes: 46 additions & 0 deletions modules/caddyhttp/fileserver/matcher_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package fileserver

import (
"context"
"io/fs"
"net/http"
"net/http/httptest"
"net/url"
Expand All @@ -24,6 +25,7 @@ import (
"runtime"
"strings"
"testing"
"testing/fstest"

"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/internal/filesystems"
Expand Down Expand Up @@ -952,3 +954,47 @@ func BenchmarkFileMatcher(b *testing.B) {
})
}
}

type statCountingFS struct {
fs.FS
stats int
}

func (c *statCountingFS) Stat(name string) (fs.FileInfo, error) {
c.stats++
return fs.Stat(c.FS, name)
}

func TestTryFilesStatsExistingCandidateOnce(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Glob is already skipped on Windows")
}

counted := &statCountingFS{FS: fstest.MapFS{
"file.txt": &fstest.MapFile{Data: []byte("hello")},
}}
fsmap := &filesystems.FileSystemMap{}
fsmap.Register("count", counted)

m := &MatchFile{
fsmap: fsmap,
FileSystem: "count",
Root: ".",
TryFiles: []string{"file.txt"},
}

req := httptest.NewRequest(http.MethodGet, "/", nil)
repl := caddyhttp.NewTestReplacer(req)
req = req.WithContext(context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl))

matched, err := m.MatchWithError(req)
if err != nil {
t.Fatal(err)
}
if !matched {
t.Fatal("expected file.txt to match")
}
if counted.stats != 1 {
t.Fatalf("stat calls = %d, want 1", counted.stats)
}
}