Debian Codegraph @

mtxclient/examples/crypto_bot.cpp

raw symbols SCIP
1 #include <csignal>
2 #include <cstdlib>
3
4 #include "spdlog/sinks/stdout_color_sinks.h"
5 #include "spdlog/spdlog.h"
6
7 #include <atomic>
8 #include <cstdint>
9 #include <fstream>
10 #include <iostream>
11 #include <nlohmann/json.hpp>
12 #include <stdexcept>
13 #include <thread>
14 #include <variant>
15
16 #include <mtx.hpp>
17 #include <mtx/identifiers.hpp>
18
19 #include "mtxclient/crypto/client.hpp"
20 #include "mtxclient/http/client.hpp"
21 #include "mtxclient/http/errors.hpp"
22
23 #include "mtxclient/utils.hpp"
24
25 //
26 // Simple example bot that will accept any invite.
27 //
28
29 using namespace std;
30 using namespace mtx::client;
31 using namespace mtx::crypto;
32 using namespace mtx::http;
33 using namespace mtx::events;
34 using namespace mtx::identifiers;
35
36 using TimelineEvent = mtx::events::collections::TimelineEvents;
37
38 constexpr auto OLM_ALGO = "m.olm.v1.curve25519-aes-sha2";
39 constexpr auto STORAGE_KEY = "secret";
40
41 struct OlmCipherContent
42 {
43 std::string body;
44 uint8_t type;
45 };
46
47 inline void
48 from_json(const nlohmann::json &obj, OlmCipherContent &msg)
49 {
50 msg.body = obj.at("body").get<std::string>();
51 msg.type = obj.at("type").get<uint8_t>();
52 }
53
54 struct OlmMessage
55 {
56 std::string sender_key;
57 std::string sender;
58
59 using RecipientKey = std::string;
60 std::map<RecipientKey, OlmCipherContent> ciphertext;
61 };
62
63 inline void
64 from_json(const nlohmann::json &obj, OlmMessage &msg)
65 {
66 if (obj.at("type") != "m.room.encrypted") {
67 throw std::invalid_argument("invalid type for olm message");
68 }
69
70 if (obj.at("content").at("algorithm") != OLM_ALGO)
71 throw std::invalid_argument("invalid algorithm for olm message");
72
73 msg.sender = obj.at("sender").get<std::string>();
74 msg.sender_key = obj.at("content").at("sender_key").get<std::string>();
75 msg.ciphertext =
76 obj.at("content").at("ciphertext").get<std::map<std::string, OlmCipherContent>>();
77 }
78
79 template<class Container, class Item>
80 bool
81 exists(const Container &container, const Item &item)
82 {
83 return container.find(item) != container.end();
84 }
85
86 void
87 get_device_keys(const UserId &user);
88
89 void
90 save_device_keys(const mtx::responses::QueryKeys &res);
91
92 void
93 mark_encrypted_room(const RoomId &id);
94
95 void
96 handle_to_device_msgs(const mtx::responses::ToDevice &to_device);
97
98 struct OutboundSessionData
99 {
100 std::string session_id;
101 std::string session_key;
102 uint64_t message_index = 0;
103 };
104
105 inline void
106 to_json(nlohmann::json &obj, const OutboundSessionData &msg)
107 {
108 obj["session_id"] = msg.session_id;
109 obj["session_key"] = msg.session_key;
110 obj["message_index"] = msg.message_index;
111 }
112
113 inline void
114 from_json(const nlohmann::json &obj, OutboundSessionData &msg)
115 {
116 msg.session_id = obj.at("session_id").get<std::string>();
117 msg.session_key = obj.at("session_key").get<std::string>();
118 msg.message_index = obj.at("message_index").get<uint64_t>();
119 }
120
121 struct OutboundSessionDataRef
122 {
123 OlmOutboundGroupSession *session;
124 OutboundSessionData data;
125 };
126
127 struct DevKeys
128 {
129 std::string ed25519;
130 std::string curve25519;
131 };
132
133 inline void
134 to_json(nlohmann::json &obj, const DevKeys &msg)
135 {
136 obj["ed25519"] = msg.ed25519;
137 obj["curve25519"] = msg.curve25519;
138 }
139
140 inline void
141 from_json(const nlohmann::json &obj, DevKeys &msg)
142 {
143 msg.ed25519 = obj.at("ed25519").get<std::string>();
144 msg.curve25519 = obj.at("curve25519").get<std::string>();
145 }
146
147 auto console = spdlog::stdout_color_mt("console");
148
149 std::shared_ptr<Client> client = nullptr;
150 std::shared_ptr<OlmClient> olm_client = nullptr;
151
152 struct Storage
153 {
154 //! Storage for the user_id -> list of devices mapping.
155 std::map<std::string, std::vector<std::string>> devices;
156 //! Storage for the identity key for a device.
157 std::map<std::string, DevKeys> device_keys;
158 //! Flag that indicate if a specific room has encryption enabled.
159 std::map<std::string, bool> encrypted_rooms;
160
161 //! Keep track of members per room.
162 std::map<std::string, std::map<std::string, bool>> members;
163
164 void add_member(const std::string &room_id, const std::string &user_id)
165 {
166 members[room_id][user_id] = true;
167 }
168
169 //! Mapping from curve25519 to session.
170 std::map<std::string, OlmSessionPtr> olm_inbound_sessions;
171 std::map<std::string, OlmSessionPtr> olm_outbound_sessions;
172
173 // TODO: store message_index / event_id
174 std::map<std::string, InboundGroupSessionPtr> inbound_group_sessions;
175 // TODO: store rotation period
176 std::map<std::string, OutboundSessionData> outbound_group_session_data;
177 std::map<std::string, OutboundGroupSessionPtr> outbound_group_sessions;
178
179 bool outbound_group_exists(const std::string &room_id)
180 {
181 return (outbound_group_sessions.find(room_id) != outbound_group_sessions.end()) &&
182 (outbound_group_session_data.find(room_id) != outbound_group_session_data.end());
183 }
184
185 void set_outbound_group_session(const std::string &room_id,
186 OutboundGroupSessionPtr session,
187 OutboundSessionData data)
188 {
189 outbound_group_session_data[room_id] = data;
190 outbound_group_sessions[room_id] = std::move(session);
191 }
192
193 OutboundSessionDataRef get_outbound_group_session(const std::string &room_id)
194 {
195 return OutboundSessionDataRef{outbound_group_sessions[room_id].get(),
196 outbound_group_session_data[room_id]};
197 }
198
199 bool inbound_group_exists(const std::string &room_id,
200 const std::string &session_id,
201 const std::string &sender_key)
202 {
203 const auto key = room_id + session_id + sender_key;
204 return inbound_group_sessions.find(key) != inbound_group_sessions.end();
205 }
206
207 void set_inbound_group_session(const std::string &room_id,
208 const std::string &session_id,
209 const std::string &sender_key,
210 InboundGroupSessionPtr session)
211 {
212 const auto key = room_id + session_id + sender_key;
213 inbound_group_sessions[key] = std::move(session);
214 }
215
216 OlmInboundGroupSession *get_inbound_group_session(const std::string &room_id,
217 const std::string &session_id,
218 const std::string &sender_key)
219 {
220 const auto key = room_id + session_id + sender_key;
221 return inbound_group_sessions[key].get();
222 }
223
224 void load()
225 {
226 console->info("restoring storage");
227
228 ifstream db("db.json");
229 string db_data((istreambuf_iterator<char>(db)), istreambuf_iterator<char>());
230
231 if (db_data.empty())
232 return;
233
234 nlohmann::json obj = nlohmann::json::parse(db_data);
235
236 devices = obj.at("devices").get<map<string, vector<string>>>();
237 device_keys = obj.at("device_keys").get<map<string, DevKeys>>();
238 encrypted_rooms = obj.at("encrypted_rooms").get<map<string, bool>>();
239 members = obj.at("members").get<map<string, map<string, bool>>>();
240
241 if (obj.count("olm_inbound_sessions") != 0) {
242 auto sessions = obj.at("olm_inbound_sessions").get<map<string, string>>();
243 for (const auto &s : sessions)
244 olm_inbound_sessions[s.first] = unpickle<SessionObject>(s.second, STORAGE_KEY);
245 }
246
247 if (obj.count("olm_outbound_sessions") != 0) {
248 auto sessions = obj.at("olm_outbound_sessions").get<map<string, string>>();
249 for (const auto &s : sessions)
250 olm_outbound_sessions[s.first] = unpickle<SessionObject>(s.second, STORAGE_KEY);
251 }
252
253 if (obj.count("inbound_group_sessions") != 0) {
254 auto sessions = obj.at("inbound_group_sessions").get<map<string, string>>();
255 for (const auto &s : sessions)
256 inbound_group_sessions[s.first] =
257 unpickle<InboundSessionObject>(s.second, STORAGE_KEY);
258 }
259
260 if (obj.count("outbound_group_sessions") != 0) {
261 auto sessions = obj.at("outbound_group_sessions").get<map<string, string>>();
262 for (const auto &s : sessions)
263 outbound_group_sessions[s.first] =
264 unpickle<OutboundSessionObject>(s.second, STORAGE_KEY);
265 }
266
267 if (obj.count("outbound_group_session_data") != 0) {
268 auto sessions =
269 obj.at("outbound_group_session_data").get<map<string, OutboundSessionData>>();
270 for (const auto &s : sessions)
271 outbound_group_session_data[s.first] = s.second;
272 }
273 }
274
275 void save()
276 {
277 console->info("saving storage");
278
279 std::ofstream db("db.json");
280 if (!db.is_open()) {
281 console->error("couldn't open file to save keys");
282 return;
283 }
284
285 nlohmann::json data;
286 data["devices"] = devices;
287 data["device_keys"] = device_keys;
288 data["encrypted_rooms"] = encrypted_rooms;
289 data["members"] = members;
290
291 // Save inbound sessions
292 for (const auto &s : olm_inbound_sessions)
293 data["olm_inbound_sessions"][s.first] =
294 mtx::crypto::pickle<SessionObject>(s.second.get(), STORAGE_KEY);
295
296 for (const auto &s : olm_outbound_sessions)
297 data["olm_outbound_sessions"][s.first] =
298 mtx::crypto::pickle<SessionObject>(s.second.get(), STORAGE_KEY);
299
300 for (const auto &s : inbound_group_sessions)
301 data["inbound_group_sessions"][s.first] =
302 mtx::crypto::pickle<InboundSessionObject>(s.second.get(), STORAGE_KEY);
303
304 for (const auto &s : outbound_group_sessions)
305 data["outbound_group_sessions"][s.first] =
306 mtx::crypto::pickle<OutboundSessionObject>(s.second.get(), STORAGE_KEY);
307
308 for (const auto &s : outbound_group_session_data)
309 data["outbound_group_session_data"][s.first] = s.second;
310
311 // Save to file
312 db << data.dump(2);
313 db.close();
314 }
315 };
316
317 namespace {
318 Storage storage;
319 }
320
321 void
322 print_errors(RequestErr err)
323 {
324 if (err->status_code)
325 console->error("status code: {}", static_cast<uint16_t>(err->status_code));
326 if (!err->matrix_error.error.empty())
327 console->error("matrix error: {}", err->matrix_error.error);
328 if (err->error_code)
329 console->error("error code: {}", err->error_code);
330 }
331
332 template<class T>
333 bool
334 is_room_encryption(const T &event)
335 {
336 using namespace mtx::events;
337 using namespace mtx::events::state;
338 return std::holds_alternative<StateEvent<Encryption>>(event);
339 }
340
341 void
342 send_group_message(OlmOutboundGroupSession *session,
343 const std::string &session_id,
344 const std::string &room_id,
345 const std::string &msg)
346 {
347 // Create event payload
348 nlohmann::json doc{{"type", "m.room.message"},
349 {"content", {{"type", "m.text"}, {"body", msg}}},
350 {"room_id", room_id}};
351
352 auto payload = olm_client->encrypt_group_message(session, doc.dump());
353
354 using namespace mtx::events;
355 using namespace mtx::identifiers;
356
357 msg::Encrypted data;
358 data.ciphertext = std::string((char *)payload.data(), payload.size());
359 data.sender_key = olm_client->identity_keys().curve25519;
360 data.session_id = session_id;
361 data.device_id = client->device_id();
362
363 client->send_room_message<msg::Encrypted>(
364 room_id, data, [](const mtx::responses::EventId &res, RequestErr err) {
365 if (err) {
366 print_errors(err);
367 return;
368 }
369
370 console->info("message sent with event_id: {}", res.event_id.to_string());
371 });
372 }
373
374 void
375 create_outbound_megolm_session(const std::string &room_id, const std::string &reply_msg)
376 {
377 // Create an outbound session
378 auto outbound_session = olm_client->init_outbound_group_session();
379
380 const auto session_id = mtx::crypto::session_id(outbound_session.get());
381 const auto session_key = mtx::crypto::session_key(outbound_session.get());
382
383 mtx::events::DeviceEvent<mtx::events::msg::RoomKey> megolm_payload;
384 megolm_payload.content.algorithm = "m.megolm.v1.aes-sha2";
385 megolm_payload.content.room_id = room_id;
386 megolm_payload.content.session_id = session_id;
387 megolm_payload.content.session_key = session_key;
388 megolm_payload.type = mtx::events::EventType::RoomKey;
389
390 if (storage.members.find(room_id) == storage.members.end()) {
391 console->error("no members found for room {}", room_id);
392 return;
393 }
394
395 const auto members = storage.members[room_id];
396
397 for (const auto &member : members) {
398 const auto devices = storage.devices[member.first];
399
400 // TODO: Figure out for which devices we don't have olm sessions.
401 for (const auto &dev : devices) {
402 // TODO: check if we have downloaded the keys
403 const auto device_keys = storage.device_keys[dev];
404
405 auto to_device_cb = [](RequestErr err) {
406 if (err) {
407 print_errors(err);
408 }
409 };
410
411 if (storage.olm_outbound_sessions.find(device_keys.curve25519) !=
412 storage.olm_outbound_sessions.end()) {
413 console->info("found existing olm outbound session with device {}", dev);
414 auto olm_session = storage.olm_outbound_sessions[device_keys.curve25519].get();
415
416 auto device_msg = olm_client->create_olm_encrypted_content(olm_session,
417 megolm_payload,
418 UserId(member.first),
419 device_keys.ed25519,
420 device_keys.curve25519);
421
422 nlohmann::json body{{"messages", {{member, {{dev, device_msg}}}}}};
423
424 client->send_to_device("m.room.encrypted", body, to_device_cb);
425 // TODO: send message to device
426 } else {
427 console->info("claiming one time keys for device {}", dev);
428 auto cb = [member = member.first, dev, megolm_payload, to_device_cb](
429 const mtx::responses::ClaimKeys &res, RequestErr err) {
430 if (err) {
431 print_errors(err);
432 return;
433 }
434
435 console->info("claimed keys for {} - {}", member, dev);
436 console->info("room_key {}", nlohmann::json(megolm_payload).dump(4));
437
438 console->warn("signed one time keys");
439 auto retrieved_devices = res.one_time_keys.at(member);
440 for (const auto &rd : retrieved_devices) {
441 console->info("{} : \n {}", rd.first, rd.second.dump(2));
442
443 // TODO: Verify signatures
444 auto otk = rd.second.begin()->at("key");
445 auto id_key = storage.device_keys[dev].curve25519;
446
447 auto session =
448 olm_client->create_outbound_session(id_key, otk.get<std::string>());
449
450 auto device_msg = olm_client->create_olm_encrypted_content(
451 session.get(),
452 megolm_payload,
453 UserId(member),
454 storage.device_keys[dev].ed25519,
455 storage.device_keys[dev].curve25519);
456
457 // TODO: saving should happen when the message is
458 // sent.
459 storage.olm_outbound_sessions[id_key] = std::move(session);
460
461 nlohmann::json body{{"messages", {{member, {{dev, device_msg}}}}}};
462
463 client->send_to_device("m.room.encrypted", body, to_device_cb);
464 }
465 };
466
467 mtx::requests::ClaimKeys claim_keys;
468 claim_keys.one_time_keys[member.first][dev] = SIGNED_CURVE25519;
469
470 // TODO: we should bulk request device keys here
471 client->claim_keys(claim_keys, cb);
472 }
473 }
474 }
475
476 console->info("waiting to send sendToDevice messages");
477 std::this_thread::sleep_for(std::chrono::milliseconds(2000));
478 console->info("sending encrypted group message");
479
480 // TODO: This should be done after all sendToDevice messages have been sent.
481 send_group_message(outbound_session.get(), session_id, room_id, reply_msg);
482
483 // TODO: save message index also.
484 storage.set_outbound_group_session(
485 room_id, std::move(outbound_session), {session_id, session_key});
486 }
487
488 bool
489 is_encrypted(const TimelineEvent &event)
490 {
491 using namespace mtx::events;
492 return std::holds_alternative<EncryptedEvent<msg::Encrypted>>(event);
493 }
494
495 template<class T>
496 bool
497 is_member_event(const T &event)
498 {
499 using namespace mtx::events;
500 using namespace mtx::events::state;
501 return std::holds_alternative<StateEvent<Member>>(event);
502 }
503
504 // Check if the given event has a textual representation.
505 bool
506 is_room_message(const TimelineEvent &e)
507 {
508 return (std::holds_alternative<mtx::events::RoomEvent<msg::Audio>>(e)) ||
509 (std::holds_alternative<mtx::events::RoomEvent<msg::Emote>>(e)) ||
510 (std::holds_alternative<mtx::events::RoomEvent<msg::File>>(e)) ||
511 (std::holds_alternative<mtx::events::RoomEvent<msg::Image>>(e)) ||
512 (std::holds_alternative<mtx::events::RoomEvent<msg::Notice>>(e)) ||
513 (std::holds_alternative<mtx::events::RoomEvent<msg::Text>>(e)) ||
514 (std::holds_alternative<mtx::events::RoomEvent<msg::Video>>(e));
515 }
516
517 // Retrieves the fallback body value from the event.
518 std::string
519 get_body(const TimelineEvent &e)
520 {
521 if (auto ev = std::get_if<RoomEvent<msg::Audio>>(&e); ev != nullptr)
522 return ev->content.body;
523 else if (auto ev = std::get_if<RoomEvent<msg::Emote>>(&e); ev != nullptr)
524 return ev->content.body;
525 else if (auto ev = std::get_if<RoomEvent<msg::File>>(&e); ev != nullptr)
526 return ev->content.body;
527 else if (auto ev = std::get_if<RoomEvent<msg::Image>>(&e); ev != nullptr)
528 return ev->content.body;
529 else if (auto ev = std::get_if<RoomEvent<msg::Notice>>(&e); ev != nullptr)
530 return ev->content.body;
531 else if (auto ev = std::get_if<RoomEvent<msg::Text>>(&e); ev != nullptr)
532 return ev->content.body;
533 else if (auto ev = std::get_if<RoomEvent<msg::Video>>(&e); ev != nullptr)
534 return ev->content.body;
535
536 return "";
537 }
538
539 // Retrieves the sender of the event.
540 std::string
541 get_sender(const TimelineEvent &event)
542 {
543 return std::visit([](const auto &e) { return e.sender; }, event);
544 }
545
546 template<class T>
547 std::string
548 get_json(const T &event)
549 {
550 return std::visit([](const auto &e) { return nlohmann::json(e).dump(2); }, event);
551 }
552
553 void
554 keys_uploaded_cb(const mtx::responses::UploadKeys &, RequestErr err)
555 {
556 if (err) {
557 print_errors(err);
558 return;
559 }
560
561 olm_client->mark_keys_as_published();
562 console->info("keys uploaded");
563 }
564
565 void
566 mark_encrypted_room(const RoomId &id)
567 {
568 console->info("encryption is enabled for room: {}", id.get());
569 storage.encrypted_rooms[id.get()] = true;
570 }
571
572 void
573 send_encrypted_reply(const std::string &room_id, const std::string &reply_msg)
574 {
575 console->info("sending reply");
576
577 // Create a megolm session if it doesn't already exist.
578 if (storage.outbound_group_exists(room_id)) {
579 auto session_obj = storage.get_outbound_group_session(room_id);
580
581 send_group_message(session_obj.session, session_obj.data.session_id, room_id, reply_msg);
582
583 } else {
584 console->info("creating new megolm outbound session");
585 create_outbound_megolm_session(room_id, reply_msg);
586 }
587 }
588
589 void
590 decrypt_olm_message(const OlmMessage &olm_msg)
591 {
592 console->info("OLM message");
593 console->info("sender: {}", olm_msg.sender);
594 console->info("sender_key: {}", olm_msg.sender_key);
595
596 const auto my_id_key = olm_client->identity_keys().curve25519;
597 for (const auto &cipher : olm_msg.ciphertext) {
598 if (cipher.first == my_id_key) {
599 const auto msg_body = cipher.second.body;
600 const auto msg_type = cipher.second.type;
601
602 console->info("the message is meant for us");
603 console->info("body: {}", msg_body);
604 console->info("type: {}", msg_type);
605
606 if (msg_type == 0) {
607 console->info("opening session with {}", olm_msg.sender);
608 auto inbound_session = olm_client->create_inbound_session(msg_body);
609
610 auto ok =
611 matches_inbound_session_from(inbound_session.get(), olm_msg.sender_key, msg_body);
612
613 if (!ok) {
614 console->error("session could not be established");
615
616 } else {
617 auto output =
618 olm_client->decrypt_message(inbound_session.get(), msg_type, msg_body);
619
620 auto plaintext =
621 nlohmann::json::parse(std::string((char *)output.data(), output.size()));
622 console->info("decrypted message: \n {}", plaintext.dump(2));
623
624 storage.olm_inbound_sessions.emplace(olm_msg.sender_key,
625 std::move(inbound_session));
626
627 std::string room_id = plaintext.at("content").at("room_id").get<std::string>();
628 std::string session_id =
629 plaintext.at("content").at("session_id").get<std::string>();
630 std::string session_key =
631 plaintext.at("content").at("session_key").get<std::string>();
632
633 if (storage.inbound_group_exists(room_id, session_id, olm_msg.sender_key)) {
634 console->warn("megolm session already exists");
635 } else {
636 auto megolm_session = olm_client->init_inbound_group_session(session_key);
637
638 storage.set_inbound_group_session(
639 room_id, session_id, olm_msg.sender_key, std::move(megolm_session));
640
641 console->info("megolm_session saved");
642 }
643 }
644 }
645 }
646 }
647 }
648
649 void
650 parse_messages(const mtx::responses::Sync &res)
651 {
652 for (const auto &room : res.rooms.invite) {
653 auto room_id = room.first;
654
655 console->info("joining room {}", room_id);
656 client->join_room(room_id, [room_id](const mtx::responses::RoomId &, RequestErr e) {
657 if (e) {
658 print_errors(e);
659 console->error("failed to join room {}", room_id);
660 return;
661 }
662 });
663 }
664
665 // Check if we have any new m.room_key messages (i.e starting a new megolm session)
666 handle_to_device_msgs(res.to_device);
667
668 // Check if the uploaded one time keys are enough
669 for (const auto &device : res.device_one_time_keys_count) {
670 if (device.second < 50) {
671 console->info("number of one time keys: {}", device.second);
672 olm_client->generate_one_time_keys(50 - device.second);
673 // TODO: Mark keys as sent
674 client->upload_keys(olm_client->create_upload_keys_request(), &keys_uploaded_cb);
675 }
676 }
677
678 for (const auto &room : res.rooms.join) {
679 const std::string room_id = room.first;
680
681 for (const auto &e : room.second.state.events) {
682 if (is_room_encryption(e)) {
683 mark_encrypted_room(RoomId(room_id));
684 console->debug("{}", get_json(e));
685 } else if (is_member_event(e)) {
686 auto m = std::get<mtx::events::StateEvent<mtx::events::state::Member>>(e);
687
688 get_device_keys(UserId(m.state_key));
689 storage.add_member(room_id, m.state_key);
690 }
691 }
692
693 for (const auto &e : room.second.timeline.events) {
694 if (is_room_encryption(e)) {
695 mark_encrypted_room(RoomId(room_id));
696 console->debug("{}", get_json(e));
697 } else if (is_member_event(e)) {
698 auto m = std::get<mtx::events::StateEvent<mtx::events::state::Member>>(e);
699
700 get_device_keys(UserId(m.state_key));
701 storage.add_member(room_id, m.state_key);
702 } else if (is_encrypted(e)) {
703 console->info("received an encrypted event: {}", room_id);
704 console->info("{}", get_json(e));
705
706 auto msg = std::get<EncryptedEvent<msg::Encrypted>>(e);
707
708 if (storage.inbound_group_exists(
709 room_id, msg.content.session_id, msg.content.sender_key)) {
710 auto res = olm_client->decrypt_group_message(
711 storage.get_inbound_group_session(
712 room_id, msg.content.session_id, msg.content.sender_key),
713 msg.content.ciphertext);
714
715 auto msg_str = std::string((char *)res.data.data(), res.data.size());
716 const auto body =
717 nlohmann::json::parse(msg_str).at("content").at("body").get<std::string>();
718
719 console->info("decrypted data: {}", body);
720 console->info("decrypted message_index: {}", res.message_index);
721
722 if (msg.sender != client->user_id().to_string()) {
723 // Send a reply back to the sender.
724 std::string reply_txt(msg.sender + ": you said '" + body + "'");
725 send_encrypted_reply(room_id, reply_txt);
726 }
727
728 } else {
729 console->warn("no megolm session found to decrypt the event");
730 }
731 }
732 }
733 }
734 }
735
736 // Callback to executed after a /sync request completes.
737 void
738 sync_handler(const mtx::responses::Sync &res, RequestErr err)
739 {
740 SyncOpts opts;
741
742 if (err) {
743 console->error("error during sync");
744 print_errors(err);
745 opts.since = client->next_batch_token();
746 client->sync(opts, &sync_handler);
747 return;
748 }
749
750 parse_messages(res);
751
752 opts.since = res.next_batch;
753 client->set_next_batch_token(res.next_batch);
754 client->sync(opts, &sync_handler);
755 }
756
757 // Callback to executed after the first (initial) /sync request completes.
758 void
759 initial_sync_handler(const mtx::responses::Sync &res, RequestErr err)
760 {
761 SyncOpts opts;
762
763 if (err) {
764 console->error("error during initial sync");
765 print_errors(err);
766
767 if (err->status_code != 200) {
768 console->error("retrying initial sync ..");
769 opts.timeout = 0;
770 client->sync(opts, &initial_sync_handler);
771 }
772
773 return;
774 }
775
776 parse_messages(res);
777
778 for (const auto &room : res.rooms.join) {
779 const auto room_id = room.first;
780
781 for (const auto &e : room.second.state.events) {
782 if (is_member_event(e)) {
783 auto m = std::get<mtx::events::StateEvent<mtx::events::state::Member>>(e);
784
785 get_device_keys(UserId(m.state_key));
786 storage.add_member(room_id, m.state_key);
787 }
788 }
789 }
790
791 opts.since = res.next_batch;
792 client->set_next_batch_token(res.next_batch);
793 client->sync(opts, &sync_handler);
794 }
795
796 void
797 save_device_keys(const mtx::responses::QueryKeys &res)
798 {
799 for (const auto &entry : res.device_keys) {
800 const auto user_id = entry.first;
801
802 if (!exists(storage.devices, user_id))
803 console->info("keys for {}", user_id);
804
805 std::vector<std::string> device_list;
806 for (const auto &device : entry.second) {
807 const auto key_struct = device.second;
808
809 const std::string device_id = key_struct.device_id;
810 const std::string index = "curve25519:" + device_id;
811
812 if (key_struct.keys.find(index) == key_struct.keys.end())
813 continue;
814
815 const auto key = key_struct.keys.at(index);
816
817 if (!exists(storage.device_keys, device_id)) {
818 console->info("{} => {}", device_id, key);
819 storage.device_keys[device_id] = {key_struct.keys.at("ed25519:" + device_id),
820 key_struct.keys.at("curve25519:" + device_id)};
821 }
822
823 device_list.push_back(device_id);
824 }
825
826 if (!exists(storage.devices, user_id)) {
827 storage.devices[user_id] = device_list;
828 }
829 }
830 }
831
832 void
833 get_device_keys(const UserId &user)
834 {
835 // Retrieve all devices keys.
836 mtx::requests::QueryKeys query;
837 query.device_keys[user.get()] = {};
838
839 client->query_keys(query, [](const mtx::responses::QueryKeys &res, RequestErr err) {
840 if (err) {
841 print_errors(err);
842 return;
843 }
844
845 for (const auto &key : res.device_keys) {
846 const auto user_id = key.first;
847 const auto devices = key.second;
848
849 for (const auto &device : devices) {
850 const auto id = device.first;
851 const auto data = device.second;
852
853 try {
854 auto ok =
855 verify_identity_signature(nlohmann::json(data).get<mtx::crypto::DeviceKeys>(),
856 DeviceId(id),
857 UserId(user_id));
858
859 if (!ok) {
860 console->warn("signature could not be verified");
861 console->warn(nlohmann::json(data).dump(2));
862 }
863 } catch (const olm_exception &e) {
864 console->warn(e.what());
865 }
866 }
867 }
868
869 save_device_keys(std::move(res));
870 });
871 }
872
873 void
874 handle_to_device_msgs(const mtx::responses::ToDevice &msgs)
875 {
876 if (!msgs.events.empty())
877 console->info("inspecting {} to_device messages", msgs.events.size());
878
879 for (const auto &msg : msgs.events) {
880 console->info(std::visit([](const auto &e) { return nlohmann::json(e); }, msg).dump(2));
881
882 try {
883 OlmMessage olm_msg =
884 std::visit([](const auto &e) { return nlohmann::json(e).get<OlmMessage>(); }, msg);
885 decrypt_olm_message(std::move(olm_msg));
886 } catch (const nlohmann::json::exception &e) {
887 console->warn("parsing error for olm message: {}", e.what());
888 } catch (const std::invalid_argument &e) {
889 console->warn("validation error for olm message: {}", e.what());
890 }
891 }
892 }
893
894 void
895 login_cb(const mtx::responses::Login &, RequestErr err)
896 {
897 if (err) {
898 console->error("login error");
899 print_errors(err);
900 return;
901 }
902
903 console->info("User ID: {}", client->user_id().to_string());
904 console->info("Device ID: {}", client->device_id());
905 console->info("ed25519: {}", olm_client->identity_keys().ed25519);
906 console->info("curve25519: {}", olm_client->identity_keys().curve25519);
907
908 // Upload one time keys.
909 olm_client->set_user_id(client->user_id().to_string());
910 olm_client->set_device_id(client->device_id());
911 olm_client->generate_one_time_keys(50);
912
913 client->upload_keys(olm_client->create_upload_keys_request(),
914 [](const mtx::responses::UploadKeys &, RequestErr err) {
915 if (err) {
916 print_errors(err);
917 return;
918 }
919
920 olm_client->mark_keys_as_published();
921 console->info("keys uploaded");
922 console->debug("starting initial sync");
923
924 SyncOpts opts;
925 opts.timeout = 0;
926 client->sync(opts, &initial_sync_handler);
927 });
928 }
929
930 void
931 join_room_cb(const mtx::responses::RoomId &, RequestErr err)
932 {
933 if (err) {
934 print_errors(err);
935 return;
936 }
937
938 // Fetch device list for all users.
939 }
940
941 void
942 shutdown_handler(int sig)
943 {
944 console->warn("received {} signal", sig);
945 storage.save();
946
947 std::ofstream db("account.json");
948 if (!db.is_open()) {
949 console->error("couldn't open file to save account keys");
950 return;
951 }
952
953 nlohmann::json data;
954 data["account"] = olm_client->save(STORAGE_KEY);
955
956 db << data.dump(2);
957 db.close();
958
959 // The sync calls will stop.
960 client->shutdown();
961 }
962
963 int
964 main()
965 {
966 spdlog::set_pattern("[%H:%M:%S] [tid %t] [%^%l%$] %v");
967
968 std::signal(SIGINT, shutdown_handler);
969
970 std::string username("alice");
971 std::string server("localhost");
972 std::string password("secret");
973
974 client = std::make_shared<Client>(server);
975
976 olm_client = make_shared<OlmClient>();
977
978 ifstream db("account.json");
979 string db_data((istreambuf_iterator<char>(db)), istreambuf_iterator<char>());
980
981 if (db_data.empty())
982 olm_client->create_new_account();
983 else
984 olm_client->load(nlohmann::json::parse(db_data).at("account").get<std::string>(),
985 STORAGE_KEY);
986
987 storage.load();
988
989 client->login(username, password, login_cb);
990 client->close();
991
992 console->info("exit");
993
994 return 0;
995 }