LCOV - code coverage report
Current view: top level - foo/src - account.h (source / functions) Hit Total Coverage
Test: jami-coverage-filtered.info Lines: 66 107 61.7 %
Date: 2026-02-28 10:41:24 Functions: 39 56 69.6 %

          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             : #ifdef HAVE_CONFIG_H
      20             : #include "config.h"
      21             : #endif
      22             : 
      23             : #include "client/jami_signal.h"
      24             : #include "configurationmanager_interface.h"
      25             : #include "noncopyable.h"
      26             : #include "config/serializable.h"
      27             : #include "registration_states.h"
      28             : #include "im/message_engine.h"
      29             : #include "media/media_codec.h"
      30             : #include "media/media_attribute.h"
      31             : #include "logger.h"
      32             : #include "compiler_intrinsics.h" // include the "UNUSED" macro
      33             : #include "call_set.h"
      34             : #include "account_config.h"
      35             : #include "vcard.h"
      36             : 
      37             : #include <dhtnet/ip_utils.h>
      38             : #include <dhtnet/upnp/upnp_control.h>
      39             : 
      40             : #include <functional>
      41             : #include <string>
      42             : #include <vector>
      43             : #include <memory>
      44             : #include <map>
      45             : #include <set>
      46             : #include <random>
      47             : #include <stdexcept>
      48             : #include <atomic>
      49             : #include <mutex>
      50             : #include <chrono>
      51             : 
      52             : namespace Json {
      53             : class Value;
      54             : }
      55             : 
      56             : namespace dht {
      57             : namespace crypto {
      58             : struct Certificate;
      59             : }
      60             : } // namespace dht
      61             : 
      62             : namespace jami {
      63             : static constexpr uint64_t JAMI_ID_MAX_VAL = 9007199254740992;
      64             : constexpr static const char RINGDIR[] = "ringtones";
      65             : 
      66             : class Call;
      67             : class SystemCodecContainer;
      68             : 
      69             : class VoipLinkException : public std::runtime_error
      70             : {
      71             : public:
      72           0 :     VoipLinkException(const std::string& str = "")
      73           0 :         : std::runtime_error("VoipLinkException occurred: " + str)
      74           0 :     {}
      75             : };
      76             : 
      77             : /**
      78             :  * @file account.h
      79             :  * @brief Interface to protocol account (ex: SIPAccount)
      80             :  * It can be enable on loading or activate after.
      81             :  * It contains account, configuration, VoIP Link and Calls (inside the VoIPLink)
      82             :  */
      83             : 
      84             : class Account : public std::enable_shared_from_this<Account>
      85             : {
      86             : public:
      87             :     Account(const std::string& accountID);
      88             : 
      89             :     /**
      90             :      * Virtual destructor
      91             :      */
      92             :     virtual ~Account();
      93             : 
      94             :     /**
      95             :      * Free all ressources related to this account.
      96             :      *   ***Current calls using this account are HANG-UP***
      97             :      */
      98             :     void hangupCalls();
      99             : 
     100             :     virtual std::unique_ptr<AccountConfig> buildConfig() const = 0;
     101             : 
     102           0 :     void setConfig(std::unique_ptr<AccountConfig>&& config)
     103             :     {
     104           0 :         std::lock_guard lock(configurationMutex_);
     105           0 :         config_ = std::move(config);
     106           0 :         loadConfig();
     107           0 :     }
     108             : 
     109             :     /**
     110             :      * Load the settings in this account.
     111             :      */
     112             :     virtual void loadConfig();
     113             : 
     114       41531 :     const AccountConfig& config() const
     115             :     {
     116       41531 :         if (config_)
     117       41536 :             return *config_;
     118             :         else
     119           0 :             throw std::runtime_error("Account doesn't have a configuration");
     120             :     }
     121             : 
     122         786 :     inline void editConfig(std::function<void(AccountConfig& config)>&& edit)
     123             :     {
     124         786 :         std::lock_guard lock(configurationMutex_);
     125         786 :         edit(*config_);
     126         786 :         saveConfig();
     127         786 :     }
     128             : 
     129             :     virtual void saveConfig() const;
     130             : 
     131         801 :     void setAccountDetails(const std::map<std::string, std::string>& details)
     132             :     {
     133         801 :         std::lock_guard lock(configurationMutex_);
     134         801 :         if (not config_)
     135         781 :             config_ = buildConfig();
     136         801 :         config_->fromMap(details);
     137         801 :         loadConfig();
     138         801 :         saveConfig();
     139         801 :     }
     140             : 
     141         314 :     std::map<std::string, std::string> getAccountDetails() const
     142             :     {
     143         314 :         std::lock_guard lock(configurationMutex_);
     144         628 :         return config().toMap();
     145         314 :     }
     146             : 
     147             :     virtual std::map<std::string, std::string> getVolatileAccountDetails() const;
     148             : 
     149             :     virtual std::string getFromUri() const = 0;
     150             : 
     151             :     /**
     152             :      * Get the account ID
     153             :      * @return constant account id
     154             :      */
     155       97170 :     inline const std::string& getAccountID() const { return accountID_; }
     156             : 
     157             :     virtual std::string_view getAccountType() const = 0;
     158             : 
     159        6710 :     const std::filesystem::path& getPath() const { return idPath_; }
     160             : 
     161             :     /**
     162             :      * Returns true if this is the IP2IP account
     163             :      */
     164        4591 :     virtual bool isIP2IP() const { return false; }
     165             : 
     166             :     /**
     167             :      * Register the account.
     168             :      * This should update the getRegistrationState() return value.
     169             :      */
     170             :     virtual void doRegister() = 0;
     171             : 
     172             :     /**
     173             :      * Unregister the account.
     174             :      * This should update the getRegistrationState() return value.
     175             :      */
     176             :     virtual void doUnregister(bool forceShutdownConnections = false) = 0;
     177             : 
     178           6 :     RegistrationState getRegistrationState() const { return registrationState_; }
     179             : 
     180             :     /**
     181             :      * Create a new outgoing call.
     182             :      *
     183             :      * @param toUrl The address to call
     184             :      * @param mediaList A list of media
     185             :      * @return The created call
     186             :      */
     187             :     virtual std::shared_ptr<Call> newOutgoingCall(std::string_view toUrl,
     188             :                                                   const std::vector<libjami::MediaMap>& mediaList)
     189             :         = 0;
     190             : 
     191             :     /**
     192             :      * If supported, send a text message from this account.
     193             :      * @return a token to query the message status
     194             :      */
     195           0 :     virtual uint64_t sendTextMessage(const std::string& /*to*/,
     196             :                                      const std::string& /*deviceId*/,
     197             :                                      const std::map<std::string, std::string>& /*payloads*/,
     198             :                                      uint64_t /*refreshToken*/ = 0,
     199             :                                      bool /*onlyConnected*/ = false)
     200             :     {
     201           0 :         return 0;
     202             :     }
     203             : 
     204           0 :     virtual void setIsComposing(const std::string& /*conversationUri*/, bool /*isWriting*/) {};
     205             : 
     206           0 :     virtual bool setMessageDisplayed(const std::string& /*conversationUri*/,
     207             :                                      const std::string& /*messageId*/,
     208             :                                      int /*status*/)
     209             :     {
     210           0 :         return false;
     211             :     };
     212             : 
     213           0 :     virtual std::vector<libjami::Message> getLastMessages(const uint64_t& /*base_timestamp*/) { return {}; }
     214             : 
     215           0 :     virtual std::map<std::string, std::string> getNearbyPeers() const { return {}; }
     216             : 
     217             :     virtual void updateProfile(const std::string& /*displayName*/,
     218             :                                const std::string& /*avatar*/,
     219             :                                const std::string& /*fileType*/,
     220             :                                int32_t /*flag*/)
     221             :         = 0;
     222             : 
     223             :     vCard::utils::VCardData getProfileVcard() const;
     224             : 
     225             :     /**
     226             :      * Return the status corresponding to the token.
     227             :      */
     228           0 :     virtual im::MessageStatus getMessageStatus(uint64_t /*id*/) const { return im::MessageStatus::UNKNOWN; }
     229             : 
     230           0 :     virtual bool setPushNotificationToken(const std::string& pushDeviceToken = "")
     231             :     {
     232           0 :         std::lock_guard lock(configurationMutex_);
     233           0 :         if (config_ && config_->deviceKey != pushDeviceToken) {
     234           0 :             config_->deviceKey = pushDeviceToken;
     235           0 :             saveConfig();
     236           0 :             return true;
     237             :         }
     238           0 :         return false;
     239           0 :     }
     240             : 
     241           0 :     virtual bool setPushNotificationTopic(const std::string& topic = "")
     242             :     {
     243           0 :         std::lock_guard lock(configurationMutex_);
     244           0 :         if (config_ && config_->notificationTopic != topic) {
     245           0 :             config_->notificationTopic = topic;
     246           0 :             saveConfig();
     247           0 :             return true;
     248             :         }
     249           0 :         return false;
     250           0 :     }
     251             : 
     252             :     virtual bool setPushNotificationConfig(const std::map<std::string, std::string>& data);
     253             : 
     254             :     /**
     255             :      * Tell if the account is enable or not.
     256             :      * @return true if enabled, false otherwise
     257             :      */
     258        1817 :     bool isEnabled() const { return config().enabled; }
     259             : 
     260         212 :     void setEnabled(bool enable)
     261             :     {
     262         212 :         config_->enabled = enable;
     263             :         // Update the UPnP controller to make sure it's in the correct state since this
     264             :         // depends on whether the account is enabled or not (in particular, we don't want
     265             :         // disabled accounts to generate UPnP activity).
     266         212 :         updateUpnpController();
     267         212 :     }
     268             : 
     269             :     /**
     270             :      * Tell if the account is activated
     271             :      * (can currently be used).
     272             :      */
     273           0 :     bool isActive() const noexcept { return active_; }
     274             : 
     275           0 :     void setActive(bool active) noexcept { active_ = active; }
     276             : 
     277        2721 :     bool isUsable() const { return config().enabled and active_; }
     278             : 
     279           2 :     void enableVideo(bool enable)
     280             :     {
     281           2 :         editConfig([&](AccountConfig& config) { config.videoEnabled = enable; });
     282           2 :     }
     283         490 :     bool isVideoEnabled() const { return config().videoEnabled; }
     284             : 
     285             :     /**
     286             :      * Set the registration state of the specified link
     287             :      * @param state The registration state of underlying VoIPLink
     288             :      */
     289             :     virtual void setRegistrationState(RegistrationState state, int detail_code = 0, const std::string& detail_str = {});
     290             : 
     291       10980 :     const std::string& getUsername() const { return config().username; }
     292             :     const std::string& getHostname() const { return config().hostname; }
     293             :     const std::string& getAlias() const { return config().alias; }
     294             : 
     295             :     static std::vector<unsigned> getDefaultCodecsId();
     296             :     static std::map<std::string, std::string> getDefaultCodecDetails(const unsigned& codecId);
     297             : 
     298             :     /* Accessor to data structures
     299             :      * @return The list that reflects the user's choice
     300             :      */
     301             :     std::vector<unsigned> getActiveCodecs(MediaType mediaType = MEDIA_ALL) const;
     302             :     bool hasActiveCodec(MediaType mediaType) const;
     303             : 
     304             :     /**
     305             :      * Update both the codec order structure and the codec string used for
     306             :      * SDP offer and configuration respectively
     307             :      */
     308             :     virtual void setActiveCodecs(const std::vector<unsigned>& list);
     309             :     std::shared_ptr<SystemCodecInfo> searchCodecById(unsigned codecId, MediaType mediaType);
     310             :     std::vector<std::shared_ptr<SystemCodecInfo>> getActiveAccountCodecInfoList(MediaType mediaType) const;
     311             :     std::shared_ptr<SystemCodecInfo> searchCodecByPayload(unsigned payload, MediaType mediaType);
     312             : 
     313          50 :     std::filesystem::path getRingtonePath() const { return ringtonePath_; }
     314          50 :     bool getRingtoneEnabled() const { return config().ringtoneEnabled; }
     315         725 :     std::string getDisplayName() const { return config().displayName; }
     316             :     std::string getMailBox() const { return config().mailbox; }
     317             : 
     318         190 :     bool isRendezVous() const { return config().isRendezVous; }
     319          92 :     bool isAutoAnswerEnabled() const { return config().autoAnswerEnabled; }
     320          35 :     bool isDenySecondCallEnabled() const { return config().denySecondCallEnabled; }
     321          18 :     bool isReadReceiptEnabled() const { return config().sendReadReceipt; }
     322          28 :     bool isComposingEnabled() const { return config().sendComposing; }
     323             : 
     324             :     /**
     325             :      * returns whether or not UPnP is enabled and active
     326             :      * ie: if it is able to make port mappings
     327             :      */
     328             :     bool getUPnPActive() const;
     329             : 
     330             :     /**
     331             :      * Get the UPnP IP (external router) address.
     332             :      * If use UPnP is set to false, the address will be empty.
     333             :      */
     334             :     dhtnet::IpAddr getUPnPIpAddress() const;
     335             : 
     336             :     /**
     337             :      * Random generator engine
     338             :      * Logical account state shall never rely on the state of the random generator.
     339             :      */
     340             :     mutable std::mt19937_64 rand;
     341             : 
     342             :     /**
     343             :      * Inform the account that the network status has changed.
     344             :      */
     345           0 :     virtual void connectivityChanged() {};
     346             : 
     347           0 :     virtual bool handleMessage(const std::shared_ptr<dht::crypto::Certificate>& /*cert*/,
     348             :                                const std::string& /*from*/,
     349             :                                const std::pair<std::string, std::string>& /*message*/)
     350             :     {
     351           0 :         return false;
     352             :     };
     353             : 
     354             :     /**
     355             :      * Helper function used to load the default codec order from the codec factory
     356             :      */
     357             :     void loadDefaultCodecs();
     358             : 
     359             :     void setCodecActive(unsigned codecId);
     360             : 
     361             :     void setCodecInactive(unsigned codecId);
     362             : 
     363             :     /**
     364             :      * Get the user-agent
     365             :      */
     366             :     const std::string& getUserAgentName();
     367             : 
     368          68 :     std::set<std::string> getDefaultModerators() const { return config().defaultModerators; }
     369             : 
     370             :     void addDefaultModerator(const std::string& peerURI);
     371             :     void removeDefaultModerator(const std::string& peerURI);
     372             : 
     373          68 :     bool isLocalModeratorsEnabled() const { return config().localModeratorsEnabled; }
     374          68 :     bool isAllModerators() const { return config().allModeratorsEnabled; }
     375             : 
     376             :     // Enable/disable ICE for media
     377         359 :     bool isIceForMediaEnabled() const { return iceForMediaEnabled_; }
     378           0 :     void enableIceForMedia(bool enable) { iceForMediaEnabled_ = enable; }
     379             : 
     380             :     // Enable/disable generation of empty offers
     381           4 :     bool isEmptyOffersEnabled() const { return false; }
     382             : 
     383             :     // Check if a Daemon version (typically peer's version) satisfies the
     384             :     // minimum required version. This check is typically used to disable a
     385             :     // feature if it's not backward compatible with the peer's version.
     386             :     static bool meetMinimumRequiredVersion(const std::vector<unsigned>& jamiVersion,
     387             :                                            const std::vector<unsigned>& minRequiredVersion);
     388             : 
     389             :     // Enable/disable compliancy with RFC-5245 for component IDs format.
     390             :     // The ICE component IDs are enumerated relative to the SDP session,
     391             :     // i.e., starts from 1 and incremented for each component.
     392             :     // However, RFC-5245 requires that the ICE component IDs are enumerated
     393             :     // relative to the media stream, e.g., component IDs 1 and 2 for audio,
     394             :     // and component IDs 1 and 2 for video. This non-conformity can cause
     395             :     // inter-operability issues.
     396             :     // When the compliancy feature is enabled, the component ID in the
     397             :     // generated SDP will be compliant to RFC-5245. This feature should be
     398             :     // enabled only when the peer is compliant to RFC-5245 as well.
     399             :     // The current version is able to correctly parse both formats.
     400             :     // This feature is needed for backward compatiblity, and should be removed
     401             :     // once the  backward compatibility is no more required.
     402         213 :     bool isIceCompIdRfc5245Compliant() const { return iceCompIdRfc5245Compliant_; }
     403           4 :     void enableIceCompIdRfc5245Compliance(bool enable) { iceCompIdRfc5245Compliant_ = enable; }
     404           0 :     void enableAutoLoadConversations(bool enable) { autoLoadConversations_ = enable; }
     405             : 
     406         635 :     std::shared_ptr<Call> getCall(const std::string& callId) const { return callSet_.getCall(callId); }
     407           0 :     std::vector<std::string> getCallList() const { return callSet_.getCallIds(); }
     408          97 :     std::shared_ptr<Conference> getConference(const std::string& confId) const
     409             :     {
     410          97 :         return callSet_.getConference(confId);
     411             :     }
     412           4 :     std::vector<std::string> getConferenceList() const { return callSet_.getConferenceIds(); }
     413         359 :     void attach(const std::shared_ptr<Call>& call) { callSet_.add(call); }
     414         372 :     bool detach(const std::shared_ptr<Call>& call) { return callSet_.remove(call); }
     415          37 :     void attach(const std::shared_ptr<Conference>& conf) { callSet_.add(conf); }
     416          57 :     bool removeConference(const std::string& confId)
     417             :     {
     418          57 :         auto result = callSet_.removeConference(confId);
     419          57 :         if (result)
     420          33 :             emitSignal<libjami::CallSignal::ConferenceRemoved>(getAccountID(), confId);
     421          57 :         return result;
     422             :     }
     423             : 
     424             : public:
     425             :     // virtual methods that has to be implemented by concrete classes
     426             :     /**
     427             :      * This method is called to request removal of possible account traces on the system,
     428             :      * like internal account setup files.
     429             :      */
     430         780 :     virtual void flush() { /* nothing to do here - overload */ };
     431             : 
     432             : private:
     433             :     NON_COPYABLE(Account);
     434             : 
     435             :     /**
     436             :      * Set of calls attached to the account.
     437             :      */
     438             :     CallSet callSet_;
     439             : 
     440             : protected:
     441             :     virtual void updateUpnpController();
     442             : 
     443             :     std::unique_ptr<AccountConfig> config_ {};
     444             : 
     445             :     friend class ConfigurationTest;
     446             : 
     447             :     static const std::string DEFAULT_USER_AGENT;
     448             : 
     449             :     static std::string mapStateNumberToString(RegistrationState state);
     450             : 
     451             :     /**
     452             :      * Build the user-agent string
     453             :      */
     454             :     static std::string getDefaultUserAgent();
     455             : 
     456             :     /**
     457             :      * Account ID are assign in constructor and shall not changed
     458             :      */
     459             :     const std::string accountID_;
     460             : 
     461             :     mutable std::recursive_mutex configurationMutex_ {};
     462             : 
     463             :     /**
     464             :      * Tells if the account is active now.
     465             :      * This allows doRegister to be called.
     466             :      * When an account is unactivated, doUnregister must be called.
     467             :      */
     468             :     bool active_ {true};
     469             : 
     470             :     /*
     471             :      * The general, protocol neutral registration
     472             :      * state of the account
     473             :      */
     474             :     RegistrationState registrationState_ {RegistrationState::UNLOADED};
     475             : 
     476             :     /**
     477             :      * Vector containing all system codecs (with default parameters)
     478             :      */
     479             :     std::shared_ptr<SystemCodecContainer> systemCodecContainer_;
     480             :     /**
     481             :      * Vector containing all account codecs (set of system codecs with custom parameters)
     482             :      */
     483             :     std::vector<std::shared_ptr<SystemCodecInfo>> accountCodecInfoList_;
     484             : 
     485             :     /**
     486             :      * path to account
     487             :      */
     488             :     std::filesystem::path idPath_ {};
     489             : 
     490             :     /**
     491             :      * Ringtone .au file used for this account
     492             :      */
     493             :     std::filesystem::path ringtonePath_;
     494             : 
     495             :     /**
     496             :      * UPnP IGD controller and the mutex to access it
     497             :      */
     498             :     mutable std::mutex upnp_mtx {};
     499             :     std::shared_ptr<dhtnet::upnp::Controller> upnpCtrl_;
     500             : 
     501             :     bool iceForMediaEnabled_ {true};
     502             :     bool iceCompIdRfc5245Compliant_ {false};
     503             :     /**
     504             :      * Auto load conversations when creatinf convModule()
     505             :      */
     506             :     bool autoLoadConversations_ {true};
     507             : 
     508             :     /**
     509             :      * private account codec searching functions
     510             :      */
     511             :     std::shared_ptr<SystemCodecInfo> searchCodecByName(const std::string& name, MediaType mediaType);
     512             :     std::vector<unsigned> getAccountCodecInfoIdList(MediaType mediaType) const;
     513             :     void setAllCodecsActive(MediaType mediaType, bool active);
     514             :     void sortCodec();
     515             : };
     516             : 
     517             : static inline std::ostream&
     518           4 : operator<<(std::ostream& os, const Account& acc)
     519             : {
     520           4 :     os << "[Account " << acc.getAccountID() << "] ";
     521           4 :     return os;
     522             : }
     523             : 
     524             : } // namespace jami

Generated by: LCOV version 1.14