Skip to content
pi-c Artifact [2f9e76ab9b]
Login

Artifact [2f9e76ab9b]

Artifact 2f9e76ab9b8a513009a0c90abdb0e006311cc6f7270824e0e7ae5cb3100057ed:


/* The OAuth machinery the sign-in flows share; see oauth.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 <sys/socket.h>
#include <sys/wait.h>
#include <termios.h>
#include <time.h>
#include <unistd.h>

#include "bearssl.h"
#include "http.h"
#include "net.h"
#include "oauth.h"
#include "platform.h"
#include "userdb.h"

#define OAUTH_BODY_CAP (1u << 20)
#define OAUTH_REQUEST_CAP 8192 /* a redirect's request line and headers */
#define OAUTH_PASTE_CAP 8192
#define OAUTH_CONN_SECONDS 5   /* one browser connection, start to end */
#define OAUTH_LINE_MS 1000     /* its request line */
#define OAUTH_POST_IDLE 15
#define OAUTH_POST_DEADLINE 30

static const pic_oauth_flow *const oauth_flows[] = {&pic_oauth_flow_openai, &pic_oauth_flow_openrouter};

static const pic_oauth_flow *oauth_flow_for(const char *provider) {
    for (size_t i = 0; i < sizeof oauth_flows / sizeof oauth_flows[0]; i++) {
        if (strcmp(oauth_flows[i]->provider, provider) == 0) {
            return oauth_flows[i];
        }
    }
    return NULL;
}

const char *pic_oauth_seam(const char *env, const char *fallback) {
#ifdef PIC_FAULTS
    const char *v = getenv(env);
    if (v && *v) {
        return v;
    }
#else
    (void)env;
#endif
    return fallback;
}

/* ---- the ops the credential store calls ------------------------------------ */

static const char *oauth_label(const char *provider) {
    const pic_oauth_flow *f = oauth_flow_for(provider);
    return f ? f->label : NULL;
}

static int oauth_login(const char *provider, int flags, const char **kind, char **secret, char *err, size_t errcap) {
    const pic_oauth_flow *f = oauth_flow_for(provider);
    pic_oauth_io io = {flags & PIC_CRED_NO_TERMINAL ? stderr : stdout, flags & PIC_CRED_NO_TERMINAL ? -1 : STDIN_FILENO, flags,
                       (flags & PIC_CRED_PIPE) != 0};
    int rc;
    if (!f) {
        (void)snprintf(err, errcap, "%s has no subscription sign-in", provider);
        return -1;
    }
    rc = f->login(&io, kind, secret, err, errcap);
    (void)fflush(io.out);
    return rc;
}

static int oauth_refresh(const char *provider, const char *cred, char **out, char *err, size_t errcap) {
    const pic_oauth_flow *f = oauth_flow_for(provider);
    if (!f) {
        (void)snprintf(err, errcap, "%s has no subscription sign-in", provider);
        return -1;
    }
    return f->refresh(cred, out, err, errcap);
}

static const char *oauth_origin(const char *provider) {
    const pic_oauth_flow *f = oauth_flow_for(provider);
    return f && f->origin ? f->origin() : NULL;
}

static const pic_cred_oauth_ops oauth_ops_table = {oauth_label, oauth_login, oauth_refresh, oauth_origin};

const pic_cred_oauth_ops *pic_oauth_ops(void) { return &oauth_ops_table; }

/* ---- encoding ---------------------------------------------------------------- */

