code60-transmission-server 0.1.0-staging.13 → 0.1.0-staging.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/INTENT.md +47 -0
  2. package/README.md +36 -345
  3. package/dist/src/acp.js +115 -0
  4. package/dist/src/contract.js +60 -0
  5. package/dist/src/engine.js +481 -0
  6. package/dist/src/main.js +70 -25
  7. package/dist/src/repository.js +94 -0
  8. package/dist/src/service.js +184 -0
  9. package/package.json +16 -35
  10. package/reference/openapi.json +423 -0
  11. package/README.engine.md +0 -463
  12. package/dist/src/broker/filesystem.js +0 -385
  13. package/dist/src/broker/index.js +0 -777
  14. package/dist/src/broker/native/README.md +0 -207
  15. package/dist/src/broker/native/build.js +0 -46
  16. package/dist/src/broker/native/command-helper.c +0 -93
  17. package/dist/src/broker/native/fs-helper.c +0 -529
  18. package/dist/src/broker/native/git-helper.c +0 -205
  19. package/dist/src/broker/policy.js +0 -149
  20. package/dist/src/broker/startup-lock.js +0 -14
  21. package/dist/src/broker/types.js +0 -11
  22. package/dist/src/cli/configure.js +0 -208
  23. package/dist/src/cli/daemon.js +0 -369
  24. package/dist/src/cli/helpers.js +0 -112
  25. package/dist/src/cli/main.js +0 -189
  26. package/dist/src/cli/runtime-build.js +0 -38
  27. package/dist/src/config/coding-policy.js +0 -4
  28. package/dist/src/config/deployment.js +0 -183
  29. package/dist/src/config/documents.js +0 -29
  30. package/dist/src/config/profile-validation.js +0 -129
  31. package/dist/src/config/schema-graph.js +0 -237
  32. package/dist/src/config/schema-loader.js +0 -185
  33. package/dist/src/config/validation-pool.js +0 -105
  34. package/dist/src/config/validation-protocol.js +0 -1
  35. package/dist/src/config/validation-worker.js +0 -106
  36. package/dist/src/config/workflow-language.js +0 -9
  37. package/dist/src/config/workflow-schema.json +0 -545
  38. package/dist/src/config/workflow-types.js +0 -1
  39. package/dist/src/config/workflow-validation.js +0 -95
  40. package/dist/src/engine/budgets.js +0 -50
  41. package/dist/src/engine/clocks.js +0 -27
  42. package/dist/src/engine/commands.js +0 -477
  43. package/dist/src/engine/contracts.js +0 -11
  44. package/dist/src/engine/drain-state.js +0 -31
  45. package/dist/src/engine/effective-permissions.js +0 -120
  46. package/dist/src/engine/instruction-pins.js +0 -205
  47. package/dist/src/engine/retries.js +0 -50
  48. package/dist/src/engine/state.js +0 -1
  49. package/dist/src/engine/timing.js +0 -23
  50. package/dist/src/engine/tool-observations.js +0 -87
  51. package/dist/src/engine/workflow-engine.js +0 -1864
  52. package/dist/src/mcp/catalog.js +0 -71
  53. package/dist/src/mcp/main.js +0 -26
  54. package/dist/src/mcp/server.js +0 -177
  55. package/dist/src/runtime/codex-app-server.js +0 -91
  56. package/dist/src/runtime/codex-executable.js +0 -50
  57. package/dist/src/runtime/containment.js +0 -82
  58. package/dist/src/runtime/engine-driver.js +0 -221
  59. package/dist/src/runtime/json-line-writer.js +0 -192
  60. package/dist/src/runtime/pinned-instruction-sources.js +0 -24
  61. package/dist/src/runtime/protocol-client.js +0 -264
  62. package/dist/src/runtime/protocol-pool.js +0 -183
  63. package/dist/src/runtime/protocol-projection.js +0 -393
  64. package/dist/src/runtime/protocol-types.js +0 -1
  65. package/dist/src/runtime/protocol-worker.js +0 -18
  66. package/dist/src/runtime/provider-bridge.js +0 -290
  67. package/dist/src/runtime/provider-credentials.js +0 -41
  68. package/dist/src/runtime/provider-transport.js +0 -406
  69. package/dist/src/runtime/runtime-broker.js +0 -213
  70. package/dist/src/runtime/workspace-instructions.js +0 -120
  71. package/dist/src/runtime/workspace-view.js +0 -74
  72. package/dist/src/server/api-contract.json +0 -11637
  73. package/dist/src/server/api-types.js +0 -1
  74. package/dist/src/server/application.js +0 -44
  75. package/dist/src/server/auth.js +0 -67
  76. package/dist/src/server/broker-handlers.js +0 -242
  77. package/dist/src/server/coding.js +0 -281
  78. package/dist/src/server/control-plane.js +0 -50
  79. package/dist/src/server/deployment.js +0 -249
  80. package/dist/src/server/errors.js +0 -22
  81. package/dist/src/server/history-handlers.js +0 -130
  82. package/dist/src/server/http.js +0 -124
  83. package/dist/src/server/paging.js +0 -56
  84. package/dist/src/server/publication.js +0 -119
  85. package/dist/src/server/tool-event-handler.js +0 -77
  86. package/dist/src/server/workspace-handlers.js +0 -34
  87. package/dist/src/storage/coordinator.js +0 -224
  88. package/dist/src/storage/startup-lock.js +0 -71
  89. package/dist/src/storage/store.js +0 -167
  90. package/dist/src/tools/check-worker.js +0 -81
  91. package/dist/src/tools/checks.js +0 -117
  92. package/dist/src/tools/command-check.js +0 -34
  93. package/dist/src/tools/commands.js +0 -312
  94. package/dist/src/tools/developer.js +0 -355
  95. package/dist/src/tools/dns.js +0 -248
  96. package/dist/src/tools/http-contract.js +0 -38
  97. package/dist/src/tools/http.js +0 -358
  98. package/dist/src/tools/index.js +0 -194
  99. package/dist/src/tools/worker-check.js +0 -73
  100. package/dist/src/workspaces/git.js +0 -227
  101. package/dist/src/workspaces/index.js +0 -937
  102. package/dist/src/workspaces/source.js +0 -295
  103. package/examples/deployment.local.json +0 -22
  104. package/scripts/postinstall.mjs +0 -26
