436 lines
16 KiB
Go
436 lines
16 KiB
Go
package engine
|
|
|
|
import (
|
|
"errors"
|
|
"io/fs"
|
|
"path"
|
|
"path/filepath"
|
|
"sort"
|
|
"strings"
|
|
)
|
|
|
|
const globReadBatch = 128
|
|
|
|
// A parent step can give distinct link targets the same lexical spelling.
|
|
// Keep both coordinates until traversal and source admission have completed.
|
|
type globCandidateKey struct {
|
|
lexical string
|
|
physical string
|
|
}
|
|
|
|
// selectGlobImportCandidates expands path components while retaining the
|
|
// lexical spelling used for filtering and later source admission.
|
|
func selectGlobImportCandidates(access *filesystemAccess, basePath string, spec importDeclarationSpec, policy resolvedImportPolicy, limits importLimits, accounting *importAccounting) (importSelection, []Diagnostic) {
|
|
site := spec.fieldSites["glob"]
|
|
segments := spec.globSegments
|
|
if len(segments) == 0 {
|
|
var valid bool
|
|
segments, valid = validGlobPattern(spec.glob)
|
|
if !valid {
|
|
return importSelection{}, []Diagnostic{*importSelectionDiagnostic(site, CodeImportInvalid, "import glob pattern is invalid")}
|
|
}
|
|
}
|
|
if accounting == nil {
|
|
accounting = &importAccounting{}
|
|
}
|
|
candidates, prefixLength, diagnostics := globStartingCandidates(access, basePath, spec.glob, segments, site)
|
|
if len(diagnostics) != 0 {
|
|
return importSelection{}, diagnostics
|
|
}
|
|
for index := prefixLength; index < len(segments); index++ {
|
|
segment := segments[index]
|
|
last := index == len(segments)-1
|
|
literal, patterned := globLiteralSegment(segment)
|
|
// nextByPath is the set union of candidates reached from each matching
|
|
// parent at this segment; final exclusions below are set difference.
|
|
nextByPath := make(map[globCandidateKey]selectedImportCandidate)
|
|
for _, parent := range candidates {
|
|
if !patterned {
|
|
childPath := access.join(parent.path, literal)
|
|
parentAccessPath := parent.accessPath
|
|
if literal == ".." {
|
|
target, err := access.importEntryTarget(parent.accessPath, nil, true)
|
|
if err != nil {
|
|
return importSelection{}, []Diagnostic{globCandidateDiagnostic(err, site.location, "glob parent directory could not be inspected")}
|
|
}
|
|
if !target.dir {
|
|
continue
|
|
}
|
|
if target.identity != "" {
|
|
parentAccessPath = target.identity
|
|
}
|
|
}
|
|
childAccessPath := access.join(parentAccessPath, literal)
|
|
candidate, missing, diagnostics := explicitGlobCandidate(access, basePath, childPath, childAccessPath, site, last)
|
|
if len(diagnostics) != 0 {
|
|
return importSelection{}, diagnostics
|
|
}
|
|
if !missing {
|
|
nextByPath[globCandidateKey{candidate.path, candidate.accessPath}] = candidate
|
|
}
|
|
continue
|
|
}
|
|
|
|
entries, missing, diagnostics := readGlobEntries(access, parent.accessPath, site.location, limits, accounting)
|
|
if len(diagnostics) != 0 {
|
|
return importSelection{}, diagnostics
|
|
}
|
|
if missing {
|
|
continue
|
|
}
|
|
for _, entry := range entries {
|
|
candidate, selected, diagnostic := prepareGlobEntry(access, basePath, parent, entry, segment, last, policy)
|
|
if diagnostic != nil {
|
|
return importSelection{}, []Diagnostic{*diagnostic}
|
|
}
|
|
if selected {
|
|
nextByPath[globCandidateKey{candidate.path, candidate.accessPath}] = candidate
|
|
}
|
|
}
|
|
}
|
|
candidates = candidatesFromMap(nextByPath)
|
|
if len(candidates) == 0 {
|
|
break
|
|
}
|
|
}
|
|
|
|
selected := make([]selectedImportCandidate, 0, len(candidates))
|
|
for _, candidate := range candidates {
|
|
missing, _, diagnostic := validateNamedImportTarget(access, candidate, false, false)
|
|
if diagnostic != nil {
|
|
return importSelection{}, []Diagnostic{*diagnostic}
|
|
}
|
|
if missing || excludedBasename(path.Base(candidate.path), policy.exclude) {
|
|
continue
|
|
}
|
|
selected = append(selected, candidate)
|
|
}
|
|
if policy.required && len(selected) == 0 {
|
|
return importSelection{}, []Diagnostic{*importSelectionDiagnostic(site, CodeImportMissing, "required import glob selected no files")}
|
|
}
|
|
// Source allowance is charged by source admission, after this filtered set
|
|
// reaches the traversal; that preserves repeated-source diagnostics first.
|
|
selection := importSelection{candidates: selected}
|
|
return selection, nil
|
|
}
|
|
|
|
func prepareGlobEntry(access *filesystemAccess, basePath string, parent selectedImportCandidate, entry fs.DirEntry, pattern string, last bool, policy resolvedImportPolicy) (selectedImportCandidate, bool, *Diagnostic) {
|
|
name := entry.Name()
|
|
matched, err := path.Match(pattern, name)
|
|
if err != nil {
|
|
return selectedImportCandidate{}, false, importSelectionDiagnostic(parent.site, CodeImportInvalid, "import glob pattern is invalid")
|
|
}
|
|
if !matched || !policy.hidden && strings.HasPrefix(name, ".") {
|
|
return selectedImportCandidate{}, false, nil
|
|
}
|
|
|
|
accessPath := access.join(parent.accessPath, name)
|
|
lexicalPath := access.join(parent.path, name)
|
|
if !access.contains(accessPath) || !access.contains(lexicalPath) {
|
|
return selectedImportCandidate{}, false, importSelectionDiagnostic(parent.site, CodeImportOutsideRoot, "glob traversal is outside the configuration root")
|
|
}
|
|
target, err := access.importEntryTarget(accessPath, entry, policy.follow)
|
|
if err != nil {
|
|
diagnostic := globCandidateDiagnostic(err, parent.site.location, "glob match could not be inspected")
|
|
return selectedImportCandidate{}, false, &diagnostic
|
|
}
|
|
if target.symlink && !policy.follow || !last && !target.dir {
|
|
return selectedImportCandidate{}, false, nil
|
|
}
|
|
|
|
physicalPath := target.identity
|
|
// Native source identity and relative imports use the namespace spelling;
|
|
// resolved link identities belong only to discovery.
|
|
if access.native != nil {
|
|
physicalPath = accessPath
|
|
}
|
|
if physicalPath == "" {
|
|
physicalPath, err = access.canonical(accessPath)
|
|
if err != nil {
|
|
diagnostic := globFilesystemDiagnostic(err, "glob match could not be canonicalized", parent.site.location)
|
|
return selectedImportCandidate{}, false, &diagnostic
|
|
}
|
|
}
|
|
|
|
return selectedImportCandidate{
|
|
path: normalizedImportCandidatePath(access, lexicalPath), accessPath: physicalPath,
|
|
label: relativeImportLabel(access, basePath, lexicalPath), site: parent.site,
|
|
}, true, nil
|
|
}
|
|
|
|
func explicitGlobCandidate(access *filesystemAccess, basePath, candidatePath, accessPath string, site importFieldSite, last bool) (selectedImportCandidate, bool, []Diagnostic) {
|
|
if !access.contains(candidatePath) || !access.contains(accessPath) {
|
|
return selectedImportCandidate{}, false, []Diagnostic{*importSelectionDiagnostic(site, CodeImportOutsideRoot, "glob traversal is outside the configuration root")}
|
|
}
|
|
target, err := access.importEntryTarget(accessPath, nil, true)
|
|
if err != nil {
|
|
if errors.Is(err, fs.ErrNotExist) {
|
|
return selectedImportCandidate{}, true, nil
|
|
}
|
|
return selectedImportCandidate{}, false, []Diagnostic{globCandidateDiagnostic(err, site.location, "glob match could not be inspected")}
|
|
}
|
|
canonical, err := access.canonical(accessPath)
|
|
if err != nil {
|
|
if errors.Is(err, fs.ErrNotExist) {
|
|
return selectedImportCandidate{}, true, nil
|
|
}
|
|
return selectedImportCandidate{}, false, []Diagnostic{globFilesystemDiagnostic(err, "glob match could not be canonicalized", site.location)}
|
|
}
|
|
if !access.contains(canonical) {
|
|
return selectedImportCandidate{}, false, []Diagnostic{*importSelectionDiagnostic(site, CodeImportOutsideRoot, "glob traversal resolves outside the configuration root")}
|
|
}
|
|
if !last {
|
|
if !target.dir {
|
|
return selectedImportCandidate{}, true, nil
|
|
}
|
|
}
|
|
return selectedImportCandidate{
|
|
path: normalizedImportCandidatePath(access, candidatePath), accessPath: canonical,
|
|
label: relativeImportLabel(access, basePath, candidatePath), site: site,
|
|
}, false, nil
|
|
}
|
|
|
|
func readGlobEntries(access *filesystemAccess, directory string, location Location, limits importLimits, accounting *importAccounting) ([]fs.DirEntry, bool, []Diagnostic) {
|
|
target, err := access.importEntryTarget(directory, nil, true)
|
|
if err != nil {
|
|
if errors.Is(err, fs.ErrNotExist) {
|
|
return nil, true, nil
|
|
}
|
|
return nil, false, []Diagnostic{globCandidateDiagnostic(err, location, "glob directory could not be inspected")}
|
|
}
|
|
canonical, err := access.canonical(directory)
|
|
if err != nil {
|
|
if errors.Is(err, fs.ErrNotExist) {
|
|
return nil, true, nil
|
|
}
|
|
return nil, false, []Diagnostic{globFilesystemDiagnostic(err, "glob directory could not be canonicalized", location)}
|
|
}
|
|
if !access.contains(canonical) {
|
|
return nil, false, []Diagnostic{importDiagnostic(CodeImportOutsideRoot, "glob directory resolves outside the configuration root", &location)}
|
|
}
|
|
if _, err := access.relative(canonical); err != nil {
|
|
return nil, false, []Diagnostic{importDiagnostic(CodeImportOutsideRoot, "glob directory could not be addressed inside the configuration root", &location)}
|
|
}
|
|
readPath := target.identity
|
|
if readPath == "" {
|
|
readPath = canonical
|
|
}
|
|
entries := make([]fs.DirEntry, 0)
|
|
err = visitBoundedImportDirectory(access, readPath, limits.entries, accounting, func(entry fs.DirEntry) error {
|
|
entries = append(entries, entry)
|
|
return nil
|
|
})
|
|
if errors.Is(err, errImportDirectoryEntryLimit) {
|
|
return nil, false, []Diagnostic{importDiagnostic(CodeImportLimitExceeded, "glob traversal exceeds the directory-entry visit limit", &location)}
|
|
}
|
|
if missingDirectoryOpen(err) {
|
|
return nil, true, nil
|
|
}
|
|
if err != nil {
|
|
return nil, false, []Diagnostic{globFilesystemDiagnostic(err, "glob directory could not be traversed", location)}
|
|
}
|
|
sort.Slice(entries, func(left, right int) bool { return entries[left].Name() < entries[right].Name() })
|
|
return entries, false, nil
|
|
}
|
|
|
|
func globCandidateDiagnostic(err error, location Location, message string) Diagnostic {
|
|
if errors.Is(err, errImportDirectoryLinkCycle) {
|
|
return importDiagnostic(CodeImportCycle, "directory traversal cycle detected", &location)
|
|
}
|
|
if errors.Is(err, errImportPathOutsideRoot) {
|
|
return importDiagnostic(CodeImportOutsideRoot, "glob traversal resolves outside the configuration root", &location)
|
|
}
|
|
return globFilesystemDiagnostic(err, message, location)
|
|
}
|
|
|
|
func candidatesFromMap(candidates map[globCandidateKey]selectedImportCandidate) []selectedImportCandidate {
|
|
result := make([]selectedImportCandidate, 0, len(candidates))
|
|
for _, candidate := range candidates {
|
|
result = append(result, candidate)
|
|
}
|
|
sort.Slice(result, func(i, j int) bool {
|
|
if result[i].path != result[j].path {
|
|
return result[i].path < result[j].path
|
|
}
|
|
return result[i].accessPath < result[j].accessPath
|
|
})
|
|
return result
|
|
}
|
|
|
|
func validGlobPattern(pattern string) ([]string, bool) {
|
|
if !validImportPath(pattern) {
|
|
return nil, false
|
|
}
|
|
_, remainder := splitImportSelectorRoot(pattern)
|
|
segments := strings.Split(remainder, "/")
|
|
for _, segment := range segments {
|
|
if segment == "" || hasRecursiveStars(segment) {
|
|
return nil, false
|
|
}
|
|
if _, err := path.Match(segment, ""); err != nil {
|
|
return nil, false
|
|
}
|
|
}
|
|
return segments, true
|
|
}
|
|
|
|
func hasRecursiveStars(segment string) bool {
|
|
inClass := false
|
|
for index := 0; index < len(segment); index++ {
|
|
switch segment[index] {
|
|
case '\\':
|
|
index++
|
|
case '[':
|
|
inClass = true
|
|
case ']':
|
|
inClass = false
|
|
case '*':
|
|
if !inClass && index+1 < len(segment) && segment[index+1] == '*' {
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func globLiteralSegment(segment string) (string, bool) {
|
|
var literal strings.Builder
|
|
for index := 0; index < len(segment); index++ {
|
|
switch segment[index] {
|
|
case '*', '?', '[':
|
|
return "", true
|
|
case '\\':
|
|
index++
|
|
if index < len(segment) {
|
|
literal.WriteByte(segment[index])
|
|
}
|
|
default:
|
|
literal.WriteByte(segment[index])
|
|
}
|
|
}
|
|
return literal.String(), false
|
|
}
|
|
|
|
func globFilesystemDiagnostic(err error, message string, location Location) Diagnostic {
|
|
code := CodeImportRead
|
|
if errors.Is(err, fs.ErrPermission) {
|
|
code = CodeImportPermission
|
|
}
|
|
return importDiagnostic(code, message, &location)
|
|
}
|
|
|
|
// globStartingCandidates inspects the literal prefix before wildcard discovery.
|
|
// Ancestors of an explicit root are resolution prefixes, never discovery roots.
|
|
func globStartingCandidates(access *filesystemAccess, base, pattern string, segments []string, site importFieldSite) ([]selectedImportCandidate, int, []Diagnostic) {
|
|
root, _ := splitImportSelectorRoot(pattern)
|
|
start := base
|
|
if root != "" {
|
|
start = root
|
|
if access.native != nil {
|
|
if root != "/" {
|
|
return nil, 0, []Diagnostic{*importSelectionDiagnostic(site, CodeImportOutsideRoot, "glob root is outside the selected namespace")}
|
|
}
|
|
start = "."
|
|
}
|
|
}
|
|
prefixAccess := *access
|
|
if access.native != nil {
|
|
prefixAccess.rootPath = "."
|
|
} else {
|
|
prefixAccess.rootPath, prefixAccess.root = "", nil
|
|
}
|
|
candidate := selectedImportCandidate{path: normalizedImportCandidatePath(access, start), accessPath: start, site: site}
|
|
literals := make([]string, 0, len(segments))
|
|
for _, segment := range segments {
|
|
literal, patterned := globLiteralSegment(segment)
|
|
if patterned {
|
|
break
|
|
}
|
|
literals = append(literals, literal)
|
|
}
|
|
if len(literals) != 0 {
|
|
baseTarget, err := prefixAccess.importEntryTarget(start, nil, true)
|
|
if err != nil {
|
|
if errors.Is(err, fs.ErrNotExist) {
|
|
return nil, len(literals), nil
|
|
}
|
|
return nil, 0, []Diagnostic{globCandidateDiagnostic(err, site.location, "glob starting directory could not be inspected")}
|
|
}
|
|
if !baseTarget.dir {
|
|
return nil, len(literals), nil
|
|
}
|
|
resolvedBase := baseTarget.identity
|
|
if resolvedBase == "" {
|
|
resolvedBase = start
|
|
}
|
|
operations := hostImportLinkOperations(&prefixAccess)
|
|
if access.native != nil {
|
|
if links, ok := access.native.(fs.ReadLinkFS); ok {
|
|
operations = nativeImportLinkOperations(&prefixAccess, links)
|
|
} else {
|
|
operations = importLinkOperations{lstat: prefixAccess.stat}
|
|
}
|
|
}
|
|
index := 0
|
|
operations.visit = func(physical string, info fs.FileInfo) error {
|
|
literal := literals[index]
|
|
lexical, err := resolveLiteralImportSelector(&prefixAccess, candidate.path, literal)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
accessPath := physical
|
|
if access.native != nil && literal != ".." {
|
|
// Keep native source spelling; resolved identities guide traversal.
|
|
accessPath = access.join(candidate.accessPath, literal)
|
|
}
|
|
// Retain filesystem access errors as well as link inspection errors.
|
|
if access.native != nil {
|
|
if _, err := prefixAccess.canonical(accessPath); err != nil {
|
|
return err
|
|
}
|
|
} else if _, err := prefixAccess.stat(physical); err != nil {
|
|
return err
|
|
}
|
|
if !globResolutionPrefixAllowed(access, physical) {
|
|
return errImportPathOutsideRoot
|
|
}
|
|
if index < len(segments)-1 && !info.IsDir() {
|
|
return fs.ErrNotExist
|
|
}
|
|
candidate = selectedImportCandidate{path: normalizedImportCandidatePath(access, lexical), accessPath: accessPath,
|
|
label: relativeImportLabel(access, base, lexical), site: site}
|
|
index++
|
|
return nil
|
|
}
|
|
_, err = resolveImportLinkPathFrom(resolvedBase, strings.Join(literals, "/"), operations)
|
|
if err != nil {
|
|
if errors.Is(err, fs.ErrNotExist) {
|
|
return nil, len(literals), nil
|
|
}
|
|
return nil, 0, []Diagnostic{globCandidateDiagnostic(err, site.location, "glob prefix could not be inspected")}
|
|
}
|
|
}
|
|
consumed := len(literals)
|
|
if !access.contains(candidate.accessPath) || !access.contains(candidate.path) {
|
|
return nil, 0, []Diagnostic{*importSelectionDiagnostic(site, CodeImportOutsideRoot, "glob discovery starts outside the configuration root")}
|
|
}
|
|
// Native links preserve their namespace spelling; inspect with the actual
|
|
// boundary once the literal prefix has entered the selected root.
|
|
if access.native != nil {
|
|
if _, err := access.importEntryTarget(candidate.accessPath, nil, true); err != nil {
|
|
return nil, 0, []Diagnostic{globCandidateDiagnostic(err, site.location, "glob starting location could not be inspected")}
|
|
}
|
|
}
|
|
return []selectedImportCandidate{candidate}, consumed, nil
|
|
}
|
|
|
|
func globResolutionPrefixAllowed(access *filesystemAccess, name string) bool {
|
|
if access.contains(name) {
|
|
return true
|
|
}
|
|
if access.native != nil {
|
|
return containsNativePath(name, access.rootPath)
|
|
}
|
|
return access.rootPath != "" && containedPath(filepath.FromSlash(name), access.rootPath)
|
|
}
|