blob: 7c3c8d22cdfd12797cc17fd63ded5443f2a8e4f8 [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 }
Sébastien Blin3cf0acc2023-10-23 09:45:32 -04001188
1189 std::unique_lock<std::mutex> lk(dinfo->mtx_);
1190 dinfo->info.erase(vid);
1191
1192 if (dinfo->empty()) {
1193 infos_.removeDeviceInfo(dinfo->deviceId);
1194 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001195 } else {
1196 // The socket is ready, store it
1197 if (isDhtRequest) {
1198 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001199 config_->logger->debug("[device {}] Connection is ready - Initied by DHT request. Vid: {}",
Adrien Béraud612b55b2023-05-29 10:42:04 -04001200 deviceId,
1201 vid);
1202 } else {
1203 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001204 config_->logger->debug("[device {}] Connection is ready - Initied by connectDevice(). channel: {} - vid: {}",
Adrien Béraud612b55b2023-05-29 10:42:04 -04001205 deviceId,
1206 name,
1207 vid);
1208 }
1209
Adrien Béraud75754b22023-10-17 09:16:06 -04001210 // Note: do not remove pending there it's done in sendChannelRequest
1211 std::unique_lock<std::mutex> lk2 {dinfo->mtx_};
Adrien Béraudb941e922023-10-16 12:56:14 -04001212 auto pendingIds = dinfo->requestPendingOps();
Adrien Béraud75754b22023-10-17 09:16:06 -04001213 lk2.unlock();
1214 std::unique_lock<std::mutex> lk {info->mutex_};
1215 addNewMultiplexedSocket(dinfo, deviceId, vid, info);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001216 // Finally, open the channel and launch pending callbacks
Adrien Béraud75754b22023-10-17 09:16:06 -04001217 lk.unlock();
1218 for (const auto& [id, name]: pendingIds) {
1219 if (config_->logger)
1220 config_->logger->debug("[device {}] Send request on TLS socket for channel {}",
1221 deviceId, name);
1222 sendChannelRequest(dinfo, info->socket_, name, id);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001223 }
1224 }
1225}
1226
1227void
1228ConnectionManager::Impl::answerTo(IceTransport& ice,
1229 const dht::Value::Id& id,
1230 const std::shared_ptr<dht::crypto::PublicKey>& from)
1231{
1232 // NOTE: This is a shortest version of a real SDP message to save some bits
1233 auto iceAttributes = ice.getLocalAttributes();
1234 std::ostringstream icemsg;
1235 icemsg << iceAttributes.ufrag << "\n";
1236 icemsg << iceAttributes.pwd << "\n";
1237 for (const auto& addr : ice.getLocalCandidates(1)) {
1238 icemsg << addr << "\n";
1239 }
1240
1241 // Send PeerConnection response
1242 PeerConnectionRequest val;
1243 val.id = id;
1244 val.ice_msg = icemsg.str();
1245 val.isAnswer = true;
1246 auto value = std::make_shared<dht::Value>(std::move(val));
1247 value->user_type = "peer_request";
1248
1249 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001250 config_->logger->debug("[device {}] Connection accepted, DHT reply", from->getLongId());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001251 dht()->putEncrypted(dht::InfoHash::get(PeerConnectionRequest::key_prefix
1252 + from->getId().toString()),
1253 from,
1254 value,
1255 [from,l=config_->logger](bool ok) {
1256 if (l)
Adrien Béraud23852462023-07-22 01:46:27 -04001257 l->debug("[device {}] Answer to connection request: put encrypted {:s}",
Adrien Béraud612b55b2023-05-29 10:42:04 -04001258 from->getLongId(),
1259 (ok ? "ok" : "failed"));
1260 });
1261}
1262
1263bool
Adrien Béraud75754b22023-10-17 09:16:06 -04001264ConnectionManager::Impl::onRequestStartIce(const std::shared_ptr<ConnectionInfo>& info, const PeerConnectionRequest& req)
Adrien Béraud612b55b2023-05-29 10:42:04 -04001265{
Adrien Béraud612b55b2023-05-29 10:42:04 -04001266 if (!info)
1267 return false;
1268
Adrien Béraud75754b22023-10-17 09:16:06 -04001269 auto deviceId = req.owner->getLongId();
Adrien Béraud612b55b2023-05-29 10:42:04 -04001270 std::unique_lock<std::mutex> lk {info->mutex_};
1271 auto& ice = info->ice_;
1272 if (!ice) {
1273 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001274 config_->logger->error("[device {}] No ICE detected", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001275 if (connReadyCb_)
1276 connReadyCb_(deviceId, "", nullptr);
1277 return false;
1278 }
1279
1280 auto sdp = ice->parseIceCandidates(req.ice_msg);
1281 answerTo(*ice, req.id, req.owner);
1282 if (not ice->startIce({sdp.rem_ufrag, sdp.rem_pwd}, std::move(sdp.rem_candidates))) {
1283 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001284 config_->logger->error("[device {}] Start ICE failed", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001285 ice = nullptr;
1286 if (connReadyCb_)
1287 connReadyCb_(deviceId, "", nullptr);
1288 return false;
1289 }
1290 return true;
1291}
1292
1293bool
Adrien Béraud75754b22023-10-17 09:16:06 -04001294ConnectionManager::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 -04001295{
Adrien Béraud612b55b2023-05-29 10:42:04 -04001296 if (!info)
1297 return false;
1298
Adrien Béraud75754b22023-10-17 09:16:06 -04001299 auto deviceId = req.owner->getLongId();
Adrien Béraud612b55b2023-05-29 10:42:04 -04001300 std::unique_lock<std::mutex> lk {info->mutex_};
1301 auto& ice = info->ice_;
1302 if (!ice) {
1303 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001304 config_->logger->error("[device {}] No ICE detected", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001305 return false;
1306 }
1307
1308 // Build socket
1309 auto endpoint = std::make_unique<IceSocketEndpoint>(std::shared_ptr<IceTransport>(
1310 std::move(ice)),
1311 false);
1312
1313 // init TLS session
1314 auto ph = req.from;
1315 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001316 config_->logger->debug("[device {}] Start TLS session - Initied by DHT request. vid: {}",
1317 deviceId,
Adrien Béraud612b55b2023-05-29 10:42:04 -04001318 req.id);
1319 info->tls_ = std::make_unique<TlsSocketEndpoint>(
1320 std::move(endpoint),
1321 certStore(),
Adrien Béraud3f93ddf2023-07-21 14:46:22 -04001322 config_->ioContext,
Adrien Béraud612b55b2023-05-29 10:42:04 -04001323 identity(),
1324 dhParams(),
Adrien Béraud75754b22023-10-17 09:16:06 -04001325 [ph, deviceId, w=weak_from_this(), l=config_->logger](const dht::crypto::Certificate& cert) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001326 auto shared = w.lock();
1327 if (!shared)
1328 return false;
Adrien Béraud9efbd442023-08-27 12:38:07 -04001329 if (cert.getPublicKey().getId() != ph
1330 || deviceId != cert.getPublicKey().getLongId()) {
1331 if (l) l->warn("[device {}] TLS certificate with ID {} doesn't match the DHT request.",
1332 deviceId,
1333 cert.getPublicKey().getLongId());
1334 return false;
1335 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001336 auto crt = shared->certStore().getCertificate(cert.getLongId().toString());
1337 if (!crt)
1338 return false;
1339 return crt->getPacked() == cert.getPacked();
1340 });
1341
1342 info->tls_->setOnReady(
Adrien Béraud75754b22023-10-17 09:16:06 -04001343 [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 -04001344 if (auto shared = w.lock())
Adrien Béraud75754b22023-10-17 09:16:06 -04001345 shared->onTlsNegotiationDone(dinfo.lock(), winfo.lock(), ok, deviceId, vid);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001346 });
1347 return true;
1348}
1349
1350void
1351ConnectionManager::Impl::onDhtPeerRequest(const PeerConnectionRequest& req,
1352 const std::shared_ptr<dht::crypto::Certificate>& /*cert*/)
1353{
1354 auto deviceId = req.owner->getLongId();
1355 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001356 config_->logger->debug("[device {}] New connection request", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001357 if (!iceReqCb_ || !iceReqCb_(deviceId)) {
1358 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001359 config_->logger->debug("[device {}] Refusing connection", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001360 return;
1361 }
1362
1363 // Because the connection is accepted, create an ICE socket.
Adrien Béraud75754b22023-10-17 09:16:06 -04001364 getIceOptions([w = weak_from_this(), req, deviceId](auto&& ice_config) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001365 auto shared = w.lock();
1366 if (!shared)
1367 return;
Adrien Béraud75754b22023-10-17 09:16:06 -04001368
1369 auto di = shared->infos_.createDeviceInfo(deviceId);
1370 auto info = std::make_shared<ConnectionInfo>();
1371 auto wdi = std::weak_ptr(di);
1372 auto winfo = std::weak_ptr(info);
1373
Adrien Béraud612b55b2023-05-29 10:42:04 -04001374 // Note: used when the ice negotiation fails to erase
1375 // all stored structures.
Adrien Béraud75754b22023-10-17 09:16:06 -04001376 auto eraseInfo = [w, wdi, id = req.id] {
1377 auto shared = w.lock();
1378 if (auto di = wdi.lock()) {
1379 std::unique_lock<std::mutex> lk(di->mtx_);
1380 di->info.erase(id);
1381 auto ops = di->extractPendingOperations(id, nullptr);
1382 if (di->empty()) {
1383 if (shared)
1384 shared->infos_.removeDeviceInfo(di->deviceId);
1385 }
1386 lk.unlock();
1387 for (const auto& op: ops)
1388 op.cb(nullptr, di->deviceId);
1389 if (shared && shared->connReadyCb_)
1390 shared->connReadyCb_(di->deviceId, "", nullptr);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001391 }
1392 };
1393
Adrien Béraud75754b22023-10-17 09:16:06 -04001394 ice_config.master = true;
1395 ice_config.streamsCount = 1;
1396 ice_config.compCountPerStream = 1; // TCP
Adrien Béraud612b55b2023-05-29 10:42:04 -04001397 ice_config.tcpEnable = true;
Adrien Béraud75754b22023-10-17 09:16:06 -04001398 ice_config.onInitDone = [w, winfo, req, eraseInfo](bool ok) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001399 auto shared = w.lock();
1400 if (!shared)
1401 return;
1402 if (!ok) {
1403 if (shared->config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001404 shared->config_->logger->error("[device {}] Cannot initialize ICE session.", req.owner->getLongId());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001405 dht::ThreadPool::io().run([eraseInfo = std::move(eraseInfo)] { eraseInfo(); });
1406 return;
1407 }
1408
1409 dht::ThreadPool::io().run(
Adrien Béraud75754b22023-10-17 09:16:06 -04001410 [w = std::move(w), winfo = std::move(winfo), req = std::move(req), eraseInfo = std::move(eraseInfo)] {
1411 if (auto shared = w.lock()) {
1412 if (!shared->onRequestStartIce(winfo.lock(), req))
1413 eraseInfo();
1414 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001415 });
1416 };
1417
Adrien Béraud75754b22023-10-17 09:16:06 -04001418 ice_config.onNegoDone = [w, wdi, winfo, req, eraseInfo](bool ok) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001419 auto shared = w.lock();
1420 if (!shared)
1421 return;
1422 if (!ok) {
1423 if (shared->config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001424 shared->config_->logger->error("[device {}] ICE negotiation failed.", req.owner->getLongId());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001425 dht::ThreadPool::io().run([eraseInfo = std::move(eraseInfo)] { eraseInfo(); });
1426 return;
1427 }
1428
1429 dht::ThreadPool::io().run(
Adrien Béraud75754b22023-10-17 09:16:06 -04001430 [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 -04001431 if (auto shared = w.lock())
Adrien Béraud75754b22023-10-17 09:16:06 -04001432 if (!shared->onRequestOnNegoDone(wdi.lock(), winfo.lock(), req))
Adrien Béraud612b55b2023-05-29 10:42:04 -04001433 eraseInfo();
1434 });
1435 };
1436
1437 // Negotiate a new ICE socket
Adrien Béraud612b55b2023-05-29 10:42:04 -04001438 {
Adrien Béraud75754b22023-10-17 09:16:06 -04001439 std::lock_guard<std::mutex> lk(di->mtx_);
1440 di->info[req.id] = info;
Adrien Béraud612b55b2023-05-29 10:42:04 -04001441 }
Adrien Béraud75754b22023-10-17 09:16:06 -04001442
Adrien Béraud612b55b2023-05-29 10:42:04 -04001443 if (shared->config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001444 shared->config_->logger->debug("[device {}] Accepting connection", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001445 std::unique_lock<std::mutex> lk {info->mutex_};
Sébastien Blin34086512023-07-25 09:52:14 -04001446 info->ice_ = shared->config_->factory->createUTransport("");
Adrien Béraud612b55b2023-05-29 10:42:04 -04001447 if (not info->ice_) {
1448 if (shared->config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001449 shared->config_->logger->error("[device {}] Cannot initialize ICE session", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001450 eraseInfo();
1451 return;
1452 }
1453 // We need to detect any shutdown if the ice session is destroyed before going to the TLS session;
1454 info->ice_->setOnShutdown([eraseInfo]() {
1455 dht::ThreadPool::io().run([eraseInfo = std::move(eraseInfo)] { eraseInfo(); });
1456 });
Adrien Béraud4cda2d72023-06-01 15:44:43 -04001457 try {
1458 info->ice_->initIceInstance(ice_config);
1459 } catch (const std::exception& e) {
1460 if (shared->config_->logger)
1461 shared->config_->logger->error("{}", e.what());
1462 dht::ThreadPool::io().run([eraseInfo = std::move(eraseInfo)] { eraseInfo(); });
1463 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001464 });
1465}
1466
1467void
Adrien Béraud75754b22023-10-17 09:16:06 -04001468ConnectionManager::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 -04001469{
Adrien Béraud75754b22023-10-17 09:16:06 -04001470 info->socket_ = std::make_shared<MultiplexedSocket>(config_->ioContext, deviceId, std::move(info->tls_), config_->logger);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001471 info->socket_->setOnReady(
Adrien Béraud75754b22023-10-17 09:16:06 -04001472 [w = weak_from_this()](const DeviceId& deviceId, const std::shared_ptr<ChannelSocket>& socket) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001473 if (auto sthis = w.lock())
1474 if (sthis->connReadyCb_)
1475 sthis->connReadyCb_(deviceId, socket->name(), socket);
1476 });
Adrien Béraud75754b22023-10-17 09:16:06 -04001477 info->socket_->setOnRequest([w = weak_from_this()](const std::shared_ptr<dht::crypto::Certificate>& peer,
Adrien Béraud612b55b2023-05-29 10:42:04 -04001478 const uint16_t&,
1479 const std::string& name) {
1480 if (auto sthis = w.lock())
1481 if (sthis->channelReqCb_)
1482 return sthis->channelReqCb_(peer, name);
1483 return false;
1484 });
Adrien Béraud75754b22023-10-17 09:16:06 -04001485 info->socket_->onShutdown([dinfo, wi=std::weak_ptr(info), vid]() {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001486 // Cancel current outgoing connections
Adrien Béraud75754b22023-10-17 09:16:06 -04001487 dht::ThreadPool::io().run([dinfo, wi, vid] {
1488 std::set<dht::Value::Id> ids;
1489 if (auto info = wi.lock()) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001490 std::lock_guard<std::mutex> lk(info->mutex_);
1491 if (info->socket_) {
1492 ids = std::move(info->cbIds_);
1493 info->socket_->shutdown();
1494 }
1495 }
Adrien Béraud75754b22023-10-17 09:16:06 -04001496 if (auto deviceInfo = dinfo.lock()) {
1497 std::shared_ptr<ConnectionInfo> info;
1498 std::vector<PendingCb> ops;
1499 std::unique_lock<std::mutex> lk(deviceInfo->mtx_);
1500 auto it = deviceInfo->info.find(vid);
1501 if (it != deviceInfo->info.end()) {
1502 info = std::move(it->second);
1503 deviceInfo->info.erase(it);
1504 }
1505 for (const auto& cbId : ids) {
1506 auto po = deviceInfo->extractPendingOperations(cbId, nullptr);
1507 ops.insert(ops.end(), po.begin(), po.end());
1508 }
1509 lk.unlock();
1510 for (auto& op : ops)
1511 op.cb(nullptr, deviceInfo->deviceId);
1512 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001513 });
1514 });
1515}
1516
1517const std::shared_future<tls::DhParams>
1518ConnectionManager::Impl::dhParams() const
1519{
1520 return dht::ThreadPool::computation().get<tls::DhParams>(
Adrien Béraud2a4e73d2023-08-27 12:53:55 -04001521 std::bind(tls::DhParams::loadDhParams, config_->cachePath / "dhParams"));
Adrien Béraud612b55b2023-05-29 10:42:04 -04001522}
1523
1524template<typename ID = dht::Value::Id>
1525std::set<ID, std::less<>>
Adrien Béraud1299a0d2023-09-19 15:03:28 -04001526loadIdList(const std::filesystem::path& path)
Adrien Béraud612b55b2023-05-29 10:42:04 -04001527{
1528 std::set<ID, std::less<>> ids;
Adrien Béraud1299a0d2023-09-19 15:03:28 -04001529 std::ifstream file(path);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001530 if (!file.is_open()) {
1531 //JAMI_DBG("Could not load %s", path.c_str());
1532 return ids;
1533 }
1534 std::string line;
1535 while (std::getline(file, line)) {
1536 if constexpr (std::is_same<ID, std::string>::value) {
1537 ids.emplace(std::move(line));
1538 } else if constexpr (std::is_integral<ID>::value) {
1539 ID vid;
1540 if (auto [p, ec] = std::from_chars(line.data(), line.data() + line.size(), vid, 16);
1541 ec == std::errc()) {
1542 ids.emplace(vid);
1543 }
1544 }
1545 }
1546 return ids;
1547}
1548
1549template<typename List = std::set<dht::Value::Id>>
1550void
Adrien Béraud2a4e73d2023-08-27 12:53:55 -04001551saveIdList(const std::filesystem::path& path, const List& ids)
Adrien Béraud612b55b2023-05-29 10:42:04 -04001552{
Adrien Béraud1299a0d2023-09-19 15:03:28 -04001553 std::ofstream file(path, std::ios::trunc | std::ios::binary);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001554 if (!file.is_open()) {
1555 //JAMI_ERR("Could not save to %s", path.c_str());
1556 return;
1557 }
1558 for (auto& c : ids)
1559 file << std::hex << c << "\n";
1560}
1561
1562void
1563ConnectionManager::Impl::loadTreatedMessages()
1564{
1565 std::lock_guard<std::mutex> lock(messageMutex_);
Adrien Béraud2a4e73d2023-08-27 12:53:55 -04001566 auto path = config_->cachePath / "treatedMessages";
Aline Gondim Santos406c0f42023-09-13 12:10:23 -03001567 treatedMessages_ = loadIdList<std::string>(path.string());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001568 if (treatedMessages_.empty()) {
Aline Gondim Santos406c0f42023-09-13 12:10:23 -03001569 auto messages = loadIdList(path.string());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001570 for (const auto& m : messages)
1571 treatedMessages_.emplace(to_hex_string(m));
1572 }
1573}
1574
1575void
1576ConnectionManager::Impl::saveTreatedMessages() const
1577{
Adrien Béraud75754b22023-10-17 09:16:06 -04001578 dht::ThreadPool::io().run([w = weak_from_this()]() {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001579 if (auto sthis = w.lock()) {
1580 auto& this_ = *sthis;
1581 std::lock_guard<std::mutex> lock(this_.messageMutex_);
1582 fileutils::check_dir(this_.config_->cachePath.c_str());
Adrien Béraud2a4e73d2023-08-27 12:53:55 -04001583 saveIdList<decltype(this_.treatedMessages_)>(this_.config_->cachePath / "treatedMessages",
Adrien Béraud612b55b2023-05-29 10:42:04 -04001584 this_.treatedMessages_);
1585 }
1586 });
1587}
1588
1589bool
1590ConnectionManager::Impl::isMessageTreated(std::string_view id)
1591{
1592 std::lock_guard<std::mutex> lock(messageMutex_);
1593 auto res = treatedMessages_.emplace(id);
1594 if (res.second) {
1595 saveTreatedMessages();
1596 return false;
1597 }
1598 return true;
1599}
1600
1601/**
1602 * returns whether or not UPnP is enabled and active_
1603 * ie: if it is able to make port mappings
1604 */
1605bool
1606ConnectionManager::Impl::getUPnPActive() const
1607{
1608 return config_->getUPnPActive();
1609}
1610
1611IpAddr
1612ConnectionManager::Impl::getPublishedIpAddress(uint16_t family) const
1613{
1614 if (family == AF_INET)
1615 return publishedIp_[0];
1616 if (family == AF_INET6)
1617 return publishedIp_[1];
1618
1619 assert(family == AF_UNSPEC);
1620
1621 // If family is not set, prefere IPv4 if available. It's more
1622 // likely to succeed behind NAT.
1623 if (publishedIp_[0])
1624 return publishedIp_[0];
1625 if (publishedIp_[1])
1626 return publishedIp_[1];
1627 return {};
1628}
1629
1630void
1631ConnectionManager::Impl::setPublishedAddress(const IpAddr& ip_addr)
1632{
1633 if (ip_addr.getFamily() == AF_INET) {
1634 publishedIp_[0] = ip_addr;
1635 } else {
1636 publishedIp_[1] = ip_addr;
1637 }
1638}
1639
1640void
1641ConnectionManager::Impl::storeActiveIpAddress(std::function<void()>&& cb)
1642{
Adrien Béraud75754b22023-10-17 09:16:06 -04001643 dht()->getPublicAddress([w=weak_from_this(), cb = std::move(cb)](std::vector<dht::SockAddr>&& results) {
Sébastien Blinb6504372023-10-12 10:35:35 -04001644 auto shared = w.lock();
1645 if (!shared)
1646 return;
Adrien Béraud612b55b2023-05-29 10:42:04 -04001647 bool hasIpv4 {false}, hasIpv6 {false};
1648 for (auto& result : results) {
1649 auto family = result.getFamily();
1650 if (family == AF_INET) {
1651 if (not hasIpv4) {
1652 hasIpv4 = true;
Sébastien Blinb6504372023-10-12 10:35:35 -04001653 if (shared->config_->logger)
1654 shared->config_->logger->debug("Store DHT public IPv4 address: {}", result);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001655 //JAMI_DBG("Store DHT public IPv4 address : %s", result.toString().c_str());
Sébastien Blinb6504372023-10-12 10:35:35 -04001656 shared->setPublishedAddress(*result.get());
1657 if (shared->config_->upnpCtrl) {
1658 shared->config_->upnpCtrl->setPublicAddress(*result.get());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001659 }
1660 }
1661 } else if (family == AF_INET6) {
1662 if (not hasIpv6) {
1663 hasIpv6 = true;
Sébastien Blinb6504372023-10-12 10:35:35 -04001664 if (shared->config_->logger)
1665 shared->config_->logger->debug("Store DHT public IPv6 address: {}", result);
1666 shared->setPublishedAddress(*result.get());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001667 }
1668 }
1669 if (hasIpv4 and hasIpv6)
1670 break;
1671 }
1672 if (cb)
1673 cb();
1674 });
1675}
1676
1677void
1678ConnectionManager::Impl::getIceOptions(std::function<void(IceTransportOptions&&)> cb) noexcept
1679{
1680 storeActiveIpAddress([this, cb = std::move(cb)] {
1681 IceTransportOptions opts = ConnectionManager::Impl::getIceOptions();
1682 auto publishedAddr = getPublishedIpAddress();
1683
1684 if (publishedAddr) {
1685 auto interfaceAddr = ip_utils::getInterfaceAddr(getLocalInterface(),
1686 publishedAddr.getFamily());
1687 if (interfaceAddr) {
1688 opts.accountLocalAddr = interfaceAddr;
1689 opts.accountPublicAddr = publishedAddr;
1690 }
1691 }
1692 if (cb)
1693 cb(std::move(opts));
1694 });
1695}
1696
1697IceTransportOptions
1698ConnectionManager::Impl::getIceOptions() const noexcept
1699{
1700 IceTransportOptions opts;
Sébastien Blin34086512023-07-25 09:52:14 -04001701 opts.factory = config_->factory;
Adrien Béraud612b55b2023-05-29 10:42:04 -04001702 opts.upnpEnable = getUPnPActive();
Adrien Béraud7b869d92023-08-21 09:02:35 -04001703 opts.upnpContext = config_->upnpCtrl ? config_->upnpCtrl->upnpContext() : nullptr;
Adrien Béraud612b55b2023-05-29 10:42:04 -04001704
1705 if (config_->stunEnabled)
1706 opts.stunServers.emplace_back(StunServerInfo().setUri(config_->stunServer));
1707 if (config_->turnEnabled) {
Sébastien Blin84bf4182023-07-21 14:18:39 -04001708 if (config_->turnCache) {
1709 auto turnAddr = config_->turnCache->getResolvedTurn();
1710 if (turnAddr != std::nullopt) {
1711 opts.turnServers.emplace_back(TurnServerInfo()
1712 .setUri(turnAddr->toString())
1713 .setUsername(config_->turnServerUserName)
1714 .setPassword(config_->turnServerPwd)
1715 .setRealm(config_->turnServerRealm));
1716 }
1717 } else {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001718 opts.turnServers.emplace_back(TurnServerInfo()
Sébastien Blin84bf4182023-07-21 14:18:39 -04001719 .setUri(config_->turnServer)
1720 .setUsername(config_->turnServerUserName)
1721 .setPassword(config_->turnServerPwd)
1722 .setRealm(config_->turnServerRealm));
Adrien Béraud612b55b2023-05-29 10:42:04 -04001723 }
1724 // NOTE: first test with ipv6 turn was not concluant and resulted in multiple
1725 // co issues. So this needs some debug. for now just disable
1726 // if (cacheTurnV6 && *cacheTurnV6) {
1727 // opts.turnServers.emplace_back(TurnServerInfo()
1728 // .setUri(cacheTurnV6->toString(true))
1729 // .setUsername(turnServerUserName_)
1730 // .setPassword(turnServerPwd_)
1731 // .setRealm(turnServerRealm_));
1732 //}
Adrien Béraud612b55b2023-05-29 10:42:04 -04001733 }
1734 return opts;
1735}
1736
1737bool
1738ConnectionManager::Impl::foundPeerDevice(const std::shared_ptr<dht::crypto::Certificate>& crt,
1739 dht::InfoHash& account_id,
1740 const std::shared_ptr<Logger>& logger)
1741{
1742 if (not crt)
1743 return false;
1744
1745 auto top_issuer = crt;
1746 while (top_issuer->issuer)
1747 top_issuer = top_issuer->issuer;
1748
1749 // Device certificate can't be self-signed
Adrien Béraudc631a832023-07-26 22:19:00 -04001750 if (top_issuer == crt) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001751 if (logger)
Adrien Béraud8b831a82023-07-21 14:13:06 -04001752 logger->warn("Found invalid (self-signed) peer device: {}", crt->getLongId());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001753 return false;
Adrien Béraudc631a832023-07-26 22:19:00 -04001754 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001755
1756 // Check peer certificate chain
1757 // Trust store with top issuer as the only CA
1758 dht::crypto::TrustList peer_trust;
1759 peer_trust.add(*top_issuer);
1760 if (not peer_trust.verify(*crt)) {
1761 if (logger)
1762 logger->warn("Found invalid peer device: {}", crt->getLongId());
1763 return false;
1764 }
1765
1766 // Check cached OCSP response
1767 if (crt->ocspResponse and crt->ocspResponse->getCertificateStatus() != GNUTLS_OCSP_CERT_GOOD) {
1768 if (logger)
Adrien Béraud8b831a82023-07-21 14:13:06 -04001769 logger->error("Certificate {} is disabled by cached OCSP response", crt->getLongId());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001770 return false;
1771 }
1772
Adrien Béraudc631a832023-07-26 22:19:00 -04001773 account_id = crt->issuer->getId();
1774 if (logger)
1775 logger->warn("Found peer device: {} account:{} CA:{}",
1776 crt->getLongId(),
1777 account_id,
1778 top_issuer->getId());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001779 return true;
1780}
1781
1782bool
1783ConnectionManager::Impl::findCertificate(
1784 const dht::PkId& id, std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb)
1785{
1786 if (auto cert = certStore().getCertificate(id.toString())) {
1787 if (cb)
1788 cb(cert);
1789 } else if (cb)
1790 cb(nullptr);
1791 return true;
1792}
1793
Sébastien Blin34086512023-07-25 09:52:14 -04001794bool
1795ConnectionManager::Impl::findCertificate(const dht::InfoHash& h,
1796 std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb)
1797{
1798 if (auto cert = certStore().getCertificate(h.toString())) {
1799 if (cb)
1800 cb(cert);
1801 } else {
1802 dht()->findCertificate(h,
1803 [cb = std::move(cb), this](
1804 const std::shared_ptr<dht::crypto::Certificate>& crt) {
1805 if (crt)
1806 certStore().pinCertificate(crt);
1807 if (cb)
1808 cb(crt);
1809 });
1810 }
1811 return true;
1812}
1813
Amna81221ad2023-09-14 17:33:26 -04001814std::shared_ptr<ConnectionManager::Config>
1815buildDefaultConfig(dht::crypto::Identity id){
1816 auto conf = std::make_shared<ConnectionManager::Config>();
1817 conf->id = std::move(id);
1818 return conf;
1819}
1820
Adrien Béraud612b55b2023-05-29 10:42:04 -04001821ConnectionManager::ConnectionManager(std::shared_ptr<ConnectionManager::Config> config_)
1822 : pimpl_ {std::make_shared<Impl>(config_)}
1823{}
1824
Amna81221ad2023-09-14 17:33:26 -04001825ConnectionManager::ConnectionManager(dht::crypto::Identity id)
1826 : ConnectionManager {buildDefaultConfig(id)}
1827{}
1828
Adrien Béraud612b55b2023-05-29 10:42:04 -04001829ConnectionManager::~ConnectionManager()
1830{
1831 if (pimpl_)
1832 pimpl_->shutdown();
1833}
1834
1835void
1836ConnectionManager::connectDevice(const DeviceId& deviceId,
1837 const std::string& name,
1838 ConnectCallback cb,
1839 bool noNewSocket,
1840 bool forceNewSocket,
1841 const std::string& connType)
1842{
1843 pimpl_->connectDevice(deviceId, name, std::move(cb), noNewSocket, forceNewSocket, connType);
1844}
1845
1846void
Amna0cf544d2023-07-25 14:25:09 -04001847ConnectionManager::connectDevice(const dht::InfoHash& deviceId,
1848 const std::string& name,
1849 ConnectCallbackLegacy cb,
1850 bool noNewSocket,
1851 bool forceNewSocket,
1852 const std::string& connType)
1853{
1854 pimpl_->connectDevice(deviceId, name, std::move(cb), noNewSocket, forceNewSocket, connType);
1855}
1856
1857
1858void
Adrien Béraud612b55b2023-05-29 10:42:04 -04001859ConnectionManager::connectDevice(const std::shared_ptr<dht::crypto::Certificate>& cert,
1860 const std::string& name,
1861 ConnectCallback cb,
1862 bool noNewSocket,
1863 bool forceNewSocket,
1864 const std::string& connType)
1865{
1866 pimpl_->connectDevice(cert, name, std::move(cb), noNewSocket, forceNewSocket, connType);
1867}
1868
1869bool
1870ConnectionManager::isConnecting(const DeviceId& deviceId, const std::string& name) const
1871{
Adrien Béraud75754b22023-10-17 09:16:06 -04001872 if (auto dinfo = pimpl_->infos_.getDeviceInfo(deviceId)) {
1873 std::unique_lock<std::mutex> lk {dinfo->mtx_};
Adrien Béraudb941e922023-10-16 12:56:14 -04001874 return dinfo->isConnecting(name);
Adrien Béraud75754b22023-10-17 09:16:06 -04001875 }
1876 return false;
Adrien Béraud612b55b2023-05-29 10:42:04 -04001877}
1878
1879void
1880ConnectionManager::closeConnectionsWith(const std::string& peerUri)
1881{
Adrien Béraud75754b22023-10-17 09:16:06 -04001882 std::vector<std::shared_ptr<DeviceInfo>> dInfos;
1883 for (const auto& dinfo: pimpl_->infos_.getDeviceInfos()) {
1884 std::unique_lock<std::mutex> lk(dinfo->mtx_);
1885 bool isPeer = false;
1886 for (auto const& [id, cinfo]: dinfo->info) {
1887 std::lock_guard<std::mutex> lkv {cinfo->mutex_};
1888 auto tls = cinfo->tls_ ? cinfo->tls_.get() : (cinfo->socket_ ? cinfo->socket_->endpoint() : nullptr);
Adrien Béraudafa8e282023-09-24 12:53:20 -04001889 auto cert = tls ? tls->peerCertificate() : nullptr;
1890 if (not cert)
Adrien Béraud75754b22023-10-17 09:16:06 -04001891 cert = pimpl_->certStore().getCertificate(dinfo->deviceId.toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001892 if (cert && cert->issuer && peerUri == cert->issuer->getId().toString()) {
Adrien Béraud75754b22023-10-17 09:16:06 -04001893 isPeer = true;
1894 break;
Adrien Béraud612b55b2023-05-29 10:42:04 -04001895 }
1896 }
Adrien Béraud75754b22023-10-17 09:16:06 -04001897 lk.unlock();
1898 if (isPeer) {
1899 dInfos.emplace_back(std::move(dinfo));
1900 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001901 }
1902 // Stop connections to all peers devices
Adrien Béraud75754b22023-10-17 09:16:06 -04001903 for (const auto& dinfo : dInfos) {
1904 std::unique_lock<std::mutex> lk {dinfo->mtx_};
1905 auto unused = dinfo->extractUnusedConnections();
1906 auto pending = dinfo->extractPendingOperations(0, nullptr);
1907 pimpl_->infos_.removeDeviceInfo(dinfo->deviceId);
1908 lk.unlock();
1909 for (auto& op : unused)
1910 op->shutdown();
1911 for (auto& op : pending)
1912 op.cb(nullptr, dinfo->deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001913 }
1914}
1915
1916void
1917ConnectionManager::onDhtConnected(const dht::crypto::PublicKey& devicePk)
1918{
1919 pimpl_->onDhtConnected(devicePk);
1920}
1921
1922void
1923ConnectionManager::onICERequest(onICERequestCallback&& cb)
1924{
1925 pimpl_->iceReqCb_ = std::move(cb);
1926}
1927
1928void
1929ConnectionManager::onChannelRequest(ChannelRequestCallback&& cb)
1930{
1931 pimpl_->channelReqCb_ = std::move(cb);
1932}
1933
1934void
1935ConnectionManager::onConnectionReady(ConnectionReadyCallback&& cb)
1936{
1937 pimpl_->connReadyCb_ = std::move(cb);
1938}
1939
1940void
1941ConnectionManager::oniOSConnected(iOSConnectedCallback&& cb)
1942{
1943 pimpl_->iOSConnectedCb_ = std::move(cb);
1944}
1945
1946std::size_t
1947ConnectionManager::activeSockets() const
1948{
Adrien Béraud75754b22023-10-17 09:16:06 -04001949 return pimpl_->infos_.getConnectedInfos().size();
Adrien Béraud612b55b2023-05-29 10:42:04 -04001950}
1951
1952void
1953ConnectionManager::monitor() const
1954{
Adrien Béraud612b55b2023-05-29 10:42:04 -04001955 auto logger = pimpl_->config_->logger;
1956 if (!logger)
1957 return;
1958 logger->debug("ConnectionManager current status:");
Adrien Béraud75754b22023-10-17 09:16:06 -04001959 for (const auto& ci : pimpl_->infos_.getConnectedInfos()) {
1960 std::lock_guard<std::mutex> lk(ci->mutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001961 if (ci->socket_)
1962 ci->socket_->monitor();
1963 }
1964 logger->debug("ConnectionManager end status.");
1965}
1966
1967void
1968ConnectionManager::connectivityChanged()
1969{
Adrien Béraud75754b22023-10-17 09:16:06 -04001970 for (const auto& ci : pimpl_->infos_.getConnectedInfos()) {
1971 std::lock_guard<std::mutex> lk(ci->mutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001972 if (ci->socket_)
Adrien Béraud51a54712023-10-17 21:24:30 -04001973 dht::ThreadPool::io().run([s = ci->socket_] { s->sendBeacon(); });
Adrien Béraud612b55b2023-05-29 10:42:04 -04001974 }
1975}
1976
1977void
1978ConnectionManager::getIceOptions(std::function<void(IceTransportOptions&&)> cb) noexcept
1979{
1980 return pimpl_->getIceOptions(std::move(cb));
1981}
1982
1983IceTransportOptions
1984ConnectionManager::getIceOptions() const noexcept
1985{
1986 return pimpl_->getIceOptions();
1987}
1988
1989IpAddr
1990ConnectionManager::getPublishedIpAddress(uint16_t family) const
1991{
1992 return pimpl_->getPublishedIpAddress(family);
1993}
1994
1995void
1996ConnectionManager::setPublishedAddress(const IpAddr& ip_addr)
1997{
1998 return pimpl_->setPublishedAddress(ip_addr);
1999}
2000
2001void
2002ConnectionManager::storeActiveIpAddress(std::function<void()>&& cb)
2003{
2004 return pimpl_->storeActiveIpAddress(std::move(cb));
2005}
2006
2007std::shared_ptr<ConnectionManager::Config>
2008ConnectionManager::getConfig()
2009{
2010 return pimpl_->config_;
2011}
2012
Amna31791e52023-08-03 12:40:57 -04002013std::vector<std::map<std::string, std::string>>
2014ConnectionManager::getConnectionList(const DeviceId& device) const
2015{
2016 std::vector<std::map<std::string, std::string>> connectionsList;
Amna31791e52023-08-03 12:40:57 -04002017 if (device) {
Adrien Béraud75754b22023-10-17 09:16:06 -04002018 if (auto deviceInfo = pimpl_->infos_.getDeviceInfo(device)) {
2019 connectionsList = deviceInfo->getConnectionList(pimpl_->certStore());
Amna31791e52023-08-03 12:40:57 -04002020 }
Adrien Béraud75754b22023-10-17 09:16:06 -04002021 } else {
2022 for (const auto& deviceInfo : pimpl_->infos_.getDeviceInfos()) {
2023 auto cl = deviceInfo->getConnectionList(pimpl_->certStore());
2024 connectionsList.insert(connectionsList.end(), std::make_move_iterator(cl.begin()), std::make_move_iterator(cl.end()));
Amna31791e52023-08-03 12:40:57 -04002025 }
2026 }
2027 return connectionsList;
2028}
2029
2030std::vector<std::map<std::string, std::string>>
2031ConnectionManager::getChannelList(const std::string& connectionId) const
2032{
Adrien Béraud75754b22023-10-17 09:16:06 -04002033 auto [deviceId, valueId] = parseCallbackId(connectionId);
2034 if (auto info = pimpl_->infos_.getInfo(deviceId, valueId)) {
2035 std::lock_guard<std::mutex> lk(info->mutex_);
2036 if (info->socket_)
2037 return info->socket_->getChannelList();
Amna31791e52023-08-03 12:40:57 -04002038 }
Adrien Béraud75754b22023-10-17 09:16:06 -04002039 return {};
Amna31791e52023-08-03 12:40:57 -04002040}
2041
Sébastien Blin464bdff2023-07-19 08:02:53 -04002042} // namespace dhtnet