Skip to content
pi-c Documentation
Login

Documentation

/* Core's own RPC commands for a client (rpc.h): the user's settings, trust,
 * Ctrl+P's scope, the models used lately, bug reports, paired phones, whether
 * hooks are configured and process records. The terminal interface reaches core state only
 * through these and the other registered commands. */
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "hooks.h"
#include "pic.h"
#include "procs.h"
#include "rpc.h"
#include "settings.h"
#include "userdb.h"

static int rc_done(pic_rpc_call *c, sqlite3_str *t) {
    char *res = sqlite3_str_finish(t);
    c->data = res ? strdup(res) : NULL;
    sqlite3_free(res);
    return c->data ? 0 : -1;
}

static int rc_need(pic_rpc_call *c, const char *value, const char *field) {
    if (!value) {
        (void)snprintf(c->err, sizeof c->err, "the command needs %s", field);
        return -1;
    }
    return 0;
}

/* get_setting key: {"value": the setting's text, or null when unset}. A
 * field's dotted name (compaction.reserveTokens) reads that field. */
static int rc_get_setting(pic_rpc_call *c) {
    char *key = pic_rpc_text(c, "$.key"), *v;
    const pic_setting_def *d;
    sqlite3_str *t;
    if (rc_need(c, key, "key") != 0) {
        return -1;
    }
    d = pic_settings_find(key);
    v = d && d->field ? pic_settings_stored(d) : pic_setting(key);
    t = sqlite3_str_new(NULL);
    sqlite3_str_appendall(t, "{\"value\":");
    if (v) {
        pic_rpc_quote(t, v);
    } else {
        sqlite3_str_appendall(t, "null");
    }
    sqlite3_str_appendall(t, "}");
    free(key);
    free(v);
    return rc_done(c, t);
}

static void rc_text_or_null(sqlite3_str *t, const char *v) {
    if (v) {
        pic_rpc_quote(t, v);
    } else {
        sqlite3_str_appendall(t, "null");
    }
}

static void rc_setting_row(sqlite3_str *t, const pic_setting_def *d) {
    int valid = 1;
    char *stored = pic_settings_stored(d), *value = pic_settings_effective(d, &valid);
    sqlite3_str_appendall(t, "{\"id\":");
    pic_rpc_quote(t, d->id);
    sqlite3_str_appendall(t, ",\"key\":");
    pic_rpc_quote(t, d->key);
    sqlite3_str_appendall(t, ",\"field\":");
    rc_text_or_null(t, d->field);
    sqlite3_str_appendall(t, ",\"group\":");
    pic_rpc_quote(t, d->group);
    sqlite3_str_appendall(t, ",\"name\":");
    pic_rpc_quote(t, d->name);
    sqlite3_str_appendall(t, ",\"kind\":");
    pic_rpc_quote(t, pic_settings_kind_name(d->kind));
    if (d->kind == PIC_SET_CHOICE) {
        sqlite3_str_appendall(t, ",\"values\":[");
        for (size_t i = 0; i < PIC_SETTING_VALUES && d->values[i]; i++) {
            sqlite3_str_appendall(t, i ? "," : "");
            pic_rpc_quote(t, d->values[i]);
        }
        sqlite3_str_appendall(t, "],\"labels\":[");
        for (size_t i = 0; i < PIC_SETTING_VALUES && d->values[i]; i++) {
            sqlite3_str_appendall(t, i ? "," : "");
            pic_rpc_quote(t, d->labels[i] ? d->labels[i] : d->values[i]);
        }
        sqlite3_str_appendall(t, "]");
    }
    if (d->kind == PIC_SET_NUMBER) {
        sqlite3_str_appendf(t, ",\"min\":%lld,\"max\":%lld", d->min, d->max);
    }
    sqlite3_str_appendall(t, ",\"unit\":");
    rc_text_or_null(t, d->unit);
    sqlite3_str_appendall(t, ",\"default\":");
    pic_rpc_quote(t, d->def);
    sqlite3_str_appendall(t, ",\"defaultLabel\":");
    {
        const char *shown = d->def_label ? d->def_label : d->def;
        for (size_t i = 0; !d->def_label && i < PIC_SETTING_VALUES && d->values[i]; i++) {
            shown = strcmp(d->values[i], d->def) == 0 && d->labels[i] ? d->labels[i] : shown;
        }
        pic_rpc_quote(t, shown);
    }
    sqlite3_str_appendall(t, ",\"description\":");
    pic_rpc_quote(t, d->description);
    sqlite3_str_appendall(t, ",\"applies\":");
    pic_rpc_quote(t, pic_settings_applies_name(d->applies));
    sqlite3_str_appendall(t, ",\"stored\":");
    rc_text_or_null(t, stored);
    sqlite3_str_appendall(t, ",\"value\":");
    pic_rpc_quote(t, value ? value : "");
    sqlite3_str_appendf(t, ",\"valid\":%s}", valid ? "true" : "false");
    free(stored);
    free(value);
}