static void b64url(const unsigned char *in, size_t n, char *out) {
    static const char a[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
    size_t o = 0;
    for (size_t i = 0; i < n; i += 3) {
        unsigned v = (unsigned)in[i] << 16 | (i + 1 < n ? (unsigned)in[i + 1] << 8 : 0) | (i + 2 < n ? in[i + 2] : 0);
        out[o++] = a[v >> 18 & 63];
        out[o++] = a[v >> 12 & 63];
        if (i + 1 < n) {
            out[o++] = a[v >> 6 & 63];
        }
        if (i + 2 < n) {
            out[o++] = a[v & 63];
        }
    }
    out[o] = '\0';
}

int pic_oauth_random(char *out, size_t cap, size_t bytes) {
    unsigned char b[96];
    if (bytes > sizeof b || cap < (bytes * 4 + 2) / 3 + 1 || pic_platform_get()->entropy(b, bytes) != 0) {
        return -1;
    }
    b64url(b, bytes, out);
    pic_cred_wipe(b, sizeof b);
    return 0;
}

int pic_oauth_pkce(char verifier[64], char challenge[64]) {
    br_sha256_context h;
    unsigned char d[32];
    if (pic_oauth_random(verifier, 64, 32) != 0) {
        return -1;
    }
    br_sha256_init(&h);
    br_sha256_update(&h, verifier, strlen(verifier));
    br_sha256_out(&h, d);
    b64url(d, sizeof d, challenge);
    return 0;
}

int pic_oauth_same(const char *a, const char *b) {
    size_t na = strlen(a), nb = strlen(b);
    unsigned char diff = (unsigned char)(na != nb);
    for (size_t i = 0; i < na; i++) {
        diff |= (unsigned char)(a[i] ^ b[nb ? i % nb : 0]);
    }
    return diff == 0;
}

static int hexval(int c) {
    return c >= '0' && c <= '9' ? c - '0' : c >= 'a' && c <= 'f' ? c - 'a' + 10 : c >= 'A' && c <= 'F' ? c - 'A' + 10 : -1;
}

char *pic_oauth_param(const char *query, const char *name) {
    size_t nn = strlen(name);
    for (const char *p = query; p && *p;) {
        const char *amp = strchr(p, '&'), *end = amp ? amp : p + strlen(p);
        if ((size_t)(end - p) > nn && strncmp(p, name, nn) == 0 && p[nn] == '=') {
            const char *v = p + nn + 1;
            char *out = malloc((size_t)(end - v) + 1), *o = out;
            if (!out) {
                return NULL;
            }
            while (v < end) {
                if (*v == '%' && end - v >= 3 && hexval(v[1]) >= 0 && hexval(v[2]) >= 0) {
                    *o++ = (char)(hexval(v[1]) * 16 + hexval(v[2]));
                    v += 3;
                } else {
                    *o++ = *v == '+' ? ' ' : *v;
                    v++;
                }
            }
            *o = '\0';
            return out;
        }
        p = amp ? amp + 1 : NULL;
    }
    return NULL;
}

char *pic_oauth_form(const char *const *pairs) {
    size_t cap = 1, o = 0;
    char *out;
    for (size_t i = 0; pairs[i]; i += 2) {
        cap += strlen(pairs[i]) + 2 + (pairs[i + 1] ? 3 * strlen(pairs[i + 1]) : 0);
    }
    if (!(out = malloc(cap))) {
        return NULL;
    }
    for (size_t i = 0; pairs[i]; i += 2) {
        if (!pairs[i + 1]) {
            continue;
        }
        o += (size_t)snprintf(out + o, cap - o, "%s%s=", o ? "&" : "", pairs[i]);
        for (const unsigned char *v = (const unsigned char *)pairs[i + 1]; *v; v++) {
            if ((*v >= 'A' && *v <= 'Z') || (*v >= 'a' && *v <= 'z') || (*v >= '0' && *v <= '9') || *v == '-' || *v == '_' ||
                *v == '.' || *v == '~') {
                out[o++] = (char)*v;
            } else {
                o += (size_t)snprintf(out + o, cap - o, "%%%02X", *v);
            }
        }
    }
    out[o] = '\0';
    return out;
}

/* Text from the network, made safe to print: control bytes (a terminal's
 * escape sequences among them) become '?'. */
static void oauth_clean(char *s) {
    for (; s && *s; s++) {
        if ((unsigned char)*s < 0x20 || *s == 0x7f) {
            *s = '?';
        }
    }
}

/* ---- JSON, through SQLite's functions ---------------------------------------- */

char *pic_oauth_json_text(const char *json, const char *path) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    if (db && json && sqlite3_prepare_v2(db, "SELECT json_extract(?1, ?2) WHERE json_valid(?1) AND json_type(?1, ?2) = 'text'",
                                         -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, json, -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 2, path, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW && (out = malloc((size_t)sqlite3_column_bytes(q, 0) + 1))) {
            memcpy(out, sqlite3_column_text(q, 0), (size_t)sqlite3_column_bytes(q, 0) + 1);
        }
    }
    sqlite3_finalize(q);
    return out;
}

