Skip to content
pi-c Documentation
Login

Documentation

/* See remote.h; the wire contract is docs/design/remote-protocol.md, and section numbers below
 * are its. One loop and one extra thread: the 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 everything else: handshakes, commands, following, posting. */
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <pthread.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>

#include "attach.h"
#include "cred.h"
#include "http.h"
#include "inbox.h"
#include "net.h"
#include "noise.h"
#include "pic.h"
#include "platform.h"
#include "remote.h"
#include "rpc.h"
#include "sse.h"
#include "userdb.h"

#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_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_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_CMDS 64
#define RMT_SESSIONS 32
#define RMT_LIST 50

static volatile sig_atomic_t rmt_stop;

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); }

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 sqlite3 *m;
    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;
} 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;
        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);
            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);
            }
            pic_cred_wipe(plain, sn - PIC_CRED_OVERHEAD);
        }
        free(plain);
        free(name);
        free(stat);
        free(chan);
        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;
}

static int rmt_device_add(const rmt_device *d, char *err, size_t cap) {
    sqlite3 *db = pic_userdb(err, cap);
    sqlite3_stmt *q = NULL;
    char aad[64], stat[100], chan[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);
    if (!(json = rmt_q("SELECT json_object('name', ?1, 'static', ?2, 'channel', ?3, 'push', json('null'))", 3, d->name, stat,
                       chan))) {
        (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, "INSERT INTO picu_remote_device(id, sealed, paired_ms) VALUES(?1, ?2, ?3)", -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);
        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);
    free(box);
    free(json);
    return rc;
}

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;
} 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];
    const char *hdrs[3];
    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;
    }
    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);
    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) {
        (void)snprintf(err, cap, st == 401 ? "the relay %s refused the mailbox (HTTP 401): it may need the setting remote.invite"
                                           : "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, "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' };

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;
} rmt_stream;

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;
    if (write(s->wfd, head, sizeof head) != (ssize_t)sizeof head || (n && write(s->wfd, rec, n) != (ssize_t)n)) {
        rmt_stop = 1;
    }
}

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);
    } 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;
    }
    return 0;
}

static int rmt_stream_body(void *ctx, const char *bytes, size_t n) {
    pic_sse *p = ((void **)ctx)[1];
    int rc = pic_sse_feed(p, bytes, n);
    return rc < 0 ? 1 : rc;
}

/* 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, and none lasts more than 15 minutes. */
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 && 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);
        rc = pic_http_get(net, s->url, hdrs, s->last[0] ? 3 : 2, &r, 45, 900, err, sizeof err);
        pic_sse_free(&p);
        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;
        }
        (void)rc;
        if (rmt_mono_ms() - t0 >= 30000) {
            wait = 1000;
        }
        {
            unsigned char j;
            long long w;
            (void)pic_platform_get()->entropy(&j, 1);
            w = wait - wait / 5 + (long long)j * (2 * wait / 5) / 255;
            for (long long t = 0; t < w && !rmt_stop; t += 50) {
                struct timespec ts = {0, 50000000L};
                (void)nanosleep(&ts, NULL);
            }
        }
        wait = wait * 2 > 60000 ? 60000 : wait * 2;
    }
    if (net) {
        pic_net_free(net);
    }
    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;
} 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;
}

/* One post of what waits (32 records, 256 KiB at most); records older than 30 s are dropped
 * unsent, which the phone sees as a gap. 0, or -1 when the post failed (kept for later). */
static int rmt_lane_flush(rmt_relay *r, rmt_lane *l) {
    long long now = rmt_mono_ms();
    rmt_buf body = {NULL, 0, 0};
    size_t at = 0, sent_to = 0;
    int nrec = 0, st;
    char path[128], id[32], err[256];
    if (!l->qlen || now < l->retry_ms) {
        return 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);
            return -1;
        }
        at += 10 + n;
        nrec++;
    }
    sent_to = at;
    if (!nrec) {
        return 0;
    }
    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);
    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 = now + 1000;
    return -1;
}

/* ---- sessions (section 3) --------------------------------------------------------------- */

typedef struct {
    int used, confirmed;
    int dev;            /* index of its device */
    unsigned char ch[16];
    pic_noise_transport t;
    long long started_ms, heard_ms;
    rmt_buf msg; /* a message being assembled from its records */
} rmt_sess;

/* 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;
}

/* ---- 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 {
    char *path, *workspace;
    pic_store s;
    int open;
    char why[256];
    long long version;
} rmt_journal;

enum { CMD_INBOX = 1, CMD_PROMPT = 2 };

typedef struct {
    int kind;
    int jx;
    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;
} rmt_cmd;

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 */
    pic_follow *f;
    long long fversion;
    int follow_now;
    /* the conversation list it asked for */
    int want_list;
    char *list_sent;
    rmt_cmd cmds[RMT_CMDS];
    int ncmds;
} rmt_dev;

typedef struct {
    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;
} rmt_state;

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));
}