@@ -1,207 +0,0 @@
1
- # Descriptor-relative filesystem helper
2
-
3
- The native directory also contains `command-helper`, the macOS command
4
- supervisor. It starts the command behind a handshake, verifies two unique
5
- sandbox policy probes, and enumerates processes carrying that inherited policy
6
- identity. This includes children that detach or become reparented. Cancellation
7
- signals those processes and escalates to SIGKILL; the supervisor retains the
8
- startup barrier until settlement. Private fd4 carries settlement proof; command
9
- children cannot write to it. Missing proof retains an uncertain lease.
10
-
11
- This uses macOS `libproc` and the sandbox policy-query SPI (as also used by
12
- [WebKit](https://github.com/WebKit/WebKit/blob/main/Source/WebCore/testing/Internals.cpp)).
13
- It requires a supported host implementation and fails closed when the policy
14
- identity cannot be confirmed. Automatic kqueue `NOTE_TRACK` is unavailable on
15
- supported macOS. Process enumeration and source-boundary checks do not provide
16
- isolation from a hostile same-user host process.
17
-
18
- This is a small unprivileged POSIX helper for the TypeScript broker, not a general
19
- shell, filesystem daemon, sandbox, or server. The catalog implements **read_file**,
20
- **write_file**, **list_files**, **search_files**, **delete_file** and **move_file**.
21
- Delete/move are advertised only when a private same-filesystem quarantine FD is
22
- configured. Engine-only directory/mode restoration is not a model-facing tool.
23
-
24
- ## Build and integration
25
-
26
- Prerequisites: the approved Node 24 runtime and the Mac's existing
27
- `/usr/bin/clang` (Apple Command Line Tools). No installation, download, npm native
28
- script bypass, privilege change or setuid program is involved.
29
-
30
- Normal packaging uses `npm run build` and places the native assets under
31
- `dist/src/broker/native/.build`.
32
- The explicit source-development entry point is:
33
-
34
- ```sh
35
- node --experimental-strip-types -e 'import("./src/broker/native/build.ts").then(m => console.log(m.buildFilesystemHelper()))'
36
- ```
37
-
38
- This explicitly creates `src/broker/native/.build/fs-helper`. Nothing builds or
39
- executes on module import. `buildFilesystemHelper({sanitize:true})` builds the
40
- separate AddressSanitizer/UndefinedBehaviorSanitizer executable with
41
- `-fno-sanitize-recover=all`. `tsc` alone does not build/copy this executable or the
42
- C source; use the package build for the complete deployment.
43
- Pass the absolute trusted executable path to the wrapper as deployment
44
- configuration.
45
-
46
- ```typescript
47
- import { constants, openSync } from "node:fs";
48
- import { NativeFilesystemRoot } from "../filesystem.js";
49
-
50
- // All values here are engine configuration, never model input.
51
- const rootFd = openSync(registeredRoot, constants.O_RDONLY |
52
- constants.O_DIRECTORY | constants.O_NOFOLLOW);
53
- const filesystem = new NativeFilesystemRoot({
54
- rootFd, root: "workspace", helperPath: trustedBuiltHelper,
55
- protectedRootFds: [engineStateFd, otherRegisteredRootFd],
56
- quarantineFd: enginePrivateSameFilesystemDirectoryFd,
57
- startupLockFd: alreadyAcquiredStartupWriterBarrierFd,
58
- });
59
- const broker = new ActionBroker(database, filesystem.catalog());
60
- // Bind the session and use the existing broker catalog/invoke facade.
61
- ```
62
-
63
- The engine owns the borrowed root and additional protected FDs and must keep them
64
- open and unchanged until the wrapper closes. The wrapper pins their dev/inode
65
- identity and rejects descriptor replacement. `close()` closes only its own
66
- installation/helper-directory descriptors, never the borrowed descriptors.
67
- Caller configuration must protect all engine state, source/build/install roots,
68
- credential directories, and other registered roots that must not overlap. The
69
- wrapper automatically protects its actual module installation root and helper
70
- directory; a deployment with additional source/build/install locations must add
71
- those directory FDs too.
72
-
73
- The helper rejects any physical root containment/overlap in either direction,
74
- including case/path aliases, against those protected FDs. Thus no managed
75
- tool/reset scope may replace the helper, its source, engine, or state. Reset and
76
- workspace registration must enforce the same protected scope, not assume a tool
77
- check makes a later Git cleanup safe. The engine must resolve/register the
78
- physical root before constructing this object; this helper does not grant a
79
- model permission to select a root or register a workspace.
80
-
81
- ## Fixed protocol and actual access
82
-
83
- One request/one process, no command-line options. Child stdio is protocol stdin,
84
- stdout, stderr; fd 3 is the sole assigned root; fd 4 onward are at most 64 explicit
85
- protected directory descriptors, including private quarantine when configured.
86
- The already acquired startup barrier's shared open description follows those
87
- descriptors. No database or credential descriptors are inherited. The borrowed
88
- barrier FD is validated for identity, never unlocked or reacquired by an effect
89
- child. Environment is only fixed `PATH=/usr/bin:/bin` and `LC_ALL=C`, with no
90
- ambient proxy, loader or secret environment. The wrapper spawns only the trusted
91
- absolute helper executable, never a shell or PATH-selected model command.
92
-
93
- Request header is 24 bytes: `C60F`, version byte 1, fixed operation byte, protected
94
- descriptor count byte, private-quarantine flag byte, then big-endian 32-bit path/identity/content
95
- lengths and one zero 32-bit word. Body is exact path, identity, content bytes with
96
- no trailing data. Fixed operations are probe-read (1), read (2), probe-write (3),
97
- write (4), root validation (5), tree probe/read (6/7), delete probe/effect (8/9),
98
- move probe/effect (10/11), engine-only directory-delete probe/effect (13/14),
99
- directory creation (15), mode change (16) and mode probe (17). Operation 12 is
100
- forbidden. The model never supplies protocol fields. Reply is a 16-byte `C60R` header with version/status/length
101
- and exact payload. Errors contain fixed codes, not native paths or file metadata.
102
-
103
- Limits: 4096 path bytes, 64 components, 255 bytes/component, 8191 identity bytes,
104
- and 1 MiB file/content. A tree is bounded to 1024 entries and excludes `.git`.
105
- The tree-read identity envelope is separately bounded to 1 MiB. Search authorizes
106
- every examined entry before reading content, with a 16 MiB scan limit, 1000
107
- matches and 4096 characters per reported line. The wrapper kills a helper after
108
- 3 seconds and bounds captured output. Oversize inputs/files fail rather than
109
- truncate. Malformed/truncated/extra input fails before effects.
110
-
111
- Every operation reopens from the inherited physical root using `openat`,
112
- `O_NOFOLLOW`, and pinned directory descriptors. Components are normalized relative
113
- segments, never empty, `.`, `..`, absolute, backslash, or ASCII-case variants of
114
- `.git`. Directory-entry bytes must match exactly, including filesystem case and
115
- Unicode normalization aliases. Symlinks, nonregular targets, multiply linked
116
- files, foreign-owned targets and group/world-writable files/directories fail
117
- closed. Missing intermediate directories are not automatically created.
118
-
119
- Identity includes the actual root/ancestor dev/inodes and actual opened file
120
- dev/inode/mode/uid/gid/link-count/size/nanosecond-mtime/nanosecond-ctime. It is a
121
- **stat identity**, not a content hash. Absent creation binds the exact checked
122
- parent chain. Each actual read/write rechecks that identity on the same opened
123
- file descriptor used for I/O. There is no `realpath`-then-open authority check.
124
-
125
- No destructive truncate occurs before identity validation. Existing writes use
126
- `pwrite` and `ftruncate` on the verified FD. New creation uses
127
- `O_CREAT|O_EXCL|O_NOFOLLOW`, so a target appearing after probe fails rather than
128
- being overwritten. Writes take a nonblocking advisory lock, sync the data (and
129
- new-file parent), and verify resulting content. Reads compare pre/post identity
130
- and do not expose bytes after a detected mutation. Relevant changes before claim
131
- or dispatch permanently invalidate the old authority, even if the old target is
132
- later restored.
133
-
134
- One helper handles each probe/effect and exits; there is no persistent process or
135
- open target handle to dispose between broker stages. The actual effect helper
136
- independently validates its expected identity again immediately at I/O.
137
- Interrupted/partial writes are uncertain and never automatically retried.
138
- Pre-effect known denials return structured failure; invalid UTF-8 reads fail
139
- without exposing decoded/replacement content.
140
-
141
- ### Initial denial privacy
142
-
143
- Helper status codes are trusted internal control flow, not initial model-facing
144
- diagnostics. Until actual-resource authorization succeeds, the central broker
145
- coalesces preparation/resolution failures and policy denials into the same durable
146
- denied action: `resources: []`, no approval, no target-derived reason/status, and
147
- canonical SHA-256 of that displayed ActionSpec. Empty denied resources mean no
148
- authorized resource identity is exposed; they are never an executable grant.
149
- Direct authorization, session action reads and receipt replays use this shape.
150
- `bound.invoke` reports only `{success:false,text:"broker:denied"}`. Denied handles
151
- fail claim state checks before any new target resolution.
152
-
153
- Useful execution diagnostics, such as invalid UTF-8, remain available only after
154
- actual-resource authorization. Initial missing/unsafe-path details are therefore
155
- intentionally not disclosed, even if a requested spelling might have been allowed.
156
-
157
- Trusted operator audit is stored separately in `broker_policy_audit`. It has no
158
- session-facing accessor and must never be joined/serialized into adapter action,
159
- receipt, claim or model responses. Future operator HTTP inspection requires
160
- explicit audience/scope mapping, not generic database row serialization.
161
- This result-equality policy is not a constant-time/host timing-isolation claim.
162
-
163
- ## Threat boundary and remaining requirements
164
-
165
- The broker's synchronous final gate records durable started intent and active
166
- work before invoking this synchronous helper. Applicable engine-controlled
167
- filesystem operations must share that coordinator. Model/runtime native tools,
168
- arbitrary subprocesses, unmediated MCP, recovery's old writers and all other
169
- mutation routes still must be disabled, contained, stopped or mediated. Calling
170
- an engine-controlled writer "same UID" does not exempt it from enforcement.
171
-
172
- The helper pins objects and checks before/after identity; it does **not** provide
173
- a hostile-host atomic snapshot/CAS or mandatory filesystem lock. An unrelated
174
- independent same-UID process can race multiple kernel syscalls by moving a pinned
175
- ancestor, introducing hardlinks, or modifying bytes. Advisory locking does not
176
- stop that actor. This is a documented host limitation, not permission to ignore
177
- model-induced races, old writers, verifier isolation, or external-edit conflicts.
178
-
179
- The engine must compare recorded workspace/content identities,
180
- invalidate affected evaluation, stop on detected external change, and require
181
- conflict-specific overwrite permission. A fresh action request is not that
182
- permission. This wrapper does not itself implement workspace ownership,
183
- registration, Git reset, conflict consent, whole-workspace snapshots, or HTTP
184
- authentication.
185
-
186
- Delete/move bind distinct source/destination parent and name identities. Darwin
187
- rename-excl captures into private same-filesystem quarantine, then verifies the
188
- captured object before deletion or no-overwrite installation. A conflicting
189
- capture is restored only without replacing another entry; uncertain captures
190
- are preserved. This is not conditional unlink-by-file-FD, and no hostile-host
191
- atomicity claim is made. Unsupported platform primitives fail closed.
192
-
193
- ## Validation
194
-
195
- ```sh
196
- ./node_modules/.bin/vitest run tests/pilot/broker.test.ts tests/pilot/broker-fs.test.ts --cache=false
197
- ```
198
-
199
- The filesystem suite runs the actual optimized helper and ASan+UBSan helper
200
- against fresh 0700 `/private/tmp/code60-broker-fs-*` fixtures, outside the actual
201
- engine installation. It tests actual nested read/create/overwrite/truncation,
202
- verifier project-read/scratch-write separation, symlinks/hardlinks/special files,
203
- case/Unicode aliases, switched target/parent restoration, mtime restoration,
204
- absent-parent creation conflicts, actual protected-root overlap, protocol
205
- negative cases and 1 MiB worst-case content. It is not arbitrary-host isolation,
206
- network containment or complete server conformance certification. Extended
207
- namespace/tree cases are in `tests/broker/extended-filesystem.test.ts`.
@@ -1,46 +0,0 @@
1
- import { spawnSync } from "node:child_process";
2
- import { chmodSync, mkdirSync, renameSync, rmSync } from "node:fs";
3
- import { randomUUID } from "node:crypto";
4
- import { fileURLToPath } from "node:url";
5
- import { join } from "node:path";
6
- export function buildFilesystemHelper(options = {}) {
7
- return build("fs", options);
8
- }
9
- export function buildGitHelper(options = {}) {
10
- return build("git", options);
11
- }
12
- export function buildCommandHelper(options = {}) {
13
- return build("command", options);
14
- }
15
- function build(kind, options) {
16
- const directory = fileURLToPath(new URL("./", import.meta.url));
17
- const outDir = options.outputDirectory ?? join(directory, ".build");
18
- const output = join(outDir, `${kind}-helper${options.sanitize ? "-sanitized" : ""}`);
19
- const candidate = `${output}.${randomUUID()}.tmp`;
20
- mkdirSync(outDir, { recursive: true, mode: 0o700 });
21
- const flags = options.sanitize ? ["-O1", "-g", "-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-fno-omit-frame-pointer"] : ["-O2"];
22
- if (options.minimumMacOSVersion)
23
- flags.push(`-mmacosx-version-min=${options.minimumMacOSVersion}`);
24
- const built = spawnSync("/usr/bin/clang", ["-std=c17", "-Wall", "-Wextra", "-Werror", ...flags,
25
- join(directory, `${kind}-helper.c`), "-o", candidate], {
26
- encoding: "utf8", timeout: 30_000, maxBuffer: 1_048_576, env: { PATH: "/usr/bin:/bin", LC_ALL: "C" },
27
- });
28
- if (built.error || built.status !== 0) {
29
- rmSync(candidate, { force: true });
30
- if (built.error?.code === "ENOENT") {
31
- throw new Error("Xcode Command Line Tools (/usr/bin/clang) are required to build Code60 native helpers. Run: xcode-select --install");
32
- }
33
- throw new Error(`Filesystem helper build failed: ${built.error?.message ?? built.stderr}`);
34
- }
35
- chmodSync(candidate, 0o700);
36
- // Never truncate an inode another native child may currently execute. Build
37
- // callers can overlap; publishing a fresh inode also avoids stale macOS
38
- // executable/code-signing cache state from in-place relinking.
39
- try {
40
- renameSync(candidate, output);
41
- }
42
- finally {
43
- rmSync(candidate, { force: true });
44
- }
45
- return output;
46
- }
@@ -1,93 +0,0 @@
1
- /* macOS command supervisor. Each command has two random sandbox policy probes:
2
- * allow one Mach name, deny the other. Unsandboxed processes allow both; other
3
- * sandboxes deny both. Descendants inherit this identity across exec/setsid and
4
- * reparenting. No service is registered or contacted by these policy probes.
5
- * fd4 is a parent-only engine status pipe; fd3 retains the startup barrier.
6
- * Neither descriptor is inherited by the sandboxed worker.
7
- */
8
- #include <sys/wait.h>
9
- #include <sys/proc_info.h>
10
- #include <libproc.h>
11
- #include <unistd.h>
12
- #include <signal.h>
13
- #include <errno.h>
14
- #include <stdio.h>
15
- #include <stdlib.h>
16
- #include <fcntl.h>
17
- #include <dlfcn.h>
18
- #include <time.h>
19
- #include <poll.h>
20
- #include <string.h>
21
-
22
- typedef int (*check_fn)(pid_t, const char *, int, ...);
23
- static check_fn policy_check;
24
- static int probe_flags;
25
- static volatile sig_atomic_t stopping;
26
- static void stop_handler(int signo) { (void)signo; stopping = 1; }
27
- static long long millis(void) { struct timespec t; if (clock_gettime(CLOCK_MONOTONIC, &t)) return 0; return (long long)t.tv_sec * 1000 + t.tv_nsec / 1000000; }
28
- static int marked(pid_t pid, const char *allow, const char *deny) {
29
- return policy_check(pid, "mach-lookup", probe_flags, allow) == 0 && policy_check(pid, "mach-lookup", probe_flags, deny) == 1;
30
- }
31
- static void proof(int settled, int code) { (void)dprintf(4, "{\"settled\":%s,\"exitCode\":%d}\n", settled ? "true" : "false", code); }
32
- int main(int argc, char **argv) {
33
- if (argc > 2 && !strcmp(argv[1], "--worker")) {
34
- char byte = 'R'; if (write(5, &byte, 1) != 1 || read(6, &byte, 1) != 1) return 125;
35
- close(5); close(6); signal(SIGTERM, SIG_DFL); signal(SIGINT, SIG_DFL);
36
- execv(argv[2], argv + 2); return 127;
37
- }
38
- if (argc < 3 || argv[2][0] != '/') return 125;
39
- const pid_t owner = getppid(); if (owner <= 1) return 125;
40
- policy_check = (check_fn)dlsym(RTLD_DEFAULT, "sandbox_check");
41
- const int *no_report = (const int *)dlsym(RTLD_DEFAULT, "SANDBOX_CHECK_NO_REPORT");
42
- if (!policy_check || !no_report) { proof(0, 125); return 125; }
43
- probe_flags = 2 | *no_report; /* SANDBOX_FILTER_GLOBAL_NAME */
44
- char allow[256], deny[256];
45
- if (snprintf(allow, sizeof(allow), "code60.command.%s.allow", argv[1]) >= (int)sizeof(allow) || snprintf(deny, sizeof(deny), "code60.command.%s.deny", argv[1]) >= (int)sizeof(deny)) return 125;
46
- struct sigaction action = {0}; action.sa_handler = stop_handler; sigemptyset(&action.sa_mask);
47
- if (sigaction(SIGTERM, &action, NULL) || sigaction(SIGINT, &action, NULL)) return 125;
48
- if (dprintf(4, "{\"ready\":true}\n") < 0) return 125;
49
- int ready[2], gate[2]; if (pipe(ready) || pipe(gate)) return 125;
50
- pid_t child = fork(); if (child < 0) return 125;
51
- if (!child) {
52
- int r = fcntl(ready[1], F_DUPFD, 10), g = fcntl(gate[0], F_DUPFD, 10); if (r < 0 || g < 0) _exit(125);
53
- close(ready[0]); close(ready[1]); close(gate[0]); close(gate[1]); close(4); close(3);
54
- if (dup2(r, 5) != 5 || dup2(g, 6) != 6) _exit(125); close(r); close(g);
55
- signal(SIGTERM, SIG_DFL); signal(SIGINT, SIG_DFL); execv(argv[2], argv + 2); _exit(127);
56
- }
57
- close(ready[1]); close(gate[0]);
58
- int status = 0, exited = 0, uncertain = 0, confirmed = 0; long long started = millis(), stop_at = 0;
59
- while (!confirmed) {
60
- if (getppid() != owner) { stopping = 1; break; }
61
- struct pollfd p = { .fd = ready[0], .events = POLLIN }; int n = poll(&p, 1, 20);
62
- if (n > 0 && (p.revents & POLLIN)) { char byte; if (read(ready[0], &byte, 1) == 1 && marked(child, allow, deny)) confirmed = 1; else uncertain = 1; break; }
63
- pid_t waited = waitpid(child, &status, WNOHANG); if (waited == child) { exited = 1; break; }
64
- if (stopping) break; /* The worker is still gated; no command has run. */
65
- if (millis() - started > 10000 || (n < 0 && errno != EINTR)) { uncertain = 1; break; }
66
- }
67
- close(ready[0]); if (confirmed) { char byte = 'G'; if (write(gate[1], &byte, 1) != 1) uncertain = 1; } close(gate[1]);
68
- if (!confirmed && !exited) { kill(child, SIGKILL); waitpid(child, &status, 0); exited = 1; }
69
- int capacity = 4096, empty = 0; pid_t *pids = calloc((size_t)capacity, sizeof(pid_t)); if (!pids) uncertain = 1;
70
- while (confirmed && pids) {
71
- if (getppid() != owner) stopping = 1;
72
- int needed = proc_listallpids(NULL, 0); if (needed < 0) { uncertain = 1; break; }
73
- if (needed + 256 > capacity) { capacity = needed + 1024; pid_t *next = realloc(pids, (size_t)capacity * sizeof(pid_t)); if (!next) { uncertain = 1; break; } pids = next; }
74
- int n = proc_listallpids(pids, capacity * (int)sizeof(pid_t)); if (n < 0 || n >= capacity) { uncertain = 1; break; }
75
- if (stopping && !stop_at) stop_at = millis();
76
- int active = 0;
77
- for (int i = 0; i < n; i++) {
78
- struct proc_bsdinfo info; if (pids[i] <= 1 || pids[i] == getpid()) continue;
79
- if (proc_pidinfo(pids[i], PROC_PIDTBSDINFO, 0, &info, sizeof(info)) != sizeof(info) || info.pbi_uid != geteuid() || info.pbi_status == 5) continue;
80
- if (!marked(pids[i], allow, deny)) continue;
81
- active++; if (stopping) { /* Recheck the label immediately before signaling. */
82
- if (marked(pids[i], allow, deny)) kill(pids[i], millis() - stop_at < 400 ? SIGTERM : SIGKILL);
83
- }
84
- }
85
- if (!exited && waitpid(child, &status, WNOHANG) == child) exited = 1;
86
- if (exited && !active) { if (++empty == 3) break; } else empty = 0;
87
- struct timespec delay = { .tv_sec = 0, .tv_nsec = 20000000 }; nanosleep(&delay, NULL);
88
- }
89
- free(pids);
90
- if (!exited) { kill(child, SIGKILL); while (waitpid(child, &status, 0) < 0) if (errno != EINTR) break; }
91
- int code = WIFEXITED(status) ? WEXITSTATUS(status) : 128 + (WIFSIGNALED(status) ? WTERMSIG(status) : 0);
92
- proof(!uncertain, code); return uncertain ? 125 : 0;
93
- }