From d7a61a1bd5eea7f754f71ad801d8ba9536467516 Mon Sep 17 00:00:00 2001 From: lotherk Date: Mon, 23 Nov 2026 01:23:25 +0000 Subject: [PATCH] builtin: write and edit can no longer truncate the file they replace fopen(path, "w") truncates before the new text exists, so a short write (a full disk - seen in a live session as "No space left on device" - or RLIMIT_FSIZE) left the operator with an empty file and no copy. The old code also reported success: the error arrived in fclose(), which was ignored. Both tools now share write_atomic(): temp file, fflush, fsync, rename. A symlink is resolved first, because rename() would otherwise replace the link instead of writing through it and silently detach a dotfile setup. The mode of an existing file is kept. test_builtin makes the short write deterministic with RLIMIT_FSIZE: without the fix it reports success and the original is gone (FAIL "error:" and "wichtig"), with it the file is untouched and no .tmp debris is left. A second case pins the symlink: the link survives, the target gets the new text (FAIL S_ISLNK and the target content without resolve_target). make check: all tests passed; check_asan: 45 binaries clean. --- README.md | 8 +- src/backend/builtin.c | 181 +++++++++++++++++++++++++++++++----------- tests/test_builtin.c | 77 ++++++++++++++++++ 3 files changed, 217 insertions(+), 49 deletions(-) diff --git a/README.md b/README.md index 377a98b..02d55a8 100644 --- a/README.md +++ b/README.md @@ -1010,9 +1010,13 @@ the prompt. where it stopped. - `search` (read): literal string over a directory tree, capped at 100 hits. - `list` (read): a directory. -- `write` (mutate): writes a file, up to 4 MiB. +- `write` (mutate): writes a file, up to 4 MiB. The new text goes to a sibling + `.tmp` and is renamed over the target, so a full disk or a crash can never + leave the old file truncated; a symlink is followed and stays a symlink, and + the mode of an existing file is kept. - `edit` (mutate): replaces exactly one occurrence; a non-unique `old` is an - error, because an ambiguous edit is a wrong edit waiting to happen. + error, because an ambiguous edit is a wrong edit waiting to happen. Written + the same way as `write`, atomically. - `run` (destructive): a shell command; the exit status is an observation. Its own process group, stdin `/dev/null`, an environment without splinter's API keys and tokens, so `run env` cannot hand them to the model. It is killed diff --git a/src/backend/builtin.c b/src/backend/builtin.c index 5128da1..1957d3f 100644 --- a/src/backend/builtin.c +++ b/src/backend/builtin.c @@ -301,6 +301,124 @@ tool_run(const char *args, struct sp_buf *out, void *ctx) static int count_lines(const char *s, size_t upto); static char *slurp(const char *path, size_t *lenp, struct sp_buf *err); +/* + * Follow a chain of symlinks to the file that will actually be replaced. + * + * rename(2) replaces the link, not what it points at, while the old + * fopen(path, "w") went through it. Without this step a write to + * ~/.splinter/splinter.conf -> ~/dotfiles/... would quietly turn the link into + * a plain file and leave the real config untouched - the exact opposite of what + * the operator asked for. A dangling link is followed to its (then created) + * target, which is also what fopen("w") did. + */ +static int +resolve_target(const char *path, char *out, size_t cap) +{ + char cur[1024], link[1024], tmp[1024]; + size_t hops; + + if (path == NULL || strlen(path) + 1 > sizeof(cur)) + return -1; + snprintf(cur, sizeof(cur), "%s", path); + for (hops = 0; hops < 16; hops++) { + struct stat st; + ssize_t n; + + if (lstat(cur, &st) != 0 || !S_ISLNK(st.st_mode)) + break; + n = readlink(cur, link, sizeof(link) - 1); + if (n <= 0) + return -1; + link[n] = '\0'; + if (link[0] == '/') { + n = snprintf(tmp, sizeof(tmp), "%s", link); + } else { + char *slash = strrchr(cur, '/'); + + if (slash == NULL) + n = snprintf(tmp, sizeof(tmp), "%s", link); + else + n = snprintf(tmp, sizeof(tmp), "%.*s/%s", + (int)(slash - cur), cur, link); + } + if (n < 0 || (size_t)n >= sizeof(tmp)) + return -1; + if ((size_t)n >= sizeof(cur)) + return -1; + snprintf(cur, sizeof(cur), "%s", tmp); + } + if (strlen(cur) + 1 > cap) + return -1; + snprintf(out, cap, "%s", cur); + return 0; +} + +/* + * Replace a file's content without ever leaving it half written. + * + * fopen(path, "w") truncates first: a disk that fills up, a write that is cut + * short or a crash between the two leaves the operator with an empty or + * truncated file and no way back - the old text is gone before the new one + * exists. So the new content goes to a sibling ".tmp", is flushed to disk, and + * only then is renamed over the target: rename(2) is atomic, so a reader sees + * either the old file or the new one, never a torn one. On any failure the + * temp file is unlinked and the original is left exactly as it was. + * + * The mode of an existing file is kept (a 0600 file must not become 0644 just + * because a tool wrote it); a new file gets the usual 0666 masked by umask. + */ +static int +write_atomic(const char *path, const char *text, size_t n, struct sp_buf *err) +{ + char real[1024], tmp[1024]; + struct stat st; + int have = 0, fd; + FILE *f; + + if (resolve_target(path, real, sizeof(real)) != 0) + return sp_buf_puts(err, "error: path is too long"); + if (strlen(real) + 5 > sizeof(tmp)) + return sp_buf_puts(err, "error: path is too long"); + snprintf(tmp, sizeof(tmp), "%s.tmp", real); + have = stat(real, &st) == 0; + fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC, have ? 0600 : 0666); + if (fd < 0) { + sp_buf_printf(err, "error: %s: %s", tmp, strerror(errno)); + return -1; + } + if (have && fchmod(fd, st.st_mode & 07777) != 0) { + sp_buf_printf(err, "error: %s: %s", tmp, strerror(errno)); + (void)close(fd); + (void)unlink(tmp); + return -1; + } + f = fdopen(fd, "w"); + if (f == NULL) { + sp_buf_printf(err, "error: %s: %s", tmp, strerror(errno)); + (void)close(fd); + (void)unlink(tmp); + return -1; + } + if ((n > 0 && fwrite(text, 1, n, f) != n) || fflush(f) != 0 || + fsync(fileno(f)) != 0) { + sp_buf_printf(err, "error: short write: %s", strerror(errno)); + (void)fclose(f); /* closes fd */ + (void)unlink(tmp); + return -1; + } + if (fclose(f) != 0) { + sp_buf_printf(err, "error: %s: %s", tmp, strerror(errno)); + (void)unlink(tmp); + return -1; + } + if (rename(tmp, real) != 0) { + sp_buf_printf(err, "error: %s: %s", real, strerror(errno)); + (void)unlink(tmp); + return -1; + } + return 0; +} + static int arg_int(const char *args, const char *key, int dflt) { @@ -525,7 +643,6 @@ tool_write(const char *args, struct sp_buf *out, void *ctx) { struct sp_buf keep, content; const char *path, *text; - FILE *f; size_t n; (void)ctx; @@ -548,31 +665,25 @@ tool_write(const char *args, struct sp_buf *out, void *ctx) } { /* the previous content, only to show what changed */ - size_t oldlen = 0; - char *old = NULL; - FILE *prev = fopen(path, "r"); + struct sp_buf scraperr; + size_t oldlen = 0; + char *old = NULL; - if (prev != NULL) { - old = slurp(path, &oldlen, out); - fclose(prev); + /* + * The old text is a courtesy, not a precondition: slurp() fails + * on a binary or oversized file, and that message belongs + * nowhere near the write result - a scratch buffer swallows it. + */ + if (sp_buf_init(&scraperr) == 0) { + old = slurp(path, &oldlen, &scraperr); + sp_buf_free(&scraperr); } - f = fopen(path, "w"); - if (f == NULL) { - sp_buf_printf(out, "error: %s: %s", path, strerror(errno)); + if (write_atomic(path, text, n, out) != 0) { free(old); sp_buf_free(&keep); sp_buf_free(&content); return 0; } - if (n > 0 && fwrite(text, 1, n, f) != n) { - sp_buf_printf(out, "error: short write: %s", strerror(errno)); - fclose(f); - free(old); - sp_buf_free(&keep); - sp_buf_free(&content); - return 0; - } - fclose(f); sp_buf_printf(out, "wrote %zu bytes to %s\n", n, path); emit_diff(out, path, old != NULL ? old : "", text); free(old); @@ -580,18 +691,6 @@ tool_write(const char *args, struct sp_buf *out, void *ctx) sp_buf_free(&content); return 0; } - if (n > 0 && fwrite(text, 1, n, f) != n) { - sp_buf_printf(out, "error: short write: %s", strerror(errno)); - fclose(f); - sp_buf_free(&keep); - sp_buf_free(&content); - return 0; - } - fclose(f); - sp_buf_printf(out, "wrote %zu bytes to %s", n, path); - sp_buf_free(&keep); - sp_buf_free(&content); - return 0; } /* Read a whole file into memory; NULL when it is too large or binary. */ @@ -660,7 +759,6 @@ tool_edit(const char *args, struct sp_buf *out, void *ctx) char *text, *hit, *result; size_t len, oldlen, newlen, prefix; int count; - FILE *f; (void)ctx; if (sp_buf_init(&keep) != 0 || sp_buf_init(&bufs[0]) != 0 || @@ -719,21 +817,10 @@ tool_edit(const char *args, struct sp_buf *out, void *ctx) len - prefix - oldlen); result[len - oldlen + newlen] = '\0'; - f = fopen(path, "w"); - if (f == NULL) { - sp_buf_printf(out, "error: %s: %s", path, strerror(errno)); - } else { - size_t outlen = len - oldlen + newlen; - - if (fwrite(result, 1, outlen, f) != outlen) - sp_buf_printf(out, "error: short write: %s", - strerror(errno)); - else { - sp_buf_printf(out, "edited %s (line %d)\n", path, - 1 + count_lines(text, prefix)); - emit_diff(out, path, text, result); - } - fclose(f); + if (write_atomic(path, result, len - oldlen + newlen, out) == 0) { + sp_buf_printf(out, "edited %s (line %d)\n", path, + 1 + count_lines(text, prefix)); + emit_diff(out, path, text, result); } free(result); free(text); diff --git a/tests/test_builtin.c b/tests/test_builtin.c index fce0caf..bb6fbb6 100644 --- a/tests/test_builtin.c +++ b/tests/test_builtin.c @@ -6,9 +6,11 @@ * an ambiguous edit, a binary file, a write that is too large. */ #include +#include #include #include #include +#include #include #include @@ -126,6 +128,81 @@ main(void) CHECK(tool(&r, "read")->run(big, &out, NULL) == 0); CHECK(strstr(out.p, "y") == NULL); /* nothing was written */ + /* + * ---- a write that cannot finish must not eat the old file ---- + * + * The tools used to truncate with fopen(path, "w") and then write, so a + * short write (a full disk, RLIMIT_FSIZE) left the operator with an + * empty file and no copy. RLIMIT_FSIZE makes the short write + * deterministic; SIGXFSZ is ignored so the write returns EFBIG instead + * of killing the test. + */ + { + struct rlimit rl; + struct sigaction sa, oldsa; + char safe[700], big2[1600]; + + snprintf(safe, sizeof(safe), "%s/keep.txt", dir); + write_file(safe, "wichtig\n"); + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = SIG_IGN; + sigemptyset(&sa.sa_mask); + CHECK(sigaction(SIGXFSZ, &sa, &oldsa) == 0); + CHECK(getrlimit(RLIMIT_FSIZE, &rl) == 0); + { + struct rlimit lim = rl; + + lim.rlim_cur = 4; /* fewer bytes than the new text */ + CHECK(setrlimit(RLIMIT_FSIZE, &lim) == 0); + } + sp_buf_clear(&out); + snprintf(big2, sizeof(big2), + "{\"path\":\"%s\",\"content\":\"0123456789\"}", safe); + CHECK(tool(&r, "write")->run(big2, &out, NULL) == 0); + CHECK(strstr(out.p, "error:") != NULL); + CHECK(setrlimit(RLIMIT_FSIZE, &rl) == 0); + CHECK(sigaction(SIGXFSZ, &oldsa, NULL) == 0); + + /* the original is untouched, byte for byte */ + sp_buf_clear(&out); + snprintf(big2, sizeof(big2), "{\"path\":\"%s\"}", safe); + CHECK(tool(&r, "read")->run(big2, &out, NULL) == 0); + CHECK(strstr(out.p, "wichtig") != NULL); + CHECK(strstr(out.p, "0123456789") == NULL); + + /* and no debris was left behind */ + snprintf(big2, sizeof(big2), "%s.tmp", safe); + CHECK(access(big2, F_OK) != 0); + } + + /* + * ---- a write through a symlink writes the target, not the link ---- + * + * The old fopen(path, "w") went through the link; a temp file plus + * rename() replaces the link instead, which would silently detach a + * dotfile setup. Both must agree: the link stays, the target changes. + */ + { + char real[700], link[700], big2[1600]; + struct stat st; + + snprintf(real, sizeof(real), "%s/real.conf", dir); + snprintf(link, sizeof(link), "%s/link.conf", dir); + write_file(real, "alt\n"); + if (symlink(real, link) == 0) { + sp_buf_clear(&out); + snprintf(big2, sizeof(big2), + "{\"path\":\"%s\",\"content\":\"neu\\n\"}", link); + CHECK(tool(&r, "write")->run(big2, &out, NULL) == 0); + CHECK(lstat(link, &st) == 0); + CHECK(S_ISLNK(st.st_mode)); /* still a link */ + sp_buf_clear(&out); + snprintf(big2, sizeof(big2), "{\"path\":\"%s\"}", real); + CHECK(tool(&r, "read")->run(big2, &out, NULL) == 0); + CHECK(strstr(out.p, "neu") != NULL); /* target written */ + } + } + /* ---- read refuses a binary file ---- */ { FILE *f;