Files
reverse-engineering-anything/src/pcap/PcapNativeBound.ts
T
morluto 5f718ce30e refactor(kernel): give error-message, byte-hex and SHA-256 hex helpers one owner in a new src/kernel layer (#11542)
* refactor(kernel): give error-to-message text one owner in a new src/kernel layer

* fix(kernel): keep the regex worker's own error text inside its isolated source

* refactor(kernel): exclude copies that run in another realm from the error-message guard by name

The regex worker's source string and the page.evaluate fetch in PlaywrightScenarioRequest cannot import errorMessage. The guard now names them, so the counted baseline does not invite a later slice to rewrite them.

* refactor(kernel): migrate the long tail of inline error-message copies to errorMessage (#11552)

Every provider and adapter folder with six or fewer copies now calls errorMessage from src/kernel. Local helpers whose whole body was the copy (failureMessage, gdbErrorMessage, message, describe, reasonOf, recoveryFailureMessage and four local errorMessage definitions) are removed and their call sites call the owner.

Refs #11548

* refactor(kernel): give byte-to-hex formatting one owner in src/kernel (#11560)

byteToHex returns the two lowercase hexadecimal digits of one byte. All eight inline copies (native, contracts, domain firmware and desktop, pcap) call it, keeping their own 0x, % or \x notation, and a counted guard with an empty baseline keeps new copies out.

Refs #11548

* refactor(kernel): give one-shot SHA-256 hex digests one owner in src/kernel (#11562)

sha256Hex digests one in-memory value. A counted guard records the one-shot createHash("sha256").update(x).digest("hex") chains (115 in 101 files) and the first slice migrates domain, contracts and process (35 copies), removing local wrappers (sha256, sha256Text, hash) and the exported sha256Text. Incremental and streamed hashing is not counted.

Refs #11548

* refactor(kernel): migrate the application layer's inline error-message copies to errorMessage (#11563)

All 69 copies in src/application call errorMessage from src/kernel. Local helpers whose whole body was the copy (errorDetail, causeReason and five local errorMessage definitions) are removed and their call sites call the owner.

Refs #11548

* refactor(kernel): migrate the native provider's inline error-message copies to errorMessage (#11567)

All 49 copies in src/native call errorMessage from src/kernel. The local errorReason helpers in LldbCallTracer and LldbRetainedObservations, whose whole body was the copy, are removed and their call sites call the owner.

Refs #11548

* refactor(kernel): migrate the remaining inline error-message copies to errorMessage (#11569)
2026-11-16 07:05:30 +08:00

188 lines
7.4 KiB
TypeScript

import { BOUNDED_PRODUCER_LIMITS } from "../domain/producerResourceLimits.js";
import { selectArtifactCommandPath } from "../process/ArtifactCommandPath.js";
import {
pcapCaptureHostSupported,
PCAP_CAPTURE_UNSUPPORTED_HOST_REASON,
} from "../domain/pcap/pcapAnalysis.js";
import { access, stat } from "node:fs/promises";
import { constants } from "node:fs";
import { basename, isAbsolute } from "node:path";
import {
AnalysisError,
type AnalysisCapturedOutput,
} from "../domain/analysisErrorBase.js";
import {
AnalysisCapabilityUnavailableError,
AnalysisOutputError,
cancelledBy,
} from "../domain/analysisErrorCore.js";
import type { ArtifactAnalysisResources } from "../process/ArtifactAnalysisResources.js";
import { prlimitCeilingArguments } from "../process/LinuxResourceLimits.js";
import type { runPcapCommand } from "./PcapCommand.js";
import type { ArtifactCommandPath } from "../process/ArtifactCommandPath.js";
import { errorMessage } from "../kernel/errorMessage.js";
const PRLIMIT_COMMAND_ENV = "REA_TSHARK_PRLIMIT_COMMAND";
/** Repair for an unusable selected capture limiter; readiness and admission share it. */
export const PCAP_LIMITER_REMEDIATION = `Check that ${PRLIMIT_COMMAND_ENV} (default /usr/bin/prlimit) names an absolute, executable util-linux prlimit.`;
/** Which stage an unsuccessful limited capture command's exit belongs to. */
export type PcapLimitedExitStage =
| { readonly stage: "tool" }
| { readonly stage: "tool-launch"; readonly refusal: "missing" | "denied" }
| { readonly stage: "limiter" };
/**
* Attribute an unsuccessful exit of a command run through util-linux prlimit.
* prlimit sets the limits and then replaces itself with the tool (execvp), so
* once that succeeds the exit status and output are the tool's own. Before
* that, prlimit reports its own failure through err(3) on stderr, prefixed
* with its invocation name: a failed exec exits 127 (ENOENT) or 126, any
* other prlimit failure exits 1. Commands run with LC_ALL=C, so the message
* is untranslated.
*/
export const attributePcapLimitedExit = (
limiterInvocationPath: string,
exit: {
readonly exitCode: number | null | undefined;
readonly signal: string | null | undefined;
readonly stderr: string;
},
): PcapLimitedExitStage => {
const prefix = `${basename(limiterInvocationPath)}: `;
// A signal or output without prlimit's own prefix belongs to the tool.
if (
(exit.signal !== null && exit.signal !== undefined) ||
!exit.stderr.startsWith(prefix)
)
return { stage: "tool" };
if (
(exit.exitCode === 126 || exit.exitCode === 127) &&
exit.stderr.startsWith(`${prefix}failed to execute `)
)
return {
stage: "tool-launch",
refusal: exit.exitCode === 127 ? "missing" : "denied",
};
return exit.exitCode === 1 ? { stage: "limiter" } : { stage: "tool" };
};
/** Capture CPU ceiling, in seconds. */
const PCAP_CPU_SECONDS = 300;
/** Own native capture admission and the exact enforced resource profile. */
export const preparePcapNativeBound = async (
platform: NodeJS.Platform,
environment: Readonly<Record<string, string | undefined>>,
resources: ArtifactAnalysisResources,
probe: (
selected: ArtifactCommandPath,
arguments_: string[],
) => Promise<{
readonly stdout: string;
readonly capturedOutput: AnalysisCapturedOutput;
}>,
signal?: AbortSignal,
operation:
| "inspect_pcap_client"
| "inspect_pcap_capture" = "inspect_pcap_capture",
): Promise<{
nativeBound: NonNullable<Parameters<typeof runPcapCommand>[0]["nativeBound"]>;
limitations: readonly string[];
}> => {
if (platform === "win32") {
return {
nativeBound: {
memoryLimitBytes: BOUNDED_PRODUCER_LIMITS.address_space_bytes,
},
limitations: [
"Each owned Windows tool tree has a 1 GiB Job Object committed-memory limit; this is not a machine-wide quota.",
],
};
}
if (!pcapCaptureHostSupported(platform)) {
const reason = PCAP_CAPTURE_UNSUPPORTED_HOST_REASON;
throw new AnalysisCapabilityUnavailableError("pcap", operation, reason, {
userMessage: reason,
});
}
const configured = environment[PRLIMIT_COMMAND_ENV] ?? "/usr/bin/prlimit";
let probeFailure: AnalysisError | undefined;
let capturedOutput: AnalysisCapturedOutput | undefined;
try {
if (!isAbsolute(configured))
throw new Error(`${PRLIMIT_COMMAND_ENV} must be absolute.`);
const selection = await selectArtifactCommandPath(configured, signal);
if (!(await stat(selection.resolvedPath)).isFile())
throw new Error("The selected limiter is not a regular file.");
await access(selection.resolvedPath, constants.X_OK);
const readProbe = async (argument: "--version" | "--help") => {
try {
const output = await probe(selection, [argument]);
capturedOutput = output.capturedOutput;
return output.stdout;
} catch (cause) {
if (
(cause instanceof AnalysisCapabilityUnavailableError ||
cause instanceof AnalysisOutputError) &&
!cause.cleanupIncomplete
) {
probeFailure = cause;
throw new Error(
cause instanceof AnalysisOutputError
? `The selected limiter produced unreadable ${argument === "--version" ? "version" : "help"} output.`
: "The selected limiter could not be run.",
{ cause },
);
}
throw cause;
}
};
const version = await readProbe("--version");
const prefix = `${basename(selection.invocationPath)} from util-linux `;
if (
!version.startsWith(prefix) ||
version.slice(prefix.length).trim() === ""
)
throw new Error(
"The selected limiter did not report a util-linux prlimit version.",
);
const help = await readProbe("--help");
for (const flag of ["--as", "--fsize", "--cpu", "--core"]) {
if (!new RegExp(`(?:^|\\s)${flag}(?:[=\\[\\s,]|$)`, "u").test(help))
throw new Error(`The selected limiter does not advertise ${flag}.`);
}
const limits = await resources.readLimits({
address_space_bytes: BOUNDED_PRODUCER_LIMITS.address_space_bytes,
file_bytes: BOUNDED_PRODUCER_LIMITS.file_bytes,
cpu_seconds: PCAP_CPU_SECONDS,
});
const nativeBound = {
limiter: {
command: selection,
arguments: prlimitCeilingArguments(limits),
},
};
const limitations = [
`Linux prlimit preserves stricter inherited ceilings: ${limits.address_space_bytes} bytes of per-process address space, ${limits.file_bytes} bytes per file and ${limits.cpu_seconds} CPU seconds; core dumps are disabled. These are not aggregate machine quotas.`,
];
return { nativeBound, limitations };
} catch (cause) {
if (signal?.aborted === true && !(cause instanceof AnalysisError))
throw cancelledBy(operation, signal);
if (cause instanceof AnalysisError) throw cause;
const reason =
"Cannot establish the selected Linux resource limiter before processing capture bytes.";
throw new AnalysisCapabilityUnavailableError("pcap", operation, reason, {
cause,
capturedOutput: probeFailure?.capturedOutput ?? capturedOutput,
diagnostics: {
...probeFailure?.diagnostics,
configuration_key: PRLIMIT_COMMAND_ENV,
configured,
},
userMessage: `${reason} (${errorMessage(cause)}) ${PCAP_LIMITER_REMEDIATION}`,
remediationAction: PCAP_LIMITER_REMEDIATION,
});
}
};