/* * 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 struct Room { Db *db; DbRef *ref; char *id; int version; }; static pthread_mutex_t streamLock = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t streamCond = PTHREAD_COND_INITIALIZER; static uint64_t streamPos = 0; static int streamInit = 0; static void StreamInitLocked(Db * db) { if (!streamInit && db) { DbRef *ref = DbLock(db, 1, "sync"); if (ref) { JsonValue *v = HashMapGet(DbJson(ref), "pos"); streamPos = v ? JsonValueAsInteger(v) : 0; DbUnlock(db, ref); } streamInit = 1; } } uint64_t RoomStreamPosition(Db * db) { uint64_t pos; pthread_mutex_lock(&streamLock); StreamInitLocked(db); pos = streamPos; pthread_mutex_unlock(&streamLock); return pos; } uint64_t RoomWaitForStream(Db * db, uint64_t since, long timeoutMs) { struct timespec deadline; clock_gettime(CLOCK_REALTIME, &deadline); deadline.tv_sec += timeoutMs / 1000; deadline.tv_nsec += (timeoutMs % 1000) * 1000000L; if (deadline.tv_nsec >= 1000000000L) { deadline.tv_sec++; deadline.tv_nsec -= 1000000000L; } pthread_mutex_lock(&streamLock); StreamInitLocked(db); while (streamPos <= since) { if (pthread_cond_timedwait(&streamCond, &streamLock, &deadline) != 0) { break; } } since = streamPos; pthread_mutex_unlock(&streamLock); return since; } Array * RoomPrevEventsGet(Room * room) { DbRef *ref; Array *out = NULL; Array *ids; size_t i; if (!room) { return NULL; } ref = DbLock(room->db, 3, "rooms", room->id, "extremities"); if (!ref) { return ArrayCreate(); } ids = JsonValueAsArray(JsonGet(DbJson(ref), 1, "events")); out = ArrayCreate(); for (i = 0; ids && i < ArraySize(ids); i++) { char *id = JsonValueAsString(ArrayGet(ids, i)); if (id && out) { ArrayAdd(out, JsonValueString(StrDuplicate(id))); } } DbUnlock(room->db, ref); return out; } int RoomPrevEventsSet(Room * room, Array * events) { DbRef *ref; Array *ids; size_t i; if (!room) { return 0; } ref = DbLock(room->db, 3, "rooms", room->id, "extremities"); if (!ref) { ref = DbCreate(room->db, 3, "rooms", room->id, "extremities"); } if (!ref) { return 0; } ids = ArrayCreate(); for (i = 0; events && i < ArraySize(events); i++) { char *id = JsonValueAsString(ArrayGet(events, i)); if (id) { ArrayAdd(ids, JsonValueString(StrDuplicate(id))); } } HashMapSet(DbJson(ref), "events", JsonValueArray(ids)); DbUnlock(room->db, ref); return 1; } Room * RoomCreateFederated(Db * db, char * roomId, Array * stateEvents) { DbRef *ref; HashMap *state; size_t i; if (!db || !roomId) { return NULL; } ref = DbCreate(db, 3, "rooms", roomId, "state"); if (!ref) { ref = DbLock(db, 3, "rooms", roomId, "state"); } if (!ref) { return NULL; } state = DbJson(ref); for (i = 0; stateEvents && i < ArraySize(stateEvents); i++) { HashMap *ev = JsonValueAsObject(ArrayGet(stateEvents, i)); char *type = ev ? JsonValueAsString(HashMapGet(ev, "type")) : NULL; char *skey = ev ? JsonValueAsString(HashMapGet(ev, "state_key")) : NULL; HashMap *content = ev ? JsonValueAsObject(HashMapGet(ev, "content")) : NULL; if (type && skey && content) { JsonSet(state, JsonValueObject(JsonDuplicate(content)), 2, type, skey); } } DbUnlock(db, ref); return RoomLock(db, roomId); } Room * RoomCreate(Db * db, RoomCreateRequest * req, char *creator) { Room *room; DbRef *ref; HashMap *state; HashMap *content; HashMap *users; char *id; if (!db || !req || !creator) { return NULL; } id = StrConcat(2, "!", StrRandom(18)); if (!id) { return NULL; } ref = DbCreate(db, 3, "rooms", id, "state"); if (!ref) { Free(id); return NULL; } state = DbJson(ref); content = HashMapCreate(); HashMapSet(content, "creator", JsonValueString(creator)); HashMapSet(content, "room_version", JsonValueString((req->room_version && req->room_version[0]) ? req->room_version : "10")); JsonSet(state, JsonValueObject(content), 2, "m.room.create", ""); content = HashMapCreate(); HashMapSet(content, "membership", JsonValueString("join")); JsonSet(state, JsonValueObject(content), 2, "m.room.member", creator); content = HashMapCreate(); users = HashMapCreate(); HashMapSet(users, creator, JsonValueInteger(100)); HashMapSet(content, "users", JsonValueObject(users)); HashMapSet(content, "users_default", JsonValueInteger(0)); HashMapSet(content, "events_default", JsonValueInteger(0)); HashMapSet(content, "state_default", JsonValueInteger(50)); HashMapSet(content, "invite", JsonValueInteger(0)); HashMapSet(content, "kick", JsonValueInteger(50)); HashMapSet(content, "ban", JsonValueInteger(50)); HashMapSet(content, "redact", JsonValueInteger(50)); JsonSet(state, JsonValueObject(content), 2, "m.room.power_levels", ""); content = HashMapCreate(); HashMapSet(content, "join_rule", JsonValueString(req->preset == ROOM_CREATE_PUBLIC ? "public" : "invite")); JsonSet(state, JsonValueObject(content), 2, "m.room.join_rules", ""); if (req->topic) { content = HashMapCreate(); HashMapSet(content, "topic", JsonValueString(req->topic)); JsonSet(state, JsonValueObject(content), 2, "m.room.topic", ""); } if (req->name) { content = HashMapCreate(); HashMapSet(content, "name", JsonValueString(req->name)); JsonSet(state, JsonValueObject(content), 2, "m.room.name", ""); } if (req->invite) { size_t i; for (i = 0; i < ArraySize(req->invite); i++) { char *invitee = ArrayGet(req->invite, i); if (!invitee) { continue; } content = HashMapCreate(); HashMapSet(content, "membership", JsonValueString("invite")); JsonSet(state, JsonValueObject(content), 2, "m.room.member", invitee); } } if (req->initial_state) { size_t i; for (i = 0; i < ArraySize(req->initial_state); i++) { RoomStateEvent *ev = ArrayGet(req->initial_state, i); if (!ev || !ev->type || !ev->content) { continue; } JsonSet(state, JsonValueObject(JsonDuplicate(ev->content)), 2, ev->type, ev->state_key ? ev->state_key : ""); } } { DbRef *iref; HashMap *index; Array *ids; iref = DbLock(db, 2, "rooms", "index"); if (!iref) { iref = DbCreate(db, 2, "rooms", "index"); } if (iref) { index = DbJson(iref); ids = JsonValueAsArray(HashMapGet(index, "rooms")); if (!ids) { ids = ArrayCreate(); HashMapSet(index, "rooms", JsonValueArray(ids)); } ArrayAdd(ids, JsonValueString(id)); DbUnlock(db, iref); } } room = Malloc(sizeof(Room)); if (!room) { DbUnlock(db, ref); Free(id); return NULL; } room->db = db; room->ref = ref; room->id = id; room->version = 1; return room; } Room * RoomLock(Db * db, char *id) { DbRef *ref; Room *room; if (!db || !id) { return NULL; } ref = DbLock(db, 3, "rooms", id, "state"); if (!ref) { return NULL; } room = Malloc(sizeof(Room)); if (!room) { DbUnlock(db, ref); return NULL; } room->db = db; room->ref = ref; room->id = StrDuplicate(id); return room; } int RoomUnlock(Room * room) { Db *db; DbRef *ref; if (!room) { return 0; } db = room->db; ref = room->ref; Free(room->id); Free(room); return DbUnlock(db, ref); } char * RoomIdGet(Room * room) { return room ? room->id : NULL; } Db * RoomDbGet(Room * room) { return room ? room->db : NULL; } int RoomVersionGet(Room * room) { HashMap *state; JsonValue *create; HashMap *content; char *version; if (!room) { return 0; } state = RoomStateGet(room); create = state ? JsonGet(state, 2, "m.room.create", "") : NULL; content = create ? JsonValueAsObject(create) : NULL; version = content ? JsonValueAsString(HashMapGet(content, "room_version")) : NULL; return version ? atoi(version) : 1; } HashMap * RoomStateGet(Room * room) { if (!room) { return NULL; } return DbJson(room->ref); } static HashMap * RoomStoreEvent(Room * room, HashMap * event, int sign) { DbRef *ref; HashMap *store; Array *events; if (!room || !event) { return NULL; } if (sign) { EventSign(room, event); } ref = DbLock(room->db, 3, "rooms", room->id, "events"); if (!ref) { ref = DbCreate(room->db, 3, "rooms", room->id, "events"); } if (!ref) { return NULL; } store = DbJson(ref); events = JsonValueAsArray(HashMapGet(store, "events")); if (!events) { events = ArrayCreate(); HashMapSet(store, "events", JsonValueArray(events)); } { DbRef *sref; HashMap *sm; uint64_t seq; pthread_mutex_lock(&streamLock); StreamInitLocked(room->db); seq = streamPos + 1; streamPos = seq; pthread_cond_broadcast(&streamCond); pthread_mutex_unlock(&streamLock); HashMapSet(event, "_seq", JsonValueInteger(seq)); sref = DbLock(room->db, 1, "sync"); if (!sref) { sref = DbCreate(room->db, 1, "sync"); } if (sref) { sm = DbJson(sref); HashMapSet(sm, "pos", JsonValueInteger(seq)); DbUnlock(room->db, sref); } } { JsonValue *skv = HashMapGet(event, "state_key"); if (skv) { char *stateKey = JsonValueAsString(skv); char *etype = JsonValueAsString(HashMapGet(event, "type")); HashMap *content = JsonValueAsObject(HashMapGet(event, "content")); if (stateKey && etype && content) { JsonSet(DbJson(room->ref), JsonValueObject(JsonDuplicate(content)), 2, etype, stateKey); } } } ArrayAdd(events, JsonValueObject(JsonDuplicate(event))); DbUnlock(room->db, ref); AppserviceQueueEvent(event, DbJson(room->ref)); PushNotifyEvent(room->db, room->id, DbJson(room->ref), event); return event; } HashMap * RoomEventSend(Room * room, HashMap * event) { return RoomStoreEvent(room, event, 1); } HashMap * RoomEventAppend(Room * room, HashMap * event) { return RoomStoreEvent(room, event, 0); } static char * LatestEventId(Array * events, char * type, char * stateKey) { char *id = NULL; size_t i; for (i = 0; events && i < ArraySize(events); i++) { HashMap *ev = JsonValueAsObject(ArrayGet(events, i)); char *t = ev ? JsonValueAsString(HashMapGet(ev, "type")) : NULL; char *sk = ev ? JsonValueAsString(HashMapGet(ev, "state_key")) : NULL; if (t && StrEquals(t, type) && sk && stateKey && StrEquals(sk, stateKey)) { char *eid = JsonValueAsString(HashMapGet(ev, "event_id")); if (eid) { Free(id); id = StrDuplicate(eid); } } } return id; } void RoomEventFill(Room * room, HashMap * event) { DbRef *ref; HashMap *store; Array *events; Array *prev; Array *auth; char *sender; size_t i; uint64_t depth = 1; if (!room || !event) { return; } ref = DbLock(room->db, 3, "rooms", room->id, "events"); events = ref ? JsonValueAsArray(HashMapGet(DbJson(ref), "events")) : NULL; prev = RoomPrevEventsGet(room); HashMapSet(event, "prev_events", JsonValueArray(prev ? prev : ArrayCreate())); auth = ArrayCreate(); { char *ids[2]; char *sender = JsonValueAsString(HashMapGet(event, "sender")); ids[0] = LatestEventId(events, "m.room.create", ""); ids[1] = LatestEventId(events, "m.room.power_levels", ""); for (i = 0; i < 2; i++) { if (ids[i]) { ArrayAdd(auth, JsonValueString(ids[i])); } } if (sender) { char *mid = LatestEventId(events, "m.room.member", sender); if (mid) { ArrayAdd(auth, JsonValueString(mid)); } } } HashMapSet(event, "auth_events", JsonValueArray(auth)); for (i = 0; events && i < ArraySize(events); i++) { HashMap *ev = JsonValueAsObject(ArrayGet(events, i)); JsonValue *d = ev ? HashMapGet(ev, "depth") : NULL; uint64_t v = d ? (uint64_t) JsonValueAsInteger(d) : 1; if (v >= depth) { depth = v + 1; } } HashMapSet(event, "depth", JsonValueInteger(depth)); if (ref) { DbUnlock(room->db, ref); } }