blob: 2eb0a1c3fea196a3ba9e0605a3448f23623368dc [file] [log] [blame]
Adrien Béraud612b55b2023-05-29 10:42:04 -04001/*
Adrien Béraudcb753622023-07-17 22:32:49 -04002 * Copyright (C) 2004-2023 Savoir-faire Linux Inc.
Adrien Béraud612b55b2023-05-29 10:42:04 -04003 *
Adrien Béraudcb753622023-07-17 22:32:49 -04004 * This program is free software: you can redistribute it and/or modify
Adrien Béraud612b55b2023-05-29 10:42:04 -04005 * it under the terms of the GNU General Public License as published by
Adrien Béraudcb753622023-07-17 22:32:49 -04006 * the Free Software Foundation, either version 3 of the License, or
Adrien Béraud612b55b2023-05-29 10:42:04 -04007 * (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
Adrien Béraudcb753622023-07-17 22:32:49 -040011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
Adrien Béraud612b55b2023-05-29 10:42:04 -040012 * 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#include "connectionmanager.h"
18#include "peer_connection.h"
19#include "upnp/upnp_control.h"
20#include "certstore.h"
21#include "fileutils.h"
22#include "sip_utils.h"
23#include "string_utils.h"
24
25#include <opendht/crypto.h>
26#include <opendht/thread_pool.h>
27#include <opendht/value.h>
28#include <asio.hpp>
29
30#include <algorithm>
31#include <mutex>
32#include <map>
33#include <condition_variable>
34#include <set>
35#include <charconv>
Morteza Namvar5f639522023-07-04 17:08:58 -040036#include <fstream>
Adrien Béraud612b55b2023-05-29 10:42:04 -040037
Adrien Béraud1ae60aa2023-07-07 09:55:09 -040038namespace dhtnet {
Adrien Béraud612b55b2023-05-29 10:42:04 -040039static constexpr std::chrono::seconds DHT_MSG_TIMEOUT {30};
40static constexpr uint64_t ID_MAX_VAL = 9007199254740992;
41
42using ValueIdDist = std::uniform_int_distribution<dht::Value::Id>;
Adrien Béraud75754b22023-10-17 09:16:06 -040043
Amna31791e52023-08-03 12:40:57 -040044std::string
45callbackIdToString(const dhtnet::DeviceId& did, const dht::Value::Id& vid)
46{
47 return fmt::format("{} {}", did.to_view(), vid);
48}
Adrien Béraud612b55b2023-05-29 10:42:04 -040049
Adrien Béraud75754b22023-10-17 09:16:06 -040050std::pair<dhtnet::DeviceId, dht::Value::Id> parseCallbackId(std::string_view ci)
Amna31791e52023-08-03 12:40:57 -040051{
52 auto sep = ci.find(' ');
53 std::string_view deviceIdString = ci.substr(0, sep);
54 std::string_view vidString = ci.substr(sep + 1);
55
56 dhtnet::DeviceId deviceId(deviceIdString);
57 dht::Value::Id vid = std::stoul(std::string(vidString), nullptr, 10);
Adrien Béraud75754b22023-10-17 09:16:06 -040058 return {deviceId, vid};
Amna31791e52023-08-03 12:40:57 -040059}
Amna81221ad2023-09-14 17:33:26 -040060
61std::shared_ptr<ConnectionManager::Config>
62createConfig(std::shared_ptr<ConnectionManager::Config> config_)
63{
64 if (!config_->certStore){
65 config_->certStore = std::make_shared<dhtnet::tls::CertificateStore>("client", config_->logger);
66 }
67 if (!config_->dht) {
68 dht::DhtRunner::Config dhtConfig;
69 dhtConfig.dht_config.id = config_->id;
70 dhtConfig.threaded = true;
71 dht::DhtRunner::Context dhtContext;
72 dhtContext.certificateStore = [c = config_->certStore](const dht::InfoHash& pk_id) {
73 std::vector<std::shared_ptr<dht::crypto::Certificate>> ret;
74 if (auto cert = c->getCertificate(pk_id.toString()))
75 ret.emplace_back(std::move(cert));
76 return ret;
77 };
78 config_->dht = std::make_shared<dht::DhtRunner>();
79 config_->dht->run(dhtConfig, std::move(dhtContext));
80 config_->dht->bootstrap("bootstrap.jami.net");
81 }
82 if (!config_->factory){
83 config_->factory = std::make_shared<IceTransportFactory>(config_->logger);
84 }
85 return config_;
86}
87
Adrien Béraud612b55b2023-05-29 10:42:04 -040088struct ConnectionInfo
89{
90 ~ConnectionInfo()
91 {
92 if (socket_)
93 socket_->join();
94 }
95
96 std::mutex mutex_ {};
97 bool responseReceived_ {false};
98 PeerConnectionRequest response_ {};
99 std::unique_ptr<IceTransport> ice_ {nullptr};
100 // Used to store currently non ready TLS Socket
101 std::unique_ptr<TlsSocketEndpoint> tls_ {nullptr};
102 std::shared_ptr<MultiplexedSocket> socket_ {};
Adrien Béraud75754b22023-10-17 09:16:06 -0400103 std::set<dht::Value::Id> cbIds_ {};
Adrien Béraud612b55b2023-05-29 10:42:04 -0400104
105 std::function<void(bool)> onConnected_;
106 std::unique_ptr<asio::steady_timer> waitForAnswer_ {};
Adrien Béraud75754b22023-10-17 09:16:06 -0400107
108 void shutdown() {
109 std::lock_guard<std::mutex> lk(mutex_);
110 if (tls_)
111 tls_->shutdown();
112 if (socket_)
113 socket_->shutdown();
114 if (waitForAnswer_)
115 waitForAnswer_->cancel();
116 if (ice_) {
117 dht::ThreadPool::io().run(
118 [ice = std::shared_ptr<IceTransport>(std::move(ice_))] {});
119 }
120 }
121
122 std::map<std::string, std::string>
123 getInfo(const DeviceId& deviceId, dht::Value::Id valueId, tls::CertificateStore& certStore) const
124 {
125 std::map<std::string, std::string> connectionInfo;
126 connectionInfo["id"] = callbackIdToString(deviceId, valueId);
127 connectionInfo["device"] = deviceId.toString();
128 auto cert = tls_ ? tls_->peerCertificate() : (socket_ ? socket_->peerCertificate() : nullptr);
129 if (not cert)
130 cert = certStore.getCertificate(deviceId.toString());
131 if (cert) {
132 connectionInfo["peer"] = cert->issuer->getId().toString();
133 }
134 if (socket_) {
135 connectionInfo["status"] = std::to_string(static_cast<int>(ConnectionStatus::Connected));
136 connectionInfo["remoteAddress"] = socket_->getRemoteAddress();
137 } else if (tls_) {
138 connectionInfo["status"] = std::to_string(static_cast<int>(ConnectionStatus::TLS));
139 connectionInfo["remoteAddress"] = tls_->getRemoteAddress();
140 } else if(ice_) {
141 connectionInfo["status"] = std::to_string(static_cast<int>(ConnectionStatus::ICE));
142 connectionInfo["remoteAddress"] = ice_->getRemoteAddress(ICE_COMP_ID_SIP_TRANSPORT);
143 }
144 return connectionInfo;
145 }
Adrien Béraud612b55b2023-05-29 10:42:04 -0400146};
147
Adrien Béraud75754b22023-10-17 09:16:06 -0400148struct PendingCb {
149 std::string name;
150 ConnectCallback cb;
Adrien Béraudb941e922023-10-16 12:56:14 -0400151 bool requested {false};
Adrien Béraud75754b22023-10-17 09:16:06 -0400152};
153
154struct DeviceInfo {
155 const DeviceId deviceId;
156 mutable std::mutex mtx_ {};
157 std::map<dht::Value::Id, std::shared_ptr<ConnectionInfo>> info;
158 std::map<dht::Value::Id, PendingCb> connecting;
159 std::map<dht::Value::Id, PendingCb> waiting;
160 DeviceInfo(DeviceId id) : deviceId {id} {}
161
162 inline bool isConnecting() const {
163 return !connecting.empty() || !waiting.empty();
164 }
165
166 inline bool empty() const {
167 return info.empty() && connecting.empty() && waiting.empty();
168 }
169
170 dht::Value::Id newId(std::mt19937_64& rand) const {
171 ValueIdDist dist(1, ID_MAX_VAL);
172 dht::Value::Id id;
173 do {
174 id = dist(rand);
175 } while (info.find(id) != info.end()
176 || connecting.find(id) != connecting.end()
177 || waiting.find(id) != waiting.end());
178 return id;
179 }
180
181 std::shared_ptr<ConnectionInfo> getConnectedInfo() const {
182 for (auto& [id, ci] : info) {
183 if (ci->socket_)
184 return ci;
185 }
186 return {};
187 }
188
189 std::vector<PendingCb> extractPendingOperations(dht::Value::Id vid, const std::shared_ptr<ChannelSocket>& sock, bool accepted = true)
190 {
191 std::vector<PendingCb> ret;
192 if (vid == 0) {
193 // Extract all pending callbacks
194 ret.reserve(connecting.size() + waiting.size());
195 for (auto& [vid, cb] : connecting)
196 ret.emplace_back(std::move(cb));
197 connecting.clear();
198 for (auto& [vid, cb] : waiting)
199 ret.emplace_back(std::move(cb));
200 waiting.clear();
201 } else if (auto n = waiting.extract(vid)) {
202 // If it's a waiting operation, just move it
203 ret.emplace_back(std::move(n.mapped()));
204 } else if (auto n = connecting.extract(vid)) {
205 ret.emplace_back(std::move(n.mapped()));
206 // If sock is nullptr, execute if it's the last connecting operation
207 // If accepted is false, it means that underlying socket is ok, but channel is declined
208 if (!sock && connecting.empty() && accepted) {
209 for (auto& [vid, cb] : waiting)
210 ret.emplace_back(std::move(cb));
211 waiting.clear();
212 for (auto& [vid, cb] : connecting)
213 ret.emplace_back(std::move(cb));
214 connecting.clear();
215 }
216 }
217 return ret;
218 }
219
220 std::vector<std::shared_ptr<ConnectionInfo>> extractUnusedConnections() {
221 std::vector<std::shared_ptr<ConnectionInfo>> unused {};
222 for (auto& [id, info] : info)
223 unused.emplace_back(std::move(info));
224 info.clear();
225 return unused;
226 }
227
228 void executePendingOperations(std::unique_lock<std::mutex>& lock, dht::Value::Id vid, const std::shared_ptr<ChannelSocket>& sock, bool accepted = true) {
229 auto ops = extractPendingOperations(vid, sock, accepted);
230 lock.unlock();
231 for (auto& cb : ops)
232 cb.cb(sock, deviceId);
233 }
234 void executePendingOperations(dht::Value::Id vid, const std::shared_ptr<ChannelSocket>& sock, bool accepted = true) {
235 std::unique_lock<std::mutex> lock(mtx_);
236 executePendingOperations(lock, vid, sock, accepted);
237 }
238
Adrien Béraudb941e922023-10-16 12:56:14 -0400239 bool isConnecting(const std::string& name) const {
Adrien Béraud75754b22023-10-17 09:16:06 -0400240 for (const auto& [id, pc]: connecting)
Adrien Béraudb941e922023-10-16 12:56:14 -0400241 if (pc.name == name)
242 return true;
Adrien Béraud75754b22023-10-17 09:16:06 -0400243 for (const auto& [id, pc]: waiting)
Adrien Béraudb941e922023-10-16 12:56:14 -0400244 if (pc.name == name)
245 return true;
246 return false;
247 }
248 std::map<dht::Value::Id, std::string> requestPendingOps() {
249 std::map<dht::Value::Id, std::string> ret;
250 for (auto& [id, pc]: connecting) {
251 if (!pc.requested) {
252 ret[id] = pc.name;
253 pc.requested = true;
254 }
255 }
256 for (auto& [id, pc]: waiting) {
257 if (!pc.requested) {
258 ret[id] = pc.name;
259 pc.requested = true;
260 }
261 }
Adrien Béraud75754b22023-10-17 09:16:06 -0400262 return ret;
263 }
264
265 std::vector<std::map<std::string, std::string>>
266 getConnectionList(tls::CertificateStore& certStore) const {
267 std::lock_guard<std::mutex> lk(mtx_);
268 std::vector<std::map<std::string, std::string>> ret;
269 ret.reserve(info.size());
270 for (auto& [id, ci] : info) {
271 std::lock_guard<std::mutex> lk(ci->mutex_);
272 ret.emplace_back(ci->getInfo(deviceId, id, certStore));
273 }
274 auto cert = certStore.getCertificate(deviceId.toString());
275 for (const auto& [vid, ci] : connecting) {
276 ret.emplace_back(std::map<std::string, std::string> {
277 {"id", callbackIdToString(deviceId, vid)},
278 {"status", std::to_string(static_cast<int>(ConnectionStatus::Connecting))},
279 {"device", deviceId.toString()},
280 {"peer", cert ? cert->issuer->getId().toString() : ""}
281 });
282 }
283 for (const auto& [vid, ci] : waiting) {
284 ret.emplace_back(std::map<std::string, std::string> {
285 {"id", callbackIdToString(deviceId, vid)},
286 {"status", std::to_string(static_cast<int>(ConnectionStatus::Waiting))},
287 {"device", deviceId.toString()},
288 {"peer", cert ? cert->issuer->getId().toString() : ""}
289 });
290 }
291 return ret;
292 }
293};
294
295class DeviceInfoSet {
296public:
297 std::shared_ptr<DeviceInfo> getDeviceInfo(const DeviceId& deviceId) {
298 std::lock_guard<std::mutex> lk(mtx_);
299 auto it = infos_.find(deviceId);
300 if (it != infos_.end())
301 return it->second;
302 return {};
303 }
304
305 std::vector<std::shared_ptr<DeviceInfo>> getDeviceInfos() {
306 std::vector<std::shared_ptr<DeviceInfo>> deviceInfos;
307 std::lock_guard<std::mutex> lk(mtx_);
308 deviceInfos.reserve(infos_.size());
309 for (auto& [deviceId, info] : infos_)
310 deviceInfos.emplace_back(info);
311 return deviceInfos;
312 }
313
314 std::shared_ptr<DeviceInfo> createDeviceInfo(const DeviceId& deviceId) {
315 std::lock_guard<std::mutex> lk(mtx_);
316 auto& info = infos_[deviceId];
317 if (!info)
318 info = std::make_shared<DeviceInfo>(deviceId);
319 return info;
320 }
321
322 bool removeDeviceInfo(const DeviceId& deviceId) {
323 std::lock_guard<std::mutex> lk(mtx_);
324 return infos_.erase(deviceId) != 0;
325 }
326
327 std::shared_ptr<ConnectionInfo> getInfo(const DeviceId& deviceId, const dht::Value::Id& id) {
328 if (auto info = getDeviceInfo(deviceId)) {
329 std::lock_guard<std::mutex> lk(info->mtx_);
330 auto it = info->info.find(id);
331 if (it != info->info.end())
332 return it->second;
333 }
334 return {};
335 }
336
337 std::vector<std::shared_ptr<ConnectionInfo>> getConnectedInfos() {
338 auto deviceInfos = getDeviceInfos();
339 std::vector<std::shared_ptr<ConnectionInfo>> ret;
340 ret.reserve(deviceInfos.size());
341 for (auto& info : deviceInfos) {
342 std::lock_guard<std::mutex> lk(info->mtx_);
343 for (auto& [id, ci] : info->info) {
344 if (ci->socket_)
345 ret.emplace_back(ci);
346 }
347 }
348 return ret;
349 }
350 std::vector<std::shared_ptr<DeviceInfo>> shutdown() {
351 std::vector<std::shared_ptr<DeviceInfo>> ret;
352 std::lock_guard<std::mutex> lk(mtx_);
353 ret.reserve(infos_.size());
354 for (auto& [deviceId, info] : infos_) {
355 ret.emplace_back(std::move(info));
356 }
357 infos_.clear();
358 return ret;
359 }
360
361private:
362 std::mutex mtx_ {};
363 std::map<DeviceId, std::shared_ptr<DeviceInfo>> infos_ {};
364};
365
366
Adrien Béraud612b55b2023-05-29 10:42:04 -0400367/**
368 * returns whether or not UPnP is enabled and active_
369 * ie: if it is able to make port mappings
370 */
371bool
372ConnectionManager::Config::getUPnPActive() const
373{
374 if (upnpCtrl)
375 return upnpCtrl->isReady();
376 return false;
377}
378
379class ConnectionManager::Impl : public std::enable_shared_from_this<ConnectionManager::Impl>
380{
381public:
382 explicit Impl(std::shared_ptr<ConnectionManager::Config> config_)
Amna81221ad2023-09-14 17:33:26 -0400383 : config_ {std::move(createConfig(config_))}
Adrien Béraud75754b22023-10-17 09:16:06 -0400384 , rand_ {dht::crypto::getSeededRandomEngine<std::mt19937_64>()}
Kateryna Kostiukc39f6672023-09-15 16:49:42 -0400385 {
Kateryna Kostiukbb300a12023-10-02 13:19:50 -0400386 loadTreatedMessages();
Amna81221ad2023-09-14 17:33:26 -0400387 if(!config_->ioContext) {
388 config_->ioContext = std::make_shared<asio::io_context>();
389 ioContextRunner_ = std::make_unique<std::thread>([context = config_->ioContext, l=config_->logger]() {
390 try {
391 auto work = asio::make_work_guard(*context);
392 context->run();
393 } catch (const std::exception& ex) {
394 if (l) l->error("Exception: {}", ex.what());
395 }
396 });
397 }
Kateryna Kostiukc39f6672023-09-15 16:49:42 -0400398 }
Amna81221ad2023-09-14 17:33:26 -0400399 ~Impl() {
400 if (ioContextRunner_) {
401 if (config_->logger) config_->logger->debug("ConnectionManager: stopping io_context thread");
402 config_->ioContext->stop();
403 ioContextRunner_->join();
404 ioContextRunner_.reset();
405 }
406 }
Adrien Béraud612b55b2023-05-29 10:42:04 -0400407
408 std::shared_ptr<dht::DhtRunner> dht() { return config_->dht; }
409 const dht::crypto::Identity& identity() const { return config_->id; }
410
Adrien Béraud75754b22023-10-17 09:16:06 -0400411 void shutdown()
Adrien Béraud612b55b2023-05-29 10:42:04 -0400412 {
Adrien Béraud75754b22023-10-17 09:16:06 -0400413 if (isDestroying_.exchange(true))
414 return;
415 std::vector<std::shared_ptr<ConnectionInfo>> unused;
416 std::vector<std::pair<DeviceId, std::vector<PendingCb>>> pending;
417 for (auto& dinfo: infos_.shutdown()) {
418 std::lock_guard<std::mutex> lk(dinfo->mtx_);
419 auto p = dinfo->extractPendingOperations(0, nullptr, false);
420 if (!p.empty())
421 pending.emplace_back(dinfo->deviceId, std::move(p));
422 auto uc = dinfo->extractUnusedConnections();
423 unused.insert(unused.end(), std::make_move_iterator(uc.begin()), std::make_move_iterator(uc.end()));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400424 }
Adrien Béraud75754b22023-10-17 09:16:06 -0400425 for (auto& info: unused)
426 info->shutdown();
427 for (auto& op: pending)
428 for (auto& cb: op.second)
429 cb.cb(nullptr, op.first);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400430 if (!unused.empty())
Amna81221ad2023-09-14 17:33:26 -0400431 dht::ThreadPool::io().run([infos = std::move(unused)]() mutable {
432 infos.clear();
433 });
Adrien Béraud612b55b2023-05-29 10:42:04 -0400434 }
435
Adrien Béraud75754b22023-10-17 09:16:06 -0400436 void connectDeviceStartIce(const std::shared_ptr<ConnectionInfo>& info,
437 const std::shared_ptr<dht::crypto::PublicKey>& devicePk,
Adrien Béraud612b55b2023-05-29 10:42:04 -0400438 const dht::Value::Id& vid,
439 const std::string& connType,
440 std::function<void(bool)> onConnected);
Adrien Béraud75754b22023-10-17 09:16:06 -0400441 void onResponse(const asio::error_code& ec, const std::weak_ptr<ConnectionInfo>& info, const DeviceId& deviceId, const dht::Value::Id& vid);
442 bool connectDeviceOnNegoDone(const std::weak_ptr<DeviceInfo>& dinfo,
443 const std::shared_ptr<ConnectionInfo>& info,
444 const DeviceId& deviceId,
Adrien Béraud612b55b2023-05-29 10:42:04 -0400445 const std::string& name,
446 const dht::Value::Id& vid,
447 const std::shared_ptr<dht::crypto::Certificate>& cert);
448 void connectDevice(const DeviceId& deviceId,
449 const std::string& uri,
450 ConnectCallback cb,
451 bool noNewSocket = false,
452 bool forceNewSocket = false,
453 const std::string& connType = "");
Amna0cf544d2023-07-25 14:25:09 -0400454 void connectDevice(const dht::InfoHash& deviceId,
455 const std::string& uri,
456 ConnectCallbackLegacy cb,
457 bool noNewSocket = false,
458 bool forceNewSocket = false,
459 const std::string& connType = "");
460
Adrien Béraud612b55b2023-05-29 10:42:04 -0400461 void connectDevice(const std::shared_ptr<dht::crypto::Certificate>& cert,
462 const std::string& name,
463 ConnectCallback cb,
464 bool noNewSocket = false,
465 bool forceNewSocket = false,
466 const std::string& connType = "");
467 /**
468 * Send a ChannelRequest on the TLS socket. Triggers cb when ready
469 * @param sock socket used to send the request
470 * @param name channel's name
471 * @param vid channel's id
472 * @param deviceId to identify the linked ConnectCallback
473 */
Adrien Béraud75754b22023-10-17 09:16:06 -0400474 void sendChannelRequest(const std::weak_ptr<DeviceInfo>& dinfo,
475 const std::shared_ptr<MultiplexedSocket>& sock,
Adrien Béraud612b55b2023-05-29 10:42:04 -0400476 const std::string& name,
Adrien Béraud612b55b2023-05-29 10:42:04 -0400477 const dht::Value::Id& vid);
478 /**
479 * Triggered when a PeerConnectionRequest comes from the DHT
480 */
481 void answerTo(IceTransport& ice,
482 const dht::Value::Id& id,
483 const std::shared_ptr<dht::crypto::PublicKey>& fromPk);
Adrien Béraud75754b22023-10-17 09:16:06 -0400484 bool onRequestStartIce(const std::shared_ptr<ConnectionInfo>& info, const PeerConnectionRequest& req);
485 bool onRequestOnNegoDone(const std::weak_ptr<DeviceInfo>& dinfo, const std::shared_ptr<ConnectionInfo>& info, const PeerConnectionRequest& req);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400486 void onDhtPeerRequest(const PeerConnectionRequest& req,
487 const std::shared_ptr<dht::crypto::Certificate>& cert);
Adrien Béraud75754b22023-10-17 09:16:06 -0400488 /**
489 * Triggered when a new TLS socket is ready to use
490 * @param ok If succeed
491 * @param deviceId Related device
492 * @param vid vid of the connection request
493 * @param name non empty if TLS was created by connectDevice()
494 */
495 void onTlsNegotiationDone(const std::shared_ptr<DeviceInfo>& dinfo,
496 const std::shared_ptr<ConnectionInfo>& info,
497 bool ok,
498 const DeviceId& deviceId,
499 const dht::Value::Id& vid,
500 const std::string& name = "");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400501
Adrien Béraud75754b22023-10-17 09:16:06 -0400502 void addNewMultiplexedSocket(const std::weak_ptr<DeviceInfo>& dinfo, const DeviceId& deviceId, const dht::Value::Id& vid, const std::shared_ptr<ConnectionInfo>& info);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400503 void onPeerResponse(const PeerConnectionRequest& req);
504 void onDhtConnected(const dht::crypto::PublicKey& devicePk);
505
Adrien Béraud75754b22023-10-17 09:16:06 -0400506
Adrien Béraud612b55b2023-05-29 10:42:04 -0400507 const std::shared_future<tls::DhParams> dhParams() const;
508 tls::CertificateStore& certStore() const { return *config_->certStore; }
509
510 mutable std::mutex messageMutex_ {};
511 std::set<std::string, std::less<>> treatedMessages_ {};
512
513 void loadTreatedMessages();
514 void saveTreatedMessages() const;
515
516 /// \return true if the given DHT message identifier has been treated
517 /// \note if message has not been treated yet this method st/ore this id and returns true at
518 /// further calls
519 bool isMessageTreated(std::string_view id);
520
521 const std::shared_ptr<dht::log::Logger>& logger() const { return config_->logger; }
522
523 /**
524 * Published IPv4/IPv6 addresses, used only if defined by the user in account
525 * configuration
526 *
527 */
528 IpAddr publishedIp_[2] {};
529
Adrien Béraud612b55b2023-05-29 10:42:04 -0400530 /**
531 * interface name on which this account is bound
532 */
533 std::string interface_ {"default"};
534
535 /**
536 * Get the local interface name on which this account is bound.
537 */
538 const std::string& getLocalInterface() const { return interface_; }
539
540 /**
541 * Get the published IP address, fallbacks to NAT if family is unspecified
542 * Prefers the usage of IPv4 if possible.
543 */
544 IpAddr getPublishedIpAddress(uint16_t family = PF_UNSPEC) const;
545
546 /**
547 * Set published IP address according to given family
548 */
549 void setPublishedAddress(const IpAddr& ip_addr);
550
551 /**
552 * Store the local/public addresses used to register
553 */
554 void storeActiveIpAddress(std::function<void()>&& cb = {});
555
556 /**
557 * Create and return ICE options.
558 */
559 void getIceOptions(std::function<void(IceTransportOptions&&)> cb) noexcept;
560 IceTransportOptions getIceOptions() const noexcept;
561
562 /**
563 * Inform that a potential peer device have been found.
564 * Returns true only if the device certificate is a valid device certificate.
565 * In that case (true is returned) the account_id parameter is set to the peer account ID.
566 */
567 static bool foundPeerDevice(const std::shared_ptr<dht::crypto::Certificate>& crt,
568 dht::InfoHash& account_id, const std::shared_ptr<Logger>& logger);
569
570 bool findCertificate(const dht::PkId& id,
571 std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb);
Sébastien Blin34086512023-07-25 09:52:14 -0400572 bool findCertificate(const dht::InfoHash& h, std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400573
574 /**
575 * returns whether or not UPnP is enabled and active
576 * ie: if it is able to make port mappings
577 */
578 bool getUPnPActive() const;
579
Adrien Béraud612b55b2023-05-29 10:42:04 -0400580 std::shared_ptr<ConnectionManager::Config> config_;
Amna81221ad2023-09-14 17:33:26 -0400581 std::unique_ptr<std::thread> ioContextRunner_;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400582
Adrien Béraud75754b22023-10-17 09:16:06 -0400583 mutable std::mutex randMtx_;
584 mutable std::mt19937_64 rand_;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400585
586 iOSConnectedCallback iOSConnectedCb_ {};
587
Adrien Béraud75754b22023-10-17 09:16:06 -0400588 DeviceInfoSet infos_ {};
Adrien Béraud612b55b2023-05-29 10:42:04 -0400589
590 ChannelRequestCallback channelReqCb_ {};
591 ConnectionReadyCallback connReadyCb_ {};
592 onICERequestCallback iceReqCb_ {};
Adrien Béraud612b55b2023-05-29 10:42:04 -0400593 std::atomic_bool isDestroying_ {false};
594};
595
596void
597ConnectionManager::Impl::connectDeviceStartIce(
Adrien Béraud75754b22023-10-17 09:16:06 -0400598 const std::shared_ptr<ConnectionInfo>& info,
Adrien Béraud612b55b2023-05-29 10:42:04 -0400599 const std::shared_ptr<dht::crypto::PublicKey>& devicePk,
600 const dht::Value::Id& vid,
601 const std::string& connType,
602 std::function<void(bool)> onConnected)
603{
604 auto deviceId = devicePk->getLongId();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400605 if (!info) {
606 onConnected(false);
607 return;
608 }
609
610 std::unique_lock<std::mutex> lk(info->mutex_);
611 auto& ice = info->ice_;
612
613 if (!ice) {
614 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -0400615 config_->logger->error("[device {}] No ICE detected", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400616 onConnected(false);
617 return;
618 }
619
620 auto iceAttributes = ice->getLocalAttributes();
621 std::ostringstream icemsg;
622 icemsg << iceAttributes.ufrag << "\n";
623 icemsg << iceAttributes.pwd << "\n";
624 for (const auto& addr : ice->getLocalCandidates(1)) {
625 icemsg << addr << "\n";
626 if (config_->logger)
Sébastien Blinaec46fc2023-07-25 15:43:10 -0400627 config_->logger->debug("[device {}] Added local ICE candidate {}", deviceId, addr);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400628 }
629
630 // Prepare connection request as a DHT message
631 PeerConnectionRequest val;
632
633 val.id = vid; /* Random id for the message unicity */
634 val.ice_msg = icemsg.str();
635 val.connType = connType;
636
637 auto value = std::make_shared<dht::Value>(std::move(val));
638 value->user_type = "peer_request";
639
640 // Send connection request through DHT
641 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -0400642 config_->logger->debug("[device {}] Sending connection request", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400643 dht()->putEncrypted(dht::InfoHash::get(PeerConnectionRequest::key_prefix
644 + devicePk->getId().toString()),
645 devicePk,
646 value,
647 [l=config_->logger,deviceId](bool ok) {
648 if (l)
Adrien Béraud23852462023-07-22 01:46:27 -0400649 l->debug("[device {}] Sent connection request. Put encrypted {:s}",
Adrien Béraud612b55b2023-05-29 10:42:04 -0400650 deviceId,
651 (ok ? "ok" : "failed"));
652 });
653 // Wait for call to onResponse() operated by DHT
654 if (isDestroying_) {
655 onConnected(true); // This avoid to wait new negotiation when destroying
656 return;
657 }
658
659 info->onConnected_ = std::move(onConnected);
660 info->waitForAnswer_ = std::make_unique<asio::steady_timer>(*config_->ioContext,
661 std::chrono::steady_clock::now()
662 + DHT_MSG_TIMEOUT);
663 info->waitForAnswer_->async_wait(
Adrien Béraud75754b22023-10-17 09:16:06 -0400664 std::bind(&ConnectionManager::Impl::onResponse, this, std::placeholders::_1, info, deviceId, vid));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400665}
666
667void
668ConnectionManager::Impl::onResponse(const asio::error_code& ec,
Adrien Béraud75754b22023-10-17 09:16:06 -0400669 const std::weak_ptr<ConnectionInfo>& winfo,
Adrien Béraud612b55b2023-05-29 10:42:04 -0400670 const DeviceId& deviceId,
671 const dht::Value::Id& vid)
672{
673 if (ec == asio::error::operation_aborted)
674 return;
Adrien Béraud75754b22023-10-17 09:16:06 -0400675 auto info = winfo.lock();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400676 if (!info)
677 return;
678
679 std::unique_lock<std::mutex> lk(info->mutex_);
680 auto& ice = info->ice_;
681 if (isDestroying_) {
682 info->onConnected_(true); // The destructor can wake a pending wait here.
683 return;
684 }
685 if (!info->responseReceived_) {
686 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -0400687 config_->logger->error("[device {}] no response from DHT to ICE request.", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400688 info->onConnected_(false);
689 return;
690 }
691
692 if (!info->ice_) {
693 info->onConnected_(false);
694 return;
695 }
696
697 auto sdp = ice->parseIceCandidates(info->response_.ice_msg);
698
699 if (not ice->startIce({sdp.rem_ufrag, sdp.rem_pwd}, std::move(sdp.rem_candidates))) {
700 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -0400701 config_->logger->warn("[device {}] start ICE failed", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400702 info->onConnected_(false);
703 return;
704 }
705 info->onConnected_(true);
706}
707
708bool
709ConnectionManager::Impl::connectDeviceOnNegoDone(
Adrien Béraud75754b22023-10-17 09:16:06 -0400710 const std::weak_ptr<DeviceInfo>& dinfo,
711 const std::shared_ptr<ConnectionInfo>& info,
Adrien Béraud612b55b2023-05-29 10:42:04 -0400712 const DeviceId& deviceId,
713 const std::string& name,
714 const dht::Value::Id& vid,
715 const std::shared_ptr<dht::crypto::Certificate>& cert)
716{
Adrien Béraud612b55b2023-05-29 10:42:04 -0400717 if (!info)
718 return false;
719
720 std::unique_lock<std::mutex> lk {info->mutex_};
721 if (info->waitForAnswer_) {
722 // Negotiation is done and connected, go to handshake
723 // and avoid any cancellation at this point.
724 info->waitForAnswer_->cancel();
725 }
726 auto& ice = info->ice_;
727 if (!ice || !ice->isRunning()) {
728 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -0400729 config_->logger->error("[device {}] No ICE detected or not running", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400730 return false;
731 }
732
733 // Build socket
734 auto endpoint = std::make_unique<IceSocketEndpoint>(std::shared_ptr<IceTransport>(
735 std::move(ice)),
736 true);
737
738 // Negotiate a TLS session
739 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -0400740 config_->logger->debug("[device {}] Start TLS session - Initied by connectDevice(). Launched by channel: {} - vid: {}", deviceId, name, vid);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400741 info->tls_ = std::make_unique<TlsSocketEndpoint>(std::move(endpoint),
742 certStore(),
Adrien Béraud3f93ddf2023-07-21 14:46:22 -0400743 config_->ioContext,
Adrien Béraud612b55b2023-05-29 10:42:04 -0400744 identity(),
745 dhParams(),
746 *cert);
747
748 info->tls_->setOnReady(
Adrien Béraud75754b22023-10-17 09:16:06 -0400749 [w = weak_from_this(), dinfo, winfo=std::weak_ptr(info), deviceId = std::move(deviceId), vid = std::move(vid), name = std::move(name)](
Adrien Béraud612b55b2023-05-29 10:42:04 -0400750 bool ok) {
751 if (auto shared = w.lock())
Adrien Béraud75754b22023-10-17 09:16:06 -0400752 shared->onTlsNegotiationDone(dinfo.lock(), winfo.lock(), ok, deviceId, vid, name);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400753 });
754 return true;
755}
756
757void
758ConnectionManager::Impl::connectDevice(const DeviceId& deviceId,
759 const std::string& name,
760 ConnectCallback cb,
761 bool noNewSocket,
762 bool forceNewSocket,
763 const std::string& connType)
764{
765 if (!dht()) {
766 cb(nullptr, deviceId);
767 return;
768 }
769 if (deviceId.toString() == identity().second->getLongId().toString()) {
770 cb(nullptr, deviceId);
771 return;
772 }
773 findCertificate(deviceId,
Adrien Béraud75754b22023-10-17 09:16:06 -0400774 [w = weak_from_this(),
Adrien Béraud612b55b2023-05-29 10:42:04 -0400775 deviceId,
776 name,
777 cb = std::move(cb),
778 noNewSocket,
779 forceNewSocket,
780 connType](const std::shared_ptr<dht::crypto::Certificate>& cert) {
781 if (!cert) {
782 if (auto shared = w.lock())
783 if (shared->config_->logger)
784 shared->config_->logger->error(
785 "No valid certificate found for device {}",
786 deviceId);
787 cb(nullptr, deviceId);
788 return;
789 }
790 if (auto shared = w.lock()) {
791 shared->connectDevice(cert,
792 name,
793 std::move(cb),
794 noNewSocket,
795 forceNewSocket,
796 connType);
797 } else
798 cb(nullptr, deviceId);
799 });
800}
801
802void
Amna0cf544d2023-07-25 14:25:09 -0400803ConnectionManager::Impl::connectDevice(const dht::InfoHash& deviceId,
804 const std::string& name,
805 ConnectCallbackLegacy cb,
806 bool noNewSocket,
807 bool forceNewSocket,
808 const std::string& connType)
809{
810 if (!dht()) {
811 cb(nullptr, deviceId);
812 return;
813 }
814 if (deviceId.toString() == identity().second->getLongId().toString()) {
815 cb(nullptr, deviceId);
816 return;
817 }
818 findCertificate(deviceId,
Adrien Béraud75754b22023-10-17 09:16:06 -0400819 [w = weak_from_this(),
Amna0cf544d2023-07-25 14:25:09 -0400820 deviceId,
821 name,
822 cb = std::move(cb),
823 noNewSocket,
824 forceNewSocket,
825 connType](const std::shared_ptr<dht::crypto::Certificate>& cert) {
826 if (!cert) {
827 if (auto shared = w.lock())
828 if (shared->config_->logger)
829 shared->config_->logger->error(
830 "No valid certificate found for device {}",
831 deviceId);
832 cb(nullptr, deviceId);
833 return;
834 }
835 if (auto shared = w.lock()) {
836 shared->connectDevice(cert,
837 name,
Adrien Béraudd78d1ac2023-08-25 10:43:33 -0400838 [cb, deviceId](const std::shared_ptr<ChannelSocket>& sock, const DeviceId& /*did*/){
Amna0cf544d2023-07-25 14:25:09 -0400839 cb(sock, deviceId);
840 },
841 noNewSocket,
842 forceNewSocket,
843 connType);
844 } else
845 cb(nullptr, deviceId);
846 });
847}
848
849void
Adrien Béraud612b55b2023-05-29 10:42:04 -0400850ConnectionManager::Impl::connectDevice(const std::shared_ptr<dht::crypto::Certificate>& cert,
851 const std::string& name,
852 ConnectCallback cb,
853 bool noNewSocket,
854 bool forceNewSocket,
855 const std::string& connType)
856{
857 // Avoid dht operation in a DHT callback to avoid deadlocks
Adrien Béraud75754b22023-10-17 09:16:06 -0400858 dht::ThreadPool::computation().run([w = weak_from_this(),
Adrien Béraud612b55b2023-05-29 10:42:04 -0400859 name = std::move(name),
860 cert = std::move(cert),
861 cb = std::move(cb),
862 noNewSocket,
863 forceNewSocket,
864 connType] {
865 auto devicePk = cert->getSharedPublicKey();
866 auto deviceId = devicePk->getLongId();
867 auto sthis = w.lock();
868 if (!sthis || sthis->isDestroying_) {
869 cb(nullptr, deviceId);
870 return;
871 }
Adrien Béraud75754b22023-10-17 09:16:06 -0400872 auto di = sthis->infos_.createDeviceInfo(deviceId);
873 std::unique_lock<std::mutex> lk(di->mtx_);
874
Adrien Béraud26365c92023-09-23 23:42:43 -0400875 dht::Value::Id vid;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400876 {
Adrien Béraud75754b22023-10-17 09:16:06 -0400877 std::lock_guard<std::mutex> lkr(sthis->randMtx_);
878 vid = di->newId(sthis->rand_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400879 }
880
Adrien Béraud75754b22023-10-17 09:16:06 -0400881 // Check if already connecting
882 auto isConnectingToDevice = di->isConnecting();
883 // Note: we can be in a state where first
884 // socket is negotiated and first channel is pending
885 // so return only after we checked the info
Adrien Béraudb941e922023-10-16 12:56:14 -0400886 auto& diw = (isConnectingToDevice && !forceNewSocket)
887 ? di->waiting[vid]
888 : di->connecting[vid];
889 diw = PendingCb {name, std::move(cb)};
890
Adrien Béraud612b55b2023-05-29 10:42:04 -0400891 // Check if already negotiated
Adrien Béraud75754b22023-10-17 09:16:06 -0400892 if (auto info = di->getConnectedInfo()) {
893 std::unique_lock<std::mutex> lkc(info->mutex_);
894 if (auto sock = info->socket_) {
895 info->cbIds_.emplace(vid);
Adrien Béraudb941e922023-10-16 12:56:14 -0400896 diw.requested = true;
Adrien Béraud75754b22023-10-17 09:16:06 -0400897 lkc.unlock();
898 lk.unlock();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400899 if (sthis->config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -0400900 sthis->config_->logger->debug("[device {}] Peer already connected. Add a new channel", deviceId);
Adrien Béraud75754b22023-10-17 09:16:06 -0400901 sthis->sendChannelRequest(di, sock, name, vid);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400902 return;
903 }
904 }
905
906 if (isConnectingToDevice && !forceNewSocket) {
907 if (sthis->config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -0400908 sthis->config_->logger->debug("[device {}] Already connecting, wait for ICE negotiation", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400909 return;
910 }
911 if (noNewSocket) {
912 // If no new socket is specified, we don't try to generate a new socket
Adrien Béraud75754b22023-10-17 09:16:06 -0400913 di->executePendingOperations(lk, vid, nullptr);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400914 return;
915 }
916
917 // Note: used when the ice negotiation fails to erase
918 // all stored structures.
Adrien Béraud75754b22023-10-17 09:16:06 -0400919 auto eraseInfo = [w, diw=std::weak_ptr(di), vid] {
920 if (auto di = diw.lock()) {
921 std::unique_lock<std::mutex> lk(di->mtx_);
922 di->info.erase(vid);
923 auto ops = di->extractPendingOperations(vid, nullptr);
924 if (di->empty()) {
925 if (auto shared = w.lock())
926 shared->infos_.removeDeviceInfo(di->deviceId);
927 }
928 lk.unlock();
929 for (const auto& op: ops)
930 op.cb(nullptr, di->deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400931 }
932 };
933
934 // If no socket exists, we need to initiate an ICE connection.
935 sthis->getIceOptions([w,
936 deviceId = std::move(deviceId),
937 devicePk = std::move(devicePk),
Adrien Béraud75754b22023-10-17 09:16:06 -0400938 diw=std::weak_ptr(di),
Adrien Béraud612b55b2023-05-29 10:42:04 -0400939 name = std::move(name),
940 cert = std::move(cert),
941 vid,
942 connType,
943 eraseInfo](auto&& ice_config) {
944 auto sthis = w.lock();
945 if (!sthis) {
946 dht::ThreadPool::io().run([eraseInfo = std::move(eraseInfo)] { eraseInfo(); });
947 return;
948 }
Adrien Béraud75754b22023-10-17 09:16:06 -0400949 auto info = std::make_shared<ConnectionInfo>();
950 auto winfo = std::weak_ptr(info);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400951 ice_config.tcpEnable = true;
952 ice_config.onInitDone = [w,
Adrien Béraud612b55b2023-05-29 10:42:04 -0400953 devicePk = std::move(devicePk),
954 name = std::move(name),
955 cert = std::move(cert),
Adrien Béraud75754b22023-10-17 09:16:06 -0400956 diw,
957 winfo = std::weak_ptr(info),
Adrien Béraud612b55b2023-05-29 10:42:04 -0400958 vid,
959 connType,
960 eraseInfo](bool ok) {
961 dht::ThreadPool::io().run([w = std::move(w),
962 devicePk = std::move(devicePk),
Adrien Béraud75754b22023-10-17 09:16:06 -0400963 vid,
964 winfo,
Adrien Béraud612b55b2023-05-29 10:42:04 -0400965 eraseInfo,
966 connType, ok] {
967 auto sthis = w.lock();
968 if (!ok && sthis && sthis->config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -0400969 sthis->config_->logger->error("[device {}] Cannot initialize ICE session.", devicePk->getLongId());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400970 if (!sthis || !ok) {
971 eraseInfo();
972 return;
973 }
Adrien Béraud75754b22023-10-17 09:16:06 -0400974 sthis->connectDeviceStartIce(winfo.lock(), devicePk, vid, connType, [=](bool ok) {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400975 if (!ok) {
976 dht::ThreadPool::io().run([eraseInfo = std::move(eraseInfo)] { eraseInfo(); });
977 }
978 });
979 });
980 };
981 ice_config.onNegoDone = [w,
982 deviceId,
983 name,
984 cert = std::move(cert),
Adrien Béraud75754b22023-10-17 09:16:06 -0400985 diw,
986 winfo = std::weak_ptr(info),
Adrien Béraud612b55b2023-05-29 10:42:04 -0400987 vid,
988 eraseInfo](bool ok) {
989 dht::ThreadPool::io().run([w = std::move(w),
990 deviceId = std::move(deviceId),
991 name = std::move(name),
992 cert = std::move(cert),
Adrien Béraud75754b22023-10-17 09:16:06 -0400993 diw = std::move(diw),
994 winfo = std::move(winfo),
Adrien Béraud612b55b2023-05-29 10:42:04 -0400995 vid = std::move(vid),
996 eraseInfo = std::move(eraseInfo),
997 ok] {
998 auto sthis = w.lock();
999 if (!ok && sthis && sthis->config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001000 sthis->config_->logger->error("[device {}] ICE negotiation failed.", deviceId);
Adrien Béraud75754b22023-10-17 09:16:06 -04001001 if (!sthis || !ok || !sthis->connectDeviceOnNegoDone(diw, winfo.lock(), deviceId, name, vid, cert))
Adrien Béraud612b55b2023-05-29 10:42:04 -04001002 eraseInfo();
1003 });
1004 };
1005
Adrien Béraud75754b22023-10-17 09:16:06 -04001006 if (auto di = diw.lock()) {
1007 std::lock_guard<std::mutex> lk(di->mtx_);
1008 di->info[vid] = info;
Adrien Béraud612b55b2023-05-29 10:42:04 -04001009 }
1010 std::unique_lock<std::mutex> lk {info->mutex_};
1011 ice_config.master = false;
1012 ice_config.streamsCount = 1;
1013 ice_config.compCountPerStream = 1;
Sébastien Blin34086512023-07-25 09:52:14 -04001014 info->ice_ = sthis->config_->factory->createUTransport("");
Adrien Béraud612b55b2023-05-29 10:42:04 -04001015 if (!info->ice_) {
1016 if (sthis->config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001017 sthis->config_->logger->error("[device {}] Cannot initialize ICE session.", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001018 eraseInfo();
1019 return;
1020 }
1021 // We need to detect any shutdown if the ice session is destroyed before going to the
1022 // TLS session;
1023 info->ice_->setOnShutdown([eraseInfo]() {
1024 dht::ThreadPool::io().run([eraseInfo = std::move(eraseInfo)] { eraseInfo(); });
1025 });
Adrien Béraud4cda2d72023-06-01 15:44:43 -04001026 try {
1027 info->ice_->initIceInstance(ice_config);
1028 } catch (const std::exception& e) {
1029 if (sthis->config_->logger)
1030 sthis->config_->logger->error("{}", e.what());
1031 dht::ThreadPool::io().run([eraseInfo = std::move(eraseInfo)] { eraseInfo(); });
1032 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001033 });
1034 });
1035}
1036
1037void
Adrien Béraud75754b22023-10-17 09:16:06 -04001038ConnectionManager::Impl::sendChannelRequest(const std::weak_ptr<DeviceInfo>& dinfo,
1039 const std::shared_ptr<MultiplexedSocket>& sock,
Adrien Béraud612b55b2023-05-29 10:42:04 -04001040 const std::string& name,
Adrien Béraud612b55b2023-05-29 10:42:04 -04001041 const dht::Value::Id& vid)
1042{
1043 auto channelSock = sock->addChannel(name);
Adrien Béraud75754b22023-10-17 09:16:06 -04001044 channelSock->onShutdown([dinfo, name, vid] {
1045 if (auto info = dinfo.lock())
1046 info->executePendingOperations(vid, nullptr);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001047 });
1048 channelSock->onReady(
Adrien Béraud75754b22023-10-17 09:16:06 -04001049 [dinfo, wSock = std::weak_ptr(channelSock), name, vid](bool accepted) {
1050 if (auto info = dinfo.lock())
1051 info->executePendingOperations(vid, accepted ? wSock.lock() : nullptr, accepted);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001052 });
1053
1054 ChannelRequest val;
1055 val.name = channelSock->name();
1056 val.state = ChannelRequestState::REQUEST;
1057 val.channel = channelSock->channel();
1058 msgpack::sbuffer buffer(256);
1059 msgpack::pack(buffer, val);
1060
1061 std::error_code ec;
1062 int res = sock->write(CONTROL_CHANNEL,
1063 reinterpret_cast<const uint8_t*>(buffer.data()),
1064 buffer.size(),
1065 ec);
1066 if (res < 0) {
1067 // TODO check if we should handle errors here
1068 if (config_->logger)
Adrien Béraud75754b22023-10-17 09:16:06 -04001069 config_->logger->error("sendChannelRequest failed - error: {}", ec.message());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001070 }
1071}
1072
1073void
1074ConnectionManager::Impl::onPeerResponse(const PeerConnectionRequest& req)
1075{
1076 auto device = req.owner->getLongId();
Adrien Béraud75754b22023-10-17 09:16:06 -04001077 if (auto info = infos_.getInfo(device, req.id)) {
Adrien Béraud23852462023-07-22 01:46:27 -04001078 if (config_->logger)
1079 config_->logger->debug("[device {}] New response received", device);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001080 std::lock_guard<std::mutex> lk {info->mutex_};
1081 info->responseReceived_ = true;
1082 info->response_ = std::move(req);
1083 info->waitForAnswer_->expires_at(std::chrono::steady_clock::now());
1084 info->waitForAnswer_->async_wait(std::bind(&ConnectionManager::Impl::onResponse,
1085 this,
1086 std::placeholders::_1,
Adrien Béraud75754b22023-10-17 09:16:06 -04001087 std::weak_ptr(info),
Adrien Béraud612b55b2023-05-29 10:42:04 -04001088 device,
1089 req.id));
1090 } else {
1091 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001092 config_->logger->warn("[device {}] Respond received, but cannot find request", device);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001093 }
1094}
1095
1096void
1097ConnectionManager::Impl::onDhtConnected(const dht::crypto::PublicKey& devicePk)
1098{
1099 if (!dht())
1100 return;
1101 dht()->listen<PeerConnectionRequest>(
1102 dht::InfoHash::get(PeerConnectionRequest::key_prefix + devicePk.getId().toString()),
Adrien Béraud75754b22023-10-17 09:16:06 -04001103 [w = weak_from_this()](PeerConnectionRequest&& req) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001104 auto shared = w.lock();
1105 if (!shared)
1106 return false;
1107 if (shared->isMessageTreated(to_hex_string(req.id))) {
1108 // Message already treated. Just ignore
1109 return true;
1110 }
1111 if (req.isAnswer) {
1112 if (shared->config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001113 shared->config_->logger->debug("[device {}] Received request answer", req.owner->getLongId());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001114 } else {
1115 if (shared->config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001116 shared->config_->logger->debug("[device {}] Received request", req.owner->getLongId());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001117 }
1118 if (req.isAnswer) {
1119 shared->onPeerResponse(req);
1120 } else {
1121 // Async certificate checking
Sébastien Blin34086512023-07-25 09:52:14 -04001122 shared->findCertificate(
Adrien Béraud612b55b2023-05-29 10:42:04 -04001123 req.from,
1124 [w, req = std::move(req)](
1125 const std::shared_ptr<dht::crypto::Certificate>& cert) mutable {
1126 auto shared = w.lock();
1127 if (!shared)
1128 return;
1129 dht::InfoHash peer_h;
1130 if (foundPeerDevice(cert, peer_h, shared->config_->logger)) {
1131#if TARGET_OS_IOS
1132 if (shared->iOSConnectedCb_(req.connType, peer_h))
1133 return;
1134#endif
1135 shared->onDhtPeerRequest(req, cert);
1136 } else {
1137 if (shared->config_->logger)
1138 shared->config_->logger->warn(
Adrien Béraud23852462023-07-22 01:46:27 -04001139 "[device {}] Received request from untrusted peer",
Adrien Béraud612b55b2023-05-29 10:42:04 -04001140 req.owner->getLongId());
1141 }
1142 });
1143 }
1144
1145 return true;
1146 },
1147 dht::Value::UserTypeFilter("peer_request"));
1148}
1149
1150void
Adrien Béraud75754b22023-10-17 09:16:06 -04001151ConnectionManager::Impl::onTlsNegotiationDone(const std::shared_ptr<DeviceInfo>& dinfo,
1152 const std::shared_ptr<ConnectionInfo>& info,
1153 bool ok,
Adrien Béraud612b55b2023-05-29 10:42:04 -04001154 const DeviceId& deviceId,
1155 const dht::Value::Id& vid,
1156 const std::string& name)
1157{
1158 if (isDestroying_)
1159 return;
1160 // Note: only handle pendingCallbacks here for TLS initied by connectDevice()
1161 // Note: if not initied by connectDevice() the channel name will be empty (because no channel
1162 // asked yet)
1163 auto isDhtRequest = name.empty();
1164 if (!ok) {
1165 if (isDhtRequest) {
1166 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001167 config_->logger->error("[device {}] TLS connection failure - Initied by DHT request. channel: {} - vid: {}",
Adrien Béraud612b55b2023-05-29 10:42:04 -04001168 deviceId,
1169 name,
1170 vid);
1171 if (connReadyCb_)
1172 connReadyCb_(deviceId, "", nullptr);
1173 } else {
1174 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001175 config_->logger->error("[device {}] TLS connection failure - Initied by connectDevice. channel: {} - vid: {}",
Adrien Béraud612b55b2023-05-29 10:42:04 -04001176 deviceId,
1177 name,
1178 vid);
Adrien Béraud75754b22023-10-17 09:16:06 -04001179 dinfo->executePendingOperations(vid, nullptr);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001180 }
1181 } else {
1182 // The socket is ready, store it
1183 if (isDhtRequest) {
1184 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001185 config_->logger->debug("[device {}] Connection is ready - Initied by DHT request. Vid: {}",
Adrien Béraud612b55b2023-05-29 10:42:04 -04001186 deviceId,
1187 vid);
1188 } else {
1189 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001190 config_->logger->debug("[device {}] Connection is ready - Initied by connectDevice(). channel: {} - vid: {}",
Adrien Béraud612b55b2023-05-29 10:42:04 -04001191 deviceId,
1192 name,
1193 vid);
1194 }
1195
Adrien Béraud75754b22023-10-17 09:16:06 -04001196 // Note: do not remove pending there it's done in sendChannelRequest
1197 std::unique_lock<std::mutex> lk2 {dinfo->mtx_};
Adrien Béraudb941e922023-10-16 12:56:14 -04001198 auto pendingIds = dinfo->requestPendingOps();
Adrien Béraud75754b22023-10-17 09:16:06 -04001199 lk2.unlock();
1200 std::unique_lock<std::mutex> lk {info->mutex_};
1201 addNewMultiplexedSocket(dinfo, deviceId, vid, info);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001202 // Finally, open the channel and launch pending callbacks
Adrien Béraud75754b22023-10-17 09:16:06 -04001203 lk.unlock();
1204 for (const auto& [id, name]: pendingIds) {
1205 if (config_->logger)
1206 config_->logger->debug("[device {}] Send request on TLS socket for channel {}",
1207 deviceId, name);
1208 sendChannelRequest(dinfo, info->socket_, name, id);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001209 }
1210 }
1211}
1212
1213void
1214ConnectionManager::Impl::answerTo(IceTransport& ice,
1215 const dht::Value::Id& id,
1216 const std::shared_ptr<dht::crypto::PublicKey>& from)
1217{
1218 // NOTE: This is a shortest version of a real SDP message to save some bits
1219 auto iceAttributes = ice.getLocalAttributes();
1220 std::ostringstream icemsg;
1221 icemsg << iceAttributes.ufrag << "\n";
1222 icemsg << iceAttributes.pwd << "\n";
1223 for (const auto& addr : ice.getLocalCandidates(1)) {
1224 icemsg << addr << "\n";
1225 }
1226
1227 // Send PeerConnection response
1228 PeerConnectionRequest val;
1229 val.id = id;
1230 val.ice_msg = icemsg.str();
1231 val.isAnswer = true;
1232 auto value = std::make_shared<dht::Value>(std::move(val));
1233 value->user_type = "peer_request";
1234
1235 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001236 config_->logger->debug("[device {}] Connection accepted, DHT reply", from->getLongId());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001237 dht()->putEncrypted(dht::InfoHash::get(PeerConnectionRequest::key_prefix
1238 + from->getId().toString()),
1239 from,
1240 value,
1241 [from,l=config_->logger](bool ok) {
1242 if (l)
Adrien Béraud23852462023-07-22 01:46:27 -04001243 l->debug("[device {}] Answer to connection request: put encrypted {:s}",
Adrien Béraud612b55b2023-05-29 10:42:04 -04001244 from->getLongId(),
1245 (ok ? "ok" : "failed"));
1246 });
1247}
1248
1249bool
Adrien Béraud75754b22023-10-17 09:16:06 -04001250ConnectionManager::Impl::onRequestStartIce(const std::shared_ptr<ConnectionInfo>& info, const PeerConnectionRequest& req)
Adrien Béraud612b55b2023-05-29 10:42:04 -04001251{
Adrien Béraud612b55b2023-05-29 10:42:04 -04001252 if (!info)
1253 return false;
1254
Adrien Béraud75754b22023-10-17 09:16:06 -04001255 auto deviceId = req.owner->getLongId();
Adrien Béraud612b55b2023-05-29 10:42:04 -04001256 std::unique_lock<std::mutex> lk {info->mutex_};
1257 auto& ice = info->ice_;
1258 if (!ice) {
1259 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001260 config_->logger->error("[device {}] No ICE detected", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001261 if (connReadyCb_)
1262 connReadyCb_(deviceId, "", nullptr);
1263 return false;
1264 }
1265
1266 auto sdp = ice->parseIceCandidates(req.ice_msg);
1267 answerTo(*ice, req.id, req.owner);
1268 if (not ice->startIce({sdp.rem_ufrag, sdp.rem_pwd}, std::move(sdp.rem_candidates))) {
1269 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001270 config_->logger->error("[device {}] Start ICE failed", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001271 ice = nullptr;
1272 if (connReadyCb_)
1273 connReadyCb_(deviceId, "", nullptr);
1274 return false;
1275 }
1276 return true;
1277}
1278
1279bool
Adrien Béraud75754b22023-10-17 09:16:06 -04001280ConnectionManager::Impl::onRequestOnNegoDone(const std::weak_ptr<DeviceInfo>& dinfo, const std::shared_ptr<ConnectionInfo>& info, const PeerConnectionRequest& req)
Adrien Béraud612b55b2023-05-29 10:42:04 -04001281{
Adrien Béraud612b55b2023-05-29 10:42:04 -04001282 if (!info)
1283 return false;
1284
Adrien Béraud75754b22023-10-17 09:16:06 -04001285 auto deviceId = req.owner->getLongId();
Adrien Béraud612b55b2023-05-29 10:42:04 -04001286 std::unique_lock<std::mutex> lk {info->mutex_};
1287 auto& ice = info->ice_;
1288 if (!ice) {
1289 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001290 config_->logger->error("[device {}] No ICE detected", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001291 return false;
1292 }
1293
1294 // Build socket
1295 auto endpoint = std::make_unique<IceSocketEndpoint>(std::shared_ptr<IceTransport>(
1296 std::move(ice)),
1297 false);
1298
1299 // init TLS session
1300 auto ph = req.from;
1301 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001302 config_->logger->debug("[device {}] Start TLS session - Initied by DHT request. vid: {}",
1303 deviceId,
Adrien Béraud612b55b2023-05-29 10:42:04 -04001304 req.id);
1305 info->tls_ = std::make_unique<TlsSocketEndpoint>(
1306 std::move(endpoint),
1307 certStore(),
Adrien Béraud3f93ddf2023-07-21 14:46:22 -04001308 config_->ioContext,
Adrien Béraud612b55b2023-05-29 10:42:04 -04001309 identity(),
1310 dhParams(),
Adrien Béraud75754b22023-10-17 09:16:06 -04001311 [ph, deviceId, w=weak_from_this(), l=config_->logger](const dht::crypto::Certificate& cert) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001312 auto shared = w.lock();
1313 if (!shared)
1314 return false;
Adrien Béraud9efbd442023-08-27 12:38:07 -04001315 if (cert.getPublicKey().getId() != ph
1316 || deviceId != cert.getPublicKey().getLongId()) {
1317 if (l) l->warn("[device {}] TLS certificate with ID {} doesn't match the DHT request.",
1318 deviceId,
1319 cert.getPublicKey().getLongId());
1320 return false;
1321 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001322 auto crt = shared->certStore().getCertificate(cert.getLongId().toString());
1323 if (!crt)
1324 return false;
1325 return crt->getPacked() == cert.getPacked();
1326 });
1327
1328 info->tls_->setOnReady(
Adrien Béraud75754b22023-10-17 09:16:06 -04001329 [w = weak_from_this(), dinfo, winfo=std::weak_ptr(info), deviceId = std::move(deviceId), vid = std::move(req.id)](bool ok) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001330 if (auto shared = w.lock())
Adrien Béraud75754b22023-10-17 09:16:06 -04001331 shared->onTlsNegotiationDone(dinfo.lock(), winfo.lock(), ok, deviceId, vid);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001332 });
1333 return true;
1334}
1335
1336void
1337ConnectionManager::Impl::onDhtPeerRequest(const PeerConnectionRequest& req,
1338 const std::shared_ptr<dht::crypto::Certificate>& /*cert*/)
1339{
1340 auto deviceId = req.owner->getLongId();
1341 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001342 config_->logger->debug("[device {}] New connection request", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001343 if (!iceReqCb_ || !iceReqCb_(deviceId)) {
1344 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001345 config_->logger->debug("[device {}] Refusing connection", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001346 return;
1347 }
1348
1349 // Because the connection is accepted, create an ICE socket.
Adrien Béraud75754b22023-10-17 09:16:06 -04001350 getIceOptions([w = weak_from_this(), req, deviceId](auto&& ice_config) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001351 auto shared = w.lock();
1352 if (!shared)
1353 return;
Adrien Béraud75754b22023-10-17 09:16:06 -04001354
1355 auto di = shared->infos_.createDeviceInfo(deviceId);
1356 auto info = std::make_shared<ConnectionInfo>();
1357 auto wdi = std::weak_ptr(di);
1358 auto winfo = std::weak_ptr(info);
1359
Adrien Béraud612b55b2023-05-29 10:42:04 -04001360 // Note: used when the ice negotiation fails to erase
1361 // all stored structures.
Adrien Béraud75754b22023-10-17 09:16:06 -04001362 auto eraseInfo = [w, wdi, id = req.id] {
1363 auto shared = w.lock();
1364 if (auto di = wdi.lock()) {
1365 std::unique_lock<std::mutex> lk(di->mtx_);
1366 di->info.erase(id);
1367 auto ops = di->extractPendingOperations(id, nullptr);
1368 if (di->empty()) {
1369 if (shared)
1370 shared->infos_.removeDeviceInfo(di->deviceId);
1371 }
1372 lk.unlock();
1373 for (const auto& op: ops)
1374 op.cb(nullptr, di->deviceId);
1375 if (shared && shared->connReadyCb_)
1376 shared->connReadyCb_(di->deviceId, "", nullptr);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001377 }
1378 };
1379
Adrien Béraud75754b22023-10-17 09:16:06 -04001380 ice_config.master = true;
1381 ice_config.streamsCount = 1;
1382 ice_config.compCountPerStream = 1; // TCP
Adrien Béraud612b55b2023-05-29 10:42:04 -04001383 ice_config.tcpEnable = true;
Adrien Béraud75754b22023-10-17 09:16:06 -04001384 ice_config.onInitDone = [w, winfo, req, eraseInfo](bool ok) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001385 auto shared = w.lock();
1386 if (!shared)
1387 return;
1388 if (!ok) {
1389 if (shared->config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001390 shared->config_->logger->error("[device {}] Cannot initialize ICE session.", req.owner->getLongId());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001391 dht::ThreadPool::io().run([eraseInfo = std::move(eraseInfo)] { eraseInfo(); });
1392 return;
1393 }
1394
1395 dht::ThreadPool::io().run(
Adrien Béraud75754b22023-10-17 09:16:06 -04001396 [w = std::move(w), winfo = std::move(winfo), req = std::move(req), eraseInfo = std::move(eraseInfo)] {
1397 if (auto shared = w.lock()) {
1398 if (!shared->onRequestStartIce(winfo.lock(), req))
1399 eraseInfo();
1400 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001401 });
1402 };
1403
Adrien Béraud75754b22023-10-17 09:16:06 -04001404 ice_config.onNegoDone = [w, wdi, winfo, req, eraseInfo](bool ok) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001405 auto shared = w.lock();
1406 if (!shared)
1407 return;
1408 if (!ok) {
1409 if (shared->config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001410 shared->config_->logger->error("[device {}] ICE negotiation failed.", req.owner->getLongId());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001411 dht::ThreadPool::io().run([eraseInfo = std::move(eraseInfo)] { eraseInfo(); });
1412 return;
1413 }
1414
1415 dht::ThreadPool::io().run(
Adrien Béraud75754b22023-10-17 09:16:06 -04001416 [w = std::move(w), wdi = std::move(wdi), winfo = std::move(winfo), req = std::move(req), eraseInfo = std::move(eraseInfo)] {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001417 if (auto shared = w.lock())
Adrien Béraud75754b22023-10-17 09:16:06 -04001418 if (!shared->onRequestOnNegoDone(wdi.lock(), winfo.lock(), req))
Adrien Béraud612b55b2023-05-29 10:42:04 -04001419 eraseInfo();
1420 });
1421 };
1422
1423 // Negotiate a new ICE socket
Adrien Béraud612b55b2023-05-29 10:42:04 -04001424 {
Adrien Béraud75754b22023-10-17 09:16:06 -04001425 std::lock_guard<std::mutex> lk(di->mtx_);
1426 di->info[req.id] = info;
Adrien Béraud612b55b2023-05-29 10:42:04 -04001427 }
Adrien Béraud75754b22023-10-17 09:16:06 -04001428
Adrien Béraud612b55b2023-05-29 10:42:04 -04001429 if (shared->config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001430 shared->config_->logger->debug("[device {}] Accepting connection", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001431 std::unique_lock<std::mutex> lk {info->mutex_};
Sébastien Blin34086512023-07-25 09:52:14 -04001432 info->ice_ = shared->config_->factory->createUTransport("");
Adrien Béraud612b55b2023-05-29 10:42:04 -04001433 if (not info->ice_) {
1434 if (shared->config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001435 shared->config_->logger->error("[device {}] Cannot initialize ICE session", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001436 eraseInfo();
1437 return;
1438 }
1439 // We need to detect any shutdown if the ice session is destroyed before going to the TLS session;
1440 info->ice_->setOnShutdown([eraseInfo]() {
1441 dht::ThreadPool::io().run([eraseInfo = std::move(eraseInfo)] { eraseInfo(); });
1442 });
Adrien Béraud4cda2d72023-06-01 15:44:43 -04001443 try {
1444 info->ice_->initIceInstance(ice_config);
1445 } catch (const std::exception& e) {
1446 if (shared->config_->logger)
1447 shared->config_->logger->error("{}", e.what());
1448 dht::ThreadPool::io().run([eraseInfo = std::move(eraseInfo)] { eraseInfo(); });
1449 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001450 });
1451}
1452
1453void
Adrien Béraud75754b22023-10-17 09:16:06 -04001454ConnectionManager::Impl::addNewMultiplexedSocket(const std::weak_ptr<DeviceInfo>& dinfo, const DeviceId& deviceId, const dht::Value::Id& vid, const std::shared_ptr<ConnectionInfo>& info)
Adrien Béraud612b55b2023-05-29 10:42:04 -04001455{
Adrien Béraud75754b22023-10-17 09:16:06 -04001456 info->socket_ = std::make_shared<MultiplexedSocket>(config_->ioContext, deviceId, std::move(info->tls_), config_->logger);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001457 info->socket_->setOnReady(
Adrien Béraud75754b22023-10-17 09:16:06 -04001458 [w = weak_from_this()](const DeviceId& deviceId, const std::shared_ptr<ChannelSocket>& socket) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001459 if (auto sthis = w.lock())
1460 if (sthis->connReadyCb_)
1461 sthis->connReadyCb_(deviceId, socket->name(), socket);
1462 });
Adrien Béraud75754b22023-10-17 09:16:06 -04001463 info->socket_->setOnRequest([w = weak_from_this()](const std::shared_ptr<dht::crypto::Certificate>& peer,
Adrien Béraud612b55b2023-05-29 10:42:04 -04001464 const uint16_t&,
1465 const std::string& name) {
1466 if (auto sthis = w.lock())
1467 if (sthis->channelReqCb_)
1468 return sthis->channelReqCb_(peer, name);
1469 return false;
1470 });
Adrien Béraud75754b22023-10-17 09:16:06 -04001471 info->socket_->onShutdown([dinfo, wi=std::weak_ptr(info), vid]() {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001472 // Cancel current outgoing connections
Adrien Béraud75754b22023-10-17 09:16:06 -04001473 dht::ThreadPool::io().run([dinfo, wi, vid] {
1474 std::set<dht::Value::Id> ids;
1475 if (auto info = wi.lock()) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001476 std::lock_guard<std::mutex> lk(info->mutex_);
1477 if (info->socket_) {
1478 ids = std::move(info->cbIds_);
1479 info->socket_->shutdown();
1480 }
1481 }
Adrien Béraud75754b22023-10-17 09:16:06 -04001482 if (auto deviceInfo = dinfo.lock()) {
1483 std::shared_ptr<ConnectionInfo> info;
1484 std::vector<PendingCb> ops;
1485 std::unique_lock<std::mutex> lk(deviceInfo->mtx_);
1486 auto it = deviceInfo->info.find(vid);
1487 if (it != deviceInfo->info.end()) {
1488 info = std::move(it->second);
1489 deviceInfo->info.erase(it);
1490 }
1491 for (const auto& cbId : ids) {
1492 auto po = deviceInfo->extractPendingOperations(cbId, nullptr);
1493 ops.insert(ops.end(), po.begin(), po.end());
1494 }
1495 lk.unlock();
1496 for (auto& op : ops)
1497 op.cb(nullptr, deviceInfo->deviceId);
1498 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001499 });
1500 });
1501}
1502
1503const std::shared_future<tls::DhParams>
1504ConnectionManager::Impl::dhParams() const
1505{
1506 return dht::ThreadPool::computation().get<tls::DhParams>(
Adrien Béraud2a4e73d2023-08-27 12:53:55 -04001507 std::bind(tls::DhParams::loadDhParams, config_->cachePath / "dhParams"));
Adrien Béraud612b55b2023-05-29 10:42:04 -04001508}
1509
1510template<typename ID = dht::Value::Id>
1511std::set<ID, std::less<>>
Adrien Béraud1299a0d2023-09-19 15:03:28 -04001512loadIdList(const std::filesystem::path& path)
Adrien Béraud612b55b2023-05-29 10:42:04 -04001513{
1514 std::set<ID, std::less<>> ids;
Adrien Béraud1299a0d2023-09-19 15:03:28 -04001515 std::ifstream file(path);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001516 if (!file.is_open()) {
1517 //JAMI_DBG("Could not load %s", path.c_str());
1518 return ids;
1519 }
1520 std::string line;
1521 while (std::getline(file, line)) {
1522 if constexpr (std::is_same<ID, std::string>::value) {
1523 ids.emplace(std::move(line));
1524 } else if constexpr (std::is_integral<ID>::value) {
1525 ID vid;
1526 if (auto [p, ec] = std::from_chars(line.data(), line.data() + line.size(), vid, 16);
1527 ec == std::errc()) {
1528 ids.emplace(vid);
1529 }
1530 }
1531 }
1532 return ids;
1533}
1534
1535template<typename List = std::set<dht::Value::Id>>
1536void
Adrien Béraud2a4e73d2023-08-27 12:53:55 -04001537saveIdList(const std::filesystem::path& path, const List& ids)
Adrien Béraud612b55b2023-05-29 10:42:04 -04001538{
Adrien Béraud1299a0d2023-09-19 15:03:28 -04001539 std::ofstream file(path, std::ios::trunc | std::ios::binary);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001540 if (!file.is_open()) {
1541 //JAMI_ERR("Could not save to %s", path.c_str());
1542 return;
1543 }
1544 for (auto& c : ids)
1545 file << std::hex << c << "\n";
1546}
1547
1548void
1549ConnectionManager::Impl::loadTreatedMessages()
1550{
1551 std::lock_guard<std::mutex> lock(messageMutex_);
Adrien Béraud2a4e73d2023-08-27 12:53:55 -04001552 auto path = config_->cachePath / "treatedMessages";
Aline Gondim Santos406c0f42023-09-13 12:10:23 -03001553 treatedMessages_ = loadIdList<std::string>(path.string());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001554 if (treatedMessages_.empty()) {
Aline Gondim Santos406c0f42023-09-13 12:10:23 -03001555 auto messages = loadIdList(path.string());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001556 for (const auto& m : messages)
1557 treatedMessages_.emplace(to_hex_string(m));
1558 }
1559}
1560
1561void
1562ConnectionManager::Impl::saveTreatedMessages() const
1563{
Adrien Béraud75754b22023-10-17 09:16:06 -04001564 dht::ThreadPool::io().run([w = weak_from_this()]() {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001565 if (auto sthis = w.lock()) {
1566 auto& this_ = *sthis;
1567 std::lock_guard<std::mutex> lock(this_.messageMutex_);
1568 fileutils::check_dir(this_.config_->cachePath.c_str());
Adrien Béraud2a4e73d2023-08-27 12:53:55 -04001569 saveIdList<decltype(this_.treatedMessages_)>(this_.config_->cachePath / "treatedMessages",
Adrien Béraud612b55b2023-05-29 10:42:04 -04001570 this_.treatedMessages_);
1571 }
1572 });
1573}
1574
1575bool
1576ConnectionManager::Impl::isMessageTreated(std::string_view id)
1577{
1578 std::lock_guard<std::mutex> lock(messageMutex_);
1579 auto res = treatedMessages_.emplace(id);
1580 if (res.second) {
1581 saveTreatedMessages();
1582 return false;
1583 }
1584 return true;
1585}
1586
1587/**
1588 * returns whether or not UPnP is enabled and active_
1589 * ie: if it is able to make port mappings
1590 */
1591bool
1592ConnectionManager::Impl::getUPnPActive() const
1593{
1594 return config_->getUPnPActive();
1595}
1596
1597IpAddr
1598ConnectionManager::Impl::getPublishedIpAddress(uint16_t family) const
1599{
1600 if (family == AF_INET)
1601 return publishedIp_[0];
1602 if (family == AF_INET6)
1603 return publishedIp_[1];
1604
1605 assert(family == AF_UNSPEC);
1606
1607 // If family is not set, prefere IPv4 if available. It's more
1608 // likely to succeed behind NAT.
1609 if (publishedIp_[0])
1610 return publishedIp_[0];
1611 if (publishedIp_[1])
1612 return publishedIp_[1];
1613 return {};
1614}
1615
1616void
1617ConnectionManager::Impl::setPublishedAddress(const IpAddr& ip_addr)
1618{
1619 if (ip_addr.getFamily() == AF_INET) {
1620 publishedIp_[0] = ip_addr;
1621 } else {
1622 publishedIp_[1] = ip_addr;
1623 }
1624}
1625
1626void
1627ConnectionManager::Impl::storeActiveIpAddress(std::function<void()>&& cb)
1628{
Adrien Béraud75754b22023-10-17 09:16:06 -04001629 dht()->getPublicAddress([w=weak_from_this(), cb = std::move(cb)](std::vector<dht::SockAddr>&& results) {
Sébastien Blinb6504372023-10-12 10:35:35 -04001630 auto shared = w.lock();
1631 if (!shared)
1632 return;
Adrien Béraud612b55b2023-05-29 10:42:04 -04001633 bool hasIpv4 {false}, hasIpv6 {false};
1634 for (auto& result : results) {
1635 auto family = result.getFamily();
1636 if (family == AF_INET) {
1637 if (not hasIpv4) {
1638 hasIpv4 = true;
Sébastien Blinb6504372023-10-12 10:35:35 -04001639 if (shared->config_->logger)
1640 shared->config_->logger->debug("Store DHT public IPv4 address: {}", result);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001641 //JAMI_DBG("Store DHT public IPv4 address : %s", result.toString().c_str());
Sébastien Blinb6504372023-10-12 10:35:35 -04001642 shared->setPublishedAddress(*result.get());
1643 if (shared->config_->upnpCtrl) {
1644 shared->config_->upnpCtrl->setPublicAddress(*result.get());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001645 }
1646 }
1647 } else if (family == AF_INET6) {
1648 if (not hasIpv6) {
1649 hasIpv6 = true;
Sébastien Blinb6504372023-10-12 10:35:35 -04001650 if (shared->config_->logger)
1651 shared->config_->logger->debug("Store DHT public IPv6 address: {}", result);
1652 shared->setPublishedAddress(*result.get());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001653 }
1654 }
1655 if (hasIpv4 and hasIpv6)
1656 break;
1657 }
1658 if (cb)
1659 cb();
1660 });
1661}
1662
1663void
1664ConnectionManager::Impl::getIceOptions(std::function<void(IceTransportOptions&&)> cb) noexcept
1665{
1666 storeActiveIpAddress([this, cb = std::move(cb)] {
1667 IceTransportOptions opts = ConnectionManager::Impl::getIceOptions();
1668 auto publishedAddr = getPublishedIpAddress();
1669
1670 if (publishedAddr) {
1671 auto interfaceAddr = ip_utils::getInterfaceAddr(getLocalInterface(),
1672 publishedAddr.getFamily());
1673 if (interfaceAddr) {
1674 opts.accountLocalAddr = interfaceAddr;
1675 opts.accountPublicAddr = publishedAddr;
1676 }
1677 }
1678 if (cb)
1679 cb(std::move(opts));
1680 });
1681}
1682
1683IceTransportOptions
1684ConnectionManager::Impl::getIceOptions() const noexcept
1685{
1686 IceTransportOptions opts;
Sébastien Blin34086512023-07-25 09:52:14 -04001687 opts.factory = config_->factory;
Adrien Béraud612b55b2023-05-29 10:42:04 -04001688 opts.upnpEnable = getUPnPActive();
Adrien Béraud7b869d92023-08-21 09:02:35 -04001689 opts.upnpContext = config_->upnpCtrl ? config_->upnpCtrl->upnpContext() : nullptr;
Adrien Béraud612b55b2023-05-29 10:42:04 -04001690
1691 if (config_->stunEnabled)
1692 opts.stunServers.emplace_back(StunServerInfo().setUri(config_->stunServer));
1693 if (config_->turnEnabled) {
Sébastien Blin84bf4182023-07-21 14:18:39 -04001694 if (config_->turnCache) {
1695 auto turnAddr = config_->turnCache->getResolvedTurn();
1696 if (turnAddr != std::nullopt) {
1697 opts.turnServers.emplace_back(TurnServerInfo()
1698 .setUri(turnAddr->toString())
1699 .setUsername(config_->turnServerUserName)
1700 .setPassword(config_->turnServerPwd)
1701 .setRealm(config_->turnServerRealm));
1702 }
1703 } else {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001704 opts.turnServers.emplace_back(TurnServerInfo()
Sébastien Blin84bf4182023-07-21 14:18:39 -04001705 .setUri(config_->turnServer)
1706 .setUsername(config_->turnServerUserName)
1707 .setPassword(config_->turnServerPwd)
1708 .setRealm(config_->turnServerRealm));
Adrien Béraud612b55b2023-05-29 10:42:04 -04001709 }
1710 // NOTE: first test with ipv6 turn was not concluant and resulted in multiple
1711 // co issues. So this needs some debug. for now just disable
1712 // if (cacheTurnV6 && *cacheTurnV6) {
1713 // opts.turnServers.emplace_back(TurnServerInfo()
1714 // .setUri(cacheTurnV6->toString(true))
1715 // .setUsername(turnServerUserName_)
1716 // .setPassword(turnServerPwd_)
1717 // .setRealm(turnServerRealm_));
1718 //}
Adrien Béraud612b55b2023-05-29 10:42:04 -04001719 }
1720 return opts;
1721}
1722
1723bool
1724ConnectionManager::Impl::foundPeerDevice(const std::shared_ptr<dht::crypto::Certificate>& crt,
1725 dht::InfoHash& account_id,
1726 const std::shared_ptr<Logger>& logger)
1727{
1728 if (not crt)
1729 return false;
1730
1731 auto top_issuer = crt;
1732 while (top_issuer->issuer)
1733 top_issuer = top_issuer->issuer;
1734
1735 // Device certificate can't be self-signed
Adrien Béraudc631a832023-07-26 22:19:00 -04001736 if (top_issuer == crt) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001737 if (logger)
Adrien Béraud8b831a82023-07-21 14:13:06 -04001738 logger->warn("Found invalid (self-signed) peer device: {}", crt->getLongId());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001739 return false;
Adrien Béraudc631a832023-07-26 22:19:00 -04001740 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001741
1742 // Check peer certificate chain
1743 // Trust store with top issuer as the only CA
1744 dht::crypto::TrustList peer_trust;
1745 peer_trust.add(*top_issuer);
1746 if (not peer_trust.verify(*crt)) {
1747 if (logger)
1748 logger->warn("Found invalid peer device: {}", crt->getLongId());
1749 return false;
1750 }
1751
1752 // Check cached OCSP response
1753 if (crt->ocspResponse and crt->ocspResponse->getCertificateStatus() != GNUTLS_OCSP_CERT_GOOD) {
1754 if (logger)
Adrien Béraud8b831a82023-07-21 14:13:06 -04001755 logger->error("Certificate {} is disabled by cached OCSP response", crt->getLongId());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001756 return false;
1757 }
1758
Adrien Béraudc631a832023-07-26 22:19:00 -04001759 account_id = crt->issuer->getId();
1760 if (logger)
1761 logger->warn("Found peer device: {} account:{} CA:{}",
1762 crt->getLongId(),
1763 account_id,
1764 top_issuer->getId());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001765 return true;
1766}
1767
1768bool
1769ConnectionManager::Impl::findCertificate(
1770 const dht::PkId& id, std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb)
1771{
1772 if (auto cert = certStore().getCertificate(id.toString())) {
1773 if (cb)
1774 cb(cert);
1775 } else if (cb)
1776 cb(nullptr);
1777 return true;
1778}
1779
Sébastien Blin34086512023-07-25 09:52:14 -04001780bool
1781ConnectionManager::Impl::findCertificate(const dht::InfoHash& h,
1782 std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb)
1783{
1784 if (auto cert = certStore().getCertificate(h.toString())) {
1785 if (cb)
1786 cb(cert);
1787 } else {
1788 dht()->findCertificate(h,
1789 [cb = std::move(cb), this](
1790 const std::shared_ptr<dht::crypto::Certificate>& crt) {
1791 if (crt)
1792 certStore().pinCertificate(crt);
1793 if (cb)
1794 cb(crt);
1795 });
1796 }
1797 return true;
1798}
1799
Amna81221ad2023-09-14 17:33:26 -04001800std::shared_ptr<ConnectionManager::Config>
1801buildDefaultConfig(dht::crypto::Identity id){
1802 auto conf = std::make_shared<ConnectionManager::Config>();
1803 conf->id = std::move(id);
1804 return conf;
1805}
1806
Adrien Béraud612b55b2023-05-29 10:42:04 -04001807ConnectionManager::ConnectionManager(std::shared_ptr<ConnectionManager::Config> config_)
1808 : pimpl_ {std::make_shared<Impl>(config_)}
1809{}
1810
Amna81221ad2023-09-14 17:33:26 -04001811ConnectionManager::ConnectionManager(dht::crypto::Identity id)
1812 : ConnectionManager {buildDefaultConfig(id)}
1813{}
1814
Adrien Béraud612b55b2023-05-29 10:42:04 -04001815ConnectionManager::~ConnectionManager()
1816{
1817 if (pimpl_)
1818 pimpl_->shutdown();
1819}
1820
1821void
1822ConnectionManager::connectDevice(const DeviceId& deviceId,
1823 const std::string& name,
1824 ConnectCallback cb,
1825 bool noNewSocket,
1826 bool forceNewSocket,
1827 const std::string& connType)
1828{
1829 pimpl_->connectDevice(deviceId, name, std::move(cb), noNewSocket, forceNewSocket, connType);
1830}
1831
1832void
Amna0cf544d2023-07-25 14:25:09 -04001833ConnectionManager::connectDevice(const dht::InfoHash& deviceId,
1834 const std::string& name,
1835 ConnectCallbackLegacy cb,
1836 bool noNewSocket,
1837 bool forceNewSocket,
1838 const std::string& connType)
1839{
1840 pimpl_->connectDevice(deviceId, name, std::move(cb), noNewSocket, forceNewSocket, connType);
1841}
1842
1843
1844void
Adrien Béraud612b55b2023-05-29 10:42:04 -04001845ConnectionManager::connectDevice(const std::shared_ptr<dht::crypto::Certificate>& cert,
1846 const std::string& name,
1847 ConnectCallback cb,
1848 bool noNewSocket,
1849 bool forceNewSocket,
1850 const std::string& connType)
1851{
1852 pimpl_->connectDevice(cert, name, std::move(cb), noNewSocket, forceNewSocket, connType);
1853}
1854
1855bool
1856ConnectionManager::isConnecting(const DeviceId& deviceId, const std::string& name) const
1857{
Adrien Béraud75754b22023-10-17 09:16:06 -04001858 if (auto dinfo = pimpl_->infos_.getDeviceInfo(deviceId)) {
1859 std::unique_lock<std::mutex> lk {dinfo->mtx_};
Adrien Béraudb941e922023-10-16 12:56:14 -04001860 return dinfo->isConnecting(name);
Adrien Béraud75754b22023-10-17 09:16:06 -04001861 }
1862 return false;
Adrien Béraud612b55b2023-05-29 10:42:04 -04001863}
1864
1865void
1866ConnectionManager::closeConnectionsWith(const std::string& peerUri)
1867{
Adrien Béraud75754b22023-10-17 09:16:06 -04001868 std::vector<std::shared_ptr<DeviceInfo>> dInfos;
1869 for (const auto& dinfo: pimpl_->infos_.getDeviceInfos()) {
1870 std::unique_lock<std::mutex> lk(dinfo->mtx_);
1871 bool isPeer = false;
1872 for (auto const& [id, cinfo]: dinfo->info) {
1873 std::lock_guard<std::mutex> lkv {cinfo->mutex_};
1874 auto tls = cinfo->tls_ ? cinfo->tls_.get() : (cinfo->socket_ ? cinfo->socket_->endpoint() : nullptr);
Adrien Béraudafa8e282023-09-24 12:53:20 -04001875 auto cert = tls ? tls->peerCertificate() : nullptr;
1876 if (not cert)
Adrien Béraud75754b22023-10-17 09:16:06 -04001877 cert = pimpl_->certStore().getCertificate(dinfo->deviceId.toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001878 if (cert && cert->issuer && peerUri == cert->issuer->getId().toString()) {
Adrien Béraud75754b22023-10-17 09:16:06 -04001879 isPeer = true;
1880 break;
Adrien Béraud612b55b2023-05-29 10:42:04 -04001881 }
1882 }
Adrien Béraud75754b22023-10-17 09:16:06 -04001883 lk.unlock();
1884 if (isPeer) {
1885 dInfos.emplace_back(std::move(dinfo));
1886 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001887 }
1888 // Stop connections to all peers devices
Adrien Béraud75754b22023-10-17 09:16:06 -04001889 for (const auto& dinfo : dInfos) {
1890 std::unique_lock<std::mutex> lk {dinfo->mtx_};
1891 auto unused = dinfo->extractUnusedConnections();
1892 auto pending = dinfo->extractPendingOperations(0, nullptr);
1893 pimpl_->infos_.removeDeviceInfo(dinfo->deviceId);
1894 lk.unlock();
1895 for (auto& op : unused)
1896 op->shutdown();
1897 for (auto& op : pending)
1898 op.cb(nullptr, dinfo->deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001899 }
1900}
1901
1902void
1903ConnectionManager::onDhtConnected(const dht::crypto::PublicKey& devicePk)
1904{
1905 pimpl_->onDhtConnected(devicePk);
1906}
1907
1908void
1909ConnectionManager::onICERequest(onICERequestCallback&& cb)
1910{
1911 pimpl_->iceReqCb_ = std::move(cb);
1912}
1913
1914void
1915ConnectionManager::onChannelRequest(ChannelRequestCallback&& cb)
1916{
1917 pimpl_->channelReqCb_ = std::move(cb);
1918}
1919
1920void
1921ConnectionManager::onConnectionReady(ConnectionReadyCallback&& cb)
1922{
1923 pimpl_->connReadyCb_ = std::move(cb);
1924}
1925
1926void
1927ConnectionManager::oniOSConnected(iOSConnectedCallback&& cb)
1928{
1929 pimpl_->iOSConnectedCb_ = std::move(cb);
1930}
1931
1932std::size_t
1933ConnectionManager::activeSockets() const
1934{
Adrien Béraud75754b22023-10-17 09:16:06 -04001935 return pimpl_->infos_.getConnectedInfos().size();
Adrien Béraud612b55b2023-05-29 10:42:04 -04001936}
1937
1938void
1939ConnectionManager::monitor() const
1940{
Adrien Béraud612b55b2023-05-29 10:42:04 -04001941 auto logger = pimpl_->config_->logger;
1942 if (!logger)
1943 return;
1944 logger->debug("ConnectionManager current status:");
Adrien Béraud75754b22023-10-17 09:16:06 -04001945 for (const auto& ci : pimpl_->infos_.getConnectedInfos()) {
1946 std::lock_guard<std::mutex> lk(ci->mutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001947 if (ci->socket_)
1948 ci->socket_->monitor();
1949 }
1950 logger->debug("ConnectionManager end status.");
1951}
1952
1953void
1954ConnectionManager::connectivityChanged()
1955{
Adrien Béraud75754b22023-10-17 09:16:06 -04001956 for (const auto& ci : pimpl_->infos_.getConnectedInfos()) {
1957 std::lock_guard<std::mutex> lk(ci->mutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001958 if (ci->socket_)
1959 ci->socket_->sendBeacon();
1960 }
1961}
1962
1963void
1964ConnectionManager::getIceOptions(std::function<void(IceTransportOptions&&)> cb) noexcept
1965{
1966 return pimpl_->getIceOptions(std::move(cb));
1967}
1968
1969IceTransportOptions
1970ConnectionManager::getIceOptions() const noexcept
1971{
1972 return pimpl_->getIceOptions();
1973}
1974
1975IpAddr
1976ConnectionManager::getPublishedIpAddress(uint16_t family) const
1977{
1978 return pimpl_->getPublishedIpAddress(family);
1979}
1980
1981void
1982ConnectionManager::setPublishedAddress(const IpAddr& ip_addr)
1983{
1984 return pimpl_->setPublishedAddress(ip_addr);
1985}
1986
1987void
1988ConnectionManager::storeActiveIpAddress(std::function<void()>&& cb)
1989{
1990 return pimpl_->storeActiveIpAddress(std::move(cb));
1991}
1992
1993std::shared_ptr<ConnectionManager::Config>
1994ConnectionManager::getConfig()
1995{
1996 return pimpl_->config_;
1997}
1998
Amna31791e52023-08-03 12:40:57 -04001999std::vector<std::map<std::string, std::string>>
2000ConnectionManager::getConnectionList(const DeviceId& device) const
2001{
2002 std::vector<std::map<std::string, std::string>> connectionsList;
Amna31791e52023-08-03 12:40:57 -04002003 if (device) {
Adrien Béraud75754b22023-10-17 09:16:06 -04002004 if (auto deviceInfo = pimpl_->infos_.getDeviceInfo(device)) {
2005 connectionsList = deviceInfo->getConnectionList(pimpl_->certStore());
Amna31791e52023-08-03 12:40:57 -04002006 }
Adrien Béraud75754b22023-10-17 09:16:06 -04002007 } else {
2008 for (const auto& deviceInfo : pimpl_->infos_.getDeviceInfos()) {
2009 auto cl = deviceInfo->getConnectionList(pimpl_->certStore());
2010 connectionsList.insert(connectionsList.end(), std::make_move_iterator(cl.begin()), std::make_move_iterator(cl.end()));
Amna31791e52023-08-03 12:40:57 -04002011 }
2012 }
2013 return connectionsList;
2014}
2015
2016std::vector<std::map<std::string, std::string>>
2017ConnectionManager::getChannelList(const std::string& connectionId) const
2018{
Adrien Béraud75754b22023-10-17 09:16:06 -04002019 auto [deviceId, valueId] = parseCallbackId(connectionId);
2020 if (auto info = pimpl_->infos_.getInfo(deviceId, valueId)) {
2021 std::lock_guard<std::mutex> lk(info->mutex_);
2022 if (info->socket_)
2023 return info->socket_->getChannelList();
Amna31791e52023-08-03 12:40:57 -04002024 }
Adrien Béraud75754b22023-10-17 09:16:06 -04002025 return {};
Amna31791e52023-08-03 12:40:57 -04002026}
2027
Sébastien Blin464bdff2023-07-19 08:02:53 -04002028} // namespace dhtnet