Skip to content
pi-c Artifact [3ae5e65b99]
Login

Artifact [3ae5e65b99]

Artifact 3ae5e65b9954b6ef8ff683e5d1a80bb4df247f30107736970e0c7594739992f9:


/* Test-only phone for pic remote (docs/design/remote-protocol.md): the initiator's side of the
 * protocol on pic's own Noise module, over the relay's HTTP API, as the phone page does it.
 *
 * Usage:
 *   fake_phone DIR pair URL NAME [wrong-psk | late MS | resend | rival | rival-badchan]
 *       pairs with the offer at URL (the QR code's address): prints "code NNN NNN" once the
 *       handshake is done, sends pair_ready, then "paired" (exit 0) or "refused" (exit 3); an
 *       expired offer prints "expired" (exit 5), one whose channel is gone "gone" (exit 4), and no
 *       answer in 5 s "no answer" (exit 6). wrong-psk sends a first message under another secret.
 *       late MS stops reading its down lane once pair_ready is sent (the test relay's cut ends the
 *       stream), prints "away", and reads again MS later, with its Last-Event-ID.
 *       resend posts its first message again once it has the second (a reconnect). rival and
 *       rival-badchan have a second phone, which scanned the same code, post its own valid first
 *       message then, with a 16-byte channel or a 12-byte one.
 *       Once paired it prints "channel B64U", its device channel's id.
 *       The pairing is kept in DIR/pairing.
 *   fake_phone DIR run < SCRIPT
 *       opens a session with the paired computer and runs SCRIPT, one command a line:
 *         send JSON          an envelope message (in it, $CURSOR is the last mark's seq, and $CODE
 *                            the six digits of the last pair_request)
 *         cmd KEY JSON       a command, sent again every 2 s and on each new session until it
 *                            has an ack or a response for KEY
 *         cmdfile KEY FILE   cmd with the JSON in FILE (one too long for a line)
 *         expect TEXT        waits up to 30 s for a received message containing TEXT
 *         seen TEXT          waits up to 30 s for any message so far containing TEXT
 *         expectnot TEXT MS  fails if one containing TEXT arrives within MS
 *         replay             posts the last record again (a replay)
 *         garble N           posts N pings whose tags are broken (records that never open)
 *         swapsend JSON      seals JSON, then a ping, and posts the ping first (a reordering: the
 *                            record with the lower counter arrives late)
 *         nosession MS       fails if a session is made within MS (a phone pic must not answer)
 *         awaitgone          serves the session until the relay says the channel is gone ("gone",
 *                            exit 4), 30 s at most
 *         expectreset        waits up to 30 s for a reset record, if none came yet
 *         count TEXT N       fails unless exactly N received messages contain TEXT
 *         waitcount TEXT N   count, once N have come or 30 s have passed
 *         mark NAME          creates DIR/NAME (or NAME when it is absolute), for the test to act on
 *         waitfor NAME       serves the session until DIR/NAME (or NAME) exists, 30 s at most
 *         skip               leaves a counter unused (a gap)
 *         newsession         starts a new handshake, then sync from the cursor and the commands
 *         sleep MS
 *         ping MS            sends a ping and waits up to MS for a pong that came after it: prints
 *                            "pong N ms", or "late pong" (not a failure: the test counts them)
 *         timed MS KEY JSON  sends JSON and waits up to MS for a message with "key":"KEY": prints
 *                            "answered KEY in N ms", or "late KEY" (not a failure)
 *         keyed              fails if an event or mark came without its sync's key (each sync
 *                            carries a new one; one for an earlier sync is dropped, "stale")
 *         replica FILE       writes what it holds of the followed conversation, as the page would
 *                            show it: each event it took in at a mark, one a line (SEQ TAB JSON)
 *       Each message received is printed as "<- JSON"; a gap as "gap"; a new session as "session".
 *       After a gap it drops what came since its last mark and syncs from it in a new session.
 *       FAKE_PHONE_PING_MS: a ping that often, as the page does, so a lost record shows as a gap.
 *       FAKE_PHONE_IGNORE_BYE: a bye is printed and nothing else is done (a phone that ignores it).
 *       A session not answered in 3 s is tried again, as is one that got a reset. The ping that
 *       confirms a new session is the phone's own: its pong is printed but no expect sees it.
 *       PIC_TEST_SLOW: every wait for an answer (30 s, 5 s, 60 s here) is four times as long.
 *   fake_phone DIR pushkeys ENDPOINT [NOTIFY]
 *       makes a push subscription for ENDPOINT, as the page's pushManager would (a P-256 key pair
 *       and an auth secret, kept in DIR/push), and prints the push message that sends it up, with
 *       NOTIFY when given.
 *   fake_phone DIR pushread FILE
 *       decrypts the push in FILE (a request the test push service saved: headers, then the
 *       body) with DIR/push's keys, as the phone's browser does (RFC 8291), and prints the
 *       plaintext; exit 1 when it does not open. */
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <time.h>
#include <unistd.h>

#include "bearssl.h"
#include "http.h"
#include "net.h"
#include "noise.h"
#include "platform.h"
#include "sse.h"

typedef struct {
    char base[512];
    pic_noise_keypair stat;
    unsigned char pic_pub[65], mailbox[16], token[32], channel[16], device[16];
} pairing;

static pairing P;
static int pfd[2];
static volatile int away; /* the reader stays off the lane while set */
static char stream_url[1024], stream_auth[128];

static long long mono_ms(void) {
    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC, &ts);
    return (long long)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
}

/* How long to wait for an answer before giving up: MS, or four times it under PIC_TEST_SLOW (a
 * loaded machine). Only failures wait the whole time. */
static long long patience(long long ms) {
    const char *s = getenv("PIC_TEST_SLOW");
    return s && *s && strcmp(s, "0") != 0 ? ms * 4 : ms;
}

static void die(const char *what) {
    fprintf(stderr, "fake_phone: %s\n", what);
    exit(1);
}

static void hexw(FILE *f, const unsigned char *b, size_t n) {
    for (size_t i = 0; i < n; i++) {
        fprintf(f, "%02x", b[i]);
    }
    fputc('\n', f);
}

