Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

LinuxProcessIdentity.ts

59 lines2.2 KB

1// @effect-diagnostics nodeBuiltinImport:off - Recovery reads /proc synchronously inside its helper process.
2import * as NodeFS from "node:fs";
3import * as NodeProcess from "node:process";
4​
5import type { MacProcessAuditToken } from "./MacProcessAuditToken.ts";
6​
7// Same 32-byte layout as a macOS audit token, so records and auditTokenPid work unchanged:
8// the start time (clock ticks since boot) in bytes 0-7 and the PID at byte 20.
9const TOKEN_BYTES = 32;
10const PID_OFFSET = 20;
11​
12function readStat(pid: number): { state: string; parent: number; startTime: bigint } | undefined {
13 let stat: string;
14 try {
15 stat = NodeFS.readFileSync(`/proc/${pid}/stat`, "utf8");
16 } catch {
17 return undefined;
18 }
19 // proc(5): the command name is in parentheses and may itself contain ") ".
20 const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
21 const parent = Number(fields[1]);
22 const startTime = fields[19];
23 if (fields[0] === undefined || !Number.isSafeInteger(parent) || !/^\d+$/.test(startTime ?? "")) {
24 return undefined;
25 }
26 return { state: fields[0], parent, startTime: BigInt(startTime!) };
28​
29/** A PID with its start time; the recovery record's boot id makes the pair unique. */
30export const linuxProcessIdentity: MacProcessAuditToken = {
31 read(pid) {
32 const stat = readStat(pid);
33 // A zombie holds no lock and cannot be signalled into exiting.
34 if (stat === undefined || stat.state === "Z") return undefined;
35 const token = Buffer.alloc(TOKEN_BYTES);
36 token.writeBigUInt64LE(stat.startTime);
37 token.writeUInt32LE(pid, PID_OFFSET);
38 return token.toString("hex");
39 },
40 executable(pid) {
41 try {
42 return NodeFS.readlinkSync(`/proc/${pid}/exe`);
43 } catch {
44 return undefined;
45 }
46 },
47 parent: (pid) => readStat(pid)?.parent,
48 signal(token, name) {
49 const pid = Buffer.from(token, "hex").readUInt32LE(PID_OFFSET);
50 // Node has no pidfd signal; checking the start time first leaves only a reuse race of
51 // microseconds, after the record's process was already seen as this backend.
52 if (linuxProcessIdentity.read(pid) !== token) return;
53 try {
54 NodeProcess.kill(pid, name);
55 } catch (error) {
56 if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error;
57 }
58 },
59};