#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include struct Appservice { char *id; char *asToken; char *hsToken; char *url; char *sender; Array *users; Array *aliases; }; typedef struct AsTxn { Appservice *as; char *txnId; char *body; } AsTxn; static Array *queue = NULL; static pthread_mutex_t queueLock = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t queueCond = PTHREAD_COND_INITIALIZER; static Array *appservices = NULL; static regex_t * CompileRegex(char *pattern) { regex_t *re; if (!pattern) { return NULL; } re = Malloc(sizeof(regex_t)); if (!re) { return NULL; } if (regcomp(re, pattern, REG_EXTENDED | REG_NOSUB) != 0) { Free(re); return NULL; } return re; } static Array * CompileList(JsonValue * list) { Array *arr = ArrayCreate(); Array *in = JsonValueAsArray(list); size_t i; if (!in) { return arr; } for (i = 0; i < ArraySize(in); i++) { HashMap *ns = JsonValueAsObject(ArrayGet(in, i)); char *pattern = ns ? JsonValueAsString(HashMapGet(ns, "regex")) : NULL; regex_t *re = CompileRegex(pattern); if (re) { ArrayAdd(arr, re); } } return arr; } static char * Trim(char * s) { char *end; while (*s == ' ' || *s == '\t') { s++; } end = s + strlen(s); while (end > s && (end[-1] == '\n' || end[-1] == '\r' || end[-1] == ' ' || end[-1] == '\t')) { end--; } *end = '\0'; return s; } static char * Unquote(char * s) { size_t n = strlen(s); char *read; char *write; if (n < 2 || ((s[0] != '"' || s[n - 1] != '"') && (s[0] != '\'' || s[n - 1] != '\''))) { return s; } s[n - 1] = '\0'; s++; if (n < 3) { return s; } read = s; write = s; while (*read) { if (*read == '\\' && read[1] != '\0') { read++; if (*read == 'n') { *write++ = '\n'; } else if (*read == 't') { *write++ = '\t'; } else { *write++ = *read; } } else { *write++ = *read; } read++; } *write = '\0'; return s; } static HashMap * YamlLoad(const char * path) { FILE *file = fopen(path, "r"); HashMap *root; HashMap *ns; Array *users = NULL; Array *aliases = NULL; Array *rooms = NULL; Array *current = NULL; int inNamespaces = 0; char line[1024]; if (!file) { return NULL; } root = HashMapCreate(); ns = HashMapCreate(); while (fgets(line, sizeof(line), file)) { char *s = Trim(line); char *colon; if (!*s || *s == '#') { continue; } if (*s == '-') { char *item = Trim(s + 1); if (current && strncmp(item, "regex:", 6) == 0) { HashMap *entry = HashMapCreate(); HashMapSet(entry, "regex", JsonValueString(Unquote(Trim(item + 6)))); ArrayAdd(current, JsonValueObject(entry)); } continue; } colon = strchr(s, ':'); if (!colon) { continue; } *colon = '\0'; s = Trim(s); if (strcmp(s, "namespaces") == 0) { inNamespaces = 1; current = NULL; continue; } if (inNamespaces) { if (strcmp(s, "users") == 0) { users = ArrayCreate(); current = users; } else if (strcmp(s, "aliases") == 0) { aliases = ArrayCreate(); current = aliases; } else if (strcmp(s, "rooms") == 0) { rooms = ArrayCreate(); current = rooms; } continue; } HashMapSet(root, s, JsonValueString(Unquote(Trim(colon + 1)))); } fclose(file); if (users) { HashMapSet(ns, "users", JsonValueArray(users)); } if (aliases) { HashMapSet(ns, "aliases", JsonValueArray(aliases)); } if (rooms) { HashMapSet(ns, "rooms", JsonValueArray(rooms)); } HashMapSet(root, "namespaces", JsonValueObject(ns)); return root; } static Appservice * FromJson(HashMap * json) { Appservice *as; HashMap *ns; if (!json) { return NULL; } as = Malloc(sizeof(Appservice)); if (!as) { return NULL; } memset(as, 0, sizeof(Appservice)); as->id = StrDuplicate(JsonValueAsString(HashMapGet(json, "id"))); as->asToken = StrDuplicate(JsonValueAsString(HashMapGet(json, "as_token"))); as->hsToken = StrDuplicate(JsonValueAsString(HashMapGet(json, "hs_token"))); as->url = StrDuplicate(JsonValueAsString(HashMapGet(json, "url"))); as->sender = StrDuplicate(JsonValueAsString(HashMapGet(json, "sender_localpart"))); ns = JsonValueAsObject(HashMapGet(json, "namespaces")); as->users = CompileList(ns ? HashMapGet(ns, "users") : NULL); as->aliases = CompileList(ns ? HashMapGet(ns, "aliases") : NULL); if (!as->id || !as->asToken) { Free(as->id); Free(as->asToken); Free(as); return NULL; } return as; } int AppserviceInit(void) { DIR *dir; struct dirent *ent; if (appservices) { return 0; } appservices = ArrayCreate(); dir = opendir("appservices"); if (!dir) { return 0; } while ((ent = readdir(dir)) != NULL) { char *path; Stream *stream; HashMap *json; Appservice *as; if (ent->d_name[0] == '.') { continue; } path = StrConcat(2, "appservices/", ent->d_name); stream = StreamOpen(path, "r"); if (!stream) { Free(path); continue; } if (strstr(ent->d_name, ".json")) { json = JsonDecode(stream); StreamClose(stream); } else { StreamClose(stream); json = YamlLoad(path); } Free(path); as = FromJson(json); JsonFree(json); if (as) { ArrayAdd(appservices, as); Log(LOG_INFO, "Loaded appservice: %s", as->id); } } closedir(dir); return 0; } Appservice * AppserviceGet(const char *id) { size_t i; if (!appservices || !id) { return NULL; } for (i = 0; i < ArraySize(appservices); i++) { Appservice *as = ArrayGet(appservices, i); if (as->id && StrEquals(as->id, (char *) id)) { return as; } } return NULL; } Appservice * AppserviceFromToken(const char *token) { size_t i; if (!appservices || !token) { return NULL; } for (i = 0; i < ArraySize(appservices); i++) { Appservice *as = ArrayGet(appservices, i); if (as->asToken && StrEquals(as->asToken, (char *) token)) { return as; } } return NULL; } char * AppserviceID(Appservice * as) { return as ? as->id : NULL; } char * AppserviceSender(Appservice * as, const char *serverName) { if (!as || !as->sender || !serverName) { return NULL; } return StrConcat(4, "@", as->sender, ":", serverName); } static int MatchAny(Array * patterns, const char *value) { size_t i; if (!patterns || !value) { return 0; } for (i = 0; i < ArraySize(patterns); i++) { regex_t *re = ArrayGet(patterns, i); if (re && regexec(re, value, 0, NULL, 0) == 0) { return 1; } } return 0; } int AppserviceAllowsUser(Appservice * as, const char *userId) { return as ? MatchAny(as->users, userId) : 0; } int AppserviceAllowsAlias(Appservice * as, const char *alias) { return as ? MatchAny(as->aliases, alias) : 0; } static int ParseTarget(Appservice * as, char ** host, unsigned short *port) { char *rest; char *colon; if (!as->url || strncmp(as->url, "http://", 7) != 0) { return 0; } rest = StrDuplicate(as->url + 7); if (!rest) { return 0; } colon = strrchr(rest, ':'); if (colon) { *colon = '\0'; *port = (unsigned short) atoi(colon + 1); } else { *port = 80; } *host = rest; return 1; } static int SendTxn(AsTxn * t) { char *host = NULL; unsigned short port = 0; int attempt; int delivered = 0; if (!ParseTarget(t->as, &host, &port)) { Log(LOG_WARNING, "Appservice %s has no usable http url", t->as->id); return 0; } for (attempt = 0; attempt < 3 && !delivered; attempt++) { char *path = StrConcat(2, "/_matrix/app/v1/transactions/", t->txnId); HttpClientContext *context = HttpRequest(HTTP_PUT, 0, port, host, path); Free(path); if (context) { Stream *stream = HttpClientStream(context); char *auth = StrConcat(2, "Bearer ", t->as->hsToken ? t->as->hsToken : ""); char lenBuf[32]; HttpStatus status; snprintf(lenBuf, sizeof(lenBuf), "%lu", (unsigned long) strlen(t->body)); HttpRequestHeader(context, "Authorization", auth); HttpRequestHeader(context, "Content-Type", "application/json"); HttpRequestHeader(context, "Content-Length", lenBuf); HttpRequestSendHeaders(context); StreamPuts(stream, t->body); status = HttpRequestSend(context); Free(auth); HttpClientContextFree(context); if (status >= HTTP_OK && status < HTTP_MULTIPLE_CHOICES) { delivered = 1; } } if (!delivered) { usleep(300000 * (attempt + 1)); } } Free(host); return delivered; } static char * QueuePath(const char * txnId) { return StrConcat(3, "appservice-queue/", (char *) txnId, ".json"); } static void QueuePersist(AsTxn * txn) { HashMap *json = HashMapCreate(); Stream *stream; char *path = QueuePath(txn->txnId); HashMapSet(json, "as", JsonValueString(txn->as->id)); HashMapSet(json, "txn", JsonValueString(txn->txnId)); HashMapSet(json, "body", JsonValueString(txn->body)); stream = StreamOpen(path, "w"); if (stream) { JsonEncode(json, stream, -1); StreamClose(stream); } Free(path); JsonFree(json); } static void QueueRemove(AsTxn * txn) { char *path = QueuePath(txn->txnId); remove(path); Free(path); } static void QueueLoad(void) { DIR *dir = opendir("appservice-queue"); struct dirent *ent; if (!dir) { return; } while ((ent = readdir(dir)) != NULL) { char *path; Stream *stream; HashMap *json; AsTxn *txn; char *asId; char *txnId; char *body; if (ent->d_name[0] == '.') { continue; } path = StrConcat(2, "appservice-queue/", ent->d_name); stream = StreamOpen(path, "r"); Free(path); if (!stream) { continue; } json = JsonDecode(stream); StreamClose(stream); asId = json ? JsonValueAsString(HashMapGet(json, "as")) : NULL; txnId = json ? JsonValueAsString(HashMapGet(json, "txn")) : NULL; body = json ? JsonValueAsString(HashMapGet(json, "body")) : NULL; txn = NULL; if (asId && txnId && body) { Appservice *as = AppserviceGet(asId); if (as) { txn = Malloc(sizeof(AsTxn)); if (txn) { txn->as = as; txn->txnId = StrDuplicate(txnId); txn->body = StrDuplicate(body); } } } JsonFree(json); if (txn) { ArrayAdd(queue, txn); } } closedir(dir); } static void * QueueWorker(void *arg) { (void) arg; while (1) { AsTxn *txn; pthread_mutex_lock(&queueLock); while (ArraySize(queue) == 0) { pthread_cond_wait(&queueCond, &queueLock); } txn = ArrayDelete(queue, 0); pthread_mutex_unlock(&queueLock); if (txn) { int tries = 0; while (!SendTxn(txn) && tries < 20) { tries++; sleep(10); } QueueRemove(txn); Free(txn->txnId); Free(txn->body); Free(txn); } } return NULL; } void AppserviceStart(void) { pthread_t thread; if (!queue) { queue = ArrayCreate(); } if (!queue) { return; } mkdir("appservice-queue", 0700); QueueLoad(); if (pthread_create(&thread, NULL, QueueWorker, NULL) == 0) { pthread_detach(thread); } } static int RoomMatches(Appservice * as, HashMap * state) { HashMap *members; char *userId; void *value; size_t i = 0; if (!state) { return 0; } members = JsonValueAsObject(HashMapGet(state, "m.room.member")); if (!members) { return 0; } while (HashMapIterateReentrant(members, &userId, &value, &i)) { if (MatchAny(as->users, userId)) { return 1; } } return 0; } void AppserviceQueueEvent(HashMap * event, HashMap * state) { char *sender; size_t i; if (!appservices || !event) { return; } sender = JsonValueAsString(HashMapGet(event, "sender")); for (i = 0; i < ArraySize(appservices); i++) { Appservice *as = ArrayGet(appservices, i); HashMap *payload; HashMap *copy; Array *events; AsTxn *txn; FILE *mem; Stream *out; char *body = NULL; size_t len = 0; if (!MatchAny(as->users, sender) && !RoomMatches(as, state)) { continue; } copy = JsonDuplicate(event); HashMapDelete(copy, "_seq"); events = ArrayCreate(); ArrayAdd(events, JsonValueObject(copy)); payload = HashMapCreate(); HashMapSet(payload, "events", JsonValueArray(events)); mem = open_memstream(&body, &len); if (!mem) { JsonFree(payload); continue; } out = StreamFile(mem); if (!out) { fclose(mem); free(body); JsonFree(payload); continue; } JsonEncode(payload, out, -1); StreamClose(out); JsonFree(payload); txn = Malloc(sizeof(AsTxn)); if (!txn) { free(body); continue; } txn->as = as; txn->txnId = StrRandom(16); txn->body = StrDuplicate(body); free(body); if (!txn->txnId || !txn->body) { Free(txn->txnId); Free(txn->body); Free(txn); continue; } QueuePersist(txn); pthread_mutex_lock(&queueLock); ArrayAdd(queue, txn); pthread_cond_signal(&queueCond); pthread_mutex_unlock(&queueLock); } }