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 "contact_list.h"
24 : #include "logger.h"
25 : #include "namedirectory.h"
26 :
27 : #include <opendht/crypto.h>
28 : #include <optional>
29 : #include <functional>
30 : #include <map>
31 : #include <string>
32 : #include <filesystem>
33 :
34 : #include <dhtnet/multiplexed_socket.h>
35 :
36 : namespace dht {
37 : class DhtRunner;
38 : }
39 :
40 : namespace jami {
41 :
42 : using DeviceId = dht::PkId;
43 : struct AccountArchive;
44 : class AuthChannelHandler;
45 :
46 : struct AccountInfo
47 : {
48 : dht::crypto::Identity identity;
49 : std::unique_ptr<ContactList> contacts;
50 : std::string accountId;
51 : std::string deviceId;
52 : std::shared_ptr<dht::crypto::PublicKey> devicePk;
53 : std::shared_ptr<dht::Value> announce;
54 : std::string ethAccount;
55 : std::string username;
56 :
57 : std::string displayName;
58 : std::string photo;
59 : };
60 :
61 : template<typename To, typename From>
62 : std::unique_ptr<To>
63 777 : dynamic_unique_cast(std::unique_ptr<From>&& p)
64 : {
65 777 : if (auto cast = dynamic_cast<To*>(p.get())) {
66 777 : std::unique_ptr<To> result(cast);
67 777 : p.release();
68 777 : return result;
69 777 : }
70 0 : return {};
71 : }
72 :
73 : class AccountManager : public std::enable_shared_from_this<AccountManager>
74 : {
75 : public:
76 : using OnChangeCallback = ContactList::OnChangeCallback;
77 : using clock = std::chrono::system_clock;
78 : using time_point = clock::time_point;
79 : using OnNewDeviceCb = std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>;
80 : using OnDeviceAnnouncedCb = std::function<void()>;
81 :
82 793 : AccountManager(const std::string& accountId, const std::filesystem::path& path, const std::string& nameServer)
83 1586 : : accountId_(accountId)
84 793 : , path_(path)
85 1586 : , nameDir_(NameDirectory::instance(nameServer)) {};
86 :
87 : virtual ~AccountManager();
88 :
89 : constexpr static const char* const DHT_TYPE_NS = "cx.ring";
90 :
91 : // Auth
92 :
93 : enum class AuthError { UNKNOWN, INVALID_ARGUMENTS, SERVER_ERROR, NETWORK };
94 :
95 : using AuthSuccessCallback = std::function<void(const AccountInfo& info,
96 : const std::map<std::string, std::string>& config,
97 : std::string&& receipt,
98 : std::vector<uint8_t>&& receipt_signature)>;
99 :
100 : using AuthFailureCallback = std::function<void(AuthError error, const std::string& message)>;
101 : using DeviceSyncCallback = std::function<void(DeviceSync&& syncData)>;
102 : using CertRequest = std::future<std::unique_ptr<dht::crypto::CertificateRequest>>;
103 : using PrivateKey = std::shared_future<std::shared_ptr<dht::crypto::PrivateKey>>;
104 :
105 : CertRequest buildRequest(PrivateKey fDeviceKey);
106 :
107 : struct AccountCredentials
108 : {
109 : std::string scheme;
110 : std::string uri;
111 : std::string password_scheme;
112 : std::string password;
113 773 : virtual ~AccountCredentials() {};
114 : };
115 :
116 : virtual void initAuthentication(std::string deviceName,
117 : std::unique_ptr<AccountCredentials> credentials,
118 : AuthSuccessCallback onSuccess,
119 : AuthFailureCallback onFailure,
120 : const OnChangeCallback& onChange)
121 : = 0;
122 :
123 : virtual bool changePassword(const std::string& password_old, const std::string& password_new) = 0;
124 :
125 : virtual void syncDevices() = 0;
126 : virtual void onSyncData(DeviceSync&& device, bool checkDevice = true);
127 :
128 0 : virtual bool isPasswordValid(const std::string& /*password*/) { return false; };
129 0 : virtual std::vector<uint8_t> getPasswordKey(const std::string& /*password*/) { return {}; };
130 :
131 : dht::crypto::Identity loadIdentity(const std::string& crt_path,
132 : const std::string& key_path,
133 : const std::string& key_pwd) const;
134 :
135 : const AccountInfo* useIdentity(const dht::crypto::Identity& id,
136 : const std::string& receipt,
137 : const std::vector<uint8_t>& receiptSignature,
138 : const std::string& username,
139 : const OnChangeCallback& onChange);
140 :
141 694 : void setDht(const std::shared_ptr<dht::DhtRunner>& dht) { dht_ = dht; }
142 :
143 : virtual void startSync(const OnNewDeviceCb& cb, const OnDeviceAnnouncedCb& dcb, bool publishPresence = true);
144 :
145 88576 : const AccountInfo* getInfo() const { return info_.get(); }
146 :
147 : void reloadContacts();
148 :
149 : // Device management
150 :
151 : enum class AddDeviceError { INVALID_URI = -1, ALREADY_LINKING = -2, GENERIC = -3 };
152 :
153 : enum class RevokeDeviceResult {
154 : SUCCESS = 0,
155 : ERROR_CREDENTIALS,
156 : ERROR_NETWORK,
157 : };
158 :
159 : using RevokeDeviceCallback = std::function<void(RevokeDeviceResult)>;
160 :
161 : /**
162 : * Initiates the process of adding a new device to the account
163 : * @param uri The URI provided by the new device to be added
164 : * @param auth_scheme The auth scheme (currently only "password" is expected)
165 : * @param chanel
166 : * @return A positive operation ID if successful, or a negative value indicating an AddDeviceError:
167 : * - INVALID_URI (-1): The provided URI is invalid
168 : * - ALREADY_LINKING (-2): A device linking operation is already in progress
169 : * - GENERIC (-3): A generic error occurred during the process
170 : */
171 0 : virtual int32_t addDevice(const std::string& /*uri*/, std::string_view /*auth_scheme*/, AuthChannelHandler*)
172 : {
173 0 : return 0;
174 : };
175 0 : virtual bool cancelAddDevice(uint32_t /*token*/) { return false; };
176 0 : virtual bool confirmAddDevice(uint32_t /*token*/) { return false; };
177 0 : virtual bool revokeDevice(const std::string& /*device*/,
178 : std::string_view /*scheme*/,
179 : const std::string& /*password*/,
180 : RevokeDeviceCallback)
181 : {
182 0 : return false;
183 : };
184 :
185 : const std::map<dht::PkId, KnownDevice>& getKnownDevices() const;
186 : bool foundAccountDevice(const std::shared_ptr<dht::crypto::Certificate>& crt,
187 : const std::string& name = {},
188 0 : const time_point& last_sync = time_point::min());
189 : // bool removeAccountDevice(const dht::InfoHash& device);
190 : void setAccountDeviceName(/*const dht::InfoHash& device, */ const std::string& name);
191 : std::string getAccountDeviceName() const;
192 :
193 : void forEachDevice(const dht::InfoHash& to,
194 : std::function<void(const std::shared_ptr<dht::crypto::PublicKey>&)>&& op,
195 : std::function<void(bool)>&& end = {});
196 :
197 : using PeerCertificateCb
198 : = std::function<void(const std::shared_ptr<dht::crypto::Certificate>& crt, const dht::InfoHash& peer_account)>;
199 : void onPeerMessage(const dht::crypto::PublicKey& peer_device, bool allowPublic, PeerCertificateCb&& cb);
200 : bool onPeerCertificate(const std::shared_ptr<dht::crypto::Certificate>& crt,
201 : bool allowPublic,
202 : dht::InfoHash& account_id);
203 :
204 : /**
205 : * Inform that a potential peer device have been found.
206 : * Returns true only if the device certificate is a valid device certificate.
207 : * In that case (true is returned) the account_id parameter is set to the peer account ID.
208 : */
209 : static bool foundPeerDevice(const std::string& accoundId,
210 : const std::shared_ptr<dht::crypto::Certificate>& crt,
211 : dht::InfoHash& account_id);
212 :
213 : // Contact requests
214 :
215 : std::vector<std::map<std::string, std::string>> getTrustRequests() const;
216 : // Note: includeConversation used for compatibility test, do not use if not in test env.
217 : bool acceptTrustRequest(const std::string& from, bool includeConversation = true);
218 : bool discardTrustRequest(const std::string& from);
219 :
220 : void sendTrustRequest(const std::string& to, const std::string& convId, const std::vector<uint8_t>& payload);
221 : void sendTrustRequestConfirm(const dht::InfoHash& to,
222 : const std::string& conversationId); // TODO ideally no convId here
223 :
224 : // Contact
225 :
226 : /**
227 : * Add contact to the account contact list.
228 : * Set confirmed if we know the contact also added us.
229 : */
230 : bool addContact(const dht::InfoHash& uri, bool confirmed = false, const std::string& conversationId = "");
231 : void removeContact(const std::string& uri, bool banned = true);
232 : void removeContactConversation(const std::string& uri); // for non swarm contacts
233 : void updateContactConversation(const std::string& uri, const std::string& convId, bool added = false);
234 : std::map<dht::InfoHash, Contact> getContacts(bool includeRemoved = false) const;
235 :
236 : /** Obtain details about one account contact in serializable form. */
237 : std::map<std::string, std::string> getContactDetails(const std::string& uri) const;
238 : std::optional<Contact> getContactInfo(const std::string& uri) const;
239 :
240 : virtual bool findCertificate(const dht::InfoHash& h,
241 : std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb = {});
242 :
243 : virtual bool findCertificate(const dht::PkId& h,
244 : std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb = {});
245 :
246 : bool setCertificateStatus(const std::string& cert_id, dhtnet::tls::TrustStore::PermissionStatus status);
247 : bool setCertificateStatus(const std::shared_ptr<crypto::Certificate>& cert,
248 : dhtnet::tls::TrustStore::PermissionStatus status,
249 : bool local = true);
250 : std::vector<std::string> getCertificatesByStatus(dhtnet::tls::TrustStore::PermissionStatus status);
251 : dhtnet::tls::TrustStore::PermissionStatus getCertificateStatus(const std::string& cert_id) const;
252 : bool isAllowed(const crypto::Certificate& crt, bool allowPublic = false);
253 :
254 : static std::shared_ptr<dht::Value> parseAnnounce(const std::string& announceBase64,
255 : const std::string& accountId,
256 : const std::string& deviceSha1,
257 : const std::string& deviceSha256);
258 :
259 : // Name resolver
260 : using LookupCallback = NameDirectory::LookupCallback;
261 : using SearchResult = NameDirectory::SearchResult;
262 : using SearchCallback = NameDirectory::SearchCallback;
263 : using RegistrationCallback = NameDirectory::RegistrationCallback;
264 : using SearchResponse = NameDirectory::Response;
265 :
266 : virtual void lookupUri(const std::string& name, const std::string& defaultServer, LookupCallback cb);
267 : virtual void lookupAddress(const std::string& address, LookupCallback cb);
268 0 : virtual bool searchUser(const std::string& /*query*/, SearchCallback /*cb*/) { return false; }
269 : virtual void registerName(const std::string& name,
270 : std::string_view scheme,
271 : const std::string& password,
272 : RegistrationCallback cb)
273 : = 0;
274 :
275 : dhtnet::tls::CertificateStore& certStore() const;
276 :
277 : protected:
278 : const std::string accountId_;
279 : const std::filesystem::path path_;
280 : OnChangeCallback onChange_;
281 : std::unique_ptr<AccountInfo> info_;
282 : std::shared_ptr<dht::DhtRunner> dht_;
283 : std::reference_wrapper<NameDirectory> nameDir_;
284 : };
285 :
286 : } // namespace jami
|