/* get_settings (since, setting optional): {"version": the change counter,
 * "settings": every row of the list with its stored and effective value};
 * {"version", "unchanged": true} when the counter still equals since; setting:
 * only that row. */
static int rc_get_settings(pic_rpc_call *c) {
    char *since = pic_rpc_text(c, "$.since"), *id = pic_rpc_text(c, "$.setting");
    long long version = pic_settings_version();
    sqlite3_str *t = sqlite3_str_new(NULL);
    int first = 1;
    if (since && *since && strtoll(since, NULL, 10) == version && version >= 0) {
        sqlite3_str_appendf(t, "{\"version\":%lld,\"unchanged\":true}", version);
    } else if (id && !pic_settings_find(id)) {
        (void)snprintf(c->err, sizeof c->err, "no setting %.200s in the list", id);
        sqlite3_free(sqlite3_str_finish(t));
        free(since);
        free(id);
        return -1;
    } else {
        sqlite3_str_appendf(t, "{\"version\":%lld,\"settings\":[", version);
        for (size_t i = 0; i < pic_settings_count(); i++) {
            const pic_setting_def *d = pic_settings_at(i);
            if (id && strcmp(id, d->id) != 0) {
                continue;
            }
            sqlite3_str_appendall(t, first ? "" : ",");
            first = 0;
            rc_setting_row(t, d);
        }
        sqlite3_str_appendall(t, "]}");
    }
    free(since);
    free(id);
    return rc_done(c, t);
}

/* set_setting key value (null removes it), or key path json: one field of a
 * JSON setting, as Pi writes compaction.enabled. A key the settings list
 * knows takes only what it allows (a field by its dotted name too); other
 * keys pass unchecked. */
static int rc_set_setting(pic_rpc_call *c) {
    char *key = pic_rpc_text(c, "$.key"), *value = pic_rpc_text(c, "$.value"), *path = pic_rpc_text(c, "$.path"),
         *json = pic_rpc_text(c, "$.json");
    int rc = -1;
    if (rc_need(c, key, "key") == 0) {
        const pic_setting_def *d = path ? pic_settings_find_path(key, path) : pic_settings_find(key);
        if (path && !json) {
            (void)snprintf(c->err, sizeof c->err, "the command needs json with path");
        } else if (d && path) {
            rc = pic_settings_check(d, json, c->err, sizeof c->err) == 0 ? pic_setting_set_json(key, path, json) : -1;
        } else if (d) {
            rc = pic_settings_write(d, value, c->err, sizeof c->err);
        } else if (path) {
            rc = pic_setting_set_json(key, path, json);
        } else if (pic_settings_check_object(key, value, c->err, sizeof c->err) == 0) {
            rc = pic_setting_set(key, value);
        }
        if (rc != 0 && !c->err[0]) {
            (void)snprintf(c->err, sizeof c->err, "could not save the setting %.200s", key);
        }
    }
    free(key);
    free(value);
    free(path);
    free(json);
    return rc;
}