static void hexr(FILE *f, unsigned char *b, size_t n) {
    for (size_t i = 0; i < n; i++) {
        unsigned x;
        if (fscanf(f, "%2x", &x) != 1) {
            die("bad pairing file");
        }
        b[i] = (unsigned char)x;
    }
}

static void save(const char *dir) {
    char path[1024];
    FILE *f;
    (void)snprintf(path, sizeof path, "%s/pairing", dir);
    if (!(f = fopen(path, "w"))) {
        die("cannot write the pairing");
    }
    fprintf(f, "%s\n", P.base);
    hexw(f, P.stat.priv, 32);
    hexw(f, P.pic_pub, 65);
    hexw(f, P.mailbox, 16);
    hexw(f, P.token, 32);
    hexw(f, P.device, 16);
    fclose(f);
}

static void load(const char *dir) {
    char path[1024];
    unsigned char priv[32];
    FILE *f;
    (void)snprintf(path, sizeof path, "%s/pairing", dir);
    if (!(f = fopen(path, "r")) || !fgets(P.base, sizeof P.base, f)) {
        die("no pairing");
    }
    P.base[strcspn(P.base, "\n")] = '\0';
    hexr(f, priv, 32);
    hexr(f, P.pic_pub, 65);
    hexr(f, P.mailbox, 16);
    hexr(f, P.token, 32);
    hexr(f, P.device, 16);
    fclose(f);
    if (pic_noise_keypair_make(&P.stat, priv) != 0) {
        die("bad key");
    }
    pic_noise_id(P.channel, "pic-rc/1 channel", P.token);
}

/* ---- the down lane, read by a thread into a pipe -------------------------------------- */

static int on_event(void *ctx, const char *event, const char *data, size_t len) {
    unsigned char rec[PIC_NOISE_RECORD_CAP], head[3];
    long n;
    (void)ctx;
    if (strcmp(event, "gone") == 0) {
        head[0] = 'G';
        head[1] = head[2] = 0;
        (void)!write(pfd[1], head, 3);
        return 1;
    }
    if (strcmp(event, "frame") != 0 || (n = pic_b64u_dec(data, len, rec, sizeof rec)) <= 0) {
        return 0;
    }
    head[0] = 'F';
    head[1] = (unsigned char)(n >> 8);
    head[2] = (unsigned char)n;
    (void)!write(pfd[1], head, 3);
    (void)!write(pfd[1], rec, (size_t)n);
    return 0;
}

static int on_body(void *ctx, const char *b, size_t n) {
    int rc = pic_sse_feed(ctx, b, n);
    return rc < 0 ? 1 : rc;
}

static void *reader(void *arg) {
    char err[256], last[64] = "";
    pic_net *net = pic_net_new(err, sizeof err);
    (void)arg;
    while (net) {
        char ah[200], lh[100];
        const char *h[2] = {ah, lh};
        pic_sse p;
        pic_http_resp r;
        (void)snprintf(ah, sizeof ah, "Authorization: Bearer %s", stream_auth);
        (void)snprintf(lh, sizeof lh, "Last-Event-ID: %s", last);
        if (pic_sse_init(&p, 65536, 65536, on_event, &p) != 0) {
            break;
        }
        pic_http_resp_init(&r, on_body, &p);
        (void)pic_http_get(net, stream_url, h, last[0] ? 2 : 1, &r, 60, 900, err, sizeof err);
        (void)snprintf(last, sizeof last, "%s", p.last_id);
        pic_sse_free(&p);
        while (away) {
            struct timespec ts = {0, 20000000L};
            (void)nanosleep(&ts, NULL);
        }
        if (r.status == 404 || r.status == 401) {
            unsigned char head[3] = {'G', 0, 0};
            (void)!write(pfd[1], head, 3);
            break;
        }
        {
            struct timespec ts = {0, 200000000L};
            (void)nanosleep(&ts, NULL);
        }
    }
    return NULL;
}

/* One record from the pipe within MS: 1 with it ('F') or a gone ('G', *n 0), 0 on timeout. */
static int next_record(int ms, int *kind, unsigned char *rec, size_t *n) {
    unsigned char head[3];
    struct timeval tv = {ms / 1000, (ms % 1000) * 1000};
    fd_set rs;
    size_t len, have = 0;
    FD_ZERO(&rs);
    FD_SET(pfd[0], &rs);
    if (select(pfd[0] + 1, &rs, NULL, NULL, &tv) <= 0) {
        return 0;
    }
    if (read(pfd[0], head, 3) != 3) {
        die("pipe");
    }
    len = ((size_t)head[1] << 8) | head[2];
    while (have < len) {
        ssize_t r = read(pfd[0], rec + have, len - have);
        if (r <= 0) {
            die("pipe");
        }
        have += (size_t)r;
    }
    *kind = head[0];
    *n = len;
    return 1;
}

/* POSTs records (each behind its two-byte length) to the up lane: the status, or -1. */
static int post(const char *chan_b64, const char *auth_b64, const unsigned char *body, size_t n) {
    static pic_net *net;
    char url[1024], ah[200], err[256], mb[32];
    const char *h[2] = {ah, "Content-Type: application/octet-stream"};
    pic_http_resp r;
    if (!net && !(net = pic_net_new(err, sizeof err))) {
        return -1;
    }
    pic_b64u_enc(P.mailbox, 16, mb);
    (void)snprintf(url, sizeof url, "%s/v1/m/%s/c/%s/up", P.base, mb, chan_b64);
    (void)snprintf(ah, sizeof ah, "Authorization: Bearer %s", auth_b64);
    pic_http_resp_init(&r, NULL, NULL);
    if (pic_http_post(net, url, h, 2, (const char *)body, n, &r, 10, 20, err, sizeof err) != 0) {
        return -1;
    }
    return r.status;
}

static unsigned char last_rec[PIC_NOISE_RECORD_CAP + 2];
static size_t last_n;

static int post_record(const char *chan, const char *auth, const unsigned char *rec, size_t n) {
    last_rec[0] = (unsigned char)(n >> 8);
    last_rec[1] = (unsigned char)n;
    memcpy(last_rec + 2, rec, n);
    last_n = n + 2;
    return post(chan, auth, last_rec, last_n);
}