/* ---- 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;
}

/* Every picu_workspace row whose path still holds that journal, opened narrowly once each. */
static void rmt_journals_scan(rmt_state *st) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    if (!db || sqlite3_prepare_v2(db, "SELECT path, journal FROM picu_workspace ORDER BY last_used_ms DESC", -1, &q, NULL) !=
                   SQLITE_OK) {
        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);
        struct stat sb;
        int known = 0;
        rmt_journal **grown, *j;
        if (!ws || !jp || stat(jp, &sb) != 0 || !S_ISREG(sb.st_mode)) {
            continue;
        }
        for (int i = 0; i < st->njs; i++) {
            known = known || strcmp(st->js[i]->path, jp) == 0;
        }
        if (known || !(grown = realloc(st->js, (size_t)(st->njs + 1) * sizeof *grown))) {
            continue;
        }
        st->js = grown;
        if (!(j = calloc(1, sizeof *j))) {
            continue;
        }
        j->path = strdup(jp);
        j->workspace = strdup(ws);
        if (!j->path || !j->workspace) {
            free(j->path);
            free(j->workspace);
            free(j);
            continue;
        }
        st->js[st->njs] = j;
        if (pic_open_narrow(&j->s, jp) == 0) {
            j->open = 1;
            j->version = rmt_data_version(j->s.db);
        } else {
            (void)snprintf(j->why, sizeof j->why, "%s", j->s.err[0] ? j->s.err : "cannot open the journal");
            pic_close(&j->s);
        }
        st->njs++;
    }
    sqlite3_finalize(q);
}

/* SESSION as the phone names it, W/C: the journal and the conversation's id. 0, or -1. */
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) {
            sqlite3_stmt *q = NULL;
            int found = 0;
            if (sqlite3_prepare_v2(st->js[i]->s.db, "SELECT 1 FROM pic_session WHERE id = ?", -1, &q, NULL) == SQLITE_OK) {
                sqlite3_bind_text(q, 1, slash + 1, -1, SQLITE_STATIC);
                found = sqlite3_step(q) == SQLITE_ROW;
            }
            sqlite3_finalize(q);
            if (!found) {
                return -1;
            }
            *jx = i;
            (void)snprintf(conv, 64, "%s", slash + 1);
            return 0;
        }
    }
    return -1;
}

typedef struct {
    int jx;
    char id[64];
    char *name;
    long long ms, seq;
    int running;
} rmt_item;

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;
}

/* The sessions message: the 50 most recently active conversations across the journals. */
static char *rmt_list(rmt_state *st) {
    rmt_item *items = NULL;
    size_t n = 0, cap = 0;
    rmt_buf b = {NULL, 0, 0};
    char *out;
    (void)rmt_buf_add(&b, "[", 1);
    for (int i = 0; i < st->njs; i++) {
        sqlite3_stmt *q = NULL;
        if (!st->js[i]->open ||
            sqlite3_prepare_v2(st->js[i]->s.db,
                               "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'),"
                               " coalesce((SELECT max(e.seq) FROM pic_entry e JOIN pic_submission u ON u.id = e.submission_id"
                               " WHERE u.session_id = s.id), 0)"
                               " FROM pic_session s ORDER BY s.updated_ms DESC LIMIT 50",
                               -1, &q, NULL) != SQLITE_OK) {
            sqlite3_finalize(q);
            continue;
        }
        while (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) {
                    break;
                }
                items = grown;
            }
            it = &items[n++];
            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);
        }
        sqlite3_finalize(q);
    }
    if (n) {
        qsort(items, n, sizeof *items, rmt_item_cmp);
    }
    for (size_t i = 0; i < n && i < RMT_LIST; i++) {
        char *sess = NULL, ms[32], seq[32], *one;
        rmt_journal *j = st->js[items[i].jx];
        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);
        one = rmt_q("SELECT json_object('session', ?1, 'name', ?2, 'workspace', ?3, 'lastMs', CAST(?4 AS INTEGER),"
                    " 'running', json(?5), 'seq', CAST(?6 AS INTEGER))",
                    6, sess, items[i].name ? items[i].name : "", j->workspace, ms, items[i].running ? "true" : "false", seq);
        if (one) {
            if (b.len > 1) {
                (void)rmt_buf_add(&b, ",", 1);
            }
            (void)rmt_buf_add(&b, one, strlen(one));
        }
        free(one);
        free(sess);
    }
    for (size_t i = 0; i < n; i++) {
        free(items[i].name);
    }
    free(items);
    (void)rmt_buf_add(&b, "]", 1);
    {
        rmt_buf u = {NULL, 0, 0};
        (void)rmt_buf_add(&u, "[", 1);
        for (int i = 0; i < st->njs; i++) {
            char *one;
            if (st->js[i]->open) {
                continue;
            }
            one = rmt_q("SELECT json_object('workspace', ?1, 'reason', ?2)", 2, st->js[i]->workspace, st->js[i]->why);
            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);
        out = rmt_q("SELECT json_object('type', 'sessions', 'payload', json_object('sessions', json(?1), 'unavailable', json(?2)))",
                    2, b.buf ? b.buf : "[]", u.buf ? u.buf : "[]");
        free(u.buf);
    }
    free(b.buf);
    return out;
}

/* ---- following (section 4) --------------------------------------------------------------- */

typedef struct {
    rmt_state *st;
    rmt_dev *d;
} rmt_emit_ctx;