double pic_oauth_json_number(const char *json, const char *path) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    double v = -1;
    if (db && json && sqlite3_prepare_v2(db, "SELECT CASE WHEN json_valid(?1) AND json_type(?1, ?2) IN ('integer', 'real')"
                                             " THEN json_extract(?1, ?2) WHEN json_valid(?1) AND json_type(?1, ?2) = 'text'"
                                             " THEN CAST(trim(json_extract(?1, ?2)) AS REAL) END",
                                         -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, json, -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 2, path, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_type(q, 0) != SQLITE_NULL && sqlite3_column_double(q, 0) > 0) {
            v = sqlite3_column_double(q, 0);
        }
    }
    sqlite3_finalize(q);
    return v;
}

void pic_oauth_error(int status, const char *body, char *err, size_t errcap) {
    char *code = pic_oauth_json_text(body, "$.error"), *desc = pic_oauth_json_text(body, "$.error_description");
    if (!code) {
        code = pic_oauth_json_text(body, "$.error.code");
    }
    if (!desc) {
        desc = pic_oauth_json_text(body, "$.error.message");
    }
    (void)snprintf(err, errcap, "HTTP %d%s%.80s%s%.200s", status, code ? ": " : "", code ? code : "", desc ? ": " : "",
                   desc ? desc : "");
    oauth_clean(err);
    free(code);
    free(desc);
}

/* ---- token requests ---------------------------------------------------------- */

typedef struct {
    char *buf;
    size_t len, cap;
} oauth_body;

static int oauth_on_body(void *ctx, const char *bytes, size_t n) {
    oauth_body *b = ctx;
    if (b->len + n + 1 > b->cap) {
        size_t cap = b->cap ? b->cap : 4096;
        char *grown;
        while (cap < b->len + n + 1) {
            cap *= 2;
        }
        if (cap > OAUTH_BODY_CAP || !(grown = realloc(b->buf, cap))) {
            return -1;
        }
        b->buf = grown;
        b->cap = cap;
    }
    memcpy(b->buf + b->len, bytes, n);
    b->len += n;
    b->buf[b->len] = '\0';
    return 0;
}

int pic_oauth_post(const char *url, const char *form, int json, int *status, char **body, char *err, size_t errcap) {
    const char *headers[] = {json ? "Content-Type: application/json" : "Content-Type: application/x-www-form-urlencoded",
                             "Accept: application/json"};
    pic_net *net = pic_net_new(err, errcap);
    pic_http_resp r;
    oauth_body b = {NULL, 0, 0};
    int rc;
    *body = NULL;
    if (!net) {
        return -1;
    }
    pic_http_resp_init(&r, oauth_on_body, &b);
    rc = pic_http_post(net, url, headers, 2, form, strlen(form), &r, OAUTH_POST_IDLE, OAUTH_POST_DEADLINE, err, errcap);
    pic_net_free(net);
    if (rc != 0) {
        if (b.buf) {
            pic_cred_wipe(b.buf, b.cap);
        }
        free(b.buf);
        return -1;
    }
    *status = r.status;
    *body = b.buf ? b.buf : calloc(1, 1);
    return *body ? 0 : -1;
}

/* ---- the browser --------------------------------------------------------------- */

static int oauth_web_url(const char *url) { return strncmp(url, "https://", 8) == 0 || strncmp(url, "http://", 7) == 0; }

/* The system's opener (platform.h), detached: only for a web address. */
static void oauth_open_browser(const char *url) {
    if (oauth_web_url(url)) {
        (void)pic_host_open(url);
    }
}