/* get_trust path: {"trusted": 1, 0, or -1 undecided}. */
static int rc_get_trust(pic_rpc_call *c) {
    char *path = pic_rpc_text(c, "$.path");
    sqlite3_str *t;
    if (rc_need(c, path, "path") != 0) {
        return -1;
    }
    t = sqlite3_str_new(NULL);
    sqlite3_str_appendf(t, "{\"trusted\":%d}", pic_trust_get(path));
    free(path);
    return rc_done(c, t);
}

/* set_trust path trusted. */
static int rc_set_trust(pic_rpc_call *c) {
    char *path = pic_rpc_text(c, "$.path"), *trusted = pic_rpc_text(c, "$.trusted");
    int rc = -1;
    if (rc_need(c, path, "path") == 0 && rc_need(c, trusted, "trusted") == 0) {
        rc = pic_trust_set(path, strcmp(trusted, "1") == 0 || strcmp(trusted, "true") == 0);
        if (rc != 0) {
            (void)snprintf(c->err, sizeof c->err, "could not save the trust decision");
        }
    }
    free(path);
    free(trusted);
    return rc;
}

static int rc_scoped_row(void *ctx, const char *pattern) {
    sqlite3_str *t = ctx;
    if (sqlite3_str_length(t) > 13) {
        sqlite3_str_appendall(t, ",");
    }
    pic_rpc_quote(t, pattern);
    return 0;
}

/* get_scoped_models: {"patterns": Ctrl+P's scope, in cycling order}. */
static int rc_get_scoped(pic_rpc_call *c) {
    sqlite3_str *t = sqlite3_str_new(NULL);
    sqlite3_str_appendall(t, "{\"patterns\":[");
    (void)pic_scoped_each(rc_scoped_row, t);
    sqlite3_str_appendall(t, "]}");
    return rc_done(c, t);
}

/* The workspaces whose journals say which models were used lately: the most recently used ones. */
#define RC_RECENT_WORKSPACES 10

/* get_recent_models [limit]: {"models": [{"model", "usedMs"}]}, the models conversations were sent to,
 * the latest use first, from the journals of the workspaces used last (this one among them). */