static int rmt_emit(void *ctx, long long seq, const char *event) {
    rmt_emit_ctx *c = ctx;
    char s[32], *json;
    (void)snprintf(s, sizeof s, "%lld", seq);
    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));
        json = rmt_q("SELECT json_object('type', 'event', 'session', ?1, 'seq', CAST(?2 AS INTEGER), 'payload',"
                     " json_object('type', 'elided', 'eventType', ?3, 'bytes', CAST(?4 AS INTEGER)))",
                     4, c->d->wsess, s, t ? t : "", bytes);
        free(t);
    } else {
        json = rmt_q("SELECT json_object('type', 'event', 'session', ?1, 'seq', CAST(?2 AS INTEGER), 'payload', json(?3))", 3,
                     c->d->wsess, s, event);
    }
    rmt_send_free(c->st, c->d, json);
    return 0;
}

/* One pass for D's conversation: its events, then a mark. */
static void rmt_follow_pass(rmt_state *st, rmt_dev *d) {
    rmt_emit_ctx c = {st, d};
    long long last = 0;
    int running = 0;
    char s[32];
    if (!d->f || d->sess < 0) {
        return;
    }
    d->fversion = rmt_data_version(st->js[d->jx]->s.db);
    if (pic_follow_pass(d->f, rmt_emit, &c, &last, &running) != 0) {
        rmt_error(st, d, NULL, "unavailable", "cannot read the conversation");
        return;
    }
    (void)snprintf(s, sizeof s, "%lld", last);
    rmt_send_free(st, d,
                  rmt_q("SELECT json_object('type', 'sync', 'session', ?1, 'seq', CAST(?2 AS INTEGER), 'payload',"
                        " json_object('running', json(?3)))",
                        3, d->wsess, s, running ? "true" : "false"));
}

static void rmt_unfollow(rmt_dev *d) {
    pic_follow_free(d->f);
    d->f = NULL;
    free(d->wsess);
    d->wsess = NULL;
}

/* ---- 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;
}

static void rmt_cmd_drop(rmt_dev *d, int i) {
    free(d->cmds[i].line);
    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));
}

/* 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);
}

/* get_state and get_messages, answered from the journal; no row. */
static void rmt_query(rmt_state *st, rmt_dev *d, rmt_env *e, int jx, const char *conv) {
    pic_store *s = &st->js[jx]->s;
    char *entries = pic_pi_entries(s, conv), *msgs = entries ? pic_rpc_messages(s->db, entries) : NULL, *data = NULL, *line;
    if (msgs && strcmp(e->ptype, "get_messages") == 0) {
        data = rmt_q("SELECT json_object('messages', json(?1))", 1, msgs);
    } else if (msgs) {
        sqlite3_stmt *q = NULL;
        if (sqlite3_prepare_v2(s->db,
                               "SELECT json_object('model', (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', json_array_length(?2),"
                               " '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, msgs, -1, SQLITE_STATIC);
            if (sqlite3_step(q) == SQLITE_ROW) {
                data = strdup((const char *)sqlite3_column_text(q, 0));
            }
        }
        sqlite3_finalize(q);
    }
    line = rmt_pi_response(e->payload, e->ptype, data != NULL, data, data ? NULL : "cannot read the conversation");
    rmt_response(st, d, 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;
}

/* Whether a request was admitted under ROW (the keyed admission's key). */
static int rmt_admitted(pic_store *s, const char *row) {
    sqlite3_stmt *q = NULL;
    int yes = 0;
    if (sqlite3_prepare_v2(s->db, "SELECT 1 FROM pic_submission WHERE request_key = ?", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, row, -1, SQLITE_STATIC);
        yes = sqlite3_step(q) == SQLITE_ROW;
    }
    sqlite3_finalize(q);
    return yes;
}

/* steer, follow_up and abort through pic_inbox_accept, unchanged: ack once committed, the response
 * once the row leaves pending. */
static void rmt_inbox(rmt_state *st, rmt_dev *d, const char *key, int jx, const char *conv, const char *line) {
    pic_store *s = &st->js[jx]->s;
    pic_inbox_msg m;
    char row[96], sender[48], got[64], state[16];
    int rc;
    (void)snprintf(row, sizeof row, "rc:%s:%s", d->idb, key);
    (void)snprintf(sender, sizeof sender, "remote:%s", d->idb);
    memset(&m, 0, sizeof m);
    m.session = conv;
    m.key = row;
    m.line = line;
    m.sender = sender;
    rc = pic_inbox_accept(s, &m, got, sizeof got, state, sizeof state);
    if (rc != 0) {
        rmt_error(st, d, key, rc > 0 ? "refused" : "failed", s->err);
        return;
    }
    if (strcmp(state, "pending") == 0) {
        if (rmt_cmd_find(d, key) < 0) {
            (void)rmt_cmd_add(d, CMD_INBOX, jx, key, row, line);
        }
        rmt_send_free(st, d, 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, row, state, sizeof state, &response) == 0 && response) {
            rmt_response(st, d, key, response);
        } else {
            rmt_send_free(st, d, rmt_q("SELECT json_object('type', 'response', 'key', ?1, 'payload', json_object('state', ?2))", 2,
                                       key, state));
        }
        free(response);
    }
}

/* prompt with nothing running: 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. */
static void rmt_prompt(rmt_state *st, rmt_dev *d, const char *key, int jx, const char *conv, const char *text) {
    extern char **environ;
    rmt_journal *j = st->js[jx];
    const char *sub[] = {st->o->self, "--db", j->path, "--workspace", j->workspace, "submit", NULL, text, "--session", conv, NULL};
    const char *run[] = {st->o->self, "--db", j->path, "--workspace", j->workspace, "run", "--session", conv, NULL};
    char row[96], keyenv[32];
    char **env = NULL;
    size_t ne = 0;
    int errp[2], keyfd, null;
    pid_t pid;
    rmt_cmd *c;
    (void)snprintf(row, sizeof row, "rc:%s:%s", d->idb, key);
    sub[6] = row;
    if (rmt_admitted(&j->s, row)) { /* a second admission with the key reports the first */
        char *line = rmt_q("SELECT json_object('type', 'response', 'command', 'prompt', 'success', json('true'))", 0);
        rmt_response(st, d, key, line);
        free(line);
        return;
    }
    if (rmt_cmd_find(d, key) >= 0) {
        return; /* starting already */
    }
    /* Everything the children need is made before the fork: the stream thread may hold the
     * allocator's lock at that moment, so the child calls nothing that allocates. */
    while (environ[ne]) {
        ne++;
    }
    if (!(env = calloc(ne + 2, sizeof *env)) || pipe(errp) != 0) {
        free(env);
        rmt_error(st, d, key, "failed", strerror(errno));
        return;
    }
    if ((null = open("/dev/null", O_RDWR)) < 0) {
        free(env);
        close(errp[0]);
        close(errp[1]);
        rmt_error(st, d, key, "failed", strerror(errno));
        return;
    }
    keyfd = pic_cred_handoff();
    {
        size_t k = 0;
        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, sizeof keyenv, "PIC_KEY_FD=%d", keyfd);
            env[k++] = keyenv;
        }
        env[k] = NULL;
    }
    pid = fork();
    if (pid == 0) {
        int status = 0;
        pid_t g;
        if (st->lockfd >= 0) { /* the request must not hold pic remote's lock */
            close(st->lockfd);
        }
        (void)setsid();
        (void)signal(SIGINT, SIG_DFL);
        (void)signal(SIGTERM, SIG_DFL);
        (void)signal(SIGPIPE, SIG_DFL);
        (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]);
            execv(st->o->self, (char *const *)(void *)sub);
            _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);
        }
        if (keyfd >= 0) {
            (void)fcntl(keyfd, F_SETFD, 0);
        }
        execve(st->o->self, (char *const *)(void *)run, 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, key, "failed", strerror(errno));
        return;
    }
    (void)fcntl(errp[0], F_SETFD, FD_CLOEXEC);
    (void)fcntl(errp[0], F_SETFL, O_NONBLOCK);
    c = rmt_cmd_add(d, CMD_PROMPT, jx, key, row, NULL);
    c->pid = pid;
    c->errfd = errp[0];
}

