Files
rea/src/process/ExecutableLookup.ts
T

291 lines
11 KiB
TypeScript

import type { Stats } from "node:fs";
import { constants as fsConstants } from "node:fs";
import { access as accessPath, stat as statPath } from "node:fs/promises";
import { isAbsolute, sep } from "node:path";
import { absoluteCallerPath } from "../filesystem/callerPath.js";
import { HOST_PLATFORM } from "../platform/HostPlatform.js";
import { posixPathCandidates } from "./executableSearch.js";
import { fileDeadline } from "./FileDeadline.js";
import { reportedSystemCode } from "../kernel/reportedSystemCode.js";
/** Where a command resolves through an effective PATH, or why it does not. */
export type ExecutableLookup =
| {
readonly status: "found";
readonly path: string;
/** The absolute path that an explicitly selected command names. */
readonly selectedPath?: string;
}
/** The host refused to inspect an explicitly selected path. */
| {
readonly status: "denied";
readonly path: string;
readonly code: "EACCES" | "EPERM";
readonly cause: unknown;
}
| {
readonly status: "missing";
readonly checked: readonly string[];
/** The absolute path that an explicitly selected command names. */
readonly selectedPath?: string;
/**
* The candidate whose error ended the lookup, where at least one native
* search stops; absent when every candidate was checked.
*/
readonly stoppedAt?: {
readonly candidate: string;
readonly code?: string;
};
/**
* The first PATH candidate that a launch by name is denied with EACCES:
* one the host refused (a file without execute permission, or one under
* an unsearchable directory) or one that is not a regular file, such as
* a directory, which execve refuses. When no candidate runs, the launch
* fails with EACCES and this is where to repair access or the file.
*/
readonly deniedAt?: {
readonly candidate: string;
readonly reason: "permission" | "not-regular-file";
};
}
/** A relative command, or a match under a relative PATH entry, needed the working directory, which could not be read. */
| { readonly status: "no-working-directory"; readonly cause: unknown }
/** The caller's signal or deadline ended the lookup before it finished. */
| {
readonly status: "interrupted";
readonly by: "cancellation" | "deadline";
/** The path being checked when the lookup stopped. */
readonly candidate: string;
};
type DeniedReason = "permission" | "not-regular-file";
/** Optional bounds for one lookup. */
export interface ExecutableLookupBounds {
readonly signal?: AbortSignal | undefined;
/** Milliseconds for the whole lookup. */
readonly timeoutMs?: number | undefined;
readonly stat?: (path: string) => Promise<Stats>;
readonly access?: (path: string, mode: number) => Promise<void>;
/** The host whose native search the lookup follows; defaults to this one. */
readonly platform?: NodeJS.Platform;
}
/**
* Resolve a command the way process spawning searches for it. A command that
* contains a path separator is the selected path; PATH search continues past
* a missing file, a non-directory and a denied directory, and an existing file
* without execute permission is not a match. Any other error, such as a
* symlink loop, ends the search, as it ends a spawned search, while on Linux
* and macOS an entry too long for the native path buffer is skipped before it
* is checked, as their spawned searches skip it. Where native searches differ,
* the lookup stops, so a launch by name lets the host's own search decide. The
* working directory is read only when the search reaches a
* relative command or PATH entry, since it may have been removed. When that
* read fails, a relative PATH entry is checked as written, against the
* process's working directory, which the kernel still resolves (even `..`
* from a removed directory), as a spawned search does: an entry without the
* executable lets the search continue, and a match there ends it with
* `no-working-directory`, since its absolute path cannot be named. So
* `workingDirectory` must name the process's working directory whenever it
* can fail. A file-system call cannot itself be cancelled, so a check that an
* interrupted lookup stops waiting for keeps running until its mount answers.
*/
export const lookupExecutable = async (
command: string,
workingDirectory: () => string,
searchPath: string | undefined,
bounds: ExecutableLookupBounds = {},
): Promise<ExecutableLookup> => {
const {
signal,
timeoutMs,
stat = statPath,
access = accessPath,
platform = HOST_PLATFORM.platform,
} = bounds;
const pathMax = PATH_MAX[platform];
let cwd: string | undefined;
const readCwd = (): string => (cwd ??= workingDirectory());
// Windows resolves even an absolute path against the working directory's
// drive.
const located = (path: string): string =>
platform !== "win32" && isAbsolute(path)
? absoluteCallerPath(path)
: absoluteCallerPath(path, { cwd: readCwd() });
const explicit =
isAbsolute(command) ||
command.includes("/") ||
(sep === "\\" && command.includes("\\"));
const deadline = fileDeadline(signal, timeoutMs);
try {
const checked: string[] = [];
let selectedPath: string | undefined;
let deniedAt:
| { readonly candidate: string; readonly reason: DeniedReason }
| undefined;
const deny = (candidate: string, reason: DeniedReason): void => {
if (!explicit) deniedAt ??= { candidate, reason };
};
const movedPast = (candidate: string, code: string | undefined): void => {
checked.push(`${candidate}${systemErrorSuffix(code)}`);
if (code === "EACCES") deny(candidate, "permission");
};
const missing = (stoppedAt?: {
readonly candidate: string;
readonly code: string | undefined;
}): ExecutableLookup => ({
status: "missing",
checked,
...(selectedPath === undefined ? {} : { selectedPath }),
...(deniedAt === undefined ? {} : { deniedAt }),
...(stoppedAt === undefined
? {}
: {
stoppedAt: {
candidate: stoppedAt.candidate,
...(stoppedAt.code === undefined ? {} : { code: stoppedAt.code }),
},
}),
});
for (const { candidate, entry, unnamed } of searchCandidates(
command,
explicit,
searchPath,
readCwd,
located,
)) {
if (candidate === undefined)
return { status: "no-working-directory", cause: unnamed.cause };
const entryBytes = Buffer.byteLength(entry);
if (!explicit && pathMax !== undefined && entryBytes >= pathMax) {
checked.push(`a PATH entry of ${entryBytes} bytes (skipped)`);
continue;
}
if (explicit) selectedPath = candidate;
const metadata = await deadline.run(() => stat(candidate));
if (metadata.status === "interrupted") return { ...metadata, candidate };
if (metadata.status === "rejected") {
const code = reportedSystemCode(metadata.cause);
if (explicit && (code === "EACCES" || code === "EPERM"))
return {
status: "denied",
path: candidate,
code,
cause: metadata.cause,
};
movedPast(candidate, code);
if (searchMovesPast(code)) continue;
return missing({ candidate, code });
}
if (!metadata.value.isFile()) {
checked.push(`${candidate} (not a regular file)`);
deny(candidate, "not-regular-file");
continue;
}
const executable = await deadline.run(() =>
access(candidate, fsConstants.X_OK),
);
if (executable.status === "interrupted")
return { ...executable, candidate };
// A launch by name would run a match under an unnamed working
// directory, so the search stops there without a path to report.
if (executable.status === "fulfilled")
return unnamed === undefined
? {
status: "found",
path: candidate,
...(selectedPath === undefined ? {} : { selectedPath }),
}
: { status: "no-working-directory", cause: unnamed.cause };
const code = reportedSystemCode(executable.cause);
movedPast(candidate, code);
if (!searchMovesPast(code)) return missing({ candidate, code });
}
return missing();
} finally {
deadline.release();
}
};
/**
* The selected path, or the files a spawned search tries in PATH order, from
* the shared search owner. A relative entry whose working directory cannot be
* read is kept as written and marked `unnamed`; an explicit relative command
* then has no candidate at all.
*/
function* searchCandidates(
command: string,
explicit: boolean,
searchPath: string | undefined,
readCwd: () => string,
located: (path: string) => string,
): Generator<
| {
readonly candidate: string;
readonly entry: string;
readonly unnamed?: { readonly cause: unknown };
}
| {
readonly candidate: undefined;
readonly entry: string;
readonly unnamed: { readonly cause: unknown };
}
> {
if (explicit) {
try {
yield { candidate: located(command), entry: command };
} catch (cause) {
yield { candidate: undefined, entry: command, unnamed: { cause } };
}
return;
}
// Match Node's Unix default search path when PATH is absent.
for (const { path, entry, unresolved } of posixPathCandidates(
command,
searchPath ?? "/usr/bin:/bin",
{
relativeEntries: "resolve",
workingDirectory: readCwd,
unreadableWorkingDirectory: "as-written",
},
))
yield {
candidate: path,
entry,
...(unresolved === undefined ? {} : { unnamed: unresolved }),
};
}
/**
* The errors every native PATH search moves past: glibc's and musl's execvp,
* Android's bionic and libuv's own search on macOS. At any other error, such
* as a symlink loop, a stale NFS handle or an I/O error, some of them stop,
* so the lookup stops and the launch by name lets the host's search decide.
*/
export const searchMovesPast = (code: string | undefined): boolean =>
code === "ENOENT" || code === "ENOTDIR" || code === "EACCES";
/**
* Launch errors at which native PATH searches differ: glibc's execvp moves
* past a stale NFS handle and a missing device, while musl's stops there. A
* launch by name lets the host's search decide.
*/
export const searchesDiffer = (code: string | undefined): boolean =>
code === "ESTALE" || code === "ENODEV";
/**
* The PATH entry length, in bytes, from which the host's native search skips
* an entry its path buffer cannot hold: execvp on Linux (glibc and musl) and
* libuv on macOS. A shorter entry with an over-long component still fails
* with ENAMETOOLONG. Elsewhere, as on Android, nothing is skipped by length.
*/
const PATH_MAX: Partial<Record<NodeJS.Platform, number>> = {
linux: 4096,
darwin: 1024,
};
const systemErrorSuffix = (code: string | undefined): string =>
code === undefined ? "" : ` (${code})`;