/* File history: what write and edit found in a file before they touched it, * and what they left, so a rewind can put a file back; and the restores * that do it, journaled before any file is touched and finished by whoever * next holds the conversation if pic dies part way (docs/design/rewind.md). * * A pre-image is recorded in the transaction that commits the effect as * started, so it is on disk before the tool writes; a replay keeps the first * one. The file is read before that transaction begins: no write transaction * is held across file I/O. Which files to restore, and to what, is the * rewind component's decision; this file records and enforces. */ #include #include #include #include #include #include #include "libfossil.h" #include "pic.h" #include "userdb.h" /* Hashing reads this much at a time from a file it does not keep. */ #define FH_CHUNK 65536 static int fh_fail(pic_store *s, const char *what) { (void)snprintf(s->err, sizeof s->err, "%s: %s", what, sqlite3_errmsg(s->db)); return -1; } /* Read once per process: a changed setting applies to the next request * (the terminal runs each request as a process of its own). */ long long pic_filelog_cap(void) { static long long cap = -2; if (cap == -2) { char *v = pic_setting("rewindMaxBytes"), *end = NULL; long long n = v ? strtoll(v, &end, 10) : -1; cap = v && end && end != v && !*end && n >= 0 ? n : PIC_REWIND_MAX_BYTES; free(v); } return cap; } static void fh_hex(fsl_sha3_cx *cx, char out[65]) { fsl_sha3_end(cx); (void)snprintf(out, 65, "%s", (const char *)cx->hex); } /* The host's file, hashed a chunk at a time: no copy of it in memory. */ static int fh_stream_hash(const char *path, pic_file_state *st) { char *buf = malloc(FH_CHUNK); fsl_sha3_cx cx; long long total = 0; ssize_t n = 0; int fd = buf ? open(path, O_RDONLY | O_CLOEXEC) : -1; if (fd < 0) { free(buf); return -1; } fsl_sha3_init2(&cx, FSL_SHA3_256); while ((n = read(fd, buf, FH_CHUNK)) > 0 || (n < 0 && errno == EINTR)) { if (n > 0) { fsl_sha3_update(&cx, buf, (unsigned)n); total += n; } } close(fd); free(buf); if (n < 0) { return -1; } fh_hex(&cx, st->hash); st->size = total; return 0; } void pic_file_state_read(const char *path, long long keep, pic_file_state *st) { const pic_executor *ex = pic_executor_get(); pic_file_stat fs; char *buf = NULL; size_t len = 0; int e; memset(st, 0, sizeof *st); if ((e = ex->stat(ex->state, path, &fs)) != 0) { st->exists = e != ENOENT && e != ENOTDIR; st->kept = !st->exists; return; } st->exists = 1; st->mode = fs.mode; st->size = (long long)fs.size; if (fs.is_dir) { return; /* no hash: nothing can be checked against it or put back */ } keep = keep > PIC_FILE_KEEP_MAX ? PIC_FILE_KEEP_MAX : keep; /* Only bytes to keep are read whole; the rest are hashed as a stream * (an executor of another kind can only read whole files). */ if ((keep >= 0 && st->size <= keep) || ex != pic_executor_host()) { size_t max = keep >= 0 && st->size <= keep ? (size_t)keep : (size_t)PIC_FILE_KEEP_MAX; if ((e = ex->read(ex->state, path, max, 0, &buf, &len)) == 0) { fsl_sha3_cx cx; fsl_sha3_init2(&cx, FSL_SHA3_256); fsl_sha3_update(&cx, buf, (unsigned)len); fh_hex(&cx, st->hash); st->size = (long long)len; if (keep >= 0 && (long long)len <= keep) { st->data = buf; st->kept = 1; } else { free(buf); } return; } if (e != EFBIG || ex != pic_executor_host()) { return; } } if (fh_stream_hash(path, st) != 0) { st->hash[0] = '\0'; } } void pic_file_state_free(pic_file_state *st) { free(st->data); st->data = NULL; } int pic_file_state_same(const pic_file_state *st, int exists, const char *hash) { if (!st->exists || !exists) { return st->exists == exists; } return st->hash[0] && hash && strcmp(st->hash, hash) == 0; } /* Inside a transaction: the bytes of a kept state, once per content. */ static int fh_put_blob(pic_store *s, const pic_file_state *st) { sqlite3_stmt *q = NULL; int step; if (!st->exists || !st->kept || !st->hash[0]) { return 0; } if (sqlite3_prepare_v2(s->db, "INSERT OR IGNORE INTO pic_blob(hash, sz, data) VALUES(?1, length(?2), sqlar_compress(?2))", -1, &q, NULL) != SQLITE_OK) { return fh_fail(s, "pre-image"); } sqlite3_bind_text(q, 1, st->hash, -1, SQLITE_STATIC); sqlite3_bind_blob64(q, 2, st->data ? st->data : "", (sqlite3_uint64)st->size, SQLITE_STATIC); step = sqlite3_step(q); sqlite3_finalize(q); return step == SQLITE_DONE ? 0 : fh_fail(s, "pre-image"); } /* Binds a state's pre_ columns at FIRST (exists, mode, size, hash, kept). */ static void fh_bind_state(sqlite3_stmt *q, int first, const pic_file_state *st) { sqlite3_bind_int(q, first, st->exists); if (st->exists) { sqlite3_bind_int64(q, first + 1, (sqlite3_int64)st->mode); sqlite3_bind_int64(q, first + 2, st->size); } if (st->hash[0]) { sqlite3_bind_text(q, first + 3, st->hash, -1, SQLITE_TRANSIENT); } sqlite3_bind_int(q, first + 4, st->kept); } int pic_filelog_recorded(pic_store *s, sqlite3_int64 effect) { sqlite3_stmt *q = NULL; int has; if (sqlite3_prepare_v2(s->db, "SELECT EXISTS (SELECT 1 FROM pic_file_change WHERE effect_id = ?)", -1, &q, NULL) != SQLITE_OK) { return fh_fail(s, "pre-image"); } sqlite3_bind_int64(q, 1, effect); has = sqlite3_step(q) == SQLITE_ROW ? sqlite3_column_int(q, 0) : -1; sqlite3_finalize(q); return has < 0 ? fh_fail(s, "pre-image") : has; } int pic_filelog_before(pic_store *s, sqlite3_int64 effect, const char *path, const pic_file_state *pre) { sqlite3_stmt *q = NULL; int step; if (fh_put_blob(s, pre) != 0 || sqlite3_prepare_v2(s->db, "INSERT OR IGNORE INTO pic_file_change(effect_id, path, pre_exists, pre_mode, pre_size, pre_hash," " pre_kept) VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7)", -1, &q, NULL) != SQLITE_OK) { return s->err[0] ? -1 : fh_fail(s, "pre-image"); } sqlite3_bind_int64(q, 1, effect); sqlite3_bind_text(q, 2, path, -1, SQLITE_STATIC); fh_bind_state(q, 3, pre); step = sqlite3_step(q); sqlite3_finalize(q); return step == SQLITE_DONE ? 0 : fh_fail(s, "pre-image"); } int pic_filelog_after(pic_store *s, sqlite3_int64 effect, const pic_file_state *post) { sqlite3_stmt *q = NULL; int step; if (sqlite3_prepare_v2(s->db, "UPDATE pic_file_change SET post_exists = ?2, post_mode = ?3, post_hash = ?4 WHERE effect_id = ?1", -1, &q, NULL) != SQLITE_OK) { return fh_fail(s, "post-image"); } sqlite3_bind_int64(q, 1, effect); sqlite3_bind_int(q, 2, post->exists); if (post->exists) { sqlite3_bind_int64(q, 3, (sqlite3_int64)post->mode); } if (post->hash[0]) { sqlite3_bind_text(q, 4, post->hash, -1, SQLITE_STATIC); } step = sqlite3_step(q); sqlite3_finalize(q); return step == SQLITE_DONE ? 0 : fh_fail(s, "post-image"); } /* ---- restores ------------------------------------------------------------- */ static int fh_make_parents(const pic_executor *ex, const char *path) { char *p = strdup(path); int rc = 0; if (!p) { return ENOMEM; } for (char *c = strchr(p + 1, '/'); c && rc == 0; c = strchr(c + 1, '/')) { *c = '\0'; rc = ex->mkdir(ex->state, p); rc = rc == EEXIST ? 0 : rc; *c = '/'; } free(p); return rc; } /* One file of a restore, as journaled. */ typedef struct { sqlite3_int64 id; char *path, *pre_hash, *post_hash; int pre_exists, post_exists; unsigned post_mode; const char *outcome; } fh_row; static void fh_rows_free(fh_row *rows, size_t n) { for (size_t i = 0; i < n; i++) { free(rows[i].path); free(rows[i].pre_hash); free(rows[i].post_hash); } free(rows); } static char *fh_dup(sqlite3_stmt *q, int col) { const char *t = (const char *)sqlite3_column_text(q, col); return t ? strdup(t) : NULL; } /* The bytes of a stored state (malloc'd), or NULL. */ static char *fh_blob(pic_store *s, const char *hash, size_t *len) { sqlite3_stmt *q = NULL; char *out = NULL; if (sqlite3_prepare_v2(s->db, "SELECT sqlar_uncompress(data, sz) FROM pic_blob WHERE hash = ?", -1, &q, NULL) != SQLITE_OK) { return NULL; } sqlite3_bind_text(q, 1, hash, -1, SQLITE_STATIC); if (sqlite3_step(q) == SQLITE_ROW) { size_t n = (size_t)sqlite3_column_bytes(q, 0); if ((out = malloc(n + 1))) { if (n) { memcpy(out, sqlite3_column_blob(q, 0), n); } out[n] = '\0'; *len = n; } } sqlite3_finalize(q); return out; } /* Puts one file back, outside any transaction: nothing when it already is * as the restore leaves it, the restore's state when it is still as the * restore found it, and never over anything else. The bytes and the * directories are made ready first, so between the last look at the file * and the rename that replaces it there is only the write of a temporary * file: POSIX has no compare-and-replace, and a change in that window is * overwritten (docs/design/rewind.md). */ static void fh_apply_one(pic_store *s, fh_row *r) { const pic_executor *ex = pic_executor_get(); pic_file_state now; char *bytes = NULL; size_t len = 0; int e = 0; if (r->outcome) { /* refused when it was journaled */ return; } if (r->post_exists) { bytes = r->post_hash ? fh_blob(s, r->post_hash, &len) : NULL; e = !bytes ? ENOENT : fh_make_parents(ex, r->path); } pic_file_state_read(r->path, -1, &now); if (pic_file_state_same(&now, r->post_exists, r->post_hash)) { /* Put back already (by an attempt a crash cut short), or never moved. */ r->outcome = pic_file_state_same(&now, r->pre_exists, r->pre_hash) ? "unchanged" : "restored"; free(bytes); return; } if (!pic_file_state_same(&now, r->pre_exists, r->pre_hash)) { r->outcome = "changed"; free(bytes); return; } if (e == 0) { if (!r->post_exists) { e = ex->remove(ex->state, r->path); e = e == ENOENT ? 0 : e; } else { e = ex->write(ex->state, r->path, bytes, len, r->post_mode ? r->post_mode : 0644); } } free(bytes); r->outcome = e ? "failed" : "restored"; if (!e) { pic_fault("restore-wrote"); } } /* Applies restore ID's files and marks it done, forking its conversation in * the same transaction when it asks for that. */ static int fh_finish(pic_store *s, sqlite3_int64 id, pic_restore_result *out) { sqlite3_stmt *q = NULL; fh_row *rows = NULL; size_t n = 0; char session[64] = "", forked[64] = ""; sqlite3_int64 fork_at = -1; int has_fork = 0, rc = 0, step; if (sqlite3_prepare_v2(s->db, "SELECT session_id, fork_at, forked IS NOT NULL, coalesce(forked, '') FROM pic_restore WHERE id = ?", -1, &q, NULL) != SQLITE_OK) { return fh_fail(s, "restore"); } sqlite3_bind_int64(q, 1, id); if (sqlite3_step(q) == SQLITE_ROW) { (void)snprintf(session, sizeof session, "%s", (const char *)sqlite3_column_text(q, 0)); fork_at = sqlite3_column_type(q, 1) == SQLITE_NULL ? -1 : sqlite3_column_int64(q, 1); has_fork = sqlite3_column_int(q, 2); (void)snprintf(forked, sizeof forked, "%s", (const char *)sqlite3_column_text(q, 3)); } sqlite3_finalize(q); if (sqlite3_prepare_v2(s->db, "SELECT id, path, pre_exists, pre_hash, coalesce(post_exists, 0), coalesce(post_mode, 0), post_hash," " outcome = 'changed' FROM pic_file_change WHERE restore_id = ? ORDER BY id", -1, &q, NULL) != SQLITE_OK) { return fh_fail(s, "restore"); } sqlite3_bind_int64(q, 1, id); while ((step = sqlite3_step(q)) == SQLITE_ROW) { fh_row *grown = realloc(rows, (n + 1) * sizeof *rows); if (!grown) { rc = -1; break; } rows = grown; memset(&rows[n], 0, sizeof rows[n]); rows[n].id = sqlite3_column_int64(q, 0); rows[n].path = fh_dup(q, 1); rows[n].pre_exists = sqlite3_column_int(q, 2); rows[n].pre_hash = fh_dup(q, 3); rows[n].post_exists = sqlite3_column_int(q, 4); rows[n].post_mode = (unsigned)sqlite3_column_int64(q, 5); rows[n].post_hash = fh_dup(q, 6); rows[n].outcome = sqlite3_column_int(q, 7) ? "changed" : NULL; n++; if (!rows[n - 1].path) { rc = -1; break; } } if (rc == 0 && step != SQLITE_DONE) { rc = fh_fail(s, "restore"); } sqlite3_finalize(q); if (rc != 0) { fh_rows_free(rows, n); if (!s->err[0]) { (void)snprintf(s->err, sizeof s->err, "out of memory"); } return -1; } for (size_t i = 0; i < n; i++) { fh_apply_one(s, &rows[i]); } if (pic_begin(s) != 0) { fh_rows_free(rows, n); return -1; } for (size_t i = 0; i < n && rc == 0; i++) { if (sqlite3_prepare_v2(s->db, "UPDATE pic_file_change SET outcome = ? WHERE id = ?", -1, &q, NULL) != SQLITE_OK) { rc = fh_fail(s, "restore"); break; } sqlite3_bind_text(q, 1, rows[i].outcome, -1, SQLITE_STATIC); sqlite3_bind_int64(q, 2, rows[i].id); step = sqlite3_step(q); sqlite3_finalize(q); rc = step == SQLITE_DONE ? 0 : fh_fail(s, "restore"); } /* The conversation half: one fork, in the transaction that ends the * restore, so a crash leaves neither or both. */ if (rc == 0 && fork_at >= 0 && !has_fork) { forked[0] = '\0'; if (fork_at > 0) { rc = pic_fork(s, session, fork_at, forked, sizeof forked); } } if (rc == 0) { if (sqlite3_prepare_v2(s->db, "UPDATE pic_restore SET state = 'done', forked = CASE WHEN ?2 THEN ?3 ELSE forked END" " WHERE id = ?1", -1, &q, NULL) != SQLITE_OK) { rc = fh_fail(s, "restore"); } else { sqlite3_bind_int64(q, 1, id); sqlite3_bind_int(q, 2, fork_at >= 0 && !has_fork); sqlite3_bind_text(q, 3, forked, -1, SQLITE_STATIC); step = sqlite3_step(q); sqlite3_finalize(q); rc = step == SQLITE_DONE ? 0 : fh_fail(s, "restore"); } } if (rc != 0 || pic_commit(s) != 0) { pic_rollback(s); fh_rows_free(rows, n); return -1; } pic_fault("restore-done"); if (out) { out->id = id; out->forked = fork_at >= 0; (void)snprintf(out->conversation, sizeof out->conversation, "%s", forked); out->files = calloc(n ? n : 1, sizeof *out->files); for (size_t i = 0; out->files && i < n; i++) { out->files[i].path = rows[i].path; out->files[i].outcome = rows[i].outcome; out->files[i].deleted = !rows[i].post_exists; rows[i].path = NULL; } out->nfiles = out->files ? n : 0; } fh_rows_free(rows, n); return 0; } int pic_restore(pic_store *s, const char *session, sqlite3_int64 to_seq, sqlite3_int64 undoes, sqlite3_int64 fork_at, const pic_restore_target *t, size_t n, pic_restore_result *out) { pic_file_state *now = calloc(n ? n : 1, sizeof *now); sqlite3_stmt *q = NULL; sqlite3_int64 id = 0; int rc = 0, step; if (out) { memset(out, 0, sizeof *out); } if (!now) { (void)snprintf(s->err, sizeof s->err, "out of memory"); return -1; } /* What each file is now, read before the restore's transaction: its * guard, and what an undo puts back, kept whatever its size (the * rewindMaxBytes cap is for every write; a restore is rare). One file in * memory at a time: each one's bytes are stored in a transaction of * their own (an orphan after a crash is only a duplicate-free extra). */ for (size_t i = 0; i < n && rc == 0; i++) { pic_file_state_read(t[i].path, PIC_FILE_KEEP_MAX, &now[i]); if (now[i].data) { if (pic_begin(s) != 0 || fh_put_blob(s, &now[i]) != 0 || pic_commit(s) != 0) { pic_rollback(s); rc = -1; } } pic_file_state_free(&now[i]); } if (rc != 0) { free(now); return -1; } if (pic_begin(s) != 0) { rc = -1; } else if (sqlite3_prepare_v2(s->db, "INSERT INTO pic_restore(session_id, to_seq, undoes, fork_at, state, created_ms)" " VALUES(?1, nullif(?2, 0), nullif(?3, 0), nullif(?4, -1), 'started'," " CAST(unixepoch('subsec') * 1000 AS INTEGER))", -1, &q, NULL) != SQLITE_OK) { rc = fh_fail(s, "restore"); } else { sqlite3_bind_text(q, 1, session, -1, SQLITE_STATIC); sqlite3_bind_int64(q, 2, to_seq); sqlite3_bind_int64(q, 3, undoes); sqlite3_bind_int64(q, 4, fork_at); step = sqlite3_step(q); sqlite3_finalize(q); rc = step == SQLITE_DONE ? 0 : fh_fail(s, "restore"); id = sqlite3_last_insert_rowid(s->db); } for (size_t i = 0; rc == 0 && i < n; i++) { if (sqlite3_prepare_v2(s->db, "INSERT INTO pic_file_change(restore_id, path, pre_exists, pre_mode, pre_size, pre_hash, pre_kept," " post_exists, post_mode, post_hash, outcome) VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10," " CASE WHEN ?11 THEN 'changed' END)", -1, &q, NULL) != SQLITE_OK) { rc = s->err[0] ? -1 : fh_fail(s, "restore"); break; } sqlite3_bind_int64(q, 1, id); sqlite3_bind_text(q, 2, t[i].path, -1, SQLITE_STATIC); fh_bind_state(q, 3, &now[i]); sqlite3_bind_int(q, 8, t[i].exists); if (t[i].exists) { sqlite3_bind_int64(q, 9, (sqlite3_int64)t[i].mode); sqlite3_bind_text(q, 10, t[i].hash, -1, SQLITE_STATIC); } /* Not what the component checked, or not keepable for an undo: left. */ sqlite3_bind_int(q, 11, !pic_file_state_same(&now[i], t[i].expect_exists, t[i].expect_hash) || (now[i].exists && !now[i].kept)); step = sqlite3_step(q); sqlite3_finalize(q); rc = step == SQLITE_DONE ? 0 : fh_fail(s, "restore"); } for (size_t i = 0; i < n; i++) { pic_file_state_free(&now[i]); } free(now); if (rc != 0 || pic_commit(s) != 0) { pic_rollback(s); return -1; } pic_fault("restore-planned"); return fh_finish(s, id, out); } int pic_restore_resume(pic_store *s, const char *session) { for (;;) { sqlite3_stmt *q = NULL; sqlite3_int64 id = 0; if (sqlite3_prepare_v2(s->db, "SELECT id FROM pic_restore WHERE state = 'started' AND session_id = ? ORDER BY id LIMIT 1", -1, &q, NULL) != SQLITE_OK) { return fh_fail(s, "restore"); } sqlite3_bind_text(q, 1, session, -1, SQLITE_STATIC); if (sqlite3_step(q) == SQLITE_ROW) { id = sqlite3_column_int64(q, 0); } sqlite3_finalize(q); if (!id) { return 0; } if (fh_finish(s, id, NULL) != 0) { return -1; } } } void pic_restore_result_free(pic_restore_result *r) { for (size_t i = 0; i < r->nfiles; i++) { free(r->files[i].path); } free(r->files); memset(r, 0, sizeof *r); }