/* * CHAD * One binary for your chat networks: Matrix via mautrix bridge * bots, later IRC and XMPP. Command line only, no statusbar. * The homeserver gets https:// prepended automatically; the * password / access token is never written to the session. * * USAGE * $ chad login prompt (first run) * $ chad -r list matrix rooms * $ chad -s "bob" "txt" send message to a room * $ chad -e "bob" enter a room * $ chat -d "bob" [file] download image/video * * INSTALL * $ make install * * AUTHOR * Written by 'chat' contributors. * */ #define _GNU_SOURCE #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define CHAT_VERSION "0.2" #define UNUSED __attribute__((unused)) /* * Things you may want to modify. * * The homeserver is the Matrix server you log into; https:// is * prepended automatically when it is missing. */ #define HS "http://127.0.0.1:8008" /* * default user name when the login prompt is left empty */ #define DEFUSER "marlon" /* * session directory name below ~/.config/ */ #define CONFIGDIR "chat" /* * name cache size for resolved room / display names */ #define NCACHE 4096 /* * http request timeout in seconds (sync, send, download) */ #define HTTPTIMEOUT 120L /* * sync long-poll timeout in milliseconds when watching */ #define POLLMS 1000L /* * number of timeline events to fetch live vs. on the first poll */ #define TLLIVE 100 #define TLFIRST 5 typedef struct OlmRec OlmRec; typedef struct MegolmRec MegolmRec; /* * session */ typedef struct { char *homeserver; char *user; char *token; char *since; char *e2e_acct; char *e2e_devid; OlmRec *e2e_olms; size_t e2e_olms_n; size_t e2e_olms_cap; MegolmRec *e2e_meg_in; size_t e2e_meg_in_n; size_t e2e_meg_in_cap; MegolmRec *e2e_meg_out; size_t e2e_meg_out_n; size_t e2e_meg_out_cap; } Session; struct OlmRec { char *user; char *device; char *pickle; char *idkey; }; static int e2e_dirty; struct MegolmRec { char *room; char *sid; char *pickle; char *skey; }; /* * secret storage via `pass` (gpg-backed) */ static char * secret_get(const char *name) { char cmd[1024]; char buf[4096]; FILE *f; size_t l; snprintf(cmd, sizeof cmd, "pass show %s 2>/dev/null", name); f = popen(cmd, "r"); if(f == NULL) return NULL; if(fgets(buf, sizeof buf, f) == NULL){ pclose(f); return NULL; } pclose(f); l = strlen(buf); while(l > 0 && (buf[l-1] == '\n' || buf[l-1] == '\r')) buf[--l] = '\0'; if(l == 0) return NULL; return strdup(buf); } static int secret_put(const char *name, const char *value) { char cmd[1024]; FILE *f; snprintf(cmd, sizeof cmd, "pass insert -f %s 2>/dev/null", name); f = popen(cmd, "w"); if(f == NULL) return -1; fputs(value, f); fputc('\n', f); fputs(value, f); fputc('\n', f); if(pclose(f) != 0) return -1; return 0; } /* * http (curl) */ typedef struct { char *buf; size_t len; } Buf; static size_t write_cb(void *ptr, size_t size, size_t nmemb, void *ud) { Buf *b = ud; size_t n = size * nmemb; char *p = realloc(b->buf, b->len + n + 1); if(p == NULL) return 0; memcpy(p + b->len, ptr, n); b->buf = p; b->len += n; b->buf[b->len] = '\0'; return n; } /* * Ein einziger, persistenter curl-Handle fuer alle Requests. Dadurch bleibt * die TCP/TLS-Verbindung zum Homeserver offen und wird wiederverwendet, * statt pro Request (z.B. name_of() fuer jeden Raum) neu zu handshaken. */ static CURL * http_curl(void) { static CURL *c; if(c == NULL){ curl_global_init(CURL_GLOBAL_DEFAULT); c = curl_easy_init(); } return c; } static char g_hs_local[128]; static size_t sink_cb(void *ptr, size_t size, size_t nmemb, void *ud) { (void)ptr; (void)ud; return size * nmemb; } /* * Auf dem Rechner, der Synapse selbst hostet, ist der Umweg ueber die * oeffentliche URL (DNS -> Router -> WAN -> zurueck) reine Latenz. * Wenn lokal ein Synapse antwortet, laufen alle Matrix-Requests direkt * gegen 127.0.0.1. Auf Laptop/Handy schlaegt die Probe fehl, dort bleibt * die konfigurierte URL unveraendert. */ static void hs_local_probe(void) { static int done; CURL *c; const char *env; long st = 0; if(done) return; done = 1; env = getenv("CHAD_LOCAL_HS"); if(env != NULL && env[0] != '\0'){ snprintf(g_hs_local, sizeof g_hs_local, "%s", env); return; } c = curl_easy_init(); if(c == NULL) return; curl_easy_setopt(c, CURLOPT_URL, "http://127.0.0.1:8008/_matrix/client/versions"); curl_easy_setopt(c, CURLOPT_PROXY, ""); curl_easy_setopt(c, CURLOPT_TIMEOUT_MS, 400L); curl_easy_setopt(c, CURLOPT_CONNECTTIMEOUT_MS, 250L); curl_easy_setopt(c, CURLOPT_WRITEFUNCTION, sink_cb); curl_easy_perform(c); curl_easy_getinfo(c, CURLINFO_RESPONSE_CODE, &st); curl_easy_cleanup(c); if(st == 200) snprintf(g_hs_local, sizeof g_hs_local, "http://127.0.0.1:8008"); } static char * hs_url(const char *url) { static const char *pub = "https://matrix.marlonivo.com"; size_t pl; if(g_hs_local[0] == '\0' || strncmp(url, pub, (pl = strlen(pub))) != 0) return strdup(url); { size_t n = strlen(g_hs_local) + strlen(url + pl) + 1; char *r = malloc(n); if(r == NULL) return NULL; snprintf(r, n, "%s%s", g_hs_local, url + pl); return r; } } static char * http_req(const char *method, const char *url, const char *token, const char *body, long *status, size_t *outlen) { CURL *c; struct curl_slist *hdrs = NULL; char auth[512], *eff; Buf b = {0}; long st = 0; char errbuf[CURL_ERROR_SIZE] = {0}; c = http_curl(); if(c == NULL) return NULL; hs_local_probe(); eff = hs_url(url); if(eff == NULL) return NULL; curl_easy_reset(c); curl_easy_setopt(c, CURLOPT_URL, eff); free(eff); curl_easy_setopt(c, CURLOPT_PROXY, ""); curl_easy_setopt(c, CURLOPT_CUSTOMREQUEST, method); curl_easy_setopt(c, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); curl_easy_setopt(c, CURLOPT_WRITEFUNCTION, write_cb); curl_easy_setopt(c, CURLOPT_WRITEDATA, &b); curl_easy_setopt(c, CURLOPT_ERRORBUFFER, errbuf); curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1L); curl_easy_setopt(c, CURLOPT_CONNECTTIMEOUT, 10L); if(token != NULL){ snprintf(auth, sizeof auth, "Authorization: Bearer %s", token); hdrs = curl_slist_append(hdrs, auth); } if(body != NULL){ hdrs = curl_slist_append(hdrs, "Content-Type: application/json"); curl_easy_setopt(c, CURLOPT_POSTFIELDS, body); } if(hdrs != NULL) curl_easy_setopt(c, CURLOPT_HTTPHEADER, hdrs); curl_easy_setopt(c, CURLOPT_TIMEOUT, HTTPTIMEOUT); if(curl_easy_perform(c) != CURLE_OK && b.buf == NULL){ fprintf(stderr, "chat: http: %s\n", errbuf); curl_slist_free_all(hdrs); return NULL; } curl_easy_getinfo(c, CURLINFO_RESPONSE_CODE, &st); curl_slist_free_all(hdrs); if(status != NULL) *status = st; if(outlen != NULL) *outlen = b.len; return b.buf; } static char * http_upload(const char *url, const char *token, const void *data, size_t len, const char *content_type, long *status) { CURL *c; struct curl_slist *hdrs = NULL; char auth[512], ct[160], *eff; Buf b = {0}; long st = 0; char errbuf[CURL_ERROR_SIZE] = {0}; curl_global_init(CURL_GLOBAL_DEFAULT); c = curl_easy_init(); if(c == NULL) return NULL; hs_local_probe(); eff = hs_url(url); if(eff == NULL){ curl_easy_cleanup(c); return NULL; } curl_easy_setopt(c, CURLOPT_URL, eff); free(eff); curl_easy_setopt(c, CURLOPT_PROXY, ""); curl_easy_setopt(c, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); curl_easy_setopt(c, CURLOPT_WRITEFUNCTION, write_cb); curl_easy_setopt(c, CURLOPT_WRITEDATA, &b); curl_easy_setopt(c, CURLOPT_ERRORBUFFER, errbuf); if(token != NULL){ snprintf(auth, sizeof auth, "Authorization: Bearer %s", token); hdrs = curl_slist_append(hdrs, auth); } if(content_type != NULL){ snprintf(ct, sizeof ct, "Content-Type: %s", content_type); hdrs = curl_slist_append(hdrs, ct); } curl_easy_setopt(c, CURLOPT_POSTFIELDS, (void *)data); curl_easy_setopt(c, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t)len); if(hdrs != NULL) curl_easy_setopt(c, CURLOPT_HTTPHEADER, hdrs); curl_easy_setopt(c, CURLOPT_TIMEOUT, HTTPTIMEOUT); if(curl_easy_perform(c) != CURLE_OK && b.buf == NULL){ fprintf(stderr, "chat: http: %s\n", errbuf); curl_slist_free_all(hdrs); curl_easy_cleanup(c); return NULL; } curl_easy_getinfo(c, CURLINFO_RESPONSE_CODE, &st); curl_slist_free_all(hdrs); curl_easy_cleanup(c); if(status != NULL) *status = st; return b.buf; } static char * cfg_path(const char *cfgdir) { size_t n = strlen(cfgdir) + 1 + 8 + 1; char *p = malloc(n); snprintf(p, n, "%s/session", cfgdir); return p; } static int dir_ok(const char *dir) { struct stat st; if(stat(dir, &st) == 0 && S_ISDIR(st.st_mode)) return 1; if(mkdir(dir, 0700) == 0) return 1; return stat(dir, &st) == 0 && S_ISDIR(st.st_mode); } #define E2E_QMAX 64 static char *e2e_qdone[E2E_QMAX]; static size_t e2e_qdone_n; static void e2e_qdone_add(const char *); static int session_load(Session *s, const char *cfgdir) { char *path = cfg_path(cfgdir); char *data; FILE *f; struct json_object *o, *v; long n; long size = 0; s->homeserver = s->user = s->token = s->since = NULL; s->e2e_acct = s->e2e_devid = NULL; s->e2e_olms = NULL; s->e2e_olms_n = s->e2e_olms_cap = 0; s->e2e_meg_in = NULL; s->e2e_meg_in_n = s->e2e_meg_in_cap = 0; s->e2e_meg_out = NULL; s->e2e_meg_out_n = s->e2e_meg_out_cap = 0; f = fopen(path, "r"); if(f == NULL){ free(path); return -1; } fseek(f, 0, SEEK_END); size = ftell(f); fseek(f, 0, SEEK_SET); data = malloc(size + 1); n = fread(data, 1, size, f); data[n] = '\0'; fclose(f); free(path); o = json_tokener_parse(data); free(data); if(o == NULL) return -1; #define GET(key, dst) \ if(json_object_object_get_ex(o, key, &v)) \ dst = strdup(json_object_get_string(v)); GET("homeserver", s->homeserver); GET("user", s->user); GET("token", s->token); GET("since", s->since); GET("e2e_acct", s->e2e_acct); GET("e2e_devid", s->e2e_devid); #undef GET if(json_object_object_get_ex(o, "e2e_olms", &v)){ long na = json_object_array_length(v); if(na > 0){ long i; s->e2e_olms = calloc((size_t)na, sizeof *s->e2e_olms); if(s->e2e_olms != NULL){ s->e2e_olms_n = s->e2e_olms_cap = (size_t)na; for(i = 0; i < na; i++){ struct json_object *r = json_object_array_get_idx(v, (size_t)i); struct json_object *f; if(json_object_object_get_ex(r, "user", &f)) s->e2e_olms[i].user = strdup( json_object_get_string(f)); if(json_object_object_get_ex(r, "device", &f)) s->e2e_olms[i].device = strdup( json_object_get_string(f)); if(json_object_object_get_ex(r, "pickle", &f)) s->e2e_olms[i].pickle = strdup( json_object_get_string(f)); if(json_object_object_get_ex(r, "idkey", &f)) s->e2e_olms[i].idkey = strdup( json_object_get_string(f)); } } } } if(json_object_object_get_ex(o, "e2e_meg_in", &v)){ long na = json_object_array_length(v); if(na > 0){ long i; s->e2e_meg_in = calloc((size_t)na, sizeof *s->e2e_meg_in); if(s->e2e_meg_in != NULL){ s->e2e_meg_in_n = s->e2e_meg_in_cap = (size_t)na; for(i = 0; i < na; i++){ struct json_object *r = json_object_array_get_idx(v, (size_t)i); struct json_object *f; if(json_object_object_get_ex(r, "room", &f)) s->e2e_meg_in[i].room = strdup( json_object_get_string(f)); if(json_object_object_get_ex(r, "sid", &f)) s->e2e_meg_in[i].sid = strdup( json_object_get_string(f)); if(json_object_object_get_ex(r, "pickle", &f)) s->e2e_meg_in[i].pickle = strdup( json_object_get_string(f)); } } } } if(json_object_object_get_ex(o, "e2e_meg_out", &v)){ long na = json_object_array_length(v); if(na > 0){ long i; s->e2e_meg_out = calloc((size_t)na, sizeof *s->e2e_meg_out); if(s->e2e_meg_out != NULL){ s->e2e_meg_out_n = s->e2e_meg_out_cap = (size_t)na; for(i = 0; i < na; i++){ struct json_object *r = json_object_array_get_idx(v, (size_t)i); struct json_object *f; if(json_object_object_get_ex(r, "room", &f)) s->e2e_meg_out[i].room = strdup( json_object_get_string(f)); if(json_object_object_get_ex(r, "sid", &f)) s->e2e_meg_out[i].sid = strdup( json_object_get_string(f)); if(json_object_object_get_ex(r, "pickle", &f)) s->e2e_meg_out[i].pickle = strdup( json_object_get_string(f)); if(json_object_object_get_ex(r, "skey", &f)) s->e2e_meg_out[i].skey = strdup( json_object_get_string(f)); } } } } if(json_object_object_get_ex(o, "e2e_qdone", &v)){ long na = json_object_array_length(v); long i; for(i = 0; i < na; i++){ const char *u = json_object_get_string( json_object_array_get_idx(v, (size_t)i)); if(u != NULL) e2e_qdone_add(u); } } json_object_put(o); return 0; } static int session_save(Session *s, const char *cfgdir) { char *path; struct json_object *o; const char *sout; FILE *f; if(!dir_ok(cfgdir)) return -1; o = json_object_new_object(); json_object_object_add(o, "homeserver", json_object_new_string(s->homeserver ? s->homeserver : "")); json_object_object_add(o, "user", json_object_new_string(s->user ? s->user : "")); json_object_object_add(o, "token", json_object_new_string(s->token ? s->token : "")); json_object_object_add(o, "since", json_object_new_string(s->since ? s->since : "")); if(s->e2e_acct != NULL){ json_object_object_add(o, "e2e_acct", json_object_new_string(s->e2e_acct)); } if(s->e2e_devid != NULL){ json_object_object_add(o, "e2e_devid", json_object_new_string(s->e2e_devid)); } if(s->e2e_olms_n > 0){ struct json_object *arr = json_object_new_array(); size_t i; for(i = 0; i < s->e2e_olms_n; i++){ struct json_object *r = json_object_new_object(); json_object_object_add(r, "user", json_object_new_string(s->e2e_olms[i].user ? s->e2e_olms[i].user : "")); json_object_object_add(r, "device", json_object_new_string(s->e2e_olms[i].device ? s->e2e_olms[i].device : "")); if(s->e2e_olms[i].pickle != NULL) json_object_object_add(r, "pickle", json_object_new_string(s->e2e_olms[i].pickle)); if(s->e2e_olms[i].idkey != NULL) json_object_object_add(r, "idkey", json_object_new_string(s->e2e_olms[i].idkey)); json_object_array_add(arr, r); } json_object_object_add(o, "e2e_olms", arr); } if(s->e2e_meg_in_n > 0){ struct json_object *arr = json_object_new_array(); size_t i; for(i = 0; i < s->e2e_meg_in_n; i++){ struct json_object *r = json_object_new_object(); json_object_object_add(r, "room", json_object_new_string(s->e2e_meg_in[i].room)); json_object_object_add(r, "sid", json_object_new_string(s->e2e_meg_in[i].sid)); if(s->e2e_meg_in[i].pickle != NULL) json_object_object_add(r, "pickle", json_object_new_string(s->e2e_meg_in[i].pickle)); json_object_array_add(arr, r); } json_object_object_add(o, "e2e_meg_in", arr); } if(s->e2e_meg_out_n > 0){ struct json_object *arr = json_object_new_array(); size_t i; for(i = 0; i < s->e2e_meg_out_n; i++){ struct json_object *r = json_object_new_object(); json_object_object_add(r, "room", json_object_new_string(s->e2e_meg_out[i].room)); json_object_object_add(r, "sid", json_object_new_string(s->e2e_meg_out[i].sid)); if(s->e2e_meg_out[i].pickle != NULL) json_object_object_add(r, "pickle", json_object_new_string(s->e2e_meg_out[i].pickle)); if(s->e2e_meg_out[i].skey != NULL) json_object_object_add(r, "skey", json_object_new_string(s->e2e_meg_out[i].skey)); json_object_array_add(arr, r); } json_object_object_add(o, "e2e_meg_out", arr); } if(e2e_qdone_n > 0){ struct json_object *arr = json_object_new_array(); size_t i; for(i = 0; i < e2e_qdone_n; i++){ json_object_array_add(arr, json_object_new_string(e2e_qdone[i] ? e2e_qdone[i] : "")); } json_object_object_add(o, "e2e_qdone", arr); } sout = json_object_to_json_string(o); path = cfg_path(cfgdir); f = fopen(path, "w"); if(f == NULL){ json_object_put(o); free(path); return -1; } chmod(path, 0600); fputs(sout, f); fclose(f); free(path); json_object_put(o); return 0; } static void session_free(Session *s) { size_t i; free(s->homeserver); free(s->user); free(s->token); free(s->since); free(s->e2e_acct); free(s->e2e_devid); for(i = 0; i < s->e2e_olms_n; i++){ free(s->e2e_olms[i].user); free(s->e2e_olms[i].device); free(s->e2e_olms[i].pickle); free(s->e2e_olms[i].idkey); } free(s->e2e_olms); for(i = 0; i < s->e2e_meg_in_n; i++){ free(s->e2e_meg_in[i].room); free(s->e2e_meg_in[i].sid); free(s->e2e_meg_in[i].pickle); } free(s->e2e_meg_in); for(i = 0; i < s->e2e_meg_out_n; i++){ free(s->e2e_meg_out[i].room); free(s->e2e_meg_out[i].sid); free(s->e2e_meg_out[i].pickle); free(s->e2e_meg_out[i].skey); } free(s->e2e_meg_out); s->homeserver = s->user = s->token = s->since = NULL; s->e2e_acct = s->e2e_devid = NULL; s->e2e_olms = NULL; s->e2e_olms_n = s->e2e_olms_cap = 0; s->e2e_meg_in = NULL; s->e2e_meg_in_n = s->e2e_meg_in_cap = 0; s->e2e_meg_out = NULL; s->e2e_meg_out_n = s->e2e_meg_out_cap = 0; } static size_t hex_enc(const uint8_t *in, size_t n, char *out) { static const char d[] = "0123456789abcdef"; size_t i; for(i = 0; i < n; i++){ out[2 * i] = d[(in[i] >> 4) & 0xf]; out[2 * i + 1] = d[in[i] & 0xf]; } out[2 * n] = '\0'; return 2 * n; } static int hexval(char c) { if(c >= '0' && c <= '9') return c - '0'; if(c >= 'a' && c <= 'f') return c - 'a' + 10; if(c >= 'A' && c <= 'F') return c - 'A' + 10; return -1; } static size_t hex_dec(const char *in, uint8_t *out, size_t n) { size_t i; int hi, lo; for(i = 0; i < n; i++){ hi = hexval(in[2 * i]); lo = hexval(in[2 * i + 1]); if(hi < 0 || lo < 0) return i; out[i] = (uint8_t)((hi << 4) | lo); } return n; } static char * keyid(const char *prefix, const char *devid) { size_t n = strlen(prefix) + strlen(devid) + 1; char *p = malloc(n); if(p == NULL) return NULL; snprintf(p, n, "%s%s", prefix, devid); return p; } static int e2e_setup(Session *s) { void *acct; char *p, *hex; size_t len, rlen; ssize_t r; uint8_t rnd[64]; if(s->e2e_acct != NULL && s->e2e_acct[0] != '\0') return 0; acct = malloc(olm_account_size()); if(acct == NULL) return -1; olm_account(acct); rlen = olm_create_account_random_length(acct); if(rlen > sizeof rnd) rlen = sizeof rnd; r = getrandom(rnd, rlen, 0); if(r < 0){ olm_clear_account(acct); free(acct); return -1; } if(olm_create_account(acct, rnd, (size_t)r) != 0){ olm_clear_account(acct); free(acct); return -1; } len = olm_pickle_account_length(acct); p = malloc(len + 1); if(p == NULL){ olm_clear_account(acct); free(acct); return -1; } olm_pickle_account(acct, NULL, 0, p, len); p[len] = '\0'; hex = malloc(len * 2 + 1); if(hex == NULL){ free(p); olm_clear_account(acct); free(acct); return -1; } hex_enc((const uint8_t *)p, len, hex); free(p); olm_clear_account(acct); free(acct); s->e2e_acct = hex; return 0; } static OlmAccount * e2e_acct_open(const char *accthex) { void *mem; OlmAccount *a; char *raw; size_t n; if(accthex == NULL || accthex[0] == '\0') return NULL; n = strlen(accthex) / 2; raw = malloc(n); if(raw == NULL) return NULL; if(hex_dec(accthex, (uint8_t *)raw, n) != n){ free(raw); return NULL; } mem = malloc(olm_account_size()); if(mem == NULL){ free(raw); return NULL; } a = olm_account(mem); if(olm_unpickle_account(a, NULL, 0, raw, n) == olm_error()){ free(raw); olm_clear_account(a); free(mem); return NULL; } free(raw); return a; } static void e2e_acct_close(OlmAccount *a) { olm_clear_account(a); free(a); } static int e2e_acct_save(Session *s, OlmAccount *a) { size_t n; char *p, *hex; n = olm_pickle_account_length(a); p = malloc(n + 1); hex = p != NULL ? malloc(2 * n + 1) : NULL; if(p == NULL || hex == NULL){ free(p); free(hex); return -1; } olm_pickle_account(a, NULL, 0, p, n); p[n] = '\0'; hex_enc((const uint8_t *)p, n, hex); free(p); free(s->e2e_acct); s->e2e_acct = hex; e2e_dirty = 1; return 0; } static char * b64url(const char *b64) { size_t n = strlen(b64), i, k = 0; char *out = malloc(n + 1); if(out == NULL) return NULL; for(i = 0; i < n; i++){ char c = b64[i]; if(c == '+') c = '-'; else if(c == '/') c = '_'; else if(c == '=') continue; out[k++] = c; } out[k] = '\0'; return out; } static char * b64std(const char *u) { size_t n = strlen(u), i; char *out = malloc(n + 1); if(out == NULL) return NULL; for(i = 0; i < n; i++){ char c = u[i]; if(c == '-') c = '+'; else if(c == '_') c = '/'; out[i] = c; } out[n] = '\0'; return out; } static char * canon_esc(const char *s) { size_t n = strlen(s), i; char *out, *p; int need = 0; for(i = 0; i < n; i++) if(s[i] == '"' || s[i] == '\\') need++; out = malloc(n + need + 1); if(out == NULL) return NULL; p = out; for(i = 0; i < n; i++){ if(s[i] == '"' || s[i] == '\\') *p++ = '\\'; *p++ = s[i]; } *p = '\0'; return out; } static char * e2e_canon_device_keys(const char *user, const char *devid, const char *curve, const char *ed, const char *sig) { char *uc, *dc, *cc, *ec, *sc; char *out; size_t n; int r; uc = canon_esc(user); dc = canon_esc(devid); cc = canon_esc(curve); ec = canon_esc(ed); sc = canon_esc(sig != NULL ? sig : ""); if(uc == NULL || dc == NULL || cc == NULL || ec == NULL || sc == NULL){ free(uc); free(dc); free(cc); free(ec); free(sc); return NULL; } n = 512 + strlen(uc) + strlen(dc) + strlen(cc) + strlen(ec) + strlen(sc) + 2 * strlen(devid); out = malloc(n); if(out != NULL){ r = snprintf(out, n, "{\"algorithms\":[\"m.olm.v1.curve25519-aes-sha2\"," "\"m.megolm.v1.aes-sha2\"]," "\"device_id\":\"%s\"," "\"keys\":{\"curve25519:%s\":\"%s\"," "\"ed25519:%s\":\"%s\"}," "\"signatures\":{\"%s\":{\"ed25519:%s\":\"%s\"}}," "\"user_id\":\"%s\"}", dc, devid, cc, devid, ec, uc, devid, sc, uc); if(r < 0 || (size_t)r >= n){ free(out); out = NULL; } } free(uc); free(dc); free(cc); free(ec); free(sc); return out; } static char * e2e_our_curve(Session *s) { OlmAccount *a; size_t n; char *keys, *out = NULL; struct json_object *o, *c; if(s->e2e_acct == NULL || s->e2e_acct[0] == '\0') return NULL; a = e2e_acct_open(s->e2e_acct); if(a == NULL) return NULL; n = olm_account_identity_keys_length(a); keys = malloc(n + 1); if(keys != NULL){ olm_account_identity_keys(a, keys, n); keys[n] = '\0'; o = json_tokener_parse(keys); free(keys); if(o != NULL){ c = json_object_object_get(o, "curve25519"); if(c != NULL) out = strdup(json_object_get_string(c)); json_object_put(o); } } e2e_acct_close(a); return out; } static int e2e_otk_build(OlmAccount *a, const char *user, const char *devid, struct json_object **out) { size_t rlen, ilen, slen; uint8_t *rnd; char *keys, *kname, *canon, *sig, *ukey, *ekname; struct json_object *o, *curve, *otks, *entry, *sa, *su; int rc = -1; *out = NULL; rlen = olm_account_generate_one_time_keys_random_length(a, 50); rnd = malloc(rlen > 0 ? rlen : 1); if(rnd == NULL || getrandom(rnd, rlen, 0) != (ssize_t)rlen){ fprintf(stderr, "chat: e2e: otk: no random\n"); free(rnd); return -1; } if(olm_account_generate_one_time_keys(a, 50, rnd, rlen) == olm_error()){ fprintf(stderr, "chat: e2e: otk gen: %s\n", olm_account_last_error(a)); free(rnd); return -1; } free(rnd); ilen = olm_account_one_time_keys_length(a); keys = malloc(ilen + 1); if(keys == NULL) return -1; olm_account_one_time_keys(a, keys, ilen); keys[ilen] = '\0'; o = json_tokener_parse(keys); free(keys); if(o == NULL) return -1; curve = json_object_object_get(o, "curve25519"); if(curve == NULL){ json_object_put(o); return -1; } otks = json_object_new_object(); slen = olm_account_signature_length(a); sig = malloc(slen + 1); if(sig == NULL || otks == NULL){ free(sig); json_object_put(o); if(otks != NULL) json_object_put(otks); return -1; } json_object_object_foreach(curve, kid, kval) { const char *kb = json_object_get_string(kval); char *uc, *dc; size_t cn; ukey = b64url(kb); uc = canon_esc(user); dc = canon_esc(devid); ekname = keyid("ed25519:", devid); kname = malloc(strlen(kid) + 20); if(ukey == NULL || uc == NULL || dc == NULL || ekname == NULL || kname == NULL){ free(ukey); free(uc); free(dc); free(ekname); free(kname); continue; } sprintf(kname, "signed_curve25519:%s", kid); cn = 128 + strlen(uc) + strlen(dc) + strlen(ukey) + strlen(ekname); canon = malloc(cn); if(canon == NULL){ free(ukey); free(uc); free(dc); free(ekname); free(kname); continue; } snprintf(canon, cn, "{\"key\":\"%s\",\"signatures\":{\"%s\":{\"%s\":\"\"}}}", ukey, uc, ekname); if(olm_account_sign(a, canon, strlen(canon), sig, slen) == olm_error()){ fprintf(stderr, "chat: e2e: otk sign: %s\n", olm_account_last_error(a)); free(canon); free(ukey); free(uc); free(dc); free(ekname); free(kname); continue; } sig[slen] = '\0'; entry = json_object_new_object(); sa = json_object_new_object(); su = json_object_new_object(); if(entry == NULL || sa == NULL || su == NULL){ if(entry != NULL) json_object_put(entry); if(sa != NULL) json_object_put(sa); if(su != NULL) json_object_put(su); free(canon); free(ukey); free(uc); free(dc); free(ekname); free(kname); continue; } json_object_object_add(entry, "key", json_object_new_string(ukey)); json_object_object_add(su, ekname, json_object_new_string(sig)); json_object_object_add(sa, user, su); json_object_object_add(entry, "signatures", sa); json_object_object_add(otks, kname, entry); free(canon); free(ukey); free(uc); free(dc); free(ekname); free(kname); rc = 0; } json_object_put(o); free(sig); if(rc == 0) *out = otks; else json_object_put(otks); return rc; } static int e2e_publish_keys(Session *s) { OlmAccount *a; size_t ilen, slen, n; char *ikeys, *sig, *ckid, *ekid, *canon; struct json_object *o, *curve, *ed, *dkeys, *keys, *sa, *ent, *send, *algs; const char *body; char *url, *res; long status; int rc = -1; if(s->user == NULL || s->e2e_devid == NULL) return -1; a = e2e_acct_open(s->e2e_acct); if(a == NULL) return -1; ilen = olm_account_identity_keys_length(a); ikeys = malloc(ilen + 1); if(ikeys == NULL){ e2e_acct_close(a); return -1; } olm_account_identity_keys(a, ikeys, ilen); ikeys[ilen] = '\0'; o = json_tokener_parse(ikeys); free(ikeys); if(o == NULL){ e2e_acct_close(a); return -1; } curve = json_object_object_get(o, "curve25519"); ed = json_object_object_get(o, "ed25519"); if(curve == NULL || ed == NULL){ json_object_put(o); e2e_acct_close(a); return -1; } ckid = keyid("curve25519:", s->e2e_devid); ekid = keyid("ed25519:", s->e2e_devid); if(ckid == NULL || ekid == NULL){ free(ckid); free(ekid); json_object_put(o); e2e_acct_close(a); return -1; } canon = e2e_canon_device_keys(s->user, s->e2e_devid, json_object_get_string(curve), json_object_get_string(ed), NULL); if(canon == NULL){ free(ckid); free(ekid); json_object_put(o); e2e_acct_close(a); return -1; } slen = olm_account_signature_length(a); sig = malloc(slen + 1); if(sig == NULL || olm_account_sign(a, canon, strlen(canon), sig, slen) == olm_error()){ if(sig != NULL){ fprintf(stderr, "chat: e2e: sign: %s\n", olm_account_last_error(a)); free(sig); }else fprintf(stderr, "chat: e2e: sign: no memory\n"); free(canon); free(ckid); free(ekid); json_object_put(o); e2e_acct_close(a); return -1; } sig[slen] = '\0'; free(canon); dkeys = json_object_new_object(); keys = json_object_new_object(); algs = json_object_new_array(); json_object_array_add(algs, json_object_new_string("m.olm.v1.curve25519-aes-sha2")); json_object_array_add(algs, json_object_new_string("m.megolm.v1.aes-sha2")); json_object_object_add(dkeys, "algorithms", algs); json_object_object_add(dkeys, "device_id", json_object_new_string(s->e2e_devid ? s->e2e_devid : "")); json_object_object_add(keys, ckid, json_object_new_string(json_object_get_string(curve))); json_object_object_add(keys, ekid, json_object_new_string(json_object_get_string(ed))); json_object_object_add(dkeys, "keys", keys); json_object_object_add(dkeys, "user_id", json_object_new_string(s->user ? s->user : "")); sa = json_object_new_object(); ent = json_object_new_object(); json_object_object_add(ent, ekid, json_object_new_string(sig)); json_object_object_add(sa, s->user, ent); json_object_object_add(dkeys, "signatures", sa); send = json_object_new_object(); json_object_object_add(send, "device_keys", dkeys); { struct json_object *otks = NULL; if(e2e_otk_build(a, s->user, s->e2e_devid, &otks) == 0) json_object_object_add(send, "one_time_keys", otks); else fprintf(stderr, "chat: e2e: otk build failed, " "uploading device keys only\n"); } body = json_object_to_json_string(send); n = strlen(s->homeserver) + 48; url = malloc(n); snprintf(url, n, "%s/_matrix/client/v3/keys/upload", s->homeserver); res = http_req("PUT", url, s->token, body, &status, NULL); free(url); if(res != NULL && status == 200){ struct json_object *ro, *counts, *sc; int left = -1; ro = json_tokener_parse(res); if(ro != NULL){ if(json_object_object_get_ex(ro, "one_time_key_counts", &counts) && json_object_object_get_ex(counts, "signed_curve25519", &sc)) left = json_object_get_int(sc); json_object_put(ro); } if(left >= 0 && left < 10){ struct json_object *otks = NULL; if(e2e_otk_build(a, s->user, s->e2e_devid, &otks) == 0){ struct json_object *send2; const char *body2; char *res2 = NULL; long status2 = 0; send2 = json_object_new_object(); json_object_object_add(send2, "device_keys", json_object_get(dkeys)); json_object_object_add(send2, "one_time_keys", otks); body2 = json_object_to_json_string(send2); url = malloc(n); snprintf(url, n, "%s/_matrix/client/v3/keys/upload", s->homeserver); res2 = http_req("PUT", url, s->token, body2, &status2, NULL); free(url); if(res2 != NULL && status2 == 200) left = 99; free(res2); json_object_put(send2); } } olm_account_mark_keys_as_published(a); if(e2e_acct_save(s, a) != 0) fprintf(stderr, "chat: e2e: account pickle failed\n"); rc = 0; } free(res); json_object_put(send); free(sig); free(ckid); free(ekid); json_object_put(o); e2e_acct_close(a); return rc; } static char * e2e_olm_pickle(OlmSession *os) { size_t n; char *p, *hex; n = olm_pickle_session_length(os); p = malloc(n + 1); if(p == NULL) return NULL; olm_pickle_session(os, NULL, 0, p, n); p[n] = '\0'; hex = malloc(2 * n + 1); if(hex == NULL){ free(p); return NULL; } hex_enc((const uint8_t *)p, n, hex); free(p); return hex; } static OlmSession * e2e_olm_unpickle(const char *hex, void **mem_out) { void *mem; OlmSession *os; char *raw; size_t n; if(hex == NULL) return NULL; n = strlen(hex) / 2; raw = malloc(n); if(raw == NULL) return NULL; if(hex_dec(hex, (uint8_t *)raw, n) != n){ free(raw); return NULL; } mem = malloc(olm_session_size()); if(mem == NULL){ free(raw); return NULL; } os = olm_session(mem); if(olm_unpickle_session(os, NULL, 0, raw, n) == olm_error()){ free(raw); olm_clear_session(os); free(mem); return NULL; } free(raw); *mem_out = mem; return os; } static char * e2e_olm_new_outbound(const char *accthex, const char *idkey, const char *otk) { OlmAccount *a; void *smem; OlmSession *os; size_t rlen; uint8_t *rnd; char *hex = NULL; int got = 0; a = e2e_acct_open(accthex); if(a == NULL) return NULL; smem = malloc(olm_session_size()); if(smem == NULL){ e2e_acct_close(a); return NULL; } os = olm_session(smem); rlen = olm_create_outbound_session_random_length(os); rnd = malloc(rlen > 0 ? rlen : 1); if(rnd != NULL && getrandom(rnd, rlen, 0) == (ssize_t)rlen){ if(olm_create_outbound_session(os, a, idkey, strlen(idkey), otk, strlen(otk), rnd, rlen) != olm_error()) hex = e2e_olm_pickle(os); else fprintf(stderr, "chat: e2e: olm outbound: %s\n", olm_session_last_error(os)); got = 1; } if(!got && rnd != NULL) fprintf(stderr, "chat: e2e: olm outbound: no random\n"); free(rnd); olm_clear_session(os); free(smem); e2e_acct_close(a); return hex; } static int e2e_olm_save(Session *s, const char *user, const char *device, const char *hex) { size_t i; for(i = 0; i < s->e2e_olms_n; i++){ if(strcmp(s->e2e_olms[i].user, user) == 0 && strcmp(s->e2e_olms[i].device, device) == 0){ free(s->e2e_olms[i].pickle); s->e2e_olms[i].pickle = strdup(hex); e2e_dirty = 1; return s->e2e_olms[i].pickle != NULL ? 0 : -1; } } if(s->e2e_olms_n == s->e2e_olms_cap){ size_t nc = s->e2e_olms_cap == 0 ? 8 : s->e2e_olms_cap * 2; OlmRec *nr = realloc(s->e2e_olms, nc * sizeof *nr); if(nr == NULL) return -1; s->e2e_olms = nr; s->e2e_olms_cap = nc; } s->e2e_olms[s->e2e_olms_n].user = strdup(user); s->e2e_olms[s->e2e_olms_n].device = strdup(device); s->e2e_olms[s->e2e_olms_n].pickle = strdup(hex); s->e2e_olms[s->e2e_olms_n].idkey = NULL; if(s->e2e_olms[s->e2e_olms_n].user == NULL || s->e2e_olms[s->e2e_olms_n].device == NULL || s->e2e_olms[s->e2e_olms_n].pickle == NULL) return -1; s->e2e_olms_n++; e2e_dirty = 1; return 0; } static OlmRec * e2e_olm_rec(Session *s, const char *user, const char *device) { size_t i; for(i = 0; i < s->e2e_olms_n; i++) if(strcmp(s->e2e_olms[i].user, user) == 0 && strcmp(s->e2e_olms[i].device, device) == 0) return &s->e2e_olms[i]; return NULL; } static int e2e_olm_idkey_save(Session *s, const char *user, const char *device, const char *idkey) { OlmRec *r = e2e_olm_rec(s, user, device); if(r != NULL){ free(r->idkey); r->idkey = strdup(idkey); e2e_dirty = 1; return r->idkey != NULL ? 0 : -1; } if(s->e2e_olms_n == s->e2e_olms_cap){ size_t nc = s->e2e_olms_cap == 0 ? 8 : s->e2e_olms_cap * 2; OlmRec *nr = realloc(s->e2e_olms, nc * sizeof *nr); if(nr == NULL) return -1; s->e2e_olms = nr; s->e2e_olms_cap = nc; } s->e2e_olms[s->e2e_olms_n].user = strdup(user); s->e2e_olms[s->e2e_olms_n].device = strdup(device); s->e2e_olms[s->e2e_olms_n].pickle = NULL; s->e2e_olms[s->e2e_olms_n].idkey = strdup(idkey); if(s->e2e_olms[s->e2e_olms_n].user == NULL || s->e2e_olms[s->e2e_olms_n].device == NULL || s->e2e_olms[s->e2e_olms_n].idkey == NULL) return -1; s->e2e_olms_n++; e2e_dirty = 1; return 0; } static char * e2e_olm_wrap(const char *hex, const char *plain, char **newhex, int *type_out) { void *mem; OlmSession *os; size_t mlen, rlen; uint8_t *rnd; char *out = NULL, *nh, *cipher; os = e2e_olm_unpickle(hex, &mem); if(os == NULL) return NULL; *type_out = (int)olm_encrypt_message_type(os); rlen = olm_encrypt_random_length(os); rnd = malloc(rlen > 0 ? rlen : 1); if(rnd == NULL || getrandom(rnd, rlen, 0) != (ssize_t)rlen){ fprintf(stderr, "chat: e2e: olm wrap: no random\n"); free(rnd); olm_clear_session(os); free(mem); return NULL; } mlen = olm_encrypt_message_length(os, strlen(plain)); cipher = malloc(mlen + 1); if(cipher == NULL || olm_encrypt(os, plain, strlen(plain), rnd, rlen, cipher, mlen) == olm_error()){ fprintf(stderr, "chat: e2e: olm encrypt: %s\n", olm_session_last_error(os)); free(rnd); free(cipher); olm_clear_session(os); free(mem); return NULL; } free(rnd); cipher[mlen] = '\0'; nh = e2e_olm_pickle(os); olm_clear_session(os); free(mem); if(nh == NULL){ free(cipher); return NULL; } out = b64url(cipher); free(cipher); if(out == NULL){ free(nh); return NULL; } if(newhex != NULL) *newhex = nh; else free(nh); return out; } static const char * e2e_olm_find(Session *s, const char *user, const char *device) { size_t i; for(i = 0; i < s->e2e_olms_n; i++) if(strcmp(s->e2e_olms[i].user, user) == 0 && strcmp(s->e2e_olms[i].device, device) == 0) return s->e2e_olms[i].pickle; return NULL; } static char * e2e_meg_out_pickle(OlmOutboundGroupSession *os) { size_t n; char *p, *hex; n = olm_pickle_outbound_group_session_length(os); p = malloc(n + 1); if(p == NULL) return NULL; olm_pickle_outbound_group_session(os, NULL, 0, p, n); p[n] = '\0'; hex = malloc(2 * n + 1); if(hex == NULL){ free(p); return NULL; } hex_enc((const uint8_t *)p, n, hex); free(p); return hex; } static OlmOutboundGroupSession * e2e_meg_out_unpickle(const char *hex, void **mem_out) { void *mem; OlmOutboundGroupSession *os; char *raw; size_t n; if(hex == NULL) return NULL; n = strlen(hex) / 2; raw = malloc(n); if(raw == NULL) return NULL; if(hex_dec(hex, (uint8_t *)raw, n) != n){ free(raw); return NULL; } mem = malloc(olm_outbound_group_session_size()); if(mem == NULL){ free(raw); return NULL; } os = olm_outbound_group_session(mem); if(olm_unpickle_outbound_group_session(os, NULL, 0, raw, n) == olm_error()){ free(raw); olm_clear_outbound_group_session(os); free(mem); return NULL; } free(raw); *mem_out = mem; return os; } static char * e2e_meg_in_pickle(OlmInboundGroupSession *is) { size_t n; char *p, *hex; n = olm_pickle_inbound_group_session_length(is); p = malloc(n + 1); if(p == NULL) return NULL; olm_pickle_inbound_group_session(is, NULL, 0, p, n); p[n] = '\0'; hex = malloc(2 * n + 1); if(hex == NULL){ free(p); return NULL; } hex_enc((const uint8_t *)p, n, hex); free(p); return hex; } static OlmInboundGroupSession * e2e_meg_in_unpickle(const char *hex, void **mem_out) { void *mem; OlmInboundGroupSession *is; char *raw; size_t n; if(hex == NULL) return NULL; n = strlen(hex) / 2; raw = malloc(n); if(raw == NULL) return NULL; if(hex_dec(hex, (uint8_t *)raw, n) != n){ free(raw); return NULL; } mem = malloc(olm_inbound_group_session_size()); if(mem == NULL){ free(raw); return NULL; } is = olm_inbound_group_session(mem); if(olm_unpickle_inbound_group_session(is, NULL, 0, raw, n) == olm_error()){ free(raw); olm_clear_inbound_group_session(is); free(mem); return NULL; } free(raw); *mem_out = mem; return is; } static int e2e_meg_out_save(Session *s, const char *room, const char *sid, const char *hex, const char *skey) { size_t i; for(i = 0; i < s->e2e_meg_out_n; i++){ if(strcmp(s->e2e_meg_out[i].room, room) == 0 && strcmp(s->e2e_meg_out[i].sid, sid) == 0){ free(s->e2e_meg_out[i].pickle); free(s->e2e_meg_out[i].skey); s->e2e_meg_out[i].pickle = strdup(hex); s->e2e_meg_out[i].skey = strdup(skey); e2e_dirty = 1; return 0; } } if(s->e2e_meg_out_n == s->e2e_meg_out_cap){ size_t nc = s->e2e_meg_out_cap == 0 ? 4 : s->e2e_meg_out_cap * 2; MegolmRec *nr = realloc(s->e2e_meg_out, nc * sizeof *nr); if(nr == NULL) return -1; s->e2e_meg_out = nr; s->e2e_meg_out_cap = nc; } s->e2e_meg_out[s->e2e_meg_out_n].room = strdup(room); s->e2e_meg_out[s->e2e_meg_out_n].sid = strdup(sid); s->e2e_meg_out[s->e2e_meg_out_n].pickle = strdup(hex); s->e2e_meg_out[s->e2e_meg_out_n].skey = strdup(skey); s->e2e_meg_out_n++; e2e_dirty = 1; return 0; } static MegolmRec * e2e_meg_out_find(Session *s, const char *room) { size_t i; for(i = s->e2e_meg_out_n; i > 0; i--) if(strcmp(s->e2e_meg_out[i - 1].room, room) == 0) return &s->e2e_meg_out[i - 1]; return NULL; } static int e2e_meg_in_save(Session *s, const char *room, const char *sid, const char *hex) { size_t i; for(i = 0; i < s->e2e_meg_in_n; i++){ if(strcmp(s->e2e_meg_in[i].room, room) == 0 && strcmp(s->e2e_meg_in[i].sid, sid) == 0){ free(s->e2e_meg_in[i].pickle); s->e2e_meg_in[i].pickle = strdup(hex); e2e_dirty = 1; return 0; } } if(s->e2e_meg_in_n == s->e2e_meg_in_cap){ size_t nc = s->e2e_meg_in_cap == 0 ? 4 : s->e2e_meg_in_cap * 2; MegolmRec *nr = realloc(s->e2e_meg_in, nc * sizeof *nr); if(nr == NULL) return -1; s->e2e_meg_in = nr; s->e2e_meg_in_cap = nc; } s->e2e_meg_in[s->e2e_meg_in_n].room = strdup(room); s->e2e_meg_in[s->e2e_meg_in_n].sid = strdup(sid); s->e2e_meg_in[s->e2e_meg_in_n].pickle = strdup(hex); s->e2e_meg_in_n++; e2e_dirty = 1; return 0; } static MegolmRec * e2e_meg_in_find(Session *s, const char *room, const char *sid) { size_t i; for(i = 0; i < s->e2e_meg_in_n; i++) if(strcmp(s->e2e_meg_in[i].room, room) == 0 && strcmp(s->e2e_meg_in[i].sid, sid) == 0) return &s->e2e_meg_in[i]; return NULL; } static int e2e_meg_out_new(Session *s, const char *room) { void *mem; OlmOutboundGroupSession *os; size_t rlen, ilen, klen; uint8_t *rnd, *sid, *skey; char *hex; int rc = -1; mem = malloc(olm_outbound_group_session_size()); if(mem == NULL) return -1; os = olm_outbound_group_session(mem); rlen = olm_init_outbound_group_session_random_length(os); rnd = malloc(rlen > 0 ? rlen : 1); if(rnd == NULL || getrandom(rnd, rlen, 0) != (ssize_t)rlen){ fprintf(stderr, "chat: e2e: megolm out: no random\n"); free(rnd); olm_clear_outbound_group_session(os); free(mem); return -1; } if(olm_init_outbound_group_session(os, rnd, rlen) == olm_error()){ fprintf(stderr, "chat: e2e: megolm out: %s\n", olm_outbound_group_session_last_error(os)); free(rnd); olm_clear_outbound_group_session(os); free(mem); return -1; } free(rnd); ilen = olm_outbound_group_session_id_length(os); klen = olm_outbound_group_session_key_length(os); sid = malloc(ilen + 1); skey = malloc(klen + 1); hex = NULL; if(sid != NULL && skey != NULL){ olm_outbound_group_session_id(os, sid, ilen); sid[ilen] = '\0'; olm_outbound_group_session_key(os, skey, klen); skey[klen] = '\0'; hex = e2e_meg_out_pickle(os); if(hex != NULL && e2e_meg_out_save(s, room, (char *)sid, hex, (char *)skey) == 0) rc = 0; } free(sid); free(skey); free(hex); olm_clear_outbound_group_session(os); free(mem); return rc; } static char * e2e_meg_encrypt(const char *hex, const char *plain, char **newhex) { void *mem; OlmOutboundGroupSession *os; size_t n; char *msg, *out = NULL, *nh = NULL; os = e2e_meg_out_unpickle(hex, &mem); if(os == NULL) return NULL; n = olm_group_encrypt_message_length(os, strlen(plain)); msg = malloc(n + 1); if(msg != NULL){ if(olm_group_encrypt(os, (const uint8_t *)plain, strlen(plain), (uint8_t *)msg, n) != olm_error()){ msg[n] = '\0'; out = strdup(msg); nh = e2e_meg_out_pickle(os); }else fprintf(stderr, "chat: e2e: megolm enc: %s\n", olm_outbound_group_session_last_error(os)); free(msg); } olm_clear_outbound_group_session(os); free(mem); if(out != NULL){ if(newhex != NULL) *newhex = nh; else free(nh); }else free(nh); return out; } static char * e2e_meg_key(const char *hex) { void *mem; OlmOutboundGroupSession *os; size_t n; char *k, *out = NULL; os = e2e_meg_out_unpickle(hex, &mem); if(os == NULL) return NULL; n = olm_outbound_group_session_key_length(os); k = malloc(n + 1); if(k != NULL){ olm_outbound_group_session_key(os, (uint8_t *)k, n); k[n] = '\0'; out = strdup(k); free(k); } olm_clear_outbound_group_session(os); free(mem); return out; } static int e2e_meg_in_import(Session *s, const char *room, const char *sid, const char *skey) { void *mem; OlmInboundGroupSession *is; char *sk; char *hex; int rc = -1; mem = malloc(olm_inbound_group_session_size()); if(mem == NULL) return -1; is = olm_inbound_group_session(mem); sk = strdup(skey); if(sk != NULL){ if(olm_init_inbound_group_session(is, (const uint8_t *)sk, strlen(sk)) != olm_error()){ hex = e2e_meg_in_pickle(is); if(hex != NULL){ if(e2e_meg_in_save(s, room, sid, hex) == 0) rc = 0; free(hex); } }else fprintf(stderr, "chat: e2e: megolm import: %s\n", olm_inbound_group_session_last_error(is)); free(sk); } olm_clear_inbound_group_session(is); free(mem); return rc; } static char * e2e_meg_decrypt(const char *hex, const char *msg, char **newhex) { void *mem; OlmInboundGroupSession *is; size_t n; char *mc1, *mc2, *pt; char *out = NULL, *nh = NULL; uint32_t idx = 0; is = e2e_meg_in_unpickle(hex, &mem); if(is == NULL) return NULL; mc1 = strdup(msg); mc2 = strdup(msg); if(mc1 != NULL && mc2 != NULL){ n = olm_group_decrypt_max_plaintext_length(is, (uint8_t *)mc1, strlen(msg)); if(n != olm_error()){ pt = malloc(n + 1); if(pt != NULL){ n = olm_group_decrypt(is, (uint8_t *)mc2, strlen(msg), (uint8_t *)pt, n, &idx); pt[n] = '\0'; out = strdup(pt); nh = e2e_meg_in_pickle(is); free(pt); } }else fprintf(stderr, "chat: e2e: megolm dec: %s\n", olm_inbound_group_session_last_error(is)); } free(mc1); free(mc2); olm_clear_inbound_group_session(is); free(mem); if(out != NULL){ if(newhex != NULL) *newhex = nh; else free(nh); }else free(nh); return out; } #define E2E_TD_TYPES 8 static const char *e2e_td_type[E2E_TD_TYPES]; static size_t e2e_td_count[E2E_TD_TYPES]; static size_t e2e_td_total; static char *e2e_td_last_sender; static char *e2e_td_last_device; static char *e2e_td_last_type; static char * e2e_olm_session_for(Session *s, const char *user, const char *device, size_t mtype, const char *body_std) { const char *ph = e2e_olm_find(s, user, device); void *mem = NULL; OlmSession *os = NULL; OlmAccount *a = NULL; char *pt = NULL, *c; int open_acct = 0; if(ph != NULL){ os = e2e_olm_unpickle(ph, &mem); if(os != NULL && mtype == OLM_MESSAGE_TYPE_PRE_KEY){ c = strdup(body_std); if(c == NULL){ olm_clear_session(os); free(mem); os = NULL; mem = NULL; }else if(olm_matches_inbound_session(os, c, strlen(c)) != 1){ free(c); olm_clear_session(os); free(mem); os = NULL; mem = NULL; }else free(c); } } if(os == NULL){ a = e2e_acct_open(s->e2e_acct); if(a == NULL) return NULL; open_acct = 1; mem = malloc(olm_session_size()); if(mem == NULL){ e2e_acct_close(a); return NULL; } os = olm_session(mem); c = strdup(body_std); if(c == NULL){ olm_clear_session(os); free(mem); e2e_acct_close(a); return NULL; } if(olm_create_inbound_session(os, a, c, strlen(c)) == olm_error()){ fprintf(stderr, "chat: e2e: inbound: %s\n", olm_session_last_error(os)); free(c); olm_clear_session(os); free(mem); e2e_acct_close(a); return NULL; } free(c); } { size_t mlen; char *c1, *c2, *nh; c1 = strdup(body_std); c2 = strdup(body_std); if(c1 == NULL || c2 == NULL){ free(c1); free(c2); goto done; } mlen = olm_decrypt_max_plaintext_length(os, mtype, c1, strlen(c1)); if(mlen == olm_error()){ fprintf(stderr, "chat: e2e: olm decrypt: %s\n", olm_session_last_error(os)); free(c1); free(c2); goto done; } pt = malloc(mlen + 1); if(pt == NULL){ free(c1); free(c2); goto done; } if(olm_decrypt(os, mtype, c2, strlen(c2), pt, mlen) == olm_error()){ fprintf(stderr, "chat: e2e: olm decrypt: %s\n", olm_session_last_error(os)); free(pt); pt = NULL; }else{ pt[mlen] = '\0'; nh = e2e_olm_pickle(os); if(nh != NULL){ e2e_olm_save(s, user, device, nh); free(nh); } } free(c1); free(c2); } done: if(open_acct){ olm_remove_one_time_keys(a, os); e2e_acct_save(s, a); } if(os != NULL){ olm_clear_session(os); free(mem); } if(a != NULL) e2e_acct_close(a); return pt; } static size_t e2e_rkr_total; static void e2e_rkr_handle(Session *, const char *, const char *, struct json_object *); static void e2e_todevice_handle(Session *s, struct json_object *ev) { const char *type, *sender, *algo, *dev; struct json_object *content, *ct, *ent; char *ourcurve, *body_u, *body_std, *pt; size_t mtype; type = json_object_get_string(json_object_object_get(ev, "type")); sender = json_object_get_string(json_object_object_get(ev, "sender")); if(type == NULL || sender == NULL) return; if(strcmp(type, "m.room.encrypted") != 0) return; content = json_object_object_get(ev, "content"); if(content == NULL) return; algo = json_object_get_string(json_object_object_get( content, "algorithm")); if(algo == NULL || strcmp(algo, "m.olm.v1.curve25519-aes-sha2") != 0) return; dev = json_object_get_string(json_object_object_get( content, "device_id")); if(dev == NULL || dev[0] == '\0') return; ct = json_object_object_get(content, "ciphertext"); if(ct == NULL) return; ourcurve = e2e_our_curve(s); ent = ourcurve != NULL ? json_object_object_get(ct, ourcurve) : NULL; free(ourcurve); if(ent == NULL) return; mtype = (size_t)json_object_get_int( json_object_object_get(ent, "type")); body_u = strdup(json_object_get_string( json_object_object_get(ent, "body"))); if(body_u == NULL || body_u[0] == '\0'){ free(body_u); return; } body_std = b64std(body_u); free(body_u); if(body_std == NULL) return; pt = e2e_olm_session_for(s, sender, dev, mtype, body_std); free(body_std); if(pt == NULL) return; { struct json_object *o = json_tokener_parse(pt); const char *t2; free(pt); if(o == NULL) return; t2 = json_object_get_string(json_object_object_get(o, "type")); if(t2 != NULL && strcmp(t2, "m.room_key") == 0){ struct json_object *c = json_object_object_get( o, "content"); const char *room, *sid, *sk; room = c != NULL ? json_object_get_string( json_object_object_get(c, "room_id")) : NULL; sid = c != NULL ? json_object_get_string( json_object_object_get(c, "session_id")) : NULL; sk = c != NULL ? json_object_get_string( json_object_object_get(c, "session_key")) : NULL; if(room != NULL && sid != NULL && sk != NULL) e2e_meg_in_import(s, room, sid, sk); }else if(t2 != NULL && strcmp(t2, "m.room_key_request") == 0){ e2e_rkr_total++; e2e_rkr_handle(s, sender, dev, o); } json_object_put(o); } } static void e2e_todevice_ev(Session *s, struct json_object *ev) { const char *type, *sender, *dev; size_t i; type = json_object_get_string(json_object_object_get(ev, "type")); sender = json_object_get_string(json_object_object_get(ev, "sender")); if(type == NULL || sender == NULL) return; dev = json_object_get_string(json_object_object_get( json_object_object_get(ev, "content"), "device_id")); free(e2e_td_last_sender); free(e2e_td_last_device); free(e2e_td_last_type); e2e_td_last_sender = strdup(sender); e2e_td_last_type = strdup(type); e2e_td_last_device = dev != NULL ? strdup(dev) : NULL; for(i = 0; i < e2e_td_total && i < E2E_TD_TYPES; i++) if(strcmp(e2e_td_type[i], type) == 0){ e2e_td_count[i]++; e2e_todevice_handle(s, ev); return; } if(e2e_td_total < E2E_TD_TYPES){ e2e_td_type[e2e_td_total] = strdup(type); e2e_td_count[e2e_td_total] = 1; e2e_td_total++; } e2e_todevice_handle(s, ev); } #define E2E_CHANGED_MAX 64 static char *e2e_changed[E2E_CHANGED_MAX]; static size_t e2e_changed_n; static int e2e_qdone_has(const char *u) { size_t i; for(i = 0; i < e2e_qdone_n; i++) if(strcmp(e2e_qdone[i], u) == 0) return 1; return 0; } static void e2e_qdone_add(const char *u) { if(e2e_qdone_n < E2E_QMAX && !e2e_qdone_has(u)) e2e_qdone[e2e_qdone_n++] = strdup(u); } static void e2e_qdone_del(const char *u) { size_t i; for(i = 0; i < e2e_qdone_n; i++) if(strcmp(e2e_qdone[i], u) == 0){ free(e2e_qdone[i]); e2e_qdone[i] = e2e_qdone[--e2e_qdone_n]; return; } } static void e2e_devlist_changed(const char *user) { size_t i; if(user == NULL || user[0] == '\0') return; e2e_qdone_del(user); for(i = 0; i < e2e_changed_n; i++) if(strcmp(e2e_changed[i], user) == 0) return; if(e2e_changed_n < E2E_CHANGED_MAX){ e2e_changed[e2e_changed_n] = strdup(user); e2e_changed_n++; } } static int e2e_keys_query(Session *, const char *); static int e2e_keys_query_many(Session *, char *const *, size_t); static void e2e_query_changed(Session *); static void e2e_sync(Session *s, struct json_object *o) { struct json_object *dl, *arr; size_t i, n; dl = json_object_object_get(o, "device_lists"); arr = dl != NULL ? json_object_object_get(dl, "changed") : NULL; if(arr != NULL){ n = json_object_array_length(arr); for(i = 0; i < n; i++){ const char *u = json_object_get_string( json_object_array_get_idx(arr, i)); if(u != NULL) e2e_devlist_changed(u); } } dl = json_object_object_get(o, "to_device"); arr = dl != NULL ? json_object_object_get(dl, "events") : NULL; if(arr != NULL){ n = json_object_array_length(arr); for(i = 0; i < n; i++) e2e_todevice_ev(s, json_object_array_get_idx(arr, i)); } e2e_query_changed(s); } /* * matrix */ static char *urlencode(const char *); /* * name cache (rooms + display names) */ static char *c_key[NCACHE]; static char *c_val[NCACHE]; static int c_n; static const char * cget(const char *k) { int i; for(i = 0; i < c_n; i++) if(c_key[i] && strcmp(c_key[i], k) == 0) return c_val[i]; return NULL; } static void cput(const char *k, const char *v) { int i; if(cget(k) != NULL || v == NULL || v[0] == '\0') return; if(c_n >= NCACHE) return; for(i = 0; i < c_n; i++){ if(c_key[i] == NULL){ c_key[i] = strdup(k); c_val[i] = strdup(v); return; } } c_key[c_n] = strdup(k); c_val[c_n] = strdup(v); c_n++; } static char *cfgdir(void); static void backlog_add(const char *, const char *, const char *, long long); static void names_save(const char *cfgdir) { struct json_object *o; const char *sout; char *path; FILE *f; int i; o = json_object_new_object(); for(i = 0; i < c_n; i++){ if(c_key[i] == NULL) continue; if(c_key[i][0] != '!' && c_key[i][0] != '@') continue; json_object_object_add(o, c_key[i], json_object_new_string(c_val[i])); } sout = json_object_to_json_string(o); path = malloc(strlen(cfgdir) + 16); sprintf(path, "%s/names.json", cfgdir); if(dir_ok((char *)cfgdir)){ f = fopen(path, "w"); if(f != NULL){ fputs(sout, f); fputc('\n', f); fclose(f); } } free(path); json_object_put(o); } static void names_load(const char *cfgdir) { struct json_object *o; char *path, *data; FILE *f; long n, size = 0; path = malloc(strlen(cfgdir) + 16); sprintf(path, "%s/names.json", cfgdir); f = fopen(path, "r"); if(f == NULL){ free(path); return; } fseek(f, 0, SEEK_END); size = ftell(f); fseek(f, 0, SEEK_SET); data = malloc(size + 1); n = fread(data, 1, size, f); data[n] = '\0'; fclose(f); free(path); o = json_tokener_parse(data); free(data); if(o == NULL) return; json_object_object_foreach(o, k, v) { const char *s = json_object_get_string(v); if(s != NULL) cput(k, s); } json_object_put(o); } /* * room filter for -e (NULL = all rooms) */ static const char *g_filter; static int g_skip_backlog; static void mx_set_filter(const char *rid) { g_filter = rid; } static char * urlencode(const char *s) { CURL *c = curl_easy_init(); char *out; if(c == NULL) return NULL; out = curl_easy_escape(c, s, 0); curl_easy_cleanup(c); return out; } static char * resolve_room(const char *hs, const char *token, const char *rid) { char *e = urlencode(rid); char *url, *res, *out = NULL; long status; struct json_object *o, *c, *nm; url = malloc(strlen(hs) + strlen(e) + 96); snprintf(url, strlen(hs) + strlen(e) + 96, "%s/_matrix/client/v3/rooms/%s/state/m.room.name", hs, e); free(e); res = http_req("GET", url, token, NULL, &status, NULL); free(url); if(res == NULL || status != 200){ free(res); return NULL; } o = json_tokener_parse(res); free(res); if(o == NULL) return NULL; c = json_object_object_get(o, "content"); nm = c != NULL ? json_object_object_get(c, "name") : NULL; if(nm == NULL) nm = json_object_object_get(o, "name"); if(nm != NULL) out = strdup(json_object_get_string(nm)); json_object_put(o); return out; } static char * resolve_dn(const char *hs, const char *token, const char *mxid) { char *e = urlencode(mxid); char *url, *res, *out = NULL; long status; struct json_object *o, *dn; url = malloc(strlen(hs) + strlen(e) + 96); snprintf(url, strlen(hs) + strlen(e) + 96, "%s/_matrix/client/v3/profile/%s/displayname", hs, e); free(e); res = http_req("GET", url, token, NULL, &status, NULL); free(url); if(res == NULL || status != 200){ free(res); return NULL; } o = json_tokener_parse(res); free(res); if(o == NULL) return NULL; dn = json_object_object_get(o, "displayname"); if(dn != NULL && json_object_get_string(dn) != NULL && json_object_get_string(dn)[0] != '\0') out = strdup(json_object_get_string(dn)); json_object_put(o); return out; } #define E2E_ENCR_MAX 64 static struct { char *rid; int enc; } e2e_encr[E2E_ENCR_MAX]; static size_t e2e_encr_n; static int e2e_encr_known(const char *rid) { size_t i; for(i = 0; i < e2e_encr_n; i++) if(strcmp(e2e_encr[i].rid, rid) == 0) return e2e_encr[i].enc; return -1; } static void e2e_encr_set(const char *rid, int enc) { size_t i; for(i = 0; i < e2e_encr_n; i++) if(strcmp(e2e_encr[i].rid, rid) == 0){ e2e_encr[i].enc = enc; return; } if(e2e_encr_n >= E2E_ENCR_MAX){ free(e2e_encr[0].rid); e2e_encr[0] = e2e_encr[--e2e_encr_n]; } e2e_encr[e2e_encr_n].rid = strdup(rid); e2e_encr[e2e_encr_n].enc = enc; e2e_encr_n++; } static int e2e_room_encrypted(Session *s, const char *rid) { int k; char *e, *url, *res; long status; int enc = 0; size_t n; k = e2e_encr_known(rid); if(k >= 0) return k; if(s->token == NULL || s->token[0] == '\0') return 0; e = urlencode(rid); n = strlen(s->homeserver) + strlen(e) + 96; url = malloc(n); snprintf(url, n, "%s/_matrix/client/v3/rooms/%s/state/m.room.encrypted", s->homeserver, e); free(e); res = http_req("GET", url, s->token, NULL, &status, NULL); free(url); enc = (res != NULL && status == 200) ? 1 : 0; free(res); e2e_encr_set(rid, enc); return enc; } static int e2e_room_members(Session *s, const char *rid, char ***out) { char *e, *url, *res; struct json_object *o, *joined; long status; int n, k; char **us = NULL; size_t un; *out = NULL; e = urlencode(rid); un = strlen(s->homeserver) + strlen(e) + 96; url = malloc(un); snprintf(url, un, "%s/_matrix/client/v3/rooms/%s/joined_members", s->homeserver, e); free(e); res = http_req("GET", url, s->token, NULL, &status, NULL); free(url); if(res == NULL || status != 200){ free(res); return -1; } o = json_tokener_parse(res); free(res); if(o == NULL) return -1; joined = json_object_object_get(o, "joined"); if(joined != NULL){ n = (int)json_object_object_length(joined); if(n > 0){ us = calloc((size_t)n, sizeof *us); if(us != NULL){ k = 0; json_object_object_foreach(joined, u, v){ (void)v; us[k++] = strdup(u); } }else n = -1; } }else n = -1; json_object_put(o); *out = us; return n; } static char * e2e_roomkey_doc(const char *rid, const char *sid, const char *skey) { struct json_object *o, *c; char *out; o = json_object_new_object(); c = json_object_new_object(); json_object_object_add(c, "algorithm", json_object_new_string("m.megolm.v1.aes-sha2")); json_object_object_add(c, "room_id", json_object_new_string(rid)); json_object_object_add(c, "session_id", json_object_new_string(sid)); json_object_object_add(c, "session_key", json_object_new_string(skey)); json_object_object_add(o, "content", c); json_object_object_add(o, "type", json_object_new_string("m.room_key")); out = strdup(json_object_to_json_string(o)); json_object_put(o); return out; } static char * e2e_rkr_cancel_doc(const char *req_dev, const char *request_id) { struct json_object *o, *c; char *out; o = json_object_new_object(); c = json_object_new_object(); json_object_object_add(c, "action", json_object_new_string("request_cancellation")); json_object_object_add(c, "requesting_device_id", json_object_new_string(req_dev)); json_object_object_add(c, "request_id", json_object_new_string(request_id)); json_object_object_add(o, "content", c); json_object_object_add(o, "type", json_object_new_string("m.room_key_request")); out = strdup(json_object_to_json_string(o)); json_object_put(o); return out; } static int e2e_keys_handle(Session *s, const char *user, struct json_object *ud) { struct json_object *keys; int rc = -1; json_object_object_foreach(ud, devid, devobj2) { char *keyname, *idkey; const char *cu; keys = json_object_object_get(devobj2, "keys"); if(keys == NULL) continue; keyname = keyid("curve25519:", devid); if(keyname == NULL) continue; cu = json_object_get_string( json_object_object_get(keys, keyname)); free(keyname); if(cu == NULL) continue; idkey = b64std(cu); if(idkey != NULL){ e2e_olm_idkey_save(s, user, devid, idkey); free(idkey); rc = 0; } } return rc; } static int e2e_keys_query(Session *s, const char *user) { struct json_object *o, *dk, *ud; const char *body; char *url, *res; long status; int rc = -1; size_t n; if(e2e_qdone_has(user)) return 0; o = json_object_new_object(); dk = json_object_new_object(); ud = json_object_new_array(); json_object_object_add(dk, user, ud); json_object_object_add(o, "device_keys", dk); body = json_object_to_json_string(o); n = strlen(s->homeserver) + 64; url = malloc(n); snprintf(url, n, "%s/_matrix/client/v3/keys/query", s->homeserver); res = http_req("POST", url, s->token, body, &status, NULL); free(url); json_object_put(o); if(res == NULL || status != 200){ free(res); return -1; } o = json_tokener_parse(res); free(res); if(o == NULL) return -1; if(json_object_object_get_ex(o, "device_keys", &dk) && json_object_object_get_ex(dk, user, &ud)) rc = e2e_keys_handle(s, user, ud); json_object_put(o); e2e_qdone_add(user); return rc; } static int e2e_keys_query_many(Session *s, char *const *users, size_t nusers) { struct json_object *o, *dk; const char *body; char *url, *res; long status; size_t i; o = json_object_new_object(); dk = json_object_new_object(); for(i = 0; i < nusers; i++){ if(e2e_qdone_has(users[i])) continue; json_object_object_add(dk, users[i], json_object_new_array()); } json_object_object_add(o, "device_keys", dk); if(json_object_object_length(dk) == 0){ json_object_put(o); return 0; } body = json_object_to_json_string(o); url = malloc(strlen(s->homeserver) + 64); snprintf(url, strlen(s->homeserver) + 64, "%s/_matrix/client/v3/keys/query", s->homeserver); res = http_req("POST", url, s->token, body, &status, NULL); free(url); json_object_put(o); if(res == NULL || status != 200){ free(res); return -1; } o = json_tokener_parse(res); free(res); if(o == NULL) return -1; for(i = 0; i < nusers; i++){ struct json_object *ud; if(e2e_qdone_has(users[i])) continue; if(json_object_object_get_ex(o, "device_keys", &dk) && json_object_object_get_ex(dk, users[i], &ud)) e2e_keys_handle(s, users[i], ud); e2e_qdone_add(users[i]); } json_object_put(o); return 0; } static void e2e_query_changed(Session *s) { size_t i; for(i = 0; i < e2e_changed_n; i++){ if(e2e_keys_query(s, e2e_changed[i]) != 0) free(e2e_changed[i]); } e2e_changed_n = 0; } typedef struct { char *user; char *device; char *otk; } OtkRec; #define E2E_OTK_MAX 64 static OtkRec e2e_otk[E2E_OTK_MAX]; static size_t e2e_otk_n; static void e2e_otk_drop(const char *user, const char *device) { size_t i; for(i = 0; i < e2e_otk_n; i++) if(strcmp(e2e_otk[i].user, user) == 0 && strcmp(e2e_otk[i].device, device) == 0){ free(e2e_otk[i].user); free(e2e_otk[i].device); free(e2e_otk[i].otk); e2e_otk[i] = e2e_otk[--e2e_otk_n]; return; } } static char * e2e_otk_claim(Session *s, const char *user, const char *device) { size_t i, n; char *url, *res, *uk, *out = NULL; struct json_object *o, *otk, *ud, *dv, *kobj; const char *body, *keyval; long status; for(i = 0; i < e2e_otk_n; i++) if(strcmp(e2e_otk[i].user, user) == 0 && strcmp(e2e_otk[i].device, device) == 0) return strdup(e2e_otk[i].otk); o = json_object_new_object(); otk = json_object_new_object(); ud = json_object_new_object(); dv = json_object_new_array(); json_object_array_add(dv, json_object_new_string("signed_curve25519")); json_object_object_add(ud, device, dv); json_object_object_add(otk, user, ud); json_object_object_add(o, "one_time_keys", otk); body = json_object_to_json_string(o); n = strlen(s->homeserver) + 64; url = malloc(n); snprintf(url, n, "%s/_matrix/client/v3/keys/claim", s->homeserver); res = http_req("POST", url, s->token, body, &status, NULL); free(url); json_object_put(o); if(res == NULL || status != 200){ free(res); return NULL; } o = json_tokener_parse(res); free(res); if(o == NULL) return NULL; if(json_object_object_get_ex(o, "one_time_keys", &otk) && json_object_object_get_ex(otk, user, &ud) && json_object_object_get_ex(ud, device, &dv) && json_object_object_length(dv) > 0){ struct json_object_iterator it = json_object_iter_begin(dv); struct json_object_iterator ite = json_object_iter_end(dv); if(!json_object_iter_equal(&it, &ite)){ kobj = json_object_iter_peek_value(&it); keyval = json_object_get_string( json_object_object_get(kobj, "key")); if(keyval != NULL){ uk = b64std(keyval); if(uk != NULL){ out = uk; if(e2e_otk_n < E2E_OTK_MAX){ e2e_otk[e2e_otk_n].user = strdup(user); e2e_otk[e2e_otk_n].device = strdup(device); e2e_otk[e2e_otk_n].otk = strdup(uk); if(e2e_otk[e2e_otk_n].user == NULL || e2e_otk[e2e_otk_n].device == NULL || e2e_otk[e2e_otk_n].otk == NULL) e2e_otk_drop(user, device); else e2e_otk_n++; } } } } } json_object_put(o); return out; } #define E2E_RKR_RING 32 static char *e2e_rkr_ring[E2E_RKR_RING]; static size_t e2e_rkr_n; static size_t e2e_rkr_pos; static int e2e_rkr_seen(const char *key) { size_t i; for(i = 0; i < e2e_rkr_n; i++) if(strcmp(e2e_rkr_ring[i], key) == 0) return 1; return 0; } static void e2e_rkr_mark(const char *key) { if(e2e_rkr_seen(key)) return; if(e2e_rkr_n < E2E_RKR_RING){ e2e_rkr_ring[e2e_rkr_n++] = strdup(key); return; } free(e2e_rkr_ring[e2e_rkr_pos]); e2e_rkr_ring[e2e_rkr_pos] = strdup(key); e2e_rkr_pos = (e2e_rkr_pos + 1) % E2E_RKR_RING; } static int e2e_td_add(Session *s, struct json_object *msg, const char *ourcurve, const char *user, const char *dev, const char *pickle_hex, const char *doc) { char *cipher_url, *nh = NULL; int mtype; struct json_object *userobj, *devobj, *cipherobj, *entry; int rc = -1; cipher_url = e2e_olm_wrap(pickle_hex, doc, &nh, &mtype); if(cipher_url != NULL){ entry = json_object_new_object(); json_object_object_add(entry, "type", json_object_new_int(mtype)); json_object_object_add(entry, "body", json_object_new_string(cipher_url)); cipherobj = json_object_new_object(); json_object_object_add(cipherobj, ourcurve, entry); devobj = json_object_new_object(); json_object_object_add(devobj, "algorithm", json_object_new_string("m.olm.v1.curve25519-aes-sha2")); json_object_object_add(devobj, "sender_key", json_object_new_string(ourcurve)); json_object_object_add(devobj, "ciphertext", cipherobj); userobj = json_object_object_get(msg, user); if(userobj == NULL){ userobj = json_object_new_object(); json_object_object_add(msg, user, userobj); } json_object_object_add(userobj, dev, devobj); if(nh != NULL){ e2e_olm_save(s, user, dev, nh); free(nh); } rc = 0; } free(cipher_url); return rc; } static void e2e_td_send(Session *s, struct json_object *msg) { const char *sbody; char *url, *txn, *res; long status; size_t un; sbody = json_object_to_json_string(msg); txn = malloc(64); snprintf(txn, 64, "chat%ld%ld", (long)getpid(), (long)time(NULL)); un = strlen(s->homeserver) + strlen(txn) + 80; url = malloc(un); snprintf(url, un, "%s/_matrix/client/v3/sendToDevice/m.room.encrypted/%s", s->homeserver, txn); res = http_req("PUT", url, s->token, sbody, &status, NULL); free(url); free(txn); free(res); } static void e2e_rkr_handle(Session *s, const char *sender, const char *dev, struct json_object *o) { struct json_object *c, *b; const char *action, *room, *sid, *request_id, *req_dev; MegolmRec *mr; char *skey, *dock, *docc, *keyname, *ourcurve; const char *pickle_hex; struct json_object *msg; int sent = 0; c = json_object_object_get(o, "content"); action = c != NULL ? json_object_get_string( json_object_object_get(c, "action")) : NULL; if(action == NULL || strcmp(action, "request") != 0) return; b = c != NULL ? json_object_object_get(c, "body") : NULL; room = b != NULL ? json_object_get_string( json_object_object_get(b, "room_id")) : NULL; sid = b != NULL ? json_object_get_string( json_object_object_get(b, "session_id")) : NULL; request_id = c != NULL ? json_object_get_string( json_object_object_get(c, "request_id")) : NULL; req_dev = c != NULL ? json_object_get_string( json_object_object_get(c, "requesting_device_id")) : NULL; if(room == NULL || sid == NULL || request_id == NULL) return; mr = e2e_meg_out_find(s, room); if(mr == NULL || mr->sid == NULL || strcmp(mr->sid, sid) != 0){ return; } keyname = malloc(strlen(sender) + strlen(room) + strlen(sid) + 4); snprintf(keyname, strlen(sender) + strlen(room) + strlen(sid) + 4, "%s:%s:%s", sender, room, sid); if(e2e_rkr_seen(keyname)){ free(keyname); return; } skey = e2e_meg_key(mr->pickle); if(skey == NULL){ free(keyname); return; } dock = e2e_roomkey_doc(room, sid, skey); free(skey); docc = e2e_rkr_cancel_doc(req_dev != NULL ? req_dev : dev, request_id); if(dock == NULL || docc == NULL){ free(dock); free(docc); free(keyname); return; } pickle_hex = e2e_olm_find(s, sender, dev); if(pickle_hex == NULL){ OlmRec *rec; char *otk; if(e2e_keys_query(s, sender) != 0){ free(dock); free(docc); free(keyname); return; } rec = e2e_olm_rec(s, sender, dev); if(rec == NULL || rec->idkey == NULL){ free(dock); free(docc); free(keyname); return; } otk = e2e_otk_claim(s, sender, dev); if(otk == NULL){ free(dock); free(docc); free(keyname); return; } pickle_hex = e2e_olm_new_outbound(s->e2e_acct, rec->idkey, otk); free(otk); if(pickle_hex == NULL){ free(dock); free(docc); free(keyname); return; } e2e_olm_save(s, sender, dev, pickle_hex); free((char *)pickle_hex); pickle_hex = e2e_olm_find(s, sender, dev); } if(pickle_hex == NULL){ free(dock); free(docc); free(keyname); return; } ourcurve = e2e_our_curve(s); if(ourcurve == NULL){ free(dock); free(docc); free(keyname); return; } msg = json_object_new_object(); if(e2e_td_add(s, msg, ourcurve, sender, dev, pickle_hex, dock) == 0){ e2e_td_send(s, msg); sent++; } json_object_put(msg); pickle_hex = e2e_olm_find(s, sender, dev); msg = json_object_new_object(); if(pickle_hex != NULL && e2e_td_add(s, msg, ourcurve, sender, dev, pickle_hex, docc) == 0){ e2e_td_send(s, msg); sent++; } json_object_put(msg); free(dock); free(docc); free(ourcurve); if(sent > 0){ e2e_rkr_mark(keyname); } free(keyname); } typedef struct { char *room; char *sid; } SharedRec; #define E2E_SHARED_MAX 32 static SharedRec e2e_shared[E2E_SHARED_MAX]; static size_t e2e_shared_n; static int e2e_shared_take(const char *room, const char *sid) { size_t i; for(i = 0; i < e2e_shared_n; i++) if(strcmp(e2e_shared[i].room, room) == 0 && strcmp(e2e_shared[i].sid, sid) == 0) return 0; if(e2e_shared_n < E2E_SHARED_MAX){ e2e_shared[e2e_shared_n].room = strdup(room); e2e_shared[e2e_shared_n].sid = strdup(sid); if(e2e_shared[e2e_shared_n].room != NULL && e2e_shared[e2e_shared_n].sid != NULL) e2e_shared_n++; } return 1; } static int e2e_share_roomkey(Session *s, const char *rid, const char *sid, const char *skey, int to_all) { char **users = NULL; int nusers, sent = 0, i; char *doc, *ourcurve; struct json_object *msg, *userobj, *devobj, *cipherobj, *entry; char *url, *txn, *res; long status; size_t un; nusers = e2e_room_members(s, rid, &users); if(nusers <= 0){ for(i = 0; i < nusers && users != NULL; i++) free(users[i]); free(users); return 0; } doc = e2e_roomkey_doc(rid, sid, skey); ourcurve = e2e_our_curve(s); msg = json_object_new_object(); if(doc == NULL || ourcurve == NULL || msg == NULL){ free(doc); free(ourcurve); if(msg != NULL) json_object_put(msg); for(i = 0; i < nusers; i++) free(users[i]); free(users); return 0; } e2e_keys_query_many(s, users, (size_t)nusers); for(i = 0; i < nusers; i++){ const char *u = users[i]; size_t k; if(strcmp(u, s->user) == 0) continue; for(k = 0; k < s->e2e_olms_n; k++){ OlmRec *rec = &s->e2e_olms[k]; const char *pickle_hex; char *nh, *cipher_url; int mtype; if(strcmp(rec->user, u) != 0 || rec->idkey == NULL) continue; if(strcmp(u, s->user) == 0 && strcmp(rec->device, s->e2e_devid) == 0) continue; pickle_hex = rec->pickle; if(pickle_hex == NULL){ char *otk = e2e_otk_claim(s, u, rec->device); if(otk == NULL){ continue; } pickle_hex = e2e_olm_new_outbound( s->e2e_acct, rec->idkey, otk); free(otk); if(pickle_hex == NULL){ fprintf(stderr, "[e2e] no session %s %s\n", u, rec->device); e2e_otk_drop(u, rec->device); continue; } e2e_olm_save(s, u, rec->device, pickle_hex); free((char *)pickle_hex); pickle_hex = e2e_olm_find(s, u, rec->device); } if(pickle_hex == NULL) continue; if(!to_all && rec->pickle != NULL) continue; cipher_url = e2e_olm_wrap(pickle_hex, doc, &nh, &mtype); if(cipher_url == NULL) continue; if(nh != NULL){ e2e_olm_save(s, u, rec->device, nh); free(nh); } entry = json_object_new_object(); json_object_object_add(entry, "type", json_object_new_int(mtype)); json_object_object_add(entry, "body", json_object_new_string(cipher_url)); cipherobj = json_object_new_object(); json_object_object_add(cipherobj, ourcurve, entry); devobj = json_object_new_object(); json_object_object_add(devobj, "algorithm", json_object_new_string( "m.olm.v1.curve25519-aes-sha2")); json_object_object_add(devobj, "sender_key", json_object_new_string(ourcurve)); json_object_object_add(devobj, "ciphertext", cipherobj); userobj = json_object_object_get(msg, u); if(userobj == NULL){ userobj = json_object_new_object(); json_object_object_add(msg, u, userobj); } json_object_object_add(userobj, rec->device, devobj); free(cipher_url); sent++; } } free(doc); free(ourcurve); for(i = 0; i < nusers; i++) free(users[i]); free(users); if(sent > 0){ const char *sbody = json_object_to_json_string(msg); txn = malloc(64); snprintf(txn, 64, "chat%ld%ld%d", (long)getpid(), (long)time(NULL), sent); un = strlen(s->homeserver) + strlen(txn) + 80; url = malloc(un); snprintf(url, un, "%s/_matrix/client/v3/sendToDevice/" "m.room.encrypted/%s", s->homeserver, txn); res = http_req("PUT", url, s->token, sbody, &status, NULL); free(url); free(txn); free(res); } json_object_put(msg); return sent; } static int e2e_send_json(Session *s, const char *rid, struct json_object *ev) { MegolmRec *mr; char *cipher_std, *cipher_url = NULL, *newhex = NULL, *nskey; char *curve = NULL, *rid_e, *url, *txn, *res = NULL; struct json_object *body = NULL; const char *sbody; long status; size_t un; int rc = -1, need_all; if(s->e2e_acct == NULL || s->e2e_acct[0] == '\0') return -1; mr = e2e_meg_out_find(s, rid); if(mr == NULL){ if(e2e_meg_out_new(s, rid) != 0) return -1; mr = e2e_meg_out_find(s, rid); if(mr == NULL) return -1; } need_all = e2e_shared_take(rid, mr->sid); e2e_share_roomkey(s, rid, mr->sid, mr->skey, need_all); sbody = json_object_to_json_string(ev); cipher_std = e2e_meg_encrypt(mr->pickle, sbody, &newhex); if(cipher_std == NULL) return -1; cipher_url = b64url(cipher_std); free(cipher_std); if(cipher_url == NULL){ free(newhex); return -1; } nskey = e2e_meg_key(newhex); curve = e2e_our_curve(s); if(newhex != NULL && nskey != NULL && curve != NULL){ e2e_meg_out_save(s, rid, mr->sid, newhex, nskey); body = json_object_new_object(); json_object_object_add(body, "algorithm", json_object_new_string("m.megolm.v1.aes-sha2")); json_object_object_add(body, "sender_key", json_object_new_string(curve)); json_object_object_add(body, "session_id", json_object_new_string(mr->sid)); json_object_object_add(body, "ciphertext", json_object_new_string(cipher_url)); sbody = json_object_to_json_string(body); rid_e = urlencode(rid); txn = malloc(64); snprintf(txn, 64, "chat%ld%ld", (long)getpid(), (long)time(NULL)); un = strlen(s->homeserver) + strlen(rid_e) + strlen(txn) + 96; url = malloc(un); snprintf(url, un, "%s/_matrix/client/v3/rooms/%s/send/" "m.room.encrypted/%s", s->homeserver, rid_e, txn); res = http_req("PUT", url, s->token, sbody, &status, NULL); free(url); free(txn); free(rid_e); free(res); if(status == 200) rc = 0; } free(cipher_url); free(newhex); free(nskey); free(curve); if(body != NULL) json_object_put(body); return rc; } static int e2e_send_text(Session *s, const char *rid, const char *text) { struct json_object *body, *ev; int rc; body = json_object_new_object(); json_object_object_add(body, "msgtype", json_object_new_string("m.text")); json_object_object_add(body, "body", json_object_new_string(text)); ev = json_object_new_object(); json_object_object_add(ev, "type", json_object_new_string("m.room.message")); json_object_object_add(ev, "content", body); rc = e2e_send_json(s, rid, ev); json_object_put(ev); return rc; } static char e2e_kr_last[256]; static int e2e_kr_quota; static void e2e_meg_keyreq(Session *s, const char *rid, const char *sender, const char *sid) { struct json_object *body, *bbody, *userobj, *devobj, *msg, *arr; const char *sbody; char *url, *txn; long status; size_t n; if(s->e2e_devid == NULL || rid == NULL || sender == NULL || sid == NULL) return; if(e2e_kr_last[0] != '\0' && strcmp(e2e_kr_last, sid) == 0) return; if(e2e_kr_quota <= 0) return; e2e_kr_quota--; strncpy(e2e_kr_last, sid, sizeof(e2e_kr_last) - 1); e2e_kr_last[sizeof(e2e_kr_last) - 1] = '\0'; bbody = json_object_new_object(); json_object_object_add(bbody, "algorithm", json_object_new_string("m.megolm.v1.aes-sha2")); json_object_object_add(bbody, "room_id", json_object_new_string(rid)); json_object_object_add(bbody, "session_id", json_object_new_string(sid)); body = json_object_new_object(); json_object_object_add(body, "action", json_object_new_string("request")); json_object_object_add(body, "body", json_object_get(bbody)); json_object_object_add(body, "requesting_device_id", json_object_new_string(s->e2e_devid ? s->e2e_devid : "")); devobj = json_object_new_object(); arr = json_object_new_array(); json_object_array_add(arr, json_object_get(body)); json_object_object_add(devobj, "*", arr); userobj = json_object_new_object(); json_object_object_add(userobj, sender, devobj); msg = json_object_new_object(); json_object_object_add(msg, "messages", userobj); sbody = json_object_to_json_string(msg); txn = malloc(64); snprintf(txn, 64, "chat%ld%ld%d", (long)getpid(), (long)time(NULL), (int)(strlen(sid) % 997)); n = strlen(s->homeserver) + strlen(txn) + 64; url = malloc(n); snprintf(url, n, "%s/_matrix/client/v3/sendToDevice/" "m.room_key_request/%s", s->homeserver, txn); http_req("PUT", url, s->token, sbody, &status, NULL); free(url); free(txn); json_object_put(msg); json_object_put(bbody); } static char * e2e_meg_event_body(Session *s, const char *rid, struct json_object *ev) { struct json_object *content, *c, *cc, *o; const char *algo, *sid, *cipher_u, *mt; MegolmRec *rec; char *cipher_std, *pt, *newhex, *out = NULL; content = json_object_object_get(ev, "content"); if(content == NULL) return NULL; algo = json_object_get_string(json_object_object_get( content, "algorithm")); if(algo == NULL || strcmp(algo, "m.megolm.v1.aes-sha2") != 0) return NULL; sid = json_object_get_string(json_object_object_get( content, "session_id")); cipher_u = json_object_get_string(json_object_object_get( content, "ciphertext")); if(sid == NULL || cipher_u == NULL) return NULL; rec = e2e_meg_in_find(s, rid, sid); if(rec == NULL){ const char *sender = json_object_get_string( json_object_object_get(ev, "sender")); if(sender == NULL) sender = ""; e2e_meg_keyreq(s, rid, sender, sid); return NULL; } cipher_std = b64std(cipher_u); if(cipher_std == NULL) return NULL; pt = e2e_meg_decrypt(rec->pickle, cipher_std, &newhex); free(cipher_std); if(pt == NULL) return NULL; if(newhex != NULL){ e2e_meg_in_save(s, rid, sid, newhex); free(newhex); } o = json_tokener_parse(pt); free(pt); if(o == NULL) return NULL; c = json_object_object_get(o, "content"); if(strcmp(json_object_get_string(json_object_object_get(o, "type")), "m.room.message") != 0 || c == NULL){ json_object_put(o); return NULL; } { const char *rt = json_object_get_string(json_object_object_get( json_object_object_get(c, "m.relates_to"), "rel_type")); if(rt != NULL){ json_object_put(o); return NULL; } } cc = json_object_object_get(c, "body"); if(cc == NULL){ json_object_put(o); return NULL; } mt = json_object_get_string(json_object_object_get(c, "msgtype")); if(mt != NULL && (strcmp(mt, "m.image") == 0 || strcmp(mt, "m.video") == 0)) out = strdup("[Image/Video sent - chat -d to save]"); else out = strdup(json_object_get_string(cc)); json_object_put(o); return out; } static int b64v(char c) { if(c >= 'A' && c <= 'Z') return c - 'A'; if(c >= 'a' && c <= 'z') return c - 'a' + 26; if(c >= '0' && c <= '9') return c - '0' + 52; if(c == '+' || c == '-') return 62; if(c == '/' || c == '_') return 63; return -1; } static size_t b64dec(const char *in, unsigned char *out, size_t max) { size_t n = strlen(in), i, k = 0; int acc = 0, bits = 0; for(i = 0; i < n; i++){ int v; if(in[i] == '=') break; v = b64v(in[i]); if(v < 0) continue; acc = (acc << 6) | v; bits += 6; if(bits >= 8){ bits -= 8; if(k < max) out[k++] = (unsigned char)((acc >> bits) & 0xff); } } return k; } static char * b64enc(const unsigned char *d, size_t n) { size_t m = 4 * ((n + 2) / 3) + 1; char *out; int r; out = malloc(m); if(out == NULL) return NULL; r = EVP_EncodeBlock((unsigned char *)out, d, (int)n); if(r < 0){ free(out); return NULL; } out[r] = '\0'; return out; } static char * b64uenc(const unsigned char *d, size_t n) { char *b, *u; b = b64enc(d, n); if(b == NULL) return NULL; u = b64url(b); free(b); return u; } static int e2e_att_encrypt(const unsigned char *data, size_t n, const char *mime, struct json_object **fileo, unsigned char **ct_out, size_t *ctlen_out) { unsigned char k[32], iv[16], aeskey[32], md[EVP_MAX_MD_SIZE], sh[EVP_MAX_MD_SIZE]; unsigned int mdlen = 0, shlen = 0; unsigned char *ct; int clen = 0, flen = 0; EVP_CIPHER_CTX *ctx; char *b64ct, *macb, *ku, *ivu, *hu; struct json_object *o, *h, *keyo, *ops; size_t tot; int rc = -1; *fileo = NULL; *ct_out = NULL; *ctlen_out = 0; if(n > 0x7fffffff || getrandom(k, sizeof k, 0) != (ssize_t)sizeof k || getrandom(iv, sizeof iv, 0) != (ssize_t)sizeof iv) return -1; memcpy(aeskey, k, 16); memset(aeskey + 16, 0, 16); ct = malloc(n + EVP_MAX_BLOCK_LENGTH); if(ct == NULL) return -1; ctx = EVP_CIPHER_CTX_new(); if(ctx == NULL){ free(ct); return -1; } if(EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, aeskey, iv) != 1 || EVP_EncryptUpdate(ctx, ct, &clen, data, (int)n) != 1 || EVP_EncryptFinal_ex(ctx, ct + clen, &flen) != 1){ EVP_CIPHER_CTX_free(ctx); free(ct); return -1; } EVP_CIPHER_CTX_free(ctx); tot = (size_t)clen + (size_t)flen; b64ct = b64enc(ct, tot); if(b64ct == NULL){ free(ct); return -1; } if(HMAC(EVP_sha256(), k + 16, 16, (const unsigned char *)b64ct, strlen(b64ct), md, &mdlen) == NULL){ free(b64ct); free(ct); return -1; } macb = b64uenc(md, mdlen); EVP_Digest(ct, tot, sh, &shlen, EVP_sha256(), NULL); ku = b64uenc(k, sizeof k); ivu = b64uenc(iv, sizeof iv); hu = b64uenc(sh, shlen); if(macb != NULL && ku != NULL && ivu != NULL && hu != NULL){ o = json_object_new_object(); keyo = json_object_new_object(); ops = json_object_new_array(); json_object_array_add(ops, json_object_new_string("encrypt")); json_object_object_add(keyo, "kty", json_object_new_string("oct")); json_object_object_add(keyo, "key_ops", ops); json_object_object_add(keyo, "alg", json_object_new_string("A264")); json_object_object_add(keyo, "k", json_object_new_string(ku)); json_object_object_add(keyo, "ext", json_object_new_boolean(1)); json_object_object_add(o, "key", keyo); json_object_object_add(o, "iv", json_object_new_string(ivu)); h = json_object_new_object(); json_object_object_add(h, "sha256", json_object_new_string(hu)); json_object_object_add(o, "hashes", h); json_object_object_add(o, "mac", json_object_new_string(macb)); json_object_object_add(o, "v", json_object_new_int(2)); json_object_object_add(o, "algorithm", json_object_new_string("AES-256-CBC")); if(mime != NULL) json_object_object_add(o, "mime_type", json_object_new_string(mime)); json_object_object_add(o, "size", json_object_new_int64((int64_t)n)); if(o != NULL){ *fileo = o; *ct_out = ct; *ctlen_out = tot; rc = 0; ct = NULL; }else json_object_put(o); } free(macb); free(ku); free(ivu); free(hu); free(b64ct); free(ct); return rc; } static UNUSED unsigned char * e2e_att_decrypt(const struct json_object *fileo, const unsigned char *ct, size_t ctlen, size_t *outlen) { struct json_object *ko, *kk; const char *keys, *ivs, *macs; unsigned char k[64], iv[32], aeskey[32], md[EVP_MAX_MD_SIZE], mac[EVP_MAX_MD_SIZE]; size_t kn, ivn, macn; unsigned int mdlen = 0; char *b64ct, *macb; unsigned char *pt = NULL; int plen = 0, flen = 0; EVP_CIPHER_CTX *ctx; int ok = 0; *outlen = 0; if(fileo == NULL || ct == NULL) return NULL; ko = json_object_object_get(fileo, "key"); if(ko == NULL) return NULL; if(json_object_get_type(ko) == json_type_object){ kk = json_object_object_get(ko, "k"); if(kk == NULL) return NULL; keys = json_object_get_string(kk); }else keys = json_object_get_string(ko); ivs = json_object_get_string(json_object_object_get(fileo, "iv")); macs = json_object_get_string(json_object_object_get(fileo, "mac")); if(keys == NULL || ivs == NULL || macs == NULL) return NULL; kn = b64dec(keys, k, sizeof k); ivn = b64dec(ivs, iv, sizeof iv); if(kn != 32 || ivn != 16) return NULL; b64ct = b64enc(ct, ctlen); if(b64ct == NULL) return NULL; if(HMAC(EVP_sha256(), k + 16, 16, (const unsigned char *)b64ct, strlen(b64ct), md, &mdlen) == NULL){ free(b64ct); return NULL; } macb = b64enc(md, mdlen); macn = 0; if(macb != NULL){ macn = b64dec(macs, mac, sizeof mac); if(macn == mdlen && memcmp(mac, md, mdlen) == 0) ok = 1; free(macb); } free(b64ct); if(!ok) return NULL; memcpy(aeskey, k, 16); memset(aeskey + 16, 0, 16); pt = malloc(ctlen + 1); if(pt == NULL) return NULL; ctx = EVP_CIPHER_CTX_new(); if(ctx == NULL){ free(pt); return NULL; } if(EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, aeskey, iv) != 1 || EVP_DecryptUpdate(ctx, pt, &plen, ct, (int)ctlen) != 1 || EVP_DecryptFinal_ex(ctx, pt + plen, &flen) != 1){ EVP_CIPHER_CTX_free(ctx); free(pt); return NULL; } EVP_CIPHER_CTX_free(ctx); *outlen = (size_t)plen + (size_t)flen; return pt; } static int e2e_ensure(Session *s) { if(s->token == NULL || s->token[0] == '\0' || s->e2e_devid == NULL) return -1; if(s->e2e_acct == NULL || s->e2e_acct[0] == '\0'){ if(e2e_setup(s) != 0) return -1; } return e2e_publish_keys(s); } static void cache_state(const char *rid, struct json_object *events) { size_t i, n; if(events == NULL) return; n = json_object_array_length(events); for(i = 0; i < n; i++){ struct json_object *ev = json_object_array_get_idx(events, i); const char *t = json_object_get_string( json_object_object_get(ev, "type")); if(t == NULL) continue; if(strcmp(t, "m.room.name") == 0){ struct json_object *c = json_object_object_get(ev, "content"); struct json_object *nm = c != NULL ? json_object_object_get(c, "name") : NULL; if(nm != NULL) cput(rid, json_object_get_string(nm)); }else if(strcmp(t, "m.room.member") == 0){ const char *sk = json_object_get_string( json_object_object_get(ev, "state_key")); struct json_object *c = json_object_object_get(ev, "content"); struct json_object *dn = c != NULL ? json_object_object_get(c, "displayname") : NULL; if(sk != NULL && dn != NULL) cput(sk, json_object_get_string(dn)); }else if(strcmp(t, "m.room.encrypted") == 0) e2e_encr_set(rid, 1); } } static const char * room_disp(const char *hs, const char *token, const char *rid) { const char *n = cget(rid); if(n != NULL) return n; { char *r = resolve_room(hs, token, rid); if(r != NULL){ cput(rid, r); free(r); return cget(rid); } } return rid; } static const char * user_disp(const char *hs, const char *token, const char *mxid) { const char *n = cget(mxid); if(n != NULL) return n; { char *r = resolve_dn(hs, token, mxid); if(r != NULL){ cput(mxid, r); free(r); return cget(mxid); } } return mxid; } static char * mx_login(const char *hs, const char *user, const char *pass, long *st) { struct json_object *body; const char *sbody; char *res, *url; long status; size_t hslen = strlen(hs); body = json_object_new_object(); json_object_object_add(body, "type", json_object_new_string("m.login.password")); { struct json_object *id = json_object_new_object(); json_object_object_add(id, "type", json_object_new_string("m.id.user")); json_object_object_add(id, "user", json_object_new_string(user)); json_object_object_add(body, "identifier", id); } json_object_object_add(body, "password", json_object_new_string(pass)); json_object_object_add(body, "initial_device_display_name", json_object_new_string("chat")); sbody = json_object_to_json_string(body); url = malloc(hslen + 32); snprintf(url, hslen + 32, "%s/_matrix/client/v3/login", hs); res = http_req("POST", url, NULL, sbody, &status, NULL); free(url); json_object_put(body); if(st != NULL) *st = status; return res; } static double mono_sec(void) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (double)ts.tv_sec + (double)ts.tv_nsec / 1e9; } static char * mx_rooms(const char *hs, const char *token, const char *since, char **since_out) { const char *flt = "{\"room\":{\"timeline\":{\"limit\":0}," "\"state\":{\"limit\":50},\"account_data\":{\"limit\":0}}," "\"presence\":{\"limit\":0}}"; struct json_object *o; char *url, *res; if(since != NULL && since[0] != '\0'){ char *e = urlencode(since); size_t n = strlen(hs) + strlen(flt) + strlen(e) + 96; url = malloc(n); snprintf(url, n, "%s/_matrix/client/v3/sync?timeout=0&filter=%s&since=%s", hs, flt, e); free(e); }else{ size_t n = strlen(hs) + strlen(flt) + 64; url = malloc(n); snprintf(url, n, "%s/_matrix/client/v3/sync?timeout=0&filter=%s", hs, flt); } { double t0 = mono_sec(); res = http_req("GET", url, token, NULL, NULL, NULL); } free(url); if(res != NULL){ o = json_tokener_parse(res); if(o != NULL){ struct json_object *nb = json_object_object_get(o, "next_batch"); struct json_object *rooms, *join; if(nb != NULL && since_out != NULL) *since_out = strdup(json_object_get_string(nb)); rooms = json_object_object_get(o, "rooms"); join = rooms != NULL ? json_object_object_get(rooms, "join") : NULL; if(join != NULL){ json_object_object_foreach(join, rid, roomval){ struct json_object *st = json_object_object_get(roomval, "state"); cache_state(rid, st != NULL ? json_object_object_get(st, "events") : NULL); } } json_object_put(o); }else{ free(res); res = NULL; } } return res; } static char *mx_joined_rooms(const char *, const char *); static char * mx_first_room(const char *hs, const char *token) { char *res = mx_joined_rooms(hs, token); char *rid = NULL; if(res != NULL){ struct json_object *o = json_tokener_parse(res); if(o != NULL){ struct json_object *arr; if(json_object_object_get_ex(o, "joined_rooms", &arr) && json_object_is_type(arr, json_type_array) && json_object_array_length(arr) > 0){ const char *k = json_object_get_string( json_object_array_get_idx(arr, 0)); if(k) rid = strdup(k); } json_object_put(o); } free(res); } return rid; } static char * room_name_for(struct json_object *join) { struct json_object *state, *events, *ev, *contento, *nameo; size_t i, n; state = json_object_object_get(join, "state"); if(state == NULL) return NULL; events = json_object_object_get(state, "events"); if(events == NULL) return NULL; n = json_object_array_length(events); for(i = 0; i < n; i++){ ev = json_object_array_get_idx(events, i); if(strcmp(json_object_get_string(json_object_object_get(ev, "type")), "m.room.name") != 0) continue; contento = json_object_object_get(ev, "content"); nameo = json_object_object_get(contento, "name"); if(nameo != NULL) return strdup(json_object_get_string(nameo)); } return NULL; } static char * mx_joined_rooms(const char *hs, const char *token) { char *url, *res; long status; url = malloc(strlen(hs) + 48); snprintf(url, strlen(hs) + 48, "%s/_matrix/client/v3/joined_rooms", hs); res = http_req("GET", url, token, NULL, &status, NULL); free(url); if(res == NULL || status != 200){ free(res); return NULL; } return res; } static const char * name_of(const char *hs, const char *token, const char *rid) { const char *n = cget(rid); if(n != NULL) return n; n = resolve_room(hs, token, rid); if(n != NULL){ cput(rid, n); free((char *)n); } return cget(rid); } static void mx_dump_rooms(const char *json) { struct json_object *o, *join, *rooms; char **names; size_t i, n, k; o = json_tokener_parse(json); if(o == NULL){ fprintf(stderr, "chat: rooms: parse error\n"); return; } rooms = json_object_object_get(o, "rooms"); join = json_object_object_get(rooms, "join"); if(join == NULL){ fprintf(stderr, "chat: no joined rooms\n"); json_object_put(o); return; } n = json_object_object_length(join); if(n == 0){ json_object_put(o); return; } names = calloc(n, sizeof *names); k = 0; json_object_object_foreach(join, rid, roomval) { char *name = room_name_for(roomval); names[k++] = name != NULL ? name : strdup(rid); (void)rid; } for(i = 0; i < n; i++) printf("%s\n", names[i]); for(i = 0; i < n; i++) free(names[i]); free(names); json_object_put(o); } static char * room_name(const char *json, const char *query) { struct json_object *o, *join, *rooms; char *match = NULL; size_t qlen = strlen(query); o = json_tokener_parse(json); if(o == NULL) return NULL; rooms = json_object_object_get(o, "rooms"); join = json_object_object_get(rooms, "join"); if(join != NULL){ json_object_object_foreach(join, rid, roomval) { char *name = room_name_for(roomval); if(name == NULL) name = strdup(rid); if(strncasecmp(name, query, qlen) == 0){ match = strdup(rid); free(name); break; } free(name); } } json_object_put(o); return match; } static int mx_send_plain(const char *hs, const char *token, const char *room, const char *text) { struct json_object *body; const char *sbody; char *rid, *url, *txn, *res; long status; size_t un = strlen(hs) + strlen(room) + 96; int rc = -1; body = json_object_new_object(); json_object_object_add(body, "msgtype", json_object_new_string("m.text")); json_object_object_add(body, "body", json_object_new_string(text)); sbody = json_object_to_json_string(body); rid = urlencode(room); url = malloc(un); txn = malloc(32); snprintf(txn, 32, "chat%ld%ld", (long)getpid(), (long)time(NULL)); snprintf(url, un, "%s/_matrix/client/v3/rooms/%s/send/m.room.message/%s", hs, rid, txn); res = http_req("PUT", url, token, sbody, &status, NULL); if(res != NULL && status == 200) rc = 0; free(res); free(url); free(txn); free(rid); json_object_put(body); return rc; } static int mx_send(Session *s, const char *room, const char *text) { if(e2e_room_encrypted(s, room)) return e2e_send_text(s, room, text); return mx_send_plain(s->homeserver, s->token, room, text); } static void detect_type(const unsigned char *d, size_t n, const char *path, const char **msgtype, const char **mime) { *msgtype = "m.file"; *mime = "application/octet-stream"; if(n >= 4){ if(d[0] == 0x89 && d[1] == 0x50 && d[2] == 0x4E && d[3] == 0x47){ *msgtype = "m.image"; *mime = "image/png"; return; } if(d[0] == 0xFF && d[1] == 0xD8 && d[2] == 0xFF){ *msgtype = "m.image"; *mime = "image/jpeg"; return; } if(d[0] == 'G' && d[1] == 'I' && d[2] == 'F' && d[3] == '8'){ *msgtype = "m.image"; *mime = "image/gif"; return; } if(d[0] == 'B' && d[1] == 'M'){ *msgtype = "m.image"; *mime = "image/bmp"; return; } if(d[0] == 'O' && d[1] == 'g' && d[2] == 'g' && d[3] == 'S'){ *msgtype = "m.audio"; *mime = "audio/ogg"; return; } if(d[0] == 'f' && d[1] == 'L' && d[2] == 'a' && d[3] == 'C'){ *msgtype = "m.audio"; *mime = "audio/flac"; return; } if((d[0] == 'I' && d[1] == 'D' && d[2] == '3') || (d[0] == 0xFF && (d[1] & 0xE0) == 0xE0)){ *msgtype = "m.audio"; *mime = "audio/mpeg"; return; } if(d[0] == 'R' && d[1] == 'I' && d[2] == 'F' && d[3] == 'F' && n >= 12){ if(d[8] == 'W' && d[9] == 'E' && d[10] == 'B' && d[11] == 'P'){ *msgtype = "m.image"; *mime = "image/webp"; return; } if(d[8] == 'W' && d[9] == 'A' && d[10] == 'V' && d[11] == 'E'){ *msgtype = "m.audio"; *mime = "audio/wav"; return; } } if(d[0] == 0x1A && d[1] == 0x45 && d[2] == 0xDF && d[3] == 0xA3){ *msgtype = "m.video"; *mime = "video/webm"; return; } if(n >= 12 && d[4] == 'f' && d[5] == 't' && d[6] == 'y' && d[7] == 'p'){ *msgtype = "m.video"; *mime = "video/mp4"; return; } } if(path != NULL){ const char *e = strrchr(path, '.'); if(e != NULL){ if(!strcasecmp(e, ".pdf")) *mime = "application/pdf"; else if(!strcasecmp(e, ".zip")) *mime = "application/zip"; else if(!strcasecmp(e, ".txt")) *mime = "text/plain"; else if(!strcasecmp(e, ".json")) *mime = "application/json"; else if(!strcasecmp(e, ".png")) *mime = "image/png"; else if(!strcasecmp(e, ".jpg") || !strcasecmp(e, ".jpeg")) *mime = "image/jpeg"; else if(!strcasecmp(e, ".gif")) *mime = "image/gif"; else if(!strcasecmp(e, ".webp")) *mime = "image/webp"; else if(!strcasecmp(e, ".bmp")) *mime = "image/bmp"; else if(!strcasecmp(e, ".mp4") || !strcasecmp(e, ".m4v")) *mime = "video/mp4"; else if(!strcasecmp(e, ".webm")) *mime = "video/webm"; else if(!strcasecmp(e, ".mov")) *mime = "video/quicktime"; else if(!strcasecmp(e, ".ogg")) *mime = "audio/ogg"; else if(!strcasecmp(e, ".mp3")) *mime = "audio/mpeg"; } } } static int mx_sendfile(Session *s, const char *room, const char *path) { FILE *f; long sz; unsigned char *buf; char *res, *url, *txn, *rid, *mxc = NULL; const char *msgtype, *mime, *base, *sbody; struct json_object *body, *info; long status; struct stat st; size_t un; int rc = -1; if(stat(path, &st) != 0 || st.st_size < 0) return -1; sz = (long)st.st_size; f = fopen(path, "rb"); if(f == NULL) return -1; buf = malloc(sz > 0 ? (size_t)sz : 1); if(buf == NULL){ fclose(f); return -1; } if(fread(buf, 1, (size_t)sz, f) != (size_t)sz){ free(buf); fclose(f); return -1; } fclose(f); detect_type(buf, (size_t)sz, path, &msgtype, &mime); base = strrchr(path, '/'); base = base != NULL ? base + 1 : path; if(e2e_room_encrypted(s, room)){ struct json_object *fileo = NULL, *ev; unsigned char *ct = NULL; size_t ctlen = 0; if(e2e_att_encrypt(buf, (size_t)sz, mime, &fileo, &ct, &ctlen) != 0){ fprintf(stderr, "chat: e2e: attach encrypt failed\n"); free(buf); return -1; } url = malloc(strlen(s->homeserver) + 64); snprintf(url, strlen(s->homeserver) + 64, "%s/_matrix/media/v3/upload", s->homeserver); res = http_upload(url, s->token, ct, ctlen, "application/octet-stream", &status); free(url); if(res != NULL && status == 200){ struct json_object *o = json_tokener_parse(res); if(o != NULL){ struct json_object *cu = json_object_object_get(o, "content_uri"); if(cu != NULL) mxc = strdup(json_object_get_string(cu)); json_object_put(o); } } free(res); free(ct); free(buf); if(mxc == NULL){ fprintf(stderr, "chat: e2e: attach upload failed\n"); if(fileo != NULL) json_object_put(fileo); return -1; } body = json_object_new_object(); json_object_object_add(body, "msgtype", json_object_new_string(msgtype)); json_object_object_add(body, "body", json_object_new_string(base)); json_object_object_add(body, "url", json_object_new_string(mxc)); info = json_object_new_object(); json_object_object_add(info, "size", json_object_new_int64((int64_t)sz)); json_object_object_add(info, "mimetype", json_object_new_string(mime)); json_object_object_add(info, "file", fileo); json_object_object_add(body, "info", info); ev = json_object_new_object(); json_object_object_add(ev, "type", json_object_new_string("m.room.message")); json_object_object_add(ev, "content", body); rc = e2e_send_json(s, room, ev); json_object_put(ev); free(mxc); return rc; } url = malloc(strlen(s->homeserver) + 64); snprintf(url, strlen(s->homeserver) + 64, "%s/_matrix/media/v3/upload", s->homeserver); res = http_upload(url, s->token, buf, (size_t)sz, mime, &status); free(url); if(res != NULL && status == 200){ struct json_object *o = json_tokener_parse(res); if(o != NULL){ struct json_object *cu = json_object_object_get(o, "content_uri"); if(cu != NULL) mxc = strdup(json_object_get_string(cu)); json_object_put(o); } } free(res); free(buf); if(mxc == NULL) return -1; body = json_object_new_object(); json_object_object_add(body, "msgtype", json_object_new_string(msgtype)); json_object_object_add(body, "body", json_object_new_string(base)); json_object_object_add(body, "url", json_object_new_string(mxc)); info = json_object_new_object(); json_object_object_add(info, "size", json_object_new_int64((int64_t)sz)); json_object_object_add(info, "mimetype", json_object_new_string(mime)); json_object_object_add(body, "info", info); sbody = json_object_to_json_string(body); rid = urlencode(room); txn = malloc(32); snprintf(txn, 32, "chat%ld%ld", (long)getpid(), (long)time(NULL)); un = strlen(s->homeserver) + strlen(room) + 96; url = malloc(un); snprintf(url, un, "%s/_matrix/client/v3/rooms/%s/send/m.room.message/%s", s->homeserver, rid, txn); res = http_req("PUT", url, s->token, sbody, &status, NULL); if(res != NULL && status == 200) rc = 0; free(res); free(mxc); free(url); free(txn); free(rid); json_object_put(body); return rc; } static int mx_mediaget(const char *hs, const char *token, const char *mxc, const char *out) { char *url, *data, *mp, *slash, *enc; size_t len; long status; FILE *f; if(strncmp(mxc, "mxc://", 6) != 0) return -1; mp = strdup(mxc + 6); slash = strchr(mp, '/'); if(slash == NULL){ free(mp); return -1; } *slash = '\0'; enc = urlencode(slash + 1); url = malloc(strlen(hs) + strlen(mp) + strlen(enc) + 64); snprintf(url, strlen(hs) + strlen(mp) + strlen(enc) + 64, "%s/_matrix/client/v1/media/download/%s/%s", hs, mp, enc); free(enc); free(mp); data = http_req("GET", url, token, NULL, &status, &len); free(url); if(data == NULL || status != 200){ free(data); return -1; } f = fopen(out, "wb"); if(f == NULL){ free(data); return -1; } fwrite(data, 1, len, f); fclose(f); free(data); return 0; } static int mx_download_latest(const char *hs, const char *token, const char *rid, const char *out, char **body_out) { char flt[256]; char *url, *res; long status; struct json_object *o, *rooms, *join, *roomval, *tl, *ev; const char *mxc = NULL, *body = NULL; size_t i, n; if(body_out != NULL) *body_out = NULL; snprintf(flt, sizeof flt, "{\"room\":{\"timeline\":{\"limit\":40}," "\"state\":{\"limit\":0},\"account_data\":{\"limit\":0}}," "\"presence\":{\"limit\":0}}"); url = malloc(strlen(hs) + sizeof flt + 64); snprintf(url, strlen(hs) + sizeof flt + 64, "%s/_matrix/client/v3/sync?timeout=0&filter=%s", hs, flt); res = http_req("GET", url, token, NULL, &status, NULL); free(url); if(res == NULL || status != 200){ free(res); return -1; } o = json_tokener_parse(res); free(res); if(o == NULL) return -1; rooms = json_object_object_get(o, "rooms"); join = json_object_object_get(rooms, "join"); roomval = join != NULL ? json_object_object_get(join, rid) : NULL; tl = roomval != NULL ? json_object_object_get(json_object_object_get(roomval, "timeline"), "events") : NULL; if(tl != NULL){ n = json_object_array_length(tl); for(i = 0; i < n; i++){ const char *mt, *u, *b; ev = json_object_array_get_idx(tl, i); if(strcmp(json_object_get_string( json_object_object_get(ev, "type")), "m.room.message") != 0) continue; mt = json_object_get_string(json_object_object_get( json_object_object_get(ev, "content"), "msgtype")); u = json_object_get_string(json_object_object_get( json_object_object_get(ev, "content"), "url")); b = json_object_get_string(json_object_object_get( json_object_object_get(ev, "content"), "body")); if(mt != NULL && (strcmp(mt, "m.image") == 0 || strcmp(mt, "m.video") == 0) && u != NULL && strncmp(u, "mxc://", 6) == 0){ mxc = u; body = b; } } } if(mxc != NULL){ if(body_out != NULL && body != NULL) *body_out = strdup(body); int rc = mx_mediaget(hs, token, mxc, out); json_object_put(o); return rc; } json_object_put(o); return -1; } static void print_line(const char *roomname, const char *dn, const char *sender, const char *body) { char linebuf[2048]; char *local = NULL; if(dn == NULL){ local = strdup(sender); if(local != NULL){ char *at = strchr(local, ':'); if(at != NULL) *at = '\0'; } dn = local; } snprintf(linebuf, sizeof linebuf, "%s <%s> %s", roomname, dn, body); fputs(linebuf, stdout); putchar('\n'); fflush(stdout); free(local); } static void print_event(Session *s, const char *rid, const char *roomname, const char *senderdn, struct json_object *ev) { struct json_object *typeo, *contento, *bodyo, *sendero; const char *type, *body, *sender, *relation, *mt; char *eb = NULL; typeo = json_object_object_get(ev, "type"); if(typeo == NULL) return; type = json_object_get_string(typeo); if(strcmp(type, "m.room.message") == 0){ contento = json_object_object_get(ev, "content"); if(contento == NULL) return; relation = json_object_get_string(json_object_object_get( json_object_object_get(contento, "m.relates_to"), "rel_type")); if(relation != NULL) return; bodyo = json_object_object_get(contento, "body"); if(bodyo == NULL) return; body = json_object_get_string(bodyo); mt = json_object_get_string(json_object_object_get(contento, "msgtype")); if(mt != NULL && (strcmp(mt, "m.image") == 0 || strcmp(mt, "m.video") == 0)) body = "[Image/Video sent - chat -d to save]"; }else if(strcmp(type, "m.room.encrypted") == 0){ eb = e2e_meg_event_body(s, rid, ev); if(eb == NULL) return; body = eb; }else return; sendero = json_object_object_get(ev, "sender"); sender = sendero != NULL ? json_object_get_string(sendero) : "?"; backlog_add(roomname, senderdn, body, json_object_get_int64(json_object_object_get(ev, "origin_server_ts"))); print_line(roomname, senderdn, sender, body); free(eb); } typedef struct Msg { long long ts; char *room; char *sender; char *body; char *imgurl; } Msg; static int msg_cmp(const void *a, const void *b) { const Msg *x = a, *y = b; return (y->ts > x->ts) - (y->ts < x->ts); } static Msg *g_bl; static size_t g_bl_n, g_bl_cap; static void backlog_add(const char *room, const char *sender, const char *body, long long ts) { size_t i; if(body == NULL) return; for(i = 0; i < g_bl_n; i++) if(g_bl[i].ts == ts && strcmp(g_bl[i].room, room ? room : "") == 0 && strcmp(g_bl[i].sender, sender ? sender : "") == 0) return; if(g_bl_n == g_bl_cap){ size_t nc = g_bl_cap == 0 ? 256 : g_bl_cap * 2; Msg *nb = realloc(g_bl, nc * sizeof *nb); if(nb == NULL) return; g_bl = nb; g_bl_cap = nc; } g_bl[g_bl_n].ts = ts; g_bl[g_bl_n].room = strdup(room != NULL ? room : ""); g_bl[g_bl_n].sender = strdup(sender != NULL ? sender : ""); g_bl[g_bl_n].body = strdup(body); g_bl[g_bl_n].imgurl = NULL; g_bl_n++; } static void backlog_load(void) { char path[1024], line[8192]; FILE *f; snprintf(path, sizeof path, "%s/backlog", cfgdir()); f = fopen(path, "r"); if(f == NULL) return; while(fgets(line, sizeof line, f) != NULL){ char *p1, *p2, *p3, *nl; nl = strchr(line, '\n'); if(nl != NULL) *nl = '\0'; p1 = strchr(line, '\t'); if(p1 == NULL) continue; *p1++ = '\0'; p2 = strchr(p1, '\t'); if(p2 == NULL) continue; *p2++ = '\0'; p3 = strchr(p2, '\t'); if(p3 == NULL) continue; *p3++ = '\0'; backlog_add(p1, p2, p3, strtoll(line, NULL, 10)); } fclose(f); } static void backlog_save(void) { char path[1024]; FILE *f; size_t i, n; if(g_bl_n == 0) return; qsort(g_bl, g_bl_n, sizeof *g_bl, msg_cmp); n = g_bl_n > 200 ? 200 : g_bl_n; snprintf(path, sizeof path, "%s/backlog", cfgdir()); f = fopen(path, "w"); if(f == NULL) return; for(i = n; i > 0; i--){ char *room = g_bl[i - 1].room, *sender = g_bl[i - 1].sender; char *body = g_bl[i - 1].body, *q; for(q = room; *q != '\0'; q++) if(*q == '\t' || *q == '\n') *q = ' '; for(q = sender; *q != '\0'; q++) if(*q == '\t' || *q == '\n') *q = ' '; for(q = body; *q != '\0'; q++) if(*q == '\t' || *q == '\n') *q = ' '; fprintf(f, "%lld\t%s\t%s\t%s\n", g_bl[i - 1].ts, room, sender, body); } fclose(f); } static void backlog_print(size_t max) { size_t i, n; if(g_bl_n == 0) return; qsort(g_bl, g_bl_n, sizeof *g_bl, msg_cmp); n = g_bl_n > max ? max : g_bl_n; for(i = n; i > 0; i--) print_line(g_bl[i - 1].room, NULL, g_bl[i - 1].sender, g_bl[i - 1].body); } static int mx_poll(Session *s, const char *since, char **since_out, long tmo) { char flt[512]; char *e, *url, *res; struct json_object *o, *rooms, *join, *nb, *tl, *ev; char *new_since = NULL; size_t i, n, un; long tlimit = since != NULL && since[0] != '\0' ? TLLIVE : TLFIRST; long slimit = since != NULL && since[0] != '\0' ? 100 : 0; long status; double tnet = 0, tpar = 0, te2e = 0, twhole = mono_sec(); e2e_kr_quota = 8; snprintf(flt, sizeof flt, "{\"room\":{\"timeline\":{\"limit\":%ld}," "\"state\":{\"lazy_load_members\":true," "\"include_recent_senders\":true,\"limit\":%ld}," "\"account_data\":{\"limit\":0}}," "\"presence\":{\"limit\":0}," "\"to_device\":{\"limit\":20}}", tlimit, slimit); if(since != NULL && since[0] != '\0'){ e = urlencode(since); un = strlen(s->homeserver) + strlen(flt) + strlen(e) + 96; url = malloc(un); snprintf(url, un, "%s/_matrix/client/v3/sync?timeout=%ld&filter=%s&since=%s", s->homeserver, tmo, flt, e); free(e); }else{ un = strlen(s->homeserver) + strlen(flt) + 64; url = malloc(un); snprintf(url, un, "%s/_matrix/client/v3/sync?timeout=0&filter=%s", s->homeserver, flt); } tnet = mono_sec(); res = http_req("GET", url, s->token, NULL, &status, NULL); free(url); if(res == NULL || status != 200){ free(res); return -1; } tpar = mono_sec(); o = json_tokener_parse(res); free(res); if(o == NULL) return -1; nb = json_object_object_get(o, "next_batch"); if(nb != NULL) new_since = strdup(json_object_get_string(nb)); te2e = mono_sec(); e2e_sync(s, o); rooms = json_object_object_get(o, "rooms"); join = json_object_object_get(rooms, "join"); if(join != NULL){ int backlog = since == NULL || since[0] == '\0'; json_object_object_foreach(join, rid, roomval) { struct json_object *state, *stateevents; if(g_filter != NULL && strcmp(rid, g_filter) != 0) continue; state = json_object_object_get(roomval, "state"); stateevents = state != NULL ? json_object_object_get(state, "events") : NULL; cache_state(rid, stateevents); tl = json_object_object_get( json_object_object_get(roomval, "timeline"), "events"); if(tl == NULL) continue; n = json_object_array_length(tl); for(i = 0; i < n; i++){ const char *sender, *dn, *rn; const char *t2; ev = json_object_array_get_idx(tl, i); t2 = json_object_get_string( json_object_object_get(ev, "type")); if(t2 == NULL || (strcmp(t2, "m.room.message") != 0 && strcmp(t2, "m.room.encrypted") != 0)) continue; if(backlog) continue; sender = json_object_get_string( json_object_object_get(ev, "sender")); dn = user_disp(s->homeserver, s->token, sender); rn = room_disp(s->homeserver, s->token, rid); print_event(s, rid, rn, dn, ev); } } if(backlog){ size_t k; Msg *msgs = NULL; size_t nm = 0, cap = 0; json_object_object_foreach(join, rid2, roomval2) { struct json_object *tl2, *st2; if(g_filter != NULL && strcmp(rid2, g_filter) != 0) continue; st2 = json_object_object_get(roomval2, "state"); cache_state(rid2, st2 != NULL ? json_object_object_get(st2, "events") : NULL); tl2 = json_object_object_get( json_object_object_get(roomval2, "timeline"), "events"); if(tl2 == NULL) continue; size_t nn = json_object_array_length(tl2); for(k = 0; k < nn; k++){ struct json_object *ev2 = json_object_array_get_idx(tl2, k); const char *sender, *body, *mt, *t2; char *eb = NULL; t2 = json_object_get_string( json_object_object_get(ev2, "type")); if(t2 == NULL || (strcmp(t2, "m.room.message") != 0 && strcmp(t2, "m.room.encrypted") != 0)) continue; if(nm == cap){ cap = cap == 0 ? 16 : cap * 2; msgs = realloc(msgs, cap*sizeof(Msg)); } eb = NULL; if(strcmp(t2, "m.room.encrypted") == 0){ eb = e2e_meg_event_body(s, rid2, ev2); if(eb == NULL) continue; body = eb; mt = NULL; }else{ body = json_object_get_string( json_object_object_get( json_object_object_get( ev2, "content"), "body")); if(body == NULL) continue; mt = json_object_get_string( json_object_object_get( json_object_object_get( ev2, "content"), "msgtype")); } sender = json_object_get_string( json_object_object_get(ev2, "sender")); msgs[nm].ts = json_object_get_int64( json_object_object_get(ev2, "origin_server_ts")); msgs[nm].room = strdup( room_disp(s->homeserver, s->token, rid2)); msgs[nm].sender = strdup( user_disp(s->homeserver, s->token, sender)); msgs[nm].body = strdup( (mt != NULL && (strcmp(mt, "m.image") == 0 || strcmp(mt, "m.video") == 0)) ? "[Image/Video sent]" : body); msgs[nm].imgurl = NULL; if(eb != NULL) free(eb); nm++; } } qsort(msgs, nm, sizeof(Msg), msg_cmp); for(k = nm; k > 0; k--) backlog_add(msgs[k - 1].room, msgs[k - 1].sender, msgs[k - 1].body, msgs[k - 1].ts); if(!g_skip_backlog){ for(k = nm < 10 ? nm : 10; k > 0; k--) print_line(msgs[k - 1].room, NULL, msgs[k - 1].sender, msgs[k - 1].body); } g_skip_backlog = 0; for(k = 0; k < nm; k++){ free(msgs[k].room); free(msgs[k].sender); free(msgs[k].body); } free(msgs); } } json_object_put(o); if(getenv("CHAD_DEBUG")) fprintf(stderr, "poll: net=%.3f parse=%.3f e2e=%.3f total=%.3f\n", tpar - tnet, te2e - tpar, mono_sec() - te2e, mono_sec() - twhole); if(new_since != NULL){ if(since_out != NULL){ free(*since_out); *since_out = new_since; }else free(new_since); } return 0; } /* * main */ static void usage(void) { fprintf(stderr, "usage: chad [-d [file]] [-e enter ] [-r rooms] [-s message \"Text\" \"file.png\"] [-l log in] [-x log out matrix] [-D daemon sync] [-h help]\n" "\n" " (no args) watch all chats; first run logs you in\n" " -d [file] download the last image/video from a room (default: ./download)\n" " -e enter a room: show its backlog, then keep printing live\n" " -r list your rooms\n" " -s send a message (or a file) to a room or a person\n" " -l log in (asks server, user, password)\n" " -x log out: delete the session file and the stored password\n" " -h show this help\n"); exit(1); } static char * cfgdir(void) { char *home = getenv("HOME"); char *p; if(home == NULL) home = "/root"; p = malloc(strlen(home) + 16 + 9); sprintf(p, "%s/.config/%s", home, CONFIGDIR); return p; } static char * read_password(const char *prompt) { struct termios old, no; char buf[256]; char *p; int c, n = 0; fprintf(stderr, "%s", prompt); fflush(stderr); if(tcgetattr(0, &old) == 0){ no = old; no.c_lflag &= ~(ECHO | ECHONL); tcsetattr(0, TCSAFLUSH, &no); } while((c = getchar()) != EOF && c != '\n' && n < (int)sizeof(buf) - 1) buf[n++] = c; buf[n] = '\0'; if(tcgetattr(0, &old) == 0) tcsetattr(0, TCSAFLUSH, &old); fprintf(stderr, "\n"); if(n == 0) return NULL; p = malloc(n + 1); memcpy(p, buf, n + 1); return p; } static void term_normal(void) { struct termios t; if(tcgetattr(0, &t) == 0){ t.c_lflag |= (ICANON | ECHO); tcsetattr(0, TCSAFLUSH, &t); } } static char * read_line(const char *prompt) { char buf[1024]; fprintf(stderr, "%s", prompt); fflush(stderr); if(fgets(buf, sizeof buf, stdin) == NULL) return NULL; { size_t l = strlen(buf); if(l && buf[l-1] == '\n') buf[--l] = '\0'; } if(buf[0] == '\0') return NULL; return strdup(buf); } static char * session_load_token_fallback(char *file_token, char *secret_token) { if(secret_token != NULL && secret_token[0] != '\0'){ free(file_token); return secret_token; } free(secret_token); return file_token; } static int load_matrix(Session *s) { memset(s, 0, sizeof *s); if(session_load(s, cfgdir()) != 0){ fprintf(stderr, "chat: not logged in (run 'chat -l')\n"); return -1; } names_load(cfgdir()); s->token = session_load_token_fallback(s->token, secret_get("chat/matrix")); return 0; } static int matrix_login(const char *addr) { const char *hs = addr; char *hsbuf = NULL, *user, *pass, *cred, *dir; struct json_object *o, *tok; long status; Session s; memset(&s, 0, sizeof s); if(strncmp(hs, "http://", 7) != 0 && strncmp(hs, "https://", 8) != 0){ hsbuf = malloc(strlen(hs) + 9); sprintf(hsbuf, "https://%s", hs); hs = hsbuf; } user = read_line("user: "); if(user == NULL || user[0] == '\0'){ free(user); user = strdup(DEFUSER); } pass = read_password("password: "); term_normal(); if(pass == NULL){ free(user); free(hsbuf); return 1; } cred = mx_login(hs, user, pass, &status); memset(pass, 0, strlen(pass)); free(pass); if(cred == NULL || status != 200){ fprintf(stderr, "login failed (status %ld)\n", status); free(cred); free(user); free(hsbuf); return 1; } o = json_tokener_parse(cred); free(cred); if(o == NULL){ fprintf(stderr, "login: bad response\n"); free(user); free(hsbuf); return 1; } tok = json_object_object_get(o, "user_id"); if(tok == NULL){ fprintf(stderr, "login: no user_id in response\n"); json_object_put(o); free(user); free(hsbuf); return 1; } s.user = strdup(json_object_get_string(tok)); tok = json_object_object_get(o, "access_token"); if(tok == NULL){ fprintf(stderr, "login: no token in response\n"); json_object_put(o); session_free(&s); free(user); free(hsbuf); return 1; } s.token = strdup(json_object_get_string(tok)); tok = json_object_object_get(o, "device_id"); if(tok != NULL) s.e2e_devid = strdup(json_object_get_string(tok)); s.homeserver = strdup(hs); s.since = NULL; if(e2e_setup(&s) != 0) fprintf(stderr, "warning: e2e keys init failed\n"); else if(s.e2e_devid == NULL) fprintf(stderr, "warning: login response had no device_id\n"); else if(e2e_publish_keys(&s) != 0) fprintf(stderr, "warning: e2e keys upload failed\n"); dir = cfgdir(); if(secret_put("chat/matrix", s.token) != 0) fprintf(stderr, "warning: could not store token in `pass`\n"); if(session_save(&s, dir) != 0) fprintf(stderr, "login: cannot save session\n"); json_object_put(o); session_free(&s); free(dir); free(user); free(hsbuf); fprintf(stderr, "logged in (matrix). session saved.\n"); return 0; } static int cmd_login(void) { char *addr = read_line("matrix homeserver: "); if(addr == NULL || addr[0] == '\0'){ free(addr); addr = strdup(HS); } { int rc = matrix_login(addr); free(addr); return rc; } } static int cmd_logout(void) { char *dir = cfgdir(); char *p; p = malloc(strlen(dir) + 16); sprintf(p, "%s/session", dir); unlink(p); free(p); system("pass delete -f chat/matrix >/dev/null 2>&1"); free(dir); fprintf(stderr, "matrix: logged out\n"); return 0; } static int cmd_watch(void); static char * sanitize_path(const char *path) { const char *p, *slash; char *out; slash = NULL; for(p = path; *p; p++){ if(*p == '/' || *p == '\\') slash = p + 1; } out = strdup(slash ? slash : path); return out; } static char * resolve_room_id(Session *s, const char *q) { char *json, *match = NULL; struct json_object *o = NULL, *arr; size_t qlen = strlen(q), i, n; json = mx_joined_rooms(s->homeserver, s->token); if(json == NULL) goto fallback; o = json_tokener_parse(json); free(json); if(o == NULL) goto fallback; if(!json_object_object_get_ex(o, "joined_rooms", &arr) || !json_object_is_type(arr, json_type_array)){ json_object_put(o); goto fallback; } n = json_object_array_length(arr); for(i = 0; i < n; i++){ const char *rid = json_object_get_string( json_object_array_get_idx(arr, i)); const char *nm; if(rid == NULL) continue; nm = name_of(s->homeserver, s->token, rid); if(nm == NULL) nm = rid; if(strncasecmp(nm, q, qlen) == 0){ match = strdup(rid); break; } } json_object_put(o); if(match == NULL) goto fallback; return match; fallback: if(json == NULL || o == NULL){ free(json); json = mx_rooms(s->homeserver, s->token, NULL, NULL); if(json != NULL){ match = room_name(json, q); free(json); } } if(match == NULL) fprintf(stderr, "chat: no room matching '%s'\n", q); return match; } static void join_invited(const char *hs, const char *token, const char *since) { char url[1024], *json, *e = NULL; struct json_object *o, *rooms, *invite; long st; if(since != NULL && since[0] != '\0'){ e = urlencode(since); snprintf(url, sizeof url, "%s/_matrix/client/v3/sync?timeout=0&filter=%s&since=%s", hs, "{\"room\":{\"timeline\":{\"limit\":0},\"state\":{\"limit\":0},\"account_data\":{\"limit\":0}},\"presence\":{\"limit\":0}}", e); free(e); }else snprintf(url, sizeof url, "%s/_matrix/client/v3/sync?timeout=0&filter=%s", hs, "{\"room\":{\"timeline\":{\"limit\":0},\"state\":{\"limit\":0},\"account_data\":{\"limit\":0}},\"presence\":{\"limit\":0}}"); json = http_req("GET", url, token, NULL, &st, NULL); if(json == NULL || st != 200){ free(json); return; } o = json_tokener_parse(json); free(json); if(o == NULL) return; rooms = json_object_object_get(o, "rooms"); invite = rooms == NULL ? NULL : json_object_object_get(rooms, "invite"); if(invite != NULL){ json_object_object_foreach(invite, ridinv, roomval) { snprintf(url, sizeof url, "%s/_matrix/client/v3/rooms/%s/join", hs, ridinv); http_req("POST", url, token, "{}", &st, NULL); } } json_object_put(o); } static int cmd_rooms(Session *s) { char *json; struct json_object *o, *arr; double t0 = mono_sec(); size_t i, n; join_invited(s->homeserver, s->token, s->since); json = mx_joined_rooms(s->homeserver, s->token); if(json != NULL){ o = json_tokener_parse(json); free(json); if(o != NULL && json_object_object_get_ex(o, "joined_rooms", &arr) && json_object_is_type(arr, json_type_array)){ n = json_object_array_length(arr); for(i = 0; i < n; i++){ const char *rid = json_object_get_string( json_object_array_get_idx(arr, i)); const char *nm; if(rid == NULL) continue; nm = name_of(s->homeserver, s->token, rid); printf("%s\n", nm != NULL ? nm : rid); } json_object_put(o); names_save(cfgdir()); printf("load %.3fs\n", mono_sec() - t0); fflush(stdout); return 0; } if(o != NULL) json_object_put(o); } json = mx_rooms(s->homeserver, s->token, NULL, NULL); if(json == NULL){ fprintf(stderr, "chat: cannot list rooms\n"); return 1; } mx_dump_rooms(json); free(json); names_save(cfgdir()); printf("load %.3fs\n", mono_sec() - t0); fflush(stdout); return 0; } static int cmd_send_multi(Session *s, const char *room, int argc, char **argv, int start) { char *rid = NULL; char *text = NULL; size_t tlen = 0, tcap = 0; int rc = 1, sent = 0; int j; if(room != NULL) rid = resolve_room_id(s, room); if(rid == NULL) return 1; e2e_ensure(s); for(j = start; j < argc; j++){ const char *a = argv[j]; struct stat st; if(stat(a, &st) == 0 && S_ISREG(st.st_mode)){ int r = mx_sendfile(s, rid, a); if(r != 0) fprintf(stderr, "chat: send file failed: %s\n", a); else sent = 1; }else{ size_t al = strlen(a); size_t need = tlen + al + 2; if(need > tcap){ tcap = need * 2 + 16; text = realloc(text, tcap); } if(tlen > 0) text[tlen++] = ' '; memcpy(text + tlen, a, al + 1); tlen += al; } } if(text != NULL && tlen > 0){ int r = mx_send(s, rid, text); if(r != 0) fprintf(stderr, "chat: send failed\n"); else sent = 1; } free(text); free(rid); if(e2e_dirty) session_save(s, cfgdir()); if(sent) rc = 0; return rc; } static int mx_sync_since(Session *s, const char *since, char *out, size_t outsz) { char flt[512]; struct json_object *o, *nb, *rooms, *join; char *e, *url, *res; long status; size_t n; snprintf(flt, sizeof flt, "{\"room\":{\"timeline\":{\"limit\":20}," "\"state\":{\"limit\":100},\"account_data\":{\"limit\":0}}," "\"presence\":{\"limit\":0}," "\"to_device\":{\"limit\":20}}"); if(since != NULL && since[0] != '\0'){ e = urlencode(since); n = strlen(s->homeserver) + strlen(flt) + strlen(e) + 96; url = malloc(n); snprintf(url, n, "%s/_matrix/client/v3/sync?timeout=30000&filter=%s&since=%s", s->homeserver, flt, e); free(e); }else{ n = strlen(s->homeserver) + strlen(flt) + 64; url = malloc(n); snprintf(url, n, "%s/_matrix/client/v3/sync?timeout=30000&filter=%s", s->homeserver, flt); } res = http_req("GET", url, s->token, NULL, &status, NULL); free(url); if(res == NULL || status != 200){ free(res); return -1; } o = json_tokener_parse(res); free(res); if(o == NULL) return -1; nb = json_object_object_get(o, "next_batch"); if(nb != NULL) snprintf(out, outsz, "%s", json_object_get_string(nb)); e2e_sync(s, o); rooms = json_object_object_get(o, "rooms"); join = rooms != NULL ? json_object_object_get(rooms, "join") : NULL; if(join != NULL){ json_object_object_foreach(join, rid, roomval) { struct json_object *st, *tl; size_t i, nn; st = json_object_object_get(roomval, "state"); cache_state(rid, st != NULL ? json_object_object_get(st, "events") : NULL); tl = json_object_object_get( json_object_object_get(roomval, "timeline"), "events"); if(tl == NULL) continue; nn = json_object_array_length(tl); for(i = 0; i < nn; i++){ struct json_object *ev = json_object_array_get_idx(tl, i); const char *t2 = json_object_get_string( json_object_object_get(ev, "type")); if(t2 != NULL && strcmp(t2, "m.room.encrypted") == 0){ char *pt = e2e_meg_event_body(s, rid, ev); free(pt); } } } } json_object_put(o); return nb != NULL ? 0 : -1; } static int cmd_daemon(void) { Session *mx; char *since = NULL; int rc = 0; const char *dir; mx = malloc(sizeof *mx); if(load_matrix(mx) != 0){ free(mx); return 1; } if(mx->token == NULL || mx->token[0] == '\0'){ fprintf(stderr, "chat: token missing -- run 'chad -l'.\n"); session_free(mx); free(mx); return 1; } since = mx->since; dir = cfgdir(); e2e_ensure(mx); for(;;){ char newbuf[256]; int save = 0; if(mx_sync_since(mx, since, newbuf, sizeof newbuf) != 0){ sleep(5); continue; } if(newbuf[0] != '\0' && (mx->since == NULL || strcmp(mx->since, newbuf) != 0)){ char *old = mx->since; mx->since = strdup(newbuf); free(old); since = mx->since; save = 1; } if(e2e_dirty) save = 1; if(save){ session_save(mx, dir); e2e_dirty = 0; } } session_free(mx); free(mx); return rc; } static int mx_backfill(Session *s, const char *rid) { char *e, *url, *res, *from = NULL; const char *rn; struct json_object *o, *chunk, *end; struct json_object **evs = NULL; long status; size_t i, m = 0, total = 0, cap = 0, pages; char lastid[256] = ""; rn = room_disp(s->homeserver, s->token, rid); for(pages = 0; pages < 500; pages++){ char *ridenc = urlencode(rid); if(ridenc == NULL) break; if(from != NULL){ e = urlencode(from); m = strlen(s->homeserver) + strlen(ridenc) + strlen(e) + 160; url = malloc(m); snprintf(url, m, "%s/_matrix/client/v3/rooms/%s/messages" "?dir=b&limit=100&from=%s", s->homeserver, ridenc, e); free(e); }else{ m = strlen(s->homeserver) + strlen(ridenc) + 128; url = malloc(m); snprintf(url, m, "%s/_matrix/client/v3/rooms/%s/messages" "?dir=b&limit=100", s->homeserver, ridenc); } free(ridenc); res = http_req("GET", url, s->token, NULL, &status, NULL); free(url); if(res == NULL || status != 200){ free(res); break; } o = json_tokener_parse(res); free(res); if(o == NULL) break; chunk = json_object_object_get(o, "chunk"); m = chunk != NULL ? json_object_array_length(chunk) : 0; for(i = 0; i < m; i++){ struct json_object *ev = json_object_array_get_idx(chunk, i); const char *t = json_object_get_string( json_object_object_get(ev, "type")); if(t == NULL || (strcmp(t, "m.room.message") != 0 && strcmp(t, "m.room.encrypted") != 0)) continue; { const char *eid = json_object_get_string( json_object_object_get(ev, "event_id")); if(eid != NULL && lastid[0] != '\0' && strcmp(eid, lastid) == 0) continue; if(eid != NULL) snprintf(lastid, sizeof lastid, "%s", eid); } if(total == cap){ cap = cap == 0 ? 64 : cap * 2; evs = realloc(evs, cap * sizeof(*evs)); if(evs == NULL){ total = 0; break; } } evs[total++] = json_object_get(ev); } end = json_object_object_get(o, "end"); if(end == NULL || json_object_get_string(end) == NULL || json_object_get_string(end)[0] == '\0' || m == 0){ json_object_put(o); break; } free(from); from = strdup(json_object_get_string(end)); json_object_put(o); } free(from); for(i = total; i > 0; i--){ struct json_object *ev = evs[i - 1]; const char *sender = json_object_get_string( json_object_object_get(ev, "sender")); const char *dn = user_disp(s->homeserver, s->token, sender); print_event(s, rid, rn, dn, ev); json_object_put(ev); } free(evs); return total > 0 ? 0 : -1; } static int cmd_enter(Session *s, const char *room){ char *rid = resolve_room_id(s, room); int rc; if(rid == NULL) return 1; mx_set_filter(rid); rc = cmd_watch(); mx_set_filter(NULL); free(rid); return rc; } /* * matrix watch */ static int cmd_watch(void) { Session *mx = NULL; char *since = NULL; int rc = 0; double t0, t1; mx = malloc(sizeof *mx); if(load_matrix(mx) != 0){ free(mx); fprintf(stderr, "chat: nothing configured -- starting login.\n"); if(cmd_login() == 0) return cmd_watch(); return 1; } if(mx->token == NULL){ session_free(mx); free(mx); fprintf(stderr, "chat: token missing -- run 'chat -l'.\n"); return 1; } t0 = mono_sec(); join_invited(mx->homeserver, mx->token, mx->since); if(getenv("CHAD_DEBUG")) fprintf(stderr, "join_invited: %.3f\n", mono_sec() - t0); e2e_ensure(mx); if(getenv("CHAD_DEBUG")) fprintf(stderr, "e2e_ensure: %.3f\n", mono_sec() - t0); if(g_filter != NULL){ mx_backfill(mx, g_filter); g_skip_backlog = 1; } backlog_load(); if(g_bl_n > 0 && g_filter == NULL) backlog_print(10); if(mx_poll(mx, (g_bl_n > 0 && mx->since != NULL && mx->since[0] != '\0') ? mx->since : NULL, &since, 0L) != 0) fprintf(stderr, "chat: matrix poll failed\n"); if(since != NULL && since[0] != '\0' && (mx->since == NULL || strcmp(mx->since, since) != 0)){ char *old = mx->since; mx->since = strdup(since); free(old); session_save(mx, cfgdir()); } if(e2e_dirty){ session_save(mx, cfgdir()); e2e_dirty = 0; } backlog_save(); t1 = mono_sec(); printf("load %.3fs\n", t1 - t0); fflush(stdout); for(;;){ struct pollfd pfd[1]; pfd[0].fd = STDIN_FILENO; pfd[0].events = POLLIN; pfd[0].revents = 0; if(poll(pfd, 1, 1000) < 0){ if(errno == EINTR) continue; break; } if(pfd[0].revents & POLLIN){ char buf[2048]; if(fgets(buf, sizeof buf, stdin) == NULL) break; { size_t l = strlen(buf); if(l && buf[l-1] == '\n') buf[--l] = '\0'; } if(strncasecmp(buf, "/quit", 5) == 0) break; if(buf[0] != '\0'){ char *rid = mx_first_room(mx->homeserver, mx->token); if(rid != NULL){ if(mx_send(mx, rid, buf) != 0) fprintf(stderr, "chat: matrix send failed\n"); free(rid); }else fprintf(stderr, "chat: no matrix room\n"); } } if(mx_poll(mx, since, &since, POLLMS) != 0) fprintf(stderr, "chat: matrix poll failed\n"); if(e2e_dirty){ session_save(mx, cfgdir()); e2e_dirty = 0; } } free(since); names_save(cfgdir()); session_free(mx); free(mx); return rc; } int main(int argc, char **argv) { int i; const char *opt_d = NULL, *opt_e = NULL, *opt_s = NULL; const char *opt_dfile = NULL; int opt_r = 0, opt_l = 0, opt_h = 0, opt_x = 0; int opt_D = 0; int s_msg = -1; for(i = 1; i < argc; i++){ if(strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "help") == 0){ opt_h = 1; }else if(strcmp(argv[i], "-l") == 0){ opt_l = 1; }else if(strcmp(argv[i], "-r") == 0){ opt_r = 1; }else if(strcmp(argv[i], "-d") == 0){ if(++i >= argc) usage(); opt_d = argv[i]; if(i + 1 < argc && argv[i + 1][0] != '-'){ opt_dfile = argv[++i]; } }else if(strcmp(argv[i], "-e") == 0){ if(++i >= argc) usage(); opt_e = argv[i]; }else if(strcmp(argv[i], "-s") == 0){ if(i + 2 >= argc) usage(); opt_s = argv[i + 1]; s_msg = i + 2; i = argc; }else if(strcmp(argv[i], "-x") == 0){ opt_x = 1; }else if(strcmp(argv[i], "-D") == 0){ opt_D = 1; }else{ usage(); } } if(opt_h) usage(); if(opt_l) return cmd_login(); if(opt_x) return cmd_logout(); if(opt_D) return cmd_daemon(); if(opt_r || opt_d != NULL || opt_e != NULL || opt_s != NULL){ Session *s = malloc(sizeof *s); int rc; if(load_matrix(s) != 0){ free(s); return 1; } if(opt_d != NULL){ char *rid = resolve_room_id(s, opt_d); char *body = NULL; const char *outpath; if(rid == NULL){ session_free(s); free(s); return 1; } if(opt_dfile != NULL){ outpath = opt_dfile; }else{ mx_download_latest(s->homeserver, s->token, rid, "/dev/null", &body); outpath = sanitize_path( body ? body : "download"); } rc = mx_download_latest(s->homeserver, s->token, rid, outpath, NULL); if(rc == 0) printf("saved to %s\n", outpath); else fprintf(stderr, "chat: no image/video found\n"); if(opt_dfile == NULL) free((char *)outpath); free(body); free(rid); }else if(opt_r){ rc = cmd_rooms(s); }else if(opt_s != NULL){ rc = cmd_send_multi(s, opt_s, argc, argv, s_msg); }else{ rc = cmd_enter(s, opt_e); } session_free(s); free(s); names_save(cfgdir()); return rc; } return cmd_watch(); }