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