package server import ( "errors" "io" "io/fs" "os" "path/filepath" "sort" "strings" "time" "git.a-wan.net/alan/pipelines/internal/protocol" ) // directoryListingScanLimit bounds how many names one list_directory reads // before sorting, so a huge directory cannot make the server read without end. // The reply itself is capped at protocol.DirectoryListingMaxEntries. const directoryListingScanLimit = 5 * protocol.DirectoryListingMaxEntries // handleDirectoryListing answers list_directory. It returns true when the // request was a list_directory and has been answered. func handleDirectoryListing(request protocol.Message, write func(protocol.Message) error) bool { if request.Type != protocol.ListDirectory { return false } path := "" if request.ListDirectory != nil { path = request.ListDirectory.Path } home, err := OperatorHomeDirectory() if err == nil { var listing protocol.DirectoryListingResult listing, err = listHomeDirectory(home, path, protocol.DirectoryListingMaxEntries) if err == nil { _ = write(protocol.Message{Type: protocol.DirectoryListing, ID: request.ID, DirectoryListing: &listing}) return true } } _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}) return true } // listHomeDirectory lists one directory inside home. The requested path is // cleaned and its symlinks resolved before the containment check, so neither // ".." nor a symlink can escape home. The listed path is reported under home // (as the operator sees it) even when home itself is reached through a link. func listHomeDirectory(home, requested string, maxEntries int) (protocol.DirectoryListingResult, error) { home = filepath.Clean(home) realHome, err := filepath.EvalSymlinks(home) if err != nil { return protocol.DirectoryListingResult{}, errors.New("resolve home directory: " + err.Error()) } target, err := expandHomePath(home, requested) if err != nil { return protocol.DirectoryListingResult{}, err } rel, realTarget, err := resolveInsideHome(realHome, target) if err != nil { return protocol.DirectoryListingResult{}, err } shown := filepath.Join(home, rel) info, err := os.Stat(realTarget) if err != nil { return protocol.DirectoryListingResult{}, describePathError(shown, err) } if !info.IsDir() { return protocol.DirectoryListingResult{}, errors.New(shown + " is not a directory") } if specialFilesystem(realTarget) { return protocol.DirectoryListingResult{}, errors.New(shown + " is on a special filesystem and cannot be listed") } entries, truncated, err := readDirectoryEntries(realHome, realTarget, shown, maxEntries) if err != nil { return protocol.DirectoryListingResult{}, err } result := protocol.DirectoryListingResult{Path: shown, Home: home, Entries: entries, Truncated: truncated} if rel != "." { parent := filepath.Dir(shown) result.Parent = &parent } return result, nil } // expandHomePath turns "", "~" and "~/sub" into paths under home and requires // anything else to be absolute. "~user" forms are refused. func expandHomePath(home, requested string) (string, error) { requested = strings.TrimSpace(requested) switch { case requested == "" || requested == "~": return home, nil case strings.HasPrefix(requested, "~/"): return filepath.Join(home, requested[2:]), nil case strings.HasPrefix(requested, "~"): return "", errors.New("path " + requested + " must be absolute or start with ~/") case !filepath.IsAbs(requested): return "", errors.New("path " + requested + " must be absolute or start with ~") } return filepath.Clean(requested), nil } // resolveInsideHome resolves every symlink in target and returns its path // relative to realHome, refusing anything outside the home subtree. func resolveInsideHome(realHome, target string) (string, string, error) { realTarget, err := filepath.EvalSymlinks(target) if err != nil { return "", "", describePathError(target, err) } rel, ok := relInside(realHome, realTarget) if !ok { return "", "", errors.New("path " + target + " is outside the home directory " + realHome + "; only folders inside home can be listed") } return rel, realTarget, nil } func relInside(root, path string) (string, bool) { rel, err := filepath.Rel(root, path) if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || filepath.IsAbs(rel) { return "", false } return rel, true } func describePathError(path string, err error) error { switch { case errors.Is(err, fs.ErrPermission): return errors.New("permission denied: " + path) case errors.Is(err, fs.ErrNotExist): return errors.New(path + " does not exist") } return errors.New(path + " is not available: " + err.Error()) } // readDirectoryEntries reads at most directoryListingScanLimit names, sorts // directories first then case-insensitively, and caps the result. No file is // opened. func readDirectoryEntries(realHome, realDir, shown string, maxEntries int) ([]protocol.DirectoryEntry, bool, error) { dir, err := os.Open(realDir) if err != nil { return nil, false, describePathError(shown, err) } defer dir.Close() items, err := dir.ReadDir(directoryListingScanLimit + 1) if err != nil && !errors.Is(err, io.EOF) { return nil, false, describePathError(shown, err) } truncated := len(items) > directoryListingScanLimit if truncated { items = items[:directoryListingScanLimit] } entries := make([]protocol.DirectoryEntry, 0, len(items)) for _, item := range items { entries = append(entries, describeEntry(realHome, realDir, shown, item)) } sort.SliceStable(entries, func(i, j int) bool { a, b := entries[i], entries[j] if a.IsDir != b.IsDir { return a.IsDir } la, lb := strings.ToLower(a.Name), strings.ToLower(b.Name) if la != lb { return la < lb } return a.Name < b.Name }) if len(entries) > maxEntries { entries = entries[:maxEntries] truncated = true } return entries, truncated, nil } // describeEntry classifies one name. A symlink counts as a directory only when // it resolves to a directory still inside home; one that escapes is shown as a // plain, non-selectable name. Devices, sockets and pipes are plain names too. func describeEntry(realHome, realDir, shown string, item fs.DirEntry) protocol.DirectoryEntry { name := item.Name() entry := protocol.DirectoryEntry{Name: name, Path: filepath.Join(shown, name), Hidden: strings.HasPrefix(name, ".")} full := filepath.Join(realDir, name) switch { case item.IsDir(): entry.IsDir = true case item.Type()&fs.ModeSymlink != 0: resolved, err := filepath.EvalSymlinks(full) if err != nil { break } if _, ok := relInside(realHome, resolved); !ok { break } if info, err := os.Stat(resolved); err == nil && info.IsDir() { entry.IsDir = true } } if !entry.IsDir { if info, err := item.Info(); err == nil { entry.Size = info.Size() entry.Modified = info.ModTime().UTC().Format(time.RFC3339) } } if entry.IsDir { if _, err := os.Lstat(filepath.Join(full, ".git")); err == nil { entry.IsGitRepo = true } } return entry }