Skip to content
pi-c Documentation
Login

Documentation

/* Test-only relay: section 6 of docs/design/remote-protocol.md on plain HTTP at 127.0.0.1,
 * without its limits, so pic remote and the scripted phone can be tested with no Worker. Every
 * endpoint checks its bearer token by hashing it to the id in the path, as the real relay does.
 * Records are held in memory until a reader acknowledges them (a later Last-Event-ID or Pic-Ack)
 * or for 60 seconds. It exits on its own deadline. As the deployed Worker does: a new mailbox
 * without the invite is 403, a ninth device channel 409, a body that does not parse 400; a new
 * pairing channel replaces the one before; Pic-Ack acknowledges only the lane the requester reads
 * (pic: its mailbox stream or a pairing channel's up lane; a phone: its down lane); and a stream
 * gets "event: peer" with "1" or "0" when the other side's reader comes or goes ("C.1" or "C.0"
 * on pic's mailbox stream), once when it opens, and every POST answers Pic-Peer.
 *
 * Usage: fake_relay PORT_FILE DEADLINE_SECONDS [INVITE]
 *   INVITE: PUT /v1/m/M of a new mailbox needs the header Pic-Invite: INVITE.
 * Test controls, not part of the protocol, at POST /_test/ACTION:
 *   cut         ends every open stream (the relay may end any stream at any time)
 *   drop-down   drops the next record posted to any down lane (the phone sees a gap)
 *   dup-up      delivers the next record posted to any up lane twice (a replay)
 *   state       200 with "mailboxes N channels N held N"
 *   down?MS     closes every connection and refuses new ones for MS (the network went away)
 *   mute?MS     open streams get nothing for MS, not even the keepalive (a connection that died
 *               without a word); they stay open
 * Environment: FAKE_RELAY_PORT binds that port (to restart a killed relay where it was);
 * FAKE_RELAY_STATE keeps the mailboxes and channels in that file, as the Worker keeps them in
 * storage (held records are memory only, so a restart is a gap); FAKE_RELAY_BEAT_MS is the
 * keepalive (default 15000). Event ids start from the clock, so a new life never repeats one. */
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <poll.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/socket.h>
#include <time.h>
#include <unistd.h>

#include "noise.h"

#define MAX_CONN 64
#define MAX_MB 8
#define MAX_CH 16
#define MAX_HELD 1024
#define RETAIN_MS 60000LL

enum { K_DEVICE = 1, K_PAIR = 2 };
enum { UP = 0, DOWN = 1 };
enum { ST_NONE, ST_MAILBOX_UP, ST_CHAN_UP, ST_CHAN_DOWN };

typedef struct {
    unsigned char id[16];
    int kind;
    long long expires_ms; /* 0: never */
} channel;

typedef struct {
    int used;
    unsigned char id[16];
    channel ch[MAX_CH];
    int nch;
} mailbox;

typedef struct {
    int used;
    unsigned long long id;
    long long ms;
    int mb, dir;
    unsigned char ch[16];
    size_t len;
    unsigned char *rec;
} held;

typedef struct {
    int fd;
    char *in;
    size_t inlen, incap;
    char *out;
    size_t outlen, outcap;
    int stream, mb;
    unsigned char ch[16];
    unsigned long long sent; /* the last record id this stream sent */
    long long beat_ms;
    int closing;
} conn;

static mailbox mbs[MAX_MB];
static held hold[MAX_HELD];
static conn conns[MAX_CONN];
static unsigned long long next_id = 1, first_id = 1;
static const char *invite;
static int drop_down, dup_up;
static long long beat_ms = 15000, down_until, mute_until;
static const char *state_file;

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

static void die(const char *what) {
    perror(what);
    exit(2);
}

static void out_add(conn *c, const void *b, size_t n) {
    if (c->outlen + n > c->outcap) {
        size_t cap = c->outcap ? c->outcap : 8192;
        while (cap < c->outlen + n) {
            cap *= 2;
        }
        if (!(c->out = realloc(c->out, cap))) {
            die("realloc");
        }
        c->outcap = cap;
    }
    memcpy(c->out + c->outlen, b, n);
    c->outlen += n;
}

static void out_str(conn *c, const char *s) { out_add(c, s, strlen(s)); }

static void reply(conn *c, int status, const char *reason, const char *extra, const char *body) {
    char head[512];
    size_t bn = body ? strlen(body) : 0;
    (void)snprintf(head, sizeof head, "HTTP/1.1 %d %s\r\n%sContent-Length: %zu\r\n%sConnection: close\r\n\r\n", status,
                   reason, extra ? extra : "", bn, bn ? "Content-Type: application/json\r\n" : "");
    out_str(c, head);
    if (bn) {
        out_str(c, body);
    }
    c->closing = 1;
}

