blob: 68f40b1704854a36af3d7136f19a3889ad167337 [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éraud1addf952023-09-30 17:38:35 -0400503 void onPeerResponse(PeerConnectionRequest&& req);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400504 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éraud9a4e98b2023-10-15 12:10:21 -04001044 if (!channelSock) {
1045 if (config_->logger)
1046 config_->logger->error("sendChannelRequest failed - cannot create channel");
1047 if (auto info = dinfo.lock())
1048 info->executePendingOperations(vid, nullptr);
1049 return;
1050 }
Adrien Béraud75754b22023-10-17 09:16:06 -04001051 channelSock->onShutdown([dinfo, name, vid] {
1052 if (auto info = dinfo.lock())
1053 info->executePendingOperations(vid, nullptr);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001054 });
1055 channelSock->onReady(
Adrien Béraud75754b22023-10-17 09:16:06 -04001056 [dinfo, wSock = std::weak_ptr(channelSock), name, vid](bool accepted) {
1057 if (auto info = dinfo.lock())
1058 info->executePendingOperations(vid, accepted ? wSock.lock() : nullptr, accepted);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001059 });
1060
1061 ChannelRequest val;
1062 val.name = channelSock->name();
1063 val.state = ChannelRequestState::REQUEST;
1064 val.channel = channelSock->channel();
1065 msgpack::sbuffer buffer(256);
1066 msgpack::pack(buffer, val);
1067
1068 std::error_code ec;
1069 int res = sock->write(CONTROL_CHANNEL,
1070 reinterpret_cast<const uint8_t*>(buffer.data()),
1071 buffer.size(),
1072 ec);
1073 if (res < 0) {
1074 // TODO check if we should handle errors here
1075 if (config_->logger)
Adrien Béraud75754b22023-10-17 09:16:06 -04001076 config_->logger->error("sendChannelRequest failed - error: {}", ec.message());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001077 }
1078}
1079
1080void
Adrien Béraud1addf952023-09-30 17:38:35 -04001081ConnectionManager::Impl::onPeerResponse(PeerConnectionRequest&& req)
Adrien Béraud612b55b2023-05-29 10:42:04 -04001082{
1083 auto device = req.owner->getLongId();
Adrien Béraud75754b22023-10-17 09:16:06 -04001084 if (auto info = infos_.getInfo(device, req.id)) {
Adrien Béraud23852462023-07-22 01:46:27 -04001085 if (config_->logger)
1086 config_->logger->debug("[device {}] New response received", device);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001087 std::lock_guard<std::mutex> lk {info->mutex_};
1088 info->responseReceived_ = true;
1089 info->response_ = std::move(req);
1090 info->waitForAnswer_->expires_at(std::chrono::steady_clock::now());
1091 info->waitForAnswer_->async_wait(std::bind(&ConnectionManager::Impl::onResponse,
1092 this,
1093 std::placeholders::_1,
Adrien Béraud75754b22023-10-17 09:16:06 -04001094 std::weak_ptr(info),
Adrien Béraud612b55b2023-05-29 10:42:04 -04001095 device,
1096 req.id));
1097 } else {
1098 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001099 config_->logger->warn("[device {}] Respond received, but cannot find request", device);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001100 }
1101}
1102
1103void
1104ConnectionManager::Impl::onDhtConnected(const dht::crypto::PublicKey& devicePk)
1105{
1106 if (!dht())
1107 return;
1108 dht()->listen<PeerConnectionRequest>(
1109 dht::InfoHash::get(PeerConnectionRequest::key_prefix + devicePk.getId().toString()),
Adrien Béraud75754b22023-10-17 09:16:06 -04001110 [w = weak_from_this()](PeerConnectionRequest&& req) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001111 auto shared = w.lock();
1112 if (!shared)
1113 return false;
1114 if (shared->isMessageTreated(to_hex_string(req.id))) {
1115 // Message already treated. Just ignore
1116 return true;
1117 }
1118 if (req.isAnswer) {
1119 if (shared->config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001120 shared->config_->logger->debug("[device {}] Received request answer", req.owner->getLongId());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001121 } else {
1122 if (shared->config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001123 shared->config_->logger->debug("[device {}] Received request", req.owner->getLongId());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001124 }
1125 if (req.isAnswer) {
Adrien Béraud1addf952023-09-30 17:38:35 -04001126 shared->onPeerResponse(std::move(req));
Adrien Béraud612b55b2023-05-29 10:42:04 -04001127 } else {
1128 // Async certificate checking
Sébastien Blin34086512023-07-25 09:52:14 -04001129 shared->findCertificate(
Adrien Béraud612b55b2023-05-29 10:42:04 -04001130 req.from,
1131 [w, req = std::move(req)](
1132 const std::shared_ptr<dht::crypto::Certificate>& cert) mutable {
1133 auto shared = w.lock();
1134 if (!shared)
1135 return;
1136 dht::InfoHash peer_h;
1137 if (foundPeerDevice(cert, peer_h, shared->config_->logger)) {
1138#if TARGET_OS_IOS
1139 if (shared->iOSConnectedCb_(req.connType, peer_h))
1140 return;
1141#endif
1142 shared->onDhtPeerRequest(req, cert);
1143 } else {
1144 if (shared->config_->logger)
1145 shared->config_->logger->warn(
Adrien Béraud23852462023-07-22 01:46:27 -04001146 "[device {}] Received request from untrusted peer",
Adrien Béraud612b55b2023-05-29 10:42:04 -04001147 req.owner->getLongId());
1148 }
1149 });
1150 }
1151
1152 return true;
1153 },
1154 dht::Value::UserTypeFilter("peer_request"));
1155}
1156
1157void
Adrien Béraud75754b22023-10-17 09:16:06 -04001158ConnectionManager::Impl::onTlsNegotiationDone(const std::shared_ptr<DeviceInfo>& dinfo,
1159 const std::shared_ptr<ConnectionInfo>& info,
1160 bool ok,
Adrien Béraud612b55b2023-05-29 10:42:04 -04001161 const DeviceId& deviceId,
1162 const dht::Value::Id& vid,
1163 const std::string& name)
1164{
1165 if (isDestroying_)
1166 return;
1167 // Note: only handle pendingCallbacks here for TLS initied by connectDevice()
1168 // Note: if not initied by connectDevice() the channel name will be empty (because no channel
1169 // asked yet)
1170 auto isDhtRequest = name.empty();
1171 if (!ok) {
1172 if (isDhtRequest) {
1173 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001174 config_->logger->error("[device {}] TLS connection failure - Initied by DHT request. channel: {} - vid: {}",
Adrien Béraud612b55b2023-05-29 10:42:04 -04001175 deviceId,
1176 name,
1177 vid);
1178 if (connReadyCb_)
1179 connReadyCb_(deviceId, "", nullptr);
1180 } else {
1181 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001182 config_->logger->error("[device {}] TLS connection failure - Initied by connectDevice. channel: {} - vid: {}",
Adrien Béraud612b55b2023-05-29 10:42:04 -04001183 deviceId,
1184 name,
1185 vid);
Adrien Béraud75754b22023-10-17 09:16:06 -04001186 dinfo->executePendingOperations(vid, nullptr);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001187 }
1188 } else {
1189 // The socket is ready, store it
1190 if (isDhtRequest) {
1191 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001192 config_->logger->debug("[device {}] Connection is ready - Initied by DHT request. Vid: {}",
Adrien Béraud612b55b2023-05-29 10:42:04 -04001193 deviceId,
1194 vid);
1195 } else {
1196 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001197 config_->logger->debug("[device {}] Connection is ready - Initied by connectDevice(). channel: {} - vid: {}",
Adrien Béraud612b55b2023-05-29 10:42:04 -04001198 deviceId,
1199 name,
1200 vid);
1201 }
1202
Adrien Béraud75754b22023-10-17 09:16:06 -04001203 // Note: do not remove pending there it's done in sendChannelRequest
1204 std::unique_lock<std::mutex> lk2 {dinfo->mtx_};
Adrien Béraudb941e922023-10-16 12:56:14 -04001205 auto pendingIds = dinfo->requestPendingOps();
Adrien Béraud75754b22023-10-17 09:16:06 -04001206 lk2.unlock();
1207 std::unique_lock<std::mutex> lk {info->mutex_};
1208 addNewMultiplexedSocket(dinfo, deviceId, vid, info);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001209 // Finally, open the channel and launch pending callbacks
Adrien Béraud75754b22023-10-17 09:16:06 -04001210 lk.unlock();
1211 for (const auto& [id, name]: pendingIds) {
1212 if (config_->logger)
1213 config_->logger->debug("[device {}] Send request on TLS socket for channel {}",
1214 deviceId, name);
1215 sendChannelRequest(dinfo, info->socket_, name, id);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001216 }
1217 }
1218}
1219
1220void
1221ConnectionManager::Impl::answerTo(IceTransport& ice,
1222 const dht::Value::Id& id,
1223 const std::shared_ptr<dht::crypto::PublicKey>& from)
1224{
1225 // NOTE: This is a shortest version of a real SDP message to save some bits
1226 auto iceAttributes = ice.getLocalAttributes();
1227 std::ostringstream icemsg;
1228 icemsg << iceAttributes.ufrag << "\n";
1229 icemsg << iceAttributes.pwd << "\n";
1230 for (const auto& addr : ice.getLocalCandidates(1)) {
1231 icemsg << addr << "\n";
1232 }
1233
1234 // Send PeerConnection response
1235 PeerConnectionRequest val;
1236 val.id = id;
1237 val.ice_msg = icemsg.str();
1238 val.isAnswer = true;
1239 auto value = std::make_shared<dht::Value>(std::move(val));
1240 value->user_type = "peer_request";
1241
1242 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001243 config_->logger->debug("[device {}] Connection accepted, DHT reply", from->getLongId());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001244 dht()->putEncrypted(dht::InfoHash::get(PeerConnectionRequest::key_prefix
1245 + from->getId().toString()),
1246 from,
1247 value,
1248 [from,l=config_->logger](bool ok) {
1249 if (l)
Adrien Béraud23852462023-07-22 01:46:27 -04001250 l->debug("[device {}] Answer to connection request: put encrypted {:s}",
Adrien Béraud612b55b2023-05-29 10:42:04 -04001251 from->getLongId(),
1252 (ok ? "ok" : "failed"));
1253 });
1254}
1255
1256bool
Adrien Béraud75754b22023-10-17 09:16:06 -04001257ConnectionManager::Impl::onRequestStartIce(const std::shared_ptr<ConnectionInfo>& info, const PeerConnectionRequest& req)
Adrien Béraud612b55b2023-05-29 10:42:04 -04001258{
Adrien Béraud612b55b2023-05-29 10:42:04 -04001259 if (!info)
1260 return false;
1261
Adrien Béraud75754b22023-10-17 09:16:06 -04001262 auto deviceId = req.owner->getLongId();
Adrien Béraud612b55b2023-05-29 10:42:04 -04001263 std::unique_lock<std::mutex> lk {info->mutex_};
1264 auto& ice = info->ice_;
1265 if (!ice) {
1266 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001267 config_->logger->error("[device {}] No ICE detected", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001268 if (connReadyCb_)
1269 connReadyCb_(deviceId, "", nullptr);
1270 return false;
1271 }
1272
1273 auto sdp = ice->parseIceCandidates(req.ice_msg);
1274 answerTo(*ice, req.id, req.owner);
1275 if (not ice->startIce({sdp.rem_ufrag, sdp.rem_pwd}, std::move(sdp.rem_candidates))) {
1276 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001277 config_->logger->error("[device {}] Start ICE failed", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001278 ice = nullptr;
1279 if (connReadyCb_)
1280 connReadyCb_(deviceId, "", nullptr);
1281 return false;
1282 }
1283 return true;
1284}
1285
1286bool
Adrien Béraud75754b22023-10-17 09:16:06 -04001287ConnectionManager::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 -04001288{
Adrien Béraud612b55b2023-05-29 10:42:04 -04001289 if (!info)
1290 return false;
1291
Adrien Béraud75754b22023-10-17 09:16:06 -04001292 auto deviceId = req.owner->getLongId();
Adrien Béraud612b55b2023-05-29 10:42:04 -04001293 std::unique_lock<std::mutex> lk {info->mutex_};
1294 auto& ice = info->ice_;
1295 if (!ice) {
1296 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001297 config_->logger->error("[device {}] No ICE detected", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001298 return false;
1299 }
1300
1301 // Build socket
1302 auto endpoint = std::make_unique<IceSocketEndpoint>(std::shared_ptr<IceTransport>(
1303 std::move(ice)),
1304 false);
1305
1306 // init TLS session
1307 auto ph = req.from;
1308 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001309 config_->logger->debug("[device {}] Start TLS session - Initied by DHT request. vid: {}",
1310 deviceId,
Adrien Béraud612b55b2023-05-29 10:42:04 -04001311 req.id);
1312 info->tls_ = std::make_unique<TlsSocketEndpoint>(
1313 std::move(endpoint),
1314 certStore(),
Adrien Béraud3f93ddf2023-07-21 14:46:22 -04001315 config_->ioContext,
Adrien Béraud612b55b2023-05-29 10:42:04 -04001316 identity(),
1317 dhParams(),
Adrien Béraud75754b22023-10-17 09:16:06 -04001318 [ph, deviceId, w=weak_from_this(), l=config_->logger](const dht::crypto::Certificate& cert) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001319 auto shared = w.lock();
1320 if (!shared)
1321 return false;
Adrien Béraud9efbd442023-08-27 12:38:07 -04001322 if (cert.getPublicKey().getId() != ph
1323 || deviceId != cert.getPublicKey().getLongId()) {
1324 if (l) l->warn("[device {}] TLS certificate with ID {} doesn't match the DHT request.",
1325 deviceId,
1326 cert.getPublicKey().getLongId());
1327 return false;
1328 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001329 auto crt = shared->certStore().getCertificate(cert.getLongId().toString());
1330 if (!crt)
1331 return false;
1332 return crt->getPacked() == cert.getPacked();
1333 });
1334
1335 info->tls_->setOnReady(
Adrien Béraud75754b22023-10-17 09:16:06 -04001336 [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 -04001337 if (auto shared = w.lock())
Adrien Béraud75754b22023-10-17 09:16:06 -04001338 shared->onTlsNegotiationDone(dinfo.lock(), winfo.lock(), ok, deviceId, vid);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001339 });
1340 return true;
1341}
1342
1343void
1344ConnectionManager::Impl::onDhtPeerRequest(const PeerConnectionRequest& req,
1345 const std::shared_ptr<dht::crypto::Certificate>& /*cert*/)
1346{
1347 auto deviceId = req.owner->getLongId();
1348 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001349 config_->logger->debug("[device {}] New connection request", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001350 if (!iceReqCb_ || !iceReqCb_(deviceId)) {
1351 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001352 config_->logger->debug("[device {}] Refusing connection", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001353 return;
1354 }
1355
1356 // Because the connection is accepted, create an ICE socket.
Adrien Béraud75754b22023-10-17 09:16:06 -04001357 getIceOptions([w = weak_from_this(), req, deviceId](auto&& ice_config) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001358 auto shared = w.lock();
1359 if (!shared)
1360 return;
Adrien Béraud75754b22023-10-17 09:16:06 -04001361
1362 auto di = shared->infos_.createDeviceInfo(deviceId);
1363 auto info = std::make_shared<ConnectionInfo>();
1364 auto wdi = std::weak_ptr(di);
1365 auto winfo = std::weak_ptr(info);
1366
Adrien Béraud612b55b2023-05-29 10:42:04 -04001367 // Note: used when the ice negotiation fails to erase
1368 // all stored structures.
Adrien Béraud75754b22023-10-17 09:16:06 -04001369 auto eraseInfo = [w, wdi, id = req.id] {
1370 auto shared = w.lock();
1371 if (auto di = wdi.lock()) {
1372 std::unique_lock<std::mutex> lk(di->mtx_);
1373 di->info.erase(id);
1374 auto ops = di->extractPendingOperations(id, nullptr);
1375 if (di->empty()) {
1376 if (shared)
1377 shared->infos_.removeDeviceInfo(di->deviceId);
1378 }
1379 lk.unlock();
1380 for (const auto& op: ops)
1381 op.cb(nullptr, di->deviceId);
1382 if (shared && shared->connReadyCb_)
1383 shared->connReadyCb_(di->deviceId, "", nullptr);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001384 }
1385 };
1386
Adrien Béraud75754b22023-10-17 09:16:06 -04001387 ice_config.master = true;
1388 ice_config.streamsCount = 1;
1389 ice_config.compCountPerStream = 1; // TCP
Adrien Béraud612b55b2023-05-29 10:42:04 -04001390 ice_config.tcpEnable = true;
Adrien Béraud75754b22023-10-17 09:16:06 -04001391 ice_config.onInitDone = [w, winfo, req, eraseInfo](bool ok) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001392 auto shared = w.lock();
1393 if (!shared)
1394 return;
1395 if (!ok) {
1396 if (shared->config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001397 shared->config_->logger->error("[device {}] Cannot initialize ICE session.", req.owner->getLongId());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001398 dht::ThreadPool::io().run([eraseInfo = std::move(eraseInfo)] { eraseInfo(); });
1399 return;
1400 }
1401
1402 dht::ThreadPool::io().run(
Adrien Béraud75754b22023-10-17 09:16:06 -04001403 [w = std::move(w), winfo = std::move(winfo), req = std::move(req), eraseInfo = std::move(eraseInfo)] {
1404 if (auto shared = w.lock()) {
1405 if (!shared->onRequestStartIce(winfo.lock(), req))
1406 eraseInfo();
1407 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001408 });
1409 };
1410
Adrien Béraud75754b22023-10-17 09:16:06 -04001411 ice_config.onNegoDone = [w, wdi, winfo, req, eraseInfo](bool ok) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001412 auto shared = w.lock();
1413 if (!shared)
1414 return;
1415 if (!ok) {
1416 if (shared->config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001417 shared->config_->logger->error("[device {}] ICE negotiation failed.", req.owner->getLongId());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001418 dht::ThreadPool::io().run([eraseInfo = std::move(eraseInfo)] { eraseInfo(); });
1419 return;
1420 }
1421
1422 dht::ThreadPool::io().run(
Adrien Béraud75754b22023-10-17 09:16:06 -04001423 [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 -04001424 if (auto shared = w.lock())
Adrien Béraud75754b22023-10-17 09:16:06 -04001425 if (!shared->onRequestOnNegoDone(wdi.lock(), winfo.lock(), req))
Adrien Béraud612b55b2023-05-29 10:42:04 -04001426 eraseInfo();
1427 });
1428 };
1429
1430 // Negotiate a new ICE socket
Adrien Béraud612b55b2023-05-29 10:42:04 -04001431 {
Adrien Béraud75754b22023-10-17 09:16:06 -04001432 std::lock_guard<std::mutex> lk(di->mtx_);
1433 di->info[req.id] = info;
Adrien Béraud612b55b2023-05-29 10:42:04 -04001434 }
Adrien Béraud75754b22023-10-17 09:16:06 -04001435
Adrien Béraud612b55b2023-05-29 10:42:04 -04001436 if (shared->config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001437 shared->config_->logger->debug("[device {}] Accepting connection", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001438 std::unique_lock<std::mutex> lk {info->mutex_};
Sébastien Blin34086512023-07-25 09:52:14 -04001439 info->ice_ = shared->config_->factory->createUTransport("");
Adrien Béraud612b55b2023-05-29 10:42:04 -04001440 if (not info->ice_) {
1441 if (shared->config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001442 shared->config_->logger->error("[device {}] Cannot initialize ICE session", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001443 eraseInfo();
1444 return;
1445 }
1446 // We need to detect any shutdown if the ice session is destroyed before going to the TLS session;
1447 info->ice_->setOnShutdown([eraseInfo]() {
1448 dht::ThreadPool::io().run([eraseInfo = std::move(eraseInfo)] { eraseInfo(); });
1449 });
Adrien Béraud4cda2d72023-06-01 15:44:43 -04001450 try {
1451 info->ice_->initIceInstance(ice_config);
1452 } catch (const std::exception& e) {
1453 if (shared->config_->logger)
1454 shared->config_->logger->error("{}", e.what());
1455 dht::ThreadPool::io().run([eraseInfo = std::move(eraseInfo)] { eraseInfo(); });
1456 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001457 });
1458}
1459
1460void
Adrien Béraud75754b22023-10-17 09:16:06 -04001461ConnectionManager::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 -04001462{
Adrien Béraud75754b22023-10-17 09:16:06 -04001463 info->socket_ = std::make_shared<MultiplexedSocket>(config_->ioContext, deviceId, std::move(info->tls_), config_->logger);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001464 info->socket_->setOnReady(
Adrien Béraud75754b22023-10-17 09:16:06 -04001465 [w = weak_from_this()](const DeviceId& deviceId, const std::shared_ptr<ChannelSocket>& socket) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001466 if (auto sthis = w.lock())
1467 if (sthis->connReadyCb_)
1468 sthis->connReadyCb_(deviceId, socket->name(), socket);
1469 });
Adrien Béraud75754b22023-10-17 09:16:06 -04001470 info->socket_->setOnRequest([w = weak_from_this()](const std::shared_ptr<dht::crypto::Certificate>& peer,
Adrien Béraud612b55b2023-05-29 10:42:04 -04001471 const uint16_t&,
1472 const std::string& name) {
1473 if (auto sthis = w.lock())
1474 if (sthis->channelReqCb_)
1475 return sthis->channelReqCb_(peer, name);
1476 return false;
1477 });
Adrien Béraud75754b22023-10-17 09:16:06 -04001478 info->socket_->onShutdown([dinfo, wi=std::weak_ptr(info), vid]() {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001479 // Cancel current outgoing connections
Adrien Béraud75754b22023-10-17 09:16:06 -04001480 dht::ThreadPool::io().run([dinfo, wi, vid] {
1481 std::set<dht::Value::Id> ids;
1482 if (auto info = wi.lock()) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001483 std::lock_guard<std::mutex> lk(info->mutex_);
1484 if (info->socket_) {
1485 ids = std::move(info->cbIds_);
1486 info->socket_->shutdown();
1487 }
1488 }
Adrien Béraud75754b22023-10-17 09:16:06 -04001489 if (auto deviceInfo = dinfo.lock()) {
1490 std::shared_ptr<ConnectionInfo> info;
1491 std::vector<PendingCb> ops;
1492 std::unique_lock<std::mutex> lk(deviceInfo->mtx_);
1493 auto it = deviceInfo->info.find(vid);
1494 if (it != deviceInfo->info.end()) {
1495 info = std::move(it->second);
1496 deviceInfo->info.erase(it);
1497 }
1498 for (const auto& cbId : ids) {
1499 auto po = deviceInfo->extractPendingOperations(cbId, nullptr);
1500 ops.insert(ops.end(), po.begin(), po.end());
1501 }
1502 lk.unlock();
1503 for (auto& op : ops)
1504 op.cb(nullptr, deviceInfo->deviceId);
1505 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001506 });
1507 });
1508}
1509
1510const std::shared_future<tls::DhParams>
1511ConnectionManager::Impl::dhParams() const
1512{
1513 return dht::ThreadPool::computation().get<tls::DhParams>(
Adrien Béraud2a4e73d2023-08-27 12:53:55 -04001514 std::bind(tls::DhParams::loadDhParams, config_->cachePath / "dhParams"));
Adrien Béraud612b55b2023-05-29 10:42:04 -04001515}
1516
1517template<typename ID = dht::Value::Id>
1518std::set<ID, std::less<>>
Adrien Béraud1299a0d2023-09-19 15:03:28 -04001519loadIdList(const std::filesystem::path& path)
Adrien Béraud612b55b2023-05-29 10:42:04 -04001520{
1521 std::set<ID, std::less<>> ids;
Adrien Béraud1299a0d2023-09-19 15:03:28 -04001522 std::ifstream file(path);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001523 if (!file.is_open()) {
1524 //JAMI_DBG("Could not load %s", path.c_str());
1525 return ids;
1526 }
1527 std::string line;
1528 while (std::getline(file, line)) {
1529 if constexpr (std::is_same<ID, std::string>::value) {
1530 ids.emplace(std::move(line));
1531 } else if constexpr (std::is_integral<ID>::value) {
1532 ID vid;
1533 if (auto [p, ec] = std::from_chars(line.data(), line.data() + line.size(), vid, 16);
1534 ec == std::errc()) {
1535 ids.emplace(vid);
1536 }
1537 }
1538 }
1539 return ids;
1540}
1541
1542template<typename List = std::set<dht::Value::Id>>
1543void
Adrien Béraud2a4e73d2023-08-27 12:53:55 -04001544saveIdList(const std::filesystem::path& path, const List& ids)
Adrien Béraud612b55b2023-05-29 10:42:04 -04001545{
Adrien Béraud1299a0d2023-09-19 15:03:28 -04001546 std::ofstream file(path, std::ios::trunc | std::ios::binary);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001547 if (!file.is_open()) {
1548 //JAMI_ERR("Could not save to %s", path.c_str());
1549 return;
1550 }
1551 for (auto& c : ids)
1552 file << std::hex << c << "\n";
1553}
1554
1555void
1556ConnectionManager::Impl::loadTreatedMessages()
1557{
1558 std::lock_guard<std::mutex> lock(messageMutex_);
Adrien Béraud2a4e73d2023-08-27 12:53:55 -04001559 auto path = config_->cachePath / "treatedMessages";
Aline Gondim Santos406c0f42023-09-13 12:10:23 -03001560 treatedMessages_ = loadIdList<std::string>(path.string());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001561 if (treatedMessages_.empty()) {
Aline Gondim Santos406c0f42023-09-13 12:10:23 -03001562 auto messages = loadIdList(path.string());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001563 for (const auto& m : messages)
1564 treatedMessages_.emplace(to_hex_string(m));
1565 }
1566}
1567
1568void
1569ConnectionManager::Impl::saveTreatedMessages() const
1570{
Adrien Béraud75754b22023-10-17 09:16:06 -04001571 dht::ThreadPool::io().run([w = weak_from_this()]() {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001572 if (auto sthis = w.lock()) {
1573 auto& this_ = *sthis;
1574 std::lock_guard<std::mutex> lock(this_.messageMutex_);
1575 fileutils::check_dir(this_.config_->cachePath.c_str());
Adrien Béraud2a4e73d2023-08-27 12:53:55 -04001576 saveIdList<decltype(this_.treatedMessages_)>(this_.config_->cachePath / "treatedMessages",
Adrien Béraud612b55b2023-05-29 10:42:04 -04001577 this_.treatedMessages_);
1578 }
1579 });
1580}
1581
1582bool
1583ConnectionManager::Impl::isMessageTreated(std::string_view id)
1584{
1585 std::lock_guard<std::mutex> lock(messageMutex_);
1586 auto res = treatedMessages_.emplace(id);
1587 if (res.second) {
1588 saveTreatedMessages();
1589 return false;
1590 }
1591 return true;
1592}
1593
1594/**
1595 * returns whether or not UPnP is enabled and active_
1596 * ie: if it is able to make port mappings
1597 */
1598bool
1599ConnectionManager::Impl::getUPnPActive() const
1600{
1601 return config_->getUPnPActive();
1602}
1603
1604IpAddr
1605ConnectionManager::Impl::getPublishedIpAddress(uint16_t family) const
1606{
1607 if (family == AF_INET)
1608 return publishedIp_[0];
1609 if (family == AF_INET6)
1610 return publishedIp_[1];
1611
1612 assert(family == AF_UNSPEC);
1613
1614 // If family is not set, prefere IPv4 if available. It's more
1615 // likely to succeed behind NAT.
1616 if (publishedIp_[0])
1617 return publishedIp_[0];
1618 if (publishedIp_[1])
1619 return publishedIp_[1];
1620 return {};
1621}
1622
1623void
1624ConnectionManager::Impl::setPublishedAddress(const IpAddr& ip_addr)
1625{
1626 if (ip_addr.getFamily() == AF_INET) {
1627 publishedIp_[0] = ip_addr;
1628 } else {
1629 publishedIp_[1] = ip_addr;
1630 }
1631}
1632
1633void
1634ConnectionManager::Impl::storeActiveIpAddress(std::function<void()>&& cb)
1635{
Adrien Béraud75754b22023-10-17 09:16:06 -04001636 dht()->getPublicAddress([w=weak_from_this(), cb = std::move(cb)](std::vector<dht::SockAddr>&& results) {
Sébastien Blinb6504372023-10-12 10:35:35 -04001637 auto shared = w.lock();
1638 if (!shared)
1639 return;
Adrien Béraud612b55b2023-05-29 10:42:04 -04001640 bool hasIpv4 {false}, hasIpv6 {false};
1641 for (auto& result : results) {
1642 auto family = result.getFamily();
1643 if (family == AF_INET) {
1644 if (not hasIpv4) {
1645 hasIpv4 = true;
Sébastien Blinb6504372023-10-12 10:35:35 -04001646 if (shared->config_->logger)
1647 shared->config_->logger->debug("Store DHT public IPv4 address: {}", result);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001648 //JAMI_DBG("Store DHT public IPv4 address : %s", result.toString().c_str());
Sébastien Blinb6504372023-10-12 10:35:35 -04001649 shared->setPublishedAddress(*result.get());
1650 if (shared->config_->upnpCtrl) {
1651 shared->config_->upnpCtrl->setPublicAddress(*result.get());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001652 }
1653 }
1654 } else if (family == AF_INET6) {
1655 if (not hasIpv6) {
1656 hasIpv6 = true;
Sébastien Blinb6504372023-10-12 10:35:35 -04001657 if (shared->config_->logger)
1658 shared->config_->logger->debug("Store DHT public IPv6 address: {}", result);
1659 shared->setPublishedAddress(*result.get());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001660 }
1661 }
1662 if (hasIpv4 and hasIpv6)
1663 break;
1664 }
1665 if (cb)
1666 cb();
1667 });
1668}
1669
1670void
1671ConnectionManager::Impl::getIceOptions(std::function<void(IceTransportOptions&&)> cb) noexcept
1672{
1673 storeActiveIpAddress([this, cb = std::move(cb)] {
1674 IceTransportOptions opts = ConnectionManager::Impl::getIceOptions();
1675 auto publishedAddr = getPublishedIpAddress();
1676
1677 if (publishedAddr) {
1678 auto interfaceAddr = ip_utils::getInterfaceAddr(getLocalInterface(),
1679 publishedAddr.getFamily());
1680 if (interfaceAddr) {
1681 opts.accountLocalAddr = interfaceAddr;
1682 opts.accountPublicAddr = publishedAddr;
1683 }
1684 }
1685 if (cb)
1686 cb(std::move(opts));
1687 });
1688}
1689
1690IceTransportOptions
1691ConnectionManager::Impl::getIceOptions() const noexcept
1692{
1693 IceTransportOptions opts;
Sébastien Blin34086512023-07-25 09:52:14 -04001694 opts.factory = config_->factory;
Adrien Béraud612b55b2023-05-29 10:42:04 -04001695 opts.upnpEnable = getUPnPActive();
Adrien Béraud7b869d92023-08-21 09:02:35 -04001696 opts.upnpContext = config_->upnpCtrl ? config_->upnpCtrl->upnpContext() : nullptr;
Adrien Béraud612b55b2023-05-29 10:42:04 -04001697
1698 if (config_->stunEnabled)
1699 opts.stunServers.emplace_back(StunServerInfo().setUri(config_->stunServer));
1700 if (config_->turnEnabled) {
Sébastien Blin84bf4182023-07-21 14:18:39 -04001701 if (config_->turnCache) {
1702 auto turnAddr = config_->turnCache->getResolvedTurn();
1703 if (turnAddr != std::nullopt) {
1704 opts.turnServers.emplace_back(TurnServerInfo()
1705 .setUri(turnAddr->toString())
1706 .setUsername(config_->turnServerUserName)
1707 .setPassword(config_->turnServerPwd)
1708 .setRealm(config_->turnServerRealm));
1709 }
1710 } else {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001711 opts.turnServers.emplace_back(TurnServerInfo()
Sébastien Blin84bf4182023-07-21 14:18:39 -04001712 .setUri(config_->turnServer)
1713 .setUsername(config_->turnServerUserName)
1714 .setPassword(config_->turnServerPwd)
1715 .setRealm(config_->turnServerRealm));
Adrien Béraud612b55b2023-05-29 10:42:04 -04001716 }
1717 // NOTE: first test with ipv6 turn was not concluant and resulted in multiple
1718 // co issues. So this needs some debug. for now just disable
1719 // if (cacheTurnV6 && *cacheTurnV6) {
1720 // opts.turnServers.emplace_back(TurnServerInfo()
1721 // .setUri(cacheTurnV6->toString(true))
1722 // .setUsername(turnServerUserName_)
1723 // .setPassword(turnServerPwd_)
1724 // .setRealm(turnServerRealm_));
1725 //}
Adrien Béraud612b55b2023-05-29 10:42:04 -04001726 }
1727 return opts;
1728}
1729
1730bool
1731ConnectionManager::Impl::foundPeerDevice(const std::shared_ptr<dht::crypto::Certificate>& crt,
1732 dht::InfoHash& account_id,
1733 const std::shared_ptr<Logger>& logger)
1734{
1735 if (not crt)
1736 return false;
1737
1738 auto top_issuer = crt;
1739 while (top_issuer->issuer)
1740 top_issuer = top_issuer->issuer;
1741
1742 // Device certificate can't be self-signed
Adrien Béraudc631a832023-07-26 22:19:00 -04001743 if (top_issuer == crt) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001744 if (logger)
Adrien Béraud8b831a82023-07-21 14:13:06 -04001745 logger->warn("Found invalid (self-signed) peer device: {}", crt->getLongId());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001746 return false;
Adrien Béraudc631a832023-07-26 22:19:00 -04001747 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001748
1749 // Check peer certificate chain
1750 // Trust store with top issuer as the only CA
1751 dht::crypto::TrustList peer_trust;
1752 peer_trust.add(*top_issuer);
1753 if (not peer_trust.verify(*crt)) {
1754 if (logger)
1755 logger->warn("Found invalid peer device: {}", crt->getLongId());
1756 return false;
1757 }
1758
1759 // Check cached OCSP response
1760 if (crt->ocspResponse and crt->ocspResponse->getCertificateStatus() != GNUTLS_OCSP_CERT_GOOD) {
1761 if (logger)
Adrien Béraud8b831a82023-07-21 14:13:06 -04001762 logger->error("Certificate {} is disabled by cached OCSP response", crt->getLongId());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001763 return false;
1764 }
1765
Adrien Béraudc631a832023-07-26 22:19:00 -04001766 account_id = crt->issuer->getId();
1767 if (logger)
1768 logger->warn("Found peer device: {} account:{} CA:{}",
1769 crt->getLongId(),
1770 account_id,
1771 top_issuer->getId());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001772 return true;
1773}
1774
1775bool
1776ConnectionManager::Impl::findCertificate(
1777 const dht::PkId& id, std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb)
1778{
1779 if (auto cert = certStore().getCertificate(id.toString())) {
1780 if (cb)
1781 cb(cert);
1782 } else if (cb)
1783 cb(nullptr);
1784 return true;
1785}
1786
Sébastien Blin34086512023-07-25 09:52:14 -04001787bool
1788ConnectionManager::Impl::findCertificate(const dht::InfoHash& h,
1789 std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb)
1790{
1791 if (auto cert = certStore().getCertificate(h.toString())) {
1792 if (cb)
1793 cb(cert);
1794 } else {
1795 dht()->findCertificate(h,
1796 [cb = std::move(cb), this](
1797 const std::shared_ptr<dht::crypto::Certificate>& crt) {
1798 if (crt)
1799 certStore().pinCertificate(crt);
1800 if (cb)
1801 cb(crt);
1802 });
1803 }
1804 return true;
1805}
1806
Amna81221ad2023-09-14 17:33:26 -04001807std::shared_ptr<ConnectionManager::Config>
1808buildDefaultConfig(dht::crypto::Identity id){
1809 auto conf = std::make_shared<ConnectionManager::Config>();
1810 conf->id = std::move(id);
1811 return conf;
1812}
1813
Adrien Béraud612b55b2023-05-29 10:42:04 -04001814ConnectionManager::ConnectionManager(std::shared_ptr<ConnectionManager::Config> config_)
1815 : pimpl_ {std::make_shared<Impl>(config_)}
1816{}
1817
Amna81221ad2023-09-14 17:33:26 -04001818ConnectionManager::ConnectionManager(dht::crypto::Identity id)
1819 : ConnectionManager {buildDefaultConfig(id)}
1820{}
1821
Adrien Béraud612b55b2023-05-29 10:42:04 -04001822ConnectionManager::~ConnectionManager()
1823{
1824 if (pimpl_)
1825 pimpl_->shutdown();
1826}
1827
1828void
1829ConnectionManager::connectDevice(const DeviceId& deviceId,
1830 const std::string& name,
1831 ConnectCallback cb,
1832 bool noNewSocket,
1833 bool forceNewSocket,
1834 const std::string& connType)
1835{
1836 pimpl_->connectDevice(deviceId, name, std::move(cb), noNewSocket, forceNewSocket, connType);
1837}
1838
1839void
Amna0cf544d2023-07-25 14:25:09 -04001840ConnectionManager::connectDevice(const dht::InfoHash& deviceId,
1841 const std::string& name,
1842 ConnectCallbackLegacy cb,
1843 bool noNewSocket,
1844 bool forceNewSocket,
1845 const std::string& connType)
1846{
1847 pimpl_->connectDevice(deviceId, name, std::move(cb), noNewSocket, forceNewSocket, connType);
1848}
1849
1850
1851void
Adrien Béraud612b55b2023-05-29 10:42:04 -04001852ConnectionManager::connectDevice(const std::shared_ptr<dht::crypto::Certificate>& cert,
1853 const std::string& name,
1854 ConnectCallback cb,
1855 bool noNewSocket,
1856 bool forceNewSocket,
1857 const std::string& connType)
1858{
1859 pimpl_->connectDevice(cert, name, std::move(cb), noNewSocket, forceNewSocket, connType);
1860}
1861
1862bool
1863ConnectionManager::isConnecting(const DeviceId& deviceId, const std::string& name) const
1864{
Adrien Béraud75754b22023-10-17 09:16:06 -04001865 if (auto dinfo = pimpl_->infos_.getDeviceInfo(deviceId)) {
1866 std::unique_lock<std::mutex> lk {dinfo->mtx_};
Adrien Béraudb941e922023-10-16 12:56:14 -04001867 return dinfo->isConnecting(name);
Adrien Béraud75754b22023-10-17 09:16:06 -04001868 }
1869 return false;
Adrien Béraud612b55b2023-05-29 10:42:04 -04001870}
1871
1872void
1873ConnectionManager::closeConnectionsWith(const std::string& peerUri)
1874{
Adrien Béraud75754b22023-10-17 09:16:06 -04001875 std::vector<std::shared_ptr<DeviceInfo>> dInfos;
1876 for (const auto& dinfo: pimpl_->infos_.getDeviceInfos()) {
1877 std::unique_lock<std::mutex> lk(dinfo->mtx_);
1878 bool isPeer = false;
1879 for (auto const& [id, cinfo]: dinfo->info) {
1880 std::lock_guard<std::mutex> lkv {cinfo->mutex_};
1881 auto tls = cinfo->tls_ ? cinfo->tls_.get() : (cinfo->socket_ ? cinfo->socket_->endpoint() : nullptr);
Adrien Béraudafa8e282023-09-24 12:53:20 -04001882 auto cert = tls ? tls->peerCertificate() : nullptr;
1883 if (not cert)
Adrien Béraud75754b22023-10-17 09:16:06 -04001884 cert = pimpl_->certStore().getCertificate(dinfo->deviceId.toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001885 if (cert && cert->issuer && peerUri == cert->issuer->getId().toString()) {
Adrien Béraud75754b22023-10-17 09:16:06 -04001886 isPeer = true;
1887 break;
Adrien Béraud612b55b2023-05-29 10:42:04 -04001888 }
1889 }
Adrien Béraud75754b22023-10-17 09:16:06 -04001890 lk.unlock();
1891 if (isPeer) {
1892 dInfos.emplace_back(std::move(dinfo));
1893 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001894 }
1895 // Stop connections to all peers devices
Adrien Béraud75754b22023-10-17 09:16:06 -04001896 for (const auto& dinfo : dInfos) {
1897 std::unique_lock<std::mutex> lk {dinfo->mtx_};
1898 auto unused = dinfo->extractUnusedConnections();
1899 auto pending = dinfo->extractPendingOperations(0, nullptr);
1900 pimpl_->infos_.removeDeviceInfo(dinfo->deviceId);
1901 lk.unlock();
1902 for (auto& op : unused)
1903 op->shutdown();
1904 for (auto& op : pending)
1905 op.cb(nullptr, dinfo->deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001906 }
1907}
1908
1909void
1910ConnectionManager::onDhtConnected(const dht::crypto::PublicKey& devicePk)
1911{
1912 pimpl_->onDhtConnected(devicePk);
1913}
1914
1915void
1916ConnectionManager::onICERequest(onICERequestCallback&& cb)
1917{
1918 pimpl_->iceReqCb_ = std::move(cb);
1919}
1920
1921void
1922ConnectionManager::onChannelRequest(ChannelRequestCallback&& cb)
1923{
1924 pimpl_->channelReqCb_ = std::move(cb);
1925}
1926
1927void
1928ConnectionManager::onConnectionReady(ConnectionReadyCallback&& cb)
1929{
1930 pimpl_->connReadyCb_ = std::move(cb);
1931}
1932
1933void
1934ConnectionManager::oniOSConnected(iOSConnectedCallback&& cb)
1935{
1936 pimpl_->iOSConnectedCb_ = std::move(cb);
1937}
1938
1939std::size_t
1940ConnectionManager::activeSockets() const
1941{
Adrien Béraud75754b22023-10-17 09:16:06 -04001942 return pimpl_->infos_.getConnectedInfos().size();
Adrien Béraud612b55b2023-05-29 10:42:04 -04001943}
1944
1945void
1946ConnectionManager::monitor() const
1947{
Adrien Béraud612b55b2023-05-29 10:42:04 -04001948 auto logger = pimpl_->config_->logger;
1949 if (!logger)
1950 return;
1951 logger->debug("ConnectionManager current status:");
Adrien Béraud75754b22023-10-17 09:16:06 -04001952 for (const auto& ci : pimpl_->infos_.getConnectedInfos()) {
1953 std::lock_guard<std::mutex> lk(ci->mutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001954 if (ci->socket_)
1955 ci->socket_->monitor();
1956 }
1957 logger->debug("ConnectionManager end status.");
1958}
1959
1960void
1961ConnectionManager::connectivityChanged()
1962{
Adrien Béraud75754b22023-10-17 09:16:06 -04001963 for (const auto& ci : pimpl_->infos_.getConnectedInfos()) {
1964 std::lock_guard<std::mutex> lk(ci->mutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001965 if (ci->socket_)
Adrien Béraud51a54712023-10-17 21:24:30 -04001966 dht::ThreadPool::io().run([s = ci->socket_] { s->sendBeacon(); });
Adrien Béraud612b55b2023-05-29 10:42:04 -04001967 }
1968}
1969
1970void
1971ConnectionManager::getIceOptions(std::function<void(IceTransportOptions&&)> cb) noexcept
1972{
1973 return pimpl_->getIceOptions(std::move(cb));
1974}
1975
1976IceTransportOptions
1977ConnectionManager::getIceOptions() const noexcept
1978{
1979 return pimpl_->getIceOptions();
1980}
1981
1982IpAddr
1983ConnectionManager::getPublishedIpAddress(uint16_t family) const
1984{
1985 return pimpl_->getPublishedIpAddress(family);
1986}
1987
1988void
1989ConnectionManager::setPublishedAddress(const IpAddr& ip_addr)
1990{
1991 return pimpl_->setPublishedAddress(ip_addr);
1992}
1993
1994void
1995ConnectionManager::storeActiveIpAddress(std::function<void()>&& cb)
1996{
1997 return pimpl_->storeActiveIpAddress(std::move(cb));
1998}
1999
2000std::shared_ptr<ConnectionManager::Config>
2001ConnectionManager::getConfig()
2002{
2003 return pimpl_->config_;
2004}
2005
Amna31791e52023-08-03 12:40:57 -04002006std::vector<std::map<std::string, std::string>>
2007ConnectionManager::getConnectionList(const DeviceId& device) const
2008{
2009 std::vector<std::map<std::string, std::string>> connectionsList;
Amna31791e52023-08-03 12:40:57 -04002010 if (device) {
Adrien Béraud75754b22023-10-17 09:16:06 -04002011 if (auto deviceInfo = pimpl_->infos_.getDeviceInfo(device)) {
2012 connectionsList = deviceInfo->getConnectionList(pimpl_->certStore());
Amna31791e52023-08-03 12:40:57 -04002013 }
Adrien Béraud75754b22023-10-17 09:16:06 -04002014 } else {
2015 for (const auto& deviceInfo : pimpl_->infos_.getDeviceInfos()) {
2016 auto cl = deviceInfo->getConnectionList(pimpl_->certStore());
2017 connectionsList.insert(connectionsList.end(), std::make_move_iterator(cl.begin()), std::make_move_iterator(cl.end()));
Amna31791e52023-08-03 12:40:57 -04002018 }
2019 }
2020 return connectionsList;
2021}
2022
2023std::vector<std::map<std::string, std::string>>
2024ConnectionManager::getChannelList(const std::string& connectionId) const
2025{
Adrien Béraud75754b22023-10-17 09:16:06 -04002026 auto [deviceId, valueId] = parseCallbackId(connectionId);
2027 if (auto info = pimpl_->infos_.getInfo(deviceId, valueId)) {
2028 std::lock_guard<std::mutex> lk(info->mutex_);
2029 if (info->socket_)
2030 return info->socket_->getChannelList();
Amna31791e52023-08-03 12:40:57 -04002031 }
Adrien Béraud75754b22023-10-17 09:16:06 -04002032 return {};
Amna31791e52023-08-03 12:40:57 -04002033}
2034
Sébastien Blin464bdff2023-07-19 08:02:53 -04002035} // namespace dhtnet