Skip to content
pi-c Artifact [0ef06085d8]
Login

Artifact [0ef06085d8]

Artifact 0ef06085d8d4586ed94a2ca0064eef154fe137d2009efcaeae1a37e0cda1fc6c:


/* 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]
 *       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.
 *       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)
 *         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
 *         expect TEXT        waits up to 30 s for a received message containing TEXT
 *         expectnot TEXT MS  fails if one containing TEXT arrives within MS
 *         replay             posts the last record again (a replay)
 *         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)
 *         count TEXT N       fails unless exactly N received messages contain TEXT
 *         mark NAME          creates DIR/NAME, for the test to act on
 *         waitfor NAME       serves the session until DIR/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
 *       Each message received is printed as "<- JSON"; a gap as "gap"; a new session as "session".
 *       A session not answered in 3 s is tried again, as is one that got a reset. */
#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 "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;
}

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 int pair(const char *dir, const char *url, const char *name, int wrong, int late) {
    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];
    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);
    {
        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() + 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");
                }
            }
            pic_noise_split(&hs, up, down);
            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);
            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() + 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");
            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;
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];
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;
    m1_ms = mono_ms();
    if (post_record(chan_b64, tok_b64, rec, rn) == 404) {
        puts("gone");
        (void)fflush(stdout);
    }
}

static void resume(void) {
    if (follow[0]) {
        char sync[2300];
        (void)snprintf(sync, sizeof sync, "{\"type\":\"sync\",\"session\":%s,\"seq\":%lld}", follow, cursor);
        send_raw(sync);
    }
    for (int i = 0; i < npend; i++) {
        send_raw(pend[i].json);
        pend[i].sent_ms = mono_ms();
    }
}

static void got_message(const char *json) {
    printf("<- %s\n", json);
    (void)fflush(stdout);
    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 && follow[0] && strstr(json, follow)) {
        const char *s = strstr(json, "\"seq\":");
        if (s) {
            cursor = atoll(s + 6);
        }
    }
    if (strstr(json, "\"type\":\"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) {
    long long until = mono_ms() + ms;
    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();
        }
        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;
            }
            pic_noise_split(&hs, up, down);
            pic_noise_transport_init(&T, 1, sid, up, down);
            have_session = 1;
            waiting_m2 = 0;
            alen = 0;
            puts("session");
            (void)fflush(stdout);
            if (!follow[0] && !npend) {
                send_raw("{\"type\":\"ping\"}"); /* the first message confirms the session */
            }
            resume();
        } else if (rec[0] == PIC_NOISE_REC_RESET) {
            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) {
                continue;
            }
            if (gap) {
                puts("gap");
                (void)fflush(stdout);
                alen = 0;
            }
            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");
    if (!at) {
        (void)snprintf(out, sizeof out, "%s", line);
    } else {
        (void)snprintf(out, sizeof out, "%.*s%lld%s", (int)(at - line), line, cursor, at + 7);
    }
    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_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, "expect") == 0 && arg) {
            long long until = mono_ms() + 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, "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, "nosession") == 0 && arg) {
            pump(atoi(arg));
            if (have_session) {
                puts("FAIL a session was made");
                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, "mark") == 0 && arg) {
            char path[1200];
            FILE *f;
            (void)snprintf(path, sizeof path, "%s/%s", dir, 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() + 30000;
            (void)snprintf(path, sizeof path, "%s/%s", dir, 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, "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 {
            printf("FAIL unknown script line %s\n", l);
            return 1;
        }
    }
    pump(200);
    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);
    }
    if (argc == 3 && strcmp(argv[2], "run") == 0) {
        return run(argv[1]);
    }
    fputs("usage: fake_phone DIR pair URL NAME [wrong-psk | late MS] | fake_phone DIR run < SCRIPT\n", stderr);
    return 2;
}