/* S as a JSON string, to F. */
static void oauth_json_string(FILE *f, const char *s) {
    fputc('"', f);
    for (; *s; s++) {
        if (*s == '"' || *s == '\\') {
            fprintf(f, "\\%c", *s);
        } else if ((unsigned char)*s < 0x20) {
            fprintf(f, "\\u%04x", (unsigned char)*s);
        } else {
            fputc(*s, f);
        }
    }
    fputc('"', f);
}

/* {"type":TYPE,K1:V1[,K2:V2]} on its own line. */
static void oauth_json_line(FILE *f, const char *type, const char *k1, const char *v1, const char *k2, const char *v2) {
    fprintf(f, "{\"type\":\"%s\",\"%s\":", type, k1);
    oauth_json_string(f, v1);
    if (k2 && v2) {
        fprintf(f, ",\"%s\":", k2);
        oauth_json_string(f, v2);
    }
    fputs("}\n", f);
    (void)fflush(f);
}

void pic_oauth_say(const pic_oauth_io *io, const char *message) {
    if (io->json) {
        oauth_json_line(io->out, "progress", "message", message, NULL, NULL);
    } else {
        fprintf(io->out, "%s\n", message);
        (void)fflush(io->out);
    }
}

void pic_oauth_show_url(const pic_oauth_io *io, const char *url, const char *instructions) {
    if (io->json) {
        oauth_json_line(io->out, "auth_url", "url", url, "instructions", instructions);
    } else {
        fprintf(io->out, "Open this URL to sign in:\n  %s\n", url);
        if (instructions) {
            fprintf(io->out, "%s\n", instructions);
        }
        (void)fflush(io->out);
    }
    if (!(io->flags & PIC_CRED_NO_BROWSER)) {
        oauth_open_browser(url);
    }
}

/* ---- the loopback redirect ------------------------------------------------------- */