static void err_reply(conn *c, int status, const char *code) {
    char body[96];
    const char *reason = status == 401   ? "Unauthorized"
                         : status == 403 ? "Forbidden"
                         : status == 404 ? "Not Found"
                         : status == 409 ? "Conflict"
                         : status == 413 ? "Too Large"
                                         : "Bad Request";
    (void)snprintf(body, sizeof body, "{\"error\":\"%s\"}", code);
    reply(c, status, reason, NULL, body);
}

static int id_from(const char *s, size_t n, unsigned char out[16]) { return pic_b64u_dec(s, n, out, 16) == 16 ? 0 : -1; }

/* The bearer token, hashed with LABEL: 0 with the id, or -1. */
static int bearer_id(const char *auth, const char *label, unsigned char out[16]) {
    unsigned char tok[32];
    if (!auth || strncmp(auth, "Bearer ", 7) != 0 || pic_b64u_dec(auth + 7, strlen(auth + 7), tok, sizeof tok) != 32) {
        return -1;
    }
    pic_noise_id(out, label, tok);
    return 0;
}

static int find_mb(const unsigned char id[16]) {
    for (int i = 0; i < MAX_MB; i++) {
        if (mbs[i].used && memcmp(mbs[i].id, id, 16) == 0) {
            return i;
        }
    }
    return -1;
}

static channel *find_ch(int mb, const unsigned char id[16]) {
    mailbox *m = &mbs[mb];
    for (int i = 0; i < m->nch; i++) {
        if (memcmp(m->ch[i].id, id, 16) == 0) {
            if (m->ch[i].expires_ms && m->ch[i].expires_ms < now_ms()) {
                return NULL;
            }
            return &m->ch[i];
        }
    }
    return NULL;
}

static void stream_event(conn *c, const char *event, unsigned long long id, const char *data) {
    char line[64];
    if (id) {
        (void)snprintf(line, sizeof line, "id: %llu\n", id);
        out_str(c, line);
    }
    out_str(c, "event: ");
    out_str(c, event);
    out_str(c, "\ndata: ");
    out_str(c, data);
    out_str(c, "\n\n");
}

/* Whether held record H belongs on stream C. */
static int belongs(const conn *c, const held *h) {
    if (!h->used || h->mb != c->mb) {
        return 0;
    }
    switch (c->stream) {
    case ST_MAILBOX_UP: {
        const channel *ch = find_ch(h->mb, h->ch);
        return h->dir == UP && ch && ch->kind == K_DEVICE;
    }
    case ST_CHAN_UP:
        return h->dir == UP && memcmp(h->ch, c->ch, 16) == 0;
    case ST_CHAN_DOWN:
        return h->dir == DOWN && memcmp(h->ch, c->ch, 16) == 0;
    default:
        return 0;
    }
}

static void send_held(conn *c) {
    for (int i = 0; i < MAX_HELD; i++) {
        held *h = &hold[i];
        char *data;
        size_t at = 0;
        if (!belongs(c, h) || h->id <= c->sent) {
            continue;
        }
        if (!(data = malloc(24 + 4 * (h->len / 3 + 2) + 1))) {
            die("malloc");
        }
        if (c->stream == ST_MAILBOX_UP) {
            at = pic_b64u_enc(h->ch, 16, data);
            data[at++] = '.';
        }
        pic_b64u_enc(h->rec, h->len, data + at);
        stream_event(c, "frame", h->id, data);
        free(data);
        c->sent = h->id;
    }
}

/* Records with ids up to UPTO on the lanes C reads are acknowledged. */
static void ack(conn *c, unsigned long long upto) {
    for (int i = 0; i < MAX_HELD; i++) {
        if (belongs(c, &hold[i]) && hold[i].id <= upto) {
            free(hold[i].rec);
            hold[i].used = 0;
        }
    }
}

static void expire(void) {
    long long cut = now_ms() - RETAIN_MS;
    for (int i = 0; i < MAX_HELD; i++) {
        if (hold[i].used && hold[i].ms < cut) {
            free(hold[i].rec);
            hold[i].used = 0;
        }
    }
}

static void push_record(int mb, const unsigned char ch[16], int dir, const unsigned char *rec, size_t len) {
    int slot = -1;
    for (int i = 0; i < MAX_HELD; i++) {
        if (!hold[i].used) {
            slot = i;
            break;
        }
    }
    if (slot < 0) {
        return; /* full: dropped, a gap */
    }
    hold[slot].used = 1;
    hold[slot].id = next_id++;
    hold[slot].ms = now_ms();
    hold[slot].mb = mb;
    hold[slot].dir = dir;
    memcpy(hold[slot].ch, ch, 16);
    hold[slot].len = len;
    if (!(hold[slot].rec = malloc(len))) {
        die("malloc");
    }
    memcpy(hold[slot].rec, rec, len);
}

