blob: 87704a8d702dae42e953ddf4e686c00ab1f45249 [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;
Adrien Béraudd5ec7a82023-10-28 18:07:03 -0400269 ret.reserve(info.size() + connecting.size() + waiting.size());
Adrien Béraud75754b22023-10-17 09:16:06 -0400270 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,
Adrien Bérauda9ef2a52023-11-05 00:47:24 -0400475 const std::weak_ptr<ConnectionInfo>& cinfo,
Adrien Béraud75754b22023-10-17 09:16:06 -0400476 const std::shared_ptr<MultiplexedSocket>& sock,
Adrien Béraud612b55b2023-05-29 10:42:04 -0400477 const std::string& name,
Adrien Béraud612b55b2023-05-29 10:42:04 -0400478 const dht::Value::Id& vid);
479 /**
480 * Triggered when a PeerConnectionRequest comes from the DHT
481 */
482 void answerTo(IceTransport& ice,
483 const dht::Value::Id& id,
484 const std::shared_ptr<dht::crypto::PublicKey>& fromPk);
Adrien Béraud75754b22023-10-17 09:16:06 -0400485 bool onRequestStartIce(const std::shared_ptr<ConnectionInfo>& info, const PeerConnectionRequest& req);
486 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 -0400487 void onDhtPeerRequest(const PeerConnectionRequest& req,
488 const std::shared_ptr<dht::crypto::Certificate>& cert);
Adrien Béraud75754b22023-10-17 09:16:06 -0400489 /**
490 * Triggered when a new TLS socket is ready to use
491 * @param ok If succeed
492 * @param deviceId Related device
493 * @param vid vid of the connection request
494 * @param name non empty if TLS was created by connectDevice()
495 */
496 void onTlsNegotiationDone(const std::shared_ptr<DeviceInfo>& dinfo,
497 const std::shared_ptr<ConnectionInfo>& info,
498 bool ok,
499 const DeviceId& deviceId,
500 const dht::Value::Id& vid,
501 const std::string& name = "");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400502
Adrien Béraud75754b22023-10-17 09:16:06 -0400503 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 -0400504 void onPeerResponse(PeerConnectionRequest&& req);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400505 void onDhtConnected(const dht::crypto::PublicKey& devicePk);
506
Adrien Béraud75754b22023-10-17 09:16:06 -0400507
Adrien Béraud612b55b2023-05-29 10:42:04 -0400508 const std::shared_future<tls::DhParams> dhParams() const;
509 tls::CertificateStore& certStore() const { return *config_->certStore; }
510
511 mutable std::mutex messageMutex_ {};
512 std::set<std::string, std::less<>> treatedMessages_ {};
513
514 void loadTreatedMessages();
515 void saveTreatedMessages() const;
516
517 /// \return true if the given DHT message identifier has been treated
518 /// \note if message has not been treated yet this method st/ore this id and returns true at
519 /// further calls
520 bool isMessageTreated(std::string_view id);
521
522 const std::shared_ptr<dht::log::Logger>& logger() const { return config_->logger; }
523
524 /**
525 * Published IPv4/IPv6 addresses, used only if defined by the user in account
526 * configuration
527 *
528 */
529 IpAddr publishedIp_[2] {};
530
Adrien Béraud612b55b2023-05-29 10:42:04 -0400531 /**
532 * interface name on which this account is bound
533 */
534 std::string interface_ {"default"};
535
536 /**
537 * Get the local interface name on which this account is bound.
538 */
539 const std::string& getLocalInterface() const { return interface_; }
540
541 /**
542 * Get the published IP address, fallbacks to NAT if family is unspecified
543 * Prefers the usage of IPv4 if possible.
544 */
545 IpAddr getPublishedIpAddress(uint16_t family = PF_UNSPEC) const;
546
547 /**
548 * Set published IP address according to given family
549 */
550 void setPublishedAddress(const IpAddr& ip_addr);
551
552 /**
553 * Store the local/public addresses used to register
554 */
555 void storeActiveIpAddress(std::function<void()>&& cb = {});
556
557 /**
558 * Create and return ICE options.
559 */
560 void getIceOptions(std::function<void(IceTransportOptions&&)> cb) noexcept;
561 IceTransportOptions getIceOptions() const noexcept;
562
563 /**
564 * Inform that a potential peer device have been found.
565 * Returns true only if the device certificate is a valid device certificate.
566 * In that case (true is returned) the account_id parameter is set to the peer account ID.
567 */
568 static bool foundPeerDevice(const std::shared_ptr<dht::crypto::Certificate>& crt,
569 dht::InfoHash& account_id, const std::shared_ptr<Logger>& logger);
570
571 bool findCertificate(const dht::PkId& id,
572 std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb);
Sébastien Blin34086512023-07-25 09:52:14 -0400573 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 -0400574
575 /**
576 * returns whether or not UPnP is enabled and active
577 * ie: if it is able to make port mappings
578 */
579 bool getUPnPActive() const;
580
Adrien Béraud612b55b2023-05-29 10:42:04 -0400581 std::shared_ptr<ConnectionManager::Config> config_;
Amna81221ad2023-09-14 17:33:26 -0400582 std::unique_ptr<std::thread> ioContextRunner_;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400583
Adrien Béraud75754b22023-10-17 09:16:06 -0400584 mutable std::mutex randMtx_;
585 mutable std::mt19937_64 rand_;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400586
587 iOSConnectedCallback iOSConnectedCb_ {};
588
Adrien Béraud75754b22023-10-17 09:16:06 -0400589 DeviceInfoSet infos_ {};
Adrien Béraud612b55b2023-05-29 10:42:04 -0400590
591 ChannelRequestCallback channelReqCb_ {};
592 ConnectionReadyCallback connReadyCb_ {};
593 onICERequestCallback iceReqCb_ {};
Adrien Béraud612b55b2023-05-29 10:42:04 -0400594 std::atomic_bool isDestroying_ {false};
595};
596
597void
598ConnectionManager::Impl::connectDeviceStartIce(
Adrien Béraud75754b22023-10-17 09:16:06 -0400599 const std::shared_ptr<ConnectionInfo>& info,
Adrien Béraud612b55b2023-05-29 10:42:04 -0400600 const std::shared_ptr<dht::crypto::PublicKey>& devicePk,
601 const dht::Value::Id& vid,
602 const std::string& connType,
603 std::function<void(bool)> onConnected)
604{
605 auto deviceId = devicePk->getLongId();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400606 if (!info) {
607 onConnected(false);
608 return;
609 }
610
611 std::unique_lock<std::mutex> lk(info->mutex_);
612 auto& ice = info->ice_;
613
614 if (!ice) {
615 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -0400616 config_->logger->error("[device {}] No ICE detected", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400617 onConnected(false);
618 return;
619 }
620
621 auto iceAttributes = ice->getLocalAttributes();
622 std::ostringstream icemsg;
623 icemsg << iceAttributes.ufrag << "\n";
624 icemsg << iceAttributes.pwd << "\n";
625 for (const auto& addr : ice->getLocalCandidates(1)) {
626 icemsg << addr << "\n";
627 if (config_->logger)
Sébastien Blinaec46fc2023-07-25 15:43:10 -0400628 config_->logger->debug("[device {}] Added local ICE candidate {}", deviceId, addr);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400629 }
630
631 // Prepare connection request as a DHT message
632 PeerConnectionRequest val;
633
634 val.id = vid; /* Random id for the message unicity */
635 val.ice_msg = icemsg.str();
636 val.connType = connType;
637
638 auto value = std::make_shared<dht::Value>(std::move(val));
639 value->user_type = "peer_request";
640
641 // Send connection request through DHT
642 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -0400643 config_->logger->debug("[device {}] Sending connection request", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400644 dht()->putEncrypted(dht::InfoHash::get(PeerConnectionRequest::key_prefix
645 + devicePk->getId().toString()),
646 devicePk,
647 value,
648 [l=config_->logger,deviceId](bool ok) {
649 if (l)
Adrien Béraud23852462023-07-22 01:46:27 -0400650 l->debug("[device {}] Sent connection request. Put encrypted {:s}",
Adrien Béraud612b55b2023-05-29 10:42:04 -0400651 deviceId,
652 (ok ? "ok" : "failed"));
653 });
654 // Wait for call to onResponse() operated by DHT
655 if (isDestroying_) {
656 onConnected(true); // This avoid to wait new negotiation when destroying
657 return;
658 }
659
660 info->onConnected_ = std::move(onConnected);
661 info->waitForAnswer_ = std::make_unique<asio::steady_timer>(*config_->ioContext,
662 std::chrono::steady_clock::now()
663 + DHT_MSG_TIMEOUT);
664 info->waitForAnswer_->async_wait(
Adrien Béraud75754b22023-10-17 09:16:06 -0400665 std::bind(&ConnectionManager::Impl::onResponse, this, std::placeholders::_1, info, deviceId, vid));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400666}
667
668void
669ConnectionManager::Impl::onResponse(const asio::error_code& ec,
Adrien Béraud75754b22023-10-17 09:16:06 -0400670 const std::weak_ptr<ConnectionInfo>& winfo,
Adrien Béraud612b55b2023-05-29 10:42:04 -0400671 const DeviceId& deviceId,
672 const dht::Value::Id& vid)
673{
674 if (ec == asio::error::operation_aborted)
675 return;
Adrien Béraud75754b22023-10-17 09:16:06 -0400676 auto info = winfo.lock();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400677 if (!info)
678 return;
679
680 std::unique_lock<std::mutex> lk(info->mutex_);
681 auto& ice = info->ice_;
682 if (isDestroying_) {
683 info->onConnected_(true); // The destructor can wake a pending wait here.
684 return;
685 }
686 if (!info->responseReceived_) {
687 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -0400688 config_->logger->error("[device {}] no response from DHT to ICE request.", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400689 info->onConnected_(false);
690 return;
691 }
692
693 if (!info->ice_) {
694 info->onConnected_(false);
695 return;
696 }
697
698 auto sdp = ice->parseIceCandidates(info->response_.ice_msg);
699
700 if (not ice->startIce({sdp.rem_ufrag, sdp.rem_pwd}, std::move(sdp.rem_candidates))) {
701 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -0400702 config_->logger->warn("[device {}] start ICE failed", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400703 info->onConnected_(false);
704 return;
705 }
706 info->onConnected_(true);
707}
708
709bool
710ConnectionManager::Impl::connectDeviceOnNegoDone(
Adrien Béraud75754b22023-10-17 09:16:06 -0400711 const std::weak_ptr<DeviceInfo>& dinfo,
712 const std::shared_ptr<ConnectionInfo>& info,
Adrien Béraud612b55b2023-05-29 10:42:04 -0400713 const DeviceId& deviceId,
714 const std::string& name,
715 const dht::Value::Id& vid,
716 const std::shared_ptr<dht::crypto::Certificate>& cert)
717{
Adrien Béraud612b55b2023-05-29 10:42:04 -0400718 if (!info)
719 return false;
720
721 std::unique_lock<std::mutex> lk {info->mutex_};
722 if (info->waitForAnswer_) {
723 // Negotiation is done and connected, go to handshake
724 // and avoid any cancellation at this point.
725 info->waitForAnswer_->cancel();
726 }
727 auto& ice = info->ice_;
728 if (!ice || !ice->isRunning()) {
729 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -0400730 config_->logger->error("[device {}] No ICE detected or not running", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400731 return false;
732 }
733
734 // Build socket
735 auto endpoint = std::make_unique<IceSocketEndpoint>(std::shared_ptr<IceTransport>(
736 std::move(ice)),
737 true);
738
739 // Negotiate a TLS session
740 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -0400741 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 -0400742 info->tls_ = std::make_unique<TlsSocketEndpoint>(std::move(endpoint),
743 certStore(),
Adrien Béraud3f93ddf2023-07-21 14:46:22 -0400744 config_->ioContext,
Adrien Béraud612b55b2023-05-29 10:42:04 -0400745 identity(),
746 dhParams(),
747 *cert);
748
749 info->tls_->setOnReady(
Adrien Béraud75754b22023-10-17 09:16:06 -0400750 [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 -0400751 bool ok) {
752 if (auto shared = w.lock())
Adrien Béraud75754b22023-10-17 09:16:06 -0400753 shared->onTlsNegotiationDone(dinfo.lock(), winfo.lock(), ok, deviceId, vid, name);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400754 });
755 return true;
756}
757
758void
759ConnectionManager::Impl::connectDevice(const DeviceId& deviceId,
760 const std::string& name,
761 ConnectCallback cb,
762 bool noNewSocket,
763 bool forceNewSocket,
764 const std::string& connType)
765{
766 if (!dht()) {
767 cb(nullptr, deviceId);
768 return;
769 }
770 if (deviceId.toString() == identity().second->getLongId().toString()) {
771 cb(nullptr, deviceId);
772 return;
773 }
774 findCertificate(deviceId,
Adrien Béraud75754b22023-10-17 09:16:06 -0400775 [w = weak_from_this(),
Adrien Béraud612b55b2023-05-29 10:42:04 -0400776 deviceId,
777 name,
778 cb = std::move(cb),
779 noNewSocket,
780 forceNewSocket,
781 connType](const std::shared_ptr<dht::crypto::Certificate>& cert) {
782 if (!cert) {
783 if (auto shared = w.lock())
784 if (shared->config_->logger)
785 shared->config_->logger->error(
786 "No valid certificate found for device {}",
787 deviceId);
788 cb(nullptr, deviceId);
789 return;
790 }
791 if (auto shared = w.lock()) {
792 shared->connectDevice(cert,
793 name,
794 std::move(cb),
795 noNewSocket,
796 forceNewSocket,
797 connType);
798 } else
799 cb(nullptr, deviceId);
800 });
801}
802
803void
Amna0cf544d2023-07-25 14:25:09 -0400804ConnectionManager::Impl::connectDevice(const dht::InfoHash& deviceId,
805 const std::string& name,
806 ConnectCallbackLegacy cb,
807 bool noNewSocket,
808 bool forceNewSocket,
809 const std::string& connType)
810{
811 if (!dht()) {
812 cb(nullptr, deviceId);
813 return;
814 }
815 if (deviceId.toString() == identity().second->getLongId().toString()) {
816 cb(nullptr, deviceId);
817 return;
818 }
819 findCertificate(deviceId,
Adrien Béraud75754b22023-10-17 09:16:06 -0400820 [w = weak_from_this(),
Amna0cf544d2023-07-25 14:25:09 -0400821 deviceId,
822 name,
823 cb = std::move(cb),
824 noNewSocket,
825 forceNewSocket,
826 connType](const std::shared_ptr<dht::crypto::Certificate>& cert) {
827 if (!cert) {
828 if (auto shared = w.lock())
829 if (shared->config_->logger)
830 shared->config_->logger->error(
831 "No valid certificate found for device {}",
832 deviceId);
833 cb(nullptr, deviceId);
834 return;
835 }
836 if (auto shared = w.lock()) {
837 shared->connectDevice(cert,
838 name,
Adrien Béraudd78d1ac2023-08-25 10:43:33 -0400839 [cb, deviceId](const std::shared_ptr<ChannelSocket>& sock, const DeviceId& /*did*/){
Amna0cf544d2023-07-25 14:25:09 -0400840 cb(sock, deviceId);
841 },
842 noNewSocket,
843 forceNewSocket,
844 connType);
845 } else
846 cb(nullptr, deviceId);
847 });
848}
849
850void
Adrien Béraud612b55b2023-05-29 10:42:04 -0400851ConnectionManager::Impl::connectDevice(const std::shared_ptr<dht::crypto::Certificate>& cert,
852 const std::string& name,
853 ConnectCallback cb,
854 bool noNewSocket,
855 bool forceNewSocket,
856 const std::string& connType)
857{
858 // Avoid dht operation in a DHT callback to avoid deadlocks
Adrien Béraud75754b22023-10-17 09:16:06 -0400859 dht::ThreadPool::computation().run([w = weak_from_this(),
Adrien Béraud612b55b2023-05-29 10:42:04 -0400860 name = std::move(name),
861 cert = std::move(cert),
862 cb = std::move(cb),
863 noNewSocket,
864 forceNewSocket,
865 connType] {
866 auto devicePk = cert->getSharedPublicKey();
867 auto deviceId = devicePk->getLongId();
868 auto sthis = w.lock();
869 if (!sthis || sthis->isDestroying_) {
870 cb(nullptr, deviceId);
871 return;
872 }
Adrien Béraud75754b22023-10-17 09:16:06 -0400873 auto di = sthis->infos_.createDeviceInfo(deviceId);
874 std::unique_lock<std::mutex> lk(di->mtx_);
875
Adrien Béraud26365c92023-09-23 23:42:43 -0400876 dht::Value::Id vid;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400877 {
Adrien Béraud75754b22023-10-17 09:16:06 -0400878 std::lock_guard<std::mutex> lkr(sthis->randMtx_);
879 vid = di->newId(sthis->rand_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400880 }
881
Adrien Béraud75754b22023-10-17 09:16:06 -0400882 // Check if already connecting
883 auto isConnectingToDevice = di->isConnecting();
884 // Note: we can be in a state where first
885 // socket is negotiated and first channel is pending
886 // so return only after we checked the info
Adrien Béraudb941e922023-10-16 12:56:14 -0400887 auto& diw = (isConnectingToDevice && !forceNewSocket)
888 ? di->waiting[vid]
889 : di->connecting[vid];
890 diw = PendingCb {name, std::move(cb)};
891
Adrien Béraud612b55b2023-05-29 10:42:04 -0400892 // Check if already negotiated
Adrien Béraud75754b22023-10-17 09:16:06 -0400893 if (auto info = di->getConnectedInfo()) {
894 std::unique_lock<std::mutex> lkc(info->mutex_);
895 if (auto sock = info->socket_) {
896 info->cbIds_.emplace(vid);
Adrien Béraudb941e922023-10-16 12:56:14 -0400897 diw.requested = true;
Adrien Béraud75754b22023-10-17 09:16:06 -0400898 lkc.unlock();
899 lk.unlock();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400900 if (sthis->config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -0400901 sthis->config_->logger->debug("[device {}] Peer already connected. Add a new channel", deviceId);
Adrien Bérauda9ef2a52023-11-05 00:47:24 -0400902 sthis->sendChannelRequest(di, info, sock, name, vid);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400903 return;
904 }
905 }
906
907 if (isConnectingToDevice && !forceNewSocket) {
908 if (sthis->config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -0400909 sthis->config_->logger->debug("[device {}] Already connecting, wait for ICE negotiation", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400910 return;
911 }
912 if (noNewSocket) {
913 // If no new socket is specified, we don't try to generate a new socket
Adrien Béraud75754b22023-10-17 09:16:06 -0400914 di->executePendingOperations(lk, vid, nullptr);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400915 return;
916 }
917
918 // Note: used when the ice negotiation fails to erase
919 // all stored structures.
Adrien Béraud75754b22023-10-17 09:16:06 -0400920 auto eraseInfo = [w, diw=std::weak_ptr(di), vid] {
921 if (auto di = diw.lock()) {
922 std::unique_lock<std::mutex> lk(di->mtx_);
923 di->info.erase(vid);
924 auto ops = di->extractPendingOperations(vid, nullptr);
925 if (di->empty()) {
926 if (auto shared = w.lock())
927 shared->infos_.removeDeviceInfo(di->deviceId);
928 }
929 lk.unlock();
930 for (const auto& op: ops)
931 op.cb(nullptr, di->deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400932 }
933 };
934
935 // If no socket exists, we need to initiate an ICE connection.
936 sthis->getIceOptions([w,
937 deviceId = std::move(deviceId),
938 devicePk = std::move(devicePk),
Adrien Béraud75754b22023-10-17 09:16:06 -0400939 diw=std::weak_ptr(di),
Adrien Béraud612b55b2023-05-29 10:42:04 -0400940 name = std::move(name),
941 cert = std::move(cert),
942 vid,
943 connType,
944 eraseInfo](auto&& ice_config) {
945 auto sthis = w.lock();
946 if (!sthis) {
947 dht::ThreadPool::io().run([eraseInfo = std::move(eraseInfo)] { eraseInfo(); });
948 return;
949 }
Adrien Béraud75754b22023-10-17 09:16:06 -0400950 auto info = std::make_shared<ConnectionInfo>();
951 auto winfo = std::weak_ptr(info);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400952 ice_config.tcpEnable = true;
953 ice_config.onInitDone = [w,
Adrien Béraud612b55b2023-05-29 10:42:04 -0400954 devicePk = std::move(devicePk),
955 name = std::move(name),
956 cert = std::move(cert),
Adrien Béraud75754b22023-10-17 09:16:06 -0400957 diw,
958 winfo = std::weak_ptr(info),
Adrien Béraud612b55b2023-05-29 10:42:04 -0400959 vid,
960 connType,
961 eraseInfo](bool ok) {
962 dht::ThreadPool::io().run([w = std::move(w),
963 devicePk = std::move(devicePk),
Adrien Béraud75754b22023-10-17 09:16:06 -0400964 vid,
965 winfo,
Adrien Béraud612b55b2023-05-29 10:42:04 -0400966 eraseInfo,
967 connType, ok] {
968 auto sthis = w.lock();
969 if (!ok && sthis && sthis->config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -0400970 sthis->config_->logger->error("[device {}] Cannot initialize ICE session.", devicePk->getLongId());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400971 if (!sthis || !ok) {
972 eraseInfo();
973 return;
974 }
Adrien Béraud75754b22023-10-17 09:16:06 -0400975 sthis->connectDeviceStartIce(winfo.lock(), devicePk, vid, connType, [=](bool ok) {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400976 if (!ok) {
977 dht::ThreadPool::io().run([eraseInfo = std::move(eraseInfo)] { eraseInfo(); });
978 }
979 });
980 });
981 };
982 ice_config.onNegoDone = [w,
983 deviceId,
984 name,
985 cert = std::move(cert),
Adrien Béraud75754b22023-10-17 09:16:06 -0400986 diw,
987 winfo = std::weak_ptr(info),
Adrien Béraud612b55b2023-05-29 10:42:04 -0400988 vid,
989 eraseInfo](bool ok) {
990 dht::ThreadPool::io().run([w = std::move(w),
991 deviceId = std::move(deviceId),
992 name = std::move(name),
993 cert = std::move(cert),
Adrien Béraud75754b22023-10-17 09:16:06 -0400994 diw = std::move(diw),
995 winfo = std::move(winfo),
Adrien Béraud612b55b2023-05-29 10:42:04 -0400996 vid = std::move(vid),
997 eraseInfo = std::move(eraseInfo),
998 ok] {
999 auto sthis = w.lock();
1000 if (!ok && sthis && sthis->config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001001 sthis->config_->logger->error("[device {}] ICE negotiation failed.", deviceId);
Adrien Béraud75754b22023-10-17 09:16:06 -04001002 if (!sthis || !ok || !sthis->connectDeviceOnNegoDone(diw, winfo.lock(), deviceId, name, vid, cert))
Adrien Béraud612b55b2023-05-29 10:42:04 -04001003 eraseInfo();
1004 });
1005 };
1006
Adrien Béraud75754b22023-10-17 09:16:06 -04001007 if (auto di = diw.lock()) {
1008 std::lock_guard<std::mutex> lk(di->mtx_);
1009 di->info[vid] = info;
Adrien Béraud612b55b2023-05-29 10:42:04 -04001010 }
1011 std::unique_lock<std::mutex> lk {info->mutex_};
1012 ice_config.master = false;
1013 ice_config.streamsCount = 1;
1014 ice_config.compCountPerStream = 1;
Sébastien Blin34086512023-07-25 09:52:14 -04001015 info->ice_ = sthis->config_->factory->createUTransport("");
Adrien Béraud612b55b2023-05-29 10:42:04 -04001016 if (!info->ice_) {
1017 if (sthis->config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001018 sthis->config_->logger->error("[device {}] Cannot initialize ICE session.", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001019 eraseInfo();
1020 return;
1021 }
1022 // We need to detect any shutdown if the ice session is destroyed before going to the
1023 // TLS session;
1024 info->ice_->setOnShutdown([eraseInfo]() {
1025 dht::ThreadPool::io().run([eraseInfo = std::move(eraseInfo)] { eraseInfo(); });
1026 });
Adrien Béraud4cda2d72023-06-01 15:44:43 -04001027 try {
1028 info->ice_->initIceInstance(ice_config);
1029 } catch (const std::exception& e) {
1030 if (sthis->config_->logger)
1031 sthis->config_->logger->error("{}", e.what());
1032 dht::ThreadPool::io().run([eraseInfo = std::move(eraseInfo)] { eraseInfo(); });
1033 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001034 });
1035 });
1036}
1037
1038void
Adrien Bérauda9ef2a52023-11-05 00:47:24 -04001039ConnectionManager::Impl::sendChannelRequest(const std::weak_ptr<DeviceInfo>& dinfow,
1040 const std::weak_ptr<ConnectionInfo>& cinfow,
Adrien Béraud75754b22023-10-17 09:16:06 -04001041 const std::shared_ptr<MultiplexedSocket>& sock,
Adrien Béraud612b55b2023-05-29 10:42:04 -04001042 const std::string& name,
Adrien Béraud612b55b2023-05-29 10:42:04 -04001043 const dht::Value::Id& vid)
1044{
1045 auto channelSock = sock->addChannel(name);
Adrien Béraud9a4e98b2023-10-15 12:10:21 -04001046 if (!channelSock) {
1047 if (config_->logger)
1048 config_->logger->error("sendChannelRequest failed - cannot create channel");
Adrien Bérauda9ef2a52023-11-05 00:47:24 -04001049 if (auto info = dinfow.lock())
Adrien Béraud9a4e98b2023-10-15 12:10:21 -04001050 info->executePendingOperations(vid, nullptr);
1051 return;
1052 }
Adrien Bérauda9ef2a52023-11-05 00:47:24 -04001053 channelSock->onShutdown([dinfow, name, vid] {
1054 if (auto info = dinfow.lock())
Adrien Béraud75754b22023-10-17 09:16:06 -04001055 info->executePendingOperations(vid, nullptr);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001056 });
1057 channelSock->onReady(
Adrien Bérauda9ef2a52023-11-05 00:47:24 -04001058 [dinfow, cinfow, wSock = std::weak_ptr(channelSock), name, vid](bool accepted) {
1059 if (auto dinfo = dinfow.lock()) {
1060 dinfo->executePendingOperations(vid, accepted ? wSock.lock() : nullptr, accepted);
1061 if (auto cinfo = cinfow.lock()) {
1062 std::lock_guard<std::mutex> lk(cinfo->mutex_);
1063 cinfo->cbIds_.erase(vid);
1064 }
1065 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001066 });
1067
1068 ChannelRequest val;
1069 val.name = channelSock->name();
1070 val.state = ChannelRequestState::REQUEST;
1071 val.channel = channelSock->channel();
1072 msgpack::sbuffer buffer(256);
1073 msgpack::pack(buffer, val);
1074
1075 std::error_code ec;
1076 int res = sock->write(CONTROL_CHANNEL,
1077 reinterpret_cast<const uint8_t*>(buffer.data()),
1078 buffer.size(),
1079 ec);
1080 if (res < 0) {
1081 // TODO check if we should handle errors here
1082 if (config_->logger)
Adrien Béraud75754b22023-10-17 09:16:06 -04001083 config_->logger->error("sendChannelRequest failed - error: {}", ec.message());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001084 }
1085}
1086
1087void
Adrien Béraud1addf952023-09-30 17:38:35 -04001088ConnectionManager::Impl::onPeerResponse(PeerConnectionRequest&& req)
Adrien Béraud612b55b2023-05-29 10:42:04 -04001089{
1090 auto device = req.owner->getLongId();
Adrien Béraud75754b22023-10-17 09:16:06 -04001091 if (auto info = infos_.getInfo(device, req.id)) {
Adrien Béraud23852462023-07-22 01:46:27 -04001092 if (config_->logger)
1093 config_->logger->debug("[device {}] New response received", device);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001094 std::lock_guard<std::mutex> lk {info->mutex_};
1095 info->responseReceived_ = true;
1096 info->response_ = std::move(req);
1097 info->waitForAnswer_->expires_at(std::chrono::steady_clock::now());
1098 info->waitForAnswer_->async_wait(std::bind(&ConnectionManager::Impl::onResponse,
1099 this,
1100 std::placeholders::_1,
Adrien Béraud75754b22023-10-17 09:16:06 -04001101 std::weak_ptr(info),
Adrien Béraud612b55b2023-05-29 10:42:04 -04001102 device,
1103 req.id));
1104 } else {
1105 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001106 config_->logger->warn("[device {}] Respond received, but cannot find request", device);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001107 }
1108}
1109
1110void
1111ConnectionManager::Impl::onDhtConnected(const dht::crypto::PublicKey& devicePk)
1112{
1113 if (!dht())
1114 return;
1115 dht()->listen<PeerConnectionRequest>(
1116 dht::InfoHash::get(PeerConnectionRequest::key_prefix + devicePk.getId().toString()),
Adrien Béraud75754b22023-10-17 09:16:06 -04001117 [w = weak_from_this()](PeerConnectionRequest&& req) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001118 auto shared = w.lock();
1119 if (!shared)
1120 return false;
1121 if (shared->isMessageTreated(to_hex_string(req.id))) {
1122 // Message already treated. Just ignore
1123 return true;
1124 }
1125 if (req.isAnswer) {
1126 if (shared->config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001127 shared->config_->logger->debug("[device {}] Received request answer", req.owner->getLongId());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001128 } else {
1129 if (shared->config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001130 shared->config_->logger->debug("[device {}] Received request", req.owner->getLongId());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001131 }
1132 if (req.isAnswer) {
Adrien Béraud1addf952023-09-30 17:38:35 -04001133 shared->onPeerResponse(std::move(req));
Adrien Béraud612b55b2023-05-29 10:42:04 -04001134 } else {
1135 // Async certificate checking
Sébastien Blin34086512023-07-25 09:52:14 -04001136 shared->findCertificate(
Adrien Béraud612b55b2023-05-29 10:42:04 -04001137 req.from,
1138 [w, req = std::move(req)](
1139 const std::shared_ptr<dht::crypto::Certificate>& cert) mutable {
1140 auto shared = w.lock();
1141 if (!shared)
1142 return;
1143 dht::InfoHash peer_h;
1144 if (foundPeerDevice(cert, peer_h, shared->config_->logger)) {
1145#if TARGET_OS_IOS
1146 if (shared->iOSConnectedCb_(req.connType, peer_h))
1147 return;
1148#endif
1149 shared->onDhtPeerRequest(req, cert);
1150 } else {
1151 if (shared->config_->logger)
1152 shared->config_->logger->warn(
Adrien Béraud23852462023-07-22 01:46:27 -04001153 "[device {}] Received request from untrusted peer",
Adrien Béraud612b55b2023-05-29 10:42:04 -04001154 req.owner->getLongId());
1155 }
1156 });
1157 }
1158
1159 return true;
1160 },
1161 dht::Value::UserTypeFilter("peer_request"));
1162}
1163
1164void
Adrien Béraud75754b22023-10-17 09:16:06 -04001165ConnectionManager::Impl::onTlsNegotiationDone(const std::shared_ptr<DeviceInfo>& dinfo,
1166 const std::shared_ptr<ConnectionInfo>& info,
1167 bool ok,
Adrien Béraud612b55b2023-05-29 10:42:04 -04001168 const DeviceId& deviceId,
1169 const dht::Value::Id& vid,
1170 const std::string& name)
1171{
1172 if (isDestroying_)
1173 return;
1174 // Note: only handle pendingCallbacks here for TLS initied by connectDevice()
1175 // Note: if not initied by connectDevice() the channel name will be empty (because no channel
1176 // asked yet)
1177 auto isDhtRequest = name.empty();
1178 if (!ok) {
1179 if (isDhtRequest) {
1180 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001181 config_->logger->error("[device {}] TLS connection failure - Initied by DHT request. channel: {} - vid: {}",
Adrien Béraud612b55b2023-05-29 10:42:04 -04001182 deviceId,
1183 name,
1184 vid);
1185 if (connReadyCb_)
1186 connReadyCb_(deviceId, "", nullptr);
1187 } else {
1188 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001189 config_->logger->error("[device {}] TLS connection failure - Initied by connectDevice. channel: {} - vid: {}",
Adrien Béraud612b55b2023-05-29 10:42:04 -04001190 deviceId,
1191 name,
1192 vid);
Adrien Béraud75754b22023-10-17 09:16:06 -04001193 dinfo->executePendingOperations(vid, nullptr);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001194 }
Sébastien Blin3cf0acc2023-10-23 09:45:32 -04001195
1196 std::unique_lock<std::mutex> lk(dinfo->mtx_);
1197 dinfo->info.erase(vid);
1198
1199 if (dinfo->empty()) {
1200 infos_.removeDeviceInfo(dinfo->deviceId);
1201 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001202 } else {
1203 // The socket is ready, store it
1204 if (isDhtRequest) {
1205 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001206 config_->logger->debug("[device {}] Connection is ready - Initied by DHT request. Vid: {}",
Adrien Béraud612b55b2023-05-29 10:42:04 -04001207 deviceId,
1208 vid);
1209 } else {
1210 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001211 config_->logger->debug("[device {}] Connection is ready - Initied by connectDevice(). channel: {} - vid: {}",
Adrien Béraud612b55b2023-05-29 10:42:04 -04001212 deviceId,
1213 name,
1214 vid);
1215 }
1216
Adrien Béraud75754b22023-10-17 09:16:06 -04001217 // Note: do not remove pending there it's done in sendChannelRequest
1218 std::unique_lock<std::mutex> lk2 {dinfo->mtx_};
Adrien Béraudb941e922023-10-16 12:56:14 -04001219 auto pendingIds = dinfo->requestPendingOps();
Adrien Béraud75754b22023-10-17 09:16:06 -04001220 lk2.unlock();
1221 std::unique_lock<std::mutex> lk {info->mutex_};
1222 addNewMultiplexedSocket(dinfo, deviceId, vid, info);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001223 // Finally, open the channel and launch pending callbacks
Adrien Béraud75754b22023-10-17 09:16:06 -04001224 lk.unlock();
1225 for (const auto& [id, name]: pendingIds) {
1226 if (config_->logger)
1227 config_->logger->debug("[device {}] Send request on TLS socket for channel {}",
1228 deviceId, name);
Adrien Bérauda9ef2a52023-11-05 00:47:24 -04001229 sendChannelRequest(dinfo, info, info->socket_, name, id);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001230 }
1231 }
1232}
1233
1234void
1235ConnectionManager::Impl::answerTo(IceTransport& ice,
1236 const dht::Value::Id& id,
1237 const std::shared_ptr<dht::crypto::PublicKey>& from)
1238{
1239 // NOTE: This is a shortest version of a real SDP message to save some bits
1240 auto iceAttributes = ice.getLocalAttributes();
1241 std::ostringstream icemsg;
1242 icemsg << iceAttributes.ufrag << "\n";
1243 icemsg << iceAttributes.pwd << "\n";
1244 for (const auto& addr : ice.getLocalCandidates(1)) {
1245 icemsg << addr << "\n";
1246 }
1247
1248 // Send PeerConnection response
1249 PeerConnectionRequest val;
1250 val.id = id;
1251 val.ice_msg = icemsg.str();
1252 val.isAnswer = true;
1253 auto value = std::make_shared<dht::Value>(std::move(val));
1254 value->user_type = "peer_request";
1255
1256 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001257 config_->logger->debug("[device {}] Connection accepted, DHT reply", from->getLongId());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001258 dht()->putEncrypted(dht::InfoHash::get(PeerConnectionRequest::key_prefix
1259 + from->getId().toString()),
1260 from,
1261 value,
1262 [from,l=config_->logger](bool ok) {
1263 if (l)
Adrien Béraud23852462023-07-22 01:46:27 -04001264 l->debug("[device {}] Answer to connection request: put encrypted {:s}",
Adrien Béraud612b55b2023-05-29 10:42:04 -04001265 from->getLongId(),
1266 (ok ? "ok" : "failed"));
1267 });
1268}
1269
1270bool
Adrien Béraud75754b22023-10-17 09:16:06 -04001271ConnectionManager::Impl::onRequestStartIce(const std::shared_ptr<ConnectionInfo>& info, const PeerConnectionRequest& req)
Adrien Béraud612b55b2023-05-29 10:42:04 -04001272{
Adrien Béraud612b55b2023-05-29 10:42:04 -04001273 if (!info)
1274 return false;
1275
Adrien Béraud75754b22023-10-17 09:16:06 -04001276 auto deviceId = req.owner->getLongId();
Adrien Béraud612b55b2023-05-29 10:42:04 -04001277 std::unique_lock<std::mutex> lk {info->mutex_};
1278 auto& ice = info->ice_;
1279 if (!ice) {
1280 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001281 config_->logger->error("[device {}] No ICE detected", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001282 if (connReadyCb_)
1283 connReadyCb_(deviceId, "", nullptr);
1284 return false;
1285 }
1286
1287 auto sdp = ice->parseIceCandidates(req.ice_msg);
1288 answerTo(*ice, req.id, req.owner);
1289 if (not ice->startIce({sdp.rem_ufrag, sdp.rem_pwd}, std::move(sdp.rem_candidates))) {
1290 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001291 config_->logger->error("[device {}] Start ICE failed", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001292 ice = nullptr;
1293 if (connReadyCb_)
1294 connReadyCb_(deviceId, "", nullptr);
1295 return false;
1296 }
1297 return true;
1298}
1299
1300bool
Adrien Béraud75754b22023-10-17 09:16:06 -04001301ConnectionManager::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 -04001302{
Adrien Béraud612b55b2023-05-29 10:42:04 -04001303 if (!info)
1304 return false;
1305
Adrien Béraud75754b22023-10-17 09:16:06 -04001306 auto deviceId = req.owner->getLongId();
Adrien Béraud612b55b2023-05-29 10:42:04 -04001307 std::unique_lock<std::mutex> lk {info->mutex_};
1308 auto& ice = info->ice_;
1309 if (!ice) {
1310 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001311 config_->logger->error("[device {}] No ICE detected", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001312 return false;
1313 }
1314
1315 // Build socket
1316 auto endpoint = std::make_unique<IceSocketEndpoint>(std::shared_ptr<IceTransport>(
1317 std::move(ice)),
1318 false);
1319
1320 // init TLS session
1321 auto ph = req.from;
1322 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001323 config_->logger->debug("[device {}] Start TLS session - Initied by DHT request. vid: {}",
1324 deviceId,
Adrien Béraud612b55b2023-05-29 10:42:04 -04001325 req.id);
1326 info->tls_ = std::make_unique<TlsSocketEndpoint>(
1327 std::move(endpoint),
1328 certStore(),
Adrien Béraud3f93ddf2023-07-21 14:46:22 -04001329 config_->ioContext,
Adrien Béraud612b55b2023-05-29 10:42:04 -04001330 identity(),
1331 dhParams(),
Adrien Béraud75754b22023-10-17 09:16:06 -04001332 [ph, deviceId, w=weak_from_this(), l=config_->logger](const dht::crypto::Certificate& cert) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001333 auto shared = w.lock();
1334 if (!shared)
1335 return false;
Adrien Béraud9efbd442023-08-27 12:38:07 -04001336 if (cert.getPublicKey().getId() != ph
1337 || deviceId != cert.getPublicKey().getLongId()) {
1338 if (l) l->warn("[device {}] TLS certificate with ID {} doesn't match the DHT request.",
1339 deviceId,
1340 cert.getPublicKey().getLongId());
1341 return false;
1342 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001343 auto crt = shared->certStore().getCertificate(cert.getLongId().toString());
1344 if (!crt)
1345 return false;
1346 return crt->getPacked() == cert.getPacked();
1347 });
1348
1349 info->tls_->setOnReady(
Adrien Béraud75754b22023-10-17 09:16:06 -04001350 [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 -04001351 if (auto shared = w.lock())
Adrien Béraud75754b22023-10-17 09:16:06 -04001352 shared->onTlsNegotiationDone(dinfo.lock(), winfo.lock(), ok, deviceId, vid);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001353 });
1354 return true;
1355}
1356
1357void
1358ConnectionManager::Impl::onDhtPeerRequest(const PeerConnectionRequest& req,
1359 const std::shared_ptr<dht::crypto::Certificate>& /*cert*/)
1360{
1361 auto deviceId = req.owner->getLongId();
1362 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001363 config_->logger->debug("[device {}] New connection request", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001364 if (!iceReqCb_ || !iceReqCb_(deviceId)) {
1365 if (config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001366 config_->logger->debug("[device {}] Refusing connection", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001367 return;
1368 }
1369
1370 // Because the connection is accepted, create an ICE socket.
Adrien Béraud75754b22023-10-17 09:16:06 -04001371 getIceOptions([w = weak_from_this(), req, deviceId](auto&& ice_config) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001372 auto shared = w.lock();
1373 if (!shared)
1374 return;
Adrien Béraud75754b22023-10-17 09:16:06 -04001375
1376 auto di = shared->infos_.createDeviceInfo(deviceId);
1377 auto info = std::make_shared<ConnectionInfo>();
1378 auto wdi = std::weak_ptr(di);
1379 auto winfo = std::weak_ptr(info);
1380
Adrien Béraud612b55b2023-05-29 10:42:04 -04001381 // Note: used when the ice negotiation fails to erase
1382 // all stored structures.
Adrien Béraud75754b22023-10-17 09:16:06 -04001383 auto eraseInfo = [w, wdi, id = req.id] {
1384 auto shared = w.lock();
1385 if (auto di = wdi.lock()) {
1386 std::unique_lock<std::mutex> lk(di->mtx_);
1387 di->info.erase(id);
1388 auto ops = di->extractPendingOperations(id, nullptr);
1389 if (di->empty()) {
1390 if (shared)
1391 shared->infos_.removeDeviceInfo(di->deviceId);
1392 }
1393 lk.unlock();
1394 for (const auto& op: ops)
1395 op.cb(nullptr, di->deviceId);
1396 if (shared && shared->connReadyCb_)
1397 shared->connReadyCb_(di->deviceId, "", nullptr);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001398 }
1399 };
1400
Adrien Béraud75754b22023-10-17 09:16:06 -04001401 ice_config.master = true;
1402 ice_config.streamsCount = 1;
1403 ice_config.compCountPerStream = 1; // TCP
Adrien Béraud612b55b2023-05-29 10:42:04 -04001404 ice_config.tcpEnable = true;
Adrien Béraud75754b22023-10-17 09:16:06 -04001405 ice_config.onInitDone = [w, winfo, req, eraseInfo](bool ok) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001406 auto shared = w.lock();
1407 if (!shared)
1408 return;
1409 if (!ok) {
1410 if (shared->config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001411 shared->config_->logger->error("[device {}] Cannot initialize ICE session.", req.owner->getLongId());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001412 dht::ThreadPool::io().run([eraseInfo = std::move(eraseInfo)] { eraseInfo(); });
1413 return;
1414 }
1415
1416 dht::ThreadPool::io().run(
Adrien Béraud75754b22023-10-17 09:16:06 -04001417 [w = std::move(w), winfo = std::move(winfo), req = std::move(req), eraseInfo = std::move(eraseInfo)] {
1418 if (auto shared = w.lock()) {
1419 if (!shared->onRequestStartIce(winfo.lock(), req))
1420 eraseInfo();
1421 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001422 });
1423 };
1424
Adrien Béraud75754b22023-10-17 09:16:06 -04001425 ice_config.onNegoDone = [w, wdi, winfo, req, eraseInfo](bool ok) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001426 auto shared = w.lock();
1427 if (!shared)
1428 return;
1429 if (!ok) {
1430 if (shared->config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001431 shared->config_->logger->error("[device {}] ICE negotiation failed.", req.owner->getLongId());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001432 dht::ThreadPool::io().run([eraseInfo = std::move(eraseInfo)] { eraseInfo(); });
1433 return;
1434 }
1435
1436 dht::ThreadPool::io().run(
Adrien Béraud75754b22023-10-17 09:16:06 -04001437 [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 -04001438 if (auto shared = w.lock())
Adrien Béraud75754b22023-10-17 09:16:06 -04001439 if (!shared->onRequestOnNegoDone(wdi.lock(), winfo.lock(), req))
Adrien Béraud612b55b2023-05-29 10:42:04 -04001440 eraseInfo();
1441 });
1442 };
1443
1444 // Negotiate a new ICE socket
Adrien Béraud612b55b2023-05-29 10:42:04 -04001445 {
Adrien Béraud75754b22023-10-17 09:16:06 -04001446 std::lock_guard<std::mutex> lk(di->mtx_);
1447 di->info[req.id] = info;
Adrien Béraud612b55b2023-05-29 10:42:04 -04001448 }
Adrien Béraud75754b22023-10-17 09:16:06 -04001449
Adrien Béraud612b55b2023-05-29 10:42:04 -04001450 if (shared->config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001451 shared->config_->logger->debug("[device {}] Accepting connection", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001452 std::unique_lock<std::mutex> lk {info->mutex_};
Sébastien Blin34086512023-07-25 09:52:14 -04001453 info->ice_ = shared->config_->factory->createUTransport("");
Adrien Béraud612b55b2023-05-29 10:42:04 -04001454 if (not info->ice_) {
1455 if (shared->config_->logger)
Adrien Béraud23852462023-07-22 01:46:27 -04001456 shared->config_->logger->error("[device {}] Cannot initialize ICE session", deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001457 eraseInfo();
1458 return;
1459 }
1460 // We need to detect any shutdown if the ice session is destroyed before going to the TLS session;
1461 info->ice_->setOnShutdown([eraseInfo]() {
1462 dht::ThreadPool::io().run([eraseInfo = std::move(eraseInfo)] { eraseInfo(); });
1463 });
Adrien Béraud4cda2d72023-06-01 15:44:43 -04001464 try {
1465 info->ice_->initIceInstance(ice_config);
1466 } catch (const std::exception& e) {
1467 if (shared->config_->logger)
1468 shared->config_->logger->error("{}", e.what());
1469 dht::ThreadPool::io().run([eraseInfo = std::move(eraseInfo)] { eraseInfo(); });
1470 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001471 });
1472}
1473
1474void
Adrien Béraud75754b22023-10-17 09:16:06 -04001475ConnectionManager::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 -04001476{
Adrien Béraud75754b22023-10-17 09:16:06 -04001477 info->socket_ = std::make_shared<MultiplexedSocket>(config_->ioContext, deviceId, std::move(info->tls_), config_->logger);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001478 info->socket_->setOnReady(
Adrien Béraud75754b22023-10-17 09:16:06 -04001479 [w = weak_from_this()](const DeviceId& deviceId, const std::shared_ptr<ChannelSocket>& socket) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001480 if (auto sthis = w.lock())
1481 if (sthis->connReadyCb_)
1482 sthis->connReadyCb_(deviceId, socket->name(), socket);
1483 });
Adrien Béraud75754b22023-10-17 09:16:06 -04001484 info->socket_->setOnRequest([w = weak_from_this()](const std::shared_ptr<dht::crypto::Certificate>& peer,
Adrien Béraud612b55b2023-05-29 10:42:04 -04001485 const uint16_t&,
1486 const std::string& name) {
1487 if (auto sthis = w.lock())
1488 if (sthis->channelReqCb_)
1489 return sthis->channelReqCb_(peer, name);
1490 return false;
1491 });
Adrien Béraud75754b22023-10-17 09:16:06 -04001492 info->socket_->onShutdown([dinfo, wi=std::weak_ptr(info), vid]() {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001493 // Cancel current outgoing connections
Adrien Béraud75754b22023-10-17 09:16:06 -04001494 dht::ThreadPool::io().run([dinfo, wi, vid] {
1495 std::set<dht::Value::Id> ids;
1496 if (auto info = wi.lock()) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001497 std::lock_guard<std::mutex> lk(info->mutex_);
1498 if (info->socket_) {
1499 ids = std::move(info->cbIds_);
1500 info->socket_->shutdown();
1501 }
1502 }
Adrien Béraud75754b22023-10-17 09:16:06 -04001503 if (auto deviceInfo = dinfo.lock()) {
1504 std::shared_ptr<ConnectionInfo> info;
1505 std::vector<PendingCb> ops;
1506 std::unique_lock<std::mutex> lk(deviceInfo->mtx_);
1507 auto it = deviceInfo->info.find(vid);
1508 if (it != deviceInfo->info.end()) {
1509 info = std::move(it->second);
1510 deviceInfo->info.erase(it);
1511 }
1512 for (const auto& cbId : ids) {
1513 auto po = deviceInfo->extractPendingOperations(cbId, nullptr);
1514 ops.insert(ops.end(), po.begin(), po.end());
1515 }
1516 lk.unlock();
1517 for (auto& op : ops)
1518 op.cb(nullptr, deviceInfo->deviceId);
1519 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001520 });
1521 });
1522}
1523
1524const std::shared_future<tls::DhParams>
1525ConnectionManager::Impl::dhParams() const
1526{
1527 return dht::ThreadPool::computation().get<tls::DhParams>(
Adrien Béraud2a4e73d2023-08-27 12:53:55 -04001528 std::bind(tls::DhParams::loadDhParams, config_->cachePath / "dhParams"));
Adrien Béraud612b55b2023-05-29 10:42:04 -04001529}
1530
1531template<typename ID = dht::Value::Id>
1532std::set<ID, std::less<>>
Adrien Béraud1299a0d2023-09-19 15:03:28 -04001533loadIdList(const std::filesystem::path& path)
Adrien Béraud612b55b2023-05-29 10:42:04 -04001534{
1535 std::set<ID, std::less<>> ids;
Adrien Béraud1299a0d2023-09-19 15:03:28 -04001536 std::ifstream file(path);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001537 if (!file.is_open()) {
1538 //JAMI_DBG("Could not load %s", path.c_str());
1539 return ids;
1540 }
1541 std::string line;
1542 while (std::getline(file, line)) {
1543 if constexpr (std::is_same<ID, std::string>::value) {
1544 ids.emplace(std::move(line));
1545 } else if constexpr (std::is_integral<ID>::value) {
1546 ID vid;
1547 if (auto [p, ec] = std::from_chars(line.data(), line.data() + line.size(), vid, 16);
1548 ec == std::errc()) {
1549 ids.emplace(vid);
1550 }
1551 }
1552 }
1553 return ids;
1554}
1555
1556template<typename List = std::set<dht::Value::Id>>
1557void
Adrien Béraud2a4e73d2023-08-27 12:53:55 -04001558saveIdList(const std::filesystem::path& path, const List& ids)
Adrien Béraud612b55b2023-05-29 10:42:04 -04001559{
Adrien Béraud1299a0d2023-09-19 15:03:28 -04001560 std::ofstream file(path, std::ios::trunc | std::ios::binary);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001561 if (!file.is_open()) {
1562 //JAMI_ERR("Could not save to %s", path.c_str());
1563 return;
1564 }
1565 for (auto& c : ids)
1566 file << std::hex << c << "\n";
1567}
1568
1569void
1570ConnectionManager::Impl::loadTreatedMessages()
1571{
1572 std::lock_guard<std::mutex> lock(messageMutex_);
Adrien Béraud2a4e73d2023-08-27 12:53:55 -04001573 auto path = config_->cachePath / "treatedMessages";
Aline Gondim Santos406c0f42023-09-13 12:10:23 -03001574 treatedMessages_ = loadIdList<std::string>(path.string());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001575 if (treatedMessages_.empty()) {
Aline Gondim Santos406c0f42023-09-13 12:10:23 -03001576 auto messages = loadIdList(path.string());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001577 for (const auto& m : messages)
1578 treatedMessages_.emplace(to_hex_string(m));
1579 }
1580}
1581
1582void
1583ConnectionManager::Impl::saveTreatedMessages() const
1584{
Adrien Béraud75754b22023-10-17 09:16:06 -04001585 dht::ThreadPool::io().run([w = weak_from_this()]() {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001586 if (auto sthis = w.lock()) {
1587 auto& this_ = *sthis;
1588 std::lock_guard<std::mutex> lock(this_.messageMutex_);
1589 fileutils::check_dir(this_.config_->cachePath.c_str());
Adrien Béraud2a4e73d2023-08-27 12:53:55 -04001590 saveIdList<decltype(this_.treatedMessages_)>(this_.config_->cachePath / "treatedMessages",
Adrien Béraud612b55b2023-05-29 10:42:04 -04001591 this_.treatedMessages_);
1592 }
1593 });
1594}
1595
1596bool
1597ConnectionManager::Impl::isMessageTreated(std::string_view id)
1598{
1599 std::lock_guard<std::mutex> lock(messageMutex_);
1600 auto res = treatedMessages_.emplace(id);
1601 if (res.second) {
1602 saveTreatedMessages();
1603 return false;
1604 }
1605 return true;
1606}
1607
1608/**
1609 * returns whether or not UPnP is enabled and active_
1610 * ie: if it is able to make port mappings
1611 */
1612bool
1613ConnectionManager::Impl::getUPnPActive() const
1614{
1615 return config_->getUPnPActive();
1616}
1617
1618IpAddr
1619ConnectionManager::Impl::getPublishedIpAddress(uint16_t family) const
1620{
1621 if (family == AF_INET)
1622 return publishedIp_[0];
1623 if (family == AF_INET6)
1624 return publishedIp_[1];
1625
1626 assert(family == AF_UNSPEC);
1627
1628 // If family is not set, prefere IPv4 if available. It's more
1629 // likely to succeed behind NAT.
1630 if (publishedIp_[0])
1631 return publishedIp_[0];
1632 if (publishedIp_[1])
1633 return publishedIp_[1];
1634 return {};
1635}
1636
1637void
1638ConnectionManager::Impl::setPublishedAddress(const IpAddr& ip_addr)
1639{
1640 if (ip_addr.getFamily() == AF_INET) {
1641 publishedIp_[0] = ip_addr;
1642 } else {
1643 publishedIp_[1] = ip_addr;
1644 }
1645}
1646
1647void
1648ConnectionManager::Impl::storeActiveIpAddress(std::function<void()>&& cb)
1649{
Adrien Béraud75754b22023-10-17 09:16:06 -04001650 dht()->getPublicAddress([w=weak_from_this(), cb = std::move(cb)](std::vector<dht::SockAddr>&& results) {
Sébastien Blinb6504372023-10-12 10:35:35 -04001651 auto shared = w.lock();
1652 if (!shared)
1653 return;
Adrien Béraud612b55b2023-05-29 10:42:04 -04001654 bool hasIpv4 {false}, hasIpv6 {false};
1655 for (auto& result : results) {
1656 auto family = result.getFamily();
1657 if (family == AF_INET) {
1658 if (not hasIpv4) {
1659 hasIpv4 = true;
Sébastien Blinb6504372023-10-12 10:35:35 -04001660 if (shared->config_->logger)
1661 shared->config_->logger->debug("Store DHT public IPv4 address: {}", result);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001662 //JAMI_DBG("Store DHT public IPv4 address : %s", result.toString().c_str());
Sébastien Blinb6504372023-10-12 10:35:35 -04001663 shared->setPublishedAddress(*result.get());
1664 if (shared->config_->upnpCtrl) {
1665 shared->config_->upnpCtrl->setPublicAddress(*result.get());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001666 }
1667 }
1668 } else if (family == AF_INET6) {
1669 if (not hasIpv6) {
1670 hasIpv6 = true;
Sébastien Blinb6504372023-10-12 10:35:35 -04001671 if (shared->config_->logger)
1672 shared->config_->logger->debug("Store DHT public IPv6 address: {}", result);
1673 shared->setPublishedAddress(*result.get());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001674 }
1675 }
1676 if (hasIpv4 and hasIpv6)
1677 break;
1678 }
1679 if (cb)
1680 cb();
1681 });
1682}
1683
1684void
1685ConnectionManager::Impl::getIceOptions(std::function<void(IceTransportOptions&&)> cb) noexcept
1686{
1687 storeActiveIpAddress([this, cb = std::move(cb)] {
1688 IceTransportOptions opts = ConnectionManager::Impl::getIceOptions();
1689 auto publishedAddr = getPublishedIpAddress();
1690
1691 if (publishedAddr) {
1692 auto interfaceAddr = ip_utils::getInterfaceAddr(getLocalInterface(),
1693 publishedAddr.getFamily());
1694 if (interfaceAddr) {
1695 opts.accountLocalAddr = interfaceAddr;
1696 opts.accountPublicAddr = publishedAddr;
1697 }
1698 }
1699 if (cb)
1700 cb(std::move(opts));
1701 });
1702}
1703
1704IceTransportOptions
1705ConnectionManager::Impl::getIceOptions() const noexcept
1706{
1707 IceTransportOptions opts;
Sébastien Blin34086512023-07-25 09:52:14 -04001708 opts.factory = config_->factory;
Adrien Béraud612b55b2023-05-29 10:42:04 -04001709 opts.upnpEnable = getUPnPActive();
Adrien Béraud7b869d92023-08-21 09:02:35 -04001710 opts.upnpContext = config_->upnpCtrl ? config_->upnpCtrl->upnpContext() : nullptr;
Adrien Béraud612b55b2023-05-29 10:42:04 -04001711
1712 if (config_->stunEnabled)
1713 opts.stunServers.emplace_back(StunServerInfo().setUri(config_->stunServer));
1714 if (config_->turnEnabled) {
Sébastien Blin84bf4182023-07-21 14:18:39 -04001715 if (config_->turnCache) {
1716 auto turnAddr = config_->turnCache->getResolvedTurn();
1717 if (turnAddr != std::nullopt) {
1718 opts.turnServers.emplace_back(TurnServerInfo()
1719 .setUri(turnAddr->toString())
1720 .setUsername(config_->turnServerUserName)
1721 .setPassword(config_->turnServerPwd)
1722 .setRealm(config_->turnServerRealm));
1723 }
1724 } else {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001725 opts.turnServers.emplace_back(TurnServerInfo()
Sébastien Blin84bf4182023-07-21 14:18:39 -04001726 .setUri(config_->turnServer)
1727 .setUsername(config_->turnServerUserName)
1728 .setPassword(config_->turnServerPwd)
1729 .setRealm(config_->turnServerRealm));
Adrien Béraud612b55b2023-05-29 10:42:04 -04001730 }
1731 // NOTE: first test with ipv6 turn was not concluant and resulted in multiple
1732 // co issues. So this needs some debug. for now just disable
1733 // if (cacheTurnV6 && *cacheTurnV6) {
1734 // opts.turnServers.emplace_back(TurnServerInfo()
1735 // .setUri(cacheTurnV6->toString(true))
1736 // .setUsername(turnServerUserName_)
1737 // .setPassword(turnServerPwd_)
1738 // .setRealm(turnServerRealm_));
1739 //}
Adrien Béraud612b55b2023-05-29 10:42:04 -04001740 }
1741 return opts;
1742}
1743
1744bool
1745ConnectionManager::Impl::foundPeerDevice(const std::shared_ptr<dht::crypto::Certificate>& crt,
1746 dht::InfoHash& account_id,
1747 const std::shared_ptr<Logger>& logger)
1748{
1749 if (not crt)
1750 return false;
1751
1752 auto top_issuer = crt;
1753 while (top_issuer->issuer)
1754 top_issuer = top_issuer->issuer;
1755
1756 // Device certificate can't be self-signed
Adrien Béraudc631a832023-07-26 22:19:00 -04001757 if (top_issuer == crt) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001758 if (logger)
Adrien Béraud8b831a82023-07-21 14:13:06 -04001759 logger->warn("Found invalid (self-signed) peer device: {}", crt->getLongId());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001760 return false;
Adrien Béraudc631a832023-07-26 22:19:00 -04001761 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001762
1763 // Check peer certificate chain
1764 // Trust store with top issuer as the only CA
1765 dht::crypto::TrustList peer_trust;
1766 peer_trust.add(*top_issuer);
1767 if (not peer_trust.verify(*crt)) {
1768 if (logger)
1769 logger->warn("Found invalid peer device: {}", crt->getLongId());
1770 return false;
1771 }
1772
1773 // Check cached OCSP response
1774 if (crt->ocspResponse and crt->ocspResponse->getCertificateStatus() != GNUTLS_OCSP_CERT_GOOD) {
1775 if (logger)
Adrien Béraud8b831a82023-07-21 14:13:06 -04001776 logger->error("Certificate {} is disabled by cached OCSP response", crt->getLongId());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001777 return false;
1778 }
1779
Adrien Béraudc631a832023-07-26 22:19:00 -04001780 account_id = crt->issuer->getId();
1781 if (logger)
1782 logger->warn("Found peer device: {} account:{} CA:{}",
1783 crt->getLongId(),
1784 account_id,
1785 top_issuer->getId());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001786 return true;
1787}
1788
1789bool
1790ConnectionManager::Impl::findCertificate(
1791 const dht::PkId& id, std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb)
1792{
1793 if (auto cert = certStore().getCertificate(id.toString())) {
1794 if (cb)
1795 cb(cert);
1796 } else if (cb)
1797 cb(nullptr);
1798 return true;
1799}
1800
Sébastien Blin34086512023-07-25 09:52:14 -04001801bool
1802ConnectionManager::Impl::findCertificate(const dht::InfoHash& h,
1803 std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb)
1804{
1805 if (auto cert = certStore().getCertificate(h.toString())) {
1806 if (cb)
1807 cb(cert);
1808 } else {
1809 dht()->findCertificate(h,
1810 [cb = std::move(cb), this](
1811 const std::shared_ptr<dht::crypto::Certificate>& crt) {
1812 if (crt)
1813 certStore().pinCertificate(crt);
1814 if (cb)
1815 cb(crt);
1816 });
1817 }
1818 return true;
1819}
1820
Amna81221ad2023-09-14 17:33:26 -04001821std::shared_ptr<ConnectionManager::Config>
1822buildDefaultConfig(dht::crypto::Identity id){
1823 auto conf = std::make_shared<ConnectionManager::Config>();
1824 conf->id = std::move(id);
1825 return conf;
1826}
1827
Adrien Béraud612b55b2023-05-29 10:42:04 -04001828ConnectionManager::ConnectionManager(std::shared_ptr<ConnectionManager::Config> config_)
1829 : pimpl_ {std::make_shared<Impl>(config_)}
1830{}
1831
Amna81221ad2023-09-14 17:33:26 -04001832ConnectionManager::ConnectionManager(dht::crypto::Identity id)
1833 : ConnectionManager {buildDefaultConfig(id)}
1834{}
1835
Adrien Béraud612b55b2023-05-29 10:42:04 -04001836ConnectionManager::~ConnectionManager()
1837{
1838 if (pimpl_)
1839 pimpl_->shutdown();
1840}
1841
1842void
1843ConnectionManager::connectDevice(const DeviceId& deviceId,
1844 const std::string& name,
1845 ConnectCallback cb,
1846 bool noNewSocket,
1847 bool forceNewSocket,
1848 const std::string& connType)
1849{
1850 pimpl_->connectDevice(deviceId, name, std::move(cb), noNewSocket, forceNewSocket, connType);
1851}
1852
1853void
Amna0cf544d2023-07-25 14:25:09 -04001854ConnectionManager::connectDevice(const dht::InfoHash& deviceId,
1855 const std::string& name,
1856 ConnectCallbackLegacy cb,
1857 bool noNewSocket,
1858 bool forceNewSocket,
1859 const std::string& connType)
1860{
1861 pimpl_->connectDevice(deviceId, name, std::move(cb), noNewSocket, forceNewSocket, connType);
1862}
1863
1864
1865void
Adrien Béraud612b55b2023-05-29 10:42:04 -04001866ConnectionManager::connectDevice(const std::shared_ptr<dht::crypto::Certificate>& cert,
1867 const std::string& name,
1868 ConnectCallback cb,
1869 bool noNewSocket,
1870 bool forceNewSocket,
1871 const std::string& connType)
1872{
1873 pimpl_->connectDevice(cert, name, std::move(cb), noNewSocket, forceNewSocket, connType);
1874}
1875
1876bool
1877ConnectionManager::isConnecting(const DeviceId& deviceId, const std::string& name) const
1878{
Adrien Béraud75754b22023-10-17 09:16:06 -04001879 if (auto dinfo = pimpl_->infos_.getDeviceInfo(deviceId)) {
1880 std::unique_lock<std::mutex> lk {dinfo->mtx_};
Adrien Béraudb941e922023-10-16 12:56:14 -04001881 return dinfo->isConnecting(name);
Adrien Béraud75754b22023-10-17 09:16:06 -04001882 }
1883 return false;
Adrien Béraud612b55b2023-05-29 10:42:04 -04001884}
1885
Sébastien Blind0c92c72023-12-07 15:27:51 -05001886bool
1887ConnectionManager::isConnected(const DeviceId& deviceId) const
1888{
1889 if (auto dinfo = pimpl_->infos_.getDeviceInfo(deviceId)) {
1890 std::unique_lock<std::mutex> lk {dinfo->mtx_};
1891 return dinfo->getConnectedInfo() != nullptr;
1892 }
1893 return false;
1894}
1895
Adrien Béraud612b55b2023-05-29 10:42:04 -04001896void
1897ConnectionManager::closeConnectionsWith(const std::string& peerUri)
1898{
Adrien Béraud75754b22023-10-17 09:16:06 -04001899 std::vector<std::shared_ptr<DeviceInfo>> dInfos;
1900 for (const auto& dinfo: pimpl_->infos_.getDeviceInfos()) {
1901 std::unique_lock<std::mutex> lk(dinfo->mtx_);
1902 bool isPeer = false;
1903 for (auto const& [id, cinfo]: dinfo->info) {
1904 std::lock_guard<std::mutex> lkv {cinfo->mutex_};
1905 auto tls = cinfo->tls_ ? cinfo->tls_.get() : (cinfo->socket_ ? cinfo->socket_->endpoint() : nullptr);
Adrien Béraudafa8e282023-09-24 12:53:20 -04001906 auto cert = tls ? tls->peerCertificate() : nullptr;
1907 if (not cert)
Adrien Béraud75754b22023-10-17 09:16:06 -04001908 cert = pimpl_->certStore().getCertificate(dinfo->deviceId.toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001909 if (cert && cert->issuer && peerUri == cert->issuer->getId().toString()) {
Adrien Béraud75754b22023-10-17 09:16:06 -04001910 isPeer = true;
1911 break;
Adrien Béraud612b55b2023-05-29 10:42:04 -04001912 }
1913 }
Adrien Béraud75754b22023-10-17 09:16:06 -04001914 lk.unlock();
1915 if (isPeer) {
1916 dInfos.emplace_back(std::move(dinfo));
1917 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001918 }
1919 // Stop connections to all peers devices
Adrien Béraud75754b22023-10-17 09:16:06 -04001920 for (const auto& dinfo : dInfos) {
1921 std::unique_lock<std::mutex> lk {dinfo->mtx_};
1922 auto unused = dinfo->extractUnusedConnections();
1923 auto pending = dinfo->extractPendingOperations(0, nullptr);
1924 pimpl_->infos_.removeDeviceInfo(dinfo->deviceId);
1925 lk.unlock();
1926 for (auto& op : unused)
1927 op->shutdown();
1928 for (auto& op : pending)
1929 op.cb(nullptr, dinfo->deviceId);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001930 }
1931}
1932
1933void
1934ConnectionManager::onDhtConnected(const dht::crypto::PublicKey& devicePk)
1935{
1936 pimpl_->onDhtConnected(devicePk);
1937}
1938
1939void
1940ConnectionManager::onICERequest(onICERequestCallback&& cb)
1941{
1942 pimpl_->iceReqCb_ = std::move(cb);
1943}
1944
1945void
1946ConnectionManager::onChannelRequest(ChannelRequestCallback&& cb)
1947{
1948 pimpl_->channelReqCb_ = std::move(cb);
1949}
1950
1951void
1952ConnectionManager::onConnectionReady(ConnectionReadyCallback&& cb)
1953{
1954 pimpl_->connReadyCb_ = std::move(cb);
1955}
1956
1957void
1958ConnectionManager::oniOSConnected(iOSConnectedCallback&& cb)
1959{
1960 pimpl_->iOSConnectedCb_ = std::move(cb);
1961}
1962
1963std::size_t
1964ConnectionManager::activeSockets() const
1965{
Adrien Béraud75754b22023-10-17 09:16:06 -04001966 return pimpl_->infos_.getConnectedInfos().size();
Adrien Béraud612b55b2023-05-29 10:42:04 -04001967}
1968
1969void
1970ConnectionManager::monitor() const
1971{
Adrien Béraud612b55b2023-05-29 10:42:04 -04001972 auto logger = pimpl_->config_->logger;
1973 if (!logger)
1974 return;
1975 logger->debug("ConnectionManager current status:");
Adrien Béraud75754b22023-10-17 09:16:06 -04001976 for (const auto& ci : pimpl_->infos_.getConnectedInfos()) {
1977 std::lock_guard<std::mutex> lk(ci->mutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001978 if (ci->socket_)
1979 ci->socket_->monitor();
1980 }
1981 logger->debug("ConnectionManager end status.");
1982}
1983
1984void
1985ConnectionManager::connectivityChanged()
1986{
Adrien Béraud75754b22023-10-17 09:16:06 -04001987 for (const auto& ci : pimpl_->infos_.getConnectedInfos()) {
1988 std::lock_guard<std::mutex> lk(ci->mutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001989 if (ci->socket_)
Adrien Béraud51a54712023-10-17 21:24:30 -04001990 dht::ThreadPool::io().run([s = ci->socket_] { s->sendBeacon(); });
Adrien Béraud612b55b2023-05-29 10:42:04 -04001991 }
1992}
1993
1994void
1995ConnectionManager::getIceOptions(std::function<void(IceTransportOptions&&)> cb) noexcept
1996{
1997 return pimpl_->getIceOptions(std::move(cb));
1998}
1999
2000IceTransportOptions
2001ConnectionManager::getIceOptions() const noexcept
2002{
2003 return pimpl_->getIceOptions();
2004}
2005
2006IpAddr
2007ConnectionManager::getPublishedIpAddress(uint16_t family) const
2008{
2009 return pimpl_->getPublishedIpAddress(family);
2010}
2011
2012void
2013ConnectionManager::setPublishedAddress(const IpAddr& ip_addr)
2014{
2015 return pimpl_->setPublishedAddress(ip_addr);
2016}
2017
2018void
2019ConnectionManager::storeActiveIpAddress(std::function<void()>&& cb)
2020{
2021 return pimpl_->storeActiveIpAddress(std::move(cb));
2022}
2023
2024std::shared_ptr<ConnectionManager::Config>
2025ConnectionManager::getConfig()
2026{
2027 return pimpl_->config_;
2028}
2029
Amna31791e52023-08-03 12:40:57 -04002030std::vector<std::map<std::string, std::string>>
2031ConnectionManager::getConnectionList(const DeviceId& device) const
2032{
2033 std::vector<std::map<std::string, std::string>> connectionsList;
Amna31791e52023-08-03 12:40:57 -04002034 if (device) {
Adrien Béraud75754b22023-10-17 09:16:06 -04002035 if (auto deviceInfo = pimpl_->infos_.getDeviceInfo(device)) {
2036 connectionsList = deviceInfo->getConnectionList(pimpl_->certStore());
Amna31791e52023-08-03 12:40:57 -04002037 }
Adrien Béraud75754b22023-10-17 09:16:06 -04002038 } else {
2039 for (const auto& deviceInfo : pimpl_->infos_.getDeviceInfos()) {
2040 auto cl = deviceInfo->getConnectionList(pimpl_->certStore());
2041 connectionsList.insert(connectionsList.end(), std::make_move_iterator(cl.begin()), std::make_move_iterator(cl.end()));
Amna31791e52023-08-03 12:40:57 -04002042 }
2043 }
2044 return connectionsList;
2045}
2046
2047std::vector<std::map<std::string, std::string>>
2048ConnectionManager::getChannelList(const std::string& connectionId) const
2049{
Adrien Béraud75754b22023-10-17 09:16:06 -04002050 auto [deviceId, valueId] = parseCallbackId(connectionId);
2051 if (auto info = pimpl_->infos_.getInfo(deviceId, valueId)) {
2052 std::lock_guard<std::mutex> lk(info->mutex_);
2053 if (info->socket_)
2054 return info->socket_->getChannelList();
Amna31791e52023-08-03 12:40:57 -04002055 }
Adrien Béraud75754b22023-10-17 09:16:06 -04002056 return {};
Amna31791e52023-08-03 12:40:57 -04002057}
2058
Sébastien Blin464bdff2023-07-19 08:02:53 -04002059} // namespace dhtnet