int pic_oauth_listen(pic_oauth_callback *c, int port, const char *path, const char *state, char *err, size_t errcap) {
    struct sockaddr_in a;
    socklen_t len = sizeof a;
    int one = 1;
    memset(c, 0, sizeof *c);
    c->fd = socket(AF_INET, SOCK_STREAM, 0);
    if (c->fd < 0) {
        (void)snprintf(err, errcap, "cannot open a socket: %s", strerror(errno));
        return -1;
    }
    (void)fcntl(c->fd, F_SETFD, FD_CLOEXEC);
    (void)setsockopt(c->fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
    memset(&a, 0, sizeof a);
    a.sin_family = AF_INET;
    a.sin_addr.s_addr = htonl(INADDR_LOOPBACK); /* never another interface */
    a.sin_port = htons((unsigned short)port);
    if (bind(c->fd, (struct sockaddr *)&a, sizeof a) != 0 || listen(c->fd, 4) != 0 ||
        getsockname(c->fd, (struct sockaddr *)&a, &len) != 0) {
        int e = errno;
        (void)snprintf(err, errcap, "cannot listen on 127.0.0.1:%d for the sign-in's redirect: %s", port, strerror(e));
        close(c->fd);
        c->fd = -1;
        return e == EADDRINUSE ? -2 : -1;
    }
    c->port = ntohs(a.sin_port);
    (void)snprintf(c->path, sizeof c->path, "%s", path);
    c->state = state;
    return 0;
}

void pic_oauth_close(pic_oauth_callback *c) {
    if (c && c->fd >= 0) {
        close(c->fd);
        c->fd = -1;
    }
}

static void oauth_reply(int fd, int status, const char *message) {
    char page[1024];
    int n = snprintf(page, sizeof page,
                     "HTTP/1.1 %d %s\r\nContent-Type: text/html; charset=utf-8\r\nCache-Control: no-store\r\n"
                     "Connection: close\r\nContent-Length: %zu\r\n\r\n<!doctype html><title>pic</title><p>%s</p>",
                     status, status == 200 ? "OK" : status == 404 ? "Not Found" : "Bad Request",
                     strlen("<!doctype html><title>pic</title><p></p>") + strlen(message), message);
    if (n > 0 && (size_t)n < sizeof page) {
        ssize_t w = send(fd, page, (size_t)n, 0);
        (void)w;
    }
}

/* Reads one request's head from FD (at most OAUTH_REQUEST_CAP bytes): its
 * request line within OAUTH_LINE_MS (a connection opened and left idle, as
 * browsers and stray local programs do, is dropped fast, since connections
 * are served one at a time), the rest within OAUTH_CONN_SECONDS. 0 with the
 * target in target, or -1. */
static int oauth_read_request(int fd, char *target, size_t cap) {
    char buf[OAUTH_REQUEST_CAP + 1];
    size_t len = 0;
    uint64_t start = pic_platform_get()->mono_ns(), end;
    char *sp, *sp2;
    while (len < OAUTH_REQUEST_CAP && !memmem(buf, len, "\r\n\r\n", 4) && !memmem(buf, len, "\n\n", 2)) {
        struct pollfd p = {fd, POLLIN, 0};
        uint64_t now = pic_platform_get()->mono_ns();
        ssize_t r;
        end = start + (memchr(buf, '\n', len) ? (uint64_t)OAUTH_CONN_SECONDS * 1000000000u : (uint64_t)OAUTH_LINE_MS * 1000000u);
        if (now >= end || poll(&p, 1, (int)((end - now) / 1000000u) + 1) <= 0) {
            return -1;
        }
        r = recv(fd, buf + len, OAUTH_REQUEST_CAP - len, 0);
        if (r <= 0) {
            if (r < 0 && errno == EINTR) {
                continue;
            }
            return -1;
        }
        len += (size_t)r;
    }
    buf[len] = '\0';
    if (strncmp(buf, "GET ", 4) != 0 || !(sp = strchr(buf + 4, ' ')) || (size_t)(sp - buf - 4) >= cap ||
        !(sp2 = strchr(buf, '\n')) || sp2 < sp) {
        return -1;
    }
    memcpy(target, buf + 4, (size_t)(sp - buf - 4));
    target[sp - buf - 4] = '\0';
    return 0;
}

/* One browser connection to C. 1 with *query when it carried the redirect;
 * 0 when it was answered and the wait goes on; -1 with err when the provider
 * redirected with an error. */
static int oauth_serve(pic_oauth_callback *c, char **query, char *err, size_t errcap) {
    char target[OAUTH_REQUEST_CAP], *q, *state, *code, *error;
    size_t plen = strlen(c->path);
    int fd = accept(c->fd, NULL, NULL), rc = 0;
    if (fd < 0) {
        return 0;
    }
    (void)fcntl(fd, F_SETFD, FD_CLOEXEC);
    if (oauth_read_request(fd, target, sizeof target) != 0) {
        oauth_reply(fd, 400, "Bad request.");
        close(fd);
        return 0;
    }
    if (strncmp(target, c->path, plen) != 0 || (target[plen] != '?' && target[plen] != '\0')) {
        oauth_reply(fd, 404, "Callback route not found.");
        close(fd);
        return 0;
    }
    q = target[plen] == '?' ? target + plen + 1 : target + plen;
    state = pic_oauth_param(q, "state");
    code = pic_oauth_param(q, "code");
    error = pic_oauth_param(q, "error");
    if (c->state && (!state || !pic_oauth_same(state, c->state))) {
        oauth_reply(fd, 400, "State mismatch: this page is not from the sign-in pic started.");
    } else if (error) {
        char *desc = pic_oauth_param(q, "error_description");
        oauth_reply(fd, 400, "Sign-in failed. You can close this page.");
        (void)snprintf(err, errcap, "authorization failed: %.80s%s%.200s", error, desc ? ": " : "", desc ? desc : "");
        oauth_clean(err);
        free(desc);
        rc = -1;
    } else if (!code) {
        oauth_reply(fd, 400, "Missing authorization code.");
    } else if (!(*query = malloc(strlen(q) + 1))) {
        oauth_reply(fd, 400, "Out of memory.");
        (void)snprintf(err, errcap, "out of memory");
        rc = -1;
    } else {
        memcpy(*query, q, strlen(q) + 1);
        oauth_reply(fd, 200, "Signed in to pic. You can close this page and return to the terminal.");
        rc = 1;
    }
    if (code) {
        pic_cred_wipe(code, strlen(code));
    }
    free(code);
    free(state);
    free(error);
    pic_cred_wipe(target, sizeof target);
    close(fd);
    return rc;
}

/* While a sign-in waits for a paste on a terminal, echo is off (the address
 * carries the authorization code, which should not stay in scrollback);
 * SIGINT, SIGTERM and SIGHUP put the terminal back before they act. */
static struct termios oauth_tty_old;
static volatile sig_atomic_t oauth_tty_fd = -1;
static const int oauth_tty_sigs[3] = {SIGINT, SIGTERM, SIGHUP};
static struct sigaction oauth_tty_saved[3];

static void oauth_tty_restore(void) {
    if (oauth_tty_fd >= 0) {
        (void)tcsetattr(oauth_tty_fd, TCSANOW, &oauth_tty_old);
        oauth_tty_fd = -1;
        for (int i = 0; i < 3; i++) {
            (void)sigaction(oauth_tty_sigs[i], &oauth_tty_saved[i], NULL);
        }
    }
}

static void oauth_tty_signal(int sig) {
    oauth_tty_restore();
    (void)raise(sig); /* the handler that was there before, now restored */
}

static void oauth_tty_quiet(int fd) {
    struct termios t;
    struct sigaction sa;
    if (fd < 0 || !isatty(fd) || tcgetattr(fd, &oauth_tty_old) != 0) {
        return;
    }
    memset(&sa, 0, sizeof sa);
    sa.sa_handler = oauth_tty_signal;
    sigemptyset(&sa.sa_mask);
    for (int i = 0; i < 3; i++) {
        (void)sigaction(oauth_tty_sigs[i], &sa, &oauth_tty_saved[i]);
    }
    t = oauth_tty_old;
    t.c_lflag &= ~(tcflag_t)(ECHO | ECHONL);
    oauth_tty_fd = fd;
    if (tcsetattr(fd, TCSANOW, &t) != 0) {
        oauth_tty_restore();
    }
}

static int oauth_wait(pic_oauth_callback *c, const pic_oauth_io *io, int timeout, char **query, char **pasted, char *err,
                      size_t errcap);

int pic_oauth_wait(pic_oauth_callback *c, const pic_oauth_io *io, int timeout, char **query, char **pasted, char *err,
                   size_t errcap) {
    int rc;
    oauth_tty_quiet(io ? io->in : -1);
    rc = oauth_wait(c, io, timeout, query, pasted, err, errcap);
    if (oauth_tty_fd >= 0) {
        oauth_tty_restore();
        if (*pasted && io->out) {
            fprintf(io->out, "Pasted address received.\n");
            (void)fflush(io->out);
        }
    }
    return rc;
}

static int oauth_wait(pic_oauth_callback *c, const pic_oauth_io *io, int timeout, char **query, char **pasted, char *err,
                      size_t errcap) {
    uint64_t end = pic_platform_get()->mono_ns() + (uint64_t)timeout * 1000000000u;
    char line[OAUTH_PASTE_CAP];
    size_t len = 0;
    int in_open = io && io->in >= 0;
    *query = *pasted = NULL;
    for (;;) {
        struct pollfd p[2];
        int n = 0, cfd = -1, ifd = -1, r;
        uint64_t now = pic_platform_get()->mono_ns();
        if (pic_interrupted) {
            (void)snprintf(err, errcap, "sign-in cancelled");
            return -1;
        }
        if (now >= end) {
            (void)snprintf(err, errcap, "the sign-in timed out");
            return -1;
        }
        if (c && c->fd >= 0) {
            p[n].fd = c->fd;
            p[n].events = POLLIN;
            cfd = n++;
        }
        if (in_open) {
            p[n].fd = io->in;
            p[n].events = POLLIN;
            ifd = n++;
        }
        if (n == 0) {
            (void)snprintf(err, errcap, "nothing to wait for: no redirect and no terminal");
            return -1;
        }
        r = poll(p, (nfds_t)n, (int)((end - now) / 1000000u > 500 ? 500 : (end - now) / 1000000u + 1));
        if (r < 0 && errno != EINTR) {
            (void)snprintf(err, errcap, "poll: %s", strerror(errno));
            return -1;
        }
        if (r <= 0) {
            continue;
        }
        if (cfd >= 0 && (p[cfd].revents & POLLIN)) {
            int got = oauth_serve(c, query, err, errcap);
            if (got != 0) {
                pic_cred_wipe(line, sizeof line);
                return got > 0 ? 0 : -1;
            }
        }
        if (ifd >= 0 && (p[ifd].revents & (POLLIN | POLLHUP))) {
            char ch;
            ssize_t k = read(io->in, &ch, 1);
            if (k <= 0) {
                in_open = 0; /* the terminal went away: the redirect alone */
                continue;
            }
            if (ch == '\n' || ch == '\r') {
                while (len > 0 && (line[len - 1] == ' ' || line[len - 1] == '\t')) {
                    len--;
                }
                if (len == 0) {
                    continue;
                }
                line[len] = '\0';
                *pasted = malloc(len + 1);
                if (*pasted) {
                    memcpy(*pasted, line, len + 1);
                }
                pic_cred_wipe(line, sizeof line);
                if (!*pasted) {
                    (void)snprintf(err, errcap, "out of memory");
                    return -1;
                }
                return 0;
            }
            if (len + 1 < sizeof line && !(len == 0 && (ch == ' ' || ch == '\t'))) {
                line[len++] = ch;
            }
        }
    }
}

int pic_oauth_pasted_query(const char *pasted, const char *redirect, const char *state, char **query, char *err,
                           size_t errcap) {
    size_t n = strlen(redirect);
    const char *q;
    char *got_state, *error;
    *query = NULL;
    if (strncmp(pasted, redirect, n) != 0 || (pasted[n] != '?' && pasted[n] != '\0')) {
        (void)snprintf(err, errcap, "paste the whole address the browser was sent to; it starts with %s", redirect);
        return -1;
    }
    q = pasted[n] == '?' ? pasted + n + 1 : pasted + n;
    if ((error = pic_oauth_param(q, "error")) != NULL) {
        (void)snprintf(err, errcap, "authorization failed: %.80s", error);
        oauth_clean(err);
        free(error);
        return -1;
    }
    got_state = pic_oauth_param(q, "state");
    if (!got_state || !pic_oauth_same(got_state, state)) {
        free(got_state);
        (void)snprintf(err, errcap, "state mismatch: that address is not from the sign-in pic started");
        return -1;
    }
    free(got_state);
    if (!(*query = malloc(strlen(q) + 1))) {
        (void)snprintf(err, errcap, "out of memory");
        return -1;
    }
    memcpy(*query, q, strlen(q) + 1);
    return 0;
}

/* ---- the device authorization grant (RFC 8628) ---------------------------------- */

#define DEVICE_DEFAULT_INTERVAL 5 /* RFC 8628 3.2 */
#define DEVICE_SLOW_DOWN 5        /* RFC 8628 3.5 */
#define DEVICE_DEFAULT_LIFETIME 900

static void oauth_sleep(double seconds) {
    uint64_t end = pic_platform_get()->mono_ns() + (uint64_t)(seconds * 1e9);
    for (uint64_t now; !pic_interrupted && (now = pic_platform_get()->mono_ns()) < end;) {
        uint64_t left = end - now > 100000000u ? 100000000u : end - now;
        struct timespec ts = {0, (long)left};
        (void)nanosleep(&ts, NULL);
    }
}

int pic_oauth_device(const pic_oauth_io *io, const char *device_url, const char *token_url, const char *form,
                     const char *client_id, char **token, char *err, size_t errcap) {
    char *body = NULL, *device = NULL, *user = NULL, *uri = NULL, *poll_form = NULL;
    int status = 0, rc = -1;
    double interval, lifetime;
    uint64_t end;
    *token = NULL;
    if (pic_oauth_post(device_url, form, 0, &status, &body, err, errcap) != 0) {
        return -1;
    }
    if (status != 200) {
        pic_oauth_error(status, body, err, errcap);
        goto out;
    }
    device = pic_oauth_json_text(body, "$.device_code");
    user = pic_oauth_json_text(body, "$.user_code");
    uri = pic_oauth_json_text(body, "$.verification_uri_complete");
    if (!uri) {
        uri = pic_oauth_json_text(body, "$.verification_uri");
    }
    interval = pic_oauth_json_number(body, "$.interval");
    lifetime = pic_oauth_json_number(body, "$.expires_in");
    interval = interval > 0 ? interval : DEVICE_DEFAULT_INTERVAL;
    lifetime = lifetime > 0 ? lifetime : DEVICE_DEFAULT_LIFETIME;
    if (!device || !user || !uri || !oauth_web_url(uri)) {
        (void)snprintf(err, errcap, "the device authorization response lacks a code or an http(s) address");
        goto out;
    }
    oauth_clean(uri);
    oauth_clean(user);
    if (io->json) {
        oauth_json_line(io->out, "device_code", "uri", uri, "code", user);
    } else {
        fprintf(io->out, "Open %s and enter the code: %s\nWaiting for the sign-in...\n", uri, user);
        (void)fflush(io->out);
    }
    if (!(io->flags & PIC_CRED_NO_BROWSER)) {
        oauth_open_browser(uri);
    }
    {
        const char *pairs[] = {"grant_type", "urn:ietf:params:oauth:grant-type:device_code", "device_code", device,
                               "client_id", client_id, NULL};
        poll_form = pic_oauth_form(pairs);
    }
    if (!poll_form) {
        (void)snprintf(err, errcap, "out of memory");
        goto out;
    }
    end = pic_platform_get()->mono_ns() + (uint64_t)(lifetime * 1e9);
    while (pic_platform_get()->mono_ns() < end) {
        char *reply = NULL, *code;
        oauth_sleep(interval);
        if (pic_interrupted) {
            (void)snprintf(err, errcap, "sign-in cancelled");
            goto out;
        }
        if (pic_oauth_post(token_url, poll_form, 0, &status, &reply, err, errcap) != 0) {
            goto out;
        }
        code = status == 200 ? pic_oauth_json_text(reply, "$.access_token") : NULL;
        if (code) {
            pic_cred_wipe(code, strlen(code));
            free(code);
            *token = reply;
            rc = 0;
            goto out;
        }
        code = pic_oauth_json_text(reply, "$.error");
        if (code && strcmp(code, "slow_down") == 0) {
            double asked = pic_oauth_json_number(reply, "$.interval");
            interval = asked > 0 ? asked : interval + DEVICE_SLOW_DOWN;
        } else if (!code || strcmp(code, "authorization_pending") != 0) {
            if (code && strcmp(code, "access_denied") == 0) {
                (void)snprintf(err, errcap, "the sign-in was denied");
            } else if (code && strcmp(code, "expired_token") == 0) {
                (void)snprintf(err, errcap, "the device code expired: sign in again");
            } else {
                pic_oauth_error(status, reply, err, errcap);
            }
            free(code);
            pic_cred_wipe(reply, strlen(reply));
            free(reply);
            goto out;
        }
        free(code);
        pic_cred_wipe(reply, strlen(reply));
        free(reply);
    }
    (void)snprintf(err, errcap, "the device code expired: sign in again");
out:
    if (poll_form) {
        pic_cred_wipe(poll_form, strlen(poll_form));
    }
    free(poll_form);
    free(device);
    free(user);
    free(uri);
    free(body);
    return rc;
}