static int rc_get_recent(pic_rpc_call *c) {
    char *lim = pic_rpc_text(c, "$.limit"), err[256];
    long limit = lim ? strtol(lim, NULL, 10) : 10;
    sqlite3 *u = pic_userdb(err, sizeof err), *mem = NULL;
    sqlite3_stmt *q = NULL, *add = NULL, *out = NULL;
    sqlite3_str *t = sqlite3_str_new(NULL);
    int n = 0;
    free(lim);
    sqlite3_str_appendall(t, "{\"models\":[");
    if (u && sqlite3_open(":memory:", &mem) == SQLITE_OK &&
        sqlite3_exec(mem, "CREATE TABLE r(model TEXT PRIMARY KEY, ms INTEGER NOT NULL)", NULL, NULL, NULL) == SQLITE_OK &&
        sqlite3_prepare_v2(mem, "INSERT INTO r VALUES(?1, ?2) ON CONFLICT(model) DO UPDATE SET ms = max(ms, excluded.ms)", -1,
                           &add, NULL) == SQLITE_OK &&
        sqlite3_prepare_v2(u, "SELECT journal FROM picu_workspace ORDER BY last_used_ms DESC LIMIT ?1", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_int(q, 1, RC_RECENT_WORKSPACES);
        while (sqlite3_step(q) == SQLITE_ROW) {
            const char *db = (const char *)sqlite3_column_text(q, 0);
            pic_store s;
            sqlite3_stmt *m = NULL;
            if (!db || access(db, R_OK) != 0) {
                continue; /* gone */
            }
            if (pic_open_narrow(&s, db) == 0 &&
                sqlite3_prepare_v2(s.db,
                                   "SELECT u.model, max(s.updated_ms) FROM pic_submission u JOIN pic_session s ON s.id = u.session_id"
                                   " WHERE u.model IS NOT NULL GROUP BY u.model",
                                   -1, &m, NULL) == SQLITE_OK) {
                while (sqlite3_step(m) == SQLITE_ROW) {
                    sqlite3_bind_text(add, 1, (const char *)sqlite3_column_text(m, 0), -1, SQLITE_TRANSIENT);
                    sqlite3_bind_int64(add, 2, sqlite3_column_int64(m, 1));
                    (void)sqlite3_step(add);
                    sqlite3_reset(add);
                }
            }
            sqlite3_finalize(m);
            pic_close(&s);
        }
        if (sqlite3_prepare_v2(mem, "SELECT model, ms FROM r ORDER BY ms DESC, model LIMIT ?1", -1, &out, NULL) == SQLITE_OK) {
            sqlite3_bind_int64(out, 1, limit > 0 ? limit : 10);
            while (sqlite3_step(out) == SQLITE_ROW) {
                sqlite3_str_appendall(t, n++ ? ",{\"model\":" : "{\"model\":");
                pic_rpc_quote(t, (const char *)sqlite3_column_text(out, 0));
                sqlite3_str_appendf(t, ",\"usedMs\":%lld}", (long long)sqlite3_column_int64(out, 1));
            }
        }
    }
    sqlite3_finalize(out);
    sqlite3_finalize(add);
    sqlite3_finalize(q);
    sqlite3_close(mem);
    sqlite3_str_appendall(t, "]}");
    return rc_done(c, t);
}

/* set_scoped_models patterns: replaces the scope ([] clears it). */
static int rc_set_scoped(pic_rpc_call *c) {
    const char **v = NULL;
    size_t k = 0;
    int rc = -1;
    {
        sqlite3 *db = NULL;
        sqlite3_stmt *q = NULL;
        if (sqlite3_open(":memory:", &db) == SQLITE_OK &&
            sqlite3_prepare_v2(db, "SELECT value FROM json_each(?1, '$.patterns') WHERE json_valid(?1) AND type = 'text'", -1,
                               &q, NULL) == SQLITE_OK) {
            sqlite3_bind_text(q, 1, c->line, -1, SQLITE_STATIC);
            while (sqlite3_step(q) == SQLITE_ROW) {
                const char **nv = realloc(v, (k + 1) * sizeof *v);
                if (!nv) {
                    break;
                }
                v = nv;
                v[k++] = strdup((const char *)sqlite3_column_text(q, 0));
            }
            rc = pic_scoped_set(v, k);
        }
        sqlite3_finalize(q);
        sqlite3_close(db);
    }
    for (size_t i = 0; i < k; i++) {
        free((char *)(uintptr_t)v[i]);
    }
    free(v);
    if (rc != 0) {
        (void)snprintf(c->err, sizeof c->err, "could not save the scoped models");
    }
    return rc;
}

/* report_bug description (workspace, session and model optional): {"id": the report's}. Kept
 * in the user database; nothing is sent anywhere. */
static int rc_report_bug(pic_rpc_call *c) {
    char *text = pic_rpc_text(c, "$.description"), *ws = pic_rpc_text(c, "$.workspace"),
         *sid = pic_rpc_text(c, "$.session"), *model = pic_rpc_text(c, "$.model");
    long long id = -1;
    sqlite3_str *t = NULL;
    if (rc_need(c, text, "description") == 0) {
        id = pic_bug_add(ws ? ws : c->workspace, sid ? sid : c->session, model ? model : c->model, text);
        if (id < 0) {
            (void)snprintf(c->err, sizeof c->err, "could not keep the report");
        } else {
            t = sqlite3_str_new(NULL);
            sqlite3_str_appendf(t, "{\"id\":%lld}", id);
        }
    }
    free(text);
    free(ws);
    free(sid);
    free(model);
    return t ? rc_done(c, t) : -1;
}

/* get_remote_phones: {"count": the phones paired for remote control}. */
static int rc_get_phones(pic_rpc_call *c) {
    sqlite3_str *t = sqlite3_str_new(NULL);
    sqlite3_str_appendf(t, "{\"count\":%d}", pic_remote_phones());
    return rc_done(c, t);
}

/* get_hooks: {"configured": whether any hook is configured for the workspace}. */
static int rc_get_hooks(pic_rpc_call *c) {
    pic_hooks *h = pic_hooks_load(c->workspace, NULL, NULL);
    sqlite3_str *t = sqlite3_str_new(NULL);
    sqlite3_str_appendf(t, "{\"configured\":%s}", h ? "true" : "false");
    pic_hooks_free(h);
    return rc_done(c, t);
}

/* proc_start kind command pid (pgid, workspace, session optional): records a
 * process the client started, for pic ps; {"id": its row, -1 when not recorded}. */
static int rc_proc_start(pic_rpc_call *c) {
    char *kind = pic_rpc_text(c, "$.kind"), *cmd = pic_rpc_text(c, "$.command"), *pid = pic_rpc_text(c, "$.pid"),
         *pgid = pic_rpc_text(c, "$.pgid"), *ws = pic_rpc_text(c, "$.workspace"), *sid = pic_rpc_text(c, "$.session");
    sqlite3_str *t = NULL;
    if (rc_need(c, kind, "kind") == 0 && rc_need(c, cmd, "command") == 0 && rc_need(c, pid, "pid") == 0) {
        long p = strtol(pid, NULL, 10);
        pic_proc_scope(ws ? ws : c->workspace, sid ? sid : c->session);
        t = sqlite3_str_new(NULL);
        sqlite3_str_appendf(t, "{\"id\":%lld}", pic_proc_start(kind, cmd, p, pgid ? strtol(pgid, NULL, 10) : p));
    }
    free(kind);
    free(cmd);
    free(pid);
    free(pgid);
    free(ws);
    free(sid);
    return t ? rc_done(c, t) : -1;
}

/* proc_end id exitCode signal: marks the process ended. */
static int rc_proc_end(pic_rpc_call *c) {
    char *id = pic_rpc_text(c, "$.id"), *code = pic_rpc_text(c, "$.exitCode"), *sig = pic_rpc_text(c, "$.signal");
    int rc = rc_need(c, id, "id");
    if (rc == 0) {
        pic_proc_end(strtoll(id, NULL, 10), code ? (int)strtol(code, NULL, 10) : -1, sig ? (int)strtol(sig, NULL, 10) : 0);
    }
    free(id);
    free(code);
    free(sig);
    return rc;
}

#define CORE (PIC_RPC_JOURNAL_FREE | PIC_RPC_IMMEDIATE)
const pic_rpc_command pic_get_setting_rpc = {"get_setting", "one of the user's settings", CORE, rc_get_setting};
const pic_rpc_command pic_set_setting_rpc = {"set_setting", "saves one of the user's settings", CORE, rc_set_setting};
const pic_rpc_command pic_get_settings_rpc = {"get_settings", "the settings list with each value", CORE, rc_get_settings};
const pic_rpc_command pic_get_trust_rpc = {"get_trust", "whether a folder is trusted", CORE, rc_get_trust};
const pic_rpc_command pic_set_trust_rpc = {"set_trust", "trusts a folder or not", CORE, rc_set_trust};
const pic_rpc_command pic_get_scoped_rpc = {"get_scoped_models", "Ctrl+P's model scope", CORE, rc_get_scoped};
const pic_rpc_command pic_set_scoped_rpc = {"set_scoped_models", "replaces Ctrl+P's model scope", CORE, rc_set_scoped};
const pic_rpc_command pic_get_recent_rpc = {"get_recent_models", "the models used lately", CORE, rc_get_recent};
const pic_rpc_command pic_report_bug_rpc = {"report_bug", "keeps a bug report", CORE, rc_report_bug};
const pic_rpc_command pic_get_phones_rpc = {"get_remote_phones", "how many phones are paired", CORE, rc_get_phones};
const pic_rpc_command pic_get_hooks_rpc = {"get_hooks", "whether hooks are configured", CORE, rc_get_hooks};
const pic_rpc_command pic_proc_start_rpc = {"proc_start", "records a process the client started", CORE, rc_proc_start};
const pic_rpc_command pic_proc_end_rpc = {"proc_end", "marks a recorded process ended", CORE, rc_proc_end};