Debian Codegraph @

src/Cache.cpp

raw symbols SCIP
1 // SPDX-FileCopyrightText: Nheko Contributors
2 //
3 // SPDX-License-Identifier: GPL-3.0-or-later
4
5 #include "Cache.h"
6 #include "Cache_p.h"
7
8 #include <stdexcept>
9 #include <unordered_set>
10 #include <variant>
11
12 #include <QCoreApplication>
13 #include <QCryptographicHash>
14 #include <QDir>
15 #include <QFile>
16 #include <QHash>
17 #include <QMap>
18 #include <QMessageBox>
19 #include <QStandardPaths>
20
21 #if __has_include(<lmdbxx/lmdb++.h>)
22 #include <lmdbxx/lmdb++.h>
23 #else
24 #include <lmdb++.h>
25 #endif
26
27 #if __has_include(<keychain.h>)
28 #include <keychain.h>
29 #else
30 #include <qt6keychain/keychain.h>
31 #endif
32
33 #include <nlohmann/json.hpp>
34
35 #include <mtx/responses/common.hpp>
36 #include <mtx/responses/messages.hpp>
37
38 #include "ChatPage.h"
39 #include "EventAccessors.h"
40 #include "Logging.h"
41 #include "MatrixClient.h"
42 #include "UserSettingsPage.h"
43 #include "Utils.h"
44 #include "encryption/Olm.h"
45
46 //! Should be changed when a breaking change occurs in the cache format.
47 //! This will reset client's data.
48 static constexpr std::string_view CURRENT_CACHE_FORMAT_VERSION{"2023.10.22"};
49 static constexpr std::string_view MAX_DBS_SETTINGS_KEY{"database/maxdbs"};
50 static constexpr std::string_view MAX_DB_SIZE_SETTINGS_KEY{"database/maxsize"};
51
52 //! Keys used for the DB
53 static const std::string_view NEXT_BATCH_KEY("next_batch");
54 static const std::string_view OLM_ACCOUNT_KEY("olm_account");
55 static const std::string_view CACHE_FORMAT_VERSION_KEY("cache_format_version");
56 static const std::string_view CURRENT_ONLINE_BACKUP_VERSION("current_online_backup_version");
57
58 static constexpr auto MAX_DBS_DEFAULT = 32384U;
59
60 #if Q_PROCESSOR_WORDSIZE >= 5 // 40-bit or more, up to 2^(8*WORDSIZE) words addressable.
61 static constexpr auto DB_SIZE_DEFAULT = 32ULL * 1024ULL * 1024ULL * 1024ULL; // 32 GB
62 static constexpr size_t MAX_RESTORED_MESSAGES = 30'000;
63 #elif Q_PROCESSOR_WORDSIZE == 4 // 32-bit address space limits mmaps
64 static constexpr auto DB_SIZE_DEFAULT = 1ULL * 1024ULL * 1024ULL * 1024ULL; // 1 GB
65 static constexpr size_t MAX_RESTORED_MESSAGES = 5'000;
66 #else
67 #error Not enough virtual address space for the database on target CPU
68 #endif
69
70 //! Cache databases and their format.
71 //!
72 //! Contains UI information for the joined rooms. (i.e name, topic, avatar url etc).
73 //! Format: room_id -> RoomInfo
74 static constexpr auto ROOMS_DB("rooms");
75 static constexpr auto INVITES_DB("invites");
76 //! maps each room to its parent space (id->id)
77 static constexpr auto SPACES_PARENTS_DB("space_parents");
78 //! maps each space to its current children (id->id)
79 static constexpr auto SPACES_CHILDREN_DB("space_children");
80 //! Information that must be kept between sync requests.
81 static constexpr auto SYNC_STATE_DB("sync_state");
82 //! Read receipts per room/event.
83 static constexpr auto READ_RECEIPTS_DB("read_receipts");
84 static constexpr auto NOTIFICATIONS_DB("sent_notifications");
85 static constexpr auto PRESENCE_DB("presence");
86
87 //! Encryption related databases.
88
89 //! room_ids that have encryption enabled.
90 static constexpr auto ENCRYPTED_ROOMS_DB("encrypted_rooms");
91 //! Expiration progress for each room
92 static constexpr auto EVENT_EXPIRATION_BG_JOB_DB("event_expiration_bg_job");
93
94 //! room_id -> pickled OlmInboundGroupSession
95 static constexpr auto INBOUND_MEGOLM_SESSIONS_DB("inbound_megolm_sessions");
96 //! MegolmSessionIndex -> pickled OlmOutboundGroupSession
97 static constexpr auto OUTBOUND_MEGOLM_SESSIONS_DB("outbound_megolm_sessions");
98 //! MegolmSessionIndex -> session data about which devices have access to this
99 static constexpr auto MEGOLM_SESSIONS_DATA_DB("megolm_sessions_data_db");
100 //! Curve25519 key to session_id and json encoded olm session, separated by null. Dupsorted.
101 static constexpr auto OLM_SESSIONS_DB("olm_sessions.v3");
102
103 //! flag to be set, when the db should be compacted on startup
104 bool needsCompact = false;
105
106 using CachedReceipts = std::multimap<uint64_t, std::string, std::greater<uint64_t>>;
107 using Receipts = std::map<std::string, std::map<std::string, uint64_t>>;
108
109 struct CacheDb
110 {
111 lmdb::env env_ = nullptr;
112 lmdb::dbi syncState;
113 lmdb::dbi rooms;
114 lmdb::dbi spacesChildren, spacesParents;
115 lmdb::dbi invites;
116 lmdb::dbi readReceipts;
117 lmdb::dbi notifications;
118 lmdb::dbi presence;
119
120 lmdb::dbi inboundMegolmSessions;
121 lmdb::dbi outboundMegolmSessions;
122 lmdb::dbi megolmSessionsData;
123 lmdb::dbi olmSessions;
124
125 lmdb::dbi encryptedRooms_;
126
127 lmdb::dbi eventExpiryBgJob_;
128 };
129
130 Cache::~Cache() noexcept = default;
131
132 static std::string
133 combineOlmSessionKeyFromCurveAndSessionId(std::string_view curve25519, std::string_view session_id)
134 {
135 std::string combined(curve25519.size() + 1 + session_id.size(), '\0');
136 combined.replace(0, curve25519.size(), curve25519);
137 combined.replace(curve25519.size() + 1, session_id.size(), session_id);
138 return combined;
139 }
140 static std::pair<std::string_view, std::string_view>
141 splitCurve25519AndOlmSessionId(std::string_view input)
142 {
143 auto separator = input.find('\0');
144 return std::pair(input.substr(0, separator), input.substr(separator + 1));
145 }
146
147 namespace {
148 std::unique_ptr<Cache> instance_ = nullptr;
149 }
150
151 struct RO_txn
152 {
153 ~RO_txn() { txn.reset(); }
154 operator MDB_txn *() const noexcept { return txn.handle(); }
155 operator lmdb::txn &() noexcept { return txn; }
156
157 lmdb::txn &txn;
158 };
159
160 RO_txn
161 ro_txn(lmdb::env &env)
162 {
163 thread_local lmdb::txn txn = lmdb::txn::begin(env, nullptr, MDB_RDONLY);
164 thread_local int reuse_counter = 0;
165
166 if (reuse_counter >= 100 || txn.env() != env.handle()) {
167 txn.abort();
168 txn = lmdb::txn::begin(env, nullptr, MDB_RDONLY);
169 reuse_counter = 0;
170 } else if (reuse_counter > 0) {
171 try {
172 txn.renew();
173 } catch (...) {
174 txn.abort();
175 txn = lmdb::txn::begin(env, nullptr, MDB_RDONLY);
176 reuse_counter = 0;
177 }
178 }
179 reuse_counter++;
180
181 return RO_txn{txn};
182 }
183
184 lmdb::dbi
185 Cache::getEventsDb(lmdb::txn &txn, const std::string &room_id)
186 {
187 return lmdb::dbi::open(txn, std::string(room_id + "/events").c_str(), MDB_CREATE);
188 }
189
190 lmdb::dbi
191 Cache::getEventOrderDb(lmdb::txn &txn, const std::string &room_id)
192 {
193 return lmdb::dbi::open(
194 txn, std::string(room_id + "/event_order").c_str(), MDB_CREATE | MDB_INTEGERKEY);
195 }
196
197 // inverse of EventOrderDb
198 lmdb::dbi
199 Cache::getEventToOrderDb(lmdb::txn &txn, const std::string &room_id)
200 {
201 return lmdb::dbi::open(txn, std::string(room_id + "/event2order").c_str(), MDB_CREATE);
202 }
203
204 lmdb::dbi
205 Cache::getMessageToOrderDb(lmdb::txn &txn, const std::string &room_id)
206 {
207 return lmdb::dbi::open(txn, std::string(room_id + "/msg2order").c_str(), MDB_CREATE);
208 }
209
210 lmdb::dbi
211 Cache::getOrderToMessageDb(lmdb::txn &txn, const std::string &room_id)
212 {
213 return lmdb::dbi::open(
214 txn, std::string(room_id + "/order2msg").c_str(), MDB_CREATE | MDB_INTEGERKEY);
215 }
216
217 lmdb::dbi
218 Cache::getPendingMessagesDb(lmdb::txn &txn, const std::string &room_id)
219 {
220 return lmdb::dbi::open(
221 txn, std::string(room_id + "/pending").c_str(), MDB_CREATE | MDB_INTEGERKEY);
222 }
223
224 lmdb::dbi
225 Cache::getRelationsDb(lmdb::txn &txn, const std::string &room_id)
226 {
227 return lmdb::dbi::open(
228 txn, std::string(room_id + "/related").c_str(), MDB_CREATE | MDB_DUPSORT);
229 }
230
231 lmdb::dbi
232 Cache::getInviteStatesDb(lmdb::txn &txn, const std::string &room_id)
233 {
234 return lmdb::dbi::open(txn, std::string(room_id + "/invite_state").c_str(), MDB_CREATE);
235 }
236
237 lmdb::dbi
238 Cache::getInviteMembersDb(lmdb::txn &txn, const std::string &room_id)
239 {
240 return lmdb::dbi::open(txn, std::string(room_id + "/invite_members").c_str(), MDB_CREATE);
241 }
242
243 lmdb::dbi
244 Cache::getStatesDb(lmdb::txn &txn, const std::string &room_id)
245 {
246 return lmdb::dbi::open(txn, std::string(room_id + "/state").c_str(), MDB_CREATE);
247 }
248
249 static int
250 compare_state_key(const MDB_val *a, const MDB_val *b)
251 {
252 auto get_skey = [](const MDB_val *v) {
253 auto temp = std::string_view(static_cast<const char *>(v->mv_data), v->mv_size);
254 // allow only passing the state key, in which case no null char will be in it and we
255 // return the whole string because rfind returns npos.
256 // We search from the back, because state keys could include nullbytes, event ids can
257 // not.
258 return temp.substr(0, temp.rfind('\0'));
259 };
260
261 return get_skey(a).compare(get_skey(b));
262 }
263
264 lmdb::dbi
265 Cache::getStatesKeyDb(lmdb::txn &txn, const std::string &room_id)
266 {
267 auto db_ =
268 lmdb::dbi::open(txn, std::string(room_id + "/states_key").c_str(), MDB_CREATE | MDB_DUPSORT);
269 lmdb::dbi_set_dupsort(txn, db_, compare_state_key);
270 return db_;
271 }
272
273 lmdb::dbi
274 Cache::getAccountDataDb(lmdb::txn &txn, const std::string &room_id)
275 {
276 return lmdb::dbi::open(txn, std::string(room_id + "/account_data").c_str(), MDB_CREATE);
277 }
278
279 lmdb::dbi
280 Cache::getMembersDb(lmdb::txn &txn, const std::string &room_id)
281 {
282 return lmdb::dbi::open(txn, std::string(room_id + "/members").c_str(), MDB_CREATE);
283 }
284
285 lmdb::dbi
286 Cache::getUserKeysDb(lmdb::txn &txn)
287 {
288 return lmdb::dbi::open(txn, "user_key", MDB_CREATE);
289 }
290
291 lmdb::dbi
292 Cache::getVerificationDb(lmdb::txn &txn)
293 {
294 return lmdb::dbi::open(txn, "verified", MDB_CREATE);
295 }
296
297 QString
298 Cache::getDisplayName(const mtx::events::StateEvent<mtx::events::state::Member> &event)
299 {
300 if (!event.content.display_name.empty())
301 return QString::fromStdString(event.content.display_name);
302
303 return QString::fromStdString(event.state_key);
304 }
305
306 void
307 Cache::removeLeftRooms(lmdb::txn &txn, const std::map<std::string, mtx::responses::LeftRoom> &rooms)
308 {
309 for (const auto &room : rooms) {
310 removeRoom(txn, room.first);
311
312 // Clean up leftover invites.
313 removeInvite(txn, room.first);
314 }
315 }
316
317 static void
318 compactDatabase(lmdb::env &from, lmdb::env &to)
319 {
320 auto fromTxn = lmdb::txn::begin(from, nullptr, MDB_RDONLY);
321 auto toTxn = lmdb::txn::begin(to);
322
323 auto rootDb = lmdb::dbi::open(fromTxn);
324 auto dbNames = lmdb::cursor::open(fromTxn, rootDb);
325
326 std::string_view dbName;
327 while (dbNames.get(dbName, MDB_cursor_op::MDB_NEXT_NODUP)) {
328 nhlog::db()->info("Compacting db: {}", dbName);
329
330 auto flags = MDB_CREATE;
331
332 if (dbName.ends_with("/event_order") || dbName.ends_with("/order2msg") ||
333 dbName.ends_with("/pending"))
334 flags |= MDB_INTEGERKEY;
335 if (dbName.ends_with("/related") || dbName.ends_with("/states_key") ||
336 dbName == SPACES_CHILDREN_DB || dbName == SPACES_PARENTS_DB)
337 flags |= MDB_DUPSORT;
338
339 auto dbNameStr = std::string(dbName);
340 auto fromDb = lmdb::dbi::open(fromTxn, dbNameStr.c_str(), flags);
341 auto toDb = lmdb::dbi::open(toTxn, dbNameStr.c_str(), flags);
342
343 if (dbName.ends_with("/states_key")) {
344 lmdb::dbi_set_dupsort(fromTxn, fromDb, compare_state_key);
345 lmdb::dbi_set_dupsort(toTxn, toDb, compare_state_key);
346 }
347
348 auto fromCursor = lmdb::cursor::open(fromTxn, fromDb);
349 auto toCursor = lmdb::cursor::open(toTxn, toDb);
350
351 std::string_view key, val;
352 while (fromCursor.get(key, val, MDB_cursor_op::MDB_NEXT)) {
353 toCursor.put(key, val, MDB_APPENDDUP);
354 }
355 }
356
357 toTxn.commit();
358 }
359
360 bool
361 Cache::isHiddenEvent(lmdb::txn &txn,
362 mtx::events::collections::TimelineEvents e,
363 const std::string &room_id)
364 {
365 using namespace mtx::events;
366
367 // Always hide edits
368 if (mtx::accessors::relations(e).replaces())
369 return true;
370
371 if (auto encryptedEvent = std::get_if<EncryptedEvent<msg::Encrypted>>(&e)) {
372 MegolmSessionIndex index;
373 index.room_id = room_id;
374 index.session_id = encryptedEvent->content.session_id;
375
376 auto result = olm::decryptEvent(index, *encryptedEvent, true);
377 if (!result.error)
378 e = result.event.value();
379 }
380
381 mtx::events::account_data::nheko_extensions::HiddenEvents hiddenEvents;
382 hiddenEvents.hidden_event_types = std::vector{
383 EventType::Reaction,
384 EventType::CallCandidates,
385 EventType::CallNegotiate,
386 EventType::Unsupported,
387 };
388 // check if selected answer is from to local user
389 /*
390 * localUser accepts/rejects the call and it is selected by caller - No message
391 * Another User accepts/rejects the call and it is selected by caller - "Call answered/rejected
392 * elsewhere"
393 */
394 bool callLocalUser_ = true;
395 if (callLocalUser_)
396 hiddenEvents.hidden_event_types->push_back(EventType::CallSelectAnswer);
397
398 if (auto temp = getAccountData(txn, mtx::events::EventType::NhekoHiddenEvents, "")) {
399 auto h = std::get<
400 mtx::events::AccountDataEvent<mtx::events::account_data::nheko_extensions::HiddenEvents>>(
401 *temp);
402 if (h.content.hidden_event_types)
403 hiddenEvents = std::move(h.content);
404 }
405 if (auto temp = getAccountData(txn, mtx::events::EventType::NhekoHiddenEvents, room_id)) {
406 auto h = std::get<
407 mtx::events::AccountDataEvent<mtx::events::account_data::nheko_extensions::HiddenEvents>>(
408 *temp);
409 if (h.content.hidden_event_types)
410 hiddenEvents = std::move(h.content);
411 }
412
413 return std::find(hiddenEvents.hidden_event_types->begin(),
414 hiddenEvents.hidden_event_types->end(),
415 std::visit([](const auto &ev) { return ev.type; }, e)) !=
416 hiddenEvents.hidden_event_types->end();
417 }
418
419 Cache::Cache(const QString &userId, QObject *parent)
420 : QObject{parent}
421 , localUserId_{userId}
422 , db(std::make_unique<CacheDb>())
423 {
424 connect(this, &Cache::userKeysUpdate, this, &Cache::updateUserKeys, Qt::QueuedConnection);
425 connect(
426 this,
427 &Cache::verificationStatusChanged,
428 this,
429 [this](const std::string &u) {
430 if (u == localUserId_.toStdString()) {
431 auto status = verificationStatus(u);
432 emit selfVerificationStatusChanged();
433 }
434 },
435 Qt::QueuedConnection);
436 setup();
437 }
438
439 static QString
440 cacheDirectoryName(const QString &userid, const QString &profile)
441 {
442 QCryptographicHash hash(QCryptographicHash::Algorithm::Sha256);
443 hash.addData(userid.toUtf8());
444 hash.addData(profile.toUtf8());
445 return QStringLiteral("%1/db-%2")
446 .arg(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation),
447 hash.result().toHex());
448 }
449
450 void
451 Cache::setup()
452 {
453 auto settings = UserSettings::instance();
454
455 nhlog::db()->debug("setting up cache");
456
457 // Previous location of the cache directory
458 auto oldCache2 =
459 QStringLiteral("%1/%2%3").arg(QStandardPaths::writableLocation(QStandardPaths::CacheLocation),
460 QString::fromUtf8(localUserId_.toUtf8().toHex()),
461 QString::fromUtf8(settings->profile().toUtf8().toHex()));
462
463 auto oldCache = QStringLiteral("%1/%2%3").arg(
464 QStandardPaths::writableLocation(QStandardPaths::AppDataLocation),
465 QString::fromUtf8(localUserId_.toUtf8().toHex()),
466 QString::fromUtf8(settings->profile().toUtf8().toHex()));
467
468 cacheDirectory_ = cacheDirectoryName(localUserId_, settings->profile());
469
470 nhlog::db()->debug("Database at: {}", cacheDirectory_.toStdString());
471
472 bool isInitial = !QFile::exists(cacheDirectory_);
473
474 // NOTE: If both cache directories exist it's better to do nothing: it
475 // could mean a previous migration failed or was interrupted.
476 if (isInitial) {
477 if (QFile::exists(oldCache)) {
478 nhlog::db()->info("found old state directory, migrating");
479 if (!QDir().rename(oldCache, cacheDirectory_)) {
480 throw std::runtime_error(("Unable to migrate the old state directory (" + oldCache +
481 ") to the new location (" + cacheDirectory_ + ")")
482 .toStdString()
483 .c_str());
484 }
485 nhlog::db()->info("completed state migration");
486 } else if (QFile::exists(oldCache2)) {
487 nhlog::db()->info("found very old state directory, migrating");
488 if (!QDir().rename(oldCache2, cacheDirectory_)) {
489 throw std::runtime_error(("Unable to migrate the very old state directory (" +
490 oldCache2 + ") to the new location (" + cacheDirectory_ +
491 ")")
492 .toStdString()
493 .c_str());
494 }
495 nhlog::db()->info("completed state migration");
496 }
497 }
498
499 auto openEnv = [](const QString &name) {
500 auto settings = UserSettings::instance();
501 std::size_t dbSize = std::max(
502 settings->qsettings()->value(MAX_DB_SIZE_SETTINGS_KEY, DB_SIZE_DEFAULT).toULongLong(),
503 DB_SIZE_DEFAULT);
504 unsigned dbCount =
505 std::max(settings->qsettings()->value(MAX_DBS_SETTINGS_KEY, MAX_DBS_DEFAULT).toUInt(),
506 MAX_DBS_DEFAULT);
507
508 // ignore unreasonably high values of more than a quarter of the addressable memory
509 if (dbSize > (1ull << (Q_PROCESSOR_WORDSIZE * 8 - 2))) {
510 dbSize = DB_SIZE_DEFAULT;
511 }
512 // Limit databases to about a million. This would cause more than 7-120MB to get written on
513 // every commit, which I doubt would work well. File an issue, if you tested this and it
514 // works fine.
515 if (dbCount > (1u << 20)) {
516 dbCount = 1u << 20;
517 }
518
519 auto e = lmdb::env::create();
520 e.set_mapsize(dbSize);
521 e.set_max_dbs(dbCount);
522 e.open(name.toStdString().c_str(), MDB_NOMETASYNC | MDB_NOSYNC);
523 return e;
524 };
525
526 if (isInitial) {
527 nhlog::db()->info("initializing LMDB");
528
529 if (!QDir().mkpath(cacheDirectory_)) {
530 throw std::runtime_error(
531 ("Unable to create state directory:" + cacheDirectory_).toStdString().c_str());
532 }
533 }
534
535 try {
536 // NOTE(Nico): We may want to use (MDB_MAPASYNC | MDB_WRITEMAP) in the future, but
537 // it can really mess up our database, so we shouldn't. For now, hopefully
538 // NOMETASYNC is fast enough.
539 //
540 // 2022-10-28: Disable the nosync flags again in the hope to crack down on some database
541 // corruption.
542 // 2023-02-23: Reenable the nosync flags. There was no measureable benefit to resiliency,
543 // but sync causes frequent lag sometimes even for the whole system. Possibly the data
544 // corruption is an lmdb or filesystem bug. See
545 // https://github.com/Nheko-Reborn/nheko/issues/1355
546 // https://github.com/Nheko-Reborn/nheko/issues/1303
547 db->env_ = openEnv(cacheDirectory_);
548
549 if (needsCompact) {
550 auto compactDir = cacheDirectory_ + "-compacting";
551 auto toDeleteDir = cacheDirectory_ + "-olddb";
552 if (QFile::exists(cacheDirectory_))
553 QDir(compactDir).removeRecursively();
554 if (QFile::exists(toDeleteDir))
555 QDir(toDeleteDir).removeRecursively();
556 if (!QDir().mkpath(compactDir)) {
557 nhlog::db()->warn(
558 "Failed to create directory '{}' for database compaction, skipping compaction!",
559 compactDir.toStdString());
560 } else {
561 // lmdb::env_copy(db->env_, compactDir.toStdString().c_str(), MDB_CP_COMPACT);
562
563 // create a temporary db
564 auto temp = openEnv(compactDir);
565
566 // copy data
567 compactDatabase(db->env_, temp);
568
569 // close envs
570 temp.close();
571 db->env_.close();
572
573 // swap the databases and delete old one
574 QDir().rename(cacheDirectory_, toDeleteDir);
575 QDir().rename(compactDir, cacheDirectory_);
576 QDir(toDeleteDir).removeRecursively();
577
578 // reopen env
579 db->env_ = openEnv(cacheDirectory_);
580 }
581 }
582 } catch (const lmdb::error &e) {
583 if (e.code() != MDB_VERSION_MISMATCH && e.code() != MDB_INVALID) {
584 throw std::runtime_error("LMDB initialization failed" + std::string(e.what()));
585 }
586
587 nhlog::db()->warn("resetting cache due to LMDB version mismatch: {}", e.what());
588
589 QDir stateDir(cacheDirectory_);
590
591 auto eList = stateDir.entryList(QDir::NoDotAndDotDot);
592 for (const auto &file : std::as_const(eList)) {
593 if (!stateDir.remove(file))
594 throw std::runtime_error(("Unable to delete file " + file).toStdString().c_str());
595 }
596 db->env_ = openEnv(cacheDirectory_);
597 }
598
599 auto txn = lmdb::txn::begin(db->env_);
600 db->syncState = lmdb::dbi::open(txn, SYNC_STATE_DB, MDB_CREATE);
601 db->rooms = lmdb::dbi::open(txn, ROOMS_DB, MDB_CREATE);
602 db->spacesChildren = lmdb::dbi::open(txn, SPACES_CHILDREN_DB, MDB_CREATE | MDB_DUPSORT);
603 db->spacesParents = lmdb::dbi::open(txn, SPACES_PARENTS_DB, MDB_CREATE | MDB_DUPSORT);
604 db->invites = lmdb::dbi::open(txn, INVITES_DB, MDB_CREATE);
605 db->readReceipts = lmdb::dbi::open(txn, READ_RECEIPTS_DB, MDB_CREATE);
606 db->notifications = lmdb::dbi::open(txn, NOTIFICATIONS_DB, MDB_CREATE);
607 db->presence = lmdb::dbi::open(txn, PRESENCE_DB, MDB_CREATE);
608
609 // Session management
610 db->inboundMegolmSessions = lmdb::dbi::open(txn, INBOUND_MEGOLM_SESSIONS_DB, MDB_CREATE);
611 db->outboundMegolmSessions = lmdb::dbi::open(txn, OUTBOUND_MEGOLM_SESSIONS_DB, MDB_CREATE);
612 db->megolmSessionsData = lmdb::dbi::open(txn, MEGOLM_SESSIONS_DATA_DB, MDB_CREATE);
613
614 db->olmSessions = lmdb::dbi::open(txn, OLM_SESSIONS_DB, MDB_CREATE);
615
616 // What rooms are encrypted
617 db->encryptedRooms_ = lmdb::dbi::open(txn, ENCRYPTED_ROOMS_DB, MDB_CREATE);
618 db->eventExpiryBgJob_ = lmdb::dbi::open(txn, EVENT_EXPIRATION_BG_JOB_DB, MDB_CREATE);
619
620 [[maybe_unused]] auto verificationDb = getVerificationDb(txn);
621 [[maybe_unused]] auto userKeysDb = getUserKeysDb(txn);
622
623 txn.commit();
624
625 loadSecretsFromStore(
626 {
627 {"pickle_secret", true},
628 },
629 [this](const std::string &, bool, const std::string &value) { this->pickle_secret_ = value; },
630 true);
631 }
632
633 static void
634 fatalSecretError()
635 {
636 QMessageBox::critical(
637 nullptr,
638 QCoreApplication::translate("SecretStorage", "Failed to connect to secret storage"),
639 QCoreApplication::translate(
640 "SecretStorage",
641 "Nheko could not connect to the secure storage to save encryption secrets to. This can "
642 "have multiple reasons. Check if your D-Bus service is running and you have configured a "
643 "service like KWallet, Gnome Keyring, KeePassXC or the equivalent for your platform. If "
644 "you are having trouble, feel free to open an issue here: "
645 "https://github.com/Nheko-Reborn/nheko/issues"),
646 QMessageBox::StandardButton::Close);
647
648 QCoreApplication::exit(1);
649 exit(1);
650 }
651
652 static QString
653 secretName(std::string_view name, bool internal)
654 {
655 auto settings = UserSettings::instance();
656 return (internal ? "nheko." : "matrix.") +
657 QString(
658 QCryptographicHash::hash(settings->profile().toUtf8(), QCryptographicHash::Sha256)
659 .toBase64()) +
660 "." + QString::fromUtf8(name);
661 }
662
663 void
664 Cache::loadSecretsFromStore(
665 std::vector<std::pair<std::string, bool>> toLoad,
666 std::function<void(const std::string &name, bool internal, const std::string &value)> callback,
667 bool databaseReadyOnFinished)
668 {
669 auto settings = UserSettings::instance()->qsettings();
670
671 if (toLoad.empty()) {
672 this->databaseReady_ = true;
673
674 // HACK(Nico): Some migrations would loop infinitely otherwise.
675 // So we set the database to be ready, but not emit the signal, because that would start the
676 // migrations again. :D
677 if (databaseReadyOnFinished) {
678 emit databaseReady();
679 nhlog::db()->debug("Database ready");
680 }
681 return;
682 }
683
684 if (settings->value(QStringLiteral("run_without_secure_secrets_service"), false).toBool()) {
685 for (auto &[name_, internal] : toLoad) {
686 auto name = secretName(name_, internal);
687 auto value = settings->value("secrets/" + name).toString();
688 if (value.isEmpty()) {
689 nhlog::db()->info("Restored empty secret '{}'.", name.toStdString());
690 } else {
691 callback(name_, internal, value.toStdString());
692 }
693 }
694 // if we emit the DatabaseReady signal directly it won't be received
695 QTimer::singleShot(0, this, [this, callback, databaseReadyOnFinished] {
696 loadSecretsFromStore({}, callback, databaseReadyOnFinished);
697 });
698 return;
699 }
700
701 auto [name_, internal] = toLoad.front();
702
703 auto job = new QKeychain::ReadPasswordJob(QCoreApplication::applicationName());
704 job->setAutoDelete(true);
705 job->setInsecureFallback(true);
706 job->setSettings(settings);
707 auto name = secretName(name_, internal);
708 job->setKey(name);
709
710 connect(job,
711 &QKeychain::ReadPasswordJob::finished,
712 this,
713 [this,
714 name,
715 toLoad,
716 job,
717 name__ = name_,
718 internal_ = internal,
719 callback,
720 databaseReadyOnFinished](QKeychain::Job *) mutable {
721 nhlog::db()->debug("Finished reading '{}'", toLoad.begin()->first);
722 const QString secret = job->textData();
723 if (job->error() && job->error() != QKeychain::Error::EntryNotFound) {
724 nhlog::db()->error("Restoring secret '{}' failed ({}): {}",
725 name.toStdString(),
726 static_cast<int>(job->error()),
727 job->errorString().toStdString());
728
729 fatalSecretError();
730 }
731 if (secret.isEmpty()) {
732 nhlog::db()->debug("Restored empty secret '{}'.", name.toStdString());
733 } else {
734 callback(name__, internal_, secret.toStdString());
735 }
736
737 // load next secret
738 toLoad.erase(toLoad.begin());
739
740 // You can't start a job from the finish signal of a job.
741 QTimer::singleShot(0, this, [this, toLoad, callback, databaseReadyOnFinished] {
742 loadSecretsFromStore(toLoad, callback, databaseReadyOnFinished);
743 });
744 });
745 nhlog::db()->debug("Reading '{}'", name_);
746 job->start();
747 }
748
749 std::optional<std::string>
750 Cache::secret(std::string_view name_, bool internal)
751 {
752 auto name = secretName(name_, internal);
753
754 auto txn = ro_txn(db->env_);
755 std::string_view value;
756 auto db_name = "secret." + name.toStdString();
757 if (!db->syncState.get(txn, db_name, value))
758 return std::nullopt;
759
760 mtx::secret_storage::AesHmacSha2EncryptedData data = nlohmann::json::parse(value);
761
762 auto decrypted = mtx::crypto::decrypt(data, mtx::crypto::to_binary_buf(pickle_secret_), name_);
763 if (decrypted.empty())
764 return std::nullopt;
765 else
766 return decrypted;
767 }
768
769 void
770 Cache::storeSecret(std::string_view name_, const std::string &secret, bool internal)
771 {
772 auto name = secretName(name_, internal);
773
774 auto txn = lmdb::txn::begin(db->env_);
775
776 auto encrypted =
777 mtx::crypto::encrypt(secret, mtx::crypto::to_binary_buf(pickle_secret_), name_);
778
779 auto db_name = "secret." + name.toStdString();
780 db->syncState.put(txn, db_name, nlohmann::json(encrypted).dump());
781 txn.commit();
782 emit secretChanged(std::string(name_));
783 }
784
785 void
786 Cache::deleteSecret(std::string_view name_, bool internal)
787 {
788 auto name = secretName(name_, internal);
789
790 auto txn = lmdb::txn::begin(db->env_);
791 std::string_view value;
792 auto db_name = "secret." + name.toStdString();
793 db->syncState.del(txn, db_name, value);
794 txn.commit();
795 }
796
797 void
798 Cache::storeSecretInStore(const std::string name_, const std::string secret)
799 {
800 auto name = secretName(name_, true);
801
802 auto settings = UserSettings::instance()->qsettings();
803 if (settings->value(QStringLiteral("run_without_secure_secrets_service"), false).toBool()) {
804 settings->setValue("secrets/" + name, QString::fromStdString(secret));
805 // if we emit the signal directly it won't be received
806 QTimer::singleShot(0, this, [this, name_] { emit secretChanged(name_); });
807 nhlog::db()->info("Storing secret '{}' successful", name_);
808 return;
809 }
810
811 auto job = new QKeychain::WritePasswordJob(QCoreApplication::applicationName());
812 job->setAutoDelete(true);
813 job->setInsecureFallback(true);
814 job->setSettings(settings);
815
816 job->setKey(name);
817
818 job->setTextData(QString::fromStdString(secret));
819
820 QObject::connect(
821 job,
822 &QKeychain::WritePasswordJob::finished,
823 this,
824 [name_, this](QKeychain::Job *job) {
825 if (job->error()) {
826 nhlog::db()->warn(
827 "Storing secret '{}' failed: {}", name_, job->errorString().toStdString());
828 fatalSecretError();
829 } else {
830 // if we emit the signal directly, qtkeychain breaks and won't execute new
831 // jobs. You can't start a job from the finish signal of a job.
832 QTimer::singleShot(0, this, [this, name_] { emit secretChanged(name_); });
833 nhlog::db()->info("Storing secret '{}' successful", name_);
834 }
835 },
836 Qt::ConnectionType::DirectConnection);
837 job->start();
838 }
839
840 void
841 Cache::deleteSecretFromStore(const std::string name, bool internal)
842 {
843 auto name_ = secretName(name, internal);
844
845 auto settings = UserSettings::instance()->qsettings();
846 if (settings->value(QStringLiteral("run_without_secure_secrets_service"), false).toBool()) {
847 settings->remove("secrets/" + name_);
848 // if we emit the signal directly it won't be received
849 QTimer::singleShot(0, this, [this, name] { emit secretChanged(name); });
850 return;
851 }
852
853 auto job = new QKeychain::DeletePasswordJob(QCoreApplication::applicationName());
854 job->setAutoDelete(true);
855 job->setInsecureFallback(true);
856 job->setSettings(settings);
857
858 job->setKey(name_);
859
860 job->connect(
861 job, &QKeychain::Job::finished, this, [this, name]() { emit secretChanged(name); });
862 job->start();
863 }
864
865 std::string
866 Cache::pickleSecret()
867 {
868 if (pickle_secret_.empty()) {
869 this->pickle_secret_ = mtx::client::utils::random_token(64, true);
870 storeSecretInStore("pickle_secret", pickle_secret_);
871 }
872
873 return pickle_secret_;
874 }
875
876 void
877 Cache::storeEventExpirationProgress(const std::string &room,
878 const std::string &expirationSettings,
879 const std::string &stopMarker)
880 {
881 nlohmann::json j;
882 j["s"] = expirationSettings;
883 j["m"] = stopMarker;
884
885 auto txn = lmdb::txn::begin(db->env_);
886 db->eventExpiryBgJob_.put(txn, room, j.dump());
887 txn.commit();
888 }
889
890 std::string
891 Cache::loadEventExpirationProgress(const std::string &room, const std::string &expirationSettings)
892
893 {
894 try {
895 auto txn = ro_txn(db->env_);
896 std::string_view data;
897 if (!db->eventExpiryBgJob_.get(txn, room, data))
898 return "";
899
900 auto j = nlohmann::json::parse(data);
901 if (j.value("s", "") == expirationSettings)
902 return j.value("m", "");
903 } catch (...) {
904 return "";
905 }
906 return "";
907 }
908
909 void
910 Cache::setEncryptedRoom(lmdb::txn &txn, const std::string &room_id)
911 {
912 nhlog::db()->info("mark room {} as encrypted", room_id);
913
914 db->encryptedRooms_.put(txn, room_id, "0");
915 }
916
917 bool
918 Cache::isRoomEncrypted(const std::string &room_id)
919 {
920 std::string_view unused;
921
922 auto txn = ro_txn(db->env_);
923 auto res = db->encryptedRooms_.get(txn, room_id, unused);
924
925 return res;
926 }
927
928 std::optional<mtx::events::state::Encryption>
929 Cache::roomEncryptionSettings(const std::string &room_id)
930 {
931 using namespace mtx::events;
932 using namespace mtx::events::state;
933
934 try {
935 auto txn = ro_txn(db->env_);
936 auto statesdb = getStatesDb(txn, room_id);
937 std::string_view event;
938 bool res = statesdb.get(txn, to_string(mtx::events::EventType::RoomEncryption), event);
939
940 if (res) {
941 try {
942 StateEvent<Encryption> msg =
943 nlohmann::json::parse(event).get<StateEvent<Encryption>>();
944
945 return msg.content;
946 } catch (const nlohmann::json::exception &e) {
947 nhlog::db()->warn("failed to parse m.room.encryption event: {}", e.what());
948 return Encryption{};
949 }
950 }
951 } catch (lmdb::error &) {
952 }
953
954 return std::nullopt;
955 }
956
957 mtx::crypto::ExportedSessionKeys
958 Cache::exportSessionKeys()
959 {
960 using namespace mtx::crypto;
961
962 ExportedSessionKeys keys;
963
964 auto txn = ro_txn(db->env_);
965 auto cursor = lmdb::cursor::open(txn, db->inboundMegolmSessions);
966
967 std::string_view key, value;
968 while (cursor.get(key, value, MDB_NEXT)) {
969 ExportedSession exported;
970 MegolmSessionIndex index;
971
972 auto saved_session = unpickle<InboundSessionObject>(std::string(value), pickle_secret_);
973
974 try {
975 index = nlohmann::json::parse(key).get<MegolmSessionIndex>();
976 } catch (const nlohmann::json::exception &e) {
977 nhlog::db()->critical("failed to export megolm session: {}", e.what());
978 continue;
979 }
980
981 try {
982 using namespace mtx::crypto;
983
984 std::string_view v;
985 if (db->megolmSessionsData.get(txn, nlohmann::json(index).dump(), v)) {
986 auto data = nlohmann::json::parse(v).get<GroupSessionData>();
987 exported.sender_key = data.sender_key;
988 if (!data.sender_claimed_ed25519_key.empty())
989 exported.sender_claimed_keys["ed25519"] = data.sender_claimed_ed25519_key;
990 exported.forwarding_curve25519_key_chain = data.forwarding_curve25519_key_chain;
991 } else {
992 continue;
993 }
994
995 } catch (std::exception &e) {
996 nhlog::db()->error("Failed to retrieve Megolm Session Data: {}", e.what());
997 continue;
998 }
999
1000 exported.room_id = index.room_id;
1001 exported.session_id = index.session_id;
1002 exported.session_key = export_session(saved_session.get(), -1);
1003
1004 keys.sessions.push_back(exported);
1005 }
1006
1007 cursor.close();
1008
1009 return keys;
1010 }
1011
1012 void
1013 Cache::importSessionKeys(const mtx::crypto::ExportedSessionKeys &keys)
1014 {
1015 std::size_t importCount = 0;
1016
1017 auto txn = lmdb::txn::begin(db->env_);
1018 for (const auto &s : keys.sessions) {
1019 MegolmSessionIndex index;
1020 index.room_id = s.room_id;
1021 index.session_id = s.session_id;
1022
1023 GroupSessionData data{};
1024 data.sender_key = s.sender_key;
1025 data.forwarding_curve25519_key_chain = s.forwarding_curve25519_key_chain;
1026 data.trusted = false;
1027
1028 if (s.sender_claimed_keys.count("ed25519"))
1029 data.sender_claimed_ed25519_key = s.sender_claimed_keys.at("ed25519");
1030
1031 try {
1032 auto exported_session = mtx::crypto::import_session(s.session_key);
1033
1034 using namespace mtx::crypto;
1035 const auto key = nlohmann::json(index).dump();
1036 const auto pickled =
1037 pickle<InboundSessionObject>(exported_session.get(), pickle_secret_);
1038
1039 std::string_view value;
1040 if (db->inboundMegolmSessions.get(txn, key, value)) {
1041 auto oldSession =
1042 unpickle<InboundSessionObject>(std::string(value), pickle_secret_);
1043 if (olm_inbound_group_session_first_known_index(exported_session.get()) >=
1044 olm_inbound_group_session_first_known_index(oldSession.get())) {
1045 nhlog::crypto()->warn(
1046 "Not storing inbound session with newer or equal first known index");
1047 continue;
1048 }
1049 }
1050
1051 db->inboundMegolmSessions.put(txn, key, pickled);
1052 db->megolmSessionsData.put(txn, key, nlohmann::json(data).dump());
1053
1054 ChatPage::instance()->receivedSessionKey(index.room_id, index.session_id);
1055 importCount++;
1056 } catch (const mtx::crypto::olm_exception &e) {
1057 nhlog::crypto()->critical(
1058 "failed to import inbound megolm session {}: {}", index.session_id, e.what());
1059 continue;
1060 } catch (const lmdb::error &e) {
1061 nhlog::crypto()->critical(
1062 "failed to save inbound megolm session {}: {}", index.session_id, e.what());
1063 continue;
1064 }
1065 }
1066 txn.commit();
1067
1068 nhlog::crypto()->info("Imported {} out of {} keys", importCount, keys.sessions.size());
1069 }
1070
1071 //
1072 // Session Management
1073 //
1074
1075 void
1076 Cache::saveInboundMegolmSession(const MegolmSessionIndex &index,
1077 mtx::crypto::InboundGroupSessionPtr session,
1078 const GroupSessionData &data)
1079 {
1080 using namespace mtx::crypto;
1081 const auto key = nlohmann::json(index).dump();
1082 const auto pickled = pickle<InboundSessionObject>(session.get(), pickle_secret_);
1083
1084 auto txn = lmdb::txn::begin(db->env_);
1085
1086 std::string_view value;
1087 if (db->inboundMegolmSessions.get(txn, key, value)) {
1088 auto oldSession = unpickle<InboundSessionObject>(std::string(value), pickle_secret_);
1089
1090 auto newIndex = olm_inbound_group_session_first_known_index(session.get());
1091 auto oldIndex = olm_inbound_group_session_first_known_index(oldSession.get());
1092
1093 // merge trusted > untrusted
1094 // first known index minimum
1095 if (db->megolmSessionsData.get(txn, key, value)) {
1096 auto oldData = nlohmann::json::parse(value).get<GroupSessionData>();
1097 if (oldData.trusted && newIndex >= oldIndex) {
1098 nhlog::crypto()->warn(
1099 "Not storing inbound session of lesser trust or bigger index.");
1100 return;
1101 }
1102
1103 oldData.trusted = data.trusted || oldData.trusted;
1104
1105 if (newIndex < oldIndex) {
1106 db->inboundMegolmSessions.put(txn, key, pickled);
1107 oldData.message_index = newIndex;
1108 }
1109
1110 db->megolmSessionsData.put(txn, key, nlohmann::json(oldData).dump());
1111 txn.commit();
1112 return;
1113 }
1114 }
1115
1116 db->inboundMegolmSessions.put(txn, key, pickled);
1117 db->megolmSessionsData.put(txn, key, nlohmann::json(data).dump());
1118 txn.commit();
1119 }
1120
1121 mtx::crypto::InboundGroupSessionPtr
1122 Cache::getInboundMegolmSession(const MegolmSessionIndex &index)
1123 {
1124 using namespace mtx::crypto;
1125
1126 try {
1127 auto txn = ro_txn(db->env_);
1128 std::string key = nlohmann::json(index).dump();
1129 std::string_view value;
1130
1131 if (db->inboundMegolmSessions.get(txn, key, value)) {
1132 auto session = unpickle<InboundSessionObject>(std::string(value), pickle_secret_);
1133 return session;
1134 }
1135 } catch (std::exception &e) {
1136 nhlog::db()->error("Failed to get inbound megolm session {}", e.what());
1137 }
1138
1139 return nullptr;
1140 }
1141
1142 bool
1143 Cache::inboundMegolmSessionExists(const MegolmSessionIndex &index)
1144 {
1145 using namespace mtx::crypto;
1146
1147 try {
1148 auto txn = ro_txn(db->env_);
1149 std::string key = nlohmann::json(index).dump();
1150 std::string_view value;
1151
1152 return db->inboundMegolmSessions.get(txn, key, value);
1153 } catch (std::exception &e) {
1154 nhlog::db()->error("Failed to get inbound megolm session {}", e.what());
1155 }
1156
1157 return false;
1158 }
1159
1160 void
1161 Cache::updateOutboundMegolmSession(const std::string &room_id,
1162 const GroupSessionData &data_,
1163 mtx::crypto::OutboundGroupSessionPtr &ptr)
1164 {
1165 using namespace mtx::crypto;
1166
1167 if (!outboundMegolmSessionExists(room_id))
1168 return;
1169
1170 GroupSessionData data = data_;
1171 data.message_index = olm_outbound_group_session_message_index(ptr.get());
1172 MegolmSessionIndex index;
1173 index.room_id = room_id;
1174 index.session_id = mtx::crypto::session_id(ptr.get());
1175
1176 // Save the updated pickled data for the session.
1177 nlohmann::json j;
1178 j["session"] = pickle<OutboundSessionObject>(ptr.get(), pickle_secret_);
1179
1180 auto txn = lmdb::txn::begin(db->env_);
1181 db->outboundMegolmSessions.put(txn, room_id, j.dump());
1182 db->megolmSessionsData.put(txn, nlohmann::json(index).dump(), nlohmann::json(data).dump());
1183 txn.commit();
1184 }
1185
1186 void
1187 Cache::dropOutboundMegolmSession(const std::string &room_id)
1188 {
1189 using namespace mtx::crypto;
1190
1191 if (!outboundMegolmSessionExists(room_id))
1192 return;
1193
1194 {
1195 auto txn = lmdb::txn::begin(db->env_);
1196 db->outboundMegolmSessions.del(txn, room_id);
1197 // don't delete session data, so that we can still share the session.
1198 txn.commit();
1199 }
1200 }
1201
1202 void
1203 Cache::saveOutboundMegolmSession(const std::string &room_id,
1204 const GroupSessionData &data_,
1205 mtx::crypto::OutboundGroupSessionPtr &session)
1206 {
1207 using namespace mtx::crypto;
1208 const auto pickled = pickle<OutboundSessionObject>(session.get(), pickle_secret_);
1209
1210 GroupSessionData data = data_;
1211 data.message_index = olm_outbound_group_session_message_index(session.get());
1212 MegolmSessionIndex index;
1213 index.room_id = room_id;
1214 index.session_id = mtx::crypto::session_id(session.get());
1215
1216 nlohmann::json j;
1217 j["session"] = pickled;
1218
1219 auto txn = lmdb::txn::begin(db->env_);
1220 db->outboundMegolmSessions.put(txn, room_id, j.dump());
1221 db->megolmSessionsData.put(txn, nlohmann::json(index).dump(), nlohmann::json(data).dump());
1222 txn.commit();
1223 }
1224
1225 bool
1226 Cache::outboundMegolmSessionExists(const std::string &room_id) noexcept
1227 {
1228 try {
1229 auto txn = ro_txn(db->env_);
1230 std::string_view value;
1231 return db->outboundMegolmSessions.get(txn, room_id, value);
1232 } catch (std::exception &e) {
1233 nhlog::db()->error("Failed to retrieve outbound Megolm Session: {}", e.what());
1234 return false;
1235 }
1236 }
1237
1238 OutboundGroupSessionDataRef
1239 Cache::getOutboundMegolmSession(const std::string &room_id)
1240 {
1241 try {
1242 using namespace mtx::crypto;
1243
1244 auto txn = ro_txn(db->env_);
1245 std::string_view value;
1246 db->outboundMegolmSessions.get(txn, room_id, value);
1247 auto obj = nlohmann::json::parse(value);
1248
1249 OutboundGroupSessionDataRef ref{};
1250 ref.session =
1251 unpickle<OutboundSessionObject>(obj.at("session").get<std::string>(), pickle_secret_);
1252
1253 MegolmSessionIndex index;
1254 index.room_id = room_id;
1255 index.session_id = mtx::crypto::session_id(ref.session.get());
1256
1257 if (db->megolmSessionsData.get(txn, nlohmann::json(index).dump(), value)) {
1258 ref.data = nlohmann::json::parse(value).get<GroupSessionData>();
1259 }
1260
1261 return ref;
1262 } catch (std::exception &e) {
1263 nhlog::db()->error("Failed to retrieve outbound Megolm Session: {}", e.what());
1264 return {};
1265 }
1266 }
1267
1268 std::optional<GroupSessionData>
1269 Cache::getMegolmSessionData(const MegolmSessionIndex &index)
1270 {
1271 try {
1272 using namespace mtx::crypto;
1273
1274 auto txn = ro_txn(db->env_);
1275
1276 std::string_view value;
1277 if (db->megolmSessionsData.get(txn, nlohmann::json(index).dump(), value)) {
1278 return nlohmann::json::parse(value).get<GroupSessionData>();
1279 }
1280
1281 return std::nullopt;
1282 } catch (std::exception &e) {
1283 nhlog::db()->error("Failed to retrieve Megolm Session Data: {}", e.what());
1284 return std::nullopt;
1285 }
1286 }
1287 //
1288 // OLM sessions.
1289 //
1290
1291 void
1292 Cache::saveOlmSessions(std::vector<std::pair<std::string, mtx::crypto::OlmSessionPtr>> sessions,
1293 uint64_t timestamp)
1294 {
1295 using namespace mtx::crypto;
1296
1297 auto txn = lmdb::txn::begin(db->env_);
1298 for (const auto &[curve25519, session] : sessions) {
1299 const auto pickled = pickle<SessionObject>(session.get(), pickle_secret_);
1300 const auto session_id = mtx::crypto::session_id(session.get());
1301
1302 StoredOlmSession stored_session;
1303 stored_session.pickled_session = pickled;
1304 stored_session.last_message_ts = timestamp;
1305
1306 db->olmSessions.put(txn,
1307 combineOlmSessionKeyFromCurveAndSessionId(curve25519, session_id),
1308 nlohmann::json(stored_session).dump());
1309 }
1310
1311 txn.commit();
1312 }
1313
1314 void
1315 Cache::saveOlmSession(const std::string &curve25519,
1316 mtx::crypto::OlmSessionPtr session,
1317 uint64_t timestamp)
1318 {
1319 using namespace mtx::crypto;
1320
1321 auto txn = lmdb::txn::begin(db->env_);
1322
1323 const auto pickled = pickle<SessionObject>(session.get(), pickle_secret_);
1324 const auto session_id = mtx::crypto::session_id(session.get());
1325
1326 StoredOlmSession stored_session;
1327 stored_session.pickled_session = pickled;
1328 stored_session.last_message_ts = timestamp;
1329
1330 db->olmSessions.put(txn,
1331 combineOlmSessionKeyFromCurveAndSessionId(curve25519, session_id),
1332 nlohmann::json(stored_session).dump());
1333
1334 txn.commit();
1335 }
1336
1337 std::optional<mtx::crypto::OlmSessionPtr>
1338 Cache::getOlmSession(const std::string &curve25519, const std::string &session_id)
1339 {
1340 using namespace mtx::crypto;
1341
1342 try {
1343 auto txn = ro_txn(db->env_);
1344
1345 std::string_view pickled;
1346 bool found = db->olmSessions.get(
1347 txn, combineOlmSessionKeyFromCurveAndSessionId(curve25519, session_id), pickled);
1348
1349 if (found) {
1350 auto data = nlohmann::json::parse(pickled).get<StoredOlmSession>();
1351 return unpickle<SessionObject>(data.pickled_session, pickle_secret_);
1352 }
1353
1354 } catch (...) {
1355 }
1356 return std::nullopt;
1357 }
1358
1359 std::optional<mtx::crypto::OlmSessionPtr>
1360 Cache::getLatestOlmSession(const std::string &curve25519)
1361 {
1362 using namespace mtx::crypto;
1363
1364 try {
1365 auto txn = ro_txn(db->env_);
1366
1367 std::string_view key = curve25519, pickled_session;
1368
1369 std::optional<StoredOlmSession> currentNewest;
1370
1371 auto cursor = lmdb::cursor::open(txn, db->olmSessions);
1372 bool first = true;
1373 while (cursor.get(key, pickled_session, first ? MDB_SET_RANGE : MDB_NEXT)) {
1374 first = false;
1375
1376 auto storedCurve = splitCurve25519AndOlmSessionId(key).first;
1377 if (storedCurve != curve25519)
1378 break;
1379
1380 auto data = nlohmann::json::parse(pickled_session).get<StoredOlmSession>();
1381 if (!currentNewest || currentNewest->last_message_ts < data.last_message_ts)
1382 currentNewest = data;
1383 }
1384 cursor.close();
1385
1386 return currentNewest ? std::optional(unpickle<SessionObject>(currentNewest->pickled_session,
1387 pickle_secret_))
1388 : std::nullopt;
1389 } catch (...) {
1390 return std::nullopt;
1391 }
1392 }
1393
1394 std::vector<std::string>
1395 Cache::getOlmSessions(const std::string &curve25519)
1396 {
1397 using namespace mtx::crypto;
1398
1399 try {
1400 auto txn = ro_txn(db->env_);
1401
1402 std::string_view key = curve25519, value;
1403 std::vector<std::string> res;
1404
1405 auto cursor = lmdb::cursor::open(txn, db->olmSessions);
1406
1407 bool first = true;
1408 while (cursor.get(key, value, first ? MDB_SET_RANGE : MDB_NEXT)) {
1409 first = false;
1410
1411 auto [storedCurve, session_id] = splitCurve25519AndOlmSessionId(key);
1412 if (storedCurve != curve25519)
1413 break;
1414 res.emplace_back(session_id);
1415 }
1416 cursor.close();
1417
1418 return res;
1419 } catch (...) {
1420 return {};
1421 }
1422 }
1423
1424 void
1425 Cache::saveOlmAccount(const std::string &data)
1426 {
1427 auto txn = lmdb::txn::begin(db->env_);
1428 db->syncState.put(txn, OLM_ACCOUNT_KEY, data);
1429 txn.commit();
1430 }
1431
1432 std::string
1433 Cache::restoreOlmAccount()
1434 {
1435 auto txn = ro_txn(db->env_);
1436
1437 std::string_view pickled;
1438 db->syncState.get(txn, OLM_ACCOUNT_KEY, pickled);
1439
1440 return std::string(pickled.data(), pickled.size());
1441 }
1442
1443 void
1444 Cache::saveBackupVersion(const OnlineBackupVersion &data)
1445 {
1446 auto txn = lmdb::txn::begin(db->env_);
1447 db->syncState.put(txn, CURRENT_ONLINE_BACKUP_VERSION, nlohmann::json(data).dump());
1448 txn.commit();
1449 }
1450
1451 void
1452 Cache::deleteBackupVersion()
1453 {
1454 auto txn = lmdb::txn::begin(db->env_);
1455 db->syncState.del(txn, CURRENT_ONLINE_BACKUP_VERSION);
1456 txn.commit();
1457 }
1458
1459 std::optional<OnlineBackupVersion>
1460 Cache::backupVersion()
1461 {
1462 try {
1463 auto txn = ro_txn(db->env_);
1464 std::string_view v;
1465 db->syncState.get(txn, CURRENT_ONLINE_BACKUP_VERSION, v);
1466
1467 return nlohmann::json::parse(v).get<OnlineBackupVersion>();
1468 } catch (...) {
1469 return std::nullopt;
1470 }
1471 }
1472
1473 void
1474 Cache::removeInvite(lmdb::txn &txn, const std::string &room_id)
1475 {
1476 db->invites.del(txn, room_id);
1477 getInviteStatesDb(txn, room_id).drop(txn, true);
1478 getInviteMembersDb(txn, room_id).drop(txn, true);
1479 }
1480
1481 void
1482 Cache::removeInvite(const std::string &room_id)
1483 {
1484 auto txn = lmdb::txn::begin(db->env_);
1485 removeInvite(txn, room_id);
1486 txn.commit();
1487 }
1488
1489 void
1490 Cache::removeRoom(lmdb::txn &txn, const std::string &roomid)
1491 {
1492 db->rooms.del(txn, roomid);
1493 getStatesDb(txn, roomid).drop(txn, true);
1494 getAccountDataDb(txn, roomid).drop(txn, true);
1495 getMembersDb(txn, roomid).drop(txn, true);
1496 }
1497
1498 void
1499 Cache::removeRoom(const std::string &roomid)
1500 {
1501 auto txn = lmdb::txn::begin(db->env_, nullptr, 0);
1502 db->rooms.del(txn, roomid);
1503 txn.commit();
1504 }
1505
1506 void
1507 Cache::setNextBatchToken(lmdb::txn &txn, const std::string &token)
1508 {
1509 db->syncState.put(txn, NEXT_BATCH_KEY, token);
1510 }
1511
1512 bool
1513 Cache::isInitialized()
1514 {
1515 if (!db->env_.handle())
1516 return false;
1517
1518 auto txn = ro_txn(db->env_);
1519 std::string_view token;
1520
1521 bool res = db->syncState.get(txn, NEXT_BATCH_KEY, token);
1522
1523 return res;
1524 }
1525
1526 std::string
1527 Cache::nextBatchToken()
1528 {
1529 if (!db->env_.handle())
1530 throw lmdb::error("Env already closed", MDB_INVALID);
1531
1532 auto txn = ro_txn(db->env_);
1533 std::string_view token;
1534
1535 bool result = db->syncState.get(txn, NEXT_BATCH_KEY, token);
1536
1537 if (result)
1538 return std::string(token.data(), token.size());
1539 else
1540 return "";
1541 }
1542
1543 void
1544 Cache::deleteData()
1545 {
1546 if (this->databaseReady_) {
1547 this->databaseReady_ = false;
1548 // TODO: We need to remove the db->env_ while not accepting new requests.
1549 lmdb::dbi_close(db->env_, db->syncState);
1550 lmdb::dbi_close(db->env_, db->rooms);
1551 lmdb::dbi_close(db->env_, db->invites);
1552 lmdb::dbi_close(db->env_, db->readReceipts);
1553 lmdb::dbi_close(db->env_, db->notifications);
1554
1555 lmdb::dbi_close(db->env_, db->inboundMegolmSessions);
1556 lmdb::dbi_close(db->env_, db->outboundMegolmSessions);
1557 lmdb::dbi_close(db->env_, db->megolmSessionsData);
1558
1559 db->env_.close();
1560
1561 verification_storage.status.clear();
1562
1563 if (!cacheDirectory_.isEmpty()) {
1564 QDir(cacheDirectory_).removeRecursively();
1565 nhlog::db()->info("deleted cache files from disk");
1566 }
1567
1568 deleteSecretFromStore("pickle_secret", true);
1569 }
1570 }
1571
1572 //! migrates db to the current format
1573 bool
1574 Cache::runMigrations()
1575 {
1576 std::string stored_version;
1577 {
1578 auto txn = ro_txn(db->env_);
1579
1580 std::string_view current_version;
1581 bool res = db->syncState.get(txn, CACHE_FORMAT_VERSION_KEY, current_version);
1582
1583 if (!res)
1584 return false;
1585
1586 stored_version = std::string(current_version);
1587 }
1588
1589 std::vector<std::pair<std::string, std::function<bool()>>> migrations{
1590 {"2020.05.01",
1591 [this]() {
1592 try {
1593 auto txn = lmdb::txn::begin(db->env_, nullptr);
1594 auto pending_receipts = lmdb::dbi::open(txn, "pending_receipts", MDB_CREATE);
1595 lmdb::dbi_drop(txn, pending_receipts, true);
1596 txn.commit();
1597 } catch (const lmdb::error &) {
1598 nhlog::db()->critical("Failed to delete pending_receipts database in migration!");
1599 return false;
1600 }
1601
1602 nhlog::db()->info("Successfully deleted pending receipts database.");
1603 return true;
1604 }},
1605 {"2020.07.05",
1606 [this]() {
1607 try {
1608 auto txn = lmdb::txn::begin(db->env_, nullptr);
1609 auto room_ids = getRoomIds(txn);
1610
1611 for (const auto &room_id : room_ids) {
1612 try {
1613 auto messagesDb =
1614 lmdb::dbi::open(txn, std::string(room_id + "/messages").c_str());
1615
1616 // keep some old messages and batch token
1617 {
1618 auto roomsCursor = lmdb::cursor::open(txn, messagesDb);
1619 std::string_view ts, stored_message;
1620 bool start = true;
1621 mtx::responses::Timeline oldMessages;
1622 while (
1623 roomsCursor.get(ts, stored_message, start ? MDB_FIRST : MDB_NEXT)) {
1624 start = false;
1625
1626 auto j = nlohmann::json::parse(
1627 std::string_view(stored_message.data(), stored_message.size()));
1628
1629 if (oldMessages.prev_batch.empty())
1630 oldMessages.prev_batch = j["token"].get<std::string>();
1631 else if (j["token"].get<std::string>() != oldMessages.prev_batch)
1632 break;
1633
1634 oldMessages.events.push_back(
1635 j["event"].get<mtx::events::collections::TimelineEvents>());
1636 }
1637 // messages were stored in reverse order, so we
1638 // need to reverse them
1639 std::reverse(oldMessages.events.begin(), oldMessages.events.end());
1640 // save messages using the new method
1641 auto eventsDb = getEventsDb(txn, room_id);
1642 saveTimelineMessages(txn, eventsDb, room_id, oldMessages);
1643 }
1644
1645 // delete old messages db
1646 lmdb::dbi_drop(txn, messagesDb, true);
1647 } catch (std::exception &e) {
1648 nhlog::db()->error(
1649 "While migrating messages from {}, ignoring error {}", room_id, e.what());
1650 }
1651 }
1652 txn.commit();
1653 } catch (const lmdb::error &) {
1654 nhlog::db()->critical("Failed to delete messages database in migration!");
1655 return false;
1656 }
1657
1658 nhlog::db()->info("Successfully deleted pending receipts database.");
1659 return true;
1660 }},
1661 {"2020.10.20",
1662 [this]() {
1663 try {
1664 using namespace mtx::crypto;
1665
1666 auto txn = lmdb::txn::begin(db->env_);
1667
1668 auto mainDb = lmdb::dbi::open(txn, nullptr);
1669
1670 std::string_view dbName, ignored;
1671 auto olmDbCursor = lmdb::cursor::open(txn, mainDb);
1672 while (olmDbCursor.get(dbName, ignored, MDB_NEXT)) {
1673 // skip every db but olm session dbs
1674 nhlog::db()->debug("Db {}", dbName);
1675 if (dbName.find("olm_sessions/") != 0)
1676 continue;
1677
1678 nhlog::db()->debug("Migrating {}", dbName);
1679
1680 auto olmDb = lmdb::dbi::open(txn, std::string(dbName).c_str());
1681
1682 std::string_view session_id, session_value;
1683
1684 std::vector<std::pair<std::string, StoredOlmSession>> sessions;
1685
1686 auto cursor = lmdb::cursor::open(txn, olmDb);
1687 while (cursor.get(session_id, session_value, MDB_NEXT)) {
1688 nhlog::db()->debug(
1689 "session_id {}, session_value {}", session_id, session_value);
1690 StoredOlmSession session;
1691 bool invalid = false;
1692 for (auto c : session_value)
1693 if (!isprint(c)) {
1694 invalid = true;
1695 break;
1696 }
1697 if (invalid)
1698 continue;
1699
1700 nhlog::db()->debug("Not skipped");
1701
1702 session.pickled_session = session_value;
1703 sessions.emplace_back(session_id, session);
1704 }
1705 cursor.close();
1706
1707 olmDb.drop(txn, true);
1708
1709 auto newDbName = std::string(dbName);
1710 newDbName.erase(0, sizeof("olm_sessions") - 1);
1711 newDbName = "olm_sessions.v2" + newDbName;
1712
1713 auto newDb = lmdb::dbi::open(txn, newDbName.c_str(), MDB_CREATE);
1714
1715 for (const auto &[key, value] : sessions) {
1716 // nhlog::db()->debug("{}\n{}", key, nlohmann::json(value).dump());
1717 newDb.put(txn, key, nlohmann::json(value).dump());
1718 }
1719 }
1720 olmDbCursor.close();
1721
1722 txn.commit();
1723 } catch (const lmdb::error &) {
1724 nhlog::db()->critical("Failed to migrate olm sessions,");
1725 return false;
1726 }
1727
1728 nhlog::db()->info("Successfully migrated olm sessions.");
1729 return true;
1730 }},
1731 {"2021.08.22",
1732 [this]() {
1733 try {
1734 auto txn = lmdb::txn::begin(db->env_, nullptr);
1735 auto try_drop = [&txn](const std::string &dbName) {
1736 try {
1737 lmdb::dbi::open(txn, dbName.c_str()).drop(txn, true);
1738 } catch (std::exception &e) {
1739 nhlog::db()->warn("Failed to drop '{}': {}", dbName, e.what());
1740 }
1741 };
1742
1743 auto room_ids = getRoomIds(txn);
1744
1745 for (const auto &room : room_ids) {
1746 try_drop(room + "/state");
1747 try_drop(room + "/state_by_key");
1748 try_drop(room + "/account_data");
1749 try_drop(room + "/members");
1750 try_drop(room + "/mentions");
1751 try_drop(room + "/events");
1752 try_drop(room + "/event_order");
1753 try_drop(room + "/event2order");
1754 try_drop(room + "/msg2order");
1755 try_drop(room + "/order2msg");
1756 try_drop(room + "/pending");
1757 try_drop(room + "/related");
1758 }
1759
1760 // clear db, don't delete
1761 db->rooms.drop(txn, false);
1762 setNextBatchToken(txn, "");
1763
1764 txn.commit();
1765 } catch (const lmdb::error &) {
1766 nhlog::db()->critical("Failed to clear cache!");
1767 return false;
1768 }
1769
1770 nhlog::db()->info("Successfully cleared the cache. Will do a clean sync after startup.");
1771 return true;
1772 }},
1773 {"2021.08.31",
1774 [this]() {
1775 storeSecretInStore("pickle_secret", "secret");
1776 this->pickle_secret_ = "secret";
1777 return true;
1778 }},
1779 {"2022.04.08",
1780 [this]() {
1781 try {
1782 auto txn = lmdb::txn::begin(db->env_, nullptr);
1783 auto inboundMegolmSessionDb =
1784 lmdb::dbi::open(txn, INBOUND_MEGOLM_SESSIONS_DB, MDB_CREATE);
1785 auto outboundMegolmSessionDb =
1786 lmdb::dbi::open(txn, OUTBOUND_MEGOLM_SESSIONS_DB, MDB_CREATE);
1787 auto megolmSessionDataDb = lmdb::dbi::open(txn, MEGOLM_SESSIONS_DATA_DB, MDB_CREATE);
1788 try {
1789 outboundMegolmSessionDb.drop(txn, false);
1790 } catch (std::exception &e) {
1791 nhlog::db()->warn("Failed to drop outbound sessions: {}", e.what());
1792 }
1793
1794 std::string_view key, value;
1795 auto cursor = lmdb::cursor::open(txn, inboundMegolmSessionDb);
1796 std::map<std::string, std::string> inboundSessions;
1797 std::map<std::string, std::string> megolmSessionData;
1798 while (cursor.get(key, value, MDB_NEXT)) {
1799 auto indexVal = nlohmann::json::parse(key);
1800 if (!indexVal.contains("sender_key") || !indexVal.at("sender_key").is_string())
1801 continue;
1802 auto sender_key = indexVal["sender_key"].get<std::string>();
1803 indexVal.erase("sender_key");
1804
1805 std::string_view dataVal;
1806 bool res = megolmSessionDataDb.get(txn, key, dataVal);
1807 if (res) {
1808 auto data = nlohmann::json::parse(dataVal);
1809 data["sender_key"] = sender_key;
1810 inboundSessions[indexVal.dump()] = std::string(value);
1811 megolmSessionData[indexVal.dump()] = data.dump();
1812 }
1813 }
1814 cursor.close();
1815 inboundMegolmSessionDb.drop(txn, false);
1816 megolmSessionDataDb.drop(txn, false);
1817
1818 for (const auto &[k, v] : inboundSessions) {
1819 inboundMegolmSessionDb.put(txn, k, v);
1820 }
1821 for (const auto &[k, v] : megolmSessionData) {
1822 megolmSessionDataDb.put(txn, k, v);
1823 }
1824 txn.commit();
1825 return true;
1826 } catch (std::exception &e) {
1827 nhlog::db()->warn(
1828 "Failed to migrate stored megolm session to have no sender key: {}", e.what());
1829 return false;
1830 }
1831 }},
1832 {"2022.11.06",
1833 [this]() {
1834 this->databaseReady_ = false;
1835 loadSecretsFromStore(
1836 {
1837 {std::string(mtx::secret_storage::secrets::cross_signing_master), false},
1838 {std::string(mtx::secret_storage::secrets::cross_signing_self_signing), false},
1839 {std::string(mtx::secret_storage::secrets::cross_signing_user_signing), false},
1840 {std::string(mtx::secret_storage::secrets::megolm_backup_v1), false},
1841 },
1842 [this,
1843 count = 1](const std::string &name, bool internal, const std::string &value) mutable {
1844 nhlog::db()->critical("Loaded secret {}", name);
1845 this->storeSecret(name, value, internal);
1846
1847 // HACK(Nico): delay deletion to not crash because of multiple nested deletions.
1848 // Since this is just migration code, this should be *fine*.
1849
1850 QTimer::singleShot(count * 2000, this, [this, name, internal] {
1851 deleteSecretFromStore(name, internal);
1852 });
1853 count++;
1854 },
1855 false);
1856
1857 while (!this->databaseReady_) {
1858 QCoreApplication::instance()->processEvents(QEventLoop::AllEvents, 100);
1859 }
1860
1861 return true;
1862 }},
1863 {"2023.03.12",
1864 [this]() {
1865 try {
1866 auto txn = lmdb::txn::begin(db->env_, nullptr);
1867 auto room_ids = getRoomIds(txn);
1868
1869 for (const auto &room_id : room_ids) {
1870 try {
1871 auto oldStateskeyDb =
1872 lmdb::dbi::open(txn,
1873 std::string(room_id + "/state_by_key").c_str(),
1874 MDB_CREATE | MDB_DUPSORT);
1875 lmdb::dbi_set_dupsort(
1876 txn, oldStateskeyDb, +[](const MDB_val *a, const MDB_val *b) {
1877 auto get_skey = [](const MDB_val *v) {
1878 return nlohmann::json::parse(
1879 std::string_view(static_cast<const char *>(v->mv_data),
1880 v->mv_size))
1881 .value("key", "");
1882 };
1883
1884 return get_skey(a).compare(get_skey(b));
1885 });
1886 auto newStateskeyDb = getStatesKeyDb(txn, room_id);
1887
1888 // convert the dupsort format
1889 {
1890 auto cursor = lmdb::cursor::open(txn, oldStateskeyDb);
1891 std::string_view ev_type, data;
1892 bool start = true;
1893 while (cursor.get(ev_type, data, start ? MDB_FIRST : MDB_NEXT)) {
1894 start = false;
1895
1896 auto j =
1897 nlohmann::json::parse(std::string_view(data.data(), data.size()));
1898
1899 newStateskeyDb.put(
1900 txn, ev_type, j.value("key", "") + '\0' + j.value("id", ""));
1901 }
1902 }
1903
1904 // delete old db
1905 lmdb::dbi_drop(txn, oldStateskeyDb, true);
1906 } catch (std::exception &e) {
1907 nhlog::db()->error("While migrating state events from {}, ignoring error {}",
1908 room_id,
1909 e.what());
1910 }
1911 }
1912 txn.commit();
1913 } catch (const lmdb::error &) {
1914 nhlog::db()->critical("Failed to convert states key database in migration!");
1915 return false;
1916 }
1917
1918 nhlog::db()->info("Successfully updated states key database format.");
1919 return true;
1920 }},
1921 {"2023.10.22",
1922 [this]() {
1923 // migrate olm sessions to a single db
1924 try {
1925 auto txn = lmdb::txn::begin(db->env_, nullptr);
1926 auto mainDb = lmdb::dbi::open(txn);
1927 auto dbNames = lmdb::cursor::open(txn, mainDb);
1928 bool doCommit = false;
1929
1930 std::string_view dbName;
1931 while (dbNames.get(dbName, MDB_NEXT)) {
1932 if (!dbName.starts_with("olm_sessions.v2/"))
1933 continue;
1934
1935 doCommit = true;
1936 auto curveKey = dbName;
1937 curveKey.remove_prefix(std::string_view("olm_sessions.v2/").size());
1938
1939 auto oldDb = lmdb::dbi::open(txn, std::string(dbName).c_str());
1940 auto olmCursor = lmdb::cursor::open(txn, oldDb);
1941
1942 std::string_view session_id, json;
1943 while (olmCursor.get(session_id, json, MDB_NEXT)) {
1944 db->olmSessions.put(
1945 txn,
1946 combineOlmSessionKeyFromCurveAndSessionId(curveKey, session_id),
1947 json);
1948 }
1949 olmCursor.close();
1950
1951 oldDb.drop(txn, true);
1952 }
1953 dbNames.close();
1954
1955 if (doCommit)
1956 txn.commit();
1957 } catch (const lmdb::error &e) {
1958 nhlog::db()->critical("Failed to convert olm sessions database in migration! {}",
1959 e.what());
1960 return false;
1961 }
1962
1963 nhlog::db()->info("Successfully updated olm sessions database format.");
1964 return true;
1965 }},
1966 };
1967
1968 nhlog::db()->info("Running migrations, this may take a while!");
1969 for (const auto &[target_version, migration] : migrations) {
1970 if (target_version > stored_version)
1971 if (!migration()) {
1972 nhlog::db()->critical("migration failure!");
1973 return false;
1974 }
1975 }
1976 nhlog::db()->info("Migrations finished.");
1977
1978 setCurrentFormat();
1979 return true;
1980 }
1981
1982 cache::CacheVersion
1983 Cache::formatVersion()
1984 {
1985 auto txn = ro_txn(db->env_);
1986
1987 std::string_view current_version;
1988 bool res = db->syncState.get(txn, CACHE_FORMAT_VERSION_KEY, current_version);
1989
1990 if (!res)
1991 return cache::CacheVersion::Older;
1992
1993 std::string stored_version(current_version.data(), current_version.size());
1994
1995 if (stored_version < CURRENT_CACHE_FORMAT_VERSION)
1996 return cache::CacheVersion::Older;
1997 else if (stored_version > CURRENT_CACHE_FORMAT_VERSION)
1998 return cache::CacheVersion::Older;
1999 else
2000 return cache::CacheVersion::Current;
2001 }
2002
2003 void
2004 Cache::setCurrentFormat()
2005 {
2006 auto txn = lmdb::txn::begin(db->env_);
2007
2008 db->syncState.put(txn, CACHE_FORMAT_VERSION_KEY, CURRENT_CACHE_FORMAT_VERSION);
2009
2010 txn.commit();
2011 }
2012
2013 CachedReceipts
2014 Cache::readReceipts(const QString &event_id, const QString &room_id)
2015 {
2016 CachedReceipts receipts;
2017
2018 ReadReceiptKey receipt_key{event_id.toStdString(), room_id.toStdString()};
2019 nlohmann::json json_key = receipt_key;
2020
2021 try {
2022 auto txn = ro_txn(db->env_);
2023 auto key = json_key.dump();
2024
2025 std::string_view value;
2026
2027 bool res = db->readReceipts.get(txn, key, value);
2028
2029 if (res) {
2030 auto json_response =
2031 nlohmann::json::parse(std::string_view(value.data(), value.size()));
2032 auto values = json_response.get<std::map<std::string, uint64_t>>();
2033
2034 for (const auto &v : values)
2035 // timestamp, user_id
2036 receipts.emplace(v.second, v.first);
2037 }
2038
2039 } catch (const lmdb::error &e) {
2040 nhlog::db()->critical("readReceipts: {}", e.what());
2041 }
2042
2043 return receipts;
2044 }
2045
2046 void
2047 Cache::updateReadReceipt(lmdb::txn &txn, const std::string &room_id, const Receipts &receipts)
2048 {
2049 auto user_id = this->localUserId_.toStdString();
2050 for (const auto &receipt : receipts) {
2051 const auto event_id = receipt.first;
2052 auto event_receipts = receipt.second;
2053
2054 ReadReceiptKey receipt_key{event_id, room_id};
2055 nlohmann::json json_key = receipt_key;
2056
2057 try {
2058 const auto key = json_key.dump();
2059
2060 std::string_view prev_value;
2061
2062 bool exists = db->readReceipts.get(txn, key, prev_value);
2063
2064 std::map<std::string, uint64_t> saved_receipts;
2065
2066 // If an entry for the event id already exists, we would
2067 // merge the existing receipts with the new ones.
2068 if (exists) {
2069 auto json_value =
2070 nlohmann::json::parse(std::string_view(prev_value.data(), prev_value.size()));
2071
2072 // Retrieve the saved receipts.
2073 saved_receipts = json_value.get<std::map<std::string, uint64_t>>();
2074 }
2075
2076 // Append the new ones.
2077 for (const auto &[read_by, timestamp] : event_receipts) {
2078 saved_receipts.emplace(read_by, timestamp);
2079 }
2080
2081 // Save back the merged (or only the new) receipts.
2082 nlohmann::json json_updated_value = saved_receipts;
2083 std::string merged_receipts = json_updated_value.dump();
2084
2085 db->readReceipts.put(txn, key, merged_receipts);
2086
2087 } catch (const lmdb::error &e) {
2088 nhlog::db()->critical("updateReadReceipts: {}", e.what());
2089 }
2090 }
2091 }
2092
2093 std::string
2094 Cache::getFullyReadEventId(const std::string &room_id)
2095 {
2096 auto txn = ro_txn(db->env_);
2097
2098 if (auto ev = getAccountData(txn, mtx::events::EventType::FullyRead, room_id)) {
2099 if (auto fr =
2100 std::get_if<mtx::events::AccountDataEvent<mtx::events::account_data::FullyRead>>(
2101 &ev.value())) {
2102 return fr->content.event_id;
2103 }
2104 }
2105 return std::string();
2106 }
2107
2108 void
2109 Cache::calculateRoomReadStatus()
2110 {
2111 const auto joined_rooms = joinedRooms();
2112
2113 std::map<QString, bool> readStatus;
2114
2115 for (const auto &room : joined_rooms)
2116 readStatus.emplace(QString::fromStdString(room), calculateRoomReadStatus(room));
2117
2118 emit roomReadStatus(readStatus);
2119 }
2120
2121 bool
2122 Cache::calculateRoomReadStatus(const std::string &room_id)
2123 {
2124 std::string last_event_id_, fullyReadEventId_;
2125 {
2126 auto txn = ro_txn(db->env_);
2127
2128 // Get last event id on the room.
2129 const auto last_event_id = getLastEventId(txn, room_id);
2130 const auto localUser = utils::localUser().toStdString();
2131
2132 std::string fullyReadEventId = getFullyReadEventId(room_id);
2133
2134 if (last_event_id.empty() || fullyReadEventId.empty())
2135 return true;
2136
2137 if (last_event_id == fullyReadEventId)
2138 return false;
2139
2140 last_event_id_ = std::string(last_event_id);
2141 fullyReadEventId_ = std::string(fullyReadEventId);
2142 }
2143
2144 // Retrieve all read receipts for that event.
2145 return getEventIndex(room_id, last_event_id_) > getEventIndex(room_id, fullyReadEventId_);
2146 }
2147
2148 void
2149 Cache::updateState(const std::string &room, const mtx::responses::StateEvents &state, bool wipe)
2150 {
2151 auto txn = lmdb::txn::begin(db->env_);
2152 auto statesdb = getStatesDb(txn, room);
2153 auto stateskeydb = getStatesKeyDb(txn, room);
2154 auto membersdb = getMembersDb(txn, room);
2155 auto eventsDb = getEventsDb(txn, room);
2156
2157 if (wipe) {
2158 membersdb.drop(txn);
2159 statesdb.drop(txn);
2160 stateskeydb.drop(txn);
2161 }
2162
2163 saveStateEvents(txn, statesdb, stateskeydb, membersdb, eventsDb, room, state.events);
2164
2165 RoomInfo updatedInfo;
2166
2167 {
2168 std::string_view data;
2169 if (db->rooms.get(txn, room, data)) {
2170 try {
2171 updatedInfo =
2172 nlohmann::json::parse(std::string_view(data.data(), data.size())).get<RoomInfo>();
2173 } catch (const nlohmann::json::exception &e) {
2174 nhlog::db()->warn("failed to parse room info: room_id ({}), {}: {}",
2175 room,
2176 std::string(data.data(), data.size()),
2177 e.what());
2178 }
2179 }
2180 }
2181
2182 updatedInfo.name = getRoomName(txn, statesdb, membersdb).toStdString();
2183 updatedInfo.topic = getRoomTopic(txn, statesdb).toStdString();
2184 updatedInfo.avatar_url = getRoomAvatarUrl(txn, statesdb, membersdb).toStdString();
2185 updatedInfo.version = getRoomVersion(txn, statesdb).toStdString();
2186
2187 updatedInfo.is_space = getRoomIsSpace(txn, statesdb);
2188 updatedInfo.is_tombstoned = getRoomIsTombstoned(txn, statesdb);
2189
2190 db->rooms.put(txn, room, nlohmann::json(updatedInfo).dump());
2191 updateSpaces(txn, {room}, {room});
2192 txn.commit();
2193 }
2194
2195 template<typename T>
2196 std::optional<mtx::events::StateEvent<T>>
2197 Cache::getStateEvent(lmdb::txn &txn, const std::string &room_id, std::string_view state_key)
2198 {
2199 try {
2200 constexpr auto type = mtx::events::state_content_to_type<T>;
2201 static_assert(type != mtx::events::EventType::Unsupported,
2202 "Not a supported type in state events.");
2203
2204 if (room_id.empty())
2205 return std::nullopt;
2206 const auto typeStr = to_string(type);
2207
2208 std::string_view value;
2209 if (state_key.empty()) {
2210 auto db_ = getStatesDb(txn, room_id);
2211 if (!db_.get(txn, typeStr, value)) {
2212 return std::nullopt;
2213 }
2214 } else {
2215 auto db_ = getStatesKeyDb(txn, room_id);
2216 // we can search using state key, since the compare functions defaults to the whole
2217 // string, when there is no nullbyte
2218 std::string_view data = state_key;
2219 std::string_view typeStrV = typeStr;
2220
2221 auto cursor = lmdb::cursor::open(txn, db_);
2222 if (!cursor.get(typeStrV, data, MDB_GET_BOTH))
2223 return std::nullopt;
2224
2225 try {
2226 auto eventsDb = getEventsDb(txn, room_id);
2227 auto eventid = data;
2228 if (auto sep = data.rfind('\0'); sep != std::string_view::npos) {
2229 if (!eventsDb.get(txn, eventid.substr(sep + 1), value))
2230 return std::nullopt;
2231 } else {
2232 return std::nullopt;
2233 }
2234
2235 } catch (std::exception &) {
2236 return std::nullopt;
2237 }
2238 }
2239
2240 return nlohmann::json::parse(value).get<mtx::events::StateEvent<T>>();
2241 } catch (std::exception &) {
2242 return std::nullopt;
2243 }
2244 }
2245
2246 template<typename T>
2247 std::vector<mtx::events::StateEvent<T>>
2248 Cache::getStateEventsWithType(lmdb::txn &txn,
2249 const std::string &room_id,
2250 mtx::events::EventType type)
2251
2252 {
2253 if (room_id.empty())
2254 return {};
2255
2256 std::vector<mtx::events::StateEvent<T>> events;
2257
2258 {
2259 auto db_ = getStatesKeyDb(txn, room_id);
2260 auto eventsDb = getEventsDb(txn, room_id);
2261 const auto typeStr = to_string(type);
2262 std::string_view typeStrV = typeStr;
2263 std::string_view data;
2264 std::string_view value;
2265
2266 auto cursor = lmdb::cursor::open(txn, db_);
2267 bool first = true;
2268 if (cursor.get(typeStrV, data, MDB_SET)) {
2269 while (cursor.get(typeStrV, data, first ? MDB_FIRST_DUP : MDB_NEXT_DUP)) {
2270 first = false;
2271
2272 try {
2273 auto eventid = data;
2274 if (auto sep = data.rfind('\0'); sep != std::string_view::npos) {
2275 if (eventsDb.get(txn, eventid.substr(sep + 1), value))
2276 events.push_back(
2277 nlohmann::json::parse(value).get<mtx::events::StateEvent<T>>());
2278 }
2279 } catch (std::exception &e) {
2280 nhlog::db()->warn("Failed to parse state event: {}", e.what());
2281 }
2282 }
2283 }
2284 }
2285
2286 return events;
2287 }
2288
2289 template<class T>
2290 void
2291 Cache::saveStateEvents(lmdb::txn &txn,
2292 lmdb::dbi &statesdb,
2293 lmdb::dbi &stateskeydb,
2294 lmdb::dbi &membersdb,
2295 lmdb::dbi &eventsDb,
2296 const std::string &room_id,
2297 const std::vector<T> &events)
2298 {
2299 for (const auto &e : events)
2300 saveStateEvent(txn, statesdb, stateskeydb, membersdb, eventsDb, room_id, e);
2301 }
2302
2303 template<class T>
2304 void
2305 Cache::saveStateEvent(lmdb::txn &txn,
2306 lmdb::dbi &statesdb,
2307 lmdb::dbi &stateskeydb,
2308 lmdb::dbi &membersdb,
2309 lmdb::dbi &eventsDb,
2310 const std::string &room_id,
2311 const T &event)
2312 {
2313 using namespace mtx::events;
2314 using namespace mtx::events::state;
2315
2316 if (auto e = std::get_if<StateEvent<Member>>(&event); e != nullptr) {
2317 switch (e->content.membership) {
2318 //
2319 // We only keep users with invite or join membership.
2320 //
2321 case Membership::Invite:
2322 case Membership::Join: {
2323 auto display_name =
2324 e->content.display_name.empty() ? e->state_key : e->content.display_name;
2325
2326 std::string inviter = "";
2327 if (e->content.membership == mtx::events::state::Membership::Invite) {
2328 inviter = e->sender;
2329 }
2330
2331 // Lightweight representation of a member.
2332 MemberInfo tmp{
2333 display_name,
2334 e->content.avatar_url,
2335 inviter,
2336 e->content.reason,
2337 e->content.is_direct,
2338 };
2339
2340 membersdb.put(txn, e->state_key, nlohmann::json(tmp).dump());
2341 break;
2342 }
2343 default: {
2344 membersdb.del(txn, e->state_key, "");
2345 break;
2346 }
2347 }
2348 } else if (auto encr = std::get_if<StateEvent<Encryption>>(&event)) {
2349 if (!encr->state_key.empty())
2350 return;
2351
2352 setEncryptedRoom(txn, room_id);
2353
2354 std::string_view temp;
2355 // ensure we don't replace the event in the db
2356 if (statesdb.get(txn, to_string(encr->type), temp)) {
2357 return;
2358 }
2359 }
2360
2361 std::visit(
2362 [&txn, &statesdb, &stateskeydb, &eventsDb, &membersdb](const auto &e) {
2363 if constexpr (isStateEvent_<decltype(e)>) {
2364 eventsDb.put(txn, e.event_id, nlohmann::json(e).dump());
2365
2366 if (e.type != EventType::Unsupported) {
2367 if (std::is_same_v<std::remove_cv_t<std::remove_reference_t<decltype(e)>>,
2368 StateEvent<mtx::events::msg::Redacted>>) {
2369 // apply the redaction event
2370 if (e.type == EventType::RoomMember) {
2371 // membership is not revoked, but names are yeeted (so we set the name
2372 // to the mxid)
2373 MemberInfo tmp{e.state_key, ""};
2374 membersdb.put(txn, e.state_key, nlohmann::json(tmp).dump());
2375 } else if (e.state_key.empty()) {
2376 // strictly speaking some stuff in those events can be redacted, but
2377 // this is close enough. Ref:
2378 // https://spec.matrix.org/v1.6/rooms/v10/#redactions
2379 if (e.type != EventType::RoomCreate &&
2380 e.type != EventType::RoomJoinRules &&
2381 e.type != EventType::RoomPowerLevels &&
2382 e.type != EventType::RoomHistoryVisibility)
2383 statesdb.del(txn, to_string(e.type));
2384 } else
2385 stateskeydb.del(txn, to_string(e.type), e.state_key + '\0' + e.event_id);
2386 } else if (e.state_key.empty()) {
2387 statesdb.put(txn, to_string(e.type), nlohmann::json(e).dump());
2388 } else {
2389 auto data = e.state_key + '\0' + e.event_id;
2390 auto key = to_string(e.type);
2391
2392 // Work around https://bugs.openldap.org/show_bug.cgi?id=8447
2393 stateskeydb.del(txn, key, data);
2394 stateskeydb.put(txn, key, data);
2395 }
2396 }
2397 }
2398 },
2399 event);
2400 }
2401
2402 void
2403 Cache::saveState(const mtx::responses::Sync &res)
2404 try {
2405 using namespace mtx::events;
2406 auto local_user_id = this->localUserId_.toStdString();
2407
2408 auto currentBatchToken = res.next_batch;
2409
2410 auto txn = lmdb::txn::begin(db->env_);
2411
2412 setNextBatchToken(txn, res.next_batch);
2413
2414 if (!res.account_data.events.empty()) {
2415 auto accountDataDb = getAccountDataDb(txn, "");
2416 for (const auto &ev : res.account_data.events)
2417 std::visit(
2418 [&txn, &accountDataDb](const auto &event) {
2419 if constexpr (std::is_same_v<
2420 std::remove_cv_t<std::remove_reference_t<decltype(event)>>,
2421 AccountDataEvent<
2422 mtx::events::account_data::nheko_extensions::HiddenEvents>>) {
2423 if (!event.content.hidden_event_types) {
2424 accountDataDb.del(txn, "im.nheko.hidden_events");
2425 return;
2426 }
2427 }
2428
2429 auto j = nlohmann::json(event);
2430 accountDataDb.put(txn, j["type"].get<std::string>(), j.dump());
2431 },
2432 ev);
2433 }
2434
2435 auto userKeyCacheDb = getUserKeysDb(txn);
2436
2437 std::set<std::string> spaces_with_updates;
2438 std::set<std::string> rooms_with_space_updates;
2439
2440 // Save joined rooms
2441 for (const auto &room : res.rooms.join) {
2442 auto statesdb = getStatesDb(txn, room.first);
2443 auto stateskeydb = getStatesKeyDb(txn, room.first);
2444 auto membersdb = getMembersDb(txn, room.first);
2445 auto eventsDb = getEventsDb(txn, room.first);
2446
2447 // nhlog::db()->critical(
2448 // "Saving events for room: {}, state {}, timeline {}, account {}, ephemeral {}",
2449 // room.first,
2450 // room.second.state.events.size(),
2451 // room.second.timeline.events.size(),
2452 // room.second.account_data.events.size(),
2453 // room.second.ephemeral.events.size());
2454
2455 saveStateEvents(
2456 txn, statesdb, stateskeydb, membersdb, eventsDb, room.first, room.second.state.events);
2457 saveStateEvents(
2458 txn, statesdb, stateskeydb, membersdb, eventsDb, room.first, room.second.timeline.events);
2459
2460 saveTimelineMessages(txn, eventsDb, room.first, room.second.timeline);
2461
2462 RoomInfo updatedInfo;
2463 std::string_view originalRoomInfoDump;
2464 {
2465 // retrieve the old tags and modification ts
2466 if (db->rooms.get(txn, room.first, originalRoomInfoDump)) {
2467 try {
2468 RoomInfo tmp = nlohmann::json::parse(originalRoomInfoDump).get<RoomInfo>();
2469 updatedInfo.tags = std::move(tmp.tags);
2470
2471 updatedInfo.approximate_last_modification_ts =
2472 tmp.approximate_last_modification_ts;
2473 } catch (const nlohmann::json::exception &e) {
2474 nhlog::db()->warn("failed to parse room info: room_id ({}), {}: {}",
2475 room.first,
2476 originalRoomInfoDump,
2477 e.what());
2478 }
2479 }
2480 }
2481
2482 updatedInfo.name = getRoomName(txn, statesdb, membersdb).toStdString();
2483 updatedInfo.topic = getRoomTopic(txn, statesdb).toStdString();
2484 updatedInfo.avatar_url = getRoomAvatarUrl(txn, statesdb, membersdb).toStdString();
2485 updatedInfo.version = getRoomVersion(txn, statesdb).toStdString();
2486 updatedInfo.is_space = getRoomIsSpace(txn, statesdb);
2487
2488 updatedInfo.notification_count = room.second.unread_notifications.notification_count;
2489 updatedInfo.highlight_count = room.second.unread_notifications.highlight_count;
2490
2491 if (updatedInfo.is_space) {
2492 bool space_updates = false;
2493 for (const auto &e : room.second.state.events)
2494 if (std::holds_alternative<StateEvent<state::space::Child>>(e) ||
2495 std::holds_alternative<StateEvent<state::PowerLevels>>(e))
2496 space_updates = true;
2497 for (const auto &e : room.second.timeline.events)
2498 if (std::holds_alternative<StateEvent<state::space::Child>>(e) ||
2499 std::holds_alternative<StateEvent<state::PowerLevels>>(e))
2500 space_updates = true;
2501
2502 if (space_updates)
2503 spaces_with_updates.insert(room.first);
2504 }
2505
2506 {
2507 bool room_has_space_update = false;
2508 for (const auto &e : room.second.state.events) {
2509 if (auto se = std::get_if<StateEvent<state::space::Parent>>(&e)) {
2510 if (se->state_key.empty()) {
2511 nhlog::db()->warn("Skipping space parent with empty state key in room {}",
2512 room.first);
2513 } else {
2514 spaces_with_updates.insert(se->state_key);
2515 room_has_space_update = true;
2516 }
2517 }
2518 }
2519 for (const auto &e : room.second.timeline.events) {
2520 if (auto se = std::get_if<StateEvent<state::space::Parent>>(&e)) {
2521 if (se->state_key.empty()) {
2522 nhlog::db()->warn("Skipping space child with empty state key in room {}",
2523 room.first);
2524 } else {
2525 spaces_with_updates.insert(se->state_key);
2526 room_has_space_update = true;
2527 }
2528 }
2529 }
2530
2531 if (room_has_space_update)
2532 rooms_with_space_updates.insert(room.first);
2533 }
2534
2535 // Process the account_data associated with this room
2536 if (!room.second.account_data.events.empty()) {
2537 auto accountDataDb = getAccountDataDb(txn, room.first);
2538
2539 for (const auto &evt : room.second.account_data.events) {
2540 std::visit(
2541 [&txn, &accountDataDb](const auto &event) {
2542 if constexpr (std::is_same_v<
2543 std::remove_cv_t<std::remove_reference_t<decltype(event)>>,
2544 AccountDataEvent<mtx::events::account_data::nheko_extensions::
2545 HiddenEvents>>) {
2546 if (!event.content.hidden_event_types) {
2547 accountDataDb.del(txn, "im.nheko.hidden_events");
2548 return;
2549 }
2550 }
2551 auto j = nlohmann::json(event);
2552 accountDataDb.put(txn, j["type"].get<std::string>(), j.dump());
2553 },
2554 evt);
2555
2556 // for tag events
2557 if (std::holds_alternative<AccountDataEvent<account_data::Tags>>(evt)) {
2558 auto tags_evt = std::get<AccountDataEvent<account_data::Tags>>(evt);
2559
2560 updatedInfo.tags.clear();
2561 for (const auto &tag : tags_evt.content.tags) {
2562 updatedInfo.tags.push_back(tag.first);
2563 }
2564 }
2565 }
2566 }
2567
2568 for (const auto &e : room.second.timeline.events) {
2569 if (!mtx::accessors::is_message(e))
2570 continue;
2571 updatedInfo.approximate_last_modification_ts = mtx::accessors::origin_server_ts_ms(e);
2572 }
2573
2574 if (auto newRoomInfoDump = nlohmann::json(updatedInfo).dump();
2575 newRoomInfoDump != originalRoomInfoDump) {
2576 // nhlog::db()->critical(
2577 // "Writing out new room info:\n{}\n{}", originalRoomInfoDump, newRoomInfoDump);
2578 db->rooms.put(txn, room.first, newRoomInfoDump);
2579 }
2580
2581 for (const auto &e : room.second.ephemeral.events) {
2582 if (auto receiptsEv =
2583 std::get_if<mtx::events::EphemeralEvent<mtx::events::ephemeral::Receipt>>(&e)) {
2584 Receipts receipts;
2585
2586 for (const auto &[event_id, userReceipts] : receiptsEv->content.receipts) {
2587 if (auto r = userReceipts.find(mtx::events::ephemeral::Receipt::Read);
2588 r != userReceipts.end()) {
2589 for (const auto &[user_id, receipt] : r->second.users) {
2590 receipts[event_id][user_id] = receipt.ts;
2591 }
2592 }
2593 if (userReceipts.count(mtx::events::ephemeral::Receipt::ReadPrivate)) {
2594 const auto &users =
2595 userReceipts.at(mtx::events::ephemeral::Receipt::ReadPrivate).users;
2596 if (auto ts = users.find(local_user_id);
2597 ts != users.end() && ts->second.ts != 0)
2598 receipts[event_id][local_user_id] = ts->second.ts;
2599 }
2600 }
2601 updateReadReceipt(txn, room.first, receipts);
2602 }
2603 }
2604
2605 // Clean up non-valid invites.
2606 removeInvite(txn, room.first);
2607 }
2608
2609 saveInvites(txn, res.rooms.invite);
2610
2611 savePresence(txn, res.presence);
2612
2613 markUserKeysOutOfDate(txn, userKeyCacheDb, res.device_lists.changed, currentBatchToken);
2614
2615 removeLeftRooms(txn, res.rooms.leave);
2616
2617 updateSpaces(txn, spaces_with_updates, std::move(rooms_with_space_updates));
2618
2619 txn.commit();
2620
2621 std::map<QString, bool> readStatus;
2622
2623 for (const auto &room : res.rooms.join) {
2624 for (const auto &e : room.second.ephemeral.events) {
2625 if (auto receiptsEv =
2626 std::get_if<mtx::events::EphemeralEvent<mtx::events::ephemeral::Receipt>>(&e)) {
2627 std::vector<QString> receipts;
2628
2629 for (const auto &[event_id, userReceipts] : receiptsEv->content.receipts) {
2630 if (auto r = userReceipts.find(mtx::events::ephemeral::Receipt::Read);
2631 r != userReceipts.end()) {
2632 for (const auto &[user_id, receipt] : r->second.users) {
2633 (void)receipt;
2634
2635 if (user_id != local_user_id) {
2636 receipts.push_back(QString::fromStdString(event_id));
2637 break;
2638 }
2639 }
2640 }
2641 }
2642 if (!receipts.empty())
2643 emit newReadReceipts(QString::fromStdString(room.first), receipts);
2644 }
2645 }
2646 readStatus.emplace(QString::fromStdString(room.first), calculateRoomReadStatus(room.first));
2647 }
2648
2649 emit roomReadStatus(readStatus);
2650 } catch (const lmdb::error &lmdbException) {
2651 if (lmdbException.code() == MDB_DBS_FULL || lmdbException.code() == MDB_MAP_FULL) {
2652 if (lmdbException.code() == MDB_DBS_FULL) {
2653 auto settings = UserSettings::instance();
2654
2655 unsigned roomDbCount =
2656 static_cast<unsigned>((res.rooms.invite.size() + res.rooms.join.size() +
2657 res.rooms.knock.size() + res.rooms.leave.size()) *
2658 20);
2659
2660 settings->qsettings()->setValue(
2661 MAX_DBS_SETTINGS_KEY,
2662 std::max(
2663 settings->qsettings()->value(MAX_DBS_SETTINGS_KEY, MAX_DBS_DEFAULT).toUInt() * 2,
2664 roomDbCount));
2665 } else if (lmdbException.code() == MDB_MAP_FULL) {
2666 auto settings = UserSettings::instance();
2667
2668 MDB_envinfo envinfo = {};
2669 lmdb::env_info(db->env_, &envinfo);
2670 settings->qsettings()->setValue(MAX_DB_SIZE_SETTINGS_KEY,
2671 static_cast<qulonglong>(envinfo.me_mapsize * 2));
2672 }
2673
2674 QMessageBox::warning(
2675 nullptr,
2676 tr("Database limit reached"),
2677 tr("Your account is larger than our default database limit. We have "
2678 "increased the capacity automatically, however you will need to "
2679 "restart to apply this change. Nheko will now close automatically."),
2680 QMessageBox::StandardButton::Close);
2681 QCoreApplication::exit(1);
2682 exit(1);
2683 }
2684
2685 throw;
2686 }
2687
2688 void
2689 Cache::saveInvites(lmdb::txn &txn, const std::map<std::string, mtx::responses::InvitedRoom> &rooms)
2690 {
2691 for (const auto &room : rooms) {
2692 auto statesdb = getInviteStatesDb(txn, room.first);
2693 auto membersdb = getInviteMembersDb(txn, room.first);
2694
2695 saveInvite(txn, statesdb, membersdb, room.second);
2696
2697 RoomInfo updatedInfo;
2698 updatedInfo.name = getInviteRoomName(txn, statesdb, membersdb).toStdString();
2699 updatedInfo.topic = getInviteRoomTopic(txn, statesdb).toStdString();
2700 updatedInfo.avatar_url = getInviteRoomAvatarUrl(txn, statesdb, membersdb).toStdString();
2701 updatedInfo.is_space = getInviteRoomIsSpace(txn, statesdb);
2702 updatedInfo.is_invite = true;
2703
2704 db->invites.put(txn, room.first, nlohmann::json(updatedInfo).dump());
2705 }
2706 }
2707
2708 void
2709 Cache::saveInvite(lmdb::txn &txn,
2710 lmdb::dbi &statesdb,
2711 lmdb::dbi &membersdb,
2712 const mtx::responses::InvitedRoom &room)
2713 {
2714 using namespace mtx::events;
2715 using namespace mtx::events::state;
2716
2717 for (const auto &e : room.invite_state) {
2718 if (auto msg = std::get_if<StrippedEvent<Member>>(&e)) {
2719 auto display_name =
2720 msg->content.display_name.empty() ? msg->state_key : msg->content.display_name;
2721
2722 std::string inviter = "";
2723 if (msg->content.membership == mtx::events::state::Membership::Invite) {
2724 inviter = msg->sender;
2725 }
2726
2727 MemberInfo tmp{display_name,
2728 msg->content.avatar_url,
2729 inviter,
2730 msg->content.reason,
2731 msg->content.is_direct};
2732
2733 membersdb.put(txn, msg->state_key, nlohmann::json(tmp).dump());
2734 } else {
2735 std::visit(
2736 [&txn, &statesdb](auto msg) {
2737 auto j = nlohmann::json(msg);
2738 bool res = statesdb.put(txn, j["type"].get<std::string>(), j.dump());
2739
2740 if (!res)
2741 nhlog::db()->warn("couldn't save data: {}", nlohmann::json(msg).dump());
2742 },
2743 e);
2744 }
2745 }
2746 }
2747
2748 void
2749 Cache::savePresence(
2750 lmdb::txn &txn,
2751 const std::vector<mtx::events::Event<mtx::events::presence::Presence>> &presenceUpdates)
2752 {
2753 for (const auto &update : presenceUpdates) {
2754 auto toWrite = nlohmann::json(update.content);
2755 // Nheko currently doesn't use those and it causes lots of db writes :)
2756 toWrite.erase("currently_active");
2757 toWrite.erase("last_active_ago");
2758 auto toWriteStr = toWrite.dump();
2759
2760 std::string_view oldPresenceVal;
2761
2762 db->presence.get(txn, update.sender, oldPresenceVal);
2763 if (oldPresenceVal != toWriteStr) {
2764 // nhlog::db()->critical(
2765 // "Presence update for {}: {} -> {}", update.sender, oldPresenceVal, toWriteStr);
2766 db->presence.put(txn, update.sender, toWriteStr);
2767 }
2768 }
2769 }
2770
2771 RoomInfo
2772 Cache::singleRoomInfo(const std::string &room_id)
2773 {
2774 auto txn = ro_txn(db->env_);
2775
2776 try {
2777 auto statesdb = getStatesDb(txn, room_id);
2778
2779 std::string_view data;
2780
2781 // Check if the room is joined.
2782 if (db->rooms.get(txn, room_id, data)) {
2783 try {
2784 RoomInfo tmp = nlohmann::json::parse(data).get<RoomInfo>();
2785 tmp.member_count = getMembersDb(txn, room_id).size(txn);
2786 tmp.join_rule = getRoomJoinRule(txn, statesdb);
2787 tmp.guest_access = getRoomGuestAccess(txn, statesdb);
2788
2789 return tmp;
2790 } catch (const nlohmann::json::exception &e) {
2791 nhlog::db()->warn("failed to parse room info: room_id ({}), {}: {}",
2792 room_id,
2793 std::string(data.data(), data.size()),
2794 e.what());
2795 }
2796 }
2797 } catch (const lmdb::error &e) {
2798 nhlog::db()->warn("failed to read room info from db: room_id ({}), {}", room_id, e.what());
2799 }
2800
2801 return RoomInfo();
2802 }
2803 void
2804 Cache::updateLastMessageTimestamp(const std::string &room_id, uint64_t ts)
2805 {
2806 auto txn = lmdb::txn::begin(db->env_);
2807
2808 try {
2809 auto statesdb = getStatesDb(txn, room_id);
2810
2811 std::string_view data;
2812
2813 // Check if the room is joined.
2814 if (db->rooms.get(txn, room_id, data)) {
2815 try {
2816 RoomInfo tmp = nlohmann::json::parse(data).get<RoomInfo>();
2817 tmp.approximate_last_modification_ts = ts;
2818 db->rooms.put(txn, room_id, nlohmann::json(tmp).dump());
2819 txn.commit();
2820 return;
2821 } catch (const nlohmann::json::exception &e) {
2822 nhlog::db()->warn("failed to parse room info: room_id ({}), {}: {}",
2823 room_id,
2824 std::string(data.data(), data.size()),
2825 e.what());
2826 }
2827 }
2828 } catch (const lmdb::error &e) {
2829 nhlog::db()->warn("failed to read room info from db: room_id ({}), {}", room_id, e.what());
2830 }
2831 }
2832
2833 std::map<QString, RoomInfo>
2834 Cache::getRoomInfo(const std::vector<std::string> &rooms)
2835 {
2836 std::map<QString, RoomInfo> room_info;
2837
2838 // TODO This should be read only.
2839 auto txn = lmdb::txn::begin(db->env_);
2840
2841 for (const auto &room : rooms) {
2842 std::string_view data;
2843 auto statesdb = getStatesDb(txn, room);
2844
2845 // Check if the room is joined.
2846 if (db->rooms.get(txn, room, data)) {
2847 try {
2848 RoomInfo tmp = nlohmann::json::parse(data).get<RoomInfo>();
2849 tmp.member_count = getMembersDb(txn, room).size(txn);
2850 tmp.join_rule = getRoomJoinRule(txn, statesdb);
2851 tmp.guest_access = getRoomGuestAccess(txn, statesdb);
2852
2853 room_info.emplace(QString::fromStdString(room), std::move(tmp));
2854 } catch (const nlohmann::json::exception &e) {
2855 nhlog::db()->warn("failed to parse room info: room_id ({}), {}: {}",
2856 room,
2857 std::string(data.data(), data.size()),
2858 e.what());
2859 }
2860 } else {
2861 // Check if the room is an invite.
2862 if (db->invites.get(txn, room, data)) {
2863 try {
2864 RoomInfo tmp = nlohmann::json::parse(std::string_view(data)).get<RoomInfo>();
2865 tmp.member_count = getInviteMembersDb(txn, room).size(txn);
2866
2867 room_info.emplace(QString::fromStdString(room), std::move(tmp));
2868 } catch (const nlohmann::json::exception &e) {
2869 nhlog::db()->warn("failed to parse room info for invite: "
2870 "room_id ({}), {}: {}",
2871 room,
2872 std::string(data.data(), data.size()),
2873 e.what());
2874 }
2875 }
2876 }
2877 }
2878
2879 txn.commit();
2880
2881 return room_info;
2882 }
2883
2884 std::vector<QString>
2885 Cache::roomIds()
2886 {
2887 auto txn = ro_txn(db->env_);
2888
2889 std::vector<QString> rooms;
2890 std::string_view room_id, unused;
2891
2892 auto roomsCursor = lmdb::cursor::open(txn, db->rooms);
2893 while (roomsCursor.get(room_id, unused, MDB_NEXT))
2894 rooms.push_back(QString::fromStdString(std::string(room_id)));
2895
2896 roomsCursor.close();
2897
2898 return rooms;
2899 }
2900
2901 std::string
2902 Cache::previousBatchToken(const std::string &room_id)
2903 {
2904 auto txn = ro_txn(db->env_);
2905 try {
2906 auto orderDb = getEventOrderDb(txn, room_id);
2907
2908 auto cursor = lmdb::cursor::open(txn, orderDb);
2909 std::string_view indexVal, val;
2910 if (!cursor.get(indexVal, val, MDB_FIRST)) {
2911 return "";
2912 }
2913
2914 auto j = nlohmann::json::parse(val);
2915
2916 return j.value("prev_batch", "");
2917 } catch (...) {
2918 return "";
2919 }
2920 }
2921
2922 std::optional<mtx::events::collections::TimelineEvents>
2923 Cache::getEvent(const std::string &room_id, std::string_view event_id)
2924 {
2925 auto txn = ro_txn(db->env_);
2926 auto eventsDb = getEventsDb(txn, room_id);
2927
2928 std::string_view event{};
2929 bool success = eventsDb.get(txn, event_id, event);
2930 if (!success)
2931 return {};
2932
2933 try {
2934 return nlohmann::json::parse(event).get<mtx::events::collections::TimelineEvents>();
2935 } catch (std::exception &e) {
2936 nhlog::db()->error("Failed to parse message from cache {}", e.what());
2937 return std::nullopt;
2938 }
2939 }
2940 void
2941 Cache::storeEvent(const std::string &room_id,
2942 const std::string &event_id,
2943 const mtx::events::collections::TimelineEvents &event)
2944 {
2945 auto txn = lmdb::txn::begin(db->env_);
2946 auto eventsDb = getEventsDb(txn, room_id);
2947 auto event_json = mtx::accessors::serialize_event(event);
2948 eventsDb.put(txn, event_id, event_json.dump());
2949 txn.commit();
2950 }
2951
2952 void
2953 Cache::replaceEvent(const std::string &room_id,
2954 const std::string &event_id,
2955 const mtx::events::collections::TimelineEvents &event)
2956 {
2957 auto txn = lmdb::txn::begin(db->env_);
2958 auto eventsDb = getEventsDb(txn, room_id);
2959 auto relationsDb = getRelationsDb(txn, room_id);
2960 auto event_json = mtx::accessors::serialize_event(event).dump();
2961
2962 {
2963 eventsDb.del(txn, event_id);
2964 eventsDb.put(txn, event_id, event_json);
2965 for (const auto &relation : mtx::accessors::relations(event).relations) {
2966 relationsDb.put(txn, relation.event_id, event_id);
2967 }
2968 }
2969
2970 txn.commit();
2971 }
2972
2973 std::vector<std::string>
2974 Cache::relatedEvents(const std::string &room_id, const std::string &event_id)
2975 {
2976 auto txn = ro_txn(db->env_);
2977 auto relationsDb = getRelationsDb(txn, room_id);
2978
2979 std::vector<std::string> related_ids;
2980
2981 auto related_cursor = lmdb::cursor::open(txn, relationsDb);
2982 std::string_view related_to = event_id, related_event;
2983 bool first = true;
2984
2985 try {
2986 if (!related_cursor.get(related_to, related_event, MDB_SET))
2987 return {};
2988
2989 while (
2990 related_cursor.get(related_to, related_event, first ? MDB_FIRST_DUP : MDB_NEXT_DUP)) {
2991 first = false;
2992 if (event_id != std::string_view(related_to.data(), related_to.size()))
2993 break;
2994
2995 related_ids.emplace_back(related_event.data(), related_event.size());
2996 }
2997 } catch (const lmdb::error &e) {
2998 nhlog::db()->error("related events error: {}", e.what());
2999 }
3000
3001 return related_ids;
3002 }
3003
3004 size_t
3005 Cache::memberCount(const std::string &room_id)
3006 {
3007 auto txn = ro_txn(db->env_);
3008 return getMembersDb(txn, room_id).size(txn);
3009 }
3010
3011 QMap<QString, RoomInfo>
3012 Cache::roomInfo(bool withInvites)
3013 {
3014 QMap<QString, RoomInfo> result;
3015
3016 auto txn = ro_txn(db->env_);
3017
3018 std::string_view room_id;
3019 std::string_view room_data;
3020
3021 // Gather info about the joined rooms.
3022 auto roomsCursor = lmdb::cursor::open(txn, db->rooms);
3023 while (roomsCursor.get(room_id, room_data, MDB_NEXT)) {
3024 RoomInfo tmp = nlohmann::json::parse(std::move(room_data)).get<RoomInfo>();
3025 tmp.member_count = getMembersDb(txn, std::string(room_id)).size(txn);
3026 result.insert(QString::fromStdString(std::string(room_id)), std::move(tmp));
3027 }
3028 roomsCursor.close();
3029
3030 if (withInvites) {
3031 // Gather info about the invites.
3032 auto invitesCursor = lmdb::cursor::open(txn, db->invites);
3033 while (invitesCursor.get(room_id, room_data, MDB_NEXT)) {
3034 RoomInfo tmp = nlohmann::json::parse(room_data).get<RoomInfo>();
3035 tmp.member_count = getInviteMembersDb(txn, std::string(room_id)).size(txn);
3036 result.insert(QString::fromStdString(std::string(room_id)), std::move(tmp));
3037 }
3038 invitesCursor.close();
3039 }
3040
3041 return result;
3042 }
3043
3044 std::vector<RoomNameAlias>
3045 Cache::roomNamesAndAliases()
3046 {
3047 auto txn = ro_txn(db->env_);
3048
3049 std::vector<RoomNameAlias> result;
3050 result.reserve(db->rooms.size(txn));
3051
3052 std::string_view room_id;
3053 std::string_view room_data;
3054 auto roomsCursor = lmdb::cursor::open(txn, db->rooms);
3055 while (roomsCursor.get(room_id, room_data, MDB_NEXT)) {
3056 try {
3057 std::string room_id_str = std::string(room_id);
3058 RoomInfo info = nlohmann::json::parse(std::move(room_data)).get<RoomInfo>();
3059
3060 auto aliases = getStateEvent<mtx::events::state::CanonicalAlias>(txn, room_id_str);
3061 std::string alias;
3062 if (aliases) {
3063 alias = aliases->content.alias;
3064 }
3065
3066 result.push_back(RoomNameAlias{
3067 .id = std::move(room_id_str),
3068 .name = std::move(info.name),
3069 .alias = std::move(alias),
3070 .recent_activity = info.approximate_last_modification_ts,
3071 .is_tombstoned = info.is_tombstoned,
3072 .is_space = info.is_space,
3073 });
3074 } catch (std::exception &e) {
3075 nhlog::db()->warn("Failed to add room {} to result: {}", room_id, e.what());
3076 }
3077 }
3078
3079 return result;
3080 }
3081
3082 std::string
3083 Cache::getLastEventId(lmdb::txn &txn, const std::string &room_id)
3084 {
3085 lmdb::dbi orderDb;
3086 try {
3087 orderDb = getOrderToMessageDb(txn, room_id);
3088 } catch (lmdb::runtime_error &e) {
3089 nhlog::db()->error(
3090 "Can't open db for room '{}', probably doesn't exist yet. ({})", room_id, e.what());
3091 return {};
3092 }
3093
3094 std::string_view indexVal, val;
3095
3096 auto cursor = lmdb::cursor::open(txn, orderDb);
3097 if (!cursor.get(indexVal, val, MDB_LAST)) {
3098 return {};
3099 }
3100
3101 return std::string(val.data(), val.size());
3102 }
3103
3104 std::optional<Cache::TimelineRange>
3105 Cache::getTimelineRange(const std::string &room_id)
3106 {
3107 auto txn = ro_txn(db->env_);
3108 lmdb::dbi orderDb;
3109 try {
3110 orderDb = getOrderToMessageDb(txn, room_id);
3111 } catch (lmdb::runtime_error &e) {
3112 nhlog::db()->error(
3113 "Can't open db for room '{}', probably doesn't exist yet. ({})", room_id, e.what());
3114 return {};
3115 }
3116
3117 std::string_view indexVal, val;
3118
3119 auto cursor = lmdb::cursor::open(txn, orderDb);
3120 if (!cursor.get(indexVal, val, MDB_LAST)) {
3121 return {};
3122 }
3123
3124 TimelineRange range{};
3125 range.last = lmdb::from_sv<uint64_t>(indexVal);
3126
3127 if (!cursor.get(indexVal, val, MDB_FIRST)) {
3128 return {};
3129 }
3130 range.first = lmdb::from_sv<uint64_t>(indexVal);
3131
3132 return range;
3133 }
3134 std::optional<uint64_t>
3135 Cache::getTimelineIndex(const std::string &room_id, std::string_view event_id)
3136 {
3137 if (event_id.empty() || room_id.empty())
3138 return {};
3139
3140 auto txn = ro_txn(db->env_);
3141
3142 lmdb::dbi orderDb;
3143 try {
3144 orderDb = getMessageToOrderDb(txn, room_id);
3145 } catch (lmdb::runtime_error &e) {
3146 nhlog::db()->error(
3147 "Can't open db for room '{}', probably doesn't exist yet. ({})", room_id, e.what());
3148 return {};
3149 }
3150
3151 std::string_view indexVal{event_id.data(), event_id.size()}, val;
3152
3153 bool success = orderDb.get(txn, indexVal, val);
3154 if (!success) {
3155 return {};
3156 }
3157
3158 return lmdb::from_sv<uint64_t>(val);
3159 }
3160
3161 std::optional<uint64_t>
3162 Cache::getEventIndex(const std::string &room_id, std::string_view event_id)
3163 {
3164 if (room_id.empty() || event_id.empty())
3165 return {};
3166
3167 auto txn = ro_txn(db->env_);
3168
3169 lmdb::dbi orderDb;
3170 try {
3171 orderDb = getEventToOrderDb(txn, room_id);
3172 } catch (lmdb::runtime_error &e) {
3173 nhlog::db()->error(
3174 "Can't open db for room '{}', probably doesn't exist yet. ({})", room_id, e.what());
3175 return {};
3176 }
3177
3178 std::string_view val;
3179
3180 bool success = orderDb.get(txn, event_id, val);
3181 if (!success) {
3182 return {};
3183 }
3184
3185 return lmdb::from_sv<uint64_t>(val);
3186 }
3187
3188 std::optional<std::pair<uint64_t, std::string>>
3189 Cache::lastInvisibleEventAfter(const std::string &room_id, std::string_view event_id)
3190 {
3191 if (room_id.empty() || event_id.empty())
3192 return {};
3193
3194 auto txn = ro_txn(db->env_);
3195
3196 lmdb::dbi orderDb;
3197 lmdb::dbi eventOrderDb;
3198 lmdb::dbi timelineDb;
3199 try {
3200 orderDb = getEventToOrderDb(txn, room_id);
3201 eventOrderDb = getEventOrderDb(txn, room_id);
3202 timelineDb = getMessageToOrderDb(txn, room_id);
3203 } catch (lmdb::runtime_error &e) {
3204 nhlog::db()->error(
3205 "Can't open db for room '{}', probably doesn't exist yet. ({})", room_id, e.what());
3206 return {};
3207 }
3208
3209 std::string_view indexVal;
3210
3211 bool success = orderDb.get(txn, event_id, indexVal);
3212 if (!success) {
3213 return {};
3214 }
3215
3216 try {
3217 uint64_t prevIdx = lmdb::from_sv<uint64_t>(indexVal);
3218 std::string prevId{event_id};
3219
3220 auto cursor = lmdb::cursor::open(txn, eventOrderDb);
3221 cursor.get(indexVal, MDB_SET);
3222 while (cursor.get(indexVal, event_id, MDB_NEXT)) {
3223 std::string evId = nlohmann::json::parse(event_id)["event_id"].get<std::string>();
3224 std::string_view temp;
3225 if (timelineDb.get(txn, evId, temp)) {
3226 return std::pair{prevIdx, std::string(prevId)};
3227 } else {
3228 prevIdx = lmdb::from_sv<uint64_t>(indexVal);
3229 prevId = std::move(evId);
3230 }
3231 }
3232
3233 return std::pair{prevIdx, std::string(prevId)};
3234 } catch (lmdb::runtime_error &e) {
3235 nhlog::db()->error("Failed to get last invisible event after {}", event_id, e.what());
3236 return {};
3237 }
3238 }
3239
3240 std::optional<std::pair<uint64_t, std::string>>
3241 Cache::lastVisibleEvent(const std::string &room_id, std::string_view event_id)
3242 {
3243 if (room_id.empty() || event_id.empty())
3244 return {};
3245
3246 auto txn = ro_txn(db->env_);
3247 lmdb::dbi orderDb;
3248 lmdb::dbi eventOrderDb;
3249 lmdb::dbi timelineDb;
3250 try {
3251 orderDb = getEventToOrderDb(txn, room_id);
3252 eventOrderDb = getEventOrderDb(txn, room_id);
3253 timelineDb = getMessageToOrderDb(txn, room_id);
3254
3255 std::string_view indexVal;
3256
3257 bool success = orderDb.get(txn, event_id, indexVal);
3258 if (!success) {
3259 return {};
3260 }
3261
3262 uint64_t idx = lmdb::from_sv<uint64_t>(indexVal);
3263 std::string evId{event_id};
3264
3265 auto cursor = lmdb::cursor::open(txn, eventOrderDb);
3266 if (cursor.get(indexVal, event_id, MDB_SET)) {
3267 do {
3268 evId = nlohmann::json::parse(event_id)["event_id"].get<std::string>();
3269 std::string_view temp;
3270 idx = lmdb::from_sv<uint64_t>(indexVal);
3271 if (timelineDb.get(txn, evId, temp)) {
3272 return std::pair{idx, evId};
3273 }
3274 } while (cursor.get(indexVal, event_id, MDB_PREV));
3275 }
3276
3277 return std::pair{idx, evId};
3278 } catch (lmdb::runtime_error &e) {
3279 nhlog::db()->error("Failed to get last visible event after {}", event_id, e.what());
3280 return {};
3281 }
3282 }
3283
3284 std::optional<std::string>
3285 Cache::getTimelineEventId(const std::string &room_id, uint64_t index)
3286 {
3287 auto txn = ro_txn(db->env_);
3288 lmdb::dbi orderDb;
3289 try {
3290 orderDb = getOrderToMessageDb(txn, room_id);
3291 } catch (lmdb::runtime_error &e) {
3292 nhlog::db()->error(
3293 "Can't open db for room '{}', probably doesn't exist yet. ({})", room_id, e.what());
3294 return {};
3295 }
3296
3297 std::string_view val;
3298
3299 bool success = orderDb.get(txn, lmdb::to_sv(index), val);
3300 if (!success) {
3301 return {};
3302 }
3303
3304 return std::string(val);
3305 }
3306
3307 QHash<QString, RoomInfo>
3308 Cache::invites()
3309 {
3310 QHash<QString, RoomInfo> result;
3311
3312 auto txn = ro_txn(db->env_);
3313 auto cursor = lmdb::cursor::open(txn, db->invites);
3314
3315 std::string_view room_id, room_data;
3316
3317 while (cursor.get(room_id, room_data, MDB_NEXT)) {
3318 try {
3319 RoomInfo tmp = nlohmann::json::parse(room_data).get<RoomInfo>();
3320 tmp.member_count = getInviteMembersDb(txn, std::string(room_id)).size(txn);
3321 result.insert(QString::fromStdString(std::string(room_id)), std::move(tmp));
3322 } catch (const nlohmann::json::exception &e) {
3323 nhlog::db()->warn("failed to parse room info for invite: "
3324 "room_id ({}), {}: {}",
3325 room_id,
3326 std::string(room_data),
3327 e.what());
3328 }
3329 }
3330
3331 cursor.close();
3332
3333 return result;
3334 }
3335
3336 std::optional<RoomInfo>
3337 Cache::invite(std::string_view roomid)
3338 {
3339 std::optional<RoomInfo> result;
3340
3341 auto txn = ro_txn(db->env_);
3342
3343 std::string_view room_data;
3344
3345 if (db->invites.get(txn, roomid, room_data)) {
3346 try {
3347 RoomInfo tmp = nlohmann::json::parse(room_data).get<RoomInfo>();
3348 tmp.member_count = getInviteMembersDb(txn, std::string(roomid)).size(txn);
3349 result = std::move(tmp);
3350 } catch (const nlohmann::json::exception &e) {
3351 nhlog::db()->warn("failed to parse room info for invite: "
3352 "room_id ({}), {}: {}",
3353 roomid,
3354 std::string(room_data),
3355 e.what());
3356 }
3357 }
3358
3359 return result;
3360 }
3361
3362 QString
3363 Cache::getRoomAvatarUrl(lmdb::txn &txn, lmdb::dbi &statesdb, lmdb::dbi &membersdb)
3364 {
3365 using namespace mtx::events;
3366 using namespace mtx::events::state;
3367
3368 std::string_view event;
3369 bool res = statesdb.get(txn, to_string(mtx::events::EventType::RoomAvatar), event);
3370
3371 if (res) {
3372 try {
3373 StateEvent<Avatar> msg =
3374 nlohmann::json::parse(std::string_view(event.data(), event.size()))
3375 .get<StateEvent<Avatar>>();
3376
3377 if (!msg.content.url.empty())
3378 return QString::fromStdString(msg.content.url);
3379 } catch (const nlohmann::json::exception &e) {
3380 nhlog::db()->warn("failed to parse m.room.avatar event: {}", e.what());
3381 }
3382 }
3383
3384 // We don't use an avatar for group chats.
3385 if (membersdb.size(txn) > 2)
3386 return QString();
3387
3388 auto cursor = lmdb::cursor::open(txn, membersdb);
3389 std::string_view user_id;
3390 std::string_view member_data;
3391 std::string fallback_url;
3392
3393 // Resolve avatar for 1-1 chats.
3394 while (cursor.get(user_id, member_data, MDB_NEXT)) {
3395 try {
3396 MemberInfo m = nlohmann::json::parse(member_data).get<MemberInfo>();
3397 if (user_id == localUserId_.toStdString()) {
3398 fallback_url = m.avatar_url;
3399 continue;
3400 }
3401
3402 cursor.close();
3403 return QString::fromStdString(m.avatar_url);
3404 } catch (const nlohmann::json::exception &e) {
3405 nhlog::db()->warn("failed to parse member info: {}", e.what());
3406 }
3407 }
3408
3409 cursor.close();
3410
3411 // Default case when there is only one member.
3412 return QString::fromStdString(fallback_url);
3413 }
3414
3415 QString
3416 Cache::getRoomName(lmdb::txn &txn, lmdb::dbi &statesdb, lmdb::dbi &membersdb)
3417 {
3418 using namespace mtx::events;
3419 using namespace mtx::events::state;
3420
3421 std::string_view event;
3422 bool res = statesdb.get(txn, to_string(mtx::events::EventType::RoomName), event);
3423
3424 if (res) {
3425 try {
3426 StateEvent<Name> msg =
3427 nlohmann::json::parse(std::string_view(event.data(), event.size()))
3428 .get<StateEvent<Name>>();
3429
3430 if (!msg.content.name.empty())
3431 return QString::fromStdString(msg.content.name);
3432 } catch (const nlohmann::json::exception &e) {
3433 nhlog::db()->warn("failed to parse m.room.name event: {}", e.what());
3434 }
3435 }
3436
3437 res = statesdb.get(txn, to_string(mtx::events::EventType::RoomCanonicalAlias), event);
3438
3439 if (res) {
3440 try {
3441 StateEvent<CanonicalAlias> msg =
3442 nlohmann::json::parse(std::string_view(event.data(), event.size()))
3443 .get<StateEvent<CanonicalAlias>>();
3444
3445 if (!msg.content.alias.empty())
3446 return QString::fromStdString(msg.content.alias);
3447 } catch (const nlohmann::json::exception &e) {
3448 nhlog::db()->warn("failed to parse m.room.canonical_alias event: {}", e.what());
3449 }
3450 }
3451
3452 auto cursor = lmdb::cursor::open(txn, membersdb);
3453 const auto total = membersdb.size(txn);
3454
3455 std::size_t ii = 0;
3456 std::string_view user_id;
3457 std::string_view member_data;
3458 std::map<std::string, MemberInfo> members;
3459
3460 while (cursor.get(user_id, member_data, MDB_NEXT) && ii < 3) {
3461 try {
3462 members.emplace(user_id, nlohmann::json::parse(member_data).get<MemberInfo>());
3463 } catch (const nlohmann::json::exception &e) {
3464 nhlog::db()->warn("failed to parse member info: {}", e.what());
3465 }
3466
3467 ii++;
3468 }
3469
3470 cursor.close();
3471
3472 if (total == 1 && !members.empty())
3473 return QString::fromStdString(members.begin()->second.name);
3474
3475 auto first_member = [&members, this]() {
3476 for (const auto &m : members) {
3477 if (m.first != localUserId_.toStdString())
3478 return QString::fromStdString(m.second.name);
3479 }
3480
3481 return localUserId_;
3482 }();
3483 auto second_member = [&members, this]() {
3484 bool first = true;
3485 for (const auto &m : members) {
3486 if (m.first != localUserId_.toStdString()) {
3487 if (first)
3488 first = false;
3489 else
3490 return QString::fromStdString(m.second.name);
3491 }
3492 }
3493
3494 return localUserId_;
3495 }();
3496
3497 if (total == 2)
3498 return first_member;
3499 else if (total == 3)
3500 return tr("%1 and %2", "RoomName").arg(first_member, second_member);
3501 else if (total > 3)
3502 return tr("%1 and %n other(s)", "", (int)total - 2).arg(first_member);
3503
3504 return tr("Empty Room");
3505 }
3506
3507 mtx::events::state::JoinRule
3508 Cache::getRoomJoinRule(lmdb::txn &txn, lmdb::dbi &statesdb)
3509 {
3510 using namespace mtx::events;
3511 using namespace mtx::events::state;
3512
3513 std::string_view event;
3514 bool res = statesdb.get(txn, to_string(mtx::events::EventType::RoomJoinRules), event);
3515
3516 if (res) {
3517 try {
3518 StateEvent<state::JoinRules> msg =
3519 nlohmann::json::parse(event).get<StateEvent<state::JoinRules>>();
3520 return msg.content.join_rule;
3521 } catch (const nlohmann::json::exception &e) {
3522 nhlog::db()->warn("failed to parse m.room.join_rule event: {}", e.what());
3523 }
3524 }
3525 return state::JoinRule::Knock;
3526 }
3527
3528 bool
3529 Cache::getRoomGuestAccess(lmdb::txn &txn, lmdb::dbi &statesdb)
3530 {
3531 using namespace mtx::events;
3532 using namespace mtx::events::state;
3533
3534 std::string_view event;
3535 bool res = statesdb.get(txn, to_string(mtx::events::EventType::RoomGuestAccess), event);
3536
3537 if (res) {
3538 try {
3539 StateEvent<GuestAccess> msg =
3540 nlohmann::json::parse(event).get<StateEvent<GuestAccess>>();
3541 return msg.content.guest_access == AccessState::CanJoin;
3542 } catch (const nlohmann::json::exception &e) {
3543 nhlog::db()->warn("failed to parse m.room.guest_access event: {}", e.what());
3544 }
3545 }
3546 return false;
3547 }
3548
3549 QString
3550 Cache::getRoomTopic(lmdb::txn &txn, lmdb::dbi &statesdb)
3551 {
3552 using namespace mtx::events;
3553 using namespace mtx::events::state;
3554
3555 std::string_view event;
3556 bool res = statesdb.get(txn, to_string(mtx::events::EventType::RoomTopic), event);
3557
3558 if (res) {
3559 try {
3560 StateEvent<Topic> msg = nlohmann::json::parse(event).get<StateEvent<Topic>>();
3561
3562 if (!msg.content.topic.empty())
3563 return QString::fromStdString(msg.content.topic);
3564 } catch (const nlohmann::json::exception &e) {
3565 nhlog::db()->warn("failed to parse m.room.topic event: {}", e.what());
3566 }
3567 }
3568
3569 return QString();
3570 }
3571
3572 QString
3573 Cache::getRoomVersion(lmdb::txn &txn, lmdb::dbi &statesdb)
3574 {
3575 using namespace mtx::events;
3576 using namespace mtx::events::state;
3577
3578 std::string_view event;
3579 bool res = statesdb.get(txn, to_string(mtx::events::EventType::RoomCreate), event);
3580
3581 if (res) {
3582 try {
3583 StateEvent<Create> msg = nlohmann::json::parse(event).get<StateEvent<Create>>();
3584
3585 if (!msg.content.room_version.empty())
3586 return QString::fromStdString(msg.content.room_version);
3587 } catch (const nlohmann::json::exception &e) {
3588 nhlog::db()->warn("failed to parse m.room.create event: {}", e.what());
3589 }
3590 }
3591
3592 nhlog::db()->warn("m.room.create event is missing room version, assuming version \"1\"");
3593 return QStringLiteral("1");
3594 }
3595
3596 bool
3597 Cache::getRoomIsSpace(lmdb::txn &txn, lmdb::dbi &statesdb)
3598 {
3599 using namespace mtx::events;
3600 using namespace mtx::events::state;
3601
3602 std::string_view event;
3603 bool res = statesdb.get(txn, to_string(mtx::events::EventType::RoomCreate), event);
3604
3605 if (res) {
3606 try {
3607 StateEvent<Create> msg = nlohmann::json::parse(event).get<StateEvent<Create>>();
3608
3609 return msg.content.type == mtx::events::state::room_type::space;
3610 } catch (const nlohmann::json::exception &e) {
3611 nhlog::db()->warn("failed to parse m.room.create event: {}", e.what());
3612 }
3613 }
3614
3615 nhlog::db()->warn("m.room.create event is missing room version, assuming version \"1\"");
3616 return false;
3617 }
3618
3619 bool
3620 Cache::getRoomIsTombstoned(lmdb::txn &txn, lmdb::dbi &statesdb)
3621 {
3622 using namespace mtx::events;
3623 using namespace mtx::events::state;
3624
3625 std::string_view event;
3626 bool res = statesdb.get(txn, to_string(mtx::events::EventType::RoomCreate), event);
3627
3628 if (res) {
3629 try {
3630 StateEvent<Tombstone> msg = nlohmann::json::parse(event).get<StateEvent<Tombstone>>();
3631
3632 return true;
3633 } catch (const nlohmann::json::exception &e) {
3634 nhlog::db()->warn("failed to parse m.room.tombstone event: {}", e.what());
3635 }
3636 }
3637
3638 return false;
3639 }
3640
3641 QString
3642 Cache::getInviteRoomName(lmdb::txn &txn, lmdb::dbi &statesdb, lmdb::dbi &membersdb)
3643 {
3644 using namespace mtx::events;
3645 using namespace mtx::events::state;
3646
3647 std::string_view event;
3648 bool res = statesdb.get(txn, to_string(mtx::events::EventType::RoomName), event);
3649
3650 if (res) {
3651 try {
3652 StrippedEvent<state::Name> msg =
3653 nlohmann::json::parse(event).get<StrippedEvent<state::Name>>();
3654 return QString::fromStdString(msg.content.name);
3655 } catch (const nlohmann::json::exception &e) {
3656 nhlog::db()->warn("failed to parse m.room.name event: {}", e.what());
3657 }
3658 }
3659
3660 auto cursor = lmdb::cursor::open(txn, membersdb);
3661 std::string_view user_id, member_data;
3662
3663 while (cursor.get(user_id, member_data, MDB_NEXT)) {
3664 if (user_id == localUserId_.toStdString())
3665 continue;
3666
3667 try {
3668 MemberInfo tmp = nlohmann::json::parse(member_data).get<MemberInfo>();
3669 cursor.close();
3670
3671 return QString::fromStdString(tmp.name);
3672 } catch (const nlohmann::json::exception &e) {
3673 nhlog::db()->warn("failed to parse member info: {}", e.what());
3674 }
3675 }
3676
3677 cursor.close();
3678
3679 return tr("Empty Room");
3680 }
3681
3682 QString
3683 Cache::getInviteRoomAvatarUrl(lmdb::txn &txn, lmdb::dbi &statesdb, lmdb::dbi &membersdb)
3684 {
3685 using namespace mtx::events;
3686 using namespace mtx::events::state;
3687
3688 std::string_view event;
3689 bool res = statesdb.get(txn, to_string(mtx::events::EventType::RoomAvatar), event);
3690
3691 if (res) {
3692 try {
3693 StrippedEvent<state::Avatar> msg =
3694 nlohmann::json::parse(event).get<StrippedEvent<state::Avatar>>();
3695 return QString::fromStdString(msg.content.url);
3696 } catch (const nlohmann::json::exception &e) {
3697 nhlog::db()->warn("failed to parse m.room.avatar event: {}", e.what());
3698 }
3699 }
3700
3701 auto cursor = lmdb::cursor::open(txn, membersdb);
3702 std::string_view user_id, member_data;
3703
3704 while (cursor.get(user_id, member_data, MDB_NEXT)) {
3705 if (user_id == localUserId_.toStdString())
3706 continue;
3707
3708 try {
3709 MemberInfo tmp = nlohmann::json::parse(member_data).get<MemberInfo>();
3710 cursor.close();
3711
3712 return QString::fromStdString(tmp.avatar_url);
3713 } catch (const nlohmann::json::exception &e) {
3714 nhlog::db()->warn("failed to parse member info: {}", e.what());
3715 }
3716 }
3717
3718 cursor.close();
3719
3720 return QString();
3721 }
3722
3723 QString
3724 Cache::getInviteRoomTopic(lmdb::txn &txn, lmdb::dbi &db_)
3725 {
3726 using namespace mtx::events;
3727 using namespace mtx::events::state;
3728
3729 std::string_view event;
3730 bool res = db_.get(txn, to_string(mtx::events::EventType::RoomTopic), event);
3731
3732 if (res) {
3733 try {
3734 StrippedEvent<Topic> msg = nlohmann::json::parse(event).get<StrippedEvent<Topic>>();
3735 return QString::fromStdString(msg.content.topic);
3736 } catch (const nlohmann::json::exception &e) {
3737 nhlog::db()->warn("failed to parse m.room.topic event: {}", e.what());
3738 }
3739 }
3740
3741 return QString();
3742 }
3743
3744 bool
3745 Cache::getInviteRoomIsSpace(lmdb::txn &txn, lmdb::dbi &db_)
3746 {
3747 using namespace mtx::events;
3748 using namespace mtx::events::state;
3749
3750 std::string_view event;
3751 bool res = db_.get(txn, to_string(mtx::events::EventType::RoomCreate), event);
3752
3753 if (res) {
3754 try {
3755 StrippedEvent<Create> msg = nlohmann::json::parse(event).get<StrippedEvent<Create>>();
3756 return msg.content.type == mtx::events::state::room_type::space;
3757 } catch (const nlohmann::json::exception &e) {
3758 nhlog::db()->warn("failed to parse m.room.topic event: {}", e.what());
3759 }
3760 }
3761
3762 return false;
3763 }
3764
3765 std::vector<std::string>
3766 Cache::joinedRooms()
3767 {
3768 auto txn = ro_txn(db->env_);
3769 auto roomsCursor = lmdb::cursor::open(txn, db->rooms);
3770
3771 std::string_view id, data;
3772 std::vector<std::string> room_ids;
3773
3774 // Gather the room ids for the joined rooms.
3775 while (roomsCursor.get(id, data, MDB_NEXT))
3776 room_ids.emplace_back(id);
3777
3778 roomsCursor.close();
3779
3780 return room_ids;
3781 }
3782
3783 std::map<std::string, RoomInfo>
3784 Cache::getCommonRooms(const std::string &user_id)
3785 {
3786 std::map<std::string, RoomInfo> result;
3787
3788 auto txn = ro_txn(db->env_);
3789
3790 std::string_view room_id;
3791 std::string_view room_data;
3792 std::string_view member_info;
3793
3794 auto roomsCursor = lmdb::cursor::open(txn, db->rooms);
3795 while (roomsCursor.get(room_id, room_data, MDB_NEXT)) {
3796 try {
3797 if (getMembersDb(txn, std::string(room_id)).get(txn, user_id, member_info)) {
3798 RoomInfo tmp = nlohmann::json::parse(std::move(room_data)).get<RoomInfo>();
3799 result.emplace(std::string(room_id), std::move(tmp));
3800 }
3801 } catch (std::exception &e) {
3802 nhlog::db()->warn("Failed to read common room for member ({}) in room ({}): {}",
3803 user_id,
3804 room_id,
3805 e.what());
3806 }
3807 }
3808 roomsCursor.close();
3809
3810 return result;
3811 }
3812
3813 std::optional<MemberInfo>
3814 Cache::getMember(const std::string &room_id, const std::string &user_id)
3815 {
3816 if (user_id.empty() || !db->env_.handle())
3817 return std::nullopt;
3818
3819 try {
3820 auto txn = ro_txn(db->env_);
3821
3822 auto membersdb = getMembersDb(txn, room_id);
3823
3824 std::string_view info;
3825 if (membersdb.get(txn, user_id, info)) {
3826 MemberInfo m = nlohmann::json::parse(info).get<MemberInfo>();
3827 return m;
3828 }
3829 } catch (std::exception &e) {
3830 nhlog::db()->warn(
3831 "Failed to read member ({}) in room ({}): {}", user_id, room_id, e.what());
3832 }
3833 return std::nullopt;
3834 }
3835
3836 std::vector<RoomMember>
3837 Cache::getMembers(const std::string &room_id, std::size_t startIndex, std::size_t len)
3838 {
3839 try {
3840 auto txn = ro_txn(db->env_);
3841 auto db_ = getMembersDb(txn, room_id);
3842 auto cursor = lmdb::cursor::open(txn, db_);
3843
3844 std::size_t currentIndex = 0;
3845
3846 const auto endIndex = std::min(startIndex + len, db_.size(txn));
3847
3848 std::vector<RoomMember> members;
3849
3850 std::string_view user_id, user_data;
3851 while (cursor.get(user_id, user_data, MDB_NEXT)) {
3852 if (currentIndex < startIndex) {
3853 currentIndex += 1;
3854 continue;
3855 }
3856
3857 if (currentIndex >= endIndex)
3858 break;
3859
3860 try {
3861 MemberInfo tmp = nlohmann::json::parse(user_data).get<MemberInfo>();
3862 members.emplace_back(RoomMember{
3863 QString::fromStdString(std::string(user_id)),
3864 QString::fromStdString(tmp.name),
3865 QString::fromStdString(tmp.avatar_url),
3866 });
3867 } catch (const nlohmann::json::exception &e) {
3868 nhlog::db()->warn("{}", e.what());
3869 }
3870
3871 currentIndex += 1;
3872 }
3873
3874 cursor.close();
3875
3876 return members;
3877 } catch (const lmdb::error &e) {
3878 nhlog::db()->error("Failed to retrieve members from db in room {}: {}", room_id, e.what());
3879 return {};
3880 }
3881 }
3882
3883 std::optional<MemberInfo>
3884 Cache::getInviteMember(const std::string &room_id, const std::string &user_id)
3885 {
3886 if (user_id.empty() || !db->env_.handle())
3887 return std::nullopt;
3888
3889 try {
3890 auto txn = ro_txn(db->env_);
3891
3892 auto membersdb = getInviteMembersDb(txn, room_id);
3893
3894 std::string_view info;
3895 if (membersdb.get(txn, user_id, info)) {
3896 MemberInfo m = nlohmann::json::parse(info).get<MemberInfo>();
3897 return m;
3898 }
3899 } catch (std::exception &e) {
3900 nhlog::db()->warn(
3901 "Failed to read member ({}) in invite room ({}): {}", user_id, room_id, e.what());
3902 }
3903 return std::nullopt;
3904 }
3905
3906 std::vector<RoomMember>
3907 Cache::getMembersFromInvite(const std::string &room_id, std::size_t startIndex, std::size_t len)
3908 {
3909 try {
3910 auto txn = ro_txn(db->env_);
3911 std::vector<RoomMember> members;
3912
3913 auto db_ = getInviteMembersDb(txn, room_id);
3914 auto cursor = lmdb::cursor::open(txn, db_);
3915
3916 std::size_t currentIndex = 0;
3917
3918 const auto endIndex = std::min(startIndex + len, db_.size(txn));
3919
3920 std::string_view user_id, user_data;
3921 while (cursor.get(user_id, user_data, MDB_NEXT)) {
3922 if (currentIndex < startIndex) {
3923 currentIndex += 1;
3924 continue;
3925 }
3926
3927 if (currentIndex >= endIndex)
3928 break;
3929
3930 try {
3931 MemberInfo tmp = nlohmann::json::parse(user_data).get<MemberInfo>();
3932 members.emplace_back(RoomMember{
3933 QString::fromStdString(std::string(user_id)),
3934 QString::fromStdString(tmp.name),
3935 QString::fromStdString(tmp.avatar_url),
3936 tmp.is_direct,
3937 });
3938 } catch (const nlohmann::json::exception &e) {
3939 nhlog::db()->warn("{}", e.what());
3940 }
3941
3942 currentIndex += 1;
3943 }
3944
3945 cursor.close();
3946
3947 return members;
3948 } catch (const lmdb::error &e) {
3949 nhlog::db()->error("Failed to retrieve members from db in room {}: {}", room_id, e.what());
3950 return {};
3951 }
3952 }
3953
3954 bool
3955 Cache::isRoomMember(const std::string &user_id, const std::string &room_id)
3956 {
3957 try {
3958 auto txn = ro_txn(db->env_);
3959 auto db_ = getMembersDb(txn, room_id);
3960
3961 std::string_view value;
3962 bool res = db_.get(txn, user_id, value);
3963
3964 return res;
3965 } catch (std::exception &e) {
3966 nhlog::db()->warn(
3967 "Failed to read member membership ({}) in room ({}): {}", user_id, room_id, e.what());
3968 }
3969 return false;
3970 }
3971
3972 void
3973 Cache::savePendingMessage(const std::string &room_id,
3974 const mtx::events::collections::TimelineEvents &message)
3975 {
3976 auto txn = lmdb::txn::begin(db->env_);
3977 auto eventsDb = getEventsDb(txn, room_id);
3978
3979 mtx::responses::Timeline timeline;
3980 timeline.events.push_back(message);
3981 saveTimelineMessages(txn, eventsDb, room_id, timeline);
3982
3983 auto pending = getPendingMessagesDb(txn, room_id);
3984
3985 int64_t now = QDateTime::currentMSecsSinceEpoch();
3986 pending.put(txn, lmdb::to_sv(now), mtx::accessors::event_id(message));
3987
3988 txn.commit();
3989 }
3990 std::vector<std::string>
3991 Cache::pendingEvents(const std::string &room_id)
3992 {
3993 auto txn = ro_txn(db->env_);
3994 auto pending = getPendingMessagesDb(txn, room_id);
3995
3996 std::vector<std::string> related_ids;
3997
3998 try {
3999 {
4000 auto pendingCursor = lmdb::cursor::open(txn, pending);
4001 std::string_view tsIgnored, pendingTxn;
4002 while (pendingCursor.get(tsIgnored, pendingTxn, MDB_NEXT)) {
4003 related_ids.emplace_back(pendingTxn.data(), pendingTxn.size());
4004 }
4005 }
4006 } catch (const lmdb::error &e) {
4007 nhlog::db()->error("pending events error: {}", e.what());
4008 }
4009
4010 return related_ids;
4011 }
4012
4013 std::optional<mtx::events::collections::TimelineEvents>
4014 Cache::firstPendingMessage(const std::string &room_id)
4015 {
4016 auto txn = lmdb::txn::begin(db->env_);
4017 auto pending = getPendingMessagesDb(txn, room_id);
4018
4019 try {
4020 auto pendingCursor = lmdb::cursor::open(txn, pending);
4021 std::string_view tsIgnored, pendingTxn;
4022 while (pendingCursor.get(tsIgnored, pendingTxn, MDB_NEXT)) {
4023 auto eventsDb = getEventsDb(txn, room_id);
4024 std::string_view event;
4025 if (!eventsDb.get(txn, pendingTxn, event)) {
4026 pending.del(txn, tsIgnored, pendingTxn);
4027 continue;
4028 }
4029
4030 try {
4031 mtx::events::collections::TimelineEvents te =
4032 nlohmann::json::parse(event).get<mtx::events::collections::TimelineEvents>();
4033
4034 pendingCursor.close();
4035 return te;
4036 } catch (std::exception &e) {
4037 nhlog::db()->error("Failed to parse message from cache {}", e.what());
4038 pending.del(txn, tsIgnored, pendingTxn);
4039 continue;
4040 }
4041 }
4042 } catch (const lmdb::error &e) {
4043 }
4044 return std::nullopt;
4045 }
4046
4047 void
4048 Cache::removePendingStatus(const std::string &room_id, const std::string &txn_id)
4049 {
4050 auto txn = lmdb::txn::begin(db->env_);
4051 auto pending = getPendingMessagesDb(txn, room_id);
4052
4053 {
4054 auto pendingCursor = lmdb::cursor::open(txn, pending);
4055 std::string_view tsIgnored, pendingTxn;
4056 while (pendingCursor.get(tsIgnored, pendingTxn, MDB_NEXT)) {
4057 if (std::string_view(pendingTxn.data(), pendingTxn.size()) == txn_id)
4058 lmdb::cursor_del(pendingCursor);
4059 }
4060 }
4061
4062 txn.commit();
4063 }
4064
4065 void
4066 Cache::saveTimelineMessages(lmdb::txn &txn,
4067 lmdb::dbi &eventsDb,
4068 const std::string &room_id,
4069 const mtx::responses::Timeline &res)
4070 {
4071 if (res.events.empty())
4072 return;
4073
4074 auto relationsDb = getRelationsDb(txn, room_id);
4075
4076 auto orderDb = getEventOrderDb(txn, room_id);
4077 auto evToOrderDb = getEventToOrderDb(txn, room_id);
4078 auto msg2orderDb = getMessageToOrderDb(txn, room_id);
4079 auto order2msgDb = getOrderToMessageDb(txn, room_id);
4080 auto pending = getPendingMessagesDb(txn, room_id);
4081
4082 if (res.limited) {
4083 lmdb::dbi_drop(txn, orderDb, false);
4084 lmdb::dbi_drop(txn, evToOrderDb, false);
4085 lmdb::dbi_drop(txn, msg2orderDb, false);
4086 lmdb::dbi_drop(txn, order2msgDb, false);
4087 lmdb::dbi_drop(txn, pending, true);
4088 }
4089
4090 using namespace mtx::events;
4091 using namespace mtx::events::state;
4092
4093 std::string_view indexVal, val;
4094 uint64_t index = std::numeric_limits<uint64_t>::max() / 2;
4095 auto cursor = lmdb::cursor::open(txn, orderDb);
4096 if (cursor.get(indexVal, val, MDB_LAST)) {
4097 index = lmdb::from_sv<uint64_t>(indexVal);
4098 }
4099
4100 uint64_t msgIndex = std::numeric_limits<uint64_t>::max() / 2;
4101 auto msgCursor = lmdb::cursor::open(txn, order2msgDb);
4102 if (msgCursor.get(indexVal, val, MDB_LAST)) {
4103 msgIndex = lmdb::from_sv<uint64_t>(indexVal);
4104 }
4105
4106 bool first = true;
4107 for (const auto &e : res.events) {
4108 auto event = mtx::accessors::serialize_event(e);
4109 auto txn_id = mtx::accessors::transaction_id(e);
4110
4111 std::string event_id_val = event.value("event_id", "");
4112 if (event_id_val.empty()) {
4113 nhlog::db()->error("Event without id!");
4114 continue;
4115 }
4116
4117 std::string_view event_id = event_id_val;
4118
4119 nlohmann::json orderEntry = nlohmann::json::object();
4120 orderEntry["event_id"] = event_id_val;
4121 if (first && !res.prev_batch.empty())
4122 orderEntry["prev_batch"] = res.prev_batch;
4123
4124 std::string_view txn_order;
4125 if (!txn_id.empty() && evToOrderDb.get(txn, txn_id, txn_order)) {
4126 eventsDb.put(txn, event_id, event.dump());
4127 eventsDb.del(txn, txn_id);
4128
4129 std::string_view msg_txn_order;
4130 if (msg2orderDb.get(txn, txn_id, msg_txn_order)) {
4131 order2msgDb.put(txn, msg_txn_order, event_id);
4132 msg2orderDb.put(txn, event_id, msg_txn_order);
4133 msg2orderDb.del(txn, txn_id);
4134 }
4135
4136 orderDb.put(txn, txn_order, orderEntry.dump());
4137 evToOrderDb.put(txn, event_id, txn_order);
4138 evToOrderDb.del(txn, txn_id);
4139
4140 auto relations = mtx::accessors::relations(e);
4141 if (!relations.relations.empty()) {
4142 for (const auto &r : relations.relations) {
4143 if (!r.event_id.empty()) {
4144 relationsDb.del(txn, r.event_id, txn_id);
4145 relationsDb.put(txn, r.event_id, event_id);
4146 }
4147 }
4148 }
4149
4150 auto pendingCursor = lmdb::cursor::open(txn, pending);
4151 std::string_view tsIgnored, pendingTxn;
4152 while (pendingCursor.get(tsIgnored, pendingTxn, MDB_NEXT)) {
4153 if (std::string_view(pendingTxn.data(), pendingTxn.size()) == txn_id)
4154 lmdb::cursor_del(pendingCursor);
4155 }
4156 } else if (auto redaction =
4157 std::get_if<mtx::events::RedactionEvent<mtx::events::msg::Redaction>>(&e)) {
4158 if (redaction->redacts.empty())
4159 continue;
4160
4161 // persist the first redaction in case this is a limited timeline and it is the first
4162 // event to not break pagination.
4163 if (first && res.limited) {
4164 first = false;
4165 ++index;
4166
4167 nhlog::db()->debug("saving redaction '{}'", orderEntry.dump());
4168
4169 cursor.put(lmdb::to_sv(index), orderEntry.dump(), MDB_APPEND);
4170 evToOrderDb.put(txn, event_id, lmdb::to_sv(index));
4171 eventsDb.put(txn, event_id, event.dump());
4172 }
4173
4174 std::string_view oldEvent;
4175 bool success = eventsDb.get(txn, redaction->redacts, oldEvent);
4176 if (!success)
4177 continue;
4178
4179 try {
4180 auto te = nlohmann::json::parse(std::string_view(oldEvent.data(), oldEvent.size()))
4181 .get<mtx::events::collections::TimelineEvents>();
4182
4183 // overwrite the content and add redation data
4184 std::visit(
4185 [&redaction, &room_id, &txn, &eventsDb, this](auto &ev) {
4186 ev.unsigned_data.redacted_because = *redaction;
4187 ev.unsigned_data.redacted_by = redaction->event_id;
4188
4189 if constexpr (isStateEvent_<decltype(ev)>) {
4190 auto statesdb = getStatesDb(txn, room_id);
4191 auto stateskeydb = getStatesKeyDb(txn, room_id);
4192 auto membersdb = getMembersDb(txn, room_id);
4193 mtx::events::StateEvent<mtx::events::msg::Redacted> redactedEvent;
4194 redactedEvent.event_id = ev.event_id;
4195 redactedEvent.state_key = ev.state_key;
4196 redactedEvent.type = ev.type;
4197 nhlog::db()->critical("Redacting: {}",
4198 nlohmann::json(redactedEvent).dump(2));
4199
4200 saveStateEvent(txn,
4201 statesdb,
4202 stateskeydb,
4203 membersdb,
4204 eventsDb,
4205 room_id,
4206 mtx::events::collections::StateEvents{redactedEvent});
4207 }
4208 },
4209 te);
4210 event = mtx::accessors::serialize_event(te);
4211 event["content"].clear();
4212
4213 } catch (std::exception &e) {
4214 nhlog::db()->error("Failed to parse message from cache {}", e.what());
4215 continue;
4216 }
4217
4218 eventsDb.put(txn, redaction->redacts, event.dump());
4219 eventsDb.put(txn, redaction->event_id, nlohmann::json(*redaction).dump());
4220 } else {
4221 // This check protects against duplicates in the timeline. If the event_id
4222 // is already in the DB, we skip putting it (again) in ordered DBs, and only
4223 // update the event itself and its relations.
4224 std::string_view unused_read;
4225 if (!evToOrderDb.get(txn, event_id, unused_read)) {
4226 first = false;
4227
4228 ++index;
4229
4230 nhlog::db()->debug("saving '{}'", orderEntry.dump());
4231
4232 cursor.put(lmdb::to_sv(index), orderEntry.dump(), MDB_APPEND);
4233 evToOrderDb.put(txn, event_id, lmdb::to_sv(index));
4234
4235 // TODO(Nico): Allow blacklisting more event types in UI
4236 if (!isHiddenEvent(txn, e, room_id)) {
4237 ++msgIndex;
4238 msgCursor.put(lmdb::to_sv(msgIndex), event_id, MDB_APPEND);
4239
4240 msg2orderDb.put(txn, event_id, lmdb::to_sv(msgIndex));
4241 }
4242 } else {
4243 nhlog::db()->warn("duplicate event '{}'", orderEntry.dump());
4244 }
4245 eventsDb.put(txn, event_id, event.dump());
4246
4247 auto relations = mtx::accessors::relations(e);
4248 if (!relations.relations.empty()) {
4249 for (const auto &r : relations.relations) {
4250 if (!r.event_id.empty()) {
4251 relationsDb.put(txn, r.event_id, event_id);
4252 }
4253 }
4254 }
4255 }
4256 }
4257 }
4258
4259 uint64_t
4260 Cache::saveOldMessages(const std::string &room_id, const mtx::responses::Messages &res)
4261 {
4262 auto txn = lmdb::txn::begin(db->env_);
4263 auto eventsDb = getEventsDb(txn, room_id);
4264 auto relationsDb = getRelationsDb(txn, room_id);
4265
4266 auto orderDb = getEventOrderDb(txn, room_id);
4267 auto evToOrderDb = getEventToOrderDb(txn, room_id);
4268 auto msg2orderDb = getMessageToOrderDb(txn, room_id);
4269 auto order2msgDb = getOrderToMessageDb(txn, room_id);
4270
4271 std::string_view indexVal, val;
4272 uint64_t index = std::numeric_limits<uint64_t>::max() / 2;
4273 {
4274 auto cursor = lmdb::cursor::open(txn, orderDb);
4275 if (cursor.get(indexVal, val, MDB_FIRST)) {
4276 index = lmdb::from_sv<uint64_t>(indexVal);
4277 }
4278 }
4279
4280 uint64_t msgIndex = std::numeric_limits<uint64_t>::max() / 2;
4281 {
4282 auto msgCursor = lmdb::cursor::open(txn, order2msgDb);
4283 if (msgCursor.get(indexVal, val, MDB_FIRST)) {
4284 msgIndex = lmdb::from_sv<uint64_t>(indexVal);
4285 }
4286 }
4287
4288 if (res.chunk.empty()) {
4289 if (orderDb.get(txn, lmdb::to_sv(index), val)) {
4290 auto orderEntry = nlohmann::json::parse(val);
4291 orderEntry["prev_batch"] = res.end;
4292 orderDb.put(txn, lmdb::to_sv(index), orderEntry.dump());
4293 txn.commit();
4294 }
4295 return msgIndex;
4296 }
4297
4298 std::string event_id_val;
4299 for (const auto &e : res.chunk) {
4300 if (std::holds_alternative<mtx::events::RedactionEvent<mtx::events::msg::Redaction>>(e))
4301 continue;
4302
4303 auto event = mtx::accessors::serialize_event(e);
4304 event_id_val = event["event_id"].get<std::string>();
4305 std::string_view event_id = event_id_val;
4306
4307 // This check protects against duplicates in the timeline. If the event_id is
4308 // already in the DB, we skip putting it (again) in ordered DBs, and only update the
4309 // event itself and its relations.
4310 std::string_view unused_read;
4311 if (!evToOrderDb.get(txn, event_id, unused_read)) {
4312 --index;
4313
4314 nlohmann::json orderEntry = nlohmann::json::object();
4315 orderEntry["event_id"] = event_id_val;
4316
4317 orderDb.put(txn, lmdb::to_sv(index), orderEntry.dump());
4318 evToOrderDb.put(txn, event_id, lmdb::to_sv(index));
4319
4320 // TODO(Nico): Allow blacklisting more event types in UI
4321 if (!isHiddenEvent(txn, e, room_id)) {
4322 --msgIndex;
4323 order2msgDb.put(txn, lmdb::to_sv(msgIndex), event_id);
4324
4325 msg2orderDb.put(txn, event_id, lmdb::to_sv(msgIndex));
4326 }
4327 }
4328 eventsDb.put(txn, event_id, event.dump());
4329
4330 auto relations = mtx::accessors::relations(e);
4331 if (!relations.relations.empty()) {
4332 for (const auto &r : relations.relations) {
4333 if (!r.event_id.empty()) {
4334 relationsDb.put(txn, r.event_id, event_id);
4335 }
4336 }
4337 }
4338 }
4339
4340 if (!event_id_val.empty()) {
4341 nlohmann::json orderEntry = nlohmann::json::object();
4342 orderEntry["event_id"] = event_id_val;
4343 orderEntry["prev_batch"] = res.end;
4344 orderDb.put(txn, lmdb::to_sv(index), orderEntry.dump());
4345 } else if (!res.chunk.empty()) {
4346 // to not break pagination, even if all events are redactions we try to persist something in
4347 // the batch.
4348
4349 nlohmann::json orderEntry = nlohmann::json::object();
4350 event_id_val = mtx::accessors::event_id(res.chunk.back());
4351 --index;
4352
4353 auto event = mtx::accessors::serialize_event(res.chunk.back()).dump();
4354 eventsDb.put(txn, event_id_val, event);
4355 evToOrderDb.put(txn, event_id_val, lmdb::to_sv(index));
4356
4357 orderEntry["event_id"] = event_id_val;
4358 orderEntry["prev_batch"] = res.end;
4359 orderDb.put(txn, lmdb::to_sv(index), orderEntry.dump());
4360 }
4361
4362 txn.commit();
4363
4364 return msgIndex;
4365 }
4366
4367 void
4368 Cache::clearTimeline(const std::string &room_id)
4369 {
4370 auto txn = lmdb::txn::begin(db->env_);
4371 auto eventsDb = getEventsDb(txn, room_id);
4372 auto relationsDb = getRelationsDb(txn, room_id);
4373
4374 auto orderDb = getEventOrderDb(txn, room_id);
4375 auto evToOrderDb = getEventToOrderDb(txn, room_id);
4376 auto msg2orderDb = getMessageToOrderDb(txn, room_id);
4377 auto order2msgDb = getOrderToMessageDb(txn, room_id);
4378
4379 std::string_view indexVal, val;
4380 auto cursor = lmdb::cursor::open(txn, orderDb);
4381
4382 bool start = true;
4383 bool passed_pagination_token = false;
4384 while (cursor.get(indexVal, val, start ? MDB_LAST : MDB_PREV)) {
4385 start = false;
4386 nlohmann::json obj;
4387
4388 try {
4389 obj = nlohmann::json::parse(std::string_view(val.data(), val.size()));
4390 } catch (std::exception &) {
4391 // workaround bug in the initial db format, where we sometimes didn't store
4392 // json...
4393 obj = {{"event_id", std::string(val.data(), val.size())}};
4394 }
4395
4396 if (passed_pagination_token) {
4397 if (obj.count("event_id") != 0) {
4398 std::string event_id = obj["event_id"].get<std::string>();
4399
4400 if (!event_id.empty()) {
4401 evToOrderDb.del(txn, event_id);
4402 eventsDb.del(txn, event_id);
4403 relationsDb.del(txn, event_id);
4404
4405 std::string_view order{};
4406 bool exists = msg2orderDb.get(txn, event_id, order);
4407 if (exists) {
4408 order2msgDb.del(txn, order);
4409 msg2orderDb.del(txn, event_id);
4410 }
4411 }
4412 }
4413 lmdb::cursor_del(cursor);
4414 } else {
4415 if (obj.count("prev_batch") != 0)
4416 passed_pagination_token = true;
4417 }
4418 }
4419
4420 auto msgCursor = lmdb::cursor::open(txn, order2msgDb);
4421 start = true;
4422 while (msgCursor.get(indexVal, val, start ? MDB_LAST : MDB_PREV)) {
4423 start = false;
4424
4425 std::string_view eventId;
4426 bool innerStart = true;
4427 bool found = false;
4428 while (cursor.get(indexVal, eventId, innerStart ? MDB_LAST : MDB_PREV)) {
4429 innerStart = false;
4430
4431 nlohmann::json obj;
4432 try {
4433 obj = nlohmann::json::parse(std::string_view(eventId.data(), eventId.size()));
4434 } catch (std::exception &) {
4435 obj = {{"event_id", std::string(eventId.data(), eventId.size())}};
4436 }
4437
4438 if (obj["event_id"] == std::string(val.data(), val.size())) {
4439 found = true;
4440 break;
4441 }
4442 }
4443
4444 if (!found)
4445 break;
4446 }
4447
4448 if (!start) {
4449 do {
4450 lmdb::cursor_del(msgCursor);
4451 } while (msgCursor.get(indexVal, val, MDB_PREV));
4452 }
4453
4454 cursor.close();
4455 msgCursor.close();
4456 txn.commit();
4457 }
4458
4459 void
4460 Cache::markSentNotification(const std::string &event_id)
4461 {
4462 auto txn = lmdb::txn::begin(db->env_);
4463 db->notifications.put(txn, event_id, "");
4464 txn.commit();
4465 }
4466
4467 void
4468 Cache::removeReadNotification(const std::string &event_id)
4469 {
4470 auto txn = lmdb::txn::begin(db->env_);
4471
4472 db->notifications.del(txn, event_id);
4473
4474 txn.commit();
4475 }
4476
4477 bool
4478 Cache::isNotificationSent(const std::string &event_id)
4479 {
4480 auto txn = ro_txn(db->env_);
4481
4482 std::string_view value;
4483 bool res = db->notifications.get(txn, event_id, value);
4484
4485 return res;
4486 }
4487
4488 std::vector<std::string>
4489 Cache::getRoomIds(lmdb::txn &txn)
4490 {
4491 auto cursor = lmdb::cursor::open(txn, db->rooms);
4492
4493 std::vector<std::string> rooms;
4494
4495 std::string_view room_id, _unused;
4496 while (cursor.get(room_id, _unused, MDB_NEXT))
4497 rooms.emplace_back(room_id);
4498
4499 cursor.close();
4500
4501 return rooms;
4502 }
4503
4504 void
4505 Cache::deleteOldMessages()
4506 {
4507 std::string_view indexVal, val;
4508
4509 auto txn = lmdb::txn::begin(db->env_);
4510 auto room_ids = getRoomIds(txn);
4511
4512 for (const auto &room_id : room_ids) {
4513 auto orderDb = getEventOrderDb(txn, room_id);
4514 auto evToOrderDb = getEventToOrderDb(txn, room_id);
4515 auto o2m = getOrderToMessageDb(txn, room_id);
4516 auto m2o = getMessageToOrderDb(txn, room_id);
4517 auto eventsDb = getEventsDb(txn, room_id);
4518 auto relationsDb = getRelationsDb(txn, room_id);
4519 auto cursor = lmdb::cursor::open(txn, orderDb);
4520
4521 uint64_t first, last;
4522 if (cursor.get(indexVal, val, MDB_LAST)) {
4523 last = lmdb::from_sv<uint64_t>(indexVal);
4524 } else {
4525 continue;
4526 }
4527 if (cursor.get(indexVal, val, MDB_FIRST)) {
4528 first = lmdb::from_sv<uint64_t>(indexVal);
4529 } else {
4530 continue;
4531 }
4532
4533 size_t message_count = static_cast<size_t>(last - first);
4534 if (message_count < MAX_RESTORED_MESSAGES)
4535 continue;
4536
4537 bool start = true;
4538 while (cursor.get(indexVal, val, start ? MDB_FIRST : MDB_NEXT) &&
4539 message_count-- > MAX_RESTORED_MESSAGES) {
4540 start = false;
4541 auto obj = nlohmann::json::parse(std::string_view(val.data(), val.size()));
4542
4543 if (obj.count("event_id") != 0) {
4544 std::string event_id = obj["event_id"].get<std::string>();
4545 evToOrderDb.del(txn, event_id);
4546 eventsDb.del(txn, event_id);
4547
4548 relationsDb.del(txn, event_id);
4549
4550 std::string_view order{};
4551 bool exists = m2o.get(txn, event_id, order);
4552 if (exists) {
4553 o2m.del(txn, order);
4554 m2o.del(txn, event_id);
4555 }
4556 }
4557 cursor.del();
4558 }
4559 cursor.close();
4560 }
4561 txn.commit();
4562 }
4563
4564 void
4565 Cache::deleteOldData() noexcept
4566 {
4567 try {
4568 deleteOldMessages();
4569 } catch (const lmdb::error &e) {
4570 nhlog::db()->error("failed to delete old messages: {}", e.what());
4571 }
4572 }
4573
4574 void
4575 Cache::updateSpaces(lmdb::txn &txn,
4576 const std::set<std::string> &spaces_with_updates,
4577 std::set<std::string> rooms_with_updates)
4578 {
4579 if (spaces_with_updates.empty() && rooms_with_updates.empty())
4580 return;
4581
4582 for (const auto &space : spaces_with_updates) {
4583 // delete old entries
4584 {
4585 auto cursor = lmdb::cursor::open(txn, db->spacesChildren);
4586 bool first = true;
4587 std::string_view sp = space, space_child = "";
4588
4589 if (cursor.get(sp, space_child, MDB_SET)) {
4590 while (cursor.get(sp, space_child, first ? MDB_FIRST_DUP : MDB_NEXT_DUP)) {
4591 first = false;
4592 db->spacesParents.del(txn, space_child, space);
4593 }
4594 }
4595 cursor.close();
4596 db->spacesChildren.del(txn, space);
4597 }
4598
4599 for (const auto &event :
4600 getStateEventsWithType<mtx::events::state::space::Child>(txn, space)) {
4601 if (event.content.via.has_value() && event.state_key.size() > 3 &&
4602 event.state_key.at(0) == '!') {
4603 db->spacesChildren.put(txn, space, event.state_key);
4604 db->spacesParents.put(txn, event.state_key, space);
4605 }
4606 }
4607
4608 for (const auto &r : getRoomIds(txn)) {
4609 if (auto parent = getStateEvent<mtx::events::state::space::Parent>(txn, r, space)) {
4610 rooms_with_updates.insert(r);
4611 }
4612 }
4613 }
4614
4615 const auto space_event_type = to_string(mtx::events::EventType::SpaceChild);
4616
4617 for (const auto &room : rooms_with_updates) {
4618 for (const auto &event :
4619 getStateEventsWithType<mtx::events::state::space::Parent>(txn, room)) {
4620 if (event.content.via.has_value() && event.state_key.size() > 3 &&
4621 event.state_key.at(0) == '!') {
4622 const std::string &space = event.state_key;
4623
4624 auto pls = getStateEvent<mtx::events::state::PowerLevels>(txn, space);
4625
4626 if (!pls)
4627 continue;
4628
4629 if (pls->content.user_level(event.sender) >=
4630 pls->content.state_level(space_event_type)) {
4631 db->spacesChildren.put(txn, space, room);
4632 db->spacesParents.put(txn, room, space);
4633 } else {
4634 nhlog::db()->debug("Skipping {} in {} because of missing PL. {}: {} < {}",
4635 room,
4636 space,
4637 event.sender,
4638 pls->content.user_level(event.sender),
4639 pls->content.state_level(space_event_type));
4640 }
4641 }
4642 }
4643 }
4644 }
4645
4646 QMap<QString, std::optional<RoomInfo>>
4647 Cache::spaces()
4648 {
4649 auto txn = ro_txn(db->env_);
4650
4651 QMap<QString, std::optional<RoomInfo>> ret;
4652 {
4653 auto cursor = lmdb::cursor::open(txn, db->spacesChildren);
4654 bool first = true;
4655 std::string_view space_id, space_child;
4656 while (cursor.get(space_id, space_child, first ? MDB_FIRST : MDB_NEXT)) {
4657 first = false;
4658
4659 if (!space_child.empty()) {
4660 std::string_view room_data;
4661 if (db->rooms.get(txn, space_id, room_data)) {
4662 RoomInfo tmp = nlohmann::json::parse(std::move(room_data)).get<RoomInfo>();
4663 ret.insert(QString::fromUtf8(space_id.data(), (int)space_id.size()), tmp);
4664 } else {
4665 ret.insert(QString::fromUtf8(space_id.data(), (int)space_id.size()),
4666 std::nullopt);
4667 }
4668 }
4669 }
4670 cursor.close();
4671 }
4672
4673 return ret;
4674 }
4675
4676 std::vector<std::string>
4677 Cache::getParentRoomIds(const std::string &room_id)
4678 {
4679 auto txn = ro_txn(db->env_);
4680
4681 std::vector<std::string> roomids;
4682 {
4683 auto cursor = lmdb::cursor::open(txn, db->spacesParents);
4684 bool first = true;
4685 std::string_view sp = room_id, space_parent;
4686 if (cursor.get(sp, space_parent, MDB_SET)) {
4687 while (cursor.get(sp, space_parent, first ? MDB_FIRST_DUP : MDB_NEXT_DUP)) {
4688 first = false;
4689
4690 if (!space_parent.empty())
4691 roomids.emplace_back(space_parent);
4692 }
4693 }
4694 cursor.close();
4695 }
4696
4697 return roomids;
4698 }
4699
4700 std::vector<std::string>
4701 Cache::getChildRoomIds(const std::string &room_id)
4702 {
4703 auto txn = ro_txn(db->env_);
4704
4705 std::vector<std::string> roomids;
4706 {
4707 auto cursor = lmdb::cursor::open(txn, db->spacesChildren);
4708 bool first = true;
4709 std::string_view sp = room_id, space_child;
4710 if (cursor.get(sp, space_child, MDB_SET)) {
4711 while (cursor.get(sp, space_child, first ? MDB_FIRST_DUP : MDB_NEXT_DUP)) {
4712 first = false;
4713
4714 if (!space_child.empty())
4715 roomids.emplace_back(space_child);
4716 }
4717 }
4718 cursor.close();
4719 }
4720
4721 return roomids;
4722 }
4723
4724 std::vector<ImagePackInfo>
4725 Cache::getImagePacks(const std::string &room_id, std::optional<bool> stickers)
4726 {
4727 auto txn = ro_txn(db->env_);
4728 std::vector<ImagePackInfo> infos;
4729
4730 auto addPack = [&infos, stickers](const mtx::events::msc2545::ImagePack &pack,
4731 const std::string &source_room,
4732 const std::string &state_key,
4733 bool from_space) {
4734 bool pack_is_sticker = pack.pack ? pack.pack->is_sticker() : true;
4735 bool pack_is_emoji = pack.pack ? pack.pack->is_emoji() : true;
4736 bool pack_matches =
4737 !stickers.has_value() || (stickers.value() ? pack_is_sticker : pack_is_emoji);
4738
4739 ImagePackInfo info;
4740 info.source_room = source_room;
4741 info.state_key = state_key;
4742 info.pack.pack = pack.pack;
4743 info.from_space = from_space;
4744
4745 for (const auto &img : pack.images) {
4746 if (stickers.has_value() &&
4747 (img.second.overrides_usage()
4748 ? (stickers.value() ? !img.second.is_sticker() : !img.second.is_emoji())
4749 : !pack_matches))
4750 continue;
4751
4752 info.pack.images.insert(img);
4753 }
4754
4755 if (!info.pack.images.empty())
4756 infos.push_back(std::move(info));
4757 };
4758
4759 // packs from account data
4760 if (auto accountpack =
4761 getAccountData(txn, mtx::events::EventType::ImagePackInAccountData, "")) {
4762 auto tmp =
4763 std::get_if<mtx::events::EphemeralEvent<mtx::events::msc2545::ImagePack>>(&*accountpack);
4764 if (tmp)
4765 addPack(tmp->content, "", "", false);
4766 }
4767
4768 // packs from rooms, that were enabled globally
4769 if (auto roomPacks = getAccountData(txn, mtx::events::EventType::ImagePackRooms, "")) {
4770 auto tmp = std::get_if<mtx::events::EphemeralEvent<mtx::events::msc2545::ImagePackRooms>>(
4771 &*roomPacks);
4772 if (tmp) {
4773 for (const auto &[room_id2, state_to_d] : tmp->content.rooms) {
4774 // don't add stickers from this room twice
4775 if (room_id2 == room_id)
4776 continue;
4777
4778 for (const auto &[state_id, d] : state_to_d) {
4779 (void)d;
4780 if (auto pack =
4781 getStateEvent<mtx::events::msc2545::ImagePack>(txn, room_id2, state_id))
4782 addPack(pack->content, room_id2, state_id, false);
4783 }
4784 }
4785 }
4786 }
4787
4788 std::function<void(const std::string &room_id)> addRoomAndCanonicalParents;
4789 std::unordered_set<std::string> visitedRooms;
4790 addRoomAndCanonicalParents =
4791 [this, &addRoomAndCanonicalParents, &addPack, &visitedRooms, &txn, &room_id](
4792 const std::string &current_room) {
4793 if (visitedRooms.count(current_room))
4794 return;
4795 else
4796 visitedRooms.insert(current_room);
4797
4798 if (auto pack = getStateEvent<mtx::events::msc2545::ImagePack>(txn, current_room)) {
4799 addPack(pack->content, current_room, "", current_room != room_id);
4800 }
4801 for (const auto &pack :
4802 getStateEventsWithType<mtx::events::msc2545::ImagePack>(txn, current_room)) {
4803 addPack(pack.content, current_room, pack.state_key, current_room != room_id);
4804 }
4805
4806 for (const auto &parent :
4807 getStateEventsWithType<mtx::events::state::space::Parent>(txn, current_room)) {
4808 if (parent.content.canonical && parent.content.via && !parent.content.via->empty()) {
4809 try {
4810 addRoomAndCanonicalParents(parent.state_key);
4811 } catch (const lmdb::error &) {
4812 nhlog::db()->debug("Skipping events from parent community, because we are "
4813 "not joined to it: {}",
4814 parent.state_key);
4815 }
4816 }
4817 }
4818 };
4819
4820 // packs from current room and then iterate canonical space parents
4821 addRoomAndCanonicalParents(room_id);
4822
4823 return infos;
4824 }
4825
4826 std::optional<mtx::events::collections::RoomAccountDataEvents>
4827 Cache::getAccountData(mtx::events::EventType type, const std::string &room_id)
4828 {
4829 auto txn = ro_txn(db->env_);
4830 return getAccountData(txn, type, room_id);
4831 }
4832
4833 std::optional<mtx::events::collections::RoomAccountDataEvents>
4834 Cache::getAccountData(lmdb::txn &txn, mtx::events::EventType type, const std::string &room_id)
4835 {
4836 try {
4837 auto db_ = getAccountDataDb(txn, room_id);
4838
4839 std::string_view data;
4840 if (db_.get(txn, to_string(type), data)) {
4841 mtx::responses::utils::RoomAccountDataEvents events;
4842 nlohmann::json j = nlohmann::json::array({
4843 nlohmann::json::parse(data),
4844 });
4845 mtx::responses::utils::parse_room_account_data_events(j, events);
4846 if (events.size() == 1)
4847 return events.front();
4848 }
4849 } catch (...) {
4850 }
4851 return std::nullopt;
4852 }
4853
4854 bool
4855 Cache::hasEnoughPowerLevel(const std::vector<mtx::events::EventType> &eventTypes,
4856 const std::string &room_id,
4857 const std::string &user_id)
4858 {
4859 using namespace mtx::events;
4860 using namespace mtx::events::state;
4861
4862 auto txn = ro_txn(db->env_);
4863 try {
4864 auto db_ = getStatesDb(txn, room_id);
4865
4866 int64_t min_event_level = std::numeric_limits<int64_t>::max();
4867 int64_t user_level = std::numeric_limits<int64_t>::min();
4868
4869 std::string_view event;
4870 bool res = db_.get(txn, to_string(EventType::RoomPowerLevels), event);
4871
4872 if (res) {
4873 try {
4874 StateEvent<PowerLevels> msg =
4875 nlohmann::json::parse(std::string_view(event.data(), event.size()))
4876 .get<StateEvent<PowerLevels>>();
4877
4878 user_level = msg.content.user_level(user_id);
4879
4880 for (const auto &ty : eventTypes)
4881 min_event_level =
4882 std::min(min_event_level, msg.content.state_level(to_string(ty)));
4883 } catch (const nlohmann::json::exception &e) {
4884 nhlog::db()->warn("failed to parse m.room.power_levels event: {}", e.what());
4885 }
4886 }
4887
4888 return user_level >= min_event_level;
4889 } catch (...) {
4890 return false;
4891 }
4892 }
4893
4894 std::vector<std::string>
4895 Cache::roomMembers(const std::string &room_id)
4896 {
4897 auto txn = ro_txn(db->env_);
4898
4899 try {
4900 std::vector<std::string> members;
4901 std::string_view user_id, unused;
4902
4903 auto db_ = getMembersDb(txn, room_id);
4904
4905 auto cursor = lmdb::cursor::open(txn, db_);
4906 while (cursor.get(user_id, unused, MDB_NEXT))
4907 members.emplace_back(user_id);
4908 cursor.close();
4909
4910 return members;
4911 } catch (const lmdb::error &e) {
4912 nhlog::db()->error("Failed to retrieve members from db in room {}: {}", room_id, e.what());
4913 return {};
4914 }
4915 }
4916
4917 crypto::Trust
4918 Cache::roomVerificationStatus(const std::string &room_id)
4919 {
4920 crypto::Trust trust = crypto::Verified;
4921
4922 try {
4923 auto txn = lmdb::txn::begin(db->env_);
4924
4925 auto db_ = getMembersDb(txn, room_id);
4926 auto keysDb = getUserKeysDb(txn);
4927 std::vector<std::string> keysToRequest;
4928
4929 std::string_view user_id, unused;
4930 auto cursor = lmdb::cursor::open(txn, db_);
4931 while (cursor.get(user_id, unused, MDB_NEXT)) {
4932 auto verif = verificationStatus_(std::string(user_id), txn);
4933 if (verif.unverified_device_count) {
4934 trust = crypto::Unverified;
4935 if (verif.verified_devices.empty() && verif.no_keys) {
4936 // we probably don't have the keys yet, so query them
4937 keysToRequest.push_back(std::string(user_id));
4938 }
4939 } else if (verif.user_verified == crypto::TOFU && trust == crypto::Verified)
4940 trust = crypto::TOFU;
4941 }
4942
4943 if (!keysToRequest.empty()) {
4944 std::string_view token;
4945
4946 bool result = this->db->syncState.get(txn, NEXT_BATCH_KEY, token);
4947
4948 if (!result)
4949 token = "";
4950 markUserKeysOutOfDate(txn, keysDb, keysToRequest, std::string(token));
4951 }
4952
4953 } catch (std::exception &e) {
4954 nhlog::db()->error("Failed to calculate verification status for {}: {}", room_id, e.what());
4955 trust = crypto::Unverified;
4956 }
4957
4958 return trust;
4959 }
4960
4961 std::map<std::string, std::optional<UserKeyCache>>
4962 Cache::getMembersWithKeys(const std::string &room_id, bool verified_only)
4963 {
4964 std::string_view keys;
4965
4966 try {
4967 auto txn = ro_txn(db->env_);
4968 std::map<std::string, std::optional<UserKeyCache>> members;
4969
4970 auto db_ = getMembersDb(txn, room_id);
4971 auto keysDb = getUserKeysDb(txn);
4972
4973 std::string_view user_id, unused;
4974 auto cursor = lmdb::cursor::open(txn, db_);
4975 while (cursor.get(user_id, unused, MDB_NEXT)) {
4976 auto res = keysDb.get(txn, user_id, keys);
4977
4978 if (res) {
4979 auto k = nlohmann::json::parse(keys).get<UserKeyCache>();
4980 if (verified_only) {
4981 auto verif = verificationStatus_(std::string(user_id), txn);
4982
4983 if (verif.user_verified == crypto::Trust::Verified ||
4984 !verif.verified_devices.empty()) {
4985 auto keyCopy = k;
4986 keyCopy.device_keys.clear();
4987
4988 std::copy_if(
4989 k.device_keys.begin(),
4990 k.device_keys.end(),
4991 std::inserter(keyCopy.device_keys, keyCopy.device_keys.end()),
4992 [&verif](const auto &key) {
4993 auto curve25519 = key.second.keys.find("curve25519:" + key.first);
4994 if (curve25519 == key.second.keys.end())
4995 return false;
4996 if (auto t = verif.verified_device_keys.find(curve25519->second);
4997 t == verif.verified_device_keys.end() ||
4998 t->second != crypto::Trust::Verified)
4999 return false;
5000
5001 return key.first == key.second.device_id &&
5002 std::find(verif.verified_devices.begin(),
5003 verif.verified_devices.end(),
5004 key.first) != verif.verified_devices.end();
5005 });
5006
5007 if (!keyCopy.device_keys.empty())
5008 members[std::string(user_id)] = std::move(keyCopy);
5009 }
5010 } else {
5011 members[std::string(user_id)] = std::move(k);
5012 }
5013 } else {
5014 if (!verified_only)
5015 members[std::string(user_id)] = {};
5016 }
5017 }
5018 cursor.close();
5019
5020 return members;
5021 } catch (std::exception &e) {
5022 nhlog::db()->debug("Error retrieving members: {}", e.what());
5023 return {};
5024 }
5025 }
5026
5027 QString
5028 Cache::displayName(const QString &room_id, const QString &user_id)
5029 {
5030 return QString::fromStdString(displayName(room_id.toStdString(), user_id.toStdString()));
5031 }
5032
5033 static bool
5034 isDisplaynameSafe(const std::string &s)
5035 {
5036 const auto str = QString::fromStdString(s);
5037
5038 for (QChar c : str) {
5039 if (c.isPrint() && !c.isSpace())
5040 return false;
5041 }
5042
5043 return true;
5044 }
5045
5046 std::string
5047 Cache::displayName(const std::string &room_id, const std::string &user_id)
5048 {
5049 if (auto info = getMember(room_id, user_id); info && !isDisplaynameSafe(info->name))
5050 return info->name;
5051
5052 return user_id;
5053 }
5054
5055 QString
5056 Cache::avatarUrl(const QString &room_id, const QString &user_id)
5057 {
5058 if (auto info = getMember(room_id.toStdString(), user_id.toStdString());
5059 info && !info->avatar_url.empty())
5060 return QString::fromStdString(info->avatar_url);
5061
5062 return QString();
5063 }
5064
5065 mtx::events::presence::Presence
5066 Cache::presence(const std::string &user_id)
5067 {
5068 mtx::events::presence::Presence presence_{};
5069 presence_.presence = mtx::presence::PresenceState::offline;
5070
5071 if (user_id.empty())
5072 return presence_;
5073
5074 std::string_view presenceVal;
5075
5076 auto txn = ro_txn(db->env_);
5077 auto res = db->presence.get(txn, user_id, presenceVal);
5078
5079 if (res) {
5080 presence_ = nlohmann::json::parse(std::string_view(presenceVal.data(), presenceVal.size()))
5081 .get<mtx::events::presence::Presence>();
5082 }
5083
5084 return presence_;
5085 }
5086
5087 void
5088 to_json(nlohmann::json &j, const UserKeyCache &info)
5089 {
5090 j["device_keys"] = info.device_keys;
5091 j["seen_device_keys"] = info.seen_device_keys;
5092 j["seen_device_ids"] = info.seen_device_ids;
5093 j["master_keys"] = info.master_keys;
5094 j["master_key_changed"] = info.master_key_changed;
5095 j["user_signing_keys"] = info.user_signing_keys;
5096 j["self_signing_keys"] = info.self_signing_keys;
5097 j["updated_at"] = info.updated_at;
5098 j["last_changed"] = info.last_changed;
5099 }
5100
5101 void
5102 from_json(const nlohmann::json &j, UserKeyCache &info)
5103 {
5104 info.device_keys = j.value("device_keys", std::map<std::string, mtx::crypto::DeviceKeys>{});
5105 info.seen_device_keys = j.value("seen_device_keys", std::set<std::string>{});
5106 info.seen_device_ids = j.value("seen_device_ids", std::set<std::string>{});
5107 info.master_keys = j.value("master_keys", mtx::crypto::CrossSigningKeys{});
5108 info.master_key_changed = j.value("master_key_changed", false);
5109 info.user_signing_keys = j.value("user_signing_keys", mtx::crypto::CrossSigningKeys{});
5110 info.self_signing_keys = j.value("self_signing_keys", mtx::crypto::CrossSigningKeys{});
5111 info.updated_at = j.value("updated_at", "");
5112 info.last_changed = j.value("last_changed", "");
5113 }
5114
5115 std::optional<UserKeyCache>
5116 Cache::userKeys(const std::string &user_id)
5117 {
5118 auto txn = ro_txn(db->env_);
5119 return userKeys_(user_id, txn);
5120 }
5121
5122 std::optional<UserKeyCache>
5123 Cache::userKeys_(const std::string &user_id, lmdb::txn &txn)
5124 {
5125 std::string_view keys;
5126
5127 try {
5128 auto db_ = getUserKeysDb(txn);
5129 auto res = db_.get(txn, user_id, keys);
5130
5131 if (res) {
5132 return nlohmann::json::parse(keys).get<UserKeyCache>();
5133 } else {
5134 return std::nullopt;
5135 }
5136 } catch (std::exception &e) {
5137 nhlog::db()->error("Failed to retrieve user keys for {}: {}", user_id, e.what());
5138 return std::nullopt;
5139 }
5140 }
5141
5142 void
5143 Cache::updateUserKeys(const std::string &sync_token, const mtx::responses::QueryKeys &keyQuery)
5144 {
5145 auto txn = lmdb::txn::begin(db->env_);
5146 auto db_ = getUserKeysDb(txn);
5147
5148 std::map<std::string, UserKeyCache> updates;
5149
5150 for (const auto &[user, keys] : keyQuery.device_keys)
5151 updates[user].device_keys = keys;
5152 for (const auto &[user, keys] : keyQuery.master_keys)
5153 updates[user].master_keys = keys;
5154 for (const auto &[user, keys] : keyQuery.user_signing_keys)
5155 updates[user].user_signing_keys = keys;
5156 for (const auto &[user, keys] : keyQuery.self_signing_keys)
5157 updates[user].self_signing_keys = keys;
5158
5159 for (auto &[user, update] : updates) {
5160 nhlog::db()->debug("Updated user keys: {}", user);
5161
5162 auto updateToWrite = update;
5163
5164 std::string_view oldKeys;
5165 auto res = db_.get(txn, user, oldKeys);
5166
5167 if (res) {
5168 updateToWrite = nlohmann::json::parse(oldKeys).get<UserKeyCache>();
5169 auto last_changed = updateToWrite.last_changed;
5170 // skip if we are tracking this and expect it to be up to date with the last
5171 // sync token
5172 if (!last_changed.empty() && last_changed != sync_token) {
5173 nhlog::db()->debug("Not storing update for user {}, because "
5174 "last_changed {}, but we fetched update for {}",
5175 user,
5176 last_changed,
5177 sync_token);
5178 continue;
5179 }
5180
5181 if (!updateToWrite.master_keys.keys.empty() &&
5182 update.master_keys.keys != updateToWrite.master_keys.keys) {
5183 nhlog::db()->debug("Master key of {} changed:\nold: {}\nnew: {}",
5184 user,
5185 updateToWrite.master_keys.keys.size(),
5186 update.master_keys.keys.size());
5187 updateToWrite.master_key_changed = true;
5188 }
5189
5190 updateToWrite.master_keys = update.master_keys;
5191 updateToWrite.self_signing_keys = update.self_signing_keys;
5192 updateToWrite.user_signing_keys = update.user_signing_keys;
5193
5194 auto oldDeviceKeys = std::move(updateToWrite.device_keys);
5195 updateToWrite.device_keys.clear();
5196
5197 // Don't insert keys, which we have seen once already
5198 for (const auto &[device_id, device_keys] : update.device_keys) {
5199 if (oldDeviceKeys.count(device_id) &&
5200 oldDeviceKeys.at(device_id).keys == device_keys.keys) {
5201 // this is safe, since the keys are the same
5202 updateToWrite.device_keys[device_id] = device_keys;
5203 } else {
5204 bool keyReused = false;
5205 for (const auto &[key_id, key] : device_keys.keys) {
5206 (void)key_id;
5207 if (updateToWrite.seen_device_keys.count(key)) {
5208 nhlog::crypto()->warn(
5209 "Key '{}' reused by ({}: {})", key, user, device_id);
5210 keyReused = true;
5211 break;
5212 }
5213 if (updateToWrite.seen_device_ids.count(device_id)) {
5214 nhlog::crypto()->warn("device_id '{}' reused by ({})", device_id, user);
5215 keyReused = true;
5216 break;
5217 }
5218 }
5219
5220 if (!keyReused && !oldDeviceKeys.count(device_id)) {
5221 // ensure the key has a valid signature from itself
5222 std::string device_signing_key = "ed25519:" + device_keys.device_id;
5223 if (device_id != device_keys.device_id) {
5224 nhlog::crypto()->warn("device {}:{} has a different device id "
5225 "in the body: {}",
5226 user,
5227 device_id,
5228 device_keys.device_id);
5229 continue;
5230 }
5231 if (!device_keys.signatures.count(user) ||
5232 !device_keys.signatures.at(user).count(device_signing_key)) {
5233 nhlog::crypto()->warn("device {}:{} has no signature", user, device_id);
5234 continue;
5235 }
5236 if (!device_keys.keys.count(device_signing_key) ||
5237 !device_keys.keys.count("curve25519:" + device_id)) {
5238 nhlog::crypto()->warn(
5239 "Device key has no curve25519 or ed25519 key {}:{}",
5240 user,
5241 device_id);
5242 continue;
5243 }
5244
5245 if (!mtx::crypto::ed25519_verify_signature(
5246 device_keys.keys.at(device_signing_key),
5247 nlohmann::json(device_keys),
5248 device_keys.signatures.at(user).at(device_signing_key))) {
5249 nhlog::crypto()->warn(
5250 "device {}:{} has an invalid signature", user, device_id);
5251 continue;
5252 }
5253
5254 updateToWrite.device_keys[device_id] = device_keys;
5255 }
5256 }
5257
5258 for (const auto &[key_id, key] : device_keys.keys) {
5259 (void)key_id;
5260 updateToWrite.seen_device_keys.insert(key);
5261 }
5262 updateToWrite.seen_device_ids.insert(device_id);
5263 }
5264 }
5265 updateToWrite.updated_at = sync_token;
5266 db_.put(txn, user, nlohmann::json(updateToWrite).dump());
5267 }
5268
5269 txn.commit();
5270
5271 std::map<std::string, VerificationStatus> tmp;
5272 const auto local_user = utils::localUser().toStdString();
5273
5274 {
5275 std::unique_lock<std::mutex> lock(verification_storage.verification_storage_mtx);
5276 for (auto &[user_id, update] : updates) {
5277 (void)update;
5278 if (user_id == local_user) {
5279 std::swap(tmp, verification_storage.status);
5280 } else {
5281 verification_storage.status.erase(user_id);
5282 }
5283 }
5284 }
5285
5286 for (auto &[user_id, update] : updates) {
5287 (void)update;
5288 if (user_id == local_user) {
5289 for (const auto &[user, status] : tmp) {
5290 (void)status;
5291 emit verificationStatusChanged(user);
5292 }
5293 } else {
5294 emit verificationStatusChanged(user_id);
5295 }
5296 }
5297 }
5298
5299 void
5300 Cache::markUserKeysOutOfDate(const std::vector<std::string> &user_ids)
5301 {
5302 auto currentBatchToken = nextBatchToken();
5303 auto txn = lmdb::txn::begin(db->env_);
5304 auto db_ = getUserKeysDb(txn);
5305 markUserKeysOutOfDate(txn, db_, user_ids, currentBatchToken);
5306 txn.commit();
5307 }
5308
5309 void
5310 Cache::markUserKeysOutOfDate(lmdb::txn &txn,
5311 lmdb::dbi &db_,
5312 const std::vector<std::string> &user_ids,
5313 const std::string &sync_token)
5314 {
5315 mtx::requests::QueryKeys query;
5316 query.token = sync_token;
5317
5318 for (const auto &user : user_ids) {
5319 if (user.size() > 255) {
5320 nhlog::db()->debug("Skipping device key query for user with invalid mxid: {}", user);
5321 continue;
5322 }
5323
5324 nhlog::db()->debug("Marking user keys out of date: {}", user);
5325
5326 std::string_view oldKeys;
5327
5328 UserKeyCache cacheEntry{};
5329 auto res = db_.get(txn, user, oldKeys);
5330 if (res) {
5331 try {
5332 cacheEntry = nlohmann::json::parse(std::string_view(oldKeys.data(), oldKeys.size()))
5333 .get<UserKeyCache>();
5334 } catch (std::exception &e) {
5335 nhlog::db()->error("Failed to parse {}: {}", oldKeys, e.what());
5336 }
5337 }
5338 cacheEntry.last_changed = sync_token;
5339
5340 db_.put(txn, user, nlohmann::json(cacheEntry).dump());
5341
5342 query.device_keys[user] = {};
5343
5344 if (query.device_keys.size() >= 32) {
5345 http::client()->query_keys(
5346 query,
5347 [this, sync_token](const mtx::responses::QueryKeys &keys, mtx::http::RequestErr err) {
5348 if (err) {
5349 nhlog::net()->warn("failed to query device keys: {} {}",
5350 err->matrix_error.error,
5351 static_cast<int>(err->status_code));
5352 return;
5353 }
5354
5355 emit userKeysUpdate(sync_token, keys);
5356 });
5357 query.device_keys.clear();
5358 }
5359 }
5360
5361 if (!query.device_keys.empty())
5362 http::client()->query_keys(
5363 query,
5364 [this, sync_token](const mtx::responses::QueryKeys &keys, mtx::http::RequestErr err) {
5365 if (err) {
5366 nhlog::net()->warn("failed to query device keys: {} {}",
5367 err->matrix_error.error,
5368 static_cast<int>(err->status_code));
5369 return;
5370 }
5371
5372 emit userKeysUpdate(sync_token, keys);
5373 });
5374 }
5375
5376 void
5377 Cache::query_keys(const std::string &user_id,
5378 std::function<void(const UserKeyCache &, mtx::http::RequestErr)> cb)
5379 {
5380 if (user_id.size() > 255) {
5381 nhlog::db()->debug("Skipping device key query for user with invalid mxid: {}", user_id);
5382
5383 mtx::http::ClientError err{};
5384 err.parse_error = "invalid mxid, more than 255 bytes";
5385 cb({}, err);
5386 return;
5387 }
5388
5389 mtx::requests::QueryKeys req;
5390 std::string last_changed;
5391 {
5392 auto txn = ro_txn(db->env_);
5393 auto cache_ = userKeys_(user_id, txn);
5394
5395 if (cache_.has_value()) {
5396 if (cache_->updated_at == cache_->last_changed) {
5397 cb(cache_.value(), {});
5398 return;
5399 } else
5400 nhlog::db()->info("Keys outdated for {}: {} vs {}",
5401 user_id,
5402 cache_->updated_at,
5403 cache_->last_changed);
5404 } else
5405 nhlog::db()->info("No keys found for {}", user_id);
5406
5407 req.device_keys[user_id] = {};
5408
5409 if (cache_)
5410 last_changed = cache_->last_changed;
5411 req.token = last_changed;
5412 }
5413
5414 // use context object so that we can disconnect again
5415 QObject *context{new QObject(this)};
5416 QObject::connect(
5417 this,
5418 &Cache::userKeysUpdateFinalize,
5419 context,
5420 [cb, user_id, context_ = context, this](std::string updated_user) mutable {
5421 if (user_id == updated_user) {
5422 context_->deleteLater();
5423 auto txn = ro_txn(db->env_);
5424 auto keys = this->userKeys_(user_id, txn);
5425 cb(keys.value_or(UserKeyCache{}), {});
5426 }
5427 },
5428 Qt::QueuedConnection);
5429
5430 http::client()->query_keys(
5431 req,
5432 [cb, user_id, last_changed, this](const mtx::responses::QueryKeys &res,
5433 mtx::http::RequestErr err) {
5434 if (err) {
5435 nhlog::net()->warn("failed to query device keys: {},{}",
5436 mtx::errors::to_string(err->matrix_error.errcode),
5437 static_cast<int>(err->status_code));
5438 cb({}, err);
5439 return;
5440 }
5441
5442 emit userKeysUpdate(last_changed, res);
5443 emit userKeysUpdateFinalize(user_id);
5444 });
5445 }
5446
5447 void
5448 to_json(nlohmann::json &j, const VerificationCache &info)
5449 {
5450 j["device_verified"] = info.device_verified;
5451 j["device_blocked"] = info.device_blocked;
5452 }
5453
5454 void
5455 from_json(const nlohmann::json &j, VerificationCache &info)
5456 {
5457 info.device_verified = j.at("device_verified").get<std::set<std::string>>();
5458 info.device_blocked = j.at("device_blocked").get<std::set<std::string>>();
5459 }
5460
5461 void
5462 to_json(nlohmann::json &j, const OnlineBackupVersion &info)
5463 {
5464 j["v"] = info.version;
5465 j["a"] = info.algorithm;
5466 }
5467
5468 void
5469 from_json(const nlohmann::json &j, OnlineBackupVersion &info)
5470 {
5471 info.version = j.at("v").get<std::string>();
5472 info.algorithm = j.at("a").get<std::string>();
5473 }
5474
5475 std::optional<VerificationCache>
5476 Cache::verificationCache(const std::string &user_id, lmdb::txn &txn)
5477 {
5478 std::string_view verifiedVal;
5479
5480 auto db_ = getVerificationDb(txn);
5481
5482 try {
5483 VerificationCache verified_state;
5484 auto res = db_.get(txn, user_id, verifiedVal);
5485 if (res) {
5486 verified_state = nlohmann::json::parse(verifiedVal).get<VerificationCache>();
5487 return verified_state;
5488 } else {
5489 return {};
5490 }
5491 } catch (std::exception &) {
5492 return {};
5493 }
5494 }
5495
5496 void
5497 Cache::markDeviceVerified(const std::string &user_id, const std::string &key)
5498 {
5499 {
5500 std::string_view val;
5501
5502 auto txn = lmdb::txn::begin(db->env_);
5503 auto db_ = getVerificationDb(txn);
5504
5505 try {
5506 VerificationCache verified_state;
5507 auto res = db_.get(txn, user_id, val);
5508 if (res) {
5509 verified_state = nlohmann::json::parse(val).get<VerificationCache>();
5510 }
5511
5512 for (const auto &device : verified_state.device_verified)
5513 if (device == key)
5514 return;
5515
5516 verified_state.device_verified.insert(key);
5517 db_.put(txn, user_id, nlohmann::json(verified_state).dump());
5518 txn.commit();
5519 } catch (std::exception &) {
5520 }
5521 }
5522
5523 const auto local_user = utils::localUser().toStdString();
5524 std::map<std::string, VerificationStatus> tmp;
5525 {
5526 std::unique_lock<std::mutex> lock(verification_storage.verification_storage_mtx);
5527 if (user_id == local_user) {
5528 std::swap(tmp, verification_storage.status);
5529 verification_storage.status.clear();
5530 } else {
5531 verification_storage.status.erase(user_id);
5532 }
5533 }
5534 if (user_id == local_user) {
5535 for (const auto &[user, status] : tmp) {
5536 (void)status;
5537 emit verificationStatusChanged(user);
5538 }
5539 } else {
5540 emit verificationStatusChanged(user_id);
5541 }
5542 }
5543
5544 void
5545 Cache::markDeviceUnverified(const std::string &user_id, const std::string &key)
5546 {
5547 std::string_view val;
5548
5549 auto txn = lmdb::txn::begin(db->env_);
5550 auto db_ = getVerificationDb(txn);
5551
5552 try {
5553 VerificationCache verified_state;
5554 auto res = db_.get(txn, user_id, val);
5555 if (res) {
5556 verified_state = nlohmann::json::parse(val).get<VerificationCache>();
5557 }
5558
5559 verified_state.device_verified.erase(key);
5560
5561 db_.put(txn, user_id, nlohmann::json(verified_state).dump());
5562 txn.commit();
5563 } catch (std::exception &) {
5564 }
5565
5566 const auto local_user = utils::localUser().toStdString();
5567 std::map<std::string, VerificationStatus> tmp;
5568 {
5569 std::unique_lock<std::mutex> lock(verification_storage.verification_storage_mtx);
5570 if (user_id == local_user) {
5571 std::swap(tmp, verification_storage.status);
5572 } else {
5573 verification_storage.status.erase(user_id);
5574 }
5575 }
5576 if (user_id == local_user) {
5577 for (const auto &[user, status] : tmp) {
5578 (void)status;
5579 emit verificationStatusChanged(user);
5580 }
5581 }
5582 emit verificationStatusChanged(user_id);
5583 }
5584
5585 VerificationStatus
5586 Cache::verificationStatus(const std::string &user_id)
5587 {
5588 auto txn = ro_txn(db->env_);
5589 return verificationStatus_(user_id, txn);
5590 }
5591
5592 VerificationStatus
5593 Cache::verificationStatus_(const std::string &user_id, lmdb::txn &txn)
5594 {
5595 std::unique_lock<std::mutex> lock(verification_storage.verification_storage_mtx);
5596 if (verification_storage.status.count(user_id))
5597 return verification_storage.status.at(user_id);
5598
5599 VerificationStatus status;
5600
5601 // assume there is at least one unverified device until we have checked we have the device
5602 // list for that user.
5603 status.unverified_device_count = 1;
5604 status.no_keys = true;
5605
5606 if (auto verifCache = verificationCache(user_id, txn)) {
5607 status.verified_devices = verifCache->device_verified;
5608 }
5609
5610 const auto local_user = utils::localUser().toStdString();
5611
5612 crypto::Trust trustlevel = crypto::Trust::Unverified;
5613 if (user_id == local_user) {
5614 status.verified_devices.insert(http::client()->device_id());
5615 trustlevel = crypto::Trust::Verified;
5616 }
5617
5618 auto verifyAtLeastOneSig = [](const auto &toVerif,
5619 const std::map<std::string, std::string> &keys,
5620 const std::string &keyOwner) {
5621 if (!toVerif.signatures.count(keyOwner))
5622 return false;
5623
5624 for (const auto &[key_id, signature] : toVerif.signatures.at(keyOwner)) {
5625 if (!keys.count(key_id))
5626 continue;
5627
5628 if (mtx::crypto::ed25519_verify_signature(
5629 keys.at(key_id), nlohmann::json(toVerif), signature))
5630 return true;
5631 }
5632 return false;
5633 };
5634
5635 auto updateUnverifiedDevices = [&status](auto &theirDeviceKeys) {
5636 int currentVerifiedDevices = 0;
5637 for (const auto &device_id : status.verified_devices) {
5638 if (theirDeviceKeys.count(device_id))
5639 currentVerifiedDevices++;
5640 }
5641 status.unverified_device_count =
5642 static_cast<int>(theirDeviceKeys.size()) - currentVerifiedDevices;
5643 };
5644
5645 try {
5646 // for local user verify this device_key -> our master_key -> our self_signing_key
5647 // -> our device_keys
5648 //
5649 // for other user verify this device_key -> our master_key -> our user_signing_key
5650 // -> their master_key -> their self_signing_key -> their device_keys
5651 //
5652 // This means verifying the other user adds 2 extra steps,verifying our user_signing
5653 // key and their master key
5654 auto ourKeys = userKeys_(local_user, txn);
5655 auto theirKeys = userKeys_(user_id, txn);
5656 if (theirKeys)
5657 status.no_keys = false;
5658
5659 if (!ourKeys || !theirKeys) {
5660 verification_storage.status[user_id] = status;
5661 return status;
5662 }
5663
5664 // Update verified devices count to count without cross-signing
5665 updateUnverifiedDevices(theirKeys->device_keys);
5666
5667 {
5668 auto &mk = ourKeys->master_keys;
5669 std::string dev_id = "ed25519:" + http::client()->device_id();
5670 if (!mk.signatures.count(local_user) || !mk.signatures.at(local_user).count(dev_id) ||
5671 !mtx::crypto::ed25519_verify_signature(olm::client()->identity_keys().ed25519,
5672 nlohmann::json(mk),
5673 mk.signatures.at(local_user).at(dev_id))) {
5674 nhlog::crypto()->debug("We have not verified our own master key");
5675 verification_storage.status[user_id] = status;
5676 return status;
5677 }
5678 }
5679
5680 auto master_keys = ourKeys->master_keys.keys;
5681
5682 if (user_id != local_user) {
5683 bool theirMasterKeyVerified =
5684 verifyAtLeastOneSig(ourKeys->user_signing_keys, master_keys, local_user) &&
5685 verifyAtLeastOneSig(
5686 theirKeys->master_keys, ourKeys->user_signing_keys.keys, local_user);
5687
5688 if (theirMasterKeyVerified)
5689 trustlevel = crypto::Trust::Verified;
5690 else if (!theirKeys->master_key_changed)
5691 trustlevel = crypto::Trust::TOFU;
5692 else {
5693 verification_storage.status[user_id] = status;
5694 return status;
5695 }
5696
5697 master_keys = theirKeys->master_keys.keys;
5698 }
5699
5700 status.user_verified = trustlevel;
5701
5702 verification_storage.status[user_id] = status;
5703 if (!verifyAtLeastOneSig(theirKeys->self_signing_keys, master_keys, user_id))
5704 return status;
5705
5706 for (const auto &[device, device_key] : theirKeys->device_keys) {
5707 (void)device;
5708 try {
5709 auto identkey = device_key.keys.at("curve25519:" + device_key.device_id);
5710 if (verifyAtLeastOneSig(device_key, theirKeys->self_signing_keys.keys, user_id)) {
5711 status.verified_devices.insert(device_key.device_id);
5712 status.verified_device_keys[identkey] = trustlevel;
5713 }
5714 } catch (...) {
5715 }
5716 }
5717
5718 updateUnverifiedDevices(theirKeys->device_keys);
5719 verification_storage.status[user_id] = status;
5720 return status;
5721 } catch (std::exception &e) {
5722 nhlog::db()->error("Failed to calculate verification status of {}: {}", user_id, e.what());
5723 return status;
5724 }
5725 }
5726
5727 void
5728 to_json(nlohmann::json &j, const RoomInfo &info)
5729 {
5730 j["name"] = info.name;
5731 j["topic"] = info.topic;
5732 j["avatar_url"] = info.avatar_url;
5733 j["version"] = info.version;
5734 j["is_invite"] = info.is_invite;
5735 j["is_space"] = info.is_space;
5736 j["tombst"] = info.is_tombstoned;
5737 j["join_rule"] = info.join_rule;
5738 j["guest_access"] = info.guest_access;
5739
5740 j["app_l_ts"] = info.approximate_last_modification_ts;
5741
5742 j["notification_count"] = info.notification_count;
5743 j["highlight_count"] = info.highlight_count;
5744
5745 if (info.member_count != 0)
5746 j["member_count"] = info.member_count;
5747
5748 if (info.tags.size() != 0)
5749 j["tags"] = info.tags;
5750 }
5751
5752 void
5753 from_json(const nlohmann::json &j, RoomInfo &info)
5754 {
5755 info.name = j.at("name").get<std::string>();
5756 info.topic = j.at("topic").get<std::string>();
5757 info.avatar_url = j.at("avatar_url").get<std::string>();
5758 info.version = j.value(
5759 "version", QCoreApplication::translate("RoomInfo", "no version stored").toStdString());
5760
5761 info.is_invite = j.at("is_invite").get<bool>();
5762 info.is_space = j.value("is_space", false);
5763 info.is_tombstoned = j.value("tombst", false);
5764
5765 info.join_rule = j.at("join_rule").get<mtx::events::state::JoinRule>();
5766 info.guest_access = j.at("guest_access").get<bool>();
5767
5768 info.approximate_last_modification_ts = j.value<uint64_t>("app_l_ts", 0);
5769 // workaround for bad values being stored in the past
5770 if (info.approximate_last_modification_ts < 100000000000)
5771 info.approximate_last_modification_ts = 0;
5772
5773 info.notification_count = j.value("notification_count", 0);
5774 info.highlight_count = j.value("highlight_count", 0);
5775
5776 if (j.count("member_count"))
5777 info.member_count = j.at("member_count").get<size_t>();
5778
5779 if (j.count("tags"))
5780 info.tags = j.at("tags").get<std::vector<std::string>>();
5781 }
5782
5783 void
5784 to_json(nlohmann::json &j, const ReadReceiptKey &key)
5785 {
5786 j = nlohmann::json{{"event_id", key.event_id}, {"room_id", key.room_id}};
5787 }
5788
5789 void
5790 from_json(const nlohmann::json &j, ReadReceiptKey &key)
5791 {
5792 key.event_id = j.at("event_id").get<std::string>();
5793 key.room_id = j.at("room_id").get<std::string>();
5794 }
5795
5796 void
5797 to_json(nlohmann::json &j, const MemberInfo &info)
5798 {
5799 j["name"] = info.name;
5800 j["avatar_url"] = info.avatar_url;
5801 if (!info.inviter.empty())
5802 j["inviter"] = info.inviter;
5803 if (info.is_direct)
5804 j["is_direct"] = info.is_direct;
5805 if (!info.reason.empty())
5806 j["reason"] = info.reason;
5807 }
5808
5809 void
5810 from_json(const nlohmann::json &j, MemberInfo &info)
5811 {
5812 info.name = j.value("name", "");
5813 info.avatar_url = j.value("avatar_url", "");
5814 info.is_direct = j.value("is_direct", false);
5815 info.reason = j.value("reason", "");
5816 info.inviter = j.value("inviter", "");
5817 }
5818
5819 void
5820 to_json(nlohmann::json &obj, const DeviceKeysToMsgIndex &msg)
5821 {
5822 obj["deviceids"] = msg.deviceids;
5823 }
5824
5825 void
5826 from_json(const nlohmann::json &obj, DeviceKeysToMsgIndex &msg)
5827 {
5828 msg.deviceids = obj.at("deviceids").get<decltype(msg.deviceids)>();
5829 }
5830
5831 void
5832 to_json(nlohmann::json &obj, const SharedWithUsers &msg)
5833 {
5834 obj["keys"] = msg.keys;
5835 }
5836
5837 void
5838 from_json(const nlohmann::json &obj, SharedWithUsers &msg)
5839 {
5840 msg.keys = obj.at("keys").get<std::map<std::string, DeviceKeysToMsgIndex>>();
5841 }
5842
5843 void
5844 to_json(nlohmann::json &obj, const GroupSessionData &msg)
5845 {
5846 obj["message_index"] = msg.message_index;
5847 obj["ts"] = msg.timestamp;
5848 obj["trust"] = msg.trusted;
5849
5850 obj["sender_key"] = msg.sender_key;
5851 obj["sender_claimed_ed25519_key"] = msg.sender_claimed_ed25519_key;
5852 obj["forwarding_curve25519_key_chain"] = msg.forwarding_curve25519_key_chain;
5853
5854 obj["currently"] = msg.currently;
5855
5856 obj["indices"] = msg.indices;
5857 }
5858
5859 void
5860 from_json(const nlohmann::json &obj, GroupSessionData &msg)
5861 {
5862 msg.message_index = obj.at("message_index").get<uint32_t>();
5863 msg.timestamp = obj.value("ts", 0ULL);
5864 msg.trusted = obj.value("trust", true);
5865
5866 msg.sender_key = obj.value("sender_key", "");
5867 msg.sender_claimed_ed25519_key = obj.value("sender_claimed_ed25519_key", "");
5868 msg.forwarding_curve25519_key_chain =
5869 obj.value("forwarding_curve25519_key_chain", std::vector<std::string>{});
5870
5871 msg.currently = obj.value("currently", SharedWithUsers{});
5872
5873 msg.indices = obj.value("indices", std::map<uint32_t, std::string>());
5874 }
5875
5876 void
5877 to_json(nlohmann::json &obj, const DevicePublicKeys &msg)
5878 {
5879 obj["ed25519"] = msg.ed25519;
5880 obj["curve25519"] = msg.curve25519;
5881 }
5882
5883 void
5884 from_json(const nlohmann::json &obj, DevicePublicKeys &msg)
5885 {
5886 msg.ed25519 = obj.at("ed25519").get<std::string>();
5887 msg.curve25519 = obj.at("curve25519").get<std::string>();
5888 }
5889
5890 void
5891 to_json(nlohmann::json &obj, const MegolmSessionIndex &msg)
5892 {
5893 obj["room_id"] = msg.room_id;
5894 obj["session_id"] = msg.session_id;
5895 }
5896
5897 void
5898 from_json(const nlohmann::json &obj, MegolmSessionIndex &msg)
5899 {
5900 msg.room_id = obj.at("room_id").get<std::string>();
5901 msg.session_id = obj.at("session_id").get<std::string>();
5902 }
5903
5904 void
5905 to_json(nlohmann::json &obj, const StoredOlmSession &msg)
5906 {
5907 obj["ts"] = msg.last_message_ts;
5908 obj["s"] = msg.pickled_session;
5909 }
5910 void
5911 from_json(const nlohmann::json &obj, StoredOlmSession &msg)
5912 {
5913 msg.last_message_ts = obj.at("ts").get<uint64_t>();
5914 msg.pickled_session = obj.at("s").get<std::string>();
5915 }
5916
5917 namespace cache {
5918 void
5919 setNeedsCompactFlag()
5920 {
5921 needsCompact = true;
5922 }
5923
5924 void
5925 init(const QString &user_id)
5926 {
5927 instance_ = std::make_unique<Cache>(user_id);
5928 }
5929
5930 Cache *
5931 client()
5932 {
5933 return instance_.get();
5934 }
5935
5936 std::string
5937 displayName(const std::string &room_id, const std::string &user_id)
5938 {
5939 return instance_->displayName(room_id, user_id);
5940 }
5941
5942 QString
5943 displayName(const QString &room_id, const QString &user_id)
5944 {
5945 return instance_->displayName(room_id, user_id);
5946 }
5947 QString
5948 avatarUrl(const QString &room_id, const QString &user_id)
5949 {
5950 return instance_->avatarUrl(room_id, user_id);
5951 }
5952
5953 mtx::events::presence::Presence
5954 presence(const std::string &user_id)
5955 {
5956 if (!instance_)
5957 return {};
5958 return instance_->presence(user_id);
5959 }
5960
5961 // user cache stores user keys
5962 std::optional<UserKeyCache>
5963 userKeys(const std::string &user_id)
5964 {
5965 return instance_->userKeys(user_id);
5966 }
5967 void
5968 updateUserKeys(const std::string &sync_token, const mtx::responses::QueryKeys &keyQuery)
5969 {
5970 instance_->updateUserKeys(sync_token, keyQuery);
5971 }
5972
5973 // device & user verification cache
5974 std::optional<VerificationStatus>
5975 verificationStatus(const std::string &user_id)
5976 {
5977 return instance_->verificationStatus(user_id);
5978 }
5979
5980 void
5981 markDeviceVerified(const std::string &user_id, const std::string &device)
5982 {
5983 instance_->markDeviceVerified(user_id, device);
5984 }
5985
5986 void
5987 markDeviceUnverified(const std::string &user_id, const std::string &device)
5988 {
5989 instance_->markDeviceUnverified(user_id, device);
5990 }
5991
5992 std::vector<std::string>
5993 joinedRooms()
5994 {
5995 return instance_->joinedRooms();
5996 }
5997
5998 QMap<QString, RoomInfo>
5999 roomInfo(bool withInvites)
6000 {
6001 return instance_->roomInfo(withInvites);
6002 }
6003 QHash<QString, RoomInfo>
6004 invites()
6005 {
6006 return instance_->invites();
6007 }
6008
6009 QString
6010 getRoomName(lmdb::txn &txn, lmdb::dbi &statesdb, lmdb::dbi &membersdb)
6011 {
6012 return instance_->getRoomName(txn, statesdb, membersdb);
6013 }
6014 mtx::events::state::JoinRule
6015 getRoomJoinRule(lmdb::txn &txn, lmdb::dbi &statesdb)
6016 {
6017 return instance_->getRoomJoinRule(txn, statesdb);
6018 }
6019 bool
6020 getRoomGuestAccess(lmdb::txn &txn, lmdb::dbi &statesdb)
6021 {
6022 return instance_->getRoomGuestAccess(txn, statesdb);
6023 }
6024 QString
6025 getRoomTopic(lmdb::txn &txn, lmdb::dbi &statesdb)
6026 {
6027 return instance_->getRoomTopic(txn, statesdb);
6028 }
6029 QString
6030 getRoomAvatarUrl(lmdb::txn &txn, lmdb::dbi &statesdb, lmdb::dbi &membersdb)
6031 {
6032 return instance_->getRoomAvatarUrl(txn, statesdb, membersdb);
6033 }
6034
6035 std::vector<RoomMember>
6036 getMembers(const std::string &room_id, std::size_t startIndex, std::size_t len)
6037 {
6038 return instance_->getMembers(room_id, startIndex, len);
6039 }
6040
6041 std::vector<RoomMember>
6042 getMembersFromInvite(const std::string &room_id, std::size_t startIndex, std::size_t len)
6043 {
6044 return instance_->getMembersFromInvite(room_id, startIndex, len);
6045 }
6046
6047 void
6048 saveState(const mtx::responses::Sync &res)
6049 {
6050 instance_->saveState(res);
6051 }
6052 bool
6053 isInitialized()
6054 {
6055 return instance_->isInitialized();
6056 }
6057
6058 std::string
6059 nextBatchToken()
6060 {
6061 return instance_->nextBatchToken();
6062 }
6063
6064 void
6065 deleteData()
6066 {
6067 instance_->deleteData();
6068 }
6069
6070 void
6071 removeInvite(lmdb::txn &txn, const std::string &room_id)
6072 {
6073 instance_->removeInvite(txn, room_id);
6074 }
6075 void
6076 removeInvite(const std::string &room_id)
6077 {
6078 instance_->removeInvite(room_id);
6079 }
6080 void
6081 removeRoom(lmdb::txn &txn, const std::string &roomid)
6082 {
6083 instance_->removeRoom(txn, roomid);
6084 }
6085 void
6086 removeRoom(const std::string &roomid)
6087 {
6088 instance_->removeRoom(roomid);
6089 }
6090 void
6091 removeRoom(const QString &roomid)
6092 {
6093 instance_->removeRoom(roomid.toStdString());
6094 }
6095 void
6096 setup()
6097 {
6098 instance_->setup();
6099 }
6100
6101 bool
6102 runMigrations()
6103 {
6104 return instance_->runMigrations();
6105 }
6106
6107 cache::CacheVersion
6108 formatVersion()
6109 {
6110 return instance_->formatVersion();
6111 }
6112
6113 void
6114 setCurrentFormat()
6115 {
6116 instance_->setCurrentFormat();
6117 }
6118
6119 std::vector<QString>
6120 roomIds()
6121 {
6122 return instance_->roomIds();
6123 }
6124
6125 //! Retrieve all the user ids from a room.
6126 std::vector<std::string>
6127 roomMembers(const std::string &room_id)
6128 {
6129 return instance_->roomMembers(room_id);
6130 }
6131
6132 //! Check if the given user has power level greater than
6133 //! lowest power level of the given events.
6134 bool
6135 hasEnoughPowerLevel(const std::vector<mtx::events::EventType> &eventTypes,
6136 const std::string &room_id,
6137 const std::string &user_id)
6138 {
6139 return instance_->hasEnoughPowerLevel(eventTypes, room_id, user_id);
6140 }
6141
6142 void
6143 updateReadReceipt(lmdb::txn &txn, const std::string &room_id, const Receipts &receipts)
6144 {
6145 instance_->updateReadReceipt(txn, room_id, receipts);
6146 }
6147
6148 UserReceipts
6149 readReceipts(const QString &event_id, const QString &room_id)
6150 {
6151 return instance_->readReceipts(event_id, room_id);
6152 }
6153
6154 std::optional<uint64_t>
6155 getEventIndex(const std::string &room_id, std::string_view event_id)
6156 {
6157 return instance_->getEventIndex(room_id, event_id);
6158 }
6159
6160 std::optional<std::pair<uint64_t, std::string>>
6161 lastInvisibleEventAfter(const std::string &room_id, std::string_view event_id)
6162 {
6163 return instance_->lastInvisibleEventAfter(room_id, event_id);
6164 }
6165
6166 std::optional<std::pair<uint64_t, std::string>>
6167 lastVisibleEvent(const std::string &room_id, std::string_view event_id)
6168 {
6169 return instance_->lastVisibleEvent(room_id, event_id);
6170 }
6171
6172 RoomInfo
6173 singleRoomInfo(const std::string &room_id)
6174 {
6175 return instance_->singleRoomInfo(room_id);
6176 }
6177
6178 std::map<QString, RoomInfo>
6179 getRoomInfo(const std::vector<std::string> &rooms)
6180 {
6181 return instance_->getRoomInfo(rooms);
6182 }
6183
6184 //! Calculates which the read status of a room.
6185 //! Whether all the events in the timeline have been read.
6186 std::string
6187 getFullyReadEventId(const std::string &room_id)
6188 {
6189 return instance_->getFullyReadEventId(room_id);
6190 }
6191 bool
6192 calculateRoomReadStatus(const std::string &room_id)
6193 {
6194 return instance_->calculateRoomReadStatus(room_id);
6195 }
6196 void
6197 calculateRoomReadStatus()
6198 {
6199 instance_->calculateRoomReadStatus();
6200 }
6201
6202 void
6203 markSentNotification(const std::string &event_id)
6204 {
6205 instance_->markSentNotification(event_id);
6206 }
6207 //! Removes an event from the sent notifications.
6208 void
6209 removeReadNotification(const std::string &event_id)
6210 {
6211 instance_->removeReadNotification(event_id);
6212 }
6213 //! Check if we have sent a desktop notification for the given event id.
6214 bool
6215 isNotificationSent(const std::string &event_id)
6216 {
6217 return instance_->isNotificationSent(event_id);
6218 }
6219
6220 //! Remove old unused data.
6221 void
6222 deleteOldMessages()
6223 {
6224 instance_->deleteOldMessages();
6225 }
6226 void
6227 deleteOldData() noexcept
6228 {
6229 instance_->deleteOldData();
6230 }
6231 //! Retrieve all saved room ids.
6232 std::vector<std::string>
6233 getRoomIds(lmdb::txn &txn)
6234 {
6235 return instance_->getRoomIds(txn);
6236 }
6237
6238 //! Mark a room that uses e2e encryption.
6239 void
6240 setEncryptedRoom(lmdb::txn &txn, const std::string &room_id)
6241 {
6242 instance_->setEncryptedRoom(txn, room_id);
6243 }
6244 bool
6245 isRoomEncrypted(const std::string &room_id)
6246 {
6247 return instance_->isRoomEncrypted(room_id);
6248 }
6249
6250 //! Check if a user is a member of the room.
6251 bool
6252 isRoomMember(const std::string &user_id, const std::string &room_id)
6253 {
6254 return instance_->isRoomMember(user_id, room_id);
6255 }
6256
6257 //
6258 // Outbound Megolm Sessions
6259 //
6260 void
6261 saveOutboundMegolmSession(const std::string &room_id,
6262 const GroupSessionData &data,
6263 mtx::crypto::OutboundGroupSessionPtr &session)
6264 {
6265 instance_->saveOutboundMegolmSession(room_id, data, session);
6266 }
6267 OutboundGroupSessionDataRef
6268 getOutboundMegolmSession(const std::string &room_id)
6269 {
6270 return instance_->getOutboundMegolmSession(room_id);
6271 }
6272 bool
6273 outboundMegolmSessionExists(const std::string &room_id) noexcept
6274 {
6275 return instance_->outboundMegolmSessionExists(room_id);
6276 }
6277 void
6278 updateOutboundMegolmSession(const std::string &room_id,
6279 const GroupSessionData &data,
6280 mtx::crypto::OutboundGroupSessionPtr &session)
6281 {
6282 instance_->updateOutboundMegolmSession(room_id, data, session);
6283 }
6284 void
6285 dropOutboundMegolmSession(const std::string &room_id)
6286 {
6287 instance_->dropOutboundMegolmSession(room_id);
6288 }
6289
6290 void
6291 importSessionKeys(const mtx::crypto::ExportedSessionKeys &keys)
6292 {
6293 instance_->importSessionKeys(keys);
6294 }
6295 mtx::crypto::ExportedSessionKeys
6296 exportSessionKeys()
6297 {
6298 return instance_->exportSessionKeys();
6299 }
6300
6301 //
6302 // Inbound Megolm Sessions
6303 //
6304 void
6305 saveInboundMegolmSession(const MegolmSessionIndex &index,
6306 mtx::crypto::InboundGroupSessionPtr session,
6307 const GroupSessionData &data)
6308 {
6309 instance_->saveInboundMegolmSession(index, std::move(session), data);
6310 }
6311 mtx::crypto::InboundGroupSessionPtr
6312 getInboundMegolmSession(const MegolmSessionIndex &index)
6313 {
6314 return instance_->getInboundMegolmSession(index);
6315 }
6316 bool
6317 inboundMegolmSessionExists(const MegolmSessionIndex &index)
6318 {
6319 return instance_->inboundMegolmSessionExists(index);
6320 }
6321 std::optional<GroupSessionData>
6322 getMegolmSessionData(const MegolmSessionIndex &index)
6323 {
6324 return instance_->getMegolmSessionData(index);
6325 }
6326
6327 //
6328 // Olm Sessions
6329 //
6330 void
6331 saveOlmSession(const std::string &curve25519,
6332 mtx::crypto::OlmSessionPtr session,
6333 uint64_t timestamp)
6334 {
6335 instance_->saveOlmSession(curve25519, std::move(session), timestamp);
6336 }
6337 std::vector<std::string>
6338 getOlmSessions(const std::string &curve25519)
6339 {
6340 return instance_->getOlmSessions(curve25519);
6341 }
6342 std::optional<mtx::crypto::OlmSessionPtr>
6343 getOlmSession(const std::string &curve25519, const std::string &session_id)
6344 {
6345 return instance_->getOlmSession(curve25519, session_id);
6346 }
6347 std::optional<mtx::crypto::OlmSessionPtr>
6348 getLatestOlmSession(const std::string &curve25519)
6349 {
6350 return instance_->getLatestOlmSession(curve25519);
6351 }
6352
6353 void
6354 saveOlmAccount(const std::string &pickled)
6355 {
6356 instance_->saveOlmAccount(pickled);
6357 }
6358 std::string
6359 restoreOlmAccount()
6360 {
6361 return instance_->restoreOlmAccount();
6362 }
6363
6364 void
6365 storeSecret(std::string_view name, const std::string &secret)
6366 {
6367 instance_->storeSecret(name, secret);
6368 }
6369 std::optional<std::string>
6370 secret(std::string_view name)
6371 {
6372 return instance_->secret(name);
6373 }
6374
6375 std::vector<ImagePackInfo>
6376 getImagePacks(const std::string &room_id, std::optional<bool> stickers)
6377 {
6378 return instance_->getImagePacks(room_id, stickers);
6379 }
6380 } // namespace cache
6381
6382 //! Get a specific state event
6383 template<typename T>
6384 std::optional<mtx::events::StateEvent<T>>
6385 Cache::getStateEvent(const std::string &room_id, std::string_view state_key)
6386 {
6387 auto txn = lmdb::txn::begin(db->env_, nullptr, MDB_RDONLY);
6388 return getStateEvent<T>(txn, room_id, state_key);
6389 }
6390 template<typename T>
6391 std::vector<mtx::events::StateEvent<T>>
6392 Cache::getStateEventsWithType(const std::string &room_id, mtx::events::EventType type)
6393 {
6394 auto txn = lmdb::txn::begin(db->env_, nullptr, MDB_RDONLY);
6395 return getStateEventsWithType<T>(txn, room_id, type);
6396 }
6397
6398 #define NHEKO_CACHE_GET_STATE_EVENT_DEFINITION(Content) \
6399 template std::optional<mtx::events::StateEvent<Content>> Cache::getStateEvent<Content>( \
6400 const std::string &room_id, std::string_view state_key);
6401
6402 #define NHEKO_CACHE_GET_STATE_EVENTS_DEFINITION(Content) \
6403 template std::vector<mtx::events::StateEvent<Content>> Cache::getStateEventsWithType<Content>( \
6404 const std::string &room_id, mtx::events::EventType type);
6405
6406 NHEKO_CACHE_GET_STATE_EVENT_DEFINITION(mtx::events::msc2545::ImagePack)
6407 NHEKO_CACHE_GET_STATE_EVENT_DEFINITION(mtx::events::state::CanonicalAlias)
6408 NHEKO_CACHE_GET_STATE_EVENT_DEFINITION(mtx::events::state::HistoryVisibility)
6409 NHEKO_CACHE_GET_STATE_EVENT_DEFINITION(mtx::events::state::JoinRules)
6410 NHEKO_CACHE_GET_STATE_EVENT_DEFINITION(mtx::events::state::Name)
6411 NHEKO_CACHE_GET_STATE_EVENT_DEFINITION(mtx::events::state::PinnedEvents)
6412 NHEKO_CACHE_GET_STATE_EVENT_DEFINITION(mtx::events::state::PowerLevels)
6413 NHEKO_CACHE_GET_STATE_EVENT_DEFINITION(mtx::events::state::ServerAcl)
6414 NHEKO_CACHE_GET_STATE_EVENT_DEFINITION(mtx::events::state::space::Child)
6415 NHEKO_CACHE_GET_STATE_EVENT_DEFINITION(mtx::events::state::space::Parent)
6416
6417 NHEKO_CACHE_GET_STATE_EVENTS_DEFINITION(mtx::events::state::Widget)
6418 NHEKO_CACHE_GET_STATE_EVENTS_DEFINITION(mtx::events::state::space::Parent)
6419 NHEKO_CACHE_GET_STATE_EVENTS_DEFINITION(mtx::events::msc2545::ImagePack)
6420
6421 #include "moc_Cache_p.cpp"