static void start_reader(const unsigned char ch[16], const char *auth) {
    char mb[32], c[32];
    pthread_t th;
    pic_b64u_enc(P.mailbox, 16, mb);
    pic_b64u_enc(ch, 16, c);
    (void)snprintf(stream_url, sizeof stream_url, "%s/v1/m/%s/c/%s/down", P.base, mb, c);
    (void)snprintf(stream_auth, sizeof stream_auth, "%s", auth);
    if (pipe(pfd) != 0 || pthread_create(&th, NULL, reader, NULL) != 0) {
        die("reader");
    }
}

/* ---- pairing ------------------------------------------------------------------------- */

/* The test relay's control: POST /_test/ACTION. */
static void relay_test(const char *action) {
    char url[1024], err[256];
    pic_net *net = pic_net_new(err, sizeof err);
    pic_http_resp r;
    (void)snprintf(url, sizeof url, "%s/_test/%s", P.base, action);
    pic_http_resp_init(&r, NULL, NULL);
    if (!net || pic_http_post(net, url, NULL, 0, "", 0, &r, 5, 10, err, sizeof err) != 0 || r.status != 204) {
        die("the test relay's control");
    }
    pic_net_free(net);
}

static void post_m1(const char *pc, const char *pt, const unsigned char *psk, const unsigned char *prologue, int chan_len) {
    pic_noise_keypair kp;
    pic_noise_hs h2;
    unsigned char s2[8], tok[32], ch[16], m[1024], rec[PIC_NOISE_RECORD_CAP];
    char payload[256], dc[32];
    size_t mn;
    if (pic_noise_keypair_make(&kp, NULL) != 0 || pic_platform_get()->entropy(s2, 8) != 0 ||
        pic_platform_get()->entropy(tok, 32) != 0) {
        die("entropy");
    }
    pic_noise_id(ch, "pic-rc/1 channel", tok);
    pic_b64u_enc(ch, (size_t)chan_len, dc);
    (void)snprintf(payload, sizeof payload, "{\"v\":1,\"name\":\"Rival\",\"channel\":\"%s\"}", dc);
    pic_noise_hs_init(&h2, 1, &kp, P.pic_pub, psk, prologue, 41);
    if (pic_noise_write1(&h2, payload, strlen(payload), m, sizeof m, &mn) != 0) {
        die("write1");
    }
    (void)post_record(pc, pt, rec, pic_noise_head(PIC_NOISE_REC_M1, s2, m, mn, rec));
}

static int pair(const char *dir, const char *url, const char *name, int wrong, int late, const char *mode) {
    const char *frag = strstr(url, "/#p1.");
    unsigned char offer[200], ps[32], psk[32], ptok[32], pchan[16], prologue[41], sid[8], m[1024], rec[PIC_NOISE_RECORD_CAP];
    unsigned char out[PIC_NOISE_CHUNK], m1rec[PIC_NOISE_RECORD_CAP];
    size_t m1n;
    char pc[32], pt[64], payload[256], dc[32];
    uint64_t expires = 0;
    long n;
    size_t mn, rn;
    pic_noise_hs hs;
    pic_noise_transport t;
    long long until;
    if (!frag || (n = pic_b64u_dec(frag + 5, strlen(frag + 5), offer, sizeof offer)) != PIC_NOISE_OFFER ||
        pic_noise_offer_read(offer, (size_t)n, P.mailbox, P.pic_pub, ps, &expires) != 0) {
        die("not an offer");
    }
    (void)snprintf(P.base, sizeof P.base, "%.*s", (int)(frag - url), url);
    if ((long long)expires < (long long)time(NULL)) {
        puts("expired");
        return 5;
    }
    pic_noise_pair_derive(ps, psk, ptok, pchan);
    if (wrong) { /* the right channel and token, the wrong psk */
        psk[0] ^= 1;
    }
    if (pic_noise_keypair_make(&P.stat, NULL) != 0 || pic_platform_get()->entropy(P.token, 32) != 0 ||
        pic_platform_get()->entropy(sid, 8) != 0) {
        die("entropy");
    }
    pic_noise_id(P.channel, "pic-rc/1 channel", P.token);
    pic_b64u_enc(pchan, 16, pc);
    pic_b64u_enc(ptok, 32, pt);
    pic_b64u_enc(P.channel, 16, dc);
    start_reader(pchan, pt);
    memcpy(prologue, "pic-rc/1", 8);
    prologue[8] = 0;
    memcpy(prologue + 9, P.mailbox, 16);
    memcpy(prologue + 25, pchan, 16);
    (void)snprintf(payload, sizeof payload, "{\"v\":1,\"name\":\"%s\",\"channel\":\"%s\"}", name, dc);
    pic_noise_hs_init(&hs, 1, &P.stat, P.pic_pub, psk, prologue, sizeof prologue);
    if (pic_noise_write1(&hs, payload, strlen(payload), m, sizeof m, &mn) != 0) {
        die("write1");
    }
    rn = pic_noise_head(PIC_NOISE_REC_M1, sid, m, mn, rec);
    memcpy(m1rec, rec, rn);
    m1n = rn;
    {
        int st = post_record(pc, pt, rec, rn);
        if (st == 404 || st == 401) {
            puts("gone");
            return 4;
        }
        if (st != 204) {
            die("post");
        }
    }
    until = mono_ms() + patience(5000);
    for (;;) {
        int kind;
        size_t len;
        long long left = until - mono_ms();
        if (left <= 0 || !next_record((int)left, &kind, rec, &len)) {
            puts("no answer");
            return 6;
        }
        if (kind == 'G') {
            puts("gone");
            return 4;
        }
        if (len > 9 && rec[0] == PIC_NOISE_REC_M2 && memcmp(rec + 1, sid, 8) == 0) {
            unsigned char pl[512], up[32], down[32];
            size_t pn;
            char sas[7];
            if (pic_noise_read2(&hs, rec + 9, len - 9, pl, sizeof pl, &pn) != 0) {
                die("read2");
            }
            pl[pn] = '\0';
            {
                const char *d = strstr((const char *)pl, "\"device\":\"");
                if (!d || pic_b64u_dec(d + 10, 22, P.device, 16) != 16) {
                    die("no device id");
                }
            }
            if (pic_noise_split(&hs, up, down) != 0) {
                die("split before the handshake completed");
            }
            pic_noise_transport_init(&t, 1, sid, up, down);
            pic_noise_sas(hs.h, sas);
            printf("code %.3s %.3s\n", sas, sas + 3);
            (void)fflush(stdout);
            if (strcmp(mode, "resend") == 0) {
                (void)post_record(pc, pt, m1rec, m1n);
            } else if (strcmp(mode, "rival") == 0 || strcmp(mode, "rival-badchan") == 0) {
                post_m1(pc, pt, psk, prologue, strcmp(mode, "rival") == 0 ? 16 : 12);
            }
            rn = pic_noise_record(&t, 1, "{\"type\":\"pair_ready\"}", 21, rec);
            (void)post_record(pc, pt, rec, rn);
            if (late) {
                away = 1;
                relay_test("cut");
                puts("away");
                (void)fflush(stdout);
                {
                    struct timespec ts = {late / 1000, (late % 1000) * 1000000L};
                    (void)nanosleep(&ts, NULL);
                }
                away = 0;
            }
            break;
        }
    }
    until = mono_ms() + patience(60000);
    for (;;) {
        int kind, flag, gap;
        size_t len, dn;
        long long left = until - mono_ms();
        if (left <= 0 || !next_record((int)left, &kind, rec, &len)) {
            puts("no answer");
            return 6;
        }
        if (kind == 'G') {
            puts("gone");
            return 4;
        }
        if (rec[0] != PIC_NOISE_REC_DATA || pic_noise_open_record(&t, rec, len, &flag, out, &dn, &gap) != 0) {
            continue;
        }
        out[dn] = '\0';
        if (strstr((char *)out, "\"type\":\"paired\"")) {
            save(dir);
            puts("paired");
            printf("channel %s\n", dc);
            return 0;
        }
        if (strstr((char *)out, "pair_refused")) {
            puts("refused");
            return 3;
        }
    }
}