static void rmt_command(rmt_state *st, rmt_dev *d, rmt_env *e) {
    int jx;
    char conv[64];
    const char *t = e->ptype;
    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 (rmt_resolve(st, e->session, &jx, conv) != 0) {
        rmt_error(st, d, e->key, "no_session", "no such conversation");
        return;
    }
    {
        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 (strcmp(t, "get_state") == 0 || strcmp(t, "get_messages") == 0) {
        rmt_query(st, d, e, jx, conv);
    } else if (strcmp(t, "steer") == 0 || strcmp(t, "follow_up") == 0 || strcmp(t, "abort") == 0) {
        rmt_inbox(st, d, e->key, jx, conv, e->payload);
    } else if (strcmp(t, "prompt") == 0) {
        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 = rmt_q("SELECT json_array_length(?1, '$.images')", 1, e->payload);
        char row[96];
        (void)snprintf(row, sizeof row, "rc:%s:%s", d->idb, e->key);
        if (!text || !*text) {
            rmt_error(st, d, e->key, "bad_command", "a prompt needs its message");
        } else if (images && strcmp(images, "0") != 0) {
            rmt_error(st, d, e->key, "not_available", "images in a prompt are not carried yet");
        } else if (rmt_admitted(&st->js[jx]->s, row) || rmt_cmd_find(d, e->key) >= 0 || !rmt_running(&st->js[jx]->s, conv)) {
            rmt_prompt(st, d, e->key, jx, conv, text);
        } else if (behavior && (strcmp(behavior, "steer") == 0 || strcmp(behavior, "followUp") == 0)) {
            char *line = rmt_q("SELECT json_object('type', ?1, 'message', ?2)", 2,
                               strcmp(behavior, "steer") == 0 ? "steer" : "follow_up", text);
            if (line) {
                rmt_inbox(st, d, e->key, jx, conv, 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_response(st, d, e->key, line);
            free(line);
        }
        free(text);
        free(behavior);
        free(images);
    } else if (strcmp(t, "switch_session") == 0) {
        rmt_error(st, d, e->key, "not_available", "the envelope's session selects the conversation");
    } else {
        rmt_error(st, d, e->key, "not_available", "this command is not carried by remote control yet");
    }
}

/* Each tick: commands waiting for their row to settle, or for their request to be admitted. */
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];
        pic_store *s = &st->js[c->jx]->s;
        if (c->kind == CMD_INBOX) {
            char state[16], *response = NULL;
            long long now = rmt_mono_ms();
            if (now - c->expire_ms >= 5000) { /* a write: not on every tick */
                c->expire_ms = now;
                (void)pic_inbox_expire(s, c->row);
            }
            if (pic_inbox_status(s, c->row, state, sizeof state, &response) != 0 || strcmp(state, "pending") == 0) {
                free(response);
                continue;
            }
            if (d->sess >= 0) {
                if (response) {
                    rmt_response(st, d, c->key, response);
                } else {
                    rmt_send_free(st, d, rmt_q("SELECT json_object('type', 'response', 'key', ?1, 'payload', json_object('state', ?2))",
                                               2, c->key, state));
                }
            }
            free(response);
            rmt_cmd_drop(d, i--);
            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 (rmt_admitted(s, c->row)) {
            char *line = rmt_q("SELECT json_object('type', 'response', 'command', 'prompt', 'success', json('true'))", 0);
            if (d->sess >= 0) {
                rmt_response(st, d, c->key, line);
            }
            free(line);
            rmt_cmd_drop(d, i--);
            continue;
        }
        if (c->pid > 0) {
            int status = 0;
            if (waitpid(c->pid, &status, WNOHANG) == c->pid) {
                char *last, *end;
                c->pid = 0;
                if (rmt_admitted(s, c->row)) {
                    i--; /* reported above on the next look */
                    continue;
                }
                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) {
                    char *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);
                }
                rmt_cmd_drop(d, i--);
            }
        }
    }
}

