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 :
18 : #ifdef HAVE_CONFIG_H
19 : #include "config.h"
20 : #endif
21 :
22 : #include "jamiaccount.h"
23 :
24 : #include "logger.h"
25 :
26 : #include "accountarchive.h"
27 : #include "jami_contact.h"
28 : #include "configkeys.h"
29 : #include "contact_list.h"
30 : #include "archive_account_manager.h"
31 : #include "server_account_manager.h"
32 : #include "jamidht/channeled_transport.h"
33 : #include "conversation_channel_handler.h"
34 : #include "sync_channel_handler.h"
35 : #include "message_channel_handler.h"
36 : #include "auth_channel_handler.h"
37 : #include "transfer_channel_handler.h"
38 : #include "swarm/swarm_channel_handler.h"
39 : #include "jami/media_const.h"
40 :
41 : #include "sip/sdp.h"
42 : #include "sip/sipvoiplink.h"
43 : #include "sip/sipcall.h"
44 : #include "sip/siptransport.h"
45 : #include "connectivity/sip_utils.h"
46 :
47 : #include "uri.h"
48 :
49 : #include "client/ring_signal.h"
50 : #include "jami/call_const.h"
51 : #include "jami/account_const.h"
52 :
53 : #include "system_codec_container.h"
54 :
55 : #include "account_schema.h"
56 : #include "manager.h"
57 : #include "connectivity/utf8_utils.h"
58 : #include "connectivity/ip_utils.h"
59 :
60 : #ifdef ENABLE_PLUGIN
61 : #include "plugin/jamipluginmanager.h"
62 : #include "plugin/chatservicesmanager.h"
63 : #endif
64 :
65 : #ifdef ENABLE_VIDEO
66 : #include "libav_utils.h"
67 : #endif
68 : #include "fileutils.h"
69 : #include "string_utils.h"
70 : #include "archiver.h"
71 : #include "data_transfer.h"
72 : #include "json_utils.h"
73 :
74 : #include "libdevcrypto/Common.h"
75 : #include "base64.h"
76 : #include "vcard.h"
77 : #include "im/instant_messaging.h"
78 :
79 : #include <dhtnet/ice_transport.h>
80 : #include <dhtnet/ice_transport_factory.h>
81 : #include <dhtnet/upnp/upnp_control.h>
82 : #include <dhtnet/multiplexed_socket.h>
83 : #include <dhtnet/certstore.h>
84 :
85 : #include <opendht/thread_pool.h>
86 : #include <opendht/peer_discovery.h>
87 : #include <opendht/http.h>
88 :
89 : #include <yaml-cpp/yaml.h>
90 : #include <fmt/format.h>
91 :
92 : #include <unistd.h>
93 :
94 : #include <algorithm>
95 : #include <array>
96 : #include <cctype>
97 : #include <charconv>
98 : #include <cinttypes>
99 : #include <cstdarg>
100 : #include <initializer_list>
101 : #include <memory>
102 : #include <regex>
103 : #include <sstream>
104 : #include <string>
105 : #include <system_error>
106 :
107 : using namespace std::placeholders;
108 :
109 : namespace jami {
110 :
111 : constexpr pj_str_t STR_MESSAGE_ID = jami::sip_utils::CONST_PJ_STR("Message-ID");
112 : static constexpr const char MIME_TYPE_IMDN[] {"message/imdn+xml"};
113 : static constexpr const char MIME_TYPE_PIDF[] {"application/pidf+xml"};
114 : static constexpr const char MIME_TYPE_INVITE_JSON[] {"application/invite+json"};
115 : static constexpr const char DEVICE_ID_PATH[] {"ring_device"};
116 : static constexpr auto TREATED_PATH = "treatedImMessages"sv;
117 :
118 : struct VCardMessageCtx
119 : {
120 : std::shared_ptr<std::atomic_int> success;
121 : int total;
122 : std::string path;
123 : };
124 :
125 : namespace Migration {
126 :
127 : enum class State { // Contains all the Migration states
128 : SUCCESS,
129 : INVALID
130 : };
131 :
132 : std::string
133 4 : mapStateNumberToString(const State migrationState)
134 : {
135 : #define CASE_STATE(X) \
136 : case Migration::State::X: \
137 : return #X
138 :
139 4 : switch (migrationState) {
140 0 : CASE_STATE(INVALID);
141 4 : CASE_STATE(SUCCESS);
142 : }
143 0 : return {};
144 : }
145 :
146 : void
147 4 : setState(const std::string& accountID, const State migrationState)
148 : {
149 4 : emitSignal<libjami::ConfigurationSignal::MigrationEnded>(accountID, mapStateNumberToString(migrationState));
150 4 : }
151 :
152 : } // namespace Migration
153 :
154 : struct JamiAccount::BuddyInfo
155 : {
156 : /* the buddy id */
157 : dht::InfoHash id;
158 :
159 : /* number of devices connected on the DHT */
160 : uint32_t devices_cnt {};
161 :
162 : /* The disposable object to update buddy info */
163 : std::future<size_t> listenToken;
164 :
165 34 : BuddyInfo(dht::InfoHash id)
166 34 : : id(id)
167 34 : {}
168 : };
169 :
170 : struct JamiAccount::PendingCall
171 : {
172 : std::chrono::steady_clock::time_point start;
173 : std::shared_ptr<IceTransport> ice_sp;
174 : std::shared_ptr<IceTransport> ice_tcp_sp;
175 : std::weak_ptr<SIPCall> call;
176 : std::future<size_t> listen_key;
177 : dht::InfoHash call_key;
178 : dht::InfoHash from;
179 : dht::InfoHash from_account;
180 : std::shared_ptr<dht::crypto::Certificate> from_cert;
181 : };
182 :
183 : struct JamiAccount::PendingMessage
184 : {
185 : std::set<DeviceId> to;
186 : };
187 :
188 : struct AccountPeerInfo
189 : {
190 : dht::InfoHash accountId;
191 : std::string displayName;
192 0 : MSGPACK_DEFINE(accountId, displayName)
193 : };
194 :
195 : struct JamiAccount::DiscoveredPeer
196 : {
197 : std::string displayName;
198 : std::shared_ptr<Task> cleanupTask;
199 : };
200 :
201 : static constexpr const char* const RING_URI_PREFIX = "ring:";
202 : static constexpr const char* const JAMI_URI_PREFIX = "jami:";
203 : static const auto PROXY_REGEX = std::regex("(https?://)?([\\w\\.\\-_\\~]+)(:(\\d+)|:\\[(.+)-(.+)\\])?");
204 : static const std::string PEER_DISCOVERY_JAMI_SERVICE = "jami";
205 : const constexpr auto PEER_DISCOVERY_EXPIRATION = std::chrono::minutes(1);
206 :
207 : using ValueIdDist = std::uniform_int_distribution<dht::Value::Id>;
208 :
209 : std::string_view
210 40454 : stripPrefix(std::string_view toUrl)
211 : {
212 40454 : auto dhtf = toUrl.find(RING_URI_PREFIX);
213 40418 : if (dhtf != std::string_view::npos) {
214 0 : dhtf = dhtf + 5;
215 : } else {
216 40418 : dhtf = toUrl.find(JAMI_URI_PREFIX);
217 40419 : if (dhtf != std::string_view::npos) {
218 0 : dhtf = dhtf + 5;
219 : } else {
220 40419 : dhtf = toUrl.find("sips:");
221 40414 : dhtf = (dhtf == std::string_view::npos) ? 0 : dhtf + 5;
222 : }
223 : }
224 40414 : while (dhtf < toUrl.length() && toUrl[dhtf] == '/')
225 0 : dhtf++;
226 40413 : return toUrl.substr(dhtf);
227 : }
228 :
229 : std::string_view
230 40452 : parseJamiUri(std::string_view toUrl)
231 : {
232 40452 : auto sufix = stripPrefix(toUrl);
233 40412 : if (sufix.length() < 40)
234 0 : throw std::invalid_argument("ID must be a Jami infohash");
235 :
236 40413 : const std::string_view toUri = sufix.substr(0, 40);
237 40412 : if (std::find_if_not(toUri.cbegin(), toUri.cend(), ::isxdigit) != toUri.cend())
238 0 : throw std::invalid_argument("ID must be a Jami infohash");
239 40454 : return toUri;
240 : }
241 :
242 : static constexpr std::string_view
243 4008 : dhtStatusStr(dht::NodeStatus status)
244 : {
245 : return status == dht::NodeStatus::Connected
246 2028 : ? "connected"sv
247 4008 : : (status == dht::NodeStatus::Connecting ? "connecting"sv : "disconnected"sv);
248 : }
249 :
250 777 : JamiAccount::JamiAccount(const std::string& accountId)
251 : : SIPAccountBase(accountId)
252 777 : , cachePath_(fileutils::get_cache_dir() / accountId)
253 777 : , dataPath_(cachePath_ / "values")
254 777 : , certStore_ {std::make_unique<dhtnet::tls::CertificateStore>(idPath_, Logger::dhtLogger())}
255 777 : , dht_(new dht::DhtRunner)
256 777 : , treatedMessages_(cachePath_ / TREATED_PATH)
257 777 : , connectionManager_ {}
258 3885 : , nonSwarmTransferManager_()
259 777 : {}
260 :
261 1554 : JamiAccount::~JamiAccount() noexcept
262 : {
263 777 : if (dht_)
264 777 : dht_->join();
265 777 : }
266 :
267 : void
268 797 : JamiAccount::shutdownConnections()
269 : {
270 797 : JAMI_DBG("[Account %s] Shutdown connections", getAccountID().c_str());
271 :
272 797 : decltype(gitServers_) gservers;
273 : {
274 797 : std::lock_guard lk(gitServersMtx_);
275 797 : gservers = std::move(gitServers_);
276 797 : }
277 1224 : for (auto& [_id, gs] : gservers)
278 427 : gs->stop();
279 : {
280 797 : std::lock_guard lk(connManagerMtx_);
281 : // Just move destruction on another thread.
282 1594 : dht::ThreadPool::io().run(
283 797 : [conMgr = std::make_shared<decltype(connectionManager_)>(std::move(connectionManager_))] {});
284 797 : connectionManager_.reset();
285 797 : channelHandlers_.clear();
286 797 : }
287 797 : if (convModule_) {
288 692 : convModule_->shutdownConnections();
289 : }
290 :
291 797 : std::lock_guard lk(sipConnsMtx_);
292 797 : sipConns_.clear();
293 797 : }
294 :
295 : void
296 772 : JamiAccount::flush()
297 : {
298 : // Class base method
299 772 : SIPAccountBase::flush();
300 :
301 772 : dhtnet::fileutils::removeAll(cachePath_);
302 772 : dhtnet::fileutils::removeAll(dataPath_);
303 772 : dhtnet::fileutils::removeAll(idPath_, true);
304 772 : }
305 :
306 : std::shared_ptr<SIPCall>
307 91 : JamiAccount::newIncomingCall(const std::string& from,
308 : const std::vector<libjami::MediaMap>& mediaList,
309 : const std::shared_ptr<SipTransport>& sipTransp)
310 : {
311 364 : JAMI_DEBUG("New incoming call from {:s} with {:d} media", from, mediaList.size());
312 :
313 91 : if (sipTransp) {
314 182 : auto call = Manager::instance().callFactory.newSipCall(shared(), Call::CallType::INCOMING, mediaList);
315 91 : call->setPeerUri(JAMI_URI_PREFIX + from);
316 91 : call->setPeerNumber(from);
317 :
318 91 : call->setSipTransport(sipTransp, getContactHeader(sipTransp));
319 :
320 91 : return call;
321 91 : }
322 :
323 0 : JAMI_ERR("newIncomingCall: unable to find matching call for %s", from.c_str());
324 0 : return nullptr;
325 : }
326 :
327 : std::shared_ptr<Call>
328 105 : JamiAccount::newOutgoingCall(std::string_view toUrl, const std::vector<libjami::MediaMap>& mediaList)
329 : {
330 105 : auto uri = Uri(toUrl);
331 105 : if (uri.scheme() == Uri::Scheme::SWARM || uri.scheme() == Uri::Scheme::RENDEZVOUS) {
332 : // NOTE: In this case newOutgoingCall can act as "unholdConference" and just attach the
333 : // host to the current hosted conference. So, no call will be returned in that case.
334 22 : return newSwarmOutgoingCallHelper(uri, mediaList);
335 : }
336 :
337 83 : auto& manager = Manager::instance();
338 83 : std::shared_ptr<SIPCall> call;
339 :
340 : // SIP allows sending empty invites, this use case is not used with Jami accounts.
341 83 : if (not mediaList.empty()) {
342 27 : call = manager.callFactory.newSipCall(shared(), Call::CallType::OUTGOING, mediaList);
343 : } else {
344 56 : JAMI_WARN("Media list is empty, setting a default list");
345 112 : call = manager.callFactory.newSipCall(shared(),
346 : Call::CallType::OUTGOING,
347 112 : MediaAttribute::mediaAttributesToMediaMaps(
348 168 : createDefaultMediaList(isVideoEnabled())));
349 : }
350 :
351 83 : if (not call)
352 0 : return {};
353 :
354 83 : std::shared_lock lkCM(connManagerMtx_);
355 83 : if (!connectionManager_)
356 0 : return {};
357 :
358 83 : connectionManager_->getIceOptions([call, w = weak(), uri = std::move(uri)](auto&& opts) {
359 83 : if (call->isIceEnabled()) {
360 83 : if (not call->createIceMediaTransport(false)
361 166 : or not call->initIceMediaTransport(true, std::forward<dhtnet::IceTransportOptions>(opts))) {
362 0 : return;
363 : }
364 : }
365 83 : auto shared = w.lock();
366 83 : if (!shared)
367 0 : return;
368 83 : JAMI_DBG() << "New outgoing call with " << uri.toString();
369 83 : call->setPeerNumber(uri.authority());
370 83 : call->setPeerUri(uri.toString());
371 :
372 83 : shared->newOutgoingCallHelper(call, uri);
373 83 : });
374 :
375 83 : return call;
376 105 : }
377 :
378 : void
379 83 : JamiAccount::newOutgoingCallHelper(const std::shared_ptr<SIPCall>& call, const Uri& uri)
380 : {
381 332 : JAMI_LOG("[Account {}] Calling peer {}", getAccountID(), uri.authority());
382 : try {
383 83 : startOutgoingCall(call, uri.authority());
384 0 : } catch (...) {
385 0 : auto suffix = stripPrefix(uri.toString());
386 0 : NameDirectory::lookupUri(suffix,
387 0 : config().nameServer,
388 0 : [wthis_ = weak(), call](const std::string& regName,
389 : const std::string& address,
390 : NameDirectory::Response response) {
391 : // we may run inside an unknown thread, but following code must
392 : // be called in main thread
393 0 : runOnMainThread([wthis_, regName, address, response, call]() {
394 0 : if (response != NameDirectory::Response::found) {
395 0 : call->onFailure(EINVAL);
396 0 : return;
397 : }
398 0 : if (auto sthis = wthis_.lock()) {
399 : try {
400 0 : sthis->startOutgoingCall(call, regName);
401 0 : } catch (...) {
402 0 : call->onFailure(ENOENT);
403 0 : }
404 : } else {
405 0 : call->onFailure();
406 0 : }
407 : });
408 0 : });
409 0 : }
410 83 : }
411 :
412 : std::shared_ptr<SIPCall>
413 22 : JamiAccount::newSwarmOutgoingCallHelper(const Uri& uri, const std::vector<libjami::MediaMap>& mediaList)
414 : {
415 88 : JAMI_DEBUG("[Account {}] Calling conversation {}", getAccountID(), uri.authority());
416 : return convModule()
417 66 : ->call(uri.authority(), mediaList, [this, uri](const auto& accountUri, const auto& deviceId, const auto& call) {
418 11 : if (!call)
419 0 : return;
420 11 : std::unique_lock lkSipConn(sipConnsMtx_);
421 12 : for (auto& [key, value] : sipConns_) {
422 1 : if (key.first != accountUri || key.second != deviceId)
423 1 : continue;
424 0 : if (value.empty())
425 0 : continue;
426 0 : auto& sipConn = value.back();
427 :
428 0 : if (!sipConn.channel) {
429 0 : JAMI_WARN("A SIP transport exists without Channel, this is a bug. Please report");
430 0 : continue;
431 : }
432 :
433 0 : auto transport = sipConn.transport;
434 0 : if (!transport or !sipConn.channel)
435 0 : continue;
436 0 : call->setState(Call::ConnectionState::PROGRESSING);
437 :
438 0 : auto remoted_address = sipConn.channel->getRemoteAddress();
439 : try {
440 0 : onConnectedOutgoingCall(call, uri.authority(), remoted_address);
441 0 : return;
442 0 : } catch (const VoipLinkException&) {
443 : // In this case, the main scenario is that SIPStartCall failed because
444 : // the ICE is dead and the TLS session didn't send any packet on that dead
445 : // link (connectivity change, killed by the operating system, etc)
446 : // Here, we don't need to do anything, the TLS will fail and will delete
447 : // the cached transport
448 0 : continue;
449 : }
450 : }
451 11 : lkSipConn.unlock();
452 : {
453 11 : std::lock_guard lkP(pendingCallsMutex_);
454 11 : pendingCalls_[deviceId].emplace_back(call);
455 11 : }
456 :
457 : // Else, ask for a channel (for future calls/text messages)
458 11 : auto type = call->hasVideo() ? "videoCall" : "audioCall";
459 44 : JAMI_WARNING("[call {}] No channeled socket with this peer. Send request", call->getCallId());
460 11 : requestSIPConnection(accountUri, deviceId, type, true, call);
461 33 : });
462 : }
463 :
464 : void
465 10 : JamiAccount::handleIncomingConversationCall(const std::string& callId, const std::string& destination)
466 : {
467 10 : auto split = jami::split_string(destination, '/');
468 10 : if (split.size() != 4)
469 0 : return;
470 10 : auto conversationId = std::string(split[0]);
471 10 : auto accountUri = std::string(split[1]);
472 10 : auto deviceId = std::string(split[2]);
473 10 : auto confId = std::string(split[3]);
474 :
475 10 : if (getUsername() != accountUri || currentDeviceId() != deviceId)
476 0 : return;
477 :
478 : // Avoid concurrent checks in this part
479 10 : std::lock_guard lk(rdvMtx_);
480 10 : auto isNotHosting = !convModule()->isHosting(conversationId, confId);
481 10 : if (confId == "0") {
482 1 : auto currentCalls = convModule()->getActiveCalls(conversationId);
483 1 : if (!currentCalls.empty()) {
484 0 : confId = currentCalls[0]["id"];
485 0 : isNotHosting = false;
486 : } else {
487 1 : confId = callId;
488 4 : JAMI_DEBUG("No active call to join, create conference");
489 : }
490 1 : }
491 10 : auto preferences = convModule()->getConversationPreferences(conversationId);
492 10 : auto canHost = true;
493 : #if defined(__ANDROID__) || defined(__APPLE__)
494 : // By default, mobile devices SHOULD NOT host conferences.
495 : canHost = false;
496 : #endif
497 10 : auto itPref = preferences.find(ConversationPreferences::HOST_CONFERENCES);
498 10 : if (itPref != preferences.end()) {
499 0 : canHost = itPref->second == TRUE_STR;
500 : }
501 :
502 10 : auto call = getCall(callId);
503 10 : if (!call) {
504 0 : JAMI_ERROR("Call {} not found", callId);
505 0 : return;
506 : }
507 :
508 10 : if (isNotHosting && !canHost) {
509 0 : JAMI_DEBUG("Request for hosting a conference declined");
510 0 : Manager::instance().hangupCall(getAccountID(), callId);
511 0 : return;
512 : }
513 : // Due to the fact that in a conference, the host is not the one who
514 : // provides the initial sdp offer, the following block of code is responsible
515 : // for handling the medialist that the host will form his response with.
516 : // We always want the hosts response to be the same length as that of the
517 : // peer who is asking to join (providing the offer). A priori though the peer
518 : // doesn't know what active media streams the host will have so we deal with the
519 : // possible cases here.
520 10 : std::shared_ptr<Conference> conf;
521 10 : std::vector<libjami::MediaMap> currentMediaList;
522 10 : if (!isNotHosting) {
523 7 : conf = getConference(confId);
524 7 : if (!conf) {
525 0 : JAMI_ERROR("[conf:{}] Conference not found", confId);
526 0 : return;
527 : }
528 7 : auto hostMedias = conf->currentMediaList();
529 7 : auto sipCall = std::dynamic_pointer_cast<SIPCall>(call);
530 7 : if (hostMedias.empty()) {
531 0 : currentMediaList = MediaAttribute::mediaAttributesToMediaMaps(
532 0 : createDefaultMediaList(call->hasVideo(), true));
533 7 : } else if (hostMedias.size() < sipCall->getRtpSessionList().size()) {
534 : // First case: host has less media streams than the other person is joining
535 : // with. We need to add video media to the host before accepting the offer
536 : // This can happen if we host an audio call and someone joins with video
537 0 : currentMediaList = hostMedias;
538 0 : currentMediaList.push_back(
539 : {{libjami::Media::MediaAttributeKey::MEDIA_TYPE, libjami::Media::MediaAttributeValue::VIDEO},
540 : {libjami::Media::MediaAttributeKey::ENABLED, TRUE_STR},
541 : {libjami::Media::MediaAttributeKey::MUTED, TRUE_STR},
542 : {libjami::Media::MediaAttributeKey::SOURCE, ""},
543 : {libjami::Media::MediaAttributeKey::LABEL, "video_0"}});
544 : } else {
545 7 : bool hasVideo = false;
546 7 : if (sipCall) {
547 7 : const auto rtpSessions = sipCall->getRtpSessionList();
548 7 : hasVideo = std::any_of(rtpSessions.begin(), rtpSessions.end(), [](const auto& session) {
549 13 : return session && session->getMediaType() == MediaType::MEDIA_VIDEO;
550 : });
551 7 : }
552 : // The second case is that the host has the same or more media
553 : // streams than the person joining. In this case we match all their
554 : // medias to form our offer. They will then potentially join the call without seeing
555 : // seeing all of our medias. For now we deal with this by calling a
556 : // requestmediachange once they've joined.
557 14 : for (const auto& m : conf->currentMediaList()) {
558 : // We only expect to have 1 audio stream, add it.
559 13 : if (m.at(libjami::Media::MediaAttributeKey::MEDIA_TYPE) == libjami::Media::MediaAttributeValue::AUDIO) {
560 7 : currentMediaList.emplace_back(m);
561 6 : } else if (hasVideo
562 12 : && m.at(libjami::Media::MediaAttributeKey::MEDIA_TYPE)
563 6 : == libjami::Media::MediaAttributeValue::VIDEO) {
564 6 : currentMediaList.emplace_back(m);
565 6 : break;
566 : }
567 7 : }
568 : }
569 7 : }
570 10 : Manager::instance().acceptCall(*call, currentMediaList);
571 :
572 10 : if (isNotHosting) {
573 12 : JAMI_DEBUG("Creating conference for swarm {} with ID {}", conversationId, confId);
574 : // Create conference and host it.
575 3 : convModule()->hostConference(conversationId, confId, callId);
576 : } else {
577 28 : JAMI_DEBUG("Adding participant {} for swarm {} with ID {}", callId, conversationId, confId);
578 7 : Manager::instance().addAudio(*call);
579 7 : conf->addSubCall(callId);
580 7 : emitSignal<libjami::CallSignal::ConferenceChanged>(getAccountID(), conf->getConfId(), conf->getStateStr());
581 : }
582 10 : }
583 :
584 : std::shared_ptr<SIPCall>
585 166 : JamiAccount::createSubCall(const std::shared_ptr<SIPCall>& mainCall)
586 : {
587 166 : auto mediaList = MediaAttribute::mediaAttributesToMediaMaps(mainCall->getMediaAttributeList());
588 332 : return Manager::instance().callFactory.newSipCall(shared(), Call::CallType::OUTGOING, mediaList);
589 166 : }
590 :
591 : void
592 83 : JamiAccount::startOutgoingCall(const std::shared_ptr<SIPCall>& call, const std::string& toUri)
593 : {
594 83 : if (not accountManager_ or not dht_) {
595 0 : call->onFailure(ENETDOWN);
596 0 : return;
597 : }
598 :
599 : // TODO: for now, we automatically trust all explicitly called peers
600 83 : setCertificateStatus(toUri, dhtnet::tls::TrustStore::PermissionStatus::ALLOWED);
601 :
602 83 : call->setState(Call::ConnectionState::TRYING);
603 83 : std::weak_ptr<SIPCall> wCall = call;
604 :
605 83 : accountManager_->lookupAddress(toUri,
606 83 : [wCall](const std::string& regName,
607 : const std::string& address,
608 : const NameDirectory::Response& response) {
609 83 : if (response == NameDirectory::Response::found)
610 1 : if (auto call = wCall.lock()) {
611 1 : call->setPeerRegisteredName(regName);
612 1 : }
613 83 : });
614 :
615 83 : dht::InfoHash peer_account(toUri);
616 :
617 : // Call connected devices
618 83 : std::set<DeviceId> devices;
619 83 : std::unique_lock lkSipConn(sipConnsMtx_);
620 : // NOTE: dummyCall is a call used to avoid to mark the call as failed if the
621 : // cached connection is failing with ICE (close event still not detected).
622 83 : auto dummyCall = createSubCall(call);
623 :
624 83 : call->addSubCall(*dummyCall);
625 83 : dummyCall->setIceMedia(call->getIceMedia());
626 83 : auto sendRequest = [this, wCall, toUri, dummyCall = std::move(dummyCall)](const DeviceId& deviceId,
627 395 : bool eraseDummy) {
628 162 : if (eraseDummy) {
629 : // Mark the temp call as failed to stop the main call if necessary
630 83 : if (dummyCall)
631 83 : dummyCall->onFailure(static_cast<int>(std::errc::no_such_device_or_address));
632 83 : return;
633 : }
634 79 : auto call = wCall.lock();
635 79 : if (not call)
636 0 : return;
637 79 : auto state = call->getConnectionState();
638 79 : if (state != Call::ConnectionState::PROGRESSING and state != Call::ConnectionState::TRYING)
639 0 : return;
640 :
641 79 : auto dev_call = createSubCall(call);
642 79 : dev_call->setPeerNumber(call->getPeerNumber());
643 79 : dev_call->setState(Call::ConnectionState::TRYING);
644 79 : call->addStateListener([w = weak(), deviceId](Call::CallState, Call::ConnectionState state, int) {
645 233 : if (state != Call::ConnectionState::PROGRESSING and state != Call::ConnectionState::TRYING) {
646 79 : if (auto shared = w.lock())
647 79 : shared->callConnectionClosed(deviceId, true);
648 79 : return false;
649 : }
650 154 : return true;
651 : });
652 79 : call->addSubCall(*dev_call);
653 79 : dev_call->setIceMedia(call->getIceMedia());
654 : {
655 79 : std::lock_guard lk(pendingCallsMutex_);
656 79 : pendingCalls_[deviceId].emplace_back(dev_call);
657 79 : }
658 :
659 316 : JAMI_WARNING("[call {}] No channeled socket with this peer. Send request", call->getCallId());
660 : // Else, ask for a channel (for future calls/text messages)
661 79 : auto type = call->hasVideo() ? "videoCall" : "audioCall";
662 79 : requestSIPConnection(toUri, deviceId, type, true, dev_call);
663 245 : };
664 :
665 83 : std::vector<std::shared_ptr<dhtnet::ChannelSocket>> channels;
666 135 : for (auto& [key, value] : sipConns_) {
667 52 : if (key.first != toUri)
668 48 : continue;
669 4 : if (value.empty())
670 0 : continue;
671 4 : auto& sipConn = value.back();
672 :
673 4 : if (!sipConn.channel) {
674 0 : JAMI_WARNING("A SIP transport exists without Channel, this is a bug. Please report");
675 0 : continue;
676 0 : }
677 :
678 4 : auto transport = sipConn.transport;
679 4 : auto remote_address = sipConn.channel->getRemoteAddress();
680 4 : if (!transport or !remote_address)
681 0 : continue;
682 :
683 4 : channels.emplace_back(sipConn.channel);
684 :
685 16 : JAMI_WARNING("[call {}] A channeled socket is detected with this peer.", call->getCallId());
686 :
687 4 : auto dev_call = createSubCall(call);
688 4 : dev_call->setPeerNumber(call->getPeerNumber());
689 4 : dev_call->setSipTransport(transport, getContactHeader(transport));
690 4 : call->addSubCall(*dev_call);
691 4 : dev_call->setIceMedia(call->getIceMedia());
692 :
693 : // Set the call in PROGRESSING State because the ICE session
694 : // is already ready. Note that this line should be after
695 : // addSubcall() to change the state of the main call
696 : // and avoid to get an active call in a TRYING state.
697 4 : dev_call->setState(Call::ConnectionState::PROGRESSING);
698 :
699 : {
700 4 : std::lock_guard lk(onConnectionClosedMtx_);
701 4 : onConnectionClosed_[key.second] = sendRequest;
702 4 : }
703 :
704 4 : call->addStateListener([w = weak(), deviceId = key.second](Call::CallState, Call::ConnectionState state, int) {
705 12 : if (state != Call::ConnectionState::PROGRESSING and state != Call::ConnectionState::TRYING) {
706 4 : if (auto shared = w.lock())
707 4 : shared->callConnectionClosed(deviceId, true);
708 4 : return false;
709 : }
710 8 : return true;
711 : });
712 :
713 : try {
714 4 : onConnectedOutgoingCall(dev_call, toUri, remote_address);
715 0 : } catch (const VoipLinkException&) {
716 : // In this case, the main scenario is that SIPStartCall failed because
717 : // the ICE is dead and the TLS session didn't send any packet on that dead
718 : // link (connectivity change, killed by the os, etc)
719 : // Here, we don't need to do anything, the TLS will fail and will delete
720 : // the cached transport
721 0 : continue;
722 0 : }
723 4 : devices.emplace(key.second);
724 4 : }
725 :
726 83 : lkSipConn.unlock();
727 : // Note: Send beacon can destroy the socket (if storing last occurence of shared_ptr)
728 : // causing sipConn to be destroyed. So, do it while sipConns_ not locked.
729 87 : for (const auto& channel : channels)
730 4 : channel->sendBeacon();
731 :
732 : // Find listening devices for this account
733 166 : accountManager_->forEachDevice(
734 : peer_account,
735 83 : [this, devices = std::move(devices), sendRequest](const std::shared_ptr<dht::crypto::PublicKey>& dev) {
736 : // Test if already sent via a SIP transport
737 83 : auto deviceId = dev->getLongId();
738 83 : if (devices.find(deviceId) != devices.end())
739 4 : return;
740 : {
741 79 : std::lock_guard lk(onConnectionClosedMtx_);
742 79 : onConnectionClosed_[deviceId] = sendRequest;
743 79 : }
744 79 : sendRequest(deviceId, false);
745 : },
746 83 : [wCall](bool ok) {
747 83 : if (not ok) {
748 1 : if (auto call = wCall.lock()) {
749 4 : JAMI_WARNING("[call:{}] No devices found", call->getCallId());
750 : // Note: if a P2P connection exists, the call will be at least in CONNECTING
751 1 : if (call->getConnectionState() == Call::ConnectionState::TRYING)
752 1 : call->onFailure(static_cast<int>(std::errc::no_such_device_or_address));
753 1 : }
754 : }
755 83 : });
756 83 : }
757 :
758 : void
759 91 : JamiAccount::onConnectedOutgoingCall(const std::shared_ptr<SIPCall>& call,
760 : const std::string& to_id,
761 : dhtnet::IpAddr target)
762 : {
763 91 : if (!call)
764 0 : return;
765 364 : JAMI_LOG("[call:{}] Outgoing call connected to {}", call->getCallId(), to_id);
766 :
767 91 : const auto localAddress = dhtnet::ip_utils::getInterfaceAddr(getLocalInterface(), target.getFamily());
768 :
769 91 : dhtnet::IpAddr addrSdp = getPublishedSameasLocal() ? localAddress
770 91 : : connectionManager_->getPublishedIpAddress(target.getFamily());
771 :
772 : // fallback on local address
773 91 : if (not addrSdp)
774 0 : addrSdp = localAddress;
775 :
776 : // Building the local SDP offer
777 91 : auto& sdp = call->getSDP();
778 :
779 91 : sdp.setPublishedIP(addrSdp);
780 :
781 91 : auto mediaAttrList = call->getMediaAttributeList();
782 91 : if (mediaAttrList.empty()) {
783 0 : JAMI_ERROR("[call:{}] No media. Abort!", call->getCallId());
784 0 : return;
785 : }
786 :
787 91 : if (not sdp.createOffer(mediaAttrList)) {
788 0 : JAMI_ERROR("[call:{}] Unable to send outgoing INVITE request for new call", call->getCallId());
789 0 : return;
790 : }
791 :
792 : // Note: pj_ice_strans_create can call onComplete in the same thread
793 : // This means that iceMutex_ in IceTransport can be locked when onInitDone is called
794 : // So, we need to run the call creation in the main thread
795 : // Also, we do not directly call SIPStartCall before receiving onInitDone, because
796 : // there is an inside waitForInitialization that can block the thread.
797 : // Note: avoid runMainThread as SIPStartCall use transportMutex
798 91 : dht::ThreadPool::io().run([w = weak(), call = std::move(call), target] {
799 91 : auto account = w.lock();
800 91 : if (not account)
801 0 : return;
802 :
803 91 : if (not account->SIPStartCall(*call, target)) {
804 0 : JAMI_ERROR("[call:{}] Unable to send outgoing INVITE request for new call", call->getCallId());
805 : }
806 91 : });
807 91 : }
808 :
809 : bool
810 91 : JamiAccount::SIPStartCall(SIPCall& call, const dhtnet::IpAddr& target)
811 : {
812 364 : JAMI_LOG("[call:{}] Start SIP call", call.getCallId());
813 :
814 91 : if (call.isIceEnabled())
815 91 : call.addLocalIceAttributes();
816 :
817 : std::string toUri(
818 182 : getToUri(call.getPeerNumber() + "@" + target.toString(true))); // expecting a fully well formed sip uri
819 :
820 91 : pj_str_t pjTo = sip_utils::CONST_PJ_STR(toUri);
821 :
822 : // Create the from header
823 91 : std::string from(getFromUri());
824 91 : pj_str_t pjFrom = sip_utils::CONST_PJ_STR(from);
825 :
826 91 : std::string targetStr = getToUri(target.toString(true));
827 91 : pj_str_t pjTarget = sip_utils::CONST_PJ_STR(targetStr);
828 :
829 91 : auto contact = call.getContactHeader();
830 91 : auto pjContact = sip_utils::CONST_PJ_STR(contact);
831 :
832 364 : JAMI_LOG("[call:{}] Contact header: {} / {} -> {} / {}", call.getCallId(), contact, from, toUri, targetStr);
833 :
834 91 : auto local_sdp = call.getSDP().getLocalSdpSession();
835 91 : pjsip_dialog* dialog {nullptr};
836 91 : pjsip_inv_session* inv {nullptr};
837 91 : if (!CreateClientDialogAndInvite(&pjFrom, &pjContact, &pjTo, &pjTarget, local_sdp, &dialog, &inv))
838 0 : return false;
839 :
840 91 : inv->mod_data[link_.getModId()] = &call;
841 91 : call.setInviteSession(inv);
842 :
843 : pjsip_tx_data* tdata;
844 :
845 91 : if (pjsip_inv_invite(call.inviteSession_.get(), &tdata) != PJ_SUCCESS) {
846 0 : JAMI_ERROR("[call:{}] Unable to initialize invite", call.getCallId());
847 0 : return false;
848 : }
849 :
850 : pjsip_tpselector tp_sel;
851 91 : tp_sel.type = PJSIP_TPSELECTOR_TRANSPORT;
852 91 : if (!call.getTransport()) {
853 0 : JAMI_ERROR("[call:{}] Unable to get transport", call.getCallId());
854 0 : return false;
855 : }
856 91 : tp_sel.u.transport = call.getTransport()->get();
857 91 : if (pjsip_dlg_set_transport(dialog, &tp_sel) != PJ_SUCCESS) {
858 0 : JAMI_ERROR("[call:{}] Unable to associate transport for invite session dialog", call.getCallId());
859 0 : return false;
860 : }
861 :
862 364 : JAMI_LOG("[call:{}] Sending SIP invite", call.getCallId());
863 :
864 : // Add user-agent header
865 91 : sip_utils::addUserAgentHeader(getUserAgentName(), tdata);
866 :
867 91 : if (pjsip_inv_send_msg(call.inviteSession_.get(), tdata) != PJ_SUCCESS) {
868 0 : JAMI_ERROR("[call:{}] Unable to send invite message", call.getCallId());
869 0 : return false;
870 : }
871 :
872 91 : call.setState(Call::CallState::ACTIVE, Call::ConnectionState::PROGRESSING);
873 91 : return true;
874 91 : }
875 :
876 : void
877 2555 : JamiAccount::saveConfig() const
878 : {
879 : try {
880 2555 : YAML::Emitter accountOut;
881 2555 : config().serialize(accountOut);
882 2555 : auto accountConfig = config().path / "config.yml";
883 2555 : std::lock_guard lock(dhtnet::fileutils::getFileLock(accountConfig));
884 2555 : std::ofstream fout(accountConfig);
885 2555 : fout.write(accountOut.c_str(), accountOut.size());
886 10220 : JAMI_LOG("Saved account config to {}", accountConfig);
887 2555 : } catch (const std::exception& e) {
888 0 : JAMI_ERROR("Error saving account config: {}", e.what());
889 0 : }
890 2555 : }
891 :
892 : void
893 792 : JamiAccount::loadConfig()
894 : {
895 792 : SIPAccountBase::loadConfig();
896 792 : registeredName_ = config().registeredName;
897 792 : if (accountManager_)
898 20 : accountManager_->setAccountDeviceName(config().deviceName);
899 792 : if (connectionManager_) {
900 16 : if (auto c = connectionManager_->getConfig()) {
901 : // Update connectionManager's config
902 16 : c->upnpEnabled = config().upnpEnabled;
903 16 : c->turnEnabled = config().turnEnabled;
904 16 : c->turnServer = config().turnServer;
905 16 : c->turnServerUserName = config().turnServerUserName;
906 16 : c->turnServerPwd = config().turnServerPwd;
907 16 : c->turnServerRealm = config().turnServerRealm;
908 16 : }
909 : }
910 792 : if (config().proxyEnabled) {
911 : try {
912 0 : auto str = fileutils::loadCacheTextFile(cachePath_ / "dhtproxy", std::chrono::hours(24 * 14));
913 0 : Json::Value root;
914 0 : if (json::parse(str, root)) {
915 0 : proxyServerCached_ = root[getProxyConfigKey()].asString();
916 : }
917 0 : } catch (const std::exception& e) {
918 0 : JAMI_LOG("[Account {}] Unable to load proxy URL from cache: {}", getAccountID(), e.what());
919 0 : proxyServerCached_.clear();
920 0 : }
921 : } else {
922 792 : proxyServerCached_.clear();
923 792 : std::error_code ec;
924 792 : std::filesystem::remove(cachePath_ / "dhtproxy", ec);
925 : }
926 792 : auto credentials = consumeConfigCredentials();
927 792 : loadAccount(credentials.archive_password_scheme, credentials.archive_password, credentials.archive_path);
928 792 : }
929 :
930 : bool
931 4 : JamiAccount::changeArchivePassword(const std::string& password_old, const std::string& password_new)
932 : {
933 : try {
934 4 : if (!accountManager_->changePassword(password_old, password_new)) {
935 8 : JAMI_ERROR("[Account {}] Unable to change archive password", getAccountID());
936 2 : return false;
937 : }
938 4 : editConfig([&](JamiAccountConfig& config) { config.archiveHasPassword = not password_new.empty(); });
939 0 : } catch (const std::exception& ex) {
940 0 : JAMI_ERROR("[Account {}] Unable to change archive password: {}", getAccountID(), ex.what());
941 0 : if (password_old.empty()) {
942 0 : editConfig([&](JamiAccountConfig& config) { config.archiveHasPassword = true; });
943 0 : emitSignal<libjami::ConfigurationSignal::AccountDetailsChanged>(getAccountID(), getAccountDetails());
944 : }
945 0 : return false;
946 0 : }
947 2 : if (password_old != password_new)
948 2 : emitSignal<libjami::ConfigurationSignal::AccountDetailsChanged>(getAccountID(), getAccountDetails());
949 2 : return true;
950 : }
951 :
952 : bool
953 3 : JamiAccount::isPasswordValid(const std::string& password)
954 : {
955 3 : return accountManager_ and accountManager_->isPasswordValid(password);
956 : }
957 :
958 : std::vector<uint8_t>
959 0 : JamiAccount::getPasswordKey(const std::string& password)
960 : {
961 0 : return accountManager_ ? accountManager_->getPasswordKey(password) : std::vector<uint8_t>();
962 : }
963 :
964 : bool
965 7 : JamiAccount::provideAccountAuthentication(const std::string& credentialsFromUser, const std::string& scheme)
966 : {
967 7 : if (auto manager = std::dynamic_pointer_cast<ArchiveAccountManager>(accountManager_)) {
968 7 : return manager->provideAccountAuthentication(credentialsFromUser, scheme);
969 7 : }
970 0 : JAMI_ERR("[LinkDevice] Invalid AccountManager instance while providing current account "
971 : "authentication.");
972 0 : return false;
973 : }
974 :
975 : int32_t
976 5 : JamiAccount::addDevice(const std::string& uriProvided)
977 : {
978 20 : JAMI_LOG("[LinkDevice] JamiAccount::addDevice({}, {})", getAccountID(), uriProvided);
979 5 : if (not accountManager_) {
980 0 : JAMI_ERR("[LinkDevice] Invalid AccountManager instance while adding a device.");
981 0 : return static_cast<int32_t>(AccountManager::AddDeviceError::GENERIC);
982 : }
983 5 : auto authHandler = channelHandlers_.find(Uri::Scheme::AUTH);
984 5 : if (authHandler == channelHandlers_.end())
985 0 : return static_cast<int32_t>(AccountManager::AddDeviceError::GENERIC);
986 10 : return accountManager_->addDevice(uriProvided,
987 5 : config().archiveHasPassword ? fileutils::ARCHIVE_AUTH_SCHEME_PASSWORD
988 : : fileutils::ARCHIVE_AUTH_SCHEME_NONE,
989 10 : (AuthChannelHandler*) authHandler->second.get());
990 : }
991 :
992 : bool
993 0 : JamiAccount::cancelAddDevice(uint32_t op_token)
994 : {
995 0 : if (!accountManager_)
996 0 : return false;
997 0 : return accountManager_->cancelAddDevice(op_token);
998 : }
999 :
1000 : bool
1001 4 : JamiAccount::confirmAddDevice(uint32_t op_token)
1002 : {
1003 4 : if (!accountManager_)
1004 0 : return false;
1005 4 : return accountManager_->confirmAddDevice(op_token);
1006 : }
1007 :
1008 : bool
1009 38 : JamiAccount::exportArchive(const std::string& destinationPath, std::string_view scheme, const std::string& password)
1010 : {
1011 38 : if (auto manager = dynamic_cast<ArchiveAccountManager*>(accountManager_.get())) {
1012 38 : return manager->exportArchive(destinationPath, scheme, password);
1013 : }
1014 0 : return false;
1015 : }
1016 :
1017 : bool
1018 2 : JamiAccount::setValidity(std::string_view scheme, const std::string& pwd, const dht::InfoHash& id, int64_t validity)
1019 : {
1020 2 : if (auto manager = dynamic_cast<ArchiveAccountManager*>(accountManager_.get())) {
1021 2 : if (manager->setValidity(scheme, pwd, id_, id, validity)) {
1022 2 : saveIdentity(id_, idPath_, DEVICE_ID_PATH);
1023 2 : return true;
1024 : }
1025 : }
1026 0 : return false;
1027 : }
1028 :
1029 : void
1030 4 : JamiAccount::forceReloadAccount()
1031 : {
1032 4 : editConfig([&](JamiAccountConfig& conf) {
1033 4 : conf.receipt.clear();
1034 4 : conf.receiptSignature.clear();
1035 4 : });
1036 4 : loadAccount();
1037 4 : }
1038 :
1039 : void
1040 2 : JamiAccount::unlinkConversations(const std::set<std::string>& removed)
1041 : {
1042 2 : std::lock_guard lock(configurationMutex_);
1043 2 : if (auto info = accountManager_->getInfo()) {
1044 2 : auto contacts = info->contacts->getContacts();
1045 4 : for (auto& [id, c] : contacts) {
1046 2 : if (removed.find(c.conversationId) != removed.end()) {
1047 1 : info->contacts->updateConversation(id, "");
1048 4 : JAMI_WARNING("[Account {}] Detected removed conversation ({}) in contact details for {}",
1049 : getAccountID(),
1050 : c.conversationId,
1051 : id.toString());
1052 : }
1053 : }
1054 2 : }
1055 2 : }
1056 :
1057 : bool
1058 1022 : JamiAccount::isValidAccountDevice(const dht::crypto::Certificate& cert) const
1059 : {
1060 1022 : if (accountManager_) {
1061 1022 : if (auto info = accountManager_->getInfo()) {
1062 1022 : if (info->contacts)
1063 1022 : return info->contacts->isValidAccountDevice(cert).isValid();
1064 : }
1065 : }
1066 0 : return false;
1067 : }
1068 :
1069 : bool
1070 3 : JamiAccount::revokeDevice(const std::string& device, std::string_view scheme, const std::string& password)
1071 : {
1072 3 : if (not accountManager_)
1073 0 : return false;
1074 3 : return accountManager_
1075 6 : ->revokeDevice(device, scheme, password, [this, device](AccountManager::RevokeDeviceResult result) {
1076 3 : emitSignal<libjami::ConfigurationSignal::DeviceRevocationEnded>(getAccountID(),
1077 3 : device,
1078 : static_cast<int>(result));
1079 6 : });
1080 : return true;
1081 : }
1082 :
1083 : std::pair<std::string, std::string>
1084 774 : JamiAccount::saveIdentity(const dht::crypto::Identity id, const std::filesystem::path& path, const std::string& name)
1085 : {
1086 1548 : auto names = std::make_pair(name + ".key", name + ".crt");
1087 774 : if (id.first)
1088 774 : fileutils::saveFile(path / names.first, id.first->serialize(), 0600);
1089 774 : if (id.second)
1090 774 : fileutils::saveFile(path / names.second, id.second->getPacked(), 0600);
1091 774 : return names;
1092 0 : }
1093 :
1094 : // must be called while configurationMutex_ is locked
1095 : void
1096 796 : JamiAccount::loadAccount(const std::string& archive_password_scheme,
1097 : const std::string& archive_password,
1098 : const std::string& archive_path)
1099 : {
1100 796 : if (registrationState_ == RegistrationState::INITIALIZING)
1101 4 : return;
1102 :
1103 3168 : JAMI_DEBUG("[Account {:s}] Loading account", getAccountID());
1104 : AccountManager::OnChangeCallback callbacks {
1105 321 : [this](const std::string& uri, bool confirmed) {
1106 162 : if (!id_.first)
1107 3 : return;
1108 159 : if (jami::Manager::instance().syncOnRegister) {
1109 159 : dht::ThreadPool::io().run([w = weak(), uri, confirmed] {
1110 159 : if (auto shared = w.lock()) {
1111 159 : if (auto cm = shared->convModule(true)) {
1112 159 : auto activeConv = cm->getOneToOneConversation(uri);
1113 159 : if (!activeConv.empty())
1114 159 : cm->bootstrap(activeConv);
1115 159 : }
1116 159 : emitSignal<libjami::ConfigurationSignal::ContactAdded>(shared->getAccountID(), uri, confirmed);
1117 159 : }
1118 159 : });
1119 : }
1120 : },
1121 46 : [this](const std::string& uri, bool banned) {
1122 23 : if (!id_.first)
1123 0 : return;
1124 23 : dht::ThreadPool::io().run([w = weak(), uri, banned] {
1125 23 : if (auto shared = w.lock()) {
1126 : // Erase linked conversation's requests
1127 23 : if (auto convModule = shared->convModule(true))
1128 23 : convModule->removeContact(uri, banned);
1129 : // Remove current connections with contact
1130 : // Note: if contact is ourself, we don't close the connection
1131 : // because it's used for syncing other conversations.
1132 23 : if (shared->connectionManager_ && uri != shared->getUsername()) {
1133 22 : shared->connectionManager_->closeConnectionsWith(uri);
1134 : }
1135 : // Update client.
1136 23 : emitSignal<libjami::ConfigurationSignal::ContactRemoved>(shared->getAccountID(), uri, banned);
1137 23 : }
1138 23 : });
1139 : },
1140 83 : [this](const std::string& uri,
1141 : const std::string& conversationId,
1142 : const std::vector<uint8_t>& payload,
1143 166 : time_t received) {
1144 83 : if (!id_.first)
1145 0 : return;
1146 83 : dht::ThreadPool::io().run([w = weak(), uri, conversationId, payload, received] {
1147 83 : if (auto shared = w.lock()) {
1148 83 : shared->clearProfileCache(uri);
1149 83 : if (conversationId.empty()) {
1150 : // Old path
1151 0 : emitSignal<libjami::ConfigurationSignal::IncomingTrustRequest>(shared->getAccountID(),
1152 0 : conversationId,
1153 0 : uri,
1154 0 : payload,
1155 : received);
1156 0 : return;
1157 : }
1158 : // Here account can be initializing
1159 83 : if (auto cm = shared->convModule(true)) {
1160 83 : auto activeConv = cm->getOneToOneConversation(uri);
1161 83 : if (activeConv != conversationId)
1162 76 : cm->onTrustRequest(uri, conversationId, payload, received);
1163 83 : }
1164 83 : }
1165 : });
1166 : },
1167 5848 : [this](const std::map<DeviceId, KnownDevice>& devices) {
1168 2924 : std::map<std::string, std::string> ids;
1169 1010983 : for (auto& d : devices) {
1170 1008059 : auto id = d.first.toString();
1171 1008059 : auto label = d.second.name.empty() ? id.substr(0, 8) : d.second.name;
1172 1008059 : ids.emplace(std::move(id), std::move(label));
1173 1008059 : }
1174 2924 : runOnMainThread([id = getAccountID(), devices = std::move(ids)] {
1175 2924 : emitSignal<libjami::ConfigurationSignal::KnownDevicesChanged>(id, devices);
1176 2924 : });
1177 2924 : },
1178 53 : [this](const std::string& conversationId, const std::string& deviceId) {
1179 : // Note: Do not retrigger on another thread. This has to be done
1180 : // at the same time of acceptTrustRequest a synced state between TrustRequest
1181 : // and convRequests.
1182 53 : if (auto cm = convModule(true))
1183 53 : cm->acceptConversationRequest(conversationId, deviceId);
1184 53 : },
1185 76 : [this](const std::string& uri, const std::string& convFromReq) {
1186 38 : dht::ThreadPool::io().run([w = weak(), convFromReq, uri] {
1187 38 : if (auto shared = w.lock()) {
1188 38 : auto cm = shared->convModule(true);
1189 : // Remove cached payload if there is one
1190 76 : auto requestPath = shared->cachePath_ / "requests" / uri;
1191 38 : dhtnet::fileutils::remove(requestPath);
1192 : // Following replay logic could incorrectly be triggered for conversations
1193 : // already fetched and used by other devices, so it is disabled for now.
1194 : /*if (!convFromReq.empty()) {
1195 : auto oldConv = cm->getOneToOneConversation(uri);
1196 : // If we previously removed the contact, and re-add it, we may
1197 : // receive a convId different from the request. In that case,
1198 : // we need to remove the current conversation and clone the old
1199 : // one (given by convFromReq).
1200 : // TODO: In the future, we may want to re-commit the messages we
1201 : // may have send in the request we sent.
1202 : if (oldConv != convFromReq
1203 : && cm->updateConvForContact(uri, oldConv, convFromReq)) {
1204 : cm->initReplay(oldConv, convFromReq);
1205 : cm->cloneConversationFrom(convFromReq, uri, oldConv);
1206 : }
1207 : }*/
1208 76 : }
1209 38 : });
1210 830 : }};
1211 :
1212 792 : const auto& conf = config();
1213 : try {
1214 792 : auto oldIdentity = id_.first ? id_.first->getPublicKey().getLongId() : DeviceId();
1215 792 : if (conf.managerUri.empty()) {
1216 2376 : accountManager_ = std::make_shared<ArchiveAccountManager>(
1217 792 : getAccountID(),
1218 : getPath(),
1219 42 : [this]() { return getAccountDetails(); },
1220 813 : [this](DeviceSync&& syncData) {
1221 813 : if (auto sm = syncModule()) {
1222 813 : auto syncDataPtr = std::make_shared<SyncMsg>();
1223 813 : syncDataPtr->ds = std::move(syncData);
1224 813 : sm->syncWithConnected(syncDataPtr);
1225 813 : }
1226 813 : },
1227 1584 : conf.archivePath.empty() ? "archive.gz" : conf.archivePath,
1228 1584 : conf.nameServer);
1229 : } else {
1230 0 : accountManager_ = std::make_shared<ServerAccountManager>(getAccountID(),
1231 : getPath(),
1232 0 : conf.managerUri,
1233 0 : conf.nameServer);
1234 : }
1235 :
1236 792 : auto id = accountManager_->loadIdentity(conf.tlsCertificateFile, conf.tlsPrivateKeyFile, conf.tlsPassword);
1237 :
1238 1584 : if (auto info = accountManager_
1239 792 : ->useIdentity(id, conf.receipt, conf.receiptSignature, conf.managerUsername, callbacks)) {
1240 : // normal loading path
1241 16 : id_ = std::move(id);
1242 16 : config_->username = info->accountId;
1243 64 : JAMI_WARNING("[Account {:s}] Loaded account identity", getAccountID());
1244 16 : if (info->identity.first->getPublicKey().getLongId() != oldIdentity) {
1245 0 : JAMI_WARNING("[Account {:s}] Identity changed", getAccountID());
1246 : {
1247 0 : std::lock_guard lk(moduleMtx_);
1248 0 : convModule_.reset();
1249 0 : }
1250 0 : convModule(); // convModule must absolutely be initialized in
1251 : // both branches of the if statement here in order
1252 : // for it to exist for subsequent use.
1253 : } else {
1254 16 : convModule()->setAccountManager(accountManager_);
1255 : }
1256 16 : if (not isEnabled()) {
1257 0 : setRegistrationState(RegistrationState::UNREGISTERED);
1258 : }
1259 776 : } else if (isEnabled()) {
1260 3104 : JAMI_WARNING("[Account {}] useIdentity failed!", getAccountID());
1261 776 : if (not conf.managerUri.empty() and archive_password.empty()) {
1262 0 : Migration::setState(accountID_, Migration::State::INVALID);
1263 0 : setRegistrationState(RegistrationState::ERROR_NEED_MIGRATION);
1264 0 : return;
1265 : }
1266 :
1267 776 : bool migrating = registrationState_ == RegistrationState::ERROR_NEED_MIGRATION;
1268 776 : setRegistrationState(RegistrationState::INITIALIZING);
1269 776 : auto fDeviceKey = dht::ThreadPool::computation().getShared<std::shared_ptr<dht::crypto::PrivateKey>>(
1270 2328 : []() { return std::make_shared<dht::crypto::PrivateKey>(dht::crypto::PrivateKey::generate()); });
1271 :
1272 776 : std::unique_ptr<AccountManager::AccountCredentials> creds;
1273 776 : if (conf.managerUri.empty()) {
1274 776 : auto acreds = std::make_unique<ArchiveAccountManager::ArchiveAccountCredentials>();
1275 776 : auto archivePath = fileutils::getFullPath(idPath_, conf.archivePath);
1276 : // bool hasArchive = std::filesystem::is_regular_file(archivePath);
1277 :
1278 776 : if (!archive_path.empty()) {
1279 : // Importing external archive
1280 39 : acreds->scheme = "file";
1281 39 : acreds->uri = archive_path;
1282 737 : } else if (!conf.archive_url.empty() && conf.archive_url == "jami-auth") {
1283 : // Importing over a Peer2Peer TLS connection with DHT as DNS
1284 20 : JAMI_DEBUG("[Account {}] [LinkDevice] scheme p2p & uri {}", getAccountID(), conf.archive_url);
1285 5 : acreds->scheme = "p2p";
1286 5 : acreds->uri = conf.archive_url;
1287 732 : } else if (std::filesystem::is_regular_file(archivePath)) {
1288 : // Migrating local account
1289 4 : acreds->scheme = "local";
1290 4 : acreds->uri = archivePath.string();
1291 4 : acreds->updateIdentity = id;
1292 4 : migrating = true;
1293 : }
1294 776 : creds = std::move(acreds);
1295 776 : } else {
1296 0 : auto screds = std::make_unique<ServerAccountManager::ServerAccountCredentials>();
1297 0 : screds->username = conf.managerUsername;
1298 0 : creds = std::move(screds);
1299 0 : }
1300 776 : creds->password = archive_password;
1301 776 : bool hasPassword = !archive_password.empty();
1302 776 : if (hasPassword && archive_password_scheme.empty())
1303 10 : creds->password_scheme = fileutils::ARCHIVE_AUTH_SCHEME_PASSWORD;
1304 : else
1305 766 : creds->password_scheme = archive_password_scheme;
1306 :
1307 3104 : JAMI_WARNING("[Account {}] initAuthentication {} {}",
1308 : getAccountID(),
1309 : fmt::ptr(this),
1310 : fmt::ptr(accountManager_));
1311 :
1312 3880 : accountManager_->initAuthentication(
1313 : fDeviceKey,
1314 1552 : ip_utils::getDeviceName(),
1315 776 : std::move(creds),
1316 772 : [w = weak(), this, migrating, hasPassword](const AccountInfo& info,
1317 : const std::map<std::string, std::string>& config,
1318 : std::string&& receipt,
1319 6952 : std::vector<uint8_t>&& receipt_signature) {
1320 772 : auto sthis = w.lock();
1321 772 : if (not sthis)
1322 0 : return;
1323 3088 : JAMI_LOG("[Account {}] Auth success! Device: {}", getAccountID(), info.deviceId);
1324 :
1325 772 : dhtnet::fileutils::check_dir(idPath_, 0700);
1326 :
1327 772 : auto id = info.identity;
1328 772 : editConfig([&](JamiAccountConfig& conf) {
1329 2316 : std::tie(conf.tlsPrivateKeyFile, conf.tlsCertificateFile) = saveIdentity(id,
1330 772 : idPath_,
1331 772 : DEVICE_ID_PATH);
1332 772 : conf.tlsPassword = {};
1333 772 : auto passwordIt = config.find(libjami::Account::ConfProperties::ARCHIVE_HAS_PASSWORD);
1334 772 : if (passwordIt != config.end() && !passwordIt->second.empty()) {
1335 772 : conf.archiveHasPassword = passwordIt->second == "true";
1336 : } else {
1337 0 : conf.archiveHasPassword = hasPassword;
1338 : }
1339 :
1340 772 : if (not conf.managerUri.empty()) {
1341 0 : conf.registeredName = conf.managerUsername;
1342 0 : registeredName_ = conf.managerUsername;
1343 : }
1344 772 : conf.username = info.accountId;
1345 772 : conf.deviceName = accountManager_->getAccountDeviceName();
1346 :
1347 772 : auto nameServerIt = config.find(libjami::Account::ConfProperties::Nameserver::URI);
1348 772 : if (nameServerIt != config.end() && !nameServerIt->second.empty()) {
1349 0 : conf.nameServer = nameServerIt->second;
1350 : }
1351 772 : auto displayNameIt = config.find(libjami::Account::ConfProperties::DISPLAYNAME);
1352 772 : if (displayNameIt != config.end() && !displayNameIt->second.empty()) {
1353 41 : conf.displayName = displayNameIt->second;
1354 : }
1355 772 : conf.receipt = std::move(receipt);
1356 772 : conf.receiptSignature = std::move(receipt_signature);
1357 772 : conf.fromMap(config);
1358 772 : });
1359 772 : id_ = std::move(id);
1360 : {
1361 772 : std::lock_guard lk(moduleMtx_);
1362 772 : convModule_.reset();
1363 772 : }
1364 772 : if (migrating) {
1365 4 : Migration::setState(getAccountID(), Migration::State::SUCCESS);
1366 : }
1367 772 : if (not info.photo.empty() or not info.displayName.empty()) {
1368 : try {
1369 0 : auto newProfile = vCard::utils::initVcard();
1370 0 : newProfile[std::string(vCard::Property::FORMATTED_NAME)] = info.displayName;
1371 0 : newProfile[std::string(vCard::Property::PHOTO)] = info.photo;
1372 0 : const auto& profiles = idPath_ / "profiles";
1373 0 : const auto& vCardPath = profiles / fmt::format("{}.vcf", base64::encode(info.accountId));
1374 0 : vCard::utils::save(newProfile, vCardPath, profilePath());
1375 0 : runOnMainThread([w = weak(), id = info.accountId, vCardPath]() {
1376 0 : if (auto shared = w.lock()) {
1377 0 : emitSignal<libjami::ConfigurationSignal::ProfileReceived>(shared->getAccountID(),
1378 0 : id,
1379 0 : vCardPath.string());
1380 0 : }
1381 0 : });
1382 0 : } catch (const std::exception& e) {
1383 0 : JAMI_WARNING("[Account {}] Unable to save profile after authentication: {}",
1384 : getAccountID(),
1385 : e.what());
1386 0 : }
1387 : }
1388 772 : setRegistrationState(RegistrationState::UNREGISTERED);
1389 772 : doRegister();
1390 772 : },
1391 776 : [w = weak(), id, accountId = getAccountID(), migrating](AccountManager::AuthError error,
1392 0 : const std::string& message) {
1393 0 : JAMI_WARNING("[Account {}] Auth error: {} {}", accountId, (int) error, message);
1394 0 : if ((id.first || migrating) && error == AccountManager::AuthError::INVALID_ARGUMENTS) {
1395 : // In cast of a migration or manager connexion failure stop the migration
1396 : // and block the account
1397 0 : Migration::setState(accountId, Migration::State::INVALID);
1398 0 : if (auto acc = w.lock())
1399 0 : acc->setRegistrationState(RegistrationState::ERROR_NEED_MIGRATION);
1400 : } else {
1401 : // In case of a DHT or backup import failure, just remove the account
1402 0 : if (auto acc = w.lock())
1403 0 : acc->setRegistrationState(RegistrationState::ERROR_GENERIC);
1404 0 : runOnMainThread(
1405 0 : [accountId = std::move(accountId)] { Manager::instance().removeAccount(accountId, true); });
1406 : }
1407 0 : },
1408 : callbacks);
1409 776 : }
1410 792 : } catch (const std::exception& e) {
1411 0 : JAMI_WARNING("[Account {}] Error loading account: {}", getAccountID(), e.what());
1412 0 : accountManager_.reset();
1413 0 : setRegistrationState(RegistrationState::ERROR_GENERIC);
1414 0 : }
1415 792 : }
1416 :
1417 : std::map<std::string, std::string>
1418 4555 : JamiAccount::getVolatileAccountDetails() const
1419 : {
1420 4555 : auto a = SIPAccountBase::getVolatileAccountDetails();
1421 4555 : a.emplace(libjami::Account::VolatileProperties::InstantMessaging::OFF_CALL, TRUE_STR);
1422 4555 : auto registeredName = getRegisteredName();
1423 4555 : if (not registeredName.empty())
1424 2 : a.emplace(libjami::Account::VolatileProperties::REGISTERED_NAME, registeredName);
1425 4555 : a.emplace(libjami::Account::ConfProperties::PROXY_SERVER, proxyServerCached_);
1426 4555 : a.emplace(libjami::Account::VolatileProperties::DHT_BOUND_PORT, std::to_string(dhtBoundPort_));
1427 4555 : a.emplace(libjami::Account::VolatileProperties::DEVICE_ANNOUNCED, deviceAnnounced_ ? TRUE_STR : FALSE_STR);
1428 4555 : if (accountManager_) {
1429 4555 : if (auto info = accountManager_->getInfo()) {
1430 3777 : a.emplace(libjami::Account::ConfProperties::DEVICE_ID, info->deviceId);
1431 : }
1432 : }
1433 9110 : return a;
1434 4555 : }
1435 :
1436 : void
1437 3 : JamiAccount::lookupName(const std::string& name)
1438 : {
1439 3 : std::lock_guard lock(configurationMutex_);
1440 3 : if (accountManager_)
1441 9 : accountManager_->lookupUri(name,
1442 3 : config().nameServer,
1443 3 : [acc = getAccountID(), name](const std::string& regName,
1444 : const std::string& address,
1445 : NameDirectory::Response response) {
1446 6 : emitSignal<libjami::ConfigurationSignal::RegisteredNameFound>(acc,
1447 3 : name,
1448 : (int) response,
1449 : address,
1450 : regName);
1451 3 : });
1452 3 : }
1453 :
1454 : void
1455 3 : JamiAccount::lookupAddress(const std::string& addr)
1456 : {
1457 3 : std::lock_guard lock(configurationMutex_);
1458 3 : auto acc = getAccountID();
1459 3 : if (accountManager_)
1460 3 : accountManager_->lookupAddress(addr,
1461 3 : [acc, addr](const std::string& regName,
1462 : const std::string& address,
1463 : NameDirectory::Response response) {
1464 6 : emitSignal<libjami::ConfigurationSignal::RegisteredNameFound>(acc,
1465 3 : addr,
1466 : (int) response,
1467 : address,
1468 : regName);
1469 3 : });
1470 3 : }
1471 :
1472 : void
1473 1 : JamiAccount::registerName(const std::string& name, const std::string& scheme, const std::string& password)
1474 : {
1475 1 : std::lock_guard lock(configurationMutex_);
1476 1 : if (accountManager_)
1477 1 : accountManager_
1478 2 : ->registerName(name,
1479 : scheme,
1480 : password,
1481 1 : [acc = getAccountID(), name, w = weak()](NameDirectory::RegistrationResponse response,
1482 : const std::string& regName) {
1483 1 : auto res = (int) std::min(response, NameDirectory::RegistrationResponse::error);
1484 1 : if (response == NameDirectory::RegistrationResponse::success) {
1485 1 : if (auto this_ = w.lock()) {
1486 1 : if (this_->setRegisteredName(regName)) {
1487 1 : this_->editConfig(
1488 1 : [&](JamiAccountConfig& config) { config.registeredName = regName; });
1489 1 : emitSignal<libjami::ConfigurationSignal::VolatileDetailsChanged>(
1490 2 : this_->accountID_, this_->getVolatileAccountDetails());
1491 : }
1492 1 : }
1493 : }
1494 1 : emitSignal<libjami::ConfigurationSignal::NameRegistrationEnded>(acc, res, name);
1495 1 : });
1496 1 : }
1497 :
1498 : bool
1499 0 : JamiAccount::searchUser(const std::string& query)
1500 : {
1501 0 : if (accountManager_)
1502 0 : return accountManager_
1503 0 : ->searchUser(query,
1504 0 : [acc = getAccountID(), query](const jami::NameDirectory::SearchResult& result,
1505 : jami::NameDirectory::Response response) {
1506 0 : jami::emitSignal<libjami::ConfigurationSignal::UserSearchEnded>(acc,
1507 : (int) response,
1508 0 : query,
1509 : result);
1510 0 : });
1511 0 : return false;
1512 : }
1513 :
1514 : void
1515 176 : JamiAccount::forEachPendingCall(const DeviceId& deviceId, const std::function<void(const std::shared_ptr<SIPCall>&)>& cb)
1516 : {
1517 176 : std::vector<std::shared_ptr<SIPCall>> pc;
1518 : {
1519 176 : std::lock_guard lk(pendingCallsMutex_);
1520 176 : pc = std::move(pendingCalls_[deviceId]);
1521 176 : }
1522 263 : for (const auto& pendingCall : pc) {
1523 87 : cb(pendingCall);
1524 : }
1525 176 : }
1526 :
1527 : void
1528 691 : JamiAccount::registerAsyncOps()
1529 : {
1530 2702 : auto onLoad = [this, loaded = std::make_shared<std::atomic_uint>()] {
1531 2011 : if (++(*loaded) == 2u) {
1532 691 : runOnMainThread([w = weak()] {
1533 691 : if (auto s = w.lock()) {
1534 691 : std::lock_guard lock(s->configurationMutex_);
1535 691 : s->doRegister_();
1536 1382 : }
1537 691 : });
1538 : }
1539 2702 : };
1540 :
1541 1382 : loadCachedProxyServer([onLoad](const std::string&) { onLoad(); });
1542 :
1543 691 : if (upnpCtrl_) {
1544 2668 : JAMI_LOG("[Account {:s}] UPnP: attempting to map ports", getAccountID());
1545 :
1546 : // Release current mapping if any.
1547 667 : if (dhtUpnpMapping_.isValid()) {
1548 0 : upnpCtrl_->releaseMapping(dhtUpnpMapping_);
1549 : }
1550 :
1551 667 : dhtUpnpMapping_.enableAutoUpdate(true);
1552 :
1553 : // Set the notify callback.
1554 1334 : dhtUpnpMapping_.setNotifyCallback(
1555 667 : [w = weak(), onLoad, update = std::make_shared<bool>(false)](dhtnet::upnp::Mapping::sharedPtr_t mapRes) {
1556 639 : if (auto accPtr = w.lock()) {
1557 639 : auto& dhtMap = accPtr->dhtUpnpMapping_;
1558 639 : const auto& accId = accPtr->getAccountID();
1559 :
1560 2556 : JAMI_LOG("[Account {:s}] DHT UPnP mapping changed to {:s}", accId, mapRes->toString(true));
1561 :
1562 639 : if (*update) {
1563 : // Check if we need to update the mapping and the registration.
1564 5 : if (dhtMap.getMapKey() != mapRes->getMapKey() or dhtMap.getState() != mapRes->getState()) {
1565 : // The connectivity must be restarted, if either:
1566 : // - the state changed to "OPEN",
1567 : // - the state changed to "FAILED" and the mapping was in use.
1568 5 : if (mapRes->getState() == dhtnet::upnp::MappingState::OPEN
1569 10 : or (mapRes->getState() == dhtnet::upnp::MappingState::FAILED
1570 5 : and dhtMap.getState() == dhtnet::upnp::MappingState::OPEN)) {
1571 : // Update the mapping and restart the registration.
1572 0 : dhtMap.updateFrom(mapRes);
1573 :
1574 0 : JAMI_WARNING("[Account {:s}] Allocated port changed to {}. Restarting the "
1575 : "registration",
1576 : accId,
1577 : accPtr->dhtPortUsed());
1578 :
1579 0 : accPtr->dht_->connectivityChanged();
1580 :
1581 : } else {
1582 : // Only update the mapping.
1583 5 : dhtMap.updateFrom(mapRes);
1584 : }
1585 : }
1586 : } else {
1587 634 : *update = true;
1588 : // Set connection info and load the account.
1589 634 : if (mapRes->getState() == dhtnet::upnp::MappingState::OPEN) {
1590 0 : dhtMap.updateFrom(mapRes);
1591 0 : JAMI_LOG("[Account {:s}] Mapping {:s} successfully allocated: starting the DHT",
1592 : accId,
1593 : dhtMap.toString());
1594 : } else {
1595 2536 : JAMI_WARNING("[Account {:s}] Mapping request is in {:s} state: starting "
1596 : "the DHT anyway",
1597 : accId,
1598 : mapRes->getStateStr());
1599 : }
1600 :
1601 : // Load the account and start the DHT.
1602 634 : onLoad();
1603 : }
1604 639 : }
1605 639 : });
1606 :
1607 : // Request the mapping.
1608 667 : auto map = upnpCtrl_->reserveMapping(dhtUpnpMapping_);
1609 : // The returned mapping is invalid. Load the account now since
1610 : // we may never receive the callback.
1611 667 : if (not map) {
1612 662 : onLoad();
1613 : }
1614 667 : } else {
1615 : // No UPNP. Load the account and start the DHT. The local DHT
1616 : // might not be reachable for peers if we are behind a NAT.
1617 24 : onLoad();
1618 : }
1619 691 : }
1620 :
1621 : void
1622 1603 : JamiAccount::doRegister()
1623 : {
1624 1603 : std::lock_guard lock(configurationMutex_);
1625 1603 : if (not isUsable()) {
1626 560 : JAMI_WARNING("[Account {:s}] Account must be enabled and active to register, ignoring", getAccountID());
1627 140 : return;
1628 : }
1629 :
1630 5852 : JAMI_LOG("[Account {:s}] Starting account…", getAccountID());
1631 :
1632 : // invalid state transitions:
1633 : // INITIALIZING: generating/loading certificates, unable to register
1634 : // NEED_MIGRATION: old account detected, user needs to migrate
1635 1463 : if (registrationState_ == RegistrationState::INITIALIZING
1636 691 : || registrationState_ == RegistrationState::ERROR_NEED_MIGRATION)
1637 772 : return;
1638 :
1639 691 : convModule(); // Init conv module before passing in trying
1640 691 : setRegistrationState(RegistrationState::TRYING);
1641 : /* if UPnP is enabled, then wait for IGD to complete registration */
1642 691 : if (upnpCtrl_ or proxyServerCached_.empty()) {
1643 691 : registerAsyncOps();
1644 : } else {
1645 0 : doRegister_();
1646 : }
1647 1603 : }
1648 :
1649 : std::vector<std::string>
1650 691 : JamiAccount::loadBootstrap() const
1651 : {
1652 691 : std::vector<std::string> bootstrap;
1653 691 : std::string_view stream(config().hostname), node_addr;
1654 1382 : while (jami::getline(stream, node_addr, ';'))
1655 691 : bootstrap.emplace_back(node_addr);
1656 1382 : for (const auto& b : bootstrap)
1657 691 : JAMI_DBG("[Account %s] Bootstrap node: %s", getAccountID().c_str(), b.c_str());
1658 1382 : return bootstrap;
1659 0 : }
1660 :
1661 : void
1662 34 : JamiAccount::trackBuddyPresence(const std::string& buddy_id, bool track)
1663 : {
1664 34 : std::string buddyUri;
1665 : try {
1666 34 : buddyUri = parseJamiUri(buddy_id);
1667 0 : } catch (...) {
1668 0 : JAMI_ERROR("[Account {:s}] Failed to track presence: invalid URI {:s}", getAccountID(), buddy_id);
1669 0 : return;
1670 0 : }
1671 136 : JAMI_LOG("[Account {:s}] {:s} presence for {:s}", getAccountID(), track ? "Track" : "Untrack", buddy_id);
1672 :
1673 34 : auto h = dht::InfoHash(buddyUri);
1674 34 : std::unique_lock lock(buddyInfoMtx);
1675 34 : if (track) {
1676 34 : auto buddy = trackedBuddies_.emplace(h, BuddyInfo {h});
1677 34 : if (buddy.second) {
1678 34 : trackPresence(buddy.first->first, buddy.first->second);
1679 : }
1680 34 : auto it = presenceState_.find(buddyUri);
1681 34 : if (it != presenceState_.end() && it->second != PresenceState::DISCONNECTED) {
1682 1 : lock.unlock();
1683 1 : emitSignal<libjami::PresenceSignal::NewBuddyNotification>(getAccountID(),
1684 : buddyUri,
1685 1 : static_cast<int>(it->second),
1686 : "");
1687 : }
1688 : } else {
1689 0 : auto buddy = trackedBuddies_.find(h);
1690 0 : if (buddy != trackedBuddies_.end()) {
1691 0 : if (auto dht = dht_)
1692 0 : if (dht->isRunning())
1693 0 : dht->cancelListen(h, std::move(buddy->second.listenToken));
1694 0 : trackedBuddies_.erase(buddy);
1695 : }
1696 : }
1697 34 : }
1698 :
1699 : void
1700 35 : JamiAccount::trackPresence(const dht::InfoHash& h, BuddyInfo& buddy)
1701 : {
1702 35 : auto dht = dht_;
1703 35 : if (not dht or not dht->isRunning()) {
1704 1 : return;
1705 : }
1706 68 : buddy.listenToken = dht->listen<DeviceAnnouncement>(h, [this, h](DeviceAnnouncement&& dev, bool expired) {
1707 : bool wasConnected, isConnected;
1708 : {
1709 66 : std::lock_guard lock(buddyInfoMtx);
1710 66 : auto buddy = trackedBuddies_.find(h);
1711 66 : if (buddy == trackedBuddies_.end())
1712 0 : return true;
1713 66 : wasConnected = buddy->second.devices_cnt > 0;
1714 66 : if (expired)
1715 33 : --buddy->second.devices_cnt;
1716 : else
1717 33 : ++buddy->second.devices_cnt;
1718 66 : isConnected = buddy->second.devices_cnt > 0;
1719 66 : }
1720 : // NOTE: the rest can use configurationMtx_, that can be locked during unregister so
1721 : // do not retrigger on dht
1722 66 : runOnMainThread([w = weak(), h, dev, expired, isConnected, wasConnected]() {
1723 66 : auto sthis = w.lock();
1724 66 : if (!sthis)
1725 0 : return;
1726 66 : if (not expired) {
1727 : // Retry messages every time a new device announce its presence
1728 33 : sthis->messageEngine_.onPeerOnline(h.toString());
1729 : }
1730 66 : if (isConnected and not wasConnected) {
1731 32 : sthis->onTrackedBuddyOnline(h);
1732 34 : } else if (not isConnected and wasConnected) {
1733 32 : sthis->onTrackedBuddyOffline(h);
1734 : }
1735 66 : });
1736 :
1737 66 : return true;
1738 34 : });
1739 35 : }
1740 :
1741 : std::map<std::string, bool>
1742 2 : JamiAccount::getTrackedBuddyPresence() const
1743 : {
1744 2 : std::lock_guard lock(buddyInfoMtx);
1745 2 : std::map<std::string, bool> presence_info;
1746 4 : for (const auto& buddy_info_p : trackedBuddies_)
1747 2 : presence_info.emplace(buddy_info_p.first.toString(), buddy_info_p.second.devices_cnt > 0);
1748 4 : return presence_info;
1749 2 : }
1750 :
1751 : void
1752 32 : JamiAccount::onTrackedBuddyOnline(const dht::InfoHash& contactId)
1753 : {
1754 32 : std::string id(contactId.toString());
1755 128 : JAMI_DEBUG("[Account {:s}] Buddy {} online", getAccountID(), id);
1756 32 : auto& state = presenceState_[id];
1757 32 : if (state < PresenceState::AVAILABLE) {
1758 32 : state = PresenceState::AVAILABLE;
1759 32 : emitSignal<libjami::PresenceSignal::NewBuddyNotification>(getAccountID(),
1760 : id,
1761 : static_cast<int>(PresenceState::AVAILABLE),
1762 : "");
1763 : }
1764 :
1765 32 : if (auto details = getContactInfo(id)) {
1766 5 : if (!details->confirmed) {
1767 5 : auto convId = convModule()->getOneToOneConversation(id);
1768 5 : if (convId.empty())
1769 0 : return;
1770 : // In this case, the TrustRequest was sent but never confirmed (cause the contact was
1771 : // offline maybe) To avoid the contact to never receive the conv request, retry there
1772 5 : std::lock_guard lock(configurationMutex_);
1773 5 : if (accountManager_) {
1774 : // Retrieve cached payload for trust request.
1775 10 : auto requestPath = cachePath_ / "requests" / id;
1776 5 : std::vector<uint8_t> payload;
1777 : try {
1778 8 : payload = fileutils::loadFile(requestPath);
1779 3 : } catch (...) {
1780 3 : }
1781 5 : if (payload.size() >= 64000) {
1782 0 : JAMI_WARNING("[Account {:s}] Trust request for contact {:s} is too big, reset payload",
1783 : getAccountID(),
1784 : id);
1785 0 : payload.clear();
1786 : }
1787 5 : accountManager_->sendTrustRequest(id, convId, payload);
1788 5 : }
1789 5 : }
1790 32 : }
1791 32 : }
1792 :
1793 : void
1794 32 : JamiAccount::onTrackedBuddyOffline(const dht::InfoHash& contactId)
1795 : {
1796 32 : auto id = contactId.toString();
1797 128 : JAMI_DEBUG("[Account {:s}] Buddy {} offline", getAccountID(), id);
1798 32 : auto& state = presenceState_[id];
1799 32 : if (state > PresenceState::DISCONNECTED) {
1800 32 : if (state == PresenceState::CONNECTED) {
1801 0 : JAMI_WARNING("[Account {:s}] Buddy {} is not present on the DHT, but P2P connected", getAccountID(), id);
1802 0 : return;
1803 : }
1804 32 : state = PresenceState::DISCONNECTED;
1805 32 : emitSignal<libjami::PresenceSignal::NewBuddyNotification>(getAccountID(),
1806 : id,
1807 : static_cast<int>(PresenceState::DISCONNECTED),
1808 : "");
1809 : }
1810 32 : }
1811 :
1812 : void
1813 691 : JamiAccount::doRegister_()
1814 : {
1815 691 : if (registrationState_ != RegistrationState::TRYING) {
1816 0 : JAMI_ERROR("[Account {}] Already registered", getAccountID());
1817 0 : return;
1818 : }
1819 :
1820 2764 : JAMI_DEBUG("[Account {}] Starting account…", getAccountID());
1821 691 : const auto& conf = config();
1822 :
1823 : try {
1824 691 : if (not accountManager_ or not accountManager_->getInfo())
1825 0 : throw std::runtime_error("No identity configured for this account.");
1826 :
1827 691 : if (dht_->isRunning()) {
1828 8 : JAMI_ERROR("[Account {}] DHT already running (stopping it first).", getAccountID());
1829 2 : dht_->join();
1830 : }
1831 :
1832 691 : convModule()->clearPendingFetch();
1833 :
1834 : // Look for registered name
1835 691 : accountManager_->lookupAddress(accountManager_->getInfo()->accountId,
1836 691 : [w = weak()](const std::string& regName,
1837 : const std::string& address,
1838 : const NameDirectory::Response& response) {
1839 691 : if (auto this_ = w.lock()) {
1840 690 : if (response == NameDirectory::Response::found
1841 690 : or response == NameDirectory::Response::notFound) {
1842 690 : const auto& nameResult = response == NameDirectory::Response::found
1843 : ? regName
1844 690 : : "";
1845 690 : if (this_->setRegisteredName(nameResult)) {
1846 0 : this_->editConfig([&](JamiAccountConfig& config) {
1847 0 : config.registeredName = nameResult;
1848 0 : });
1849 0 : emitSignal<libjami::ConfigurationSignal::VolatileDetailsChanged>(
1850 0 : this_->accountID_, this_->getVolatileAccountDetails());
1851 : }
1852 690 : }
1853 691 : }
1854 691 : });
1855 :
1856 691 : dht::DhtRunner::Config config {};
1857 691 : config.dht_config.node_config.network = 0;
1858 691 : config.dht_config.node_config.maintain_storage = false;
1859 691 : config.dht_config.node_config.persist_path = (cachePath_ / "dhtstate").string();
1860 691 : config.dht_config.id = id_;
1861 691 : config.dht_config.cert_cache_all = true;
1862 691 : config.push_node_id = getAccountID();
1863 691 : config.push_token = conf.deviceKey;
1864 691 : config.push_topic = conf.notificationTopic;
1865 691 : config.push_platform = conf.platform;
1866 691 : config.proxy_user_agent = jami::userAgent();
1867 691 : config.threaded = true;
1868 691 : config.peer_discovery = conf.dhtPeerDiscovery;
1869 691 : config.peer_publish = conf.dhtPeerDiscovery;
1870 691 : if (conf.proxyEnabled)
1871 0 : config.proxy_server = proxyServerCached_;
1872 :
1873 691 : if (not config.proxy_server.empty()) {
1874 0 : JAMI_LOG("[Account {}] Using proxy server {}", getAccountID(), config.proxy_server);
1875 0 : if (not config.push_token.empty()) {
1876 0 : JAMI_LOG("[Account {}] using push notifications with platform: {}, topic: {}, token: {}",
1877 : getAccountID(),
1878 : config.push_platform,
1879 : config.push_topic,
1880 : config.push_token);
1881 : }
1882 : }
1883 :
1884 : // check if dht peer service is enabled
1885 691 : if (conf.accountPeerDiscovery or conf.accountPublish) {
1886 0 : peerDiscovery_ = std::make_shared<dht::PeerDiscovery>();
1887 0 : if (conf.accountPeerDiscovery) {
1888 0 : JAMI_LOG("[Account {}] Starting Jami account discovery…", getAccountID());
1889 0 : startAccountDiscovery();
1890 : }
1891 0 : if (conf.accountPublish)
1892 0 : startAccountPublish();
1893 : }
1894 691 : dht::DhtRunner::Context context {};
1895 691 : context.peerDiscovery = peerDiscovery_;
1896 691 : context.rng = std::make_unique<std::mt19937_64>(dht::crypto::getDerivedRandomEngine(rand));
1897 :
1898 691 : auto dht_log_level = Manager::instance().dhtLogLevel;
1899 691 : if (dht_log_level > 0) {
1900 0 : context.logger = Logger::dhtLogger();
1901 : }
1902 547 : context.certificateStore = [&](const dht::InfoHash& pk_id) {
1903 547 : std::vector<std::shared_ptr<dht::crypto::Certificate>> ret;
1904 1094 : if (auto cert = certStore().getCertificate(pk_id.toString()))
1905 547 : ret.emplace_back(std::move(cert));
1906 2188 : JAMI_LOG("[Account {}] Query for local certificate store: {}: {} found.",
1907 : getAccountID(),
1908 : pk_id.toString(),
1909 : ret.size());
1910 547 : return ret;
1911 691 : };
1912 891 : context.certificateStorePkId = [&](const DeviceId& pk_id) {
1913 891 : std::vector<std::shared_ptr<dht::crypto::Certificate>> ret;
1914 1782 : if (auto cert = certStore().getCertificate(pk_id.toString()))
1915 891 : ret.emplace_back(std::move(cert));
1916 3564 : JAMI_LOG("[Account {}] Query for local certificate store: {}: {} found.",
1917 : getAccountID(),
1918 : pk_id.toString(),
1919 : ret.size());
1920 891 : return ret;
1921 691 : };
1922 :
1923 6012 : context.statusChangedCallback = [this](dht::NodeStatus s4, dht::NodeStatus s6) {
1924 8016 : JAMI_LOG("[Account {}] DHT status: IPv4 {}; IPv6 {}", getAccountID(), dhtStatusStr(s4), dhtStatusStr(s6));
1925 : RegistrationState state;
1926 2004 : auto newStatus = std::max(s4, s6);
1927 2004 : switch (newStatus) {
1928 666 : case dht::NodeStatus::Connecting:
1929 666 : state = RegistrationState::TRYING;
1930 666 : break;
1931 1338 : case dht::NodeStatus::Connected:
1932 1338 : state = RegistrationState::REGISTERED;
1933 1338 : break;
1934 0 : case dht::NodeStatus::Disconnected:
1935 0 : state = RegistrationState::UNREGISTERED;
1936 0 : break;
1937 0 : default:
1938 0 : state = RegistrationState::ERROR_GENERIC;
1939 0 : break;
1940 : }
1941 :
1942 2004 : setRegistrationState(state);
1943 2695 : };
1944 3397 : context.identityAnnouncedCb = [this](bool ok) {
1945 689 : if (!ok) {
1946 64 : JAMI_ERROR("[Account {}] Identity announcement failed", getAccountID());
1947 16 : return;
1948 : }
1949 2692 : JAMI_WARNING("[Account {}] Identity announcement succeeded", getAccountID());
1950 1346 : accountManager_->startSync(
1951 1568 : [this](const std::shared_ptr<dht::crypto::Certificate>& crt) {
1952 748 : if (jami::Manager::instance().syncOnRegister) {
1953 748 : if (!crt)
1954 676 : return;
1955 748 : auto deviceId = crt->getLongId().toString();
1956 748 : if (accountManager_->getInfo()->deviceId == deviceId)
1957 676 : return;
1958 :
1959 72 : dht::ThreadPool::io().run([w = weak(), deviceId, crt] {
1960 72 : auto shared = w.lock();
1961 72 : if (!shared)
1962 0 : return;
1963 72 : std::unique_lock lk(shared->connManagerMtx_);
1964 72 : shared->initConnectionManager();
1965 72 : lk.unlock();
1966 72 : std::shared_lock slk(shared->connManagerMtx_);
1967 : // NOTE: connectionManager_ and channelHandlers_ get initialized at the
1968 : // same time and are both protected by connManagerMtx_, so this check
1969 : // ensures that the access to channelHandlers_ below is valid.
1970 72 : if (!shared->connectionManager_)
1971 0 : return;
1972 72 : shared->requestMessageConnection(shared->getUsername(), crt->getLongId(), "sync");
1973 72 : if (!shared->syncModule()->isConnected(crt->getLongId())) {
1974 68 : shared->channelHandlers_[Uri::Scheme::SYNC]
1975 68 : ->connect(crt->getLongId(),
1976 : "",
1977 68 : [](std::shared_ptr<dhtnet::ChannelSocket> socket,
1978 68 : const DeviceId& deviceId) {});
1979 : }
1980 72 : });
1981 748 : }
1982 : },
1983 3365 : [this] {
1984 673 : if (jami::Manager::instance().syncOnRegister) {
1985 673 : deviceAnnounced_ = true;
1986 :
1987 : // Bootstrap at the end to avoid to be long to load.
1988 673 : dht::ThreadPool::io().run([w = weak()] {
1989 673 : if (auto shared = w.lock())
1990 673 : shared->convModule()->bootstrap();
1991 673 : });
1992 673 : emitSignal<libjami::ConfigurationSignal::VolatileDetailsChanged>(accountID_,
1993 1346 : getVolatileAccountDetails());
1994 : }
1995 673 : },
1996 673 : publishPresence_);
1997 691 : };
1998 :
1999 691 : dht_->run(dhtPortUsed(), config, std::move(context));
2000 :
2001 1382 : for (const auto& bootstrap : loadBootstrap())
2002 1382 : dht_->bootstrap(bootstrap);
2003 :
2004 691 : dhtBoundPort_ = dht_->getBoundPort();
2005 :
2006 691 : accountManager_->setDht(dht_);
2007 :
2008 691 : std::unique_lock lkCM(connManagerMtx_);
2009 691 : initConnectionManager();
2010 691 : connectionManager_->dhtStarted();
2011 691 : connectionManager_->onICERequest([this](const DeviceId& deviceId) {
2012 746 : std::promise<bool> accept;
2013 746 : std::future<bool> fut = accept.get_future();
2014 746 : accountManager_
2015 746 : ->findCertificate(deviceId, [this, &accept](const std::shared_ptr<dht::crypto::Certificate>& cert) {
2016 746 : if (!cert) {
2017 0 : accept.set_value(false);
2018 0 : return;
2019 : }
2020 746 : dht::InfoHash peer_account_id;
2021 746 : auto res = accountManager_->onPeerCertificate(cert,
2022 746 : this->config().dhtPublicInCalls,
2023 746 : peer_account_id);
2024 2984 : JAMI_LOG("[Account {}] [device {}] {} ICE request from {}",
2025 : getAccountID(),
2026 : cert->getLongId(),
2027 : res ? "Accepting" : "Discarding",
2028 : peer_account_id);
2029 746 : accept.set_value(res);
2030 : });
2031 746 : fut.wait();
2032 746 : auto result = fut.get();
2033 746 : return result;
2034 746 : });
2035 691 : connectionManager_->onChannelRequest([this](const std::shared_ptr<dht::crypto::Certificate>& cert,
2036 15109 : const std::string& name) {
2037 8606 : JAMI_LOG("[Account {}] [device {}] New channel requested: '{}'", getAccountID(), cert->getLongId(), name);
2038 :
2039 2154 : if (this->config().turnEnabled && turnCache_) {
2040 2154 : auto addr = turnCache_->getResolvedTurn();
2041 2154 : if (addr == std::nullopt) {
2042 : // If TURN is enabled, but no TURN cached, there can be a temporary
2043 : // resolution error to solve. Sometimes, a connectivity change is not
2044 : // enough, so even if this case is really rare, it should be easy to avoid.
2045 32 : turnCache_->refresh();
2046 : }
2047 : }
2048 :
2049 2153 : auto uri = Uri(name);
2050 2154 : std::shared_lock lk(connManagerMtx_);
2051 2154 : auto itHandler = channelHandlers_.find(uri.scheme());
2052 2154 : if (itHandler != channelHandlers_.end() && itHandler->second)
2053 2045 : return itHandler->second->onRequest(cert, name);
2054 109 : return name == "sip";
2055 2154 : });
2056 691 : connectionManager_->onConnectionReady(
2057 23430 : [this](const DeviceId& deviceId, const std::string& name, std::shared_ptr<dhtnet::ChannelSocket> channel) {
2058 4101 : if (channel) {
2059 4102 : auto cert = channel->peerCertificate();
2060 4102 : if (!cert || !cert->issuer)
2061 0 : return;
2062 4100 : auto peerId = cert->issuer->getId().toString();
2063 : // A connection request can be sent just before member is banned and this must be ignored.
2064 4101 : if (accountManager()->getCertificateStatus(peerId)
2065 4103 : == dhtnet::tls::TrustStore::PermissionStatus::BANNED) {
2066 56 : channel->shutdown();
2067 56 : return;
2068 : }
2069 4047 : if (name == "sip") {
2070 176 : cacheSIPConnection(std::move(channel), peerId, deviceId);
2071 3871 : } else if (name.find("git://") == 0) {
2072 1680 : auto sep = name.find_last_of('/');
2073 1680 : auto conversationId = name.substr(sep + 1);
2074 1680 : auto remoteDevice = name.substr(6, sep - 6);
2075 :
2076 1680 : if (channel->isInitiator()) {
2077 : // Check if wanted remote is our side (git://remoteDevice/conversationId)
2078 832 : return;
2079 : }
2080 :
2081 : // Check if pull from banned device
2082 848 : if (convModule()->isBanned(conversationId, remoteDevice)) {
2083 0 : JAMI_WARNING("[Account {:s}] [Conversation {}] Git server requested, but the "
2084 : "device is unauthorized ({:s}) ",
2085 : getAccountID(),
2086 : conversationId,
2087 : remoteDevice);
2088 0 : channel->shutdown();
2089 0 : return;
2090 : }
2091 :
2092 848 : auto sock = convModule()->gitSocket(deviceId.toString(), conversationId);
2093 848 : if (sock == channel) {
2094 : // The onConnectionReady is already used as client (for retrieving messages)
2095 : // So it's not the server socket
2096 0 : return;
2097 : }
2098 3392 : JAMI_LOG("[Account {:s}] [Conversation {}] [device {}] Git server requested",
2099 : accountID_,
2100 : conversationId,
2101 : deviceId.toString());
2102 848 : auto gs = std::make_unique<GitServer>(accountID_, conversationId, channel);
2103 848 : syncCnt_.fetch_add(1);
2104 848 : gs->setOnFetched([w = weak(), conversationId, deviceId](const std::string& commit) {
2105 1114 : dht::ThreadPool::computation().run([w, conversationId, deviceId, commit]() {
2106 1114 : if (auto shared = w.lock()) {
2107 1114 : shared->convModule()->setFetched(conversationId, deviceId.toString(), commit);
2108 2228 : if (shared->syncCnt_.fetch_sub(1) == 1) {
2109 311 : emitSignal<libjami::ConversationSignal::ConversationCloned>(
2110 311 : shared->getAccountID().c_str());
2111 : }
2112 1114 : }
2113 1114 : });
2114 1114 : });
2115 848 : const dht::Value::Id serverId = ValueIdDist()(rand);
2116 : {
2117 848 : std::lock_guard lk(gitServersMtx_);
2118 848 : gitServers_[serverId] = std::move(gs);
2119 848 : }
2120 848 : channel->onShutdown([w = weak(), serverId](const std::error_code&) {
2121 : // Run on main thread to avoid to be in mxSock's eventLoop
2122 848 : runOnMainThread([serverId, w]() {
2123 848 : if (auto sthis = w.lock()) {
2124 848 : std::lock_guard lk(sthis->gitServersMtx_);
2125 848 : sthis->gitServers_.erase(serverId);
2126 1696 : }
2127 848 : });
2128 848 : });
2129 2512 : } else {
2130 : // TODO move git://
2131 2192 : std::shared_lock lk(connManagerMtx_);
2132 2191 : auto uri = Uri(name);
2133 2190 : auto itHandler = channelHandlers_.find(uri.scheme());
2134 2191 : if (itHandler != channelHandlers_.end() && itHandler->second)
2135 2188 : itHandler->second->onReady(cert, name, std::move(channel));
2136 2191 : }
2137 4992 : }
2138 : });
2139 691 : lkCM.unlock();
2140 :
2141 691 : if (!conf.managerUri.empty() && accountManager_) {
2142 0 : dynamic_cast<ServerAccountManager*>(accountManager_.get())->onNeedsMigration([this]() {
2143 0 : editConfig([&](JamiAccountConfig& conf) {
2144 0 : conf.receipt.clear();
2145 0 : conf.receiptSignature.clear();
2146 0 : });
2147 0 : Migration::setState(accountID_, Migration::State::INVALID);
2148 0 : setRegistrationState(RegistrationState::ERROR_NEED_MIGRATION);
2149 0 : });
2150 0 : dynamic_cast<ServerAccountManager*>(accountManager_.get())
2151 0 : ->syncBlueprintConfig([this](const std::map<std::string, std::string>& config) {
2152 0 : editConfig([&](JamiAccountConfig& conf) { conf.fromMap(config); });
2153 0 : emitSignal<libjami::ConfigurationSignal::AccountDetailsChanged>(getAccountID(), getAccountDetails());
2154 0 : });
2155 : }
2156 :
2157 691 : std::lock_guard lock(buddyInfoMtx);
2158 692 : for (auto& buddy : trackedBuddies_) {
2159 1 : buddy.second.devices_cnt = 0;
2160 1 : trackPresence(buddy.first, buddy.second);
2161 : }
2162 691 : } catch (const std::exception& e) {
2163 0 : JAMI_ERR("Error registering DHT account: %s", e.what());
2164 0 : setRegistrationState(RegistrationState::ERROR_GENERIC);
2165 0 : }
2166 : }
2167 :
2168 : ConversationModule*
2169 27528 : JamiAccount::convModule(bool noCreation)
2170 : {
2171 27528 : if (noCreation)
2172 5387 : return convModule_.get();
2173 22141 : if (!accountManager() || currentDeviceId() == "") {
2174 0 : JAMI_ERROR("[Account {}] Calling convModule() with an uninitialized account", getAccountID());
2175 0 : return nullptr;
2176 : }
2177 22148 : std::unique_lock lock(configurationMutex_);
2178 22144 : std::lock_guard lk(moduleMtx_);
2179 22148 : if (!convModule_) {
2180 1334 : convModule_ = std::make_unique<ConversationModule>(
2181 667 : shared(),
2182 667 : accountManager_,
2183 3110 : [this](auto&& syncMsg) {
2184 3110 : dht::ThreadPool::computation().run([w = weak(), syncMsg] {
2185 3110 : if (auto shared = w.lock()) {
2186 1555 : auto& config = shared->config();
2187 : // For JAMS account, we must update the server
2188 : // for now, only sync with the JAMS server for changes to the conversation list
2189 1555 : if (!config.managerUri.empty() && !syncMsg)
2190 0 : if (auto am = shared->accountManager())
2191 0 : am->syncDevices();
2192 1555 : if (auto sm = shared->syncModule())
2193 1555 : sm->syncWithConnected(syncMsg);
2194 : }
2195 : });
2196 1555 : },
2197 26939 : [this](auto&& uri, auto&& device, auto&& msg, auto token = 0) {
2198 : // No need to retrigger, sendTextMessage will call
2199 : // messageEngine_.sendMessage, already retriggering on
2200 : // main thread.
2201 13468 : auto deviceId = device ? device.toString() : "";
2202 26942 : return sendTextMessage(uri, deviceId, msg, token);
2203 13471 : },
2204 4238 : [this](const auto& convId, const auto& deviceId, auto cb, const auto& type) {
2205 2119 : dht::ThreadPool::io().run([w = weak(), convId, deviceId, cb = std::move(cb), type] {
2206 2119 : auto shared = w.lock();
2207 2119 : if (!shared)
2208 0 : return;
2209 3320 : if (auto socket = shared->convModule()->gitSocket(deviceId, convId)) {
2210 1201 : if (!cb(socket))
2211 0 : socket->shutdown();
2212 : else
2213 1201 : cb({});
2214 1201 : return;
2215 : }
2216 918 : std::shared_lock lkCM(shared->connManagerMtx_);
2217 918 : if (!shared->connectionManager_) {
2218 11 : lkCM.unlock();
2219 11 : cb({});
2220 11 : return;
2221 : }
2222 :
2223 4535 : shared->connectionManager_->connectDevice(
2224 1814 : DeviceId(deviceId),
2225 907 : fmt::format("git://{}/{}", deviceId, convId),
2226 1814 : [w, cb = std::move(cb), convId](std::shared_ptr<dhtnet::ChannelSocket> socket, const DeviceId&) {
2227 1814 : dht::ThreadPool::io().run([w, cb = std::move(cb), socket = std::move(socket), convId] {
2228 907 : if (socket) {
2229 1696 : socket->onShutdown(
2230 848 : [w, deviceId = socket->deviceId(), convId](const std::error_code&) {
2231 1696 : dht::ThreadPool::io().run([w, deviceId, convId] {
2232 1694 : if (auto shared = w.lock())
2233 847 : shared->convModule()->removeGitSocket(deviceId.toString(), convId);
2234 : });
2235 : });
2236 848 : if (!cb(socket))
2237 0 : socket->shutdown();
2238 : } else
2239 59 : cb({});
2240 : });
2241 : },
2242 : false,
2243 : false,
2244 907 : type);
2245 2130 : });
2246 2119 : },
2247 1364 : [this](const auto& convId, const auto& deviceId, auto&& cb, const auto& connectionType) {
2248 682 : dht::ThreadPool::io().run([w = weak(), convId, deviceId, cb = std::move(cb), connectionType] {
2249 682 : auto shared = w.lock();
2250 682 : if (!shared)
2251 0 : return;
2252 682 : auto cm = shared->convModule();
2253 682 : std::shared_lock lkCM(shared->connManagerMtx_);
2254 682 : if (!shared->connectionManager_ || !cm || cm->isBanned(convId, deviceId)) {
2255 72 : asio::post(*Manager::instance().ioContext(), [cb = std::move(cb)] { cb({}); });
2256 36 : return;
2257 : }
2258 1292 : if (!shared->connectionManager_->isConnecting(DeviceId(deviceId),
2259 646 : fmt::format("swarm://{}", convId))) {
2260 606 : shared->connectionManager_
2261 1818 : ->connectDevice(DeviceId(deviceId),
2262 606 : fmt::format("swarm://{}", convId),
2263 606 : [w, cb = std::move(cb)](std::shared_ptr<dhtnet::ChannelSocket> socket,
2264 : const DeviceId& deviceId) {
2265 1818 : dht::ThreadPool::io().run(
2266 1212 : [w, cb = std::move(cb), socket = std::move(socket), deviceId] {
2267 606 : if (socket) {
2268 316 : auto shared = w.lock();
2269 316 : if (!shared)
2270 0 : return;
2271 316 : auto remoteCert = socket->peerCertificate();
2272 316 : auto uri = remoteCert->issuer->getId().toString();
2273 316 : if (shared->accountManager()->getCertificateStatus(uri)
2274 316 : == dhtnet::tls::TrustStore::PermissionStatus::BANNED) {
2275 0 : cb(nullptr);
2276 0 : return;
2277 : }
2278 316 : shared->requestMessageConnection(uri, deviceId, "");
2279 316 : }
2280 606 : cb(socket);
2281 : });
2282 : });
2283 : }
2284 718 : });
2285 682 : },
2286 4 : [this](auto&& convId, auto&& from) {
2287 2 : accountManager_->findCertificate(dht::InfoHash(from),
2288 2 : [this, from, convId](
2289 : const std::shared_ptr<dht::crypto::Certificate>& cert) {
2290 2 : auto info = accountManager_->getInfo();
2291 2 : if (!cert || !info)
2292 0 : return;
2293 4 : info->contacts->onTrustRequest(dht::InfoHash(from),
2294 : cert->getSharedPublicKey(),
2295 : time(nullptr),
2296 : false,
2297 2 : convId,
2298 : {});
2299 : });
2300 2 : },
2301 1334 : autoLoadConversations_);
2302 : }
2303 22145 : return convModule_.get();
2304 22149 : }
2305 :
2306 : SyncModule*
2307 2568 : JamiAccount::syncModule()
2308 : {
2309 2568 : if (!accountManager() || currentDeviceId() == "") {
2310 0 : JAMI_ERR() << "Calling syncModule() with an uninitialized account.";
2311 0 : return nullptr;
2312 : }
2313 2568 : std::lock_guard lk(moduleMtx_);
2314 2568 : if (!syncModule_)
2315 657 : syncModule_ = std::make_unique<SyncModule>(shared());
2316 2568 : return syncModule_.get();
2317 2568 : }
2318 :
2319 : void
2320 12541 : JamiAccount::onTextMessage(const std::string& id,
2321 : const std::string& from,
2322 : const std::shared_ptr<dht::crypto::Certificate>& peerCert,
2323 : const std::map<std::string, std::string>& payloads)
2324 : {
2325 : try {
2326 12541 : const std::string fromUri {parseJamiUri(from)};
2327 12541 : SIPAccountBase::onTextMessage(id, fromUri, peerCert, payloads);
2328 12546 : } catch (...) {
2329 0 : }
2330 12546 : }
2331 :
2332 : void
2333 0 : JamiAccount::loadConversation(const std::string& convId)
2334 : {
2335 0 : if (auto cm = convModule(true))
2336 0 : cm->loadSingleConversation(convId);
2337 0 : }
2338 :
2339 : void
2340 957 : JamiAccount::doUnregister(bool forceShutdownConnections)
2341 : {
2342 957 : std::unique_lock lock(configurationMutex_);
2343 957 : if (registrationState_ >= RegistrationState::ERROR_GENERIC) {
2344 144 : return;
2345 : }
2346 :
2347 813 : std::mutex mtx;
2348 813 : std::condition_variable cv;
2349 813 : bool shutdown_complete {false};
2350 :
2351 813 : if (peerDiscovery_) {
2352 0 : peerDiscovery_->stopPublish(PEER_DISCOVERY_JAMI_SERVICE);
2353 0 : peerDiscovery_->stopDiscovery(PEER_DISCOVERY_JAMI_SERVICE);
2354 : }
2355 :
2356 813 : JAMI_WARN("[Account %s] Unregistering account %p", getAccountID().c_str(), this);
2357 813 : dht_->shutdown(
2358 813 : [&] {
2359 813 : JAMI_WARN("[Account %s] DHT shutdown complete", getAccountID().c_str());
2360 813 : std::lock_guard lock(mtx);
2361 813 : shutdown_complete = true;
2362 813 : cv.notify_all();
2363 813 : },
2364 : true);
2365 :
2366 : {
2367 813 : std::lock_guard lk(pendingCallsMutex_);
2368 813 : pendingCalls_.clear();
2369 813 : }
2370 :
2371 : // Stop all current P2P connections if account is disabled
2372 : // or if explicitly requested by the caller.
2373 : // NOTE: Leaving the connections open is useful when changing an account's config.
2374 813 : if (not isEnabled() || forceShutdownConnections)
2375 797 : shutdownConnections();
2376 :
2377 : // Release current UPnP mapping if any.
2378 813 : if (upnpCtrl_ and dhtUpnpMapping_.isValid()) {
2379 0 : upnpCtrl_->releaseMapping(dhtUpnpMapping_);
2380 : }
2381 :
2382 : {
2383 813 : std::unique_lock lock(mtx);
2384 2310 : cv.wait(lock, [&] { return shutdown_complete; });
2385 813 : }
2386 813 : dht_->join();
2387 813 : setRegistrationState(RegistrationState::UNREGISTERED);
2388 :
2389 813 : lock.unlock();
2390 :
2391 : #ifdef ENABLE_PLUGIN
2392 813 : jami::Manager::instance().getJamiPluginManager().getChatServicesManager().cleanChatSubjects(getAccountID());
2393 : #endif
2394 957 : }
2395 :
2396 : void
2397 5056 : JamiAccount::setRegistrationState(RegistrationState state, int detail_code, const std::string& detail_str)
2398 : {
2399 5056 : if (registrationState_ != state) {
2400 3614 : if (state == RegistrationState::REGISTERED) {
2401 2760 : JAMI_WARNING("[Account {}] Connected", getAccountID());
2402 690 : turnCache_->refresh();
2403 690 : if (connectionManager_)
2404 680 : connectionManager_->storeActiveIpAddress();
2405 2924 : } else if (state == RegistrationState::TRYING) {
2406 2764 : JAMI_WARNING("[Account {}] Connecting…", getAccountID());
2407 : } else {
2408 2233 : deviceAnnounced_ = false;
2409 8932 : JAMI_WARNING("[Account {}] Disconnected", getAccountID());
2410 : }
2411 : }
2412 : // Update registrationState_ & emit signals
2413 5056 : Account::setRegistrationState(state, detail_code, detail_str);
2414 5056 : }
2415 :
2416 : void
2417 0 : JamiAccount::reloadContacts()
2418 : {
2419 0 : accountManager_->reloadContacts();
2420 0 : }
2421 :
2422 : void
2423 0 : JamiAccount::connectivityChanged()
2424 : {
2425 0 : JAMI_WARN("connectivityChanged");
2426 0 : if (not isUsable()) {
2427 : // nothing to do
2428 0 : return;
2429 : }
2430 :
2431 0 : if (auto cm = convModule())
2432 0 : cm->connectivityChanged();
2433 0 : dht_->connectivityChanged();
2434 : {
2435 0 : std::shared_lock lkCM(connManagerMtx_);
2436 0 : if (connectionManager_) {
2437 0 : connectionManager_->connectivityChanged();
2438 : // reset cache
2439 0 : connectionManager_->setPublishedAddress({});
2440 : }
2441 0 : }
2442 : }
2443 :
2444 : bool
2445 0 : JamiAccount::findCertificate(const dht::InfoHash& h,
2446 : std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb)
2447 : {
2448 0 : if (accountManager_)
2449 0 : return accountManager_->findCertificate(h, std::move(cb));
2450 0 : return false;
2451 : }
2452 :
2453 : bool
2454 0 : JamiAccount::findCertificate(const dht::PkId& id,
2455 : std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb)
2456 : {
2457 0 : if (accountManager_)
2458 0 : return accountManager_->findCertificate(id, std::move(cb));
2459 0 : return false;
2460 : }
2461 :
2462 : bool
2463 80 : JamiAccount::findCertificate(const std::string& crt_id)
2464 : {
2465 80 : if (accountManager_)
2466 80 : return accountManager_->findCertificate(dht::InfoHash(crt_id));
2467 0 : return false;
2468 : }
2469 :
2470 : bool
2471 83 : JamiAccount::setCertificateStatus(const std::string& cert_id, dhtnet::tls::TrustStore::PermissionStatus status)
2472 : {
2473 83 : bool done = accountManager_ ? accountManager_->setCertificateStatus(cert_id, status) : false;
2474 83 : if (done) {
2475 80 : findCertificate(cert_id);
2476 80 : emitSignal<libjami::ConfigurationSignal::CertificateStateChanged>(getAccountID(),
2477 : cert_id,
2478 : dhtnet::tls::TrustStore::statusToStr(status));
2479 : }
2480 83 : return done;
2481 : }
2482 :
2483 : bool
2484 0 : JamiAccount::setCertificateStatus(const std::shared_ptr<crypto::Certificate>& cert,
2485 : dhtnet::tls::TrustStore::PermissionStatus status,
2486 : bool local)
2487 : {
2488 0 : bool done = accountManager_ ? accountManager_->setCertificateStatus(cert, status, local) : false;
2489 0 : if (done) {
2490 0 : findCertificate(cert->getId().toString());
2491 0 : emitSignal<libjami::ConfigurationSignal::CertificateStateChanged>(getAccountID(),
2492 0 : cert->getId().toString(),
2493 : dhtnet::tls::TrustStore::statusToStr(status));
2494 : }
2495 0 : return done;
2496 : }
2497 :
2498 : std::vector<std::string>
2499 0 : JamiAccount::getCertificatesByStatus(dhtnet::tls::TrustStore::PermissionStatus status)
2500 : {
2501 0 : if (accountManager_)
2502 0 : return accountManager_->getCertificatesByStatus(status);
2503 0 : return {};
2504 : }
2505 :
2506 : bool
2507 0 : JamiAccount::isMessageTreated(dht::Value::Id id)
2508 : {
2509 0 : std::lock_guard lock(messageMutex_);
2510 0 : return !treatedMessages_.add(id);
2511 0 : }
2512 :
2513 : bool
2514 13 : JamiAccount::sha3SumVerify() const
2515 : {
2516 13 : return !noSha3sumVerification_;
2517 : }
2518 :
2519 : #ifdef LIBJAMI_TEST
2520 : void
2521 1 : JamiAccount::noSha3sumVerification(bool newValue)
2522 : {
2523 1 : noSha3sumVerification_ = newValue;
2524 1 : }
2525 : #endif
2526 :
2527 : std::map<std::string, std::string>
2528 186 : JamiAccount::getKnownDevices() const
2529 : {
2530 186 : std::lock_guard lock(configurationMutex_);
2531 186 : if (not accountManager_ or not accountManager_->getInfo())
2532 0 : return {};
2533 186 : std::map<std::string, std::string> ids;
2534 1375 : for (const auto& d : accountManager_->getKnownDevices()) {
2535 1189 : auto id = d.first.toString();
2536 1189 : auto label = d.second.name.empty() ? id.substr(0, 8) : d.second.name;
2537 1189 : ids.emplace(std::move(id), std::move(label));
2538 1189 : }
2539 186 : return ids;
2540 186 : }
2541 :
2542 : void
2543 0 : JamiAccount::loadCachedUrl(const std::string& url,
2544 : const std::filesystem::path& cachePath,
2545 : const std::chrono::seconds& cacheDuration,
2546 : std::function<void(const dht::http::Response& response)> cb)
2547 : {
2548 0 : dht::ThreadPool::io().run([cb, url, cachePath, cacheDuration, w = weak()]() {
2549 : try {
2550 0 : std::string data;
2551 : {
2552 0 : std::lock_guard lk(dhtnet::fileutils::getFileLock(cachePath));
2553 0 : data = fileutils::loadCacheTextFile(cachePath, cacheDuration);
2554 0 : }
2555 0 : dht::http::Response ret;
2556 0 : ret.body = std::move(data);
2557 0 : ret.status_code = 200;
2558 0 : cb(ret);
2559 0 : } catch (const std::exception& e) {
2560 0 : JAMI_LOG("Failed to load '{}' from '{}': {}", url, cachePath, e.what());
2561 :
2562 0 : if (auto sthis = w.lock()) {
2563 : auto req = std::make_shared<dht::http::Request>(
2564 0 : *Manager::instance().ioContext(), url, [cb, cachePath, w](const dht::http::Response& response) {
2565 0 : if (response.status_code == 200) {
2566 : try {
2567 0 : std::lock_guard lk(dhtnet::fileutils::getFileLock(cachePath));
2568 0 : fileutils::saveFile(cachePath,
2569 0 : (const uint8_t*) response.body.data(),
2570 : response.body.size(),
2571 : 0600);
2572 0 : JAMI_LOG("Cached result to '{}'", cachePath);
2573 0 : } catch (const std::exception& ex) {
2574 0 : JAMI_WARNING("Failed to save result to '{}': {}", cachePath, ex.what());
2575 0 : }
2576 0 : cb(response);
2577 : } else {
2578 : try {
2579 0 : if (std::filesystem::exists(cachePath)) {
2580 0 : JAMI_WARNING("Failed to download URL, using cached data");
2581 0 : std::string data;
2582 : {
2583 0 : std::lock_guard lk(dhtnet::fileutils::getFileLock(cachePath));
2584 0 : data = fileutils::loadTextFile(cachePath);
2585 0 : }
2586 0 : dht::http::Response ret;
2587 0 : ret.body = std::move(data);
2588 0 : ret.status_code = 200;
2589 0 : cb(ret);
2590 0 : } else
2591 0 : throw std::runtime_error("No cached data");
2592 0 : } catch (...) {
2593 0 : cb(response);
2594 0 : }
2595 : }
2596 0 : if (auto req = response.request.lock())
2597 0 : if (auto sthis = w.lock())
2598 0 : sthis->requests_.erase(req);
2599 0 : });
2600 0 : sthis->requests_.emplace(req);
2601 0 : req->send();
2602 0 : }
2603 0 : }
2604 0 : });
2605 0 : }
2606 :
2607 : void
2608 691 : JamiAccount::loadCachedProxyServer(std::function<void(const std::string& proxy)> cb)
2609 : {
2610 691 : const auto& conf = config();
2611 691 : if (conf.proxyEnabled and proxyServerCached_.empty()) {
2612 0 : JAMI_DEBUG("[Account {:s}] Loading DHT proxy URL: {:s}", getAccountID(), conf.proxyListUrl);
2613 0 : if (conf.proxyListUrl.empty() or not conf.proxyListEnabled) {
2614 0 : cb(getDhtProxyServer(conf.proxyServer));
2615 : } else {
2616 0 : loadCachedUrl(conf.proxyListUrl,
2617 0 : cachePath_ / "dhtproxylist",
2618 0 : std::chrono::hours(24 * 3),
2619 0 : [w = weak(), cb = std::move(cb)](const dht::http::Response& response) {
2620 0 : if (auto sthis = w.lock()) {
2621 0 : if (response.status_code == 200) {
2622 0 : cb(sthis->getDhtProxyServer(response.body));
2623 : } else {
2624 0 : cb(sthis->getDhtProxyServer(sthis->config().proxyServer));
2625 : }
2626 0 : }
2627 0 : });
2628 : }
2629 : } else {
2630 691 : cb(proxyServerCached_);
2631 : }
2632 691 : }
2633 :
2634 : std::string
2635 0 : JamiAccount::getDhtProxyServer(const std::string& serverList)
2636 : {
2637 0 : if (proxyServerCached_.empty()) {
2638 0 : std::vector<std::string> proxys;
2639 : // Split the list of servers
2640 0 : std::sregex_iterator begin = {serverList.begin(), serverList.end(), PROXY_REGEX}, end;
2641 0 : for (auto it = begin; it != end; ++it) {
2642 0 : auto& match = *it;
2643 0 : if (match[5].matched and match[6].matched) {
2644 : try {
2645 0 : auto start = std::stoi(match[5]), end = std::stoi(match[6]);
2646 0 : for (auto p = start; p <= end; p++)
2647 0 : proxys.emplace_back(match[1].str() + match[2].str() + ":" + std::to_string(p));
2648 0 : } catch (...) {
2649 0 : JAMI_WARN("Malformed proxy, ignore it");
2650 0 : continue;
2651 0 : }
2652 : } else {
2653 0 : proxys.emplace_back(match[0].str());
2654 : }
2655 0 : }
2656 0 : if (proxys.empty())
2657 0 : return {};
2658 : // Select one of the list as the current proxy.
2659 0 : auto randIt = proxys.begin();
2660 0 : std::advance(randIt, std::uniform_int_distribution<unsigned long>(0, proxys.size() - 1)(rand));
2661 0 : proxyServerCached_ = *randIt;
2662 : // Cache it!
2663 0 : dhtnet::fileutils::check_dir(cachePath_, 0700);
2664 0 : auto proxyCachePath = cachePath_ / "dhtproxy";
2665 0 : std::ofstream file(proxyCachePath);
2666 0 : JAMI_DEBUG("Cache DHT proxy server: {}", proxyServerCached_);
2667 0 : Json::Value node(Json::objectValue);
2668 0 : node[getProxyConfigKey()] = proxyServerCached_;
2669 0 : if (file.is_open())
2670 0 : file << node;
2671 : else
2672 0 : JAMI_WARNING("Unable to write into {}", proxyCachePath);
2673 0 : }
2674 0 : return proxyServerCached_;
2675 : }
2676 :
2677 : MatchRank
2678 0 : JamiAccount::matches(std::string_view userName, std::string_view server) const
2679 : {
2680 0 : if (not accountManager_ or not accountManager_->getInfo())
2681 0 : return MatchRank::NONE;
2682 :
2683 0 : if (userName == accountManager_->getInfo()->accountId || server == accountManager_->getInfo()->accountId
2684 0 : || userName == accountManager_->getInfo()->deviceId) {
2685 0 : JAMI_LOG("Matching account ID in request with username {}", userName);
2686 0 : return MatchRank::FULL;
2687 : } else {
2688 0 : return MatchRank::NONE;
2689 : }
2690 : }
2691 :
2692 : std::string
2693 325 : JamiAccount::getFromUri() const
2694 : {
2695 325 : const std::string uri = "<sip:" + accountManager_->getInfo()->accountId + "@ring.dht>";
2696 322 : if (not config().displayName.empty())
2697 646 : return "\"" + config().displayName + "\" " + uri;
2698 0 : return uri;
2699 323 : }
2700 :
2701 : std::string
2702 274 : JamiAccount::getToUri(const std::string& to) const
2703 : {
2704 274 : auto username = to;
2705 274 : string_replace(username, "sip:", "");
2706 274 : return fmt::format("<sips:{};transport=tls>", username);
2707 274 : }
2708 :
2709 : std::string
2710 7 : getDisplayed(const std::string& conversationId, const std::string& messageId)
2711 : {
2712 : // implementing https://tools.ietf.org/rfc/rfc5438.txt
2713 : return fmt::format("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n"
2714 : "<imdn><message-id>{}</message-id>\n"
2715 : "{}"
2716 : "<display-notification><status><displayed/></status></display-notification>\n"
2717 : "</imdn>",
2718 : messageId,
2719 14 : conversationId.empty() ? "" : "<conversation>" + conversationId + "</conversation>");
2720 : }
2721 :
2722 : std::string
2723 6 : getPIDF(const std::string& note)
2724 : {
2725 : // implementing https://datatracker.ietf.org/doc/html/rfc3863
2726 : return fmt::format("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2727 : "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\">\n"
2728 : " <tuple>\n"
2729 : " <status>\n"
2730 : " <basic>{}</basic>\n"
2731 : " </status>\n"
2732 : " </tuple>\n"
2733 : "</presence>",
2734 6 : note);
2735 : }
2736 :
2737 : void
2738 5 : JamiAccount::setIsComposing(const std::string& conversationUri, bool isWriting)
2739 : {
2740 5 : Uri uri(conversationUri);
2741 5 : std::string conversationId = {};
2742 5 : if (uri.scheme() == Uri::Scheme::SWARM) {
2743 5 : conversationId = uri.authority();
2744 : } else {
2745 0 : return;
2746 : }
2747 :
2748 5 : if (auto cm = convModule(true)) {
2749 5 : if (auto typer = cm->getTypers(conversationId)) {
2750 5 : if (isWriting)
2751 4 : typer->addTyper(getUsername(), true);
2752 : else
2753 1 : typer->removeTyper(getUsername(), true);
2754 5 : }
2755 : }
2756 5 : }
2757 :
2758 : bool
2759 9 : JamiAccount::setMessageDisplayed(const std::string& conversationUri, const std::string& messageId, int status)
2760 : {
2761 9 : Uri uri(conversationUri);
2762 9 : std::string conversationId = {};
2763 9 : if (uri.scheme() == Uri::Scheme::SWARM)
2764 9 : conversationId = uri.authority();
2765 9 : auto sendMessage = status == (int) libjami::Account::MessageStates::DISPLAYED && isReadReceiptEnabled();
2766 9 : if (!conversationId.empty())
2767 9 : sendMessage &= convModule()->onMessageDisplayed(getUsername(), conversationId, messageId);
2768 9 : if (sendMessage)
2769 14 : sendInstantMessage(uri.authority(), {{MIME_TYPE_IMDN, getDisplayed(conversationId, messageId)}});
2770 9 : return true;
2771 9 : }
2772 :
2773 : std::string
2774 182 : JamiAccount::getContactHeader(const std::shared_ptr<SipTransport>& sipTransport)
2775 : {
2776 182 : if (sipTransport and sipTransport->get() != nullptr) {
2777 182 : auto transport = sipTransport->get();
2778 182 : auto* td = reinterpret_cast<tls::AbstractSIPTransport::TransportData*>(transport);
2779 182 : auto address = td->self->getLocalAddress().toString(true);
2780 182 : bool reliable = transport->flag & PJSIP_TRANSPORT_RELIABLE;
2781 : return fmt::format("\"{}\" <sips:{}{}{};transport={}>",
2782 182 : config().displayName,
2783 182 : id_.second->getId().toString(),
2784 182 : address.empty() ? "" : "@",
2785 : address,
2786 364 : reliable ? "tls" : "dtls");
2787 182 : } else {
2788 0 : JAMI_ERR("getContactHeader: no SIP transport provided");
2789 0 : return fmt::format("\"{}\" <sips:{}@ring.dht>", config().displayName, id_.second->getId().toString());
2790 : }
2791 : }
2792 :
2793 : void
2794 67 : JamiAccount::addContact(const std::string& uri, bool confirmed)
2795 : {
2796 67 : dht::InfoHash h(uri);
2797 67 : if (not h) {
2798 4 : JAMI_ERROR("addContact: invalid contact URI");
2799 1 : return;
2800 : }
2801 66 : auto conversation = convModule()->getOneToOneConversation(uri);
2802 66 : if (!confirmed && conversation.empty())
2803 66 : conversation = convModule()->startConversation(ConversationMode::ONE_TO_ONE, h);
2804 66 : std::unique_lock lock(configurationMutex_);
2805 66 : if (accountManager_)
2806 66 : accountManager_->addContact(h, confirmed, conversation);
2807 : else
2808 0 : JAMI_WARNING("[Account {}] addContact: account not loaded", getAccountID());
2809 66 : }
2810 :
2811 : void
2812 19 : JamiAccount::removeContact(const std::string& uri, bool ban)
2813 : {
2814 19 : std::lock_guard lock(configurationMutex_);
2815 19 : if (accountManager_)
2816 19 : accountManager_->removeContact(uri, ban);
2817 : else
2818 0 : JAMI_WARNING("[Account {}] removeContact: account not loaded", getAccountID());
2819 19 : }
2820 :
2821 : std::map<std::string, std::string>
2822 8 : JamiAccount::getContactDetails(const std::string& uri) const
2823 : {
2824 8 : std::lock_guard lock(configurationMutex_);
2825 16 : return accountManager_ ? accountManager_->getContactDetails(uri) : std::map<std::string, std::string> {};
2826 8 : }
2827 :
2828 : std::optional<Contact>
2829 32 : JamiAccount::getContactInfo(const std::string& uri) const
2830 : {
2831 32 : std::lock_guard lock(configurationMutex_);
2832 64 : return accountManager_ ? accountManager_->getContactInfo(uri) : std::nullopt;
2833 32 : }
2834 :
2835 : std::vector<std::map<std::string, std::string>>
2836 1 : JamiAccount::getContacts(bool includeRemoved) const
2837 : {
2838 1 : std::lock_guard lock(configurationMutex_);
2839 1 : if (not accountManager_)
2840 0 : return {};
2841 1 : const auto& contacts = accountManager_->getContacts(includeRemoved);
2842 1 : std::vector<std::map<std::string, std::string>> ret;
2843 1 : ret.reserve(contacts.size());
2844 2 : for (const auto& c : contacts) {
2845 1 : auto details = c.second.toMap();
2846 1 : if (not details.empty()) {
2847 1 : details["id"] = c.first.toString();
2848 1 : ret.emplace_back(std::move(details));
2849 : }
2850 1 : }
2851 1 : return ret;
2852 1 : }
2853 :
2854 : /* trust requests */
2855 :
2856 : std::vector<std::map<std::string, std::string>>
2857 700 : JamiAccount::getTrustRequests() const
2858 : {
2859 700 : std::lock_guard lock(configurationMutex_);
2860 1400 : return accountManager_ ? accountManager_->getTrustRequests() : std::vector<std::map<std::string, std::string>> {};
2861 700 : }
2862 :
2863 : bool
2864 28 : JamiAccount::acceptTrustRequest(const std::string& from, bool includeConversation)
2865 : {
2866 28 : dht::InfoHash h(from);
2867 28 : if (not h) {
2868 0 : JAMI_ERROR("addContact: invalid contact URI");
2869 0 : return false;
2870 : }
2871 28 : std::unique_lock lock(configurationMutex_);
2872 28 : if (accountManager_) {
2873 28 : if (!accountManager_->acceptTrustRequest(from, includeConversation)) {
2874 : // Note: unused for swarm
2875 : // Typically the case where the trust request doesn't exists, only incoming DHT messages
2876 0 : return accountManager_->addContact(h, true);
2877 : }
2878 28 : return true;
2879 : }
2880 0 : JAMI_WARNING("[Account {}] acceptTrustRequest: account not loaded", getAccountID());
2881 0 : return false;
2882 28 : }
2883 :
2884 : bool
2885 2 : JamiAccount::discardTrustRequest(const std::string& from)
2886 : {
2887 : // Remove 1:1 generated conv requests
2888 2 : auto requests = getTrustRequests();
2889 4 : for (const auto& req : requests) {
2890 2 : if (req.at(libjami::Account::TrustRequest::FROM) == from) {
2891 2 : convModule()->declineConversationRequest(req.at(libjami::Account::TrustRequest::CONVERSATIONID));
2892 : }
2893 : }
2894 :
2895 : // Remove trust request
2896 2 : std::lock_guard lock(configurationMutex_);
2897 2 : if (accountManager_)
2898 2 : return accountManager_->discardTrustRequest(from);
2899 0 : JAMI_WARNING("[Account {:s}] discardTrustRequest: account not loaded", getAccountID());
2900 0 : return false;
2901 2 : }
2902 :
2903 : void
2904 3 : JamiAccount::declineConversationRequest(const std::string& conversationId)
2905 : {
2906 3 : auto peerId = convModule()->peerFromConversationRequest(conversationId);
2907 3 : convModule()->declineConversationRequest(conversationId);
2908 3 : if (!peerId.empty()) {
2909 3 : std::lock_guard lock(configurationMutex_);
2910 3 : if (auto info = accountManager_->getInfo()) {
2911 : // Verify if we have a trust request with this peer + convId
2912 3 : auto req = info->contacts->getTrustRequest(dht::InfoHash(peerId));
2913 6 : if (req.find(libjami::Account::TrustRequest::CONVERSATIONID) != req.end()
2914 6 : && req.at(libjami::Account::TrustRequest::CONVERSATIONID) == conversationId) {
2915 1 : accountManager_->discardTrustRequest(peerId);
2916 4 : JAMI_DEBUG("[Account {:s}] Declined trust request with {:s}", getAccountID(), peerId);
2917 : }
2918 3 : }
2919 3 : }
2920 3 : }
2921 :
2922 : void
2923 57 : JamiAccount::sendTrustRequest(const std::string& to, const std::vector<uint8_t>& payload)
2924 : {
2925 57 : dht::InfoHash h(to);
2926 57 : if (not h) {
2927 0 : JAMI_ERROR("addContact: invalid contact URI");
2928 0 : return;
2929 : }
2930 : // Here we cache payload sent by the client
2931 57 : auto requestPath = cachePath_ / "requests";
2932 57 : dhtnet::fileutils::recursive_mkdir(requestPath, 0700);
2933 57 : auto cachedFile = requestPath / to;
2934 57 : std::ofstream req(cachedFile, std::ios::trunc | std::ios::binary);
2935 57 : if (!req.is_open()) {
2936 0 : JAMI_ERROR("Unable to write data to {}", cachedFile);
2937 0 : return;
2938 : }
2939 :
2940 57 : if (not payload.empty()) {
2941 3 : req.write(reinterpret_cast<const char*>(payload.data()), payload.size());
2942 : }
2943 :
2944 57 : if (payload.size() >= 64000) {
2945 1 : JAMI_WARN() << "Trust request is too big. Remove payload";
2946 : }
2947 :
2948 57 : auto conversation = convModule()->getOneToOneConversation(to);
2949 57 : if (conversation.empty())
2950 0 : conversation = convModule()->startConversation(ConversationMode::ONE_TO_ONE, h);
2951 57 : if (not conversation.empty()) {
2952 57 : std::lock_guard lock(configurationMutex_);
2953 57 : if (accountManager_)
2954 114 : accountManager_->sendTrustRequest(to,
2955 : conversation,
2956 114 : payload.size() >= 64000 ? std::vector<uint8_t> {} : payload);
2957 : else
2958 0 : JAMI_WARNING("[Account {}] sendTrustRequest: account not loaded", getAccountID());
2959 57 : } else
2960 0 : JAMI_WARNING("[Account {}] sendTrustRequest: account not loaded", getAccountID());
2961 57 : }
2962 :
2963 : void
2964 296 : JamiAccount::forEachDevice(const dht::InfoHash& to,
2965 : std::function<void(const std::shared_ptr<dht::crypto::PublicKey>&)>&& op,
2966 : std::function<void(bool)>&& end)
2967 : {
2968 296 : accountManager_->forEachDevice(to, std::move(op), std::move(end));
2969 296 : }
2970 :
2971 : uint64_t
2972 13470 : JamiAccount::sendTextMessage(const std::string& to,
2973 : const std::string& deviceId,
2974 : const std::map<std::string, std::string>& payloads,
2975 : uint64_t refreshToken,
2976 : bool onlyConnected)
2977 : {
2978 13470 : Uri uri(to);
2979 13472 : if (uri.scheme() == Uri::Scheme::SWARM) {
2980 0 : sendInstantMessage(uri.authority(), payloads);
2981 0 : return 0;
2982 : }
2983 :
2984 13471 : std::string toUri;
2985 : try {
2986 13471 : toUri = parseJamiUri(to);
2987 0 : } catch (...) {
2988 0 : JAMI_ERROR("Failed to send a text message due to an invalid URI {}", to);
2989 0 : return 0;
2990 0 : }
2991 13472 : if (payloads.size() != 1) {
2992 0 : JAMI_ERROR("Multi-part im is not supported yet by JamiAccount");
2993 0 : return 0;
2994 : }
2995 13470 : return SIPAccountBase::sendTextMessage(toUri, deviceId, payloads, refreshToken, onlyConnected);
2996 13472 : }
2997 :
2998 : void
2999 14417 : JamiAccount::sendMessage(const std::string& to,
3000 : const std::string& deviceId,
3001 : const std::map<std::string, std::string>& payloads,
3002 : uint64_t token,
3003 : bool retryOnTimeout,
3004 : bool onlyConnected)
3005 : {
3006 14417 : std::string toUri;
3007 : try {
3008 14417 : toUri = parseJamiUri(to);
3009 0 : } catch (...) {
3010 0 : JAMI_ERROR("[Account {}] Failed to send a text message due to an invalid URI {}", getAccountID(), to);
3011 0 : if (!onlyConnected)
3012 0 : messageEngine_.onMessageSent(to, token, false, deviceId);
3013 0 : return;
3014 0 : }
3015 14417 : if (payloads.size() != 1) {
3016 0 : JAMI_ERROR("Multi-part im is not supported");
3017 0 : if (!onlyConnected)
3018 0 : messageEngine_.onMessageSent(toUri, token, false, deviceId);
3019 0 : return;
3020 : }
3021 :
3022 : // Use the Message channel if available
3023 14417 : std::shared_lock clk(connManagerMtx_);
3024 14417 : auto* handler = static_cast<MessageChannelHandler*>(channelHandlers_[Uri::Scheme::MESSAGE].get());
3025 14417 : if (!handler) {
3026 23 : clk.unlock();
3027 23 : if (!onlyConnected)
3028 23 : messageEngine_.onMessageSent(to, token, false, deviceId);
3029 23 : return;
3030 : }
3031 :
3032 : /**
3033 : * Track sending state for a single message to one or more devices.
3034 : */
3035 : class SendMessageContext
3036 : {
3037 : public:
3038 : using OnComplete = std::function<void(bool, bool)>;
3039 14394 : SendMessageContext(OnComplete onComplete)
3040 14394 : : onComplete(std::move(onComplete))
3041 14394 : {}
3042 : /** Track new pending message for device */
3043 12761 : bool add(const DeviceId& device)
3044 : {
3045 12761 : std::lock_guard lk(mtx);
3046 25522 : return devices.insert(device).second;
3047 12761 : }
3048 : /** Call after all messages are sent */
3049 14394 : void start()
3050 : {
3051 14394 : std::unique_lock lk(mtx);
3052 14394 : started = true;
3053 14394 : checkComplete(lk);
3054 14394 : }
3055 : /** Complete pending message for device */
3056 12546 : bool complete(const DeviceId& device, bool success)
3057 : {
3058 12546 : std::unique_lock lk(mtx);
3059 12546 : if (devices.erase(device) == 0)
3060 0 : return false;
3061 12544 : ++completeCount;
3062 12544 : if (success)
3063 12542 : ++successCount;
3064 12544 : checkComplete(lk);
3065 12549 : return true;
3066 12549 : }
3067 : bool empty() const
3068 : {
3069 : std::lock_guard lk(mtx);
3070 : return devices.empty();
3071 : }
3072 2729 : bool pending(const DeviceId& device) const
3073 : {
3074 2729 : std::lock_guard lk(mtx);
3075 5458 : return devices.find(device) != devices.end();
3076 2729 : }
3077 :
3078 : private:
3079 : mutable std::mutex mtx;
3080 : OnComplete onComplete;
3081 : std::set<DeviceId> devices;
3082 : unsigned completeCount = 0;
3083 : unsigned successCount = 0;
3084 : bool started {false};
3085 :
3086 26930 : void checkComplete(std::unique_lock<std::mutex>& lk)
3087 : {
3088 26930 : if (started && (devices.empty() || successCount)) {
3089 14388 : if (onComplete) {
3090 14388 : auto cb = std::move(onComplete);
3091 14388 : auto success = successCount != 0;
3092 14388 : auto complete = completeCount != 0;
3093 14388 : onComplete = {};
3094 14387 : lk.unlock();
3095 14389 : cb(success, complete);
3096 14393 : }
3097 : }
3098 26929 : }
3099 : };
3100 : auto devices = std::make_shared<SendMessageContext>(
3101 41318 : [w = weak(), to, token, deviceId, onlyConnected, retryOnTimeout](bool success, bool sent) {
3102 14386 : if (auto acc = w.lock())
3103 14390 : acc->onMessageSent(to, token, deviceId, success, onlyConnected, sent && retryOnTimeout);
3104 28788 : });
3105 :
3106 : struct TextMessageCtx
3107 : {
3108 : std::weak_ptr<JamiAccount> acc;
3109 : std::string peerId;
3110 : DeviceId deviceId;
3111 : std::shared_ptr<SendMessageContext> devices;
3112 : std::shared_ptr<dhtnet::ChannelSocket> sipChannel;
3113 : };
3114 :
3115 : auto completed =
3116 12547 : [w = weak(), to, devices](const DeviceId& device, std::shared_ptr<dhtnet::ChannelSocket> conn, bool success) {
3117 12547 : if (!success)
3118 2 : if (auto acc = w.lock()) {
3119 2 : std::shared_lock clk(acc->connManagerMtx_);
3120 2 : if (auto* handler = static_cast<MessageChannelHandler*>(
3121 2 : acc->channelHandlers_[Uri::Scheme::MESSAGE].get())) {
3122 2 : handler->closeChannel(to, device, conn);
3123 : }
3124 4 : }
3125 12547 : devices->complete(device, success);
3126 26943 : };
3127 :
3128 14394 : const auto& payload = *payloads.begin();
3129 14394 : auto msg = std::make_shared<MessageChannelHandler::Message>();
3130 14394 : msg->id = token;
3131 14394 : msg->t = payload.first;
3132 14394 : msg->c = payload.second;
3133 14394 : auto device = deviceId.empty() ? DeviceId() : DeviceId(deviceId);
3134 14394 : if (deviceId.empty()) {
3135 3322 : auto conns = handler->getChannels(toUri);
3136 3322 : clk.unlock();
3137 5070 : for (const auto& conn : conns) {
3138 1748 : auto connDevice = conn->deviceId();
3139 1748 : if (!devices->add(connDevice))
3140 211 : continue;
3141 1537 : dht::ThreadPool::io().run([completed, connDevice, conn, msg] {
3142 1537 : completed(connDevice, conn, MessageChannelHandler::sendMessage(conn, *msg));
3143 1537 : });
3144 : }
3145 3322 : } else {
3146 11072 : if (auto conn = handler->getChannel(toUri, device)) {
3147 11013 : clk.unlock();
3148 11013 : devices->add(device);
3149 11013 : dht::ThreadPool::io().run([completed, device, conn, msg] {
3150 11013 : completed(device, conn, MessageChannelHandler::sendMessage(conn, *msg));
3151 11013 : });
3152 11013 : devices->start();
3153 11013 : return;
3154 11072 : }
3155 : }
3156 3381 : if (clk)
3157 59 : clk.unlock();
3158 :
3159 3381 : std::unique_lock lk(sipConnsMtx_);
3160 3401 : for (auto& [key, value] : sipConns_) {
3161 20 : if (key.first != to or value.empty())
3162 20 : continue;
3163 0 : if (!deviceId.empty() && key.second != device)
3164 0 : continue;
3165 0 : if (!devices->add(key.second))
3166 0 : continue;
3167 :
3168 0 : auto& conn = value.back();
3169 0 : auto& channel = conn.channel;
3170 :
3171 : // Set input token into callback
3172 0 : auto ctx = std::make_unique<TextMessageCtx>();
3173 0 : ctx->acc = weak();
3174 0 : ctx->peerId = to;
3175 0 : ctx->deviceId = key.second;
3176 0 : ctx->devices = devices;
3177 0 : ctx->sipChannel = channel;
3178 :
3179 : try {
3180 0 : auto res = sendSIPMessage(conn, to, ctx.release(), token, payloads, [](void* token, pjsip_event* event) {
3181 0 : if (auto c = std::shared_ptr<TextMessageCtx> {(TextMessageCtx*) token})
3182 0 : runOnMainThread([c = std::move(c), code = event->body.tsx_state.tsx->status_code] {
3183 0 : bool success = code == PJSIP_SC_OK;
3184 : // Note: This can be called from PJSIP's eventloop while
3185 : // sipConnsMtx_ is locked. So we should retrigger the shutdown.
3186 0 : if (!success) {
3187 0 : JAMI_WARNING("Timeout when send a message, close current connection");
3188 0 : if (auto acc = c->acc.lock())
3189 0 : acc->shutdownSIPConnection(c->sipChannel, c->peerId, c->deviceId);
3190 : }
3191 0 : c->devices->complete(c->deviceId, code == PJSIP_SC_OK);
3192 0 : });
3193 0 : });
3194 0 : if (!res) {
3195 0 : devices->complete(key.second, false);
3196 0 : continue;
3197 : }
3198 0 : } catch (const std::runtime_error& ex) {
3199 0 : JAMI_WARNING("{}", ex.what());
3200 : // Remove connection in incorrect state
3201 0 : shutdownSIPConnection(channel, to, key.second);
3202 0 : devices->complete(key.second, false);
3203 0 : continue;
3204 0 : }
3205 :
3206 0 : if (key.second == device) {
3207 0 : devices->start();
3208 0 : return;
3209 : }
3210 0 : }
3211 3381 : lk.unlock();
3212 3381 : devices->start();
3213 :
3214 3381 : if (onlyConnected)
3215 22 : return;
3216 : // We are unable to send the message directly, try connecting
3217 :
3218 : // Get conversation id, which will be used by the iOS notification extension
3219 : // to load the conversation.
3220 2778 : auto extractIdFromJson = [](const std::string& jsonData) -> std::string {
3221 2778 : Json::Value parsed;
3222 2778 : if (json::parse(jsonData, parsed)) {
3223 2778 : auto value = parsed.get("id", Json::nullValue);
3224 2778 : if (value && value.isString()) {
3225 2778 : return value.asString();
3226 : }
3227 2778 : } else {
3228 0 : JAMI_WARNING("Unable to parse jsonData to get conversation ID");
3229 : }
3230 0 : return "";
3231 2778 : };
3232 :
3233 : // get request type
3234 3359 : auto payload_type = msg->t;
3235 3359 : if (payload_type == MIME_TYPE_GIT) {
3236 2778 : std::string id = extractIdFromJson(msg->c);
3237 2778 : if (!id.empty()) {
3238 2778 : payload_type += "/" + id;
3239 : }
3240 2778 : }
3241 :
3242 3359 : if (deviceId.empty()) {
3243 3300 : auto toH = dht::InfoHash(toUri);
3244 : // Find listening devices for this account
3245 3300 : accountManager_->forEachDevice(toH,
3246 3331 : [this, to, devices, payload_type, currentDevice = DeviceId(currentDeviceId())](
3247 2729 : const std::shared_ptr<dht::crypto::PublicKey>& dev) {
3248 : // Test if already sent
3249 3331 : auto deviceId = dev->getLongId();
3250 3331 : if (deviceId == currentDevice || devices->pending(deviceId)) {
3251 602 : return;
3252 : }
3253 :
3254 : // Else, ask for a channel to send the message
3255 2729 : dht::ThreadPool::io().run([this, to, deviceId, payload_type]() {
3256 2729 : requestMessageConnection(to, deviceId, payload_type);
3257 2729 : });
3258 : });
3259 : } else {
3260 59 : requestMessageConnection(to, device, payload_type);
3261 : }
3262 58602 : }
3263 :
3264 : void
3265 14390 : JamiAccount::onMessageSent(
3266 : const std::string& to, uint64_t id, const std::string& deviceId, bool success, bool onlyConnected, bool retry)
3267 : {
3268 14390 : if (!onlyConnected)
3269 14363 : messageEngine_.onMessageSent(to, id, success, deviceId);
3270 :
3271 14393 : if (!success) {
3272 1847 : if (retry)
3273 2 : messageEngine_.onPeerOnline(to, deviceId);
3274 : }
3275 14393 : }
3276 :
3277 : dhtnet::IceTransportOptions
3278 118 : JamiAccount::getIceOptions() const
3279 : {
3280 118 : return connectionManager_->getIceOptions();
3281 : }
3282 :
3283 : void
3284 11 : JamiAccount::getIceOptions(std::function<void(dhtnet::IceTransportOptions&&)> cb) const
3285 : {
3286 11 : return connectionManager_->getIceOptions(std::move(cb));
3287 : }
3288 :
3289 : dhtnet::IpAddr
3290 100 : JamiAccount::getPublishedIpAddress(uint16_t family) const
3291 : {
3292 100 : return connectionManager_->getPublishedIpAddress(family);
3293 : }
3294 :
3295 : bool
3296 0 : JamiAccount::setPushNotificationToken(const std::string& token)
3297 : {
3298 0 : if (SIPAccountBase::setPushNotificationToken(token)) {
3299 0 : JAMI_WARNING("[Account {:s}] setPushNotificationToken: {:s}", getAccountID(), token);
3300 0 : if (dht_)
3301 0 : dht_->setPushNotificationToken(token);
3302 0 : return true;
3303 : }
3304 0 : return false;
3305 : }
3306 :
3307 : bool
3308 0 : JamiAccount::setPushNotificationTopic(const std::string& topic)
3309 : {
3310 0 : if (SIPAccountBase::setPushNotificationTopic(topic)) {
3311 0 : if (dht_)
3312 0 : dht_->setPushNotificationTopic(topic);
3313 0 : return true;
3314 : }
3315 0 : return false;
3316 : }
3317 :
3318 : bool
3319 0 : JamiAccount::setPushNotificationConfig(const std::map<std::string, std::string>& data)
3320 : {
3321 0 : if (SIPAccountBase::setPushNotificationConfig(data)) {
3322 0 : if (dht_) {
3323 0 : dht_->setPushNotificationPlatform(config_->platform);
3324 0 : dht_->setPushNotificationTopic(config_->notificationTopic);
3325 0 : dht_->setPushNotificationToken(config_->deviceKey);
3326 : }
3327 0 : return true;
3328 : }
3329 0 : return false;
3330 : }
3331 :
3332 : /**
3333 : * To be called by clients with relevant data when a push notification is received.
3334 : */
3335 : void
3336 0 : JamiAccount::pushNotificationReceived(const std::string& from, const std::map<std::string, std::string>& data)
3337 : {
3338 0 : auto ret_future = dht_->pushNotificationReceived(data);
3339 0 : dht::ThreadPool::computation().run([id = getAccountID(), ret_future = ret_future.share()] {
3340 0 : JAMI_WARNING("[Account {:s}] pushNotificationReceived: {}", id, (uint8_t) ret_future.get());
3341 0 : });
3342 0 : }
3343 :
3344 : std::string
3345 1 : JamiAccount::getUserUri() const
3346 : {
3347 1 : if (not registeredName_.empty())
3348 0 : return JAMI_URI_PREFIX + registeredName_;
3349 1 : return JAMI_URI_PREFIX + config().username;
3350 : }
3351 :
3352 : std::vector<libjami::Message>
3353 0 : JamiAccount::getLastMessages(const uint64_t& base_timestamp)
3354 : {
3355 0 : return SIPAccountBase::getLastMessages(base_timestamp);
3356 : }
3357 :
3358 : void
3359 0 : JamiAccount::startAccountPublish()
3360 : {
3361 0 : AccountPeerInfo info_pub;
3362 0 : info_pub.accountId = dht::InfoHash(accountManager_->getInfo()->accountId);
3363 0 : info_pub.displayName = config().displayName;
3364 0 : peerDiscovery_->startPublish<AccountPeerInfo>(PEER_DISCOVERY_JAMI_SERVICE, info_pub);
3365 0 : }
3366 :
3367 : void
3368 0 : JamiAccount::startAccountDiscovery()
3369 : {
3370 0 : auto id = dht::InfoHash(accountManager_->getInfo()->accountId);
3371 0 : peerDiscovery_
3372 0 : ->startDiscovery<AccountPeerInfo>(PEER_DISCOVERY_JAMI_SERVICE, [this, id](AccountPeerInfo&& v, dht::SockAddr&&) {
3373 0 : std::lock_guard lc(discoveryMapMtx_);
3374 : // Make sure that account itself will not be recorded
3375 0 : if (v.accountId != id) {
3376 : // Create or find the old one
3377 0 : auto& dp = discoveredPeers_[v.accountId];
3378 0 : dp.displayName = v.displayName;
3379 0 : discoveredPeerMap_[v.accountId.toString()] = v.displayName;
3380 0 : if (dp.cleanupTask) {
3381 0 : dp.cleanupTask->cancel();
3382 : } else {
3383 : // Avoid repeat reception of same peer
3384 0 : JAMI_LOG("Account discovered: {}: {}", v.displayName, v.accountId.to_c_str());
3385 : // Send Added Peer and corrsponding accoundID
3386 0 : emitSignal<libjami::PresenceSignal::NearbyPeerNotification>(getAccountID(),
3387 0 : v.accountId.toString(),
3388 : 0,
3389 0 : v.displayName);
3390 : }
3391 0 : dp.cleanupTask = Manager::instance().scheduler().scheduleIn(
3392 0 : [w = weak(), p = v.accountId, a = v.displayName] {
3393 0 : if (auto this_ = w.lock()) {
3394 : {
3395 0 : std::lock_guard lc(this_->discoveryMapMtx_);
3396 0 : this_->discoveredPeers_.erase(p);
3397 0 : this_->discoveredPeerMap_.erase(p.toString());
3398 0 : }
3399 : // Send deleted peer
3400 0 : emitSignal<libjami::PresenceSignal::NearbyPeerNotification>(this_->getAccountID(),
3401 0 : p.toString(),
3402 : 1,
3403 0 : a);
3404 0 : }
3405 0 : JAMI_INFO("Account removed from discovery list: %s", a.c_str());
3406 0 : },
3407 0 : PEER_DISCOVERY_EXPIRATION);
3408 : }
3409 0 : });
3410 0 : }
3411 :
3412 : std::map<std::string, std::string>
3413 0 : JamiAccount::getNearbyPeers() const
3414 : {
3415 0 : return discoveredPeerMap_;
3416 : }
3417 :
3418 : void
3419 0 : JamiAccount::sendProfileToPeers()
3420 : {
3421 0 : if (!connectionManager_)
3422 0 : return;
3423 0 : std::set<std::string> peers;
3424 0 : const auto& accountUri = accountManager_->getInfo()->accountId;
3425 : // TODO: avoid using getConnectionList
3426 0 : for (const auto& connection : connectionManager_->getConnectionList()) {
3427 0 : const auto& device = connection.at("device");
3428 0 : const auto& peer = connection.at("peer");
3429 0 : if (!peers.emplace(peer).second)
3430 0 : continue;
3431 0 : if (peer == accountUri) {
3432 0 : sendProfile("", accountUri, device);
3433 0 : continue;
3434 : }
3435 0 : const auto& conversationId = convModule()->getOneToOneConversation(peer);
3436 0 : if (!conversationId.empty()) {
3437 0 : sendProfile(conversationId, peer, device);
3438 : }
3439 0 : }
3440 0 : }
3441 :
3442 : void
3443 0 : JamiAccount::updateProfile(const std::string& displayName,
3444 : const std::string& avatar,
3445 : const std::string& fileType,
3446 : int32_t flag)
3447 : {
3448 : // if the fileType is empty then only the display name will be upated
3449 :
3450 0 : const auto& accountUri = accountManager_->getInfo()->accountId;
3451 0 : const auto& path = profilePath();
3452 0 : const auto& profiles = idPath_ / "profiles";
3453 :
3454 : try {
3455 0 : if (!std::filesystem::exists(profiles)) {
3456 0 : std::filesystem::create_directories(profiles);
3457 : }
3458 0 : } catch (const std::exception& e) {
3459 0 : JAMI_ERROR("Failed to create profiles directory: {}", e.what());
3460 0 : return;
3461 0 : }
3462 :
3463 0 : const auto& vCardPath = profiles / fmt::format("{}.vcf", base64::encode(accountUri));
3464 :
3465 0 : auto profile = getProfileVcard();
3466 0 : if (profile.empty()) {
3467 0 : profile = vCard::utils::initVcard();
3468 : }
3469 :
3470 0 : profile[std::string(vCard::Property::FORMATTED_NAME)] = displayName;
3471 0 : editConfig([&](JamiAccountConfig& config) { config.displayName = displayName; });
3472 0 : emitSignal<libjami::ConfigurationSignal::AccountDetailsChanged>(getAccountID(), getAccountDetails());
3473 :
3474 0 : if (!fileType.empty()) {
3475 0 : const std::string& key = "PHOTO;ENCODING=BASE64;TYPE=" + fileType;
3476 0 : if (flag == 0) {
3477 0 : vCard::utils::removeByKey(profile, vCard::Property::PHOTO);
3478 0 : const auto& avatarPath = std::filesystem::path(avatar);
3479 0 : if (std::filesystem::exists(avatarPath)) {
3480 : try {
3481 0 : profile[key] = base64::encode(fileutils::loadFile(avatarPath));
3482 0 : } catch (const std::exception& e) {
3483 0 : JAMI_ERROR("Failed to load avatar: {}", e.what());
3484 0 : }
3485 : }
3486 0 : } else if (flag == 1) {
3487 0 : vCard::utils::removeByKey(profile, vCard::Property::PHOTO);
3488 0 : profile[key] = avatar;
3489 : }
3490 0 : }
3491 0 : if (flag == 2) {
3492 0 : vCard::utils::removeByKey(profile, vCard::Property::PHOTO);
3493 : }
3494 : try {
3495 0 : vCard::utils::save(profile, vCardPath, path);
3496 0 : emitSignal<libjami::ConfigurationSignal::ProfileReceived>(getAccountID(), accountUri, path.string());
3497 :
3498 : // Delete all profile sent markers:
3499 0 : std::error_code ec;
3500 0 : std::filesystem::remove_all(cachePath_ / "vcard", ec);
3501 0 : sendProfileToPeers();
3502 0 : } catch (const std::exception& e) {
3503 0 : JAMI_ERROR("Error writing profile: {}", e.what());
3504 0 : }
3505 0 : }
3506 :
3507 : void
3508 792 : JamiAccount::setActiveCodecs(const std::vector<unsigned>& list)
3509 : {
3510 792 : Account::setActiveCodecs(list);
3511 792 : if (!hasActiveCodec(MEDIA_AUDIO))
3512 772 : setCodecActive(AV_CODEC_ID_OPUS);
3513 792 : if (!hasActiveCodec(MEDIA_VIDEO)) {
3514 772 : setCodecActive(AV_CODEC_ID_HEVC);
3515 772 : setCodecActive(AV_CODEC_ID_H264);
3516 772 : setCodecActive(AV_CODEC_ID_VP8);
3517 : }
3518 792 : config_->activeCodecs = getActiveCodecs(MEDIA_ALL);
3519 792 : }
3520 :
3521 : void
3522 11 : JamiAccount::sendInstantMessage(const std::string& convId, const std::map<std::string, std::string>& msg)
3523 : {
3524 11 : auto members = convModule()->getConversationMembers(convId);
3525 11 : if (convId.empty() && members.empty()) {
3526 : // TODO remove, it's for old API for contacts
3527 0 : sendTextMessage(convId, "", msg);
3528 0 : return;
3529 : }
3530 33 : for (const auto& m : members) {
3531 22 : const auto& uri = m.at("uri");
3532 22 : auto token = std::uniform_int_distribution<uint64_t> {1, JAMI_ID_MAX_VAL}(rand);
3533 : // Announce to all members that a new message is sent
3534 22 : sendMessage(uri, "", msg, token, false, true);
3535 : }
3536 11 : }
3537 :
3538 : bool
3539 12545 : JamiAccount::handleMessage(const std::shared_ptr<dht::crypto::Certificate>& cert,
3540 : const std::string& from,
3541 : const std::pair<std::string, std::string>& m)
3542 : {
3543 12545 : if (not cert or not cert->issuer)
3544 0 : return true; // stop processing message
3545 :
3546 12544 : if (cert->issuer->getId().to_view() != from) {
3547 0 : JAMI_WARNING("[Account {}] [device {}] handleMessage: invalid author {}",
3548 : getAccountID(),
3549 : cert->issuer->getId().to_view(),
3550 : from);
3551 0 : return true;
3552 : }
3553 12546 : if (m.first == MIME_TYPE_GIT) {
3554 12130 : Json::Value json;
3555 12130 : if (!json::parse(m.second, json)) {
3556 0 : return true;
3557 : }
3558 :
3559 : // fetchNewCommits will do heavy stuff like fetching, avoid to block SIP socket
3560 24262 : dht::ThreadPool::io().run([w = weak(),
3561 : from,
3562 12130 : deviceId = json["deviceId"].asString(),
3563 12129 : id = json["id"].asString(),
3564 12129 : commit = json["commit"].asString()] {
3565 12126 : if (auto shared = w.lock()) {
3566 12122 : if (auto cm = shared->convModule())
3567 12115 : cm->fetchNewCommits(from, deviceId, id, commit);
3568 12130 : }
3569 12131 : });
3570 12131 : return true;
3571 12546 : } else if (m.first == MIME_TYPE_INVITE) {
3572 136 : convModule()->onNeedConversationRequest(from, m.second);
3573 136 : return true;
3574 279 : } else if (m.first == MIME_TYPE_INVITE_JSON) {
3575 261 : Json::Value json;
3576 261 : if (!json::parse(m.second, json)) {
3577 0 : return true;
3578 : }
3579 261 : convModule()->onConversationRequest(from, json);
3580 261 : return true;
3581 279 : } else if (m.first == MIME_TYPE_IM_COMPOSING) {
3582 : try {
3583 4 : static const std::regex COMPOSING_REGEX("<state>\\s*(\\w+)\\s*<\\/state>");
3584 4 : std::smatch matched_pattern;
3585 4 : std::regex_search(m.second, matched_pattern, COMPOSING_REGEX);
3586 4 : bool isComposing {false};
3587 4 : if (matched_pattern.ready() && !matched_pattern.empty() && matched_pattern[1].matched) {
3588 4 : isComposing = matched_pattern[1] == "active";
3589 : }
3590 4 : static const std::regex CONVID_REGEX("<conversation>\\s*(\\w+)\\s*<\\/conversation>");
3591 4 : std::regex_search(m.second, matched_pattern, CONVID_REGEX);
3592 4 : std::string conversationId = "";
3593 4 : if (matched_pattern.ready() && !matched_pattern.empty() && matched_pattern[1].matched) {
3594 4 : conversationId = matched_pattern[1];
3595 : }
3596 4 : if (!conversationId.empty()) {
3597 4 : if (auto cm = convModule(true)) {
3598 4 : if (auto typer = cm->getTypers(conversationId)) {
3599 4 : if (isComposing)
3600 3 : typer->addTyper(from);
3601 : else
3602 1 : typer->removeTyper(from);
3603 4 : }
3604 : }
3605 : }
3606 4 : return true;
3607 4 : } catch (const std::exception& e) {
3608 0 : JAMI_WARNING("Error parsing composing state: {}", e.what());
3609 0 : }
3610 14 : } else if (m.first == MIME_TYPE_IMDN) {
3611 : try {
3612 9 : static const std::regex IMDN_MSG_ID_REGEX("<message-id>\\s*(\\w+)\\s*<\\/message-id>");
3613 9 : std::smatch matched_pattern;
3614 :
3615 9 : std::regex_search(m.second, matched_pattern, IMDN_MSG_ID_REGEX);
3616 9 : std::string messageId;
3617 9 : if (matched_pattern.ready() && !matched_pattern.empty() && matched_pattern[1].matched) {
3618 9 : messageId = matched_pattern[1];
3619 : } else {
3620 0 : JAMI_WARNING("Message displayed: unable to parse message ID");
3621 0 : return true;
3622 : }
3623 :
3624 9 : static const std::regex STATUS_REGEX("<status>\\s*<(\\w+)\\/>\\s*<\\/status>");
3625 9 : std::regex_search(m.second, matched_pattern, STATUS_REGEX);
3626 9 : bool isDisplayed {false};
3627 9 : if (matched_pattern.ready() && !matched_pattern.empty() && matched_pattern[1].matched) {
3628 9 : isDisplayed = matched_pattern[1] == "displayed";
3629 : } else {
3630 0 : JAMI_WARNING("Message displayed: unable to parse status");
3631 0 : return true;
3632 : }
3633 :
3634 9 : static const std::regex CONVID_REGEX("<conversation>\\s*(\\w+)\\s*<\\/conversation>");
3635 9 : std::regex_search(m.second, matched_pattern, CONVID_REGEX);
3636 9 : std::string conversationId = "";
3637 9 : if (matched_pattern.ready() && !matched_pattern.empty() && matched_pattern[1].matched) {
3638 9 : conversationId = matched_pattern[1];
3639 : }
3640 :
3641 9 : if (!isReadReceiptEnabled())
3642 0 : return true;
3643 9 : if (isDisplayed) {
3644 9 : if (convModule()->onMessageDisplayed(from, conversationId, messageId)) {
3645 36 : JAMI_DEBUG("[message {}] Displayed by peer", messageId);
3646 18 : emitSignal<libjami::ConfigurationSignal::AccountMessageStatusChanged>(
3647 9 : accountID_,
3648 : conversationId,
3649 : from,
3650 : messageId,
3651 : static_cast<int>(libjami::Account::MessageStates::DISPLAYED));
3652 : }
3653 : }
3654 9 : return true;
3655 9 : } catch (const std::exception& e) {
3656 0 : JAMI_ERROR("Error parsing display notification: {}", e.what());
3657 0 : }
3658 5 : } else if (m.first == MIME_TYPE_PIDF) {
3659 5 : std::smatch matched_pattern;
3660 5 : static const std::regex BASIC_REGEX("<basic>([\\w\\s]+)<\\/basic>");
3661 5 : std::regex_search(m.second, matched_pattern, BASIC_REGEX);
3662 5 : std::string customStatus {};
3663 5 : if (matched_pattern.ready() && !matched_pattern.empty() && matched_pattern[1].matched) {
3664 5 : customStatus = matched_pattern[1];
3665 5 : emitSignal<libjami::PresenceSignal::NewBuddyNotification>(getAccountID(),
3666 : from,
3667 : static_cast<int>(PresenceState::CONNECTED),
3668 : customStatus);
3669 : } else {
3670 0 : JAMI_WARNING("Presence: unable to parse status");
3671 : }
3672 5 : return true;
3673 5 : }
3674 :
3675 0 : return false;
3676 : }
3677 :
3678 : void
3679 262 : JamiAccount::callConnectionClosed(const DeviceId& deviceId, bool eraseDummy)
3680 : {
3681 262 : std::function<void(const DeviceId&, bool)> cb;
3682 : {
3683 262 : std::lock_guard lk(onConnectionClosedMtx_);
3684 262 : auto it = onConnectionClosed_.find(deviceId);
3685 262 : if (it != onConnectionClosed_.end()) {
3686 83 : if (eraseDummy) {
3687 83 : cb = std::move(it->second);
3688 83 : onConnectionClosed_.erase(it);
3689 : } else {
3690 : // In this case a new subcall is created and the callback
3691 : // will be re-called once with eraseDummy = true
3692 0 : cb = it->second;
3693 : }
3694 : }
3695 262 : }
3696 262 : dht::ThreadPool::io().run([w = weak(), cb = std::move(cb), id = deviceId, erase = std::move(eraseDummy)] {
3697 262 : if (auto acc = w.lock()) {
3698 262 : if (cb)
3699 83 : cb(id, erase);
3700 262 : }
3701 262 : });
3702 262 : }
3703 :
3704 : void
3705 3176 : JamiAccount::requestMessageConnection(const std::string& peerId,
3706 : const DeviceId& deviceId,
3707 : const std::string& connectionType)
3708 : {
3709 3176 : std::shared_lock lk(connManagerMtx_);
3710 3176 : auto* handler = static_cast<MessageChannelHandler*>(channelHandlers_[Uri::Scheme::MESSAGE].get());
3711 3176 : if (!handler)
3712 0 : return;
3713 3176 : if (deviceId) {
3714 3176 : if (auto connected = handler->getChannel(peerId, deviceId)) {
3715 1805 : return;
3716 3176 : }
3717 : } else {
3718 0 : auto connected = handler->getChannels(peerId);
3719 0 : if (!connected.empty()) {
3720 0 : return;
3721 : }
3722 0 : }
3723 1371 : handler->connect(
3724 : deviceId,
3725 : "",
3726 766 : [w = weak(), peerId](std::shared_ptr<dhtnet::ChannelSocket> socket, const DeviceId& deviceId) {
3727 766 : if (socket)
3728 668 : dht::ThreadPool::io().run([w, peerId, deviceId] {
3729 668 : if (auto acc = w.lock()) {
3730 668 : acc->messageEngine_.onPeerOnline(peerId);
3731 668 : acc->messageEngine_.onPeerOnline(peerId, deviceId.toString(), true);
3732 668 : if (!acc->presenceNote_.empty()) {
3733 : // If a presence note is set, send it to this device.
3734 3 : auto token = std::uniform_int_distribution<uint64_t> {1, JAMI_ID_MAX_VAL}(acc->rand);
3735 12 : std::map<std::string, std::string> msg = {{MIME_TYPE_PIDF, getPIDF(acc->presenceNote_)}};
3736 3 : acc->sendMessage(peerId, deviceId.toString(), msg, token, false, true);
3737 3 : }
3738 668 : acc->convModule()->syncConversations(peerId, deviceId.toString());
3739 667 : }
3740 668 : });
3741 766 : },
3742 : connectionType);
3743 3176 : }
3744 :
3745 : void
3746 90 : JamiAccount::requestSIPConnection(const std::string& peerId,
3747 : const DeviceId& deviceId,
3748 : const std::string& connectionType,
3749 : bool forceNewConnection,
3750 : const std::shared_ptr<SIPCall>& pc)
3751 : {
3752 90 : if (peerId == getUsername()) {
3753 0 : if (!syncModule()->isConnected(deviceId))
3754 0 : channelHandlers_[Uri::Scheme::SYNC]->connect(deviceId,
3755 : "",
3756 0 : [](std::shared_ptr<dhtnet::ChannelSocket> socket,
3757 0 : const DeviceId& deviceId) {});
3758 : }
3759 :
3760 360 : JAMI_LOG("[Account {}] Request SIP connection to peer {} on device {}", getAccountID(), peerId, deviceId);
3761 :
3762 : // If a connection already exists or is in progress, no need to do this
3763 90 : std::lock_guard lk(sipConnsMtx_);
3764 90 : auto id = std::make_pair(peerId, deviceId);
3765 :
3766 90 : if (sipConns_.find(id) != sipConns_.end()) {
3767 0 : JAMI_LOG("[Account {}] A SIP connection with {} already exists", getAccountID(), deviceId);
3768 0 : return;
3769 : }
3770 : // If not present, create it
3771 90 : std::shared_lock lkCM(connManagerMtx_);
3772 90 : if (!connectionManager_)
3773 0 : return;
3774 : // Note, Even if we send 50 "sip" request, the connectionManager_ will only use one socket.
3775 : // however, this will still ask for multiple channels, so only ask
3776 : // if there is no pending request
3777 90 : if (!forceNewConnection && connectionManager_->isConnecting(deviceId, "sip")) {
3778 0 : JAMI_LOG("[Account {}] Already connecting to {}", getAccountID(), deviceId);
3779 0 : return;
3780 : }
3781 360 : JAMI_LOG("[Account {}] Ask {} for a new SIP channel", getAccountID(), deviceId);
3782 270 : connectionManager_->connectDevice(
3783 : deviceId,
3784 : "sip",
3785 180 : [w = weak(), id = std::move(id), pc = std::move(pc)](std::shared_ptr<dhtnet::ChannelSocket> socket,
3786 : const DeviceId&) {
3787 90 : if (socket)
3788 87 : return;
3789 3 : auto shared = w.lock();
3790 3 : if (!shared)
3791 0 : return;
3792 : // If this is triggered, this means that the
3793 : // connectDevice didn't get any response from the DHT.
3794 : // Stop searching pending call.
3795 3 : shared->callConnectionClosed(id.second, true);
3796 3 : if (pc)
3797 3 : pc->onFailure();
3798 3 : },
3799 : false,
3800 : forceNewConnection,
3801 : connectionType);
3802 90 : }
3803 :
3804 : bool
3805 2603 : JamiAccount::isConnectedWith(const DeviceId& deviceId) const
3806 : {
3807 2603 : std::shared_lock lkCM(connManagerMtx_);
3808 2603 : if (connectionManager_)
3809 2603 : return connectionManager_->isConnected(deviceId);
3810 0 : return false;
3811 2603 : }
3812 :
3813 : void
3814 3 : JamiAccount::sendPresenceNote(const std::string& note)
3815 : {
3816 3 : if (auto info = accountManager_->getInfo()) {
3817 3 : if (!info || !info->contacts)
3818 0 : return;
3819 3 : presenceNote_ = note;
3820 3 : auto contacts = info->contacts->getContacts();
3821 3 : std::vector<std::pair<std::string, DeviceId>> keys;
3822 : {
3823 3 : std::shared_lock lkCM(connManagerMtx_);
3824 3 : auto* handler = static_cast<MessageChannelHandler*>(channelHandlers_[Uri::Scheme::MESSAGE].get());
3825 3 : if (!handler)
3826 0 : return;
3827 5 : for (const auto& contact : contacts) {
3828 2 : auto peerId = contact.first.toString();
3829 2 : auto channels = handler->getChannels(peerId);
3830 4 : for (const auto& channel : channels) {
3831 2 : keys.emplace_back(peerId, channel->deviceId());
3832 : }
3833 2 : }
3834 3 : }
3835 3 : auto token = std::uniform_int_distribution<uint64_t> {1, JAMI_ID_MAX_VAL}(rand);
3836 12 : std::map<std::string, std::string> msg = {{MIME_TYPE_PIDF, getPIDF(presenceNote_)}};
3837 5 : for (auto& key : keys) {
3838 2 : sendMessage(key.first, key.second.toString(), msg, token, false, true);
3839 : }
3840 3 : }
3841 : }
3842 :
3843 : void
3844 759 : JamiAccount::sendProfile(const std::string& convId, const std::string& peerUri, const std::string& deviceId)
3845 : {
3846 759 : auto accProfilePath = profilePath();
3847 758 : if (not std::filesystem::is_regular_file(accProfilePath))
3848 753 : return;
3849 6 : auto currentSha3 = fileutils::sha3File(accProfilePath);
3850 : // VCard sync for peerUri
3851 6 : if (not needToSendProfile(peerUri, deviceId, currentSha3)) {
3852 0 : JAMI_DEBUG("[Account {}] [device {}] Peer {} already got an up-to-date vCard",
3853 : getAccountID(),
3854 : deviceId,
3855 : peerUri);
3856 0 : return;
3857 : }
3858 : // We need a new channel
3859 18 : transferFile(convId,
3860 12 : accProfilePath.string(),
3861 : deviceId,
3862 : "profile.vcf",
3863 : "",
3864 : 0,
3865 : 0,
3866 : currentSha3,
3867 : fileutils::lastWriteTimeInSeconds(accProfilePath),
3868 6 : [accId = getAccountID(), peerUri, deviceId]() {
3869 : // Mark the VCard as sent
3870 8 : auto sendDir = fileutils::get_cache_dir() / accId / "vcard" / peerUri;
3871 4 : auto path = sendDir / deviceId;
3872 4 : dhtnet::fileutils::recursive_mkdir(sendDir);
3873 4 : std::lock_guard lock(dhtnet::fileutils::getFileLock(path));
3874 4 : if (std::filesystem::is_regular_file(path))
3875 0 : return;
3876 4 : std::ofstream p(path);
3877 4 : });
3878 759 : }
3879 :
3880 : bool
3881 6 : JamiAccount::needToSendProfile(const std::string& peerUri, const std::string& deviceId, const std::string& sha3Sum)
3882 : {
3883 6 : std::string previousSha3 {};
3884 6 : auto vCardPath = cachePath_ / "vcard";
3885 6 : auto sha3Path = vCardPath / "sha3";
3886 6 : dhtnet::fileutils::check_dir(vCardPath, 0700);
3887 : try {
3888 9 : previousSha3 = fileutils::loadTextFile(sha3Path);
3889 3 : } catch (...) {
3890 3 : fileutils::saveFile(sha3Path, (const uint8_t*) sha3Sum.data(), sha3Sum.size(), 0600);
3891 3 : return true;
3892 3 : }
3893 3 : if (sha3Sum != previousSha3) {
3894 : // Incorrect sha3 stored. Update it
3895 0 : dhtnet::fileutils::removeAll(vCardPath, true);
3896 0 : dhtnet::fileutils::check_dir(vCardPath, 0700);
3897 0 : fileutils::saveFile(sha3Path, (const uint8_t*) sha3Sum.data(), sha3Sum.size(), 0600);
3898 0 : return true;
3899 : }
3900 3 : auto peerPath = vCardPath / peerUri;
3901 3 : dhtnet::fileutils::recursive_mkdir(peerPath);
3902 3 : return not std::filesystem::is_regular_file(peerPath / deviceId);
3903 6 : }
3904 :
3905 : bool
3906 0 : JamiAccount::sendSIPMessage(SipConnection& conn,
3907 : const std::string& to,
3908 : void* ctx,
3909 : uint64_t token,
3910 : const std::map<std::string, std::string>& data,
3911 : pjsip_endpt_send_callback cb)
3912 : {
3913 0 : auto transport = conn.transport;
3914 0 : auto channel = conn.channel;
3915 0 : if (!channel)
3916 0 : throw std::runtime_error("A SIP transport exists without Channel, this is a bug. Please report");
3917 0 : auto remote_address = channel->getRemoteAddress();
3918 0 : if (!remote_address)
3919 0 : return false;
3920 :
3921 : // Build SIP Message
3922 : // "deviceID@IP"
3923 0 : auto toURI = getToUri(fmt::format("{}@{}", to, remote_address.toString(true)));
3924 0 : std::string from = getFromUri();
3925 :
3926 : // Build SIP message
3927 0 : constexpr pjsip_method msg_method = {PJSIP_OTHER_METHOD, sip_utils::CONST_PJ_STR(sip_utils::SIP_METHODS::MESSAGE)};
3928 0 : pj_str_t pjFrom = sip_utils::CONST_PJ_STR(from);
3929 0 : pj_str_t pjTo = sip_utils::CONST_PJ_STR(toURI);
3930 :
3931 : // Create request.
3932 0 : pjsip_tx_data* tdata = nullptr;
3933 0 : pj_status_t status = pjsip_endpt_create_request(
3934 0 : link_.getEndpoint(), &msg_method, &pjTo, &pjFrom, &pjTo, nullptr, nullptr, -1, nullptr, &tdata);
3935 0 : if (status != PJ_SUCCESS) {
3936 0 : JAMI_ERROR("Unable to create request: {}", sip_utils::sip_strerror(status));
3937 0 : return false;
3938 : }
3939 :
3940 : // Add Date Header.
3941 : pj_str_t date_str;
3942 0 : constexpr auto key = sip_utils::CONST_PJ_STR("Date");
3943 : pjsip_hdr* hdr;
3944 0 : auto time = std::time(nullptr);
3945 0 : auto date = std::ctime(&time);
3946 : // the erase-remove idiom for a cstring, removes _all_ new lines with in date
3947 0 : *std::remove(date, date + strlen(date), '\n') = '\0';
3948 :
3949 : // Add Header
3950 0 : hdr = reinterpret_cast<pjsip_hdr*>(pjsip_date_hdr_create(tdata->pool, &key, pj_cstr(&date_str, date)));
3951 0 : pjsip_msg_add_hdr(tdata->msg, hdr);
3952 :
3953 : // https://tools.ietf.org/html/rfc5438#section-6.3
3954 0 : auto token_str = to_hex_string(token);
3955 0 : auto pjMessageId = sip_utils::CONST_PJ_STR(token_str);
3956 0 : hdr = reinterpret_cast<pjsip_hdr*>(pjsip_generic_string_hdr_create(tdata->pool, &STR_MESSAGE_ID, &pjMessageId));
3957 0 : pjsip_msg_add_hdr(tdata->msg, hdr);
3958 :
3959 : // Add user-agent header
3960 0 : sip_utils::addUserAgentHeader(getUserAgentName(), tdata);
3961 :
3962 : // Init tdata
3963 0 : const pjsip_tpselector tp_sel = SIPVoIPLink::getTransportSelector(transport->get());
3964 0 : status = pjsip_tx_data_set_transport(tdata, &tp_sel);
3965 0 : if (status != PJ_SUCCESS) {
3966 0 : JAMI_ERROR("Unable to create request: {}", sip_utils::sip_strerror(status));
3967 0 : return false;
3968 : }
3969 0 : im::fillPJSIPMessageBody(*tdata, data);
3970 :
3971 : // Because pjsip_endpt_send_request can take quite some time, move it in a io thread to avoid to block
3972 0 : dht::ThreadPool::io().run([w = weak(), tdata, ctx, cb = std::move(cb)] {
3973 0 : auto shared = w.lock();
3974 0 : if (!shared)
3975 0 : return;
3976 0 : auto status = pjsip_endpt_send_request(shared->link_.getEndpoint(), tdata, -1, ctx, cb);
3977 0 : if (status != PJ_SUCCESS)
3978 0 : JAMI_ERROR("Unable to send request: {}", sip_utils::sip_strerror(status));
3979 0 : });
3980 0 : return true;
3981 0 : }
3982 :
3983 : void
3984 83 : JamiAccount::clearProfileCache(const std::string& peerUri)
3985 : {
3986 83 : std::error_code ec;
3987 83 : std::filesystem::remove_all(cachePath_ / "vcard" / peerUri, ec);
3988 83 : }
3989 :
3990 : std::filesystem::path
3991 761 : JamiAccount::profilePath() const
3992 : {
3993 761 : return idPath_ / "profile.vcf";
3994 : }
3995 :
3996 : void
3997 176 : JamiAccount::cacheSIPConnection(std::shared_ptr<dhtnet::ChannelSocket>&& socket,
3998 : const std::string& peerId,
3999 : const DeviceId& deviceId)
4000 : {
4001 176 : std::unique_lock lk(sipConnsMtx_);
4002 : // Verify that the connection is not already cached
4003 176 : SipConnectionKey key(peerId, deviceId);
4004 176 : auto& connections = sipConns_[key];
4005 178 : auto conn = std::find_if(connections.begin(), connections.end(), [&](const auto& v) { return v.channel == socket; });
4006 176 : if (conn != connections.end()) {
4007 0 : JAMI_WARNING("[Account {}] Channel socket already cached with this peer", getAccountID());
4008 0 : return;
4009 : }
4010 :
4011 : // Convert to SIP transport
4012 176 : auto onShutdown = [w = weak(), peerId, key, socket]() {
4013 176 : dht::ThreadPool::io().run([w = std::move(w), peerId, key, socket] {
4014 176 : auto shared = w.lock();
4015 176 : if (!shared)
4016 0 : return;
4017 176 : shared->shutdownSIPConnection(socket, key.first, key.second);
4018 : // The connection can be closed during the SIP initialization, so
4019 : // if this happens, the request should be re-sent to ask for a new
4020 : // SIP channel to make the call pass through
4021 176 : shared->callConnectionClosed(key.second, false);
4022 176 : });
4023 352 : };
4024 352 : auto sip_tr = link_.sipTransportBroker->getChanneledTransport(shared(), socket, std::move(onShutdown));
4025 176 : if (!sip_tr) {
4026 0 : JAMI_ERROR("No channeled transport found");
4027 0 : return;
4028 : }
4029 : // Store the connection
4030 176 : connections.emplace_back(SipConnection {sip_tr, socket});
4031 701 : JAMI_WARNING("[Account {:s}] [device {}] New SIP channel opened", getAccountID(), deviceId);
4032 176 : lk.unlock();
4033 :
4034 : // Retry messages
4035 176 : messageEngine_.onPeerOnline(peerId);
4036 176 : messageEngine_.onPeerOnline(peerId, deviceId.toString(), true);
4037 :
4038 : // Connect pending calls
4039 176 : forEachPendingCall(deviceId, [&](const auto& pc) {
4040 87 : if (pc->getConnectionState() != Call::ConnectionState::TRYING
4041 87 : and pc->getConnectionState() != Call::ConnectionState::PROGRESSING)
4042 0 : return;
4043 87 : pc->setSipTransport(sip_tr, getContactHeader(sip_tr));
4044 87 : pc->setState(Call::ConnectionState::PROGRESSING);
4045 87 : if (auto remote_address = socket->getRemoteAddress()) {
4046 : try {
4047 87 : onConnectedOutgoingCall(pc, peerId, remote_address);
4048 0 : } catch (const VoipLinkException&) {
4049 : // In this case, the main scenario is that SIPStartCall failed because
4050 : // the ICE is dead and the TLS session didn't send any packet on that dead
4051 : // link (connectivity change, killed by the os, etc)
4052 : // Here, we don't need to do anything, the TLS will fail and will delete
4053 : // the cached transport
4054 : }
4055 : }
4056 : });
4057 176 : }
4058 :
4059 : void
4060 176 : JamiAccount::shutdownSIPConnection(const std::shared_ptr<dhtnet::ChannelSocket>& channel,
4061 : const std::string& peerId,
4062 : const DeviceId& deviceId)
4063 : {
4064 176 : std::unique_lock lk(sipConnsMtx_);
4065 176 : SipConnectionKey key(peerId, deviceId);
4066 176 : auto it = sipConns_.find(key);
4067 176 : if (it != sipConns_.end()) {
4068 90 : auto& conns = it->second;
4069 181 : conns.erase(std::remove_if(conns.begin(), conns.end(), [&](auto v) { return v.channel == channel; }),
4070 90 : conns.end());
4071 90 : if (conns.empty()) {
4072 89 : sipConns_.erase(it);
4073 : }
4074 : }
4075 176 : lk.unlock();
4076 : // Shutdown after removal to let the callbacks do stuff if needed
4077 176 : if (channel)
4078 176 : channel->shutdown();
4079 176 : }
4080 :
4081 : std::string_view
4082 29852 : JamiAccount::currentDeviceId() const
4083 : {
4084 29852 : if (!accountManager_ or not accountManager_->getInfo())
4085 0 : return {};
4086 29845 : return accountManager_->getInfo()->deviceId;
4087 : }
4088 :
4089 : std::shared_ptr<TransferManager>
4090 148 : JamiAccount::dataTransfer(const std::string& id)
4091 : {
4092 148 : if (id.empty())
4093 68 : return nonSwarmTransferManager_;
4094 80 : if (auto cm = convModule())
4095 80 : return cm->dataTransfer(id);
4096 0 : return {};
4097 : }
4098 :
4099 : void
4100 0 : JamiAccount::monitor()
4101 : {
4102 0 : JAMI_DEBUG("[Account {:s}] Monitor connections", getAccountID());
4103 0 : JAMI_DEBUG("[Account {:s}] Using proxy: {:s}", getAccountID(), proxyServerCached_);
4104 :
4105 0 : if (auto cm = convModule())
4106 0 : cm->monitor();
4107 0 : std::shared_lock lkCM(connManagerMtx_);
4108 0 : if (connectionManager_)
4109 0 : connectionManager_->monitor();
4110 0 : }
4111 :
4112 : std::vector<std::map<std::string, std::string>>
4113 0 : JamiAccount::getConnectionList(const std::string& conversationId)
4114 : {
4115 0 : std::shared_lock lkCM(connManagerMtx_);
4116 0 : if (connectionManager_ && conversationId.empty()) {
4117 0 : return connectionManager_->getConnectionList();
4118 0 : } else if (connectionManager_ && convModule_) {
4119 0 : std::vector<std::map<std::string, std::string>> connectionList;
4120 0 : if (auto conv = convModule_->getConversation(conversationId)) {
4121 0 : for (const auto& deviceId : conv->getDeviceIdList()) {
4122 0 : auto connections = connectionManager_->getConnectionList(deviceId);
4123 0 : connectionList.reserve(connectionList.size() + connections.size());
4124 0 : std::move(connections.begin(), connections.end(), std::back_inserter(connectionList));
4125 0 : }
4126 0 : }
4127 0 : return connectionList;
4128 0 : } else {
4129 0 : return {};
4130 : }
4131 0 : }
4132 :
4133 : std::vector<std::map<std::string, std::string>>
4134 0 : JamiAccount::getChannelList(const std::string& connectionId)
4135 : {
4136 0 : std::shared_lock lkCM(connManagerMtx_);
4137 0 : if (!connectionManager_)
4138 0 : return {};
4139 0 : return connectionManager_->getChannelList(connectionId);
4140 0 : }
4141 :
4142 : void
4143 13 : JamiAccount::sendFile(const std::string& conversationId,
4144 : const std::filesystem::path& path,
4145 : const std::string& name,
4146 : const std::string& replyTo)
4147 : {
4148 13 : if (!std::filesystem::is_regular_file(path)) {
4149 0 : JAMI_ERROR("Invalid filename '{}'", path);
4150 0 : return;
4151 : }
4152 : // NOTE: this sendMessage is in a computation thread because
4153 : // sha3sum can take quite some time to computer if the user decide
4154 : // to send a big file
4155 13 : dht::ThreadPool::computation().run([w = weak(), conversationId, path, name, replyTo]() {
4156 13 : if (auto shared = w.lock()) {
4157 13 : Json::Value value;
4158 13 : auto tid = jami::generateUID(shared->rand);
4159 13 : value["tid"] = std::to_string(tid);
4160 13 : value["displayName"] = name.empty() ? path.filename().string() : name;
4161 13 : value["totalSize"] = std::to_string(fileutils::size(path));
4162 13 : value["sha3sum"] = fileutils::sha3File(path);
4163 13 : value["type"] = "application/data-transfer+json";
4164 :
4165 : shared->convModule()
4166 52 : ->sendMessage(conversationId,
4167 13 : std::move(value),
4168 13 : replyTo,
4169 : true,
4170 26 : [accId = shared->getAccountID(), conversationId, tid, path](const std::string& commitId) {
4171 : // Create a symlink to answer to re-ask
4172 26 : auto filelinkPath = fileutils::get_data_dir() / accId / "conversation_data"
4173 65 : / conversationId / fmt::format("{}_{}", commitId, tid);
4174 13 : filelinkPath += path.extension();
4175 13 : if (path != filelinkPath && !std::filesystem::is_symlink(filelinkPath)) {
4176 13 : if (!fileutils::createFileLink(filelinkPath, path, true)) {
4177 0 : JAMI_WARNING("Unable to create symlink for file transfer {} - {}. Copy file",
4178 : filelinkPath,
4179 : path);
4180 0 : std::error_code ec;
4181 0 : auto success = std::filesystem::copy_file(path, filelinkPath, ec);
4182 0 : if (ec || !success) {
4183 0 : JAMI_ERROR("Unable to copy file for file transfer {} - {}",
4184 : filelinkPath,
4185 : path);
4186 : // Signal to notify clients that the operation failed.
4187 : // The fileId field sends the filePath.
4188 : // libjami::DataTransferEventCode::unsupported (2) is unused elsewhere.
4189 0 : emitSignal<libjami::DataTransferSignal::DataTransferEvent>(
4190 0 : accId,
4191 0 : conversationId,
4192 : commitId,
4193 0 : path.u8string(),
4194 : uint32_t(libjami::DataTransferEventCode::invalid));
4195 : } else {
4196 : // Signal to notify clients that the file is copied and can be
4197 : // safely deleted. The fileId field sends the filePath.
4198 : // libjami::DataTransferEventCode::created (1) is unused elsewhere.
4199 0 : emitSignal<libjami::DataTransferSignal::DataTransferEvent>(
4200 0 : accId,
4201 0 : conversationId,
4202 : commitId,
4203 0 : path.u8string(),
4204 : uint32_t(libjami::DataTransferEventCode::created));
4205 : }
4206 : } else {
4207 26 : emitSignal<libjami::DataTransferSignal::DataTransferEvent>(
4208 13 : accId,
4209 13 : conversationId,
4210 : commitId,
4211 26 : path.u8string(),
4212 : uint32_t(libjami::DataTransferEventCode::created));
4213 : }
4214 : }
4215 13 : });
4216 26 : }
4217 13 : });
4218 : }
4219 :
4220 : void
4221 5 : JamiAccount::transferFile(const std::string& conversationId,
4222 : const std::string& path,
4223 : const std::string& deviceId,
4224 : const std::string& fileId,
4225 : const std::string& interactionId,
4226 : size_t start,
4227 : size_t end,
4228 : const std::string& sha3Sum,
4229 : uint64_t lastWriteTime,
4230 : std::function<void()> onFinished)
4231 : {
4232 5 : std::string modified;
4233 6 : if (lastWriteTime != 0) {
4234 6 : modified = fmt::format("&modified={}", lastWriteTime);
4235 : }
4236 18 : auto fid = fileId == "profile.vcf" ? fmt::format("profile.vcf?sha3={}{}", sha3Sum, modified) : fileId;
4237 6 : auto channelName = conversationId.empty()
4238 : ? fmt::format("{}profile.vcf?sha3={}{}", DATA_TRANSFER_SCHEME, sha3Sum, modified)
4239 18 : : fmt::format("{}{}/{}/{}", DATA_TRANSFER_SCHEME, conversationId, currentDeviceId(), fid);
4240 6 : std::shared_lock lkCM(connManagerMtx_);
4241 6 : if (!connectionManager_)
4242 0 : return;
4243 30 : connectionManager_->connectDevice(
4244 12 : DeviceId(deviceId),
4245 : channelName,
4246 6 : [this,
4247 : conversationId,
4248 6 : path = std::move(path),
4249 : fileId,
4250 : interactionId,
4251 : start,
4252 : end,
4253 6 : onFinished = std::move(onFinished)](std::shared_ptr<dhtnet::ChannelSocket> socket, const DeviceId&) {
4254 6 : if (!socket)
4255 0 : return;
4256 30 : dht::ThreadPool::io().run([w = weak(),
4257 6 : path = std::move(path),
4258 6 : socket = std::move(socket),
4259 6 : conversationId = std::move(conversationId),
4260 6 : fileId,
4261 6 : interactionId,
4262 : start,
4263 : end,
4264 6 : onFinished = std::move(onFinished)] {
4265 6 : if (auto shared = w.lock())
4266 6 : if (auto dt = shared->dataTransfer(conversationId))
4267 12 : dt->transferFile(socket, fileId, interactionId, path, start, end, std::move(onFinished));
4268 6 : });
4269 : });
4270 6 : }
4271 :
4272 : void
4273 13 : JamiAccount::askForFileChannel(const std::string& conversationId,
4274 : const std::string& deviceId,
4275 : const std::string& interactionId,
4276 : const std::string& fileId,
4277 : size_t start,
4278 : size_t end)
4279 : {
4280 28 : auto tryDevice = [=](const auto& did) {
4281 28 : std::shared_lock lkCM(connManagerMtx_);
4282 28 : if (!connectionManager_)
4283 0 : return;
4284 :
4285 28 : auto channelName = fmt::format("{}{}/{}/{}", DATA_TRANSFER_SCHEME, conversationId, currentDeviceId(), fileId);
4286 28 : if (start != 0 || end != 0) {
4287 6 : channelName += fmt::format("?start={}&end={}", start, end);
4288 : }
4289 : // We can avoid to negotiate new sessions, as the file notif
4290 : // probably came from an online device or last connected device.
4291 56 : connectionManager_->connectDevice(
4292 : did,
4293 : channelName,
4294 28 : [w = weak(), conversationId, fileId, interactionId, start](std::shared_ptr<dhtnet::ChannelSocket> channel,
4295 : const DeviceId&) {
4296 28 : if (!channel)
4297 16 : return;
4298 12 : dht::ThreadPool::io().run([w, conversationId, channel, fileId, interactionId, start] {
4299 12 : auto shared = w.lock();
4300 12 : if (!shared)
4301 0 : return;
4302 12 : auto dt = shared->dataTransfer(conversationId);
4303 12 : if (!dt)
4304 0 : return;
4305 12 : if (interactionId.empty())
4306 0 : dt->onIncomingProfile(channel);
4307 : else
4308 12 : dt->onIncomingFileTransfer(fileId, channel, start);
4309 12 : });
4310 : },
4311 : false);
4312 41 : };
4313 :
4314 13 : if (!deviceId.empty()) {
4315 : // Only ask for device
4316 1 : tryDevice(DeviceId(deviceId));
4317 : } else {
4318 : // Only ask for connected devices. For others we will attempt
4319 : // with new peer online
4320 40 : for (const auto& m : convModule()->getConversationMembers(conversationId)) {
4321 28 : accountManager_->forEachDevice(dht::InfoHash(m.at("uri")),
4322 27 : [tryDevice](const std::shared_ptr<dht::crypto::PublicKey>& dev) {
4323 27 : tryDevice(dev->getLongId());
4324 27 : });
4325 12 : }
4326 : }
4327 13 : }
4328 :
4329 : void
4330 57 : JamiAccount::askForProfile(const std::string& conversationId, const std::string& deviceId, const std::string& memberUri)
4331 : {
4332 57 : std::shared_lock lkCM(connManagerMtx_);
4333 57 : if (!connectionManager_)
4334 0 : return;
4335 :
4336 0 : auto channelName = fmt::format("{}{}/profile/{}.vcf", DATA_TRANSFER_SCHEME, conversationId, memberUri);
4337 : // We can avoid to negotiate new sessions, as the file notif
4338 : // probably came from an online device or last connected device.
4339 171 : connectionManager_->connectDevice(
4340 114 : DeviceId(deviceId),
4341 : channelName,
4342 102 : [this, conversationId](std::shared_ptr<dhtnet::ChannelSocket> channel, const DeviceId&) {
4343 57 : if (!channel)
4344 12 : return;
4345 45 : dht::ThreadPool::io().run([w = weak(), conversationId, channel] {
4346 45 : if (auto shared = w.lock())
4347 45 : if (auto dt = shared->dataTransfer(conversationId))
4348 90 : dt->onIncomingProfile(channel);
4349 45 : });
4350 : },
4351 : false);
4352 57 : }
4353 :
4354 : void
4355 2164 : JamiAccount::onPeerConnected(const std::string& peerId, bool connected)
4356 : {
4357 2164 : std::unique_lock lock(buddyInfoMtx);
4358 2164 : auto& state = presenceState_[peerId];
4359 2164 : auto it = trackedBuddies_.find(dht::InfoHash(peerId));
4360 2164 : auto isOnline = it != trackedBuddies_.end() && it->second.devices_cnt > 0;
4361 3246 : auto newState = connected ? PresenceState::CONNECTED
4362 1082 : : (isOnline ? PresenceState::AVAILABLE : PresenceState::DISCONNECTED);
4363 2164 : if (state != newState) {
4364 2164 : state = newState;
4365 2164 : lock.unlock();
4366 2164 : emitSignal<libjami::PresenceSignal::NewBuddyNotification>(getAccountID(),
4367 : peerId,
4368 : static_cast<int>(newState),
4369 : "");
4370 : }
4371 2164 : }
4372 :
4373 : void
4374 763 : JamiAccount::initConnectionManager()
4375 : {
4376 763 : if (!nonSwarmTransferManager_)
4377 658 : nonSwarmTransferManager_ = std::make_shared<TransferManager>(accountID_,
4378 658 : config().username,
4379 : "",
4380 1974 : dht::crypto::getDerivedRandomEngine(rand));
4381 763 : if (!connectionManager_) {
4382 669 : auto connectionManagerConfig = std::make_shared<dhtnet::ConnectionManager::Config>();
4383 669 : connectionManagerConfig->ioContext = Manager::instance().ioContext();
4384 669 : connectionManagerConfig->dht = dht();
4385 669 : connectionManagerConfig->certStore = certStore_;
4386 669 : connectionManagerConfig->id = identity();
4387 669 : connectionManagerConfig->upnpCtrl = upnpCtrl_;
4388 669 : connectionManagerConfig->turnServer = config().turnServer;
4389 669 : connectionManagerConfig->upnpEnabled = config().upnpEnabled;
4390 669 : connectionManagerConfig->turnServerUserName = config().turnServerUserName;
4391 669 : connectionManagerConfig->turnServerPwd = config().turnServerPwd;
4392 669 : connectionManagerConfig->turnServerRealm = config().turnServerRealm;
4393 669 : connectionManagerConfig->turnEnabled = config().turnEnabled;
4394 669 : connectionManagerConfig->cachePath = cachePath_;
4395 669 : connectionManagerConfig->logger = Logger::dhtLogger();
4396 669 : connectionManagerConfig->factory = Manager::instance().getIceTransportFactory();
4397 669 : connectionManagerConfig->turnCache = turnCache_;
4398 669 : connectionManagerConfig->rng = std::make_unique<std::mt19937_64>(dht::crypto::getDerivedRandomEngine(rand));
4399 669 : connectionManager_ = std::make_unique<dhtnet::ConnectionManager>(connectionManagerConfig);
4400 1338 : channelHandlers_[Uri::Scheme::SWARM] = std::make_unique<SwarmChannelHandler>(shared(),
4401 1338 : *connectionManager_.get());
4402 1338 : channelHandlers_[Uri::Scheme::GIT] = std::make_unique<ConversationChannelHandler>(shared(),
4403 1338 : *connectionManager_.get());
4404 669 : channelHandlers_[Uri::Scheme::SYNC] = std::make_unique<SyncChannelHandler>(shared(), *connectionManager_.get());
4405 669 : channelHandlers_[Uri::Scheme::DATA_TRANSFER]
4406 1338 : = std::make_unique<TransferChannelHandler>(shared(), *connectionManager_.get());
4407 2007 : channelHandlers_[Uri::Scheme::MESSAGE] = std::make_unique<MessageChannelHandler>(
4408 669 : *connectionManager_.get(),
4409 12542 : [this](const auto& cert, std::string& type, const std::string& content) {
4410 25088 : onTextMessage("", cert->issuer->getId().toString(), cert, {{type, content}});
4411 12546 : },
4412 2164 : [w = weak()](const std::string& peer, bool connected) {
4413 2164 : asio::post(*Manager::instance().ioContext(), [w, peer, connected] {
4414 2164 : if (auto acc = w.lock())
4415 2164 : acc->onPeerConnected(peer, connected);
4416 2164 : });
4417 2833 : });
4418 669 : channelHandlers_[Uri::Scheme::AUTH] = std::make_unique<AuthChannelHandler>(shared(), *connectionManager_.get());
4419 :
4420 : #if TARGET_OS_IOS
4421 : connectionManager_->oniOSConnected([&](const std::string& connType, dht::InfoHash peer_h) {
4422 : if ((connType == "videoCall" || connType == "audioCall") && jami::Manager::instance().isIOSExtension) {
4423 : bool hasVideo = connType == "videoCall";
4424 : emitSignal<libjami::ConversationSignal::CallConnectionRequest>("", peer_h.toString(), hasVideo);
4425 : return true;
4426 : }
4427 : return false;
4428 : });
4429 : #endif
4430 669 : }
4431 763 : }
4432 :
4433 : void
4434 1004 : JamiAccount::updateUpnpController()
4435 : {
4436 1004 : Account::updateUpnpController();
4437 1004 : if (connectionManager_) {
4438 47 : auto config = connectionManager_->getConfig();
4439 47 : if (config)
4440 47 : config->upnpCtrl = upnpCtrl_;
4441 47 : }
4442 1004 : }
4443 :
4444 : } // namespace jami
|