/* ---- a session and its script ---------------------------------------------------------- */

typedef struct {
    char key[64];
    char *json;
    long long sent_ms;
} pending;

static pic_noise_hs hs;
static pic_noise_transport T;
static int have_session, waiting_m2;
/* The ping that confirms a new session: its pong is not the script's, so expect never takes it for
 * the answer to a ping the script sent. */
static int auto_pong;
static int resets; /* reset records seen */
static unsigned char sid[8];
static long long m1_ms, cursor = -1;
static char follow[2048];
static pending pend[64];
static int npend;
static char *inbox[4096];
static int ninbox;
static char chan_b64[32], tok_b64[64];
/* The replica: events taken in at a mark (rep) and those since the last one (tent). */
static char **rep_ev, **tent_ev;
static size_t nrep, ntent, caprep, captent;

static void list_add(char ***l, size_t *n, size_t *cap, char *v) {
    if (*n == *cap) {
        *cap = *cap ? *cap * 2 : 256;
        if (!(*l = realloc(*l, *cap * sizeof **l))) {
            die("memory");
        }
    }
    (*l)[(*n)++] = v;
}

static void tent_drop(void) {
    for (size_t i = 0; i < ntent; i++) {
        free(tent_ev[i]);
    }
    ntent = 0;
}
static unsigned char *assembled;
static size_t alen;

static void send_raw(const char *json) {
    size_t n = strlen(json), at = 0;
    unsigned char rec[PIC_NOISE_RECORD_CAP];
    if (!have_session) {
        return;
    }
    do {
        size_t part = n - at > PIC_NOISE_CHUNK ? PIC_NOISE_CHUNK : n - at;
        size_t rn = pic_noise_record(&T, at + part == n, json + at, part, rec);
        (void)post_record(chan_b64, tok_b64, rec, rn);
        at += part;
    } while (at < n);
}

static void hello(void) {
    unsigned char prologue[41], m[512], rec[600];
    size_t mn, rn;
    memcpy(prologue, "pic-rc/1", 8);
    prologue[8] = 0;
    memcpy(prologue + 9, P.mailbox, 16);
    memcpy(prologue + 25, P.channel, 16);
    if (pic_platform_get()->entropy(sid, 8) != 0) {
        die("entropy");
    }
    pic_noise_hs_init(&hs, 1, &P.stat, P.pic_pub, NULL, prologue, sizeof prologue);
    if (pic_noise_write1(&hs, "{\"v\":1}", 7, m, sizeof m, &mn) != 0) {
        die("write1");
    }
    rn = pic_noise_head(PIC_NOISE_REC_M1, sid, m, mn, rec);
    have_session = 0;
    waiting_m2 = 1;
    auto_pong = 0;
    m1_ms = mono_ms();
    if (post_record(chan_b64, tok_b64, rec, rn) == 404) {
        puts("gone");
        (void)fflush(stdout);
    }
}

/* A sync with a new key, as the page sends it: what comes for an earlier one is dropped. */
static char skey[48];
static int nokey;

static void send_sync(void) {
    char sync[2300];
    unsigned char r[12];
    if (pic_platform_get()->entropy(r, sizeof r) != 0) {
        die("entropy");
    }
    pic_b64u_enc(r, sizeof r, skey);
    (void)snprintf(sync, sizeof sync, "{\"type\":\"sync\",\"session\":%s,\"seq\":%lld,\"key\":\"%s\"}", follow, cursor, skey);
    send_raw(sync);
}

/* 1 when JSON (an event or a mark) is for the latest sync; one with no key is counted. */
static int this_sync(const char *json) {
    const char *pl = strstr(json, "\"payload\":"), *k = strstr(json, "\"key\":\"");
    size_t n = strlen(skey);
    if (!k || (pl && k > pl)) {
        nokey++;
        puts("nokey");
        return 1;
    }
    if (strncmp(k + 7, skey, n) != 0 || k[7 + n] != '"') {
        puts("stale");
        return 0;
    }
    return 1;
}

