LCOV - code coverage report
Current view: top level - foo/src/jamidht - jamiaccount.h (source / functions) Hit Total Coverage
Test: jami-coverage-filtered.info Lines: 34 38 89.5 %
Date: 2026-01-22 10:39:23 Functions: 19 21 90.5 %

          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 "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        3204 :     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       55678 :     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       20345 :     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             :     bool setCertificateStatus(const std::string& cert_id, dhtnet::tls::TrustStore::PermissionStatus status);
     253             :     bool setCertificateStatus(const std::shared_ptr<crypto::Certificate>& cert,
     254             :                               dhtnet::tls::TrustStore::PermissionStatus status,
     255             :                               bool local = true);
     256             :     std::vector<std::string> getCertificatesByStatus(dhtnet::tls::TrustStore::PermissionStatus status);
     257             : 
     258             :     bool findCertificate(const std::string& id);
     259             :     bool findCertificate(const dht::InfoHash& h,
     260             :                          std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb = {});
     261             :     bool findCertificate(const dht::PkId& h,
     262             :                          std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb = {});
     263             : 
     264             :     /* contact requests */
     265             :     std::vector<std::map<std::string, std::string>> getTrustRequests() const;
     266             :     // Note: includeConversation used for compatibility test. Do not change
     267             :     bool acceptTrustRequest(const std::string& from, bool includeConversation = true);
     268             :     bool discardTrustRequest(const std::string& from);
     269             :     void declineConversationRequest(const std::string& conversationId);
     270             : 
     271             :     /**
     272             :      * Add contact to the account contact list.
     273             :      * Set confirmed if we know the contact also added us.
     274             :      */
     275             :     void addContact(const std::string& uri, bool confirmed = false);
     276             :     void removeContact(const std::string& uri, bool banned = true);
     277             :     std::vector<std::map<std::string, std::string>> getContacts(bool includeRemoved = false) const;
     278             : 
     279             :     ///
     280             :     /// Obtain details about one account contact in serializable form.
     281             :     ///
     282             :     std::map<std::string, std::string> getContactDetails(const std::string& uri) const;
     283             :     std::optional<Contact> getContactInfo(const std::string& uri) const;
     284             : 
     285             :     void sendTrustRequest(const std::string& to, const std::vector<uint8_t>& payload);
     286             :     void sendMessage(const std::string& to,
     287             :                      const std::string& deviceId,
     288             :                      const std::map<std::string, std::string>& payloads,
     289             :                      uint64_t id,
     290             :                      bool retryOnTimeout = true,
     291             :                      bool onlyConnected = false) override;
     292             : 
     293             :     uint64_t sendTextMessage(const std::string& to,
     294             :                              const std::string& deviceId,
     295             :                              const std::map<std::string, std::string>& payloads,
     296             :                              uint64_t refreshToken = 0,
     297             :                              bool onlyConnected = false) override;
     298             :     void sendInstantMessage(const std::string& convId, const std::map<std::string, std::string>& msg);
     299             : 
     300             :     /**
     301             :      * Create and return ICE options.
     302             :      */
     303             :     dhtnet::IceTransportOptions getIceOptions() const override;
     304             :     void getIceOptions(std::function<void(dhtnet::IceTransportOptions&&)> cb) const;
     305             :     dhtnet::IpAddr getPublishedIpAddress(uint16_t family = PF_UNSPEC) const override;
     306             : 
     307             :     /* Devices - existing device */
     308             :     /**
     309             :      * Initiates the process of adding a new device to this account
     310             :      * @param uriProvided The URI provided by the new device to be added
     311             :      * @return A positive operation ID if successful, or a negative value indicating an AddDeviceError:
     312             :      *         - INVALID_URI (-1): The provided URI is invalid
     313             :      *         - ALREADY_LINKING (-2): A device linking operation is already in progress
     314             :      *         - GENERIC (-3): A generic error occurred during the process
     315             :      */
     316             :     int32_t addDevice(const std::string& uriProvided);
     317             :     bool cancelAddDevice(uint32_t op_token);
     318             :     bool confirmAddDevice(uint32_t op_token);
     319             :     /* Devices - new device */
     320             :     bool provideAccountAuthentication(const std::string& credentialsFromUser, const std::string& scheme);
     321             : 
     322             :     /**
     323             :      * Export the archive to a file
     324             :      * @param destinationPath
     325             :      * @param (optional) password, if not provided, will update the contacts only if the archive
     326             :      * doesn't have a password
     327             :      * @return if the archive was exported
     328             :      */
     329             :     bool exportArchive(const std::string& destinationPath,
     330             :                        std::string_view scheme = {},
     331             :                        const std::string& password = {});
     332             :     bool revokeDevice(const std::string& device, std::string_view scheme = {}, const std::string& password = {});
     333             :     std::map<std::string, std::string> getKnownDevices() const;
     334             : 
     335             :     bool isPasswordValid(const std::string& password);
     336             :     std::vector<uint8_t> getPasswordKey(const std::string& password);
     337             : 
     338             :     bool changeArchivePassword(const std::string& password_old, const std::string& password_new);
     339             : 
     340             :     void connectivityChanged() override;
     341             : 
     342             :     // overloaded methods
     343             :     void flush() override;
     344             : 
     345             :     void lookupName(const std::string& name);
     346             :     void lookupAddress(const std::string& address);
     347             :     void registerName(const std::string& name, const std::string& scheme, const std::string& password);
     348             :     bool searchUser(const std::string& nameQuery);
     349             : 
     350             :     /// \return true if the given DHT message identifier has been treated
     351             :     /// \note if message has not been treated yet this method store this id and returns true at
     352             :     /// further calls
     353             :     bool isMessageTreated(dht::Value::Id id);
     354             : 
     355         671 :     std::shared_ptr<dht::DhtRunner> dht() { return dht_; }
     356             : 
     357        2183 :     const dht::crypto::Identity& identity() const { return id_; }
     358             : 
     359             :     void forEachDevice(const dht::InfoHash& to,
     360             :                        std::function<void(const std::shared_ptr<dht::crypto::PublicKey>&)>&& op,
     361             :                        std::function<void(bool)>&& end = {});
     362             : 
     363             :     bool setPushNotificationToken(const std::string& pushDeviceToken = "") override;
     364             :     bool setPushNotificationTopic(const std::string& topic) override;
     365             :     bool setPushNotificationConfig(const std::map<std::string, std::string>& data) override;
     366             : 
     367             :     /**
     368             :      * To be called by clients with relevant data when a push notification is received.
     369             :      */
     370             :     void pushNotificationReceived(const std::string& from, const std::map<std::string, std::string>& data);
     371             : 
     372             :     std::string getUserUri() const override;
     373             : 
     374             :     /**
     375             :      * Get last messages (should be used to retrieve messages when launching the client)
     376             :      * @param base_timestamp
     377             :      */
     378             :     std::vector<libjami::Message> getLastMessages(const uint64_t& base_timestamp) override;
     379             : 
     380             :     /**
     381             :      * Start Publish the Jami Account onto the Network
     382             :      */
     383             :     void startAccountPublish();
     384             : 
     385             :     /**
     386             :      * Start Discovery the Jami Account from the Network
     387             :      */
     388             :     void startAccountDiscovery();
     389             : 
     390             :     void saveConfig() const override;
     391             : 
     392         779 :     inline void editConfig(std::function<void(JamiAccountConfig& conf)>&& edit)
     393             :     {
     394        1558 :         Account::editConfig([&](AccountConfig& conf) { edit(*static_cast<JamiAccountConfig*>(&conf)); });
     395         779 :     }
     396             : 
     397             :     /**
     398             :      * Get current discovered peers account id and display name
     399             :      */
     400             :     std::map<std::string, std::string> getNearbyPeers() const override;
     401             : 
     402             :     void sendProfileToPeers();
     403             : 
     404             :     /**
     405             :      * Update the profile vcard and send it to peers
     406             :      * @param displayName Current or new display name
     407             :      * @param avatar Current or new avatar
     408             :      * @param flag  0 for path to avatar, 1 for base64 avatar
     409             :      */
     410             :     void updateProfile(const std::string& displayName,
     411             :                        const std::string& avatar,
     412             :                        const std::string& fileType,
     413             :                        int32_t flag) override;
     414             : 
     415             : #ifdef LIBJAMI_TEST
     416           1 :     dhtnet::ConnectionManager& connectionManager() { return *connectionManager_; }
     417             : 
     418             :     /**
     419             :      * Only used for tests, disable sha3sum verification for transfers.
     420             :      * @param newValue
     421             :      */
     422             :     void noSha3sumVerification(bool newValue);
     423             : 
     424           2 :     void publishPresence(bool newValue) { publishPresence_ = newValue; }
     425             : #endif
     426             : 
     427             :     /**
     428             :      * This should be called before flushing the account.
     429             :      * ConnectionManager needs the account to exists
     430             :      */
     431             :     void shutdownConnections();
     432             : 
     433             :     std::string_view currentDeviceId() const;
     434             : 
     435             :     // Received a new commit notification
     436             : 
     437             :     bool handleMessage(const std::shared_ptr<dht::crypto::Certificate>& cert,
     438             :                        const std::string& from,
     439             :                        const std::pair<std::string, std::string>& message) override;
     440             : 
     441             :     void monitor();
     442             :     // conversationId optional
     443             :     std::vector<std::map<std::string, std::string>> getConnectionList(const std::string& conversationId = "");
     444             :     std::vector<std::map<std::string, std::string>> getChannelList(const std::string& connectionId);
     445             : 
     446             :     // File transfer
     447             :     void sendFile(const std::string& conversationId,
     448             :                   const std::filesystem::path& path,
     449             :                   const std::string& name,
     450             :                   const std::string& replyTo);
     451             : 
     452             :     void transferFile(const std::string& conversationId,
     453             :                       const std::string& path,
     454             :                       const std::string& deviceId,
     455             :                       const std::string& fileId,
     456             :                       const std::string& interactionId,
     457             :                       size_t start = 0,
     458             :                       size_t end = 0,
     459             :                       const std::string& sha3Sum = "",
     460             :                       uint64_t lastWriteTime = 0,
     461             :                       std::function<void()> onFinished = {});
     462             : 
     463             :     void askForFileChannel(const std::string& conversationId,
     464             :                            const std::string& deviceId,
     465             :                            const std::string& interactionId,
     466             :                            const std::string& fileId,
     467             :                            size_t start = 0,
     468             :                            size_t end = 0);
     469             : 
     470             :     void askForProfile(const std::string& conversationId, const std::string& deviceId, const std::string& memberUri);
     471             : 
     472             :     /**
     473             :      * Retrieve linked transfer manager
     474             :      * @param id    conversationId or empty for fallback
     475             :      * @return linked transfer manager
     476             :      */
     477             :     std::shared_ptr<TransferManager> dataTransfer(const std::string& id = "");
     478             : 
     479             :     /**
     480             :      *   Used to get the instance of the ConversationModule class which is
     481             :      *  responsible for managing conversations and messages between users.
     482             :      * @param noCreate    whether or not to create a new instance
     483             :      * @return conversationModule instance
     484             :      */
     485             :     ConversationModule* convModule(bool noCreation = false);
     486             :     SyncModule* syncModule();
     487             : 
     488             :     /**
     489             :      * Check (via the cache) if we need to send our profile to a specific device
     490             :      * @param peerUri       Uri that will receive the profile
     491             :      * @param deviceId      Device that will receive the profile
     492             :      * @param sha3Sum       SHA3 hash of the profile
     493             :      */
     494             :     // Note: when swarm will be merged, this can be moved in transferManager
     495             :     bool needToSendProfile(const std::string& peerUri, const std::string& deviceId, const std::string& sha3Sum);
     496             :     /**
     497             :      * Send Profile via cached SIP connection
     498             :      * @param convId        Conversation's identifier (can be empty for self profile on sync)
     499             :      * @param peerUri       Uri that will receive the profile
     500             :      * @param deviceId      Device that will receive the profile
     501             :      */
     502             :     void sendProfile(const std::string& convId, const std::string& peerUri, const std::string& deviceId);
     503             :     /**
     504             :      * Send profile via cached SIP connection
     505             :      * @param peerUri       Uri that will receive the profile
     506             :      * @param deviceId      Device that will receive the profile
     507             :      */
     508             :     void sendProfile(const std::string& peerUri, const std::string& deviceId);
     509             :     /**
     510             :      * Clear sent profiles (because of a removed contact or new trust request)
     511             :      * @param peerUri       Uri used to clear cache
     512             :      */
     513             :     void clearProfileCache(const std::string& peerUri);
     514             : 
     515             :     std::filesystem::path profilePath() const;
     516             : 
     517       32905 :     const std::shared_ptr<AccountManager>& accountManager() { return accountManager_; }
     518             : 
     519             :     bool sha3SumVerify() const;
     520             : 
     521             :     /**
     522             :      * Change certificate's validity period
     523             :      * @param pwd       Password for the archive
     524             :      * @param id        Certificate to update ({} for updating the whole chain)
     525             :      * @param validity  New validity
     526             :      * @note forceReloadAccount may be necessary to retrigger the migration
     527             :      */
     528             :     bool setValidity(std::string_view scheme, const std::string& pwd, const dht::InfoHash& id, int64_t validity);
     529             :     /**
     530             :      * Try to reload the account to force the identity to be updated
     531             :      */
     532             :     void forceReloadAccount();
     533             : 
     534             :     void reloadContacts();
     535             : 
     536             :     /**
     537             :      * Make sure appdata/contacts.yml contains correct information
     538             :      * @param removedConv   The current removed conversations
     539             :      */
     540             :     void unlinkConversations(const std::set<std::string>& removedConv);
     541             : 
     542             :     bool isValidAccountDevice(const dht::crypto::Certificate& cert) const;
     543             : 
     544             :     /**
     545             :      * Join incoming call to hosted conference
     546             :      * @param callId        The call to join
     547             :      * @param destination   conversation/uri/device/confId to join
     548             :      */
     549             :     void handleIncomingConversationCall(const std::string& callId, const std::string& destination);
     550             : 
     551             :     /**
     552             :      * The DRT component is composed on some special nodes, that are usually present but not
     553             :      * connected. This kind of node corresponds to devices with push notifications & proxy and are
     554             :      * stored in the mobile nodes
     555             :      */
     556             :     bool isMobile() const { return config().proxyEnabled and not config().deviceKey.empty(); }
     557             : 
     558             : #ifdef LIBJAMI_TEST
     559           1 :     std::map<Uri::Scheme, std::unique_ptr<ChannelHandlerInterface>>& channelHandlers() { return channelHandlers_; };
     560             : #endif
     561             : 
     562       28745 :     dhtnet::tls::CertificateStore& certStore() const { return *certStore_; }
     563             :     /**
     564             :      * Check if a Device is connected
     565             :      * @param deviceId
     566             :      * @return true if connected
     567             :      */
     568             :     bool isConnectedWith(const DeviceId& deviceId) const;
     569             : 
     570             :     /**
     571             :      * Send a presence note
     572             :      * @param note
     573             :      */
     574             :     void sendPresenceNote(const std::string& note);
     575             : 
     576             : private:
     577             :     NON_COPYABLE(JamiAccount);
     578             : 
     579             :     using clock = std::chrono::system_clock;
     580             :     using time_point = clock::time_point;
     581             : 
     582             :     /**
     583             :      * Private structures
     584             :      */
     585             :     struct PendingCall;
     586             :     struct PendingMessage;
     587             :     struct BuddyInfo;
     588             :     struct DiscoveredPeer;
     589             : 
     590           0 :     inline std::string getProxyConfigKey() const
     591             :     {
     592           0 :         const auto& conf = config();
     593           0 :         return dht::InfoHash::get(conf.proxyServer + conf.proxyListUrl).toString();
     594             :     }
     595             : 
     596             :     /**
     597             :      * Compute archive encryption key and DHT storage location from password and PIN.
     598             :      */
     599             :     /* static std::pair<std::vector<uint8_t>, dht::InfoHash> computeKeys(const std::string&
     600             :        password, const std::string& pin, bool previous = false);
     601             :                                       */
     602             : 
     603             :     void trackPresence(const dht::InfoHash& h, BuddyInfo& buddy);
     604             :     void onPeerConnected(const std::string& peerId, bool connected);
     605             : 
     606             :     void doRegister_();
     607             : 
     608         777 :     const dht::ValueType USER_PROFILE_TYPE = {9, "User profile", std::chrono::hours(24 * 7)};
     609             : 
     610             :     void startOutgoingCall(const std::shared_ptr<SIPCall>& call, const std::string& toUri);
     611             : 
     612             :     void onConnectedOutgoingCall(const std::shared_ptr<SIPCall>& call, const std::string& to_id, dhtnet::IpAddr target);
     613             : 
     614             :     /**
     615             :      * Start a SIP Call
     616             :      * @param call  The current call
     617             :      * @return true if all is correct
     618             :      */
     619             :     bool SIPStartCall(SIPCall& call, const dhtnet::IpAddr& target);
     620             : 
     621             :     /**
     622             :      * Update tracking info when buddy appears offline.
     623             :      */
     624             :     void onTrackedBuddyOffline(const dht::InfoHash&);
     625             : 
     626             :     /**
     627             :      * Update tracking info when buddy appears offline.
     628             :      */
     629             :     void onTrackedBuddyOnline(const dht::InfoHash&);
     630             : 
     631             :     /**
     632             :      * Maps require port via UPnP and other async ops
     633             :      */
     634             :     void registerAsyncOps();
     635             :     /**
     636             :      * Add port mapping callback function.
     637             :      */
     638             :     void onPortMappingAdded(uint16_t port_used, bool success);
     639             :     void forEachPendingCall(const DeviceId& deviceId, const std::function<void(const std::shared_ptr<SIPCall>&)>& cb);
     640             : 
     641             :     void loadAccount(const std::string& archive_password_scheme = {},
     642             :                      const std::string& archive_password = {},
     643             :                      const std::string& archive_path = {});
     644             : 
     645             :     std::vector<std::string> loadBootstrap() const;
     646             : 
     647             :     static std::pair<std::string, std::string> saveIdentity(const dht::crypto::Identity id,
     648             :                                                             const std::filesystem::path& path,
     649             :                                                             const std::string& name);
     650             : 
     651             :     void replyToIncomingIceMsg(const std::shared_ptr<SIPCall>&,
     652             :                                const std::shared_ptr<IceTransport>&,
     653             :                                const std::shared_ptr<IceTransport>&,
     654             :                                const dht::IceCandidates&,
     655             :                                const std::shared_ptr<dht::crypto::Certificate>& from_cert,
     656             :                                const dht::InfoHash& from);
     657             : 
     658             :     void loadCachedUrl(const std::string& url,
     659             :                        const std::filesystem::path& cachePath,
     660             :                        const std::chrono::seconds& cacheDuration,
     661             :                        std::function<void(const dht::http::Response& response)>);
     662             : 
     663             :     std::string getDhtProxyServer(const std::string& serverList);
     664             :     void loadCachedProxyServer(std::function<void(const std::string&)> cb);
     665             : 
     666             :     /**
     667             :      * The TLS settings, used only if tls is chosen as a sip transport.
     668             :      */
     669             :     void generateDhParams();
     670             : 
     671             :     void newOutgoingCallHelper(const std::shared_ptr<SIPCall>& call, const Uri& uri);
     672             :     std::shared_ptr<SIPCall> newSwarmOutgoingCallHelper(const Uri& uri, const std::vector<libjami::MediaMap>& mediaList);
     673             :     std::shared_ptr<SIPCall> createSubCall(const std::shared_ptr<SIPCall>& mainCall);
     674             : 
     675             :     std::filesystem::path cachePath_ {};
     676             :     std::filesystem::path dataPath_ {};
     677             : 
     678             :     mutable std::mutex registeredNameMutex_;
     679             :     std::string registeredName_;
     680             : 
     681         689 :     bool setRegisteredName(const std::string& name)
     682             :     {
     683         689 :         std::lock_guard<std::mutex> lock(registeredNameMutex_);
     684         689 :         if (registeredName_ != name) {
     685           1 :             registeredName_ = name;
     686           1 :             return true;
     687             :         }
     688         688 :         return false;
     689         689 :     }
     690        4558 :     std::string getRegisteredName() const
     691             :     {
     692        4558 :         std::lock_guard<std::mutex> lock(registeredNameMutex_);
     693        9116 :         return registeredName_;
     694        4558 :     }
     695             : 
     696             :     std::shared_ptr<dht::Logger> logger_;
     697             :     std::shared_ptr<dhtnet::tls::CertificateStore> certStore_;
     698             : 
     699             :     std::shared_ptr<dht::DhtRunner> dht_ {};
     700             :     std::shared_ptr<AccountManager> accountManager_;
     701             :     dht::crypto::Identity id_ {};
     702             : 
     703             :     mutable std::mutex messageMutex_ {};
     704             :     std::map<dht::Value::Id, PendingMessage> sentMessages_;
     705             :     dhtnet::fileutils::IdList treatedMessages_;
     706             : 
     707             :     /* tracked buddies presence */
     708             :     mutable std::mutex buddyInfoMtx;
     709             :     std::map<dht::InfoHash, BuddyInfo> trackedBuddies_;
     710             : 
     711             :     mutable std::mutex dhtValuesMtx_;
     712             : 
     713             :     std::atomic_int syncCnt_ {0};
     714             : 
     715             :     /**
     716             :      * DHT port actually used.
     717             :      * This holds the actual DHT port, which might different from the port
     718             :      * set in the configuration. This can be the case if UPnP is used.
     719             :      */
     720         690 :     in_port_t dhtPortUsed()
     721             :     {
     722         690 :         return (upnpCtrl_ and dhtUpnpMapping_.isValid()) ? dhtUpnpMapping_.getExternalPort() : config().dhtPort;
     723             :     }
     724             : 
     725             :     /* Current UPNP mapping */
     726             :     dhtnet::upnp::Mapping dhtUpnpMapping_ {dhtnet::upnp::PortType::UDP};
     727             : 
     728             :     /**
     729             :      * Proxy
     730             :      */
     731             :     std::string proxyServerCached_ {};
     732             : 
     733             :     /**
     734             :      * Optional: via_addr construct from received parameters
     735             :      */
     736             :     pjsip_host_port via_addr_ {};
     737             : 
     738             :     pjsip_transport* via_tp_ {nullptr};
     739             : 
     740             :     /** ConnectionManager is thread-safe.
     741             :      * The shared mutex protects the pointer while allowing
     742             :      * multiple threads to access the ConnectionManager concurrently  */
     743             :     mutable std::shared_mutex connManagerMtx_ {};
     744             :     std::unique_ptr<dhtnet::ConnectionManager> connectionManager_;
     745             : 
     746             :     virtual void updateUpnpController() override;
     747             : 
     748             :     std::mutex discoveryMapMtx_;
     749             :     std::shared_ptr<dht::PeerDiscovery> peerDiscovery_;
     750             :     std::map<dht::InfoHash, DiscoveredPeer> discoveredPeers_;
     751             :     std::map<std::string, std::string> discoveredPeerMap_;
     752             : 
     753             :     std::set<std::shared_ptr<dht::http::Request>> requests_;
     754             : 
     755             :     mutable std::mutex sipConnsMtx_ {};
     756             :     struct SipConnection
     757             :     {
     758             :         std::shared_ptr<SipTransport> transport;
     759             :         // Needs to keep track of that channel to access underlying ICE
     760             :         // information, as the SipTransport use a generic transport
     761             :         std::shared_ptr<dhtnet::ChannelSocket> channel;
     762             :     };
     763             :     // NOTE: here we use a vector to avoid race conditions. In fact the contact
     764             :     // can ask for a SIP channel when we are creating a new SIP Channel with this
     765             :     // peer too.
     766             :     std::map<SipConnectionKey, std::vector<SipConnection>> sipConns_;
     767             : 
     768             :     std::mutex pendingCallsMutex_;
     769             :     std::map<DeviceId, std::vector<std::shared_ptr<SIPCall>>> pendingCalls_;
     770             : 
     771             :     std::mutex onConnectionClosedMtx_ {};
     772             :     std::map<DeviceId, std::function<void(const DeviceId&, bool)>> onConnectionClosed_ {};
     773             :     /**
     774             :      * onConnectionClosed contains callbacks that need to be called if a sub call is failing
     775             :      * @param deviceId      The device we are calling
     776             :      * @param eraseDummy    Erase the dummy call (a temporary subcall that must be stop when we will
     777             :      * not create new subcalls)
     778             :      */
     779             :     void callConnectionClosed(const DeviceId& deviceId, bool eraseDummy);
     780             : 
     781             :     /**
     782             :      * Ask a device to open a channeled SIP socket
     783             :      * @param peerId             The contact who owns the device
     784             :      * @param deviceId           The device to ask
     785             :      * @param forceNewConnection If we want a new SIP connection
     786             :      * @param pc                 A pending call to stop if the request fails
     787             :      * @note triggers cacheSIPConnection
     788             :      */
     789             :     void requestSIPConnection(const std::string& peerId,
     790             :                               const DeviceId& deviceId,
     791             :                               const std::string& connectionType,
     792             :                               bool forceNewConnection = false,
     793             :                               const std::shared_ptr<SIPCall>& pc = {});
     794             :     /**
     795             :      * Store a new SIP connection into sipConnections_
     796             :      * @param channel   The new sip channel
     797             :      * @param peerId    The contact who owns the device
     798             :      * @param deviceId  Device linked to that transport
     799             :      */
     800             :     void cacheSIPConnection(std::shared_ptr<dhtnet::ChannelSocket>&& channel,
     801             :                             const std::string& peerId,
     802             :                             const DeviceId& deviceId);
     803             :     /**
     804             :      * Shutdown a SIP connection
     805             :      * @param channel   The channel to close
     806             :      * @param peerId    The contact who owns the device
     807             :      * @param deviceId  Device linked to that transport
     808             :      */
     809             :     void shutdownSIPConnection(const std::shared_ptr<dhtnet::ChannelSocket>& channel,
     810             :                                const std::string& peerId,
     811             :                                const DeviceId& deviceId);
     812             : 
     813             :     void requestMessageConnection(const std::string& peerId,
     814             :                                   const DeviceId& deviceId,
     815             :                                   const std::string& connectionType);
     816             : 
     817             :     // File transfers
     818             :     std::mutex transfersMtx_ {};
     819             :     std::set<std::string> incomingFileTransfers_ {};
     820             : 
     821             :     /**
     822             :      * Helper used to send SIP messages on a channeled connection
     823             :      * @param conn      The connection used
     824             :      * @param to        Peer URI
     825             :      * @param ctx       Context passed to the send request
     826             :      * @param token     Token used
     827             :      * @param data      Message to send
     828             :      * @param cb        Callback to trigger when message is sent
     829             :      * @throw runtime_error if connection is invalid
     830             :      * @return if the request will be sent
     831             :      */
     832             :     bool sendSIPMessage(SipConnection& conn,
     833             :                         const std::string& to,
     834             :                         void* ctx,
     835             :                         uint64_t token,
     836             :                         const std::map<std::string, std::string>& data,
     837             :                         pjsip_endpt_send_callback cb);
     838             :     void onMessageSent(
     839             :         const std::string& to, uint64_t id, const std::string& deviceId, bool success, bool onlyConnected, bool retry);
     840             : 
     841             :     std::mutex gitServersMtx_ {};
     842             :     std::map<dht::Value::Id, std::unique_ptr<GitServer>> gitServers_ {};
     843             : 
     844             :     //// File transfer (for profiles)
     845             :     std::shared_ptr<TransferManager> nonSwarmTransferManager_;
     846             : 
     847             :     std::atomic_bool deviceAnnounced_ {false};
     848             :     std::atomic_bool noSha3sumVerification_ {false};
     849             : 
     850             :     bool publishPresence_ {true};
     851             : 
     852             :     std::map<Uri::Scheme, std::unique_ptr<ChannelHandlerInterface>> channelHandlers_ {};
     853             : 
     854             :     std::unique_ptr<ConversationModule> convModule_;
     855             :     std::mutex moduleMtx_;
     856             :     std::unique_ptr<SyncModule> syncModule_;
     857             : 
     858             :     std::mutex rdvMtx_;
     859             : 
     860             :     int dhtBoundPort_ {0};
     861             : 
     862             :     void initConnectionManager();
     863             : 
     864             :     enum class PresenceState : int { DISCONNECTED = 0, AVAILABLE, CONNECTED };
     865             :     std::map<std::string, PresenceState> presenceState_;
     866             :     std::string presenceNote_;
     867             : };
     868             : 
     869             : static inline std::ostream&
     870             : operator<<(std::ostream& os, const JamiAccount& acc)
     871             : {
     872             :     os << "[Account " << acc.getAccountID() << "] ";
     873             :     return os;
     874             : }
     875             : 
     876             : } // namespace jami

Generated by: LCOV version 1.14