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 : #pragma once
18 :
19 : #include "def.h"
20 : #ifdef HAVE_CONFIG_H
21 : #include "config.h"
22 : #endif
23 :
24 : #include "sip/sipaccountbase.h"
25 : #include "jami/datatransfer_interface.h"
26 : #include "jamidht/conversation.h"
27 : #include "data_transfer.h"
28 : #include "uri.h"
29 : #include "jamiaccount_config.h"
30 :
31 : #include "noncopyable.h"
32 : #include "scheduled_executor.h"
33 : #include "gitserver.h"
34 : #include "channel_handler.h"
35 : #include "conversation_module.h"
36 : #include "sync_module.h"
37 : #include "conversationrepository.h"
38 : #include "namedirectory.h"
39 :
40 : #include <dhtnet/diffie-hellman.h>
41 : #include <dhtnet/tls_session.h>
42 : #include <dhtnet/multiplexed_socket.h>
43 : #include <dhtnet/certstore.h>
44 : #include <dhtnet/connectionmanager.h>
45 : #include <dhtnet/upnp/mapping.h>
46 : #include <dhtnet/ip_utils.h>
47 : #include <dhtnet/fileutils.h>
48 :
49 : #include <opendht/dhtrunner.h>
50 : #include <opendht/default_types.h>
51 :
52 : #include <pjsip/sip_types.h>
53 : #include <json/json.h>
54 :
55 : #include <chrono>
56 : #include <functional>
57 : #include <future>
58 : #include <list>
59 : #include <map>
60 : #include <optional>
61 : #include <vector>
62 : #include <filesystem>
63 : #include <shared_mutex>
64 :
65 : namespace dev {
66 : template<unsigned N>
67 : class FixedHash;
68 : using h160 = FixedHash<20>;
69 : using Address = h160;
70 : } // namespace dev
71 :
72 : namespace jami {
73 :
74 : class IceTransport;
75 : struct Contact;
76 : struct AccountArchive;
77 : class DhtPeerConnector;
78 : class AccountManager;
79 : struct AccountInfo;
80 : class SipTransport;
81 : class ChanneledOutgoingTransfer;
82 : class SyncModule;
83 :
84 : using SipConnectionKey = std::pair<std::string /* uri */, DeviceId>;
85 :
86 : static constexpr const char MIME_TYPE_IM_COMPOSING[] {"application/im-iscomposing+xml"};
87 :
88 : /**
89 : * @brief Ring Account is build on top of SIPAccountBase and uses DHT to handle call connectivity.
90 : */
91 : class JamiAccount : public SIPAccountBase
92 : {
93 : public:
94 : constexpr static auto ACCOUNT_TYPE = ACCOUNT_TYPE_JAMI;
95 : constexpr static const std::pair<uint16_t, uint16_t> DHT_PORT_RANGE {4000, 8888};
96 : constexpr static int ICE_STREAMS_COUNT {1};
97 : constexpr static int ICE_COMP_COUNT_PER_STREAM {1};
98 :
99 3206 : std::string_view getAccountType() const override { return ACCOUNT_TYPE; }
100 :
101 5185 : std::shared_ptr<JamiAccount> shared() { return std::static_pointer_cast<JamiAccount>(shared_from_this()); }
102 : std::shared_ptr<JamiAccount const> shared() const
103 : {
104 : return std::static_pointer_cast<JamiAccount const>(shared_from_this());
105 : }
106 54666 : std::weak_ptr<JamiAccount> weak() { return std::static_pointer_cast<JamiAccount>(shared_from_this()); }
107 : std::weak_ptr<JamiAccount const> weak() const
108 : {
109 : return std::static_pointer_cast<JamiAccount const>(shared_from_this());
110 : }
111 :
112 20332 : const JamiAccountConfig& config() const { return *static_cast<const JamiAccountConfig*>(&Account::config()); }
113 :
114 792 : JamiAccountConfig::Credentials consumeConfigCredentials()
115 : {
116 792 : auto conf = static_cast<JamiAccountConfig*>(config_.get());
117 792 : return std::move(conf->credentials);
118 : }
119 :
120 : void loadConfig() override;
121 :
122 : /**
123 : * Constructor
124 : * @param accountID The account identifier
125 : */
126 : JamiAccount(const std::string& accountId);
127 :
128 : ~JamiAccount() noexcept;
129 :
130 : /**
131 : * Retrieve volatile details such as recent registration errors
132 : * @return std::map< std::string, std::string > The account volatile details
133 : */
134 : virtual std::map<std::string, std::string> getVolatileAccountDetails() const override;
135 :
136 772 : std::unique_ptr<AccountConfig> buildConfig() const override
137 : {
138 772 : return std::make_unique<JamiAccountConfig>(getAccountID(), idPath_);
139 : }
140 :
141 : /**
142 : * Adds an account id to the list of accounts to track on the DHT for
143 : * buddy presence.
144 : *
145 : * @param buddy_id The buddy id.
146 : */
147 : void trackBuddyPresence(const std::string& buddy_id, bool track);
148 :
149 : /**
150 : * Tells for each tracked account id if it has been seen online so far
151 : * in the last DeviceAnnouncement::TYPE.expiration minutes.
152 : *
153 : * @return map of buddy_uri to bool (online or not)
154 : */
155 : std::map<std::string, bool> getTrackedBuddyPresence() const;
156 :
157 : void setActiveCodecs(const std::vector<unsigned>& list) override;
158 :
159 : /**
160 : * Connect to the DHT.
161 : */
162 : void doRegister() override;
163 :
164 : /**
165 : * Disconnect from the DHT.
166 : */
167 : void doUnregister(bool forceShutdownConnections = false) override;
168 :
169 : /**
170 : * Set the registration state of the specified link
171 : * @param state The registration state of underlying VoIPLink
172 : */
173 : void setRegistrationState(RegistrationState state, int detail_code = 0, const std::string& detail_str = {}) override;
174 :
175 : /**
176 : * @return pj_str_t "From" uri based on account information.
177 : * From RFC3261: "The To header field first and foremost specifies the desired
178 : * logical" recipient of the request, or the address-of-record of the
179 : * user or resource that is the target of this request. [...] As such, it is
180 : * very important that the From URI not contain IP addresses or the FQDN
181 : * of the host on which the UA is running, since these are not logical
182 : * names."
183 : */
184 : std::string getFromUri() const override;
185 :
186 : /**
187 : * This method adds the correct scheme, hostname and append
188 : * the ;transport= parameter at the end of the uri, in accordance with RFC3261.
189 : * It is expected that "port" is present in the internal hostname_.
190 : *
191 : * @return pj_str_t "To" uri based on @param username
192 : * @param username A string formatted as : "username"
193 : */
194 : std::string getToUri(const std::string& username) const override;
195 :
196 : /**
197 : * In the current version, "srv" uri is obtained in the preformated
198 : * way: hostname:port. This method adds the correct scheme and append
199 : * the ;transport= parameter at the end of the uri, in accordance with RFC3261.
200 : *
201 : * @return pj_str_t "server" uri based on @param hostPort
202 : * @param hostPort A string formatted as : "hostname:port"
203 : */
204 : std::string getServerUri() const { return ""; };
205 :
206 : void setIsComposing(const std::string& conversationUri, bool isWriting) override;
207 :
208 : bool setMessageDisplayed(const std::string& conversationUri, const std::string& messageId, int status) override;
209 :
210 : /**
211 : * Get the contact header for
212 : * @return The contact header based on account information
213 : */
214 : std::string getContactHeader(const std::shared_ptr<SipTransport>& sipTransport);
215 :
216 : /* Returns true if the username and/or hostname match this account */
217 : MatchRank matches(std::string_view username, std::string_view hostname) const override;
218 :
219 : /**
220 : * Create outgoing SIPCall.
221 : * @note Accepts several urls:
222 : * + jami:uri for calling someone
223 : * + swarm:id for calling a group (will host or join if an active call is detected)
224 : * + rdv:id/uri/device/confId to join a specific conference hosted on (uri, device)
225 : * @param[in] toUrl The address to call
226 : * @param[in] mediaList list of medias
227 : * @return A shared pointer on the created call.
228 : */
229 : std::shared_ptr<Call> newOutgoingCall(std::string_view toUrl,
230 : const std::vector<libjami::MediaMap>& mediaList) override;
231 :
232 : /**
233 : * Create incoming SIPCall.
234 : * @param[in] from The origin of the call
235 : * @param mediaList A list of media
236 : * @param sipTr: SIP Transport
237 : * @return A shared pointer on the created call.
238 : */
239 : std::shared_ptr<SIPCall> newIncomingCall(const std::string& from,
240 : const std::vector<libjami::MediaMap>& mediaList,
241 : const std::shared_ptr<SipTransport>& sipTr = {}) override;
242 :
243 : void onTextMessage(const std::string& id,
244 : const std::string& from,
245 : const std::shared_ptr<dht::crypto::Certificate>& peerCert,
246 : const std::map<std::string, std::string>& payloads) override;
247 : void loadConversation(const std::string& convId);
248 :
249 0 : virtual bool isTlsEnabled() const override { return true; }
250 426 : bool isSrtpEnabled() const override { return true; }
251 :
252 0 : virtual bool getSrtpFallback() const override { return false; }
253 :
254 : bool setCertificateStatus(const std::string& cert_id, dhtnet::tls::TrustStore::PermissionStatus status);
255 : bool setCertificateStatus(const std::shared_ptr<crypto::Certificate>& cert,
256 : dhtnet::tls::TrustStore::PermissionStatus status,
257 : bool local = true);
258 : std::vector<std::string> getCertificatesByStatus(dhtnet::tls::TrustStore::PermissionStatus status);
259 :
260 : bool findCertificate(const std::string& id);
261 : bool findCertificate(const dht::InfoHash& h,
262 : std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb = {});
263 : bool findCertificate(const dht::PkId& h,
264 : std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb = {});
265 :
266 : /* contact requests */
267 : std::vector<std::map<std::string, std::string>> getTrustRequests() const;
268 : // Note: includeConversation used for compatibility test. Do not change
269 : bool acceptTrustRequest(const std::string& from, bool includeConversation = true);
270 : bool discardTrustRequest(const std::string& from);
271 : void declineConversationRequest(const std::string& conversationId);
272 :
273 : /**
274 : * Add contact to the account contact list.
275 : * Set confirmed if we know the contact also added us.
276 : */
277 : void addContact(const std::string& uri, bool confirmed = false);
278 : void removeContact(const std::string& uri, bool banned = true);
279 : std::vector<std::map<std::string, std::string>> getContacts(bool includeRemoved = false) const;
280 :
281 : ///
282 : /// Obtain details about one account contact in serializable form.
283 : ///
284 : std::map<std::string, std::string> getContactDetails(const std::string& uri) const;
285 : std::optional<Contact> getContactInfo(const std::string& uri) const;
286 :
287 : void sendTrustRequest(const std::string& to, const std::vector<uint8_t>& payload);
288 : void sendMessage(const std::string& to,
289 : const std::string& deviceId,
290 : const std::map<std::string, std::string>& payloads,
291 : uint64_t id,
292 : bool retryOnTimeout = true,
293 : bool onlyConnected = false) override;
294 :
295 : uint64_t sendTextMessage(const std::string& to,
296 : const std::string& deviceId,
297 : const std::map<std::string, std::string>& payloads,
298 : uint64_t refreshToken = 0,
299 : bool onlyConnected = false) override;
300 : void sendInstantMessage(const std::string& convId, const std::map<std::string, std::string>& msg);
301 :
302 : /**
303 : * Create and return ICE options.
304 : */
305 : dhtnet::IceTransportOptions getIceOptions() const override;
306 : void getIceOptions(std::function<void(dhtnet::IceTransportOptions&&)> cb) const;
307 : dhtnet::IpAddr getPublishedIpAddress(uint16_t family = PF_UNSPEC) const override;
308 :
309 : /* Devices - existing device */
310 : /**
311 : * Initiates the process of adding a new device to this account
312 : * @param uriProvided The URI provided by the new device to be added
313 : * @return A positive operation ID if successful, or a negative value indicating an AddDeviceError:
314 : * - INVALID_URI (-1): The provided URI is invalid
315 : * - ALREADY_LINKING (-2): A device linking operation is already in progress
316 : * - GENERIC (-3): A generic error occurred during the process
317 : */
318 : int32_t addDevice(const std::string& uriProvided);
319 : bool cancelAddDevice(uint32_t op_token);
320 : bool confirmAddDevice(uint32_t op_token);
321 : /* Devices - new device */
322 : bool provideAccountAuthentication(const std::string& credentialsFromUser, const std::string& scheme);
323 :
324 : /**
325 : * Export the archive to a file
326 : * @param destinationPath
327 : * @param (optional) password, if not provided, will update the contacts only if the archive
328 : * doesn't have a password
329 : * @return if the archive was exported
330 : */
331 : bool exportArchive(const std::string& destinationPath,
332 : std::string_view scheme = {},
333 : const std::string& password = {});
334 : bool revokeDevice(const std::string& device, std::string_view scheme = {}, const std::string& password = {});
335 : std::map<std::string, std::string> getKnownDevices() const;
336 :
337 : bool isPasswordValid(const std::string& password);
338 : std::vector<uint8_t> getPasswordKey(const std::string& password);
339 :
340 : bool changeArchivePassword(const std::string& password_old, const std::string& password_new);
341 :
342 : void connectivityChanged() override;
343 :
344 : // overloaded methods
345 : void flush() override;
346 :
347 : void lookupName(const std::string& name);
348 : void lookupAddress(const std::string& address);
349 : void registerName(const std::string& name, const std::string& scheme, const std::string& password);
350 : bool searchUser(const std::string& nameQuery);
351 :
352 : /// \return true if the given DHT message identifier has been treated
353 : /// \note if message has not been treated yet this method store this id and returns true at
354 : /// further calls
355 : bool isMessageTreated(dht::Value::Id id);
356 :
357 671 : std::shared_ptr<dht::DhtRunner> dht() { return dht_; }
358 :
359 2175 : const dht::crypto::Identity& identity() const { return id_; }
360 :
361 : void forEachDevice(const dht::InfoHash& to,
362 : std::function<void(const std::shared_ptr<dht::crypto::PublicKey>&)>&& op,
363 : std::function<void(bool)>&& end = {});
364 :
365 : bool setPushNotificationToken(const std::string& pushDeviceToken = "") override;
366 : bool setPushNotificationTopic(const std::string& topic) override;
367 : bool setPushNotificationConfig(const std::map<std::string, std::string>& data) override;
368 :
369 : /**
370 : * To be called by clients with relevant data when a push notification is received.
371 : */
372 : void pushNotificationReceived(const std::string& from, const std::map<std::string, std::string>& data);
373 :
374 : std::string getUserUri() const override;
375 :
376 : /**
377 : * Get last messages (should be used to retrieve messages when launching the client)
378 : * @param base_timestamp
379 : */
380 : std::vector<libjami::Message> getLastMessages(const uint64_t& base_timestamp) override;
381 :
382 : /**
383 : * Start Publish the Jami Account onto the Network
384 : */
385 : void startAccountPublish();
386 :
387 : /**
388 : * Start Discovery the Jami Account from the Network
389 : */
390 : void startAccountDiscovery();
391 :
392 : void saveConfig() const override;
393 :
394 779 : inline void editConfig(std::function<void(JamiAccountConfig& conf)>&& edit)
395 : {
396 1558 : Account::editConfig([&](AccountConfig& conf) { edit(*static_cast<JamiAccountConfig*>(&conf)); });
397 779 : }
398 :
399 : /**
400 : * Get current discovered peers account id and display name
401 : */
402 : std::map<std::string, std::string> getNearbyPeers() const override;
403 :
404 : void sendProfileToPeers();
405 :
406 : /**
407 : * Update the profile vcard and send it to peers
408 : * @param displayName Current or new display name
409 : * @param avatar Current or new avatar
410 : * @param flag 0 for path to avatar, 1 for base64 avatar
411 : */
412 : void updateProfile(const std::string& displayName,
413 : const std::string& avatar,
414 : const std::string& fileType,
415 : int32_t flag) override;
416 :
417 : #ifdef LIBJAMI_TEST
418 1 : dhtnet::ConnectionManager& connectionManager() { return *connectionManager_; }
419 :
420 : /**
421 : * Only used for tests, disable sha3sum verification for transfers.
422 : * @param newValue
423 : */
424 : void noSha3sumVerification(bool newValue);
425 :
426 2 : void publishPresence(bool newValue) { publishPresence_ = newValue; }
427 : #endif
428 :
429 : /**
430 : * This should be called before flushing the account.
431 : * ConnectionManager needs the account to exists
432 : */
433 : void shutdownConnections();
434 :
435 : std::string_view currentDeviceId() const;
436 :
437 : // Received a new commit notification
438 :
439 : bool handleMessage(const std::shared_ptr<dht::crypto::Certificate>& cert,
440 : const std::string& from,
441 : const std::pair<std::string, std::string>& message) override;
442 :
443 : void monitor();
444 : // conversationId optional
445 : std::vector<std::map<std::string, std::string>> getConnectionList(const std::string& conversationId = "");
446 : std::vector<std::map<std::string, std::string>> getChannelList(const std::string& connectionId);
447 :
448 : // File transfer
449 : void sendFile(const std::string& conversationId,
450 : const std::filesystem::path& path,
451 : const std::string& name,
452 : const std::string& replyTo);
453 :
454 : void transferFile(const std::string& conversationId,
455 : const std::string& path,
456 : const std::string& deviceId,
457 : const std::string& fileId,
458 : const std::string& interactionId,
459 : size_t start = 0,
460 : size_t end = 0,
461 : const std::string& sha3Sum = "",
462 : uint64_t lastWriteTime = 0,
463 : std::function<void()> onFinished = {});
464 :
465 : void askForFileChannel(const std::string& conversationId,
466 : const std::string& deviceId,
467 : const std::string& interactionId,
468 : const std::string& fileId,
469 : size_t start = 0,
470 : size_t end = 0);
471 :
472 : void askForProfile(const std::string& conversationId, const std::string& deviceId, const std::string& memberUri);
473 :
474 : /**
475 : * Retrieve linked transfer manager
476 : * @param id conversationId or empty for fallback
477 : * @return linked transfer manager
478 : */
479 : std::shared_ptr<TransferManager> dataTransfer(const std::string& id = "");
480 :
481 : /**
482 : * Used to get the instance of the ConversationModule class which is
483 : * responsible for managing conversations and messages between users.
484 : * @param noCreate whether or not to create a new instance
485 : * @return conversationModule instance
486 : */
487 : ConversationModule* convModule(bool noCreation = false);
488 : SyncModule* syncModule();
489 :
490 : /**
491 : * Check (via the cache) if we need to send our profile to a specific device
492 : * @param peerUri Uri that will receive the profile
493 : * @param deviceId Device that will receive the profile
494 : * @param sha3Sum SHA3 hash of the profile
495 : */
496 : // Note: when swarm will be merged, this can be moved in transferManager
497 : bool needToSendProfile(const std::string& peerUri, const std::string& deviceId, const std::string& sha3Sum);
498 : /**
499 : * Send Profile via cached SIP connection
500 : * @param convId Conversation's identifier (can be empty for self profile on sync)
501 : * @param peerUri Uri that will receive the profile
502 : * @param deviceId Device that will receive the profile
503 : */
504 : void sendProfile(const std::string& convId, const std::string& peerUri, const std::string& deviceId);
505 : /**
506 : * Send profile via cached SIP connection
507 : * @param peerUri Uri that will receive the profile
508 : * @param deviceId Device that will receive the profile
509 : */
510 : void sendProfile(const std::string& peerUri, const std::string& deviceId);
511 : /**
512 : * Clear sent profiles (because of a removed contact or new trust request)
513 : * @param peerUri Uri used to clear cache
514 : */
515 : void clearProfileCache(const std::string& peerUri);
516 :
517 : std::filesystem::path profilePath() const;
518 :
519 32337 : const std::shared_ptr<AccountManager>& accountManager() { return accountManager_; }
520 :
521 : bool sha3SumVerify() const;
522 :
523 : /**
524 : * Change certificate's validity period
525 : * @param pwd Password for the archive
526 : * @param id Certificate to update ({} for updating the whole chain)
527 : * @param validity New validity
528 : * @note forceReloadAccount may be necessary to retrigger the migration
529 : */
530 : bool setValidity(std::string_view scheme, const std::string& pwd, const dht::InfoHash& id, int64_t validity);
531 : /**
532 : * Try to reload the account to force the identity to be updated
533 : */
534 : void forceReloadAccount();
535 :
536 : void reloadContacts();
537 :
538 : /**
539 : * Make sure appdata/contacts.yml contains correct information
540 : * @param removedConv The current removed conversations
541 : */
542 : void unlinkConversations(const std::set<std::string>& removedConv);
543 :
544 : bool isValidAccountDevice(const dht::crypto::Certificate& cert) const;
545 :
546 : /**
547 : * Join incoming call to hosted conference
548 : * @param callId The call to join
549 : * @param destination conversation/uri/device/confId to join
550 : */
551 : void handleIncomingConversationCall(const std::string& callId, const std::string& destination);
552 :
553 : /**
554 : * The DRT component is composed on some special nodes, that are usually present but not
555 : * connected. This kind of node corresponds to devices with push notifications & proxy and are
556 : * stored in the mobile nodes
557 : */
558 : bool isMobile() const { return config().proxyEnabled and not config().deviceKey.empty(); }
559 :
560 : #ifdef LIBJAMI_TEST
561 1 : std::map<Uri::Scheme, std::unique_ptr<ChannelHandlerInterface>>& channelHandlers() { return channelHandlers_; };
562 : #endif
563 :
564 28333 : dhtnet::tls::CertificateStore& certStore() const { return *certStore_; }
565 : /**
566 : * Check if a Device is connected
567 : * @param deviceId
568 : * @return true if connected
569 : */
570 : bool isConnectedWith(const DeviceId& deviceId) const;
571 :
572 : /**
573 : * Send a presence note
574 : * @param note
575 : */
576 : void sendPresenceNote(const std::string& note);
577 :
578 : private:
579 : NON_COPYABLE(JamiAccount);
580 :
581 : using clock = std::chrono::system_clock;
582 : using time_point = clock::time_point;
583 :
584 : /**
585 : * Private structures
586 : */
587 : struct PendingCall;
588 : struct PendingMessage;
589 : struct BuddyInfo;
590 : struct DiscoveredPeer;
591 :
592 0 : inline std::string getProxyConfigKey() const
593 : {
594 0 : const auto& conf = config();
595 0 : return dht::InfoHash::get(conf.proxyServer + conf.proxyListUrl).toString();
596 : }
597 :
598 : /**
599 : * Compute archive encryption key and DHT storage location from password and PIN.
600 : */
601 : /* static std::pair<std::vector<uint8_t>, dht::InfoHash> computeKeys(const std::string&
602 : password, const std::string& pin, bool previous = false);
603 : */
604 :
605 : void trackPresence(const dht::InfoHash& h, BuddyInfo& buddy);
606 : void onPeerConnected(const std::string& peerId, bool connected);
607 :
608 : void doRegister_();
609 :
610 777 : const dht::ValueType USER_PROFILE_TYPE = {9, "User profile", std::chrono::hours(24 * 7)};
611 :
612 : void startOutgoingCall(const std::shared_ptr<SIPCall>& call, const std::string& toUri);
613 :
614 : void onConnectedOutgoingCall(const std::shared_ptr<SIPCall>& call, const std::string& to_id, dhtnet::IpAddr target);
615 :
616 : /**
617 : * Start a SIP Call
618 : * @param call The current call
619 : * @return true if all is correct
620 : */
621 : bool SIPStartCall(SIPCall& call, const dhtnet::IpAddr& target);
622 :
623 : /**
624 : * Update tracking info when buddy appears offline.
625 : */
626 : void onTrackedBuddyOffline(const dht::InfoHash&);
627 :
628 : /**
629 : * Update tracking info when buddy appears offline.
630 : */
631 : void onTrackedBuddyOnline(const dht::InfoHash&);
632 :
633 : /**
634 : * Maps require port via UPnP and other async ops
635 : */
636 : void registerAsyncOps();
637 : /**
638 : * Add port mapping callback function.
639 : */
640 : void onPortMappingAdded(uint16_t port_used, bool success);
641 : void forEachPendingCall(const DeviceId& deviceId, const std::function<void(const std::shared_ptr<SIPCall>&)>& cb);
642 :
643 : void loadAccount(const std::string& archive_password_scheme = {},
644 : const std::string& archive_password = {},
645 : const std::string& archive_path = {});
646 :
647 : std::vector<std::string> loadBootstrap() const;
648 :
649 : static std::pair<std::string, std::string> saveIdentity(const dht::crypto::Identity id,
650 : const std::filesystem::path& path,
651 : const std::string& name);
652 :
653 : void replyToIncomingIceMsg(const std::shared_ptr<SIPCall>&,
654 : const std::shared_ptr<IceTransport>&,
655 : const std::shared_ptr<IceTransport>&,
656 : const dht::IceCandidates&,
657 : const std::shared_ptr<dht::crypto::Certificate>& from_cert,
658 : const dht::InfoHash& from);
659 :
660 : void loadCachedUrl(const std::string& url,
661 : const std::filesystem::path& cachePath,
662 : const std::chrono::seconds& cacheDuration,
663 : std::function<void(const dht::http::Response& response)>);
664 :
665 : std::string getDhtProxyServer(const std::string& serverList);
666 : void loadCachedProxyServer(std::function<void(const std::string&)> cb);
667 :
668 : /**
669 : * The TLS settings, used only if tls is chosen as a sip transport.
670 : */
671 : void generateDhParams();
672 :
673 : void newOutgoingCallHelper(const std::shared_ptr<SIPCall>& call, const Uri& uri);
674 : std::shared_ptr<SIPCall> newSwarmOutgoingCallHelper(const Uri& uri, const std::vector<libjami::MediaMap>& mediaList);
675 : std::shared_ptr<SIPCall> createSubCall(const std::shared_ptr<SIPCall>& mainCall);
676 :
677 : std::filesystem::path cachePath_ {};
678 : std::filesystem::path dataPath_ {};
679 :
680 : mutable std::mutex registeredNameMutex_;
681 : std::string registeredName_;
682 :
683 691 : bool setRegisteredName(const std::string& name)
684 : {
685 691 : std::lock_guard<std::mutex> lock(registeredNameMutex_);
686 691 : if (registeredName_ != name) {
687 1 : registeredName_ = name;
688 1 : return true;
689 : }
690 690 : return false;
691 691 : }
692 4555 : std::string getRegisteredName() const
693 : {
694 4555 : std::lock_guard<std::mutex> lock(registeredNameMutex_);
695 9110 : return registeredName_;
696 4555 : }
697 :
698 : std::shared_ptr<dht::Logger> logger_;
699 : std::shared_ptr<dhtnet::tls::CertificateStore> certStore_;
700 :
701 : std::shared_ptr<dht::DhtRunner> dht_ {};
702 : std::shared_ptr<AccountManager> accountManager_;
703 : dht::crypto::Identity id_ {};
704 :
705 : mutable std::mutex messageMutex_ {};
706 : std::map<dht::Value::Id, PendingMessage> sentMessages_;
707 : dhtnet::fileutils::IdList treatedMessages_;
708 :
709 : /* tracked buddies presence */
710 : mutable std::mutex buddyInfoMtx;
711 : std::map<dht::InfoHash, BuddyInfo> trackedBuddies_;
712 :
713 : mutable std::mutex dhtValuesMtx_;
714 :
715 : std::atomic_int syncCnt_ {0};
716 :
717 : /**
718 : * DHT port actually used.
719 : * This holds the actual DHT port, which might different from the port
720 : * set in the configuration. This can be the case if UPnP is used.
721 : */
722 691 : in_port_t dhtPortUsed()
723 : {
724 691 : return (upnpCtrl_ and dhtUpnpMapping_.isValid()) ? dhtUpnpMapping_.getExternalPort() : config().dhtPort;
725 : }
726 :
727 : /* Current UPNP mapping */
728 : dhtnet::upnp::Mapping dhtUpnpMapping_ {dhtnet::upnp::PortType::UDP};
729 :
730 : /**
731 : * Proxy
732 : */
733 : std::string proxyServerCached_ {};
734 :
735 : /**
736 : * Optional: via_addr construct from received parameters
737 : */
738 : pjsip_host_port via_addr_ {};
739 :
740 : pjsip_transport* via_tp_ {nullptr};
741 :
742 : /** ConnectionManager is thread-safe.
743 : * The shared mutex protects the pointer while allowing
744 : * multiple threads to access the ConnectionManager concurrently */
745 : mutable std::shared_mutex connManagerMtx_ {};
746 : std::unique_ptr<dhtnet::ConnectionManager> connectionManager_;
747 :
748 : virtual void updateUpnpController() override;
749 :
750 : std::mutex discoveryMapMtx_;
751 : std::shared_ptr<dht::PeerDiscovery> peerDiscovery_;
752 : std::map<dht::InfoHash, DiscoveredPeer> discoveredPeers_;
753 : std::map<std::string, std::string> discoveredPeerMap_;
754 :
755 : std::set<std::shared_ptr<dht::http::Request>> requests_;
756 :
757 : mutable std::mutex sipConnsMtx_ {};
758 : struct SipConnection
759 : {
760 : std::shared_ptr<SipTransport> transport;
761 : // Needs to keep track of that channel to access underlying ICE
762 : // information, as the SipTransport use a generic transport
763 : std::shared_ptr<dhtnet::ChannelSocket> channel;
764 : };
765 : // NOTE: here we use a vector to avoid race conditions. In fact the contact
766 : // can ask for a SIP channel when we are creating a new SIP Channel with this
767 : // peer too.
768 : std::map<SipConnectionKey, std::vector<SipConnection>> sipConns_;
769 :
770 : std::mutex pendingCallsMutex_;
771 : std::map<DeviceId, std::vector<std::shared_ptr<SIPCall>>> pendingCalls_;
772 :
773 : std::mutex onConnectionClosedMtx_ {};
774 : std::map<DeviceId, std::function<void(const DeviceId&, bool)>> onConnectionClosed_ {};
775 : /**
776 : * onConnectionClosed contains callbacks that need to be called if a sub call is failing
777 : * @param deviceId The device we are calling
778 : * @param eraseDummy Erase the dummy call (a temporary subcall that must be stop when we will
779 : * not create new subcalls)
780 : */
781 : void callConnectionClosed(const DeviceId& deviceId, bool eraseDummy);
782 :
783 : /**
784 : * Ask a device to open a channeled SIP socket
785 : * @param peerId The contact who owns the device
786 : * @param deviceId The device to ask
787 : * @param forceNewConnection If we want a new SIP connection
788 : * @param pc A pending call to stop if the request fails
789 : * @note triggers cacheSIPConnection
790 : */
791 : void requestSIPConnection(const std::string& peerId,
792 : const DeviceId& deviceId,
793 : const std::string& connectionType,
794 : bool forceNewConnection = false,
795 : const std::shared_ptr<SIPCall>& pc = {});
796 : /**
797 : * Store a new SIP connection into sipConnections_
798 : * @param channel The new sip channel
799 : * @param peerId The contact who owns the device
800 : * @param deviceId Device linked to that transport
801 : */
802 : void cacheSIPConnection(std::shared_ptr<dhtnet::ChannelSocket>&& channel,
803 : const std::string& peerId,
804 : const DeviceId& deviceId);
805 : /**
806 : * Shutdown a SIP connection
807 : * @param channel The channel to close
808 : * @param peerId The contact who owns the device
809 : * @param deviceId Device linked to that transport
810 : */
811 : void shutdownSIPConnection(const std::shared_ptr<dhtnet::ChannelSocket>& channel,
812 : const std::string& peerId,
813 : const DeviceId& deviceId);
814 :
815 : void requestMessageConnection(const std::string& peerId,
816 : const DeviceId& deviceId,
817 : const std::string& connectionType);
818 :
819 : // File transfers
820 : std::mutex transfersMtx_ {};
821 : std::set<std::string> incomingFileTransfers_ {};
822 :
823 : /**
824 : * Helper used to send SIP messages on a channeled connection
825 : * @param conn The connection used
826 : * @param to Peer URI
827 : * @param ctx Context passed to the send request
828 : * @param token Token used
829 : * @param data Message to send
830 : * @param cb Callback to trigger when message is sent
831 : * @throw runtime_error if connection is invalid
832 : * @return if the request will be sent
833 : */
834 : bool sendSIPMessage(SipConnection& conn,
835 : const std::string& to,
836 : void* ctx,
837 : uint64_t token,
838 : const std::map<std::string, std::string>& data,
839 : pjsip_endpt_send_callback cb);
840 : void onMessageSent(
841 : const std::string& to, uint64_t id, const std::string& deviceId, bool success, bool onlyConnected, bool retry);
842 :
843 : std::mutex gitServersMtx_ {};
844 : std::map<dht::Value::Id, std::unique_ptr<GitServer>> gitServers_ {};
845 :
846 : //// File transfer (for profiles)
847 : std::shared_ptr<TransferManager> nonSwarmTransferManager_;
848 :
849 : std::atomic_bool deviceAnnounced_ {false};
850 : std::atomic_bool noSha3sumVerification_ {false};
851 :
852 : bool publishPresence_ {true};
853 :
854 : std::map<Uri::Scheme, std::unique_ptr<ChannelHandlerInterface>> channelHandlers_ {};
855 :
856 : std::unique_ptr<ConversationModule> convModule_;
857 : std::mutex moduleMtx_;
858 : std::unique_ptr<SyncModule> syncModule_;
859 :
860 : std::mutex rdvMtx_;
861 :
862 : int dhtBoundPort_ {0};
863 :
864 : void initConnectionManager();
865 :
866 : enum class PresenceState : int { DISCONNECTED = 0, AVAILABLE, CONNECTED };
867 : std::map<std::string, PresenceState> presenceState_;
868 : std::string presenceNote_;
869 : };
870 :
871 : static inline std::ostream&
872 : operator<<(std::ostream& os, const JamiAccount& acc)
873 : {
874 : os << "[Account " << acc.getAccountID() << "] ";
875 : return os;
876 : }
877 :
878 : } // namespace jami
|