static void resume(void) {
    if (follow[0]) {
        send_sync();
    }
    for (int i = 0; i < npend; i++) {
        send_raw(pend[i].json);
        pend[i].sent_ms = mono_ms();
    }
}

static char pair_code[8]; /* the six digits of the last pair_request, for $CODE */

static void got_message(const char *json) {
    printf("<- %s\n", json);
    (void)fflush(stdout);
    if (strncmp(json, "{\"type\":\"pair_request\"", 22) == 0) {
        const char *c = strstr(json, "\"code\":\"");
        if (c) {
            (void)snprintf(pair_code, sizeof pair_code, "%.6s", c + 8);
        }
    }
    for (int i = 0; i < npend; i++) {
        char k[100];
        (void)snprintf(k, sizeof k, "\"key\":\"%s\"", pend[i].key);
        if (strstr(json, k) && (strstr(json, "\"type\":\"ack\"") || strstr(json, "\"type\":\"response\"") ||
                                strstr(json, "\"type\":\"error\""))) {
            free(pend[i].json);
            pend[i] = pend[--npend];
            i--;
        }
    }
    if ((strncmp(json, "{\"type\":\"sync\"", 14) == 0 || strncmp(json, "{\"type\":\"event\"", 15) == 0) && follow[0] &&
        strstr(json, follow) && !this_sync(json)) {
        return;
    }
    if (strncmp(json, "{\"type\":\"sync\"", 14) == 0 && follow[0] && strstr(json, follow)) {
        const char *s = strstr(json, "\"seq\":");
        if (s) {
            cursor = atoll(s + 6);
        }
        for (size_t i = 0; i < ntent; i++) { /* a mark: what came since is the replica's now */
            list_add(&rep_ev, &nrep, &caprep, tent_ev[i]);
        }
        ntent = 0;
    } else if (strncmp(json, "{\"type\":\"event\"", 15) == 0 && follow[0] && strstr(json, follow)) {
        const char *s = strstr(json, "\"seq\":"), *pl = strstr(json, "\"payload\":");
        char *one = malloc(strlen(json) + 32);
        if (!one) {
            die("memory");
        }
        (void)sprintf(one, "%lld\t%s", s ? atoll(s + 6) : -1, pl ? pl + 10 : json);
        list_add(&tent_ev, &ntent, &captent, one);
    }
    if (auto_pong && strcmp(json, "{\"type\":\"pong\"}") == 0) {
        auto_pong = 0;
        return;
    }
    if (strstr(json, "\"type\":\"bye\"") && !getenv("FAKE_PHONE_IGNORE_BYE")) {
        have_session = 0;
        waiting_m2 = 0;
        m1_ms = 0; /* a new handshake at once */
    }
    if (ninbox < 4096) {
        inbox[ninbox++] = strdup(json);
    }
}

/* Serves the session for MS: handshakes, records, retries. */
static void pump(int ms) {
    static long long last_ping;
    long long until = mono_ms() + ms, every = getenv("FAKE_PHONE_PING_MS") ? atoll(getenv("FAKE_PHONE_PING_MS")) : 0;
    for (;;) {
        int kind;
        size_t len;
        unsigned char rec[PIC_NOISE_RECORD_CAP];
        long long now = mono_ms(), left = until - now;
        if (!have_session && (!waiting_m2 || now - m1_ms > 3000)) {
            hello();
        }
        if (every > 0 && have_session && now - last_ping > every) {
            last_ping = now;
            send_raw("{\"type\":\"ping\"}");
        }
        for (int i = 0; have_session && i < npend; i++) {
            if (now - pend[i].sent_ms > 2000) {
                send_raw(pend[i].json);
                pend[i].sent_ms = now;
            }
        }
        if (left <= 0) {
            return;
        }
        if (!next_record((int)(left > 100 ? 100 : left), &kind, rec, &len)) {
            continue;
        }
        if (kind == 'G') {
            puts("gone");
            (void)fflush(stdout);
            exit(4);
        }
        if (len < 9 || memcmp(rec + 1, sid, 8) != 0) {
            continue;
        }
        if (rec[0] == PIC_NOISE_REC_M2 && waiting_m2) {
            unsigned char pl[256], up[32], down[32];
            size_t pn;
            if (pic_noise_read2(&hs, rec + 9, len - 9, pl, sizeof pl, &pn) != 0) {
                continue;
            }
            if (pic_noise_split(&hs, up, down) != 0) {
                continue;
            }
            pic_noise_transport_init(&T, 1, sid, up, down);
            have_session = 1;
            waiting_m2 = 0;
            alen = 0;
            tent_drop();
            puts("session");
            (void)fflush(stdout);
            if (!follow[0] && !npend) {
                send_raw("{\"type\":\"ping\"}"); /* the first message confirms the session */
                auto_pong = 1;
            }
            resume();
        } else if (rec[0] == PIC_NOISE_REC_RESET) {
            puts("reset");
            (void)fflush(stdout);
            resets++;
            if (have_session && now - m1_ms > 5000) { /* at most once every 5 s */
                have_session = 0;
                waiting_m2 = 0;
            }
        } else if (rec[0] == PIC_NOISE_REC_DATA && have_session) {
            unsigned char out[PIC_NOISE_CHUNK];
            size_t dn;
            int flag, gap;
            if (pic_noise_open_record(&T, rec, len, &flag, out, &dn, &gap) != 0) {
                unsigned long long c = 0;
                for (size_t k = 9; k < 17 && k < len; k++) {
                    c = (c << 8) | rec[k];
                }
                printf("unopened record, counter %llu after %lld, %zu bytes\n", c, (long long)T.last, len);
                (void)fflush(stdout);
                continue;
            }
            if (gap) {
                puts("gap");
                (void)fflush(stdout);
                alen = 0;
                /* What it holds past the cursor goes, and it syncs from the cursor in a new session:
                 * records the old one still brings are then dropped by their session id, so the
                 * events sent again are not taken twice. */
                tent_drop();
                have_session = 0;
                waiting_m2 = 0;
                continue;
            }
            if (!(assembled = realloc(assembled, alen + dn + 1))) {
                die("memory");
            }
            memcpy(assembled + alen, out, dn);
            alen += dn;
            if (flag == 1) {
                assembled[alen] = '\0';
                alen = 0;
                got_message((char *)assembled);
            }
        }
    }
}

