#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "http.h"
#include "noise.h"
#include "platform.h"
#include "webpush.h"
#define WEBPUSH_CLAIM_MAX 512
static void webpush_wipe(void *p, size_t n) {
volatile unsigned char *v = p;
while (n--) {
*v++ = 0;
}
}
static const char webpush_alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
/* Splits an http or https URL: 0 with its parts (HOST lowercased), or -1. *EXPLICIT is 1 when a
* port was written. */
static int webpush_url(const char *url, int *tls, char *host, size_t hostcap, int *port, int *explicit_port) {
const char *p, *end;
size_t n;
if (strncmp(url, "https://", 8) == 0) {
*tls = 1;
p = url + 8;
} else if (strncmp(url, "http://", 7) == 0) {
*tls = 0;
p = url + 7;
} else {
return -1;
}
end = p + strcspn(p, "/?#");
if (memchr(p, '@', (size_t)(end - p))) {
return -1;
}
*port = *tls ? 443 : 80;
*explicit_port = 0;
{
const char *colon = NULL;
const char *hend = end;
if (*p == '[') {
const char *rb = memchr(p, ']', (size_t)(end - p));
if (!rb) {
return -1;
}
hend = rb + 1;
if (hend < end && *hend == ':') {
colon = hend;
} else if (hend != end) {
return -1;
}
} else {
colon = memchr(p, ':', (size_t)(end - p));
if (colon) {
hend = colon;
}
}
if (colon) {
long v = 0;
const char *d = colon + 1;
if (d == end || end - d > 5) {
return -1;
}
for (; d < end; d++) {
if (*d < '0' || *d > '9') {
return -1;
}
v = v * 10 + (*d - '0');
}
if (v < 1 || v > 65535) {
return -1;
}
*port = (int)v;
*explicit_port = 1;
}
n = (size_t)(hend - p);
}
if (n == 0 || n >= hostcap) {
return -1;
}
for (size_t i = 0; i < n; i++) {
char c = p[i];
host[i] = c >= 'A' && c <= 'Z' ? (char)(c - 'A' + 'a') : c;
}
host[n] = '\0';
return 0;
}
int pic_webpush_origin(const char *url, char *out, size_t cap) {
char host[256];
int tls, port, explicit_port, n;
if (webpush_url(url, &tls, host, sizeof host, &port, &explicit_port) != 0) {
return -1;
}
n = port == (tls ? 443 : 80) ? snprintf(out, cap, "%s://%s", tls ? "https" : "http", host)
: snprintf(out, cap, "%s://%s:%d", tls ? "https" : "http", host, port);
return n < 0 || (size_t)n >= cap ? -1 : n;
}
int pic_webpush_endpoint_ok(const char *endpoint) {
char host[256];
int tls, port, explicit_port, digits_only = 1;
size_t label = 0;
for (const char *c = endpoint; *c; c++) {
if ((unsigned char)*c <= 0x20 || (unsigned char)*c >= 0x7f) {
return 0;
}
}
if (webpush_url(endpoint, &tls, host, sizeof host, &port, &explicit_port) != 0 || !tls || port != 443) {
return 0;
}
/* A host name: dot-separated labels of letters, digits and hyphens, the last not all digits
* (which leaves out IPv4 addresses; IPv6 ones fail at their bracket). */
for (const char *c = host;; c++) {
if (*c == '.' || *c == '\0') {
if (label == 0 || label > 63) {
return 0;
}
if (*c == '\0') {
break;
}
label = 0;
digits_only = 1;
continue;
}
if (!((*c >= 'a' && *c <= 'z') || (*c >= '0' && *c <= '9') || *c == '-')) {
return 0;
}
digits_only = digits_only && *c >= '0' && *c <= '9';
label++;
}
return !digits_only;
}
static int webpush_claim_ok(const char *s) {
size_t n = strlen(s);
if (n == 0 || n > WEBPUSH_CLAIM_MAX) {
return 0;
}
for (size_t i = 0; i < n; i++) {
unsigned char c = (unsigned char)s[i];
if (c < 0x20 || c == 0x7f || c == '"' || c == '\\') {
return 0;
}
}
return 1;
}
int pic_webpush_authorization(const unsigned char priv[PIC_WEBPUSH_PRIV], const char *aud, int64_t exp,
const char *subject, char *out, size_t cap) {
static const char header[] = "{\"typ\":\"JWT\",\"alg\":\"ES256\"}";
char claims[2 * WEBPUSH_CLAIM_MAX + 64];
char *token;
unsigned char sig[64];
pic_noise_keypair k;
size_t tn, need;
int cn, rc = -1;
if (!webpush_claim_ok(aud) || !webpush_claim_ok(subject)) {
return -1;
}
cn = snprintf(claims, sizeof claims, "{\"aud\":\"%s\",\"exp\":%lld,\"sub\":\"%s\"}", aud, (long long)exp, subject);
if (cn < 0 || (size_t)cn >= sizeof claims) {
return -1;
}
/* "vapid t=" header "." claims "." sig ", k=" pub */
need = 8 + 4 * ((sizeof header - 1 + 2) / 3) + 1 + 4 * (((size_t)cn + 2) / 3) + 1 + 86 + 4 + 87 + 1;
token = malloc(need);
if (!token) {
return -1;
}
memcpy(token, "vapid t=", 8);
tn = 8;
tn += pic_b64u_enc((const unsigned char *)header, sizeof header - 1, token + tn);
token[tn++] = '.';
tn += pic_b64u_enc((const unsigned char *)claims, (size_t)cn, token + tn);
/* The signature refuses a scalar that is zero or not below the order, so the key pair after
* it is a valid one. */
if (pic_noise_es256(priv, token + 8, sig) == 0 && pic_noise_keypair_make(&k, priv) == 0) {
token[tn++] = '.';
tn += pic_b64u_enc(sig, sizeof sig, token + tn);
memcpy(token + tn, ", k=", 4);
tn += 4;
tn += pic_b64u_enc(k.pub, sizeof k.pub, token + tn);
if (tn < cap) {
memcpy(out, token, tn + 1);
rc = (int)tn;
}
webpush_wipe(&k, sizeof k);
}
free(token);
return rc;
}
void pic_webpush_topic(const unsigned char auth[PIC_WEBPUSH_AUTH], const char *session, char out[PIC_WEBPUSH_TOPIC]) {
unsigned char mac[32];
pic_noise_hmac(mac, auth, PIC_WEBPUSH_AUTH, "pic-rc/1 topic", 15, session, strlen(session));
(void)pic_b64u_enc(mac, 16, out);
webpush_wipe(mac, sizeof mac);
}
static int webpush_topic_ok(const char *topic) {
size_t n = strlen(topic);
if (n == 0 || n > 32) {
return 0;
}
for (size_t i = 0; i < n; i++) {
if (!strchr(webpush_alphabet, topic[i])) {
return 0;
}
}
return 1;
}
/* Seconds from a Retry-After that is a number of them, else -1 (an HTTP date is not read). */
static long webpush_retry_after(const char *v) {
long s = 0;
size_t n = strlen(v);
if (n == 0 || n > 9) {
return -1;
}
for (size_t i = 0; i < n; i++) {
if (v[i] < '0' || v[i] > '9') {
return -1;
}
s = s * 10 + (v[i] - '0');
}
return s;
}
static int webpush_done(pic_webpush_result *res, pic_webpush_outcome outcome, int status, const char *err) {
res->outcome = outcome;
res->status = status;
if (err) {
(void)snprintf(res->err, sizeof res->err, "%s", err);
}
return outcome == PIC_WEBPUSH_SENT ? 0 : -1;
}
int pic_webpush_send(pic_net *net, const pic_webpush_sub *sub, const pic_webpush_vapid *vapid, const char *topic,
const void *payload, size_t len, int ttl, pic_webpush_result *res) {
const pic_platform *plat = pic_platform_get();
char aud[300], auth_h[16 + 2400], ttl_h[32], topic_h[48], err[160];
const char *headers[6];
size_t nh = 0, body_n;
unsigned char salt[16], *body;
pic_noise_keypair as;
pic_http_resp r;
int64_t now_ns;
int rc;
memset(res, 0, sizeof *res);
res->retry_after = -1;
if (len > PIC_WEBPUSH_MAX) {
return webpush_done(res, PIC_WEBPUSH_TOO_LARGE, 0, "the payload is too large for one push");
}
if (topic && !webpush_topic_ok(topic)) {
return webpush_done(res, PIC_WEBPUSH_FAILED, 0, "the topic is not 1 to 32 base64url characters");
}
if (pic_webpush_origin(sub->endpoint, aud, sizeof aud) < 0) {
return webpush_done(res, PIC_WEBPUSH_FAILED, 0, "the endpoint is not an http or https address");
}
if ((now_ns = plat->wall_ns()) < 0) {
return webpush_done(res, PIC_WEBPUSH_FAILED, 0, "the date is unknown");
}
memcpy(auth_h, "Authorization: ", 15);
if (pic_webpush_authorization(vapid->priv, aud, now_ns / 1000000000 + PIC_WEBPUSH_EXPIRY, vapid->subject,
auth_h + 15, sizeof auth_h - 15) < 0) {
return webpush_done(res, PIC_WEBPUSH_FAILED, 0, "cannot make the VAPID token");
}
/* A new key pair and salt for every push. */
if (pic_noise_keypair_make(&as, NULL) != 0 || plat->entropy(salt, sizeof salt) != 0) {
webpush_wipe(&as, sizeof as);
return webpush_done(res, PIC_WEBPUSH_FAILED, 0, "cannot get random bytes");
}
body = malloc(len + PIC_WEBPUSH_OVERHEAD);
body_n = body ? pic_noise_webpush(&as, salt, sub->p256dh, sub->auth, payload, len, body) : 0;
webpush_wipe(&as, sizeof as);
webpush_wipe(salt, sizeof salt);
if (body_n == 0) {
free(body);
return webpush_done(res, PIC_WEBPUSH_FAILED, 0,
body ? "the subscription's key is not a P-256 public key" : "out of memory");
}
(void)snprintf(ttl_h, sizeof ttl_h, "TTL: %d", ttl < 0 ? 0 : ttl);
headers[nh++] = ttl_h;
headers[nh++] = "Urgency: normal";
if (topic) {
(void)snprintf(topic_h, sizeof topic_h, "Topic: %s", topic);
headers[nh++] = topic_h;
}
headers[nh++] = "Content-Encoding: aes128gcm";
headers[nh++] = "Content-Type: application/octet-stream";
headers[nh++] = auth_h;
pic_http_resp_init(&r, NULL, NULL);
err[0] = '\0';
rc = pic_http_post(net, sub->endpoint, headers, nh, (const char *)body, body_n, &r, 15, 30, err, sizeof err);
webpush_wipe(body, body_n);
free(body);
webpush_wipe(auth_h, sizeof auth_h);
if (rc != 0) {
return webpush_done(res, PIC_WEBPUSH_FAILED, 0, err[0] ? err : "the push service did not answer");
}
(void)snprintf(err, sizeof err, "the push service answered %d", r.status);
switch (r.status) {
case 201:
return webpush_done(res, PIC_WEBPUSH_SENT, r.status, NULL);
case 404:
case 410:
return webpush_done(res, PIC_WEBPUSH_GONE, r.status, err);
case 413:
return webpush_done(res, PIC_WEBPUSH_TOO_LARGE, r.status, err);
case 429:
res->retry_after = webpush_retry_after(r.retry_after);
return webpush_done(res, PIC_WEBPUSH_RETRY, r.status, err);
default:
return webpush_done(res, PIC_WEBPUSH_FAILED, r.status, err);
}
}