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 / src / osh / host / osh_journal.c

642 lines · 23988 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/*
18 * osh_journal.c -- durable effect journal (OSH_PLATFORM_ABI.md section 10). Format and rules: osh_journal.h.
19 * Plain POSIX: open(O_APPEND), one write() per batch, fsync(file), fsync(directory) when the file is created.
20 */
21#ifndef _GNU_SOURCE
22#define _GNU_SOURCE
23#endif
24#include "osh_journal.h"
25
26#include <ctype.h>
27#include <errno.h>
28#include <fcntl.h>
29#include <stdio.h>
30#include <stdlib.h>
31#include <string.h>
32#include <sys/random.h>
33#include <sys/file.h>
34#include <sys/stat.h>
35#include <unistd.h>
36
37#include "sha256.h"
38
39static const char *const k_outcome[] = {"NOT_STARTED", "COMPLETED", "FAILED_NO_EFFECT", "CANCELLED", "OUTCOME_UNKNOWN"};
40
41/* ---- redaction ---- */
42
43/* The ABI draft names "a secret list" (section 13) but does not define it. ASSUMPTION: a variable NAME is secret when,
44 * compared case-insensitively, it contains any of these fragments. False positives only blank a value inside a digest. */
45int osh_secret_name(const char *name)
46{
47 static const char *const frag[] = {"PASSWORD", "PASSWD", "PASSPHRASE", "SECRET", "TOKEN", "CREDENTIAL", "APIKEY",
48 "API_KEY", "PRIVATE", "AUTH", "COOKIE", "KEY", "SESSION", "SIGNATURE"};
49 size_t n = strlen(name);
50 for (size_t f = 0; f < sizeof frag / sizeof frag[0]; f++) {
51 size_t fl = strlen(frag[f]);
52 for (size_t i = 0; i + fl <= n; i++) {
53 size_t k = 0;
54 while (k < fl && toupper((unsigned char)name[i + k]) == frag[f][k]) k++;
55 if (k == fl) return 1;
56 }
57 }
58 return 0;
59}
60
61/* ---- request digest ---- */
62
63static void h_u64(sha256_ctx *h, uint64_t v)
64{
65 uint8_t b[8];
66 for (int i = 0; i < 8; i++) b[i] = (uint8_t)(v >> (8 * i));
67 sha256_update(h, b, 8);
68}
69
70static void h_str(sha256_ctx *h, const char *s)
71{
72 size_t n = s ? strlen(s) : 0;
73 h_u64(h, n);
74 if (n) sha256_update(h, (const uint8_t *)s, n);
75}
76
77/* Canonical encoding: domain tag, ncmds, connector, flags, then per command the builtin id, argv, assignments
78 * (name, value; a secret name's value is replaced by the marker "\x01REDACTED"), redirections. Lengths are prefixed. */
79static void canon(sha256_ctx *hp, const OshRequest *r)
80{
81 sha256_ctx h = *hp;
82 h_str(&h, "OSHREQ1");
83 h_u64(&h, (uint64_t)r->ncmds);
84 h_u64(&h, (uint64_t)r->connector_after);
85 h_u64(&h, r->flags);
86 for (int i = 0; i < r->ncmds; i++) {
87 const OshCmd *c = &r->cmd[i];
88 h_u64(&h, (uint64_t)c->builtin_id);
89 h_u64(&h, (uint64_t)c->nargv);
90 for (int k = 0; k < c->nargv; k++) h_str(&h, c->argv[k]);
91 h_u64(&h, (uint64_t)c->nassign);
92 for (int k = 0; k < c->nassign; k++) {
93 h_str(&h, c->assign[k].name);
94 h_str(&h, osh_secret_name(c->assign[k].name) ? "\x01REDACTED" : c->assign[k].value);
95 }
96 h_u64(&h, (uint64_t)c->nredir);
97 for (int k = 0; k < c->nredir; k++) {
98 h_u64(&h, (uint64_t)c->redir[k].kind);
99 h_u64(&h, (uint64_t)c->redir[k].fd);
100 h_u64(&h, (uint64_t)c->redir[k].src_fd);
101 h_str(&h, c->redir[k].path);
102 }
103 }
104 *hp = h;
105}
106
107void osh_req_digest_unkeyed(const OshRequest *r, uint8_t out[32])
108{
109 sha256_ctx h;
110 sha256_init(&h);
111 canon(&h, r);
112 sha256_final(&h, out);
113}
114
115/* HMAC-SHA256 (RFC 2104) over omega's src/sha256.c, key 32 bytes. (src/fabric/fab_hmac.c is a test-only stand-in that refuses to
116 * build in a production program, so it is not used.) */
117static void hmac_begin(sha256_ctx *h, const uint8_t key[32])
118{
119 uint8_t pad[64];
120 memset(pad, 0x36, sizeof pad);
121 for (int i = 0; i < 32; i++) pad[i] ^= key[i];
122 sha256_init(h);
123 sha256_update(h, pad, sizeof pad);
124}
125
126static void hmac_end(sha256_ctx *h, const uint8_t key[32], uint8_t out[32])
127{
128 uint8_t pad[64], inner[32];
129 sha256_final(h, inner);
130 memset(pad, 0x5c, sizeof pad);
131 for (int i = 0; i < 32; i++) pad[i] ^= key[i];
132 sha256_init(h);
133 sha256_update(h, pad, sizeof pad);
134 sha256_update(h, inner, sizeof inner);
135 sha256_final(h, out);
136}
137
138void osh_req_digest(const OshJournal *j, const OshRequest *r, uint8_t out[32])
139{
140 sha256_ctx h;
141 hmac_begin(&h, j->key);
142 canon(&h, r);
143 hmac_end(&h, j->key, out);
144}
145
146#ifdef OSH_JOURNAL_TEST_HOOKS
147/* the same HMAC, over a byte string, so the test can check RFC 4231 vectors (key given zero-extended to 32 bytes, which HMAC treats as the shorter key) */
148void osh_hmac_for_test(const uint8_t key[32], const uint8_t *msg, size_t n, uint8_t out[32])
149{
150 sha256_ctx h;
151 hmac_begin(&h, key);
152 sha256_update(&h, msg, n);
153 hmac_end(&h, key, out);
154}
155#endif
156
157static void hex(const uint8_t d[32], char out[65])
158{
159 static const char x[] = "0123456789abcdef";
160 for (int i = 0; i < 32; i++) {
161 out[2 * i] = x[d[i] >> 4];
162 out[2 * i + 1] = x[d[i] & 15];
163 }
164 out[64] = 0;
165}
166
167/* ---- low-level io ---- */
168
169static int write_all(int fd, const char *p, size_t n)
170{
171 while (n) {
172 ssize_t w = write(fd, p, n);
173 if (w < 0) {
174 if (errno == EINTR) continue;
175 return -1;
176 }
177 p += w;
178 n -= (size_t)w;
179 }
180 return 0;
181}
182
183static int sync_fd(int fd)
184{
185 for (;;) {
186 if (fsync(fd) == 0) return 0;
187 if (errno != EINTR) return -1;
188 }
189}
190
191static int fsync_parent(const char *path)
192{
193 char d[4096];
194 if (strlen(path) >= sizeof d) return -ENAMETOOLONG;
195 strcpy(d, path);
196 char *sl = strrchr(d, '/');
197 if (!sl) strcpy(d, ".");
198 else if (sl == d) d[1] = 0;
199 else *sl = 0;
200 int fd = open(d, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
201 if (fd < 0) return -errno;
202 int rc = sync_fd(fd) == 0 ? 0 : -errno;
203 close(fd);
204 return rc;
205}
206
207/* the journal's own fsync; the test build can make one fail (the tests also count real fsync(2) calls) */
208static int jsync(OshJournal *j)
209{
210#ifdef OSH_JOURNAL_TEST_HOOKS
211 if (j->fail_fsync_at && j->n_commit == j->fail_fsync_at) { errno = EIO; return -1; }
212#endif
213 return sync_fd(j->fd);
214}
215
216/* Append one batch and make it durable. STICKY: the first failed write or fsync poisons the journal for the rest of the
217 * session, and after that no new intent is written (every later effect is refused instead). Reason: a short write can
218 * leave a fragment with no newline, and a record appended after it would be glued onto it and be unreadable, so an effect
219 * could run with no readable intent. On a failed write the fragment is cut back to the previous end (tail_clean); only
220 * then may an OUTCOME for an effect that already started still be appended (is_outcome), because it cannot be glued. After
221 * a failed fsync the tail is unknown and nothing more is written. Reopening also closes a torn tail with a newline. */
222static int commit(OshJournal *j, const char *buf, size_t n, int is_outcome)
223{
224 if (j->fd < 0) return -1;
225 if (j->poisoned && !(is_outcome && j->tail_clean)) { errno = EIO; return -1; }
226 off_t pre = lseek(j->fd, 0, SEEK_END);
227 int rc = 0, e = 0, wrote_failed = 0;
228#ifdef OSH_JOURNAL_TEST_HOOKS
229 j->n_commit++;
230 if (j->fail_write_at && j->n_commit == j->fail_write_at) {
231 if (n > 1) (void)write_all(j->fd, buf, n / 2);
232 rc = -1;
233 e = ENOSPC;
234 wrote_failed = 1;
235 }
236#endif
237 if (!rc && write_all(j->fd, buf, n) != 0) { rc = -1; e = errno; wrote_failed = 1; }
238 if (wrote_failed) {
239 j->tail_clean = pre >= 0 && ftruncate(j->fd, pre) == 0;
240 } else if (!rc && jsync(j) != 0) {
241 rc = -1;
242 e = errno;
243 j->tail_clean = 0;
244 }
245 if (rc) {
246 j->poisoned = 1;
247 errno = e ? e : EIO;
248 return -1;
249 }
250 return 0;
251}
252
253/* ---- parsing (shared by open and recover) ---- */
254
255typedef struct {
256 int kind; /* 'I', 'O', 0 = unparsable */
257 uint64_t rec, ref;
258 char digest[65];
259 int idx, ncmds;
260 char a0[200];
261} Line;
262
263static void parse_line(char *s, Line *o)
264{
265 memset(o, 0, sizeof *o);
266 char *sv = NULL, *tok = strtok_r(s, " ", &sv);
267 if (!tok || strcmp(tok, "OSHJ1")) return;
268 if (!(tok = strtok_r(NULL, " ", &sv))) return;
269 o->rec = strtoull(tok, NULL, 10);
270 if (!(tok = strtok_r(NULL, " ", &sv)) || (tok[0] != 'I' && tok[0] != 'O') || tok[1]) return;
271 char kind = tok[0];
272 if (kind == 'O') {
273 if (!(tok = strtok_r(NULL, " ", &sv))) return;
274 o->ref = strtoull(tok, NULL, 10);
275 }
276 if (!(tok = strtok_r(NULL, " ", &sv)) || strlen(tok) != 64) return;
277 memcpy(o->digest, tok, 65);
278 if (!(tok = strtok_r(NULL, " ", &sv)) || sscanf(tok, "%d/%d", &o->idx, &o->ncmds) != 2) return;
279 if (kind == 'I') {
280 for (int k = 0; k < 3; k++) /* b= argc= wr= */
281 if (!strtok_r(NULL, " ", &sv)) return;
282 if (!(tok = strtok_r(NULL, " ", &sv)) || strncmp(tok, "a0=", 3)) return;
283 snprintf(o->a0, sizeof o->a0, "%s", tok + 3);
284 }
285 o->kind = kind;
286}
287
288/* Visit every line of the file. cb returns nothing; torn/garbled lines are counted in *bad. */
289static int scan(const char *path, void (*cb)(void *, const Line *), void *ctx, int *bad, int *ends_nl)
290{
291 int fd = open(path, O_RDONLY | O_CLOEXEC);
292 if (fd < 0) return -errno;
293 size_t cap = 1 << 16, len = 0;
294 char *buf = malloc(cap);
295 if (!buf) { close(fd); return -ENOMEM; }
296 for (;;) {
297 if (len == cap) {
298 char *nb = realloc(buf, cap * 2);
299 if (!nb) { free(buf); close(fd); return -ENOMEM; }
300 buf = nb;
301 cap *= 2;
302 }
303 ssize_t n = read(fd, buf + len, cap - len);
304 if (n < 0 && errno == EINTR) continue;
305 if (n < 0) { int e = errno; free(buf); close(fd); return -e; }
306 if (n == 0) break;
307 len += (size_t)n;
308 }
309 close(fd);
310 if (ends_nl) *ends_nl = len == 0 || buf[len - 1] == '\n';
311 size_t i = 0;
312 while (i < len) {
313 size_t e = i;
314 while (e < len && buf[e] != '\n') e++;
315 int terminated = e < len;
316 char *line = malloc(e - i + 1);
317 if (!line) { free(buf); return -ENOMEM; }
318 memcpy(line, buf + i, e - i);
319 line[e - i] = 0;
320 Line l;
321 parse_line(line, &l);
322 if (!terminated || !l.kind || l.rec == 0) { if (bad && (e > i)) (*bad)++; }
323 else cb(ctx, &l);
324 free(line);
325 i = e + 1;
326 }
327 free(buf);
328 return 0;
329}
330
331static void max_cb(void *ctx, const Line *l) { uint64_t *m = ctx; if (l->rec > *m) *m = l->rec; }
332
333static int jfail(OshJournal *j, int e, const char *fmt, const char *a, unsigned m)
334{
335 snprintf(j->why, sizeof j->why, fmt, a, m);
336 return -e;
337}
338
339static int random_bytes(uint8_t *b, size_t n)
340{
341 size_t got = 0;
342 while (got < n) {
343 ssize_t r = getrandom(b + got, n - got, 0);
344 if (r < 0 && errno == EINTR) continue;
345 if (r <= 0) break;
346 got += (size_t)r;
347 }
348 if (got == n) return 0;
349 int fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
350 if (fd < 0) return -1;
351 while (got < n) {
352 ssize_t r = read(fd, b + got, n - got);
353 if (r < 0 && errno == EINTR) continue;
354 if (r <= 0) { close(fd); return -1; }
355 got += (size_t)r;
356 }
357 close(fd);
358 return 0;
359}
360
361/* The per-journal HMAC key lives beside the journal as <journal>.key (32 random bytes, 0600, owned by the caller).
362 * Created atomically (temporary file with O_EXCL, fsync, link(2) which never overwrites, fsync of the directory) and
363 * reused when present. FAIL CLOSED: an existing key with another owner, a mode other than 0600, a size other than 32 or
364 * that cannot be read refuses the journal; so does a missing key beside a journal that already holds records (a new
365 * key would silently make every earlier digest meaningless). */
366static int load_key(OshJournal *j, const char *path, int have_records)
367{
368 char kp[4200];
369 if (snprintf(kp, sizeof kp, "%s.key", path) >= (int)sizeof kp) return jfail(j, ENAMETOOLONG, "journal path too long%s", "", 0);
370 int fd = open(kp, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
371 if (fd < 0 && errno == ENOENT) {
372 if (have_records) return jfail(j, ENOENT, "key file %s is missing but the journal already has records; refusing to start a new key", kp, 0);
373 char tmp[4300];
374 snprintf(tmp, sizeof tmp, "%s.tmp.%ld", kp, (long)getpid());
375 int tfd = open(tmp, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600);
376 if (tfd < 0) return jfail(j, errno, "cannot create key file %s", kp, 0);
377 uint8_t k[32];
378 int ok = random_bytes(k, sizeof k) == 0 && write_all(tfd, (const char *)k, sizeof k) == 0 && sync_fd(tfd) == 0;
379 int e = ok ? 0 : (errno ? errno : EIO);
380 close(tfd);
381 memset(k, 0, sizeof k);
382 if (ok && link(tmp, kp) != 0 && errno != EEXIST) { ok = 0; e = errno; }
383 unlink(tmp);
384 if (!ok) return jfail(j, e, "cannot create key file %s", kp, 0);
385 int dr = fsync_parent(kp);
386 if (dr) return jfail(j, -dr, "cannot sync the directory of key file %s", kp, 0);
387 fd = open(kp, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
388 }
389 if (fd < 0) return jfail(j, errno, "cannot open key file %s", kp, 0);
390 struct stat st;
391 if (fstat(fd, &st) != 0) { int e = errno; close(fd); return jfail(j, e, "cannot stat key file %s", kp, 0); }
392 if (!S_ISREG(st.st_mode) || st.st_uid != geteuid() || (st.st_mode & 0777) != 0600 || st.st_size != 32) {
393 close(fd);
394 return jfail(j, EACCES, "key file %s must be a regular file of 32 bytes, owned by you, mode 0600 (found mode %04o); refusing it", kp, (unsigned)(st.st_mode & 07777));
395 }
396 size_t got = 0;
397 while (got < 32) {
398 ssize_t r = read(fd, j->key + got, 32 - got);
399 if (r < 0 && errno == EINTR) continue;
400 if (r <= 0) { close(fd); return jfail(j, EIO, "cannot read key file %s", kp, 0); }
401 got += (size_t)r;
402 }
403 close(fd);
404 return 0;
405}
406
407int osh_journal_open(OshJournal *j, const char *path)
408{
409 memset(j, 0, sizeof *j);
410 j->fd = -1;
411 struct stat st;
412 int existed = lstat(path, &st) == 0;
413 long size = 0;
414 if (existed) {
415 if (!S_ISREG(st.st_mode) || st.st_uid != geteuid() || (st.st_mode & 07777) != 0600)
416 return jfail(j, EACCES, "journal %s must be a regular file owned by you with mode 0600 (found mode %04o); refusing it, fix or remove it", path, (unsigned)(st.st_mode & 07777));
417 size = (long)st.st_size;
418 }
419 int fd = open(path, O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW | O_CLOEXEC, 0600);
420 if (fd < 0) return jfail(j, errno, "cannot open journal %s", path, 0);
421 /* ONE SESSION PER JOURNAL: take the lock first, before the key is read or created and before recovery runs, so a live
422 * session's open intents are never reported UNKNOWN by another. The kernel drops the lock when this process exits or dies. */
423 if (flock(fd, LOCK_EX | LOCK_NB) != 0) {
424 int e = errno;
425 close(fd);
426 if (e == EWOULDBLOCK) return jfail(j, EBUSY, "journal %s is in use by another osh session (one session per journal); start this one with --journal FILE to use a separate journal", path, 0);
427 return jfail(j, e, "cannot lock journal %s", path, 0);
428 }
429 /* everything below is decided from the locked descriptor, not from the earlier lstat (another session may have created or filled the file meanwhile) */
430 if (fstat(fd, &st) != 0) { int e = errno; close(fd); return jfail(j, e, "cannot stat journal %s", path, 0); }
431 if (!S_ISREG(st.st_mode) || st.st_uid != geteuid() || (st.st_mode & 07777) != 0600) {
432 close(fd);
433 return jfail(j, EACCES, "journal %s must be a regular file owned by you with mode 0600 (found mode %04o); refusing it, fix or remove it", path, (unsigned)(st.st_mode & 07777));
434 }
435 size = (long)st.st_size;
436 int krc = load_key(j, path, size > 0);
437 if (krc) { close(fd); return krc; }
438 if (size == 0) { /* empty: new, so make it and its directory entry durable */
439 int rc = sync_fd(fd) == 0 ? fsync_parent(path) : -errno;
440 if (rc) { close(fd); return jfail(j, rc < 0 ? -rc : EIO, "cannot sync new journal %s", path, 0); }
441 }
442 uint64_t mx = 0;
443 int nl = 1;
444 if (size > 0) {
445 int bad = 0;
446 int rc = scan(path, max_cb, &mx, &bad, &nl);
447 if (rc && rc != -ENOENT) { close(fd); return jfail(j, -rc, "cannot read journal %s", path, 0); }
448 }
449 j->fd = fd;
450 j->next_rec = mx + 1;
451 if (!nl && commit(j, "\n", 1, 0) != 0) { int e = errno; close(fd); j->fd = -1; return jfail(j, e ? e : EIO, "cannot repair journal tail %s", path, 0); }
452 return 0;
453}
454
455/* a state directory made by an earlier run must be ours and private; otherwise refuse (0 ok, -EACCES with why) */
456int osh_journal_check_dir(OshJournal *j, const char *dir)
457{
458 struct stat st;
459 if (stat(dir, &st) != 0) return jfail(j, errno, "cannot stat state directory %s", dir, 0);
460 if (!S_ISDIR(st.st_mode) || st.st_uid != geteuid() || (st.st_mode & 077) != 0)
461 return jfail(j, EACCES, "state directory %s must be owned by you with mode 0700 (found mode %04o); refusing it, fix it with chmod 700", dir, (unsigned)(st.st_mode & 07777));
462 return 0;
463}
464
465void osh_journal_close(OshJournal *j)
466{
467 if (j->fd >= 0) close(j->fd);
468 j->fd = -1;
469 memset(j->key, 0, sizeof j->key);
470}
471
472/* ---- records ---- */
473
474static void esc(const char *s, char *out, size_t cap)
475{
476 size_t o = 0, n = strlen(s);
477 if (!n) { snprintf(out, cap, "%%"); return; } /* an empty argv[0] */
478 size_t from = n > 64 ? n - 64 : 0; /* keep the LAST 64 bytes: the program name matters, not its directory */
479 if (from && o + 1 < cap) out[o++] = '~';
480 for (size_t i = from; i < n && o + 4 < cap; i++) {
481 unsigned char c = (unsigned char)s[i];
482 if (isalnum(c) || c == '.' || c == '_' || c == '/' || c == '-' || c == '+') out[o++] = (char)c;
483 else o += (size_t)snprintf(out + o, cap - o, "%%%02X", c);
484 }
485 out[o] = 0;
486}
487
488uint64_t osh_journal_intent(OshJournal *j, const uint8_t dig[32], const OshRequest *r, int idx)
489{
490 const OshCmd *c = &r->cmd[idx];
491 char dh[65], a0[200], lens[OSH_MAX_ARGV * 6 + 4], line[1024];
492 hex(dig, dh);
493 esc(c->nargv > 0 ? c->argv[0] : "", a0, sizeof a0);
494 size_t lo = 0;
495 for (int k = 0; k < c->nargv; k++) lo += (size_t)snprintf(lens + lo, sizeof lens - lo, "%s%zu", k ? "," : "", strlen(c->argv[k]));
496 if (!lo) strcpy(lens, "-");
497 int wr = 0;
498 for (int k = 0; k < c->nredir; k++) wr += c->redir[k].kind == OSH_R_OUT || c->redir[k].kind == OSH_R_APPEND;
499 uint64_t rec = j->next_rec;
500 int n = snprintf(line, sizeof line, "OSHJ1 %llu I %s %d/%d b=%d argc=%d wr=%d a0=%s lens=%s\n", (unsigned long long)rec, dh, idx,
501 r->ncmds, c->builtin_id, c->nargv, wr, a0, lens);
502 if (n <= 0 || (size_t)n >= sizeof line) return 0;
503 if (commit(j, line, (size_t)n, 0) != 0) return 0;
504 j->next_rec++;
505#ifdef OSH_JOURNAL_TEST_HOOKS
506 if (j->die_after_intent && ++j->n_intent == j->die_after_intent) _exit(77);
507#endif
508 return rec;
509}
510
511int osh_journal_outcomes(OshJournal *j, const uint8_t dig[32], int ncmds, const OshJournalOutcome *o, int n)
512{
513 if (n <= 0) return 0;
514 char dh[65];
515 hex(dig, dh);
516 char *buf = malloc((size_t)n * 160 + 1);
517 if (!buf) return -1;
518 size_t len = 0;
519 uint64_t rec = j->next_rec;
520 for (int i = 0; i < n; i++) {
521 int oc = o[i].outcome;
522 if (oc < 0 || oc > 4) oc = 4;
523 len += (size_t)snprintf(buf + len, 160, "OSHJ1 %llu O %llu %s %d/%d %s st=%d err=%d\n", (unsigned long long)rec++,
524 (unsigned long long)o[i].ref, dh, o[i].idx, ncmds, k_outcome[oc], o[i].status, o[i].err);
525 }
526 int rc = commit(j, buf, len, 1);
527 free(buf);
528 if (rc != 0) return -1;
529 j->next_rec = rec;
530 return 0;
531}
532
533/* ---- recovery ---- */
534
535typedef struct {
536 Line *open;
537 int n, cap;
538 uint64_t *closed;
539 int nclosed, capclosed;
540} Rec;
541
542static void rec_cb(void *ctx, const Line *l)
543{
544 Rec *r = ctx;
545 if (l->kind == 'I') {
546 if (r->n == r->cap) {
547 int nc = r->cap ? r->cap * 2 : 64;
548 Line *p = realloc(r->open, (size_t)nc * sizeof *p);
549 if (!p) return;
550 r->open = p;
551 r->cap = nc;
552 }
553 r->open[r->n++] = *l;
554 } else if (l->ref) {
555 if (r->nclosed == r->capclosed) {
556 int nc = r->capclosed ? r->capclosed * 2 : 64;
557 uint64_t *p = realloc(r->closed, (size_t)nc * sizeof *p);
558 if (!p) return;
559 r->closed = p;
560 r->capclosed = nc;
561 }
562 r->closed[r->nclosed++] = l->ref;
563 }
564}
565
566int osh_journal_recover(OshJournal *j, const char *path, OshJournalUnknown *out, int cap, int *bad)
567{
568 Rec r;
569 memset(&r, 0, sizeof r);
570 int nb = 0;
571 int rc = scan(path, rec_cb, &r, &nb, NULL);
572 if (bad) *bad = nb;
573 if (rc) { free(r.open); free(r.closed); return rc; }
574 int found = 0;
575 for (int i = 0; i < r.n; i++) {
576 int closed = 0;
577 for (int k = 0; k < r.nclosed && !closed; k++) closed = r.closed[k] == r.open[i].rec;
578 if (closed) continue;
579 if (out && found < cap) {
580 OshJournalUnknown *u = &out[found];
581 u->intent_rec = r.open[i].rec;
582 memcpy(u->digest, r.open[i].digest, 65);
583 u->idx = r.open[i].idx;
584 u->ncmds = r.open[i].ncmds;
585 snprintf(u->argv0, sizeof u->argv0, "%s", r.open[i].a0);
586 }
587 found++;
588 char line[256];
589 int n = snprintf(line, sizeof line, "OSHJ1 %llu O %llu %s %d/%d OUTCOME_UNKNOWN st=-1 err=%d recovered=1\n",
590 (unsigned long long)j->next_rec, (unsigned long long)r.open[i].rec, r.open[i].digest, r.open[i].idx,
591 r.open[i].ncmds, OSH_E_OUTCOME_UNKNOWN);
592 if (commit(j, line, (size_t)n, 1) != 0) { found = -EIO; break; }
593 j->next_rec++;
594 }
595 free(r.open);
596 free(r.closed);
597 return found;
598}
599
600/* ---- default location ---- */
601
602int osh_journal_default_path(const char *xdg, const char *home, char *out, size_t cap)
603{
604 int n;
605 if (xdg && xdg[0] == '/') n = snprintf(out, cap, "%s/osh/effects.journal", xdg);
606 else if (home && home[0] == '/') n = snprintf(out, cap, "%s/.local/state/osh/effects.journal", home);
607 else return -1;
608 return n > 0 && (size_t)n < cap ? 0 : -1;
609}
610
611int osh_journal_mkparents(const char *path)
612{
613 char d[4096];
614 if (strlen(path) >= sizeof d) return -ENAMETOOLONG;
615 strcpy(d, path);
616 char *last = strrchr(d, '/');
617 if (!last) return 0;
618 *last = 0;
619 for (char *p = d + 1; ; p++) {
620 if (*p == '/' || *p == 0) {
621 char c = *p;
622 *p = 0;
623 if (mkdir(d, 0700) == 0) { /* newly created: make it and its place in the parent durable */
624 int dfd = open(d, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
625 if (dfd < 0) return -errno;
626 int sr = sync_fd(dfd) == 0 ? 0 : -errno;
627 close(dfd);
628 if (sr) return sr;
629 int pr = fsync_parent(d);
630 if (pr) return pr;
631 } else if (errno != EEXIST) return -errno;
632 *p = c;
633 if (!c) break;
634 }
635 }
636 return 0;
637}
638
639#ifdef OSH_JOURNAL_TEST_HOOKS
640/* marker symbol: the build checks the shipped osh does NOT contain it (so no test hook is compiled into production) */
641int osh_journal_test_hooks_compiled(void) { return 1; }
642#endif