static char *subst(const char *line) {
    static char out[65536];
    const char *at = strstr(line, "$CURSOR"), *code = strstr(line, "$CODE");
    if (at) {
        (void)snprintf(out, sizeof out, "%.*s%lld%s", (int)(at - line), line, cursor, at + 7);
    } else if (code) {
        (void)snprintf(out, sizeof out, "%.*s%s%s", (int)(code - line), line, pair_code, code + 5);
    } else {
        (void)snprintf(out, sizeof out, "%s", line);
    }
    return out;
}

static int run(const char *dir) {
    char line[65536];
    int seen = 0; /* messages examined by expect */
    load(dir);
    pic_b64u_enc(P.channel, 16, chan_b64);
    pic_b64u_enc(P.token, 32, tok_b64);
    start_reader(P.channel, tok_b64);
    hello();
    while (fgets(line, sizeof line, stdin)) {
        char *l = line, *arg;
        line[strcspn(line, "\n")] = '\0';
        while (*l == ' ') {
            l++;
        }
        if (!*l || *l == '#') {
            continue;
        }
        arg = strchr(l, ' ');
        if (arg) {
            *arg++ = '\0';
        }
        if (strcmp(l, "send") == 0 && arg) {
            const char *j = subst(arg);
            const char *f = strstr(j, "\"type\":\"sync\"");
            while (!have_session) {
                pump(100);
            }
            if (f) { /* remember what is followed, for resumption */
                const char *s = strstr(j, "\"session\":");
                if (s) {
                    const char *e = strchr(s + 11, '"');
                    if (e) {
                        (void)snprintf(follow, sizeof follow, "%.*s", (int)(e - (s + 10) + 1), s + 10);
                    }
                }
                const char *q = strstr(j, "\"seq\":");
                if (q) {
                    cursor = atoll(q + 6);
                }
                send_sync();
            } else {
                send_raw(j);
            }
        } else if (strcmp(l, "cmd") == 0 && arg && strchr(arg, ' ')) {
            char *json = strchr(arg, ' ');
            *json++ = '\0';
            while (!have_session) {
                pump(100);
            }
            if (npend < 64) {
                (void)snprintf(pend[npend].key, sizeof pend[npend].key, "%s", arg);
                pend[npend].json = strdup(subst(json));
                pend[npend].sent_ms = mono_ms();
                send_raw(pend[npend].json);
                npend++;
            }
        } else if (strcmp(l, "cmdfile") == 0 && arg && strchr(arg, ' ')) {
            char *file = strchr(arg, ' '), *json = NULL;
            FILE *f;
            long len = 0;
            *file++ = '\0';
            if (!(f = fopen(file, "rb")) || fseek(f, 0, SEEK_END) != 0 || (len = ftell(f)) < 0 || fseek(f, 0, SEEK_SET) != 0 ||
                !(json = malloc((size_t)len + 1)) || fread(json, 1, (size_t)len, f) != (size_t)len) {
                die("cmdfile");
            }
            fclose(f);
            json[len] = '\0';
            json[strcspn(json, "\n")] = '\0';
            while (!have_session) {
                pump(100);
            }
            if (npend < 64) {
                (void)snprintf(pend[npend].key, sizeof pend[npend].key, "%s", arg);
                pend[npend].json = json;
                pend[npend].sent_ms = mono_ms();
                send_raw(pend[npend].json);
                npend++;
            } else {
                free(json);
            }
        } else if (strcmp(l, "expect") == 0 && arg) {
            long long until = mono_ms() + patience(30000);
            int found = 0;
            while (!found && mono_ms() < until) {
                for (; seen < ninbox && !found; seen++) {
                    found = strstr(inbox[seen], arg) != NULL;
                }
                if (!found) {
                    pump(100);
                }
            }
            if (!found) {
                printf("FAIL expect %s\n", arg);
                return 1;
            }
        } else if (strcmp(l, "seen") == 0 && arg) { /* any message so far, in whatever order they came */
            long long until = mono_ms() + patience(30000);
            int found = 0;
            while (!found && mono_ms() < until) {
                for (int i = 0; i < ninbox && !found; i++) {
                    found = strstr(inbox[i], arg) != NULL;
                }
                if (!found) {
                    pump(100);
                }
            }
            if (!found) {
                printf("FAIL seen %s\n", arg);
                return 1;
            }
        } else if (strcmp(l, "expectnot") == 0 && arg && strrchr(arg, ' ')) {
            char *ms = strrchr(arg, ' ');
            int from = ninbox;
            *ms++ = '\0';
            pump(atoi(ms));
            for (int i = from; i < ninbox; i++) {
                if (strstr(inbox[i], arg)) {
                    printf("FAIL expectnot %s\n", arg);
                    return 1;
                }
            }
        } else if (strcmp(l, "swapsend") == 0 && arg) {
            unsigned char a[PIC_NOISE_RECORD_CAP], b[PIC_NOISE_RECORD_CAP], body[2 * PIC_NOISE_RECORD_CAP + 4];
            size_t an, bn;
            const char *j = subst(arg);
            while (!have_session) {
                pump(100);
            }
            an = pic_noise_record(&T, 1, j, strlen(j), a);
            bn = pic_noise_record(&T, 1, "{\"type\":\"ping\"}", 15, b);
            body[0] = (unsigned char)(bn >> 8);
            body[1] = (unsigned char)bn;
            memcpy(body + 2, b, bn);
            body[2 + bn] = (unsigned char)(an >> 8);
            body[3 + bn] = (unsigned char)an;
            memcpy(body + 4 + bn, a, an);
            (void)post(chan_b64, tok_b64, body, an + bn + 4);
        } else if (strcmp(l, "awaitgone") == 0) { /* pump exits 4 once the channel is gone */
            long long until = mono_ms() + patience(30000);
            while (mono_ms() < until) {
                pump(100);
            }
            puts("FAIL awaitgone: the channel is still there");
            return 1;
        } else if (strcmp(l, "expectreset") == 0) {
            long long until = mono_ms() + patience(30000);
            while (!resets && mono_ms() < until) {
                pump(100);
            }
            if (!resets) {
                puts("FAIL expectreset");
                return 1;
            }
        } else if (strcmp(l, "nosession") == 0 && arg) {
            pump(atoi(arg));
            if (have_session) {
                puts("FAIL a session was made");
                return 1;
            }
        } else if (strcmp(l, "keyed") == 0) {
            if (nokey) {
                printf("FAIL keyed: %d events or marks without the sync's key\n", nokey);
                return 1;
            }
        } else if (strcmp(l, "count") == 0 && arg && strrchr(arg, ' ')) {
            char *num = strrchr(arg, ' ');
            int want, got = 0;
            *num++ = '\0';
            want = atoi(num);
            for (int i = 0; i < ninbox; i++) {
                got += strstr(inbox[i], arg) != NULL;
            }
            if (got != want) {
                printf("FAIL count %s: %d, not %d\n", arg, got, want);
                return 1;
            }
        } else if (strcmp(l, "waitcount") == 0 && arg && strrchr(arg, ' ')) { /* count, once that many came */
            char *num = strrchr(arg, ' ');
            long long until = mono_ms() + patience(30000);
            int want, got = 0;
            *num++ = '\0';
            want = atoi(num);
            for (;;) {
                got = 0;
                for (int i = 0; i < ninbox; i++) {
                    got += strstr(inbox[i], arg) != NULL;
                }
                if (got >= want || mono_ms() >= until) {
                    break;
                }
                pump(100);
            }
            if (got != want) {
                printf("FAIL waitcount %s: %d, not %d\n", arg, got, want);
                return 1;
            }
        } else if (strcmp(l, "mark") == 0 && arg) {
            char path[1200];
            FILE *f;
            (void)snprintf(path, sizeof path, "%s%s%s", arg[0] == '/' ? "" : dir, arg[0] == '/' ? "" : "/", arg);
            if (!(f = fopen(path, "w"))) {
                die("mark");
            }
            fclose(f);
        } else if (strcmp(l, "waitfor") == 0 && arg) {
            char path[1200];
            long long until = mono_ms() + patience(30000);
            (void)snprintf(path, sizeof path, "%s%s%s", arg[0] == '/' ? "" : dir, arg[0] == '/' ? "" : "/", arg);
            while (access(path, F_OK) != 0) {
                if (mono_ms() > until) {
                    printf("FAIL waitfor %s\n", arg);
                    return 1;
                }
                pump(50);
            }
        } else if (strcmp(l, "replay") == 0) {
            (void)post(chan_b64, tok_b64, last_rec, last_n);
        } else if (strcmp(l, "garble") == 0 && arg) {
            while (!have_session) {
                pump(100);
            }
            for (int k = atoi(arg); k > 0; k--) {
                unsigned char rec[PIC_NOISE_RECORD_CAP];
                size_t rn = pic_noise_record(&T, 1, "{\"type\":\"ping\"}", 15, rec);
                rec[rn - 1] ^= 0x5a;
                (void)post_record(chan_b64, tok_b64, rec, rn);
            }
        } else if (strcmp(l, "skip") == 0) {
            T.send_n++;
        } else if (strcmp(l, "newsession") == 0) {
            have_session = 0;
            waiting_m2 = 0;
            pump(10);
        } else if (strcmp(l, "sleep") == 0 && arg) {
            pump(atoi(arg));
        } else if (strcmp(l, "timed") == 0 && arg && strchr(arg, ' ') && strchr(strchr(arg, ' ') + 1, ' ')) {
            char *key = strchr(arg, ' ') + 1, *json = strchr(key, ' '), want[100];
            long long t0, until;
            int from, found = 0;
            *json++ = '\0';
            (void)snprintf(want, sizeof want, "\"key\":\"%s\"", key);
            while (!have_session) {
                pump(100);
            }
            from = ninbox;
            t0 = mono_ms();
            until = t0 + atoll(arg);
            send_raw(subst(json));
            while (!found && mono_ms() < until) {
                pump(20);
                for (int i = from; i < ninbox && !found; i++) {
                    found = strstr(inbox[i], want) != NULL;
                }
            }
            if (found) {
                printf("answered %s in %lld ms\n", key, mono_ms() - t0);
            } else {
                printf("late %s\n", key);
            }
            (void)fflush(stdout);
        } else if (strcmp(l, "ping") == 0 && arg) {
            long long t0, until;
            int from, found = 0;
            while (!have_session) {
                pump(100);
            }
            from = ninbox;
            t0 = mono_ms();
            until = t0 + atoll(arg);
            send_raw("{\"type\":\"ping\"}");
            while (!found && mono_ms() < until) {
                pump(20);
                for (int i = from; i < ninbox && !found; i++) {
                    found = strcmp(inbox[i], "{\"type\":\"pong\"}") == 0;
                }
            }
            if (found) {
                printf("pong %lld ms\n", mono_ms() - t0);
            } else {
                puts("late pong");
            }
            (void)fflush(stdout);
        } else if (strcmp(l, "replica") == 0 && arg) {
            FILE *f = fopen(arg, "w");
            if (!f) {
                die("replica");
            }
            for (size_t i = 0; i < nrep; i++) {
                fprintf(f, "%s\n", rep_ev[i]);
            }
            fclose(f);
        } else {
            printf("FAIL unknown script line %s\n", l);
            return 1;
        }
    }
    pump(200);
    return 0;
}

