interplane.Get Omega
Read in your language

omega-mv

Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.

Brought by drakestapleton

branch main Branches Tags History

omega-mv / tools / quietlock / quietlock.c

956 lines · 28949 bytes Raw Blame History
1/* SPDX-License-Identifier: Apache-2.0
2 * Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* quietlock: the Spark quiet flag as a real lock (HD-13).
18 *
19 * The quiet flag is the file $QUIETLOCK_DIR/.spark-quiet (default
20 * $HOME/workspace/.spark-quiet). Its first line keeps the format that
21 * ~/.claude/hooks/quiet-guard.sh and orchestrate-lanes/lanes.sh already read:
22 *
23 * <f1> <f2> <f3> ... start=<iso> expected_end=<iso UTC> pid=<n> [hold=<id>]
24 *
25 * (first three fields = holder; pid= and expected_end= tokens anywhere).
26 * quietlock adds a hold=<id> token; old lines without it still parse. After
27 * `hold` starts its command it also adds job=<pid> jobgroup=<pgid> (the
28 * command runs in its own process group). The holder counts as alive while
29 * pid=, job= or any process in jobgroup= is alive (zombies count as dead).
30 *
31 * Subcommands
32 * hold --owner ID --minutes N [--reason TEXT] -- CMD...
33 * Acquire the flag (flock on .spark-quiet.lock around the
34 * read-modify-write, flag published with link(2) so it never clobbers),
35 * run CMD with QUIETLOCK_HOLD=<id>, release when CMD and every process
36 * left in its process group have exited. Exit = CMD's exit.
37 * N > 20 needs the approval token (see below). Exit 75 if already held,
38 * 77 if the approval token is missing or does not cover this hold.
39 * check
40 * Exit 0 if no flag, if the flag is stale (holder pid dead AND
41 * expected_end passed; holder = pid, job and jobgroup), or if $QUIETLOCK_HOLD equals the live hold id.
42 * Otherwise exit 75 with the holder on stderr.
43 * run -- CMD...
44 * check, then exec CMD.
45 * release-stale
46 * Remove the flag only when the holder (pid, job and jobgroup) is dead
47 * AND expected_end has passed (the quiet-guard.sh rule). Never touches a live hold (exit 3).
48 *
49 * Approval token ($QUIETLOCK_DIR/.spark-quiet-approval), key=value lines:
50 * owner=<ID> max_minutes=<N> expires_at=<iso UTC>
51 * THIS IS A POLICY FILE, NOT CRYPTOGRAPHIC. Anyone who can write the
52 * directory can write a token. It stops accidental or unthinking long holds
53 * and leaves an audit line in .spark-quiet.history for every use; it does not
54 * stop a determined local user. A signed token is a separate follow-up.
55 *
56 * Where the lock is enforced: at real entry points only (mk/quiet.mk for every
57 * omega make goal, scripts run under `quietlock run --` or `quietlock hold`,
58 * and lanes.sh queue/flush/forge once wired to call quietlock). The decision
59 * is never made by pattern-matching command text; the Claude hook
60 * (tools/quietlock/quiet-guard.sh) is only a courtesy filter in front of it.
61 *
62 * Rules worth knowing
63 * - No state dir (GitHub CI, another machine): check is clear (exit 0).
64 * - Refusals print the fixed marker QUIETLOCK_REFUSED and exit 75.
65 * - Overrun: expected_end is ADVISORY (Drake 2026-10-01). If the command is
66 * still running when it passes, `hold` KEEPS the flag and logs one
67 * "overrun:" warning; the flag is released only when the command exits.
68 * The command is never killed.
69 * - Legacy flags (no hold= token) let their holder through with
70 * QUIET_HOLDER=1, DEPRECATED, logged, for the transition only.
71 * - QUIETLOCK_DIR moves the state dir (tests use it). Anyone can point it at an
72 * empty dir and pass check: this is a cooperative lock against accidents,
73 * not a security boundary, like the token below.
74 * - Times must end in Z (UTC). A time without Z never counts as passed.
75 *
76 * Plain C + POSIX, plus flock(2) (Linux/BSD) as the brief requires.
77 */
78#ifndef _GNU_SOURCE
79#define _GNU_SOURCE
80#endif
81#include <dirent.h>
82#include <errno.h>
83#include <fcntl.h>
84#include <limits.h>
85#include <signal.h>
86#include <stdarg.h>
87#include <stdio.h>
88#include <stdlib.h>
89#include <string.h>
90#include <sys/file.h>
91#include <sys/stat.h>
92#include <sys/types.h>
93#include <sys/wait.h>
94#include <termios.h>
95#include <time.h>
96#include <unistd.h>
97
98#define EXIT_HELD 75
99#define EXIT_NOAPPROVAL 77
100#define EXIT_LIVE 3
101#define MAX_UNAPPROVED_MINUTES 20L
102#define MAX_MINUTES (7L * 24L * 60L)
103
104#define PBUF (PATH_MAX + 64)
105static char g_dir[PATH_MAX];
106static char g_flag[PBUF];
107static char g_lock[PBUF];
108static char g_hist[PBUF];
109static char g_appr[PBUF];
110
111struct flag {
112 int present;
113 char line[1024];
114 char holder[256];
115 long pid;
116 int has_pid;
117 long job; /* job= : the command quietlock hold started */
118 int has_job;
119 long jobgrp; /* jobgroup= : that command's own process group */
120 int has_jobgrp;
121 time_t end;
122 int has_end;
123 char end_text[64];
124 char hold[128];
125};
126
127static void die(const char *fmt, ...)
128{
129 va_list ap;
130 fputs("quietlock: ", stderr);
131 va_start(ap, fmt);
132 vfprintf(stderr, fmt, ap);
133 va_end(ap);
134 fputc('\n', stderr);
135 exit(1);
136}
137
138static void mkpath(char *dst, size_t n, const char *name)
139{
140 int r = snprintf(dst, n, "%s/%s", g_dir, name);
141 if (r < 0 || (size_t)r >= n)
142 die("state path too long");
143}
144
145static void paths_init(void)
146{
147 const char *d = getenv("QUIETLOCK_DIR");
148 int r;
149 if (d && *d) {
150 r = snprintf(g_dir, sizeof g_dir, "%s", d);
151 } else {
152 const char *h = getenv("HOME");
153 if (!h || !*h)
154 die("neither QUIETLOCK_DIR nor HOME is set");
155 r = snprintf(g_dir, sizeof g_dir, "%s/workspace", h);
156 }
157 if (r < 0 || (size_t)r >= sizeof g_dir)
158 die("state dir path too long");
159 mkpath(g_flag, sizeof g_flag, ".spark-quiet");
160 mkpath(g_lock, sizeof g_lock, ".spark-quiet.lock");
161 mkpath(g_hist, sizeof g_hist, ".spark-quiet.history");
162 mkpath(g_appr, sizeof g_appr, ".spark-quiet-approval");
163}
164
165static void iso_utc(time_t t, char *buf, size_t n)
166{
167 struct tm tm;
168 gmtime_r(&t, &tm);
169 if (strftime(buf, n, "%Y-%m-%dT%H:%M:%SZ", &tm) == 0 && n)
170 buf[0] = '\0';
171}
172
173/* Accepts YYYY-MM-DDTHH:MM:SSZ and YYYY-MM-DDTHH:MMZ only. The trailing Z is
174 * REQUIRED: quiet-guard.sh and lanes.sh read a no-Z time with `date -d` as local
175 * time, so a no-Z (or +00:00) time is treated as unreadable, which never counts
176 * as passed (fails safe: such a flag is never stale). */
177static int parse_iso(const char *s, time_t *out)
178{
179 static const char *fmts[] = { "%Y-%m-%dT%H:%M:%S", "%Y-%m-%dT%H:%M" };
180 size_t i;
181 for (i = 0; i < sizeof fmts / sizeof fmts[0]; i++) {
182 struct tm tm;
183 char *e;
184 memset(&tm, 0, sizeof tm);
185 e = strptime(s, fmts[i], &tm);
186 if (!e)
187 continue;
188 if (*e != 'Z' || e[1] != '\0')
189 continue;
190 *out = timegm(&tm);
191 return *out == (time_t)-1 ? -1 : 0;
192 }
193 return -1;
194}
195
196static void history(const char *fmt, ...)
197{
198 char msg[2048], ts[32], out[2200];
199 va_list ap;
200 int fd, n;
201 va_start(ap, fmt);
202 vsnprintf(msg, sizeof msg, fmt, ap);
203 va_end(ap);
204 iso_utc(time(NULL), ts, sizeof ts);
205 n = snprintf(out, sizeof out, "[%s] quietlock: %s\n", ts, msg);
206 if (n < 0)
207 return;
208 if ((size_t)n >= sizeof out)
209 n = (int)sizeof out - 1;
210 fd = open(g_hist, O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0644);
211 if (fd < 0) {
212 fprintf(stderr, "quietlock: cannot append history %s: %s\n", g_hist, strerror(errno));
213 return;
214 }
215 if (write(fd, out, (size_t)n) != n)
216 fprintf(stderr, "quietlock: short write to history\n");
217 close(fd);
218}
219
220static int lock_take(int op)
221{
222 int fd = open(g_lock, O_RDWR | O_CREAT | O_CLOEXEC, 0644);
223 if (fd < 0)
224 die("cannot open lock file %s: %s", g_lock, strerror(errno));
225 while (flock(fd, op) != 0) {
226 if (errno != EINTR)
227 die("flock %s: %s", g_lock, strerror(errno));
228 }
229 return fd;
230}
231
232static void lock_drop(int fd)
233{
234 flock(fd, LOCK_UN);
235 close(fd);
236}
237
238static void read_flag(struct flag *f)
239{
240 FILE *fp;
241 char copy[1024], *tok, *save = NULL;
242 int field = 0;
243 size_t hl = 0;
244
245 memset(f, 0, sizeof *f);
246 fp = fopen(g_flag, "r");
247 if (!fp) {
248 if (errno != ENOENT)
249 die("cannot read flag %s: %s", g_flag, strerror(errno));
250 return;
251 }
252 f->present = 1;
253 if (!fgets(f->line, sizeof f->line, fp))
254 f->line[0] = '\0';
255 fclose(fp);
256 f->line[strcspn(f->line, "\r\n")] = '\0';
257
258 memcpy(copy, f->line, sizeof copy);
259 for (tok = strtok_r(copy, " \t", &save); tok; tok = strtok_r(NULL, " \t", &save)) {
260 if (field < 3) {
261 size_t tl = strlen(tok);
262 if (hl + tl + 2 < sizeof f->holder) {
263 if (hl)
264 f->holder[hl++] = ' ';
265 memcpy(f->holder + hl, tok, tl);
266 hl += tl;
267 f->holder[hl] = '\0';
268 }
269 field++;
270 }
271 if (!f->has_pid && strncmp(tok, "pid=", 4) == 0) {
272 char *e;
273 long v;
274 errno = 0;
275 v = strtol(tok + 4, &e, 10);
276 if (e != tok + 4 && errno == 0 && v > 0) {
277 f->pid = v;
278 f->has_pid = 1;
279 }
280 } else if (!f->has_end && strncmp(tok, "expected_end=", 13) == 0) {
281 snprintf(f->end_text, sizeof f->end_text, "%s", tok + 13);
282 if (parse_iso(tok + 13, &f->end) == 0)
283 f->has_end = 1;
284 } else if (!f->hold[0] && strncmp(tok, "hold=", 5) == 0) {
285 snprintf(f->hold, sizeof f->hold, "%s", tok + 5);
286 } else if (!f->has_job && strncmp(tok, "job=", 4) == 0) {
287 char *e;
288 long v;
289 errno = 0;
290 v = strtol(tok + 4, &e, 10);
291 if (e != tok + 4 && errno == 0 && v > 0) {
292 f->job = v;
293 f->has_job = 1;
294 }
295 } else if (!f->has_jobgrp && strncmp(tok, "jobgroup=", 9) == 0) {
296 char *e;
297 long v;
298 errno = 0;
299 v = strtol(tok + 9, &e, 10);
300 if (e != tok + 9 && errno == 0 && v > 0) {
301 f->jobgrp = v;
302 f->has_jobgrp = 1;
303 }
304 }
305 }
306}
307
308/* Reads /proc/<pid>/stat: state letter and process group. 0 = read, -1 = not readable. */
309static int proc_stat(const char *pid, char *state, long *pgrp)
310{
311 char path[64], buf[512], *p;
312 FILE *fp;
313 long ppid;
314 snprintf(path, sizeof path, "/proc/%s/stat", pid);
315 fp = fopen(path, "r");
316 if (!fp)
317 return -1;
318 if (!fgets(buf, sizeof buf, fp)) {
319 fclose(fp);
320 return -1;
321 }
322 fclose(fp);
323 p = strrchr(buf, ')'); /* comm may hold spaces or ')' */
324 if (!p || sscanf(p + 1, " %c %ld %ld", state, &ppid, pgrp) != 3)
325 return -1;
326 return 0;
327}
328
329/* A zombie counts as dead (it runs nothing; an orphan may wait on a slow reaper). */
330static int pid_alive(long pid)
331{
332 char s[32], state;
333 long pg;
334 if (pid <= 0)
335 return 0;
336 if (kill((pid_t)pid, 0) != 0 && errno != EPERM) /* EPERM: exists, owned by someone else */
337 return 0;
338 snprintf(s, sizeof s, "%ld", pid);
339 if (proc_stat(s, &state, &pg) == 0 && state == 'Z')
340 return 0;
341 return 1;
342}
343
344/* Any non-zombie process in process group pgid. Without /proc: kill(-pgid, 0). */
345static int group_alive(long pgid)
346{
347 DIR *dir;
348 struct dirent *de;
349 if (pgid <= 0)
350 return 0;
351 if (kill((pid_t)-pgid, 0) != 0 && errno != EPERM)
352 return 0;
353 dir = opendir("/proc");
354 if (!dir)
355 return 1;
356 while ((de = readdir(dir)) != NULL) {
357 char state;
358 long pg;
359 if (de->d_name[0] < '1' || de->d_name[0] > '9')
360 continue;
361 if (proc_stat(de->d_name, &state, &pg) == 0 && pg == pgid && state != 'Z') {
362 closedir(dir);
363 return 1;
364 }
365 }
366 closedir(dir);
367 return 0;
368}
369
370/* Drake 2026-10-01: a hold lasts while its job runs. The holder is alive while
371 * the quietlock process (pid=) OR the job it started (job=) OR any process in
372 * the job's own process group (jobgroup=) is alive. */
373static int holder_alive(const struct flag *f)
374{
375 return (f->has_pid && pid_alive(f->pid)) || (f->has_job && pid_alive(f->job)) ||
376 (f->has_jobgrp && group_alive(f->jobgrp));
377}
378
379/* Stale = holder pid known, holder (quietlock, job and job group) all dead,
380 * AND expected_end known and passed. */
381static int flag_stale(const struct flag *f)
382{
383 if (!f->has_pid || holder_alive(f))
384 return 0;
385 if (!f->has_end)
386 return 0;
387 return time(NULL) > f->end;
388}
389
390static void describe(const struct flag *f, char *buf, size_t n)
391{
392 char pid[32], job[64];
393 int alive = holder_alive(f);
394 if (f->has_pid)
395 snprintf(pid, sizeof pid, "%ld", f->pid);
396 else
397 snprintf(pid, sizeof pid, "?");
398 job[0] = '\0';
399 if (f->has_job || f->has_jobgrp)
400 snprintf(job, sizeof job, " job=%ld jobgroup=%ld", f->has_job ? f->job : 0L,
401 f->has_jobgrp ? f->jobgrp : 0L);
402 snprintf(buf, n, "holder='%s' pid=%s%s alive=%s expected_end=%s%s", f->holder[0] ? f->holder : "unknown",
403 pid, job, alive ? "yes" : "no", f->end_text[0] ? f->end_text : "?",
404 alive && f->has_end && time(NULL) > f->end ? " overrun=yes" : "");
405}
406
407/* No state dir (GitHub CI, another machine, fresh account): nothing can be held. */
408static int state_dir_missing(void)
409{
410 struct stat st;
411 return stat(g_dir, &st) != 0 && errno == ENOENT;
412}
413
414static int cmd_check(void)
415{
416 struct flag f;
417 const char *mine = getenv("QUIETLOCK_HOLD");
418 const char *legacy = getenv("QUIET_HOLDER");
419 char d[512];
420 int fd;
421 if (state_dir_missing()) {
422 fprintf(stderr, "quietlock: no state dir %s, so no quiet flag: clear\n", g_dir);
423 return 0;
424 }
425 fd = lock_take(LOCK_SH);
426 read_flag(&f);
427 lock_drop(fd);
428 if (!f.present)
429 return 0;
430 if (f.hold[0] && mine && strcmp(mine, f.hold) == 0)
431 return 0;
432 describe(&f, d, sizeof d);
433 if (flag_stale(&f)) {
434 fprintf(stderr, "quietlock: stale quiet flag (%s): holder dead and past expected_end, treating as clear; "
435 "'quietlock release-stale' removes it\n", d);
436 return 0;
437 }
438 /* DEPRECATED transition escape: a legacy flag (written before quietlock, so no
439 * hold= token) lets its holder through with QUIET_HOLDER=1, as quiet-guard.sh
440 * did. Never applies to a quietlock hold. Every use is logged. */
441 if (!f.hold[0] && legacy && strcmp(legacy, "1") == 0) {
442 history("DEPRECATED QUIET_HOLDER=1 passed legacy flag: %s", f.line);
443 fprintf(stderr, "quietlock: legacy flag passed with QUIET_HOLDER=1 (deprecated; use 'quietlock hold')\n");
444 return 0;
445 }
446 fprintf(stderr, "quietlock: QUIETLOCK_REFUSED Spark quiet flag HELD (%s) at %s. Builds and tests wait until it "
447 "is released. The holder runs its commands under 'quietlock hold'.\n", d, g_flag);
448 return EXIT_HELD;
449}
450
451static int valid_owner(const char *s)
452{
453 size_t n = strlen(s), i;
454 if (n == 0 || n > 64)
455 return 0;
456 for (i = 0; i < n; i++) {
457 char c = s[i];
458 if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' ||
459 c == '_' || c == '.'))
460 return 0;
461 }
462 return 1;
463}
464
465static int parse_long(const char *s, long *out)
466{
467 char *e;
468 long v;
469 if (!s || !*s)
470 return -1;
471 errno = 0;
472 v = strtol(s, &e, 10);
473 if (*e != '\0' || errno)
474 return -1;
475 *out = v;
476 return 0;
477}
478
479/* 0 = token covers (owner, minutes); else -1 with why. Writes no history. */
480static int approval_ok(const char *owner, long minutes, char *why, size_t wn, char *info, size_t in)
481{
482 FILE *fp = fopen(g_appr, "r");
483 char line[512], tok_owner[128] = "", tok_max[64] = "", tok_exp[64] = "";
484 long maxm;
485 time_t exp;
486 if (!fp) {
487 snprintf(why, wn, "no approval token at %s", g_appr);
488 return -1;
489 }
490 while (fgets(line, sizeof line, fp)) {
491 char *k = line, *v;
492 line[strcspn(line, "\r\n")] = '\0';
493 while (*k == ' ' || *k == '\t')
494 k++;
495 if (*k == '#' || *k == '\0')
496 continue;
497 v = strchr(k, '=');
498 if (!v)
499 continue;
500 *v++ = '\0';
501 if (strcmp(k, "owner") == 0)
502 snprintf(tok_owner, sizeof tok_owner, "%s", v);
503 else if (strcmp(k, "max_minutes") == 0)
504 snprintf(tok_max, sizeof tok_max, "%s", v);
505 else if (strcmp(k, "expires_at") == 0)
506 snprintf(tok_exp, sizeof tok_exp, "%s", v);
507 }
508 fclose(fp);
509 snprintf(info, in, "token owner=%s max_minutes=%s expires_at=%s", tok_owner, tok_max, tok_exp);
510 if (strcmp(tok_owner, owner) != 0) {
511 snprintf(why, wn, "approval token names owner '%s', not '%s'", tok_owner, owner);
512 return -1;
513 }
514 if (parse_long(tok_max, &maxm) != 0 || maxm < minutes) {
515 snprintf(why, wn, "approval token max_minutes '%s' does not cover %ld minutes", tok_max, minutes);
516 return -1;
517 }
518 if (parse_iso(tok_exp, &exp) != 0) {
519 snprintf(why, wn, "approval token expires_at '%s' is unreadable", tok_exp);
520 return -1;
521 }
522 if (time(NULL) >= exp) {
523 snprintf(why, wn, "approval token expired at %s", tok_exp);
524 return -1;
525 }
526 return 0;
527}
528
529static volatile sig_atomic_t g_child;
530static volatile sig_atomic_t g_sig;
531static const int g_fwd[] = { SIGINT, SIGTERM, SIGHUP, SIGQUIT };
532
533/* Forward to the job's whole process group (the job runs in its own group, so a
534 * signal sent to our group no longer reaches it directly); fall back to the pid. */
535static void on_signal(int sig)
536{
537 int e = errno;
538 g_sig = sig;
539 if (g_child > 0 && kill((pid_t)-g_child, sig) != 0)
540 kill((pid_t)g_child, sig);
541 errno = e;
542}
543
544/* After fork: add job=<pid> jobgroup=<pgid> to our own flag (under the flock,
545 * only if the flag still carries our hold id), published with rename(2). */
546static int record_job(const char *id, pid_t child)
547{
548 struct flag f;
549 char nl[1200], tmp[PBUF + 32];
550 int fd, tfd, n, ok = -1;
551 fd = lock_take(LOCK_EX);
552 read_flag(&f);
553 if (!f.present || strcmp(f.hold, id) != 0) {
554 lock_drop(fd);
555 history("hold %s: flag gone or replaced before the job was recorded, left alone", id);
556 return 0;
557 }
558 n = snprintf(nl, sizeof nl, "%s job=%ld jobgroup=%ld\n", f.line, (long)child, (long)child);
559 snprintf(tmp, sizeof tmp, "%s.tmp.%ld", g_flag, (long)getpid());
560 unlink(tmp);
561 if (n > 0 && (size_t)n < sizeof nl) {
562 tfd = open(tmp, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0644);
563 if (tfd >= 0) {
564 int wok = write(tfd, nl, (size_t)n) == n && fsync(tfd) == 0;
565 if (close(tfd) == 0 && wok && rename(tmp, g_flag) == 0)
566 ok = 0;
567 }
568 }
569 if (ok != 0) {
570 fprintf(stderr, "quietlock: cannot record the job in %s: %s\n", g_flag, strerror(errno));
571 unlink(tmp);
572 } else {
573 history("hold %s: job=%ld jobgroup=%ld recorded", id, (long)child, (long)child);
574 }
575 lock_drop(fd);
576 return ok;
577}
578
579static void make_hold_id(char *buf, size_t n)
580{
581 unsigned int r = 0;
582 struct timespec ts;
583 int fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
584 if (fd >= 0) {
585 if (read(fd, &r, sizeof r) != (ssize_t)sizeof r)
586 r = 0;
587 close(fd);
588 }
589 clock_gettime(CLOCK_REALTIME, &ts);
590 r ^= (unsigned int)ts.tv_nsec;
591 snprintf(buf, n, "q%ld-%lld-%08x", (long)getpid(), (long long)ts.tv_sec, r);
592}
593
594static void on_alarm(int sig)
595{
596 (void)sig; /* only interrupts waitpid() */
597}
598
599/* Remove the flag only if it still carries our hold id (never a foreign flag). */
600static void warn_overrun(const char *id)
601{
602 history("overrun: hold %s passed expected_end while command still running; flag KEPT "
603 "until the command exits, command NOT killed", id);
604 fprintf(stderr, "quietlock: WARNING overrun: hold %s passed expected_end; flag kept until "
605 "the command exits\n", id);
606}
607
608static void release_mine(const char *id, int rc, int overrun)
609{
610 struct flag f;
611 int fd = lock_take(LOCK_EX);
612 read_flag(&f);
613 if (f.present && strcmp(f.hold, id) == 0) {
614 if (unlink(g_flag) != 0)
615 fprintf(stderr, "quietlock: cannot remove flag %s: %s\n", g_flag, strerror(errno));
616 if (overrun)
617 history("hold %s released when its command exited after overrun (command exit %d)", id, rc);
618 else
619 history("hold %s released (command exit %d)", id, rc);
620 } else {
621 history("hold %s: flag already gone or replaced at exit, left alone (command exit %d)", id, rc);
622 }
623 lock_drop(fd);
624}
625
626/* Seconds per --minutes unit. 60, except a test build may shorten it with
627 * QUIETLOCK_TEST=1 QUIETLOCK_TEST_MINUTE_SECONDS=N (only ever SHORTER holds). */
628static long minute_seconds(void)
629{
630 const char *t = getenv("QUIETLOCK_TEST"), *s = getenv("QUIETLOCK_TEST_MINUTE_SECONDS");
631 long v;
632 if (t && strcmp(t, "1") == 0 && parse_long(s, &v) == 0 && v >= 1 && v < 60)
633 return v;
634 return 60;
635}
636
637static int cmd_hold(const char *owner, const char *mins, const char *reason_in, char **argv)
638{
639 long minutes;
640 char reason[65], why[PBUF + 128], info[512], id[96], start[32], end[32], line[512], tmp[PBUF + 32], d[512];
641 struct flag f;
642 struct sigaction sa;
643 size_t i;
644 int fd, tfd, n, status = 0, rc;
645 pid_t child;
646 time_t now, end_t;
647 int overrun = 0, tty = 0;
648 int gate[2];
649
650 if (!owner || !valid_owner(owner)) {
651 fprintf(stderr, "quietlock: --owner must be 1-64 chars of A-Z a-z 0-9 . _ -\n");
652 return 2;
653 }
654 if (parse_long(mins, &minutes) != 0 || minutes < 1 || minutes > MAX_MINUTES) {
655 fprintf(stderr, "quietlock: --minutes must be an integer from 1 to %ld\n", MAX_MINUTES);
656 return 2;
657 }
658 snprintf(reason, sizeof reason, "%s", reason_in && *reason_in ? reason_in : "hold");
659 for (i = 0; reason[i]; i++) {
660 char c = reason[i];
661 if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' ||
662 c == '_' || c == '.'))
663 reason[i] = '_';
664 }
665
666 if (state_dir_missing() && mkdir(g_dir, 0755) != 0 && errno != EEXIST)
667 die("cannot create state dir %s: %s", g_dir, strerror(errno));
668 fd = lock_take(LOCK_EX);
669 read_flag(&f);
670 if (f.present) {
671 describe(&f, d, sizeof d);
672 lock_drop(fd);
673 fprintf(stderr, "quietlock: QUIETLOCK_REFUSED hold refused, quiet flag already held (%s)%s\n", d,
674 flag_stale(&f) ? "; it is stale, run 'quietlock release-stale' first" : "");
675 return EXIT_HELD;
676 }
677 if (minutes > MAX_UNAPPROVED_MINUTES) {
678 info[0] = '\0';
679 if (approval_ok(owner, minutes, why, sizeof why, info, sizeof info) != 0) {
680 history("REFUSED %ld-minute hold for %s: %s", minutes, owner, why);
681 lock_drop(fd);
682 fprintf(stderr, "quietlock: refused: holds over %ld minutes need Drake's approval token: %s\n",
683 MAX_UNAPPROVED_MINUTES, why);
684 return EXIT_NOAPPROVAL;
685 }
686 history("approval token USED for %ld-minute hold by %s (%s)", minutes, owner, info);
687 }
688
689 make_hold_id(id, sizeof id);
690 now = time(NULL);
691 iso_utc(now, start, sizeof start);
692 end_t = now + minutes * minute_seconds();
693 iso_utc(end_t, end, sizeof end);
694 n = snprintf(line, sizeof line, "%s quietlock %s start=%s expected_end=%s pid=%ld hold=%s\n", owner, reason,
695 start, end, (long)getpid(), id);
696 if (n < 0 || (size_t)n >= sizeof line) {
697 lock_drop(fd);
698 die("flag line too long");
699 }
700 snprintf(tmp, sizeof tmp, "%s.tmp.%ld", g_flag, (long)getpid());
701 unlink(tmp); /* leftover of a crashed run with the same pid; we hold the flock */
702 tfd = open(tmp, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0644);
703 if (tfd < 0) {
704 lock_drop(fd);
705 die("cannot create %s: %s", tmp, strerror(errno));
706 }
707 if (write(tfd, line, (size_t)n) != n || fsync(tfd) != 0) {
708 close(tfd);
709 unlink(tmp);
710 lock_drop(fd);
711 die("cannot write %s", tmp);
712 }
713 close(tfd);
714 /* link(2) publishes the complete line and fails if a flag appeared meanwhile. */
715 if (link(tmp, g_flag) != 0) {
716 int e = errno;
717 unlink(tmp);
718 lock_drop(fd);
719 if (e == EEXIST) {
720 fprintf(stderr, "quietlock: refused: quiet flag appeared while acquiring\n");
721 return EXIT_HELD;
722 }
723 die("cannot publish flag %s: %s", g_flag, strerror(e));
724 }
725 unlink(tmp);
726 line[n - 1] = '\0';
727 history("hold acquired: %s", line);
728 lock_drop(fd);
729
730 memset(&sa, 0, sizeof sa);
731 sa.sa_handler = on_signal;
732 sigemptyset(&sa.sa_mask);
733 for (i = 0; i < sizeof g_fwd / sizeof g_fwd[0]; i++)
734 sigaction(g_fwd[i], &sa, NULL);
735 sa.sa_handler = on_alarm; /* no SA_RESTART: interrupts waitpid at expected_end */
736 sigaction(SIGALRM, &sa, NULL);
737
738 /* The job runs in its own process group and waits on a pipe until its pid
739 * and group are in the flag, so it never runs unrecorded: if quietlock dies
740 * first, the job sees EOF and exits 127 without running. */
741 if (pipe(gate) != 0) {
742 fprintf(stderr, "quietlock: pipe: %s\n", strerror(errno));
743 release_mine(id, 1, 0);
744 return 1;
745 }
746 child = fork();
747 if (child < 0) {
748 fprintf(stderr, "quietlock: fork: %s\n", strerror(errno));
749 close(gate[0]);
750 close(gate[1]);
751 release_mine(id, 1, 0);
752 return 1;
753 }
754 if (child == 0) {
755 struct sigaction dfl;
756 char go;
757 ssize_t r;
758 memset(&dfl, 0, sizeof dfl);
759 dfl.sa_handler = SIG_DFL;
760 sigemptyset(&dfl.sa_mask);
761 for (i = 0; i < sizeof g_fwd / sizeof g_fwd[0]; i++)
762 sigaction(g_fwd[i], &dfl, NULL);
763 close(gate[1]);
764 setpgid(0, 0);
765 do
766 r = read(gate[0], &go, 1);
767 while (r < 0 && errno == EINTR);
768 if (r != 1)
769 _exit(127);
770 close(gate[0]);
771 if (setenv("QUIETLOCK_HOLD", id, 1) != 0)
772 _exit(127);
773 execvp(argv[0], argv);
774 fprintf(stderr, "quietlock: cannot run %s: %s\n", argv[0], strerror(errno));
775 _exit(127);
776 }
777 close(gate[0]);
778 setpgid(child, child); /* also done by the child; whichever runs first wins */
779 signal(SIGPIPE, SIG_IGN); /* a job that died before the go byte must not kill us */
780 g_child = child;
781 /* Interactive use: hand the terminal to the job's group (as a shell does) so
782 * it can read the keyboard and gets Ctrl-C directly; taken back at exit. */
783 tty = isatty(STDIN_FILENO) && tcgetpgrp(STDIN_FILENO) == getpgrp();
784 if (tty) {
785 signal(SIGTTOU, SIG_IGN);
786 tcsetpgrp(STDIN_FILENO, child);
787 }
788 if (record_job(id, child) != 0) {
789 close(gate[1]); /* EOF: the job exits 127 without running */
790 while (waitpid(child, &status, 0) < 0 && errno == EINTR)
791 ;
792 if (tty)
793 tcsetpgrp(STDIN_FILENO, getpgrp());
794 release_mine(id, 1, 0);
795 return 1;
796 }
797 {
798 ssize_t wr;
799 do
800 wr = write(gate[1], "g", 1);
801 while (wr < 0 && errno == EINTR);
802 }
803 close(gate[1]);
804 if (g_sig)
805 on_signal(g_sig);
806 /* Drake 2026-10-01: expected_end is ADVISORY. When it passes and the command
807 * is still running, the hold is KEPT and one overrun warning is logged. The
808 * flag is released only when the command exits (below). The command is NEVER
809 * killed (standing rule: chip tests are never killed). */
810 for (;;) {
811 pid_t w;
812 if (!overrun) {
813 time_t t = time(NULL);
814 if (t >= end_t) {
815 overrun = 1;
816 warn_overrun(id);
817 } else {
818 alarm((unsigned)(end_t - t));
819 }
820 }
821 w = waitpid(child, &status, 0);
822 if (w == child)
823 break;
824 if (w < 0 && errno != EINTR) {
825 status = 1 << 8;
826 break;
827 }
828 }
829 alarm(0);
830 if (WIFEXITED(status))
831 rc = WEXITSTATUS(status);
832 else if (WIFSIGNALED(status))
833 rc = 128 + WTERMSIG(status);
834 else
835 rc = 1;
836 /* The hold lasts until no process of the job's group is left (the same rule
837 * check and release-stale apply when quietlock is gone). Leftover members are
838 * never killed; we wait for them, once a second. Zombies count as dead. */
839 if (group_alive((long)child)) {
840 struct timespec sec = { 1, 0 };
841 history("hold %s: job exited (exit %d) but its group %ld still has processes; flag KEPT until "
842 "the group is gone, nothing killed", id, rc, (long)child);
843 fprintf(stderr, "quietlock: job exited, processes remain in its group %ld; holding until they end\n",
844 (long)child);
845 while (group_alive((long)child)) {
846 if (!overrun && time(NULL) >= end_t) {
847 overrun = 1;
848 warn_overrun(id);
849 }
850 nanosleep(&sec, NULL);
851 }
852 history("hold %s: last process of group %ld ended", id, (long)child);
853 }
854 g_child = 0;
855 if (tty)
856 tcsetpgrp(STDIN_FILENO, getpgrp());
857 release_mine(id, rc, overrun);
858 return rc;
859}
860
861static int cmd_release_stale(void)
862{
863 struct flag f;
864 char d[512];
865 int fd;
866 if (state_dir_missing()) {
867 printf("no flag\n");
868 return 0;
869 }
870 fd = lock_take(LOCK_EX);
871 read_flag(&f);
872 if (!f.present) {
873 lock_drop(fd);
874 printf("no flag\n");
875 return 0;
876 }
877 describe(&f, d, sizeof d);
878 if (!flag_stale(&f)) {
879 lock_drop(fd);
880 printf("flag is LIVE (%s); not touching it\n", d);
881 return EXIT_LIVE;
882 }
883 if (unlink(g_flag) != 0) {
884 int e = errno;
885 lock_drop(fd);
886 die("cannot remove flag %s: %s", g_flag, strerror(e));
887 }
888 history("released stale flag: %s", f.line);
889 lock_drop(fd);
890 printf("released stale flag (holder dead, past expected_end)\n");
891 return 0;
892}
893
894static void usage(void)
895{
896 fprintf(stderr, "usage: quietlock hold --owner ID --minutes N [--reason TEXT] -- CMD...\n"
897 " quietlock check\n"
898 " quietlock run -- CMD...\n"
899 " quietlock release-stale\n"
900 "state dir: $QUIETLOCK_DIR (default $HOME/workspace)\n");
901}
902
903int main(int argc, char **argv)
904{
905 if (argc < 2) {
906 usage();
907 return 2;
908 }
909 paths_init();
910 if (strcmp(argv[1], "check") == 0 && argc == 2)
911 return cmd_check();
912 if (strcmp(argv[1], "release-stale") == 0 && argc == 2)
913 return cmd_release_stale();
914 if (strcmp(argv[1], "run") == 0) {
915 int rc;
916 if (argc < 4 || strcmp(argv[2], "--") != 0) {
917 usage();
918 return 2;
919 }
920 rc = cmd_check();
921 if (rc != 0)
922 return rc;
923 execvp(argv[3], argv + 3);
924 fprintf(stderr, "quietlock: cannot run %s: %s\n", argv[3], strerror(errno));
925 return 127;
926 }
927 if (strcmp(argv[1], "hold") == 0) {
928 const char *owner = NULL, *mins = NULL, *reason = NULL;
929 int i;
930 for (i = 2; i < argc; i++) {
931 if (strcmp(argv[i], "--") == 0)
932 break;
933 if (i + 1 >= argc) {
934 usage();
935 return 2;
936 }
937 if (strcmp(argv[i], "--owner") == 0)
938 owner = argv[++i];
939 else if (strcmp(argv[i], "--minutes") == 0)
940 mins = argv[++i];
941 else if (strcmp(argv[i], "--reason") == 0)
942 reason = argv[++i];
943 else {
944 usage();
945 return 2;
946 }
947 }
948 if (i >= argc - 1) {
949 usage();
950 return 2;
951 }
952 return cmd_hold(owner, mins, reason, argv + i + 1);
953 }
954 usage();
955 return 2;
956}