/* The reader of lane KIND (of channel CH, unless it is the mailbox's), or NULL. */
static conn *reader_of(int kind, int mb, const unsigned char *ch, const conn *besides) {
    for (int i = 0; i < MAX_CONN; i++) {
        conn *o = &conns[i];
        if (o != besides && o->fd >= 0 && !o->closing && o->stream == kind && o->mb == mb &&
            (kind == ST_MAILBOX_UP || memcmp(o->ch, ch, 16) == 0)) {
            return o;
        }
    }
    return NULL;
}

/* The other side hears that C's reader came (PRESENT 1) or went. */
static void announce(const conn *c, int present) {
    const char *flag = present ? "1" : "0";
    if (c->stream == ST_MAILBOX_UP) {
        for (int i = 0; i < mbs[c->mb].nch; i++) {
            conn *o;
            if (mbs[c->mb].ch[i].kind == K_DEVICE && (o = reader_of(ST_CHAN_DOWN, c->mb, mbs[c->mb].ch[i].id, c))) {
                stream_event(o, "peer", 0, flag);
            }
        }
    } else if (c->stream == ST_CHAN_UP) {
        conn *o = reader_of(ST_CHAN_DOWN, c->mb, c->ch, c);
        if (o) {
            stream_event(o, "peer", 0, flag);
        }
    } else if (c->stream == ST_CHAN_DOWN) {
        const channel *ch = find_ch(c->mb, c->ch);
        if (ch && ch->kind == K_PAIR) {
            conn *o = reader_of(ST_CHAN_UP, c->mb, c->ch, c);
            if (o) {
                stream_event(o, "peer", 0, flag);
            }
        } else {
            conn *o = reader_of(ST_MAILBOX_UP, c->mb, NULL, c);
            if (o) {
                char data[40];
                size_t n = pic_b64u_enc(c->ch, 16, data);
                (void)snprintf(data + n, sizeof data - n, ".%s", flag);
                stream_event(o, "peer", 0, data);
            }
        }
    }
}

/* A stream that ends without another taking its lane: the other side hears it went. */
static void stream_lost(conn *c) {
    if (c->stream != ST_NONE) {
        announce(c, 0);
        c->stream = ST_NONE;
    }
}