/* ---- Web Push, as the phone's browser does it ----------------------------------------------- */

static int pushkeys(const char *dir, const char *endpoint, const char *notify) {
    pic_noise_keypair kp;
    unsigned char auth[16];
    char path[1100], priv[64], pub[100], au[32];
    FILE *f;
    if (pic_noise_keypair_make(&kp, NULL) != 0 || pic_platform_get()->entropy(auth, 16) != 0) {
        die("entropy");
    }
    pic_b64u_enc(kp.priv, 32, priv);
    pic_b64u_enc(kp.pub, 65, pub);
    pic_b64u_enc(auth, 16, au);
    (void)snprintf(path, sizeof path, "%s/push", dir);
    if (!(f = fopen(path, "w"))) {
        die("cannot write the push keys");
    }
    fprintf(f, "%s\n%s\n%s\n", priv, pub, au);
    fclose(f);
    printf("{\"type\":\"push\",\"payload\":{\"subscription\":{\"endpoint\":\"%s\",\"keys\":{\"p256dh\":\"%s\",\"auth\":\"%s\"}}", endpoint,
           pub, au);
    if (notify) {
        printf(",\"notify\":\"%s\"", notify);
    }
    printf("}}\n");
    return 0;
}

static void push_hmac(unsigned char out[32], const unsigned char *k, size_t kn, const void *a, size_t an) {
    br_hmac_key_context kc;
    br_hmac_context c;
    br_hmac_key_init(&kc, &br_sha256_vtable, k, kn);
    br_hmac_init(&c, &kc, 0);
    br_hmac_update(&c, a, an);
    br_hmac_out(&c, out);
}

