/* * RoutesRoom.c - bundled Matrix route handlers. * * merged from: RouteCreateRoom.c, RouteJoinRoom.c, RouteLeaveRoom.c, RouteSendEvent.c, RouteMessages.c, RouteSync.c, RouteRoomAliases.c, RouteAliasDirectory.c, RouteFilter.c * (each handler registered in Routes.c) */ /* * Copyright (C) 2022-2025 Jordan Bancino <@jordan:synapse.telodendria.org> * with other valuable contributors. See CONTRIBUTORS.txt for the full list. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation files * (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static Array * StateEventsToArray(HashMap *); static Array * TimelineSince(Db *, char *, uint64_t, int); static int RoomMemberJoined(Room *, char *); static int RoomUserPower(Room *, char *); static int RoomEventRequiredLevel(Room *, char *); static int RoomStateRequiredLevel(Room *, char *); static int RoomRedactLevel(Room *); static int EventTypeAllowed(char *, Array *, Array *); static HashMap * FilterDecodeInline(char *); static int RoomFilterAllowed(char *, Array *, Array *); static void TypingSet(char *, char *, long); static Array * TypingUsers(char *); static char * RoomSendMembership(Room * room, char * sender, char * target, char * membership) { HashMap *event = HashMapCreate(); HashMap *content = HashMapCreate(); char *eventId = StrConcat(2, "$", StrRandom(24)); char *roomId = RoomIdGet(room); HashMapSet(content, "membership", JsonValueString(membership)); HashMapSet(event, "event_id", JsonValueString(eventId)); HashMapSet(event, "type", JsonValueString("m.room.member")); HashMapSet(event, "state_key", JsonValueString(target)); HashMapSet(event, "sender", JsonValueString(sender)); HashMapSet(event, "room_id", JsonValueString(roomId)); HashMapSet(event, "origin_server_ts", JsonValueInteger((uint64_t) time(NULL) * 1000)); HashMapSet(event, "content", JsonValueObject(content)); RoomEventSend(room, event); JsonFree(event); return eventId; } ROUTE_IMPL(RouteCreateRoom, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *request = NULL; HashMap *response = NULL; RoomCreateRequest parsed; User *user = NULL; Room *room = NULL; Config config; char *err = NULL; char *token = NULL; char *userId = NULL; char *roomId = NULL; (void) path; memset(&parsed, 0, sizeof(parsed)); if (HttpRequestMethodGet(args->context) != HTTP_POST) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, NULL); } ConfigLock(db, &config); if (!config.ok) { Log(LOG_ERR, "%s", config.err); HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } request = JsonDecode(HttpServerStream(args->context)); if (!request) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_NOT_JSON, NULL); goto finish; } if (!RoomCreateRequestFromJson(request, &parsed, &err)) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_BAD_JSON, err); goto finish; } if (!HashMapGet(request, "preset")) { JsonValue *vis = HashMapGet(request, "visibility"); parsed.preset = (vis && StrEquals(JsonValueAsString(vis), "public")) ? ROOM_CREATE_PUBLIC : ROOM_CREATE_PRIVATE; } userId = StrConcat(4, "@", UserGetName(user), ":", config.serverName); room = RoomCreate(db, &parsed, userId); if (!room) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); response = MatrixErrorCreate(M_UNKNOWN, NULL); goto finish; } roomId = StrDuplicate(RoomIdGet(room)); response = HashMapCreate(); HashMapSet(response, "room_id", JsonValueString(roomId)); finish: if (room) { RoomUnlock(room); } if (user) { UserUnlock(user); } if (request) { JsonFree(request); } ConfigUnlock(&config); Free(userId); Free(roomId); return response; } /* * Copyright (C) 2022-2025 Jordan Bancino <@jordan:synapse.telodendria.org> * with other valuable contributors. See CONTRIBUTORS.txt for the full list. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation files * (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include #include #include #include #include #include #include #include ROUTE_IMPL(RouteJoinRoom, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *response = NULL; User *user = NULL; Room *room = NULL; Config config; char *token = NULL; char *roomId; char *userId = NULL; int resolvedRoom = 0; if (HttpRequestMethodGet(args->context) != HTTP_POST) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, NULL); } roomId = ArrayGet(path, 0); ConfigLock(db, &config); if (!config.ok) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } userId = StrConcat(4, "@", UserGetName(user), ":", config.serverName); if (roomId && roomId[0] == '#') { char *resolved = FederationResolveAlias(db, config.serverName, roomId); if (resolved) { roomId = resolved; resolvedRoom = 1; } } room = RoomLock(db, roomId); if (room) { char *colon = strrchr(roomId, ':'); if (colon && !StrEquals(colon + 1, config.serverName)) { HashMap *member = JsonValueAsObject(JsonGet(RoomStateGet(room), 2, "m.room.member", userId)); char *membership = member ? JsonValueAsString(HashMapGet(member, "membership")) : NULL; if (!membership || !StrEquals(membership, "join")) { char *err = NULL; RoomUnlock(room); room = NULL; if (FederationJoinRemote(db, config.serverName, roomId, userId, &err) == 0) { Free(err); response = HashMapCreate(); HashMapSet(response, "room_id", JsonValueString(StrDuplicate(roomId))); goto finish; } HttpResponseStatus(args->context, HTTP_BAD_GATEWAY); response = MatrixErrorCreate(M_UNKNOWN, err ? err : "federation join failed"); Free(err); goto finish; } } } else { char *colon = strrchr(roomId, ':'); if (colon && !StrEquals(colon + 1, config.serverName)) { char *err = NULL; if (FederationJoinRemote(db, config.serverName, roomId, userId, &err) == 0) { Free(err); response = HashMapCreate(); HashMapSet(response, "room_id", JsonValueString(StrDuplicate(roomId))); goto finish; } HttpResponseStatus(args->context, HTTP_BAD_GATEWAY); response = MatrixErrorCreate(M_UNKNOWN, err ? err : "federation join failed"); Free(err); goto finish; } HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, NULL); goto finish; } { HashMap *state = RoomStateGet(room); HashMap *rules = JsonValueAsObject(JsonGet(state, 2, "m.room.join_rules", "")); char *joinRule = rules ? JsonValueAsString(HashMapGet(rules, "join_rule")) : NULL; HashMap *member = JsonValueAsObject(JsonGet(state, 2, "m.room.member", userId)); char *membership = member ? JsonValueAsString(HashMapGet(member, "membership")) : NULL; if ((!joinRule || !StrEquals(joinRule, "public")) && (!membership || !StrEquals(membership, "invite")) && (!membership || !StrEquals(membership, "join"))) { HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, NULL); goto finish; } if (!membership || !StrEquals(membership, "join")) { Free(RoomSendMembership(room, userId, userId, "join")); } } response = HashMapCreate(); HashMapSet(response, "room_id", JsonValueString(roomId)); finish: if (room) { RoomUnlock(room); } if (user) { UserUnlock(user); } ConfigUnlock(&config); Free(userId); return response; } /* * Copyright (C) 2022-2025 Jordan Bancino <@jordan:synapse.telodendria.org> * with other valuable contributors. See CONTRIBUTORS.txt for the full list. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation files * (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include #include #include #include #include #include #include #include #include ROUTE_IMPL(RouteLeaveRoom, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *response = NULL; User *user = NULL; Room *room = NULL; Config config; char *token = NULL; char *roomId; char *userId = NULL; if (HttpRequestMethodGet(args->context) != HTTP_POST) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, NULL); } roomId = ArrayGet(path, 0); ConfigLock(db, &config); if (!config.ok) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } room = RoomLock(db, roomId); if (!room) { HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, NULL); goto finish; } userId = StrConcat(4, "@", UserGetName(user), ":", config.serverName); { HashMap *state = RoomStateGet(room); HashMap *member = JsonValueAsObject(JsonGet(state, 2, "m.room.member", userId)); char *membership = member ? JsonValueAsString(HashMapGet(member, "membership")) : NULL; if (membership && StrEquals(membership, "join")) { Free(RoomSendMembership(room, userId, userId, "leave")); } } response = HashMapCreate(); finish: if (room) { RoomUnlock(room); } if (user) { UserUnlock(user); } ConfigUnlock(&config); Free(userId); return response; } /* * Copyright (C) 2022-2025 Jordan Bancino <@jordan:synapse.telodendria.org> * with other valuable contributors. See CONTRIBUTORS.txt for the full list. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation files * (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include #include #include #include #include #include #include #include #include ROUTE_IMPL(RouteSendEvent, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *request = NULL; HashMap *response = NULL; HashMap *event = NULL; User *user = NULL; Room *room = NULL; Config config; char *token = NULL; char *roomId; char *type; char *txn; char *userId = NULL; char *eventId = NULL; if (HttpRequestMethodGet(args->context) != HTTP_PUT) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, NULL); } roomId = ArrayGet(path, 0); type = ArrayGet(path, 1); txn = ArrayGet(path, 2); (void) txn; ConfigLock(db, &config); if (!config.ok) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } request = JsonDecode(HttpServerStream(args->context)); if (!request) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_NOT_JSON, NULL); goto finish; } room = RoomLock(db, roomId); if (!room) { HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, NULL); goto finish; } userId = StrConcat(4, "@", UserGetName(user), ":", config.serverName); eventId = StrConcat(2, "$", StrRandom(24)); if (!RoomMemberJoined(room, userId)) { HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, NULL); goto finish; } if (RoomUserPower(room, userId) < RoomEventRequiredLevel(room, type)) { HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, NULL); goto finish; } event = HashMapCreate(); HashMapSet(event, "type", JsonValueString(type)); HashMapSet(event, "sender", JsonValueString(userId)); HashMapSet(event, "room_id", JsonValueString(roomId)); HashMapSet(event, "origin_server_ts", JsonValueInteger((uint64_t) time(NULL) * 1000)); HashMapSet(event, "content", JsonValueObject(JsonDuplicate(request))); RoomEventFill(room, event); EventSign(room, event); Free(eventId); eventId = EventIdGet(room, event); HashMapSet(event, "event_id", JsonValueString(StrDuplicate(eventId))); if (!RoomEventAppend(room, event)) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); response = MatrixErrorCreate(M_UNKNOWN, NULL); goto finish; } { Array *ids = ArrayCreate(); ArrayAdd(ids, JsonValueString(StrDuplicate(eventId))); RoomPrevEventsSet(room, ids); JsonValueFree(JsonValueArray(ids)); } FederationSendPdu(db, config.serverName, roomId, event); response = HashMapCreate(); HashMapSet(response, "event_id", JsonValueString(eventId)); finish: if (room) { RoomUnlock(room); } if (user) { UserUnlock(user); } if (event) { JsonFree(event); } if (request) { JsonFree(request); } ConfigUnlock(&config); Free(userId); Free(eventId); return response; } /* * Copyright (C) 2022-2025 Jordan Bancino <@jordan:synapse.telodendria.org> * with other valuable contributors. See CONTRIBUTORS.txt for the full list. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation files * (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include #include #include #include #include #include #include #include ROUTE_IMPL(RouteMessages, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *response = NULL; User *user = NULL; Room *room = NULL; Array *events = NULL; Config config; char *token = NULL; char *roomId; char startTok[32]; char endTok[32]; size_t i; if (HttpRequestMethodGet(args->context) != HTTP_GET) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, NULL); } roomId = ArrayGet(path, 0); ConfigLock(db, &config); if (!config.ok) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } room = RoomLock(db, roomId); if (!room) { HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, NULL); goto finish; } events = ArrayCreate(); { HashMap *params = HttpRequestParams(args->context); Array *stored = NULL; DbRef *eref; char *fromStr = NULL; char *toStr = NULL; size_t n = 0; long limit = 10; int back = 1; uint64_t from = 0, to = 0, maxseq = 0, endseq = 0; int hasTo = 0; HashMap *msgFilter = NULL; Array *msgTypes = NULL; Array *msgNotTypes = NULL; if (params) { char *l = HashMapGet(params, "limit"); char *d = HashMapGet(params, "dir"); fromStr = HashMapGet(params, "from"); toStr = HashMapGet(params, "to"); if (l) { limit = atol(l); } if (d && StrEquals(d, "f")) { back = 0; } } if (limit < 1) { limit = 1; } if (limit > 1000) { limit = 1000; } if (toStr && *toStr) { to = strtoull(toStr, NULL, 10); hasTo = 1; } if (params) { char *f = HashMapGet(params, "filter"); if (f && f[0]) { if (f[0] == '{') { msgFilter = FilterDecodeInline(f); } else { DbRef *fref = DbLock(db, 3, "filters", UserGetName(user), f); if (fref) { msgFilter = JsonDuplicate(DbJson(fref)); DbUnlock(db, fref); } } if (msgFilter) { HashMap *roomF = JsonValueAsObject(HashMapGet(msgFilter, "room")); HashMap *tlF = roomF ? JsonValueAsObject(HashMapGet(roomF, "timeline")) : NULL; msgTypes = tlF ? JsonValueAsArray(HashMapGet(tlF, "types")) : NULL; msgNotTypes = tlF ? JsonValueAsArray(HashMapGet(tlF, "not_types")) : NULL; } } } eref = DbLock(db, 3, "rooms", roomId, "events"); if (eref) { stored = JsonValueAsArray(HashMapGet(DbJson(eref), "events")); } if (stored) { n = ArraySize(stored); for (i = 0; i < n; i++) { JsonValue *sv = HashMapGet(JsonValueAsObject((JsonValue *) ArrayGet(stored, i)), "_seq"); if (sv && (uint64_t) JsonValueAsInteger(sv) > maxseq) { maxseq = JsonValueAsInteger(sv); } } } if (fromStr && *fromStr && !StrEquals(fromStr, "t0")) { from = strtoull(fromStr, NULL, 10); } else { from = back ? maxseq + 1 : 0; } if (stored && back) { for (i = n; i > 0 && ArraySize(events) < (size_t) limit; i--) { HashMap *ev = JsonValueAsObject(ArrayGet(stored, i - 1)); JsonValue *sv = ev ? HashMapGet(ev, "_seq") : NULL; uint64_t seq = sv ? JsonValueAsInteger(sv) : 0; char *etype; if (seq >= from) { continue; } if (hasTo && seq <= to) { break; } endseq = seq; etype = ev ? JsonValueAsString(HashMapGet(ev, "type")) : NULL; if (!EventTypeAllowed(etype, msgTypes, msgNotTypes)) { continue; } { HashMap *copy = JsonDuplicate(ev); HashMapDelete(copy, "_seq"); ArrayAdd(events, JsonValueObject(copy)); } } } else if (stored) { for (i = 0; i < n && ArraySize(events) < (size_t) limit; i++) { HashMap *ev = JsonValueAsObject(ArrayGet(stored, i)); JsonValue *sv = ev ? HashMapGet(ev, "_seq") : NULL; uint64_t seq = sv ? JsonValueAsInteger(sv) : 0; char *etype; if (seq <= from) { continue; } if (hasTo && seq >= to) { break; } endseq = seq; etype = ev ? JsonValueAsString(HashMapGet(ev, "type")) : NULL; if (!EventTypeAllowed(etype, msgTypes, msgNotTypes)) { continue; } { HashMap *copy = JsonDuplicate(ev); HashMapDelete(copy, "_seq"); ArrayAdd(events, JsonValueObject(copy)); } } } if (eref) { DbUnlock(db, eref); } if (endseq == 0) { endseq = from; } snprintf(startTok, sizeof(startTok), "%llu", (unsigned long long) from); snprintf(endTok, sizeof(endTok), "%llu", (unsigned long long) endseq); JsonFree(msgFilter); } response = HashMapCreate(); HashMapSet(response, "chunk", JsonValueArray(events)); HashMapSet(response, "start", JsonValueString(startTok)); HashMapSet(response, "end", JsonValueString(endTok)); finish: if (room) { RoomUnlock(room); } if (user) { UserUnlock(user); } ConfigUnlock(&config); return response; } /* * Copyright (C) 2022-2025 Jordan Bancino <@jordan:synapse.telodendria.org> * with other valuable contributors. See CONTRIBUTORS.txt for the full list. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation files * (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static Array * StateEventsToArray(HashMap * state) { Array *arr = ArrayCreate(); char *type; void *val; while (HashMapIterate(state, &type, &val)) { HashMap *keys = JsonValueAsObject(val); char *skey; void *val2; while (HashMapIterate(keys, &skey, &val2)) { HashMap *ev = HashMapCreate(); HashMapSet(ev, "type", JsonValueString(type)); HashMapSet(ev, "state_key", JsonValueString(skey)); HashMapSet(ev, "content", JsonValueObject(JsonDuplicate(JsonValueAsObject(val2)))); ArrayAdd(arr, JsonValueObject(ev)); } } return arr; } static int EventTypeAllowed(char *type, Array *types, Array *notTypes) { size_t i; int found; if (!type) { return 0; } if (types && ArraySize(types) > 0) { found = 0; for (i = 0; i < ArraySize(types); i++) { char *pattern = JsonValueAsString(ArrayGet(types, i)); if (pattern && fnmatch(pattern, type, 0) == 0) { found = 1; break; } } if (!found) { return 0; } } for (i = 0; notTypes && i < ArraySize(notTypes); i++) { char *pattern = JsonValueAsString(ArrayGet(notTypes, i)); if (pattern && fnmatch(pattern, type, 0) == 0) { return 0; } } return 1; } static HashMap * FilterDecodeInline(char *json) { FILE *mem; Stream *stream; HashMap *out; mem = fmemopen(json, strlen(json), "r"); if (!mem) { return NULL; } stream = StreamFile(mem); if (!stream) { fclose(mem); return NULL; } out = JsonDecode(stream); StreamClose(stream); return out; } static int RoomFilterAllowed(char *rid, Array *rooms, Array *notRooms) { size_t i; int found; if (rooms && ArraySize(rooms) > 0) { found = 0; for (i = 0; i < ArraySize(rooms); i++) { char *r = JsonValueAsString(ArrayGet(rooms, i)); if (r && StrEquals(r, rid)) { found = 1; break; } } if (!found) { return 0; } } for (i = 0; notRooms && i < ArraySize(notRooms); i++) { char *r = JsonValueAsString(ArrayGet(notRooms, i)); if (r && StrEquals(r, rid)) { return 0; } } return 1; } static Array * StateEventsToArrayFiltered(HashMap * state, char *userId, int lazy, Array *types, Array *notTypes) { Array *arr = ArrayCreate(); char *type; void *val; while (HashMapIterate(state, &type, &val)) { HashMap *keys = JsonValueAsObject(val); char *skey; void *val2; if (!EventTypeAllowed(type, types, notTypes)) { continue; } while (keys && HashMapIterate(keys, &skey, &val2)) { HashMap *ev; if (lazy && StrEquals(type, "m.room.member") && !StrEquals(skey, userId)) { continue; } ev = HashMapCreate(); HashMapSet(ev, "type", JsonValueString(type)); HashMapSet(ev, "state_key", JsonValueString(skey)); HashMapSet(ev, "content", JsonValueObject(JsonDuplicate(JsonValueAsObject(val2)))); ArrayAdd(arr, JsonValueObject(ev)); } } return arr; } static Array * TimelineSince(Db * db, char *rid, uint64_t since, int includeAll) { DbRef *ref = DbLock(db, 3, "rooms", rid, "events"); Array *arr = ArrayCreate(); if (ref) { Array *stored = JsonValueAsArray(HashMapGet(DbJson(ref), "events")); size_t i; if (stored) { for (i = 0; i < ArraySize(stored); i++) { HashMap *ev = JsonValueAsObject(ArrayGet(stored, i)); JsonValue *sv = HashMapGet(ev, "_seq"); uint64_t seq = sv ? JsonValueAsInteger(sv) : 0; if (includeAll || seq > since) { HashMap *copy = JsonDuplicate(ev); HashMapDelete(copy, "_seq"); ArrayAdd(arr, JsonValueObject(copy)); } } } DbUnlock(db, ref); } return arr; } static HashMap * ReceiptsFor(Db * db, char *rid, char *userId) { DbRef *ref = DbLock(db, 3, "rooms", rid, "receipts"); HashMap *content = NULL; if (!ref) { return NULL; } { HashMap *stored = DbJson(ref); char *key; void *val; while (HashMapIterate(stored, &key, &val)) { HashMap *mine = JsonValueAsObject((JsonValue *) val); const char *eventId = mine ? JsonValueAsString(HashMapGet(mine, "m.read")) : NULL; if (eventId) { HashMap *ev; HashMap *read; HashMap *info; JsonValue *ts; if (!content) { content = HashMapCreate(); } ev = JsonValueAsObject(HashMapGet(content, eventId)); if (!ev) { ev = HashMapCreate(); HashMapSet(content, eventId, JsonValueObject(ev)); } read = JsonValueAsObject(HashMapGet(ev, "m.read")); if (!read) { read = HashMapCreate(); HashMapSet(ev, "m.read", JsonValueObject(read)); } info = HashMapCreate(); ts = HashMapGet(mine, "ts"); if (ts) { HashMapSet(info, "ts", JsonValueDuplicate(ts)); } HashMapSet(read, key, JsonValueObject(info)); } } } if (userId) { HashMap *mine = JsonValueAsObject(HashMapGet(DbJson(ref), userId)); const char *eventId = mine ? JsonValueAsString(HashMapGet(mine, "m.read.private")) : NULL; if (eventId) { HashMap *ev; HashMap *read; HashMap *info; JsonValue *ts; if (!content) { content = HashMapCreate(); } ev = JsonValueAsObject(HashMapGet(content, eventId)); if (!ev) { ev = HashMapCreate(); HashMapSet(content, eventId, JsonValueObject(ev)); } read = JsonValueAsObject(HashMapGet(ev, "m.read.private")); if (!read) { read = HashMapCreate(); HashMapSet(ev, "m.read.private", JsonValueObject(read)); } info = HashMapCreate(); ts = HashMapGet(mine, "ts"); if (ts) { HashMapSet(info, "ts", JsonValueDuplicate(ts)); } HashMapSet(read, userId, JsonValueObject(info)); } } DbUnlock(db, ref); return content; } static HashMap * RoomSummary(Room * room, char *userId) { HashMap *state = RoomStateGet(room); HashMap *members = JsonValueAsObject(HashMapGet(state, "m.room.member")); HashMap *summary = HashMapCreate(); Array *heroes = ArrayCreate(); char *key; void *val; long joined = 0; long invited = 0; while (members && HashMapIterate(members, &key, &val)) { HashMap *m = JsonValueAsObject((JsonValue *) val); const char *mem = m ? JsonValueAsString(HashMapGet(m, "membership")) : NULL; if (mem && StrEquals(mem, "join")) { joined++; } else if (mem && StrEquals(mem, "invite")) { invited++; } if (mem && StrEquals(mem, "join") && !StrEquals(key, userId) && ArraySize(heroes) < 5) { const char *dn = JsonValueAsString(HashMapGet(m, "displayname")); ArrayAdd(heroes, JsonValueString((char *) (dn && dn[0] ? dn : key))); } } HashMapSet(summary, "m.heroes", JsonValueArray(heroes)); HashMapSet(summary, "m.joined_member_count", JsonValueInteger(joined)); HashMapSet(summary, "m.invited_member_count", JsonValueInteger(invited)); return summary; } static Array * AccountDataEvents(Db * db, char *local) { DbRef *ref; Array *events = ArrayCreate(); if (!local || !local[0]) { return events; } ref = DbLock(db, 2, "accountdata", local); if (ref) { HashMap *stored = DbJson(ref); char *type; void *val; while (HashMapIterate(stored, &type, &val)) { HashMap *ev = HashMapCreate(); HashMapSet(ev, "type", JsonValueString(type)); HashMapSet(ev, "content", JsonValueDuplicate((JsonValue *) val)); ArrayAdd(events, JsonValueObject(ev)); } DbUnlock(db, ref); } return events; } static Array * RoomAccountDataEvents(Db * db, char *rid, char *local) { DbRef *ref = DbLock(db, 4, "rooms", rid, "accountdata", local); Array *events = ArrayCreate(); if (ref) { HashMap *stored = DbJson(ref); char *type; void *val; while (HashMapIterate(stored, &type, &val)) { HashMap *ev = HashMapCreate(); HashMapSet(ev, "type", JsonValueString(type)); HashMapSet(ev, "content", JsonValueDuplicate((JsonValue *) val)); ArrayAdd(events, JsonValueObject(ev)); } DbUnlock(db, ref); } return events; } static HashMap * PresenceEvent(Db * db, char *mxid) { char *local; DbRef *ref; HashMap *out = NULL; if (!mxid || mxid[0] != '@' || !strchr(mxid, ':')) { return NULL; } local = StrSubstr(mxid, 1, strcspn(mxid + 1, ":") + 1); ref = DbLock(db, 2, "presence", local); Free(local); if (ref) { HashMap *content = JsonDuplicate(DbJson(ref)); DbUnlock(db, ref); out = HashMapCreate(); HashMapSet(out, "type", JsonValueString("m.presence")); HashMapSet(out, "sender", JsonValueString(mxid)); HashMapSet(out, "content", JsonValueObject(content)); } return out; } static int MentionsUser(HashMap * event, char *userId) { HashMap *content = JsonValueAsObject(HashMapGet(event, "content")); HashMap *mentions = content ? JsonValueAsObject(HashMapGet(content, "m.mentions")) : NULL; Array *ids = mentions ? JsonValueAsArray(HashMapGet(mentions, "user_ids")) : NULL; size_t i; for (i = 0; ids && i < ArraySize(ids); i++) { char *id = JsonValueAsString(ArrayGet(ids, i)); if (id && StrEquals(id, userId)) { return 1; } } return 0; } static HashMap * UnreadFor(Db * db, char *rid, char *userId) { HashMap *out = HashMapCreate(); char *readEvent = NULL; long count = 0; long highlights = 0; int after; { DbRef *rref = DbLock(db, 3, "rooms", rid, "receipts"); if (rref) { HashMap *mine = JsonValueAsObject(HashMapGet(DbJson(rref), userId)); if (mine) { char *priv = JsonValueAsString(HashMapGet(mine, "m.read.private")); char *pub = JsonValueAsString(HashMapGet(mine, "m.read")); readEvent = StrDuplicate(priv ? priv : pub); } DbUnlock(db, rref); } } after = readEvent ? 0 : 1; { DbRef *ref = DbLock(db, 3, "rooms", rid, "events"); Array *events = ref ? JsonValueAsArray(HashMapGet(DbJson(ref), "events")) : NULL; size_t i; for (i = 0; events && i < ArraySize(events); i++) { HashMap *ev = JsonValueAsObject(ArrayGet(events, i)); const char *eid = ev ? JsonValueAsString(HashMapGet(ev, "event_id")) : NULL; const char *sender = ev ? JsonValueAsString(HashMapGet(ev, "sender")) : NULL; const char *type = ev ? JsonValueAsString(HashMapGet(ev, "type")) : NULL; if (readEvent && eid && StrEquals(eid, readEvent)) { after = 1; continue; } if (!after || !type || !StrEquals(type, "m.room.message")) { continue; } if (sender && StrEquals(sender, userId)) { continue; } count++; if (MentionsUser(ev, userId)) { highlights++; } } if (ref) { DbUnlock(db, ref); } } Free(readEvent); HashMapSet(out, "notification_count", JsonValueInteger(count)); HashMapSet(out, "highlight_count", JsonValueInteger(highlights)); return out; } ROUTE_IMPL(RouteSync, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *response = NULL; HashMap *rooms = NULL; HashMap *join = NULL; HashMap *invite = NULL; HashMap *knock = NULL; HashMap *params = NULL; HashMap *otkCounts = NULL; Array *fallbackTypes = NULL; Array *presenceEvents = NULL; HashMap *presenceSeen = NULL; HashMap *syncFilter = NULL; Array *filterTypes = NULL; Array *filterNotTypes = NULL; Array *filterRooms = NULL; Array *filterNotRooms = NULL; Array *stateTypes = NULL; Array *stateNotTypes = NULL; long filterLimit = -1; int lazyMembers = 0; User *user = NULL; Config config; char *token = NULL; char *userId = NULL; char *syncUser = NULL; char *syncDevice = NULL; uint64_t since = 0; long timeout = 0; int cfgLocked = 0, userLocked = 0; (void) path; ConfigLock(db, &config); cfgLocked = 1; if (!config.ok) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); response = MatrixErrorCreate(M_UNKNOWN, config.err); goto finish; } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } userLocked = 1; userId = StrConcat(4, "@", UserGetName(user), ":", config.serverName); { char *devId = UserGetDeviceId(user); HashMap *devs = UserGetDevices(user); HashMap *dev = (devs && devId) ? JsonValueAsObject(HashMapGet(devs, devId)) : NULL; HashMap *otks = dev ? JsonValueAsObject(HashMapGet(dev, "one_time_keys")) : NULL; otkCounts = HashMapCreate(); fallbackTypes = ArrayCreate(); if (otks) { char *kid; void *vv; while (HashMapIterate(otks, &kid, &vv)) { const char *colon = strchr(kid, ':'); size_t n = colon ? (size_t) (colon - kid) : strlen(kid); char *alg = StrSubstr(kid, 0, n); JsonValue *have = HashMapGet(otkCounts, alg); long c = have ? (long) JsonValueAsInteger(have) : 0; JsonValue *old = HashMapSet(otkCounts, alg, JsonValueInteger(c + 1)); if (old) { JsonValueFree(old); } Free(alg); } } { HashMap *fb = dev ? JsonValueAsObject(HashMapGet(dev, "fallback_keys")) : NULL; if (fb) { char *kid; void *vv; while (HashMapIterate(fb, &kid, &vv)) { const char *colon = strchr(kid, ':'); size_t n = colon ? (size_t) (colon - kid) : strlen(kid); char *alg = StrSubstr(kid, 0, n); int seen = 0; size_t j; for (j = 0; j < ArraySize(fallbackTypes); j++) { char *have = JsonValueAsString(ArrayGet(fallbackTypes, j)); if (have && StrEquals(have, alg)) { seen = 1; break; } } if (!seen) { ArrayAdd(fallbackTypes, JsonValueString(alg)); } Free(alg); } } } } /* Release db refs before the long-poll wait: Cytoplasm holds db->lock * while any ref is held, so holding config/user across the wait would * block every other request. */ syncUser = StrDuplicate(UserGetName(user)); syncDevice = StrDuplicate(UserGetDeviceId(user)); UserUnlock(user); user = NULL; userLocked = 0; ConfigUnlock(&config); cfgLocked = 0; params = HttpRequestParams(args->context); if (params) { char *s = HashMapGet(params, "since"); char *t = HashMapGet(params, "timeout"); since = s ? strtoull(s, NULL, 10) : 0; timeout = t ? atoi(t) : 0; if (timeout > 30000) { timeout = 30000; } } if (timeout > 0 && since > 0 && RoomStreamPosition(db) <= since) { RoomWaitForStream(db, since, timeout); } { char *filterId = params ? HashMapGet(params, "filter") : NULL; if (filterId && filterId[0]) { if (filterId[0] == '{') { syncFilter = FilterDecodeInline(filterId); } else if (syncUser) { DbRef *fref = DbLock(db, 3, "filters", syncUser, filterId); if (fref) { syncFilter = JsonDuplicate(DbJson(fref)); DbUnlock(db, fref); } } if (syncFilter) { HashMap *roomF = JsonValueAsObject(HashMapGet(syncFilter, "room")); HashMap *tlF = roomF ? JsonValueAsObject(HashMapGet(roomF, "timeline")) : NULL; HashMap *stF = roomF ? JsonValueAsObject(HashMapGet(roomF, "state")) : NULL; JsonValue *lim = tlF ? HashMapGet(tlF, "limit") : NULL; if (lim) { filterLimit = JsonValueAsInteger(lim); } filterTypes = tlF ? JsonValueAsArray(HashMapGet(tlF, "types")) : NULL; filterNotTypes = tlF ? JsonValueAsArray(HashMapGet(tlF, "not_types")) : NULL; filterRooms = roomF ? JsonValueAsArray(HashMapGet(roomF, "rooms")) : NULL; filterNotRooms = roomF ? JsonValueAsArray(HashMapGet(roomF, "not_rooms")) : NULL; stateTypes = stF ? JsonValueAsArray(HashMapGet(stF, "types")) : NULL; stateNotTypes = stF ? JsonValueAsArray(HashMapGet(stF, "not_types")) : NULL; lazyMembers = stF ? JsonValueAsBoolean(HashMapGet(stF, "lazy_load_members")) : 0; } } } rooms = HashMapCreate(); join = HashMapCreate(); invite = HashMapCreate(); knock = HashMapCreate(); presenceEvents = ArrayCreate(); presenceSeen = HashMapCreate(); HashMapSet(rooms, "join", JsonValueObject(join)); HashMapSet(rooms, "invite", JsonValueObject(invite)); HashMapSet(rooms, "knock", JsonValueObject(knock)); { DbRef *iref = DbLock(db, 2, "rooms", "index"); Array *ids = iref ? JsonValueAsArray(HashMapGet(DbJson(iref), "rooms")) : NULL; size_t n = ids ? ArraySize(ids) : 0; for (size_t k = 0; k < n; k++) { char *rid = JsonValueAsString(ArrayGet(ids, k)); Room *room = RoomLock(db, rid); HashMap *state; HashMap *member; char *membership; HashMap *syncRoom; HashMap *timelineObj; Array *timeline; if (!room) { continue; } state = RoomStateGet(room); member = JsonValueAsObject(JsonGet(state, 2, "m.room.member", userId)); membership = member ? JsonValueAsString(HashMapGet(member, "membership")) : NULL; if (membership && StrEquals(membership, "invite")) { HashMap *inv = HashMapCreate(); HashMap *inviteState = HashMapCreate(); Array *evs = ArrayCreate(); HashMap *ev = HashMapCreate(); HashMapSet(ev, "type", JsonValueString("m.room.member")); HashMapSet(ev, "state_key", JsonValueString(userId)); HashMapSet(ev, "content", JsonValueObject(JsonDuplicate(member))); ArrayAdd(evs, JsonValueObject(ev)); HashMapSet(inviteState, "events", JsonValueArray(evs)); HashMapSet(inv, "invite_state", JsonValueObject(inviteState)); JsonSet(invite, JsonValueObject(inv), 1, rid); RoomUnlock(room); continue; } if (membership && StrEquals(membership, "knock")) { HashMap *kr = HashMapCreate(); HashMap *ks = HashMapCreate(); HashMapSet(ks, "events", JsonValueArray(StateEventsToArray(state))); HashMapSet(kr, "knock_state", JsonValueObject(ks)); JsonSet(knock, JsonValueObject(kr), 1, rid); RoomUnlock(room); continue; } if (!membership || !StrEquals(membership, "join")) { RoomUnlock(room); continue; } { HashMap *members = JsonValueAsObject(HashMapGet(state, "m.room.member")); char *mkey; void *mval; while (members && HashMapIterate(members, &mkey, &mval)) { if (!HashMapGet(presenceSeen, mkey)) { HashMap *pe = PresenceEvent(db, mkey); HashMapSet(presenceSeen, mkey, JsonValueBoolean(true)); if (pe) { ArrayAdd(presenceEvents, JsonValueObject(pe)); } } } } if (!RoomFilterAllowed(rid, filterRooms, filterNotRooms)) { RoomUnlock(room); continue; } timeline = TimelineSince(db, rid, since, since == 0); { int timelineLimited = 0; if (filterTypes || filterNotTypes || filterLimit >= 0) { Array *filtered = ArrayCreate(); size_t ti; size_t matched = 0; size_t skip = 0; for (ti = 0; ti < ArraySize(timeline); ti++) { HashMap *ev = JsonValueAsObject(ArrayGet(timeline, ti)); char *t = ev ? JsonValueAsString(HashMapGet(ev, "type")) : NULL; if (EventTypeAllowed(t, filterTypes, filterNotTypes)) { matched++; } } if (filterLimit >= 0 && matched > (size_t) filterLimit) { skip = matched - (size_t) filterLimit; timelineLimited = 1; } matched = 0; for (ti = 0; ti < ArraySize(timeline); ti++) { HashMap *ev = JsonValueAsObject(ArrayGet(timeline, ti)); char *t = ev ? JsonValueAsString(HashMapGet(ev, "type")) : NULL; if (!EventTypeAllowed(t, filterTypes, filterNotTypes)) { continue; } if (matched++ < skip) { continue; } ArrayAdd(filtered, JsonValueDuplicate(ArrayGet(timeline, ti))); } for (ti = 0; ti < ArraySize(timeline); ti++) { JsonValueFree(ArrayGet(timeline, ti)); } ArrayFree(timeline); timeline = filtered; } if (since == 0 || (timeline && ArraySize(timeline) > 0)) { ContactsScanRoom(db, rid, state); } timelineObj = HashMapCreate(); HashMapSet(timelineObj, "events", JsonValueArray(timeline)); HashMapSet(timelineObj, "limited", JsonValueBoolean(timelineLimited)); } { char prevBuf[32]; snprintf(prevBuf, sizeof(prevBuf), "%llu", (unsigned long long) since); HashMapSet(timelineObj, "prev_batch", JsonValueString(prevBuf)); } syncRoom = HashMapCreate(); HashMapSet(syncRoom, "timeline", JsonValueObject(timelineObj)); { Array *typingUsers = TypingUsers(rid); HashMap *ephemeral = HashMapCreate(); Array *ephemeralEvents = ArrayCreate(); HashMap *typingEvent = HashMapCreate(); HashMap *typingContent = HashMapCreate(); HashMap *receipts = ReceiptsFor(db, rid, userId); HashMapSet(typingContent, "user_ids", JsonValueArray(typingUsers)); HashMapSet(typingEvent, "type", JsonValueString("m.typing")); HashMapSet(typingEvent, "content", JsonValueObject(typingContent)); ArrayAdd(ephemeralEvents, JsonValueObject(typingEvent)); if (receipts) { HashMap *receiptEvent = HashMapCreate(); HashMapSet(receiptEvent, "type", JsonValueString("m.receipt")); HashMapSet(receiptEvent, "content", JsonValueObject(receipts)); ArrayAdd(ephemeralEvents, JsonValueObject(receiptEvent)); } HashMapSet(ephemeral, "events", JsonValueArray(ephemeralEvents)); HashMapSet(syncRoom, "ephemeral", JsonValueObject(ephemeral)); } HashMapSet(syncRoom, "summary", JsonValueObject(RoomSummary(room, userId))); HashMapSet(syncRoom, "unread_notifications", JsonValueObject(UnreadFor(db, rid, userId))); if (syncUser) { HashMap *ad = HashMapCreate(); HashMapSet(ad, "events", JsonValueArray(RoomAccountDataEvents(db, rid, syncUser))); HashMapSet(syncRoom, "account_data", JsonValueObject(ad)); } if (since == 0) { HashMap *stateObj = HashMapCreate(); HashMapSet(stateObj, "events", JsonValueArray(StateEventsToArrayFiltered(state, userId, lazyMembers, stateTypes, stateNotTypes))); HashMapSet(syncRoom, "state", JsonValueObject(stateObj)); } JsonSet(join, JsonValueObject(syncRoom), 1, rid); RoomUnlock(room); } if (iref) { DbUnlock(db, iref); } } response = HashMapCreate(); { char buf[32]; snprintf(buf, sizeof(buf), "%llu", (unsigned long long) RoomStreamPosition(db)); HashMapSet(response, "next_batch", JsonValueString(buf)); } HashMapSet(response, "rooms", JsonValueObject(rooms)); { HashMap *ad = HashMapCreate(); HashMapSet(ad, "events", JsonValueArray(AccountDataEvents(db, syncUser ? syncUser : ""))); HashMapSet(response, "account_data", JsonValueObject(ad)); } { HashMap *pres = HashMapCreate(); HashMapSet(pres, "events", JsonValueArray(presenceEvents)); HashMapSet(response, "presence", JsonValueObject(pres)); } { HashMap *dl = HashMapCreate(); Array *changed = ArrayCreate(); KeyChangesCollect(db, since ? since : 0, 0, changed); HashMapSet(dl, "changed", JsonValueArray(changed)); HashMapSet(dl, "left", JsonValueArray(ArrayCreate())); HashMapSet(response, "device_lists", JsonValueObject(dl)); } { HashMap *td = HashMapCreate(); Array *tdEvents = ArrayCreate(); if (syncUser && syncDevice) { DbRef *tdref = DbLock(db, 3, "to_device", syncUser, syncDevice); if (tdref) { HashMap *store = DbJson(tdref); Array *stored = JsonValueAsArray(HashMapGet(store, "events")); size_t i; if (stored) { for (i = 0; i < ArraySize(stored); i++) { ArrayAdd(tdEvents, JsonValueDuplicate(ArrayGet(stored, i))); } } { JsonValue *old = HashMapSet(store, "events", JsonValueArray(ArrayCreate())); if (old) { JsonValueFree(old); } } DbUnlock(db, tdref); } } HashMapSet(td, "events", JsonValueArray(tdEvents)); HashMapSet(response, "to_device", JsonValueObject(td)); } HashMapSet(response, "device_one_time_keys_count", JsonValueObject(otkCounts ? otkCounts : HashMapCreate())); HashMapSet(response, "device_unused_fallback_key_types", JsonValueArray(fallbackTypes ? fallbackTypes : ArrayCreate())); finish: if (userLocked && user) { UserUnlock(user); } if (cfgLocked) { ConfigUnlock(&config); } Free(userId); Free(syncUser); Free(syncDevice); if (presenceSeen) { HashMapFree(presenceSeen); } JsonFree(syncFilter); return response; } /* * Copyright (C) 2022-2025 Jordan Bancino <@jordan:synapse.telodendria.org> * with other valuable contributors. See CONTRIBUTORS.txt for the full list. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation files * (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include #include #include #include #include #include ROUTE_IMPL(RouteRoomAliases, path, argp) { RouteArgs *args = argp; char *roomId = ArrayGet(path, 0); char *token; char *msg; HashMap *response = NULL; HashMap *aliases = NULL; HashMap *reversealias = NULL; JsonValue *val; Db *db = args->matrixArgs->db; DbRef *ref = NULL; User *user = NULL; if (HttpRequestMethodGet(args->context) != HTTP_GET) { msg = "Route only accepts GET."; HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, msg); goto finish; } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } /* TODO: Check whenever the user is in the room or if its world readable * once this is implemented instead of just checking for the ALIAS * privilege. */ if (!(UserGetPrivileges(user) & USER_ALIAS)) { msg = "User is not allowed to get this room's aliases."; HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, msg); goto finish; } ref = DbLock(db, 1, "aliases"); aliases = DbJson(ref); reversealias = JsonValueAsObject(JsonGet(aliases, 2, "id", roomId)); if (!reversealias) { /* We do not know about the room ID. */ msg = "Unknown room ID."; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_INVALID_PARAM, msg); goto finish; } response = HashMapCreate(); val = JsonGet(reversealias, 1, "aliases"); HashMapSet(response, "aliases", JsonValueDuplicate(val)); finish: DbUnlock(db, ref); UserUnlock(user); return response; } /* * Copyright (C) 2022-2025 Jordan Bancino <@jordan:synapse.telodendria.org> * with other valuable contributors. See CONTRIBUTORS.txt for the full list. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation files * (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include #include #include #include #include #include #include ROUTE_IMPL(RouteAliasDirectory, path, argp) { RouteArgs *args = argp; char *alias = ArrayGet(path, 0); HashMap *request = NULL; HashMap *response; Db *db = args->matrixArgs->db; DbRef *ref = NULL; HashMap *aliases; HashMap *idObject; JsonValue *val; Array *arr; char *token; char *msg; User *user = NULL; CommonID aliasID; Config config; aliasID.sigil = '\0'; aliasID.local = NULL; aliasID.server.hostname = NULL; aliasID.server.port = NULL; ConfigLock(db, &config); if (!ParseCommonID(alias, &aliasID) || aliasID.sigil != '#') { msg = "Invalid room alias."; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_INVALID_PARAM, msg); goto finish; } ref = DbLock(db, 1, "aliases"); if (!ref && !(ref = DbCreate(db, 1, "aliases"))) { msg = "Unable to access alias database.", HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); response = MatrixErrorCreate(M_UNKNOWN, msg); goto finish; } aliases = DbJson(ref); switch (HttpRequestMethodGet(args->context)) { case HTTP_GET: val = JsonGet(aliases, 2, "alias", alias); if (val) { response = HashMapCreate(); HashMapSet(response, "room_id", JsonValueDuplicate(HashMapGet(JsonValueAsObject(val), "id"))); HashMapSet(response, "servers", JsonValueDuplicate(JsonGet(aliases, 3, "alias", alias, "servers"))); } else { msg = "There is no mapped room ID for this room alias."; HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, msg); } break; case HTTP_PUT: case HTTP_DELETE: response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } if (HttpRequestMethodGet(args->context) == HTTP_PUT) { HashMap *newAlias; char *id; char *serverPart; serverPart = ParserRecomposeServerPart(aliasID.server); if (!StrEquals(serverPart, config.serverName)) { msg = "Invalid server name."; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_INVALID_PARAM, msg); Free(serverPart); goto finish; } Free(serverPart); if (JsonGet(aliases, 2, "alias", alias)) { HttpResponseStatus(args->context, HTTP_CONFLICT); response = MatrixErrorCreate(M_UNKNOWN, "Room alias already exists."); goto finish; } request = JsonDecode(HttpServerStream(args->context)); if (!request) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_NOT_JSON, NULL); goto finish; } id = JsonValueAsString(HashMapGet(request, "room_id")); if (!id) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_BAD_JSON, "Missing or invalid room_id."); goto finish; } if (!ValidRoomID(id)) { msg = "Invalid room ID."; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_INVALID_PARAM, msg); goto finish; } newAlias = HashMapCreate(); HashMapSet(newAlias, "createdBy", JsonValueString(UserGetName(user))); HashMapSet(newAlias, "id", JsonValueString(id)); HashMapSet(newAlias, "servers", JsonValueArray(ArrayCreate())); JsonSet(aliases, JsonValueObject(newAlias), 2, "alias", alias); if (!(idObject = JsonValueAsObject(JsonGet(aliases, 2, "id", id)))) { arr = ArrayCreate(); idObject = HashMapCreate(); HashMapSet(idObject, "aliases", JsonValueArray(arr)); JsonSet(aliases, JsonValueObject(idObject), 2, "id", id); } val = HashMapGet(idObject, "aliases"); arr = JsonValueAsArray(val); ArrayAdd(arr, JsonValueString(alias)); } else { HashMap *roomAlias; char *id; if (!(val = JsonGet(aliases, 2, "alias", alias))) { HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, "Room alias not found."); goto finish; } roomAlias = JsonValueAsObject(val); id = StrDuplicate(JsonValueAsString(HashMapGet(roomAlias, "id"))); if (!(UserGetPrivileges(user) & USER_ALIAS) && !StrEquals(UserGetName(user), JsonValueAsString(JsonGet(roomAlias, 1, "createdBy")))) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNAUTHORIZED, NULL); Free(id); goto finish; } JsonValueFree(HashMapDelete(JsonValueAsObject(HashMapGet(aliases, "alias")), alias)); idObject = JsonValueAsObject(JsonGet(aliases, 2, "id", id)); if (idObject) { size_t i; val = HashMapGet(idObject, "aliases"); arr = JsonValueAsArray(val); for (i = 0; i < ArraySize(arr); i++) { if (StrEquals(JsonValueAsString(ArrayGet(arr, i)), alias)) { JsonValueFree(ArrayDelete(arr, i)); break; } } } Free(id); } response = HashMapCreate(); break; default: HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_UNRECOGNIZED, "Unknown request method."); goto finish; } finish: CommonIDFree(aliasID); ConfigUnlock(&config); UserUnlock(user); DbUnlock(db, ref); JsonFree(request); return response; } /* * Copyright (C) 2022-2025 Jordan Bancino <@jordan:synapse.telodendria.org> * with other valuable contributors. See CONTRIBUTORS.txt for the full list. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation files * (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include #include #include #include #include #include #include #include static char * GetServerName(Db * db) { char *name; Config config; ConfigLock(db, &config); if (!config.ok) { return NULL; } name = StrDuplicate(config.serverName); ConfigUnlock(&config); return name; } ROUTE_IMPL(RouteFilter, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *request = NULL; HashMap *response = NULL; User *user = NULL; CommonID *id = NULL; char *token = NULL; char *serverName = NULL; char *userParam = ArrayGet(path, 0); char *msg; if (!userParam) { /* Should be impossible */ HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, NULL); } serverName = GetServerName(db); if (!serverName) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); response = MatrixErrorCreate(M_UNKNOWN, NULL); goto finish; } id = UserIdParse(userParam, serverName); if (!id) { msg = "Invalid user ID."; HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_INVALID_PARAM, msg); goto finish; } if (!ParserServerNameEquals(id->server, serverName)) { msg = "Cannot use /filter for non-local users."; HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNAUTHORIZED, msg); goto finish; } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } if (!StrEquals(id->local, UserGetName(user))) { msg = "Unauthorized to use /filter."; HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_INVALID_PARAM, msg); goto finish; } if (ArraySize(path) == 2 && HttpRequestMethodGet(args->context) == HTTP_GET) { DbRef *ref = DbLock(db, 3, "filters", UserGetName(user), ArrayGet(path, 1)); if (!ref) { msg = "The filter for this user was not found."; HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, msg); goto finish; } response = JsonDuplicate(DbJson(ref)); DbUnlock(db, ref); } else if (ArraySize(path) == 1 && HttpRequestMethodGet(args->context) == HTTP_POST) { DbRef *ref; char *filterId; Filter filter = {0}; char *parseErr; HashMap *filterJson; request = JsonDecode(HttpServerStream(args->context)); if (!request) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_NOT_JSON, NULL); goto finish; } if (!FilterFromJson(request, &filter, &parseErr)) { response = MatrixErrorCreate(M_BAD_JSON, parseErr); goto finish; } filterId = StrRandom(12); if (!filterId) { msg = "Couldn't generate random filter ID; this is unintended."; HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); response = MatrixErrorCreate(M_UNKNOWN, msg); goto finish; } ref = DbCreate(db, 3, "filters", UserGetName(user), filterId); if (!ref) { Free(filterId); msg = "Couldn't write filter to the database, this is unintended."; HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); response = MatrixErrorCreate(M_UNKNOWN, msg); goto finish; } filterJson = FilterToJson(&filter); DbJsonSet(ref, filterJson); DbUnlock(db, ref); Free(filterJson); response = HashMapCreate(); HashMapSet(response, "filter_id", JsonValueString(filterId)); Free(filterId); FilterFree(&filter); } else { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_UNRECOGNIZED, NULL); } finish: Free(serverName); UserIdFree(id); UserUnlock(user); JsonFree(request); return response; } static int RoomMemberJoined(Room * room, char * userId) { HashMap *state = RoomStateGet(room); HashMap *member = state ? JsonValueAsObject(JsonGet(state, 2, "m.room.member", userId)) : NULL; char *membership = member ? JsonValueAsString(HashMapGet(member, "membership")) : NULL; return membership && StrEquals(membership, "join"); } ROUTE_IMPL(RouteRoomState, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *request = NULL; HashMap *response = NULL; HashMap *event = NULL; User *user = NULL; Room *room = NULL; Config config; HttpRequestMethod method; char *token = NULL; char *roomId; char *type = NULL; char *stateKey = NULL; char *userId = NULL; char *eventId = NULL; method = HttpRequestMethodGet(args->context); roomId = ArrayGet(path, 0); if (ArraySize(path) >= 2) { type = ArrayGet(path, 1); } if (ArraySize(path) >= 3) { stateKey = ArrayGet(path, 2); } if (!stateKey) { stateKey = ""; } ConfigLock(db, &config); if (!config.ok) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } room = RoomLock(db, roomId); if (!room) { HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, NULL); goto finish; } userId = StrConcat(4, "@", UserGetName(user), ":", config.serverName); if (!RoomMemberJoined(room, userId)) { HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, NULL); goto finish; } if (method == HTTP_GET) { HashMap *state = RoomStateGet(room); if (!type) { response = HashMapCreate(); HashMapSet(response, "events", JsonValueArray(StateEventsToArray(state))); } else { HashMap *content = JsonValueAsObject(JsonGet(state, 2, type, stateKey)); if (!content) { HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, NULL); goto finish; } response = JsonDuplicate(content); } goto finish; } if (method != HTTP_PUT) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_UNRECOGNIZED, NULL); goto finish; } if (!type) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_UNRECOGNIZED, NULL); goto finish; } request = JsonDecode(HttpServerStream(args->context)); if (!request) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_NOT_JSON, NULL); goto finish; } { int myPower = RoomUserPower(room, userId); if (myPower < RoomStateRequiredLevel(room, type)) { HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, NULL); goto finish; } if (StrEquals(type, "m.room.power_levels")) { HashMap *users = JsonValueAsObject(HashMapGet(request, "users")); char *uk; void *uv; JsonValue *ud = HashMapGet(request, "users_default"); while (users && HashMapIterate(users, &uk, &uv)) { if (JsonValueType((JsonValue *) uv) == JSON_INTEGER && (int) JsonValueAsInteger((JsonValue *) uv) > myPower) { HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, NULL); goto finish; } } if (ud && JsonValueType(ud) == JSON_INTEGER && (int) JsonValueAsInteger(ud) > myPower) { HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, NULL); goto finish; } } } eventId = StrConcat(2, "$", StrRandom(24)); event = HashMapCreate(); HashMapSet(event, "event_id", JsonValueString(eventId)); HashMapSet(event, "type", JsonValueString(type)); HashMapSet(event, "state_key", JsonValueString(stateKey)); HashMapSet(event, "sender", JsonValueString(userId)); HashMapSet(event, "room_id", JsonValueString(roomId)); HashMapSet(event, "origin_server_ts", JsonValueInteger((uint64_t) time(NULL) * 1000)); HashMapSet(event, "content", JsonValueObject(JsonDuplicate(request))); if (!RoomEventSend(room, event)) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); response = MatrixErrorCreate(M_UNKNOWN, NULL); goto finish; } response = HashMapCreate(); HashMapSet(response, "event_id", JsonValueString(eventId)); finish: if (room) { RoomUnlock(room); } if (user) { UserUnlock(user); } JsonFree(event); JsonFree(request); ConfigUnlock(&config); Free(userId); Free(eventId); return response; } ROUTE_IMPL(RouteRoomMembers, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *response = NULL; HashMap *state = NULL; User *user = NULL; Room *room = NULL; Config config; Array *chunk = NULL; char *token = NULL; char *roomId; char *userId = NULL; char *wantMembership = NULL; char *notMembership = NULL; (void) path; if (HttpRequestMethodGet(args->context) != HTTP_GET) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, NULL); } roomId = ArrayGet(path, 0); if (!roomId) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, NULL); } ConfigLock(db, &config); if (!config.ok) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } room = RoomLock(db, roomId); if (!room) { HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, NULL); goto finish; } userId = StrConcat(4, "@", UserGetName(user), ":", config.serverName); if (!RoomMemberJoined(room, userId)) { HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, NULL); goto finish; } state = RoomStateGet(room); chunk = ArrayCreate(); { HashMap *params = HttpRequestParams(args->context); if (params) { wantMembership = HashMapGet(params, "membership"); notMembership = HashMapGet(params, "not_membership"); } } { HashMap *members = state ? JsonValueAsObject(HashMapGet(state, "m.room.member")) : NULL; char *key; void *val; if (members) { while (HashMapIterate(members, &key, &val)) { HashMap *content = JsonValueAsObject((JsonValue *) val); char *membership = content ? JsonValueAsString(HashMapGet(content, "membership")) : NULL; HashMap *ev; if (wantMembership && (!membership || !StrEquals(membership, wantMembership))) { continue; } if (notMembership && membership && StrEquals(membership, notMembership)) { continue; } ev = HashMapCreate(); HashMapSet(ev, "type", JsonValueString("m.room.member")); HashMapSet(ev, "state_key", JsonValueString(key)); HashMapSet(ev, "sender", JsonValueString(key)); HashMapSet(ev, "content", JsonValueObject(JsonDuplicate(content))); ArrayAdd(chunk, JsonValueObject(ev)); } } } response = HashMapCreate(); HashMapSet(response, "chunk", JsonValueArray(chunk)); finish: if (room) { RoomUnlock(room); } if (user) { UserUnlock(user); } ConfigUnlock(&config); Free(userId); return response; } ROUTE_IMPL(RouteJoinedRooms, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *response = NULL; User *user = NULL; Config config; Array *joined = NULL; char *token = NULL; char *userId = NULL; (void) path; if (HttpRequestMethodGet(args->context) != HTTP_GET) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, NULL); } ConfigLock(db, &config); if (!config.ok) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } userId = StrConcat(4, "@", UserGetName(user), ":", config.serverName); joined = ArrayCreate(); { DbRef *iref = DbLock(db, 2, "rooms", "index"); Array *ids = iref ? JsonValueAsArray(HashMapGet(DbJson(iref), "rooms")) : NULL; size_t n = ids ? ArraySize(ids) : 0; for (size_t k = 0; k < n; k++) { char *rid = JsonValueAsString(ArrayGet(ids, k)); Room *room = rid ? RoomLock(db, rid) : NULL; if (!room) { continue; } if (RoomMemberJoined(room, userId)) { ArrayAdd(joined, JsonValueString(rid)); } RoomUnlock(room); } if (iref) { DbUnlock(db, iref); } } response = HashMapCreate(); HashMapSet(response, "joined_rooms", JsonValueArray(joined)); finish: if (user) { UserUnlock(user); } ConfigUnlock(&config); Free(userId); return response; } ROUTE_IMPL(RoutePublicRooms, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *response = NULL; Array *chunk = NULL; long limit = 50; long offset = 0; (void) path; if (HttpRequestMethodGet(args->context) != HTTP_GET && HttpRequestMethodGet(args->context) != HTTP_POST) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, NULL); } { HashMap *params = HttpRequestParams(args->context); if (params) { char *l = HashMapGet(params, "limit"); char *s = HashMapGet(params, "since"); if (l) { limit = atol(l); } if (s) { offset = atol(s); } } } if (limit < 1) { limit = 1; } if (limit > 500) { limit = 500; } if (offset < 0) { offset = 0; } chunk = ArrayCreate(); { DbRef *iref = DbLock(db, 2, "rooms", "index"); Array *ids = iref ? JsonValueAsArray(HashMapGet(DbJson(iref), "rooms")) : NULL; size_t n = ids ? ArraySize(ids) : 0; for (size_t k = 0; k < n; k++) { char *rid = JsonValueAsString(ArrayGet(ids, k)); Room *room = rid ? RoomLock(db, rid) : NULL; HashMap *state; HashMap *rules; char *joinRule; int joined = 0; if (!room) { continue; } state = RoomStateGet(room); rules = state ? JsonValueAsObject(JsonGet(state, 2, "m.room.join_rules", "")) : NULL; joinRule = rules ? JsonValueAsString(HashMapGet(rules, "join_rule")) : NULL; if (joinRule && StrEquals(joinRule, "public")) { HashMap *info = HashMapCreate(); HashMap *members = state ? JsonValueAsObject(HashMapGet(state, "m.room.member")) : NULL; HashMap *name = state ? JsonValueAsObject(JsonGet(state, 2, "m.room.name", "")) : NULL; char *roomName = name ? JsonValueAsString(HashMapGet(name, "name")) : NULL; char *key; void *val; if (members) { while (HashMapIterate(members, &key, &val)) { HashMap *m = JsonValueAsObject(val); char *ms = m ? JsonValueAsString(HashMapGet(m, "membership")) : NULL; if (ms && StrEquals(ms, "join")) { joined++; } } } HashMapSet(info, "room_id", JsonValueString(rid)); HashMapSet(info, "num_joined_members", JsonValueInteger(joined)); HashMapSet(info, "guest_can_join", JsonValueBoolean(false)); HashMapSet(info, "world_readable", JsonValueBoolean(false)); if (roomName) { HashMapSet(info, "name", JsonValueString(roomName)); } ArrayAdd(chunk, JsonValueObject(info)); } RoomUnlock(room); } if (iref) { DbUnlock(db, iref); } } response = HashMapCreate(); { size_t total = ArraySize(chunk); size_t start = (size_t) offset < total ? (size_t) offset : total; size_t end = start + (size_t) limit; Array *page = ArrayCreate(); size_t i; if (end > total) { end = total; } for (i = 0; i < total; i++) { if (i >= start && i < end) { ArrayAdd(page, JsonValueDuplicate(ArrayGet(chunk, i))); } JsonValueFree(ArrayGet(chunk, i)); } ArrayFree(chunk); chunk = page; HashMapSet(response, "chunk", JsonValueArray(chunk)); HashMapSet(response, "total_room_count_estimate", JsonValueInteger((long) total)); if (end < total) { char buf[32]; snprintf(buf, sizeof(buf), "%ld", (long) end); HashMapSet(response, "next_batch", JsonValueString(buf)); } } return response; } ROUTE_IMPL(RouteRedact, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *response = NULL; HashMap *event = NULL; User *user = NULL; Room *room = NULL; DbRef *eref = NULL; Config config; char *token = NULL; char *roomId; char *redactId; char *userId = NULL; char *newId = NULL; char *targetSender = NULL; (void) path; if (HttpRequestMethodGet(args->context) != HTTP_POST && HttpRequestMethodGet(args->context) != HTTP_PUT) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, NULL); } roomId = ArrayGet(path, 0); redactId = ArrayGet(path, 1); ConfigLock(db, &config); if (!config.ok) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } room = RoomLock(db, roomId); if (!room) { HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, NULL); goto finish; } userId = StrConcat(4, "@", UserGetName(user), ":", config.serverName); if (!RoomMemberJoined(room, userId)) { HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, NULL); goto finish; } eref = DbLock(db, 3, "rooms", roomId, "events"); if (eref) { Array *stored = JsonValueAsArray(HashMapGet(DbJson(eref), "events")); size_t i; if (stored) { for (i = 0; i < ArraySize(stored); i++) { HashMap *ev = JsonValueAsObject(ArrayGet(stored, i)); char *eid = ev ? JsonValueAsString(HashMapGet(ev, "event_id")) : NULL; if (eid && StrEquals(eid, redactId)) { HashMap *oldContent = JsonValueAsObject(HashMapGet(ev, "content")); HashMap *newContent = HashMapCreate(); char *etype = JsonValueAsString(HashMapGet(ev, "type")); targetSender = StrDuplicate(JsonValueAsString(HashMapGet(ev, "sender"))); if (etype && StrEquals(etype, "m.room.member")) { char *mem = oldContent ? JsonValueAsString(HashMapGet(oldContent, "membership")) : NULL; if (mem) { HashMapSet(newContent, "membership", JsonValueString(mem)); } } else if (etype && StrEquals(etype, "m.room.create")) { char *creator = oldContent ? JsonValueAsString(HashMapGet(oldContent, "creator")) : NULL; if (creator) { HashMapSet(newContent, "creator", JsonValueString(creator)); } } else if (etype && StrEquals(etype, "m.room.join_rules")) { char *rule = oldContent ? JsonValueAsString(HashMapGet(oldContent, "join_rule")) : NULL; if (rule) { HashMapSet(newContent, "join_rule", JsonValueString(rule)); } } HashMapSet(ev, "content", JsonValueObject(newContent)); break; } } } } if (!targetSender) { HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, NULL); goto finish; } if (!StrEquals(targetSender, userId) && RoomUserPower(room, userId) < RoomRedactLevel(room)) { HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, NULL); goto finish; } newId = StrConcat(2, "$", StrRandom(24)); event = HashMapCreate(); HashMapSet(event, "event_id", JsonValueString(newId)); HashMapSet(event, "type", JsonValueString("m.room.redaction")); HashMapSet(event, "sender", JsonValueString(userId)); HashMapSet(event, "room_id", JsonValueString(roomId)); HashMapSet(event, "origin_server_ts", JsonValueInteger((uint64_t) time(NULL) * 1000)); { HashMap *content = HashMapCreate(); HashMapSet(content, "redacts", JsonValueString(redactId)); HashMapSet(event, "content", JsonValueObject(content)); } RoomEventSend(room, event); response = HashMapCreate(); HashMapSet(response, "event_id", JsonValueString(newId)); finish: if (eref) { DbUnlock(db, eref); } if (room) { RoomUnlock(room); } if (user) { UserUnlock(user); } JsonFree(event); ConfigUnlock(&config); Free(userId); Free(newId); Free(targetSender); return response; } static int RoomUserPower(Room * room, char * userId) { HashMap *state = RoomStateGet(room); HashMap *pl = state ? JsonValueAsObject(JsonGet(state, 2, "m.room.power_levels", "")) : NULL; HashMap *users; JsonValue *v; JsonValue *d; if (!pl) { return 0; } users = JsonValueAsObject(HashMapGet(pl, "users")); v = users ? HashMapGet(users, userId) : NULL; if (v && JsonValueType(v) == JSON_INTEGER) { return (int) JsonValueAsInteger(v); } d = HashMapGet(pl, "users_default"); return (d && JsonValueType(d) == JSON_INTEGER) ? (int) JsonValueAsInteger(d) : 0; } static int RoomRedactLevel(Room * room) { HashMap *state = RoomStateGet(room); HashMap *pl = state ? JsonValueAsObject(JsonGet(state, 2, "m.room.power_levels", "")) : NULL; JsonValue *v = pl ? HashMapGet(pl, "redact") : NULL; return (v && JsonValueType(v) == JSON_INTEGER) ? (int) JsonValueAsInteger(v) : 50; } static int RoomEventRequiredLevel(Room * room, char * type) { HashMap *state = RoomStateGet(room); HashMap *pl = state ? JsonValueAsObject(JsonGet(state, 2, "m.room.power_levels", "")) : NULL; HashMap *events; JsonValue *v; int level = 0; if (!pl) { return 0; } v = HashMapGet(pl, "events_default"); if (v && JsonValueType(v) == JSON_INTEGER) { level = (int) JsonValueAsInteger(v); } events = JsonValueAsObject(HashMapGet(pl, "events")); v = events ? HashMapGet(events, type) : NULL; if (v && JsonValueType(v) == JSON_INTEGER) { level = (int) JsonValueAsInteger(v); } return level; } static int RoomStateRequiredLevel(Room * room, char * type) { HashMap *state = RoomStateGet(room); HashMap *pl = state ? JsonValueAsObject(JsonGet(state, 2, "m.room.power_levels", "")) : NULL; HashMap *events; JsonValue *v; int level = 50; if (!pl) { return 50; } v = HashMapGet(pl, "state_default"); if (v && JsonValueType(v) == JSON_INTEGER) { level = (int) JsonValueAsInteger(v); } events = JsonValueAsObject(HashMapGet(pl, "events")); v = events ? HashMapGet(events, type) : NULL; if (v && JsonValueType(v) == JSON_INTEGER) { level = (int) JsonValueAsInteger(v); } return level; } ROUTE_IMPL(RouteRoomMembership, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *request = NULL; HashMap *response = NULL; HashMap *state = NULL; User *user = NULL; Room *room = NULL; Config config; char *action; char *target = NULL; char *token = NULL; char *roomId; char *userId = NULL; if (HttpRequestMethodGet(args->context) != HTTP_POST) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, NULL); } roomId = ArrayGet(path, 0); action = ArrayGet(path, 1); ConfigLock(db, &config); if (!config.ok) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } room = RoomLock(db, roomId); if (!room) { HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, NULL); goto finish; } userId = StrConcat(4, "@", UserGetName(user), ":", config.serverName); if (!RoomMemberJoined(room, userId)) { HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, NULL); goto finish; } request = JsonDecode(HttpServerStream(args->context)); if (!request) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_NOT_JSON, NULL); goto finish; } target = JsonValueAsString(HashMapGet(request, "user_id")); if (!target) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_BAD_JSON, "user_id is required"); goto finish; } state = RoomStateGet(room); if (StrEquals(action, "invite")) { HashMap *member = JsonValueAsObject(JsonGet(state, 2, "m.room.member", target)); char *membership = member ? JsonValueAsString(HashMapGet(member, "membership")) : NULL; if (membership && (StrEquals(membership, "join") || StrEquals(membership, "ban"))) { HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, NULL); goto finish; } Free(RoomSendMembership(room, userId, target, "invite")); } else { int myPower = RoomUserPower(room, userId); int theirPower = RoomUserPower(room, target); char *membership = StrEquals(action, "ban") ? "ban" : "leave"; if (myPower < 50 || myPower <= theirPower) { HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, NULL); goto finish; } Free(RoomSendMembership(room, userId, target, membership)); } response = HashMapCreate(); finish: if (room) { RoomUnlock(room); } if (user) { UserUnlock(user); } JsonFree(request); ConfigUnlock(&config); Free(userId); return response; } ROUTE_IMPL(RouteReceipt, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *response = NULL; User *user = NULL; Room *room = NULL; DbRef *rref = NULL; Config config; char *token = NULL; char *roomId; char *receiptType; char *eventId; char *userId = NULL; if (HttpRequestMethodGet(args->context) != HTTP_POST) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, NULL); } roomId = ArrayGet(path, 0); receiptType = ArrayGet(path, 1); eventId = ArrayGet(path, 2); ConfigLock(db, &config); if (!config.ok) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } room = RoomLock(db, roomId); if (!room) { HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, NULL); goto finish; } userId = StrConcat(4, "@", UserGetName(user), ":", config.serverName); if (!RoomMemberJoined(room, userId)) { HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, NULL); goto finish; } rref = DbLock(db, 3, "rooms", roomId, "receipts"); if (!rref) { rref = DbCreate(db, 3, "rooms", roomId, "receipts"); } if (rref) { HashMap *all = DbJson(rref); HashMap *mine = JsonValueAsObject(HashMapGet(all, userId)); if (!mine) { mine = HashMapCreate(); HashMapSet(all, userId, JsonValueObject(mine)); } if (eventId) { if (receiptType && StrEquals(receiptType, "m.read.private")) { HashMapSet(mine, "m.read.private", JsonValueString(eventId)); } else { HashMapSet(mine, "m.read", JsonValueString(eventId)); } } HashMapSet(mine, "ts", JsonValueInteger((uint64_t) time(NULL) * 1000)); } response = HashMapCreate(); finish: if (rref) { DbUnlock(db, rref); } if (room) { RoomUnlock(room); } if (user) { UserUnlock(user); } ConfigUnlock(&config); Free(userId); return response; } ROUTE_IMPL(RouteReadMarkers, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *request = NULL; HashMap *response = NULL; User *user = NULL; Room *room = NULL; DbRef *rref = NULL; Config config; char *token = NULL; char *roomId; char *userId = NULL; if (HttpRequestMethodGet(args->context) != HTTP_POST) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, NULL); } roomId = ArrayGet(path, 0); ConfigLock(db, &config); if (!config.ok) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } room = RoomLock(db, roomId); if (!room) { HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, NULL); goto finish; } userId = StrConcat(4, "@", UserGetName(user), ":", config.serverName); if (!RoomMemberJoined(room, userId)) { HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, NULL); goto finish; } request = JsonDecode(HttpServerStream(args->context)); if (!request) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_NOT_JSON, NULL); goto finish; } rref = DbLock(db, 3, "rooms", roomId, "receipts"); if (!rref) { rref = DbCreate(db, 3, "rooms", roomId, "receipts"); } if (rref) { HashMap *all = DbJson(rref); HashMap *mine = JsonValueAsObject(HashMapGet(all, userId)); char *full = JsonValueAsString(HashMapGet(request, "m.fully_read")); char *read = JsonValueAsString(HashMapGet(request, "m.read")); char *privateRead = JsonValueAsString(HashMapGet(request, "m.read.private")); if (!mine) { mine = HashMapCreate(); HashMapSet(all, userId, JsonValueObject(mine)); } if (full) { HashMapSet(mine, "m.fully_read", JsonValueString(full)); } if (read) { HashMapSet(mine, "m.read", JsonValueString(read)); } if (privateRead) { HashMapSet(mine, "m.read.private", JsonValueString(privateRead)); } } response = HashMapCreate(); finish: if (rref) { DbUnlock(db, rref); } if (room) { RoomUnlock(room); } if (user) { UserUnlock(user); } JsonFree(request); ConfigUnlock(&config); Free(userId); return response; } #define TYPING_MAX 256 typedef struct TypingEntry { char *room; char *user; uint64_t expires; } TypingEntry; static TypingEntry typingEntries[TYPING_MAX]; static pthread_mutex_t typingLock = PTHREAD_MUTEX_INITIALIZER; static uint64_t NowMs(void) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (uint64_t) ts.tv_sec * 1000 + (uint64_t) (ts.tv_nsec / 1000000); } static void TypingSet(char * room, char * user, long timeoutMs) { size_t i; size_t freeSlot = TYPING_MAX; pthread_mutex_lock(&typingLock); for (i = 0; i < TYPING_MAX; i++) { if (typingEntries[i].room && typingEntries[i].user && StrEquals(typingEntries[i].room, room) && StrEquals(typingEntries[i].user, user)) { if (timeoutMs <= 0) { Free(typingEntries[i].room); Free(typingEntries[i].user); typingEntries[i].room = NULL; typingEntries[i].user = NULL; typingEntries[i].expires = 0; } else { typingEntries[i].expires = NowMs() + (uint64_t) timeoutMs; } pthread_mutex_unlock(&typingLock); return; } if (!typingEntries[i].room && freeSlot == TYPING_MAX) { freeSlot = i; } } if (timeoutMs > 0) { if (freeSlot == TYPING_MAX) { freeSlot = 0; Free(typingEntries[freeSlot].room); Free(typingEntries[freeSlot].user); } typingEntries[freeSlot].room = StrDuplicate(room); typingEntries[freeSlot].user = StrDuplicate(user); typingEntries[freeSlot].expires = NowMs() + (uint64_t) timeoutMs; } pthread_mutex_unlock(&typingLock); } static Array * TypingUsers(char * room) { Array *users = ArrayCreate(); uint64_t now = NowMs(); size_t i; pthread_mutex_lock(&typingLock); for (i = 0; i < TYPING_MAX; i++) { if (typingEntries[i].room && StrEquals(typingEntries[i].room, room)) { if (typingEntries[i].expires > now) { ArrayAdd(users, JsonValueString(typingEntries[i].user)); } else { Free(typingEntries[i].room); Free(typingEntries[i].user); typingEntries[i].room = NULL; typingEntries[i].user = NULL; typingEntries[i].expires = 0; } } } pthread_mutex_unlock(&typingLock); return users; } ROUTE_IMPL(RouteTyping, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *request = NULL; HashMap *response = NULL; User *user = NULL; Room *room = NULL; Config config; char *token = NULL; char *roomId; char *userId = NULL; JsonValue *typingValue; if (HttpRequestMethodGet(args->context) != HTTP_POST) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, NULL); } roomId = ArrayGet(path, 0); ConfigLock(db, &config); if (!config.ok) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } room = RoomLock(db, roomId); if (!room) { HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, NULL); goto finish; } userId = StrConcat(4, "@", UserGetName(user), ":", config.serverName); if (!RoomMemberJoined(room, userId)) { HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, NULL); goto finish; } request = JsonDecode(HttpServerStream(args->context)); if (!request) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_NOT_JSON, NULL); goto finish; } typingValue = HashMapGet(request, "typing"); if (typingValue && JsonValueBoolean(typingValue)) { JsonValue *t = HashMapGet(request, "timeout"); long timeout = 30000; if (t && JsonValueType(t) == JSON_INTEGER) { timeout = (long) JsonValueAsInteger(t); } TypingSet(roomId, userId, timeout); } else { TypingSet(roomId, userId, 0); } response = HashMapCreate(); finish: if (room) { RoomUnlock(room); } if (user) { UserUnlock(user); } JsonFree(request); ConfigUnlock(&config); Free(userId); return response; } static HashMap * RoomEventFind(Db * db, char *roomId, char *eventId) { DbRef *ref = DbLock(db, 3, "rooms", roomId, "events"); HashMap *found = NULL; if (ref) { Array *events = JsonValueAsArray(HashMapGet(DbJson(ref), "events")); size_t i; for (i = 0; events && i < ArraySize(events); i++) { HashMap *ev = JsonValueAsObject(ArrayGet(events, i)); char *eid = ev ? JsonValueAsString(HashMapGet(ev, "event_id")) : NULL; if (eid && StrEquals(eid, eventId)) { found = JsonDuplicate(ev); HashMapDelete(found, "_seq"); break; } } DbUnlock(db, ref); } return found; } ROUTE_IMPL(RouteRoomEvent, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *response = NULL; User *user = NULL; Room *room = NULL; Config config; char *token = NULL; char *roomId = ArrayGet(path, 0); char *eventId = ArrayGet(path, 1); char *userId = NULL; if (HttpRequestMethodGet(args->context) != HTTP_GET) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, NULL); } ConfigLock(db, &config); if (!config.ok) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } room = RoomLock(db, roomId); if (!room) { HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, NULL); goto finish; } userId = StrConcat(4, "@", UserGetName(user), ":", config.serverName); if (!RoomMemberJoined(room, userId)) { HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, NULL); goto finish; } response = RoomEventFind(db, roomId, eventId); if (!response) { HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, NULL); } finish: if (room) { RoomUnlock(room); } if (user) { UserUnlock(user); } ConfigUnlock(&config); Free(userId); return response; } ROUTE_IMPL(RouteRoomContext, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *response = NULL; HashMap *params; User *user = NULL; Room *room = NULL; Config config; DbRef *ref = NULL; char *token = NULL; char *roomId = ArrayGet(path, 0); char *eventId = ArrayGet(path, 1); char *userId = NULL; long limit = 10; if (HttpRequestMethodGet(args->context) != HTTP_GET) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, NULL); } ConfigLock(db, &config); if (!config.ok) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } room = RoomLock(db, roomId); if (!room) { HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, NULL); goto finish; } userId = StrConcat(4, "@", UserGetName(user), ":", config.serverName); if (!RoomMemberJoined(room, userId)) { HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, NULL); goto finish; } params = HttpRequestParams(args->context); if (params) { char *l = HashMapGet(params, "limit"); if (l) { limit = atol(l); } } if (limit < 1) { limit = 1; } if (limit > 100) { limit = 100; } ref = DbLock(db, 3, "rooms", roomId, "events"); if (!ref) { HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, NULL); goto finish; } { Array *events = JsonValueAsArray(HashMapGet(DbJson(ref), "events")); Array *before = ArrayCreate(); Array *after = ArrayCreate(); HashMap *event = NULL; long index = -1; long i; long n = events ? (long) ArraySize(events) : 0; char buf[32]; for (i = 0; i < n; i++) { HashMap *ev = JsonValueAsObject(ArrayGet(events, i)); char *eid = ev ? JsonValueAsString(HashMapGet(ev, "event_id")) : NULL; if (eid && StrEquals(eid, eventId)) { index = i; event = JsonDuplicate(ev); HashMapDelete(event, "_seq"); break; } } if (!event) { HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, NULL); goto finish; } for (i = index - 1; i >= 0 && (long) ArraySize(before) < limit; i--) { HashMap *ev = JsonDuplicate(JsonValueAsObject(ArrayGet(events, i))); HashMapDelete(ev, "_seq"); ArrayAdd(before, JsonValueObject(ev)); } for (i = index + 1; i < n && (long) ArraySize(after) < limit; i++) { HashMap *ev = JsonDuplicate(JsonValueAsObject(ArrayGet(events, i))); HashMapDelete(ev, "_seq"); ArrayAdd(after, JsonValueObject(ev)); } response = HashMapCreate(); snprintf(buf, sizeof(buf), "t%ld", index < limit ? 0 : index - limit); HashMapSet(response, "start", JsonValueString(buf)); snprintf(buf, sizeof(buf), "t%ld", index + limit + 1); HashMapSet(response, "end", JsonValueString(buf)); HashMapSet(response, "events_before", JsonValueArray(before)); HashMapSet(response, "event", JsonValueObject(event)); HashMapSet(response, "events_after", JsonValueArray(after)); HashMapSet(response, "state", JsonValueArray(ArrayCreate())); } finish: if (ref) { DbUnlock(db, ref); } if (room) { RoomUnlock(room); } if (user) { UserUnlock(user); } ConfigUnlock(&config); Free(userId); return response; } ROUTE_IMPL(RouteRoomRelations, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *response = NULL; User *user = NULL; Room *room = NULL; Config config; DbRef *ref = NULL; char *token = NULL; char *roomId = ArrayGet(path, 0); char *eventId = ArrayGet(path, 1); char *userId = NULL; if (HttpRequestMethodGet(args->context) != HTTP_GET) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, NULL); } ConfigLock(db, &config); if (!config.ok) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } room = RoomLock(db, roomId); if (!room) { HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, NULL); goto finish; } userId = StrConcat(4, "@", UserGetName(user), ":", config.serverName); if (!RoomMemberJoined(room, userId)) { HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, NULL); goto finish; } response = HashMapCreate(); HashMapSet(response, "chunk", JsonValueArray(ArrayCreate())); HashMapSet(response, "next_batch", JsonValueNull()); HashMapSet(response, "prev_batch", JsonValueNull()); ref = DbLock(db, 3, "rooms", roomId, "events"); if (ref) { Array *events = JsonValueAsArray(HashMapGet(DbJson(ref), "events")); Array *chunk = JsonValueAsArray(HashMapGet(response, "chunk")); size_t i; for (i = 0; events && i < ArraySize(events); i++) { HashMap *ev = JsonValueAsObject(ArrayGet(events, i)); HashMap *content = ev ? JsonValueAsObject(HashMapGet(ev, "content")) : NULL; HashMap *relates = content ? JsonValueAsObject(HashMapGet(content, "m.relates_to")) : NULL; char *rel = relates ? JsonValueAsString(HashMapGet(relates, "event_id")) : NULL; if (rel && StrEquals(rel, eventId)) { HashMap *copy = JsonDuplicate(ev); HashMapDelete(copy, "_seq"); ArrayAdd(chunk, JsonValueObject(copy)); } } } finish: if (ref) { DbUnlock(db, ref); } if (room) { RoomUnlock(room); } if (user) { UserUnlock(user); } ConfigUnlock(&config); Free(userId); return response; } ROUTE_IMPL(RouteRoomTags, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *request = NULL; HashMap *response = NULL; User *user = NULL; DbRef *ref = NULL; Config config; HttpRequestMethod method = HttpRequestMethodGet(args->context); char *token = NULL; char *userParam = ArrayGet(path, 0); char *roomId = ArrayGet(path, 1); char *tag = ArraySize(path) > 2 ? ArrayGet(path, 2) : NULL; char *expected = NULL; ConfigLock(db, &config); if (!config.ok) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } expected = StrConcat(4, "@", UserGetName(user), ":", config.serverName); if (!userParam || !StrEquals(userParam, expected) || !roomId) { HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, NULL); goto finish; } if (method == HTTP_PUT) { request = JsonDecode(HttpServerStream(args->context)); if (!request || !tag) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_NOT_JSON, NULL); goto finish; } } ref = DbLock(db, 4, "rooms", roomId, "accountdata", UserGetName(user)); if (method == HTTP_GET) { HashMap *content = ref ? JsonValueAsObject(HashMapGet(DbJson(ref), "m.tag")) : NULL; response = content ? JsonDuplicate(content) : HashMapCreate(); goto finish; } if (!ref) { ref = DbCreate(db, 4, "rooms", roomId, "accountdata", UserGetName(user)); } if (!ref) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); response = MatrixErrorCreate(M_UNKNOWN, NULL); goto finish; } { HashMap *all = DbJson(ref); HashMap *content = JsonValueAsObject(HashMapGet(all, "m.tag")); HashMap *tags; if (!content) { content = HashMapCreate(); HashMapSet(all, "m.tag", JsonValueObject(content)); } tags = JsonValueAsObject(HashMapGet(content, "tags")); if (!tags) { tags = HashMapCreate(); HashMapSet(content, "tags", JsonValueObject(tags)); } if (method == HTTP_PUT) { HashMapSet(tags, tag, JsonValueObject(JsonDuplicate(request))); } else if (method == HTTP_DELETE) { HashMapDelete(tags, tag); } } response = HashMapCreate(); finish: if (ref) { DbUnlock(db, ref); } if (user) { UserUnlock(user); } JsonFree(request); ConfigUnlock(&config); Free(expected); return response; } ROUTE_IMPL(RouteForgetRoom, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *response = NULL; HashMap *state; HashMap *member; User *user = NULL; Room *room = NULL; Config config; char *token = NULL; char *roomId = ArrayGet(path, 0); char *userId = NULL; if (HttpRequestMethodGet(args->context) != HTTP_POST) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, NULL); } ConfigLock(db, &config); if (!config.ok) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } room = RoomLock(db, roomId); if (!room) { HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, NULL); goto finish; } userId = StrConcat(4, "@", UserGetName(user), ":", config.serverName); state = RoomStateGet(room); member = JsonValueAsObject(JsonGet(state, 2, "m.room.member", userId)); if (member) { char *membership = JsonValueAsString(HashMapGet(member, "membership")); if (membership && !StrEquals(membership, "leave")) { char *eventId = RoomSendMembership(room, userId, userId, "leave"); Free(eventId); } } response = HashMapCreate(); finish: if (room) { RoomUnlock(room); } if (user) { UserUnlock(user); } ConfigUnlock(&config); Free(userId); return response; } ROUTE_IMPL(RouteTimestampToEvent, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *response = NULL; HashMap *params; User *user = NULL; Room *room = NULL; Config config; DbRef *ref = NULL; char *token = NULL; char *roomId = ArrayGet(path, 0); char *userId = NULL; uint64_t target = 0; int forward = 0; if (HttpRequestMethodGet(args->context) != HTTP_GET) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, NULL); } ConfigLock(db, &config); if (!config.ok) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } room = RoomLock(db, roomId); if (!room) { HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, NULL); goto finish; } userId = StrConcat(4, "@", UserGetName(user), ":", config.serverName); if (!RoomMemberJoined(room, userId)) { HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, NULL); goto finish; } params = HttpRequestParams(args->context); if (params) { char *ts = HashMapGet(params, "ts"); char *dir = HashMapGet(params, "dir"); target = ts ? strtoull(ts, NULL, 10) : 0; forward = dir && StrEquals(dir, "f"); } ref = DbLock(db, 3, "rooms", roomId, "events"); if (ref) { Array *events = JsonValueAsArray(HashMapGet(DbJson(ref), "events")); HashMap *best = NULL; uint64_t bestTs = 0; size_t i; for (i = 0; events && i < ArraySize(events); i++) { HashMap *ev = JsonValueAsObject(ArrayGet(events, i)); JsonValue *tsv = ev ? HashMapGet(ev, "origin_server_ts") : NULL; uint64_t ts = tsv ? (uint64_t) JsonValueAsInteger(tsv) : 0; int better; if (!ts) { continue; } better = forward ? (ts >= target && (!best || ts < bestTs)) : (ts <= target && (!best || ts > bestTs)); if (better) { best = ev; bestTs = ts; } } if (best) { HashMap *copy = JsonDuplicate(best); HashMapDelete(copy, "_seq"); response = copy; } } if (!response) { HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, NULL); } finish: if (ref) { DbUnlock(db, ref); } if (room) { RoomUnlock(room); } if (user) { UserUnlock(user); } ConfigUnlock(&config); Free(userId); return response; } static int ContainsCase(char *haystack, char *needle) { size_t i; size_t n; if (!haystack || !needle || !needle[0]) { return 0; } n = strlen(needle); for (i = 0; haystack[i]; i++) { if (!strncasecmp(haystack + i, needle, n)) { return 1; } } return 0; } ROUTE_IMPL(RouteSearch, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *request = NULL; HashMap *response = NULL; HashMap *categories; HashMap *roomEvents; HashMap *reqCategories; HashMap *reqRoomEvents; HashMap *filter; Array *roomsFilter = NULL; Array *notRooms = NULL; Array *results; User *user = NULL; Config config; char *token = NULL; char *userId = NULL; char *term = NULL; long limit = 50; (void) path; if (HttpRequestMethodGet(args->context) != HTTP_POST) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, NULL); } ConfigLock(db, &config); if (!config.ok) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } request = JsonDecode(HttpServerStream(args->context)); if (!request) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_NOT_JSON, NULL); goto finish; } reqCategories = JsonValueAsObject(HashMapGet(request, "search_categories")); reqRoomEvents = reqCategories ? JsonValueAsObject(HashMapGet(reqCategories, "room_events")) : NULL; term = reqRoomEvents ? JsonValueAsString(HashMapGet(reqRoomEvents, "search_term")) : NULL; if (!term || !term[0]) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_BAD_JSON, "search_term is required"); goto finish; } filter = reqRoomEvents ? JsonValueAsObject(HashMapGet(reqRoomEvents, "filter")) : NULL; if (filter) { JsonValue *l = HashMapGet(filter, "limit"); if (l) { limit = JsonValueAsInteger(l); } roomsFilter = JsonValueAsArray(HashMapGet(filter, "rooms")); notRooms = JsonValueAsArray(HashMapGet(filter, "not_rooms")); } if (limit < 1) { limit = 1; } if (limit > 100) { limit = 100; } userId = StrConcat(4, "@", UserGetName(user), ":", config.serverName); results = ArrayCreate(); { DbRef *iref = DbLock(db, 2, "rooms", "index"); Array *ids = iref ? JsonValueAsArray(HashMapGet(DbJson(iref), "rooms")) : NULL; size_t n = ids ? ArraySize(ids) : 0; size_t k; for (k = 0; k < n && (long) ArraySize(results) < limit; k++) { char *rid = JsonValueAsString(ArrayGet(ids, k)); Room *room = rid ? RoomLock(db, rid) : NULL; DbRef *eref; Array *events; size_t i; int skip = 0; if (!room) { continue; } if (!RoomMemberJoined(room, userId)) { RoomUnlock(room); continue; } if (roomsFilter) { skip = 1; for (i = 0; i < ArraySize(roomsFilter); i++) { char *r = JsonValueAsString(ArrayGet(roomsFilter, i)); if (r && StrEquals(r, rid)) { skip = 0; break; } } } if (notRooms) { for (i = 0; i < ArraySize(notRooms); i++) { char *r = JsonValueAsString(ArrayGet(notRooms, i)); if (r && StrEquals(r, rid)) { skip = 1; break; } } } eref = skip ? NULL : DbLock(db, 3, "rooms", rid, "events"); events = eref ? JsonValueAsArray(HashMapGet(DbJson(eref), "events")) : NULL; for (i = 0; events && i < ArraySize(events) && (long) ArraySize(results) < limit; i++) { HashMap *ev = JsonValueAsObject(ArrayGet(events, i)); char *type = ev ? JsonValueAsString(HashMapGet(ev, "type")) : NULL; HashMap *content = ev ? JsonValueAsObject(HashMapGet(ev, "content")) : NULL; char *body = content ? JsonValueAsString(HashMapGet(content, "body")) : NULL; if (type && StrEquals(type, "m.room.message") && ContainsCase(body, term)) { HashMap *result = HashMapCreate(); HashMap *copy = JsonDuplicate(ev); HashMapDelete(copy, "_seq"); HashMapSet(result, "rank", JsonValueFloat(0.5)); HashMapSet(result, "result", JsonValueObject(copy)); HashMapSet(result, "context", JsonValueObject(HashMapCreate())); ArrayAdd(results, JsonValueObject(result)); } } if (eref) { DbUnlock(db, eref); } RoomUnlock(room); } if (iref) { DbUnlock(db, iref); } } response = HashMapCreate(); categories = HashMapCreate(); roomEvents = HashMapCreate(); HashMapSet(roomEvents, "count", JsonValueInteger((long) ArraySize(results))); HashMapSet(roomEvents, "highlights", JsonValueArray(ArrayCreate())); HashMapSet(roomEvents, "results", JsonValueArray(results)); HashMapSet(categories, "room_events", JsonValueObject(roomEvents)); HashMapSet(response, "search_categories", JsonValueObject(categories)); finish: if (user) { UserUnlock(user); } JsonFree(request); ConfigUnlock(&config); Free(userId); return response; } static void HierarchyFill(HashMap * out, Room * room) { HashMap *state = RoomStateGet(room); HashMap *content; const char *value; HashMap *members; char *key; void *val; long joined = 0; char *roomId = RoomIdGet(room); HashMapSet(out, "room_id", JsonValueString(roomId)); content = JsonValueAsObject(JsonGet(state, 2, "m.room.name", "")); value = content ? JsonValueAsString(HashMapGet(content, "name")) : NULL; if (value) HashMapSet(out, "name", JsonValueString((char *) value)); content = JsonValueAsObject(JsonGet(state, 2, "m.room.topic", "")); value = content ? JsonValueAsString(HashMapGet(content, "topic")) : NULL; if (value) HashMapSet(out, "topic", JsonValueString((char *) value)); content = JsonValueAsObject(JsonGet(state, 2, "m.room.avatar", "")); value = content ? JsonValueAsString(HashMapGet(content, "url")) : NULL; if (value) HashMapSet(out, "avatar_url", JsonValueString((char *) value)); content = JsonValueAsObject(JsonGet(state, 2, "m.room.canonical_alias", "")); value = content ? JsonValueAsString(HashMapGet(content, "alias")) : NULL; if (value) HashMapSet(out, "canonical_alias", JsonValueString((char *) value)); content = JsonValueAsObject(JsonGet(state, 2, "m.room.join_rules", "")); value = content ? JsonValueAsString(HashMapGet(content, "join_rule")) : NULL; HashMapSet(out, "join_rule", JsonValueString((char *) (value ? value : "invite"))); content = JsonValueAsObject(JsonGet(state, 2, "m.room.create", "")); value = content ? JsonValueAsString(HashMapGet(content, "type")) : NULL; if (value) HashMapSet(out, "room_type", JsonValueString((char *) value)); members = JsonValueAsObject(HashMapGet(state, "m.room.member")); while (members && HashMapIterate(members, &key, &val)) { HashMap *m = JsonValueAsObject((JsonValue *) val); const char *mem = m ? JsonValueAsString(HashMapGet(m, "membership")) : NULL; if (mem && StrEquals(mem, "join")) joined++; } HashMapSet(out, "num_joined_members", JsonValueInteger(joined)); HashMapSet(out, "world_readable", JsonValueBoolean(false)); HashMapSet(out, "guest_can_join", JsonValueBoolean(false)); HashMapSet(out, "children_state", JsonValueArray(ArrayCreate())); } ROUTE_IMPL(RouteRoomHierarchy, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *response = NULL; User *user = NULL; Room *room = NULL; Config config; char *token = NULL; char *roomId = ArrayGet(path, 0); char *userId = NULL; if (HttpRequestMethodGet(args->context) != HTTP_GET) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, NULL); } ConfigLock(db, &config); if (!config.ok) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } room = RoomLock(db, roomId); if (!room) { HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, NULL); goto finish; } userId = StrConcat(4, "@", UserGetName(user), ":", config.serverName); response = HashMapCreate(); HashMapSet(response, "rooms", JsonValueArray(ArrayCreate())); HashMapSet(response, "next_batch", JsonValueNull()); { HashMap *children = JsonValueAsObject(HashMapGet(RoomStateGet(room), "m.space.child")); Array *list = JsonValueAsArray(HashMapGet(response, "rooms")); char *childId; void *val; if (children) { while (HashMapIterate(children, &childId, &val)) { HashMap *childContent = JsonValueAsObject((JsonValue *) val); Room *child; if (!childContent || !HashMapGet(childContent, "via")) { continue; } child = RoomLock(db, childId); if (!child) { continue; } { HashMap *info = HashMapCreate(); HierarchyFill(info, child); ArrayAdd(list, JsonValueObject(info)); } RoomUnlock(child); } } } (void) userId; finish: if (room) { RoomUnlock(room); } if (user) { UserUnlock(user); } ConfigUnlock(&config); Free(userId); return response; } ROUTE_IMPL(RouteUpgradeRoom, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *request = NULL; HashMap *response = NULL; HashMap *state; HashMap *content; User *user = NULL; Room *room = NULL; Room *replacement = NULL; Config config; RoomCreateRequest parsed; char *token = NULL; char *roomId = ArrayGet(path, 0); char *userId = NULL; char *newVersion = NULL; char *tombstoneId = NULL; char *replacementId = NULL; memset(&parsed, 0, sizeof(parsed)); if (HttpRequestMethodGet(args->context) != HTTP_POST) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, NULL); } ConfigLock(db, &config); if (!config.ok) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } room = RoomLock(db, roomId); if (!room) { HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, NULL); goto finish; } userId = StrConcat(4, "@", UserGetName(user), ":", config.serverName); if (!RoomMemberJoined(room, userId) || RoomUserPower(room, userId) < 50) { HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, NULL); goto finish; } request = JsonDecode(HttpServerStream(args->context)); if (!request) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); response = MatrixErrorCreate(M_NOT_JSON, NULL); goto finish; } newVersion = JsonValueAsString(HashMapGet(request, "new_version")); state = RoomStateGet(room); parsed.room_version = newVersion ? StrDuplicate(newVersion) : StrDuplicate("10"); content = JsonValueAsObject(JsonGet(state, 2, "m.room.name", "")); if (content && HashMapGet(content, "name")) { parsed.name = StrDuplicate(JsonValueAsString(HashMapGet(content, "name"))); } content = JsonValueAsObject(JsonGet(state, 2, "m.room.topic", "")); if (content && HashMapGet(content, "topic")) { parsed.topic = StrDuplicate(JsonValueAsString(HashMapGet(content, "topic"))); } content = JsonValueAsObject(JsonGet(state, 2, "m.room.join_rules", "")); { char *rule = content ? JsonValueAsString(HashMapGet(content, "join_rule")) : NULL; parsed.preset = (rule && StrEquals(rule, "public")) ? ROOM_CREATE_PUBLIC : ROOM_CREATE_PRIVATE; } tombstoneId = StrConcat(2, "$", StrRandom(24)); replacement = RoomCreate(db, &parsed, userId); if (!replacement) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); response = MatrixErrorCreate(M_UNKNOWN, NULL); goto finish; } replacementId = StrDuplicate(RoomIdGet(replacement)); { HashMap *newState = RoomStateGet(replacement); HashMap *create = JsonValueAsObject(JsonGet(newState, 2, "m.room.create", "")); HashMap *predecessor = HashMapCreate(); HashMapSet(predecessor, "room_id", JsonValueString(roomId)); HashMapSet(predecessor, "event_id", JsonValueString(tombstoneId)); if (create) { HashMapSet(create, "predecessor", JsonValueObject(predecessor)); } } { HashMap *event = HashMapCreate(); HashMap *body = HashMapCreate(); HashMapSet(body, "body", JsonValueString("This room has been replaced")); HashMapSet(body, "replacement_room", JsonValueString(replacementId)); HashMapSet(event, "event_id", JsonValueString(tombstoneId)); HashMapSet(event, "type", JsonValueString("m.room.tombstone")); HashMapSet(event, "state_key", JsonValueString("")); HashMapSet(event, "sender", JsonValueString(userId)); HashMapSet(event, "room_id", JsonValueString(roomId)); HashMapSet(event, "origin_server_ts", JsonValueInteger((long) time(NULL) * 1000)); HashMapSet(event, "content", JsonValueObject(body)); RoomEventSend(room, event); JsonFree(event); } response = HashMapCreate(); HashMapSet(response, "replacement_room", JsonValueString(replacementId)); finish: if (replacement) { RoomUnlock(replacement); } if (room) { RoomUnlock(room); } if (user) { UserUnlock(user); } JsonFree(request); ConfigUnlock(&config); Free(parsed.room_version); Free(parsed.name); Free(parsed.topic); Free(userId); Free(tombstoneId); Free(replacementId); return response; } ROUTE_IMPL(RouteKnockRoom, path, argp) { RouteArgs *args = argp; Db *db = args->matrixArgs->db; HashMap *response = NULL; HashMap *state; HashMap *member; HashMap *rules; User *user = NULL; Room *room = NULL; Config config; char *token = NULL; char *roomId = ArrayGet(path, 0); char *userId = NULL; if (HttpRequestMethodGet(args->context) != HTTP_POST) { HttpResponseStatus(args->context, HTTP_BAD_REQUEST); return MatrixErrorCreate(M_UNRECOGNIZED, NULL); } ConfigLock(db, &config); if (!config.ok) { HttpResponseStatus(args->context, HTTP_INTERNAL_SERVER_ERROR); return MatrixErrorCreate(M_UNKNOWN, config.err); } response = MatrixGetAccessToken(args->context, &token); if (response) { goto finish; } user = MatrixAuthenticateUser(db, args->context, token); if (!user) { HttpResponseStatus(args->context, HTTP_UNAUTHORIZED); response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL); goto finish; } room = RoomLock(db, roomId); if (!room) { HttpResponseStatus(args->context, HTTP_NOT_FOUND); response = MatrixErrorCreate(M_NOT_FOUND, NULL); goto finish; } userId = StrConcat(4, "@", UserGetName(user), ":", config.serverName); state = RoomStateGet(room); member = JsonValueAsObject(JsonGet(state, 2, "m.room.member", userId)); if (member) { char *membership = JsonValueAsString(HashMapGet(member, "membership")); if (membership && (StrEquals(membership, "join") || StrEquals(membership, "invite") || StrEquals(membership, "knock") || StrEquals(membership, "ban"))) { HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, NULL); goto finish; } } rules = JsonValueAsObject(JsonGet(state, 2, "m.room.join_rules", "")); { char *rule = rules ? JsonValueAsString(HashMapGet(rules, "join_rule")) : NULL; if (!rule || (!StrEquals(rule, "knock") && !StrEquals(rule, "restricted"))) { HttpResponseStatus(args->context, HTTP_FORBIDDEN); response = MatrixErrorCreate(M_FORBIDDEN, NULL); goto finish; } } Free(RoomSendMembership(room, userId, userId, "knock")); response = HashMapCreate(); finish: if (room) { RoomUnlock(room); } if (user) { UserUnlock(user); } ConfigUnlock(&config); Free(userId); return response; }