Line data Source code
1 : /*
2 : * Copyright (C) 2004-2025 Savoir-faire Linux Inc.
3 : *
4 : * This program is free software: you can redistribute it and/or modify
5 : * it under the terms of the GNU General Public License as published by
6 : * the Free Software Foundation, either version 3 of the License, or
7 : * (at your option) any later version.
8 : *
9 : * This program is distributed in the hope that it will be useful,
10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 : * GNU General Public License for more details.
13 : *
14 : * You should have received a copy of the GNU General Public License
15 : * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 : */
17 : #include "account_manager.h"
18 : #include "accountarchive.h"
19 : #include "jamiaccount.h"
20 : #include "base64.h"
21 : #include "jami/account_const.h"
22 : #include "account_schema.h"
23 : #include "archiver.h"
24 : #include "manager.h"
25 :
26 : #include "libdevcrypto/Common.h"
27 : #include "json_utils.h"
28 :
29 : #include <opendht/thread_pool.h>
30 : #include <opendht/crypto.h>
31 :
32 : #include <exception>
33 : #include <future>
34 : #include <fstream>
35 : #include <gnutls/ocsp.h>
36 :
37 : namespace jami {
38 :
39 : AccountManager::CertRequest
40 634 : AccountManager::buildRequest(PrivateKey fDeviceKey)
41 : {
42 634 : return dht::ThreadPool::computation().get<std::unique_ptr<dht::crypto::CertificateRequest>>(
43 634 : [fDeviceKey = std::move(fDeviceKey)] {
44 634 : auto request = std::make_unique<dht::crypto::CertificateRequest>();
45 634 : request->setName("Jami device");
46 634 : const auto& deviceKey = fDeviceKey.get();
47 634 : request->setUID(deviceKey->getPublicKey().getId().toString());
48 634 : request->sign(*deviceKey);
49 634 : return request;
50 634 : });
51 : }
52 :
53 1938 : AccountManager::~AccountManager() {
54 646 : if (dht_)
55 576 : dht_->join();
56 646 : }
57 :
58 : void
59 309 : AccountManager::onSyncData(DeviceSync&& sync, bool checkDevice)
60 : {
61 309 : auto sync_date = clock::time_point(clock::duration(sync.date));
62 309 : if (checkDevice) {
63 : // If the DHT is used, we need to check the device here
64 0 : if (not info_->contacts->syncDevice(sync.owner->getLongId(), sync_date)) {
65 0 : return;
66 : }
67 : }
68 :
69 : // Sync known devices
70 927 : JAMI_DEBUG("[Account {}] [Contacts] received device sync data ({:d} devices, {:d} contacts, {:d} requests)",
71 : accountId_,
72 : sync.devices_known.size() + sync.devices.size(),
73 : sync.peers.size(),
74 : sync.trust_requests.size());
75 309 : for (const auto& d : sync.devices_known) {
76 0 : findCertificate(d.first, [this, d](const std::shared_ptr<dht::crypto::Certificate>& crt) {
77 0 : if (not crt)
78 0 : return;
79 : // std::lock_guard lock(deviceListMutex_);
80 0 : foundAccountDevice(crt, d.second);
81 : });
82 : }
83 670 : for (const auto& d : sync.devices) {
84 361 : findCertificate(d.second.sha1,
85 722 : [this, d](const std::shared_ptr<dht::crypto::Certificate>& crt) {
86 361 : if (not crt || crt->getLongId() != d.first)
87 0 : return;
88 : // std::lock_guard lock(deviceListMutex_);
89 361 : foundAccountDevice(crt, d.second.name);
90 : });
91 : }
92 : // saveKnownDevices();
93 :
94 : // Sync contacts
95 309 : if (!sync.peers.empty()) {
96 120 : for (const auto &peer: sync.peers) {
97 60 : info_->contacts->updateContact(peer.first, peer.second);
98 : }
99 60 : info_->contacts->saveContacts();
100 : }
101 :
102 : // Sync trust requests
103 316 : for (const auto& tr : sync.trust_requests)
104 14 : info_->contacts->onTrustRequest(tr.first,
105 7 : tr.second.device,
106 7 : tr.second.received,
107 : false,
108 7 : tr.second.conversationId,
109 : {});
110 : }
111 :
112 : dht::crypto::Identity
113 647 : AccountManager::loadIdentity(const std::string& crt_path,
114 : const std::string& key_path,
115 : const std::string& key_pwd) const
116 : {
117 : // Return to avoid unnecessary log if certificate or key is missing. Example case: when
118 : // importing an account when the certificate has not been unpacked from the archive.
119 647 : if (crt_path.empty() or key_path.empty())
120 630 : return {};
121 :
122 51 : JAMI_DEBUG("[Account {}] [Auth] Loading certificate from '{}' and key from '{}' at {}",
123 : accountId_,
124 : crt_path,
125 : key_path,
126 : path_);
127 : try {
128 34 : dht::crypto::Certificate dht_cert(fileutils::loadFile(crt_path, path_));
129 34 : dht::crypto::PrivateKey dht_key(fileutils::loadFile(key_path, path_), key_pwd);
130 17 : auto crt_id = dht_cert.getLongId();
131 17 : if (!crt_id or crt_id != dht_key.getPublicKey().getLongId()) {
132 0 : JAMI_ERROR("[Account {}] [Auth] Device certificate not matching public key!", accountId_);
133 0 : return {};
134 : }
135 17 : auto& issuer = dht_cert.issuer;
136 17 : if (not issuer) {
137 0 : JAMI_ERROR("[Account {}] [Auth] Device certificate {:s} has no issuer", accountId_, dht_cert.getId().to_view());
138 0 : return {};
139 : }
140 : // load revocation lists for device authority (account certificate).
141 17 : Manager::instance().certStore(accountId_).loadRevocations(*issuer);
142 :
143 34 : return {std::make_shared<dht::crypto::PrivateKey>(std::move(dht_key)),
144 17 : std::make_shared<dht::crypto::Certificate>(std::move(dht_cert))};
145 17 : } catch (const std::exception& e) {
146 0 : JAMI_ERROR("[Account {}] [Auth] Error loading identity: {}", accountId_, e.what());
147 0 : }
148 0 : return {};
149 : }
150 :
151 : std::shared_ptr<dht::Value>
152 13 : AccountManager::parseAnnounce(const std::string& announceBase64,
153 : const std::string& accountId,
154 : const std::string& deviceSha1,
155 : const std::string& deviceSha256)
156 : {
157 13 : auto announce_val = std::make_shared<dht::Value>();
158 : try {
159 13 : auto announce = base64::decode(announceBase64);
160 13 : msgpack::object_handle announce_msg = msgpack::unpack((const char*) announce.data(),
161 26 : announce.size());
162 13 : announce_val->msgpack_unpack(announce_msg.get());
163 13 : if (not announce_val->checkSignature()) {
164 0 : JAMI_ERROR("[Auth] announce signature check failed");
165 0 : return {};
166 : }
167 13 : DeviceAnnouncement da;
168 13 : da.unpackValue(*announce_val);
169 13 : if (da.from.toString() != accountId) {
170 0 : JAMI_ERROR("[Auth] Account ID mismatch in announce (account: {}, in announce: {})", accountId, da.from.toString());
171 0 : return {};
172 : }
173 13 : if ((da.pk && da.pk->getLongId().to_view() != deviceSha256) || da.dev.toString() != deviceSha1) {
174 0 : JAMI_ERROR("[Auth] Device ID mismatch in announce (device: {}, in announce: {})", da.pk ? deviceSha256 : deviceSha1, da.pk ? da.pk->getLongId().to_view() : da.dev.toString());
175 0 : return {};
176 : }
177 13 : } catch (const std::exception& e) {
178 0 : JAMI_ERROR("[Auth] unable to read announce: {}", e.what());
179 0 : return {};
180 0 : }
181 13 : return announce_val;
182 13 : }
183 :
184 : const AccountInfo*
185 647 : AccountManager::useIdentity(const dht::crypto::Identity& identity,
186 : const std::string& receipt,
187 : const std::vector<uint8_t>& receiptSignature,
188 : const std::string& username,
189 : const OnChangeCallback& onChange)
190 : {
191 647 : if (receipt.empty() or receiptSignature.empty())
192 634 : return nullptr;
193 :
194 13 : if (not identity.first or not identity.second) {
195 0 : JAMI_ERROR("[Account {}] [Auth] no identity provided", accountId_);
196 0 : return nullptr;
197 : }
198 :
199 13 : auto accountCertificate = identity.second->issuer;
200 13 : if (not accountCertificate) {
201 0 : JAMI_ERROR("[Account {}] [Auth] device certificate must be issued by the account certificate", accountId_);
202 0 : return nullptr;
203 : }
204 :
205 : // match certificate chain
206 13 : auto contactList = std::make_unique<ContactList>(accountId_, accountCertificate, path_, onChange);
207 13 : auto result = contactList->isValidAccountDevice(*identity.second);
208 13 : if (not result) {
209 0 : JAMI_ERROR("[Account {}] [Auth] unable to use identity: device certificate chain is unable to be verified: {}", accountId_,
210 : result.toString());
211 0 : return nullptr;
212 : }
213 :
214 13 : auto pk = accountCertificate->getSharedPublicKey();
215 39 : JAMI_LOG("[Account {}] [Auth] checking device receipt for account:{} device:{}", accountId_, pk->getId().toString(), identity.second->getLongId().toString());
216 13 : if (!pk->checkSignature({receipt.begin(), receipt.end()}, receiptSignature)) {
217 0 : JAMI_ERROR("[Account {}] [Auth] device receipt signature check failed", accountId_);
218 0 : return nullptr;
219 : }
220 :
221 13 : Json::Value root;
222 13 : if (!json::parse(receipt, root) || !root.isMember("announce")) {
223 0 : JAMI_ERROR("[Account {}] [Auth] device receipt parsing error", accountId_);
224 0 : return nullptr;
225 : }
226 :
227 13 : auto dev_id = root["dev"].asString();
228 13 : if (dev_id != identity.second->getId().toString()) {
229 0 : JAMI_ERROR("[Account {}] [Auth] device ID mismatch between receipt and certificate", accountId_);
230 0 : return nullptr;
231 : }
232 13 : auto id = root["id"].asString();
233 13 : if (id != pk->getId().toString()) {
234 0 : JAMI_ERROR("[Account {}] [Auth] account ID mismatch between receipt and certificate", accountId_);
235 0 : return nullptr;
236 : }
237 :
238 13 : auto devicePk = identity.first->getSharedPublicKey();
239 13 : if (!devicePk) {
240 0 : JAMI_ERROR("[Account {}] [Auth] No device pk found", accountId_);
241 0 : return nullptr;
242 : }
243 :
244 26 : auto announce = parseAnnounce(root["announce"].asString(), id, devicePk->getId().toString(), devicePk->getLongId().toString());
245 13 : if (not announce) {
246 0 : return nullptr;
247 : }
248 :
249 13 : onChange_ = std::move(onChange);
250 :
251 13 : auto info = std::make_unique<AccountInfo>();
252 13 : info->identity = identity;
253 13 : info->contacts = std::move(contactList);
254 13 : info->contacts->load();
255 13 : info->accountId = id;
256 13 : info->devicePk = std::move(devicePk);
257 13 : info->deviceId = info->devicePk->getLongId().toString();
258 13 : info->announce = std::move(announce);
259 13 : info->ethAccount = root["eth"].asString();
260 13 : info->username = username;
261 13 : info_ = std::move(info);
262 :
263 39 : JAMI_LOG("[Account {}] [Auth] Device {} receipt checked successfully for user {}", accountId_,
264 : info_->deviceId, id);
265 13 : return info_.get();
266 13 : }
267 :
268 : void
269 0 : AccountManager::reloadContacts()
270 : {
271 0 : if (info_) {
272 0 : info_->contacts->load();
273 : }
274 0 : }
275 :
276 : void
277 1135 : AccountManager::startSync(const OnNewDeviceCb& cb, const OnDeviceAnnouncedCb& dcb, bool publishPresence)
278 : {
279 : // Put device announcement
280 1135 : if (info_->announce) {
281 1135 : auto h = dht::InfoHash(info_->accountId);
282 1135 : if (publishPresence) {
283 4540 : dht_->put(
284 : h,
285 1135 : info_->announce,
286 2270 : [dcb = std::move(dcb), h, accountId=accountId_](bool ok) {
287 1135 : if (ok)
288 3339 : JAMI_DEBUG("[Account {}] device announced at {}", accountId, h.toString());
289 : // We do not care about the status, it's a permanent put, if this fail,
290 : // this means the DHT is disconnected but the put will be retried when connected.
291 1135 : if (dcb)
292 1135 : dcb();
293 1135 : },
294 : {},
295 : true);
296 : }
297 1135 : for (const auto& crl : info_->identity.second->issuer->getRevocationLists())
298 1135 : dht_->put(h, crl, dht::DoneCallback {}, {}, true);
299 1135 : dht_->listen<DeviceAnnouncement>(h, [this, cb = std::move(cb)](DeviceAnnouncement&& dev) {
300 1250 : findCertificate(dev.dev,
301 1250 : [this, cb](const std::shared_ptr<dht::crypto::Certificate>& crt) {
302 1250 : foundAccountDevice(crt);
303 1250 : if (cb)
304 1250 : cb(crt);
305 1250 : });
306 1250 : return true;
307 : });
308 1135 : dht_->listen<dht::crypto::RevocationList>(h, [this](dht::crypto::RevocationList&& crl) {
309 6 : if (crl.isSignedBy(*info_->identity.second->issuer)) {
310 18 : JAMI_DEBUG("[Account {}] Found CRL for account.", accountId_);
311 6 : certStore()
312 6 : .pinRevocationList(info_->accountId,
313 12 : std::make_shared<dht::crypto::RevocationList>(
314 6 : std::move(crl)));
315 : }
316 6 : return true;
317 : });
318 1135 : syncDevices();
319 : } else {
320 0 : JAMI_ERROR("[Account {}] Unable to announce device: no announcement.", accountId_);
321 : }
322 :
323 1135 : auto inboxKey = dht::InfoHash::get("inbox:" + info_->devicePk->getId().toString());
324 1135 : dht_->listen<dht::TrustRequest>(inboxKey, [this](dht::TrustRequest&& v) {
325 197 : if (v.service != DHT_TYPE_NS)
326 0 : return true;
327 :
328 : // allowPublic always true for trust requests (only forbidden if banned)
329 394 : onPeerMessage(
330 197 : *v.owner,
331 : true,
332 194 : [this, v](const std::shared_ptr<dht::crypto::Certificate>&,
333 656 : dht::InfoHash peer_account) mutable {
334 582 : JAMI_WARNING("[Account {}] Got trust request (confirm: {}) from: {} / {}. ConversationId: {}",
335 : accountId_,
336 : v.confirm,
337 : peer_account.toString(),
338 : v.from.toString(),
339 : v.conversationId);
340 194 : if (info_)
341 388 : if (info_->contacts->onTrustRequest(peer_account,
342 194 : v.owner,
343 : time(nullptr),
344 194 : v.confirm,
345 194 : v.conversationId,
346 194 : std::move(v.payload))) {
347 37 : if (v.confirm) // No need to send a confirmation as already accepted here
348 29 : return;
349 37 : auto conversationId = v.conversationId;
350 : // Check if there was an old active conversation.
351 37 : if (auto details = info_->contacts->getContactInfo(peer_account)) {
352 37 : if (!details->conversationId.empty()) {
353 37 : if (details->conversationId == conversationId) {
354 : // Here, it's possible that we already have accepted the conversation
355 : // but contact were offline and sync failed.
356 : // So, retrigger the callback so upper layer will clone conversation if needed
357 : // instead of getting stuck in sync.
358 29 : info_->contacts->acceptConversation(conversationId, v.owner->getLongId().toString());
359 29 : return;
360 : }
361 8 : conversationId = details->conversationId;
362 24 : JAMI_WARNING("Accept with old convId: {}", conversationId);
363 : }
364 37 : }
365 8 : sendTrustRequestConfirm(peer_account, conversationId);
366 37 : }
367 : });
368 197 : return true;
369 : });
370 1135 : }
371 :
372 : const std::map<dht::PkId, KnownDevice>&
373 1550 : AccountManager::getKnownDevices() const
374 : {
375 1550 : return info_->contacts->getKnownDevices();
376 : }
377 :
378 : bool
379 1611 : AccountManager::foundAccountDevice(const std::shared_ptr<dht::crypto::Certificate>& crt,
380 : const std::string& name,
381 : const time_point& last_sync)
382 : {
383 1611 : return info_->contacts->foundAccountDevice(crt, name, last_sync);
384 : }
385 :
386 : void
387 17 : AccountManager::setAccountDeviceName(const std::string& name)
388 : {
389 17 : if (info_)
390 13 : info_->contacts->setAccountDeviceName(DeviceId(info_->deviceId), name);
391 17 : }
392 :
393 : std::string
394 630 : AccountManager::getAccountDeviceName() const
395 : {
396 630 : if (info_)
397 1260 : return info_->contacts->getAccountDeviceName(DeviceId(info_->deviceId));
398 0 : return {};
399 : }
400 :
401 : bool
402 911 : AccountManager::foundPeerDevice(const std::string& accountId, const std::shared_ptr<dht::crypto::Certificate>& crt,
403 : dht::InfoHash& peer_id)
404 : {
405 911 : if (not crt)
406 0 : return false;
407 :
408 911 : auto top_issuer = crt;
409 2733 : while (top_issuer->issuer)
410 1822 : top_issuer = top_issuer->issuer;
411 :
412 : // Device certificate is unable to be self-signed
413 911 : if (top_issuer == crt) {
414 0 : JAMI_WARNING("[Account {}] Found invalid peer device: {}", accountId, crt->getLongId().toString());
415 0 : return false;
416 : }
417 :
418 : // Check peer certificate chain
419 : // Trust store with top issuer as the only CA
420 911 : dht::crypto::TrustList peer_trust;
421 911 : peer_trust.add(*top_issuer);
422 911 : if (not peer_trust.verify(*crt)) {
423 0 : JAMI_WARNING("[Account {}] Found invalid peer device: {}", accountId, crt->getLongId().toString());
424 0 : return false;
425 : }
426 :
427 : // Check cached OCSP response
428 911 : if (crt->ocspResponse and crt->ocspResponse->getCertificateStatus() != GNUTLS_OCSP_CERT_GOOD) {
429 0 : JAMI_WARNING("[Account {}] Certificate {} is disabled by cached OCSP response", accountId, crt->getLongId());
430 0 : return false;
431 : }
432 :
433 911 : peer_id = crt->issuer->getId();
434 2733 : JAMI_LOG("[Account {}] Found peer device: {} account:{} CA:{}",
435 : accountId,
436 : crt->getLongId().toString(),
437 : peer_id.toString(),
438 : top_issuer->getId().toString());
439 911 : return true;
440 911 : }
441 :
442 : void
443 197 : AccountManager::onPeerMessage(const dht::crypto::PublicKey& peer_device,
444 : bool allowPublic,
445 : std::function<void(const std::shared_ptr<dht::crypto::Certificate>& crt,
446 : const dht::InfoHash& peer_account)>&& cb)
447 : {
448 : // quick check in case we already explicilty banned this device
449 197 : auto trustStatus = getCertificateStatus(peer_device.toString());
450 197 : if (trustStatus == dhtnet::tls::TrustStore::PermissionStatus::BANNED) {
451 0 : JAMI_WARNING("[Account {}] [Auth] Discarding message from banned device {}", accountId_, peer_device.toString());
452 0 : return;
453 : }
454 :
455 197 : findCertificate(peer_device.getId(),
456 197 : [this, cb = std::move(cb), allowPublic](
457 197 : const std::shared_ptr<dht::crypto::Certificate>& cert) {
458 197 : dht::InfoHash peer_account_id;
459 197 : if (onPeerCertificate(cert, allowPublic, peer_account_id)) {
460 194 : cb(cert, peer_account_id);
461 : }
462 197 : });
463 : }
464 :
465 : bool
466 911 : AccountManager::onPeerCertificate(const std::shared_ptr<dht::crypto::Certificate>& cert,
467 : bool allowPublic,
468 : dht::InfoHash& account_id)
469 : {
470 911 : dht::InfoHash peer_account_id;
471 911 : if (not foundPeerDevice(accountId_, cert, peer_account_id)) {
472 0 : JAMI_WARNING("[Account {}] [Auth] Discarding message from invalid peer certificate", accountId_);
473 0 : return false;
474 : }
475 :
476 911 : if (not isAllowed(*cert, allowPublic)) {
477 21 : JAMI_WARNING("[Account {}] [Auth] Discarding message from unauthorized peer {}.",
478 : accountId_, peer_account_id.toString());
479 7 : return false;
480 : }
481 :
482 904 : account_id = peer_account_id;
483 904 : return true;
484 : }
485 :
486 : bool
487 55 : AccountManager::addContact(const dht::InfoHash& uri, bool confirmed, const std::string& conversationId)
488 : {
489 55 : if (not info_) {
490 0 : JAMI_ERROR("addContact(): account not loaded");
491 0 : return false;
492 : }
493 165 : JAMI_WARNING("[Account {}] addContact {}", accountId_, confirmed);
494 55 : if (info_->contacts->addContact(uri, confirmed, conversationId)) {
495 55 : syncDevices();
496 55 : return true;
497 : }
498 0 : return false;
499 : }
500 :
501 : void
502 17 : AccountManager::removeContact(const std::string& uri, bool banned)
503 : {
504 17 : dht::InfoHash h(uri);
505 17 : if (not h) {
506 0 : JAMI_ERROR("[Account {}] removeContact: invalid contact URI", accountId_);
507 0 : return;
508 : }
509 17 : if (not info_) {
510 0 : JAMI_ERROR("[Account {}] removeContact: account not loaded", accountId_);
511 0 : return;
512 : }
513 17 : if (info_->contacts->removeContact(h, banned))
514 17 : syncDevices();
515 : }
516 :
517 : void
518 0 : AccountManager::removeContactConversation(const std::string& uri)
519 : {
520 0 : dht::InfoHash h(uri);
521 0 : if (not h) {
522 0 : JAMI_ERROR("[Account {}] removeContactConversation: invalid contact URI", accountId_);
523 0 : return;
524 : }
525 0 : if (not info_) {
526 0 : JAMI_ERROR("[Account {}] removeContactConversation: account not loaded", accountId_);
527 0 : return;
528 : }
529 0 : if (info_->contacts->removeContactConversation(h))
530 0 : syncDevices();
531 : }
532 :
533 : void
534 17 : AccountManager::updateContactConversation(const std::string& uri, const std::string& convId)
535 : {
536 17 : dht::InfoHash h(uri);
537 17 : if (not h) {
538 0 : JAMI_ERROR("[Account {}] updateContactConversation: invalid contact URI", accountId_);
539 0 : return;
540 : }
541 17 : if (not info_) {
542 0 : JAMI_ERROR("[Account {}] updateContactConversation: account not loaded", accountId_);
543 0 : return;
544 : }
545 17 : info_->contacts->updateConversation(h, convId);
546 : // Also decline trust request if there is one
547 17 : auto req = info_->contacts->getTrustRequest(h);
548 34 : if (req.find(libjami::Account::TrustRequest::CONVERSATIONID) != req.end()
549 34 : && req.at(libjami::Account::TrustRequest::CONVERSATIONID) == convId) {
550 0 : discardTrustRequest(uri);
551 : }
552 17 : syncDevices();
553 17 : }
554 :
555 : std::vector<std::map<std::string, std::string>>
556 587 : AccountManager::getContacts(bool includeRemoved) const
557 : {
558 587 : if (not info_) {
559 0 : JAMI_ERROR("[Account {}] getContacts(): account not loaded", accountId_);
560 0 : return {};
561 : }
562 587 : const auto& contacts = info_->contacts->getContacts();
563 587 : std::vector<std::map<std::string, std::string>> ret;
564 587 : ret.reserve(contacts.size());
565 :
566 590 : for (const auto& c : contacts) {
567 3 : if (!c.second.isActive() && !includeRemoved && !c.second.isBanned())
568 0 : continue;
569 3 : auto details = c.second.toMap();
570 3 : if (not details.empty()) {
571 3 : details["id"] = c.first.toString();
572 3 : ret.emplace_back(std::move(details));
573 : }
574 3 : }
575 587 : return ret;
576 587 : }
577 :
578 : /** Obtain details about one account contact in serializable form. */
579 : std::map<std::string, std::string>
580 2 : AccountManager::getContactDetails(const std::string& uri) const
581 : {
582 2 : if (!info_) {
583 0 : JAMI_ERROR("[Account {}] getContactDetails(): account not loaded", accountId_);
584 0 : return {};
585 : }
586 2 : dht::InfoHash h(uri);
587 2 : if (not h) {
588 0 : JAMI_ERROR("[Account {}] getContactDetails: invalid contact URI", accountId_);
589 0 : return {};
590 : }
591 2 : return info_->contacts->getContactDetails(h);
592 : }
593 :
594 : std::optional<Contact>
595 603 : AccountManager::getContactInfo(const std::string& uri) const
596 : {
597 603 : if (!info_) {
598 0 : JAMI_ERROR("[Account {}] getContactInfo(): account not loaded", accountId_);
599 0 : return {};
600 : }
601 603 : dht::InfoHash h(uri);
602 603 : if (not h) {
603 0 : JAMI_ERROR("[Account {}] getContactInfo: invalid contact URI", accountId_);
604 0 : return {};
605 : }
606 603 : return info_->contacts->getContactInfo(h);
607 : }
608 :
609 : bool
610 5682 : AccountManager::findCertificate(
611 : const dht::InfoHash& h,
612 : std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb)
613 : {
614 11364 : if (auto cert = certStore().getCertificate(h.toString())) {
615 4719 : if (cb)
616 4715 : cb(cert);
617 963 : } else if (dht_) {
618 1926 : dht_->findCertificate(h,
619 963 : [cb = std::move(cb), this](
620 1762 : const std::shared_ptr<dht::crypto::Certificate>& crt) {
621 963 : if (crt && info_) {
622 881 : certStore().pinCertificate(crt);
623 : }
624 963 : if (cb)
625 881 : cb(crt);
626 963 : });
627 5682 : }
628 5682 : return true;
629 : }
630 :
631 : bool
632 717 : AccountManager::findCertificate(
633 : const dht::PkId& id, std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb)
634 : {
635 1434 : if (auto cert = certStore().getCertificate(id.toString())) {
636 716 : if (cb)
637 716 : cb(cert);
638 4 : } else if (auto cert = certStore().getCertificateLegacy(fileutils::get_data_dir().string(),
639 3 : id.toString())) {
640 0 : if (cb)
641 0 : cb(cert);
642 1 : } else if (cb)
643 718 : cb(nullptr);
644 717 : return true;
645 : }
646 :
647 : bool
648 89 : AccountManager::setCertificateStatus(const std::string& cert_id,
649 : dhtnet::tls::TrustStore::PermissionStatus status)
650 : {
651 89 : return info_ and info_->contacts->setCertificateStatus(cert_id, status);
652 : }
653 :
654 : bool
655 0 : AccountManager::setCertificateStatus(const std::shared_ptr<crypto::Certificate>& cert,
656 : dhtnet::tls::TrustStore::PermissionStatus status,
657 : bool local)
658 : {
659 0 : return info_ and info_->contacts->setCertificateStatus(cert, status, local);
660 : }
661 :
662 : std::vector<std::string>
663 0 : AccountManager::getCertificatesByStatus(dhtnet::tls::TrustStore::PermissionStatus status)
664 : {
665 0 : return info_ ? info_->contacts->getCertificatesByStatus(status) : std::vector<std::string> {};
666 : }
667 :
668 : dhtnet::tls::TrustStore::PermissionStatus
669 7849 : AccountManager::getCertificateStatus(const std::string& cert_id) const
670 : {
671 7849 : return info_ ? info_->contacts->getCertificateStatus(cert_id)
672 15698 : : dhtnet::tls::TrustStore::PermissionStatus::UNDEFINED;
673 : }
674 :
675 : bool
676 911 : AccountManager::isAllowed(const crypto::Certificate& crt, bool allowPublic)
677 : {
678 911 : return info_ and info_->contacts->isAllowed(crt, allowPublic);
679 : }
680 :
681 : std::vector<std::map<std::string, std::string>>
682 608 : AccountManager::getTrustRequests() const
683 : {
684 608 : if (not info_) {
685 0 : JAMI_ERROR("[Account {}] getTrustRequests(): account not loaded", accountId_);
686 0 : return {};
687 : }
688 608 : return info_->contacts->getTrustRequests();
689 : }
690 :
691 : bool
692 167 : AccountManager::acceptTrustRequest(const std::string& from, bool includeConversation)
693 : {
694 167 : dht::InfoHash f(from);
695 167 : if (info_) {
696 167 : auto req = info_->contacts->getTrustRequest(dht::InfoHash(from));
697 167 : if (info_->contacts->acceptTrustRequest(f)) {
698 36 : sendTrustRequestConfirm(f,
699 : includeConversation
700 72 : ? req[libjami::Account::TrustRequest::CONVERSATIONID]
701 : : "");
702 36 : syncDevices();
703 36 : return true;
704 : }
705 131 : return false;
706 167 : }
707 0 : return false;
708 : }
709 :
710 : bool
711 3 : AccountManager::discardTrustRequest(const std::string& from)
712 : {
713 3 : dht::InfoHash f(from);
714 3 : return info_ and info_->contacts->discardTrustRequest(f);
715 : }
716 :
717 : void
718 53 : AccountManager::sendTrustRequest(const std::string& to,
719 : const std::string& convId,
720 : const std::vector<uint8_t>& payload)
721 : {
722 159 : JAMI_WARNING("[Account {}] AccountManager::sendTrustRequest", accountId_);
723 53 : auto toH = dht::InfoHash(to);
724 53 : if (not toH) {
725 0 : JAMI_ERROR("[Account {}] Unable to send trust request to invalid hash: {}", accountId_, to);
726 0 : return;
727 : }
728 53 : if (not info_) {
729 0 : JAMI_ERROR("[Account {}] sendTrustRequest(): account not loaded", accountId_);
730 0 : return;
731 : }
732 53 : if (info_->contacts->addContact(toH, false, convId)) {
733 1 : syncDevices();
734 : }
735 53 : forEachDevice(toH,
736 174 : [this, toH, convId, payload](const std::shared_ptr<dht::crypto::PublicKey>& dev) {
737 58 : auto to = toH.toString();
738 174 : JAMI_WARNING("[Account {}] Sending trust request to: {:s} / {:s} of size {:d}",
739 : accountId_, to, dev->getLongId(), payload.size());
740 232 : dht_->putEncrypted(dht::InfoHash::get("inbox:" + dev->getId().toString()),
741 : dev,
742 116 : dht::TrustRequest(DHT_TYPE_NS, convId, payload),
743 58 : [to, size = payload.size()](bool ok) {
744 58 : if (!ok)
745 45 : JAMI_ERROR("Tried to send request {:s} (size: "
746 : "{:d}), but put failed",
747 : to,
748 : size);
749 58 : });
750 58 : });
751 : }
752 :
753 : void
754 44 : AccountManager::sendTrustRequestConfirm(const dht::InfoHash& toH, const std::string& convId)
755 : {
756 132 : JAMI_WARNING("[Account {}] AccountManager::sendTrustRequestConfirm to {} (conversation {})", accountId_, toH, convId);
757 88 : dht::TrustRequest answer {DHT_TYPE_NS, convId};
758 44 : answer.confirm = true;
759 :
760 44 : if (!convId.empty() && info_)
761 44 : info_->contacts->acceptConversation(convId);
762 :
763 44 : forEachDevice(toH, [this, toH, answer](const std::shared_ptr<dht::crypto::PublicKey>& dev) {
764 138 : JAMI_WARNING("[Account {}] sending trust request reply: {} / {}",
765 : accountId_, toH, dev->getLongId());
766 46 : dht_->putEncrypted(dht::InfoHash::get("inbox:" + dev->getId().toString()), dev, answer);
767 46 : });
768 44 : }
769 :
770 : void
771 3737 : AccountManager::forEachDevice(
772 : const dht::InfoHash& to,
773 : std::function<void(const std::shared_ptr<dht::crypto::PublicKey>&)>&& op,
774 : std::function<void(bool)>&& end)
775 : {
776 3737 : if (not dht_) {
777 0 : JAMI_ERROR("[Account {}] forEachDevice: no dht", accountId_);
778 0 : if (end)
779 0 : end(false);
780 0 : return;
781 : }
782 3737 : dht_->get<dht::crypto::RevocationList>(to, [to, this](dht::crypto::RevocationList&& crl) {
783 0 : certStore().pinRevocationList(to.toString(), std::move(crl));
784 0 : return true;
785 : });
786 :
787 : struct State
788 : {
789 : const dht::InfoHash to;
790 : const std::string accountId;
791 : // Note: state is initialized to 1, because we need to wait that the get is finished
792 : unsigned remaining {1};
793 : std::set<dht::PkId> treatedDevices {};
794 : std::function<void(const std::shared_ptr<dht::crypto::PublicKey>&)> onDevice;
795 : std::function<void(bool)> onEnd;
796 :
797 3737 : State(dht::InfoHash to, std::string accountId)
798 3737 : : to(std::move(to)), accountId(std::move(accountId)) {}
799 :
800 7524 : void found(const std::shared_ptr<dht::crypto::PublicKey>& pk)
801 : {
802 7524 : remaining--;
803 7524 : if (pk && *pk) {
804 3787 : auto longId = pk->getLongId();
805 3787 : if (treatedDevices.emplace(longId).second) {
806 3782 : onDevice(pk);
807 : }
808 : }
809 7524 : ended();
810 7524 : }
811 :
812 7524 : void ended()
813 : {
814 7524 : if (remaining == 0 && onEnd) {
815 966 : JAMI_LOG("[Account {}] Found {:d} device(s) for {}", accountId, treatedDevices.size(), to);
816 322 : onEnd(not treatedDevices.empty());
817 322 : onDevice = {};
818 322 : onEnd = {};
819 : }
820 7524 : }
821 : };
822 3737 : auto state = std::make_shared<State>(to, accountId_);
823 3737 : state->onDevice = std::move(op);
824 3737 : state->onEnd = std::move(end);
825 :
826 3737 : dht_->get<DeviceAnnouncement>(
827 : to,
828 7574 : [this, to, state](DeviceAnnouncement&& dev) {
829 3787 : if (dev.from != to)
830 0 : return true;
831 3787 : state->remaining++;
832 3787 : findCertificate(dev.dev, [state](const std::shared_ptr<dht::crypto::Certificate>& cert) {
833 7574 : state->found(cert ? cert->getSharedPublicKey()
834 3787 : : std::shared_ptr<dht::crypto::PublicKey> {});
835 3787 : });
836 3787 : return true;
837 : },
838 3737 : [state](bool /*ok*/) { state->found({}); });
839 3737 : }
840 :
841 : void
842 3 : AccountManager::lookupUri(const std::string& name,
843 : const std::string& defaultServer,
844 : LookupCallback cb)
845 : {
846 3 : nameDir_.get().lookupUri(name, defaultServer, std::move(cb));
847 3 : }
848 :
849 : void
850 679 : AccountManager::lookupAddress(const std::string& addr, LookupCallback cb)
851 : {
852 679 : nameDir_.get().lookupAddress(addr, cb);
853 679 : }
854 :
855 : dhtnet::tls::CertificateStore&
856 7291 : AccountManager::certStore() const
857 : {
858 7291 : return Manager::instance().certStore(info_->contacts->accountId());
859 : }
860 :
861 : } // namespace jami
|