/* A stream on C replaces any other reader of the same lane. */
static void start_stream(conn *c, int kind, int mb, const unsigned char *ch, const char *last) {
    int replaced = 0;
    for (int i = 0; i < MAX_CONN; i++) {
        conn *o = &conns[i];
        if (o != c && o->fd >= 0 && o->stream == kind && o->mb == mb && (!ch || memcmp(o->ch, ch, 16) == 0)) {
            stream_event(o, "replaced", 0, "replaced");
            o->closing = 1;
            o->stream = ST_NONE;
            replaced = 1;
        }
    }
    c->stream = kind;
    c->mb = mb;
    if (ch) {
        memcpy(c->ch, ch, 16);
    }
    out_str(c, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n");
    if (!replaced) {
        announce(c, 1);
    }
    if (kind == ST_MAILBOX_UP) { /* the other side as it is now */
        for (int i = 0; i < mbs[mb].nch; i++) {
            if (mbs[mb].ch[i].kind == K_DEVICE && reader_of(ST_CHAN_DOWN, mb, mbs[mb].ch[i].id, c)) {
                char data[40];
                size_t n = pic_b64u_enc(mbs[mb].ch[i].id, 16, data);
                (void)snprintf(data + n, sizeof data - n, ".1");
                stream_event(c, "peer", 0, data);
            }
        }
    } else {
        const channel *chn = find_ch(mb, c->ch);
        int other = kind == ST_CHAN_UP ? ST_CHAN_DOWN : chn && chn->kind == K_PAIR ? ST_CHAN_UP : ST_MAILBOX_UP;
        stream_event(c, "peer", 0, reader_of(other, mb, c->ch, c) ? "1" : "0");
    }
    c->sent = 0;
    if (last) {
        unsigned long long n = strtoull(last, NULL, 10);
        int known = 0;
        for (int i = 0; i < MAX_HELD; i++) {
            known = known || (belongs(c, &hold[i]) && hold[i].id <= n);
        }
        ack(c, n);
        c->sent = n >= first_id && n < next_id ? n : 0; /* an id it does not know: all it holds */
        (void)known;
    }
    c->beat_ms = now_ms();
    send_held(c);
}

static void end_streams_of(int mb, const unsigned char *ch) {
    for (int i = 0; i < MAX_CONN; i++) {
        conn *o = &conns[i];
        if (o->fd >= 0 && o->stream != ST_NONE && o->mb == mb && (!ch || (o->stream != ST_MAILBOX_UP && memcmp(o->ch, ch, 16) == 0))) {
            stream_event(o, "gone", 0, "{}");
            o->closing = 1;
            o->stream = ST_NONE;
        }
    }
}

static const char *header(const char *head, const char *name, char *out, size_t cap) {
    size_t nl = strlen(name);
    for (const char *p = strstr(head, "\r\n"); p && p[2]; p = strstr(p + 2, "\r\n")) {
        const char *l = p + 2;
        if (strncasecmp(l, name, nl) == 0 && l[nl] == ':') {
            const char *v = l + nl + 1, *e = strstr(v, "\r\n");
            size_t n;
            while (*v == ' ') {
                v++;
            }
            n = e ? (size_t)(e - v) : strlen(v);
            if (n >= cap) {
                n = cap - 1;
            }
            memcpy(out, v, n);
            out[n] = '\0';
            return out;
        }
    }
    return NULL;
}

/* PATH's segments after /v1/m/: M, then optionally "c", C, LANE, or "up", or "c" alone. */
static void hex16(const unsigned char *b, char out[33]) {
    for (int i = 0; i < 16; i++) {
        (void)snprintf(out + 2 * i, 3, "%02x", b[i]);
    }
}

static int unhex16(const char *h, unsigned char out[16]) {
    for (int i = 0; i < 16; i++) {
        unsigned v;
        if (sscanf(h + 2 * i, "%2x", &v) != 1) {
            return -1;
        }
        out[i] = (unsigned char)v;
    }
    return 0;
}

/* The mailboxes and channels, as the Worker keeps them in storage. */
static void save_state(void) {
    char tmp[4096];
    FILE *f;
    if (!state_file) {
        return;
    }
    (void)snprintf(tmp, sizeof tmp, "%s.tmp", state_file);
    if (!(f = fopen(tmp, "w"))) {
        return;
    }
    for (int i = 0; i < MAX_MB; i++) {
        char h[33];
        if (!mbs[i].used) {
            continue;
        }
        hex16(mbs[i].id, h);
        fprintf(f, "M %s\n", h);
        for (int k = 0; k < mbs[i].nch; k++) {
            hex16(mbs[i].ch[k].id, h);
            fprintf(f, "C %s %d %lld\n", h, mbs[i].ch[k].kind, mbs[i].ch[k].expires_ms);
        }
    }
    fclose(f);
    (void)rename(tmp, state_file);
}

static void load_state(void) {
    char line[256];
    int mb = -1;
    FILE *f = state_file ? fopen(state_file, "r") : NULL;
    while (f && fgets(line, sizeof line, f)) {
        if (line[0] == 'M' && mb + 1 < MAX_MB && unhex16(line + 2, mbs[mb + 1].id) == 0) {
            mbs[++mb].used = 1;
            mbs[mb].nch = 0;
        } else if (line[0] == 'C' && mb >= 0 && mbs[mb].nch < MAX_CH) {
            channel *ch = &mbs[mb].ch[mbs[mb].nch];
            if (unhex16(line + 2, ch->id) == 0 && sscanf(line + 35, "%d %lld", &ch->kind, &ch->expires_ms) == 2) {
                mbs[mb].nch++;
            }
        }
    }
    if (f) {
        fclose(f);
    }
}

static void handle(conn *c, const char *method, const char *path, const char *head, const char *body, size_t blen) {
    char auth[256], last[32], inv[256], ackv[32];
    const char *a = header(head, "Authorization", auth, sizeof auth);
    const char *seg[6];
    size_t segn[6];
    int ns = 0, mb;
    unsigned char mid[16], cid[16], got[16];
    if (strncmp(path, "/_test/", 7) == 0 && strcmp(method, "POST") == 0) {
        const char *act = path + 7;
        if (strcmp(act, "cut") == 0) {
            for (int i = 0; i < MAX_CONN; i++) {
                if (conns[i].fd >= 0 && conns[i].stream != ST_NONE) {
                    conns[i].closing = 1;
                }
            }
            for (int i = 0; i < MAX_CONN; i++) {
                if (conns[i].fd >= 0 && conns[i].stream != ST_NONE) {
                    stream_lost(&conns[i]);
                }
            }
            reply(c, 204, "No Content", NULL, NULL);
        } else if (strcmp(act, "drop-down") == 0) {
            drop_down++;
            reply(c, 204, "No Content", NULL, NULL);
        } else if (strcmp(act, "dup-up") == 0) {
            dup_up++;
            reply(c, 204, "No Content", NULL, NULL);
        } else if (strncmp(act, "down?", 5) == 0) {
            down_until = now_ms() + atoll(act + 5);
            for (int i = 0; i < MAX_CONN; i++) {
                if (conns[i].fd >= 0 && &conns[i] != c) {
                    conns[i].closing = 1;
                    conns[i].outlen = 0; /* cut, not ended: nothing more is sent */
                }
            }
            reply(c, 204, "No Content", NULL, NULL);
        } else if (strncmp(act, "mute?", 5) == 0) {
            mute_until = now_ms() + atoll(act + 5);
            reply(c, 204, "No Content", NULL, NULL);
        } else if (strcmp(act, "state") == 0) {
            char s[128];
            int nm = 0, nc = 0, nh = 0;
            for (int i = 0; i < MAX_MB; i++) {
                if (mbs[i].used) {
                    nm++;
                    for (int k = 0; k < mbs[i].nch; k++) {
                        nc += !mbs[i].ch[k].expires_ms || mbs[i].ch[k].expires_ms >= now_ms();
                    }
                }
            }
            for (int i = 0; i < MAX_HELD; i++) {
                nh += hold[i].used;
            }
            (void)snprintf(s, sizeof s, "\"mailboxes %d channels %d held %d\"", nm, nc, nh);
            reply(c, 200, "OK", NULL, s);
        } else {
            err_reply(c, 404, "not_found");
        }
        return;
    }
    if (strncmp(path, "/v1/m/", 6) != 0) {
        err_reply(c, 404, "not_found");
        return;
    }
    for (const char *p = path + 6; *p && ns < 6;) {
        const char *e = strchr(p, '/');
        size_t n = e ? (size_t)(e - p) : strlen(p);
        seg[ns] = p;
        segn[ns++] = n;
        if (!e) {
            break;
        }
        p = e + 1;
    }
    if (ns < 1 || id_from(seg[0], segn[0], mid) != 0) {
        err_reply(c, 404, "not_found");
        return;
    }
    if (header(head, "Pic-Ack", ackv, sizeof ackv) && (mb = find_mb(mid)) >= 0) {
        /* acknowledged on any request, for the lane the requester reads: a phone its down lane;
         * pic a pairing channel's up lane, or else its mailbox stream */
        conn tmp = *c;
        int owner = bearer_id(a, "pic-rc/1 mailbox", got) == 0 && memcmp(got, mid, 16) == 0;
        const channel *chn;
        tmp.mb = mb;
        memset(tmp.ch, 0, 16);
        if (ns >= 3) {
            (void)id_from(seg[2], segn[2], tmp.ch);
        }
        chn = ns >= 3 ? find_ch(mb, tmp.ch) : NULL;
        tmp.stream = !owner ? ST_CHAN_DOWN : chn && chn->kind == K_PAIR ? ST_CHAN_UP : ST_MAILBOX_UP;
        ack(&tmp, strtoull(ackv, NULL, 10));
    }
    /* the phone's two requests: a channel token */
    if (ns == 4 && segn[1] == 1 && seg[1][0] == 'c' && id_from(seg[2], segn[2], cid) == 0 &&
        ((strcmp(method, "GET") == 0 && segn[3] == 4 && strncmp(seg[3], "down", 4) == 0) ||
         (strcmp(method, "POST") == 0 && segn[3] == 2 && strncmp(seg[3], "up", 2) == 0))) {
        channel *ch;
        if (bearer_id(a, "pic-rc/1 channel", got) != 0 || memcmp(got, cid, 16) != 0) {
            err_reply(c, 401, "unauthorized");
            return;
        }
        if ((mb = find_mb(mid)) < 0 || !(ch = find_ch(mb, cid))) {
            err_reply(c, 404, "not_found");
            return;
        }
        if (strcmp(method, "GET") == 0) {
            start_stream(c, ST_CHAN_DOWN, mb, cid, header(head, "Last-Event-ID", last, sizeof last));
            return;
        }
        goto post_records;
    }
    /* everything else is the owner's */
    if (bearer_id(a, "pic-rc/1 mailbox", got) != 0 || memcmp(got, mid, 16) != 0) {
        err_reply(c, 401, "unauthorized");
        return;
    }
    mb = find_mb(mid);
    if (ns == 1 && strcmp(method, "PUT") == 0) {
        if (mb < 0) {
            if (invite && (!header(head, "Pic-Invite", inv, sizeof inv) || strcmp(inv, invite) != 0)) {
                err_reply(c, 403, "invite_required");
                return;
            }
            for (int i = 0; i < MAX_MB; i++) {
                if (!mbs[i].used) {
                    memset(&mbs[i], 0, sizeof mbs[i]);
                    mbs[i].used = 1;
                    memcpy(mbs[i].id, mid, 16);
                    break;
                }
            }
        }
        reply(c, 204, "No Content", NULL, NULL);
        return;
    }
    if (mb < 0) {
        err_reply(c, 404, "not_found");
        return;
    }
    if (ns == 1 && strcmp(method, "DELETE") == 0) {
        end_streams_of(mb, NULL);
        for (int i = 0; i < MAX_CONN; i++) {
            if (conns[i].fd >= 0 && conns[i].mb == mb && conns[i].stream == ST_MAILBOX_UP) {
                stream_event(&conns[i], "gone", 0, "{}");
                conns[i].closing = 1;
                conns[i].stream = ST_NONE;
            }
        }
        mbs[mb].used = 0;
        reply(c, 204, "No Content", NULL, NULL);
        return;
    }
    if (ns == 2 && segn[1] == 1 && seg[1][0] == 'c' && strcmp(method, "GET") == 0) {
        char list[4096];
        size_t o = 0;
        long long now = now_ms();
        list[o++] = '[';
        for (int i = 0; i < mbs[mb].nch; i++) {
            channel *ch = &mbs[mb].ch[i];
            char id[32];
            if (ch->expires_ms && ch->expires_ms < now) {
                continue;
            }
            pic_b64u_enc(ch->id, 16, id);
            o += (size_t)snprintf(list + o, sizeof list - o, "%s{\"id\":\"%s\",\"kind\":\"%s\",\"expires\":%lld}", o > 1 ? "," : "",
                                  id, ch->kind == K_DEVICE ? "device" : "pair", ch->expires_ms ? ch->expires_ms / 1000 : 0LL);
        }
        (void)snprintf(list + o, sizeof list - o, "]");
        reply(c, 200, "OK", NULL, list);
        return;
    }
    if (ns == 2 && segn[1] == 2 && strncmp(seg[1], "up", 2) == 0 && strcmp(method, "GET") == 0) {
        start_stream(c, ST_MAILBOX_UP, mb, NULL, header(head, "Last-Event-ID", last, sizeof last));
        return;
    }
    if (ns < 3 || segn[1] != 1 || seg[1][0] != 'c' || id_from(seg[2], segn[2], cid) != 0) {
        err_reply(c, 404, "not_found");
        return;
    }
    if (ns == 3 && strcmp(method, "PUT") == 0) {
        channel *ch = NULL;
        int kind = strstr(body ? body : "", "\"pair\"") ? K_PAIR : strstr(body ? body : "", "\"device\"") ? K_DEVICE : 0;
        const char *ttl = body ? strstr(body, "\"ttl\":") : NULL;
        if (!kind || blen > 1024) {
            err_reply(c, 400, "bad_request");
            return;
        }
        for (int i = 0; i < mbs[mb].nch; i++) {
            if (memcmp(mbs[mb].ch[i].id, cid, 16) == 0) {
                ch = &mbs[mb].ch[i];
            }
        }
        if (kind == K_DEVICE && !(ch && ch->kind == K_DEVICE)) {
            int devices = 0;
            for (int i = 0; i < mbs[mb].nch; i++) {
                devices += mbs[mb].ch[i].kind == K_DEVICE;
            }
            if (devices >= 8) {
                err_reply(c, 409, "too_many_channels");
                return;
            }
        }
        if (kind == K_PAIR) { /* one pairing channel a mailbox: a new offer replaces the one before */
            for (int i = 0; i < mbs[mb].nch; i++) {
                if (mbs[mb].ch[i].kind == K_PAIR && memcmp(mbs[mb].ch[i].id, cid, 16) != 0) {
                    end_streams_of(mb, mbs[mb].ch[i].id);
                    mbs[mb].ch[i--] = mbs[mb].ch[--mbs[mb].nch];
                }
            }
            ch = NULL;
            for (int i = 0; i < mbs[mb].nch; i++) {
                if (memcmp(mbs[mb].ch[i].id, cid, 16) == 0) {
                    ch = &mbs[mb].ch[i];
                }
            }
        }
        if (!ch) {
            if (mbs[mb].nch == MAX_CH) {
                err_reply(c, 409, "too_many_channels");
                return;
            }
            ch = &mbs[mb].ch[mbs[mb].nch++];
            memcpy(ch->id, cid, 16);
        }
        ch->kind = kind;
        ch->expires_ms = kind == K_PAIR ? now_ms() + 1000LL * (ttl ? atoll(ttl + 6) : 600) : 0;
        reply(c, 204, "No Content", NULL, NULL);
        return;
    }
    if (ns == 3 && strcmp(method, "DELETE") == 0) {
        for (int i = 0; i < mbs[mb].nch; i++) {
            if (memcmp(mbs[mb].ch[i].id, cid, 16) == 0) {
                end_streams_of(mb, cid);
                mbs[mb].ch[i] = mbs[mb].ch[--mbs[mb].nch];
                reply(c, 204, "No Content", NULL, NULL);
                return;
            }
        }
        err_reply(c, 404, "not_found");
        return;
    }
    if (ns == 4 && !find_ch(mb, cid)) {
        err_reply(c, 404, "not_found");
        return;
    }
    if (ns == 4 && strcmp(method, "GET") == 0 && segn[3] == 2 && strncmp(seg[3], "up", 2) == 0) {
        start_stream(c, ST_CHAN_UP, mb, cid, header(head, "Last-Event-ID", last, sizeof last));
        return;
    }
    if (ns == 4 && strcmp(method, "POST") == 0 && segn[3] == 4 && strncmp(seg[3], "down", 4) == 0) {
        goto post_records;
    }
    err_reply(c, 404, "not_found");
    return;
post_records : {
    int dir = strncmp(seg[3], "up", 2) == 0 ? UP : DOWN, count = 0;
    char extra[32];
    if (blen > 256 * 1024) {
        err_reply(c, 413, "too_large");
        return;
    }
    for (size_t o = 0; o < blen;) {
        size_t n;
        if (blen - o < 2) {
            err_reply(c, 400, "bad_request");
            return;
        }
        n = ((size_t)(unsigned char)body[o] << 8) | (unsigned char)body[o + 1];
        if (n == 0 || n > PIC_NOISE_RECORD_CAP || blen - o - 2 < n || ++count > 32) {
            err_reply(c, n > PIC_NOISE_RECORD_CAP ? 413 : 400, n > PIC_NOISE_RECORD_CAP ? "too_large" : "bad_request");
            return;
        }
        o += 2 + n;
    }
    for (size_t o = 0; o < blen;) {
        size_t n = ((size_t)(unsigned char)body[o] << 8) | (unsigned char)body[o + 1];
        if (dir == DOWN && drop_down > 0) {
            drop_down--;
        } else {
            push_record(mb, cid, dir, (const unsigned char *)body + o + 2, n);
            if (dir == UP && dup_up > 0) {
                dup_up--;
                push_record(mb, cid, dir, (const unsigned char *)body + o + 2, n);
            }
        }
        o += 2 + n;
    }
    {
        const channel *chn = find_ch(mb, cid);
        int lane = dir == DOWN ? ST_CHAN_DOWN : chn && chn->kind == K_PAIR ? ST_CHAN_UP : ST_MAILBOX_UP;
        (void)snprintf(extra, sizeof extra, "Pic-Peer: %d\r\n", reader_of(lane, mb, cid, NULL) != NULL);
    }
    reply(c, 204, "No Content", extra, NULL);
}
}

/* A request is whole: its head, and Content-Length bytes after it. */
static void try_request(conn *c) {
    char *end, method[16], path[512], cl[32], *head;
    size_t hl, blen = 0;
    if (c->stream != ST_NONE || c->closing || !(end = memmem(c->in, c->inlen, "\r\n\r\n", 4))) {
        return;
    }
    hl = (size_t)(end - c->in) + 4;
    if (!(head = malloc(hl + 1))) {
        die("malloc");
    }
    memcpy(head, c->in, hl);
    head[hl] = '\0';
    if (header(head, "Content-Length", cl, sizeof cl)) {
        blen = strtoul(cl, NULL, 10);
    }
    if (c->inlen < hl + blen) {
        free(head);
        return;
    }
    if (sscanf(head, "%15s %511s", method, path) != 2) {
        free(head);
        err_reply(c, 400, "bad_request");
        return;
    }
    {
        char *body = malloc(blen + 1);
        if (!body) {
            die("malloc");
        }
        memcpy(body, c->in + hl, blen);
        body[blen] = '\0';
        handle(c, method, path, head, body, blen);
        if (strcmp(method, "PUT") == 0 || strcmp(method, "DELETE") == 0) {
            save_state();
        }
        free(body);
    }
    free(head);
}

static void close_conn(conn *c) {
    stream_lost(c);
    close(c->fd);
    free(c->in);
    free(c->out);
    memset(c, 0, sizeof *c);
    c->fd = -1;
}

int main(int argc, char **argv) {
    struct sockaddr_in addr;
    socklen_t alen = sizeof addr;
    int lfd, one = 1;
    long long deadline;
    FILE *pf;
    if (argc < 3) {
        fputs("usage: fake_relay PORT_FILE DEADLINE_SECONDS [INVITE]\n", stderr);
        return 2;
    }
    invite = argc > 3 ? argv[3] : NULL;
    deadline = now_ms() + 1000LL * atoll(argv[2]);
    state_file = getenv("FAKE_RELAY_STATE");
    if (getenv("FAKE_RELAY_BEAT_MS")) {
        beat_ms = atoll(getenv("FAKE_RELAY_BEAT_MS"));
    }
    first_id = next_id = (unsigned long long)now_ms() * 1000;
    load_state();
    signal(SIGPIPE, SIG_IGN);
    for (int i = 0; i < MAX_CONN; i++) {
        conns[i].fd = -1;
    }
    if ((lfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        die("socket");
    }
    (void)setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
    memset(&addr, 0, sizeof addr);
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    addr.sin_port = htons((unsigned short)(getenv("FAKE_RELAY_PORT") ? atoi(getenv("FAKE_RELAY_PORT")) : 0));
    if (bind(lfd, (struct sockaddr *)&addr, sizeof addr) != 0 || listen(lfd, 64) != 0 ||
        getsockname(lfd, (struct sockaddr *)&addr, &alen) != 0) {
        die("bind");
    }
    {
        char tmp[4096];
        (void)snprintf(tmp, sizeof tmp, "%s.tmp", argv[1]);
        if (!(pf = fopen(tmp, "w"))) {
            die(tmp);
        }
        fprintf(pf, "%d\n", ntohs(addr.sin_port));
        fclose(pf);
        if (rename(tmp, argv[1]) != 0) {
            die("rename");
        }
    }
    while (now_ms() < deadline) {
        struct pollfd p[MAX_CONN + 1];
        int idx[MAX_CONN + 1], np = 0;
        long long now = now_ms();
        p[np].fd = lfd;
        p[np].events = POLLIN;
        idx[np++] = -1;
        for (int i = 0; i < MAX_CONN; i++) {
            conn *c = &conns[i];
            if (c->fd < 0) {
                continue;
            }
            if (c->stream != ST_NONE && now >= mute_until) {
                send_held(c);
                if (now - c->beat_ms > beat_ms) {
                    out_str(c, ": beat\n\n");
                    c->beat_ms = now;
                }
            }
            if (c->closing && c->outlen == 0) {
                close_conn(c);
                continue;
            }
            p[np].fd = c->fd;
            p[np].events = (short)(POLLIN | (c->outlen ? POLLOUT : 0));
            idx[np++] = i;
        }
        expire();
        if (poll(p, (nfds_t)np, 50) < 0 && errno != EINTR) {
            die("poll");
        }
        for (int k = 0; k < np; k++) {
            if (idx[k] < 0) {
                if (p[k].revents & POLLIN) {
                    int fd = accept(lfd, NULL, NULL);
                    int slot = -1;
                    for (int i = 0; i < MAX_CONN && fd >= 0; i++) {
                        if (conns[i].fd < 0) {
                            slot = i;
                            break;
                        }
                    }
                    if (fd >= 0 && (slot < 0 || now_ms() < down_until)) {
                        close(fd); /* full, or the network is down */
                    } else if (fd >= 0) {
                        (void)fcntl(fd, F_SETFL, O_NONBLOCK);
                        memset(&conns[slot], 0, sizeof conns[slot]);
                        conns[slot].fd = fd;
                        conns[slot].mb = -1;
                    }
                }
                continue;
            }
            conn *c = &conns[idx[k]];
            if (p[k].revents & POLLOUT && c->outlen) {
                ssize_t w = write(c->fd, c->out, c->outlen);
                if (w > 0) {
                    memmove(c->out, c->out + w, c->outlen - (size_t)w);
                    c->outlen -= (size_t)w;
                } else if (w < 0 && errno != EAGAIN && errno != EINTR) {
                    close_conn(c);
                    continue;
                }
            }
            if (p[k].revents & (POLLIN | POLLHUP | POLLERR)) {
                char buf[65536];
                ssize_t r = read(c->fd, buf, sizeof buf);
                if (r > 0) {
                    if (c->inlen + (size_t)r > c->incap) {
                        size_t cap = c->incap ? c->incap : 65536;
                        while (cap < c->inlen + (size_t)r) {
                            cap *= 2;
                        }
                        if (!(c->in = realloc(c->in, cap))) {
                            die("realloc");
                        }
                        c->incap = cap;
                    }
                    memcpy(c->in + c->inlen, buf, (size_t)r);
                    c->inlen += (size_t)r;
                    try_request(c);
                } else if (r == 0 || (errno != EAGAIN && errno != EINTR)) {
                    close_conn(c);
                }
            }
        }
    }
    return 0;
}