/* Rewind: back to an earlier user message, restoring the conversation (a
* fork at the entry before it, as /fork does), the files write and edit
* changed after it (their pre-images, from the file history core keeps), or
* both. This file decides which files and what they go back to, and when to
* refuse; core journals the restore and finishes it after a crash
* (filelog.c). Changes made by bash or outside pic are not tracked. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "pic.h"
#include "rewind.h"
/* ?1 is the conversation: p is every entry on its path. */
#define RW_PATH \
"WITH RECURSIVE p(seq) AS (SELECT head_seq FROM pic_session WHERE id = ?1" \
" UNION ALL SELECT e.parent_seq FROM pic_entry e JOIN p ON e.seq = p.seq WHERE e.parent_seq IS NOT NULL) "
/* The user messages a rewind can go back to: on the path, not a "!" command. */
#define RW_MESSAGE(e) e ".seq IN p AND " e ".kind = 'user' AND NOT EXISTS (SELECT 1 FROM pic_bash b WHERE b.entry_seq = " e ".seq)"
static int rw_fail(pic_store *s) {
(void)snprintf(s->err, sizeof s->err, "sql: %s", sqlite3_errmsg(s->db));
return -1;
}
static char *rw_dup(sqlite3_stmt *q, int col) {
const char *t = (const char *)sqlite3_column_text(q, col);
return t ? strdup(t) : NULL;
}
int pic_rewind_points(pic_store *s, const char *session, FILE *out) {
sqlite3_stmt *q = NULL;
char sid[64];
int step;
if (pic_session_resolve(s, session, sid, sizeof sid) != 0) {
return -1;
}
if (sqlite3_prepare_v2(s->db,
RW_PATH "SELECT json_object('entry', e.seq, 'text', e.body, 'files', (SELECT count(DISTINCT c.path)"
" FROM pic_file_change c JOIN pic_effect f ON f.id = c.effect_id"
" WHERE f.entry_seq IN p AND f.entry_seq > e.seq))"
" FROM pic_entry e WHERE " RW_MESSAGE("e") " ORDER BY e.seq DESC",
-1, &q, NULL) != SQLITE_OK) {
return rw_fail(s);
}
sqlite3_bind_text(q, 1, sid, -1, SQLITE_STATIC);
while ((step = sqlite3_step(q)) == SQLITE_ROW) {
fprintf(out, "%s\n", (const char *)sqlite3_column_text(q, 0));
}
sqlite3_finalize(q);
return step == SQLITE_DONE ? 0 : rw_fail(s);
}
/* One file a rewind would put back: what it goes back to, and what the
* conversation last left there. */
typedef struct {
char *path, *hash, *expect_hash;
int exists, kept, has_hash, expect_known, expect_exists;
unsigned mode;
} rw_file;
typedef struct {
rw_file *v;
size_t n;
} rw_files;
static void rw_files_free(rw_files *f) {
for (size_t i = 0; i < f->n; i++) {
free(f->v[i].path);
free(f->v[i].hash);
free(f->v[i].expect_hash);
}
free(f->v);
f->v = NULL;
f->n = 0;
}
static rw_file *rw_find(rw_files *f, const char *path) {
for (size_t i = 0; i < f->n; i++) {
if (strcmp(f->v[i].path, path) == 0) {
return &f->v[i];
}
}
return NULL;
}
/* Rows of (path, pre_exists, pre_mode, pre_hash, pre_kept[, post_exists,
* post_hash]) into F, the first row of each path standing. */
static int rw_collect(pic_store *s, sqlite3_stmt *q, rw_files *f, int with_post) {
int step;
while ((step = sqlite3_step(q)) == SQLITE_ROW) {
const char *path = (const char *)sqlite3_column_text(q, 0);
rw_file *grown, *x;
if (!path || rw_find(f, path)) {
continue;
}
if (!(grown = realloc(f->v, (f->n + 1) * sizeof *grown))) {
(void)snprintf(s->err, sizeof s->err, "out of memory");
return -1;
}
f->v = grown;
x = &f->v[f->n++];
memset(x, 0, sizeof *x);
x->path = strdup(path);
x->exists = sqlite3_column_int(q, 1);
x->mode = (unsigned)sqlite3_column_int64(q, 2);
x->hash = rw_dup(q, 3);
x->has_hash = x->hash != NULL;
x->kept = sqlite3_column_int(q, 4);
if (with_post) {
x->expect_known = sqlite3_column_type(q, 5) != SQLITE_NULL;
x->expect_exists = sqlite3_column_int(q, 5);
x->expect_hash = rw_dup(q, 6);
}
if (!x->path) {
(void)snprintf(s->err, sizeof s->err, "out of memory");
return -1;
}
}
return step == SQLITE_DONE ? 0 : rw_fail(s);
}
/* What conversation SID last left in each file: its latest write or edit
* on its path, or a restore of it that put the file back. */
static int rw_expect(pic_store *s, const char *sid, rw_files *f) {
for (size_t i = 0; i < f->n; i++) {
sqlite3_stmt *q = NULL;
rw_file *x = &f->v[i];
if (sqlite3_prepare_v2(s->db,
RW_PATH "SELECT c.post_exists, c.post_hash FROM pic_file_change c"
" LEFT JOIN pic_effect f ON f.id = c.effect_id LEFT JOIN pic_restore r ON r.id = c.restore_id"
" WHERE c.path = ?2 AND ((f.id IS NOT NULL AND f.entry_seq IN p) OR (r.state = 'done'"
" AND (r.session_id = ?1 OR r.forked = ?1) AND c.outcome IN ('restored','unchanged')))"
" ORDER BY c.id DESC LIMIT 1",
-1, &q, NULL) != SQLITE_OK) {
return rw_fail(s);
}
sqlite3_bind_text(q, 1, sid, -1, SQLITE_STATIC);
sqlite3_bind_text(q, 2, x->path, -1, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW) {
x->expect_known = sqlite3_column_type(q, 0) != SQLITE_NULL;
x->expect_exists = sqlite3_column_int(q, 0);
x->expect_hash = rw_dup(q, 1);
}
sqlite3_finalize(q);
}
return 0;
}
static int rw_refuse(pic_store *s, pic_rewind_report *r, const char *path, const char *why) {
struct pic_rewind_refusal *grown = realloc(r->refused, (r->nrefused + 1) * sizeof *grown);
char *copy = strdup(path);
if (grown) {
r->refused = grown;
}
if (!grown || !copy) {
free(copy);
(void)snprintf(s->err, sizeof s->err, "out of memory");
return -1;
}
r->refused[r->nrefused++] = (struct pic_rewind_refusal){copy, why};
return 0;
}
/* Checks each file against what the conversation last left there, and
* makes the targets of those that pass and need putting back. */
static int rw_plan(pic_store *s, rw_files *f, pic_rewind_report *r, pic_restore_target **out, size_t *nout) {
pic_restore_target *t = calloc(f->n ? f->n : 1, sizeof *t);
size_t n = 0;
if (!t) {
(void)snprintf(s->err, sizeof s->err, "out of memory");
return -1;
}
for (size_t i = 0; i < f->n; i++) {
rw_file *x = &f->v[i];
const char *why = NULL;
pic_file_state now;
pic_file_state_read(x->path, -1, &now);
if (x->exists && (!x->has_hash || !x->kept)) {
why = x->has_hash ? "its earlier contents were larger than rewindMaxBytes and were not kept"
: "pic could not read it before changing it";
} else if (!x->expect_known) {
why = "pic did not finish changing it";
} else if (!pic_file_state_same(&now, x->expect_exists, x->expect_hash)) {
why = "it changed since pic last wrote it";
} else if (pic_file_state_same(&now, x->exists, x->hash)) {
continue; /* already as it was */
}
if (why) {
if (rw_refuse(s, r, x->path, why) != 0) {
free(t);
return -1;
}
continue;
}
t[n++] = (pic_restore_target){x->path, x->exists, x->mode, x->hash};
}
*out = t;
*nout = n;
return 0;
}
/* Takes SESSION's lease (it must be idle) and resolves it into SID. */
static int rw_claim(pic_store *s, const char *session, char sid[64]) {
if (!session || !*session) {
(void)snprintf(s->err, sizeof s->err, "no conversation to rewind yet");
return -1;
}
if (pic_session_resolve(s, session, sid, 64) != 0) {
return -1;
}
return pic_lease(s, sid, PIC_LEASE_WAIT_MS) == 0 ? 0 : -1;
}
/* Whether SID can be forked at AT: tried, then rolled back. */
static int rw_can_fork(pic_store *s, const char *sid, sqlite3_int64 at) {
char made[64];
int rc;
if (at <= 0) {
return 0;
}
if (pic_begin(s) != 0) {
return -1;
}
rc = pic_fork(s, sid, at, made, sizeof made);
pic_rollback(s);
return rc;
}
int pic_rewind(pic_store *s, const char *session, sqlite3_int64 entry, int mode, int force_partial, pic_rewind_report *r) {
sqlite3_stmt *q = NULL;
rw_files f = {NULL, 0};
pic_restore_target *t = NULL;
size_t nt = 0;
sqlite3_int64 parent = 0;
char sid[64];
int found = 0, rc = 0;
memset(r, 0, sizeof *r);
if (rw_claim(s, session, sid) != 0) {
return -1;
}
if (sqlite3_prepare_v2(s->db, RW_PATH "SELECT coalesce(e.parent_seq, 0), e.body FROM pic_entry e WHERE e.seq = ?2 AND " RW_MESSAGE("e"),
-1, &q, NULL) != SQLITE_OK) {
return rw_fail(s);
}
sqlite3_bind_text(q, 1, sid, -1, SQLITE_STATIC);
sqlite3_bind_int64(q, 2, entry);
if (sqlite3_step(q) == SQLITE_ROW) {
found = 1;
parent = sqlite3_column_int64(q, 0);
r->text = rw_dup(q, 1);
}
sqlite3_finalize(q);
if (!found) {
(void)snprintf(s->err, sizeof s->err, "entry %lld is not a message of conversation %s (pic rewind %s --list shows them)",
(long long)entry, sid, sid);
return -1;
}
if (mode != PIC_REWIND_FILES && rw_can_fork(s, sid, parent) != 0) {
return -1;
}
if (mode != PIC_REWIND_CONVERSATION) {
if (sqlite3_prepare_v2(s->db,
RW_PATH "SELECT c.path, c.pre_exists, coalesce(c.pre_mode, 0), c.pre_hash, c.pre_kept"
" FROM pic_file_change c JOIN pic_effect f ON f.id = c.effect_id"
" WHERE f.entry_seq IN p AND f.entry_seq > ?2 ORDER BY c.id",
-1, &q, NULL) != SQLITE_OK) {
return rw_fail(s);
}
sqlite3_bind_text(q, 1, sid, -1, SQLITE_STATIC);
sqlite3_bind_int64(q, 2, entry);
rc = rw_collect(s, q, &f, 0);
sqlite3_finalize(q);
if (rc == 0) {
rc = rw_expect(s, sid, &f);
}
if (rc == 0) {
rc = rw_plan(s, &f, r, &t, &nt);
}
if (rc != 0 || (r->nrefused && !force_partial)) {
rw_files_free(&f);
free(t);
return rc;
}
}
r->applied = 1;
if (mode == PIC_REWIND_CONVERSATION || (mode == PIC_REWIND_FILES && nt == 0)) {
if (mode == PIC_REWIND_CONVERSATION) {
r->switched = 1;
rc = parent > 0 ? pic_fork(s, sid, parent, r->conversation, sizeof r->conversation) : 0;
}
} else {
rc = pic_restore(s, sid, entry, 0, mode == PIC_REWIND_BOTH ? parent : -1, t, nt, &r->restore);
if (rc == 0 && r->restore.forked) {
r->switched = 1;
(void)snprintf(r->conversation, sizeof r->conversation, "%s", r->restore.conversation);
}
}
rw_files_free(&f);
free(t);
return rc;
}
int pic_rewind_undo(pic_store *s, const char *session, int force_partial, pic_rewind_report *r) {
sqlite3_stmt *q = NULL;
rw_files f = {NULL, 0};
pic_restore_target *t = NULL;
size_t nt = 0;
sqlite3_int64 last = 0;
char sid[64];
int rc;
memset(r, 0, sizeof *r);
if (rw_claim(s, session, sid) != 0) {
return -1;
}
if (sqlite3_prepare_v2(s->db, "SELECT id FROM pic_restore WHERE state = 'done' AND (session_id = ?1 OR forked = ?1)"
" ORDER BY id DESC LIMIT 1",
-1, &q, NULL) != SQLITE_OK) {
return rw_fail(s);
}
sqlite3_bind_text(q, 1, sid, -1, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW) {
last = sqlite3_column_int64(q, 0);
}
sqlite3_finalize(q);
if (!last) {
(void)snprintf(s->err, sizeof s->err, "conversation %s has no rewind of files to undo", sid);
return -1;
}
/* What the restore found goes back, where the file is still as it left it. */
if (sqlite3_prepare_v2(s->db,
"SELECT path, pre_exists, coalesce(pre_mode, 0), pre_hash, pre_kept, post_exists, post_hash"
" FROM pic_file_change WHERE restore_id = ? AND outcome = 'restored' ORDER BY id",
-1, &q, NULL) != SQLITE_OK) {
return rw_fail(s);
}
sqlite3_bind_int64(q, 1, last);
rc = rw_collect(s, q, &f, 1);
sqlite3_finalize(q);
if (rc == 0) {
rc = rw_plan(s, &f, r, &t, &nt);
}
if (rc == 0 && (!r->nrefused || force_partial)) {
r->applied = 1;
rc = nt ? pic_restore(s, sid, 0, last, -1, t, nt, &r->restore) : 0;
}
rw_files_free(&f);
free(t);
return rc;
}
void pic_rewind_report_free(pic_rewind_report *r) {
free(r->text);
for (size_t i = 0; i < r->nrefused; i++) {
free(r->refused[i].path);
}
free(r->refused);
pic_restore_result_free(&r->restore);
memset(r, 0, sizeof *r);
}
/* PATH relative to WORKSPACE when it is inside it. */
static const char *rw_shown(const char *path, const char *workspace) {
size_t n = workspace ? strlen(workspace) : 0;
if (n && strncmp(path, workspace, n) == 0 && path[n] == '/') {
return path + n + 1;
}
return path;
}
static void rw_json_string(sqlite3_str *o, const char *t) {
sqlite3_str_appendchar(o, 1, '"');
for (const unsigned char *c = (const unsigned char *)t; c && *c; c++) {
if (*c == '"' || *c == '\\') {
sqlite3_str_appendf(o, "\\%c", *c);
} else if (*c < 0x20) {
sqlite3_str_appendf(o, "\\u%04x", *c);
} else {
sqlite3_str_appendchar(o, 1, (char)*c);
}
}
sqlite3_str_appendchar(o, 1, '"');
}
/* The report as JSON (sqlite3_malloc'd). */
static char *rw_json(const pic_rewind_report *r, const char *workspace) {
sqlite3_str *o = sqlite3_str_new(NULL);
static const char *const lists[] = {"restored", "deleted", "unchanged", "left", "failed"};
sqlite3_str_appendf(o, "{\"applied\":%s,\"text\":", r->applied ? "true" : "false");
rw_json_string(o, r->text ? r->text : "");
sqlite3_str_appendall(o, ",\"conversation\":");
if (r->switched) {
rw_json_string(o, r->conversation);
} else {
sqlite3_str_appendall(o, "null");
}
for (size_t l = 0; l < sizeof lists / sizeof lists[0]; l++) {
int first = 1;
sqlite3_str_appendf(o, ",\"%s\":[", lists[l]);
for (size_t i = 0; i < r->restore.nfiles; i++) {
const struct pic_restore_file *x = &r->restore.files[i];
const char *kind = strcmp(x->outcome, "restored") == 0 ? (x->deleted ? "deleted" : "restored")
: strcmp(x->outcome, "changed") == 0 ? "left"
: x->outcome;
if (strcmp(kind, lists[l]) == 0) {
sqlite3_str_appendall(o, first ? "" : ",");
rw_json_string(o, rw_shown(x->path, workspace));
first = 0;
}
}
sqlite3_str_appendall(o, "]");
}
sqlite3_str_appendall(o, ",\"refused\":[");
for (size_t i = 0; i < r->nrefused; i++) {
sqlite3_str_appendall(o, i ? ",{\"path\":" : "{\"path\":");
rw_json_string(o, rw_shown(r->refused[i].path, workspace));
sqlite3_str_appendall(o, ",\"why\":");
rw_json_string(o, r->refused[i].why);
sqlite3_str_appendall(o, "}");
}
sqlite3_str_appendall(o, "]}");
return sqlite3_str_finish(o);
}
void pic_rewind_print(const pic_rewind_report *r, const char *workspace, int json, FILE *out) {
if (json) {
char *j = rw_json(r, workspace);
fprintf(out, "%s\n", j ? j : "{}");
sqlite3_free(j);
return;
}
if (!r->applied) {
fprintf(out, "nothing done: %s not be restored (--force-partial restores the rest)\n",
r->nrefused == 1 ? "this file can" : "these files can");
}
for (size_t i = 0; i < r->nrefused; i++) {
fprintf(out, "%s %s: %s\n", r->applied ? "not restored" : " ", rw_shown(r->refused[i].path, workspace),
r->refused[i].why);
}
if (!r->applied) {
return;
}
for (size_t i = 0; i < r->restore.nfiles; i++) {
const struct pic_restore_file *x = &r->restore.files[i];
const char *shown = rw_shown(x->path, workspace);
if (strcmp(x->outcome, "restored") == 0) {
fprintf(out, "%s %s\n", x->deleted ? "deleted" : "restored", shown);
} else if (strcmp(x->outcome, "changed") == 0) {
fprintf(out, "not restored %s: it changed while the rewind ran\n", shown);
} else if (strcmp(x->outcome, "failed") == 0) {
fprintf(out, "not restored %s: it could not be written\n", shown);
}
}
if (r->switched) {
fprintf(out, r->conversation[0] ? "conversation rewound: now in %s\n" : "conversation rewound: a new conversation%s\n",
r->conversation);
}
}
/* {"type":"rewind","entryId":"N","mode":"both"|"conversation"|"files",
* "forcePartial":true}, or {"type":"rewind","undo":true}. */
static int rw_answer(pic_store *s, const char *session, const char *line, char **data, int *switched, char *next,
size_t cap) {
sqlite3_stmt *q = NULL;
sqlite3_int64 entry = 0;
char mode_name[16] = "both";
int force = 0, undo = 0, mode, rc;
pic_rewind_report r;
if (sqlite3_prepare_v2(s->db,
"SELECT CAST(json_extract(?1, '$.entryId') AS INTEGER), coalesce(json_extract(?1, '$.mode'), 'both'),"
" json_extract(?1, '$.forcePartial') IS 1, json_extract(?1, '$.undo') IS 1",
-1, &q, NULL) != SQLITE_OK) {
return rw_fail(s);
}
sqlite3_bind_text(q, 1, line, -1, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW) {
entry = sqlite3_column_int64(q, 0);
(void)snprintf(mode_name, sizeof mode_name, "%s", (const char *)sqlite3_column_text(q, 1));
force = sqlite3_column_int(q, 2);
undo = sqlite3_column_int(q, 3);
}
sqlite3_finalize(q);
mode = strcmp(mode_name, "both") == 0 ? PIC_REWIND_BOTH
: strcmp(mode_name, "conversation") == 0 ? PIC_REWIND_CONVERSATION
: strcmp(mode_name, "files") == 0 ? PIC_REWIND_FILES
: -1;
if (mode < 0) {
(void)snprintf(s->err, sizeof s->err, "mode must be both, conversation or files");
return -1;
}
if (!undo && entry <= 0) {
(void)snprintf(s->err, sizeof s->err, "entryId must name a user message (get_fork_messages lists them)");
return -1;
}
rc = undo ? pic_rewind_undo(s, session, force, &r) : pic_rewind(s, session, entry, mode, force, &r);
if (rc == 0) {
char *j = rw_json(&r, NULL);
*data = j ? strdup(j) : NULL;
sqlite3_free(j);
if (r.switched) {
*switched = 1;
(void)snprintf(next, cap, "%s", r.conversation);
}
}
pic_rewind_report_free(&r);
return rc;
}
const pic_rpc_command pic_rewind_rpc = {"rewind", rw_answer};