/* ---- a whole message from a phone -------------------------------------------------------- */

static void rmt_unpair_device(rmt_state *st, int di, int tell);

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;
        rmt_device_seen(d->d.id);
    }
    if (rmt_env_parse(json, &e) != 0) {
        rmt_error(st, d, NULL, "bad_message", "not an envelope message");
        return;
    }
    if (strcmp(e.type, "sessions") == 0) {
        d->want_list = 1;
        free(d->list_sent);
        d->list_sent = NULL;
    } else if (strcmp(e.type, "sync") == 0) {
        int jx;
        char conv[64], err[256];
        if (rmt_resolve(st, e.session, &jx, conv) != 0) {
            rmt_error(st, d, NULL, "no_session", "no such conversation");
        } else {
            rmt_unfollow(d); /* a new sync replaces the one before */
            d->jx = jx;
            (void)snprintf(d->conv, sizeof d->conv, "%s", conv);
            d->wsess = strdup(e.session);
            d->f = pic_follow_new(&st->js[jx]->s, conv, e.has_seq ? e.seq : -1, err, sizeof err);
            if (!d->f) {
                rmt_error(st, d, NULL, "unavailable", err);
            } else {
                d->follow_now = 1;
            }
        }
    } else if (strcmp(e.type, "command") == 0) {
        rmt_command(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 || strcmp(e.type, "push") == 0 || strcmp(e.type, "pair_ready") == 0 ||
               strcmp(e.type, "fetch") == 0) {
        /* presence and push serve notifications, and fetch scrolling back: later landings */
        if (strcmp(e.type, "fetch") == 0) {
            rmt_error(st, d, NULL, "not_available", "fetch is not carried yet");
        }
    } 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;
}

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);
}

/* 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 void rmt_handshake(rmt_state *st, const unsigned char ch[16], const unsigned char *rec, size_t n) {
    int di = rmt_dev_by_channel(st, ch), slot = -1, unconfirmed = 0;
    unsigned char prologue[41], pl[512], m2[256], out[300];
    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 ||
        memcmp(hs.rs, st->devs[di].d.stat, PIC_NOISE_PUB) != 0) {
        pic_noise_hs_wipe(&hs);
        return;
    }
    if (pic_noise_write2(&hs, "{\"v\":1}", 7, m2, sizeof m2, &mn) != 0) {
        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_noise_hs_wipe(&hs);
        return;
    }
    {
        rmt_sess *s = &st->sess[slot];
        unsigned char up[32], down[32];
        free(s->msg.buf);
        memset(s, 0, sizeof *s);
        s->used = 1;
        s->dev = di;
        memcpy(s->ch, ch, 16);
        pic_noise_split(&hs, up, down);
        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));
}

static void rmt_record(rmt_state *st, const unsigned char ch[16], const unsigned char *rec, size_t n) {
    int di;
    if (n < 9) {
        return;
    }
    if (rec[0] == PIC_NOISE_REC_M1) {
        rmt_handshake(st, ch, rec, n);
        return;
    }
    if (rec[0] != PIC_NOISE_REC_DATA || (di = rmt_dev_by_channel(st, ch)) < 0) {
        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) {
            return; /* dropped; nothing changed */
        }
        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];
        (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_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 (d->alive) {
        rmt_device_delete(d->d.id);
    }
    d->alive = 0;
    rmt_unfollow(d);
    rmt_delete_channel(&st->r, d->d.channel);
    d->lane.qlen = 0;
}

/* The table, read again: new rows are served from now on, deleted ones end their sessions. */
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;
    }
    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);
            if (!quiet) {
                printf("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;
            if (rmt_put_channel(&st->r, d->d.channel, 0, err, sizeof err) != 0 && !quiet) {
                fprintf(stderr, "pic remote: %s\n", err);
            }
            if (!quiet) {
                printf("pic remote: serving %s\n", d->d.name);
                (void)fflush(stdout);
            }
        }
    }
    free(list);
    return 0;
}

