From 327730c2c6621143f262d05a18c9eb856ccbb9d1 Mon Sep 17 00:00:00 2001 From: lda Date: Sat, 18 May 2024 20:17:54 +0200 Subject: [PATCH] [ADD/WIP] Basic PDU depth system. NOTE: This is *not* a good way to compute depth. --- src/Room.c | 57 ++++++++++++++++++++++++++++++++++++++++++++++ src/include/Room.h | 6 +++++ 2 files changed, 63 insertions(+) diff --git a/src/Room.c b/src/Room.c index 8682b1c..652c083 100644 --- a/src/Room.c +++ b/src/Room.c @@ -91,6 +91,8 @@ RoomCreate(Db * db, User *user, RoomCreateRequest * req, ServerPart s) char *sender_str, *key; JsonValue *val; HashMap *override; + Array *initial_states; + size_t i; if (!db || !req || !user) { return NULL; @@ -164,6 +166,21 @@ RoomCreate(Db * db, User *user, RoomCreateRequest * req, ServerPart s) /* TODO: Events set by the preset */ /* TODO: Events in initial_state */ + initial_states = req->initial_state; + for (i = 0; i < ArraySize(initial_states); i++) + { + RoomStateEvent *rse = ArrayGet(initial_states, i); + HashMap *rseObject = RoomStateEventToJson(rse); + + if (!HashMapGet(rseObject, "state_key")) + { + HashMapSet(rseObject, "state_key", JsonValueString("")); + } + HashMapSet(rseObject, "sender", JsonValueString(sender_str)); + + JsonFree(RoomEventSend(room, rseObject)); + JsonFree(rseObject); + } if (req->name) { content = HashMapCreate(); @@ -481,6 +498,7 @@ PopulateEventV1(Room * room, HashMap * event, PduV1 * pdu, ServerPart serv) JsonDuplicate(JsonValueAsObject(JsonGet(event, 1, "content"))); pdu->room_id = StrDuplicate(room->id); pdu->signatures = HashMapCreate(); + pdu->depth = RoomGetDepth(room) + 1; /* TODO: Clamp this value. */ /* Create a random event ID for this PDU. * TODO: Optionally verify whenever it's already used, but that @@ -1661,3 +1679,42 @@ RoomEventCreate(char *sender, char *type, char *key, HashMap *c) return event; } + +/* TODO: This has it's fair share of problems, as a malicious + * homserver could *easily* fake a PDU depth and put this + * function to the depth limit. */ +uint64_t +RoomGetDepth(Room *room) +{ + Array *leaves; + HashMap *pdu; + size_t i; + uint64_t max; + if (!room) + { + return 0; + } + + leaves = RoomPrevEventsGet(room); + if (!leaves) + { + return 0; + } + + max = 0; + for (i = 0; i < ArraySize(leaves); i++) + { + uint64_t depth; + pdu = JsonValueAsObject(ArrayGet(leaves, i)); + + depth = JsonValueAsInteger(HashMapGet(pdu, "depth")); + if (depth > max) + { + max = depth; + } + } + (void) i; + (void) pdu; + + return max; +} diff --git a/src/include/Room.h b/src/include/Room.h index 7213916..feeec5a 100644 --- a/src/include/Room.h +++ b/src/include/Room.h @@ -170,4 +170,10 @@ extern bool RoomAddEventV1(Room *, PduV1); */ extern HashMap * RoomEventCreate(char *, char *, char *, HashMap *); +/** + * Computes an approximation of the PDU depth by looking at + * the leaves stored in the room data. + */ +extern uint64_t RoomGetDepth(Room *); + #endif /* TELODENDRIA_ROOM_H */