static int pushread(const char *dir, const char *file) {
    unsigned char priv[32], pub[65], auth[16], as_pub[65], shared[65], key[32], ikm[32], prk[32], cek[32], nonce[32];
    unsigned char info[160], *body, *pt;
    char path[1100], lines[3][128];
    static char req[65536];
    size_t n, o = 0, ctn;
    char *cl, *start;
    br_aes_ct_ctr_keys ac;
    br_gcm_context g;
    FILE *f;
    (void)snprintf(path, sizeof path, "%s/push", dir);
    if (!(f = fopen(path, "r"))) {
        die("no push keys");
    }
    for (int i = 0; i < 3; i++) {
        if (!fgets(lines[i], sizeof lines[i], f)) {
            die("push keys");
        }
        lines[i][strcspn(lines[i], "\n")] = '\0';
    }
    fclose(f);
    if (pic_b64u_dec(lines[0], strlen(lines[0]), priv, 32) != 32 || pic_b64u_dec(lines[1], strlen(lines[1]), pub, 65) != 65 ||
        pic_b64u_dec(lines[2], strlen(lines[2]), auth, 16) != 16) {
        die("push keys");
    }
    if (!(f = fopen(file, "rb"))) {
        die("no request");
    }
    n = fread(req, 1, sizeof req - 1, f);
    fclose(f);
    req[n] = '\0';
    start = strstr(req, "\r\n\r\n");
    cl = strstr(req, "Content-Length: ");
    if (!start || !cl) {
        return 1;
    }
    body = (unsigned char *)start + 4;
    n = (size_t)atol(cl + 16);
    if (n < 86 + 17 || body + n > (unsigned char *)req + sizeof req || memcmp(body + 16, "\x00\x00\x10\x00\x41", 5) != 0) {
        return 1;
    }
    memcpy(as_pub, body + 21, 65);
    memcpy(shared, as_pub, 65);
    if (!br_ec_p256_m31.mul(shared, 65, priv, 32, BR_EC_secp256r1)) {
        return 1;
    }
    { /* HMAC(auth, ecdh_secret), then the IKM */
        br_hmac_key_context kc;
        br_hmac_context c;
        br_hmac_key_init(&kc, &br_sha256_vtable, auth, 16);
        br_hmac_init(&c, &kc, 0);
        br_hmac_update(&c, shared + 1, 32);
        br_hmac_out(&c, key);
    }
    memcpy(info, "WebPush: info", 14);
    o = 14;
    memcpy(info + o, pub, 65);
    o += 65;
    memcpy(info + o, as_pub, 65);
    o += 65;
    info[o++] = 1;
    push_hmac(ikm, key, 32, info, o);
    push_hmac(prk, body, 16, ikm, 32);
    push_hmac(cek, prk, 32, "Content-Encoding: aes128gcm\0\1", 29);
    push_hmac(nonce, prk, 32, "Content-Encoding: nonce\0\1", 25);
    ctn = n - 86 - 16;
    if (!(pt = malloc(ctn + 1))) {
        die("memory");
    }
    memcpy(pt, body + 86, ctn);
    br_aes_ct_ctr_init(&ac, cek, 16);
    br_gcm_init(&g, &ac.vtable, br_ghash_ctmul32);
    br_gcm_reset(&g, nonce, 12);
    br_gcm_flip(&g);
    br_gcm_run(&g, 0, pt, ctn);
    if (!br_gcm_check_tag(&g, body + 86 + ctn) || ctn == 0 || pt[ctn - 1] != 0x02) {
        free(pt);
        return 1;
    }
    fwrite(pt, 1, ctn - 1, stdout);
    putchar('\n');
    free(pt);
    return 0;
}

int main(int argc, char **argv) {
    signal(SIGPIPE, SIG_IGN);
    setvbuf(stdout, NULL, _IOLBF, 0);
    if (argc >= 5 && strcmp(argv[2], "pair") == 0) {
        return pair(argv[1], argv[3], argv[4], argc > 5 && strcmp(argv[5], "wrong-psk") == 0,
                    argc > 6 && strcmp(argv[5], "late") == 0 ? atoi(argv[6]) : 0, argc > 5 ? argv[5] : "");
    }
    if (argc == 3 && strcmp(argv[2], "run") == 0) {
        return run(argv[1]);
    }
    if (argc >= 4 && strcmp(argv[2], "pushkeys") == 0) {
        return pushkeys(argv[1], argv[3], argc > 4 ? argv[4] : NULL);
    }
    if (argc == 4 && strcmp(argv[2], "pushread") == 0) {
        return pushread(argv[1], argv[3]);
    }
    fputs("usage: fake_phone DIR pair URL NAME [wrong-psk | late MS | resend | rival | rival-badchan] | fake_phone DIR run < SCRIPT | fake_phone DIR pushkeys ENDPOINT [NOTIFY] | fake_phone DIR pushread FILE\n", stderr);
    return 2;
}