/* 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) {
    (void)sig;
    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 passphrase, asked on the terminal every time: never a key handed down by a parent. */
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 passphrase yet: pair a phone with /rc or pic remote pair first");
        return -1;
    }
    return pic_cred_unlock(err, cap);
}

/* 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);
    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);
    }
}

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;
        }
        if ((!s->confirmed && now - s->started_ms > RMT_UNCONFIRMED_MS) || now - s->heard_ms > RMT_SILENT_MS) {
            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 && (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->started_ms = now; /* asked once a day */
            }
        }
    }
    for (int i = 0; i < st->ndevs; i++) {
        rmt_dev *d = &st->devs[i];
        if (!d->alive) {
            continue;
        }
        if (d->sess >= 0) {
            if (d->f && (d->follow_now || rmt_data_version(st->js[d->jx]->s.db) != d->fversion)) {
                d->follow_now = 0;
                rmt_follow_pass(st, d);
            }
            if (d->want_list && !d->list_sent) { /* asked for now; looked at again each second */
                rmt_list_check(st, d);
            }
        }
        rmt_commands_poll(st, d);
        (void)rmt_lane_flush(&st->r, &d->lane);
    }
}

static int rmt_serve(const pic_remote_options *o) {
    rmt_state st;
    rmt_stream str;
    char err[512];
    int lock, pfd[2], waiting = 0;
    long long last_list = 0, last_user = 0;
    struct sigaction sa;
    memset(&st, 0, sizeof st);
    st.o = o;
    st.lockfd = -1;
    if ((lock = rmt_lock()) < 0) {
        fputs(lock == -2 ? "pic remote: one is already running for this user\n" : "pic remote: cannot take ~/.pic/remote.lock\n",
              stderr);
        return 1;
    }
    st.lockfd = lock;
    if (rmt_unlock_fresh(err, sizeof err) != 0) {
        fprintf(stderr, "pic remote: %s\n", err);
        return 1;
    }
    {
        int rc = rmt_keys_load(&st.k, 0, err, sizeof err);
        if (rc != 0) {
            fprintf(stderr, "pic remote: %s\n", rc > 0 ? "no phone is paired: pair one with /rc in pic, or pic remote pair" : err);
            return 1;
        }
    }
    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)signal(SIGPIPE, SIG_IGN);
    rmt_relay_init(&st.r, &st.k);
    st.user_version = rmt_data_version(pic_userdb(NULL, 0));
    if (rmt_devices_sync(&st, 1) != 0) {
        fprintf(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) {
            puts("pic remote: no phone is paired yet; pair one with /rc in pic (waiting)");
            (void)fflush(stdout);
            waiting = 1;
        }
        {
            struct timespec ts = {1, 0};
            (void)nanosleep(&ts, NULL);
        }
        (void)rmt_devices_sync(&st, 1);
    }
    if (rmt_stop) {
        return 0;
    }
    if (rmt_reconcile(&st, err, sizeof err) != 0) {
        fprintf(stderr, "pic remote: %s\n", err);
        return 1;
    }
    rmt_journals_scan(&st);
    if (pipe(pfd) != 0) {
        fprintf(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;
    if (rmt_stream_start(&str, pfd[1]) != 0) {
        fprintf(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;
        }
        printf("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);
    }
    while (!rmt_stop) {
        struct timeval tv = {0, 100000};
        fd_set rs;
        long long now = rmt_mono_ms();
        FD_ZERO(&rs);
        FD_SET(pfd[0], &rs);
        if (select(pfd[0] + 1, &rs, NULL, NULL, &tv) > 0) {
            for (;;) {
                int kind, got;
                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) {
                    if (got < 0) {
                        rmt_stop = 1;
                    }
                    break;
                }
                if (kind == RMT_EV_FRAME) {
                    rmt_record(&st, ch, rec, n);
                } else if (kind == RMT_EV_REPLACED) {
                    fputs("pic remote: another connection took the relay's stream; stopping\n", stderr);
                    rmt_stop = 1;
                } else if (kind == RMT_EV_GONE || kind == RMT_EV_REFUSED) {
                    fputs("pic remote: the relay no longer has this mailbox (it was reset); stopping\n", stderr);
                    rmt_stop = 1;
                }
            }
        }
        if (now - last_user >= 1000) { /* devices paired or unpaired meanwhile, new workspaces */
            long long v = rmt_data_version(pic_userdb(NULL, 0));
            last_user = now;
            if (v != st.user_version) {
                st.user_version = v;
                (void)rmt_devices_sync(&st, 0);
                rmt_journals_scan(&st);
            }
        }
        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_list_check(&st, &st.devs[i]);
                }
            }
        }
        rmt_serve_tick(&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);
        }
    }
    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);
    }
}

