/* 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. */
#ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE 1
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "libfossil.h"
#include "pic.h"
#include "platform.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 calls a file change can belong to, by the key it carries: the model's calls, and the calls
* those made (minus their row's id, loop.c), which belong to their caller's entry. */
#define RW_CALLS \
"(SELECT id, entry_seq FROM pic_effect UNION ALL SELECT -n.id, f.entry_seq FROM pic_nested_effect n" \
" JOIN pic_effect f ON f.id = n.parent_id)"
/* 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 " RW_CALLS " 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;
sqlite3_int64 first; /* the first change after the message */
int broken; /* changed outside pic between two of its changes */
int now_exists; /* what the check found, for the restore's guard */
char now_hash[65];
} 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, id) into F, the first row of each path standing; the post
* columns are what to expect now when WITH_POST. */
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);
x->first = sqlite3_column_int64(q, 7);
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);
}
static int rw_same(int e1, const char *h1, int e2, const char *h2) {
return !e1 || !e2 ? e1 == e2 : h1 && h2 && strcmp(h1, h2) == 0;
}
/* Walks each file's changes in conversation SID from the first after the
* message (its writes and edits on the path, and its own restores that put
* the file back): each write or edit must have found the file as the change
* before left it, or something outside pic changed it in between and putting
* back the oldest state would lose that. What the last one left is what the file
* must be now. */
static int rw_chain(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];
char *prev = NULL;
int rows = 0, step, prev_exists = 0;
if (sqlite3_prepare_v2(s->db,
RW_PATH "SELECT c.pre_exists, c.pre_hash, c.post_exists, c.post_hash,"
" CASE WHEN c.restore_id IS NULL THEN 0 WHEN r.session_id = ?1 THEN 1 ELSE 2 END"
" FROM pic_file_change c"
" LEFT JOIN " RW_CALLS " f ON f.id = c.effect_id LEFT JOIN pic_restore r ON r.id = c.restore_id"
" WHERE c.path = ?2 AND c.id >= ?3 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",
-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);
sqlite3_bind_int64(q, 3, x->first);
x->expect_known = 1;
while ((step = sqlite3_step(q)) == SQLITE_ROW) {
const char *pre = (const char *)sqlite3_column_text(q, 1), *post = (const char *)sqlite3_column_text(q, 3);
/* This conversation's own restore checked what it found against
* this same chain: the chain starts again after it. The restore
* that made this fork found the file in the conversation it came
* from, whose changes are not on this path; what it put back is
* the earliest state after the fork point, which is what this path
* last left there unless something outside pic came between. */
int kind = sqlite3_column_int(q, 4);
if (rows++ && kind != 1 &&
!(kind == 0 ? rw_same(prev_exists, prev, sqlite3_column_int(q, 0), pre)
: rw_same(prev_exists, prev, sqlite3_column_int(q, 2), post))) {
x->broken = 1;
}
if (sqlite3_column_type(q, 2) == SQLITE_NULL) {
x->expect_known = 0; /* a call that never finished */
}
prev_exists = sqlite3_column_int(q, 2);
free(prev);
prev = post ? strdup(post) : NULL;
}
sqlite3_finalize(q);
if (step != SQLITE_DONE) {
free(prev);
return rw_fail(s);
}
x->expect_exists = prev_exists;
x->expect_hash = prev;
x->expect_known = x->expect_known && rows > 0;
}
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);
x->now_exists = now.exists;
(void)snprintf(x->now_hash, sizeof x->now_hash, "%s", now.hash);
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 (x->broken) {
why = "it was changed outside pic between its changes";
} else if (!pic_file_state_same(&now, x->expect_exists, x->expect_hash)) {
why = "it changed since pic last wrote it";
} else if (now.exists && now.size > PIC_FILE_KEEP_MAX) {
why = "it is larger than pic keeps for an undo (256 MiB)";
} 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, x->now_exists, x->now_hash, x->first};
}
*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,"
" c.post_exists, c.post_hash, c.id FROM pic_file_change c JOIN " RW_CALLS " 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_chain(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;
}
}
pic_fault("restore-checked"); /* between the check and the journaled restore */
r->applied = 1;
if (mode == PIC_REWIND_CONVERSATION || nt == 0) { /* no file to put back: no restore to journal */
if (mode != PIC_REWIND_FILES) {
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)"
" AND EXISTS (SELECT 1 FROM pic_file_change c WHERE c.restore_id = pic_restore.id"
" AND c.outcome = 'restored') 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, id"
" 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);
}
for (size_t i = 0; i < nt; i++) {
t[i].since = 0; /* the writes an undo's files came from are not its to remove folders for */
}
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 == '\n' || *c == '\t') {
sqlite3_str_appendf(o, "\\%c", *c == '\n' ? 'n' : 't');
} 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_rpc_call *c) {
pic_store *s = c->s;
const char *session = c->session, *line = c->line;
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);
c->data = j ? strdup(j) : NULL;
sqlite3_free(j);
if (r.switched) {
c->switched = 1;
(void)snprintf(c->next, sizeof c->next, "%s", r.conversation);
}
}
pic_rewind_report_free(&r);
return rc;
}
const pic_rpc_command pic_rewind_rpc = {"rewind", "go back to an earlier user message: the conversation, the files or both",
0, rw_answer};
/* What a conversation changed in files, for a phone's Changes view. Every limit counts the bytes
* as they go out (JSON-escaped), so the answer always fits a remote message (4 MiB). */
#define RW_CHANGES_FILES 200
#define RW_CHANGES_KEEP (4LL << 20) /* a file read whole to be compared, either side */
#define RW_CHANGES_DIFF (256LL << 10) /* one file's diff text, at most */
#define RW_CHANGES_TOTAL (1LL << 20) /* every file's diff text, at most */
#define RW_CHANGES_ANSWER (3LL << 20) /* the whole answer, paths and all */
/* ?1 is the conversation: p is every entry on its path, and on the paths of the helpers it
* started in this journal (pic_session_origin.parent ends in its id), theirs included. */
#define RW_PATH_HELPERS \
"WITH RECURSIVE k(id) AS (SELECT ?1 UNION SELECT o.session_id FROM pic_session_origin o JOIN k" \
" ON substr(o.parent, -length(k.id) - 1) = '/' || k.id)," \
" p(seq) AS (SELECT head_seq FROM pic_session WHERE id IN k" \
" UNION SELECT e.parent_seq FROM pic_entry e JOIN p ON e.seq = p.seq WHERE e.parent_seq IS NOT NULL) "
#define RW_CHANGES_SELECT \
"SELECT c.path, min(c.id), c.pre_exists, c.pre_hash, c.pre_kept FROM pic_file_change c JOIN " RW_CALLS \
" f ON f.id = c.effect_id WHERE f.entry_seq IN p AND c.path != '' GROUP BY c.path ORDER BY c.path"
/* Whether the N bytes at T are valid UTF-8 text with no NUL: what a diff can show. */
static int rw_text(const char *t, size_t n) {
const unsigned char *p = (const unsigned char *)t, *end = p + n;
while (p < end) {
unsigned c = *p++;
int more = c < 0x80 ? 0 : c >= 0xc2 && c <= 0xdf ? 1 : c >= 0xe0 && c <= 0xef ? 2 : c >= 0xf0 && c <= 0xf4 ? 3 : -1;
if (c == 0 || more < 0 || end - p < more) {
return 0;
}
if ((c == 0xe0 && p[0] < 0xa0) || (c == 0xed && p[0] > 0x9f) || (c == 0xf0 && p[0] < 0x90) || (c == 0xf4 && p[0] > 0x8f)) {
return 0;
}
for (int k = 0; k < more; k++) {
if ((p[k] & 0xc0) != 0x80) {
return 0;
}
}
p += more;
}
return 1;
}
/* How many bytes T takes as rw_json_string writes it, quotes included. */
static long long rw_json_len(const char *t) {
long long n = 2;
for (const unsigned char *c = (const unsigned char *)t; c && *c; c++) {
n += *c == '"' || *c == '\\' || *c == '\n' || *c == '\t' ? 2 : *c < 0x20 ? 6 : 1;
}
return n;
}
/* The unified diff of A and B in OUT, made once. 0, or -1: no diff can be shown (binary, or out
* of memory). */
static int rw_diff(const char *a, size_t na, const char *b, size_t nb, fsl_b *out) {
fsl_b pa = fsl_b_empty, pb = fsl_b_empty;
fsl_dibu_opt opt = fsl_dibu_opt_empty;
fsl_dibu *d = NULL;
int rc;
if (!rw_text(a, na) || !rw_text(b, nb)) {
return -1;
}
fsl_b_external(&pa, na ? a : "", (fsl_int_t)na);
fsl_b_external(&pb, nb ? b : "", (fsl_int_t)nb);
opt.diffFlags = FSL_DIFF2_NOINDEX;
opt.contextLines = 3;
opt.out = fsl_output_f_b;
opt.outState = out;
if (fsl_dibu_factory(FSL_DIBU_UNIFIED_TEXT, &d) != 0) {
return -1;
}
d->opt = &opt;
rc = fsl_diff_v2(&pa, &pb, d);
d->finalize(d);
return rc == 0 ? 0 : -1;
}
/* The lines HUNKS (a unified diff's hunks) adds and removes. */
static void rw_count(const char *hunks, long long *added, long long *removed) {
*added = *removed = 0;
for (const char *l = hunks; l && *l; l = strchr(l, '\n'), l = l ? l + 1 : NULL) {
*added += *l == '+';
*removed += *l == '-';
}
}
/* A file's earlier bytes (malloc'd, NUL after them) in *OUT: 0; 1: none kept (pruned, or never);
* 2: kept but over RW_CHANGES_KEEP; -1: the read failed (out of time). */
static int rw_blob(pic_store *s, const char *hash, char **out, size_t *len) {
sqlite3_stmt *q = NULL;
int rc = 1, step;
*out = NULL;
if (sqlite3_prepare_v2(s->db, "SELECT sz, CASE WHEN sz <= ?2 THEN sqlar_uncompress(data, sz) END FROM pic_blob WHERE hash = ?1",
-1, &q, NULL) != SQLITE_OK) {
return -1;
}
sqlite3_bind_text(q, 1, hash, -1, SQLITE_STATIC);
sqlite3_bind_int64(q, 2, RW_CHANGES_KEEP);
if ((step = sqlite3_step(q)) == SQLITE_ROW) {
if (sqlite3_column_int64(q, 0) > RW_CHANGES_KEEP) {
rc = 2;
} else if (sqlite3_column_type(q, 1) != SQLITE_NULL) {
const void *p = sqlite3_column_blob(q, 1);
int nb = sqlite3_column_bytes(q, 1);
if (nb < 0 || (nb > 0 && !p)) {
rc = -1;
} else if ((*out = malloc((size_t)nb + 1))) {
if (nb > 0) {
memcpy(*out, p, (size_t)nb);
}
(*out)[nb] = '\0';
*len = (size_t)nb;
rc = 0;
} else {
rc = -1;
}
}
} else if (step != SQLITE_DONE) {
rc = -1;
}
sqlite3_finalize(q);
return rc;
}
static long long rw_now_ms(void) { return (long long)(pic_platform_get()->mono_ns() / 1000000); }
typedef struct {
char *path, *pre_hash;
int pre_exists, pre_kept;
} rw_change;
char *pic_rewind_changes(pic_store *s, const char *session, const char *workspace, long long stop_ms) {
sqlite3_stmt *q = NULL;
sqlite3_str *o;
rw_change *v = NULL;
size_t nv = 0, cap = 0;
char sid[64];
long long total = 0;
int nfiles = 0, cut = 0, step, failed = 0;
if (pic_session_resolve(s, session, sid, sizeof sid) != 0) {
return NULL;
}
/* each file's first change on the path: what it was before this conversation (the ones it was
* forked from, and its helpers) touched it; a journal with no record of origins has no
* helpers, and one from before file history no changes */
if (sqlite3_prepare_v2(s->db, RW_PATH_HELPERS RW_CHANGES_SELECT, -1, &q, NULL) != SQLITE_OK &&
sqlite3_prepare_v2(s->db, RW_PATH RW_CHANGES_SELECT, -1, &q, NULL) != SQLITE_OK) {
o = sqlite3_str_new(NULL);
sqlite3_str_appendall(o, "{\"files\":[]}");
return sqlite3_str_finish(o);
}
sqlite3_bind_text(q, 1, sid, -1, SQLITE_STATIC);
while ((step = sqlite3_step(q)) == SQLITE_ROW) {
const char *pre_hash = (const char *)sqlite3_column_text(q, 3);
if (nv == cap) {
rw_change *g = realloc(v, (cap = cap ? cap * 2 : 32) * sizeof *g);
if (!g) {
failed = 1;
break;
}
v = g;
}
v[nv].path = strdup((const char *)sqlite3_column_text(q, 0));
v[nv].pre_hash = pre_hash ? strdup(pre_hash) : NULL;
v[nv].pre_exists = sqlite3_column_int(q, 2);
v[nv].pre_kept = sqlite3_column_int(q, 4);
if (!v[nv++].path || (pre_hash && !v[nv - 1].pre_hash)) {
failed = 1;
break;
}
}
if (failed) {
(void)snprintf(s->err, sizeof s->err, "out of memory");
}
if (!failed && step != SQLITE_DONE) {
(void)rw_fail(s);
failed = 1;
}
sqlite3_finalize(q);
o = sqlite3_str_new(NULL);
sqlite3_str_appendall(o, "{\"files\":[");
for (size_t i = 0; !failed && i < nv; i++) {
const char *path = v[i].path, *pre_hash = v[i].pre_hash, *why = NULL, *status, *shown = rw_shown(path, workspace);
int pre_exists = v[i].pre_exists, got = 1;
long long room = RW_CHANGES_TOTAL - total, added = 0, removed = 0, esc = 0;
pic_file_state now;
char *before = NULL;
size_t nbefore = 0;
fsl_b diff = fsl_b_empty;
const char *hunks = NULL;
if (stop_ms && rw_now_ms() > stop_ms) {
cut = 1; /* out of time: what is listed is right, and the rest is not */
break;
}
#ifdef PIC_FAULTS
if (getenv("PIC_TEST_CHANGES_FILE_MS")) { /* the tests' seam: each file slow to read and diff */
long long ms = atoll(getenv("PIC_TEST_CHANGES_FILE_MS"));
struct timespec ts = {(time_t)(ms / 1000), (long)(ms % 1000) * 1000000L};
(void)nanosleep(&ts, NULL);
}
#endif
/* past the total there is no diff to send: the file is hashed, not read */
pic_file_state_read(path, room > 0 ? RW_CHANGES_KEEP : -1, &now);
if (pic_file_state_same(&now, pre_exists, pre_hash ? pre_hash : "")) {
pic_file_state_free(&now);
continue; /* as it was: put back, or changed and changed back */
}
if (nfiles == RW_CHANGES_FILES || (long long)sqlite3_str_length(o) + rw_json_len(shown) + 128 > RW_CHANGES_ANSWER) {
pic_file_state_free(&now);
cut = 1;
break;
}
status = !pre_exists ? "added" : !now.exists ? "deleted" : "modified";
if (pre_exists && (!v[i].pre_kept || !pre_hash)) {
why = "not kept"; /* too large to keep */
} else if (now.exists && !now.kept && !now.hash[0]) {
why = "not a file";
} else if (room <= 0 || (now.exists && !now.kept)) {
why = "too large"; /* over 4 MiB now, or the diffs together are at their most */
} else if (pre_exists && (got = rw_blob(s, pre_hash, &before, &nbefore)) == 1) {
why = "not kept"; /* pruned since */
} else if (got < 0) {
pic_file_state_free(&now);
cut = 1; /* the read was cut short: say no more than is known */
break;
} else if (got == 2) {
why = "too large"; /* over 4 MiB before */
} else if (rw_diff(before ? before : "", nbefore, now.data ? now.data : "", now.data ? (size_t)now.size : 0, &diff) != 0) {
why = "binary";
} else {
/* the hunks alone: the file is named by path */
const char *t;
(void)fsl_b_appendch(&diff, '\0');
t = diff.mem ? (const char *)diff.mem : "";
hunks = strncmp(t, "@@", 2) == 0 ? t : strstr(t, "\n@@");
hunks = hunks ? hunks + (*hunks == '\n') : t + strlen(t);
esc = rw_json_len(hunks);
if (esc > RW_CHANGES_DIFF || esc > room || (long long)sqlite3_str_length(o) + rw_json_len(shown) + esc + 128 > RW_CHANGES_ANSWER) {
why = "too large";
} else {
rw_count(hunks, &added, &removed);
}
}
sqlite3_str_appendall(o, nfiles++ ? ",{\"path\":" : "{\"path\":");
rw_json_string(o, shown);
sqlite3_str_appendf(o, ",\"status\":\"%s\"", status);
if (why) {
sqlite3_str_appendf(o, ",\"why\":\"%s\"", why);
} else {
sqlite3_str_appendf(o, ",\"added\":%lld,\"removed\":%lld,\"diff\":", added, removed);
rw_json_string(o, hunks);
total += esc;
}
sqlite3_str_appendall(o, "}");
fsl_b_clear(&diff);
free(before);
pic_file_state_free(&now);
}
for (size_t i = 0; i < nv; i++) {
free(v[i].path);
free(v[i].pre_hash);
}
free(v);
sqlite3_str_appendf(o, "]%s}", cut ? ",\"cut\":true" : "");
if (failed) {
sqlite3_free(sqlite3_str_finish(o));
return NULL;
}
return sqlite3_str_finish(o);
}