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