package app import ( "os" "path/filepath" "runtime" "strings" ) // evalExisting resolves symlinks of the longest existing prefix of p and keeps // the rest as written, so a path that does not exist yet can still be checked. func evalExisting(p string) (string, error) { p, err := filepath.Abs(p) if err != nil { return "", err } rest := "" cur := p for { if resolved, err := filepath.EvalSymlinks(cur); err == nil { return filepath.Join(resolved, rest), nil } parent := filepath.Dir(cur) if parent == cur { return p, nil } rest = filepath.Join(filepath.Base(cur), rest) cur = parent } } // pathInside reports whether p stays strictly inside root once symlinks are // resolved. Neither path needs to exist yet. func pathInside(root, p string) bool { if strings.TrimSpace(root) == "" || strings.TrimSpace(p) == "" { return false } r, err := evalExisting(root) if err != nil { return false } c, err := evalExisting(p) if err != nil { return false } if runtime.GOOS == "windows" { r, c = strings.ToLower(r), strings.ToLower(c) } rel, err := filepath.Rel(r, c) if err != nil || rel == "." || rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) || filepath.IsAbs(rel) { return false } return true } // pathInsideAny is pathInside for several allowed roots. func pathInsideAny(p string, roots ...string) bool { for _, root := range roots { if pathInside(root, p) { return true } } return false }