static int rmt_pair(const pic_remote_options *o, int pipe_mode) {
    rmt_keys k;
    rmt_relay r;
    rmt_stream str;
    rmt_lane lane;
    char err[512], host[256] = "", url[1024], b64[200], tok[64];
    unsigned char ps[32], psk[32], ptok[32], P[16], offer[PIC_NOISE_OFFER], prologue[41];
    char vapid_b64[100];
    unsigned char dev_id[16];
    long long expires, mono_end;
    int pfd[2], fails = 0, stage = 0, rc = 1;
    pic_noise_hs hs;
    pic_noise_transport t;
    rmt_device d;
    char sas[7] = "", name[72] = "";
    unsigned char sid[8];
    rmt_buf msg = {NULL, 0, 0};
    memset(&lane, 0, sizeof lane);
    memset(&d, 0, sizeof d);
    memset(&t, 0, sizeof t);
    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;
    }
    (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;
    }
    if (pic_platform_get()->entropy(ps, sizeof ps) != 0 || pic_platform_get()->entropy(dev_id, sizeof dev_id) != 0) {
        fputs("pic remote: no entropy\n", stderr);
        return 1;
    }
    pic_noise_pair_derive(ps, psk, ptok, P);
    memcpy(lane.ch, P, 16);
    if (rmt_put_channel(&r, P, 1, err, sizeof err) != 0) {
        rmt_say(pipe_mode, "error", "message", err, NULL, NULL);
        fprintf(stderr, "pic remote: %s\n", err);
        return 1;
    }
    expires = rmt_wall_ms() / 1000 + RMT_PAIR_TTL;
    mono_end = rmt_mono_ms() + 1000LL * RMT_PAIR_TTL;
    pic_noise_offer(k.mailbox, k.stat.pub, ps, (uint64_t)expires, offer);
    pic_b64u_enc(offer, sizeof offer, b64);
    (void)snprintf(url, sizeof url, "%s/#p1.%s", r.base, b64);
    pic_cred_wipe(ps, sizeof ps);
    (void)gethostname(host, sizeof host - 1);
    if (pipe(pfd) != 0) {
        return 1;
    }
    (void)fcntl(pfd[0], F_SETFL, O_NONBLOCK);
    memset(&str, 0, sizeof str);
    pic_b64u_enc(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, 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", 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(url);
        }
        printf("%s\n", url);
        puts("On an iPhone or iPad, open it, add the page to the Home Screen (Share, then Add to Home Screen), and pair");
        puts("from the Home Screen's page: notifications only reach a page installed there.");
        (void)fflush(stdout);
    }
    rmt_prologue(k.mailbox, P, prologue);
    pic_b64u_enc(k.vapid.pub, sizeof k.vapid.pub, vapid_b64);
    while (rc == 1 && stage < 3) {
        struct timeval tv = {0, 100000};
        fd_set rs;
        int maxfd = pfd[0];
        FD_ZERO(&rs);
        FD_SET(pfd[0], &rs);
        if (stage == 2) {
            FD_SET(STDIN_FILENO, &rs);
            maxfd = maxfd > STDIN_FILENO ? maxfd : STDIN_FILENO;
        }
        if (rmt_mono_ms() > 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 (stage == 2 && FD_ISSET(STDIN_FILENO, &rs)) {
                char line[64];
                ssize_t n = read(STDIN_FILENO, line, sizeof line - 1);
                int yes = n > 0 && (line[0] == 'y' || line[0] == 'Y');
                if (yes) {
                    memcpy(d.id, dev_id, 16);
                    (void)snprintf(d.name, sizeof d.name, "%s", name);
                    if (rmt_device_add(&d, err, sizeof err) != 0 || rmt_put_channel(&r, d.channel, 0, err, sizeof err) != 0) {
                        rmt_say(pipe_mode, "error", "message", err, NULL, NULL);
                        fprintf(stderr, "pic remote: %s\n", err);
                        break;
                    }
                    {
                        unsigned char rec[PIC_NOISE_RECORD_CAP];
                        size_t rn = pic_noise_record(&t, 1, "{\"type\":\"paired\"}", 17, rec);
                        (void)rmt_lane_add(&lane, rec, rn);
                        (void)rmt_lane_flush(&r, &lane);
                    }
                    rmt_say(pipe_mode, "paired", "name", name, NULL, NULL);
                    if (!pipe_mode) {
                        printf("Paired %s. Run pic remote to reach this computer from it.\n", name);
                    }
                    rc = 0;
                } else {
                    unsigned char rec[PIC_NOISE_RECORD_CAP];
                    static const char refused[] = "{\"type\":\"error\",\"payload\":{\"code\":\"pair_refused\"}}";
                    size_t rn = pic_noise_record(&t, 1, refused, sizeof refused - 1, rec);
                    (void)rmt_lane_add(&lane, rec, rn);
                    (void)rmt_lane_flush(&r, &lane);
                    rmt_say(pipe_mode, "refused", NULL, NULL, NULL, NULL);
                    if (!pipe_mode) {
                        puts("Not paired.");
                    }
                    rc = 2;
                }
                stage = 3;
                continue;
            }
            for (;;) {
                int kind, got;
                unsigned char ch[16], rec[PIC_NOISE_RECORD_CAP], pl[1024], m2[512], out[600];
                size_t n, pn, mn;
                got = rmt_pipe_read(pfd[0], &kind, ch, rec, &n);
                if (got <= 0) {
                    break;
                }
                if (kind != RMT_EV_FRAME) {
                    rmt_say(pipe_mode, "error", "message", "the relay ended the pairing offer", NULL, NULL);
                    stage = 3;
                    break;
                }
                if (n > 9 && rec[0] == PIC_NOISE_REC_M1 && stage < 2) {
                    char *payload, *pname, *pchan, *pv, idb[32], *reply;
                    pic_noise_hs_init(&hs, 0, &k.stat, NULL, psk, prologue, sizeof prologue);
                    if (pic_noise_read1(&hs, rec + 9, n - 9, pl, sizeof pl - 1, &pn) != 0) {
                        pic_noise_hs_wipe(&hs);
                        if (++fails >= RMT_PAIR_FAILS) {
                            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.");
                            }
                            stage = 3;
                            break;
                        }
                        continue;
                    }
                    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), d.channel, sizeof d.channel) != 16) {
                        free(pv);
                        free(pname);
                        free(pchan);
                        pic_noise_hs_wipe(&hs);
                        continue;
                    }
                    for (char *c = pname; *c; c++) { /* a name for a terminal: no control characters */
                        if ((unsigned char)*c < 0x20 || *c == 0x7f) {
                            *c = '?';
                        }
                    }
                    (void)snprintf(name, sizeof name, "%s", pname);
                    memcpy(d.stat, hs.rs, PIC_NOISE_PUB);
                    free(pv);
                    free(pname);
                    free(pchan);
                    pic_b64u_enc(dev_id, 16, idb);
                    reply = rmt_q("SELECT json_object('v', 1, 'device', ?1, 'name', ?2, 'vapid', ?3)", 3, idb, host, vapid_b64);
                    if (!reply || pic_noise_write2(&hs, reply, strlen(reply), m2, sizeof m2, &mn) != 0) {
                        free(reply);
                        pic_noise_hs_wipe(&hs);
                        continue;
                    }
                    free(reply);
                    memcpy(sid, rec + 1, 8);
                    {
                        unsigned char up[32], down[32];
                        pic_noise_split(&hs, up, down);
                        pic_noise_transport_init(&t, 0, sid, up, down);
                        pic_noise_sas(hs.h, sas);
                        pic_cred_wipe(up, sizeof up);
                        pic_cred_wipe(down, sizeof down);
                    }
                    pic_noise_hs_wipe(&hs);
                    (void)rmt_lane_add(&lane, out, pic_noise_head(PIC_NOISE_REC_M2, sid, m2, mn, out));
                    (void)rmt_lane_flush(&r, &lane);
                    stage = 1;
                    msg.len = 0;
                } else if (n > 9 && rec[0] == PIC_NOISE_REC_DATA && stage == 1 && memcmp(rec + 1, sid, 8) == 0) {
                    unsigned char data[PIC_NOISE_CHUNK];
                    size_t dn;
                    int flag, gap;
                    char *type;
                    if (pic_noise_open_record(&t, rec, n, &flag, data, &dn, &gap) != 0) {
                        continue;
                    }
                    if (gap) {
                        msg.len = 0;
                    }
                    (void)rmt_buf_add(&msg, data, dn);
                    if (flag != 1) {
                        continue;
                    }
                    type = rmt_q("SELECT json_extract(?1, '$.type')", 1, msg.buf);
                    msg.len = 0;
                    if (type && strcmp(type, "pair_ready") == 0) {
                        char shown[8];
                        (void)snprintf(shown, sizeof shown, "%.3s %.3s", sas, sas + 3);
                        rmt_say(pipe_mode, "code", "name", name, "code", shown);
                        if (!pipe_mode) {
                            printf("Pair %s? It should show %s. [y/N] ", name, shown);
                            (void)fflush(stdout);
                        }
                        stage = 2;
                    }
                    free(type);
                }
            }
        }
        (void)rmt_lane_flush(&r, &lane);
    }
    if (stage < 3 && stage >= 1) { /* expired or failed after a handshake: the phone hears no */
        unsigned char rec[PIC_NOISE_RECORD_CAP];
        static const char refused[] = "{\"type\":\"error\",\"payload\":{\"code\":\"pair_refused\"}}";
        size_t rn = pic_noise_record(&t, 1, refused, sizeof refused - 1, rec);
        (void)rmt_lane_add(&lane, rec, rn);
        (void)rmt_lane_flush(&r, &lane);
    }
    for (int i = 0; i < 20 && lane.qlen; i++) { /* the last word, before the channel goes */
        struct timespec ts = {0, 100000000L};
        lane.retry_ms = 0;
        (void)rmt_lane_flush(&r, &lane);
        if (lane.qlen) {
            (void)nanosleep(&ts, NULL);
        }
    }
    rmt_delete_channel(&r, P);
    pic_cred_wipe(psk, sizeof psk);
    free(msg.buf);
    free(lane.q);
    (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], paired[32], seen[32], *one;
            rmt_hex(list[i].id, 16, hex);
            (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))", 4,
                        hex, list[i].name, paired, seen);
            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\n", hex, list[i].name, paired, seen);
        }
    }
    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 || 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;
}

/* Every device row and all three keys, and the mailbox at the relay. */
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 (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;
}

int pic_remote_main(const pic_remote_options *o, int argc, char **argv) {
    if (argc == 0) {
        return rmt_serve(o);
    }
    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 | unpair ID | reset]\n", stderr);
    return 2;
}