/* See remote.h; the wire contract is docs/design/remote-protocol.md, and section numbers below
* are its. One loop, a stream thread and a few workers: the stream thread reads the relay's stream
* and writes whole records to a pipe, never touching SQLite; the loop waits on that pipe and a
* 100 ms tick, as pic attach does, and does the handshakes, the sessions and the posting; every
* read or write of a journal or the user database is a job a worker runs (docs/dev/remote.md). */
#ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE 1
#endif
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <pthread.h>
#include <signal.h>
#include <stdarg.h>
#include <stdatomic.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <termios.h>
#include <time.h>
#include <unistd.h>
#include "ask.h"
#include "attach.h"
#include "cred.h"
#include "folder.h"
#include "http.h"
#include "inbox.h"
#include "models.h"
#include "net.h"
#include "noise.h"
#include "perm.h"
#include "pic.h"
#include "platform.h"
#include "prompts.h"
#include "remote.h"
#include "rpc.h"
#include "sqlar.h"
#include "skills.h"
#include "sse.h"
#include "userdb.h"
#include "wake.h"
#include "webpush.h"
extern char **environ;
#define RMT_PAIR_TTL 600 /* an offer's lifetime, seconds */
#define RMT_PAIR_FAILS 5 /* first messages that fail to verify before an offer ends */
#define RMT_PHONE_PAIR_TTL 300 /* an offer a paired phone asked for, seconds */
#define RMT_PAIR_AGAIN 16 /* the same first message answered again (the phone reconnected) */
#define RMT_LAST_WORD_MS 30000LL /* how long paired (or a refusal) waits for the phone to read it */
#define RMT_NO_PEER_MS 2000LL /* the wait when the relay does not say whether it reads */
#define RMT_UNCONFIRMED_MS 30000LL
#define RMT_SILENT_MS 600000LL /* a session silent this long is dropped */
#define RMT_REKEY_MS 86400000LL /* a session older than this is asked to start again */
#define RMT_BYE_GRACE_MS 60000LL /* and dropped if it has not, this long after */
#define RMT_POST_WAIT_MS 30000LL /* a record that waited this long to be posted is dropped */
#define RMT_MSG_CAP (4u << 20) /* an envelope message */
#define RMT_POST_RECORDS 32
#define RMT_POST_BYTES (256u << 10)
#define RMT_POST_SMALL (16u << 10) /* a post this small (a pong, an answer) may go on the quick poster */
#define RMT_FETCH_BYTES (2u << 20) /* about the most a fetch's page sends; the rest is its next page */
#define RMT_CMDS 64
#define RMT_CHOICES 32 /* conversations with a model or level chosen from a phone */
#define RMT_EARLIER 5 /* the requests an "earlier" sync point adds */
#define RMT_SESSIONS 32
#define RMT_LIST 50
#define RMT_IDLE_S 45 /* a stream with no byte this long is dead: the relay comments every 15 s */
#define RMT_QUIET_MS 120000LL /* no record this long while a phone is on screen (it pings each minute): reconnect */
#define RMT_OPEN_FAILS 3 /* records in a row that do not open end a session */
#define RMT_TALLY_MS 10000LL /* a kind of drop or reset is logged at most this often */
#define RMT_LOCK_WAIT_MS 5000 /* how long a starting pic remote waits for its lock to come free */
#define RMT_BUSY_MS 250 /* the longest the loop waits for a journal another pic is writing */
#define RMT_STALL_MS 10000LL /* a loop tick this long is a stall: logged, and status says so */
#define RMT_PAGE 200 /* the most journal entries one follow pass sends; the rest next tick */
#define RMT_ASKS 50 /* the most asks one look reads from a journal; the rest next tick */
#define RMT_ASK_RING 64 /* the expired asks a journal remembers telling */
#define RMT_RECYCLE_MS 30000 /* a stream this old that the relay ends cleanly is a recycle */
#define RMT_SLOW_REOPEN_MS 10000 /* a stream back after longer than this is logged */
#define RMT_BACKOFF_MAX_MS 60000LL
#define RMT_JUMP_MS 10000LL /* a tick this late, or a wall clock this far ahead: a sleep or a stop */
#define RMT_LIVE_MS 250LL /* at most one live value this often per phone */
#define RMT_LIVE_KEEP 8192 /* the bytes of streamed text a live value carries */
#define RMT_PUSH_GAP_MS 30000LL /* at most one notification per conversation this often */
#define RMT_PUSH_TTL 3600
#define RMT_PUSH_QUEUE 32 /* notifications waiting to be sent; more are dropped */
#define RMT_PUSH_REFUSED 3 /* 400s or 403s in a row that end a subscription */
#define RMT_ENDPOINT 2048
#define RMT_ACK_BYTES (256 << 10) /* read and not yet acknowledged: acknowledged at once past this, */
#define RMT_ACK_RECORDS 128 /* or this many records (a lane holds 1 MiB or 256), */
#define RMT_ACK_MS 5000LL /* or after this long with no post to carry it */
static volatile sig_atomic_t rmt_stop;
static volatile sig_atomic_t rmt_restart_asked; /* SIGUSR1: pic remote restart */
/* The program this pic remote runs and its file's stamp when it started (platform.h's file_stamp):
* a newer pic installed over it starts in its place at a quiet moment. */
static char rmt_exe[PATH_MAX], rmt_exe_stamp[128];
static long long rmt_started_ms;
static long long rmt_wall_ms(void) { return (long long)(pic_platform_get()->wall_ns() / 1000000); }
static long long rmt_mono_ms(void) { return (long long)(pic_platform_get()->mono_ns() / 1000000); }
/* A line of what pic remote says (~/.pic/remote.log when it runs at login), after the UTC time. */
static void rmt_log(FILE *f, const char *fmt, ...) {
char when[32] = "";
time_t t = (time_t)(rmt_wall_ms() / 1000);
struct tm tm;
va_list ap;
if (gmtime_r(&t, &tm)) {
(void)strftime(when, sizeof when, "%Y-%m-%dT%H:%M:%SZ", &tm);
}
flockfile(f);
fprintf(f, "%s ", when);
va_start(ap, fmt);
vfprintf(f, fmt, ap);
va_end(ap);
funlockfile(f);
(void)fflush(f);
}
/* The loop's watchdog: the loop stamps each tick and says what it is doing; a thread of its own
* logs a tick that has not ended in RMT_STALL_MS, since the loop cannot say so itself. */
static atomic_llong rmt_beat_ms;
static atomic_llong rmt_stuck_ms; /* the stamp of the tick the watchdog logged as stuck, or 0 */
static pthread_mutex_t rmt_doing_mu = PTHREAD_MUTEX_INITIALIZER;
static char rmt_doing_what[256] = "starting";
static long long rmt_doing_ms; /* when the phase was named (mono), under rmt_doing_mu */
/* Names the phase the loop enters: each call that may block is named just before it, with the
* journal or phone it is for, so a stall says where it is. */
static void rmt_doing(const char *what, const char *detail) {
pthread_mutex_lock(&rmt_doing_mu);
(void)snprintf(rmt_doing_what, sizeof rmt_doing_what, "%s%s%s", what, detail ? " " : "", detail ? detail : "");
rmt_doing_ms = rmt_mono_ms();
pthread_mutex_unlock(&rmt_doing_mu);
#ifdef PIC_FAULTS
{
/* the tests' seam: "TEXT:MS" sleeps MS, once, in the first phase whose name has TEXT */
static int slept;
const char *v = getenv("PIC_TEST_RC_SLOW_PHASE"), *colon = v ? strrchr(v, ':') : NULL;
if (colon && !slept) {
char want[128];
(void)snprintf(want, sizeof want, "%.*s", (int)(colon - v), v);
if (strstr(rmt_doing_what, want)) {
long long ms = atoll(colon + 1);
struct timespec ts = {(time_t)(ms / 1000), (long)(ms % 1000) * 1000000L};
slept = 1;
(void)nanosleep(&ts, NULL);
}
}
}
#endif
}
static long long rmt_stall_ms(void) {
#ifdef PIC_FAULTS
if (getenv("PIC_TEST_RC_STALL_MS")) { /* the tests' seam: a stall seen in a second or two */
return atoll(getenv("PIC_TEST_RC_STALL_MS"));
}
#endif
return RMT_STALL_MS;
}
static void *rmt_watch_main(void *arg) {
(void)arg;
for (;;) {
struct timespec ts = {0, 250000000L};
long long beat, now;
(void)nanosleep(&ts, NULL);
beat = atomic_load(&rmt_beat_ms);
now = rmt_mono_ms();
/* the loop stamps its tick before it takes back the stuck mark: a stamp still unchanged
* after the mark was looked at is a tick that has not ended */
if (beat && now - beat > rmt_stall_ms() && atomic_load(&rmt_stuck_ms) != beat && atomic_load(&rmt_beat_ms) == beat) {
char what[256];
long long since;
pthread_mutex_lock(&rmt_doing_mu);
(void)snprintf(what, sizeof what, "%s", rmt_doing_what);
since = rmt_doing_ms;
pthread_mutex_unlock(&rmt_doing_mu);
atomic_store(&rmt_stuck_ms, beat);
rmt_log(stdout, "pic remote: stalled: the loop has been stuck for %lld s; its last phase, named %lld s ago: %s\n",
(now - beat) / 1000, (now - since) / 1000, what);
}
}
return NULL;
}
static void rmt_hex(const unsigned char *b, size_t n, char *out) {
static const char d[] = "0123456789abcdef";
for (size_t i = 0; i < n; i++) {
out[2 * i] = d[b[i] >> 4];
out[2 * i + 1] = d[b[i] & 15];
}
out[2 * n] = '\0';
}
/* ---- JSON through SQLite's functions, on a private connection ------------------------ */
static sqlite3 *rmt_mem(void) {
static _Thread_local sqlite3 *m; /* one a thread: the loop's and each worker's */
if (!m && sqlite3_open(":memory:", &m) != SQLITE_OK) {
sqlite3_close(m);
m = NULL;
}
return m;
}
/* The first column of SQL with N text binds (a NULL binds NULL), malloc'd; NULL when it is NULL
* or on failure. */
static char *rmt_q(const char *sql, int n, ...) {
sqlite3 *m = rmt_mem();
sqlite3_stmt *q = NULL;
char *out = NULL;
va_list ap;
if (!m || sqlite3_prepare_v2(m, sql, -1, &q, NULL) != SQLITE_OK) {
return NULL;
}
va_start(ap, n);
for (int i = 1; i <= n; i++) {
const char *v = va_arg(ap, const char *);
if (v) {
sqlite3_bind_text(q, i, v, -1, SQLITE_TRANSIENT);
}
}
va_end(ap);
if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_type(q, 0) != SQLITE_NULL) {
out = strdup((const char *)sqlite3_column_text(q, 0));
}
sqlite3_finalize(q);
return out;
}
/* ---- keys and devices (section 1) ------------------------------------------------- */
typedef struct {
pic_noise_keypair stat, vapid;
unsigned char owner[32], mailbox[16];
} rmt_keys;
typedef struct {
unsigned char id[16];
char name[72];
unsigned char stat[PIC_NOISE_PUB];
unsigned char channel[16];
long long paired_ms, seen_ms;
/* its push subscription (section 5): notify is "all" or "remote", "" for none */
char notify[8];
char endpoint[RMT_ENDPOINT];
unsigned char p256dh[PIC_WEBPUSH_PUB], auth[PIC_WEBPUSH_AUTH];
} rmt_device;
/* NAME's row: 0 with its public column in PUB (*PN bytes) and the opened secret in SEC (*SN
* bytes); 1 when there is none; -1 with err. */
static int rmt_key_read(sqlite3 *db, const char *name, unsigned char *pub, size_t pcap, size_t *pn, unsigned char *sec,
size_t scap, size_t *sn, char *err, size_t cap) {
sqlite3_stmt *q = NULL;
char aad[64];
int rc = 1;
(void)snprintf(aad, sizeof aad, "remote-key:%s", name);
if (sqlite3_prepare_v2(db, "SELECT public, sealed FROM picu_remote_key WHERE name = ?", -1, &q, NULL) != SQLITE_OK) {
(void)snprintf(err, cap, "%s", sqlite3_errmsg(db));
return -1;
}
sqlite3_bind_text(q, 1, name, -1, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW) {
size_t p = (size_t)sqlite3_column_bytes(q, 0), s = (size_t)sqlite3_column_bytes(q, 1);
rc = -1;
if (p > pcap || s < PIC_CRED_OVERHEAD || s - PIC_CRED_OVERHEAD > scap) {
(void)snprintf(err, cap, "the remote key %s is damaged", name);
} else if (pic_cred_unbox(aad, sqlite3_column_blob(q, 1), s, sec, err, cap) == 0) {
if (p) {
memcpy(pub, sqlite3_column_blob(q, 0), p);
}
*pn = p;
*sn = s - PIC_CRED_OVERHEAD;
rc = 0;
}
}
sqlite3_finalize(q);
return rc;
}
static int rmt_key_write(sqlite3 *db, const char *name, const unsigned char *pub, size_t pn, const unsigned char *sec,
size_t sn, char *err, size_t cap) {
unsigned char box[64 + PIC_CRED_OVERHEAD];
sqlite3_stmt *q = NULL;
char aad[64];
int rc = -1;
(void)snprintf(aad, sizeof aad, "remote-key:%s", name);
if (sn > 64 || pic_cred_box(aad, sec, sn, box, err, cap) != 0) {
return -1;
}
if (sqlite3_prepare_v2(db, "INSERT INTO picu_remote_key(name, public, sealed, created_ms) VALUES(?1, ?2, ?3, ?4)", -1, &q,
NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, name, -1, SQLITE_STATIC);
sqlite3_bind_blob(q, 2, pub, (int)pn, SQLITE_STATIC);
sqlite3_bind_blob(q, 3, box, (int)(sn + PIC_CRED_OVERHEAD), SQLITE_STATIC);
sqlite3_bind_int64(q, 4, rmt_wall_ms());
rc = sqlite3_step(q) == SQLITE_DONE ? 0 : -1;
}
if (rc != 0) {
(void)snprintf(err, cap, "%s", sqlite3_errmsg(db));
}
sqlite3_finalize(q);
pic_cred_wipe(box, sizeof box);
return rc;
}
/* The three keys, opened; CREATE makes the missing ones (the first /rc). The store must be
* unlocked. 0; 1 when they do not exist and CREATE is 0; -1 with err. */
static int rmt_keys_load(rmt_keys *k, int create, char *err, size_t cap) {
sqlite3 *db = pic_userdb(err, cap);
unsigned char pub[PIC_NOISE_PUB], sec[64];
size_t pn, sn;
int rc;
if (!db) {
return -1;
}
if (create && sqlite3_exec(db, "BEGIN IMMEDIATE", NULL, NULL, NULL) != SQLITE_OK) {
(void)snprintf(err, cap, "%s", sqlite3_errmsg(db));
return -1;
}
rc = 0;
{
static const char *const names[] = {"static", "vapid", "mailbox"};
for (int i = 0; i < 3 && rc == 0; i++) {
int got = rmt_key_read(db, names[i], pub, sizeof pub, &pn, sec, sizeof sec, &sn, err, cap);
if (got < 0) {
rc = -1;
} else if (got == 1 && !create) {
rc = 1;
} else if (got == 1) { /* made now */
if (i < 2) {
pic_noise_keypair kp;
rc = pic_noise_keypair_make(&kp, NULL) == 0 ? 0 : -1;
if (rc == 0) {
rc = rmt_key_write(db, names[i], kp.pub, sizeof kp.pub, kp.priv, sizeof kp.priv, err, cap);
*(i == 0 ? &k->stat : &k->vapid) = kp;
} else {
(void)snprintf(err, cap, "no entropy for a key");
}
pic_cred_wipe(&kp, sizeof kp);
} else if (pic_platform_get()->entropy(k->owner, 32) != 0) {
(void)snprintf(err, cap, "no entropy for a key");
rc = -1;
} else {
pic_noise_id(k->mailbox, "pic-rc/1 mailbox", k->owner);
rc = rmt_key_write(db, names[i], k->mailbox, 16, k->owner, 32, err, cap);
}
} else if (i < 2) {
pic_noise_keypair *kp = i == 0 ? &k->stat : &k->vapid;
if (sn != 32 || pn != PIC_NOISE_PUB || pic_noise_keypair_make(kp, sec) != 0 || memcmp(kp->pub, pub, pn) != 0) {
(void)snprintf(err, cap, "the remote key %s is damaged", names[i]);
rc = -1;
}
} else {
unsigned char m[16];
memcpy(k->owner, sec, 32);
pic_noise_id(m, "pic-rc/1 mailbox", k->owner);
if (sn != 32 || pn != 16 || memcmp(m, pub, 16) != 0) {
(void)snprintf(err, cap, "the remote key mailbox is damaged");
rc = -1;
}
memcpy(k->mailbox, m, 16);
}
}
}
pic_cred_wipe(sec, sizeof sec);
if (create) {
(void)sqlite3_exec(db, rc == 0 ? "COMMIT" : "ROLLBACK", NULL, NULL, NULL);
}
return rc;
}
static void rmt_device_aad(const unsigned char id[16], char out[64]) {
char hex[33];
rmt_hex(id, 16, hex);
(void)snprintf(out, 64, "remote-device:%s", hex);
}
/* Every device row that opens under the store's key, oldest first: *OUT (malloc'd) and *N. A row
* that does not open is not a device, and is counted in *BAD. 0, or -1 with err. */
static int rmt_devices_load(rmt_device **out, int *n, int *bad, char *err, size_t cap) {
sqlite3 *db = pic_userdb(err, cap);
sqlite3_stmt *q = NULL;
rmt_device *list = NULL;
int count = 0, room = 0;
*out = NULL;
*n = 0;
if (bad) {
*bad = 0;
}
if (!db || sqlite3_prepare_v2(db, "SELECT id, sealed, paired_ms, coalesce(seen_ms, 0) FROM picu_remote_device ORDER BY paired_ms",
-1, &q, NULL) != SQLITE_OK) {
if (db) {
(void)snprintf(err, cap, "%s", sqlite3_errmsg(db));
}
return -1;
}
while (sqlite3_step(q) == SQLITE_ROW) {
rmt_device d;
char aad[64], *plain, *name = NULL, *stat = NULL, *chan = NULL, *push = NULL;
size_t sn = (size_t)sqlite3_column_bytes(q, 1);
int ok = 0;
memset(&d, 0, sizeof d);
if (sqlite3_column_bytes(q, 0) != 16 || sn < PIC_CRED_OVERHEAD + 2 || sn > 65536 + PIC_CRED_OVERHEAD) {
if (bad) {
(*bad)++;
}
continue;
}
memcpy(d.id, sqlite3_column_blob(q, 0), 16);
rmt_device_aad(d.id, aad);
if (!(plain = malloc(sn - PIC_CRED_OVERHEAD + 1))) {
break;
}
if (pic_cred_unbox(aad, sqlite3_column_blob(q, 1), sn, plain, err, cap) == 0) {
plain[sn - PIC_CRED_OVERHEAD] = '\0';
name = rmt_q("SELECT json_extract(?1, '$.name')", 1, plain);
stat = rmt_q("SELECT json_extract(?1, '$.static')", 1, plain);
chan = rmt_q("SELECT json_extract(?1, '$.channel')", 1, plain);
push = rmt_q("SELECT CASE json_type(?1, '$.push') WHEN 'object' THEN json_extract(?1, '$.push') END", 1, plain);
ok = name && stat && chan && pic_b64u_dec(stat, strlen(stat), d.stat, sizeof d.stat) == PIC_NOISE_PUB &&
pic_b64u_dec(chan, strlen(chan), d.channel, sizeof d.channel) == 16;
if (ok) {
(void)snprintf(d.name, sizeof d.name, "%s", name);
}
if (ok && push) { /* a subscription that does not read is none */
char *ep = rmt_q("SELECT json_extract(?1, '$.endpoint')", 1, push);
char *pk = rmt_q("SELECT json_extract(?1, '$.p256dh')", 1, push);
char *au = rmt_q("SELECT json_extract(?1, '$.auth')", 1, push);
char *nt = rmt_q("SELECT json_extract(?1, '$.notify')", 1, push);
if (ep && pk && au && nt && strlen(ep) < sizeof d.endpoint && (!strcmp(nt, "all") || !strcmp(nt, "remote")) &&
pic_b64u_dec(pk, strlen(pk), d.p256dh, sizeof d.p256dh) == PIC_WEBPUSH_PUB &&
pic_b64u_dec(au, strlen(au), d.auth, sizeof d.auth) == PIC_WEBPUSH_AUTH) {
(void)snprintf(d.endpoint, sizeof d.endpoint, "%s", ep);
(void)snprintf(d.notify, sizeof d.notify, "%s", nt);
}
free(ep);
free(pk);
free(au);
free(nt);
}
pic_cred_wipe(plain, sn - PIC_CRED_OVERHEAD);
}
free(plain);
free(name);
free(stat);
free(chan);
free(push);
if (!ok) {
if (bad) {
(*bad)++;
}
continue;
}
d.paired_ms = sqlite3_column_int64(q, 2);
d.seen_ms = sqlite3_column_int64(q, 3);
if (count == room) {
rmt_device *grown = realloc(list, (size_t)(room = room ? room * 2 : 8) * sizeof *grown);
if (!grown) {
break;
}
list = grown;
}
list[count++] = d;
}
sqlite3_finalize(q);
*out = list;
*n = count;
return 0;
}
/* D's row sealed: a new one (ADD), or the existing one's sealed column replaced. 0, or -1 with err. */
static int rmt_device_write(const rmt_device *d, int add, char *err, size_t cap) {
sqlite3 *db = pic_userdb(err, cap);
sqlite3_stmt *q = NULL;
char aad[64], stat[100], chan[32], pk[100], au[32], *json;
unsigned char *box;
size_t n;
int rc = -1;
if (!db) {
return -1;
}
pic_b64u_enc(d->stat, sizeof d->stat, stat);
pic_b64u_enc(d->channel, sizeof d->channel, chan);
pic_b64u_enc(d->p256dh, sizeof d->p256dh, pk);
pic_b64u_enc(d->auth, sizeof d->auth, au);
if (!(json = rmt_q("SELECT json_object('name', ?1, 'static', ?2, 'channel', ?3, 'push', CASE WHEN ?7 = '' THEN json('null')"
" ELSE json_object('endpoint', ?4, 'p256dh', ?5, 'auth', ?6, 'notify', ?7) END)",
7, d->name, stat, chan, d->endpoint, pk, au, d->notify))) {
(void)snprintf(err, cap, "out of memory");
return -1;
}
n = strlen(json);
rmt_device_aad(d->id, aad);
if ((box = malloc(n + PIC_CRED_OVERHEAD)) && pic_cred_box(aad, json, n, box, err, cap) == 0 &&
sqlite3_prepare_v2(db,
add ? "INSERT INTO picu_remote_device(id, sealed, paired_ms) VALUES(?1, ?2, ?3)"
: "UPDATE picu_remote_device SET sealed = ?2 WHERE id = ?1",
-1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_blob(q, 1, d->id, 16, SQLITE_STATIC);
sqlite3_bind_blob(q, 2, box, (int)(n + PIC_CRED_OVERHEAD), SQLITE_STATIC);
if (add) {
sqlite3_bind_int64(q, 3, rmt_wall_ms());
}
rc = sqlite3_step(q) == SQLITE_DONE ? 0 : -1;
if (rc != 0) {
(void)snprintf(err, cap, "%s", sqlite3_errmsg(db));
}
}
sqlite3_finalize(q);
if (box) {
pic_cred_wipe(box, n + PIC_CRED_OVERHEAD);
}
free(box);
pic_cred_wipe(json, n);
free(json);
return rc;
}
static int rmt_device_add(const rmt_device *d, char *err, size_t cap) { return rmt_device_write(d, 1, err, cap); }
static void rmt_device_seen(const unsigned char id[16]) {
sqlite3 *db = pic_userdb(NULL, 0);
sqlite3_stmt *q = NULL;
if (db && sqlite3_prepare_v2(db, "UPDATE picu_remote_device SET seen_ms = ?2 WHERE id = ?1", -1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_blob(q, 1, id, 16, SQLITE_STATIC);
sqlite3_bind_int64(q, 2, rmt_wall_ms());
(void)sqlite3_step(q);
}
sqlite3_finalize(q);
}
static void rmt_device_delete(const unsigned char id[16]) {
sqlite3 *db = pic_userdb(NULL, 0);
sqlite3_stmt *q = NULL;
if (db && sqlite3_prepare_v2(db, "DELETE FROM picu_remote_device WHERE id = ?1", -1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_blob(q, 1, id, 16, SQLITE_STATIC);
(void)sqlite3_step(q);
}
sqlite3_finalize(q);
}
/* ---- the relay's API (section 6) ------------------------------------------------- */
typedef struct {
char base[512]; /* https://host[:port], no trailing slash */
char invite[512]; /* the setting remote.invite, or "" */
char owner[64]; /* b64u(owner token) */
char mbx[32]; /* b64u(mailbox id) */
pic_net *net;
int peer; /* the last POST's Pic-Peer: 1, 0, or -1 when it had none */
int last_status; /* the last call's HTTP status, 0 when it got no answer */
char ack[24]; /* Pic-Ack for the mailbox stream, sent with each call while set */
int acked; /* a call carried it and the relay took it */
} rmt_relay;
static void rmt_relay_init(rmt_relay *r, const rmt_keys *k) {
char *v = pic_setting("remote.relay");
size_t n;
memset(r, 0, sizeof *r);
(void)snprintf(r->base, sizeof r->base, "%s", v && *v ? v : PIC_REMOTE_RELAY);
free(v);
n = strlen(r->base);
while (n && r->base[n - 1] == '/') {
r->base[--n] = '\0';
}
v = pic_setting("remote.invite");
(void)snprintf(r->invite, sizeof r->invite, "%s", v ? v : "");
free(v);
if (k) {
pic_b64u_enc(k->owner, 32, r->owner);
pic_b64u_enc(k->mailbox, 16, r->mbx);
}
}
typedef struct {
char *buf;
size_t len, cap;
} rmt_buf;
static int rmt_buf_add(rmt_buf *b, const void *p, size_t n) {
if (b->len + n + 1 > b->cap) {
size_t cap = b->cap ? b->cap : 1024;
char *grown;
while (cap < b->len + n + 1) {
cap *= 2;
}
if (!(grown = realloc(b->buf, cap))) {
return -1;
}
b->buf = grown;
b->cap = cap;
}
memcpy(b->buf + b->len, p, n);
b->len += n;
b->buf[b->len] = '\0';
return 0;
}
static int rmt_collect(void *ctx, const char *bytes, size_t n) {
rmt_buf *b = ctx;
return b->len + n > 65536 ? 0 : rmt_buf_add(b, bytes, n) == 0 ? 0 : 1;
}
/* METHOD PATH (after the base) with the bearer token AUTH (b64u) and BODY: the status, the
* response body in *RESP (malloc'd, may be NULL), or -1 with err. */
static int rmt_call(rmt_relay *r, const char *method, const char *path, const char *auth, const char *body, size_t n,
const char *ctype, char **resp, char *err, size_t cap) {
char url[1024], ah[128], ch[128], ih[600], kh[48];
const char *hdrs[4];
size_t nh = 0;
pic_http_resp hr;
rmt_buf b = {NULL, 0, 0};
int rc;
if (resp) {
*resp = NULL;
}
if (!r->net && !(r->net = pic_net_new(err, cap))) {
return -1;
}
(void)snprintf(url, sizeof url, "%s%s", r->base, path);
(void)snprintf(ah, sizeof ah, "Authorization: Bearer %s", auth);
hdrs[nh++] = ah;
if (ctype) {
(void)snprintf(ch, sizeof ch, "Content-Type: %s", ctype);
hdrs[nh++] = ch;
}
if (r->invite[0] && strcmp(method, "PUT") == 0 && strchr(path + 6, '/') == NULL) {
(void)snprintf(ih, sizeof ih, "Pic-Invite: %s", r->invite);
hdrs[nh++] = ih;
}
if (r->ack[0]) {
(void)snprintf(kh, sizeof kh, "Pic-Ack: %s", r->ack);
hdrs[nh++] = kh;
}
pic_http_resp_init(&hr, rmt_collect, &b);
rc = pic_http_request(r->net, method, url, hdrs, nh, body, n, &hr, 15, 30, err, cap);
pic_cred_wipe(ah, sizeof ah);
r->peer = hr.peer[0] == '1' ? 1 : hr.peer[0] == '0' ? 0 : -1;
r->last_status = rc != 0 ? 0 : hr.status;
r->acked |= r->ack[0] && rc == 0 && hr.status >= 200 && hr.status < 300;
if (rc != 0) {
free(b.buf);
return -1;
}
if (resp) {
*resp = b.buf;
} else {
free(b.buf);
}
return hr.status;
}
static int rmt_put_mailbox(rmt_relay *r, char *err, size_t cap) {
char path[128];
int st;
(void)snprintf(path, sizeof path, "/v1/m/%s", r->mbx);
st = rmt_call(r, "PUT", path, r->owner, "", 0, "application/json", NULL, err, cap);
if (st >= 200 && st < 300) {
return 0;
}
if (st > 0) {
if (st == 403) {
(void)snprintf(err, cap, "the relay %s makes mailboxes by invitation: set it with pic settings remote.invite INVITE",
r->base);
} else if (st == 429) {
(void)snprintf(err, cap, "the relay %s refused a new mailbox for now (HTTP 429): try again later", r->base);
} else {
(void)snprintf(err, cap, "the relay %s refused the mailbox (HTTP %d)", r->base, st);
}
}
return -1;
}
static int rmt_put_channel(rmt_relay *r, const unsigned char ch[16], int pair, char *err, size_t cap) {
char path[128], id[32];
const char *body = pair ? "{\"kind\":\"pair\",\"ttl\":600}" : "{\"kind\":\"device\"}";
int st;
pic_b64u_enc(ch, 16, id);
(void)snprintf(path, sizeof path, "/v1/m/%s/c/%s", r->mbx, id);
st = rmt_call(r, "PUT", path, r->owner, body, strlen(body), "application/json", NULL, err, cap);
if (st >= 200 && st < 300) {
return 0;
}
if (st > 0) {
(void)snprintf(err, cap, st == 409 ? "the relay holds at most 8 phones for one computer: unpair one first (pic remote devices)"
: "the relay refused a channel (HTTP %d)",
st);
}
return -1;
}
static void rmt_delete_channel(rmt_relay *r, const unsigned char ch[16]) {
char path[128], id[32], err[256];
pic_b64u_enc(ch, 16, id);
(void)snprintf(path, sizeof path, "/v1/m/%s/c/%s", r->mbx, id);
(void)rmt_call(r, "DELETE", path, r->owner, NULL, 0, NULL, NULL, err, sizeof err);
}
/* ---- the stream thread (section 3) --------------------------------------------------- */
/* What the thread writes to the loop's pipe: a kind, the channel, a length, then the record. */
enum { RMT_EV_FRAME = 'F', RMT_EV_GONE = 'G', RMT_EV_REPLACED = 'R', RMT_EV_REFUSED = 'X', RMT_EV_PEER = 'P' };
/* The stream's state, for pic remote status: set by the thread, read by the loop. */
enum { RMT_CONN_CONNECTING, RMT_CONN_CONNECTED, RMT_CONN_WAITING };
typedef struct {
char url[1024];
char auth[128];
int mailbox; /* the mailbox stream: data is b64u(C).b64u(record) */
unsigned char channel[16];
int wfd;
char last[64];
pthread_t th;
int started;
atomic_int kick; /* the loop saw a wake: drop this connection and reconnect at once */
atomic_int state; /* RMT_CONN_* */
atomic_int attempts; /* failed connections since the last one that worked */
atomic_llong opened_ms; /* wall ms the current stream opened, or 0 while there is none */
atomic_llong recycles; /* streams the relay ended cleanly after RMT_RECYCLE_MS or more */
long long ended_ms; /* mono ms the last stream ended (the stream's thread only), or 0 */
atomic_llong retry_at; /* wall ms of the next try while waiting */
char why[256]; /* the last failure, written before state changes */
/* what the mailbox stream has read: the last event id, and records and bytes so far */
atomic_llong read_id, read_records, read_bytes;
atomic_llong heard_ms; /* mono ms of the last record, or of the connection when none came yet */
int asked; /* this connection was dropped for a kick (the stream's thread only) */
/* A pairing channel's stream in pic remote: told to quit when its offer ends, and freed by
* whichever of the loop and the thread lets go of it last. */
atomic_int quit;
atomic_int refs; /* 2 while both hold it; 0 for a stream that is not on the heap */
} rmt_stream;
/* Two streams may write one pipe (pic remote's mailbox stream and an offer's): an event is
* written whole under this lock. */
static pthread_mutex_t rmt_pipe_mu = PTHREAD_MUTEX_INITIALIZER;
static void rmt_stream_put(rmt_stream *s, int kind, const unsigned char ch[16], const unsigned char *rec, size_t n) {
unsigned char head[19];
head[0] = (unsigned char)kind;
memcpy(head + 1, ch, 16);
head[17] = (unsigned char)(n >> 8);
head[18] = (unsigned char)n;
pthread_mutex_lock(&rmt_pipe_mu);
if (write(s->wfd, head, sizeof head) != (ssize_t)sizeof head || (n && write(s->wfd, rec, n) != (ssize_t)n)) {
rmt_stop = 1;
}
pthread_mutex_unlock(&rmt_pipe_mu);
}
/* Lets go of a heap stream: the last of the loop and its thread to do so frees it. */
static void rmt_stream_release(rmt_stream *s) {
if (s && atomic_fetch_sub(&s->refs, 1) == 1) {
free(s);
}
}
static int rmt_on_event(void *ctx, const char *event, const char *data, size_t len) {
rmt_stream *s = ((void **)ctx)[0];
pic_sse *p = ((void **)ctx)[1];
if (strcmp(event, "frame") == 0) {
unsigned char ch[16], rec[PIC_NOISE_RECORD_CAP];
const char *dot = s->mailbox ? memchr(data, '.', len) : NULL;
const char *r = dot ? dot + 1 : data;
long n;
memcpy(ch, s->channel, 16);
if (s->mailbox && (!dot || pic_b64u_dec(data, (size_t)(dot - data), ch, 16) != 16)) {
return 0;
}
n = pic_b64u_dec(r, len - (size_t)(r - data), rec, sizeof rec);
if (n > 0) {
rmt_stream_put(s, RMT_EV_FRAME, ch, rec, (size_t)n);
}
(void)snprintf(s->last, sizeof s->last, "%s", p->last_id);
if (s->mailbox) {
atomic_store(&s->read_id, strtoll(p->last_id, NULL, 10));
atomic_fetch_add(&s->read_records, 1);
atomic_fetch_add(&s->read_bytes, (long long)len);
atomic_store(&s->heard_ms, rmt_mono_ms());
}
} else if (strcmp(event, "gone") == 0) {
rmt_stream_put(s, RMT_EV_GONE, s->channel, NULL, 0);
return 1;
} else if (strcmp(event, "replaced") == 0) {
rmt_stream_put(s, RMT_EV_REPLACED, s->channel, NULL, 0);
return 1;
} else if (strcmp(event, "peer") == 0) { /* "1" or "0"; "C.1" or "C.0" on the mailbox stream */
unsigned char ch[16], on;
const char *dot = s->mailbox ? memchr(data, '.', len) : NULL;
memcpy(ch, s->channel, 16);
if (s->mailbox && (!dot || pic_b64u_dec(data, (size_t)(dot - data), ch, 16) != 16)) {
return 0;
}
on = (unsigned char)(dot ? dot + 1 < data + len && dot[1] == '1' : len && data[0] == '1');
rmt_stream_put(s, RMT_EV_PEER, ch, &on, 1);
}
return 0;
}
static int rmt_stream_body(void *ctx, const char *bytes, size_t n) {
rmt_stream *s = ((void **)ctx)[0];
pic_sse *p = ((void **)ctx)[1];
int rc;
if (atomic_exchange(&s->kick, 0) || atomic_load(&s->quit)) {
s->asked = 1;
return 1; /* a wake: this connection may be a ghost; a new one resumes from Last-Event-ID */
}
if (atomic_load(&s->state) != RMT_CONN_CONNECTED) {
atomic_store(&s->attempts, 0);
if (!atomic_load(&s->opened_ms)) { /* opened before connected: status never says one without the other */
atomic_store(&s->opened_ms, rmt_wall_ms());
}
atomic_store(&s->state, RMT_CONN_CONNECTED);
}
rc = pic_sse_feed(p, bytes, n);
return rc < 0 ? 1 : rc;
}
/* A 200 to the stream's GET is a connection, though the relay may say nothing for 15 s. */
static int rmt_stream_head(void *ctx, const pic_http_resp *r) {
rmt_stream *s = ((void **)ctx)[0];
if (r->status == 200) {
atomic_store(&s->heard_ms, rmt_mono_ms());
}
if (r->status == 200 && atomic_load(&s->state) != RMT_CONN_CONNECTED) {
atomic_store(&s->attempts, 0);
atomic_store(&s->opened_ms, rmt_wall_ms());
atomic_store(&s->state, RMT_CONN_CONNECTED);
if (s->mailbox && s->ended_ms && rmt_mono_ms() - s->ended_ms > RMT_SLOW_REOPEN_MS) { /* a slow way back is worth a line */
rmt_log(stdout, "pic remote: the stream reopened %.1f s after it ended\n", (double)(rmt_mono_ms() - s->ended_ms) / 1000);
(void)fflush(stdout);
}
s->ended_ms = 0;
}
return 0;
}
/* How long a stream lasts before a clean end of it by the relay is a recycle, not news. */
static long long rmt_recycle_ms(void) {
#ifdef PIC_FAULTS
if (getenv("PIC_TEST_RC_RECYCLE_MS")) { /* the tests' seam */
return atoll(getenv("PIC_TEST_RC_RECYCLE_MS"));
}
#endif
return RMT_RECYCLE_MS;
}
static int rmt_idle_s(void) {
#ifdef PIC_FAULTS
if (getenv("PIC_TEST_RC_IDLE")) { /* the soak test's seam: a dead stream noticed in seconds */
return atoi(getenv("PIC_TEST_RC_IDLE"));
}
#endif
return RMT_IDLE_S;
}
static long long rmt_quiet_ms(void) {
#ifdef PIC_FAULTS
if (getenv("PIC_TEST_RC_QUIET_MS")) { /* the tests' seam: a stream bringing no records dropped in seconds */
return atoll(getenv("PIC_TEST_RC_QUIET_MS"));
}
#endif
return RMT_QUIET_MS;
}
/* Reconnects with Last-Event-ID after 1 s, doubling to 60, each wait varied by a fifth either way;
* a connection that lasted 30 s resets the wait, a wake (the loop's kick) skips it, and none lasts
* more than 15 minutes. A connection with no byte for RMT_IDLE_S (the relay comments every 15 s)
* is taken for dead. */
static void *rmt_stream_main(void *arg) {
rmt_stream *s = arg;
long long wait = 1000;
char err[256];
pic_net *net = pic_net_new(err, sizeof err);
while (!rmt_stop && !atomic_load(&s->quit) && net) {
char ah[160], lh[100];
const char *hdrs[3] = {ah, "Accept: text/event-stream", lh};
pic_sse p;
pic_http_resp r;
void *ctx[2] = {s, &p};
long long t0 = rmt_mono_ms();
int rc;
(void)snprintf(ah, sizeof ah, "Authorization: Bearer %s", s->auth);
(void)snprintf(lh, sizeof lh, "Last-Event-ID: %s", s->last);
if (pic_sse_init(&p, 65536, 2 * PIC_NOISE_RECORD_CAP + 64, rmt_on_event, ctx) != 0) {
break;
}
pic_http_resp_init(&r, rmt_stream_body, ctx);
r.on_head = rmt_stream_head;
atomic_store(&s->state, RMT_CONN_CONNECTING);
s->asked = 0;
rc = pic_http_get(net, s->url, hdrs, s->last[0] ? 3 : 2, &r, rmt_idle_s(), 900, err, sizeof err);
pic_sse_free(&p);
if (s->asked) {
(void)snprintf(s->why, sizeof s->why, "asked to reconnect");
} else if (rc != 0) {
(void)snprintf(s->why, sizeof s->why, "%s", err);
} else if (r.status != 200) {
(void)snprintf(s->why, sizeof s->why, "the relay answered HTTP %d", r.status);
} else {
(void)snprintf(s->why, sizeof s->why, "the relay ended the stream");
}
if (r.status == 401 || r.status == 404) { /* no mailbox or channel: nothing to wait for */
unsigned char st[2] = {(unsigned char)(r.status >> 8), (unsigned char)r.status};
rmt_stream_put(s, RMT_EV_REFUSED, s->channel, st, 2);
break;
}
if (rmt_mono_ms() - t0 >= 30000) {
wait = 1000;
}
atomic_store(&s->state, RMT_CONN_CONNECTING); /* not connected first, then no opening: never connected with none */
atomic_store(&s->opened_ms, 0);
if (!s->ended_ms) {
s->ended_ms = rmt_mono_ms() ? rmt_mono_ms() : 1;
}
/* The relay ends every stream after a while (60 to 90 s): a clean end of one that lasted is
* a recycle, reconnected at once, with no line and no attempt counted. */
if (!s->asked && rc == 0 && r.status == 200 && rmt_mono_ms() - t0 >= rmt_recycle_ms() && !atomic_load(&s->kick)) {
atomic_fetch_add(&s->recycles, 1);
atomic_store(&s->state, RMT_CONN_CONNECTING);
wait = 1000;
continue;
}
atomic_fetch_add(&s->attempts, 1);
{
unsigned char j;
long long w;
(void)pic_platform_get()->entropy(&j, 1);
w = wait - wait / 5 + (long long)j * (2 * wait / 5) / 255;
atomic_store(&s->retry_at, rmt_wall_ms() + w);
atomic_store(&s->state, RMT_CONN_WAITING);
if (s->mailbox && !rmt_stop) {
rmt_log(stdout, "pic remote: the stream ended (%s); reconnecting in %.1f s\n", s->why, (double)w / 1000);
}
for (long long t = 0; t < w && !rmt_stop && !atomic_load(&s->quit); t += 50) {
struct timespec ts = {0, 50000000L};
if (atomic_exchange(&s->kick, 0)) {
wait = 500; /* doubled below: the next wait after this try is a second */
break;
}
(void)nanosleep(&ts, NULL);
}
}
wait = wait * 2 > RMT_BACKOFF_MAX_MS ? RMT_BACKOFF_MAX_MS : wait * 2;
}
if (net) {
pic_net_free(net);
}
if (atomic_load(&s->refs)) {
rmt_stream_release(s);
}
return NULL;
}
static int rmt_stream_start(rmt_stream *s, int wfd) {
sigset_t all, was;
int rc;
s->wfd = wfd;
sigfillset(&all);
pthread_sigmask(SIG_BLOCK, &all, &was); /* signals are the loop's */
rc = pthread_create(&s->th, NULL, rmt_stream_main, s);
pthread_sigmask(SIG_SETMASK, &was, NULL);
s->started = rc == 0;
return rc == 0 ? 0 : -1;
}
/* Reads one whole event from the pipe: 1 with it, 0 when none is ready, -1 at its end. */
static int rmt_pipe_read(int fd, int *kind, unsigned char ch[16], unsigned char *rec, size_t *n) {
unsigned char head[19];
ssize_t got = read(fd, head, sizeof head);
size_t len, have = 0;
if (got < 0 && (errno == EAGAIN || errno == EINTR)) {
return 0;
}
if (got <= 0) {
return -1;
}
while ((size_t)got < sizeof head) { /* the rest is on its way: the writer writes it at once */
ssize_t more = read(fd, head + got, sizeof head - (size_t)got);
if (more > 0) {
got += more;
} else if (more == 0 || (errno != EAGAIN && errno != EINTR)) {
return -1;
}
}
len = ((size_t)head[17] << 8) | head[18];
while (have < len) {
ssize_t more = read(fd, rec + have, len - have);
if (more > 0) {
have += (size_t)more;
} else if (more == 0 || (errno != EAGAIN && errno != EINTR)) {
return -1;
}
}
*kind = head[0];
memcpy(ch, head + 1, 16);
*n = len;
return 1;
}
/* ---- lanes: what waits to be posted to a channel's down lane --------------------------- */
typedef struct {
unsigned char ch[16];
unsigned char *q; /* records, each as ms (8), length (2), bytes */
size_t qlen, qcap;
long long retry_ms;
int inflight; /* a post of the records at the front is with the poster: one at a time, in order */
unsigned epoch; /* raised when the front is taken another way: an older post's answer is not applied */
} rmt_lane;
static int rmt_lane_add(rmt_lane *l, const unsigned char *rec, size_t n) {
long long now = rmt_mono_ms();
if (l->qlen + n + 10 > l->qcap) {
size_t cap = l->qcap ? l->qcap : 65536;
unsigned char *grown;
while (cap < l->qlen + n + 10) {
cap *= 2;
}
if (cap > (64u << 20) || !(grown = realloc(l->q, cap))) {
return -1;
}
l->q = grown;
l->qcap = cap;
}
for (int i = 0; i < 8; i++) {
l->q[l->qlen + (size_t)i] = (unsigned char)((unsigned long long)now >> (8 * (7 - i)));
}
l->q[l->qlen + 8] = (unsigned char)(n >> 8);
l->q[l->qlen + 9] = (unsigned char)n;
memcpy(l->q + l->qlen + 10, rec, n);
l->qlen += n + 10;
return 0;
}
/* After a sleep or a stop: what waits was queued before it, not 30 s ago in waking time; it is
* posted now rather than dropped, and the next post is not held back. */
static void rmt_lane_restamp(rmt_lane *l) {
long long now = rmt_mono_ms();
for (size_t at = 0; at < l->qlen;) {
size_t n = ((size_t)l->q[at + 8] << 8) | l->q[at + 9];
for (int i = 0; i < 8; i++) {
l->q[at + (size_t)i] = (unsigned char)((unsigned long long)now >> (8 * (7 - i)));
}
at += 10 + n;
}
l->retry_ms = 0;
}
/* What waits, as one post's body (32 records, 256 KiB at most) in *BODY, and in *SENT_TO the bytes
* of the queue it takes; records older than 30 s are dropped unsent first, which the phone sees as
* a gap. The records it took, 0 when none wait, -1 out of memory. */
static int rmt_lane_body(rmt_lane *l, rmt_buf *body, size_t *sent_to) {
long long now = rmt_mono_ms();
size_t at = 0;
int nrec = 0;
while (at < l->qlen) { /* the stale ones first */
long long ms = 0;
size_t n = ((size_t)l->q[at + 8] << 8) | l->q[at + 9];
for (int i = 0; i < 8; i++) {
ms = (ms << 8) | l->q[at + (size_t)i];
}
if (now - ms < RMT_POST_WAIT_MS) {
break;
}
at += 10 + n;
}
if (at) {
memmove(l->q, l->q + at, l->qlen - at);
l->qlen -= at;
at = 0;
}
while (at < l->qlen && nrec < RMT_POST_RECORDS) {
size_t n = ((size_t)l->q[at + 8] << 8) | l->q[at + 9];
if (body->len + n + 2 > RMT_POST_BYTES) {
break;
}
if (rmt_buf_add(body, l->q + at + 8, n + 2) != 0) {
free(body->buf);
body->buf = NULL;
return -1;
}
at += 10 + n;
nrec++;
}
*sent_to = at;
return nrec;
}
/* The relay's answer ST (-1: none) to a post of the queue's first SENT_TO bytes. 0, or -1 when the
* post failed (kept for later, or dropped when the channel is gone). */
static int rmt_lane_posted(rmt_lane *l, int st, size_t sent_to) {
if (st >= 200 && st < 300) {
memmove(l->q, l->q + sent_to, l->qlen - sent_to);
l->qlen -= sent_to;
l->retry_ms = 0;
return 0;
}
if (st == 404 || st == 401) { /* the channel is gone: nobody can read these */
l->qlen = 0;
return -1;
}
l->retry_ms = rmt_mono_ms() + 1000;
return -1;
}
/* One post of what waits, here and now: for the pairing channel and for the last words on the way
* out; the loop's lanes go through the poster (rmt_lane_post). 0, or -1 when the post failed. */
static int rmt_lane_flush(rmt_relay *r, rmt_lane *l) {
rmt_buf body = {NULL, 0, 0};
size_t sent_to = 0;
int nrec, st;
char path[128], id[32], err[256];
if (!l->qlen || rmt_mono_ms() < l->retry_ms) {
return 0;
}
if (l->inflight) { /* the poster's answer is no longer this lane's; a record posted twice is a replay the phone drops */
l->inflight = 0;
l->epoch++;
}
if ((nrec = rmt_lane_body(l, &body, &sent_to)) <= 0) {
return nrec;
}
pic_b64u_enc(l->ch, 16, id);
(void)snprintf(path, sizeof path, "/v1/m/%s/c/%s/down", r->mbx, id);
st = rmt_call(r, "POST", path, r->owner, body.buf, body.len, "application/octet-stream", NULL, err, sizeof err);
free(body.buf);
return rmt_lane_posted(l, st, sent_to);
}
/* ---- the poster: posts to the relay off the loop ------------------------------------------- */
/* One post a poster thread makes for the loop: a lane's records, or the stream's acknowledgement
* alone (GET), and the relay's answer. */
typedef struct rmt_post {
struct rmt_post *next;
unsigned char ch[16];
unsigned epoch;
size_t sent_to;
char path[128];
char ack[24]; /* Pic-Ack it carries, or "" */
int get;
char *body;
size_t n;
int status; /* the relay's, or -1 for no answer */
int acked; /* it carried Pic-Ack and the relay took it */
} rmt_post;
/* Two threads, each with its own connection: one takes the oldest post, the other only small ones,
* so a pong or an answer never waits behind a large page on its way. A lane has one post with them
* at a time, so each phone's records go in order. */
#define RMT_POSTERS 2
typedef struct {
pthread_mutex_t mu;
pthread_cond_t cv;
rmt_post *todo, *done;
int started, acking;
int failed; /* no thread would start: the loop posts itself, as before the poster */
int wake; /* a byte here when a post is done: the loop's select wakes */
struct rmt_poster_thread {
void *po;
int quick;
rmt_relay r;
} t[RMT_POSTERS];
} rmt_poster;
static int rmt_post_small(const rmt_post *p) { return p->n <= RMT_POST_SMALL; }
static void *rmt_poster_main(void *arg) {
struct rmt_poster_thread *t = arg;
rmt_poster *po = t->po;
char err[256];
for (;;) {
rmt_post *p = NULL, **at;
int st;
(void)pthread_mutex_lock(&po->mu);
for (;;) {
for (at = &po->todo; *at && t->quick && !rmt_post_small(*at); at = &(*at)->next) {
}
if ((p = *at)) {
*at = p->next;
break;
}
(void)pthread_cond_wait(&po->cv, &po->mu);
}
(void)pthread_mutex_unlock(&po->mu);
(void)snprintf(t->r.ack, sizeof t->r.ack, "%s", p->ack);
t->r.acked = 0;
st = p->get ? rmt_call(&t->r, "GET", p->path, t->r.owner, NULL, 0, NULL, NULL, err, sizeof err)
: rmt_call(&t->r, "POST", p->path, t->r.owner, p->body, p->n, "application/octet-stream", NULL, err, sizeof err);
p->status = st;
p->acked = t->r.acked;
free(p->body);
p->body = NULL;
(void)pthread_mutex_lock(&po->mu);
p->next = po->done;
po->done = p;
(void)pthread_mutex_unlock(&po->mu);
while (write(po->wake, "p", 1) < 0 && errno == EINTR) {
}
}
return NULL;
}
/* The tests' seam: no poster thread starts, as when the system has none to give. */
static int rmt_poster_refused(void) {
#ifdef PIC_FAULTS
return getenv("PIC_TEST_RC_NO_POSTER") != NULL;
#else
return 0;
#endif
}
/* P to the poster, its threads started at the first: 0, or -1 (P freed; po->failed when no thread
* would start, said once, and the caller posts on the loop from then on). */
static int rmt_poster_queue(rmt_poster *po, const rmt_relay *r, int wake, rmt_post *p) {
rmt_post **at;
if (po->failed) {
free(p->body);
free(p);
return -1;
}
if (!po->started) {
pthread_attr_t a;
if (pthread_mutex_init(&po->mu, NULL) != 0 || pthread_cond_init(&po->cv, NULL) != 0) {
free(p->body);
free(p);
return -1;
}
po->wake = wake;
(void)pthread_attr_init(&a);
(void)pthread_attr_setdetachstate(&a, PTHREAD_CREATE_DETACHED);
for (int i = 0; i < RMT_POSTERS; i++) {
pthread_t th;
po->t[i].po = po;
po->t[i].quick = i > 0;
po->t[i].r = *r;
po->t[i].r.net = NULL; /* its own connection */
po->started += !rmt_poster_refused() && pthread_create(&th, &a, rmt_poster_main, &po->t[i]) == 0;
}
(void)pthread_attr_destroy(&a);
if (!po->started) {
po->failed = 1;
rmt_log(stdout, "pic remote: no poster thread would start; posting to the relay on the loop\n");
free(p->body);
free(p);
return -1;
}
}
(void)pthread_mutex_lock(&po->mu);
for (at = &po->todo; *at; at = &(*at)->next) {
}
p->next = NULL;
*at = p;
(void)pthread_cond_broadcast(&po->cv);
(void)pthread_mutex_unlock(&po->mu);
return 0;
}
/* L's next post, given to the poster unless one is with it already. */
static void rmt_lane_post(rmt_poster *po, rmt_relay *r, int wake, rmt_lane *l) {
rmt_buf body = {NULL, 0, 0};
rmt_post *p;
char id[32];
if (po->failed) {
(void)rmt_lane_flush(r, l);
return;
}
if (l->inflight || !l->qlen || rmt_mono_ms() < l->retry_ms) {
return;
}
if (!(p = calloc(1, sizeof *p))) {
return;
}
if (rmt_lane_body(l, &body, &p->sent_to) <= 0) {
free(body.buf);
free(p);
return;
}
memcpy(p->ch, l->ch, 16);
p->epoch = l->epoch;
p->body = body.buf;
p->n = body.len;
(void)snprintf(p->ack, sizeof p->ack, "%s", r->ack);
pic_b64u_enc(l->ch, 16, id);
(void)snprintf(p->path, sizeof p->path, "/v1/m/%s/c/%s/down", r->mbx, id);
if (rmt_poster_queue(po, r, wake, p) == 0) {
l->inflight = 1;
} else if (po->failed) {
(void)rmt_lane_flush(r, l);
}
}
/* The posts the poster has finished, taken by the loop: the caller applies and frees each. */
static rmt_post *rmt_poster_done(rmt_poster *po) {
rmt_post *d;
if (!po->started) {
return NULL;
}
(void)pthread_mutex_lock(&po->mu);
d = po->done;
po->done = NULL;
(void)pthread_mutex_unlock(&po->mu);
return d;
}
/* ---- sessions (section 3) --------------------------------------------------------------- */
typedef struct {
int used, confirmed;
int fails; /* records in a row that did not open */
int dev; /* index of its device */
unsigned char ch[16];
pic_noise_transport t;
long long started_ms, heard_ms, reset_ms, bye_ms;
rmt_buf msg; /* a message being assembled from its records */
} rmt_sess;
/* Equal in time that does not depend on where they differ. */
static int rmt_same(const unsigned char *a, const unsigned char *b, size_t n) {
volatile unsigned char d = 0;
for (size_t i = 0; i < n; i++) {
d |= a[i] ^ b[i];
}
return d == 0;
}
/* How often a connected phone's seen_ms is written again: "last seen" is now, give or take this. */
#define RMT_SEEN_MS 30000
static long long rmt_seen_every_ms(void) {
#ifdef PIC_FAULTS
if (getenv("PIC_TEST_RC_SEEN_MS")) { /* the tests' seam: written again after a fraction of a second */
return atoll(getenv("PIC_TEST_RC_SEEN_MS"));
}
#endif
return RMT_SEEN_MS;
}
static long long rmt_rekey_ms(void) {
#ifdef PIC_FAULTS
if (getenv("PIC_TEST_RC_REKEY_MS")) { /* the tests' seam: a session asked to start again in seconds */
return atoll(getenv("PIC_TEST_RC_REKEY_MS"));
}
#endif
return RMT_REKEY_MS;
}
/* An envelope message to a session: records of 16383 bytes at most, the last flagged 0x01. */
static int rmt_sess_send(rmt_sess *s, rmt_lane *l, const char *json) {
size_t n = strlen(json), at = 0;
unsigned char rec[PIC_NOISE_RECORD_CAP];
do {
size_t part = n - at > PIC_NOISE_CHUNK ? PIC_NOISE_CHUNK : n - at;
size_t rn = pic_noise_record(&s->t, at + part == n, json + at, part, rec);
if (rmt_lane_add(l, rec, rn) != 0) {
return -1;
}
at += part;
} while (at < n);
return 0;
}
/* Feeds a transport record's plaintext to S: 1 with a whole message in S->msg, 0 when more
* follows, -1 when it was too long. A gap inside a message discards the part received. */
static int rmt_sess_take(rmt_sess *s, int flag, const unsigned char *data, size_t n, int gap) {
if (gap) {
s->msg.len = 0;
}
if (s->msg.len + n > RMT_MSG_CAP) {
s->msg.len = 0;
return -1;
}
if (rmt_buf_add(&s->msg, data, n) != 0) {
return -1;
}
return flag == 1;
}
/* ---- an offer (section 2): its pairing channel, its one handshake, and the yes or no ------------- */
static void rmt_prologue(const unsigned char mailbox[16], const unsigned char ch[16], unsigned char out[41]) {
memcpy(out, "pic-rc/1", 8);
out[8] = 0;
memcpy(out + 9, mailbox, 16);
memcpy(out + 25, ch, 16);
}
/* A phone's name, for a terminal: each control character (C0, DEL, C1), bidi control and byte
* that is not UTF-8 becomes '?', in place. */
static void rmt_name_clean(char *s) {
const unsigned char *in = (const unsigned char *)s;
char *out = s;
while (*in) {
unsigned cp = *in;
size_t len = 1, k;
if (cp >= 0xc2 && cp <= 0xdf) {
len = 2, cp &= 0x1f;
} else if (cp >= 0xe0 && cp <= 0xef) {
len = 3, cp &= 0x0f;
} else if (cp >= 0xf0 && cp <= 0xf4) {
len = 4, cp &= 0x07;
} else if (cp >= 0x80) {
len = 0; /* a stray continuation byte or an invalid lead */
}
for (k = 1; k < len; k++) {
if ((in[k] & 0xc0) != 0x80) {
break;
}
cp = (cp << 6) | (in[k] & 0x3f);
}
if (len == 0 || k < len || (len == 3 && cp < 0x800) || (len == 4 && (cp < 0x10000 || cp > 0x10ffff)) ||
(cp >= 0xd800 && cp <= 0xdfff) || cp < 0x20 || (cp >= 0x7f && cp <= 0x9f) || cp == 0x061c || cp == 0x200e ||
cp == 0x200f || (cp >= 0x202a && cp <= 0x202e) || (cp >= 0x2066 && cp <= 0x2069)) {
*out++ = '?';
in += len && k == len ? len : 1;
continue;
}
memmove(out, in, len);
out += len;
in += len;
}
*out = '\0';
}
/* One offer: made by /rc (pic remote pair) or for a paired phone (pic remote), answered by the
* person there or by that phone. */
enum { OFFER_OPEN, OFFER_SHAKEN, OFFER_ASKING, OFFER_OVER };
enum { OFFER_EV_NONE, OFFER_EV_ASK, OFFER_EV_FAILED };
typedef struct {
int stage;
unsigned char P[16], psk[32], prologue[41], sid[8];
unsigned char m1[PIC_NOISE_RECORD_CAP], m2rec[600];
size_t m1n, m2n;
int fails, again, said;
char url[1024], vapid[100], host[256];
long long expires, mono_end; /* Unix seconds; the monotonic ms it ends at */
pic_noise_transport t;
rmt_device d; /* the device asking: its id (chosen here), name, static key and channel */
char sas[7];
rmt_lane lane;
rmt_buf msg;
} rmt_offer;
/* Makes the secret, registers the pairing channel and builds the QR code's address. */
static int rmt_offer_open(rmt_offer *o, rmt_relay *r, const rmt_keys *k, int ttl, char *err, size_t cap) {
unsigned char ps[32], ptok[32], offer[PIC_NOISE_OFFER];
char b64[200];
memset(o, 0, sizeof *o);
if (pic_platform_get()->entropy(ps, sizeof ps) != 0 || pic_platform_get()->entropy(o->d.id, sizeof o->d.id) != 0) {
(void)snprintf(err, cap, "no entropy");
return -1;
}
pic_noise_pair_derive(ps, o->psk, ptok, o->P);
pic_cred_wipe(ptok, sizeof ptok);
memcpy(o->lane.ch, o->P, 16);
if (rmt_put_channel(r, o->P, 1, err, cap) != 0) {
pic_cred_wipe(ps, sizeof ps);
pic_cred_wipe(o->psk, sizeof o->psk);
return -1;
}
o->expires = rmt_wall_ms() / 1000 + ttl;
o->mono_end = rmt_mono_ms() + 1000LL * ttl;
pic_noise_offer(k->mailbox, k->stat.pub, ps, (uint64_t)o->expires, offer);
pic_b64u_enc(offer, sizeof offer, b64);
(void)snprintf(o->url, sizeof o->url, "%s/#p1.%s", r->base, b64);
pic_cred_wipe(ps, sizeof ps);
pic_cred_wipe(offer, sizeof offer);
pic_cred_wipe(b64, sizeof b64);
(void)gethostname(o->host, sizeof o->host - 1);
rmt_prologue(k->mailbox, o->P, o->prologue);
pic_b64u_enc(k->vapid.pub, sizeof k->vapid.pub, o->vapid);
return 0;
}
/* A record from the pairing channel's up lane: OFFER_EV_ASK once the device has made the handshake
* and sent pair_ready (its name in o->d.name, the six digits in o->sas), OFFER_EV_FAILED when too
* many first messages failed to verify. */
static int rmt_offer_frame(rmt_offer *o, rmt_relay *r, const rmt_keys *k, const unsigned char *rec, size_t n) {
unsigned char pl[1024], m2[512];
size_t pn, mn;
if (n <= 9 || o->stage == OFFER_OVER) {
return OFFER_EV_NONE;
}
if (rec[0] == PIC_NOISE_REC_M1 && o->stage != OFFER_OPEN) {
/* One handshake an offer: the same first message again (the phone's stream reconnected)
* gets the same answer; any other, a second device's, nothing. */
if (n == o->m1n && memcmp(rec, o->m1, n) == 0 && ++o->again <= RMT_PAIR_AGAIN) {
(void)rmt_lane_add(&o->lane, o->m2rec, o->m2n);
(void)rmt_lane_flush(r, &o->lane);
}
return OFFER_EV_NONE;
}
if (rec[0] == PIC_NOISE_REC_M1) {
char *payload, *pname, *pchan, *pv, idb[32], *reply;
unsigned char chan[32], up[32], down[32];
pic_noise_hs hs;
pic_noise_hs_init(&hs, 0, &k->stat, NULL, o->psk, o->prologue, sizeof o->prologue);
if (pic_noise_read1(&hs, rec + 9, n - 9, pl, sizeof pl - 1, &pn) != 0) {
pic_noise_hs_wipe(&hs);
return ++o->fails >= RMT_PAIR_FAILS ? OFFER_EV_FAILED : OFFER_EV_NONE;
}
pl[pn] = '\0';
payload = (char *)pl;
pv = rmt_q("SELECT json_extract(?1, '$.v') >= 1", 1, payload);
pname = rmt_q("SELECT CASE json_type(?1, '$.name') WHEN 'text' THEN json_extract(?1, '$.name') END", 1, payload);
pchan = rmt_q("SELECT CASE json_type(?1, '$.channel') WHEN 'text' THEN json_extract(?1, '$.channel') END", 1, payload);
if (!pv || strcmp(pv, "1") != 0 || !pname || strlen(pname) > 64 || !*pname || !pchan ||
pic_b64u_dec(pchan, strlen(pchan), chan, sizeof chan) != 16) {
free(pv);
free(pname);
free(pchan);
pic_noise_hs_wipe(&hs);
return OFFER_EV_NONE;
}
rmt_name_clean(pname);
free(pv);
free(pchan);
pic_b64u_enc(o->d.id, 16, idb);
reply = rmt_q("SELECT json_object('v', 1, 'device', ?1, 'name', ?2, 'vapid', ?3)", 3, idb, o->host, o->vapid);
if (!reply || pic_noise_write2(&hs, reply, strlen(reply), m2, sizeof m2, &mn) != 0 ||
pic_noise_split(&hs, up, down) != 0) {
free(reply);
free(pname);
pic_cred_wipe(up, sizeof up);
pic_cred_wipe(down, sizeof down);
pic_noise_hs_wipe(&hs);
return OFFER_EV_NONE;
}
free(reply);
(void)snprintf(o->d.name, sizeof o->d.name, "%s", pname);
free(pname);
memcpy(o->d.stat, hs.rs, PIC_NOISE_PUB);
memcpy(o->d.channel, chan, 16);
memcpy(o->m1, rec, n);
o->m1n = n;
memcpy(o->sid, rec + 1, 8);
pic_noise_transport_init(&o->t, 0, o->sid, up, down);
pic_noise_sas(hs.h, o->sas);
pic_cred_wipe(up, sizeof up);
pic_cred_wipe(down, sizeof down);
pic_noise_hs_wipe(&hs);
o->m2n = pic_noise_head(PIC_NOISE_REC_M2, o->sid, m2, mn, o->m2rec);
(void)rmt_lane_add(&o->lane, o->m2rec, o->m2n);
(void)rmt_lane_flush(r, &o->lane);
o->stage = OFFER_SHAKEN;
o->msg.len = 0;
return OFFER_EV_NONE;
}
if (rec[0] == PIC_NOISE_REC_DATA && o->stage == OFFER_SHAKEN && memcmp(rec + 1, o->sid, 8) == 0) {
unsigned char data[PIC_NOISE_CHUNK];
size_t dn;
int flag, gap, ask = 0;
char *type;
if (pic_noise_open_record(&o->t, rec, n, &flag, data, &dn, &gap) != 0) {
return OFFER_EV_NONE;
}
if (gap || o->msg.len + dn > RMT_MSG_CAP) { /* a gap, or longer than any message */
o->msg.len = 0;
}
(void)rmt_buf_add(&o->msg, data, dn);
if (flag != 1) {
return OFFER_EV_NONE;
}
type = rmt_q("SELECT json_extract(?1, '$.type')", 1, o->msg.buf);
o->msg.len = 0;
if (type && strcmp(type, "pair_ready") == 0) {
o->stage = OFFER_ASKING;
ask = 1;
}
free(type);
return ask ? OFFER_EV_ASK : OFFER_EV_NONE;
}
return OFFER_EV_NONE;
}
static void rmt_offer_say(rmt_offer *o, rmt_relay *r, const char *json) {
unsigned char rec[PIC_NOISE_RECORD_CAP];
size_t rn = pic_noise_record(&o->t, 1, json, strlen(json), rec);
(void)rmt_lane_add(&o->lane, rec, rn);
o->said = 1;
(void)rmt_lane_flush(r, &o->lane);
}
/* Yes: the device row, its channel, then paired (section 2's order). The offer is over either way. */
static int rmt_offer_accept(rmt_offer *o, rmt_relay *r, char *err, size_t cap) {
if (o->stage != OFFER_ASKING) {
(void)snprintf(err, cap, "no device is waiting");
return -1;
}
o->stage = OFFER_OVER;
if (rmt_device_add(&o->d, err, cap) != 0) {
rmt_offer_say(o, r, "{\"type\":\"error\",\"payload\":{\"code\":\"pair_refused\"}}");
return -1;
}
if (rmt_put_channel(r, o->d.channel, 0, err, cap) != 0) { /* a row whose phone heard no would never connect */
rmt_device_delete(o->d.id);
rmt_offer_say(o, r, "{\"type\":\"error\",\"payload\":{\"code\":\"pair_refused\"}}");
return -1;
}
rmt_offer_say(o, r, "{\"type\":\"paired\"}");
return 0;
}
/* No, or the offer ended: a device that made the handshake hears so. */
static void rmt_offer_refuse(rmt_offer *o, rmt_relay *r) {
if (o->stage == OFFER_SHAKEN || o->stage == OFFER_ASKING) {
rmt_offer_say(o, r, "{\"type\":\"error\",\"payload\":{\"code\":\"pair_refused\"}}");
}
o->stage = OFFER_OVER;
}
static void rmt_offer_free(rmt_offer *o) {
pic_cred_wipe(o->psk, sizeof o->psk);
pic_cred_wipe(o->url, sizeof o->url);
pic_cred_wipe(&o->t, sizeof o->t);
free(o->msg.buf);
free(o->lane.q);
o->msg.buf = NULL;
o->lane.q = NULL;
}
/* ---- the envelope (section 4) --------------------------------------------------------- */
typedef struct {
char type[32], key[48], ptype[40];
char *session, *payload;
long long seq;
int has_seq;
} rmt_env;
static void rmt_env_free(rmt_env *e) {
free(e->session);
free(e->payload);
}
static int rmt_env_parse(const char *json, rmt_env *e) {
sqlite3 *m = rmt_mem();
sqlite3_stmt *q = NULL;
int rc = -1;
memset(e, 0, sizeof *e);
if (!m || sqlite3_prepare_v2(m,
"SELECT json_extract(?1, '$.type'), json_extract(?1, '$.session'), json_extract(?1, '$.seq'),"
" json_type(?1, '$.seq'), json_extract(?1, '$.key'),"
" CASE json_type(?1, '$.payload') WHEN 'object' THEN json_extract(?1, '$.payload') END,"
" CASE json_type(?1, '$.payload.type') WHEN 'text' THEN json_extract(?1, '$.payload.type') END"
" WHERE json_valid(?1) AND json_type(?1) = 'object' AND json_type(?1, '$.type') = 'text'",
-1, &q, NULL) != SQLITE_OK) {
return -1;
}
sqlite3_bind_text(q, 1, json, -1, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW) {
const char *t = (const char *)sqlite3_column_text(q, 0), *k = (const char *)sqlite3_column_text(q, 4);
const char *pt = (const char *)sqlite3_column_text(q, 6);
(void)snprintf(e->type, sizeof e->type, "%s", t ? t : "");
if (sqlite3_column_type(q, 1) == SQLITE_TEXT) {
e->session = strdup((const char *)sqlite3_column_text(q, 1));
}
e->has_seq = sqlite3_column_text(q, 3) && strcmp((const char *)sqlite3_column_text(q, 3), "integer") == 0;
e->seq = sqlite3_column_int64(q, 2);
if (k && sqlite3_column_type(q, 4) == SQLITE_TEXT) {
(void)snprintf(e->key, sizeof e->key, "%s", k);
}
if (sqlite3_column_type(q, 5) != SQLITE_NULL) {
e->payload = strdup((const char *)sqlite3_column_text(q, 5));
}
(void)snprintf(e->ptype, sizeof e->ptype, "%s", pt ? pt : "");
rc = 0;
}
sqlite3_finalize(q);
return rc;
}
/* A key is 16 to 43 characters of [A-Za-z0-9_-]. */
static int rmt_key_ok(const char *k) {
size_t n = strlen(k);
if (n < 16 || n > 43) {
return 0;
}
for (size_t i = 0; i < n; i++) {
char c = k[i];
if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '-')) {
return 0;
}
}
return 1;
}
/* ---- the serving state ------------------------------------------------------------------ */
typedef struct {
long long *v;
int n, cap;
} rmt_ids;
/* A conversation of the list (rmt_list), as its journal's query gave it. */
typedef struct {
int jx;
char id[64];
char *name, *title, *preview;
long long ms, seq, started; /* last activity, last entry, when it began (created_ms) */
long long deleted_ms; /* when it was deleted (in the trash, not purged); 0: not */
int running, attention, loops, asks, archived;
char perm[12]; /* its permission mode when not allow (perm.h); "" for allow */
} rmt_item;
typedef struct {
char *parent; /* JOURNAL/ID */
int n;
} rmt_helpers;
typedef struct {
char *path, *workspace;
char *real; /* path, resolved: what a helper's parent (pic_session_origin.parent) names it by */
/* The loop's: its part of the list, kept until the journal changes (a tick job builds it): -1,
* none yet; and the newest conversation's activity, for the workspaces of the list */
long long list_dv, list_tc, list_ms;
rmt_item *li;
size_t nli;
rmt_helpers *lh;
size_t nlh;
int list_slow; /* the last try ran out of time: said once */
int list_ready; /* looked at since it opened, or since a phone last asked: the first list waits for it */
unsigned list_gen; /* raised when a phone asks: a tick job queued before says nothing of readiness */
int open; /* served, as the loop knows it: set from sopen when a job of it is applied */
int hidden; /* no journal: never shown, looked at again when the registry names it */
char shown_why[256]; /* why it is not open, as the loop knows it */
const struct pic_context_policy *policy; /* get_session_stats' context estimate */
int busy; /* a job of it is in hand (the pool's lock): its lane */
int ticking, keeping; /* a tick job, a keeping job queued or running (the loop's) */
long long tick_ms, keep_ms;
pic_follow **dead; /* follows the loop let go of, freed by its next job (the pool's lock) */
int ndead, capdead;
/* The lane's, touched only by the job that holds it: */
pic_follow **follows; /* every follow open on s */
int nfollows;
int notjournal; /* the open found no journal there */
pic_store s;
int sopen;
int yielded; /* closed for a newer pic to migrate it: opened again after */
int older; /* not open because an older pic last used it: updated here once no pic has it (rmt_update) */
long long update_failed_ms; /* when updating it last failed with no pic in it (monotonic) */
char why[256];
long long version;
/* requests seen ending (section 5's When): every one above cut or in open ends here once */
long long push_cut, push_version;
rmt_ids push_open; /* admitted when this journal was first read */
rmt_ids push_told; /* above cut, already notified */
/* loops: when the journal was last asked what is due, and the newest change of a loop seen, so
* a loop that comes to need a person is told once (and a restart repeats nothing) */
long long wake_at, wake_seen;
int wake_init;
/* asks: the newest version told, and the data_version it was read at (rmt_ask_check) */
long long ask_version, ask_dv;
int ask_init;
/* asks that expired unanswered and were told so (rmt_ask_expiry), and when it last looked */
char ask_told[RMT_ASK_RING][PIC_ASK_ID_LEN + 1];
unsigned ask_told_at;
long long ask_expiry_ms;
} rmt_journal;
enum { CMD_INBOX = 1, CMD_PROMPT = 2, CMD_COMPACT = 3, CMD_DONE = 4 };
typedef struct {
int kind;
int jx;
int exited; /* a prompt's child has ended: one not admitted then failed */
char key[48]; /* the phone's */
char row[96]; /* rc:DEVICE:KEY */
char *line; /* the command, to tell a repeat from another command with the key */
pid_t pid; /* a prompt's child */
long long expire_ms; /* when its expiry was last looked at */
int errfd; /* its submit's stderr */
char err[512];
size_t errlen;
char conv[64]; /* a compaction's conversation */
char *answer; /* CMD_DONE: the response line a repeat of the key gets again */
} rmt_cmd;
/* A file a phone is sending (rmt_upload_msg): the part file's state, the lane's (only the upload's
* jobs touch it), and the loop's bookkeeping. */
typedef struct {
int dirfd, fd;
char part[128];
long long written;
char why[160]; /* the first failure, "" for none */
} rmt_upfile;
#define RMT_UPLOADS_OPEN 4 /* files one device sends at once */
typedef struct {
char id[48], name[129];
int jx;
long long size, next_n, last_ms;
rmt_upfile *f;
} rmt_upload;
/* A model or thinking level a phone chose for a conversation's next request (set_model,
* set_thinking_level): held here, as pic --mode rpc holds its own, until a request starts with it. */
typedef struct {
int jx;
char conv[64];
char model[256], thinking[32];
char key[PIC_CRED_LABEL_CAP]; /* the key, by label, of the model's provider (set_credential); "" none */
} rmt_choice;
typedef struct {
rmt_device d;
char idb[32]; /* b64u(id) */
rmt_lane lane;
int sess; /* its confirmed session, or -1 */
int alive; /* still in the table */
/* following one conversation */
int jx;
char conv[64];
char *wsess; /* the session as the phone named it, W/C */
char skey[48]; /* the sync's key, echoed on each event and mark of the follow; "" for none */
pic_follow *f; /* its journal's lane's: the loop only hands it to that journal's jobs */
unsigned fgen; /* raised at every sync and unfollow: a job's result for an older follow is dropped */
char *live_path; /* the conversation's .live file (pic_live_path) */
long long fversion;
int follow_now;
/* the conversation list it asked for */
int want_list;
int list_archived; /* it asked for the archived conversations too */
int list_trash; /* and for the deleted ones */
long long want_list_ms;
char *list_sent;
int seen_job; /* its seen_ms is being written */
rmt_cmd cmds[RMT_CMDS];
int ncmds;
long long fev; /* the highest seq of an event this follow sent */
int frunning; /* what its last mark said */
long long earlier; /* where a sync starts to show RMT_EARLIER more requests; -1: from the start already */
/* the live value (section 4): the file read, its head, the text read and the last 8 KiB of it */
long long live_ms, live_seq, live_pos, live_sent, live_chars;
dev_t live_dev;
ino_t live_ino;
size_t live_head, live_len;
char live_buf[RMT_LIVE_KEEP + 1];
/* notifications (section 5) */
int want_devices; /* asked for the device list in this session: sent again on each change */
int visible; /* the session's last presence */
int refused; /* 400s and 403s in a row */
long long push_hold_ms; /* nothing sent before this (a 429's Retry-After) */
struct {
unsigned long long conv;
long long ms;
} pushed[16]; /* the last notification per conversation */
long long seen_wr_ms; /* when seen_ms was last written (monotonic) */
/* files it is sending, its day's bytes, and the last files it finished (a repeat of upload_end) */
rmt_upload uploads[RMT_UPLOADS_OPEN];
int nuploads;
long long up_quota, up_since;
struct {
char id[48], path[160];
} upsaid[8];
unsigned upsaid_at;
} rmt_dev;
/* One notification on its way, and what came of it. */
typedef struct {
unsigned char dev[16];
char endpoint[RMT_ENDPOINT];
unsigned char p256dh[PIC_WEBPUSH_PUB], auth[PIC_WEBPUSH_AUTH];
char topic[PIC_WEBPUSH_TOPIC];
char *title, *session, *payload; /* payload: the plaintext, made by rmt_push_queue */
long long seq;
int shortened;
pic_webpush_result res;
} rmt_push;
typedef struct {
pthread_mutex_t mu;
pthread_cond_t cv;
rmt_push *todo[RMT_PUSH_QUEUE], *done[RMT_PUSH_QUEUE];
int ntodo, ndone, started;
int sending; /* one taken from todo and not yet done */
pic_webpush_vapid vapid;
char subject[512];
} rmt_pusher;
/* Counted for the log: the first is said at once, then one line every RMT_TALLY_MS at most. */
typedef struct {
long long n, said_ms;
} rmt_tally;
static int rmt_tally_due(rmt_tally *t) {
long long now = rmt_mono_ms();
if (t->n++ && now - t->said_ms < RMT_TALLY_MS) {
return 0;
}
t->said_ms = now;
return 1;
}
/* ---- work off the loop: jobs (docs/dev/remote.md's Jobs) ---------------------------------- */
/* The loop never waits on SQLite. Each piece of journal or user database work is a job: its run on
* one of RMT_WORKERS threads, then its done back on the loop, which applies what it found and
* posts its lines. A journal is a lane: one job of it at a time, in the order queued, its
* connection used by whichever worker holds the lane; the user database is one more lane. A lane
* is let go once the loop has applied its job, so one journal's answers go out in order. */
#define RMT_WORKERS 4
#define RMT_JOB_WAIT_MS 10000LL /* a command queued this long behind its journal is answered busy */
#define RMT_JOB_GRACE_MS 1000LL /* and one running this long past its budget, by the loop */
#define RMT_TICK_JOB_MS 100LL /* a journal's tick job (follows, notifications, asks) at most this often */
#define RMT_TICK_MS 5000 /* the budget of a tick job's statements */
#define RMT_USER_BUSY_MS 10000 /* a worker's wait for the user database another process writes: off the loop */
#define RMT_BACKGROUND_MS 500LL /* a tick or keeping job queued this long goes before the phones' commands */
/* The most work one phone message may do in the journals, and for how long: past either its
* statement is interrupted and the phone is told busy. */
#define RMT_MESSAGE_STEPS 50000000LL
#define RMT_MESSAGE_MS 2000
#define RMT_PURGE_MS 30000 /* a purge is one transaction under the conversation's lease: let it finish */
typedef struct rmt_state rmt_state;
typedef struct rmt_job rmt_job;
/* JSON lines, malloc'd, in the order they go. */
typedef struct {
char **v;
int n, cap;
} rmt_lines;
/* Notifications a job found to send (rmt_notify, on the loop): a request ended, a loop or a
* question needs the person. */
typedef struct {
char *conv, *ctitle, *body;
int phone;
long long seq;
} rmt_tnote;
typedef struct {
rmt_tnote *v;
int n, cap;
} rmt_tnotes;
/* A job's budget, enforced by a progress handler on its journal's connection: past its deadline
* or its steps its statement is interrupted; INNER is a part's own shorter deadline (the list's). */
typedef struct {
long long steps, most, deadline, inner;
int spent;
atomic_int *fate; /* the job's: once its work committed, no deadline cuts what follows short */
} rmt_budget;
enum { RMT_JOB_QUEUED, RMT_JOB_RUNNING, RMT_JOB_FINISHED };
/* A command's journal work and the loop's busy answer exclude each other, so busy is never said of
* a command that took effect: the first commit claims the job (COMMITTED), and the loop answers
* busy only if it claims it first (ABANDONED), after which the job's commits roll back. */
enum { RMT_FATE_OPEN, RMT_FATE_COMMITTED, RMT_FATE_ABANDONED };
struct rmt_job {
rmt_job *next; /* in the pool's queue, then its finished list (the pool's lock) */
rmt_job *held; /* in the loop's list of jobs in hand */
rmt_journal *j; /* its lane; NULL: the user database's */
int jx;
int user; /* calls into pic's own state (settings, keys, models, the registry): holds rmt_user_mu */
void (*run)(rmt_job *);
void (*done)(rmt_state *, rmt_job *);
void (*drop)(void *); /* frees ctx and what it holds */
void *ctx;
char what[192]; /* what it does, for the log and the tests' seams */
char answering[80]; /* a phone's message: its type, for the tests' count of the work */
/* the device it answers, by index and id: the loop's array may grow while it runs */
int di;
unsigned char dev[16];
char idb[32], dname[72];
char key[48]; /* a command's key: answered busy when it overruns; a repeat joins it */
char (*alias)[48]; /* the keys of the same question it took over (coalesced): answered with it */
int nalias;
int background; /* tick, keeping and look jobs: after the phones' commands, unless they waited long */
char *line; /* that command, to tell a repeat from another command with the key */
long long budget_ms, queued_ms;
atomic_int state;
atomic_llong started_ms;
int answered; /* the loop answered busy for it: what it finds is not sent */
atomic_int fate; /* RMT_FATE_*: whether its journal work committed, or the loop gave up on it first */
int slow_said, overran;
long long steps;
rmt_lines out; /* for the device */
};
typedef struct {
pthread_mutex_t mu;
pthread_cond_t cv;
rmt_job *head, *tail, *fin, *fin_tail;
int user_busy; /* the user database's lane */
int last; /* the device whose command was taken last (-1: none): the next goes to another */
int started;
int wake[2]; /* a byte when a job finishes: the loop's select wakes */
} rmt_pool;
/* A record on a channel no device has, kept until the devices are read again (a phone paired a
* moment ago in another process): answered then rather than dropped and asked again. */
typedef struct {
unsigned char ch[16];
unsigned char *rec;
size_t n;
} rmt_stashed;
#define RMT_STASH 16
struct rmt_state {
const pic_remote_options *o;
rmt_keys k;
rmt_relay r;
rmt_dev *devs;
int ndevs;
rmt_sess sess[RMT_SESSIONS];
rmt_journal **js; /* pointers: a follower holds its journal's store */
int njs;
long long user_version;
int lockfd;
long long live_rev; /* every live value this process sends has a higher one */
rmt_pusher push;
rmt_poster post;
long long acked; /* the highest stream id a call carried in Pic-Ack and the relay took */
rmt_choice choices[RMT_CHOICES];
int nchoices;
int pipe_w; /* the streams' pipe, for an offer's stream */
/* pairing from a paired phone: one offer at a time, the device that asked for it, and, once
* it is over, how long its last word may wait for the new device to read it */
rmt_offer *offer;
rmt_stream *offer_str;
int offer_dev, offer_posted, offer_reading;
long long offer_close_ms;
unsigned offer_serial; /* raised with each offer: an add job knows whether its offer is still the one */
int offer_adding; /* the approved device's row is being written */
/* records dropped and sessions reset, for the log */
rmt_tally dropped_unknown, dropped_again, reset_unknown, kept_unknown;
/* the work off the loop */
rmt_pool pool;
rmt_job *held; /* every job in hand, queued, running or finished and not yet applied */
int newer; /* a newer pic waits to start */
int draining; /* and nothing is under way: no new tick, keeping or user jobs until the jobs in hand end */
char *names; /* the devices' names by id (rmt_device_names), made again when they change */
unsigned user_gen; /* raised at each device row this process writes: an older read of the table is stale */
int user_job, user_force;
long long user_ms;
char *folders; /* the folders a phone may start a conversation in (rmt_folders_scan), as JSON */
rmt_stashed stash[RMT_STASH];
int nstash;
};
/* What the poster finished: each lane's answer applied, unless the lane's front was taken another
* way meanwhile (its epoch moved on); the acknowledgements the relay took. */
static void rmt_posts_apply(rmt_state *st) {
rmt_post *p = rmt_poster_done(&st->post), *next;
for (; p; p = next) {
next = p->next;
if (p->acked && atoll(p->ack) > st->acked) {
st->acked = atoll(p->ack);
}
if (p->get) {
st->post.acking = 0;
}
for (int i = 0; !p->get && i < st->ndevs; i++) {
rmt_lane *l = &st->devs[i].lane;
if (l->inflight && l->epoch == p->epoch && memcmp(l->ch, p->ch, 16) == 0) {
l->inflight = 0;
(void)rmt_lane_posted(l, p->status, p->sent_to);
break;
}
}
free(p);
}
}
/* The stream's acknowledgement on its own (GET /v1/m/M/c with Pic-Ack), through the poster, one at
* a time. */
static void rmt_ack_post(rmt_state *st) {
rmt_post *p;
if (st->post.acking || !st->r.ack[0] || !(p = calloc(1, sizeof *p))) {
return;
}
p->get = 1;
(void)snprintf(p->ack, sizeof p->ack, "%s", st->r.ack);
(void)snprintf(p->path, sizeof p->path, "/v1/m/%s/c", st->r.mbx);
if (rmt_poster_queue(&st->post, &st->r, st->pool.wake[1], p) == 0) {
st->post.acking = 1;
} else if (st->post.failed) { /* on the loop, as before the poster */
char path[64], err[256];
(void)snprintf(path, sizeof path, "/v1/m/%s/c", st->r.mbx);
(void)rmt_call(&st->r, "GET", path, st->r.owner, NULL, 0, NULL, NULL, err, sizeof err);
}
}
static int rmt_send(rmt_state *st, rmt_dev *d, const char *json) {
if (!json || d->sess < 0) {
return -1;
}
return rmt_sess_send(&st->sess[d->sess], &d->lane, json);
}
static void rmt_send_free(rmt_state *st, rmt_dev *d, char *json) {
(void)rmt_send(st, d, json);
free(json);
}
static void rmt_error(rmt_state *st, rmt_dev *d, const char *key, const char *code, const char *message) {
rmt_send_free(st, d,
rmt_q("SELECT json_patch('{}', json_object('type', 'error', 'key', ?1, 'payload',"
" json_patch('{}', json_object('code', ?2, 'message', ?3))))",
3, key && *key ? key : NULL, code, message));
}
/* The paired devices' names by their b64u ids, as a JSON object (malloc'd): who answered. */
static char *rmt_device_names(rmt_state *st) {
char *out = strdup("{}");
for (int i = 0; out && i < st->ndevs; i++) {
char *more;
if (!st->devs[i].alive) {
continue;
}
more = rmt_q("SELECT json_set(?1, '$.\"' || ?2 || '\"', ?3)", 3, out, st->devs[i].idb, st->devs[i].d.name);
free(out);
out = more;
}
return out;
}
#define RMT_BUSY_TEXT "this conversation is busy on the computer; try again"
/* ---- the pool (the work off the loop) ----------------------------------------------------- */
/* pic's own state that is not a journal's (settings, keys, models, the registry): one job at a time
* calls into it, as one thread always did. */
static pthread_mutex_t rmt_user_mu = PTHREAD_MUTEX_INITIALIZER;
static _Thread_local rmt_budget *rmt_budget_now; /* the running job's, on a worker */
/* Before work that does not go through the journal's connection (the user database, the process's
* own state): claim the job as committed. 0: go ahead; -1: the loop answered busy already, so do
* nothing. Outside a keyed job it always goes ahead. */
static int rmt_job_claim(void) {
int open = RMT_FATE_OPEN;
atomic_int *fate = rmt_budget_now ? rmt_budget_now->fate : NULL;
return !fate || atomic_compare_exchange_strong(fate, &open, RMT_FATE_COMMITTED) ||
open == RMT_FATE_COMMITTED
? 0
: -1;
}
static void rmt_lines_add(rmt_lines *l, char *s) { /* takes S */
if (!s) {
return;
}
if (l->n == l->cap) {
int cap = l->cap ? l->cap * 2 : 4;
char **g = realloc(l->v, (size_t)cap * sizeof *g);
if (!g) {
free(s);
return;
}
l->v = g;
l->cap = cap;
}
l->v[l->n++] = s;
}
static void rmt_lines_free(rmt_lines *l) {
for (int i = 0; i < l->n; i++) {
free(l->v[i]);
}
free(l->v);
memset(l, 0, sizeof *l);
}
static void rmt_note(rmt_tnotes *t, const char *conv, const char *ctitle, int phone, long long seq, const char *body) {
rmt_tnote *n;
if (t->n == t->cap) {
int cap = t->cap ? t->cap * 2 : 4;
rmt_tnote *g = realloc(t->v, (size_t)cap * sizeof *g);
if (!g) {
return;
}
t->v = g;
t->cap = cap;
}
n = &t->v[t->n];
n->conv = strdup(conv ? conv : "");
n->ctitle = ctitle ? strdup(ctitle) : NULL;
n->body = strdup(body);
n->phone = phone;
n->seq = seq;
if (!n->conv || !n->body) {
free(n->conv);
free(n->ctitle);
free(n->body);
return;
}
t->n++;
}
static void rmt_notes_free(rmt_tnotes *t) {
for (int i = 0; i < t->n; i++) {
free(t->v[i].conv);
free(t->v[i].ctitle);
free(t->v[i].body);
}
free(t->v);
memset(t, 0, sizeof *t);
}
static int rmt_budget_spent(void *arg) {
rmt_budget *b = arg;
long long now;
b->steps += 100;
if (b->fate && atomic_load(b->fate) == RMT_FATE_COMMITTED) {
/* it took effect: no deadline cuts reading its answer short, but the step cap still bounds it */
return b->most && b->steps > b->most;
}
now = rmt_mono_ms();
if ((b->most && b->steps > b->most) || (b->deadline && now > b->deadline)) {
b->spent = 1;
return 1;
}
return b->inner && now > b->inner;
}
static char *rmt_error_json(const char *key, const char *code, const char *message) {
return rmt_q("SELECT json_patch('{}', json_object('type', 'error', 'key', ?1, 'payload',"
" json_patch('{}', json_object('code', ?2, 'message', ?3))))",
3, key && *key ? key : NULL, code, message);
}
static void rmt_out(rmt_job *jb, char *json) { rmt_lines_add(&jb->out, json); }
static void rmt_out_error(rmt_job *jb, const char *key, const char *code, const char *message) {
rmt_out(jb, rmt_error_json(key, code, message));
}
static void rmt_out_response(rmt_job *jb, const char *key, const char *line) {
rmt_out(jb, rmt_q("SELECT json_object('type', 'response', 'key', ?1, 'payload', json(?2))", 2, key, line));
}
/* A follow the lane no longer needs: closed, on the lane, unless it is closed already (a journal
* let go of closes all of its follows, and the loop may have given one of them back meanwhile). */
static void rmt_follow_forget(rmt_journal *j, pic_follow *f) {
for (int i = 0; i < j->nfollows; i++) {
if (j->follows[i] == f) {
j->follows[i] = j->follows[--j->nfollows];
pic_follow_free(f);
return;
}
}
}
/* F kept among J's follows, so a journal let go of closes it: 0, or -1 with F closed. */
static int rmt_follow_keep(rmt_journal *j, pic_follow *f) {
pic_follow **g = realloc(j->follows, (size_t)(j->nfollows + 1) * sizeof *g);
if (!g) {
pic_follow_free(f);
return -1;
}
j->follows = g;
j->follows[j->nfollows++] = f;
return 0;
}
#ifdef PIC_FAULTS
/* The tests' seams on a worker: PIC_TEST_RC_JOB_MS="TEXT:MS" sleeps MS in every job whose name has
* TEXT (a slow disk); PIC_TEST_RC_SLOW_PHASE, as the loop's phases, once. AFTER: the job's work is
* done, and PIC_TEST_RC_JOB_AFTER_MS sleeps instead (a worker held up after its commit). */
static void rmt_job_seams(const rmt_job *jb, int after) {
static atomic_int slept;
const char *names[2] = {"PIC_TEST_RC_JOB_MS", "PIC_TEST_RC_SLOW_PHASE"};
if (after) {
names[0] = "PIC_TEST_RC_JOB_AFTER_MS";
names[1] = NULL;
}
for (int k = 0; k < 2 && names[k]; k++) {
const char *v = getenv(names[k]), *colon = v ? strrchr(v, ':') : NULL;
char want[128];
if (!colon || (k == 1 && atomic_load(&slept))) {
continue;
}
(void)snprintf(want, sizeof want, "%.*s", (int)(colon - v), v);
if (strstr(jb->what, want)) {
long long ms = atoll(colon + 1);
struct timespec ts = {(time_t)(ms / 1000), (long)(ms % 1000) * 1000000L};
if (k == 1) {
atomic_store(&slept, 1);
}
(void)nanosleep(&ts, NULL);
}
}
}
#endif
#ifdef PIC_FAULTS
/* The tests' seam: PIC_TEST_RC_JOBS_LOG=1 says each job's queueing, start and end. */
static void rmt_job_trace(const char *what, const rmt_job *jb) {
if (getenv("PIC_TEST_RC_JOBS_LOG")) {
rmt_log(stdout, "pic remote: job %s %p lane %d bg %d dev %d: %s\n", what, (const void *)jb, jb->jx, jb->background, jb->di, jb->what);
}
}
#else
#define rmt_job_trace(what, jb) ((void)0)
#endif
/* The journal connection's commit hook while JB runs: nonzero turns the commit into a rollback. */
static int rmt_job_commit(void *arg) {
rmt_job *jb = arg;
int open = RMT_FATE_OPEN;
return !atomic_compare_exchange_strong(&jb->fate, &open, RMT_FATE_COMMITTED) && open == RMT_FATE_ABANDONED;
}
/* JB's work, on a worker (or on the loop before the workers start), within its budget. */
static void rmt_job_run(rmt_job *jb) {
rmt_budget b;
memset(&b, 0, sizeof b);
b.fate = jb->key[0] ? &jb->fate : NULL;
if (jb->budget_ms > 0) {
b.deadline = rmt_mono_ms() + jb->budget_ms;
b.most = RMT_MESSAGE_STEPS;
}
#ifdef PIC_FAULTS
rmt_job_seams(jb, 0);
#endif
if (jb->j && jb->j->sopen) {
sqlite3_progress_handler(jb->j->s.db, 100, rmt_budget_spent, &b);
if (jb->key[0]) {
(void)sqlite3_commit_hook(jb->j->s.db, rmt_job_commit, jb);
}
}
if (jb->user) {
(void)pthread_mutex_lock(&rmt_user_mu);
}
rmt_budget_now = &b;
jb->run(jb);
#ifdef PIC_FAULTS
rmt_job_seams(jb, 1);
#endif
rmt_budget_now = NULL;
if (jb->user) {
(void)pthread_mutex_unlock(&rmt_user_mu);
}
if (jb->j && jb->j->sopen) {
sqlite3_progress_handler(jb->j->s.db, 0, NULL, NULL);
(void)sqlite3_commit_hook(jb->j->s.db, NULL, NULL);
}
jb->overran = b.spent;
jb->steps = b.steps;
}
/* The next job to run, taken, its lane held. Under the pool's lock. Of the jobs whose lane is free,
* a phone's command goes first, from the device after the one served last (so one device's burst
* waits its turn behind every other device's), each device's in the order queued; background work
* (ticks, keeping, looks) goes after the commands, or first once it has waited RMT_BACKGROUND_MS,
* so neither starves the other. */
static rmt_job *rmt_pool_take(rmt_pool *p) {
long long now = rmt_mono_ms(), best_rank = LLONG_MAX;
rmt_job *prev = NULL, *best = NULL, *best_prev = NULL, *bg = NULL, *bg_prev = NULL, *jb, *take, *take_prev;
for (jb = p->head; jb; prev = jb, jb = jb->next) {
int *busy = jb->j ? &jb->j->busy : &p->user_busy;
long long d = jb->di + 1, last = p->last + 1, rank;
if (*busy) {
continue;
}
if (jb->background) {
if (!bg) {
bg = jb;
bg_prev = prev;
}
continue;
}
rank = d > last ? d - last : d - last + 1000000; /* the devices after the last one first, round */
if (rank < best_rank) { /* the earliest of each device: its order holds */
best_rank = rank;
best = jb;
best_prev = prev;
}
}
if (bg && (!best || now - bg->queued_ms >= RMT_BACKGROUND_MS)) {
take = bg;
take_prev = bg_prev;
} else {
take = best;
take_prev = best_prev;
}
if (!take) {
return NULL;
}
if (!take->background) {
p->last = take->di;
}
*(take->j ? &take->j->busy : &p->user_busy) = 1;
if (take_prev) {
take_prev->next = take->next;
} else {
p->head = take->next;
}
if (p->tail == take) {
p->tail = take_prev;
}
take->next = NULL;
return take;
}
static void *rmt_worker_main(void *arg) {
rmt_pool *p = arg;
sqlite3 *u = pic_userdb(NULL, 0); /* this thread's own connection */
if (u) {
(void)pic_busy_wait(u, RMT_USER_BUSY_MS);
}
(void)pthread_mutex_lock(&p->mu);
for (;;) {
rmt_job *jb = rmt_pool_take(p);
pic_follow **dead = NULL;
int ndead = 0;
if (!jb) {
(void)pthread_cond_wait(&p->cv, &p->mu);
continue;
}
if (jb->j && jb->j->ndead) {
dead = jb->j->dead;
ndead = jb->j->ndead;
jb->j->dead = NULL;
jb->j->ndead = jb->j->capdead = 0;
}
atomic_store(&jb->started_ms, rmt_mono_ms());
atomic_store(&jb->state, RMT_JOB_RUNNING);
(void)pthread_mutex_unlock(&p->mu);
rmt_job_trace("start", jb);
for (int i = 0; i < ndead; i++) {
rmt_follow_forget(jb->j, dead[i]);
}
free(dead);
rmt_job_run(jb);
(void)pthread_mutex_lock(&p->mu);
atomic_store(&jb->state, RMT_JOB_FINISHED);
if (p->fin_tail) {
p->fin_tail->next = jb;
} else {
p->fin = jb;
}
p->fin_tail = jb;
(void)pthread_mutex_unlock(&p->mu);
while (write(p->wake[1], "j", 1) < 0 && errno == EINTR) {
}
(void)pthread_mutex_lock(&p->mu);
}
return NULL;
}
/* The workers, started with every signal blocked (signals are the loop's). 0, or -1. */
static int rmt_pool_start(rmt_state *st) {
rmt_pool *p = &st->pool;
sigset_t all, was;
int n = 0;
if (pthread_mutex_init(&p->mu, NULL) != 0 || pthread_cond_init(&p->cv, NULL) != 0 || pipe(p->wake) != 0) {
return -1;
}
p->last = -1;
for (int k = 0; k < 2; k++) {
(void)fcntl(p->wake[k], F_SETFL, O_NONBLOCK);
(void)fcntl(p->wake[k], F_SETFD, FD_CLOEXEC);
}
sigfillset(&all);
pthread_sigmask(SIG_BLOCK, &all, &was);
for (int i = 0; i < RMT_WORKERS; i++) {
pthread_t t;
pthread_attr_t a;
(void)pthread_attr_init(&a);
(void)pthread_attr_setdetachstate(&a, PTHREAD_CREATE_DETACHED);
n += pthread_create(&t, &a, rmt_worker_main, p) == 0;
(void)pthread_attr_destroy(&a);
}
pthread_sigmask(SIG_SETMASK, &was, NULL);
p->started = n > 0;
return n > 0 ? 0 : -1;
}
/* A job for D (index DI; NULL: none) on lane J (NULL: the user database), or NULL (CTX dropped). */
static rmt_job *rmt_job_new(rmt_state *st, rmt_journal *j, rmt_dev *d, void (*runfn)(rmt_job *),
void (*done)(rmt_state *, rmt_job *), void (*drop)(void *), void *ctx, const char *what) {
rmt_job *jb = calloc(1, sizeof *jb);
if (!jb) {
if (drop) {
drop(ctx);
}
return NULL;
}
jb->j = j;
jb->jx = -1;
for (int i = 0; j && i < st->njs; i++) {
jb->jx = st->js[i] == j ? i : jb->jx;
}
jb->run = runfn;
jb->done = done;
jb->drop = drop;
jb->ctx = ctx;
jb->di = -1;
if (d) {
jb->di = (int)(d - st->devs);
memcpy(jb->dev, d->d.id, 16);
(void)snprintf(jb->idb, sizeof jb->idb, "%s", d->idb);
(void)snprintf(jb->dname, sizeof jb->dname, "%s", d->d.name);
}
(void)snprintf(jb->what, sizeof jb->what, "%s", what);
atomic_store(&jb->state, RMT_JOB_QUEUED);
return jb;
}
/* The device JB answers, still paired, or NULL. */
static rmt_dev *rmt_job_dev(rmt_state *st, const rmt_job *jb) {
rmt_dev *d;
if (jb->di < 0 || jb->di >= st->ndevs) {
return NULL;
}
d = &st->devs[jb->di];
return d->alive && memcmp(d->d.id, jb->dev, 16) == 0 ? d : NULL;
}
/* JB's lines to its device: busy instead when a command's statements ran out of time, or the loop
* gave up on it, before anything committed; none when the loop answered busy already. */
static void rmt_job_reply(rmt_state *st, rmt_job *jb) {
rmt_dev *d = rmt_job_dev(st, jb);
int fate = atomic_load(&jb->fate);
if (!d || jb->answered) {
return;
}
if (jb->key[0] && (fate == RMT_FATE_ABANDONED || (jb->overran && fate != RMT_FATE_COMMITTED))) {
rmt_error(st, d, jb->key, "busy", RMT_BUSY_TEXT);
for (int k = 0; k < jb->nalias; k++) {
rmt_error(st, d, jb->alias[k], "busy", RMT_BUSY_TEXT);
}
return;
}
for (int i = 0; i < jb->out.n; i++) {
for (int k = 0; k < jb->nalias; k++) { /* the same answer under each key it took over, in the order asked */
rmt_send_free(st, d, rmt_q("SELECT CASE WHEN json_extract(?1, '$.key') = ?2 THEN json_set(?1, '$.key', ?3) END", 3,
jb->out.v[i], jb->key, jb->alias[k]));
}
(void)rmt_send(st, d, jb->out.v[i]);
}
}
/* Whether JB answers KEY, its own or one it took over. */
static int rmt_job_has_key(const rmt_job *jb, const char *key) {
if (jb->key[0] && strcmp(jb->key, key) == 0) {
return 1;
}
for (int k = 0; k < jb->nalias; k++) {
if (strcmp(jb->alias[k], key) == 0) {
return 1;
}
}
return 0;
}
/* JB, still queued, taken out of the pool's queue: 1, or 0 when a worker has it already. */
static int rmt_job_unqueue(rmt_state *st, rmt_job *jb) {
int removed = 0;
(void)pthread_mutex_lock(&st->pool.mu);
if (atomic_load(&jb->state) == RMT_JOB_QUEUED) {
rmt_job *prev = NULL;
for (rmt_job *q = st->pool.head; q; prev = q, q = q->next) {
if (q == jb) {
if (prev) {
prev->next = q->next;
} else {
st->pool.head = q->next;
}
if (st->pool.tail == q) {
st->pool.tail = prev;
}
removed = 1;
break;
}
}
}
(void)pthread_mutex_unlock(&st->pool.mu);
return removed;
}
static void rmt_done_reply(rmt_state *st, rmt_job *jb) { rmt_job_reply(st, jb); }
static void rmt_job_free(rmt_job *jb) {
if (jb->drop) {
jb->drop(jb->ctx);
}
rmt_lines_free(&jb->out);
free(jb->line);
free(jb->alias);
free(jb);
}
static void rmt_job_unhold(rmt_state *st, rmt_job *jb) {
for (rmt_job **at = &st->held; *at; at = &(*at)->held) {
if (*at == jb) {
*at = jb->held;
break;
}
}
}
static void rmt_lane_seen(rmt_state *st, rmt_job *jb);
/* A finished job, on the loop: applied, its lane let go, freed. */
static void rmt_job_finish(rmt_state *st, rmt_job *jb) {
rmt_job_trace("end", jb);
rmt_job_unhold(st, jb);
if (jb->slow_said) {
rmt_log(stdout, "pic remote: %s ended after %lld s\n", jb->what, (rmt_mono_ms() - atomic_load(&jb->started_ms)) / 1000);
(void)fflush(stdout);
}
#ifdef PIC_FAULTS
if (getenv("PIC_TEST_RC_MESSAGE_STEPS") && jb->answering[0]) { /* the tests' seam: the work each message took */
printf("pic remote: answered %s in %lld steps\n", jb->answering, jb->steps);
(void)fflush(stdout);
}
#endif
if (jb->done) {
jb->done(st, jb);
}
if (jb->j) {
rmt_lane_seen(st, jb);
}
if (st->pool.started) {
(void)pthread_mutex_lock(&st->pool.mu);
if (jb->j) {
jb->j->busy = 0;
} else {
st->pool.user_busy = 0;
}
(void)pthread_cond_broadcast(&st->pool.cv);
(void)pthread_mutex_unlock(&st->pool.mu);
}
rmt_job_free(jb);
}
/* JB queued (taken): run by a worker, or here and now before the workers start. */
static void rmt_job_add(rmt_state *st, rmt_job *jb) {
if (!jb) {
return;
}
jb->queued_ms = rmt_mono_ms();
jb->held = st->held;
st->held = jb;
rmt_job_trace("queue", jb);
if (!st->pool.started) {
if (jb->j) {
for (int i = 0; i < jb->j->ndead; i++) {
rmt_follow_forget(jb->j, jb->j->dead[i]);
}
jb->j->ndead = 0;
}
atomic_store(&jb->started_ms, rmt_mono_ms());
rmt_job_run(jb);
rmt_job_finish(st, jb);
return;
}
(void)pthread_mutex_lock(&st->pool.mu);
if (st->pool.tail) {
st->pool.tail->next = jb;
} else {
st->pool.head = jb;
}
st->pool.tail = jb;
(void)pthread_cond_signal(&st->pool.cv);
(void)pthread_mutex_unlock(&st->pool.mu);
}
/* The jobs the workers finished, applied in the order they finished. */
static void rmt_jobs_collect(rmt_state *st) {
char buf[64];
rmt_job *fin;
if (!st->pool.started) {
return;
}
while (read(st->pool.wake[0], buf, sizeof buf) > 0) {
}
(void)pthread_mutex_lock(&st->pool.mu);
fin = st->pool.fin;
st->pool.fin = st->pool.fin_tail = NULL;
(void)pthread_mutex_unlock(&st->pool.mu);
while (fin) {
rmt_job *next = fin->next;
rmt_job_finish(st, fin);
fin = next;
}
}
/* Each tick: a command queued too long behind its journal is answered busy and dropped; one
* running past its budget is answered busy (what it finds later is not sent); a job running past
* the stall time is logged once, with what it is. */
static void rmt_jobs_watch(rmt_state *st) {
long long now = rmt_mono_ms();
rmt_job *jb = st->held;
while (jb) {
rmt_job *next = jb->held;
int state = atomic_load(&jb->state);
if (jb->key[0] && !jb->answered && state == RMT_JOB_QUEUED && now - jb->queued_ms > RMT_JOB_WAIT_MS) {
if (rmt_job_unqueue(st, jb)) {
rmt_dev *d = rmt_job_dev(st, jb);
if (d) {
rmt_error(st, d, jb->key, "busy", RMT_BUSY_TEXT);
for (int k = 0; k < jb->nalias; k++) {
rmt_error(st, d, jb->alias[k], "busy", RMT_BUSY_TEXT);
}
}
rmt_job_unhold(st, jb);
rmt_job_free(jb);
}
} else if (state == RMT_JOB_RUNNING) {
long long ran = now - atomic_load(&jb->started_ms);
int open = RMT_FATE_OPEN;
if (jb->key[0] && !jb->answered && jb->budget_ms > 0 && ran > jb->budget_ms + RMT_JOB_GRACE_MS &&
(atomic_load(&jb->fate) == RMT_FATE_ABANDONED ||
atomic_compare_exchange_strong(&jb->fate, &open, RMT_FATE_ABANDONED))) { /* committed: its own answer comes */
rmt_dev *d = rmt_job_dev(st, jb);
if (d) {
rmt_error(st, d, jb->key, "busy", RMT_BUSY_TEXT);
for (int k = 0; k < jb->nalias; k++) {
rmt_error(st, d, jb->alias[k], "busy", RMT_BUSY_TEXT);
}
}
jb->answered = 1;
}
if (!jb->slow_said && ran > rmt_stall_ms()) {
jb->slow_said = 1;
rmt_log(stdout, "pic remote: slow: %s has run %lld s; the loop goes on\n", jb->what, ran / 1000);
(void)fflush(stdout);
}
}
jb = next;
}
}
/* The job in hand for D's command KEY, or NULL. */
static rmt_job *rmt_job_keyed(rmt_state *st, const rmt_dev *d, const char *key) {
for (rmt_job *jb = st->held; jb; jb = jb->held) {
if (rmt_job_has_key(jb, key) && memcmp(jb->dev, d->d.id, 16) == 0) {
return jb;
}
}
return NULL;
}
/* Whether a command of some phone is in hand. */
static int rmt_jobs_keyed(rmt_state *st) {
for (rmt_job *jb = st->held; jb; jb = jb->held) {
if (jb->key[0]) {
return 1;
}
}
return 0;
}
/* The devices' names by id, kept until they change. */
static const char *rmt_names(rmt_state *st) {
if (!st->names) {
st->names = rmt_device_names(st);
}
return st->names ? st->names : "{}";
}
static void rmt_names_changed(rmt_state *st) {
free(st->names);
st->names = NULL;
}
/* SQL: the members of ask_settled's payload for V, an ask as pic_ask_list gives it, with MAP the
* device names: id, value, by: {kind: terminal|phone|attach|rpc|expired|cancelled, device: a name or
* null, deviceId: the pairing's remote:IDB or null}. Two phones can share a name, never an id. The
* value goes in as JSON (->), not json_extract's SQL value, so true is true and not 1. */
#define RMT_SETTLED_MEMBERS(V, MAP) \
"'id', json_extract(" V ", '$.id'), 'value', json(" V " -> '$.value'), 'by', json_object('kind'," \
" CASE json_extract(" V ", '$.state') WHEN 'withdrawn' THEN 'cancelled' WHEN 'expired' THEN 'expired' ELSE" \
" CASE WHEN json_extract(" V ", '$.answeredBy') LIKE 'remote:%' THEN 'phone' ELSE json_extract(" V ", '$.answeredBy')"\
" END END, 'device', CASE WHEN json_extract(" V ", '$.answeredBy') LIKE 'remote:%' THEN json_extract(" MAP ", '$.\"' ||" \
" substr(json_extract(" V ", '$.answeredBy'), 8) || '\"') END, 'deviceId', CASE WHEN json_extract(" V ", '$.answeredBy')" \
" LIKE 'remote:%' THEN json_extract(" V ", '$.answeredBy') END)"
#define RMT_SETTLED_SQL(V, MAP) "json_object(" RMT_SETTLED_MEMBERS(V, MAP) ")"
/* ---- journals and the conversation list --------------------------------------------------- */
static long long rmt_data_version(sqlite3 *db) {
sqlite3_stmt *q = NULL;
long long v = -1;
if (db && sqlite3_prepare_v2(db, "PRAGMA data_version", -1, &q, NULL) == SQLITE_OK && sqlite3_step(q) == SQLITE_ROW) {
v = sqlite3_column_int64(q, 0);
}
sqlite3_finalize(q);
return v;
}
static void rmt_push_watch(rmt_journal *j);
static void rmt_unfollow(rmt_state *st, rmt_dev *d);
/* The schema version a journal at PATH says it has (pic_meta), or -1 when it is no journal. */
static long rmt_journal_schema(const char *path) {
sqlite3 *db = NULL;
sqlite3_stmt *q = NULL;
long v = -1;
if (sqlite3_open_v2(path, &db, SQLITE_OPEN_READONLY, pic_platform_get()->vfs) == SQLITE_OK &&
sqlite3_prepare_v2(db, "SELECT CAST(value AS INTEGER) FROM pic_meta WHERE key = 'schema_version'", -1, &q, NULL) ==
SQLITE_OK &&
sqlite3_step(q) == SQLITE_ROW) {
v = sqlite3_column_int(q, 0);
}
sqlite3_finalize(q);
sqlite3_close(db);
return v;
}
#define RMT_HELD_OLDER "open in an older pic; it updates when that pic closes"
/* Why J is not open, for a phone, by its schema SV (rmt_journal_schema). One an older pic last used
* is updated here (rmt_update); until then an older pic has it open. */
static void rmt_why(rmt_journal *j, long sv) {
j->older = 0;
if (sv >= 0 && sv < atol(PIC_SCHEMA_VERSION)) { /* a phone has no use for the store's words */
(void)snprintf(j->why, sizeof j->why, RMT_HELD_OLDER);
j->older = 1;
} else if (sv > atol(PIC_SCHEMA_VERSION)) {
(void)snprintf(j->why, sizeof j->why, "a newer pic wrote it; update pic on this computer");
} else {
(void)snprintf(j->why, sizeof j->why, "%s", j->s.err[0] ? j->s.err : "cannot open the journal");
}
}
/* J opened narrowly to be served: 0, or -1 with it closed. AGAIN: one let go of for a newer pic,
* not opened while a migration still waits. On J's lane. */
static int rmt_serve_open(rmt_journal *j, int again) {
if (pic_open_narrow(&j->s, j->path) == 0 && !(again && pic_migration_wanted(&j->s)) && pic_sqlar_register(j->s.db) == 0 &&
pic_transform_register(j->s.db) == 0) { /* the functions get_messages' queries call */
j->sopen = 1;
(void)pic_busy_wait(j->s.db, RMT_BUSY_MS); /* a job never waits long for another pic */
j->yielded = 0;
j->older = 0;
j->why[0] = '\0';
j->s.policy = j->policy; /* get_session_stats' context estimate */
j->version = rmt_data_version(j->s.db);
j->push_open.n = 0;
rmt_push_watch(j);
j->ask_init = 0; /* what was asked before is not news: sent only to a phone's new session */
j->ask_dv = -1;
return 0;
}
pic_close(&j->s);
return -1;
}
/* A journal an older pic last used, brought up to date as pic's own open does it, when no process
* has it open; one an older pic has open is left alone (never stopped) and looked at again each
* second, its reason saying so. 1 when J is served now. On J's lane. */
static int rmt_update(rmt_journal *j) {
pic_store m;
long long now = rmt_mono_ms();
if (j->sopen || !j->older) {
return j->sopen;
}
if (!pic_journal_unheld(j->path)) {
(void)snprintf(j->why, sizeof j->why, RMT_HELD_OLDER);
return 0;
}
if (j->update_failed_ms && now - j->update_failed_ms < 60000) {
return 0;
}
if (pic_open(&m, j->path) != 0) {
if (pic_journal_unheld(j->path)) { /* the update itself failed: tried again in a minute */
(void)snprintf(j->why, sizeof j->why, "pic could not update it: %s", m.err);
j->update_failed_ms = now;
rmt_log(stdout, "pic remote: could not update %s: %s\n", j->path, m.err);
(void)fflush(stdout);
} else { /* an older pic opened it meanwhile */
(void)snprintf(j->why, sizeof j->why, RMT_HELD_OLDER);
}
pic_close(&m);
return 0;
}
pic_close(&m);
j->update_failed_ms = 0;
rmt_log(stdout, "pic remote: updated %s\n", j->path);
(void)fflush(stdout);
if (rmt_serve_open(j, 0) != 0) {
rmt_why(j, rmt_journal_schema(j->path));
return 0;
}
return 1;
}
/* Whether workspace WS is under a temporary directory ($TMPDIR, /tmp, /var/folders): an agent's or
* a test's scratch, never shown to a phone. */
static int rmt_temporary(const char *ws) {
const char *roots[] = {getenv("TMPDIR"), "/tmp", "/private/tmp", "/var/folders", "/private/var/folders"};
char real[PATH_MAX], rroot[PATH_MAX];
const char *forms[2] = {ws, realpath(ws, real) ? real : ws};
int nroots = (int)(sizeof roots / sizeof roots[0]);
#ifdef PIC_FAULTS
if (getenv("PIC_TEST_RC_TEMP")) { /* the tests' seam: the temporary directories, instead */
roots[0] = getenv("PIC_TEST_RC_TEMP");
nroots = 1;
}
#endif
for (int i = 0; i < nroots; i++) {
const char *r = roots[i];
for (int form = 0; r && *r && form < 2; form++) {
const char *rt = form ? (realpath(r, rroot) ? rroot : r) : r;
size_t n = strlen(rt);
while (n > 1 && rt[n - 1] == '/') {
n--;
}
for (int k = 0; k < 2; k++) {
if (strncmp(forms[k], rt, n) == 0 && (forms[k][n] == '/' || forms[k][n] == '\0')) {
return 1;
}
}
}
}
return 0;
}
/* Whether a workspace's directory or its journal is gone (a test's, a deleted checkout). */
static int rmt_gone(const char *ws, const char *jp) {
struct stat sb;
return stat(ws, &sb) != 0 || !S_ISDIR(sb.st_mode) || stat(jp, &sb) != 0 || !S_ISREG(sb.st_mode);
}
/* The rows of picu_workspace to forget (their directory or journal gone, or a journal that is the
* user database) or mend (to the workspace's own journal, when it has one), found while reading. */
typedef struct {
char *ws, *jp; /* jp NULL: forget */
} rmt_heal;
/* A journal the registry names that pic remote does not serve yet. */
typedef struct {
char *path, *ws, *real;
} rmt_cand;
static void rmt_cands_free(rmt_cand *c, int n) {
for (int i = 0; i < n; i++) {
free(c[i].path);
free(c[i].ws);
free(c[i].real);
}
free(c);
}
/* Whether DIR is the home folder or above it, whose subfolders are not projects. */
static int rmt_home_or_above(const char *dir) {
const char *home = getenv("HOME");
char rh[PATH_MAX];
size_t n = strlen(dir);
if (strcmp(dir, "/") == 0) {
return 1;
}
if (!home || !*home) {
return 0;
}
home = realpath(home, rh) ? rh : home;
return strncmp(home, dir, n) == 0 && (home[n] == '\0' || home[n] == '/');
}
/* Whether DIR, as a default root, is better left out: under /Volumes (a mount that may hang),
* or one of the home folder's private folders, where reading raises the system's privacy prompts
* and the names are not projects (Desktop, Documents, Downloads, Library, Movies, Music, Pictures;
* iCloud's folder is under Library). The setting remote.folders can still name any of them. */
static int rmt_private_root(const char *dir) {
static const char *const mine[] = {"Desktop", "Documents", "Downloads", "Library", "Movies", "Music", "Pictures", NULL};
const char *home = getenv("HOME");
char rh[PATH_MAX];
size_t hn;
if (strncmp(dir, "/Volumes", 8) == 0 && (dir[8] == '\0' || dir[8] == '/')) {
return 1;
}
if (!home || !*home) {
return 0;
}
home = realpath(home, rh) ? rh : home;
hn = strlen(home);
if (strncmp(dir, home, hn) != 0 || dir[hn] != '/') {
return 0;
}
for (int i = 0; mine[i]; i++) {
size_t mn = strlen(mine[i]);
if (strncmp(dir + hn + 1, mine[i], mn) == 0 && (dir[hn + 1 + mn] == '\0' || dir[hn + 1 + mn] == '/')) {
return 1;
}
}
return 0;
}
/* A folder a phone may start a conversation in. */
typedef struct {
char *id, *name, *root;
long long ms;
} rmt_folder;
static int rmt_folder_cmp(const void *a, const void *b) {
const rmt_folder *x = a, *y = b;
return x->ms < y->ms ? 1 : x->ms > y->ms ? -1 : strcmp(x->id, y->id);
}
#define RMT_FOLDER_ROOTS 32
#define RMT_FOLDERS_MS 10000
#define RMT_FOLDERS_MOST 500
#define RMT_FOLDERS_READ 2000 /* entries read per root each scan: a huge folder costs a bounded time */
/* ROOT (a real path) as a root, unless it is under a temporary directory or already one. */
static void rmt_root_add(char roots[][PATH_MAX], int *n, const char *root) {
if (*n >= RMT_FOLDER_ROOTS || rmt_temporary(root)) {
return;
}
for (int i = 0; i < *n; i++) {
if (strcmp(roots[i], root) == 0) {
return;
}
}
(void)snprintf(roots[(*n)++], PATH_MAX, "%s", root);
}
/* The folders a phone may start a conversation in, as JSON [{"id","name","root"}]: the immediate
* subfolders of remote.folders (folders separated by ':', ~ the home folder), or, unset, of the
* folders holding the workspaces the registry names, but for the home folder and above it. Real
* paths only: a hidden folder, one a link takes out of its root, one under a temporary directory
* and one the registry names already are left out; the most recently changed first. NULL when the
* user database cannot be read. On the user lane. */
static char *rmt_folders_scan(void) {
sqlite3 *db = pic_userdb(NULL, 0);
sqlite3_stmt *q = NULL;
char (*roots)[PATH_MAX] = calloc(RMT_FOLDER_ROOTS, PATH_MAX), real[PATH_MAX], **known = NULL, *set;
int nroots = 0, nknown = 0;
rmt_folder *fs = NULL;
size_t nfs = 0;
rmt_buf b = {NULL, 0, 0};
if (!db || !roots) {
free(roots);
return NULL;
}
if (sqlite3_prepare_v2(db, "SELECT path FROM picu_workspace", -1, &q, NULL) == SQLITE_OK) {
while (sqlite3_step(q) == SQLITE_ROW) {
const char *ws = (const char *)sqlite3_column_text(q, 0);
char **grown = ws ? realloc(known, (size_t)(nknown + 1) * sizeof *known) : NULL;
if (grown) {
known = grown;
if ((known[nknown] = strdup(ws))) {
nknown++;
}
}
}
}
sqlite3_finalize(q);
if ((set = pic_setting("remote.folders")) && *set) {
const char *home = getenv("HOME");
for (char *at = set, *end; at; at = end ? end + 1 : NULL) {
char one[PATH_MAX];
size_t n;
if ((end = strchr(at, ':'))) {
*end = '\0';
}
while (*at == ' ') {
at++;
}
n = strlen(at);
while (n && at[n - 1] == ' ') {
at[--n] = '\0';
}
if (at[0] == '~' && (at[1] == '\0' || at[1] == '/') && home) {
(void)snprintf(one, sizeof one, "%s%s", home, at + 1);
} else {
(void)snprintf(one, sizeof one, "%s", at);
}
if (one[0] == '/' && realpath(one, real)) {
rmt_root_add(roots, &nroots, real);
}
}
} else {
for (int i = 0; i < nknown; i++) {
char *slash;
if (!realpath(known[i], real) || !(slash = strrchr(real, '/'))) {
continue;
}
*(slash == real ? slash + 1 : slash) = '\0'; /* its parent */
if (!rmt_home_or_above(real) && !rmt_private_root(real)) {
rmt_root_add(roots, &nroots, real);
}
}
}
free(set);
for (int r = 0; r < nroots; r++) {
DIR *d = opendir(roots[r]);
struct dirent *de;
size_t rn = strcmp(roots[r], "/") == 0 ? 0 : strlen(roots[r]); /* "/" names its subfolders as "/x" */
int read = 0;
while (d && read++ < RMT_FOLDERS_READ && (de = readdir(d)) != NULL) {
char path[PATH_MAX];
struct stat sb;
int seen = 0;
rmt_folder *grown;
if (de->d_name[0] == '.' || snprintf(path, sizeof path, "%s/%s", roots[r], de->d_name) >= (int)sizeof path ||
!realpath(path, real) || stat(real, &sb) != 0 || !S_ISDIR(sb.st_mode)) {
continue;
}
/* still in its root, one level down: a link out of it is not followed */
if (strncmp(real, roots[r], rn) != 0 || real[rn] != '/' || strchr(real + rn + 1, '/') || real[rn + 1] == '.' ||
rmt_temporary(real)) {
continue;
}
for (int i = 0; i < nknown && !seen; i++) {
seen = strcmp(known[i], real) == 0;
}
for (size_t i = 0; i < nfs && !seen; i++) {
seen = strcmp(fs[i].id, real) == 0;
}
if (seen || !(grown = realloc(fs, (nfs + 1) * sizeof *fs))) {
continue;
}
fs = grown;
fs[nfs].id = strdup(real);
fs[nfs].name = strdup(real + rn + 1);
fs[nfs].root = strdup(roots[r]);
fs[nfs].ms = (long long)sb.st_mtime * 1000;
if (!fs[nfs].id || !fs[nfs].name || !fs[nfs].root) {
free(fs[nfs].id);
free(fs[nfs].name);
free(fs[nfs].root);
continue;
}
nfs++;
}
if (d) {
closedir(d);
}
}
if (nfs > 1) {
qsort(fs, nfs, sizeof *fs, rmt_folder_cmp);
}
(void)rmt_buf_add(&b, "[", 1);
for (size_t i = 0; i < nfs; i++) {
char *one = i < RMT_FOLDERS_MOST ? rmt_q("SELECT json_object('id', ?1, 'name', ?2, 'root', ?3)", 3, fs[i].id, fs[i].name,
fs[i].root)
: NULL;
if (one) {
if (b.len > 1) {
(void)rmt_buf_add(&b, ",", 1);
}
(void)rmt_buf_add(&b, one, strlen(one));
}
free(one);
free(fs[i].id);
free(fs[i].name);
free(fs[i].root);
}
free(fs);
(void)rmt_buf_add(&b, "]", 1);
for (int i = 0; i < nknown; i++) {
free(known[i]);
}
free(known);
free(roots);
return b.buf;
}
/* Every picu_workspace row whose path still holds a journal not among KNOWN (paths and workspaces)
* nor already in *OUT. A row whose directory or journal is gone is forgotten, so the registry heals
* as it is read; one that names the user database is mended or forgotten. On the user lane. */
static void rmt_scan_rows(char *const *known, int nknown, rmt_cand **out, int *n, int again) {
sqlite3 *db = pic_userdb(NULL, 0);
sqlite3_stmt *q = NULL;
rmt_heal fix[64];
int nfix = 0;
if (!db || sqlite3_prepare_v2(db, "SELECT path, journal FROM picu_workspace ORDER BY last_used_ms DESC", -1, &q, NULL) !=
SQLITE_OK) {
sqlite3_finalize(q);
return;
}
while (sqlite3_step(q) == SQLITE_ROW) {
const char *ws = (const char *)sqlite3_column_text(q, 0), *jp = (const char *)sqlite3_column_text(q, 1);
char own[PATH_MAX];
int seen = 0;
rmt_cand *grown;
if (!ws || !jp) {
continue;
}
if (pic_userdb_is(jp)) { /* registered by a pic run with --db naming the user database */
if (nfix < 64) {
int mend = snprintf(own, sizeof own, "%s/.pic/journal.sqlite", ws) < (int)sizeof own && !rmt_gone(ws, own) &&
!pic_userdb_is(own);
fix[nfix].ws = strdup(ws);
fix[nfix++].jp = mend ? strdup(own) : NULL;
}
continue;
}
if (rmt_gone(ws, jp)) {
if (nfix < 64) {
fix[nfix].ws = strdup(ws);
fix[nfix++].jp = NULL;
}
continue;
}
if (rmt_temporary(ws)) { /* kept in the registry; never shown */
continue;
}
for (int i = 0; i < nknown; i++) {
seen = seen || strcmp(known[i], jp) == 0 || strcmp(known[i], ws) == 0;
}
for (int i = 0; i < *n; i++) {
seen = seen || strcmp((*out)[i].path, jp) == 0 || strcmp((*out)[i].ws, ws) == 0;
}
if (seen || !(grown = realloc(*out, (size_t)(*n + 1) * sizeof *grown))) {
continue;
}
*out = grown;
grown[*n].path = strdup(jp);
grown[*n].ws = strdup(ws);
grown[*n].real = realpath(jp, own) ? strdup(own) : strdup(jp);
if (!grown[*n].path || !grown[*n].ws || !grown[*n].real) {
free(grown[*n].path);
free(grown[*n].ws);
free(grown[*n].real);
continue;
}
(*n)++;
}
sqlite3_finalize(q);
{
int mended = 0;
for (int i = 0; i < nfix; i++) {
if (fix[i].ws) {
mended += fix[i].jp && pic_workspace_touch(fix[i].ws, fix[i].jp) == 0;
if (!fix[i].jp) {
(void)pic_workspace_forget(fix[i].ws);
}
}
free(fix[i].ws);
free(fix[i].jp);
}
if (mended && !again) { /* the mended rows, read again (once: a mended row names a journal) */
rmt_scan_rows(known, nknown, out, n, 1);
}
}
}
/* A journal opened to be served, or why not; one that is no journal is hidden. On its lane. */
static void rmt_open_run(rmt_job *jb) {
rmt_journal *j = jb->j;
long sv;
j->notjournal = 0;
if (j->sopen || rmt_serve_open(j, 0) == 0) {
return;
}
if ((sv = rmt_journal_schema(j->path)) < 0) { /* not a journal: nothing to show */
j->notjournal = 1;
return;
}
rmt_why(j, sv);
(void)rmt_update(j); /* an older pic's, at start and on an install's restart */
}
/* A journal the registry names, held from now on, hidden until it is opened; NULL out of memory. */
static rmt_journal *rmt_journal_hold(rmt_state *st, const rmt_cand *c) {
rmt_journal **grown, *j = NULL;
for (int i = 0; i < st->njs && !j; i++) { /* one that was no journal, named again */
j = st->js[i]->hidden && strcmp(st->js[i]->path, c->path) == 0 ? st->js[i] : NULL;
}
if (!j) {
if (!(grown = realloc(st->js, (size_t)(st->njs + 1) * sizeof *grown)) || !(j = calloc(1, sizeof *j))) {
if (grown) {
st->js = grown;
}
return NULL;
}
st->js = grown;
if (!(j->path = strdup(c->path)) || !(j->workspace = strdup(c->ws)) || !(j->real = strdup(c->real))) {
free(j->path);
free(j->workspace);
free(j->real);
free(j);
return NULL;
}
j->list_dv = -1;
j->policy = st->o->policy;
j->hidden = 1; /* until its open says */
st->js[st->njs++] = j;
}
return j;
}
/* A journal the registry names, served from now on (opened by a job of its own). */
static void rmt_journal_add(rmt_state *st, const rmt_cand *c) {
rmt_journal *j = rmt_journal_hold(st, c);
if (j) {
rmt_job_add(st, rmt_job_new(st, j, NULL, rmt_open_run, NULL, NULL, NULL, "opening a journal"));
}
}
/* What a job of J changed in whether it is served, applied on the loop while it still holds J's
* lane: one opened has its part of the list built afresh; one let go of (for a newer pic) took its
* follows with it, and the phones following them are told. */
static void rmt_lane_seen(rmt_state *st, rmt_job *jb) {
rmt_journal *j = jb->j;
if (j->sopen && !j->open) {
j->list_dv = -1;
j->list_ready = 0;
j->list_slow = 0;
} else if (!j->sopen && j->open) {
for (int k = 0; k < st->ndevs; k++) {
rmt_dev *d = &st->devs[k];
if (d->alive && d->f && d->jx == jb->jx) {
rmt_error(st, d, NULL, "unavailable", "a newer pic is updating this workspace");
d->f = NULL; /* closed with the journal */
rmt_unfollow(st, d);
}
}
}
j->open = j->sopen;
j->hidden = j->notjournal;
(void)snprintf(j->shown_why, sizeof j->shown_why, "%s", j->why);
}
/* SESSION as the phone names it, W/C: the open journal it names and the conversation's id. 0, or
* -1. Whether that conversation is there is for the job that reads the journal (rmt_conv_is). */
static int rmt_resolve(rmt_state *st, const char *session, int *jx, char conv[64]) {
const char *slash = session ? strrchr(session, '/') : NULL;
if (!slash || slash == session || !slash[1] || strlen(slash + 1) >= 64) {
return -1;
}
for (int i = 0; i < st->njs; i++) {
if (st->js[i]->open && strlen(st->js[i]->path) == (size_t)(slash - session) &&
memcmp(st->js[i]->path, session, (size_t)(slash - session)) == 0) {
*jx = i;
(void)snprintf(conv, 64, "%s", slash + 1);
return 0;
}
}
return -1;
}
/* Whether S has conversation CONV. On its lane. */
static int rmt_conv_is(pic_store *s, const char *conv) {
sqlite3_stmt *q = NULL;
int found = 0;
if (sqlite3_prepare_v2(s->db, "SELECT 1 FROM pic_session WHERE id = ?", -1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, conv, -1, SQLITE_STATIC);
found = sqlite3_step(q) == SQLITE_ROW;
}
sqlite3_finalize(q);
return found;
}
/* Whether journal I is shown: read now, or worth a line, with its directory and file still there. */
static int rmt_shown(rmt_state *st, int i) { return !st->js[i]->hidden && !rmt_gone(st->js[i]->workspace, st->js[i]->path); }
static const char *rmt_base(const char *p, size_t *n) {
const char *end = p + strlen(p), *b;
while (end > p + 1 && end[-1] == '/') {
end--;
}
for (b = end; b > p && b[-1] != '/'; b--) {
}
*n = (size_t)(end - b);
return b;
}
/* What a phone calls workspace I: its directory's name, or parent/name when another workspace shown
* has a directory of that name too. */
static void rmt_ws_name(rmt_state *st, int i, char *out, size_t cap) {
const char *w = st->js[i]->workspace, *b;
size_t n, m;
int twin = 0;
b = rmt_base(w, &n);
for (int k = 0; k < st->njs && !twin; k++) {
const char *o;
if (k == i || !rmt_shown(st, k)) {
continue;
}
o = rmt_base(st->js[k]->workspace, &m);
twin = m == n && memcmp(o, b, n) == 0;
}
if (twin && b > w + 1) {
const char *pe = b - 1, *ps = pe;
while (ps > w && ps[-1] != '/') {
ps--;
}
(void)snprintf(out, cap, "%.*s/%.*s", (int)(pe - ps), ps, (int)n, b);
} else {
(void)snprintf(out, cap, "%.*s", (int)n, b);
}
}
static int rmt_item_cmp(const void *a, const void *b) {
const rmt_item *x = a, *y = b;
return x->ms < y->ms ? 1 : x->ms > y->ms ? -1 : 0;
}
/* A journal's conversations for the list, newest first: id, name, last activity, running, last
* seq, title, attention, loops, start, archived, deleted, with ARCH (SQL) whether s is archived;
* then " FROM pic_session s WHERE 1", the filters, and RMT_LIST_TAIL. */
#define RMT_LIST_HEAD(ARCH) \
"SELECT s.id, coalesce(s.name, ''), s.updated_ms," \
" EXISTS (SELECT 1 FROM pic_submission u WHERE u.session_id = s.id AND u.status = 'admitted')," \
/* its newest entry: the head the store keeps, not a walk of pic_entry */ \
" coalesce(s.head_seq, 0), " PIC_TITLE_SQL("s") "," \
/* attention: the last request failed, not stopped by the person, or hit the request cap */ \
" coalesce((SELECT (u.status = 'failed' AND coalesce(u.error, '') != 'cancelled')" \
" OR coalesce(u.stop_reason, '') = 'request_cap' FROM pic_submission u WHERE u.session_id = s.id" \
" ORDER BY u.id DESC LIMIT 1), 0)" \
/* or a loop of it needs a person; and how many loops it has */ \
" OR EXISTS (SELECT 1 FROM pic_wake w WHERE w.session_id = s.id AND w.state = 'needs')," \
" (SELECT count(*) FROM pic_wake w WHERE w.session_id = s.id AND w.state != 'ended')," \
" s.created_ms, " ARCH ", coalesce((SELECT t_t.deleted_ms FROM pic_trash t_t WHERE t_t.session_id = s.id), 0)" \
" FROM pic_session s WHERE 1"
#define RMT_LIST_TAIL " ORDER BY s.updated_ms DESC LIMIT ?"
static void rmt_items_free(rmt_item *items, size_t n) {
for (size_t i = 0; i < n; i++) {
free(items[i].name);
free(items[i].title);
free(items[i].preview);
}
free(items);
}
static void rmt_helpers_free(rmt_helpers *h, size_t n) {
for (size_t i = 0; i < n; i++) {
free(h[i].parent);
}
free(h);
}
/* How long building one journal's part of the list may take: past it the part is given up and the
* last one shown, so a slow disk never holds a journal's lane for long. */
#define RMT_LIST_BUDGET_MS 250
/* The virtual machine steps the last list build's statements took on this thread: the tests'
* measure of work done, which a loaded machine's clock is not. */
static _Thread_local long long rmt_list_steps;
/* Journal I's part of the list: its MOST newest conversations a person drives, each with its
* title and last line (ITEMS), and its running helpers by parent (HELPERS). 0, or -1 (none given
* back) when it failed or took longer than BUDGET_MS. */
static int rmt_list_build(rmt_journal *j, int i, size_t most, long long budget_ms, rmt_item **items, size_t *n,
rmt_helpers **helpers, size_t *nh) {
sqlite3_stmt *q = NULL;
size_t cap = 0, hcap = 0;
long long deadline = rmt_mono_ms() + budget_ms;
int rc = 0, step;
#ifdef PIC_FAULTS
if (getenv("PIC_TEST_RC_LIST_BUDGET_MS")) { /* the tests' seam: a budget a test runs out of */
deadline = rmt_mono_ms() + atoll(getenv("PIC_TEST_RC_LIST_BUDGET_MS"));
}
#endif
*items = NULL;
*helpers = NULL;
*n = *nh = 0;
rmt_list_steps = 0;
if (rmt_budget_now) { /* the job's progress handler keeps this part's own deadline too */
rmt_budget_now->inner = deadline;
}
/* a person's alone: not an agent's, a loop's or a headless run's; a journal no pic of this
* build has opened says nothing of origins, and is a person's. The listed, the archived and the
* deleted (not purged) MOST each, so neither crowds the rest out; a journal without
* pic_archive has no archived ones. */
{
int arch = pic_archive_known(&j->s);
static const char *const passes[] = {
" AND " PIC_LISTED_SQL("s") " AND NOT " PIC_ARCHIVED_SQL("s"),
" AND " PIC_LISTED_SQL("s") " AND " PIC_ARCHIVED_SQL("s"),
" AND NOT " PIC_LISTED_SQL("s") " AND NOT " PIC_PURGED_SQL("s"),
" AND " PIC_LISTED_SQL("s"), /* without pic_archive: the first pass's */
};
for (int pass = 0; rc == 0 && pass < 3; pass++) {
const char *head = arch ? RMT_LIST_HEAD(PIC_ARCHIVED_SQL("s")) : RMT_LIST_HEAD("0");
const char *which = arch || pass == 2 ? passes[pass] : pass == 0 ? passes[3] : NULL;
if (!which) {
continue;
}
char *sql = sqlite3_mprintf("%s AND %s IN ('person', 'phone')%s%s", head, PIC_STARTED_BY_SQL("s"), which, RMT_LIST_TAIL);
if (!sql || sqlite3_prepare_v2(j->s.db, sql, -1, &q, NULL) != SQLITE_OK) {
sqlite3_finalize(q);
q = NULL;
sqlite3_free(sql);
sql = sqlite3_mprintf("%s%s%s", head, which, RMT_LIST_TAIL);
if (!sql || sqlite3_prepare_v2(j->s.db, sql, -1, &q, NULL) != SQLITE_OK) {
rc = -1;
}
}
sqlite3_free(sql);
if (rc != 0) {
break;
}
sqlite3_bind_int64(q, 1, (sqlite3_int64)most);
while ((step = sqlite3_step(q)) == SQLITE_ROW) {
rmt_item *it;
if (*n == cap) {
rmt_item *grown = realloc(*items, (cap = cap ? cap * 2 : 64) * sizeof *grown);
if (!grown) {
rc = -1;
break;
}
*items = grown;
}
it = &(*items)[(*n)++];
memset(it, 0, sizeof *it);
it->jx = i;
(void)snprintf(it->id, sizeof it->id, "%s", (const char *)sqlite3_column_text(q, 0));
it->name = strdup((const char *)sqlite3_column_text(q, 1));
it->ms = sqlite3_column_int64(q, 2);
it->running = sqlite3_column_int(q, 3);
it->seq = sqlite3_column_int64(q, 4);
it->title = sqlite3_column_type(q, 5) == SQLITE_NULL ? NULL : strdup((const char *)sqlite3_column_text(q, 5));
it->attention = sqlite3_column_int(q, 6);
it->loops = sqlite3_column_int(q, 7);
it->started = sqlite3_column_int64(q, 8);
it->deleted_ms = sqlite3_column_int64(q, 10);
it->archived = sqlite3_column_int(q, 9); /* kept when deleted: a restore brings it back archived */
}
rc = rc == 0 && step == SQLITE_DONE ? 0 : -1;
rmt_list_steps += sqlite3_stmt_status(q, SQLITE_STMTSTATUS_VM_STEP, 0);
sqlite3_finalize(q);
q = NULL;
}
}
rmt_list_steps += q ? sqlite3_stmt_status(q, SQLITE_STMTSTATUS_VM_STEP, 0) : 0;
sqlite3_finalize(q);
q = NULL;
for (size_t k = 0; rc == 0 && k < *n; k++) {
(*items)[k].preview = pic_session_last_line(&j->s, (*items)[k].id, 120);
rc = rmt_mono_ms() > deadline ? -1 : 0; /* an interrupted read gives no line: not one to keep */
}
/* the helpers running here, by the conversation that started them; a journal no pic of this
* build has opened has no origins, and no helpers */
if (rc == 0 &&
sqlite3_prepare_v2(j->s.db,
"SELECT o.parent, count(*) FROM pic_session_origin o JOIN pic_session c ON c.id = o.session_id"
" WHERE o.parent IS NOT NULL AND " PIC_LISTED_SQL("c")
" AND EXISTS (SELECT 1 FROM pic_submission u WHERE u.session_id = c.id AND u.status = 'admitted')"
" GROUP BY o.parent",
-1, &q, NULL) == SQLITE_OK) {
while ((step = sqlite3_step(q)) == SQLITE_ROW) {
if (*nh == hcap) {
rmt_helpers *grown = realloc(*helpers, (hcap = hcap ? hcap * 2 : 8) * sizeof *grown);
if (!grown) {
rc = -1;
break;
}
*helpers = grown;
}
if (!((*helpers)[*nh].parent = strdup((const char *)sqlite3_column_text(q, 0)))) {
rc = -1;
break;
}
(*helpers)[(*nh)++].n = sqlite3_column_int(q, 1);
}
rc = rc == 0 && step == SQLITE_DONE ? 0 : -1;
}
rmt_list_steps += q ? sqlite3_stmt_status(q, SQLITE_STMTSTATUS_VM_STEP, 0) : 0;
sqlite3_finalize(q);
q = NULL;
/* the questions each conversation waits on (ask.h), by index; a journal with none has no table */
if (rc == 0 && sqlite3_prepare_v2(j->s.db,
"SELECT session_id, count(*) FROM pic_ask WHERE state = 'open' AND expires_ms > ?1 GROUP BY session_id", -1,
&q, NULL) == SQLITE_OK) {
sqlite3_bind_int64(q, 1, pic_wake_now_ms());
while (sqlite3_step(q) == SQLITE_ROW) {
for (size_t k = 0; k < *n; k++) {
if (strcmp((*items)[k].id, (const char *)sqlite3_column_text(q, 0)) == 0) {
(*items)[k].asks = sqlite3_column_int(q, 1);
}
}
}
}
sqlite3_finalize(q);
q = NULL;
/* each conversation's permission mode (perm.h), when not allow; a journal with none has no table */
if (rc == 0 && sqlite3_prepare_v2(j->s.db, "SELECT session_id, mode FROM pic_permission WHERE mode != 'allow'", -1, &q, NULL) ==
SQLITE_OK) {
while (sqlite3_step(q) == SQLITE_ROW) {
for (size_t k = 0; k < *n; k++) {
if (strcmp((*items)[k].id, (const char *)sqlite3_column_text(q, 0)) == 0) {
(void)snprintf((*items)[k].perm, sizeof (*items)[k].perm, "%s", (const char *)sqlite3_column_text(q, 1));
}
}
}
}
sqlite3_finalize(q);
if (rmt_budget_now) {
rmt_budget_now->inner = 0;
}
if (rc != 0) {
rmt_items_free(*items, *n);
rmt_helpers_free(*helpers, *nh);
*items = NULL;
*helpers = NULL;
*n = *nh = 0;
}
return rc;
}
/* The sessions message: the 50 most recently active conversations across the journals, every
* workspace and those that cannot be read, from each journal's part (built by its tick jobs). With
* ONLY (a journal's index), every conversation of that workspace alone, as
* {"workspace":W,"sessions":[...]}, from OWN and OWNH, which it takes. ARCHIVED: archived
* conversations too, each marked "archived":true; TRASH: deleted ones too, each marked "deleted":true
* with deletedMs; without them they are left out. On the loop. */
static char *rmt_list(rmt_state *st, int only, rmt_item *own, size_t nown, rmt_helpers *ownh, size_t nownh, int archived,
int trash) {
rmt_item *items = NULL;
size_t n = 0, cap = 0, most = only >= 0 ? 2000 : RMT_LIST;
rmt_buf b = {NULL, 0, 0};
char *out;
(void)rmt_buf_add(&b, "[", 1);
if (only >= 0) { /* one workspace, asked once: built by its job, and not kept */
items = own;
n = nown;
} else {
for (int i = 0; i < st->njs; i++) {
rmt_journal *j = st->js[i];
if (!j->open || !rmt_shown(st, i)) {
continue;
}
if (n + j->nli > cap) {
rmt_item *grown = realloc(items, (cap = n + j->nli + 64) * sizeof *grown);
if (!grown) {
break;
}
items = grown;
}
for (size_t k = 0; k < j->nli; k++) { /* the journal's own, borrowed: freed with its part */
if (j->li[k].deleted_ms ? !trash : j->li[k].archived && !archived) { /* trash alone decides a deleted one */
continue;
}
items[n] = j->li[k];
items[n++].jx = i;
}
}
}
if (only >= 0) { /* one workspace's, built with its archived and deleted ones */
size_t k = 0;
for (size_t i = 0; i < n; i++) {
if (items[i].deleted_ms ? trash : !items[i].archived || archived) {
rmt_item t = items[k];
items[k++] = items[i];
items[i] = t;
}
}
n = k; /* the rest are still freed with OWN */
}
if (n) {
if (n > 1) { /* glibc: qsort's array may not be NULL, even empty */
qsort(items, n, sizeof *items, rmt_item_cmp);
}
}
for (size_t i = 0; i < n && i < most; i++) {
char *sess = NULL, ms[32], seq[32], *one, wname[256], loops[16], nhelp[16] = "0", nasks[16], started[32], dms[32];
rmt_journal *j = st->js[items[i].jx];
size_t rn = strlen(j->real);
for (int h = 0; h < st->njs; h++) { /* a helper may run in any journal */
rmt_helpers *hs = only >= 0 ? ownh : st->js[h]->open ? st->js[h]->lh : NULL;
size_t nhs = only >= 0 ? nownh : st->js[h]->open ? st->js[h]->nlh : 0;
for (size_t k = 0; k < nhs; k++) {
if (strncmp(hs[k].parent, j->real, rn) == 0 && hs[k].parent[rn] == '/' && strcmp(hs[k].parent + rn + 1, items[i].id) == 0) {
(void)snprintf(nhelp, sizeof nhelp, "%d", atoi(nhelp) + hs[k].n);
}
}
if (only >= 0) {
break;
}
}
rmt_ws_name(st, items[i].jx, wname, sizeof wname);
size_t pn = strlen(j->path) + strlen(items[i].id) + 2;
if ((sess = malloc(pn))) {
(void)snprintf(sess, pn, "%s/%s", j->path, items[i].id);
}
(void)snprintf(ms, sizeof ms, "%lld", items[i].ms);
(void)snprintf(seq, sizeof seq, "%lld", items[i].seq);
(void)snprintf(loops, sizeof loops, "%d", items[i].loops);
(void)snprintf(nasks, sizeof nasks, "%d", items[i].asks);
(void)snprintf(started, sizeof started, "%lld", items[i].started);
(void)snprintf(dms, sizeof dms, "%lld", items[i].deleted_ms);
/* a question waiting on the person is attention, running or not: "Needs you" */
one = rmt_q("SELECT json_patch(json_object('session', ?1, 'name', ?2, 'workspace', ?3, 'lastMs', CAST(?4 AS INTEGER),"
" 'startedMs', CAST(?14 AS INTEGER), 'running', json(?5), 'seq', CAST(?6 AS INTEGER)), json_object('title', ?7,"
" 'preview', ?8, 'state', ?9, 'workspaceName', ?10, 'loops', nullif(CAST(?11 AS INTEGER), 0), 'helpers',"
" nullif(CAST(?12 AS INTEGER), 0), 'asks', nullif(CAST(?13 AS INTEGER), 0), 'archived', CASE WHEN ?15 = '1'"
" THEN json('true') END, 'deleted', CASE WHEN ?16 != '0' THEN json('true') END, 'deletedMs',"
" nullif(CAST(?16 AS INTEGER), 0), 'permissionMode', nullif(?17, '')))",
17, sess, items[i].name ? items[i].name : "", j->workspace, ms, items[i].running ? "true" : "false", seq,
items[i].title, items[i].preview,
items[i].asks ? "attention" : items[i].running ? "running" : items[i].attention ? "attention" : "idle", wname,
loops, nhelp, nasks, started, items[i].archived ? "1" : "0", dms, items[i].perm);
if (one) {
if (b.len > 1) {
(void)rmt_buf_add(&b, ",", 1);
}
(void)rmt_buf_add(&b, one, strlen(one));
}
free(one);
free(sess);
}
if (only >= 0) {
rmt_items_free(own, nown);
} else {
free(items);
}
rmt_helpers_free(ownh, nownh);
(void)rmt_buf_add(&b, "]", 1);
if (only >= 0) {
out = rmt_q("SELECT json_object('type', 'sessions', 'payload', json_object('workspace', ?1, 'sessions', json(?2)))", 2,
st->js[only]->path, b.buf ? b.buf : "[]");
free(b.buf);
return out;
}
{
rmt_buf u = {NULL, 0, 0};
(void)rmt_buf_add(&u, "[", 1);
for (int i = 0; i < st->njs; i++) {
char *one, wname[256];
if (st->js[i]->open || !rmt_shown(st, i)) {
continue;
}
rmt_ws_name(st, i, wname, sizeof wname);
one = rmt_q("SELECT json_object('workspace', ?1, 'reason', ?2, 'name', ?3)", 3, st->js[i]->workspace,
st->js[i]->shown_why, wname);
if (one) {
if (u.len > 1) {
(void)rmt_buf_add(&u, ",", 1);
}
(void)rmt_buf_add(&u, one, strlen(one));
}
free(one);
}
(void)rmt_buf_add(&u, "]", 1);
{ /* every workspace, conversations or not, to start a new one in: W as in W/C */
rmt_buf w = {NULL, 0, 0};
(void)rmt_buf_add(&w, "[", 1);
for (int i = 0; i < st->njs; i++) {
rmt_journal *j = st->js[i];
char ms[32], *one, wname[256];
if (!j->open || !rmt_shown(st, i)) {
continue;
}
rmt_ws_name(st, i, wname, sizeof wname);
(void)snprintf(ms, sizeof ms, "%lld", j->list_ms);
one = rmt_q("SELECT json_object('id', ?1, 'workspace', ?2, 'lastMs', CAST(?3 AS INTEGER), 'name', ?4)", 4, j->path,
j->workspace, ms, wname);
if (one) {
if (w.len > 1) {
(void)rmt_buf_add(&w, ",", 1);
}
(void)rmt_buf_add(&w, one, strlen(one));
}
free(one);
}
(void)rmt_buf_add(&w, "]", 1);
{ /* the most recently used first */
char *sorted = rmt_q("SELECT json_group_array(json_remove(value, '$.lastMs')) FROM (SELECT value FROM json_each(?1)"
" ORDER BY json_extract(value, '$.lastMs') DESC)",
1, w.buf ? w.buf : "[]");
if (sorted) {
free(w.buf);
w.buf = sorted;
}
}
{ /* the folders to start one in, but for those that are workspaces now */
rmt_buf held = {NULL, 0, 0};
(void)rmt_buf_add(&held, "[", 1);
for (int i = 0; i < st->njs; i++) {
/* a hidden journal (one whose making failed, say) leaves its folder offered */
char *one = st->js[i]->hidden ? NULL : rmt_q("SELECT json_quote(?1)", 1, st->js[i]->workspace);
if (one) {
if (held.len > 1) {
(void)rmt_buf_add(&held, ",", 1);
}
(void)rmt_buf_add(&held, one, strlen(one));
}
free(one);
}
(void)rmt_buf_add(&held, "]", 1);
out = rmt_q("SELECT json_object('type', 'sessions', 'payload', json_object('sessions', json(?1), 'workspaces', json(?3),"
" 'unavailable', json(?2), 'folders', json((SELECT json_group_array(json(value)) FROM json_each(?4)"
" WHERE json_extract(value, '$.id') NOT IN (SELECT value FROM json_each(?5)))), 'features',"
" json_array('images', 'asks', 'permissions')))",
5, b.buf ? b.buf : "[]", u.buf ? u.buf : "[]", w.buf ? w.buf : "[]", st->folders ? st->folders : "[]",
held.buf ? held.buf : "[]");
free(held.buf);
}
free(w.buf);
}
free(u.buf);
}
free(b.buf);
return out;
}
/* ---- following (section 4) --------------------------------------------------------------- */
/* A follow's part of a tick job: in, the follow as the loop had it; out, its events and mark as
* lines for its phone, and what the mark said. */
typedef struct {
int di;
unsigned char dev[16];
unsigned gen;
pic_follow *f;
int now;
long long fversion, earlier;
char *wsess;
char skey[48];
rmt_lines out;
long long fev, fver;
int ran, running, more, busy;
} rmt_tfollow;
/* A person's message with images goes without their bytes: each image part names its index among
* the message's images (attach.c puts image K at K + 1) and its size, and the phone asks for the
* bytes with an image message when it shows it. NULL: EVENT has none. */
static char *rmt_image_refs(const char *event) {
if (!strstr(event, "\"type\":\"image\"")) {
return NULL;
}
return rmt_q("SELECT CASE WHEN json_extract(?1, '$.message.role') = 'user' AND json_type(?1, '$.message.content') = 'array'"
" THEN json_set(?1, '$.message.content', json((SELECT json_group_array(CASE WHEN json_extract(value, '$.type') = 'image'"
" THEN json_object('type', 'image', 'mimeType', json_extract(value, '$.mimeType'), 'index', key - 1, 'bytes',"
" length(json_extract(value, '$.data')) / 4 * 3 - (json_extract(value, '$.data') LIKE '%=')"
" - (json_extract(value, '$.data') LIKE '%==')) ELSE json(value) END ORDER BY key)"
" FROM json_each(?1, '$.message.content')))) END",
1, event);
}
static int rmt_emit(void *ctx, long long seq, const char *event) {
rmt_tfollow *c = ctx;
char s[32], *json, *refs = rmt_image_refs(event);
if (refs) {
event = refs;
}
(void)snprintf(s, sizeof s, "%lld", seq);
if (seq > c->fev) {
c->fev = seq;
}
/* The envelope's members before the payload: the sync's key, and for a person's message its
* origin, remote:DEVICE for a phone's and local for any other (section 4). */
static const char head[] =
"SELECT substr(h, 1, length(h) - 1) || ',\"payload\":' || %s || '}' FROM (SELECT json_patch('{}', json_object('type',"
" 'event', 'session', ?1, 'seq', CAST(?2 AS INTEGER), 'key', nullif(?3, ''), 'origin', CASE WHEN json_extract(?4,"
" '$.origin') LIKE 'remote:%%' THEN json_extract(?4, '$.origin') WHEN json_extract(?4, '$.type') IN ('message_start',"
" 'message_end') AND json_extract(?4, '$.message.role') = 'user' THEN 'local' END)) AS h)";
char sql[1024];
if (strlen(event) > (256u << 10)) { /* a large event goes as a note of what it was */
char bytes[32], *t = rmt_q("SELECT json_extract(?1, '$.type')", 1, event);
(void)snprintf(bytes, sizeof bytes, "%zu", strlen(event));
(void)snprintf(sql, sizeof sql, head, "json_object('type', 'elided', 'eventType', ?5, 'bytes', CAST(?6 AS INTEGER))");
json = rmt_q(sql, 6, c->wsess, s, c->skey, "{}", t ? t : "", bytes);
free(t);
} else {
(void)snprintf(sql, sizeof sql, head, "json(?4)");
json = rmt_q(sql, 4, c->wsess, s, c->skey, event);
}
free(refs);
rmt_lines_add(&c->out, json);
return 0;
}
/* Where a follow of CONV starts to show RMT_EARLIER more requests than one from FROM (-1: the latest
* request's start) does: the seq before the first entry of the oldest of them; -1 when FROM shows
* them all. The marks carry it as "earlier", and the phone's sync from it scrolls back. */
static long long rmt_earlier(pic_store *s, const char *conv, long long from) {
sqlite3_stmt *q = NULL;
long long at = -1;
if (sqlite3_prepare_v2(s->db,
"WITH f(v) AS (SELECT CASE WHEN ?2 >= 0 THEN ?2 ELSE coalesce((SELECT min(e.seq) - 1 FROM pic_entry e"
" WHERE e.submission_id = (SELECT max(id) FROM pic_submission WHERE session_id = ?1)), 0) END),"
" r(id) AS (SELECT u.id FROM pic_submission u, f WHERE u.session_id = ?1 AND EXISTS (SELECT 1 FROM"
" pic_entry x WHERE x.submission_id = u.id AND x.seq <= f.v) ORDER BY u.id DESC LIMIT ?3)"
" SELECT max(0, (SELECT min(seq) FROM pic_entry WHERE submission_id = (SELECT min(id) FROM r)) - 1)",
-1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, conv, -1, SQLITE_STATIC);
sqlite3_bind_int64(q, 2, from);
sqlite3_bind_int(q, 3, RMT_EARLIER);
if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_type(q, 0) != SQLITE_NULL) {
at = sqlite3_column_int64(q, 0);
}
}
sqlite3_finalize(q);
return at;
}
/* An image message (section 4): the bytes of image INDEX of the person's message at entry SEQ of
* the conversation, or why not. */
static void rmt_image(rmt_job *jb, rmt_journal *j, const rmt_env *e, const char *conv) {
char *index = e->payload ? rmt_q("SELECT CASE json_type(?1, '$.index') WHEN 'integer' THEN"
" json_extract(?1, '$.index') END", 1, e->payload)
: NULL;
const char *why = "no_image";
char *out = NULL;
if (!index || !e->has_seq || !e->session) {
rmt_out_error(jb, NULL, "bad_message", "an image message names its session, seq and payload.index");
free(index);
return;
}
if (j && j->sopen) {
sqlite3_stmt *q = NULL;
if (sqlite3_prepare_v2(j->s.db,
"SELECT i.mime, i.data IS NULL, (i.sz + 2) / 3 * 4 + 512 > ?4, CASE WHEN i.data IS NOT NULL AND"
" (i.sz + 2) / 3 * 4 + 512 <= ?4 THEN pic_base64(sqlar_uncompress(i.data, i.sz)) END"
" FROM pic_attachment a JOIN pic_image i ON i.hash = a.image JOIN pic_entry x ON x.seq = a.entry_seq"
" JOIN pic_submission u ON u.id = x.submission_id"
" WHERE a.entry_seq = ?1 AND a.ordinal = ?2 AND u.session_id = ?3 AND x.kind = 'user'",
-1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_int64(q, 1, e->seq);
sqlite3_bind_int64(q, 2, atoll(index));
sqlite3_bind_text(q, 3, conv, -1, SQLITE_STATIC);
sqlite3_bind_int64(q, 4, (sqlite3_int64)(RMT_MSG_CAP - strlen(e->session)));
if (sqlite3_step(q) == SQLITE_ROW) {
if (sqlite3_column_int(q, 1)) {
why = "removed"; /* pic prune took its bytes */
} else if (sqlite3_column_int(q, 2)) {
why = "too_large";
} else if (sqlite3_column_text(q, 3)) {
char s[32];
(void)snprintf(s, sizeof s, "%lld", e->seq);
out = rmt_q("SELECT json_object('type', 'image', 'session', ?1, 'seq', CAST(?2 AS INTEGER), 'payload',"
" json_object('index', CAST(?3 AS INTEGER), 'mimeType', ?4, 'data', ?5))",
5, e->session, s, index, (const char *)sqlite3_column_text(q, 0),
(const char *)sqlite3_column_text(q, 3));
}
}
}
sqlite3_finalize(q);
}
if (!out) {
char s[32];
(void)snprintf(s, sizeof s, "%lld", e->seq);
out = rmt_q("SELECT json_object('type', 'image', 'session', ?1, 'seq', CAST(?2 AS INTEGER), 'payload',"
" json_object('index', CAST(?3 AS INTEGER), 'error', ?4))",
4, e->session, s, index, why);
}
rmt_out(jb, out);
free(index);
}
static int rmt_page(void) {
#ifdef PIC_FAULTS
if (getenv("PIC_TEST_RC_PAGE")) { /* the tests' seam: a history of a few entries goes in pages */
return atoi(getenv("PIC_TEST_RC_PAGE"));
}
#endif
return RMT_PAGE;
}
/* Whether the last call on S failed because another pic holds the journal's write lock. */
static int rmt_busy(pic_store *s) { return (sqlite3_extended_errcode(s->db) & 0xff) == SQLITE_BUSY; }
/* One pass of FO's follow at J's data_version DV, on J's lane: its events, then a mark. */
static void rmt_follow_pass(rmt_journal *j, rmt_tfollow *fo, long long dv) {
long long last = 0;
int running = 0, more = 0;
char s[32], earlier[32];
fo->ran = 1;
fo->fver = dv;
if (pic_follow_pass(fo->f, rmt_emit, fo, rmt_page(), &last, &running, &more) != 0) {
int rc = sqlite3_extended_errcode(j->s.db) & 0xff;
if (rc == SQLITE_BUSY || rc == SQLITE_INTERRUPT) {
fo->busy = 1; /* looked at again next tick */
return;
}
rmt_lines_add(&fo->out, rmt_error_json(NULL, "unavailable", "cannot read the conversation"));
return;
}
fo->running = running;
fo->more = more; /* a long history goes a page a tick, between everything else */
(void)snprintf(s, sizeof s, "%lld", last);
(void)snprintf(earlier, sizeof earlier, "%lld", fo->earlier);
rmt_lines_add(&fo->out,
rmt_q("SELECT json_patch('{}', json_object('type', 'sync', 'session', ?1, 'seq', CAST(?2 AS INTEGER), 'key',"
" nullif(?4, ''), 'payload', json_object('running', json(?3), 'earlier', CASE WHEN CAST(?5 AS INTEGER) >= 0"
" THEN CAST(?5 AS INTEGER) END)))",
5, fo->wsess, s, running ? "true" : "false", fo->skey, earlier));
}
static void rmt_live_reset(rmt_dev *d) {
d->live_ino = 0;
d->live_dev = 0;
d->live_head = d->live_len = 0;
d->live_pos = d->live_chars = 0;
d->live_sent = -1;
}
/* D follows nothing: its follow goes back to its journal's lane to be closed, and whatever a job
* still in hand finds for it is dropped. */
static void rmt_unfollow(rmt_state *st, rmt_dev *d) {
if (d->f && d->jx >= 0 && d->jx < st->njs) {
rmt_journal *j = st->js[d->jx];
if (!st->pool.started) {
rmt_follow_forget(j, d->f);
} else {
(void)pthread_mutex_lock(&st->pool.mu);
if (j->ndead == j->capdead) {
int cap = j->capdead ? j->capdead * 2 : 4;
pic_follow **g = realloc(j->dead, (size_t)cap * sizeof *g);
if (g) {
j->dead = g;
j->capdead = cap;
}
}
if (j->ndead < j->capdead) {
j->dead[j->ndead++] = d->f;
}
(void)pthread_mutex_unlock(&st->pool.mu);
}
}
d->f = NULL;
d->fgen++;
free(d->live_path);
d->live_path = NULL;
free(d->wsess);
d->wsess = NULL;
d->skey[0] = '\0';
d->fev = 0;
d->frunning = 0;
d->earlier = -1;
rmt_live_reset(d);
}
/* ---- the reply as it streams (section 4) -------------------------------------------------- */
/* The characters in P's N bytes: the bytes that start one. */
static long long rmt_chars(const char *p, size_t n) {
long long c = 0;
for (size_t i = 0; i < n; i++) {
c += ((unsigned char)p[i] & 0xC0) != 0x80;
}
return c;
}
/* D's live value, from the conversation's .live file (pic_live_path), while its last mark said a
* request runs: at most one every 250 ms, and only when nothing waits to be posted to it, so one
* value never queues behind another. A value is sent when the text grew; its seq is the entry the
* reply came after, never behind an event this follow sent. */
static void rmt_live(rmt_state *st, rmt_dev *d) {
char path[4096];
struct stat sb;
long long now = rmt_mono_ms();
int fd;
if (!d->f || d->sess < 0 || !d->frunning || d->lane.qlen || now - d->live_ms < RMT_LIVE_MS || !d->live_path ||
snprintf(path, sizeof path, "%s", d->live_path) >= (int)sizeof path) {
return;
}
if ((fd = open(path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW)) < 0) {
rmt_live_reset(d); /* no reply is streaming */
return;
}
if (fstat(fd, &sb) != 0 || !S_ISREG(sb.st_mode)) {
close(fd);
return;
}
if (sb.st_ino != d->live_ino || sb.st_dev != d->live_dev) { /* a new reply */
char head[64], *nl;
ssize_t n = pread(fd, head, sizeof head - 1, 0);
long long seq;
rmt_live_reset(d);
if (n <= 0 || !(nl = memchr(head, '\n', (size_t)n)) || (head[n] = '\0', sscanf(head, "pic-live 1 %lld", &seq) != 1)) {
close(fd); /* its head not written yet */
return;
}
d->live_ino = sb.st_ino;
d->live_dev = sb.st_dev;
d->live_head = (size_t)(nl - head) + 1;
d->live_seq = seq;
}
if ((long long)sb.st_size > (long long)d->live_head + d->live_pos) {
long long avail = (long long)sb.st_size - (long long)d->live_head - d->live_pos;
size_t want = avail > (1 << 20) ? (size_t)(1 << 20) : (size_t)avail;
char *tmp = malloc(d->live_len + want);
ssize_t got = -1;
if (tmp) {
memcpy(tmp, d->live_buf, d->live_len);
got = pread(fd, tmp + d->live_len, want, (off_t)((long long)d->live_head + d->live_pos));
}
if (got > 0) {
size_t keep = d->live_len + (size_t)got, i = keep, cut;
/* a character cut off at the end waits for its other bytes */
while (i > d->live_len && keep - i < 3 && ((unsigned char)tmp[i - 1] & 0xC0) == 0x80) {
i--;
}
if (i > d->live_len) {
unsigned char c = (unsigned char)tmp[i - 1];
size_t need = c >= 0xF0 ? 4 : c >= 0xE0 ? 3 : c >= 0xC0 ? 2 : 1;
if (keep - (i - 1) < need) {
keep = i - 1;
}
}
d->live_pos += (long long)(keep - d->live_len);
cut = keep > RMT_LIVE_KEEP ? keep - RMT_LIVE_KEEP : 0;
while (cut < keep && ((unsigned char)tmp[cut] & 0xC0) == 0x80) {
cut++;
}
d->live_chars += rmt_chars(tmp, cut);
memmove(d->live_buf, tmp + cut, keep - cut);
d->live_len = keep - cut;
}
free(tmp);
}
close(fd);
if (d->live_len && d->live_pos != d->live_sent && d->live_seq >= d->fev) {
char seq[32], rev[32], off[32];
d->live_buf[d->live_len] = '\0';
(void)snprintf(seq, sizeof seq, "%lld", d->live_seq);
(void)snprintf(rev, sizeof rev, "%lld", ++st->live_rev);
(void)snprintf(off, sizeof off, "%lld", d->live_chars);
rmt_send_free(st, d,
rmt_q("SELECT json_object('type', 'live', 'session', ?1, 'seq', CAST(?2 AS INTEGER), 'payload',"
" json_object('rev', CAST(?3 AS INTEGER), 'offset', CAST(?4 AS INTEGER), 'text', ?5))",
5, d->wsess, seq, rev, off, d->live_buf));
d->live_sent = d->live_pos;
d->live_ms = now;
}
}
/* ---- commands (section 4) ----------------------------------------------------------------- */
static int rmt_cmd_find(rmt_dev *d, const char *key) {
for (int i = 0; i < d->ncmds; i++) {
if (strcmp(d->cmds[i].key, key) == 0) {
return i;
}
}
return -1;
}
/* Children whose command was dropped before they ended (a prompt's, once its request is admitted;
* any of a device unpaired): waited for each tick, so none is left defunct. The loop's alone. */
static pid_t *rmt_orphans;
static int rmt_norphans, rmt_caporphans;
static void rmt_orphan(pid_t pid) {
if (pid <= 0) {
return;
}
if (rmt_norphans == rmt_caporphans) {
int cap = rmt_caporphans ? rmt_caporphans * 2 : 16;
pid_t *g = realloc(rmt_orphans, (size_t)cap * sizeof *g);
if (!g) {
return;
}
rmt_orphans = g;
rmt_caporphans = cap;
}
rmt_orphans[rmt_norphans++] = pid;
}
static void rmt_reap(void) {
for (int i = 0; i < rmt_norphans;) {
int status;
pid_t w = waitpid(rmt_orphans[i], &status, WNOHANG);
if (w == rmt_orphans[i] || (w < 0 && errno == ECHILD)) {
rmt_orphans[i] = rmt_orphans[--rmt_norphans];
} else {
i++;
}
}
}
static void rmt_cmd_drop(rmt_dev *d, int i) {
rmt_orphan(d->cmds[i].pid);
free(d->cmds[i].line);
free(d->cmds[i].answer);
if (d->cmds[i].errfd >= 0) {
close(d->cmds[i].errfd);
}
d->cmds[i] = d->cmds[--d->ncmds];
}
static rmt_cmd *rmt_cmd_add(rmt_dev *d, int kind, int jx, const char *key, const char *row, const char *line) {
rmt_cmd *c;
if (d->ncmds == RMT_CMDS) {
rmt_cmd_drop(d, 0);
}
c = &d->cmds[d->ncmds++];
memset(c, 0, sizeof *c);
c->kind = kind;
c->jx = jx;
c->errfd = -1;
(void)snprintf(c->key, sizeof c->key, "%s", key);
(void)snprintf(c->row, sizeof c->row, "%s", row);
c->line = line ? strdup(line) : NULL;
return c;
}
static void rmt_response(rmt_state *st, rmt_dev *d, const char *key, const char *line) {
rmt_send_free(st, d, rmt_q("SELECT json_object('type', 'response', 'key', ?1, 'payload', json(?2))", 2, key, line));
}
/* A prompt's success, naming the conversation it went to in the journal at PATH (a new one's id
* is learnt here): CONV "" for none. */
static char *rmt_prompt_ok(const char *path, const char *key, const char *conv) {
char *wsess = NULL, *out;
if (conv[0]) {
size_t n = strlen(path) + strlen(conv) + 2;
if ((wsess = malloc(n))) {
(void)snprintf(wsess, n, "%s/%s", path, conv);
}
}
out = rmt_q("SELECT json_patch('{}', json_object('type', 'response', 'key', ?1, 'session', ?2, 'payload',"
" json_object('type', 'response', 'command', 'prompt', 'success', json('true'))))",
2, key, wsess);
free(wsess);
return out;
}
/* Whether a request was admitted under ROW (the keyed admission's key), and its conversation in
* CONV (64 bytes; may be NULL). On the lane. */
static int rmt_admitted(pic_store *s, const char *row, char *conv) {
sqlite3_stmt *q = NULL;
int yes = 0;
if (conv) {
conv[0] = '\0';
}
if (sqlite3_prepare_v2(s->db, "SELECT session_id FROM pic_submission WHERE request_key = ?", -1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, row, -1, SQLITE_STATIC);
if ((yes = sqlite3_step(q) == SQLITE_ROW) && conv && sqlite3_column_text(q, 0)) {
(void)snprintf(conv, 64, "%s", (const char *)sqlite3_column_text(q, 0));
}
}
sqlite3_finalize(q);
return yes;
}
/* Pi's response line for COMMAND (with the command's id, when it had one). */
static char *rmt_pi_response(const char *payload, const char *command, int success, const char *data, const char *error) {
return rmt_q("SELECT json_patch('{}', json_object('id', json_extract(?1, '$.id'), 'type', 'response', 'command', ?2,"
" 'success', json(?3), 'data', json(?4), 'error', ?5))",
5, payload, command, success ? "true" : "false", data, error);
}
/* A successful response whose DATA keeps its null members (json_patch, above, drops them): the answer's. */
static char *rmt_pi_response_keep(const char *payload, const char *command, const char *data) {
return rmt_q("SELECT json_object('id', json_extract(?1, '$.id'), 'type', 'response', 'command', ?2, 'success', json('true'),"
" 'data', json(?3))",
3, payload, command, data);
}
static rmt_choice *rmt_choice_find(rmt_state *st, int jx, const char *conv) {
for (int i = 0; i < st->nchoices; i++) {
if (st->choices[i].jx == jx && strcmp(st->choices[i].conv, conv) == 0) {
return &st->choices[i];
}
}
return NULL;
}
/* The conversation's choice, made now when it has none (the oldest gives way). */
static rmt_choice *rmt_choice_get(rmt_state *st, int jx, const char *conv) {
rmt_choice *c = rmt_choice_find(st, jx, conv);
if (c) {
return c;
}
if (st->nchoices == RMT_CHOICES) {
memmove(&st->choices[0], &st->choices[1], (RMT_CHOICES - 1) * sizeof st->choices[0]);
st->nchoices--;
}
c = &st->choices[st->nchoices++];
memset(c, 0, sizeof *c);
c->jx = jx;
(void)snprintf(c->conv, sizeof c->conv, "%s", conv);
return c;
}
static void rmt_choice_clear(rmt_state *st, int jx, const char *conv) {
rmt_choice *c = rmt_choice_find(st, jx, conv);
if (c) {
*c = st->choices[--st->nchoices];
}
}
/* The choices change on the loop and are read by a command's job when it runs (not when it was
* queued: a set_model just before it on the lane is applied by then). */
static pthread_mutex_t rmt_choice_mu = PTHREAD_MUTEX_INITIALIZER;
static void rmt_choice_copy(rmt_state *st, int jx, const char *conv, rmt_choice *out) {
rmt_choice *c;
(void)pthread_mutex_lock(&rmt_choice_mu);
c = rmt_choice_find(st, jx, conv);
if (c) {
*out = *c;
} else {
memset(out, 0, sizeof *out);
}
(void)pthread_mutex_unlock(&rmt_choice_mu);
}
/* The model and thinking level CONV's next request runs on: C, a phone's choice (NULL: none), else
* what its last request used, as at the terminal; with FRESH (a new conversation), the workspace's
* last. On the lane. */
static void rmt_next_model(pic_store *s, const char *conv, int fresh, const rmt_choice *c, char *model, size_t mcap,
char *thinking, size_t tcap) {
sqlite3_stmt *q = NULL;
model[0] = thinking[0] = '\0';
if (fresh) {
c = NULL;
}
if (sqlite3_prepare_v2(s->db,
"SELECT model, thinking FROM pic_submission WHERE (?2 OR session_id = ?1) AND model IS NOT NULL"
" ORDER BY id DESC LIMIT 1",
-1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, conv, -1, SQLITE_STATIC);
sqlite3_bind_int(q, 2, fresh);
if (sqlite3_step(q) == SQLITE_ROW) {
(void)snprintf(model, mcap, "%s", (const char *)sqlite3_column_text(q, 0));
if (sqlite3_column_type(q, 1) == SQLITE_TEXT) {
(void)snprintf(thinking, tcap, "%s", (const char *)sqlite3_column_text(q, 1));
}
}
}
sqlite3_finalize(q);
if (c && c->model[0]) {
(void)snprintf(model, mcap, "%s", c->model);
}
if (c && c->thinking[0]) {
(void)snprintf(thinking, tcap, "%s", c->thinking);
}
}
/* The newest entries of a conversation's path a phone's question reads (get_messages,
* get_session_stats, get_state's messageCount): its work is bounded by this, not by how long the
* conversation is. */
#define RMT_PATH_MOST 300
/* Whether S may build Pi entries for a phone: only with the index of generations by entry, which
* every pic since it makes when it opens the journal. Without it the build copies all of
* pic_generation (tens of megabytes) into a temporary index; then S->err says so. */
static int rmt_entries_ok(pic_store *s) {
sqlite3_stmt *q = NULL;
int ok = 0;
if (sqlite3_prepare_v2(s->db, "SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = 'pic_generation_entry'", -1, &q,
NULL) == SQLITE_OK) {
ok = sqlite3_step(q) == SQLITE_ROW;
}
sqlite3_finalize(q);
if (!ok) {
(void)snprintf(s->err, sizeof s->err, "open pic in this workspace once on the computer, then ask again");
}
return ok;
}
/* A command's job: the message as it came and what the loop knew when it was queued; then, for the
* loop, what it found to do. */
typedef struct {
rmt_env e;
rmt_state *st; /* for the choices, read under rmt_choice_mu when the job runs */
int jx;
char conv[64];
int fresh; /* +W: a prompt that starts a new conversation */
int create; /* +F: in a folder of remote.folders, whose journal it makes when it has none */
int known; /* the key is a command the device has in hand (a prompt starting) */
rmt_choice ch; /* the conversation's choice when the job ran; ch.conv "" for none */
char *names; /* the devices' names by id */
const pic_remote_options *o;
/* found */
char row[96];
char *keep; /* an inbox row left pending: its line, polled until it settles */
int start; /* 1: start the prompt's request; 2: start the compaction */
char model[256], thinking[32], keylabel[PIC_CRED_LABEL_CAP];
char *text, *focus;
int imgfd;
int setm, setk, sett; /* the choice's model, key and level change to set's */
rmt_choice set;
char cand[256]; /* set_credential: the model the choice takes when it has none */
/* +W or +F: the prompt's choice for the new conversation's first request; "" none */
char fm[256], ft[32], fk[PIC_CRED_LABEL_CAP];
} rmt_cmdjob;
static void rmt_cmdjob_drop(void *p) {
rmt_cmdjob *c = p;
if (!c) {
return;
}
rmt_env_free(&c->e);
free(c->names);
free(c->keep);
free(c->text);
free(c->focus);
if (c->imgfd >= 0) {
close(c->imgfd);
}
free(c);
}
static const rmt_choice *rmt_cmd_choice(const rmt_cmdjob *c) { return c->ch.conv[0] ? &c->ch : NULL; }
/* get_state and get_messages, answered from the journal; no row. get_state reads no entries:
* messageCount counts the messages among the newest RMT_PATH_MOST of the path. */
static void rmt_query(rmt_job *jb, rmt_journal *j, rmt_cmdjob *c) {
pic_store *s = &j->s;
rmt_env *e = &c->e;
const char *conv = c->conv;
const rmt_choice *ch = rmt_cmd_choice(c);
int state = strcmp(e->ptype, "get_state") == 0;
char *entries = NULL, *msgs = NULL, *data = NULL, *line, count[24] = "0";
s->err[0] = '\0';
if (!state) {
entries = rmt_entries_ok(s) ? pic_pi_entries(s, conv, RMT_PATH_MOST) : NULL;
msgs = entries ? pic_rpc_messages(s->db, entries) : NULL;
} else {
sqlite3_stmt *q = NULL;
if (sqlite3_prepare_v2(s->db,
"WITH RECURSIVE p(seq, n) AS (SELECT head_seq, 1 FROM pic_session WHERE id = ?1"
" UNION ALL SELECT x.parent_seq, p.n + 1 FROM pic_entry x JOIN p ON x.seq = p.seq"
" WHERE x.parent_seq IS NOT NULL AND p.n < ?2)"
" SELECT count(*) FROM p JOIN pic_entry e ON e.seq = p.seq WHERE e.kind IN ('user', 'assistant', 'tool_result')",
-1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, conv, -1, SQLITE_STATIC);
sqlite3_bind_int(q, 2, RMT_PATH_MOST);
if (sqlite3_step(q) == SQLITE_ROW) {
(void)snprintf(count, sizeof count, "%lld", (long long)sqlite3_column_int64(q, 0));
}
}
sqlite3_finalize(q);
}
if (msgs && !state) {
data = rmt_q("SELECT json_object('messages', json(?1))", 1, msgs);
} else if (state) {
sqlite3_stmt *q = NULL;
if (sqlite3_prepare_v2(s->db,
"SELECT json_object('model', json((SELECT CASE WHEN instr(model, '/') THEN json_object('provider',"
" substr(model, 1, instr(model, '/') - 1), 'id', substr(model, instr(model, '/') + 1)) END"
" FROM pic_submission WHERE session_id = ?1 AND model IS NOT NULL ORDER BY id DESC LIMIT 1)),"
" 'thinkingLevel', (SELECT thinking FROM pic_submission WHERE session_id = ?1 AND thinking IS NOT NULL"
" ORDER BY id DESC LIMIT 1),"
" 'isStreaming', json(iif(EXISTS (SELECT 1 FROM pic_submission WHERE session_id = ?1 AND"
" status = 'admitted'), 'true', 'false')), 'isCompacting', json('false'), 'sessionId', ?1,"
" 'sessionName', (SELECT name FROM pic_session WHERE id = ?1), 'messageCount', CAST(?2 AS INTEGER),"
" 'pendingMessageCount', (SELECT count(*) FROM pic_inbox WHERE session_id = ?1 AND state = 'pending'))",
-1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, conv, -1, SQLITE_STATIC);
sqlite3_bind_text(q, 2, count, -1, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW) {
data = strdup((const char *)sqlite3_column_text(q, 0));
}
}
sqlite3_finalize(q);
if (data) { /* the key the next request goes with: the phone's choice, else the conversation's own */
char model[256], thinking[16], label[PIC_CRED_LABEL_CAP], cred[PIC_CRED_NAME_CAP] = "", *patched;
int own = pic_session_choice(s, conv, model, sizeof model, thinking, sizeof thinking, label, sizeof label) == 1;
if (ch && ch->model[0]) {
(void)snprintf(model, sizeof model, "%s", ch->model);
}
if (ch && ch->key[0]) {
(void)snprintf(label, sizeof label, "%s", ch->key);
}
if ((own || (ch && ch->model[0])) && label[0] && strchr(model, '/')) {
(void)snprintf(cred, sizeof cred, "%.*s:%s", (int)(strchr(model, '/') - model), model, label);
}
patched = cred[0] ? rmt_q("SELECT json_set(?1, '$.credential', ?2)", 2, data, cred) : NULL;
if (patched) {
free(data);
data = patched;
}
}
if (data) { /* its permission mode (perm.h) */
char mode[16], *patched;
patched = pic_perm_get(s, conv, mode, sizeof mode) == 0 ? rmt_q("SELECT json_set(?1, '$.permissionMode', ?2)", 2, data, mode) : NULL;
if (patched) {
free(data);
data = patched;
}
}
if (data) { /* the questions it waits on a person for (ask.h) */
char *asks = pic_ask_list(s, conv, -1, RMT_ASKS), *settled = pic_ask_settled(s, conv);
char *patched = asks && settled && c->names
? rmt_q("SELECT json_set(?1, '$.asks', json((SELECT json_group_array(json(json_remove(value, '$.session', '$.version')))"
" FROM json_each(?2))), '$.settledAsks', json((SELECT json_group_array(json(" RMT_SETTLED_SQL("value", "?4") "))"
" FROM json_each(?3))))",
4, data, asks, settled, c->names)
: NULL;
free(settled);
if (patched) {
free(data);
data = patched;
}
free(asks);
}
if (data && ch) { /* what the next request runs on */
char model[256], thinking[32], *patched;
rmt_next_model(s, conv, 0, ch, model, sizeof model, thinking, sizeof thinking);
patched = rmt_q("SELECT json_set(?1, '$.model', CASE WHEN instr(?2, '/') THEN json_object('provider', substr(?2, 1,"
" instr(?2, '/') - 1), 'id', substr(?2, instr(?2, '/') + 1)) END, '$.thinkingLevel', nullif(?3, ''))",
3, data, model, thinking);
if (patched) {
free(data);
data = patched;
}
}
}
line = rmt_pi_response(e->payload, e->ptype, data != NULL, data, data ? NULL : s->err[0] ? s->err : "cannot read the conversation");
rmt_out_response(jb, e->key, line);
free(line);
free(data);
free(msgs);
free(entries);
}
static int rmt_running(pic_store *s, const char *conv) {
sqlite3_stmt *q = NULL;
int running = 0;
if (sqlite3_prepare_v2(s->db, "SELECT EXISTS (SELECT 1 FROM pic_submission WHERE session_id = ? AND status = 'admitted')", -1,
&q, NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, conv, -1, SQLITE_STATIC);
running = sqlite3_step(q) == SQLITE_ROW && sqlite3_column_int(q, 0);
}
sqlite3_finalize(q);
return running;
}
/* steer, follow_up and abort through pic_inbox_accept, unchanged: ack once committed, the response
* once the row leaves pending (the row is kept for the tick jobs to poll). */
static void rmt_inbox(rmt_job *jb, rmt_journal *j, rmt_cmdjob *c, const char *line) {
pic_store *s = &j->s;
const char *key = c->e.key;
pic_inbox_msg m;
char sender[48], got[64], state[16];
int rc;
(void)snprintf(c->row, sizeof c->row, "rc:%s:%s", jb->idb, key);
(void)snprintf(sender, sizeof sender, "remote:%s", jb->idb);
memset(&m, 0, sizeof m);
m.session = c->conv;
m.key = c->row;
m.line = line;
m.sender = sender;
rc = pic_inbox_accept(s, &m, got, sizeof got, state, sizeof state);
if (rc < 0 && rmt_busy(s)) {
rmt_out_error(jb, key, "busy", RMT_BUSY_TEXT);
return;
}
if (rc != 0) {
rmt_out_error(jb, key, rc > 0 ? "refused" : "failed", s->err);
return;
}
if (strcmp(state, "pending") == 0) {
free(c->keep);
c->keep = strdup(line);
rmt_out(jb, rmt_q("SELECT json_object('type', 'ack', 'key', ?1, 'payload', json_object('state', 'pending'))", 1, key));
return;
}
{
char *response = NULL;
if (pic_inbox_status(s, c->row, state, sizeof state, &response) == 0 && response) {
rmt_out_response(jb, key, response);
} else {
rmt_out(jb, rmt_q("SELECT json_object('type', 'response', 'key', ?1, 'payload', json_object('state', ?2))", 2, key,
state));
}
free(response);
}
}
/* A prompt's images, Pi's image content: 0 with none, 1 with *JSON their array (malloc'd), checked as
* a pasted image is, or -1 with WHY when they are not images pic can send. */
static int rmt_prompt_images(const char *payload, char **json, char *why, size_t cap) {
char *t = rmt_q("SELECT json_type(?1, '$.images')", 1, payload);
pic_image *images = NULL;
unsigned char *bytes = NULL;
size_t n = 0;
const char *error = NULL;
char *text = NULL;
int rc;
*json = NULL;
if (!t || strcmp(t, "null") == 0) {
free(t);
return 0;
}
rc = strcmp(t, "array") == 0 ? 0 : -1;
free(t);
if (rc != 0) {
(void)snprintf(why, cap, "images must be an array");
return -1;
}
if (pic_images_from_json(rmt_mem(), payload, "$.images", 1, &images, &n, &bytes, &error) != 0) {
(void)snprintf(why, cap, "%s", error ? error : "images must be an array of image content");
rc = -1;
} else if (n && !(text = pic_image_prepare("", images, &n, why, cap))) {
rc = -1;
} else if (n) {
rc = (*json = rmt_q("SELECT json_extract(?1, '$.images')", 1, payload)) ? 1 : -1;
if (rc < 0) {
(void)snprintf(why, cap, "out of memory");
}
}
free(text);
free(images);
free(bytes);
return rc;
}
static int rmt_uploads_dir(const char *workspace, char *why, size_t cap);
static int rmt_upload_name_ok(const char *name);
/* A prompt's files (payload.files, at most 16): each an upload of J's workspace,
* ".pic/uploads/NAME", there now. TEXT with a line "[attached: PATH]" for each appended,
* malloc'd (TEXT alone when there are none); NULL with WHY when one is not. On the lane. */
static char *rmt_prompt_files(rmt_journal *j, const char *payload, const char *text, char *why, size_t cap) {
char *t = rmt_q("SELECT json_type(?1, '$.files')", 1, payload);
sqlite3_stmt *q = NULL;
sqlite3_str *b;
int dir = -1, n = 0, ok = 1;
if (!t || strcmp(t, "null") == 0) {
free(t);
return strdup(text);
}
if (strcmp(t, "array") != 0 || sqlite3_prepare_v2(rmt_mem(), "SELECT value, type FROM json_each(?1, '$.files')", -1, &q, NULL) != SQLITE_OK) {
free(t);
sqlite3_finalize(q);
(void)snprintf(why, cap, "files is an array of uploads, .pic/uploads/NAME");
return NULL;
}
free(t);
b = sqlite3_str_new(NULL);
sqlite3_str_appendall(b, text);
sqlite3_bind_text(q, 1, payload, -1, SQLITE_STATIC);
while (ok && sqlite3_step(q) == SQLITE_ROW) {
const char *v = (const char *)sqlite3_column_text(q, 0), *ty = (const char *)sqlite3_column_text(q, 1);
struct stat sb;
ok = ++n <= 16 && ty && strcmp(ty, "text") == 0 && v && strncmp(v, ".pic/uploads/", 13) == 0 && rmt_upload_name_ok(v + 13) &&
(dir >= 0 || (dir = rmt_uploads_dir(j->workspace, why, cap)) >= 0) &&
fstatat(dir, v + 13, &sb, AT_SYMLINK_NOFOLLOW) == 0 && S_ISREG(sb.st_mode);
if (ok) {
sqlite3_str_appendf(b, "%s[attached: %s]", n == 1 ? "\n\n" : "\n", v);
}
}
sqlite3_finalize(q);
if (dir >= 0) {
close(dir);
}
{
char *got = sqlite3_str_finish(b), *out = got && ok ? strdup(got) : NULL;
sqlite3_free(got);
if (!ok) {
(void)snprintf(why, cap, "a prompt's files are files uploaded to this workspace, .pic/uploads/NAME (at most 16)");
}
return out;
}
}
/* TEXT as pic ask submits it: a skill (/skill:NAME ARGS) or a prompt template (/NAME ARGS) of
* workspace WS expanded in *OUT, else *OUT NULL (an unknown name is sent as typed, as Pi's). -1
* with WHY when the skill named is gone. Reads the trust list: a job of the user lane. */
static int rmt_expand(const char *ws, const char *text, char **out, char *why, size_t cap) {
char real[PATH_MAX];
int project, rc = 0;
*out = NULL;
if (text[0] != '/') {
return 0;
}
project = pic_trust_get(realpath(ws, real) ? real : ws) == 1;
if (strncmp(text, "/skill:", 7) == 0) {
pic_skills k;
if (pic_skills_load(&k, ws, project, NULL) == 0) {
rc = pic_skills_expand(&k, text, out, why, cap) < 0 ? -1 : 0;
pic_skills_free(&k);
}
} else {
pic_prompts p;
if (pic_prompts_load(&p, ws, project) == 0) {
*out = pic_prompts_expand(&p, text);
pic_prompts_free(&p);
}
}
return rc;
}
/* A prompt to start as a keyed admission and a detached run, for the loop to fork: its model,
* thinking level and key, and its images in a file no one else can open (gone when it closes).
* FRESH: CONV is a new conversation's id. On the lane. */
static void rmt_start(rmt_job *jb, rmt_journal *j, rmt_cmdjob *c, const char *conv, const char *text, const char *images,
int fresh) {
const rmt_choice *ch = fresh ? NULL : rmt_cmd_choice(c);
rmt_next_model(&j->s, conv, fresh, ch, c->model, sizeof c->model, c->thinking, sizeof c->thinking);
if (ch && ch->key[0]) { /* the phone's key for this conversation: the run's, as --key */
(void)snprintf(c->keylabel, sizeof c->keylabel, "%s", ch->key);
}
if (!fresh && !c->keylabel[0] && c->model[0] && (!ch || !ch->model[0])) {
/* a conversation keeps the key its replies went with (named-keys.md), as resume_choice keeps
* it for pic ask when no model is chosen: its last reply's key to this model's provider, while
* that key is there */
char own[256], level[32], label[PIC_CRED_LABEL_CAP], err[PIC_ERR_CAP];
pic_model m;
size_t pn;
if (pic_session_choice(&j->s, conv, own, sizeof own, level, sizeof level, label, sizeof label) == 1 && label[0] &&
pic_model_resolve(c->model, &m, err, sizeof err) == 0 && (pn = strlen(m.provider)) > 0 &&
strncmp(own, m.provider, pn) == 0 && own[pn] == '/') {
if (!pic_cred_has(m.provider, label, m.key_env, m.key_literal)) {
char msg[320];
char *line;
(void)snprintf(msg, sizeof msg,
"The key \"%.40s\" this conversation went with is gone from %.64s: choose another with set_credential.",
label, m.provider);
line = rmt_pi_response(c->e.payload, "prompt", 0, NULL, msg);
rmt_out_response(jb, c->e.key, line);
free(line);
return;
}
(void)snprintf(c->keylabel, sizeof c->keylabel, "%s", label);
}
}
if (fresh) { /* the prompt's own choice, checked before anything was made (rmt_fresh_choice) */
if (c->fm[0]) {
(void)snprintf(c->model, sizeof c->model, "%s", c->fm);
}
if (c->ft[0]) {
(void)snprintf(c->thinking, sizeof c->thinking, "%s", c->ft);
}
if (c->fk[0]) {
(void)snprintf(c->keylabel, sizeof c->keylabel, "%s", c->fk);
}
}
if (c->model[0] && c->thinking[0]) { /* a level the model thinks at: one carried from another model may not be */
pic_model m;
char err[PIC_ERR_CAP];
if (pic_model_resolve(c->model, &m, err, sizeof err) == 0) {
const char *at = pic_model_thinking_clamp(&m, c->thinking);
if (at && strcmp(at, c->thinking) != 0) {
(void)snprintf(c->thinking, sizeof c->thinking, "%s", at);
}
}
}
if (images) {
const char *tmp = getenv("TMPDIR");
char path[PATH_MAX];
size_t n = strlen(images), at = 0;
(void)snprintf(path, sizeof path, "%s/pic-rc-images.XXXXXX", tmp && *tmp ? tmp : "/tmp");
if ((c->imgfd = mkstemp(path)) >= 0) {
(void)unlink(path);
while (at < n) {
ssize_t w = write(c->imgfd, images + at, n - at);
if (w < 0 && errno == EINTR) {
continue;
}
if (w <= 0) {
break;
}
at += (size_t)w;
}
if (at < n || lseek(c->imgfd, 0, SEEK_SET) != 0) {
close(c->imgfd);
c->imgfd = -1;
} else {
(void)fcntl(c->imgfd, F_SETFD, FD_CLOEXEC);
}
}
if (c->imgfd < 0) {
rmt_out_error(jb, c->e.key, "failed", "cannot keep the images for the request");
return;
}
}
{ /* a skill or a template, expanded as pic ask does, so the journal keeps what the model got */
char why[PIC_ERR_CAP], *expanded = NULL;
if (rmt_expand(j->workspace, text, &expanded, why, sizeof why) != 0) {
char *line = rmt_pi_response(c->e.payload, "prompt", 0, NULL, why);
rmt_out_response(jb, c->e.key, line);
free(line);
return;
}
c->text = expanded;
}
if (!c->text && !(c->text = strdup(text))) {
rmt_out_error(jb, c->e.key, "failed", "out of memory");
return;
}
if (conv != c->conv) { /* a known conversation passes its own buffer: snprintf cannot copy onto itself */
(void)snprintf(c->conv, sizeof c->conv, "%s", conv);
}
c->fresh = fresh;
c->start = 1;
}
/* prompt: a keyed admission and a detached run while nothing runs, the inbox with
* streamingBehavior while a request does, Pi's error without it. */
static void rmt_prompt(rmt_job *jb, rmt_journal *j, rmt_cmdjob *c) {
rmt_env *e = &c->e;
char *text = rmt_q("SELECT CASE json_type(?1, '$.message') WHEN 'text' THEN json_extract(?1, '$.message') END", 1, e->payload);
char *behavior = rmt_q("SELECT json_extract(?1, '$.streamingBehavior')", 1, e->payload);
char *images = NULL, why[256], conv[64], *full = NULL;
int imgs = rmt_prompt_images(e->payload, &images, why, sizeof why);
(void)snprintf(c->row, sizeof c->row, "rc:%s:%s", jb->idb, e->key);
if (imgs >= 0 && text && (*text || imgs) && (full = rmt_prompt_files(j, e->payload, text, why, sizeof why))) {
free(text);
text = full;
}
if (imgs < 0) {
rmt_out_error(jb, e->key, "bad_command", why);
} else if (!text || (!*text && !imgs)) {
rmt_out_error(jb, e->key, "bad_command", "a prompt needs its message");
} else if (!full) {
rmt_out_error(jb, e->key, "bad_command", why);
} else if (rmt_admitted(&j->s, c->row, conv)) { /* a second admission with the key reports the first */
rmt_out(jb, rmt_prompt_ok(j->path, e->key, conv));
} else if (c->known) {
/* starting already */
} else if (!rmt_running(&j->s, c->conv)) {
rmt_start(jb, j, c, c->conv, text, images, 0);
} else if (behavior && (strcmp(behavior, "steer") == 0 || strcmp(behavior, "followUp") == 0)) {
char *line = rmt_q("SELECT json_patch(json_object('type', ?1, 'message', ?2), json_object('images', json(?3)))", 3,
strcmp(behavior, "steer") == 0 ? "steer" : "follow_up", text, images);
if (line) {
rmt_inbox(jb, j, c, line);
}
free(line);
} else {
char *line = rmt_pi_response(e->payload, "prompt", 0, NULL,
"Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.");
rmt_out_response(jb, e->key, line);
free(line);
}
free(text);
free(behavior);
free(images);
}
/* +W: a prompt that starts a new conversation in W, under a fresh id. */
static void rmt_fresh(rmt_job *jb, rmt_journal *j, rmt_cmdjob *c) {
rmt_env *e = &c->e;
const char *t = e->ptype;
char *text = strcmp(t, "prompt") == 0
? rmt_q("SELECT CASE json_type(?1, '$.message') WHEN 'text' THEN json_extract(?1, '$.message') END", 1, e->payload)
: NULL;
char why[256], conv[64], *images = NULL, *full = NULL;
int imgs = strcmp(t, "prompt") == 0 ? rmt_prompt_images(e->payload, &images, why, sizeof why) : 0;
(void)snprintf(c->row, sizeof c->row, "rc:%s:%s", jb->idb, e->key);
if (imgs >= 0 && text && (*text || imgs) && (full = rmt_prompt_files(j, e->payload, text, why, sizeof why))) {
free(text);
text = full;
}
if (strcmp(t, "prompt") != 0) {
rmt_out_error(jb, e->key, "bad_command", "a new conversation starts with a prompt");
} else if (imgs < 0) {
rmt_out_error(jb, e->key, "bad_command", why);
} else if (!text || (!*text && !imgs)) {
rmt_out_error(jb, e->key, "bad_command", "a prompt needs its message");
} else if (!full) {
rmt_out_error(jb, e->key, "bad_command", why);
} else if (rmt_admitted(&j->s, c->row, conv)) {
rmt_out(jb, rmt_prompt_ok(j->path, e->key, conv));
} else if (!c->known) {
unsigned char r[4];
char id[16] = "";
for (int tries = 0; tries < 8 && !id[0]; tries++) { /* a fresh id, as the journal makes them */
if (pic_platform_get()->entropy(r, sizeof r) != 0) {
break;
}
rmt_hex(r, sizeof r, id);
if (rmt_conv_is(&j->s, id)) {
id[0] = '\0';
}
}
if (id[0]) {
rmt_start(jb, j, c, id, text, images, 1);
} else {
rmt_out_error(jb, e->key, "failed", "no id for a new conversation");
}
}
free(text);
free(images);
}
/* compact: pic compact --now in a child of its own, with the conversation's next model; the
* response when it ends. A request running refuses it, where Pi's compact would stop the request. */
static void rmt_compact(rmt_job *jb, rmt_journal *j, rmt_cmdjob *c) {
rmt_env *e = &c->e;
if (rmt_running(&j->s, c->conv)) {
char *line = rmt_pi_response(e->payload, "compact", 0, NULL, "A request is running. Stop it, or compact when it ends.");
rmt_out_response(jb, e->key, line);
free(line);
return;
}
rmt_next_model(&j->s, c->conv, 0, rmt_cmd_choice(c), c->model, sizeof c->model, c->thinking, sizeof c->thinking);
c->focus = rmt_q("SELECT CASE json_type(?1, '$.customInstructions') WHEN 'text' THEN json_extract(?1, '$.customInstructions')"
" END", 1, e->payload);
(void)snprintf(c->row, sizeof c->row, "rc:%s:%s", jb->idb, e->key);
c->start = 2;
}
/* Whether SQL (one ?1, the payload) answers 1. */
static int rmt_q_bool(const char *sql, const char *payload) {
char *v = rmt_q(sql, 1, payload);
int yes = v && strcmp(v, "1") == 0;
free(v);
return yes;
}
/* One provider for rmt_missing: one that needs a key and has none pic remote can reach (none
* stored, its variable unset here), with the commands at the computer that give it one. */
static int rmt_missing_one(void *ctx, const char *provider) {
sqlite3_str *o = ctx;
char name[160], err[256];
pic_model m;
(void)snprintf(name, sizeof name, "%s/x", provider);
if (pic_model_available(provider) || pic_model_resolve(name, &m, err, sizeof err) != 0 || strcmp(m.provider, provider) != 0 ||
!m.key_env[0]) {
return 0;
}
{
/* never a copy of the variable's value: a key kept in a secret manager is stored as the
* command that prints it, run at each request; or a key is typed in */
char *one = rmt_q("SELECT json_object('provider', ?1, 'env', ?2, 'fix', json_array("
"'pic auth login ' || ?1 || ' --command ' || char(39) || 'COMMAND THAT PRINTS THE KEY' || char(39),"
" 'pic auth login ' || ?1 || ' --api-key'))",
2, provider, m.key_env);
if (one) {
sqlite3_str_appendf(o, "%s%s", sqlite3_str_length(o) > 1 ? "," : "", one);
}
free(one);
}
return 0;
}
/* LINE, a Pi response, with data.missing: the providers pic remote has no key for, so a phone can
* say why one is not offered (a key only in a terminal's environment never reaches a pic remote
* the system started) and what fixes it. LINE itself when it failed. */
static char *rmt_missing(char *line) {
sqlite3_str *o = sqlite3_str_new(NULL);
char *list, *out = NULL;
sqlite3_str_appendchar(o, 1, '[');
(void)pic_providers_each(rmt_missing_one, o);
sqlite3_str_appendchar(o, 1, ']');
list = sqlite3_str_finish(o);
if (list) {
out = rmt_q("SELECT json_set(?1, '$.data.missing', json(?2)) WHERE json_extract(?1, '$.success') = 1 AND"
" json_type(?1, '$.data') = 'object'",
2, line, list);
}
sqlite3_free(list);
if (!out) {
return line;
}
free(line);
return out;
}
/* Answers that need no row: the conversation's stats, the levels and models a phone can pick. */
static void rmt_ask(rmt_job *jb, rmt_journal *j, rmt_cmdjob *c) {
rmt_env *e = &c->e;
char model[256], thinking[32], *line = NULL;
const char *t = e->ptype;
rmt_next_model(&j->s, c->conv, 0, rmt_cmd_choice(c), model, sizeof model, thinking, sizeof thinking);
if (strcmp(t, "get_session_stats") == 0) {
char *data = rmt_entries_ok(&j->s) ? pic_rpc_session_stats_recent(&j->s, c->conv, model, RMT_PATH_MOST) : NULL;
line = rmt_pi_response(e->payload, t, data != NULL, data, data ? NULL : j->s.err);
free(data);
} else if (strcmp(t, "get_available_thinking_levels") == 0) {
char levels[192], data[224];
(void)pic_rpc_levels(model, levels, sizeof levels);
(void)snprintf(data, sizeof data, "{\"levels\":%s}", levels);
line = rmt_pi_response(e->payload, t, 1, data, NULL);
} else if (c->o->ask) { /* get_available_models: a component's */
line = c->o->ask(j->workspace, model, e->payload);
if (line && (strcmp(t, "get_available_models") == 0 || strcmp(t, "get_credentials") == 0)) {
line = rmt_missing(line);
}
}
if (line) {
rmt_out_response(jb, e->key, line);
} else {
rmt_out_error(jb, e->key, "failed", "no answer");
}
free(line);
}
/* The model and level a new conversation in J's workspace starts on, as rmt_start gives them: the
* workspace's last request's, else the model pic would start on. On the lane, under rmt_user_mu. */
static void rmt_fresh_model(rmt_journal *j, const rmt_cmdjob *c, char *model, size_t mcap, char *thinking, size_t tcap) {
model[0] = thinking[0] = '\0';
if (j->sopen) {
rmt_next_model(&j->s, "", 1, NULL, model, mcap, thinking, tcap);
}
if (!model[0] && c->o->initial_model) {
c->o->initial_model(model, mcap);
}
}
/* Whether T is a question a phone may ask of +W or +F, before the conversation is made. */
static int rmt_fresh_asked(const char *t) {
return strcmp(t, "get_available_models") == 0 || strcmp(t, "get_available_thinking_levels") == 0 ||
strcmp(t, "get_credentials") == 0 || strcmp(t, "check_credentials") == 0 || strcmp(t, "get_profiles") == 0;
}
/* get_available_models and the rest for +W or +F: answered for the model a new conversation there
* starts on, without making anything; get_available_models's data also says which, as model (Pi's
* model object, or null) and thinkingLevel (or null: pic's default). */
static void rmt_fresh_ask(rmt_job *jb, rmt_journal *j, rmt_cmdjob *c) {
rmt_env *e = &c->e;
const char *t = e->ptype;
char model[256], thinking[32], *line = NULL;
rmt_fresh_model(j, c, model, sizeof model, thinking, sizeof thinking);
if (strcmp(t, "get_available_thinking_levels") == 0) {
char levels[192], data[224];
(void)pic_rpc_levels(model, levels, sizeof levels);
(void)snprintf(data, sizeof data, "{\"levels\":%s}", levels);
line = rmt_pi_response(e->payload, t, 1, data, NULL);
} else if (c->o->ask) {
line = c->o->ask(j->workspace, model, e->payload);
if (line && strcmp(t, "get_available_models") == 0) {
char *obj = model[0] ? pic_rpc_model_json(model, NULL) : NULL;
char *with = rmt_q("SELECT json_set(?1, '$.data.model', json(coalesce(?2, 'null')), '$.data.thinkingLevel', ?3)"
" WHERE json_extract(?1, '$.success') = 1 AND json_type(?1, '$.data') = 'object'",
3, line, obj, thinking[0] ? thinking : NULL);
free(obj);
if (with) {
free(line);
line = with;
}
}
if (line && (strcmp(t, "get_available_models") == 0 || strcmp(t, "get_credentials") == 0)) {
line = rmt_missing(line);
}
}
if (line) {
rmt_out_response(jb, e->key, line);
} else {
rmt_out_error(jb, e->key, "failed", "no answer");
}
free(line);
}
/* A prompt to +W or +F may carry its first request's choice: provider and modelId (one of the
* workspace's get_available_models), thinkingLevel, and credential (a key of that model's provider,
* by label). 0: kept in C (fm, ft, fk) for rmt_start; -1: refused, answered, and nothing made. A
* prompt already admitted or starting under its key is not checked again: its repeat reports it. */
static int rmt_fresh_choice(rmt_job *jb, rmt_journal *j, rmt_cmdjob *c) {
rmt_env *e = &c->e;
char *name = NULL, *level = NULL, *label = NULL, *line = NULL, conv[64], msg[400];
int rc = -1, has_model, has_level, has_label;
(void)snprintf(c->row, sizeof c->row, "rc:%s:%s", jb->idb, e->key);
if (c->known || (j->sopen && rmt_admitted(&j->s, c->row, conv))) {
return 0;
}
has_model = rmt_q_bool("SELECT json_type(?1, '$.provider') IS NOT NULL OR json_type(?1, '$.modelId') IS NOT NULL", e->payload);
has_level = rmt_q_bool("SELECT json_type(?1, '$.thinkingLevel') IS NOT NULL", e->payload);
has_label = rmt_q_bool("SELECT json_type(?1, '$.credential') IS NOT NULL", e->payload);
if (has_model) {
name = rmt_q("SELECT CASE WHEN json_type(?1, '$.provider') = 'text' AND json_type(?1, '$.modelId') = 'text' THEN"
" json_extract(?1, '$.provider') || '/' || json_extract(?1, '$.modelId') END",
1, e->payload);
}
if (has_level) {
level = rmt_q("SELECT CASE json_type(?1, '$.thinkingLevel') WHEN 'text' THEN json_extract(?1, '$.thinkingLevel') END", 1,
e->payload);
}
if (has_label) {
label = rmt_q("SELECT CASE json_type(?1, '$.credential') WHEN 'text' THEN json_extract(?1, '$.credential') END", 1, e->payload);
}
if (has_model && !name) {
rmt_out_error(jb, e->key, "bad_command", "provider and modelId must be strings");
goto done;
}
if (has_label && !label) {
rmt_out_error(jb, e->key, "bad_command", "credential is a key's label");
goto done;
}
if (has_label && !has_model) {
rmt_out_error(jb, e->key, "bad_command", "a credential is chosen with its model: send provider and modelId with it");
goto done;
}
if (name) { /* one of the available models, as set_model requires */
char *all = c->o->ask ? c->o->ask(j->workspace, name, "{\"type\":\"get_available_models\"}") : NULL;
/* provider and id compared apart: an id may hold a '/', a provider never does */
char *obj = all ? rmt_q("SELECT value FROM json_each(?1, '$.data.models') WHERE json_extract(value, '$.provider') ="
" json_extract(?2, '$.provider') AND json_extract(value, '$.id') = json_extract(?2, '$.modelId')",
2, all, e->payload)
: c->o->ask || strchr(name, '/') != strrchr(name, '/') ? NULL : pic_rpc_model_json(name, NULL);
free(all);
if (!obj || strlen(name) >= sizeof c->fm) {
free(obj);
(void)snprintf(msg, sizeof msg, "Model not found: %.290s", name);
line = rmt_pi_response(e->payload, "prompt", 0, NULL, msg);
goto done;
}
free(obj);
}
if (has_level && (!level || pic_thinking_index(level) < 0)) {
(void)snprintf(msg, sizeof msg, "Invalid thinking level: %.40s (off, minimal, low, medium, high, xhigh, max)",
level ? level : "(not a string)");
line = rmt_pi_response(e->payload, "prompt", 0, NULL, msg);
goto done;
}
if (level) { /* one the model thinks at, else its run would refuse it after the conversation was made */
char model[256], dflt[32];
const char *levels[PIC_THINKING_LEVELS];
pic_model m;
int n, ok = 0;
if (name) {
(void)snprintf(model, sizeof model, "%s", name);
} else {
rmt_fresh_model(j, c, model, sizeof model, dflt, sizeof dflt);
}
if (model[0] && pic_model_resolve(model, &m, msg, sizeof msg) == 0) {
size_t used = 0;
n = pic_model_thinking_levels(&m, levels);
for (int i = 0; i < n; i++) {
ok |= strcmp(levels[i], level) == 0;
}
if (!ok) {
used = (size_t)snprintf(msg, sizeof msg, "thinking level %.32s is not supported by %.200s (supported: ", level, model);
for (int i = 0; i < n && used < sizeof msg; i++) {
used += (size_t)snprintf(msg + used, sizeof msg - used, "%s%s", i ? ", " : "", levels[i]);
}
if (used < sizeof msg) {
(void)snprintf(msg + used, sizeof msg - used, ")");
}
line = rmt_pi_response(e->payload, "prompt", 0, NULL, msg);
goto done;
}
}
}
if (label) {
pic_model m;
char err[PIC_ERR_CAP];
if (strlen(label) >= sizeof c->fk || pic_model_resolve(name, &m, err, sizeof err) != 0 ||
!pic_cred_has(m.provider, label, m.key_env, m.key_literal)) {
char *prov = rmt_q("SELECT json_extract(?1, '$.provider')", 1, e->payload);
(void)snprintf(msg, sizeof msg, "%.64s has no key named \"%.40s\"", prov ? prov : "", label);
free(prov);
line = rmt_pi_response(e->payload, "prompt", 0, NULL, msg);
goto done;
}
}
(void)snprintf(c->fm, sizeof c->fm, "%s", name ? name : "");
(void)snprintf(c->ft, sizeof c->ft, "%s", level ? level : "");
(void)snprintf(c->fk, sizeof c->fk, "%s", label ? label : "");
rc = 0;
done:
if (line) {
rmt_out_response(jb, e->key, line);
}
free(line);
free(name);
free(level);
free(label);
return rc;
}
/* set_model, set_credential and set_thinking_level: the conversation's next request runs on the
* choice, which the loop applies (in the lane's order, so a level and a model set one after the
* other stand in that order); and set_session_name, the conversation's name, written to the
* journal as pic --mode rpc does. */
static void rmt_set(rmt_job *jb, rmt_journal *j, rmt_cmdjob *c) {
rmt_env *e = &c->e;
const char *t = e->ptype;
char *line = NULL;
if (strcmp(t, "set_model") == 0) {
char *name = rmt_q("SELECT CASE WHEN json_type(?1, '$.provider') = 'text' AND json_type(?1, '$.modelId') = 'text' THEN"
" json_extract(?1, '$.provider') || '/' || json_extract(?1, '$.modelId') END",
1, e->payload);
char *profile = rmt_q("SELECT CASE json_type(?1, '$.profile') WHEN 'text' THEN json_extract(?1, '$.profile') END", 1, e->payload);
char pmodel[200] = "", pkey[PIC_CRED_LABEL_CAP] = "", plevel[16] = "";
char *obj = NULL;
if (profile && pic_profile_get(profile, pmodel, sizeof pmodel, pkey, sizeof pkey, plevel, sizeof plevel)) {
free(name); /* pic's: a profile's model, key and level */
name = strdup(pmodel);
}
free(profile);
if (name && c->o->ask) { /* one of the available models, as Pi's set_model requires */
char *all = c->o->ask(j->workspace, name, "{\"type\":\"get_available_models\"}");
obj = all ? rmt_q("SELECT value FROM json_each(?1, '$.data.models') WHERE json_extract(value, '$.provider') || '/' ||"
" json_extract(value, '$.id') = ?2",
2, all, name)
: NULL;
free(all);
} else if (name) {
obj = pic_rpc_model_json(name, NULL);
}
if (!name) {
line = rmt_pi_response(e->payload, t, 0, NULL, "provider and modelId must be strings");
} else if (!obj || strlen(name) >= sizeof c->set.model) {
char msg[320];
(void)snprintf(msg, sizeof msg, "Model not found: %.290s", name);
line = rmt_pi_response(e->payload, t, 0, NULL, msg);
} else {
(void)snprintf(c->set.model, sizeof c->set.model, "%s", name);
(void)snprintf(c->set.key, sizeof c->set.key, "%s", pkey); /* a model alone: its provider's key, by its rules */
c->setm = c->setk = 1;
if (plevel[0]) {
(void)snprintf(c->set.thinking, sizeof c->set.thinking, "%s", plevel);
c->sett = 1;
}
line = rmt_pi_response(e->payload, t, 1, obj, NULL);
}
free(obj);
free(name);
} else if (strcmp(t, "set_credential") == 0) {
/* the key this conversation's next requests use; persist: the provider's saved key, as pic auth use */
char *provider = rmt_q("SELECT CASE json_type(?1, '$.provider') WHEN 'text' THEN json_extract(?1, '$.provider') END", 1, e->payload);
char *label = rmt_q("SELECT CASE json_type(?1, '$.label') WHEN 'text' THEN json_extract(?1, '$.label') END", 1, e->payload);
char probe[128], err[PIC_ERR_CAP], model[256], thinking[32];
pic_model m;
(void)snprintf(probe, sizeof probe, "%s/x", provider ? provider : "");
rmt_next_model(&j->s, c->conv, 0, rmt_cmd_choice(c), model, sizeof model, thinking, sizeof thinking);
if (!provider || !label || pic_model_resolve(probe, &m, err, sizeof err) != 0 || strcmp(m.provider, provider) != 0) {
line = rmt_pi_response(e->payload, t, 0, NULL, "set_credential needs a provider pic knows and a label");
} else if (!pic_cred_has(provider, label, m.key_env, m.key_literal)) {
(void)snprintf(err, sizeof err, "%.64s has no key named \"%.40s\"", provider, label);
line = rmt_pi_response(e->payload, t, 0, NULL, err);
} else if (rmt_q_bool("SELECT json_extract(?1, '$.persist')", e->payload) && c->o->ask) {
/* the saved key is written to the user database, which the journal's commit hook does not
* see: claim the job first, so a phone told busy finds nothing saved */
line = rmt_job_claim() == 0 ? c->o->ask(j->workspace, model, e->payload)
: rmt_pi_response(e->payload, t, 0, NULL, RMT_BUSY_TEXT);
} else {
char data[200];
if (strncmp(model, provider, strlen(provider)) == 0 && model[strlen(provider)] == '/') {
(void)snprintf(c->cand, sizeof c->cand, "%s", model);
}
(void)snprintf(c->set.key, sizeof c->set.key, "%s", label);
c->setk = 1;
(void)snprintf(data, sizeof data, "{\"provider\":\"%s\",\"label\":\"%s\",\"persist\":false}", provider, label);
line = rmt_pi_response(e->payload, t, 1, data, NULL);
}
free(provider);
free(label);
} else if (strcmp(t, "set_thinking_level") == 0) {
char *level = rmt_q("SELECT CASE json_type(?1, '$.level') WHEN 'text' THEN json_extract(?1, '$.level') END", 1, e->payload);
if (!level || pic_thinking_index(level) < 0) {
char msg[160];
(void)snprintf(msg, sizeof msg, "Invalid thinking level: %.40s (off, minimal, low, medium, high, xhigh, max)",
level ? level : "(not a string)");
line = rmt_pi_response(e->payload, t, 0, NULL, msg);
} else {
(void)snprintf(c->set.thinking, sizeof c->set.thinking, "%s", level);
c->sett = 1;
line = rmt_pi_response(e->payload, t, 1, NULL, NULL);
}
free(level);
} else { /* set_session_name */
pic_store *s = &j->s;
char *name = rmt_q("SELECT CASE json_type(?1, '$.name') WHEN 'text' THEN trim(json_extract(?1, '$.name'), ' ' ||"
" char(9, 10, 13)) END",
1, e->payload);
if (!name || !*name) {
line = rmt_pi_response(e->payload, t, 0, NULL, "Session name cannot be empty");
} else if (pic_session_name(s, c->conv, name) != 0) {
line = rmt_pi_response(e->payload, t, 0, NULL, s->err);
} else {
line = rmt_pi_response(e->payload, t, 1, NULL, NULL);
}
free(name);
}
rmt_out_response(jb, e->key, line);
free(line);
}
/* A conversation's loops (wake.h), pic's own commands: get_wakes lists them; pause_wake,
* resume_wake and stop_wake act on one of the conversation's by id; pause_wakes on all. Each
* action is committed before the answer, and a repeat answers the same. */
static void rmt_wake(rmt_job *jb, rmt_journal *j, rmt_cmdjob *c) {
pic_store *s = &j->s;
rmt_env *e = &c->e;
const char *t = e->ptype, *conv = c->conv;
char *id = rmt_q("SELECT CASE json_type(?1, '$.id') WHEN 'text' THEN json_extract(?1, '$.id') END", 1, e->payload);
char *list = NULL, *data = NULL, *line, why[PIC_ERR_CAP] = "", by[48];
long long wid = 0;
int count = 0;
(void)snprintf(by, sizeof by, "remote:%s", jb->idb);
if (strcmp(t, "pause_wakes") == 0) {
if (pic_wake_pause_all(s, conv, "paused from a phone", &count) != 0) {
(void)snprintf(why, sizeof why, "%s", s->err);
}
} else if (strcmp(t, "get_wakes") != 0) {
char owner[64] = "";
if (!id) {
(void)snprintf(why, sizeof why, "id is required (L1)");
} else if (pic_wake_resolve(s, id, &wid) != 0) {
(void)snprintf(why, sizeof why, "%s", s->err);
} else {
sqlite3_stmt *q = NULL;
if (sqlite3_prepare_v2(s->db, "SELECT session_id FROM pic_wake WHERE id = ?", -1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_int64(q, 1, wid);
if (sqlite3_step(q) == SQLITE_ROW) {
(void)snprintf(owner, sizeof owner, "%s", (const char *)sqlite3_column_text(q, 0));
}
}
sqlite3_finalize(q);
if (strcmp(owner, conv) != 0) {
(void)snprintf(why, sizeof why, "no loop %s in this conversation", id);
} else if ((strcmp(t, "approve_wake") == 0 || strcmp(t, "decline_wake") == 0
? pic_wake_answer(s, wid, t[0] == 'a', by) % 2 /* decided so already (2) is done too */
: pic_wake_set(s, wid, strcmp(t, "pause_wake") == 0 ? "pause" : strcmp(t, "resume_wake") == 0 ? "resume" : "stop",
strcmp(t, "pause_wake") == 0 ? "paused from a phone" : NULL)) != 0) {
(void)snprintf(why, sizeof why, "%s", s->err);
}
}
}
if (!why[0] && !(list = pic_wake_list(s, conv, 0))) {
(void)snprintf(why, sizeof why, "%s", s->err);
}
if (why[0] && rmt_busy(s)) {
(void)snprintf(why, sizeof why, "%s", RMT_BUSY_TEXT);
}
if (!why[0]) {
char n[16], now[32];
(void)snprintf(n, sizeof n, "%d", count);
(void)snprintf(now, sizeof now, "%lld", pic_wake_now_ms());
data = rmt_q("SELECT json_patch(json_object('wakes', json(?1), 'nowMs', CAST(?4 AS INTEGER)), json_object('paused',"
" CASE WHEN ?2 = 'pause_wakes' THEN CAST(?3 AS INTEGER) END))",
4, list, t, n, now);
}
line = rmt_pi_response(e->payload, t, !why[0], data, why[0] ? why : NULL);
rmt_out_response(jb, e->key, line);
free(line);
free(data);
free(list);
free(id);
}
/* set_permission_mode (pic's own) {mode}: the conversation's permission mode (perm.h), committed
* before the answer, whose data is {permissionMode, allowed}. */
static void rmt_perm(rmt_job *jb, rmt_journal *j, rmt_cmdjob *c) {
pic_store *s = &j->s;
rmt_env *e = &c->e;
char *mode = rmt_q("SELECT CASE json_type(?1, '$.mode') WHEN 'text' THEN json_extract(?1, '$.mode') END", 1, e->payload);
char *data = NULL, *line, why[PIC_ERR_CAP] = "";
int rc;
(void)snprintf(c->row, sizeof c->row, "rc:%s:%s", jb->idb, e->key);
rc = pic_perm_set_keyed(s, c->conv, mode ? mode : "", c->row, &data); /* a resend gets the first answer */
if (rc != 0) {
(void)snprintf(why, sizeof why, "%s", rc < 0 && rmt_busy(s) ? RMT_BUSY_TEXT : s->err);
}
line = rmt_pi_response(e->payload, e->ptype, rc == 0, data, rc == 0 ? NULL : why);
rmt_out_response(jb, e->key, line);
free(line);
free(data);
free(mode);
}
/* delete_session and restore_session (pic's own): the conversation deleted, or brought back, as pic
* sessions delete and restore do; the list the phone gets next leaves it out, or has it again. */
static void rmt_trash(rmt_job *jb, rmt_journal *j, rmt_cmdjob *c) {
pic_store *s = &j->s;
rmt_env *e = &c->e;
char id[64], title[160], *line;
int rc = strcmp(e->ptype, "delete_session") == 0 ? pic_trash_delete(s, c->conv, id, sizeof id, title, sizeof title)
: pic_trash_restore(s, c->conv, id, sizeof id, title, sizeof title);
line = rmt_pi_response(e->payload, e->ptype, rc == 0, NULL, rc == 0 ? NULL : s->err);
rmt_out_response(jb, e->key, line);
free(line);
}
/* purge_session (pic's own): a deleted conversation emptied for good now, as pic sessions empty-trash
* does for each; one not deleted is refused, as is one running or held. */
static void rmt_purge(rmt_job *jb, rmt_journal *j, rmt_cmdjob *c) {
rmt_env *e = &c->e;
sqlite3_stmt *q = NULL;
long long count = 0;
int deleted = 0;
char *line;
if (sqlite3_prepare_v2(j->s.db, "SELECT 1 FROM pic_trash WHERE session_id = ?1 AND purged_ms IS NULL", -1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, c->conv, -1, SQLITE_STATIC);
deleted = sqlite3_step(q) == SQLITE_ROW;
}
sqlite3_finalize(q);
if (!deleted) {
line = rmt_pi_response(e->payload, e->ptype, 0, NULL, "Delete it first");
} else if (pic_trash_purge_one(&j->s, c->conv, &count) != 0) {
rmt_out_error(jb, e->key, rmt_busy(&j->s) ? "busy" : "failed", rmt_busy(&j->s) ? RMT_BUSY_TEXT : j->s.err);
return;
} else if (count == 0) {
line = rmt_pi_response(e->payload, e->ptype, 0, NULL, "It is running or open in a pic. Stop it, then purge it.");
} else {
line = rmt_pi_response(e->payload, e->ptype, 1, NULL, NULL);
}
rmt_out_response(jb, e->key, line);
free(line);
}
/* archive_session and unarchive_session (pic's own): the conversation out of the lists until it is
* unarchived, or by its next request; data {session, archived, archivedMs}. A repeat answers the
* same. */
static void rmt_archive(rmt_job *jb, rmt_journal *j, rmt_cmdjob *c) {
rmt_env *e = &c->e;
char id[64], title[160], *line, *data = NULL, ms[32];
long long when = 0;
int on = strcmp(e->ptype, "archive_session") == 0;
if (pic_archive_set(&j->s, c->conv, on, id, sizeof id, title, sizeof title, &when) != 0) {
rmt_out_error(jb, e->key, rmt_busy(&j->s) ? "busy" : "failed", rmt_busy(&j->s) ? RMT_BUSY_TEXT : j->s.err);
return;
}
(void)snprintf(ms, sizeof ms, "%lld", when);
data = rmt_q("SELECT json_object('session', ?1 || '/' || ?2, 'archived', json(iif(?3 != '0', 'true', 'false')), 'archivedMs',"
" CASE WHEN ?3 != '0' THEN CAST(?3 AS INTEGER) END)",
3, j->path, id, ms);
line = data ? rmt_pi_response_keep(e->payload, e->ptype, data) : rmt_pi_response(e->payload, e->ptype, 0, NULL, "out of memory");
rmt_out_response(jb, e->key, line);
free(line);
free(data);
}
/* The command answer {id, value}, sent under the key ask-ID: the ask of the conversation answered,
* first writer wins. data {result: answered, already_answered or expired, id, value, by} with the
* answer that stands. A repeat of the key (or of the device's own answer) gets the same result:
* it is read from the row. Not an answer, or over a limit: bad_command. */
static void rmt_answer(rmt_job *jb, rmt_journal *j, rmt_cmdjob *c) {
rmt_env *e = &c->e;
char by[48], owner[64] = "";
char *id = rmt_q("SELECT CASE json_type(?1, '$.id') WHEN 'text' THEN json_extract(?1, '$.id') END", 1, e->payload);
char *value = rmt_q("SELECT ?1 -> '$.value' WHERE json_type(?1, '$.value') IS NOT NULL", 1, e->payload);
char *standing = NULL, *data = NULL, *line;
pic_store *s = &j->s;
int rc;
if (!id || !value || strlen(id) > 64) {
rmt_out_error(jb, e->key, "bad_command", "an answer is {\"type\":\"answer\",\"id\":ID,\"value\":V}");
goto done;
}
{
sqlite3_stmt *q = NULL;
if (sqlite3_prepare_v2(s->db, "SELECT session_id FROM pic_ask WHERE id = ?1", -1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, id, -1, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW) {
(void)snprintf(owner, sizeof owner, "%s", (const char *)sqlite3_column_text(q, 0));
}
}
sqlite3_finalize(q);
}
if (strcmp(owner, c->conv) != 0) { /* no_ask, as the response's error */
line = rmt_pi_response(e->payload, "answer", 0, NULL, "no such question in this conversation");
rmt_out_response(jb, e->key, line);
free(line);
goto done;
}
{
char *len = rmt_q("SELECT iif(json_type(?1) = 'text', length(json_extract(?1, '$')), 0)", 1, value);
int over = len && atoll(len) > PIC_ASK_TEXT_MAX;
free(len);
if (over) {
rmt_out_error(jb, e->key, "bad_command", "an answer has at most 4000 characters");
goto done;
}
}
(void)snprintf(by, sizeof by, "remote:%s", jb->idb);
s->err[0] = '\0';
rc = pic_ask_answer(s, id, value, by, &standing);
j->ask_dv = -1; /* its own write does not change its data_version: the close is told next tick */
if (rc == PIC_ASK_REFUSED) { /* bad_answer, as the response's error */
line = rmt_pi_response(e->payload, "answer", 0, NULL, s->err);
rmt_out_response(jb, e->key, line);
free(line);
goto done;
}
if (rc < 0) {
rmt_out_error(jb, e->key, rmt_busy(s) ? "busy" : "failed", rmt_busy(s) ? RMT_BUSY_TEXT : s->err);
goto done;
}
if (rc == PIC_ASK_ANSWERED) {
standing = rmt_q("SELECT json_object('state', 'answered', 'value', json(?1), 'answeredBy', ?2)", 2, value, by);
}
data = rmt_q("SELECT json_object('result', ?1, " RMT_SETTLED_MEMBERS("json_set(?2, '$.id', ?4)", "?3") ")", 4,
rc == PIC_ASK_ANSWERED ? "answered" : rc == PIC_ASK_EXPIRED ? "expired" : "already_answered", standing ? standing : "{}",
c->names ? c->names : "{}", id);
line = data ? rmt_pi_response_keep(e->payload, "answer", data) : rmt_pi_response(e->payload, "answer", 0, NULL, "out of memory");
rmt_out_response(jb, e->key, line);
free(line);
done:
free(data);
free(standing);
free(id);
free(value);
}
/* The questions answered without a row, through pic's own state (models, keys). */
static int rmt_asked(const char *t) {
return strcmp(t, "get_session_stats") == 0 || strcmp(t, "get_available_thinking_levels") == 0 ||
strcmp(t, "get_available_models") == 0 || strcmp(t, "get_credentials") == 0 || strcmp(t, "check_credentials") == 0 ||
strcmp(t, "get_profiles") == 0;
}
/* J, a folder's journal, made as running pic in the folder makes it (its .pic ignoring itself, and
* named in a fossil or zit checkout's ignore rules), unless it has one, and opened to be served.
* The folder must still be the real path it was offered as. 0, or -1 with the error sent. On J's
* lane. */
static int rmt_folder_open(rmt_job *jb, rmt_journal *j) {
rmt_cmdjob *c = jb->ctx;
char real[PATH_MAX], dir[PATH_MAX], say[1024], why[PIC_ERR_CAP];
struct stat sb;
pic_store m;
if (!realpath(j->workspace, real) || strcmp(real, j->workspace) != 0 || stat(real, &sb) != 0 || !S_ISDIR(sb.st_mode) ||
snprintf(dir, sizeof dir, "%s/.pic", real) >= (int)sizeof dir) {
rmt_out_error(jb, c->e.key, "no_session", "no such workspace");
return -1;
}
if ((mkdir(dir, 0700) != 0 && errno != EEXIST) || lstat(dir, &sb) != 0 || !S_ISDIR(sb.st_mode)) {
(void)snprintf(why, sizeof why, "cannot make %s: %s", dir, errno ? strerror(errno) : "not a folder");
rmt_out_error(jb, c->e.key, "failed", why);
return -1;
}
if (pic_folder_vcs(dir, pic_folder_seal(dir), say, sizeof say)) {
rmt_log(stdout, "pic remote: %s\n", say);
(void)fflush(stdout);
}
if (pic_open(&m, j->path) != 0) {
(void)snprintf(why, sizeof why, "cannot start a journal in %s: %s", real, m.err);
pic_close(&m);
rmt_out_error(jb, c->e.key, "failed", why);
return -1;
}
pic_close(&m);
j->notjournal = 0;
if (rmt_serve_open(j, 0) != 0) {
(void)snprintf(why, sizeof why, "cannot open the journal in %s", real);
rmt_out_error(jb, c->e.key, "failed", why);
return -1;
}
return 0;
}
/* A command's work on its journal's lane. */
static void rmt_cmd_run(rmt_job *jb) {
rmt_cmdjob *c = jb->ctx;
rmt_journal *j = jb->j;
const char *t = c->e.ptype;
if (!c->fresh) {
rmt_choice_copy(c->st, c->jx, c->conv, &c->ch);
}
if (c->fresh && strcmp(t, "prompt") != 0) { /* nothing is made but by a prompt, a folder's journal included */
if (rmt_fresh_asked(t)) {
rmt_fresh_ask(jb, j, c);
} else {
rmt_out_error(jb, c->e.key, "bad_command", "a new conversation starts with a prompt");
}
return;
}
if (c->fresh && strcmp(t, "prompt") == 0 && rmt_fresh_choice(jb, j, c) != 0) {
return; /* refused before anything is made */
}
if (!j->sopen && c->create && rmt_folder_open(jb, j) != 0) {
return; /* said */
}
if (!j->sopen) {
rmt_out_error(jb, c->e.key, "no_session", c->fresh ? "no such workspace" : "no such conversation");
return;
}
if (c->fresh) {
rmt_fresh(jb, j, c);
return;
}
if (!rmt_conv_is(&j->s, c->conv)) {
rmt_out_error(jb, c->e.key, "no_session", "no such conversation");
} else if (strcmp(t, "get_state") == 0 || strcmp(t, "get_messages") == 0) {
rmt_query(jb, j, c);
} else if (strcmp(t, "steer") == 0 || strcmp(t, "follow_up") == 0 || strcmp(t, "abort") == 0) {
rmt_inbox(jb, j, c, c->e.payload);
} else if (strcmp(t, "prompt") == 0) {
rmt_prompt(jb, j, c);
} else if (strcmp(t, "set_model") == 0 || strcmp(t, "set_session_name") == 0 || strcmp(t, "set_credential") == 0 ||
strcmp(t, "set_thinking_level") == 0) {
rmt_set(jb, j, c);
} else if (strcmp(t, "compact") == 0) {
rmt_compact(jb, j, c);
} else if (strcmp(t, "delete_session") == 0 || strcmp(t, "restore_session") == 0) {
rmt_trash(jb, j, c);
} else if (strcmp(t, "archive_session") == 0 || strcmp(t, "unarchive_session") == 0) {
rmt_archive(jb, j, c);
} else if (strcmp(t, "purge_session") == 0) {
rmt_purge(jb, j, c);
} else if (strcmp(t, "answer") == 0) {
rmt_answer(jb, j, c);
} else if (strcmp(t, "set_permission_mode") == 0) {
rmt_perm(jb, j, c);
} else if (rmt_asked(t)) {
rmt_ask(jb, j, c); /* get_credentials and the rest: names, kinds, states and numbers, never a key */
} else {
rmt_wake(jb, j, c);
}
}
/* In a forked child, before exec: SIGINT, SIGTERM and SIGPIPE back to their defaults with sigaction,
* which is async-signal-safe (signal is not), as everything a child calls before exec must be:
* the workers may hold the allocator's or SQLite's locks at the fork. */
static void rmt_child_signals(void) {
struct sigaction dfl;
memset(&dfl, 0, sizeof dfl);
dfl.sa_handler = SIG_DFL;
(void)sigaction(SIGINT, &dfl, NULL);
(void)sigaction(SIGTERM, &dfl, NULL);
(void)sigaction(SIGPIPE, &dfl, NULL);
}
/* The environment for a child that gets the store's key (PIC_KEY_FD=KEYFD): ENV, ENVIRON without
* a PIC_KEY_FD of its own; KEYENV holds the new one. Everything the child needs is made before
* the fork: another thread may hold the allocator's lock at that moment. */
static char **rmt_child_env(int keyfd, char *keyenv, size_t cap) {
size_t ne = 0, k = 0;
char **env;
while (environ[ne]) {
ne++;
}
if (!(env = calloc(ne + 2, sizeof *env))) {
return NULL;
}
for (size_t i = 0; i < ne; i++) {
if (strncmp(environ[i], "PIC_KEY_FD=", 11) != 0) {
env[k++] = environ[i];
}
}
if (keyfd >= 0) {
(void)snprintf(keyenv, cap, "PIC_KEY_FD=%d", keyfd);
env[k++] = keyenv;
}
env[k] = NULL;
return env;
}
/* prompt with nothing running, on the loop: what pic submit KEY TEXT --session ID does, then pic
* run --session ID, in one detached child in a session of its own, so it outlives pic remote. The
* submit runs in a grandchild whose stderr comes back here; the run gets the master key over the
* handoff pipe and no pipe to this process. C holds the model, level, key and images its job
* found. */
static void rmt_prompt_start(rmt_state *st, rmt_dev *d, int jx, rmt_cmdjob *c) {
rmt_journal *j = st->js[jx];
const char *sub[20], *run[16], *key = c->e.key;
char keyenv[32];
char **env;
int errp[2], keyfd, null;
pid_t pid;
rmt_cmd *cmd;
{
int a = 0, b = 0;
const char *const head[] = {st->o->self, "--db", j->path, "--workspace", j->workspace};
for (int i = 0; i < 5; i++) {
sub[a++] = run[b++] = head[i];
}
if (c->model[0]) {
sub[a++] = run[b++] = "--model";
sub[a++] = run[b++] = c->model;
}
if (c->thinking[0]) {
sub[a++] = run[b++] = "--thinking";
sub[a++] = run[b++] = c->thinking;
}
if (c->keylabel[0]) {
run[b++] = "--key";
run[b++] = c->keylabel;
}
sub[a++] = "submit";
sub[a++] = c->row;
sub[a++] = c->text;
sub[a++] = c->fresh ? "--new-session" : "--session";
sub[a++] = c->conv;
if (c->imgfd >= 0) { /* on the submit's stdin */
sub[a++] = "--images";
sub[a++] = "-";
}
sub[a] = NULL;
run[b++] = "run";
run[b++] = "--session";
run[b++] = c->conv;
run[b] = NULL;
}
if (pipe(errp) != 0) {
rmt_error(st, d, key, "failed", strerror(errno));
return;
}
if ((null = open("/dev/null", O_RDWR)) < 0) {
close(errp[0]);
close(errp[1]);
rmt_error(st, d, key, "failed", strerror(errno));
return;
}
keyfd = pic_cred_handoff();
if (!(env = rmt_child_env(keyfd, keyenv, sizeof keyenv))) {
close(null);
close(errp[0]);
close(errp[1]);
if (keyfd >= 0) {
close(keyfd);
}
rmt_error(st, d, key, "failed", "out of memory");
return;
}
pid = fork();
if (pid == 0) {
int status = 0, imgfd = c->imgfd;
pid_t g;
if (st->lockfd >= 0) { /* the request must not hold pic remote's lock */
close(st->lockfd);
}
(void)setsid();
rmt_child_signals();
(void)dup2(null, STDIN_FILENO);
(void)dup2(null, STDOUT_FILENO);
close(errp[0]);
g = fork();
if (g == 0) { /* the submit: its stderr comes back; no key, which it does not need */
if (keyfd >= 0) {
close(keyfd);
}
(void)dup2(errp[1], STDERR_FILENO);
close(errp[1]);
if (imgfd >= 0) {
(void)dup2(imgfd, STDIN_FILENO);
}
execve(st->o->self, (char *const *)(void *)sub, environ);
_exit(127);
}
while (g > 0 && waitpid(g, &status, 0) < 0 && errno == EINTR) {
}
(void)dup2(null, STDERR_FILENO);
close(errp[1]);
if (g < 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
_exit(1);
}
/* the request runs in a grandchild, not pic remote's child: it outlives this one, which
* pic remote waits for, and is reaped by init when it ends */
if ((g = fork()) == 0) {
if (keyfd >= 0) {
(void)fcntl(keyfd, F_SETFD, 0);
}
execve(st->o->self, (char *const *)(void *)run, env);
_exit(127);
}
_exit(g < 0 ? 1 : 0);
}
free(env);
close(null);
if (keyfd >= 0) {
close(keyfd);
}
close(errp[1]);
if (pid < 0) {
close(errp[0]);
rmt_error(st, d, key, "failed", strerror(errno));
return;
}
(void)fcntl(errp[0], F_SETFD, FD_CLOEXEC);
(void)fcntl(errp[0], F_SETFL, O_NONBLOCK);
cmd = rmt_cmd_add(d, CMD_PROMPT, jx, key, c->row, NULL);
cmd->pid = pid;
cmd->errfd = errp[0];
if (!c->fresh) { /* the request records the choice from here on */
(void)pthread_mutex_lock(&rmt_choice_mu);
rmt_choice_clear(st, jx, c->conv);
(void)pthread_mutex_unlock(&rmt_choice_mu);
}
}
/* compact, on the loop: pic compact --now in a child of its own holding the key, with the model its
* job found; the response when it ends (rmt_commands_poll). */
static void rmt_compact_start(rmt_state *st, rmt_dev *d, int jx, rmt_cmdjob *c) {
rmt_journal *j = st->js[jx];
const char *argv[16];
char keyenv[32], **env;
int n = 0, errp[2], keyfd, null;
pid_t pid;
rmt_cmd *cmd;
argv[n++] = st->o->self;
argv[n++] = "--db";
argv[n++] = j->path;
argv[n++] = "--workspace";
argv[n++] = j->workspace;
if (c->model[0]) {
argv[n++] = "--model";
argv[n++] = c->model;
}
argv[n++] = "compact";
argv[n++] = "--now";
argv[n++] = c->conv;
if (c->focus && *c->focus) {
argv[n++] = c->focus;
}
argv[n] = NULL;
if (pipe(errp) != 0) {
rmt_error(st, d, c->e.key, "failed", strerror(errno));
return;
}
if ((null = open("/dev/null", O_RDWR)) < 0) {
close(errp[0]);
close(errp[1]);
rmt_error(st, d, c->e.key, "failed", strerror(errno));
return;
}
keyfd = pic_cred_handoff();
if (!(env = rmt_child_env(keyfd, keyenv, sizeof keyenv))) {
close(null);
close(errp[0]);
close(errp[1]);
if (keyfd >= 0) {
close(keyfd);
}
rmt_error(st, d, c->e.key, "failed", "out of memory");
return;
}
pid = fork();
if (pid == 0) { /* nothing that allocates: another thread may hold the allocator's lock */
if (st->lockfd >= 0) {
close(st->lockfd);
}
(void)setsid();
rmt_child_signals();
(void)dup2(null, STDIN_FILENO);
(void)dup2(null, STDOUT_FILENO);
(void)dup2(errp[1], STDERR_FILENO);
close(errp[0]);
close(errp[1]);
if (keyfd >= 0) {
(void)fcntl(keyfd, F_SETFD, 0);
}
execve(st->o->self, (char *const *)(void *)argv, env);
_exit(127);
}
free(env);
close(null);
if (keyfd >= 0) {
close(keyfd);
}
close(errp[1]);
if (pid < 0) {
close(errp[0]);
rmt_error(st, d, c->e.key, "failed", strerror(errno));
return;
}
(void)fcntl(errp[0], F_SETFD, FD_CLOEXEC);
(void)fcntl(errp[0], F_SETFL, O_NONBLOCK);
cmd = rmt_cmd_add(d, CMD_COMPACT, jx, c->e.key, c->row, c->e.payload);
cmd->pid = pid;
cmd->errfd = errp[0];
(void)snprintf(cmd->conv, sizeof cmd->conv, "%s", c->conv);
}
/* A command's job applied on the loop: an inbox row kept for polling, a choice changed, a child
* started; then its lines. Nothing is applied from a job whose statements ran out of time before it
* committed: what it read may be cut short, and the phone, told busy, asks again. */
static void rmt_cmd_done(rmt_state *st, rmt_job *jb) {
rmt_cmdjob *c = jb->ctx;
rmt_dev *d = rmt_job_dev(st, jb);
int fate = atomic_load(&jb->fate);
/* not when the phone is told busy: it asks again, and its repeat applies them */
if (d && !jb->answered && fate != RMT_FATE_ABANDONED && (!jb->overran || fate == RMT_FATE_COMMITTED)) {
if (c->keep && rmt_cmd_find(d, jb->key) < 0) {
(void)rmt_cmd_add(d, CMD_INBOX, jb->jx, jb->key, c->row, c->keep);
}
if (c->setm || c->setk || c->sett) {
rmt_choice *ch;
(void)pthread_mutex_lock(&rmt_choice_mu);
ch = rmt_choice_get(st, jb->jx, c->conv);
if (c->setm) {
(void)snprintf(ch->model, sizeof ch->model, "%s", c->set.model);
} else if (!ch->model[0] && c->cand[0]) {
(void)snprintf(ch->model, sizeof ch->model, "%s", c->cand);
}
if (c->setk) {
(void)snprintf(ch->key, sizeof ch->key, "%s", c->set.key);
}
if (c->sett) {
(void)snprintf(ch->thinking, sizeof ch->thinking, "%s", c->set.thinking);
}
(void)pthread_mutex_unlock(&rmt_choice_mu);
}
if (c->start && rmt_cmd_find(d, jb->key) < 0) { /* not starting already */
if (c->start == 1) {
rmt_prompt_start(st, d, jb->jx, c);
} else {
rmt_compact_start(st, d, jb->jx, c);
}
}
}
rmt_job_reply(st, jb);
}
/* A question about a conversation (get_state, get_messages, get_session_stats) asked again by the same
* device: the same question still queued is dropped, its keys answered by JB, so a burst costs one
* answer per conversation rather than one per message. */
static void rmt_coalesce(rmt_state *st, rmt_job *jb) {
rmt_cmdjob *c = jb->ctx;
rmt_job *o = st->held;
while (o) {
rmt_job *next = o->held;
rmt_cmdjob *oc = o->run == rmt_cmd_run ? o->ctx : NULL;
char (*g)[48];
if (oc && o != jb && memcmp(o->dev, jb->dev, 16) == 0 && o->j == jb->j && !oc->fresh &&
strcmp(oc->e.ptype, c->e.ptype) == 0 && strcmp(oc->conv, c->conv) == 0 &&
(g = realloc(jb->alias, (size_t)(jb->nalias + o->nalias + 1) * sizeof *g))) {
jb->alias = g;
if (!rmt_job_unqueue(st, o)) { /* running already: it answers for itself */
o = next;
continue;
}
for (int k = 0; k < o->nalias; k++) { /* oldest first, as they were asked */
(void)snprintf(jb->alias[jb->nalias++], sizeof jb->alias[0], "%s", o->alias[k]);
}
(void)snprintf(jb->alias[jb->nalias++], sizeof jb->alias[0], "%s", o->key);
rmt_job_unhold(st, o);
rmt_job_free(o);
}
o = next;
}
}
/* Whether a prompt's message starts with "/": a skill or a template, perhaps. */
static int rmt_slash(const char *payload) {
char *m = rmt_q("SELECT substr(json_extract(?1, '$.message'), 1, 1) WHERE json_type(?1, '$.message') = 'text'", 1, payload);
int slash = m && m[0] == '/';
free(m);
return slash;
}
/* F, a folder a phone may start a conversation in (as the list offers it, a real path), as a journal
* held hidden until a job opens it: the one its workspace has, or the one it is to have. Its index,
* or -1 when F is not one. On the loop. */
static int rmt_folder_hold(rmt_state *st, const char *f) {
char *offered = st->folders && *f == '/' ? rmt_q("SELECT 1 FROM json_each(?1) WHERE json_extract(value, '$.id') = ?2", 2,
st->folders, f)
: NULL;
char jp[PATH_MAX];
rmt_cand c;
rmt_journal *j;
int ok = offered != NULL;
free(offered);
if (*f != '/' || snprintf(jp, sizeof jp, "%s/.pic/journal.sqlite", f) >= (int)sizeof jp) {
return -1;
}
for (int i = 0; i < st->njs; i++) { /* one made already: a repeat of the command that made it */
if (st->js[i]->open && strcmp(st->js[i]->path, jp) == 0 && strcmp(st->js[i]->workspace, f) == 0) {
return i;
}
}
if (!ok) {
return -1;
}
c.path = jp;
c.ws = (char *)(uintptr_t)f;
c.real = jp;
if (!(j = rmt_journal_hold(st, &c))) {
return -1;
}
for (int i = 0; i < st->njs; i++) {
if (st->js[i] == j) {
return i;
}
}
return -1;
}
/* A command from D, on the loop: what needs no journal is answered here; the rest is a job on its
* journal's lane, one per key at a time (a repeat while it is in hand joins it). */
static void rmt_command(rmt_state *st, rmt_dev *d, rmt_env *e) {
int jx = -1, user, create = 0;
char conv[64] = "", what[160];
const char *t = e->ptype;
rmt_cmdjob *c;
rmt_job *jb;
if (!rmt_key_ok(e->key)) {
rmt_error(st, d, NULL, "bad_key", "a command's key is 16 to 43 characters of A-Z, a-z, 0-9, _ and -");
return;
}
if (!e->payload || !*t) {
rmt_error(st, d, e->key, "bad_command", "a command's payload is a Pi RPC command");
return;
}
if (e->session && e->session[0] == '+') { /* +W: a prompt that starts a new conversation in W */
for (int i = 0; i < st->njs; i++) {
if (st->js[i]->open && strcmp(st->js[i]->path, e->session + 1) == 0) {
jx = i;
}
}
if (jx < 0 && (jx = rmt_folder_hold(st, e->session + 1)) >= 0) {
create = 1;
}
if (jx < 0) {
rmt_error(st, d, e->key, "no_session", "no such workspace");
return;
}
} else if (rmt_resolve(st, e->session, &jx, conv) != 0) {
rmt_error(st, d, e->key, "no_session", "no such conversation");
return;
} else {
int known = rmt_cmd_find(d, e->key);
if (known >= 0 && d->cmds[known].line && strcmp(d->cmds[known].line, e->payload) != 0) {
rmt_error(st, d, e->key, "refused", "that key was used for another command");
return;
}
if (known >= 0 && d->cmds[known].kind == CMD_DONE) { /* a repeat: the same answer */
rmt_response(st, d, e->key, d->cmds[known].answer);
return;
}
if (known >= 0 && d->cmds[known].kind == CMD_COMPACT) {
return; /* still compacting */
}
}
if ((jb = rmt_job_keyed(st, d, e->key))) { /* in hand: this repeat gets its answer */
if (jb->line && strcmp(jb->key, e->key) == 0 && strcmp(jb->line, e->payload) != 0) {
rmt_error(st, d, e->key, "refused", "that key was used for another command");
} else {
jb->answered = 0;
}
return;
}
if (e->session[0] != '+') {
if (strcmp(t, "switch_session") == 0) {
rmt_error(st, d, e->key, "not_available", "the envelope's session selects the conversation");
return;
}
if (!(strcmp(t, "get_state") == 0 || strcmp(t, "get_messages") == 0 || strcmp(t, "steer") == 0 ||
strcmp(t, "follow_up") == 0 || strcmp(t, "abort") == 0 || strcmp(t, "prompt") == 0 ||
strcmp(t, "get_session_stats") == 0 || strcmp(t, "get_available_thinking_levels") == 0 ||
strcmp(t, "get_available_models") == 0 || strcmp(t, "get_credentials") == 0 ||
strcmp(t, "check_credentials") == 0 || strcmp(t, "get_profiles") == 0 || strcmp(t, "set_model") == 0 ||
strcmp(t, "set_session_name") == 0 || strcmp(t, "set_credential") == 0 || strcmp(t, "set_thinking_level") == 0 ||
strcmp(t, "compact") == 0 ||
strcmp(t, "delete_session") == 0 || strcmp(t, "restore_session") == 0 || strcmp(t, "archive_session") == 0 ||
strcmp(t, "unarchive_session") == 0 || strcmp(t, "purge_session") == 0 || strcmp(t, "get_wakes") == 0 ||
strcmp(t, "pause_wake") == 0 || strcmp(t, "resume_wake") == 0 || strcmp(t, "stop_wake") == 0 ||
strcmp(t, "pause_wakes") == 0 || strcmp(t, "approve_wake") == 0 || strcmp(t, "decline_wake") == 0 ||
strcmp(t, "answer") == 0 || strcmp(t, "set_permission_mode") == 0)) {
rmt_error(st, d, e->key, "not_available", "this command is not carried by remote control yet");
return;
}
}
if (!(c = calloc(1, sizeof *c))) {
rmt_error(st, d, e->key, "failed", "out of memory");
return;
}
c->imgfd = -1;
c->e = *e; /* takes its strings */
e->session = e->payload = NULL;
c->fresh = c->e.session[0] == '+';
c->create = create;
(void)snprintf(c->conv, sizeof c->conv, "%s", conv);
c->known = rmt_cmd_find(d, c->e.key) >= 0;
c->o = st->o;
c->st = st;
c->jx = jx;
if (strcmp(t, "get_state") == 0 || strcmp(t, "answer") == 0) {
c->names = strdup(rmt_names(st));
}
/* what calls into pic's own state (models, keys, settings, the registry) */
user = rmt_asked(t) || strcmp(t, "set_model") == 0 || strcmp(t, "set_credential") == 0 ||
(strcmp(t, "prompt") == 0 && rmt_slash(c->e.payload)) || /* a skill or template reads the trust list */
strcmp(t, "prompt") == 0; /* its choice, or the key its conversation keeps, checked against the keys */
(void)snprintf(what, sizeof what, "answering %s's command %s", d->d.name, t);
if (!(jb = rmt_job_new(st, st->js[jx], d, rmt_cmd_run, rmt_cmd_done, rmt_cmdjob_drop, c, what))) {
rmt_error(st, d, e->key, "failed", "out of memory");
return;
}
jb->user = user;
jb->budget_ms = strcmp(t, "purge_session") == 0 ? RMT_PURGE_MS : RMT_MESSAGE_MS;
(void)snprintf(jb->key, sizeof jb->key, "%s", c->e.key);
jb->line = strdup(c->e.payload);
(void)snprintf(jb->answering, sizeof jb->answering, "command %s", t);
if (strcmp(t, "get_state") == 0 || strcmp(t, "get_messages") == 0 || strcmp(t, "get_session_stats") == 0) {
rmt_coalesce(st, jb);
}
rmt_job_add(st, jb);
}
/* Each tick, on the loop: a child's stderr, a compaction's end, a prompt's child that ended. Whether
* an inbox row settled or a prompt was admitted is a tick job's to read (rmt_tick_cmds). */
static void rmt_commands_poll(rmt_state *st, rmt_dev *d) {
for (int i = 0; i < d->ncmds; i++) {
rmt_cmd *c = &d->cmds[i];
if (c->kind == CMD_DONE || c->kind == CMD_INBOX) {
continue;
}
if (c->errfd >= 0) {
char buf[256];
ssize_t n;
while ((n = read(c->errfd, buf, sizeof buf)) > 0) {
size_t k = (size_t)n;
if (c->errlen + k >= sizeof c->err) {
c->errlen = 0;
}
memcpy(c->err + c->errlen, buf, k < sizeof c->err - 1 ? k : sizeof c->err - 1);
c->errlen += k < sizeof c->err - 1 ? k : sizeof c->err - 1;
}
}
if (c->kind == CMD_COMPACT) {
int status = 0;
if (c->pid > 0 && waitpid(c->pid, &status, WNOHANG) == c->pid) {
char *line;
c->pid = 0;
if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
line = rmt_pi_response(c->line, "compact", 1, "{}", NULL);
} else {
char *last, *end;
c->err[c->errlen < sizeof c->err ? c->errlen : sizeof c->err - 1] = '\0';
end = c->err + strlen(c->err);
while (end > c->err && end[-1] == '\n') {
*--end = '\0';
}
last = strrchr(c->err, '\n');
last = last ? last + 1 : c->err;
if (strncmp(last, "pic: ", 5) == 0) {
last += 5;
}
line = rmt_pi_response(c->line, "compact", 0, NULL, *last ? last : "the compaction failed");
}
if (d->sess >= 0 && line) {
rmt_response(st, d, c->key, line);
}
close(c->errfd); /* kept as the answer to a repeat of its key */
c->errfd = -1;
c->kind = CMD_DONE;
c->answer = line;
}
continue;
}
if (c->pid > 0) { /* a prompt's child */
int status = 0;
if (waitpid(c->pid, &status, WNOHANG) == c->pid) {
c->pid = 0;
c->exited = 1;
}
}
}
}
/* A prompt whose child ended without its request admitted: the phone hears why. */
static void rmt_prompt_failed(rmt_state *st, rmt_dev *d, rmt_cmd *c) {
char *last, *end, *line;
c->err[c->errlen < sizeof c->err ? c->errlen : sizeof c->err - 1] = '\0';
end = c->err + strlen(c->err);
while (end > c->err && end[-1] == '\n') {
*--end = '\0';
}
last = strrchr(c->err, '\n');
last = last ? last + 1 : c->err;
if (strncmp(last, "pic: ", 5) == 0) {
last += 5;
}
if (d->sess >= 0) {
line = rmt_q("SELECT json_object('type', 'response', 'command', 'prompt', 'success', json('false'), 'error', ?1)", 1,
*last ? last : "the request could not be started");
rmt_response(st, d, c->key, line);
free(line);
}
}
/* ---- a whole message from a phone -------------------------------------------------------- */
/* ---- device rows, on the user database's lane --------------------------------------------- */
enum { RMT_ROW_SEEN, RMT_ROW_WRITE, RMT_ROW_DELETE, RMT_ROW_ADD };
typedef struct {
int op, rc;
rmt_device d;
int tries; /* RMT_ROW_WRITE of a subscription: writes tried so far */
char err[256];
unsigned offer; /* RMT_ROW_ADD: the offer it answers (st->offer_serial) */
} rmt_rowjob;
static void rmt_row_drop(void *p) {
if (p) {
pic_cred_wipe(p, sizeof(rmt_rowjob));
}
free(p);
}
static void rmt_row_run(rmt_job *jb) {
rmt_rowjob *r = jb->ctx;
switch (r->op) {
case RMT_ROW_SEEN:
rmt_device_seen(r->d.id);
break;
case RMT_ROW_WRITE:
r->rc = rmt_device_write(&r->d, 0, r->err, sizeof r->err);
break;
case RMT_ROW_DELETE:
rmt_device_delete(r->d.id);
break;
default:
r->rc = rmt_device_add(&r->d, r->err, sizeof r->err);
break;
}
}
/* A job that writes device DEV's row (OP), for D (NULL: none). */
static rmt_job *rmt_row_job(rmt_state *st, rmt_dev *d, int op, const rmt_device *dev, void (*done)(rmt_state *, rmt_job *),
const char *what) {
rmt_rowjob *r = calloc(1, sizeof *r);
if (!r) {
return NULL;
}
r->op = op;
r->d = *dev;
rmt_job *jb;
if (op != RMT_ROW_SEEN) {
st->user_gen++; /* a read of the table begun before this write is stale */
}
if ((jb = rmt_job_new(st, NULL, d, rmt_row_run, done, rmt_row_drop, r, what))) {
jb->user = 1; /* seals with the store's key */
}
return jb;
}
static void rmt_seen_done(rmt_state *st, rmt_job *jb) {
rmt_dev *d = rmt_job_dev(st, jb);
if (d) {
d->seen_job = 0;
}
}
/* D's last seen, written now unless a write of it is in hand. */
static void rmt_seen(rmt_state *st, rmt_dev *d) {
if (!d->seen_job) {
rmt_job *jb = rmt_row_job(st, d, RMT_ROW_SEEN, &d->d, rmt_seen_done, "writing when a phone was last seen");
d->seen_job = jb != NULL;
if (jb) {
jb->background = 1;
}
rmt_job_add(st, jb);
}
}
static void rmt_row_logged(rmt_state *st, rmt_job *jb) {
rmt_rowjob *r = jb->ctx;
(void)st;
if (r->rc != 0) {
rmt_log(stderr, "pic remote: %s\n", r->err);
}
}
/* SRC's subscription and notify, D's in memory. */
static void rmt_push_apply(rmt_dev *d, const rmt_device *src) {
(void)snprintf(d->d.notify, sizeof d->d.notify, "%s", src->notify);
(void)snprintf(d->d.endpoint, sizeof d->d.endpoint, "%s", src->endpoint);
memcpy(d->d.p256dh, src->p256dh, sizeof d->d.p256dh);
memcpy(d->d.auth, src->auth, sizeof d->d.auth);
d->refused = 0;
d->push_hold_ms = 0;
}
/* push from the phone, its row written. Its choice is in force since the message came, and stays:
* a write that failed (the user database held by another process past the busy wait) is tried
* again, up to 5 times, unless the phone sent another choice meanwhile; never put back, which
* would notify a phone that asked not to be. */
static void rmt_push_set_done(rmt_state *st, rmt_job *jb) {
rmt_rowjob *r = jb->ctx;
rmt_dev *d = rmt_job_dev(st, jb);
rmt_job *again;
if (!d || r->rc == 0 || strcmp(d->d.endpoint, r->d.endpoint) != 0 || strcmp(d->d.notify, r->d.notify) != 0) {
return;
}
if (r->tries >= 4 || !(again = rmt_row_job(st, d, RMT_ROW_WRITE, &d->d, rmt_push_set_done, "writing a phone's subscription"))) {
rmt_log(stderr, "pic remote: cannot save %s's notifications (in force until pic remote stops): %s\n", d->d.name, r->err);
return;
}
((rmt_rowjob *)again->ctx)->tries = r->tries + 1;
rmt_job_add(st, again);
}
/* ---- notifications (section 5) ------------------------------------------------------------ */
static int rmt_ids_has(const rmt_ids *a, long long v) {
for (int i = 0; i < a->n; i++) {
if (a->v[i] == v) {
return 1;
}
}
return 0;
}
static void rmt_ids_add(rmt_ids *a, long long v) {
if (a->n == a->cap) {
long long *grown = realloc(a->v, (size_t)(a->cap = a->cap ? a->cap * 2 : 8) * sizeof *grown);
if (!grown) {
a->cap = a->n;
return;
}
a->v = grown;
}
a->v[a->n++] = v;
}
/* Drops V, or (BELOW) every value up to V. */
static void rmt_ids_drop(rmt_ids *a, long long v, int below) {
int k = 0;
for (int i = 0; i < a->n; i++) {
if (below ? a->v[i] > v : a->v[i] != v) {
a->v[k++] = a->v[i];
}
}
a->n = k;
}
static long long rmt_push_gap_ms(void) {
#ifdef PIC_FAULTS
if (getenv("PIC_TEST_RC_PUSH_GAP_MS")) { /* the tests' seam: several notifications for one conversation */
return atoll(getenv("PIC_TEST_RC_PUSH_GAP_MS"));
}
#endif
return RMT_PUSH_GAP_MS;
}
/* Section 5's check of an endpoint; dev builds also take the tests' push service on loopback. */
static int rmt_endpoint_ok(const char *ep) {
#ifdef PIC_FAULTS
if (getenv("PIC_TEST_RC_PUSH_HTTP") && strncmp(ep, "http://127.0.0.1:", 17) == 0) {
return 1;
}
#endif
return pic_webpush_endpoint_ok(ep);
}
static void rmt_push_free(rmt_push *p) {
if (p) {
free(p->title);
free(p->payload);
free(p->session);
pic_cred_wipe(p, sizeof *p);
free(p);
}
}
/* The pusher: one thread that sends what the loop queues, so a slow push service never holds up
* the loop, the relay's lanes or a request. It touches no database; the loop applies outcomes. */
static void *rmt_pusher_main(void *arg) {
rmt_pusher *pu = arg;
char err[256];
pic_net *net = pic_net_new(err, sizeof err);
for (;;) {
rmt_push *p;
(void)pthread_mutex_lock(&pu->mu);
while (!pu->ntodo) {
(void)pthread_cond_wait(&pu->cv, &pu->mu);
}
p = pu->todo[0];
memmove(pu->todo, pu->todo + 1, (size_t)(pu->ntodo - 1) * sizeof *pu->todo);
pu->ntodo--;
pu->sending = 1;
(void)pthread_mutex_unlock(&pu->mu);
memset(&p->res, 0, sizeof p->res);
if (!net) {
p->res.outcome = PIC_WEBPUSH_FAILED;
(void)snprintf(p->res.err, sizeof p->res.err, "%s", err);
} else {
pic_webpush_sub sub;
sub.endpoint = p->endpoint;
memcpy(sub.p256dh, p->p256dh, sizeof sub.p256dh);
memcpy(sub.auth, p->auth, sizeof sub.auth);
(void)pic_webpush_send(net, &sub, &pu->vapid, p->topic, p->payload, strlen(p->payload), RMT_PUSH_TTL, &p->res);
}
(void)pthread_mutex_lock(&pu->mu);
pu->sending = 0;
if (pu->ndone < RMT_PUSH_QUEUE) {
pu->done[pu->ndone++] = p;
p = NULL;
}
(void)pthread_mutex_unlock(&pu->mu);
rmt_push_free(p);
}
return NULL;
}
/* Queues P for the pusher with its plaintext, {"v":1,"title","body","session","seq"} with BODY.
* P is the pusher's, or freed: 0 when queued, else -1. */
static int rmt_push_queue(rmt_state *st, rmt_push *p, const char *body) {
rmt_pusher *pu = &st->push;
char seq[32];
int queued = 0;
(void)snprintf(seq, sizeof seq, "%lld", p->seq);
free(p->payload);
p->payload = rmt_q("SELECT json_object('v', 1, 'title', ?1, 'body', ?2, 'session', ?3, 'seq', CAST(?4 AS INTEGER))", 4, p->title,
body, p->session, seq);
if (!p->payload) {
rmt_push_free(p);
return -1;
}
if (!pu->started) {
pthread_t t;
pthread_attr_t a;
(void)pthread_attr_init(&a);
(void)pthread_attr_setdetachstate(&a, PTHREAD_CREATE_DETACHED);
pu->started = pthread_create(&t, &a, rmt_pusher_main, pu) == 0;
(void)pthread_attr_destroy(&a);
if (!pu->started) {
rmt_push_free(p);
return -1;
}
}
(void)pthread_mutex_lock(&pu->mu);
if (pu->ntodo < RMT_PUSH_QUEUE) { /* else dropped: a notification is a hint */
pu->todo[pu->ntodo++] = p;
queued = 1;
(void)pthread_cond_signal(&pu->cv);
}
(void)pthread_mutex_unlock(&pu->mu);
if (!queued) {
rmt_push_free(p);
}
return queued ? 0 : -1;
}
static unsigned long long rmt_hash(const char *s) {
unsigned long long h = 1469598103934665603ull;
while (*s) {
h = (h ^ (unsigned char)*s++) * 1099511628211ull;
}
return h;
}
/* A request ended in conversation CONV of J, titled CTITLE (PIC_TITLE_SQL; "" for none): one line to
* each device that wants it (its notify, SETTING the remote.notify its job read, not looking at the
* page, not one for this conversation in the last 30 s). */
static void rmt_notify(rmt_state *st, rmt_journal *j, const char *setting, const char *conv, const char *ctitle, int phone, long long seq,
const char *body) {
char *title, *sess;
const char *mode = setting && *setting ? setting : "all"; /* remote.notify, as the job that found it read it */
long long now = rmt_mono_ms();
unsigned long long h;
size_t n;
if (strcmp(mode, "off") == 0 || (strcmp(mode, "remote") == 0 && !phone)) {
return;
}
if (ctitle && *ctitle) {
title = pic_one_line(ctitle, 60);
} else {
size_t e = strlen(j->workspace);
char *base;
while (e > 1 && j->workspace[e - 1] == '/') {
e--;
}
base = strndup(j->workspace, e);
title = base ? pic_one_line(strrchr(base, '/') ? strrchr(base, '/') + 1 : base, 60) : NULL;
free(base);
}
n = strlen(j->path) + strlen(conv) + 2;
if (!title || !(sess = malloc(n))) {
free(title);
return;
}
(void)snprintf(sess, n, "%s/%s", j->path, conv);
h = rmt_hash(sess);
for (int i = 0; i < st->ndevs; i++) {
rmt_dev *d = &st->devs[i];
rmt_push *p;
int slot = 0;
if (!d->alive || !d->d.notify[0] || (strcmp(d->d.notify, "remote") == 0 && !phone) || now < d->push_hold_ms ||
(d->sess >= 0 && st->sess[d->sess].confirmed && d->visible)) {
continue;
}
for (int k = 0; k < 16; k++) { /* this conversation's slot, else the oldest */
if (d->pushed[k].conv == h) {
slot = k;
break;
}
if (d->pushed[k].ms < d->pushed[slot].ms) {
slot = k;
}
}
if (d->pushed[slot].conv == h && d->pushed[slot].ms && now - d->pushed[slot].ms < rmt_push_gap_ms()) {
continue;
}
if (!(p = calloc(1, sizeof *p))) {
continue;
}
memcpy(p->dev, d->d.id, 16);
(void)snprintf(p->endpoint, sizeof p->endpoint, "%s", d->d.endpoint);
memcpy(p->p256dh, d->d.p256dh, sizeof p->p256dh);
memcpy(p->auth, d->d.auth, sizeof p->auth);
pic_webpush_topic(d->d.auth, sess, p->topic);
p->title = strdup(title);
p->session = strdup(sess);
p->seq = seq;
if (!p->title || !p->session) {
rmt_push_free(p);
continue;
}
if (rmt_push_queue(st, p, body) != 0) {
continue;
}
d->pushed[slot].conv = h;
d->pushed[slot].ms = now ? now : 1;
}
free(title);
free(sess);
}
/* What J holds of requests now, for watching them end: the last one, and those running. */
static void rmt_push_watch(rmt_journal *j) {
sqlite3_stmt *q = NULL;
j->push_version = rmt_data_version(j->s.db);
if (sqlite3_prepare_v2(j->s.db, "SELECT coalesce(max(id), 0) FROM pic_submission", -1, &q, NULL) == SQLITE_OK &&
sqlite3_step(q) == SQLITE_ROW) {
j->push_cut = sqlite3_column_int64(q, 0);
}
sqlite3_finalize(q);
q = NULL;
if (sqlite3_prepare_v2(j->s.db, "SELECT id FROM pic_submission WHERE status = 'admitted'", -1, &q, NULL) == SQLITE_OK) {
while (sqlite3_step(q) == SQLITE_ROW) {
rmt_ids_add(&j->push_open, sqlite3_column_int64(q, 0));
}
}
sqlite3_finalize(q);
}
/* Requests of J that ended since the last look (section 5's When): ones running when pic remote
* first read the journal, and ones admitted after, each once. A request that asked no model
* (a command the user ran) or was imported ends nothing. One read transaction. */
/* The requests of J that ended above ?1 or among ?2 (a JSON array), with FILTER (SQL) on u: id,
* conversation, status, error, stop reason, whether a phone asked, title, last seq, reply text. */
#define RMT_ENDED_SQL(FILTER) \
"SELECT u.id, u.session_id, u.status, coalesce(u.error, ''), coalesce(u.stop_reason, '')," \
" u.request_key LIKE 'rc:%' OR EXISTS (SELECT 1 FROM pic_inbox i WHERE i.submission_id = u.id AND i.sender LIKE 'remote:%')," \
" coalesce((SELECT " PIC_TITLE_SQL("t") " FROM pic_session t WHERE t.id = u.session_id), '')," \
" coalesce((SELECT max(seq) FROM pic_entry WHERE submission_id = u.id), 0)," \
" (SELECT t FROM (SELECT e.seq AS seq, (SELECT group_concat(json_extract(c.value, '$.text'), '') FROM json_each(e.body) c" \
" WHERE json_extract(c.value, '$.type') = 'text') AS t FROM pic_entry e WHERE e.submission_id = u.id" \
" AND e.kind IN ('assistant', 'answer') AND json_valid(e.body)) WHERE trim(coalesce(t, '')) != '' ORDER BY seq DESC LIMIT 1)" \
" FROM pic_submission u WHERE u.status != 'admitted' AND u.session_id IS NOT NULL" \
" AND (u.id > ?1 OR u.id IN (SELECT value FROM json_each(?2))) AND u.request_key NOT LIKE 'import-%'" FILTER \
" AND EXISTS (SELECT 1 FROM pic_generation g WHERE g.submission_id = u.id) ORDER BY u.id"
static void rmt_push_check(rmt_tnotes *notes, rmt_journal *j) {
sqlite3_stmt *q = NULL;
rmt_buf open = {NULL, 0, 0};
long long v = rmt_data_version(j->s.db);
if (v == j->push_version || sqlite3_exec(j->s.db, "BEGIN", NULL, NULL, NULL) != SQLITE_OK) {
return;
}
j->push_version = v;
(void)rmt_buf_add(&open, "[", 1);
for (int i = 0; i < j->push_open.n; i++) {
char one[32];
int k = snprintf(one, sizeof one, "%s%lld", i ? "," : "", j->push_open.v[i]);
(void)rmt_buf_add(&open, one, (size_t)k);
}
(void)rmt_buf_add(&open, "]", 2);
/* a person's conversations alone (rmt_list), so no other's words leave the computer */
if (sqlite3_prepare_v2(j->s.db,
RMT_ENDED_SQL(" AND (SELECT " PIC_STARTED_BY_SQL("t") " FROM pic_session t WHERE t.id = u.session_id)"
" IN ('person', 'phone')"),
-1, &q, NULL) == SQLITE_OK ||
(sqlite3_finalize(q), q = NULL, sqlite3_prepare_v2(j->s.db, RMT_ENDED_SQL(""), -1, &q, NULL)) == SQLITE_OK) {
sqlite3_bind_int64(q, 1, j->push_cut);
sqlite3_bind_text(q, 2, open.buf, -1, SQLITE_STATIC);
while (sqlite3_step(q) == SQLITE_ROW) {
long long id = sqlite3_column_int64(q, 0);
const char *conv = (const char *)sqlite3_column_text(q, 1), *status = (const char *)sqlite3_column_text(q, 2);
const char *error = (const char *)sqlite3_column_text(q, 3), *stop = (const char *)sqlite3_column_text(q, 4);
const char *text = (const char *)sqlite3_column_text(q, 8);
char *body, *why = NULL;
if (rmt_ids_has(&j->push_open, id)) {
rmt_ids_drop(&j->push_open, id, 0);
} else if (rmt_ids_has(&j->push_told, id)) {
continue;
} else {
rmt_ids_add(&j->push_told, id);
}
if (!text) { /* no reply text: how it ended */
if (strcmp(status, "failed") == 0 && strcmp(error, "cancelled") != 0) {
size_t n = strlen(error) + 16;
if ((why = malloc(n))) {
(void)snprintf(why, n, "Failed: %s", error);
}
}
text = why ? why
: strcmp(status, "failed") == 0 || strcmp(status, "stopped") == 0
? (strcmp(stop, "request_cap") == 0 ? "Reached the request cap" : "Stopped")
: "Done";
}
body = pic_one_line(text, 200);
if (body) {
rmt_note(notes, conv, (const char *)sqlite3_column_text(q, 6), sqlite3_column_int(q, 5), sqlite3_column_int64(q, 7),
body);
}
free(body);
free(why);
}
}
sqlite3_finalize(q);
q = NULL;
/* Everything up to the oldest request still running has been looked at. */
if (sqlite3_prepare_v2(j->s.db,
"SELECT coalesce((SELECT min(id) - 1 FROM pic_submission WHERE id > ?1 AND status = 'admitted'),"
" (SELECT max(id) FROM pic_submission), ?1)",
-1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_int64(q, 1, j->push_cut);
if (sqlite3_step(q) == SQLITE_ROW) {
j->push_cut = sqlite3_column_int64(q, 0);
}
}
sqlite3_finalize(q);
(void)sqlite3_exec(j->s.db, "COMMIT", NULL, NULL, NULL);
rmt_ids_drop(&j->push_told, j->push_cut, 1);
free(open.buf);
}
/* A device's subscription ends (gone at the push service, or refused three times). */
static void rmt_push_end(rmt_state *st, rmt_dev *d, const char *why) {
d->d.notify[0] = '\0';
d->d.endpoint[0] = '\0';
memset(d->d.p256dh, 0, sizeof d->d.p256dh);
memset(d->d.auth, 0, sizeof d->d.auth);
d->refused = 0;
rmt_job_add(st, rmt_row_job(st, NULL, RMT_ROW_WRITE, &d->d, rmt_row_logged, "ending a phone's subscription"));
rmt_log(stdout, "pic remote: notifications to %s ended: %s\n", d->d.name, why);
(void)fflush(stdout);
}
/* What the pusher made of what it sent. */
static void rmt_push_results(rmt_state *st) {
rmt_pusher *pu = &st->push;
rmt_push *done[RMT_PUSH_QUEUE];
int n;
if (!pu->started) {
return;
}
(void)pthread_mutex_lock(&pu->mu);
n = pu->ndone;
memcpy(done, pu->done, (size_t)n * sizeof *done);
pu->ndone = 0;
(void)pthread_mutex_unlock(&pu->mu);
for (int i = 0; i < n; i++) {
rmt_push *p = done[i];
rmt_dev *d = NULL;
for (int k = 0; k < st->ndevs && !d; k++) {
d = st->devs[k].alive && memcmp(st->devs[k].d.id, p->dev, 16) == 0 ? &st->devs[k] : NULL;
}
if (d && strcmp(d->d.endpoint, p->endpoint) == 0) { /* still that subscription */
switch (p->res.outcome) {
case PIC_WEBPUSH_SENT:
d->refused = 0;
break;
case PIC_WEBPUSH_GONE:
rmt_push_end(st, d, p->res.err);
break;
case PIC_WEBPUSH_RETRY: {
long secs = p->res.retry_after >= 0 ? (p->res.retry_after > 86400 ? 86400 : p->res.retry_after) : 60;
d->push_hold_ms = rmt_mono_ms() + secs * 1000LL;
break;
}
case PIC_WEBPUSH_TOO_LARGE:
if (!p->shortened) { /* once more with a shorter line: a different push, not a retry */
char *line = rmt_q("SELECT json_extract(?1, '$.body')", 1, p->payload), *cut = pic_one_line(line, 40);
free(line);
p->shortened = 1;
if (cut) {
(void)rmt_push_queue(st, p, cut); /* P is the pusher's now, or freed */
free(cut);
p = NULL;
}
}
break;
case PIC_WEBPUSH_FAILED:
if ((p->res.status == 400 || p->res.status == 403) && ++d->refused >= RMT_PUSH_REFUSED) {
rmt_push_end(st, d, p->res.err);
}
break;
}
}
rmt_push_free(p);
}
}
/* push from the phone: its subscription and notify, or null to end it, sealed into its row. */
static void rmt_push_set(rmt_state *st, rmt_dev *d, const char *payload) {
rmt_device nd = d->d;
char err[256], *t = payload ? rmt_q("SELECT json_type(?1, '$.subscription')", 1, payload) : NULL;
if (t && strcmp(t, "null") == 0) {
nd.notify[0] = '\0';
nd.endpoint[0] = '\0';
memset(nd.p256dh, 0, sizeof nd.p256dh);
memset(nd.auth, 0, sizeof nd.auth);
} else if (t && strcmp(t, "object") == 0) {
char *ep = rmt_q("SELECT CASE json_type(?1, '$.subscription.endpoint') WHEN 'text' THEN json_extract(?1, '$.subscription.endpoint') END",
1, payload);
char *pk = rmt_q("SELECT CASE json_type(?1, '$.subscription.keys.p256dh') WHEN 'text' THEN json_extract(?1,"
" '$.subscription.keys.p256dh') END",
1, payload);
char *au = rmt_q("SELECT CASE json_type(?1, '$.subscription.keys.auth') WHEN 'text' THEN json_extract(?1,"
" '$.subscription.keys.auth') END",
1, payload);
char *nt = rmt_q("SELECT CASE WHEN json_type(?1, '$.notify') IS NULL THEN 'all' WHEN json_type(?1, '$.notify') = 'text'"
" THEN json_extract(?1, '$.notify') END",
1, payload);
int ok = ep && pk && au && nt && strlen(ep) < sizeof nd.endpoint && rmt_endpoint_ok(ep) &&
(strcmp(nt, "all") == 0 || strcmp(nt, "remote") == 0) &&
pic_b64u_dec(pk, strlen(pk), nd.p256dh, sizeof nd.p256dh) == PIC_WEBPUSH_PUB && pic_noise_pub_valid(nd.p256dh) &&
pic_b64u_dec(au, strlen(au), nd.auth, sizeof nd.auth) == PIC_WEBPUSH_AUTH;
if (ok) {
(void)snprintf(nd.endpoint, sizeof nd.endpoint, "%s", ep);
(void)snprintf(nd.notify, sizeof nd.notify, "%s", nt);
}
free(ep);
free(pk);
free(au);
free(nt);
if (!ok) {
free(t);
rmt_error(st, d, NULL, "bad_message",
"a push subscription is an https endpoint on port 443 with a host name, keys.p256dh (a P-256 public key)"
" and keys.auth (16 bytes), and notify all or remote");
return;
}
} else {
free(t);
rmt_error(st, d, NULL, "bad_message", "push carries a subscription, or null");
return;
}
free(t);
if (strcmp(nd.notify, d->d.notify) == 0 && strcmp(nd.endpoint, d->d.endpoint) == 0 &&
memcmp(nd.p256dh, d->d.p256dh, sizeof nd.p256dh) == 0 && memcmp(nd.auth, d->d.auth, sizeof nd.auth) == 0) {
return;
}
(void)err;
{ /* in force now, as the phone asked: a request ending while the row is written follows it */
rmt_job *jb = rmt_row_job(st, d, RMT_ROW_WRITE, &nd, rmt_push_set_done, "writing a phone's subscription");
if (!jb) {
rmt_error(st, d, NULL, "failed", "out of memory");
return;
}
rmt_push_apply(d, &nd); /* the phone's choice holds; a failed write is tried again (rmt_push_set_done) */
rmt_job_add(st, jb);
}
}
/* ---- repair: an older page's Fix ------------------------------------------------------- */
/* repair {"workspace":W}, which pages from before pic updated journals itself send: W is updated
* now when it can be (rmt_update), and the answer says whether it is served. Nothing is offered
* for it any more. */
static void rmt_repair_run(rmt_job *jb) {
rmt_journal *j = jb->j;
int ok = rmt_update(j);
rmt_out(jb, rmt_q("SELECT json_object('type', 'repair', 'key', ?1, 'payload', json_object('workspace', ?2, 'ok', json(?3),"
" 'message', ?4))",
4, jb->key, j->workspace, ok ? "true" : "false", ok ? "It is up to date; its conversations show again." : j->why));
}
static void rmt_repair(rmt_state *st, rmt_dev *d, rmt_env *e) {
char *w = e->payload ? rmt_q("SELECT CASE json_type(?1, '$.workspace') WHEN 'text' THEN json_extract(?1, '$.workspace') END", 1,
e->payload)
: NULL;
int jx = -1;
rmt_job *jb;
for (int i = 0; w && i < st->njs && jx < 0; i++) {
jx = strcmp(st->js[i]->workspace, w) == 0 ? i : -1; /* as unavailable names it */
}
free(w);
if (!rmt_key_ok(e->key)) {
rmt_error(st, d, NULL, "bad_message", "a repair's key is 16 to 43 characters of A-Z, a-z, 0-9, _ and -");
return;
}
if (jx < 0) {
rmt_error(st, d, e->key, "no_session", "no such workspace");
return;
}
if ((jb = rmt_job_new(st, st->js[jx], d, rmt_repair_run, rmt_done_reply, NULL, NULL, "updating a journal a phone asked for"))) {
(void)snprintf(jb->key, sizeof jb->key, "%s", e->key);
(void)snprintf(jb->answering, sizeof jb->answering, "repair");
}
rmt_job_add(st, jb);
}
static void rmt_unpair_device(rmt_state *st, int di, int tell);
static void rmt_rename(rmt_state *st, rmt_dev *d, const rmt_env *e);
static void rmt_offer_tell(rmt_state *st);
static void rmt_offer_ask(rmt_state *st, int di);
static void rmt_offer_answer(rmt_state *st, int di, int yes, const char *code);
static char *rmt_devices_json(rmt_state *st, int self);
static void rmt_devices_tell(rmt_state *st);
/* ---- a phone's messages that read a journal ----------------------------------------------- */
/* sessions for one workspace: every conversation of it, built on its lane, sent from the loop. */
typedef struct {
rmt_item *li;
size_t nli;
rmt_helpers *lh;
size_t nlh;
int archived; /* the archived ones too, marked */
int trash; /* the deleted ones too, marked */
} rmt_listjob;
static void rmt_listjob_drop(void *p) {
rmt_listjob *l = p;
if (l) {
rmt_items_free(l->li, l->nli);
rmt_helpers_free(l->lh, l->nlh);
}
free(l);
}
static void rmt_listjob_run(rmt_job *jb) {
rmt_listjob *l = jb->ctx;
rmt_journal *j = jb->j;
if (j->sopen && !rmt_gone(j->workspace, j->path) &&
rmt_list_build(j, jb->jx, 2000, 4 * RMT_LIST_BUDGET_MS, &l->li, &l->nli, &l->lh, &l->nlh) != 0) {
l->li = NULL;
l->lh = NULL;
l->nli = l->nlh = 0;
}
}
static void rmt_listjob_done(rmt_state *st, rmt_job *jb) {
rmt_listjob *l = jb->ctx;
rmt_dev *d = rmt_job_dev(st, jb);
if (d) {
rmt_send_free(st, d, rmt_list(st, jb->jx, l->li, l->nli, l->lh, l->nlh, l->archived, l->trash)); /* takes them */
l->li = NULL;
l->lh = NULL;
l->nli = l->nlh = 0;
}
}
/* A follow J's lane let go of on the loop's word, closed by its next job. */
static void rmt_follow_dead(rmt_state *st, rmt_journal *j, pic_follow *f) {
if (!f) {
return;
}
if (!st->pool.started) {
rmt_follow_forget(j, f);
return;
}
(void)pthread_mutex_lock(&st->pool.mu);
if (j->ndead == j->capdead) {
int cap = j->capdead ? j->capdead * 2 : 4;
pic_follow **g = realloc(j->dead, (size_t)cap * sizeof *g);
if (g) {
j->dead = g;
j->capdead = cap;
}
}
if (j->ndead < j->capdead) {
j->dead[j->ndead++] = f;
}
(void)pthread_mutex_unlock(&st->pool.mu);
}
/* sync: a follow made on the conversation's lane, the device's once the loop applies it (unless a
* newer sync or an unfollow came meanwhile: then it goes back). */
typedef struct {
char conv[64];
long long seq, earlier;
unsigned gen;
pic_follow *f;
char *live;
} rmt_syncjob;
static void rmt_syncjob_drop(void *p) {
rmt_syncjob *y = p;
if (y) {
free(y->live);
}
free(y);
}
static void rmt_syncjob_run(rmt_job *jb) {
rmt_syncjob *y = jb->ctx;
rmt_journal *j = jb->j;
char err[256], path[4096];
if (!j->sopen || !rmt_conv_is(&j->s, y->conv)) {
rmt_out_error(jb, NULL, "no_session", "no such conversation");
return;
}
if (!(y->f = pic_follow_new(&j->s, y->conv, y->seq, err, sizeof err))) {
rmt_out_error(jb, NULL, "unavailable", err);
return;
}
if (rmt_follow_keep(j, y->f) != 0) {
y->f = NULL;
rmt_out_error(jb, NULL, "unavailable", "out of memory");
return;
}
y->earlier = rmt_earlier(&j->s, y->conv, y->seq);
y->live = pic_live_path(&j->s, y->conv, path, sizeof path) == 0 ? strdup(path) : NULL;
}
static void rmt_syncjob_done(rmt_state *st, rmt_job *jb) {
rmt_syncjob *y = jb->ctx;
rmt_dev *d = rmt_job_dev(st, jb);
if (d && y->f && d->fgen == y->gen && d->jx == jb->jx && !d->f) {
d->f = y->f;
y->f = NULL;
d->follow_now = 1;
d->earlier = y->earlier;
free(d->live_path);
d->live_path = y->live;
y->live = NULL;
}
rmt_follow_dead(st, jb->j, y->f);
y->f = NULL;
rmt_job_reply(st, jb);
}
/* fetch: a page of what came earlier, read once on the conversation's lane (section 4): the last
* LIMIT entries before BEFORE (RMT_PAGE at most), their events under the fetch's key, then the end,
* whose seq is the first entry sent and which says whether there are entries before it. */
typedef struct {
char conv[64];
char *wsess;
char key[48];
long long before;
int limit;
} rmt_fetchjob;
static void rmt_fetchjob_drop(void *p) {
rmt_fetchjob *g = p;
if (g) {
free(g->wsess);
}
free(g);
}
static void rmt_fetchjob_run(rmt_job *jb) {
rmt_fetchjob *g = jb->ctx;
rmt_journal *j = jb->j;
sqlite3_stmt *q = NULL;
long long from = -1, first;
int more = 0;
rmt_tfollow fo;
char s[32];
if (!j->sopen || !rmt_conv_is(&j->s, g->conv)) {
rmt_out_error(jb, g->key[0] ? g->key : NULL, "no_session", "no such conversation");
return;
}
if (sqlite3_prepare_v2(j->s.db,
/* the newest entries before ?2 whose events come to about ?4 bytes (a person's
* message goes twice, as message_start and message_end), one at least */
"SELECT coalesce(min(CASE WHEN n = 1 OR total <= ?4 THEN seq END), ?2) - 1 FROM (SELECT seq,"
" row_number() OVER w AS n, sum(bytes) OVER w AS total FROM (SELECT e.seq, 512 + min(length(e.body),"
" 262144) * iif(e.kind = 'user', 2, 1) AS bytes FROM pic_submission u JOIN pic_entry e ON"
" e.submission_id = u.id WHERE u.session_id = ?1 AND e.seq < ?2 ORDER BY e.seq DESC LIMIT ?3)"
" WINDOW w AS (ORDER BY seq DESC))",
-1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, g->conv, -1, SQLITE_STATIC);
sqlite3_bind_int64(q, 2, g->before);
sqlite3_bind_int(q, 3, g->limit);
sqlite3_bind_int64(q, 4, (sqlite3_int64)RMT_FETCH_BYTES);
from = sqlite3_step(q) == SQLITE_ROW ? sqlite3_column_int64(q, 0) : -1;
}
sqlite3_finalize(q);
q = NULL;
if (from >= 0 && sqlite3_prepare_v2(j->s.db,
"SELECT EXISTS (SELECT 1 FROM pic_submission u JOIN pic_entry e ON e.submission_id = u.id"
" WHERE u.session_id = ?1 AND e.seq <= ?2)",
-1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, g->conv, -1, SQLITE_STATIC);
sqlite3_bind_int64(q, 2, from);
more = sqlite3_step(q) == SQLITE_ROW && sqlite3_column_int(q, 0);
}
sqlite3_finalize(q);
memset(&fo, 0, sizeof fo);
fo.wsess = g->wsess;
(void)snprintf(fo.skey, sizeof fo.skey, "%s", g->key);
/* entries are only ever added after the last: what is before BEFORE does not change */
if (from < 0 || pic_follow_page(&j->s, g->conv, from, g->before, rmt_emit, &fo) != 0) {
int rc = sqlite3_extended_errcode(j->s.db) & 0xff;
rmt_lines_free(&fo.out);
rmt_out_error(jb, g->key[0] ? g->key : NULL, rc == SQLITE_BUSY || rc == SQLITE_INTERRUPT ? "busy" : "unavailable",
"cannot read the conversation");
return;
}
jb->out = fo.out;
first = from + 1 < g->before ? from + 1 : g->before;
if (first < g->before) { /* the first entry sent, not merely the bound */
if (sqlite3_prepare_v2(j->s.db,
"SELECT min(e.seq) FROM pic_submission u JOIN pic_entry e ON e.submission_id = u.id"
" WHERE u.session_id = ?1 AND e.seq > ?2 AND e.seq < ?3",
-1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, g->conv, -1, SQLITE_STATIC);
sqlite3_bind_int64(q, 2, from);
sqlite3_bind_int64(q, 3, g->before);
if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_type(q, 0) != SQLITE_NULL) {
first = sqlite3_column_int64(q, 0);
}
}
sqlite3_finalize(q);
}
(void)snprintf(s, sizeof s, "%lld", first);
rmt_out(jb, rmt_q("SELECT json_patch('{}', json_object('type', 'fetch', 'session', ?1, 'seq', CAST(?2 AS INTEGER), 'key',"
" nullif(?3, ''), 'payload', json_object('done', json('true'), 'more', json(?4))))",
4, g->wsess, s, g->key, more ? "true" : "false"));
}
/* image: the bytes of a person's image, read on the conversation's lane. */
typedef struct {
rmt_env e;
char conv[64];
} rmt_imagejob;
static void rmt_imagejob_drop(void *p) {
rmt_imagejob *m = p;
if (m) {
rmt_env_free(&m->e);
}
free(m);
}
static void rmt_imagejob_run(rmt_job *jb) {
rmt_imagejob *m = jb->ctx;
rmt_image(jb, jb->j && jb->j->sopen && rmt_conv_is(&jb->j->s, m->conv) ? jb->j : NULL, &m->e, m->conv);
}
static void rmt_ask_records(rmt_journal *j, const char *list, const char *names, rmt_lines *out, rmt_tnotes *notes);
/* A phone's new session: the open asks of one journal, whatever it was told before. */
static void rmt_asksjob_run(rmt_job *jb) {
char *list;
if (!jb->j->sopen) {
return;
}
list = pic_ask_list(&jb->j->s, NULL, -1, RMT_ASKS);
rmt_ask_records(jb->j, list, jb->ctx, &jb->out, NULL);
free(list);
}
static void rmt_asks_open(rmt_state *st, rmt_dev *d) {
for (int i = 0; i < st->njs; i++) {
if (st->js[i]->open) {
char *names = strdup(rmt_names(st));
if (names) {
rmt_job_add(st, rmt_job_new(st, st->js[i], d, rmt_asksjob_run, rmt_done_reply, free, names, "telling a new session the questions waiting"));
}
}
}
}
/* fetch {"before":X,"limit":N}: a job on the conversation's lane; {"after":A,"to":B} is not carried. */
static void rmt_fetch(rmt_state *st, rmt_dev *d, const rmt_env *e) {
const char *key = e->key[0] ? e->key : NULL;
char *v = e->payload ? rmt_q("SELECT CASE WHEN json_type(?1, '$.before') = 'integer' THEN json_extract(?1, '$.before')"
" || ' ' || CASE json_type(?1, '$.limit') WHEN 'integer' THEN json_extract(?1, '$.limit') ELSE -1 END"
" WHEN json_type(?1, '$.after') IS NOT NULL THEN 'after' END",
1, e->payload)
: NULL;
long long before = 0, limit = -1;
char conv[64];
int jx;
rmt_fetchjob *g;
rmt_job *jb;
if (!key || !rmt_key_ok(key)) { /* its events carry it, or they would pass for the follow's */
rmt_error(st, d, NULL, "bad_message", "a fetch's key is 16 to 43 characters of A-Z, a-z, 0-9, _ and -");
} else if (v && strcmp(v, "after") == 0) {
rmt_error(st, d, key, "not_available", "fetch carries before and limit, not after and to");
} else if (!v || sscanf(v, "%lld %lld", &before, &limit) != 2 || before <= 0) {
rmt_error(st, d, key, "bad_message", "a fetch names its session and payload.before, an entry's seq");
} else if (rmt_resolve(st, e->session, &jx, conv) != 0) {
rmt_error(st, d, key, "no_session", "no such conversation");
} else if (!(g = calloc(1, sizeof *g)) || !(g->wsess = strdup(e->session))) {
rmt_fetchjob_drop(g);
rmt_error(st, d, key, "unavailable", "out of memory");
} else {
(void)snprintf(g->conv, sizeof g->conv, "%s", conv);
(void)snprintf(g->key, sizeof g->key, "%s", e->key);
g->before = before;
g->limit = limit <= 0 || limit > RMT_PAGE ? RMT_PAGE : (int)limit;
if ((jb = rmt_job_new(st, st->js[jx], d, rmt_fetchjob_run, rmt_done_reply, rmt_fetchjob_drop, g, "reading a page of earlier entries"))) {
jb->budget_ms = RMT_MESSAGE_MS;
(void)snprintf(jb->answering, sizeof jb->answering, "fetch");
}
rmt_job_add(st, jb);
}
free(v);
}
/* ---- files from the phone (#109) ------------------------------------------------------------ */
/* A file's bytes go up in chunks to <workspace>/.pic/uploads: each step is a job on the
* workspace's lane, so the chunks are written in order and the loop never touches the disk. The
* part file is .part-DEVICE-ID beside the uploads until upload_end checks its size and sha256,
* fsyncs it, and links it to its name (NAME, else NAME-2 and on when another file has that name;
* the same bytes under that name are that file). */
#define RMT_UPLOAD_MAX (25LL << 20) /* a file's bytes */
#define RMT_UPLOAD_CHUNK (512u << 10) /* a chunk's decoded bytes */
#define RMT_UPLOAD_QUOTA (256LL << 20) /* a device's bytes in a day */
#define RMT_UPLOAD_IDLE_MS 300000LL /* an upload with no chunk this long is given up */
#define RMT_UPLOAD_NAME 128
/* <workspace>/.pic/uploads, made when missing, opened with no symbolic link at .pic or uploads:
* a descriptor, or -1 with WHY. */
static int rmt_uploads_dir(const char *workspace, char *why, size_t cap) {
int ws = open(workspace, O_RDONLY | O_DIRECTORY | O_CLOEXEC), pic = -1, up = -1;
if (ws >= 0 && (mkdirat(ws, ".pic", 0700) == 0 || errno == EEXIST) &&
(pic = openat(ws, ".pic", O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)) >= 0 &&
(mkdirat(pic, "uploads", 0700) == 0 || errno == EEXIST)) {
up = openat(pic, "uploads", O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
}
if (up < 0) {
(void)snprintf(why, cap, "cannot open the workspace's .pic/uploads: %s", strerror(errno));
}
if (pic >= 0) {
close(pic);
}
if (ws >= 0) {
close(ws);
}
return up;
}
/* Whether NAME may be an uploaded file's name: one path component, no leading dot, no control
* characters, text pic shows as it is, 1 to RMT_UPLOAD_NAME bytes. */
static int rmt_upload_name_ok(const char *name) {
char clean[RMT_UPLOAD_NAME + 1];
size_t n = strlen(name);
if (n == 0 || n > RMT_UPLOAD_NAME || name[0] == '.' || strchr(name, '/') || strchr(name, '\\')) {
return 0;
}
for (size_t i = 0; i < n; i++) {
if ((unsigned char)name[i] < 0x20 || name[i] == 0x7f) {
return 0;
}
}
memcpy(clean, name, n + 1);
rmt_name_clean(clean);
return strcmp(clean, name) == 0;
}
/* FD's bytes (at most RMT_UPLOAD_MAX) hashed into HEX (65 bytes). 0, or -1. */
static int rmt_upload_sha(int fd, char hex[65]) {
struct stat sb;
unsigned char *buf, sum[32];
size_t at = 0;
if (fstat(fd, &sb) != 0 || sb.st_size > RMT_UPLOAD_MAX || !(buf = malloc((size_t)sb.st_size + 1))) {
return -1;
}
while (at < (size_t)sb.st_size) {
ssize_t r = pread(fd, buf + at, (size_t)sb.st_size - at, (off_t)at);
if (r < 0 && errno == EINTR) {
continue;
}
if (r <= 0) {
free(buf);
return -1;
}
at += (size_t)r;
}
pic_noise_sha256(sum, buf, at, NULL, 0);
free(buf);
rmt_hex(sum, 32, hex);
return 0;
}
typedef struct {
rmt_upfile *f;
char id[48], name[RMT_UPLOAD_NAME + 1], sha[65];
long long size;
char *data; /* a chunk's base64 */
char path[256]; /* found: the file, relative to the workspace */
int ok;
} rmt_upjob;
static void rmt_upjob_drop(void *p) {
rmt_upjob *u = p;
if (u) {
free(u->data);
}
free(u);
}
static void rmt_upfile_close(rmt_upfile *f, int unlink_part) {
if (f->fd >= 0) {
close(f->fd);
f->fd = -1;
}
if (unlink_part && f->dirfd >= 0 && f->part[0]) {
(void)unlinkat(f->dirfd, f->part, 0);
}
if (f->dirfd >= 0) {
close(f->dirfd);
f->dirfd = -1;
}
}
/* upload_begin, on the lane: the part file made, and part files a day old (given up when pic remote
* stopped) removed. */
static void rmt_upbegin_run(rmt_job *jb) {
rmt_upjob *u = jb->ctx;
rmt_upfile *f = u->f;
if ((f->dirfd = rmt_uploads_dir(jb->j->workspace, f->why, sizeof f->why)) < 0) {
return;
}
{ /* bounded: at most 256 entries looked at */
int again = dup(f->dirfd);
DIR *dir = again >= 0 ? fdopendir(again) : NULL;
struct dirent *de;
time_t old = time(NULL) - 86400;
for (int k = 0; dir && k < 256 && (de = readdir(dir)); k++) {
struct stat sb;
if (strncmp(de->d_name, ".part-", 6) == 0 && fstatat(f->dirfd, de->d_name, &sb, AT_SYMLINK_NOFOLLOW) == 0 &&
sb.st_mtime < old) {
(void)unlinkat(f->dirfd, de->d_name, 0);
}
}
if (dir) {
closedir(dir);
} else if (again >= 0) {
close(again);
}
}
(void)snprintf(f->part, sizeof f->part, ".part-%s-%s", jb->idb, u->id);
(void)unlinkat(f->dirfd, f->part, 0); /* the same upload begun again */
if ((f->fd = openat(f->dirfd, f->part, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600)) < 0) { /* read back at the end */
(void)snprintf(f->why, sizeof f->why, "cannot make the file: %s", strerror(errno));
return;
}
u->ok = 1;
}
/* upload_chunk, on the lane: its bytes appended. */
static void rmt_upchunk_run(rmt_job *jb) {
rmt_upjob *u = jb->ctx;
rmt_upfile *f = u->f;
size_t n = strlen(u->data), got, at = 0;
unsigned char *bytes;
if (f->why[0] || f->fd < 0) {
return;
}
if (!(bytes = malloc(3 * (n / 4) + 3)) || (got = pic_base64_decode(u->data, n, bytes)) == (size_t)-1 || got > RMT_UPLOAD_CHUNK ||
f->written + (long long)got > u->size) {
(void)snprintf(f->why, sizeof f->why, "a chunk is not base64 of at most %u bytes within the size", RMT_UPLOAD_CHUNK);
free(bytes);
return;
}
while (at < got) {
ssize_t w = write(f->fd, bytes + at, got - at);
if (w < 0 && errno == EINTR) {
continue;
}
if (w <= 0) {
(void)snprintf(f->why, sizeof f->why, "cannot write the file: %s", strerror(errno));
break;
}
at += (size_t)w;
}
f->written += (long long)at;
free(bytes);
}
/* NAME's form K: NAME itself, then NAME-2.EXT and on. */
static void rmt_upload_variant(const char *name, int k, char *out, size_t cap) {
const char *dot = strrchr(name, '.');
if (k == 1) {
(void)snprintf(out, cap, "%s", name);
} else if (dot && dot != name) {
(void)snprintf(out, cap, "%.*s-%d%s", (int)(dot - name), name, k, dot);
} else {
(void)snprintf(out, cap, "%s-%d", name, k);
}
}
/* upload_end, on the lane: the size and sha256 checked against the bytes on disk, the file synced
* and linked to its name, the directory synced; then the part file goes. */
static void rmt_upend_run(rmt_job *jb) {
rmt_upjob *u = jb->ctx;
rmt_upfile *f = u->f;
char sha[65];
if (!f->why[0] && f->written != u->size) {
(void)snprintf(f->why, sizeof f->why, "%lld bytes came, not %lld", f->written, u->size);
}
if (!f->why[0] && (f->fd < 0 || fsync(f->fd) != 0 || rmt_upload_sha(f->fd, sha) != 0)) {
(void)snprintf(f->why, sizeof f->why, "cannot read the file back: %s", strerror(errno));
}
if (!f->why[0] && strcmp(sha, u->sha) != 0) {
(void)snprintf(f->why, sizeof f->why, "the sha256 is not the file's");
}
for (int k = 1; !f->why[0] && k < 100; k++) {
char cand[RMT_UPLOAD_NAME + 16], other[65];
int ofd;
rmt_upload_variant(u->name, k, cand, sizeof cand);
if (linkat(f->dirfd, f->part, f->dirfd, cand, 0) == 0) { /* never over another file */
(void)fsync(f->dirfd);
(void)snprintf(u->path, sizeof u->path, ".pic/uploads/%s", cand);
break;
}
if (errno != EEXIST) {
(void)snprintf(f->why, sizeof f->why, "cannot name the file: %s", strerror(errno));
break;
}
if ((ofd = openat(f->dirfd, cand, O_RDONLY | O_NOFOLLOW | O_CLOEXEC)) >= 0) { /* the same bytes: that file */
int same = rmt_upload_sha(ofd, other) == 0 && strcmp(other, sha) == 0;
close(ofd);
if (same) {
(void)snprintf(u->path, sizeof u->path, ".pic/uploads/%s", cand);
break;
}
}
}
if (!f->why[0] && !u->path[0]) {
(void)snprintf(f->why, sizeof f->why, "too many files named %s", u->name);
}
rmt_upfile_close(f, 1);
u->ok = !f->why[0];
}
static void rmt_upabort_run(rmt_job *jb) { rmt_upfile_close(((rmt_upjob *)jb->ctx)->f, 1); }
/* The upload ID of D, or -1. */
static int rmt_upload_find(const rmt_dev *d, const char *id) {
for (int i = 0; i < d->nuploads; i++) {
if (strcmp(d->uploads[i].id, id) == 0) {
return i;
}
}
return -1;
}
static void rmt_upfile_free_done(rmt_state *st, rmt_job *jb) {
rmt_upjob *u = jb->ctx;
(void)st;
free(u->f); /* its last job: nothing else holds it */
u->f = NULL;
}
/* D's upload I let go of: its slot freed now; with ABORT, its part file closed and removed by a
* job queued behind its chunks, which frees the file state. */
static void rmt_upload_forget(rmt_state *st, rmt_dev *d, int i, int abort) {
rmt_upload *up = &d->uploads[i];
if (abort && up->f) {
rmt_upjob *u = calloc(1, sizeof *u);
if (u) {
u->f = up->f;
(void)snprintf(u->id, sizeof u->id, "%s", up->id);
rmt_job_add(st, rmt_job_new(st, st->js[up->jx], d, rmt_upabort_run, rmt_upfile_free_done, rmt_upjob_drop, u,
"giving up a file from a phone"));
}
}
d->uploads[i] = d->uploads[--d->nuploads];
}
static void rmt_upload_error(rmt_state *st, rmt_dev *d, const char *id, const char *code, const char *why) {
rmt_error(st, d, id, code, why);
}
static void rmt_upbegin_done(rmt_state *st, rmt_job *jb) {
rmt_upjob *u = jb->ctx;
rmt_dev *d = rmt_job_dev(st, jb);
int i;
if (u->ok || !d) {
return;
}
rmt_upload_error(st, d, u->id, "failed", u->f->why);
if ((i = rmt_upload_find(d, u->id)) >= 0 && d->uploads[i].f == u->f) {
rmt_upload_forget(st, d, i, 1);
}
}
static void rmt_upend_done(rmt_state *st, rmt_job *jb) {
rmt_upjob *u = jb->ctx;
rmt_dev *d = rmt_job_dev(st, jb);
if (d && u->ok) {
(void)snprintf(d->upsaid[d->upsaid_at % 8].id, sizeof d->upsaid[0].id, "%s", u->id);
(void)snprintf(d->upsaid[d->upsaid_at++ % 8].path, sizeof d->upsaid[0].path, "%s", u->path);
rmt_send_free(st, d, rmt_q("SELECT json_object('type', 'uploaded', 'payload', json_object('id', ?1, 'path', ?2))", 2, u->id,
u->path));
} else if (d) {
rmt_upload_error(st, d, u->id, "bad_upload", u->f->why);
}
free(u->f);
u->f = NULL;
}
/* upload_begin, upload_chunk and upload_end from D (TYPE), on the loop: checked, and a job queued
* on the workspace's lane. */
static void rmt_upload_msg(rmt_state *st, rmt_dev *d, const rmt_env *e) {
const char *t = e->type;
char *id = e->payload ? rmt_q("SELECT CASE json_type(?1, '$.id') WHEN 'text' THEN json_extract(?1, '$.id') END", 1, e->payload) : NULL;
long long now = rmt_mono_ms();
rmt_upjob *u = NULL;
int i;
if (!id || !rmt_key_ok(id)) {
rmt_error(st, d, NULL, "bad_message", "an upload's id is 16 to 43 characters of A-Z, a-z, 0-9, _ and -");
free(id);
return;
}
i = rmt_upload_find(d, id);
if (strcmp(t, "upload_begin") == 0) {
char *name = rmt_q("SELECT CASE json_type(?1, '$.name') WHEN 'text' THEN json_extract(?1, '$.name') END", 1, e->payload);
char *size = rmt_q("SELECT CASE json_type(?1, '$.size') WHEN 'integer' THEN json_extract(?1, '$.size') END", 1, e->payload);
char conv[64];
int jx = -1;
long long n = size ? atoll(size) : -1;
if (e->session && e->session[0] == '+') {
for (int k = 0; k < st->njs; k++) {
jx = st->js[k]->open && strcmp(st->js[k]->path, e->session + 1) == 0 ? k : jx;
}
} else if (rmt_resolve(st, e->session, &jx, conv) != 0) {
jx = -1;
}
if (now - d->up_since > 86400000LL) { /* a day's quota, from the first upload of it */
d->up_since = now;
d->up_quota = 0;
}
if (!name || !rmt_upload_name_ok(name)) {
rmt_upload_error(st, d, id, "bad_message", "a file's name is one path component, no leading dot, 1 to 128 bytes of text");
} else if (n < 0) {
rmt_upload_error(st, d, id, "bad_message", "upload_begin carries the file's size");
} else if (n > RMT_UPLOAD_MAX) {
rmt_upload_error(st, d, id, "too_large", "a file from a phone is at most 25 MiB");
} else if (jx < 0) {
rmt_upload_error(st, d, id, "no_session", "no such workspace");
} else if (i >= 0 || d->nuploads >= RMT_UPLOADS_OPEN || d->up_quota + n > RMT_UPLOAD_QUOTA) {
rmt_upload_error(st, d, id, "quota", i >= 0 ? "that upload is open already" : d->nuploads >= RMT_UPLOADS_OPEN
? "at most 4 files go up at once from a phone"
: "a phone sends at most 256 MiB of files a day");
} else if ((u = calloc(1, sizeof *u)) && (u->f = calloc(1, sizeof *u->f))) {
rmt_upload *up = &d->uploads[d->nuploads++];
rmt_job *jb;
memset(up, 0, sizeof *up);
u->f->fd = u->f->dirfd = -1;
(void)snprintf(up->id, sizeof up->id, "%s", id);
(void)snprintf(up->name, sizeof up->name, "%s", name);
up->jx = jx;
up->size = n;
up->last_ms = now;
up->f = u->f;
d->up_quota += n;
(void)snprintf(u->id, sizeof u->id, "%s", id);
(void)snprintf(u->name, sizeof u->name, "%s", name);
u->size = n;
jb = rmt_job_new(st, st->js[jx], d, rmt_upbegin_run, rmt_upbegin_done, rmt_upjob_drop, u, "receiving a file from a phone");
u = NULL;
rmt_job_add(st, jb);
}
if (u) {
free(u->f);
rmt_upjob_drop(u);
}
free(name);
free(size);
} else if (i < 0) {
int said = -1;
for (int k = 0; k < 8 && strcmp(t, "upload_end") == 0; k++) { /* a repeat of a finished one: the same answer */
said = strcmp(d->upsaid[k].id, id) == 0 ? k : said;
}
if (said >= 0) {
rmt_send_free(st, d, rmt_q("SELECT json_object('type', 'uploaded', 'payload', json_object('id', ?1, 'path', ?2))", 2, id,
d->upsaid[said].path));
} else {
rmt_upload_error(st, d, id, "bad_upload", "no such upload: begin it again");
}
} else if (strcmp(t, "upload_chunk") == 0) {
rmt_upload *up = &d->uploads[i];
char *n = rmt_q("SELECT CASE json_type(?1, '$.n') WHEN 'integer' THEN json_extract(?1, '$.n') END", 1, e->payload);
char *data = rmt_q("SELECT CASE json_type(?1, '$.data') WHEN 'text' THEN json_extract(?1, '$.data') END", 1, e->payload);
if (!n || !data || atoll(n) != up->next_n) { /* in order, each once: anything else ends the upload */
rmt_upload_error(st, d, id, "bad_upload", "chunks go in order from 0, each once, with base64 data");
rmt_upload_forget(st, d, i, 1);
free(data);
} else if ((u = calloc(1, sizeof *u))) {
up->next_n++;
up->last_ms = now;
u->f = up->f;
u->size = up->size;
u->data = data;
(void)snprintf(u->id, sizeof u->id, "%s", id);
rmt_job_add(st, rmt_job_new(st, st->js[up->jx], d, rmt_upchunk_run, NULL, rmt_upjob_drop, u, "receiving a file from a phone"));
} else {
free(data);
}
free(n);
} else { /* upload_end */
rmt_upload *up = &d->uploads[i];
char *sha = rmt_q("SELECT CASE json_type(?1, '$.sha256') WHEN 'text' THEN lower(json_extract(?1, '$.sha256')) END", 1, e->payload);
if (!sha || strlen(sha) != 64) {
rmt_upload_error(st, d, id, "bad_upload", "upload_end carries the file's sha256 in hex");
rmt_upload_forget(st, d, i, 1);
} else if ((u = calloc(1, sizeof *u))) {
int jx = up->jx;
u->f = up->f;
u->size = up->size;
(void)snprintf(u->id, sizeof u->id, "%s", id);
(void)snprintf(u->sha, sizeof u->sha, "%s", sha);
/* the name, kept with the slot until now */
(void)snprintf(u->name, sizeof u->name, "%s", up->name);
rmt_upload_forget(st, d, i, 0); /* no more jobs for it: the end job frees its state */
rmt_job_add(st, rmt_job_new(st, st->js[jx], d, rmt_upend_run, rmt_upend_done, rmt_upjob_drop, u, "receiving a file from a phone"));
}
free(sha);
}
free(id);
}
/* Each tick: uploads of D silent too long are given up. */
static void rmt_uploads_tick(rmt_state *st, rmt_dev *d) {
long long now = rmt_mono_ms();
for (int i = 0; i < d->nuploads; i++) {
if (now - d->uploads[i].last_ms > RMT_UPLOAD_IDLE_MS) {
rmt_upload_forget(st, d, i--, 1);
}
}
}
static void rmt_message(rmt_state *st, int si, const char *json) {
rmt_sess *s = &st->sess[si];
rmt_dev *d = &st->devs[s->dev];
rmt_env e;
if (!s->confirmed) { /* the first message that verifies confirms the session */
s->confirmed = 1;
for (int i = 0; i < RMT_SESSIONS; i++) { /* and replaces the device's earlier ones */
if (i != si && st->sess[i].used && st->sess[i].dev == s->dev) {
free(st->sess[i].msg.buf);
memset(&st->sess[i], 0, sizeof st->sess[i]);
}
}
d->sess = si;
d->visible = 0; /* until its presence says */
rmt_unfollow(st, d); /* the phone sends sync and sessions again in a new session */
d->want_list = 0;
free(d->list_sent);
d->list_sent = NULL;
rmt_seen(st, d);
d->want_devices = 0;
if (st->offer && st->offer_dev == s->dev && st->offer->stage == OFFER_ASKING) {
rmt_offer_tell(st); /* still waiting for this phone's answer */
}
rmt_asks_open(st, d); /* the questions waiting now, whatever an earlier session was told */
d->seen_wr_ms = rmt_mono_ms();
} else if (rmt_mono_ms() - d->seen_wr_ms >= rmt_seen_every_ms()) { /* connected all along: seen now */
rmt_seen(st, d);
d->seen_wr_ms = rmt_mono_ms();
}
if (rmt_env_parse(json, &e) != 0) {
rmt_error(st, d, NULL, "bad_message", "not an envelope message");
return;
}
{
char what[160];
(void)snprintf(what, sizeof what, "%s's %s%s%s", d->d.name, e.type, e.ptype[0] ? " " : "", e.ptype);
rmt_doing("taking", what); /* a job answers what reads a journal */
}
if (strcmp(e.type, "sessions") == 0) {
char *w = e.payload ? rmt_q("SELECT CASE json_type(?1, '$.workspace') WHEN 'text' THEN json_extract(?1, '$.workspace') END",
1, e.payload)
: NULL;
int archived = e.payload && rmt_q_bool("SELECT json_type(?1, '$.archived') = 'true'", e.payload);
int trash = e.payload && rmt_q_bool("SELECT json_type(?1, '$.trash') = 'true'", e.payload);
if (w) { /* one workspace's conversations, once */
int jx = -1;
for (int i = 0; i < st->njs && jx < 0; i++) {
jx = st->js[i]->open && strcmp(st->js[i]->path, w) == 0 ? i : -1;
}
if (jx < 0) {
rmt_error(st, d, NULL, "no_session", "no such workspace");
} else {
rmt_listjob *l = calloc(1, sizeof *l);
rmt_job *jb;
if (l) {
l->archived = archived;
l->trash = trash;
}
jb = l ? rmt_job_new(st, st->js[jx], d, rmt_listjob_run, rmt_listjob_done, rmt_listjob_drop, l,
"listing a workspace's conversations")
: NULL;
if (jb) {
(void)snprintf(jb->answering, sizeof jb->answering, "sessions");
}
rmt_job_add(st, jb);
}
free(w);
} else {
d->want_list = 1;
d->list_archived = archived;
d->list_trash = trash;
d->want_list_ms = rmt_mono_ms();
free(d->list_sent);
d->list_sent = NULL;
for (int i = 0; i < st->njs; i++) { /* each part looked at again before the first list */
st->js[i]->list_ready = 0;
st->js[i]->list_gen++;
}
}
} else if (strcmp(e.type, "sync") == 0) {
int jx;
char conv[64], err[256];
if (e.key[0] && !rmt_key_ok(e.key)) {
rmt_error(st, d, NULL, "bad_message", "a sync's key is 16 to 43 characters of A-Z, a-z, 0-9, _ and -");
} else if (rmt_resolve(st, e.session, &jx, conv) != 0) {
rmt_error(st, d, NULL, "no_session", "no such conversation");
} else {
rmt_syncjob *y = calloc(1, sizeof *y);
rmt_job *jb;
for (rmt_job *o = st->held, *next; o; o = next) { /* a sync still queued is replaced too, unread */
next = o->held;
if (o->run == rmt_syncjob_run && memcmp(o->dev, d->d.id, 16) == 0 && rmt_job_unqueue(st, o)) {
rmt_job_unhold(st, o);
rmt_job_free(o);
}
}
rmt_unfollow(st, d); /* a new sync replaces the one before */
(void)snprintf(d->skey, sizeof d->skey, "%s", e.key);
d->jx = jx;
(void)snprintf(d->conv, sizeof d->conv, "%s", conv);
d->wsess = strdup(e.session);
if (y) {
(void)snprintf(y->conv, sizeof y->conv, "%s", conv);
y->seq = e.has_seq ? e.seq : -1;
y->gen = d->fgen;
}
jb = y ? rmt_job_new(st, st->js[jx], d, rmt_syncjob_run, rmt_syncjob_done, rmt_syncjob_drop, y, "starting a follow")
: NULL;
if (jb) {
jb->budget_ms = RMT_MESSAGE_MS;
(void)snprintf(jb->answering, sizeof jb->answering, "sync");
} else {
(void)snprintf(err, sizeof err, "out of memory");
rmt_error(st, d, NULL, "unavailable", err);
}
rmt_job_add(st, jb);
}
} else if (strcmp(e.type, "command") == 0) {
rmt_command(st, d, &e);
} else if (strcmp(e.type, "image") == 0) {
char conv[64];
int jx;
rmt_imagejob *m = calloc(1, sizeof *m);
if (m && rmt_resolve(st, e.session, &jx, conv) == 0) {
rmt_job *jb;
m->e = e;
e.session = e.payload = NULL;
(void)snprintf(m->conv, sizeof m->conv, "%s", conv);
if ((jb = rmt_job_new(st, st->js[jx], d, rmt_imagejob_run, rmt_done_reply, rmt_imagejob_drop, m, "reading an image"))) {
(void)snprintf(jb->answering, sizeof jb->answering, "image");
}
rmt_job_add(st, jb);
} else { /* no journal to read: answered here */
rmt_job none;
memset(&none, 0, sizeof none);
rmt_image(&none, NULL, &e, "");
for (int k = 0; k < none.out.n; k++) {
(void)rmt_send(st, d, none.out.v[k]);
}
rmt_lines_free(&none.out);
free(m);
}
} else if (strcmp(e.type, "repair") == 0) {
rmt_repair(st, d, &e);
} else if (strcmp(e.type, "ping") == 0) {
rmt_send_free(st, d, strdup("{\"type\":\"pong\"}"));
} else if (strcmp(e.type, "unpair") == 0) {
rmt_env_free(&e);
rmt_unpair_device(st, s->dev, 0);
return;
} else if (strcmp(e.type, "presence") == 0) {
char *v = e.payload ? rmt_q("SELECT json_type(?1, '$.visible')", 1, e.payload) : NULL;
d->visible = v && strcmp(v, "true") == 0;
free(v);
} else if (strcmp(e.type, "push") == 0) {
rmt_push_set(st, d, e.payload);
} else if (strcmp(e.type, "pair_offer") == 0) {
rmt_offer_ask(st, s->dev);
} else if (strcmp(e.type, "pair_approve") == 0 || strcmp(e.type, "pair_deny") == 0) {
char *code = strcmp(e.type, "pair_approve") != 0 ? NULL
: e.payload ? rmt_q("SELECT CASE json_type(?1, '$.code') WHEN 'text' THEN json_extract(?1, '$.code') END", 1,
e.payload)
: NULL;
rmt_offer_answer(st, s->dev, strcmp(e.type, "pair_approve") == 0, code ? code : "");
free(code);
} else if (strcmp(e.type, "devices") == 0) {
d->want_devices = 1;
rmt_send_free(st, d, rmt_devices_json(st, s->dev));
} else if (strcmp(e.type, "unpair_device") == 0) {
char *id = e.payload ? rmt_q("SELECT CASE json_type(?1, '$.device') WHEN 'text' THEN json_extract(?1, '$.device') END", 1,
e.payload)
: NULL;
unsigned char raw[32];
int di = -1, self = 0;
if (id && pic_b64u_dec(id, strlen(id), raw, sizeof raw) == 16) {
for (int i = 0; i < st->ndevs && di < 0; i++) {
di = st->devs[i].alive && memcmp(st->devs[i].d.id, raw, 16) == 0 ? i : -1;
}
}
free(id);
if (di < 0) {
rmt_error(st, d, NULL, "no_device", "no such paired device");
} else {
self = di == s->dev;
rmt_log(stdout, "pic remote: %s unpaired %s\n", d->d.name, st->devs[di].d.name);
(void)fflush(stdout);
rmt_unpair_device(st, di, 1); /* the list goes to the phones once its row is gone (rmt_unpaired_done) */
if (self) { /* its session is gone with it */
rmt_env_free(&e);
return;
}
}
} else if (strcmp(e.type, "upload_begin") == 0 || strcmp(e.type, "upload_chunk") == 0 || strcmp(e.type, "upload_end") == 0) {
rmt_upload_msg(st, d, &e);
} else if (strcmp(e.type, "rename_device") == 0) {
rmt_rename(st, d, &e);
} else if (strcmp(e.type, "unpair_all") == 0) {
rmt_log(stdout, "pic remote: %s unpaired every device\n", d->d.name);
(void)fflush(stdout);
rmt_env_free(&e);
for (int i = 0; i < st->ndevs; i++) {
if (st->devs[i].alive) {
rmt_unpair_device(st, i, 1);
}
}
return;
} else if (strcmp(e.type, "fetch") == 0) {
rmt_fetch(st, d, &e);
} else if (strcmp(e.type, "pair_ready") == 0) {
} else {
rmt_error(st, d, NULL, "unknown_type", e.type);
}
rmt_env_free(&e);
}
/* ---- records from the relay ----------------------------------------------------------------- */
static int rmt_dev_by_channel(rmt_state *st, const unsigned char ch[16]) {
for (int i = 0; i < st->ndevs; i++) {
if (st->devs[i].alive && memcmp(st->devs[i].d.channel, ch, 16) == 0) {
return i;
}
}
return -1;
}
/* Message 1 of a session: the static key it carries must be a device in the table, and that
* device's channel the channel it came on; otherwise it is dropped without an answer. */
static int rmt_devices_sync(rmt_state *st, int quiet);
/* The device of channel CH, or -1 (rmt_record keeps a record on an unknown channel until the
* devices are read again). */
static int rmt_dev_for_record(rmt_state *st, const unsigned char ch[16]) { return rmt_dev_by_channel(st, ch); }
static void rmt_handshake(rmt_state *st, const unsigned char ch[16], const unsigned char *rec, size_t n) {
int di = rmt_dev_for_record(st, ch), slot = -1, unconfirmed = 0;
unsigned char prologue[41], pl[512], m2[256], out[300], up[32], down[32];
size_t pn, mn;
pic_noise_hs hs;
if (di < 0 || n < 9) {
return;
}
for (int i = 0; i < RMT_SESSIONS; i++) {
rmt_sess *s = &st->sess[i];
if (s->used && memcmp(s->ch, ch, 16) == 0 && memcmp(s->t.sid, rec + 1, 8) == 0) {
if (s->confirmed) {
return; /* a replayed message 1 of a live session: nothing to gain */
}
slot = i; /* the same handshake again: answered afresh */
}
}
rmt_prologue(st->k.mailbox, ch, prologue);
pic_noise_hs_init(&hs, 0, &st->k.stat, NULL, NULL, prologue, sizeof prologue);
if (pic_noise_read1(&hs, rec + 9, n - 9, pl, sizeof pl, &pn) != 0 || !rmt_same(hs.rs, st->devs[di].d.stat, PIC_NOISE_PUB)) {
pic_noise_hs_wipe(&hs);
return;
}
if (pic_noise_write2(&hs, "{\"v\":1}", 7, m2, sizeof m2, &mn) != 0 || pic_noise_split(&hs, up, down) != 0) {
pic_cred_wipe(up, sizeof up);
pic_cred_wipe(down, sizeof down);
pic_noise_hs_wipe(&hs);
return;
}
for (int i = 0; i < RMT_SESSIONS; i++) { /* at most two unconfirmed sessions a channel */
if (i != slot && st->sess[i].used && !st->sess[i].confirmed && memcmp(st->sess[i].ch, ch, 16) == 0 && ++unconfirmed >= 2) {
free(st->sess[i].msg.buf);
memset(&st->sess[i], 0, sizeof st->sess[i]);
}
}
for (int i = 0; slot < 0 && i < RMT_SESSIONS; i++) {
if (!st->sess[i].used) {
slot = i;
}
}
if (slot < 0) {
pic_cred_wipe(up, sizeof up);
pic_cred_wipe(down, sizeof down);
pic_noise_hs_wipe(&hs);
return;
}
{
rmt_sess *s = &st->sess[slot];
free(s->msg.buf);
memset(s, 0, sizeof *s);
s->used = 1;
s->dev = di;
memcpy(s->ch, ch, 16);
pic_noise_transport_init(&s->t, 0, rec + 1, up, down);
pic_cred_wipe(up, sizeof up);
pic_cred_wipe(down, sizeof down);
s->started_ms = s->heard_ms = rmt_mono_ms();
}
pic_noise_hs_wipe(&hs);
(void)rmt_lane_add(&st->devs[di].lane, out, pic_noise_head(PIC_NOISE_REC_M2, rec + 1, m2, mn, out));
}
/* A record on CH, which no device has: kept, and the devices read again at once (a phone paired a
* moment ago, by /rc or pic remote pair in another process, is answered then rather than dropped
* and asked again). The oldest goes when too many wait. */
static void rmt_stash(rmt_state *st, const unsigned char ch[16], const unsigned char *rec, size_t n) {
unsigned char *copy = malloc(n);
if (!copy) {
return;
}
memcpy(copy, rec, n);
if (st->nstash == RMT_STASH) {
free(st->stash[0].rec);
memmove(&st->stash[0], &st->stash[1], (RMT_STASH - 1) * sizeof st->stash[0]);
st->nstash--;
}
memcpy(st->stash[st->nstash].ch, ch, 16);
st->stash[st->nstash].rec = copy;
st->stash[st->nstash++].n = n;
st->user_force = 1;
if (rmt_tally_due(&st->kept_unknown)) {
char id[24];
pic_b64u_enc(ch, 16, id);
rmt_log(stdout, "pic remote: kept a record on channel %s, which no paired device has, until the devices are read again"
" (%lld so far)\n", id, st->kept_unknown.n);
}
}
static void rmt_record_on(rmt_state *st, const unsigned char ch[16], const unsigned char *rec, size_t n, int kept);
static void rmt_record(rmt_state *st, const unsigned char ch[16], const unsigned char *rec, size_t n) {
rmt_record_on(st, ch, rec, n, 0);
}
/* The records kept for unknown channels, now that the devices were read again. */
static void rmt_stash_replay(rmt_state *st) {
int n = st->nstash;
rmt_stashed kept[RMT_STASH];
memcpy(kept, st->stash, (size_t)n * sizeof kept[0]);
st->nstash = 0;
for (int i = 0; i < n; i++) {
rmt_record_on(st, kept[i].ch, kept[i].rec, kept[i].n, 1);
free(kept[i].rec);
}
}
/* KEPT: a record kept for its unknown channel, given again; one still unknown is dropped. */
static void rmt_record_on(rmt_state *st, const unsigned char ch[16], const unsigned char *rec, size_t n, int kept) {
int di;
if (n < 9) {
return;
}
if (!kept && rmt_dev_by_channel(st, ch) < 0 && (rec[0] == PIC_NOISE_REC_M1 || rec[0] == PIC_NOISE_REC_DATA)) {
rmt_stash(st, ch, rec, n);
return;
}
if (rec[0] == PIC_NOISE_REC_M1) {
rmt_handshake(st, ch, rec, n);
return;
}
if (rec[0] != PIC_NOISE_REC_DATA) {
return;
}
if ((di = rmt_dev_for_record(st, ch)) < 0) {
if (rmt_tally_due(&st->dropped_unknown)) {
char id[24];
pic_b64u_enc(ch, 16, id);
rmt_log(stdout, "pic remote: dropped a record on channel %s, which no paired device has (%lld so far)\n", id,
st->dropped_unknown.n);
}
return;
}
for (int i = 0; i < RMT_SESSIONS; i++) {
rmt_sess *s = &st->sess[i];
unsigned char data[PIC_NOISE_CHUNK];
size_t dn;
int flag, gap, whole;
if (!s->used || memcmp(s->ch, ch, 16) != 0 || memcmp(s->t.sid, rec + 1, 8) != 0) {
continue;
}
if (pic_noise_open_record(&s->t, rec, n, &flag, data, &dn, &gap) != 0) {
/* Dropped, nothing changed. A counter already used is a replay or a duplicate, which
* says nothing against the session. On an unconfirmed session it may be the phone's
* live session after a replayed message 1 (the relay holds records a minute, so a pic
* remote started again reads the phone's last handshake): a reset, at most one a
* second, lets the phone make a new one instead of waiting out this one. A confirmed
* session whose records keep failing is reset too, or the phone would wait on it. */
long long now = rmt_mono_ms();
unsigned long long c = 0;
unsigned char out[16];
for (size_t k = 1 + PIC_NOISE_SID; k < 1 + PIC_NOISE_SID + 8 && k < n; k++) {
c = (c << 8) | rec[k];
}
if (n >= 1 + PIC_NOISE_SID + 8 && s->t.last >= 0 && c <= (unsigned long long)s->t.last) {
if (rmt_tally_due(&st->dropped_again)) {
rmt_log(stdout, "pic remote: dropped a record %s sent before (%lld so far)\n", st->devs[di].d.name,
st->dropped_again.n);
}
return;
}
if (s->confirmed || now - s->reset_ms >= 1000) {
char sid[17];
rmt_hex(s->t.sid, PIC_NOISE_SID, sid);
rmt_log(stdout,
"pic remote: dropped a record from %s that did not open (%d in a row): session %.8s, %s, counter %llu"
" after %lld, last heard %lld s ago\n",
st->devs[di].d.name, s->confirmed ? s->fails + 1 : 1, sid, s->confirmed ? "confirmed" : "unconfirmed", c,
(long long)s->t.last, (now - s->heard_ms) / 1000);
}
if (s->confirmed && ++s->fails >= RMT_OPEN_FAILS) {
rmt_log(stdout, "pic remote: reset %s's session: %d records in a row did not open\n", st->devs[di].d.name,
s->fails);
(void)rmt_lane_add(&st->devs[di].lane, out, pic_noise_head(PIC_NOISE_REC_RESET, rec + 1, NULL, 0, out));
if (st->devs[di].sess == i) {
st->devs[di].sess = -1;
}
free(s->msg.buf);
memset(s, 0, sizeof *s);
} else if (!s->confirmed && now - s->reset_ms >= 1000) {
rmt_log(stdout, "pic remote: reset a new session of %s: a record did not open\n", st->devs[di].d.name);
s->reset_ms = now;
(void)rmt_lane_add(&st->devs[di].lane, out, pic_noise_head(PIC_NOISE_REC_RESET, rec + 1, NULL, 0, out));
}
return;
}
s->fails = 0;
s->heard_ms = rmt_mono_ms();
whole = rmt_sess_take(s, flag, data, dn, gap);
if (whole == 1) {
char *json = malloc(s->msg.len + 1);
if (json) {
memcpy(json, s->msg.buf, s->msg.len);
json[s->msg.len] = '\0';
}
s->msg.len = 0;
if (json) {
rmt_message(st, i, json);
}
free(json);
}
return;
}
{ /* a session pic does not have: a reset, which can cause only a new handshake */
unsigned char out[16];
if (rmt_tally_due(&st->reset_unknown)) {
rmt_log(stdout, "pic remote: reset a session of %s that this pic remote does not have (%lld so far)\n",
st->devs[di].d.name, st->reset_unknown.n);
}
(void)rmt_lane_add(&st->devs[di].lane, out, pic_noise_head(PIC_NOISE_REC_RESET, rec + 1, NULL, 0, out));
}
}
/* ---- devices coming and going ---------------------------------------------------------------- */
static void rmt_offer_closing(rmt_state *st);
static int rmt_devices_sync(rmt_state *st, int quiet);
/* An unpaired device's row deleted: its channel at the relay goes, and the device list to every phone
* that asked for it, now that the list answers after the commit. */
static void rmt_unpaired_done(rmt_state *st, rmt_job *jb) {
rmt_delete_channel(&st->r, ((rmt_rowjob *)jb->ctx)->d.channel);
rmt_devices_tell(st);
}
static void rmt_unpair_device(rmt_state *st, int di, int tell) {
rmt_dev *d = &st->devs[di];
if (tell && d->sess >= 0) {
rmt_send_free(st, d, strdup("{\"type\":\"unpaired\"}"));
(void)rmt_lane_flush(&st->r, &d->lane);
}
for (int i = 0; i < RMT_SESSIONS; i++) {
if (st->sess[i].used && st->sess[i].dev == di) {
free(st->sess[i].msg.buf);
memset(&st->sess[i], 0, sizeof st->sess[i]);
}
}
d->sess = -1;
if (st->offer && st->offer_dev == di && st->offer->stage != OFFER_OVER) { /* its offer has no one to answer it */
rmt_offer_refuse(st->offer, &st->r);
rmt_offer_closing(st);
}
if (d->alive) { /* the row first, the revocation; its channel at the relay once it is gone */
rmt_job *jb = rmt_row_job(st, NULL, RMT_ROW_DELETE, &d->d, rmt_unpaired_done, "deleting an unpaired phone's row");
if (jb) {
rmt_job_add(st, jb);
} else {
rmt_delete_channel(&st->r, d->d.channel);
}
} else { /* deleted at the terminal already */
rmt_delete_channel(&st->r, d->d.channel);
}
while (d->nuploads) {
rmt_upload_forget(st, d, 0, 1);
}
d->alive = 0;
rmt_names_changed(st);
rmt_unfollow(st, d);
d->lane.qlen = 0;
d->lane.inflight = 0;
d->lane.epoch++;
}
/* ---- renaming a device (#111) ---------------------------------------------------------------- */
/* The device list to every phone in a session, as after a pairing. */
static void rmt_devices_tell_all(rmt_state *st) {
for (int i = 0; i < st->ndevs; i++) {
if (st->devs[i].alive && st->devs[i].sess >= 0) {
rmt_send_free(st, &st->devs[i], rmt_devices_json(st, i));
}
}
}
/* The device's row, written with its new name: the name in memory too, and every phone told. */
static void rmt_renamed(rmt_state *st, rmt_job *jb) {
rmt_rowjob *r = jb->ctx;
rmt_dev *by = rmt_job_dev(st, jb);
if (r->rc != 0) {
if (by) {
rmt_error(st, by, NULL, "failed", r->err);
}
return;
}
for (int i = 0; i < st->ndevs; i++) {
if (st->devs[i].alive && memcmp(st->devs[i].d.id, r->d.id, 16) == 0) {
(void)snprintf(st->devs[i].d.name, sizeof st->devs[i].d.name, "%s", r->d.name);
}
}
rmt_names_changed(st); /* later ask_settled says the new name in by.device */
rmt_devices_tell_all(st);
}
/* rename_device {"device":ID,"name":N} from D: any paired device, ID its b64u id or remote:ID; N by
* the rules a pairing's name follows (control characters taken out, others pic cannot show made ?,
* trimmed, 1 to 64 bytes). */
static void rmt_rename(rmt_state *st, rmt_dev *d, const rmt_env *e) {
char *id = e->payload ? rmt_q("SELECT CASE json_type(?1, '$.device') WHEN 'text' THEN json_extract(?1, '$.device') END", 1,
e->payload)
: NULL;
char *name = e->payload ? rmt_q("SELECT CASE json_type(?1, '$.name') WHEN 'text' THEN json_extract(?1, '$.name') END", 1,
e->payload)
: NULL;
unsigned char raw[32];
const char *b = id && strncmp(id, "remote:", 7) == 0 ? id + 7 : id;
int di = -1;
if (b && pic_b64u_dec(b, strlen(b), raw, sizeof raw) == 16) {
for (int i = 0; i < st->ndevs && di < 0; i++) {
di = st->devs[i].alive && memcmp(st->devs[i].d.id, raw, 16) == 0 ? i : -1;
}
}
if (name) { /* control characters out (C0, DEL, C1), then pairing's cleaning, then the spaces trimmed */
unsigned char *in = (unsigned char *)name, *out = (unsigned char *)name;
size_t len;
while (*in) {
if (*in < 0x20 || *in == 0x7f) {
in++;
} else if (in[0] == 0xc2 && in[1] >= 0x80 && in[1] <= 0x9f) {
in += 2;
} else {
*out++ = *in++;
}
}
*out = '\0';
rmt_name_clean(name);
len = strlen(name);
while (len && name[len - 1] == ' ') {
name[--len] = '\0';
}
memmove(name, name + strspn(name, " "), strlen(name + strspn(name, " ")) + 1);
}
if (!name || !*name || strlen(name) > 64) {
rmt_error(st, d, NULL, "bad_message", "a device's name is 1 to 64 bytes of text");
} else if (di < 0) {
rmt_error(st, d, NULL, "no_device", "no such paired device");
} else {
rmt_device nd = st->devs[di].d;
(void)snprintf(nd.name, sizeof nd.name, "%s", name);
rmt_log(stdout, "pic remote: %s renamed %s to %s\n", d->d.name, st->devs[di].d.name, nd.name);
(void)fflush(stdout);
rmt_job_add(st, rmt_row_job(st, d, RMT_ROW_WRITE, &nd, rmt_renamed, "renaming a device"));
pic_cred_wipe(&nd, sizeof nd);
}
free(id);
free(name);
}
/* ---- pairing from a paired phone (Amendments) ------------------------------------------------- */
/* The device list, as SELF sees it. */
static char *rmt_devices_json(rmt_state *st, int self) {
rmt_buf b = {NULL, 0, 0};
char *out;
(void)rmt_buf_add(&b, "[", 1);
for (int i = 0; i < st->ndevs; i++) {
rmt_dev *d = &st->devs[i];
char paired[24], seen[24], *one;
if (!d->alive) {
continue;
}
(void)snprintf(paired, sizeof paired, "%lld", d->d.paired_ms);
(void)snprintf(seen, sizeof seen, "%lld", d->sess >= 0 ? rmt_wall_ms() : d->d.seen_ms);
one = rmt_q("SELECT json_object('id', ?1, 'name', ?2, 'pairedMs', CAST(?3 AS INTEGER), 'seenMs', CAST(?4 AS INTEGER),"
" 'self', json(?5))",
5, d->idb, d->d.name, paired, seen, i == self ? "true" : "false");
if (one) {
if (b.len > 1) {
(void)rmt_buf_add(&b, ",", 1);
}
(void)rmt_buf_add(&b, one, strlen(one));
}
free(one);
}
(void)rmt_buf_add(&b, "]", 1);
out = rmt_q("SELECT json_object('type', 'devices', 'payload', json_object('devices', json(?1)))", 1, b.buf);
free(b.buf);
return out;
}
/* After a pairing or an unpairing: the list again to each phone that has asked for it. */
static void rmt_devices_tell(rmt_state *st) {
for (int i = 0; i < st->ndevs; i++) {
if (st->devs[i].alive && st->devs[i].sess >= 0 && st->devs[i].want_devices) {
rmt_send_free(st, &st->devs[i], rmt_devices_json(st, i));
}
}
}
static void rmt_pair_end(rmt_state *st, int di, const char *result, const char *name, const char *device) {
if (di < 0 || di >= st->ndevs || !st->devs[di].alive) {
return;
}
rmt_send_free(st, &st->devs[di],
rmt_q("SELECT json_object('type', 'pair_end', 'payload',"
" json_patch(json_object('result', ?1), json_object('name', ?2, 'device', ?3)))",
3, result, name, device));
}
/* The waiting device's name and six digits, to the phone that asked for the offer. */
static void rmt_offer_tell(rmt_state *st) {
rmt_dev *d = &st->devs[st->offer_dev];
rmt_send_free(st, d,
rmt_q("SELECT json_object('type', 'pair_request', 'payload', json_object('name', ?1, 'code', ?2))", 2,
st->offer->d.name, st->offer->sas));
}
/* The offer is over: its last word (paired, or a refusal) is posted, and the channel goes once the
* new device has read it, as rmt_pair_last_word waits, without holding up the loop. */
static void rmt_offer_closing(rmt_state *st) {
rmt_offer *o = st->offer;
long long now = rmt_mono_ms();
o->stage = OFFER_OVER;
st->offer_posted = o->said && !o->lane.qlen;
st->offer_reading = st->offer_posted ? st->r.peer : -1;
st->offer_close_ms = !o->said ? now : st->offer_posted && st->offer_reading < 0 ? now + RMT_NO_PEER_MS : now + RMT_LAST_WORD_MS;
}
static void rmt_offer_close(rmt_state *st) {
if (!st->offer) {
return;
}
rmt_delete_channel(&st->r, st->offer->P);
if (st->offer_str) {
atomic_store(&st->offer_str->quit, 1);
rmt_stream_release(st->offer_str);
st->offer_str = NULL;
}
rmt_offer_free(st->offer);
free(st->offer);
st->offer = NULL;
}
static void rmt_offer_ask(rmt_state *st, int di) {
char err[256], *set = pic_setting("remote.phonePairing"), exp[24], tok[32];
int off = set && strcmp(set, "off") == 0, alive = 0;
rmt_offer *o;
rmt_stream *str;
free(set);
if (off) {
rmt_pair_end(st, di, "off", NULL, NULL);
return;
}
if (st->offer && st->offer->stage != OFFER_OVER) {
if (st->offer_dev != di) {
rmt_pair_end(st, di, "busy", NULL, NULL);
return;
}
(void)snprintf(exp, sizeof exp, "%lld", st->offer->expires); /* asked again: the same offer */
rmt_send_free(st, &st->devs[di],
rmt_q("SELECT json_object('type', 'pair_offer', 'payload', json_object('url', ?1, 'expires', CAST(?2 AS INTEGER)))",
2, st->offer->url, exp));
if (st->offer->stage == OFFER_ASKING) {
rmt_offer_tell(st);
}
return;
}
rmt_offer_close(st); /* one whose last word still waits: a new offer replaces it at the relay anyway */
for (int i = 0; i < st->ndevs; i++) {
alive += st->devs[i].alive;
}
if (alive >= 8) {
rmt_pair_end(st, di, "full", NULL, NULL);
return;
}
o = calloc(1, sizeof *o);
str = calloc(1, sizeof *str);
if (!o || !str || rmt_offer_open(o, &st->r, &st->k, RMT_PHONE_PAIR_TTL, err, sizeof err) != 0) {
free(o);
free(str);
rmt_pair_end(st, di, "failed", NULL, NULL);
return;
}
pic_b64u_enc(o->P, 16, tok);
(void)snprintf(str->url, sizeof str->url, "%s/v1/m/%s/c/%s/up", st->r.base, st->r.mbx, tok);
(void)snprintf(str->auth, sizeof str->auth, "%s", st->r.owner);
memcpy(str->channel, o->P, 16);
atomic_store(&str->refs, 2);
if (rmt_stream_start(str, st->pipe_w) != 0) {
rmt_delete_channel(&st->r, o->P);
rmt_offer_free(o);
free(o);
free(str);
rmt_pair_end(st, di, "failed", NULL, NULL);
return;
}
(void)pthread_detach(str->th);
st->offer = o;
st->offer_serial++;
st->offer_adding = 0;
st->offer_str = str;
st->offer_dev = di;
(void)snprintf(exp, sizeof exp, "%lld", o->expires);
rmt_send_free(st, &st->devs[di],
rmt_q("SELECT json_object('type', 'pair_offer', 'payload', json_object('url', ?1, 'expires', CAST(?2 AS INTEGER)))", 2,
o->url, exp));
rmt_log(stdout, "pic remote: %s is adding a device\n", st->devs[di].d.name);
(void)fflush(stdout);
}
/* pair_approve (YES, with the six digits in CODE) or pair_deny, from device DI. Only the device
* that asked for the offer answers it, and an approval only once a device waits; a code that is
* not the waiting device's refuses the offer: one try. */
/* The approved device's row, written: the new device hears paired, and the device list goes to
* every phone once it is read again; or, when the write failed or the offer ended meanwhile, no. */
static void rmt_offer_added(rmt_state *st, rmt_job *jb) {
rmt_rowjob *r = jb->ctx;
rmt_offer *o = st->offer;
char idb[32], err[256];
int di = jb->di;
if (!o || r->offer != st->offer_serial || o->stage == OFFER_OVER) { /* the offer ended: its phone heard no */
if (r->rc == 0) {
rmt_job_add(st, rmt_row_job(st, NULL, RMT_ROW_DELETE, &r->d, NULL, "deleting a device whose pairing ended"));
}
return;
}
st->offer_adding = 0;
o->stage = OFFER_OVER;
if (r->rc != 0) {
(void)snprintf(err, sizeof err, "%s", r->err);
} else if (rmt_put_channel(&st->r, o->d.channel, 0, err, sizeof err) != 0) { /* a row whose phone heard no would never connect */
rmt_job_add(st, rmt_row_job(st, NULL, RMT_ROW_DELETE, &o->d, NULL, "deleting a device the relay refused"));
} else {
err[0] = '\0';
}
if (err[0]) {
rmt_offer_say(o, &st->r, "{\"type\":\"error\",\"payload\":{\"code\":\"pair_refused\"}}");
rmt_offer_closing(st);
rmt_pair_end(st, di, "failed", o->d.name, NULL);
rmt_log(stderr, "pic remote: %s\n", err);
return;
}
rmt_offer_say(o, &st->r, "{\"type\":\"paired\"}");
rmt_offer_closing(st);
pic_b64u_enc(o->d.id, 16, idb);
rmt_log(stdout, "pic remote: %s paired %s\n", di >= 0 && di < st->ndevs ? st->devs[di].d.name : "a phone", o->d.name);
(void)fflush(stdout);
rmt_pair_end(st, di, "paired", o->d.name, idb);
st->user_force = 1; /* this process's own write: data_version does not show it; the read tells every phone */
}
static void rmt_offer_answer(rmt_state *st, int di, int yes, const char *code) {
rmt_offer *o = st->offer;
rmt_job *jb;
if (!o || o->stage == OFFER_OVER || st->offer_adding || st->offer_dev != di || (yes && o->stage != OFFER_ASKING)) {
rmt_error(st, &st->devs[di], NULL, "no_offer", "no device is waiting for this phone's answer");
return;
}
if (!yes || strlen(code) != 6 || !rmt_same((const unsigned char *)code, (const unsigned char *)o->sas, 6) ||
rmt_dev_by_channel(st, o->d.channel) >= 0) { /* a channel already a device's is no new device's */
rmt_offer_refuse(o, &st->r);
rmt_offer_closing(st);
rmt_pair_end(st, di, "refused", o->d.name, NULL);
rmt_log(stdout, "pic remote: %s did not pair %s\n", st->devs[di].d.name, o->d.name);
(void)fflush(stdout);
return;
}
if (!(jb = rmt_row_job(st, &st->devs[di], RMT_ROW_ADD, &o->d, rmt_offer_added, "adding the device a phone approved"))) {
rmt_offer_refuse(o, &st->r);
rmt_offer_closing(st);
rmt_pair_end(st, di, "failed", o->d.name, NULL);
return;
}
((rmt_rowjob *)jb->ctx)->offer = st->offer_serial;
st->offer_adding = 1;
rmt_job_add(st, jb);
}
/* Each tick: the offer's expiry, its posts, and the end of its last word's wait. */
static void rmt_offer_tick(rmt_state *st) {
rmt_offer *o = st->offer;
long long now = rmt_mono_ms();
if (!o) {
return;
}
if (o->stage != OFFER_OVER && !st->offer_adding && now > o->mono_end) {
rmt_offer_refuse(o, &st->r);
rmt_offer_closing(st);
rmt_pair_end(st, st->offer_dev, "expired", o->d.name[0] ? o->d.name : NULL, NULL);
}
if (o->lane.qlen) {
(void)rmt_lane_flush(&st->r, &o->lane);
if (o->stage == OFFER_OVER && !o->lane.qlen && !st->offer_posted) {
st->offer_posted = 1;
st->offer_reading = st->r.peer;
if (st->offer_reading < 0) {
st->offer_close_ms = now + RMT_NO_PEER_MS;
}
}
}
if (o->stage == OFFER_OVER && ((st->offer_posted && st->offer_reading == 1) || now >= st->offer_close_ms)) {
rmt_offer_close(st);
}
}
/* An event from the offer's stream (its channel, not the mailbox stream's). */
static void rmt_offer_event(rmt_state *st, int kind, const unsigned char *rec, size_t n) {
rmt_offer *o = st->offer;
if (kind == RMT_EV_FRAME) {
int ev = rmt_offer_frame(o, &st->r, &st->k, rec, n);
if (ev == OFFER_EV_FAILED) {
rmt_offer_closing(st);
rmt_pair_end(st, st->offer_dev, "failed", NULL, NULL);
} else if (ev == OFFER_EV_ASK) {
rmt_offer_tell(st);
}
} else if (kind == RMT_EV_PEER) {
if (o->stage == OFFER_OVER && st->offer_posted && n == 1 && rec[0] == 1) {
rmt_offer_close(st); /* the new device is back, and has been sent what the relay held */
}
} else if (kind == RMT_EV_GONE || kind == RMT_EV_REFUSED) { /* another offer (/rc's) replaced it at the relay */
if (o->stage != OFFER_OVER) {
o->stage = OFFER_OVER;
rmt_pair_end(st, st->offer_dev, "failed", NULL, NULL);
}
o->said = 0;
rmt_offer_close(st);
}
}
/* The table, read again: new rows are served from now on, deleted ones end their sessions. */
/* LIST, the table as read (N rows), applied: new rows are served from now on, deleted ones end
* their sessions. Takes LIST. */
static void rmt_devices_apply(rmt_state *st, rmt_device *list, int n, int quiet) {
int changed = 0;
char err[256];
for (int i = 0; i < st->ndevs; i++) {
int still = 0;
for (int k = 0; k < n; k++) {
still = still || memcmp(list[k].id, st->devs[i].d.id, 16) == 0;
}
if (st->devs[i].alive && !still) {
st->devs[i].alive = 0; /* deleted at the terminal: the row's deletion is the revocation */
rmt_unpair_device(st, i, 1);
changed = 1;
if (!quiet) {
rmt_log(stdout, "pic remote: %s was unpaired\n", st->devs[i].d.name);
(void)fflush(stdout);
}
}
}
for (int k = 0; k < n; k++) {
int known = 0;
for (int i = 0; i < st->ndevs; i++) {
known = known || (st->devs[i].alive && memcmp(list[k].id, st->devs[i].d.id, 16) == 0);
}
if (!known) {
rmt_dev *grown = realloc(st->devs, (size_t)(st->ndevs + 1) * sizeof *grown), *d;
if (!grown) {
continue;
}
st->devs = grown;
d = &st->devs[st->ndevs++];
memset(d, 0, sizeof *d);
d->d = list[k];
pic_b64u_enc(d->d.id, 16, d->idb);
memcpy(d->lane.ch, d->d.channel, 16);
d->sess = -1;
d->alive = 1;
changed = 1;
if (rmt_put_channel(&st->r, d->d.channel, 0, err, sizeof err) != 0 && !quiet) {
rmt_log(stderr, "pic remote: %s\n", err);
}
if (!quiet) {
rmt_log(stdout, "pic remote: serving %s\n", d->d.name);
(void)fflush(stdout);
}
}
}
free(list);
if (changed) {
rmt_names_changed(st);
}
if (changed && !quiet) {
rmt_devices_tell(st);
}
}
/* The table read and applied here and now: at the start, before the workers. 0, or -1. */
static int rmt_devices_sync(rmt_state *st, int quiet) {
rmt_device *list;
int n, bad;
char err[256];
if (rmt_devices_load(&list, &n, &bad, err, sizeof err) != 0) {
return -1;
}
rmt_devices_apply(st, list, n, quiet);
return 0;
}
/* ---- the user database's look, each second ------------------------------------------------ */
/* What changed in the user database: the paired devices, the workspaces the registry names, and
* remote.notify. In: the version the loop applied last and what it serves; out: what was read. */
typedef struct {
long long version;
int force;
unsigned gen;
char **known;
int nknown;
int read;
rmt_device *list;
int n;
rmt_cand *cands;
int ncands;
char *folders; /* read again: on a change, and every RMT_FOLDERS_MS for folders made meanwhile */
} rmt_userjob;
static void rmt_userjob_drop(void *p) {
rmt_userjob *u = p;
if (!u) {
return;
}
for (int i = 0; i < u->nknown; i++) {
free(u->known[i]);
}
free(u->known);
if (u->list) {
pic_cred_wipe(u->list, (size_t)u->n * sizeof *u->list);
}
free(u->list);
rmt_cands_free(u->cands, u->ncands);
free(u->folders);
free(u);
}
static void rmt_userjob_run(rmt_job *jb) {
/* data_version counts other connections' commits on this thread's own connection: a worker
* compares it with what it saw last, never with another worker's */
static _Thread_local long long seen = -1, folders_ms = -RMT_FOLDERS_MS;
rmt_userjob *u = jb->ctx;
char err[256];
long long now = rmt_data_version(pic_userdb(NULL, 0)), mono = rmt_mono_ms();
int bad, same = now == seen && now >= 0 && !u->force;
if (!same || mono - folders_ms >= RMT_FOLDERS_MS) {
u->folders = rmt_folders_scan();
folders_ms = mono;
}
if (same) {
return;
}
seen = now;
u->version = now;
if (rmt_devices_load(&u->list, &u->n, &bad, err, sizeof err) != 0) {
u->list = NULL;
u->n = 0;
return;
}
rmt_scan_rows(u->known, u->nknown, &u->cands, &u->ncands, 0);
u->read = 1;
}
static void rmt_userjob_done(rmt_state *st, rmt_job *jb) {
rmt_userjob *u = jb->ctx;
st->user_job = 0;
if (u->folders) {
free(st->folders);
st->folders = u->folders;
u->folders = NULL;
}
if (!u->read) {
rmt_stash_replay(st);
return;
}
if (u->gen != st->user_gen) { /* this process wrote a row since: read again */
st->user_force = 1;
return;
}
st->user_version = u->version;
rmt_devices_apply(st, u->list, u->n, 0);
u->list = NULL;
for (int i = 0; i < u->ncands; i++) {
rmt_journal_add(st, &u->cands[i]);
}
rmt_stash_replay(st);
}
/* The look queued, unless one is in hand; FORCE reads the tables even when the version is the same. */
static void rmt_user_look(rmt_state *st, int force) {
rmt_userjob *u;
rmt_job *jb;
if (st->user_job || !(u = calloc(1, sizeof *u))) {
return;
}
u->version = st->user_version;
u->force = force;
u->gen = st->user_gen;
if ((u->known = calloc((size_t)(2 * st->njs + 1), sizeof *u->known))) {
for (int i = 0; i < st->njs; i++) {
if (!st->js[i]->hidden) {
u->known[u->nknown++] = strdup(st->js[i]->path);
u->known[u->nknown++] = strdup(st->js[i]->workspace);
}
}
for (int i = 0; i < u->nknown; i++) {
if (!u->known[i]) {
u->known[i] = strdup("");
}
}
}
jb = rmt_job_new(st, NULL, NULL, rmt_userjob_run, rmt_userjob_done, rmt_userjob_drop, u, "reading the paired devices and workspaces");
if (jb) {
jb->user = 1; /* opens sealed rows with the store's key, writes the registry */
jb->background = 1;
}
st->user_job = jb != NULL;
st->user_force = 0;
rmt_job_add(st, jb);
}
/* Section 7's reconcile: the mailbox, every device's channel, and no device channel without a row. */
static int rmt_reconcile(rmt_state *st, char *err, size_t cap) {
char path[128], *list = NULL;
int stc;
if (rmt_put_mailbox(&st->r, err, cap) != 0) {
return -1;
}
(void)snprintf(path, sizeof path, "/v1/m/%s/c", st->r.mbx);
stc = rmt_call(&st->r, "GET", path, st->r.owner, NULL, 0, NULL, &list, err, cap);
if (stc == 200 && list) {
sqlite3_stmt *q = NULL;
if (sqlite3_prepare_v2(rmt_mem(), "SELECT json_extract(value, '$.id') FROM json_each(?1)"
" WHERE json_extract(value, '$.kind') = 'device'",
-1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, list, -1, SQLITE_STATIC);
while (sqlite3_step(q) == SQLITE_ROW) {
const char *id = (const char *)sqlite3_column_text(q, 0);
unsigned char ch[16];
if (id && pic_b64u_dec(id, strlen(id), ch, sizeof ch) == 16 && rmt_dev_by_channel(st, ch) < 0) {
rmt_delete_channel(&st->r, ch);
}
}
}
sqlite3_finalize(q);
}
free(list);
return 0;
}
/* ---- pic remote ------------------------------------------------------------------------------ */
static void rmt_on_signal(int sig) {
if (sig == SIGUSR1) {
rmt_restart_asked = 1;
} else {
rmt_stop = 1;
}
}
static int rmt_lock(void) {
char path[PATH_MAX];
const char *home = getenv("HOME");
if (!home || snprintf(path, sizeof path, "%s/.pic/remote.lock", home) >= (int)sizeof path) {
return -1;
}
return pic_platform_get()->lock(path, 0);
}
/* Whether a pic remote is running, by trying its lock for an instant: 1, 0, or -1. */
static int rmt_running_now(void) {
int h = rmt_lock();
if (h >= 0) {
pic_platform_get()->unlock(h);
return 0;
}
return h == -2 ? 1 : -1;
}
/* The store's key from its own source every time, never one handed down by a parent: a
* passphrase store asks on the terminal; a key in the Keychain or the key file needs no one, so
* launchd can start it. */
static int rmt_unlock_fresh(char *err, size_t cap) {
pic_cred_lock();
if (pic_cred_state() == PIC_CRED_NEW) {
(void)snprintf(err, cap, "the credential store has no key yet: pair a phone with /rc or pic remote pair first");
return -1;
}
return pic_cred_unlock(err, cap);
}
/* ---- status: ~/.pic/remote.status, written by the running pic remote, read by status and stop ---- */
static int rmt_status_path(char *out, size_t cap, const char *suffix) {
const char *home = getenv("HOME");
return home && snprintf(out, cap, "%s/.pic/remote.status%s", home, suffix) < (int)cap ? 0 : -1;
}
/* The phones in a session now, as JSON: [{"name","session","visible"}], session the W/C each follows
* or null; written into the status file for the terminal's footer. */
static char *rmt_phones;
/* The running one's state, replaced whole (a rename), so a reader never sees half of it. */
static void rmt_status_write(const char *state, const char *relay, int devices, int attempts, long long retry_at,
const char *why, long long opened_ms, long long recycles) {
char path[PATH_MAX], tmp[PATH_MAX], pid[24], n[24], a[24], r[24], now[24], started[24], op[24], rc[24];
char *json, *with;
FILE *f;
if (rmt_status_path(path, sizeof path, "") != 0 || rmt_status_path(tmp, sizeof tmp, ".tmp") != 0) {
return;
}
(void)snprintf(started, sizeof started, "%lld", rmt_started_ms);
(void)snprintf(pid, sizeof pid, "%ld", (long)getpid());
(void)snprintf(n, sizeof n, "%d", devices);
(void)snprintf(a, sizeof a, "%d", attempts);
(void)snprintf(r, sizeof r, "%lld", retry_at);
(void)snprintf(now, sizeof now, "%lld", rmt_wall_ms());
json = rmt_q("SELECT json_object('pid', CAST(?1 AS INTEGER), 'state', ?2, 'relay', ?3, 'devices', CAST(?4 AS INTEGER),"
" 'attempts', CAST(?5 AS INTEGER), 'retryAtMs', CAST(?6 AS INTEGER), 'error', ?7, 'updatedMs', CAST(?8 AS INTEGER),"
" 'phones', json(?9))",
9, pid, state, relay ? relay : "", n, a, r, why ? why : "", now,
rmt_phones && strcmp(state, "connected") == 0 ? rmt_phones : "[]");
/* what it runs, for status to tell an older pic remote from this pic */
(void)snprintf(op, sizeof op, "%lld", opened_ms);
(void)snprintf(rc, sizeof rc, "%lld", recycles);
with = json ? rmt_q("SELECT json_set(?1, '$.exe', ?2, '$.exeStamp', ?3, '$.startedMs', CAST(?4 AS INTEGER), '$.streamOpenedAt',"
" CASE WHEN CAST(?5 AS INTEGER) > 0 THEN strftime('%Y-%m-%dT%H:%M:%SZ', CAST(?5 AS INTEGER) / 1000, 'unixepoch') END,"
" '$.recycles', CAST(?6 AS INTEGER))",
6, json, rmt_exe, rmt_exe_stamp, started, op, rc)
: NULL;
free(json);
json = with;
if (json && (f = fopen(tmp, "w")) != NULL) {
int ok = fputs(json, f) >= 0 && fputc('\n', f) != EOF;
ok = fclose(f) == 0 && ok;
if (!ok || rename(tmp, path) != 0) {
(void)unlink(tmp);
}
}
free(json);
}
/* What the status file says, malloc'd, or NULL. */
static char *rmt_status_read(void) {
char path[PATH_MAX], buf[4096];
FILE *f;
size_t n;
if (rmt_status_path(path, sizeof path, "") != 0 || !(f = fopen(path, "r"))) {
return NULL;
}
n = fread(buf, 1, sizeof buf - 1, f);
fclose(f);
buf[n] = '\0';
return n ? strdup(buf) : NULL;
}
static int rmt_device_count(void) { return pic_remote_phones(); }
int pic_remote_running(void) { return rmt_running_now() == 1; }
/* Appends S to OUT percent-encoded but for unreserved characters and '/'; 0, or -1 when it does not fit. */
static int rmt_link_add(char *out, size_t cap, size_t *len, const char *s, int encode) {
static const char hex[] = "0123456789ABCDEF";
for (; *s; s++) {
unsigned char c = (unsigned char)*s;
int plain = !encode || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
strchr("-._~/", c) != NULL;
if (*len + (plain ? 1 : 3) >= cap) {
return -1;
}
if (plain) {
out[(*len)++] = (char)c;
} else {
out[(*len)++] = '%';
out[(*len)++] = hex[c >> 4];
out[(*len)++] = hex[c & 15];
}
}
out[*len] = '\0';
return 0;
}
int pic_remote_link(const char *session, char *out, size_t cap) {
sqlite3 *db = pic_userdb(NULL, 0);
sqlite3_stmt *q = NULL;
rmt_relay r;
char phone[32] = "";
size_t len = 0;
int n = rmt_device_count();
if (!cap) {
return -1;
}
out[0] = '\0';
rmt_relay_init(&r, NULL);
if (n == 1 && db && sqlite3_prepare_v2(db, "SELECT id FROM picu_remote_device", -1, &q, NULL) == SQLITE_OK &&
sqlite3_step(q) == SQLITE_ROW && sqlite3_column_bytes(q, 0) == 16) {
pic_b64u_enc(sqlite3_column_blob(q, 0), 16, phone);
}
sqlite3_finalize(q);
if (rmt_link_add(out, cap, &len, r.base, 0) != 0 || rmt_link_add(out, cap, &len, "/", 0) != 0) {
return -1;
}
/* The conversation's id alone: the page finds it in the list pic remote sends, so no path is in the link. */
if (session && *session &&
(rmt_link_add(out, cap, &len, "#s=", 0) != 0 || rmt_link_add(out, cap, &len, session, 1) != 0)) {
return -1;
}
if (phone[0] && (rmt_link_add(out, cap, &len, strchr(out, '#') ? "&c=" : "#c=", 0) != 0 ||
rmt_link_add(out, cap, &len, phone, 0) != 0)) {
return -1;
}
return n;
}
/* The stream's state into the status file when it changed, and every 5 s regardless. */
static void rmt_status_tick(rmt_state *st, rmt_stream *str, int force) {
static int last_state = -1, last_attempts = -1;
static long long last_recycles = -1;
static long long last_ms;
int state = atomic_load(&str->state), attempts = atomic_load(&str->attempts), alive = 0;
long long now = rmt_mono_ms();
char *phones = NULL;
{
sqlite3_str *p = sqlite3_str_new(NULL);
sqlite3_str_appendall(p, "SELECT json_array(");
for (int i = 0, k = 0; i < st->ndevs; i++) {
if (st->devs[i].alive && st->devs[i].sess >= 0) {
sqlite3_str_appendf(p, "%sjson_object('name', %Q, 'session', %Q, 'visible', json(%Q))", k++ ? "," : "",
st->devs[i].d.name, st->devs[i].f ? st->devs[i].wsess : NULL,
st->devs[i].visible ? "true" : "false");
}
}
sqlite3_str_appendall(p, ")");
{
char *sql = sqlite3_str_finish(p);
phones = sql ? rmt_q(sql, 0) : NULL;
sqlite3_free(sql);
}
}
if (phones && (!rmt_phones || strcmp(phones, rmt_phones) != 0)) { /* a phone came, went or opened another */
free(rmt_phones);
rmt_phones = phones;
force = 1;
} else {
free(phones);
}
if (!force && state == last_state && attempts == last_attempts && atomic_load(&str->recycles) == last_recycles && now - last_ms < 5000) {
return;
}
for (int i = 0; i < st->ndevs; i++) {
alive += st->devs[i].alive;
}
last_state = state;
last_attempts = attempts;
last_recycles = atomic_load(&str->recycles);
last_ms = now;
rmt_status_write(state == RMT_CONN_CONNECTED ? "connected" : attempts ? "reconnecting" : "connecting", st->r.base, alive,
attempts, state == RMT_CONN_WAITING ? atomic_load(&str->retry_at) : 0,
state == RMT_CONN_CONNECTED ? "" : str->why, state == RMT_CONN_CONNECTED ? atomic_load(&str->opened_ms) : 0,
last_recycles);
}
/* The conversation list to D when it differs from the one it has. */
static void rmt_list_check(rmt_state *st, rmt_dev *d) {
char *list = rmt_list(st, -1, NULL, 0, NULL, 0, d->list_archived, d->list_trash);
if (list && (!d->list_sent || strcmp(list, d->list_sent) != 0)) {
(void)rmt_send(st, d, list);
free(d->list_sent);
d->list_sent = list;
} else {
free(list);
}
}
/* Whether every journal shown has had its part of the list built once: the first list waits for it. */
static int rmt_lists_ready(rmt_state *st) {
for (int i = 0; i < st->njs; i++) {
if (st->js[i]->open && !st->js[i]->list_ready && rmt_shown(st, i)) {
return 0;
}
}
return 1;
}
/* Loops with the terminal closed: every 5 seconds this journal is asked what is due (wake.h),
* which fires it and starts its request; and a loop that came to need a person since the last
* look (its message refused, its 7 days up) is a notification, once. On J's lane. */
static void rmt_wake_tick(rmt_tnotes *notes, rmt_journal *j) {
long long now = rmt_mono_ms(), next = 0;
sqlite3_stmt *q = NULL;
int fired = 0;
if (j->wake_at && now - j->wake_at < 5000 && now >= j->wake_at) {
return;
}
j->wake_at = now ? now : 1;
if (pic_wake_due(&j->s, j->workspace, NULL, 1, &fired, &next) != 0) {
j->s.err[0] = '\0';
}
if (!j->wake_init) { /* what came before this pic remote is not news */
if (sqlite3_prepare_v2(j->s.db, "SELECT coalesce(max(updated_ms), 0) FROM pic_wake", -1, &q, NULL) == SQLITE_OK &&
sqlite3_step(q) == SQLITE_ROW) {
j->wake_seen = sqlite3_column_int64(q, 0);
j->wake_init = 1;
}
sqlite3_finalize(q);
return;
}
if (sqlite3_prepare_v2(j->s.db,
"SELECT w.session_id, upper(substr(w.kind, 1, 1)) || substr(w.kind, 2) || ' ' || upper(substr(w.kind, 1, 1))"
" || w.id || CASE WHEN w.state = 'needs' THEN ' needs you: ' || coalesce(w.why, '')"
" ELSE ' has ended: its 7 days are up' END,"
" coalesce((SELECT " PIC_TITLE_SQL("t") " FROM pic_session t WHERE t.id = w.session_id), ''),"
" coalesce((SELECT t.head_seq FROM pic_session t WHERE t.id = w.session_id), 0), w.updated_ms"
" FROM pic_wake w WHERE w.updated_ms > ?1 AND (w.state = 'needs' OR (w.state = 'ended' AND w.why = 'expired'))"
/* waiting for an OK: an ask, told by rmt_ask_check */
" AND NOT (coalesce(json_extract(w.options, '$.approval'), '') = 'asked' AND w.state = 'needs'"
" AND EXISTS (SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'pic_ask'))"
" ORDER BY w.updated_ms",
-1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_int64(q, 1, j->wake_seen);
while (sqlite3_step(q) == SQLITE_ROW) {
char *body = pic_one_line((const char *)sqlite3_column_text(q, 1), 200);
if (body) {
rmt_note(notes, (const char *)sqlite3_column_text(q, 0), (const char *)sqlite3_column_text(q, 2), 1,
sqlite3_column_int64(q, 3), body);
}
free(body);
if (sqlite3_column_int64(q, 4) > j->wake_seen) {
j->wake_seen = sqlite3_column_int64(q, 4);
}
}
}
sqlite3_finalize(q);
/* changes since, of any loop: a later look need not read them again */
if (sqlite3_prepare_v2(j->s.db, "SELECT coalesce(max(updated_ms), 0) FROM pic_wake WHERE updated_ms > ?1", -1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_int64(q, 1, j->wake_seen);
if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_int64(q, 0) > j->wake_seen) {
j->wake_seen = sqlite3_column_int64(q, 0);
}
}
sqlite3_finalize(q);
}
/* ---- asks (ask.h): a question a conversation waits on a person for ------------------------- */
/* Each ask of LIST (pic_ask_list's array) of journal J, with NAMES the devices' names, as lines in
* OUT: an open one as ask, a settled one as ask_settled. With NOTES, an open one is also a
* notification, in pic's own words so nothing the question says reaches a lock screen. On J's lane. */
static void rmt_ask_records(rmt_journal *j, const char *list, const char *names, rmt_lines *out, rmt_tnotes *notes) {
sqlite3_stmt *q = NULL;
if (!list || !names ||
sqlite3_prepare_v2(rmt_mem(),
"SELECT CASE WHEN json_extract(value, '$.state') = 'open' THEN json_object('type', 'ask', 'session', ?2 || '/'"
" || json_extract(value, '$.session'), 'payload', json_remove(value, '$.session', '$.version'))"
" ELSE json_object('type', 'ask_settled', 'session', ?2 || '/' || json_extract(value, '$.session'), 'payload', "
RMT_SETTLED_SQL("value", "?3") ") END, json_extract(value, '$.session'), json_extract(value, '$.state') = 'open'"
" FROM json_each(?1)",
-1, &q, NULL) != SQLITE_OK) {
return;
}
sqlite3_bind_text(q, 1, list, -1, SQLITE_STATIC);
sqlite3_bind_text(q, 2, j->path, -1, SQLITE_STATIC);
sqlite3_bind_text(q, 3, names, -1, SQLITE_STATIC);
while (sqlite3_step(q) == SQLITE_ROW) {
rmt_lines_add(out, strdup((const char *)sqlite3_column_text(q, 0)));
if (notes && sqlite3_column_int(q, 2)) {
const char *conv = (const char *)sqlite3_column_text(q, 1);
sqlite3_stmt *t = NULL;
char *ctitle = NULL, *who = NULL, body[300];
long long seq = 0;
if (sqlite3_prepare_v2(j->s.db, "SELECT " PIC_TITLE_SQL("t") ", coalesce(t.head_seq, 0) FROM pic_session t WHERE t.id = ?1", -1, &t,
NULL) == SQLITE_OK) {
sqlite3_bind_text(t, 1, conv, -1, SQLITE_STATIC);
if (sqlite3_step(t) == SQLITE_ROW) {
ctitle = sqlite3_column_type(t, 0) == SQLITE_NULL ? NULL : strdup((const char *)sqlite3_column_text(t, 0));
seq = sqlite3_column_int64(t, 1);
}
}
sqlite3_finalize(t);
/* the title the notification shows: the conversation's, else the workspace's folder */
if (ctitle && *ctitle) {
who = pic_one_line(ctitle, 60);
} else if ((who = strdup(j->workspace))) {
size_t e = strlen(who);
while (e > 1 && who[e - 1] == '/') {
who[--e] = '\0';
}
if (strrchr(who, '/')) {
memmove(who, strrchr(who, '/') + 1, strlen(strrchr(who, '/') + 1) + 1);
}
}
(void)snprintf(body, sizeof body, "%s needs your answer", who ? who : "A conversation");
rmt_note(notes, conv, ctitle, 1, seq, body);
free(who);
free(ctitle);
}
}
sqlite3_finalize(q);
}
/* Asks of J that expired unanswered with nobody answering, looked at every 5 s by index: each is
* ask_settled with kind expired, once (the ring of those told). On J's lane. */
static void rmt_ask_expiry(rmt_journal *j, const char *names, rmt_lines *out) {
long long now = rmt_mono_ms();
sqlite3_stmt *q = NULL;
rmt_buf b = {NULL, 0, 0};
if (j->ask_expiry_ms && now - j->ask_expiry_ms < 5000 && now >= j->ask_expiry_ms) {
return;
}
j->ask_expiry_ms = now ? now : 1;
if (sqlite3_prepare_v2(j->s.db, "SELECT id, session_id FROM pic_ask WHERE state = 'open' AND expires_ms <= ?1 ORDER BY rowid LIMIT ?2",
-1, &q, NULL) != SQLITE_OK) {
sqlite3_finalize(q);
return;
}
sqlite3_bind_int64(q, 1, pic_wake_now_ms());
sqlite3_bind_int(q, 2, RMT_ASKS);
(void)rmt_buf_add(&b, "[", 1);
while (sqlite3_step(q) == SQLITE_ROW) {
const char *id = (const char *)sqlite3_column_text(q, 0);
int told = 0;
for (int k = 0; k < RMT_ASK_RING; k++) {
told |= strcmp(j->ask_told[k], id) == 0;
}
if (told) {
continue;
}
(void)snprintf(j->ask_told[j->ask_told_at++ % RMT_ASK_RING], sizeof j->ask_told[0], "%s", id);
if (j->ask_init) {
char *one = rmt_q("SELECT json_object('id', ?1, 'session', ?2, 'state', 'expired')", 2, id,
(const char *)sqlite3_column_text(q, 1));
if (one) {
if (b.len > 1) {
(void)rmt_buf_add(&b, ",", 1);
}
(void)rmt_buf_add(&b, one, strlen(one));
}
free(one);
}
}
sqlite3_finalize(q);
(void)rmt_buf_add(&b, "]", 2);
if (b.buf && b.len > 2) {
rmt_ask_records(j, b.buf, names, out, NULL);
}
free(b.buf);
}
/* The asks of J opened or closed since the last look, by version (an index), when the journal
* changed: each to every phone, an open one notified. The first look only learns where it is. */
static void rmt_ask_check(rmt_journal *j, const char *names, rmt_lines *out, rmt_tnotes *notes) {
long long v = rmt_data_version(j->s.db);
char *list;
rmt_ask_expiry(j, names, out);
if (v == j->ask_dv) {
return;
}
j->ask_dv = v;
if (!j->ask_init) {
sqlite3_stmt *q = NULL;
if (sqlite3_prepare_v2(j->s.db, "SELECT coalesce(max(version), 0) FROM pic_ask", -1, &q, NULL) == SQLITE_OK &&
sqlite3_step(q) == SQLITE_ROW) {
j->ask_version = sqlite3_column_int64(q, 0);
} else {
j->ask_version = 0; /* no asks yet: every one made from now on is news */
}
sqlite3_finalize(q);
j->ask_init = 1;
return;
}
if (!(list = pic_ask_list(&j->s, NULL, j->ask_version, RMT_ASKS))) {
j->s.err[0] = '\0';
j->ask_dv = -1; /* busy, say: looked at again next tick */
return;
}
rmt_ask_records(j, list, names, out, notes);
{
char *top = rmt_q("SELECT coalesce(max(json_extract(value, '$.version')), 0) FROM json_each(?1)", 1, list);
if (top && atoll(top) > j->ask_version) {
j->ask_version = atoll(top);
j->ask_dv = -1; /* there may be more than one page */
}
free(top);
}
free(list);
}
/* ---- a journal's tick job ------------------------------------------------------------------ */
/* A command waiting on a row of the journal: an inbox row to settle, a prompt to be admitted. */
typedef struct {
int di;
unsigned char dev[16];
char key[48], row[96];
int kind, expire, exited;
int settled, admitted; /* found */
char state[16], conv[64];
char *response;
} rmt_tcmd;
/* What a tick of one journal reads, on its lane: the phones' follows, its part of the list when a
* phone wants the list, the commands waiting on its rows, requests ended, questions and loops. */
typedef struct {
rmt_tfollow *fo;
int nfo;
rmt_tcmd *cm;
int ncm;
int list; /* build the part when the journal changed since list_dv and list_tc */
long long list_dv, list_tc;
unsigned list_gen;
char *names;
/* found */
int listed; /* 1: a new part; 2: the journal is as it was; -1: it ran out of time */
rmt_item *li;
size_t nli;
rmt_helpers *lh;
size_t nlh;
long long ldv, ltc, lms;
rmt_tnotes notes;
char notify[16]; /* remote.notify, read when the notes were made */
rmt_lines asks; /* ask and ask_settled, to every phone */
} rmt_tick;
static void rmt_tick_drop(void *p) {
rmt_tick *t = p;
if (!t) {
return;
}
for (int i = 0; i < t->nfo; i++) {
free(t->fo[i].wsess);
rmt_lines_free(&t->fo[i].out);
}
free(t->fo);
for (int i = 0; i < t->ncm; i++) {
free(t->cm[i].response);
}
free(t->cm);
free(t->names);
rmt_items_free(t->li, t->nli);
rmt_helpers_free(t->lh, t->nlh);
rmt_notes_free(&t->notes);
rmt_lines_free(&t->asks);
free(t);
}
/* Journal J's part of the list, built again only when it changed since (another process's
* commit, or this one's own write). One that runs out of time is given up, the last one kept. */
static void rmt_tick_list(rmt_tick *t, rmt_journal *j, int jx) {
long long dv = rmt_data_version(j->s.db), tc = (long long)sqlite3_total_changes64(j->s.db), t0 = rmt_mono_ms();
sqlite3_stmt *q = NULL;
if (t->list_dv == dv && t->list_tc == tc && dv >= 0) {
t->listed = 2;
return;
}
if (rmt_list_build(j, jx, RMT_LIST, RMT_LIST_BUDGET_MS, &t->li, &t->nli, &t->lh, &t->nlh) != 0) {
t->listed = -1;
return;
}
if (sqlite3_prepare_v2(j->s.db, "SELECT coalesce(max(updated_ms), 0) FROM pic_session", -1, &q, NULL) == SQLITE_OK &&
sqlite3_step(q) == SQLITE_ROW) {
t->lms = sqlite3_column_int64(q, 0);
}
sqlite3_finalize(q);
t->listed = 1;
t->ldv = dv;
t->ltc = tc;
#ifdef PIC_FAULTS
if (getenv("PIC_TEST_RC_LIST_TIMES")) { /* the tests' seam: how long each part took, and its work */
printf("pic remote: listed %s in %lld ms, %lld steps\n", j->path, rmt_mono_ms() - t0, rmt_list_steps);
(void)fflush(stdout);
}
#else
(void)t0;
#endif
}
/* The commands waiting on J's rows: an inbox row expired when due and its state read; a prompt's
* admission looked for. */
static void rmt_tick_cmds(rmt_tick *t, rmt_journal *j) {
for (int i = 0; i < t->ncm; i++) {
rmt_tcmd *c = &t->cm[i];
if (c->kind == CMD_INBOX) {
if (c->expire) { /* a write: not on every tick */
(void)pic_inbox_expire(&j->s, c->row);
}
if (pic_inbox_status(&j->s, c->row, c->state, sizeof c->state, &c->response) == 0 && strcmp(c->state, "pending") != 0) {
c->settled = 1;
}
} else {
c->admitted = rmt_admitted(&j->s, c->row, c->conv);
}
}
}
static void rmt_tick_run(rmt_job *jb) {
rmt_tick *t = jb->ctx;
rmt_journal *j = jb->j;
long long dv;
if (!j->sopen) {
return;
}
dv = rmt_data_version(j->s.db);
for (int i = 0; i < t->nfo; i++) {
int kept = 0;
for (int k = 0; k < j->nfollows && !kept; k++) { /* one given back since it was queued is closed */
kept = j->follows[k] == t->fo[i].f;
}
if (kept && (t->fo[i].now || dv != t->fo[i].fversion)) {
rmt_follow_pass(j, &t->fo[i], dv);
}
}
if (t->list) {
rmt_tick_list(t, j, jb->jx);
}
rmt_tick_cmds(t, j);
rmt_push_check(&t->notes, j);
rmt_wake_tick(&t->notes, j);
rmt_ask_check(j, t->names, &t->asks, &t->notes);
if (t->notes.n) { /* the setting as it is now, not as a look at the user database some time ago saw it */
char *v = pic_setting("remote.notify");
(void)snprintf(t->notify, sizeof t->notify, "%s", v && *v ? v : "all");
free(v);
}
}
static void rmt_tick_done(rmt_state *st, rmt_job *jb) {
rmt_tick *t = jb->ctx;
rmt_journal *j = jb->j;
j->ticking = 0;
for (int i = 0; i < t->nfo; i++) {
rmt_tfollow *fo = &t->fo[i];
rmt_dev *d = fo->di >= 0 && fo->di < st->ndevs ? &st->devs[fo->di] : NULL;
if (!d || !d->alive || memcmp(d->d.id, fo->dev, 16) != 0 || d->fgen != fo->gen || !d->f || !fo->ran) {
continue; /* not that follow any more, or nothing read */
}
for (int k = 0; k < fo->out.n; k++) {
(void)rmt_send(st, d, fo->out.v[k]);
}
if (fo->fev > d->fev) {
d->fev = fo->fev;
}
d->fversion = fo->fver;
if (fo->busy) {
d->follow_now = 1; /* looked at again next tick */
} else {
d->frunning = fo->running;
d->follow_now = fo->more;
}
}
if (t->listed == 1) {
rmt_items_free(j->li, j->nli);
rmt_helpers_free(j->lh, j->nlh);
j->li = t->li;
j->nli = t->nli;
j->lh = t->lh;
j->nlh = t->nlh;
t->li = NULL;
t->lh = NULL;
t->nli = t->nlh = 0;
j->list_dv = t->ldv;
j->list_tc = t->ltc;
j->list_ms = t->lms;
j->list_slow = 0;
j->list_ready = j->list_ready || t->list_gen == j->list_gen;
} else if (t->listed == 2) {
j->list_ready = j->list_ready || t->list_gen == j->list_gen;
} else if (t->listed == -1) {
if (!j->list_slow) {
printf("pic remote: listing %s took over %d ms; the phone sees its last list until it is done\n", j->path,
RMT_LIST_BUDGET_MS);
(void)fflush(stdout);
j->list_slow = 1;
}
j->list_ready = j->list_ready || t->list_gen == j->list_gen;
}
for (int i = 0; i < t->ncm; i++) {
rmt_tcmd *c = &t->cm[i];
rmt_dev *d = c->di >= 0 && c->di < st->ndevs ? &st->devs[c->di] : NULL;
int k;
if (!d || !d->alive || memcmp(d->d.id, c->dev, 16) != 0 || (k = rmt_cmd_find(d, c->key)) < 0 ||
strcmp(d->cmds[k].row, c->row) != 0 || d->cmds[k].kind != c->kind) {
continue;
}
if (c->kind == CMD_INBOX) {
if (!c->settled) {
continue;
}
if (d->sess >= 0) {
if (c->response) {
rmt_response(st, d, c->key, c->response);
} else {
rmt_send_free(st, d, rmt_q("SELECT json_object('type', 'response', 'key', ?1, 'payload', json_object('state', ?2))",
2, c->key, c->state));
}
}
rmt_cmd_drop(d, k);
} else if (c->admitted) {
if (d->sess >= 0) {
rmt_send_free(st, d, rmt_prompt_ok(j->path, c->key, c->conv));
}
rmt_cmd_drop(d, k);
} else if (c->exited && !jb->overran) { /* its child ended before the look, and nothing was admitted */
rmt_prompt_failed(st, d, &d->cmds[k]);
rmt_cmd_drop(d, k);
}
}
for (int i = 0; i < t->notes.n; i++) {
rmt_tnote *n = &t->notes.v[i];
rmt_notify(st, j, t->notify, n->conv, n->ctitle, n->phone, n->seq, n->body);
}
for (int k = 0; k < t->asks.n; k++) {
for (int i = 0; i < st->ndevs; i++) {
rmt_dev *o = &st->devs[i];
if (o->alive && o->sess >= 0 && st->sess[o->sess].confirmed) {
(void)rmt_send(st, o, t->asks.v[k]);
}
}
}
}
/* Journal JX's tick queued, with what the loop holds that it needs. */
static void rmt_tick_queue(rmt_state *st, int jx) {
rmt_journal *j = st->js[jx];
rmt_tick *t = calloc(1, sizeof *t);
long long now = rmt_mono_ms();
rmt_job *jb;
if (!t) {
return;
}
t->fo = calloc((size_t)st->ndevs + 1, sizeof *t->fo);
for (int i = 0; t->fo && i < st->ndevs; i++) {
rmt_dev *d = &st->devs[i];
rmt_tfollow *fo = &t->fo[t->nfo];
if (!d->alive || d->sess < 0 || !d->f || d->jx != jx) {
continue;
}
fo->di = i;
memcpy(fo->dev, d->d.id, 16);
fo->gen = d->fgen;
fo->f = d->f;
fo->now = d->follow_now && d->lane.qlen < RMT_POST_BYTES; /* a long history's next page once this one is on its way */
fo->fversion = d->fversion;
fo->earlier = d->earlier;
fo->wsess = d->wsess ? strdup(d->wsess) : NULL;
(void)snprintf(fo->skey, sizeof fo->skey, "%s", d->skey);
if (!fo->wsess) {
continue;
}
t->nfo++;
}
for (int i = 0; i < st->ndevs; i++) {
rmt_dev *d = &st->devs[i];
t->list = t->list || (d->alive && d->want_list && d->sess >= 0);
for (int k = 0; d->alive && k < d->ncmds; k++) {
rmt_cmd *c = &d->cmds[k];
rmt_tcmd *g;
if (c->jx != jx || (c->kind != CMD_INBOX && c->kind != CMD_PROMPT) ||
!(g = realloc(t->cm, (size_t)(t->ncm + 1) * sizeof *g))) {
continue;
}
t->cm = g;
memset(&g[t->ncm], 0, sizeof g[t->ncm]);
g[t->ncm].di = i;
memcpy(g[t->ncm].dev, d->d.id, 16);
(void)snprintf(g[t->ncm].key, sizeof g[t->ncm].key, "%s", c->key);
(void)snprintf(g[t->ncm].row, sizeof g[t->ncm].row, "%s", c->row);
g[t->ncm].kind = c->kind;
g[t->ncm].exited = c->exited;
if (c->kind == CMD_INBOX && now - c->expire_ms >= 5000) {
c->expire_ms = now;
g[t->ncm].expire = 1;
}
t->ncm++;
}
}
t->list_dv = j->list_dv;
t->list_tc = j->list_tc;
t->list_gen = j->list_gen;
t->names = strdup(rmt_names(st));
if ((jb = rmt_job_new(st, j, NULL, rmt_tick_run, rmt_tick_done, rmt_tick_drop, t, "following and watching a journal"))) {
jb->budget_ms = RMT_TICK_MS;
jb->background = 1;
(void)snprintf(jb->what, sizeof jb->what, "following and watching %s", j->path);
j->ticking = 1;
j->tick_ms = now;
}
rmt_job_add(st, jb);
}
static void rmt_serve_tick(rmt_state *st) {
long long now = rmt_mono_ms();
for (int i = 0; i < RMT_SESSIONS; i++) {
rmt_sess *s = &st->sess[i];
if (!s->used) {
continue;
}
/* A phone that did not start again after bye, or a session at the counters' end, is dropped. */
int ignored_bye = s->bye_ms && now - s->bye_ms > (rmt_rekey_ms() < RMT_BYE_GRACE_MS ? rmt_rekey_ms() : RMT_BYE_GRACE_MS);
int spent = s->t.send_n >= (1ull << 32) - 1024 || s->t.last >= (int64_t)((1ll << 32) - 1024);
if ((!s->confirmed && now - s->started_ms > RMT_UNCONFIRMED_MS) || now - s->heard_ms > RMT_SILENT_MS || ignored_bye || spent) {
if (st->devs[s->dev].sess == i) {
st->devs[s->dev].sess = -1;
}
free(s->msg.buf);
memset(s, 0, sizeof *s);
} else if (s->confirmed && !s->bye_ms &&
(now - s->started_ms > rmt_rekey_ms() || s->t.send_n >= 0xfff00000u || s->t.last >= (int64_t)0xfff00000u)) {
rmt_dev *d = &st->devs[s->dev];
if (d->sess == i) {
rmt_send_free(st, d, strdup("{\"type\":\"bye\",\"payload\":{\"reason\":\"rekey\"}}"));
s->bye_ms = now; /* asked once */
}
}
}
rmt_doing("applying what the poster sent", NULL);
rmt_posts_apply(st);
rmt_doing("applying what the workers found", NULL);
rmt_jobs_collect(st);
for (int i = 0; i < st->ndevs; i++) {
rmt_dev *d = &st->devs[i];
if (!d->alive) {
for (int k = 0; k < d->ncmds; k++) { /* an unpaired phone's children are waited for all the same */
rmt_orphan(d->cmds[k].pid);
d->cmds[k].pid = 0;
}
continue;
}
if (d->sess >= 0) {
if (d->want_list && !d->list_sent && (rmt_lists_ready(st) || now - d->want_list_ms > 2000)) {
rmt_doing("checking the conversation list for", d->d.name); /* asked for now; looked at again each second */
rmt_list_check(st, d);
}
rmt_doing("reading the reply as it streams for", d->d.name);
rmt_live(st, d);
}
rmt_doing("looking at the commands of", d->d.name);
rmt_commands_poll(st, d);
rmt_uploads_tick(st, d);
rmt_doing("posting to the relay for", d->d.name);
rmt_lane_post(&st->post, &st->r, st->pool.wake[1], &d->lane);
}
for (int i = 0; i < st->njs && !st->draining; i++) {
if (st->js[i]->open && !st->js[i]->ticking && now - st->js[i]->tick_ms >= RMT_TICK_JOB_MS) {
rmt_tick_queue(st, i);
}
}
rmt_doing("waiting for ended children", NULL);
rmt_reap();
rmt_doing("taking the push service's answers", NULL);
rmt_push_results(st);
rmt_doing("watching the jobs in hand", NULL);
rmt_jobs_watch(st);
}
/* How pic remote was started: at a terminal, by /rc (the key on an inherited pipe), or by the
* login agent (pic remote install), which must not fail where waiting or leaving is right: a
* failure is started again. */
enum { RMT_TERMINAL, RMT_DETACHED, RMT_LOGIN };
/* ---- a newer pic installed over this one --------------------------------------------------- */
/* 1 when this pic remote should start again: pic remote restart asked, or the file it runs was
* replaced and has then kept still for 2 s (an install is not caught halfway). */
static int rmt_exe_changed(void) {
static long long checked_ms, new_ms;
static char seen[128];
const pic_platform *p = pic_platform_get();
char now[128];
long long t = rmt_mono_ms();
if (rmt_restart_asked) {
return 1;
}
if (!p->file_stamp || !rmt_exe[0] || !rmt_exe_stamp[0] || t - checked_ms < 500) {
return 0;
}
checked_ms = t;
if (p->file_stamp(rmt_exe, now, sizeof now) != 0 || strcmp(now, rmt_exe_stamp) == 0 || access(rmt_exe, X_OK) != 0) {
seen[0] = '\0';
return 0;
}
if (strcmp(now, seen) != 0) {
(void)snprintf(seen, sizeof seen, "%s", now);
new_ms = t;
return 0;
}
{
long long settle = 2000;
#ifdef PIC_FAULTS
if (getenv("PIC_TEST_RC_SETTLE_MS")) { /* the tests' seam: a replaced file noticed and not acted on */
settle = atoll(getenv("PIC_TEST_RC_SETTLE_MS"));
}
#endif
return t - new_ms >= settle;
}
}
/* Nothing in hand that a restart would lose: no command waiting for its row or its child, no
* record waiting to be posted, no message half received, no pairing open, no push on its way. */
static int rmt_quiet(rmt_state *st) {
int busy;
if (st->offer || rmt_jobs_keyed(st) || rmt_norphans || st->post.acking) {
return 0; /* a child not yet waited for would be a stranger to the newer pic */
}
for (int i = 0; i < st->ndevs; i++) {
if (st->devs[i].alive && (st->devs[i].ncmds > 0 || st->devs[i].lane.qlen > 0)) {
return 0;
}
}
for (int i = 0; i < RMT_SESSIONS; i++) {
if (st->sess[i].used && st->sess[i].msg.len > 0) {
return 0;
}
}
(void)pthread_mutex_lock(&st->push.mu);
busy = st->push.ntodo > 0 || st->push.ndone > 0 || st->push.sending;
(void)pthread_mutex_unlock(&st->push.mu);
return !busy;
}
/* ---- a newer pic migrating a journal ------------------------------------------------------ */
/* Each second, a keeping job per journal, on its lane: one that a newer pic waits to migrate
* (pic_migration_wanted) is closed once nothing under way needs it (QUIET, as the loop saw it), its
* follows with it (rmt_lane_seen tells their phones); one closed so is opened again when no
* migration waits, or shown as a newer pic's once one has migrated it; an older pic's is updated
* once nothing has it open. */
static void rmt_keep_run(rmt_job *jb) {
rmt_journal *j = jb->j;
const char *base = strrchr(j->workspace, '/');
int quiet = *(int *)jb->ctx;
base = base && base[1] ? base + 1 : j->workspace;
if (j->sopen && quiet && pic_migration_wanted(&j->s)) {
while (j->nfollows) {
rmt_follow_forget(j, j->follows[0]);
}
pic_close(&j->s);
j->sopen = 0;
j->yielded = 1;
(void)snprintf(j->why, sizeof j->why, "a newer pic is updating %s", base);
rmt_log(stdout, "pic remote: let go of %s for a newer pic to update it\n", j->path);
(void)fflush(stdout);
} else if (!j->sopen && j->yielded) {
long sv;
if (rmt_serve_open(j, 1) == 0) {
rmt_log(stdout, "pic remote: serving %s again\n", j->path);
(void)fflush(stdout);
} else if ((sv = rmt_journal_schema(j->path)) != atol(PIC_SCHEMA_VERSION)) {
j->yielded = 0; /* not this pic's: a newer one's (a restart as it can read it), or still older */
rmt_why(j, sv);
}
} else if (!j->sopen && j->older) {
(void)rmt_update(j);
}
}
static void rmt_keep_done(rmt_state *st, rmt_job *jb) {
(void)st;
jb->j->keeping = 0;
}
/* Nothing in hand that needs a journal open: no command waiting for its row or its child, no
* message half received, no answer a job owes. Records waiting to be posted, a push, the stream's
* acknowledgement and children no longer tied to a command do not count: a journal is let go of
* without them, and they are in flight at the very tick that looks, now that the poster sends them
* on its own time. */
static int rmt_journals_quiet(rmt_state *st) {
if (rmt_jobs_keyed(st)) {
return 0;
}
for (int i = 0; i < st->ndevs; i++) {
if (st->devs[i].alive && st->devs[i].ncmds > 0) {
return 0;
}
}
for (int i = 0; i < RMT_SESSIONS; i++) {
if (st->sess[i].used && st->sess[i].msg.len > 0) {
return 0;
}
}
return 1;
}
static void rmt_yield_tick(rmt_state *st) {
int quiet = rmt_journals_quiet(st);
for (int i = 0; i < st->njs && !st->draining; i++) {
rmt_journal *j = st->js[i];
int *q;
rmt_job *jb;
if (j->keeping || j->hidden || !(q = malloc(sizeof *q))) {
continue;
}
*q = quiet;
if ((jb = rmt_job_new(st, j, NULL, rmt_keep_run, rmt_keep_done, free, q, "keeping a journal"))) {
j->keeping = 1;
jb->background = 1;
}
rmt_job_add(st, jb);
}
}
/* This process becomes the pic now at rmt_exe, keeping its pid (/rc's watch and the login agent see
* one process throughout): a bye to each session (the phone starts a new one, as after any
* restart; nothing else lives only in memory), then exec. The store's key goes on as /rc hands it
* over; the login agent's opens the store itself. Returns only when exec failed. */
static void rmt_restart(rmt_state *st, int mode) {
int keyfd = -1;
for (int i = 0; i < st->ndevs; i++) {
rmt_dev *d = &st->devs[i];
if (d->alive && d->sess >= 0) {
rmt_send_free(st, d, strdup("{\"type\":\"bye\",\"payload\":{\"reason\":\"restart\"}}"));
d->lane.retry_ms = 0;
(void)rmt_lane_flush(&st->r, &d->lane);
}
}
rmt_status_write("restarting", st->r.base, 0, 0, 0, NULL, 0, 0);
rmt_log(stdout, "pic remote: %s; starting %s\n", rmt_restart_asked ? "asked to restart" : "a newer pic was installed",
rmt_exe);
(void)fflush(stdout);
(void)fflush(stderr);
if (mode != RMT_LOGIN) {
char num[16];
if ((keyfd = pic_cred_handoff()) < 0) {
rmt_log(stderr, "pic remote: cannot hand the store's key to the new pic; going on as this one\n");
return;
}
(void)fcntl(keyfd, F_SETFD, 0);
(void)snprintf(num, sizeof num, "%d", keyfd);
(void)setenv("PIC_KEY_FD", num, 1);
}
execl(rmt_exe, rmt_exe, "remote", mode == RMT_LOGIN ? "--login" : "--detached", (char *)NULL);
rmt_log(stderr, "pic remote: cannot start %s: %s; going on as this one\n", rmt_exe, strerror(errno));
(void)unsetenv("PIC_KEY_FD");
if (keyfd >= 0) {
close(keyfd);
}
}
/* What pic remote install and --login say of a store that asks for a passphrase. */
#define RMT_NEEDS_QUIET \
"pic remote: the credential store asks for a passphrase, and no one is there to type it at login; move its key " \
"with pic auth rekey keychain (or pic auth rekey file), then run pic remote install\n"
static int rmt_serve(const pic_remote_options *o, int mode) {
rmt_state st;
rmt_stream str;
char err[512];
int lock, pfd[2], waiting = 0;
long long last_list = 0, last_user = 0, last_yield = 0, tick_mono, tick_wall;
long long ack_id = 0, ack_recs = 0, ack_bytes = 0, ack_since = 0, ack_try = 0;
struct sigaction sa;
memset(&st, 0, sizeof st);
st.o = o;
st.lockfd = -1;
#ifdef PIC_FAULTS
if (getenv("PIC_TEST_RC_DEADLINE_S")) { /* the tests' seam: a pic remote a killed test left ends by itself */
(void)alarm((unsigned)atoi(getenv("PIC_TEST_RC_DEADLINE_S"))); /* kept across a restart's exec */
}
#endif
/* Held by someone for a moment is not held by a second pic remote: every pic remote status,
* /rc and terminal footer tries this lock for an instant to see whether one runs, and a
* restart's exec leaves it free while the new image starts. Waited for up to RMT_LOCK_WAIT_MS. */
{
long long until = rmt_mono_ms() + RMT_LOCK_WAIT_MS; /* polled every 1 ms: a holder that lets go for a few ms
between turns (a stream of status probes) is not missed */
while ((lock = rmt_lock()) == -2 && rmt_mono_ms() < until) {
struct timespec ts = {0, 1000000L};
(void)nanosleep(&ts, NULL);
}
}
if (lock < 0) {
rmt_log(stderr, "%s",
lock == -2 ? "pic remote: one is already running for this user\n" : "pic remote: cannot take ~/.pic/remote.lock\n");
return lock == -2 && mode == RMT_LOGIN ? 0 : 1;
}
st.lockfd = lock;
(void)fcntl(lock, F_SETFD, FD_CLOEXEC);
{
const pic_platform *p = pic_platform_get();
rmt_started_ms = rmt_wall_ms();
if (!p->self_path || p->self_path(rmt_exe, sizeof rmt_exe) != 0 || !p->file_stamp ||
p->file_stamp(rmt_exe, rmt_exe_stamp, sizeof rmt_exe_stamp) != 0) {
rmt_exe[0] = rmt_exe_stamp[0] = '\0';
}
}
rmt_status_write("starting", NULL, 0, 0, 0, NULL, 0, 0);
/* At the terminal the key comes from the store's source every time (a passphrase store asks).
* Started by /rc (detached), the key is
* the one the person at the terminal just unlocked, handed down on an inherited pipe. */
memset(&sa, 0, sizeof sa);
sa.sa_handler = rmt_on_signal;
sigemptyset(&sa.sa_mask);
(void)sigaction(SIGINT, &sa, NULL);
(void)sigaction(SIGTERM, &sa, NULL);
(void)sigaction(SIGUSR1, &sa, NULL);
(void)signal(SIGPIPE, SIG_IGN);
if (mode == RMT_LOGIN) { /* no one to ask: a store that needs a passphrase, or none yet, is not a failure */
int q = pic_cred_state() == PIC_CRED_NEW ? 2 : pic_cred_quiet(err, sizeof err);
if (q != 0) {
if (q == 2) {
rmt_log(stderr, "pic remote: the credential store has no key yet: pair a phone with /rc or pic remote pair\n");
} else if (q == 1) {
rmt_log(stderr, "%s", RMT_NEEDS_QUIET);
} else {
rmt_log(stderr, "pic remote: %s\n", err);
}
rmt_status_write("stopped", NULL, 0, 0, 0, q < 0 ? err : NULL, 0, 0);
return q < 0 ? 1 : 0;
}
} else if ((mode == RMT_DETACHED ? pic_cred_unlock(err, sizeof err) : rmt_unlock_fresh(err, sizeof err)) != 0) {
rmt_log(stderr, "pic remote: %s\n", err);
rmt_status_write("stopped", NULL, 0, 0, 0, err, 0, 0);
return 1;
}
for (;;) {
int rc = rmt_keys_load(&st.k, 0, err, sizeof err);
if (rc < 0 || (rc > 0 && mode != RMT_LOGIN)) {
rmt_log(stderr, "pic remote: %s\n",
rc > 0 ? "no phone is paired: pair one with /rc in pic, or pic remote pair" : err);
return 1;
}
if (rc == 0) {
break;
}
if (!waiting) { /* started at login before the first pairing: it waits for one */
rmt_log(stdout, "pic remote: no phone is paired yet; pair one with /rc in pic (waiting)\n");
(void)fflush(stdout);
rmt_status_write("waiting for a phone", NULL, 0, 0, 0, NULL, 0, 0);
waiting = 1;
}
for (int t = 0; t < 10 && !rmt_stop; t++) {
struct timespec ts = {0, 100000000L};
(void)nanosleep(&ts, NULL);
}
if (rmt_stop) {
rmt_status_write("stopped", NULL, 0, 0, 0, NULL, 0, 0);
return 0;
}
}
rmt_relay_init(&st.r, &st.k);
/* the pusher's VAPID key and the token's sub, the relay's origin (section 5) */
(void)pthread_mutex_init(&st.push.mu, NULL);
(void)pthread_cond_init(&st.push.cv, NULL);
memcpy(st.push.vapid.priv, st.k.vapid.priv, sizeof st.push.vapid.priv);
if (pic_webpush_origin(st.r.base, st.push.subject, sizeof st.push.subject) < 0) {
(void)snprintf(st.push.subject, sizeof st.push.subject, "%s", PIC_REMOTE_RELAY);
}
st.push.vapid.subject = st.push.subject;
st.user_version = rmt_data_version(pic_userdb(NULL, 0));
if (rmt_devices_sync(&st, 1) != 0) {
rmt_log(stderr, "pic remote: cannot read the paired devices\n");
return 1;
}
while (!rmt_stop) { /* with no device paired: say so, and wait for one */
int alive = 0;
for (int i = 0; i < st.ndevs; i++) {
alive += st.devs[i].alive;
}
if (alive) {
break;
}
if (!waiting) {
rmt_log(stdout, "pic remote: no phone is paired yet; pair one with /rc in pic (waiting)\n");
(void)fflush(stdout);
rmt_status_write("waiting for a phone", st.r.base, 0, 0, 0, NULL, 0, 0);
waiting = 1;
}
{
struct timespec ts = {1, 0};
(void)nanosleep(&ts, NULL);
}
(void)rmt_devices_sync(&st, 1);
}
if (rmt_stop) {
return 0;
}
{ /* the relay unreachable at the start is waited for, as a broken stream is; a refusal is not */
long long wait = 1000;
int tries = 0;
while (!rmt_stop && rmt_reconcile(&st, err, sizeof err) != 0) {
unsigned char j;
long long w;
if (st.r.last_status > 0) {
rmt_log(stderr, "pic remote: %s\n", err);
rmt_status_write("stopped", st.r.base, 0, 0, 0, err, 0, 0);
return 1;
}
(void)pic_platform_get()->entropy(&j, 1);
w = wait - wait / 5 + (long long)j * (2 * wait / 5) / 255;
rmt_log(stderr, "pic remote: the relay %s is unreachable (%s); trying again in %lld s\n", st.r.base, err,
(w + 999) / 1000);
rmt_status_write("reconnecting", st.r.base, 0, ++tries, rmt_wall_ms() + w, err, 0, 0);
for (long long t = 0; t < w && !rmt_stop; t += 100) {
struct timespec ts = {0, 100000000L};
(void)nanosleep(&ts, NULL);
}
wait = wait * 2 > RMT_BACKOFF_MAX_MS ? RMT_BACKOFF_MAX_MS : wait * 2;
}
if (rmt_stop) {
rmt_status_write("stopped", st.r.base, 0, 0, 0, NULL, 0, 0);
return 0;
}
}
rmt_user_look(&st, 1); /* the workspaces, read and opened here before the workers start */
if (rmt_pool_start(&st) != 0) {
rmt_log(stderr, "pic remote: cannot start the workers\n");
return 1;
}
if (pipe(pfd) != 0) {
rmt_log(stderr, "pic remote: %s\n", strerror(errno));
return 1;
}
(void)fcntl(pfd[0], F_SETFL, O_NONBLOCK);
(void)fcntl(pfd[0], F_SETFD, FD_CLOEXEC);
(void)fcntl(pfd[1], F_SETFD, FD_CLOEXEC);
memset(&str, 0, sizeof str);
(void)snprintf(str.url, sizeof str.url, "%s/v1/m/%s/up", st.r.base, st.r.mbx);
(void)snprintf(str.auth, sizeof str.auth, "%s", st.r.owner);
str.mailbox = 1;
st.pipe_w = pfd[1];
if (rmt_stream_start(&str, pfd[1]) != 0) {
rmt_log(stderr, "pic remote: cannot start the stream reader\n");
return 1;
}
{
int alive = 0;
for (int i = 0; i < st.ndevs; i++) {
alive += st.devs[i].alive;
}
rmt_log(stdout, "pic remote: connected to %s; %d device%s, %d workspace%s\n", st.r.base, alive, alive == 1 ? "" : "s",
st.njs, st.njs == 1 ? "" : "s");
(void)fflush(stdout);
}
tick_mono = rmt_mono_ms();
tick_wall = rmt_wall_ms();
{
pthread_t wt;
sigset_t all, was;
atomic_store(&rmt_beat_ms, tick_mono);
sigfillset(&all);
pthread_sigmask(SIG_BLOCK, &all, &was); /* signals are the loop's */
if (pthread_create(&wt, NULL, rmt_watch_main, NULL) == 0) {
(void)pthread_detach(wt);
}
pthread_sigmask(SIG_SETMASK, &was, NULL);
}
while (!rmt_stop) {
struct timeval tv = {0, 100000};
fd_set rs;
long long now = rmt_mono_ms(), wall = rmt_wall_ms();
long long stuck;
atomic_store(&rmt_beat_ms, now);
stuck = atomic_exchange(&rmt_stuck_ms, 0);
rmt_doing("starting a tick", NULL);
if (stuck) {
rmt_log(stdout, "pic remote: the loop is moving again after %lld s\n", (now - stuck) / 1000);
}
#ifdef PIC_FAULTS
while (getenv("PIC_TEST_RC_STALL_FILE") && access(getenv("PIC_TEST_RC_STALL_FILE"), F_OK) == 0) {
struct timespec ts = {0, 50000000L}; /* the tests' seam: the loop held until the file goes */
rmt_doing("held by", "PIC_TEST_RC_STALL_FILE");
(void)nanosleep(&ts, NULL);
}
#endif
/* A wake from sleep or a SIGCONT: the tick came far too late, or the wall clock ran ahead
* of the monotonic one (which stops in sleep on some systems). The stream may be a ghost
* and every wait is stale: reconnect at once and post what waits. A stall the watchdog saw
* was not a sleep, but leaves the same to do. */
if (now - tick_mono > RMT_JUMP_MS || (wall - tick_wall) - (now - tick_mono) > RMT_JUMP_MS) {
long long gap = (wall - tick_wall) > (now - tick_mono) ? wall - tick_wall : now - tick_mono;
rmt_log(stdout, stuck ? "pic remote: back after %lld s (stalled); reconnecting\n"
: "pic remote: back after %lld s (asleep or stopped); reconnecting\n",
gap / 1000);
(void)fflush(stdout);
atomic_store(&str.kick, 1);
for (int i = 0; i < st.ndevs; i++) {
rmt_lane_restamp(&st.devs[i].lane);
}
}
tick_mono = now;
tick_wall = wall;
rmt_doing("writing the status file", NULL);
rmt_status_tick(&st, &str, 0);
FD_ZERO(&rs);
FD_SET(pfd[0], &rs);
FD_SET(st.pool.wake[0], &rs);
rmt_doing("waiting on the stream pipe", NULL);
if (select((pfd[0] > st.pool.wake[0] ? pfd[0] : st.pool.wake[0]) + 1, &rs, NULL, NULL, &tv) > 0 && FD_ISSET(pfd[0], &rs)) {
for (;;) {
int kind, got;
unsigned char ch[16], rec[PIC_NOISE_RECORD_CAP];
size_t n;
rmt_doing("reading the stream pipe", NULL);
got = rmt_pipe_read(pfd[0], &kind, ch, rec, &n);
if (got <= 0) {
if (got < 0) {
rmt_stop = 1;
}
break;
}
if (st.offer && memcmp(ch, st.offer->P, 16) == 0) {
rmt_doing("pairing a new phone", NULL);
rmt_offer_event(&st, kind, rec, n);
} else if (kind == RMT_EV_FRAME) {
int di = rmt_dev_by_channel(&st, ch);
rmt_doing("reading a record from", di >= 0 ? st.devs[di].d.name : "the relay");
rmt_record(&st, ch, rec, n);
} else if (memcmp(ch, str.channel, 16) != 0) {
/* an ended offer's stream, not yet gone */
} else if (kind == RMT_EV_REPLACED) {
rmt_log(stderr, "pic remote: another connection took the relay's stream; stopping\n");
rmt_stop = 1;
} else if (kind == RMT_EV_GONE || kind == RMT_EV_REFUSED) {
rmt_log(stderr, "pic remote: the relay no longer has this mailbox (it was reset); stopping\n");
rmt_stop = 1;
}
}
}
/* A phone on screen pings each minute. Keepalives on a stream that brings none of its
* records say only that the connection is open, not that the relay still writes to it:
* a new one resumes from Last-Event-ID. */
if (atomic_load(&str.state) == RMT_CONN_CONNECTED && now - atomic_load(&str.heard_ms) > rmt_quiet_ms()) {
for (int i = 0; i < st.ndevs; i++) {
rmt_dev *d = &st.devs[i];
if (d->alive && d->sess >= 0 && st.sess[d->sess].confirmed && d->visible) {
rmt_log(stdout, "pic remote: no record in %lld s while %s is open; reconnecting\n",
(now - atomic_load(&str.heard_ms)) / 1000, d->d.name);
atomic_store(&str.heard_ms, now);
atomic_store(&str.kick, 1);
break;
}
}
}
if ((now - last_user >= 1000 || st.user_force) && !st.draining) { /* devices paired or unpaired meanwhile, new workspaces */
last_user = now;
rmt_doing("asking for the paired devices and workspaces", NULL);
rmt_user_look(&st, st.user_force);
}
if (now - last_list >= 1000) {
last_list = now;
for (int i = 0; i < st.ndevs; i++) {
if (st.devs[i].alive && st.devs[i].want_list && st.devs[i].list_sent && st.devs[i].sess >= 0) {
rmt_doing("checking the conversation list for", st.devs[i].d.name);
rmt_list_check(&st, &st.devs[i]);
}
}
}
{ /* Pic-Ack (section 6): what the stream read goes with every post, and on its own, with a
* list request, when much waits or it has waited; the relay holds a lane's records until
* then, and a full lane stalls a phone's large message */
long long id = atomic_load(&str.read_id), recs = atomic_load(&str.read_records);
long long bytes = atomic_load(&str.read_bytes);
st.r.acked = 0;
st.r.ack[0] = '\0';
if (id > ack_id) {
(void)snprintf(st.r.ack, sizeof st.r.ack, "%lld", id);
ack_since = ack_since ? ack_since : now;
}
rmt_doing("serving the phones", NULL);
rmt_serve_tick(&st);
if (st.r.acked && id > st.acked) { /* a call made on the loop carried it */
st.acked = id;
}
if (st.r.ack[0] && st.acked < id && now - ack_try >= 1000 &&
(recs - ack_recs >= RMT_ACK_RECORDS || bytes - ack_bytes >= RMT_ACK_BYTES || now - ack_since >= RMT_ACK_MS)) {
ack_try = now;
rmt_doing("acknowledging the stream to the relay", NULL);
rmt_ack_post(&st);
}
if (st.acked > ack_id) {
ack_id = st.acked;
ack_recs = recs;
ack_bytes = bytes;
ack_since = 0;
}
st.r.ack[0] = '\0';
}
rmt_doing("pairing a new phone", NULL);
rmt_offer_tick(&st);
if (now - last_yield >= 1000) {
last_yield = now;
rmt_doing("checking for journals to let go", NULL);
rmt_yield_tick(&st);
}
rmt_doing("checking for a newer pic", NULL);
if (!rmt_stop && !st.newer && rmt_exe_changed()) {
st.newer = 1;
}
st.draining = st.newer && rmt_quiet(&st); /* the restart waits for the jobs in hand, starting none */
if (st.draining && !st.held) {
const pic_platform *p = pic_platform_get();
rmt_doing("starting the newer pic", NULL);
rmt_restart(&st, mode); /* back only when it failed: not tried again for this file */
rmt_restart_asked = 0;
st.newer = st.draining = 0;
(void)p->file_stamp(rmt_exe, rmt_exe_stamp, sizeof rmt_exe_stamp);
}
}
if (st.offer) { /* stopped with an offer open: the new device hears no, the channel goes */
rmt_offer_refuse(st.offer, &st.r);
st.offer->lane.retry_ms = 0;
(void)rmt_lane_flush(&st.r, &st.offer->lane);
rmt_offer_close(&st);
}
for (int i = 0; i < st.ndevs; i++) { /* SIGINT, SIGTERM: bye to each session */
rmt_dev *d = &st.devs[i];
if (d->alive && d->sess >= 0) {
rmt_send_free(&st, d, strdup("{\"type\":\"bye\",\"payload\":{\"reason\":\"stopped\"}}"));
d->lane.retry_ms = 0;
(void)rmt_lane_flush(&st.r, &d->lane);
}
}
rmt_status_write("stopped", st.r.base, 0, 0, 0, NULL, 0, 0);
puts("pic remote: stopped");
(void)fflush(stdout);
_exit(0); /* the stream thread may be in a read; the kernel drops the lock */
}
/* ---- pairing (section 2) ----------------------------------------------------------------------- */
typedef struct {
int pipe_mode; /* --pipe: JSON lines out, y or n on stdin */
} rmt_pair_opts;
static void rmt_say(int pipe_mode, const char *type, const char *k1, const char *v1, const char *k2, const char *v2) {
if (pipe_mode) {
char *line = rmt_q("SELECT json_patch('{}', json_object('type', ?1, ?2, ?3, ?4, ?5))", 5, type, k1 ? k1 : "x", v1,
k2 ? k2 : "y", v2);
if (line) {
puts(line);
}
free(line);
(void)fflush(stdout);
}
}
/* The last word (paired, or a refusal) is posted, and the pairing channel is deleted only once the
* phone has it: deleting the channel drops what the relay holds, so a phone that was reconnecting
* when the word was posted would lose it. A post answered Pic-Peer: 1 went to a phone reading the
* lane; after Pic-Peer: 0 it waits for the relay's peer event that the phone is back (the relay
* sends it what it holds as it reconnects), at most RMT_LAST_WORD_MS; with no Pic-Peer at all,
* RMT_NO_PEER_MS. */
static void rmt_pair_last_word(rmt_relay *r, rmt_lane *lane, int fd, int said) {
long long until = rmt_mono_ms() + RMT_LAST_WORD_MS;
int reading = -1, posted = 0;
if (!said) {
return; /* nothing to say: no handshake was made */
}
if (!lane->qlen) { /* posted already: the post's answer says whether the phone read it */
posted = 1;
reading = r->peer;
if (reading < 0) {
until = rmt_mono_ms() + RMT_NO_PEER_MS;
}
}
while (rmt_mono_ms() < until) {
struct timeval tv = {0, 100000};
fd_set rs;
if (lane->qlen) {
lane->retry_ms = 0;
(void)rmt_lane_flush(r, lane);
if (!lane->qlen) {
posted = 1;
reading = r->peer;
if (reading < 0) {
until = rmt_mono_ms() + RMT_NO_PEER_MS;
}
}
}
if (posted && reading == 1) {
return;
}
FD_ZERO(&rs);
FD_SET(fd, &rs);
if (select(fd + 1, &rs, NULL, NULL, &tv) > 0) {
int kind, got;
unsigned char ch[16], rec[PIC_NOISE_RECORD_CAP];
size_t n;
while ((got = rmt_pipe_read(fd, &kind, ch, rec, &n)) == 1) {
if (kind == RMT_EV_PEER && n == 1 && posted && rec[0] == 1) {
return; /* the phone is back, and has been sent what the relay held */
}
if (kind == RMT_EV_GONE || kind == RMT_EV_REFUSED) {
return;
}
}
if (got < 0) {
return;
}
}
}
}
/* A yes or no from the terminal: one key, y pairs and anything else does not. --pipe reads a line. */
/* The terminal as the question found it, while it takes one key without Enter or echo: select
* on a terminal in line mode is not ready for a key alone on Linux, so the mode is changed when
* the question is asked, not when a key has come. */
static struct termios rmt_pair_was;
static int rmt_pair_keyed;
static void rmt_pair_keys_on(void) {
struct termios raw;
if (!rmt_pair_keyed && isatty(STDIN_FILENO) && tcgetattr(STDIN_FILENO, &rmt_pair_was) == 0) {
raw = rmt_pair_was;
raw.c_lflag &= (tcflag_t) ~(ICANON | ECHO);
raw.c_cc[VMIN] = 1;
raw.c_cc[VTIME] = 0;
(void)tcsetattr(STDIN_FILENO, TCSANOW, &raw);
rmt_pair_keyed = 1;
}
}
static void rmt_pair_keys_off(void) {
if (rmt_pair_keyed) {
(void)tcsetattr(STDIN_FILENO, TCSANOW, &rmt_pair_was);
rmt_pair_keyed = 0;
}
}
/* A hangup or quit while the terminal takes single keys: it is put back, then the signal has its
* way. tcsetattr and sigaction are async-signal-safe. */
static void rmt_pair_fatal(int sig) {
struct sigaction dfl;
rmt_pair_keys_off();
memset(&dfl, 0, sizeof dfl);
dfl.sa_handler = SIG_DFL;
(void)sigaction(sig, &dfl, NULL);
(void)raise(sig);
}
static int rmt_pair_answer(int pipe_mode) {
char line[64];
int tty = !pipe_mode && rmt_pair_keyed;
ssize_t n = read(STDIN_FILENO, line, tty ? 1 : sizeof line - 1);
if (tty) {
rmt_pair_keys_off();
printf("%c\n", n > 0 && (line[0] == 'y' || line[0] == 'Y') ? 'y' : 'n');
}
return n > 0 && (line[0] == 'y' || line[0] == 'Y');
}
static int rmt_pair(const pic_remote_options *o, int pipe_mode) {
rmt_keys k;
rmt_relay r;
rmt_stream str;
rmt_offer of;
char err[512], tok[64];
long long expires;
int pfd[2], rc = 1, ttl, over = 0;
if (pic_cred_prepare(err, sizeof err) != 0 || rmt_keys_load(&k, 1, err, sizeof err) != 0) {
rmt_say(pipe_mode, "error", "message", err, NULL, NULL);
fprintf(stderr, "pic remote: %s\n", err);
return 1;
}
{
struct sigaction sa;
memset(&sa, 0, sizeof sa);
sa.sa_handler = rmt_on_signal; /* /rc closed, or Ctrl-C: the offer ends with a refusal */
sigemptyset(&sa.sa_mask);
(void)sigaction(SIGINT, &sa, NULL);
(void)sigaction(SIGTERM, &sa, NULL);
sa.sa_handler = rmt_pair_fatal;
(void)sigaction(SIGHUP, &sa, NULL);
(void)sigaction(SIGQUIT, &sa, NULL);
}
(void)atexit(rmt_pair_keys_off);
(void)signal(SIGPIPE, SIG_IGN);
rmt_relay_init(&r, &k);
if (rmt_put_mailbox(&r, err, sizeof err) != 0) {
rmt_say(pipe_mode, "error", "message", err, NULL, NULL);
fprintf(stderr, "pic remote: %s\n", err);
return 1;
}
ttl = RMT_PAIR_TTL;
#ifdef PIC_FAULTS
if (getenv("PIC_TEST_PAIR_TTL")) { /* the tests' seam: an offer that ends in seconds */
ttl = atoi(getenv("PIC_TEST_PAIR_TTL"));
}
#endif
if (rmt_offer_open(&of, &r, &k, ttl, err, sizeof err) != 0) {
rmt_say(pipe_mode, "error", "message", err, NULL, NULL);
fprintf(stderr, "pic remote: %s\n", err);
return 1;
}
expires = of.expires;
if (pipe(pfd) != 0) {
return 1;
}
(void)fcntl(pfd[0], F_SETFL, O_NONBLOCK);
memset(&str, 0, sizeof str);
pic_b64u_enc(of.P, 16, tok);
(void)snprintf(str.url, sizeof str.url, "%s/v1/m/%s/c/%s/up", r.base, r.mbx, tok);
(void)snprintf(str.auth, sizeof str.auth, "%s", r.owner);
memcpy(str.channel, of.P, 16);
if (rmt_stream_start(&str, pfd[1]) != 0) {
return 1;
}
{
char exp[32];
(void)snprintf(exp, sizeof exp, "%lld", expires);
rmt_say(pipe_mode, "offer", "url", of.url, "expires", exp);
}
if (!pipe_mode) {
puts("Scan this with your phone's camera to pair it with this computer (it works once, for ten minutes):");
if (o->show_qr) {
o->show_qr(of.url);
}
printf("%s\n", of.url);
puts("Once a phone is paired, it can add your other devices: Add a device, in its menu.");
(void)fflush(stdout);
}
while (!over && !rmt_stop) {
struct timeval tv = {0, 100000};
fd_set rs;
int maxfd = pfd[0];
FD_ZERO(&rs);
FD_SET(pfd[0], &rs);
if (of.stage == OFFER_ASKING) {
FD_SET(STDIN_FILENO, &rs);
maxfd = maxfd > STDIN_FILENO ? maxfd : STDIN_FILENO;
}
if (rmt_mono_ms() > of.mono_end) {
rmt_say(pipe_mode, "expired", NULL, NULL, NULL, NULL);
if (!pipe_mode) {
puts("The pairing offer expired.");
}
break;
}
if (select(maxfd + 1, &rs, NULL, NULL, &tv) > 0) {
if (of.stage == OFFER_ASKING && FD_ISSET(STDIN_FILENO, &rs)) {
if (rmt_pair_answer(pipe_mode)) {
if (rmt_offer_accept(&of, &r, err, sizeof err) != 0) {
rmt_say(pipe_mode, "error", "message", err, NULL, NULL);
fprintf(stderr, "pic remote: %s\n", err);
} else {
rmt_say(pipe_mode, "paired", "name", of.d.name, NULL, NULL);
if (!pipe_mode) {
printf(rmt_running_now() == 1 ? "Paired %s. pic remote is running: the phone reaches this computer now.\n"
: "Paired %s. Run pic remote (or pic remote install) to reach this computer from it.\n",
of.d.name);
}
rc = 0;
}
} else {
rmt_offer_refuse(&of, &r);
rmt_say(pipe_mode, "refused", NULL, NULL, NULL, NULL);
if (!pipe_mode) {
puts("Not paired.");
}
rc = 2;
}
over = 1;
continue;
}
for (;;) {
int kind, got, ev;
unsigned char ch[16], rec[PIC_NOISE_RECORD_CAP];
size_t n;
got = rmt_pipe_read(pfd[0], &kind, ch, rec, &n);
if (got <= 0) {
break;
}
if (kind == RMT_EV_PEER) {
continue;
}
if (kind != RMT_EV_FRAME) {
rmt_say(pipe_mode, "error", "message", "the relay ended the pairing offer", NULL, NULL);
over = 1;
break;
}
ev = rmt_offer_frame(&of, &r, &k, rec, n);
if (ev == OFFER_EV_FAILED) {
rmt_say(pipe_mode, "error", "message", "too many pairing attempts failed; the offer ended", NULL, NULL);
if (!pipe_mode) {
puts("Too many pairing attempts failed; the offer ended.");
}
over = 1;
break;
}
if (ev == OFFER_EV_ASK) {
char shown[8];
(void)snprintf(shown, sizeof shown, "%.3s %.3s", of.sas, of.sas + 3);
rmt_say(pipe_mode, "code", "name", of.d.name, "code", shown);
if (!pipe_mode) {
if (isatty(STDIN_FILENO)) { /* a key pressed before the question is not its answer */
rmt_pair_keys_on();
(void)tcflush(STDIN_FILENO, TCIFLUSH);
}
printf("Pair \"%s\"? It should show %s. y pairs, any other key does not. ", of.d.name, shown);
(void)fflush(stdout);
}
}
}
}
(void)rmt_lane_flush(&r, &of.lane);
}
rmt_pair_keys_off();
if (rmt_stop && !over) {
rmt_say(pipe_mode, "cancelled", NULL, NULL, NULL, NULL);
}
rmt_offer_refuse(&of, &r); /* expired or failed after a handshake: the phone hears no */
rmt_pair_last_word(&r, &of.lane, pfd[0], of.said);
rmt_delete_channel(&r, of.P);
rmt_offer_free(&of);
(void)fflush(stdout);
_exit(rc == 0 ? 0 : 1);
}
/* ---- the other subcommands ----------------------------------------------------------------------- */
static void rmt_when(long long ms, char *out, size_t cap) {
time_t t = (time_t)(ms / 1000);
struct tm tm;
if (!ms) {
(void)snprintf(out, cap, "never");
return;
}
(void)localtime_r(&t, &tm);
(void)strftime(out, cap, "%Y-%m-%d %H:%M", &tm);
}
static int rmt_devices(int json) {
rmt_device *list = NULL;
int n = 0, bad = 0, running = rmt_running_now();
char err[256];
if (pic_cred_state() == PIC_CRED_NEW) {
if (json) {
printf("{\"type\":\"devices\",\"running\":%s,\"devices\":[]}\n", running == 1 ? "true" : "false");
} else {
puts("No phone is paired.");
}
return 0;
}
if (pic_cred_unlock(err, sizeof err) != 0 || rmt_devices_load(&list, &n, &bad, err, sizeof err) != 0) {
fprintf(stderr, "pic remote: %s\n", err);
return 1;
}
if (json) {
rmt_buf b = {NULL, 0, 0};
char *out;
(void)rmt_buf_add(&b, "[", 1);
for (int i = 0; i < n; i++) {
char hex[33], idb[32], paired[32], seen[32], *one;
rmt_hex(list[i].id, 16, hex);
pic_b64u_enc(list[i].id, 16, idb);
(void)snprintf(paired, sizeof paired, "%lld", list[i].paired_ms);
(void)snprintf(seen, sizeof seen, "%lld", list[i].seen_ms);
one = rmt_q("SELECT json_object('id', ?1, 'name', ?2, 'pairedMs', CAST(?3 AS INTEGER), 'seenMs', CAST(?4 AS INTEGER),"
" 'origin', 'remote:' || ?5, 'notify', nullif(?6, ''))",
6, hex, list[i].name, paired, seen, idb, list[i].notify);
if (one) {
if (b.len > 1) {
(void)rmt_buf_add(&b, ",", 1);
}
(void)rmt_buf_add(&b, one, strlen(one));
}
free(one);
}
(void)rmt_buf_add(&b, "]", 1);
out = rmt_q("SELECT json_object('type', 'devices', 'running', json(?1), 'devices', json(?2))", 2,
running == 1 ? "true" : "false", b.buf);
puts(out ? out : "{}");
free(out);
free(b.buf);
} else {
printf("pic remote is %s\n", running == 1 ? "running" : "not running");
if (!n) {
puts("No phone is paired.");
}
for (int i = 0; i < n; i++) {
char hex[33], paired[32], seen[32];
rmt_hex(list[i].id, 16, hex);
rmt_when(list[i].paired_ms, paired, sizeof paired);
rmt_when(list[i].seen_ms, seen, sizeof seen);
printf("%.8s %-24s paired %s, last seen %s%s\n", hex, list[i].name, paired, seen,
!list[i].notify[0] ? "" : strcmp(list[i].notify, "remote") == 0 ? ", notifies for the phone's requests" : ", notifies");
}
}
free(list);
return 0;
}
/* Deletes the device whose id (hex) starts with PREFIX, in one transaction, asking nothing. */
static int rmt_unpair_cmd(const char *prefix) {
sqlite3 *db = pic_userdb(NULL, 0);
sqlite3_stmt *q = NULL;
int count = -1;
if (db && strcmp(prefix, "--all") == 0) { /* every device, keeping the keys and the mailbox (reset deletes those) */
if (sqlite3_exec(db, "DELETE FROM picu_remote_device", NULL, NULL, NULL) != SQLITE_OK) {
fprintf(stderr, "pic remote: %s\n", sqlite3_errmsg(db));
return 1;
}
count = sqlite3_changes(db);
printf("unpaired %d device%s\n", count, count == 1 ? "" : "s");
return 0;
}
if (!db || strlen(prefix) < 4 || strspn(prefix, "0123456789abcdefABCDEF") != strlen(prefix)) {
fputs("pic remote: unpair takes a device's id, at least its first 4 characters (pic remote devices)\n", stderr);
return 2;
}
if (sqlite3_exec(db, "BEGIN IMMEDIATE", NULL, NULL, NULL) != SQLITE_OK) {
fprintf(stderr, "pic remote: %s\n", sqlite3_errmsg(db));
return 1;
}
if (sqlite3_prepare_v2(db, "SELECT count(*) FROM picu_remote_device WHERE lower(hex(id)) LIKE lower(?1) || '%'", -1, &q, NULL) ==
SQLITE_OK) {
sqlite3_bind_text(q, 1, prefix, -1, SQLITE_STATIC);
count = sqlite3_step(q) == SQLITE_ROW ? sqlite3_column_int(q, 0) : -1;
}
sqlite3_finalize(q);
if (count == 1 && sqlite3_prepare_v2(db, "DELETE FROM picu_remote_device WHERE lower(hex(id)) LIKE lower(?1) || '%'", -1, &q,
NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, prefix, -1, SQLITE_STATIC);
count = sqlite3_step(q) == SQLITE_DONE ? 1 : -1;
sqlite3_finalize(q);
}
(void)sqlite3_exec(db, count == 1 ? "COMMIT" : "ROLLBACK", NULL, NULL, NULL);
if (count != 1) {
fprintf(stderr, count == 0 ? "pic remote: no paired device has an id starting %s\n"
: "pic remote: more than one device has an id starting %s; give more of it\n",
prefix);
return 1;
}
puts("unpaired");
return 0;
}
static int rmt_stop_cmd(void);
/* Every device row and all three keys, and the mailbox at the relay. A running pic remote is
* stopped first: it would go on serving keys that are gone. Before that the rows go, which it
* reads each second as unpair at the terminal: it tells each connected phone it was unpaired, so
* the phone does not take the mailbox's deletion for the relay losing its pairing. */
static int rmt_reset(void) {
sqlite3 *db = pic_userdb(NULL, 0);
rmt_keys k;
char err[256];
int have = 0;
if (!db) {
return 1;
}
if (rmt_running_now() == 1) {
if (pic_remote_phones() > 0 && sqlite3_exec(db, "DELETE FROM picu_remote_device", NULL, NULL, NULL) == SQLITE_OK) {
struct timespec ts = {1, 500000000L}; /* its check each second, and the message out */
(void)nanosleep(&ts, NULL);
}
if (rmt_stop_cmd() != 0) {
return 1;
}
}
if (pic_cred_state() != PIC_CRED_NEW && pic_cred_unlock(err, sizeof err) == 0 && rmt_keys_load(&k, 0, err, sizeof err) == 0) {
rmt_relay r;
char path[128];
rmt_relay_init(&r, &k);
(void)snprintf(path, sizeof path, "/v1/m/%s", r.mbx);
if (rmt_call(&r, "DELETE", path, r.owner, NULL, 0, NULL, NULL, err, sizeof err) < 0) {
fprintf(stderr, "pic remote: the relay's mailbox was not deleted (%s); it goes after 90 days unused\n", err);
}
have = 1;
}
if (sqlite3_exec(db, "BEGIN IMMEDIATE; DELETE FROM picu_remote_device; DELETE FROM picu_remote_key; COMMIT", NULL, NULL, NULL) !=
SQLITE_OK) {
fprintf(stderr, "pic remote: %s\n", sqlite3_errmsg(db));
(void)sqlite3_exec(db, "ROLLBACK", NULL, NULL, NULL);
return 1;
}
puts(have ? "reset: every phone unpaired, the keys and the mailbox deleted" : "reset: every phone unpaired, the keys deleted");
return 0;
}
/* The login agent's mechanism into KIND ("" when none is installed or the platform has none). */
static void rmt_agent_kind(char *kind, size_t cap) {
const pic_platform *p = pic_platform_get();
pic_login_agent ag;
char err[256];
memset(&ag, 0, sizeof ag);
kind[0] = '\0';
if (p->login_agent && p->login_agent(PIC_AGENT_STATE, &ag, err, sizeof err) == 1) {
(void)snprintf(kind, cap, "%s", ag.kind);
}
}
/* Whether the running pic remote, by what its status file says, runs an older pic than the one now
* at its path: 1, or 0 when it is the same or cannot be told. A status without a stamp was written
* by a pic from before stamps, older than any that has them. */
static int rmt_status_stale(const char *st) {
const pic_platform *p = pic_platform_get();
char *exe = st ? rmt_q("SELECT json_extract(?1, '$.exe')", 1, st) : NULL;
char *stamp = st ? rmt_q("SELECT json_extract(?1, '$.exeStamp')", 1, st) : NULL;
char now[128];
int stale = 0;
if (st && !stamp) {
char *v = rmt_q("SELECT json_valid(?1) AND json_type(?1, '$.exeStamp') IS NULL", 1, st);
stale = v && strcmp(v, "1") == 0;
free(v);
free(exe);
return stale;
}
if (exe && *exe && stamp && *stamp && p->file_stamp && p->file_stamp(exe, now, sizeof now) == 0) {
stale = strcmp(now, stamp) != 0;
}
free(exe);
free(stamp);
return stale;
}
/* One provider for rmt_shell_only: its key is in this shell's environment and nowhere pic remote
* started at login would find it. */
static int rmt_shell_only_one(void *ctx, const char *provider) {
char name[160], err[256];
const char *v;
pic_model m;
(void)ctx;
(void)snprintf(name, sizeof name, "%s/x", provider);
if (pic_model_resolve(name, &m, err, sizeof err) != 0 || strcmp(m.provider, provider) != 0 || !m.key_env[0] ||
!(v = getenv(m.key_env)) || !*v || pic_cred_source_of(provider, m.key_env, m.key_literal) != PIC_CRED_ENV) {
return 0;
}
printf("%s (%s) is set in this shell only: pic remote started at login will not see it. Store the command that\n"
"prints it (pic auth login %s --command '...', run at each request, so a rotated key is picked up),\n"
"or the key itself (pic auth login %s --api-key).\n",
m.key_env, provider, provider, provider);
return 0;
}
/* A line for each provider whose key this shell has only in its environment: the login agent
* starts pic remote with the system's bare environment, never the shell's. */
static void rmt_shell_only(void) { (void)pic_providers_each(rmt_shell_only_one, NULL); }
/* pic remote status [--json]: whether one runs (its lock), and what it last wrote of itself. */
static int rmt_status_cmd(int json) {
int running = rmt_running_now(), devices = rmt_device_count();
char *st = running == 1 ? rmt_status_read() : NULL;
char *state = st ? rmt_q("SELECT json_extract(?1, '$.state')", 1, st) : NULL;
char *relay = st ? rmt_q("SELECT json_extract(?1, '$.relay')", 1, st) : NULL;
char *why = st ? rmt_q("SELECT json_extract(?1, '$.error')", 1, st) : NULL;
char *pid = st ? rmt_q("SELECT json_extract(?1, '$.pid')", 1, st) : NULL;
char *retry = st ? rmt_q("SELECT json_extract(?1, '$.retryAtMs')", 1, st) : NULL;
char *att = st ? rmt_q("SELECT json_extract(?1, '$.attempts')", 1, st) : NULL;
char *phones = st ? rmt_q("SELECT json_extract(?1, '$.phones')", 1, st) : NULL;
char *updated = st ? rmt_q("SELECT json_extract(?1, '$.updatedMs')", 1, st) : NULL;
char *opened = st ? rmt_q("SELECT json_extract(?1, '$.streamOpenedAt')", 1, st) : NULL;
char *recycles = st ? rmt_q("SELECT coalesce(json_extract(?1, '$.recycles'), 0)", 1, st) : NULL;
/* when the stream opened, as this computer's clock reads it: HH:MM:SS */
char *since = opened ? rmt_q("SELECT strftime('%H:%M:%S', ?1, 'localtime')", 1, opened) : NULL;
long long in_ms = retry && atoll(retry) > 0 ? atoll(retry) - rmt_wall_ms() : 0;
/* Connected, its loop writes this file at least every 5 s: older than that and a stall is a
* loop that is stuck, whatever it last said. */
long long still_ms = updated ? rmt_wall_ms() - atoll(updated) : 0;
if (state && strcmp(state, "connected") == 0 && still_ms > rmt_stall_ms() + 5000) {
free(state);
state = strdup("stalled");
}
if (in_ms < 0) {
in_ms = 0;
}
char agent[16];
int stale = running == 1 && rmt_status_stale(st);
rmt_agent_kind(agent, sizeof agent);
if (running == 1 && (!state || !*state)) {
free(state);
state = strdup("starting");
}
if (json) {
char devs[16], ms[24];
char *out;
(void)snprintf(devs, sizeof devs, "%d", devices);
(void)snprintf(ms, sizeof ms, "%lld", in_ms);
out = rmt_q("SELECT json_object('type', 'status', 'running', json(?1), 'pid', CAST(?2 AS INTEGER), 'state', ?3,"
" 'relay', ?4, 'devices', CAST(?5 AS INTEGER), 'attempts', CAST(?6 AS INTEGER), 'retryInMs', CAST(?7 AS INTEGER),"
" 'error', ?8, 'loginAgent', ?9, 'phones', json(coalesce(?10, '[]')), 'stale', json(?11),"
" 'streamOpenedAt', ?12, 'recycles', CAST(coalesce(?13, 0) AS INTEGER))",
13, running == 1 ? "true" : "false", pid, running == 1 ? state : "off", relay, devs, att ? att : "0", ms,
why ? why : "", agent, phones, stale ? "true" : "false", running == 1 ? opened : NULL, running == 1 ? recycles : "0");
puts(out ? out : "{}");
free(out);
} else if (running != 1) {
printf("pic remote is not running; %d phone%s paired\n", devices, devices == 1 ? "" : "s");
} else if (state && strcmp(state, "stalled") == 0) {
printf("pic remote is running (pid %s): stalled for %lld s, not answering phones (~/.pic/remote.log says where); %d "
"phone%s paired\n",
pid ? pid : "?", still_ms / 1000, devices, devices == 1 ? "" : "s");
} else if (state && strcmp(state, "reconnecting") == 0) {
printf("pic remote is running (pid %s): reconnecting to %s (attempt %s, next try in %lld s)%s%s; %d phone%s paired\n",
pid ? pid : "?", relay ? relay : "the relay", att ? att : "?", (in_ms + 999) / 1000, why && *why ? ": " : "",
why ? why : "", devices, devices == 1 ? "" : "s");
} else {
char stream[96] = "";
if (since && state && strcmp(state, "connected") == 0) {
long long n = recycles ? atoll(recycles) : 0;
(void)snprintf(stream, sizeof stream, ", stream open since %s, %lld recycle%s", since, n, n == 1 ? "" : "s");
}
printf("pic remote is running (pid %s): %s%s%s%s; %d phone%s paired\n", pid ? pid : "?", state ? state : "starting",
relay && *relay ? " to " : "", relay ? relay : "", stream, devices, devices == 1 ? "" : "s");
}
if (!json && stale) {
puts("It runs an older pic than the one installed now: pic remote restart starts the new one.");
}
if (!json && agent[0]) {
printf("It starts at login (%s).\n", agent);
rmt_shell_only();
} else if (!json && pic_platform_get()->login_agent) {
puts("It does not start at login: pic remote install sets that up.");
}
free(st);
free(state);
free(relay);
free(why);
free(pid);
free(retry);
free(att);
free(phones);
free(updated);
free(opened);
free(recycles);
free(since);
return 0;
}
/* pic remote stop: SIGTERM to the running one (its pid from the status file, while it holds the
* lock), then wait up to 10 s for the lock to go. */
static int rmt_stop_cmd(void) {
char *st, *pid;
long p;
if (rmt_running_now() != 1) {
puts("pic remote is not running");
return 0;
}
st = rmt_status_read();
pid = st ? rmt_q("SELECT json_extract(?1, '$.pid')", 1, st) : NULL;
p = pid ? atol(pid) : 0;
free(st);
free(pid);
if (p <= 1 || kill((pid_t)p, SIGTERM) != 0) {
fputs("pic remote: cannot tell which process is pic remote (no ~/.pic/remote.status)\n", stderr);
return 1;
}
for (int i = 0; i < 200 && rmt_running_now() == 1; i++) {
struct timespec ts = {0, 50000000L};
(void)nanosleep(&ts, NULL);
}
if (rmt_running_now() == 1) {
fputs("pic remote: it did not stop within 10 s\n", stderr);
return 1;
}
puts("pic remote: stopped");
return 0;
}
/* pic remote restart: the running one starts again as the pic now installed (SIGUSR1), at its next
* quiet moment; waits up to 30 s for the new one's first word. One from before restarts were
* possible is only told how. */
static int rmt_restart_cmd(void) {
char *st, *pid, *was, *v;
long p;
int done = 0;
if (rmt_running_now() != 1) {
puts("pic remote is not running");
return 1;
}
st = rmt_status_read();
pid = st ? rmt_q("SELECT json_extract(?1, '$.pid')", 1, st) : NULL;
was = st ? rmt_q("SELECT json_extract(?1, '$.startedMs')", 1, st) : NULL;
p = pid ? atol(pid) : 0;
free(st);
free(pid);
if (!was) {
fputs("pic remote: the one running is too old to restart itself: pic remote stop, then turn it on again with /rc "
"(s) or pic remote\n",
stderr);
return 1;
}
if (p <= 1 || kill((pid_t)p, SIGUSR1) != 0) {
free(was);
fputs("pic remote: cannot tell which process is pic remote (no ~/.pic/remote.status)\n", stderr);
return 1;
}
for (int i = 0; i < 600 && !done; i++) {
struct timespec ts = {0, 50000000L};
(void)nanosleep(&ts, NULL);
st = rmt_status_read();
v = st ? rmt_q("SELECT json_extract(?1, '$.startedMs')", 1, st) : NULL;
done = v && strcmp(v, was) != 0;
free(v);
free(st);
}
free(was);
if (!done) {
fputs("pic remote: it has not restarted within 30 s (it waits for what it is doing to finish)\n", stderr);
return 1;
}
puts("pic remote: restarted");
return 0;
}
/* pic remote install: the platform's login agent runs pic remote --login, which needs the store
* to open with no one there. */
static int rmt_install(const pic_remote_options *o) {
const pic_platform *p = pic_platform_get();
const char *home = getenv("HOME");
pic_login_agent ag;
char err[512], log[PATH_MAX];
int rc, running;
memset(&ag, 0, sizeof ag);
if (!p->login_agent) {
fputs("pic remote: this build of pic has no way to start a program at login\n", stderr);
return 1;
}
if (!o->self || o->self[0] != '/' || !home) {
fputs("pic remote: cannot tell where this pic is, or HOME is not set\n", stderr);
return 1;
}
if (pic_cred_state() == PIC_CRED_NEW) {
fputs("pic remote: the credential store has no key yet: pair a phone with /rc or pic remote pair first\n", stderr);
return 1;
}
rc = pic_cred_quiet(err, sizeof err);
if (rc == 1 || (rc == 0 && strcmp(pic_cred_source_name(), "passphrase") == 0)) {
fputs(RMT_NEEDS_QUIET, stderr);
return 1;
}
if (rc != 0) {
fprintf(stderr, "pic remote: %s\n", err);
return 1;
}
(void)snprintf(log, sizeof log, "%s/.pic/remote.log", home);
{
const char *args[] = {o->self, "remote", "--login", NULL};
ag.argv = args;
ag.log = log;
running = rmt_running_now() == 1;
if (p->login_agent(PIC_AGENT_INSTALL, &ag, err, sizeof err) != 1) {
fprintf(stderr, "pic remote: %s\n", err);
return 1;
}
}
if (strcmp(ag.kind, "cron") == 0) {
printf("pic remote now starts whenever this computer starts (cron @reboot, in your crontab)%s\n",
running ? "; it is running now" : "; run pic remote to start it now");
} else {
printf("pic remote now starts whenever you log in (%s: %s)%s\n", ag.kind, ag.where,
running ? "; it is running now"
: ag.started ? ", and it is starting now"
: "; it starts at your next login");
}
printf("Its messages go to %s. pic remote uninstall undoes this.\n", log);
rmt_shell_only();
return 0;
}
static int rmt_uninstall(void) {
const pic_platform *p = pic_platform_get();
pic_login_agent ag;
char err[512];
int rc;
memset(&ag, 0, sizeof ag);
if (!p->login_agent) {
puts("pic remote was not set to start at login");
return 0;
}
rc = p->login_agent(PIC_AGENT_REMOVE, &ag, err, sizeof err);
if (rc < 0) {
fprintf(stderr, "pic remote: %s\n", err);
return 1;
}
if (rc == 0) {
puts("pic remote was not set to start at login");
} else {
printf("pic remote no longer starts at login (%s: %s removed)\n", ag.kind, ag.where);
}
return 0;
}
int pic_remote_main(const pic_remote_options *o, int argc, char **argv) {
if (argc == 0) {
return rmt_serve(o, RMT_TERMINAL);
}
if (argc == 1 && strcmp(argv[0], "--detached") == 0) { /* /rc's: the key on an inherited pipe */
return rmt_serve(o, RMT_DETACHED);
}
if (argc == 1 && strcmp(argv[0], "--login") == 0) { /* the login agent's */
return rmt_serve(o, RMT_LOGIN);
}
if (strcmp(argv[0], "install") == 0 && argc == 1) {
return rmt_install(o);
}
if (strcmp(argv[0], "uninstall") == 0 && argc == 1) {
return rmt_uninstall();
}
if (strcmp(argv[0], "status") == 0 && (argc == 1 || (argc == 2 && strcmp(argv[1], "--json") == 0))) {
return rmt_status_cmd(argc == 2);
}
if (strcmp(argv[0], "stop") == 0 && argc == 1) {
return rmt_stop_cmd();
}
if (strcmp(argv[0], "restart") == 0 && argc == 1) {
return rmt_restart_cmd();
}
if (strcmp(argv[0], "pair") == 0 && (argc == 1 || (argc == 2 && strcmp(argv[1], "--pipe") == 0))) {
if (argc == 1 && !isatty(STDIN_FILENO)) {
fputs("pic remote: pair asks for a yes on the terminal\n", stderr);
return 2;
}
return rmt_pair(o, argc == 2);
}
if (strcmp(argv[0], "devices") == 0 && (argc == 1 || (argc == 2 && strcmp(argv[1], "--json") == 0))) {
return rmt_devices(argc == 2);
}
if (strcmp(argv[0], "unpair") == 0 && argc == 2) {
return rmt_unpair_cmd(argv[1]);
}
if (strcmp(argv[0], "reset") == 0 && argc == 1) {
return rmt_reset();
}
fputs("usage: pic remote [pair | devices | status | stop | restart | install | uninstall | unpair ID | unpair --all | reset]\n", stderr);
return 2;
}