Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1 | /* |
Adrien Béraud | cb75362 | 2023-07-17 22:32:49 -0400 | [diff] [blame] | 2 | * Copyright (C) 2004-2023 Savoir-faire Linux Inc. |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 3 | * |
Adrien Béraud | cb75362 | 2023-07-17 22:32:49 -0400 | [diff] [blame] | 4 | * This program is free software: you can redistribute it and/or modify |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 5 | * it under the terms of the GNU General Public License as published by |
Adrien Béraud | cb75362 | 2023-07-17 22:32:49 -0400 | [diff] [blame] | 6 | * the Free Software Foundation, either version 3 of the License, or |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 7 | * (at your option) any later version. |
| 8 | * |
| 9 | * This program is distributed in the hope that it will be useful, |
| 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
Adrien Béraud | cb75362 | 2023-07-17 22:32:49 -0400 | [diff] [blame] | 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 12 | * GNU General Public License for more details. |
| 13 | * |
| 14 | * You should have received a copy of the GNU General Public License |
| 15 | * along with this program. If not, see <https://www.gnu.org/licenses/>. |
| 16 | */ |
| 17 | #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 Namvar | 5f63952 | 2023-07-04 17:08:58 -0400 | [diff] [blame] | 36 | #include <fstream> |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 37 | |
Adrien Béraud | 1ae60aa | 2023-07-07 09:55:09 -0400 | [diff] [blame] | 38 | namespace dhtnet { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 39 | static constexpr std::chrono::seconds DHT_MSG_TIMEOUT {30}; |
| 40 | static constexpr uint64_t ID_MAX_VAL = 9007199254740992; |
| 41 | |
| 42 | using ValueIdDist = std::uniform_int_distribution<dht::Value::Id>; |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 43 | |
Amna | 31791e5 | 2023-08-03 12:40:57 -0400 | [diff] [blame] | 44 | std::string |
| 45 | callbackIdToString(const dhtnet::DeviceId& did, const dht::Value::Id& vid) |
| 46 | { |
| 47 | return fmt::format("{} {}", did.to_view(), vid); |
| 48 | } |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 49 | |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 50 | std::pair<dhtnet::DeviceId, dht::Value::Id> parseCallbackId(std::string_view ci) |
Amna | 31791e5 | 2023-08-03 12:40:57 -0400 | [diff] [blame] | 51 | { |
| 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éraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 58 | return {deviceId, vid}; |
Amna | 31791e5 | 2023-08-03 12:40:57 -0400 | [diff] [blame] | 59 | } |
Amna | 81221ad | 2023-09-14 17:33:26 -0400 | [diff] [blame] | 60 | |
| 61 | std::shared_ptr<ConnectionManager::Config> |
| 62 | createConfig(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éraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 88 | struct 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éraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 103 | std::set<dht::Value::Id> cbIds_ {}; |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 104 | |
| 105 | std::function<void(bool)> onConnected_; |
| 106 | std::unique_ptr<asio::steady_timer> waitForAnswer_ {}; |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 107 | |
| 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éraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 146 | }; |
| 147 | |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 148 | struct PendingCb { |
| 149 | std::string name; |
| 150 | ConnectCallback cb; |
Adrien Béraud | b941e92 | 2023-10-16 12:56:14 -0400 | [diff] [blame] | 151 | bool requested {false}; |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 152 | }; |
| 153 | |
| 154 | struct 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éraud | b941e92 | 2023-10-16 12:56:14 -0400 | [diff] [blame] | 239 | bool isConnecting(const std::string& name) const { |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 240 | for (const auto& [id, pc]: connecting) |
Adrien Béraud | b941e92 | 2023-10-16 12:56:14 -0400 | [diff] [blame] | 241 | if (pc.name == name) |
| 242 | return true; |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 243 | for (const auto& [id, pc]: waiting) |
Adrien Béraud | b941e92 | 2023-10-16 12:56:14 -0400 | [diff] [blame] | 244 | 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éraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 262 | 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éraud | d5ec7a8 | 2023-10-28 18:07:03 -0400 | [diff] [blame] | 269 | ret.reserve(info.size() + connecting.size() + waiting.size()); |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 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 | |
| 295 | class DeviceInfoSet { |
| 296 | public: |
| 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 | |
| 361 | private: |
| 362 | std::mutex mtx_ {}; |
| 363 | std::map<DeviceId, std::shared_ptr<DeviceInfo>> infos_ {}; |
| 364 | }; |
| 365 | |
| 366 | |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 367 | /** |
| 368 | * returns whether or not UPnP is enabled and active_ |
| 369 | * ie: if it is able to make port mappings |
| 370 | */ |
| 371 | bool |
| 372 | ConnectionManager::Config::getUPnPActive() const |
| 373 | { |
| 374 | if (upnpCtrl) |
| 375 | return upnpCtrl->isReady(); |
| 376 | return false; |
| 377 | } |
| 378 | |
| 379 | class ConnectionManager::Impl : public std::enable_shared_from_this<ConnectionManager::Impl> |
| 380 | { |
| 381 | public: |
| 382 | explicit Impl(std::shared_ptr<ConnectionManager::Config> config_) |
Amna | 81221ad | 2023-09-14 17:33:26 -0400 | [diff] [blame] | 383 | : config_ {std::move(createConfig(config_))} |
Adrien Béraud | d8b6a40 | 2023-12-08 14:19:25 -0500 | [diff] [blame] | 384 | , rand_ {config_->rng ? *config_->rng : dht::crypto::getSeededRandomEngine<std::mt19937_64>()} |
Kateryna Kostiuk | c39f667 | 2023-09-15 16:49:42 -0400 | [diff] [blame] | 385 | { |
Kateryna Kostiuk | bb300a1 | 2023-10-02 13:19:50 -0400 | [diff] [blame] | 386 | loadTreatedMessages(); |
Amna | 81221ad | 2023-09-14 17:33:26 -0400 | [diff] [blame] | 387 | 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 Kostiuk | c39f667 | 2023-09-15 16:49:42 -0400 | [diff] [blame] | 398 | } |
Amna | 81221ad | 2023-09-14 17:33:26 -0400 | [diff] [blame] | 399 | ~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éraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 407 | |
| 408 | std::shared_ptr<dht::DhtRunner> dht() { return config_->dht; } |
| 409 | const dht::crypto::Identity& identity() const { return config_->id; } |
| 410 | |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 411 | void shutdown() |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 412 | { |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 413 | 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éraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 424 | } |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 425 | 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éraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 430 | if (!unused.empty()) |
Amna | 81221ad | 2023-09-14 17:33:26 -0400 | [diff] [blame] | 431 | dht::ThreadPool::io().run([infos = std::move(unused)]() mutable { |
| 432 | infos.clear(); |
| 433 | }); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 434 | } |
| 435 | |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 436 | void connectDeviceStartIce(const std::shared_ptr<ConnectionInfo>& info, |
| 437 | const std::shared_ptr<dht::crypto::PublicKey>& devicePk, |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 438 | const dht::Value::Id& vid, |
| 439 | const std::string& connType, |
| 440 | std::function<void(bool)> onConnected); |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 441 | 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éraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 445 | 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 = ""); |
Amna | 0cf544d | 2023-07-25 14:25:09 -0400 | [diff] [blame] | 454 | 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éraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 461 | 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éraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 474 | void sendChannelRequest(const std::weak_ptr<DeviceInfo>& dinfo, |
Adrien Béraud | a9ef2a5 | 2023-11-05 00:47:24 -0400 | [diff] [blame] | 475 | const std::weak_ptr<ConnectionInfo>& cinfo, |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 476 | const std::shared_ptr<MultiplexedSocket>& sock, |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 477 | const std::string& name, |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 478 | 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éraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 485 | 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éraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 487 | void onDhtPeerRequest(const PeerConnectionRequest& req, |
| 488 | const std::shared_ptr<dht::crypto::Certificate>& cert); |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 489 | /** |
| 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éraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 502 | |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 503 | void addNewMultiplexedSocket(const std::weak_ptr<DeviceInfo>& dinfo, const DeviceId& deviceId, const dht::Value::Id& vid, const std::shared_ptr<ConnectionInfo>& info); |
Adrien Béraud | 1addf95 | 2023-09-30 17:38:35 -0400 | [diff] [blame] | 504 | void onPeerResponse(PeerConnectionRequest&& req); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 505 | void onDhtConnected(const dht::crypto::PublicKey& devicePk); |
| 506 | |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 507 | |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 508 | 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éraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 531 | /** |
| 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 Blin | 3408651 | 2023-07-25 09:52:14 -0400 | [diff] [blame] | 573 | bool findCertificate(const dht::InfoHash& h, std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 574 | |
| 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éraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 581 | std::shared_ptr<ConnectionManager::Config> config_; |
Amna | 81221ad | 2023-09-14 17:33:26 -0400 | [diff] [blame] | 582 | std::unique_ptr<std::thread> ioContextRunner_; |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 583 | |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 584 | mutable std::mutex randMtx_; |
| 585 | mutable std::mt19937_64 rand_; |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 586 | |
| 587 | iOSConnectedCallback iOSConnectedCb_ {}; |
| 588 | |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 589 | DeviceInfoSet infos_ {}; |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 590 | |
| 591 | ChannelRequestCallback channelReqCb_ {}; |
| 592 | ConnectionReadyCallback connReadyCb_ {}; |
| 593 | onICERequestCallback iceReqCb_ {}; |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 594 | std::atomic_bool isDestroying_ {false}; |
| 595 | }; |
| 596 | |
| 597 | void |
| 598 | ConnectionManager::Impl::connectDeviceStartIce( |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 599 | const std::shared_ptr<ConnectionInfo>& info, |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 600 | 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éraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 606 | 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éraud | 2385246 | 2023-07-22 01:46:27 -0400 | [diff] [blame] | 616 | config_->logger->error("[device {}] No ICE detected", deviceId); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 617 | 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 Blin | aec46fc | 2023-07-25 15:43:10 -0400 | [diff] [blame] | 628 | config_->logger->debug("[device {}] Added local ICE candidate {}", deviceId, addr); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 629 | } |
| 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éraud | 2385246 | 2023-07-22 01:46:27 -0400 | [diff] [blame] | 643 | config_->logger->debug("[device {}] Sending connection request", deviceId); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 644 | 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éraud | 2385246 | 2023-07-22 01:46:27 -0400 | [diff] [blame] | 650 | l->debug("[device {}] Sent connection request. Put encrypted {:s}", |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 651 | 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éraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 665 | std::bind(&ConnectionManager::Impl::onResponse, this, std::placeholders::_1, info, deviceId, vid)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 666 | } |
| 667 | |
| 668 | void |
| 669 | ConnectionManager::Impl::onResponse(const asio::error_code& ec, |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 670 | const std::weak_ptr<ConnectionInfo>& winfo, |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 671 | const DeviceId& deviceId, |
| 672 | const dht::Value::Id& vid) |
| 673 | { |
| 674 | if (ec == asio::error::operation_aborted) |
| 675 | return; |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 676 | auto info = winfo.lock(); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 677 | 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éraud | 2385246 | 2023-07-22 01:46:27 -0400 | [diff] [blame] | 688 | config_->logger->error("[device {}] no response from DHT to ICE request.", deviceId); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 689 | 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éraud | 2385246 | 2023-07-22 01:46:27 -0400 | [diff] [blame] | 702 | config_->logger->warn("[device {}] start ICE failed", deviceId); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 703 | info->onConnected_(false); |
| 704 | return; |
| 705 | } |
| 706 | info->onConnected_(true); |
| 707 | } |
| 708 | |
| 709 | bool |
| 710 | ConnectionManager::Impl::connectDeviceOnNegoDone( |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 711 | const std::weak_ptr<DeviceInfo>& dinfo, |
| 712 | const std::shared_ptr<ConnectionInfo>& info, |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 713 | 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éraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 718 | 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éraud | 2385246 | 2023-07-22 01:46:27 -0400 | [diff] [blame] | 730 | config_->logger->error("[device {}] No ICE detected or not running", deviceId); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 731 | 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éraud | 2385246 | 2023-07-22 01:46:27 -0400 | [diff] [blame] | 741 | config_->logger->debug("[device {}] Start TLS session - Initied by connectDevice(). Launched by channel: {} - vid: {}", deviceId, name, vid); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 742 | info->tls_ = std::make_unique<TlsSocketEndpoint>(std::move(endpoint), |
| 743 | certStore(), |
Adrien Béraud | 3f93ddf | 2023-07-21 14:46:22 -0400 | [diff] [blame] | 744 | config_->ioContext, |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 745 | identity(), |
| 746 | dhParams(), |
| 747 | *cert); |
| 748 | |
| 749 | info->tls_->setOnReady( |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 750 | [w = weak_from_this(), dinfo, winfo=std::weak_ptr(info), deviceId = std::move(deviceId), vid = std::move(vid), name = std::move(name)]( |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 751 | bool ok) { |
Andreas Traczyk | 8b6e99f | 2024-01-04 17:12:55 -0500 | [diff] [blame] | 752 | if (auto shared = w.lock()) |
Andreas Traczyk | b23278d | 2023-12-11 16:14:00 -0500 | [diff] [blame] | 753 | if (auto info = winfo.lock()) { |
| 754 | shared->onTlsNegotiationDone(dinfo.lock(), info, ok, deviceId, vid, name); |
Andreas Traczyk | 8b6e99f | 2024-01-04 17:12:55 -0500 | [diff] [blame] | 755 | // Make another reference to info to avoid destruction (could lead to a deadlock/crash). |
Andreas Traczyk | b23278d | 2023-12-11 16:14:00 -0500 | [diff] [blame] | 756 | dht::ThreadPool::io().run([info = std::move(info)] {}); |
| 757 | } |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 758 | }); |
| 759 | return true; |
| 760 | } |
| 761 | |
| 762 | void |
| 763 | ConnectionManager::Impl::connectDevice(const DeviceId& deviceId, |
| 764 | const std::string& name, |
| 765 | ConnectCallback cb, |
| 766 | bool noNewSocket, |
| 767 | bool forceNewSocket, |
| 768 | const std::string& connType) |
| 769 | { |
| 770 | if (!dht()) { |
| 771 | cb(nullptr, deviceId); |
| 772 | return; |
| 773 | } |
| 774 | if (deviceId.toString() == identity().second->getLongId().toString()) { |
| 775 | cb(nullptr, deviceId); |
| 776 | return; |
| 777 | } |
| 778 | findCertificate(deviceId, |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 779 | [w = weak_from_this(), |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 780 | deviceId, |
| 781 | name, |
| 782 | cb = std::move(cb), |
| 783 | noNewSocket, |
| 784 | forceNewSocket, |
| 785 | connType](const std::shared_ptr<dht::crypto::Certificate>& cert) { |
| 786 | if (!cert) { |
| 787 | if (auto shared = w.lock()) |
| 788 | if (shared->config_->logger) |
| 789 | shared->config_->logger->error( |
| 790 | "No valid certificate found for device {}", |
| 791 | deviceId); |
| 792 | cb(nullptr, deviceId); |
| 793 | return; |
| 794 | } |
| 795 | if (auto shared = w.lock()) { |
| 796 | shared->connectDevice(cert, |
| 797 | name, |
| 798 | std::move(cb), |
| 799 | noNewSocket, |
| 800 | forceNewSocket, |
| 801 | connType); |
| 802 | } else |
| 803 | cb(nullptr, deviceId); |
| 804 | }); |
| 805 | } |
| 806 | |
| 807 | void |
Amna | 0cf544d | 2023-07-25 14:25:09 -0400 | [diff] [blame] | 808 | ConnectionManager::Impl::connectDevice(const dht::InfoHash& deviceId, |
| 809 | const std::string& name, |
| 810 | ConnectCallbackLegacy cb, |
| 811 | bool noNewSocket, |
| 812 | bool forceNewSocket, |
| 813 | const std::string& connType) |
| 814 | { |
| 815 | if (!dht()) { |
| 816 | cb(nullptr, deviceId); |
| 817 | return; |
| 818 | } |
| 819 | if (deviceId.toString() == identity().second->getLongId().toString()) { |
| 820 | cb(nullptr, deviceId); |
| 821 | return; |
| 822 | } |
| 823 | findCertificate(deviceId, |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 824 | [w = weak_from_this(), |
Amna | 0cf544d | 2023-07-25 14:25:09 -0400 | [diff] [blame] | 825 | deviceId, |
| 826 | name, |
| 827 | cb = std::move(cb), |
| 828 | noNewSocket, |
| 829 | forceNewSocket, |
| 830 | connType](const std::shared_ptr<dht::crypto::Certificate>& cert) { |
| 831 | if (!cert) { |
| 832 | if (auto shared = w.lock()) |
| 833 | if (shared->config_->logger) |
| 834 | shared->config_->logger->error( |
| 835 | "No valid certificate found for device {}", |
| 836 | deviceId); |
| 837 | cb(nullptr, deviceId); |
| 838 | return; |
| 839 | } |
| 840 | if (auto shared = w.lock()) { |
| 841 | shared->connectDevice(cert, |
| 842 | name, |
Adrien Béraud | d78d1ac | 2023-08-25 10:43:33 -0400 | [diff] [blame] | 843 | [cb, deviceId](const std::shared_ptr<ChannelSocket>& sock, const DeviceId& /*did*/){ |
Amna | 0cf544d | 2023-07-25 14:25:09 -0400 | [diff] [blame] | 844 | cb(sock, deviceId); |
| 845 | }, |
| 846 | noNewSocket, |
| 847 | forceNewSocket, |
| 848 | connType); |
| 849 | } else |
| 850 | cb(nullptr, deviceId); |
| 851 | }); |
| 852 | } |
| 853 | |
| 854 | void |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 855 | ConnectionManager::Impl::connectDevice(const std::shared_ptr<dht::crypto::Certificate>& cert, |
| 856 | const std::string& name, |
| 857 | ConnectCallback cb, |
| 858 | bool noNewSocket, |
| 859 | bool forceNewSocket, |
| 860 | const std::string& connType) |
| 861 | { |
| 862 | // Avoid dht operation in a DHT callback to avoid deadlocks |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 863 | dht::ThreadPool::computation().run([w = weak_from_this(), |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 864 | name = std::move(name), |
| 865 | cert = std::move(cert), |
| 866 | cb = std::move(cb), |
| 867 | noNewSocket, |
| 868 | forceNewSocket, |
| 869 | connType] { |
| 870 | auto devicePk = cert->getSharedPublicKey(); |
| 871 | auto deviceId = devicePk->getLongId(); |
| 872 | auto sthis = w.lock(); |
| 873 | if (!sthis || sthis->isDestroying_) { |
| 874 | cb(nullptr, deviceId); |
| 875 | return; |
| 876 | } |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 877 | auto di = sthis->infos_.createDeviceInfo(deviceId); |
| 878 | std::unique_lock<std::mutex> lk(di->mtx_); |
| 879 | |
Adrien Béraud | 26365c9 | 2023-09-23 23:42:43 -0400 | [diff] [blame] | 880 | dht::Value::Id vid; |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 881 | { |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 882 | std::lock_guard<std::mutex> lkr(sthis->randMtx_); |
| 883 | vid = di->newId(sthis->rand_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 884 | } |
| 885 | |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 886 | // Check if already connecting |
| 887 | auto isConnectingToDevice = di->isConnecting(); |
| 888 | // Note: we can be in a state where first |
| 889 | // socket is negotiated and first channel is pending |
| 890 | // so return only after we checked the info |
Adrien Béraud | b941e92 | 2023-10-16 12:56:14 -0400 | [diff] [blame] | 891 | auto& diw = (isConnectingToDevice && !forceNewSocket) |
| 892 | ? di->waiting[vid] |
| 893 | : di->connecting[vid]; |
| 894 | diw = PendingCb {name, std::move(cb)}; |
| 895 | |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 896 | // Check if already negotiated |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 897 | if (auto info = di->getConnectedInfo()) { |
| 898 | std::unique_lock<std::mutex> lkc(info->mutex_); |
| 899 | if (auto sock = info->socket_) { |
| 900 | info->cbIds_.emplace(vid); |
Adrien Béraud | b941e92 | 2023-10-16 12:56:14 -0400 | [diff] [blame] | 901 | diw.requested = true; |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 902 | lkc.unlock(); |
| 903 | lk.unlock(); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 904 | if (sthis->config_->logger) |
Adrien Béraud | 2385246 | 2023-07-22 01:46:27 -0400 | [diff] [blame] | 905 | sthis->config_->logger->debug("[device {}] Peer already connected. Add a new channel", deviceId); |
Adrien Béraud | a9ef2a5 | 2023-11-05 00:47:24 -0400 | [diff] [blame] | 906 | sthis->sendChannelRequest(di, info, sock, name, vid); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 907 | return; |
| 908 | } |
| 909 | } |
| 910 | |
| 911 | if (isConnectingToDevice && !forceNewSocket) { |
| 912 | if (sthis->config_->logger) |
Adrien Béraud | 2385246 | 2023-07-22 01:46:27 -0400 | [diff] [blame] | 913 | sthis->config_->logger->debug("[device {}] Already connecting, wait for ICE negotiation", deviceId); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 914 | return; |
| 915 | } |
| 916 | if (noNewSocket) { |
| 917 | // If no new socket is specified, we don't try to generate a new socket |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 918 | di->executePendingOperations(lk, vid, nullptr); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 919 | return; |
| 920 | } |
| 921 | |
| 922 | // Note: used when the ice negotiation fails to erase |
| 923 | // all stored structures. |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 924 | auto eraseInfo = [w, diw=std::weak_ptr(di), vid] { |
| 925 | if (auto di = diw.lock()) { |
| 926 | std::unique_lock<std::mutex> lk(di->mtx_); |
| 927 | di->info.erase(vid); |
| 928 | auto ops = di->extractPendingOperations(vid, nullptr); |
| 929 | if (di->empty()) { |
| 930 | if (auto shared = w.lock()) |
| 931 | shared->infos_.removeDeviceInfo(di->deviceId); |
| 932 | } |
| 933 | lk.unlock(); |
| 934 | for (const auto& op: ops) |
| 935 | op.cb(nullptr, di->deviceId); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 936 | } |
| 937 | }; |
| 938 | |
| 939 | // If no socket exists, we need to initiate an ICE connection. |
| 940 | sthis->getIceOptions([w, |
| 941 | deviceId = std::move(deviceId), |
| 942 | devicePk = std::move(devicePk), |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 943 | diw=std::weak_ptr(di), |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 944 | name = std::move(name), |
| 945 | cert = std::move(cert), |
| 946 | vid, |
| 947 | connType, |
| 948 | eraseInfo](auto&& ice_config) { |
| 949 | auto sthis = w.lock(); |
| 950 | if (!sthis) { |
| 951 | dht::ThreadPool::io().run([eraseInfo = std::move(eraseInfo)] { eraseInfo(); }); |
| 952 | return; |
| 953 | } |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 954 | auto info = std::make_shared<ConnectionInfo>(); |
| 955 | auto winfo = std::weak_ptr(info); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 956 | ice_config.tcpEnable = true; |
| 957 | ice_config.onInitDone = [w, |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 958 | devicePk = std::move(devicePk), |
| 959 | name = std::move(name), |
| 960 | cert = std::move(cert), |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 961 | diw, |
| 962 | winfo = std::weak_ptr(info), |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 963 | vid, |
| 964 | connType, |
| 965 | eraseInfo](bool ok) { |
| 966 | dht::ThreadPool::io().run([w = std::move(w), |
| 967 | devicePk = std::move(devicePk), |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 968 | vid, |
| 969 | winfo, |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 970 | eraseInfo, |
| 971 | connType, ok] { |
| 972 | auto sthis = w.lock(); |
| 973 | if (!ok && sthis && sthis->config_->logger) |
Adrien Béraud | 2385246 | 2023-07-22 01:46:27 -0400 | [diff] [blame] | 974 | sthis->config_->logger->error("[device {}] Cannot initialize ICE session.", devicePk->getLongId()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 975 | if (!sthis || !ok) { |
| 976 | eraseInfo(); |
| 977 | return; |
| 978 | } |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 979 | sthis->connectDeviceStartIce(winfo.lock(), devicePk, vid, connType, [=](bool ok) { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 980 | if (!ok) { |
| 981 | dht::ThreadPool::io().run([eraseInfo = std::move(eraseInfo)] { eraseInfo(); }); |
| 982 | } |
| 983 | }); |
| 984 | }); |
| 985 | }; |
| 986 | ice_config.onNegoDone = [w, |
| 987 | deviceId, |
| 988 | name, |
| 989 | cert = std::move(cert), |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 990 | diw, |
| 991 | winfo = std::weak_ptr(info), |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 992 | vid, |
| 993 | eraseInfo](bool ok) { |
| 994 | dht::ThreadPool::io().run([w = std::move(w), |
| 995 | deviceId = std::move(deviceId), |
| 996 | name = std::move(name), |
| 997 | cert = std::move(cert), |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 998 | diw = std::move(diw), |
| 999 | winfo = std::move(winfo), |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1000 | vid = std::move(vid), |
| 1001 | eraseInfo = std::move(eraseInfo), |
| 1002 | ok] { |
| 1003 | auto sthis = w.lock(); |
| 1004 | if (!ok && sthis && sthis->config_->logger) |
Adrien Béraud | 2385246 | 2023-07-22 01:46:27 -0400 | [diff] [blame] | 1005 | sthis->config_->logger->error("[device {}] ICE negotiation failed.", deviceId); |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1006 | if (!sthis || !ok || !sthis->connectDeviceOnNegoDone(diw, winfo.lock(), deviceId, name, vid, cert)) |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1007 | eraseInfo(); |
| 1008 | }); |
| 1009 | }; |
| 1010 | |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1011 | if (auto di = diw.lock()) { |
| 1012 | std::lock_guard<std::mutex> lk(di->mtx_); |
| 1013 | di->info[vid] = info; |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1014 | } |
| 1015 | std::unique_lock<std::mutex> lk {info->mutex_}; |
| 1016 | ice_config.master = false; |
| 1017 | ice_config.streamsCount = 1; |
| 1018 | ice_config.compCountPerStream = 1; |
Sébastien Blin | 3408651 | 2023-07-25 09:52:14 -0400 | [diff] [blame] | 1019 | info->ice_ = sthis->config_->factory->createUTransport(""); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1020 | if (!info->ice_) { |
| 1021 | if (sthis->config_->logger) |
Adrien Béraud | 2385246 | 2023-07-22 01:46:27 -0400 | [diff] [blame] | 1022 | sthis->config_->logger->error("[device {}] Cannot initialize ICE session.", deviceId); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1023 | eraseInfo(); |
| 1024 | return; |
| 1025 | } |
| 1026 | // We need to detect any shutdown if the ice session is destroyed before going to the |
| 1027 | // TLS session; |
| 1028 | info->ice_->setOnShutdown([eraseInfo]() { |
| 1029 | dht::ThreadPool::io().run([eraseInfo = std::move(eraseInfo)] { eraseInfo(); }); |
| 1030 | }); |
Adrien Béraud | 4cda2d7 | 2023-06-01 15:44:43 -0400 | [diff] [blame] | 1031 | try { |
| 1032 | info->ice_->initIceInstance(ice_config); |
| 1033 | } catch (const std::exception& e) { |
| 1034 | if (sthis->config_->logger) |
| 1035 | sthis->config_->logger->error("{}", e.what()); |
| 1036 | dht::ThreadPool::io().run([eraseInfo = std::move(eraseInfo)] { eraseInfo(); }); |
| 1037 | } |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1038 | }); |
| 1039 | }); |
| 1040 | } |
| 1041 | |
| 1042 | void |
Adrien Béraud | a9ef2a5 | 2023-11-05 00:47:24 -0400 | [diff] [blame] | 1043 | ConnectionManager::Impl::sendChannelRequest(const std::weak_ptr<DeviceInfo>& dinfow, |
| 1044 | const std::weak_ptr<ConnectionInfo>& cinfow, |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1045 | const std::shared_ptr<MultiplexedSocket>& sock, |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1046 | const std::string& name, |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1047 | const dht::Value::Id& vid) |
| 1048 | { |
| 1049 | auto channelSock = sock->addChannel(name); |
Adrien Béraud | 9a4e98b | 2023-10-15 12:10:21 -0400 | [diff] [blame] | 1050 | if (!channelSock) { |
| 1051 | if (config_->logger) |
| 1052 | config_->logger->error("sendChannelRequest failed - cannot create channel"); |
Adrien Béraud | a9ef2a5 | 2023-11-05 00:47:24 -0400 | [diff] [blame] | 1053 | if (auto info = dinfow.lock()) |
Adrien Béraud | 9a4e98b | 2023-10-15 12:10:21 -0400 | [diff] [blame] | 1054 | info->executePendingOperations(vid, nullptr); |
| 1055 | return; |
| 1056 | } |
Adrien Béraud | a9ef2a5 | 2023-11-05 00:47:24 -0400 | [diff] [blame] | 1057 | channelSock->onShutdown([dinfow, name, vid] { |
| 1058 | if (auto info = dinfow.lock()) |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1059 | info->executePendingOperations(vid, nullptr); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1060 | }); |
| 1061 | channelSock->onReady( |
Adrien Béraud | a9ef2a5 | 2023-11-05 00:47:24 -0400 | [diff] [blame] | 1062 | [dinfow, cinfow, wSock = std::weak_ptr(channelSock), name, vid](bool accepted) { |
| 1063 | if (auto dinfo = dinfow.lock()) { |
| 1064 | dinfo->executePendingOperations(vid, accepted ? wSock.lock() : nullptr, accepted); |
Sébastien Blin | ad16157 | 2024-01-31 14:14:51 -0500 | [diff] [blame] | 1065 | // Always lock top-down cinfo->mutex |
| 1066 | dht::ThreadPool::io().run([cinfow, vid]() { |
| 1067 | if (auto cinfo = cinfow.lock()) { |
| 1068 | std::lock_guard<std::mutex> lk(cinfo->mutex_); |
| 1069 | cinfo->cbIds_.erase(vid); |
| 1070 | } |
| 1071 | }); |
Adrien Béraud | a9ef2a5 | 2023-11-05 00:47:24 -0400 | [diff] [blame] | 1072 | } |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1073 | }); |
| 1074 | |
| 1075 | ChannelRequest val; |
| 1076 | val.name = channelSock->name(); |
| 1077 | val.state = ChannelRequestState::REQUEST; |
| 1078 | val.channel = channelSock->channel(); |
| 1079 | msgpack::sbuffer buffer(256); |
| 1080 | msgpack::pack(buffer, val); |
| 1081 | |
| 1082 | std::error_code ec; |
| 1083 | int res = sock->write(CONTROL_CHANNEL, |
| 1084 | reinterpret_cast<const uint8_t*>(buffer.data()), |
| 1085 | buffer.size(), |
| 1086 | ec); |
| 1087 | if (res < 0) { |
| 1088 | // TODO check if we should handle errors here |
| 1089 | if (config_->logger) |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1090 | config_->logger->error("sendChannelRequest failed - error: {}", ec.message()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1091 | } |
| 1092 | } |
| 1093 | |
| 1094 | void |
Adrien Béraud | 1addf95 | 2023-09-30 17:38:35 -0400 | [diff] [blame] | 1095 | ConnectionManager::Impl::onPeerResponse(PeerConnectionRequest&& req) |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1096 | { |
| 1097 | auto device = req.owner->getLongId(); |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1098 | if (auto info = infos_.getInfo(device, req.id)) { |
Adrien Béraud | 2385246 | 2023-07-22 01:46:27 -0400 | [diff] [blame] | 1099 | if (config_->logger) |
| 1100 | config_->logger->debug("[device {}] New response received", device); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1101 | std::lock_guard<std::mutex> lk {info->mutex_}; |
| 1102 | info->responseReceived_ = true; |
| 1103 | info->response_ = std::move(req); |
| 1104 | info->waitForAnswer_->expires_at(std::chrono::steady_clock::now()); |
| 1105 | info->waitForAnswer_->async_wait(std::bind(&ConnectionManager::Impl::onResponse, |
| 1106 | this, |
| 1107 | std::placeholders::_1, |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1108 | std::weak_ptr(info), |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1109 | device, |
| 1110 | req.id)); |
| 1111 | } else { |
| 1112 | if (config_->logger) |
Adrien Béraud | 2385246 | 2023-07-22 01:46:27 -0400 | [diff] [blame] | 1113 | config_->logger->warn("[device {}] Respond received, but cannot find request", device); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1114 | } |
| 1115 | } |
| 1116 | |
| 1117 | void |
| 1118 | ConnectionManager::Impl::onDhtConnected(const dht::crypto::PublicKey& devicePk) |
| 1119 | { |
| 1120 | if (!dht()) |
| 1121 | return; |
| 1122 | dht()->listen<PeerConnectionRequest>( |
| 1123 | dht::InfoHash::get(PeerConnectionRequest::key_prefix + devicePk.getId().toString()), |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1124 | [w = weak_from_this()](PeerConnectionRequest&& req) { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1125 | auto shared = w.lock(); |
| 1126 | if (!shared) |
| 1127 | return false; |
| 1128 | if (shared->isMessageTreated(to_hex_string(req.id))) { |
| 1129 | // Message already treated. Just ignore |
| 1130 | return true; |
| 1131 | } |
| 1132 | if (req.isAnswer) { |
| 1133 | if (shared->config_->logger) |
Adrien Béraud | 2385246 | 2023-07-22 01:46:27 -0400 | [diff] [blame] | 1134 | shared->config_->logger->debug("[device {}] Received request answer", req.owner->getLongId()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1135 | } else { |
| 1136 | if (shared->config_->logger) |
Adrien Béraud | 2385246 | 2023-07-22 01:46:27 -0400 | [diff] [blame] | 1137 | shared->config_->logger->debug("[device {}] Received request", req.owner->getLongId()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1138 | } |
| 1139 | if (req.isAnswer) { |
Adrien Béraud | 1addf95 | 2023-09-30 17:38:35 -0400 | [diff] [blame] | 1140 | shared->onPeerResponse(std::move(req)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1141 | } else { |
| 1142 | // Async certificate checking |
Sébastien Blin | 3408651 | 2023-07-25 09:52:14 -0400 | [diff] [blame] | 1143 | shared->findCertificate( |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1144 | req.from, |
| 1145 | [w, req = std::move(req)]( |
| 1146 | const std::shared_ptr<dht::crypto::Certificate>& cert) mutable { |
| 1147 | auto shared = w.lock(); |
| 1148 | if (!shared) |
| 1149 | return; |
| 1150 | dht::InfoHash peer_h; |
| 1151 | if (foundPeerDevice(cert, peer_h, shared->config_->logger)) { |
| 1152 | #if TARGET_OS_IOS |
| 1153 | if (shared->iOSConnectedCb_(req.connType, peer_h)) |
| 1154 | return; |
| 1155 | #endif |
| 1156 | shared->onDhtPeerRequest(req, cert); |
| 1157 | } else { |
| 1158 | if (shared->config_->logger) |
| 1159 | shared->config_->logger->warn( |
Adrien Béraud | 2385246 | 2023-07-22 01:46:27 -0400 | [diff] [blame] | 1160 | "[device {}] Received request from untrusted peer", |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1161 | req.owner->getLongId()); |
| 1162 | } |
| 1163 | }); |
| 1164 | } |
| 1165 | |
| 1166 | return true; |
| 1167 | }, |
| 1168 | dht::Value::UserTypeFilter("peer_request")); |
| 1169 | } |
| 1170 | |
| 1171 | void |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1172 | ConnectionManager::Impl::onTlsNegotiationDone(const std::shared_ptr<DeviceInfo>& dinfo, |
| 1173 | const std::shared_ptr<ConnectionInfo>& info, |
| 1174 | bool ok, |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1175 | const DeviceId& deviceId, |
| 1176 | const dht::Value::Id& vid, |
| 1177 | const std::string& name) |
| 1178 | { |
| 1179 | if (isDestroying_) |
| 1180 | return; |
| 1181 | // Note: only handle pendingCallbacks here for TLS initied by connectDevice() |
| 1182 | // Note: if not initied by connectDevice() the channel name will be empty (because no channel |
| 1183 | // asked yet) |
| 1184 | auto isDhtRequest = name.empty(); |
| 1185 | if (!ok) { |
| 1186 | if (isDhtRequest) { |
| 1187 | if (config_->logger) |
Adrien Béraud | 2385246 | 2023-07-22 01:46:27 -0400 | [diff] [blame] | 1188 | config_->logger->error("[device {}] TLS connection failure - Initied by DHT request. channel: {} - vid: {}", |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1189 | deviceId, |
| 1190 | name, |
| 1191 | vid); |
| 1192 | if (connReadyCb_) |
| 1193 | connReadyCb_(deviceId, "", nullptr); |
| 1194 | } else { |
| 1195 | if (config_->logger) |
Adrien Béraud | 2385246 | 2023-07-22 01:46:27 -0400 | [diff] [blame] | 1196 | config_->logger->error("[device {}] TLS connection failure - Initied by connectDevice. channel: {} - vid: {}", |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1197 | deviceId, |
| 1198 | name, |
| 1199 | vid); |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1200 | dinfo->executePendingOperations(vid, nullptr); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1201 | } |
Sébastien Blin | 3cf0acc | 2023-10-23 09:45:32 -0400 | [diff] [blame] | 1202 | |
| 1203 | std::unique_lock<std::mutex> lk(dinfo->mtx_); |
| 1204 | dinfo->info.erase(vid); |
| 1205 | |
| 1206 | if (dinfo->empty()) { |
| 1207 | infos_.removeDeviceInfo(dinfo->deviceId); |
| 1208 | } |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1209 | } else { |
| 1210 | // The socket is ready, store it |
| 1211 | if (isDhtRequest) { |
| 1212 | if (config_->logger) |
Adrien Béraud | 2385246 | 2023-07-22 01:46:27 -0400 | [diff] [blame] | 1213 | config_->logger->debug("[device {}] Connection is ready - Initied by DHT request. Vid: {}", |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1214 | deviceId, |
| 1215 | vid); |
| 1216 | } else { |
| 1217 | if (config_->logger) |
Adrien Béraud | 2385246 | 2023-07-22 01:46:27 -0400 | [diff] [blame] | 1218 | config_->logger->debug("[device {}] Connection is ready - Initied by connectDevice(). channel: {} - vid: {}", |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1219 | deviceId, |
| 1220 | name, |
| 1221 | vid); |
| 1222 | } |
| 1223 | |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1224 | // Note: do not remove pending there it's done in sendChannelRequest |
| 1225 | std::unique_lock<std::mutex> lk2 {dinfo->mtx_}; |
Adrien Béraud | b941e92 | 2023-10-16 12:56:14 -0400 | [diff] [blame] | 1226 | auto pendingIds = dinfo->requestPendingOps(); |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1227 | lk2.unlock(); |
| 1228 | std::unique_lock<std::mutex> lk {info->mutex_}; |
| 1229 | addNewMultiplexedSocket(dinfo, deviceId, vid, info); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1230 | // Finally, open the channel and launch pending callbacks |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1231 | lk.unlock(); |
| 1232 | for (const auto& [id, name]: pendingIds) { |
| 1233 | if (config_->logger) |
| 1234 | config_->logger->debug("[device {}] Send request on TLS socket for channel {}", |
| 1235 | deviceId, name); |
Adrien Béraud | a9ef2a5 | 2023-11-05 00:47:24 -0400 | [diff] [blame] | 1236 | sendChannelRequest(dinfo, info, info->socket_, name, id); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1237 | } |
| 1238 | } |
| 1239 | } |
| 1240 | |
| 1241 | void |
| 1242 | ConnectionManager::Impl::answerTo(IceTransport& ice, |
| 1243 | const dht::Value::Id& id, |
| 1244 | const std::shared_ptr<dht::crypto::PublicKey>& from) |
| 1245 | { |
| 1246 | // NOTE: This is a shortest version of a real SDP message to save some bits |
| 1247 | auto iceAttributes = ice.getLocalAttributes(); |
| 1248 | std::ostringstream icemsg; |
| 1249 | icemsg << iceAttributes.ufrag << "\n"; |
| 1250 | icemsg << iceAttributes.pwd << "\n"; |
| 1251 | for (const auto& addr : ice.getLocalCandidates(1)) { |
| 1252 | icemsg << addr << "\n"; |
| 1253 | } |
| 1254 | |
| 1255 | // Send PeerConnection response |
| 1256 | PeerConnectionRequest val; |
| 1257 | val.id = id; |
| 1258 | val.ice_msg = icemsg.str(); |
| 1259 | val.isAnswer = true; |
| 1260 | auto value = std::make_shared<dht::Value>(std::move(val)); |
| 1261 | value->user_type = "peer_request"; |
| 1262 | |
| 1263 | if (config_->logger) |
Adrien Béraud | 2385246 | 2023-07-22 01:46:27 -0400 | [diff] [blame] | 1264 | config_->logger->debug("[device {}] Connection accepted, DHT reply", from->getLongId()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1265 | dht()->putEncrypted(dht::InfoHash::get(PeerConnectionRequest::key_prefix |
| 1266 | + from->getId().toString()), |
| 1267 | from, |
| 1268 | value, |
| 1269 | [from,l=config_->logger](bool ok) { |
| 1270 | if (l) |
Adrien Béraud | 2385246 | 2023-07-22 01:46:27 -0400 | [diff] [blame] | 1271 | l->debug("[device {}] Answer to connection request: put encrypted {:s}", |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1272 | from->getLongId(), |
| 1273 | (ok ? "ok" : "failed")); |
| 1274 | }); |
| 1275 | } |
| 1276 | |
| 1277 | bool |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1278 | ConnectionManager::Impl::onRequestStartIce(const std::shared_ptr<ConnectionInfo>& info, const PeerConnectionRequest& req) |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1279 | { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1280 | if (!info) |
| 1281 | return false; |
| 1282 | |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1283 | auto deviceId = req.owner->getLongId(); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1284 | std::unique_lock<std::mutex> lk {info->mutex_}; |
| 1285 | auto& ice = info->ice_; |
| 1286 | if (!ice) { |
| 1287 | if (config_->logger) |
Adrien Béraud | 2385246 | 2023-07-22 01:46:27 -0400 | [diff] [blame] | 1288 | config_->logger->error("[device {}] No ICE detected", deviceId); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1289 | if (connReadyCb_) |
| 1290 | connReadyCb_(deviceId, "", nullptr); |
| 1291 | return false; |
| 1292 | } |
| 1293 | |
| 1294 | auto sdp = ice->parseIceCandidates(req.ice_msg); |
| 1295 | answerTo(*ice, req.id, req.owner); |
| 1296 | if (not ice->startIce({sdp.rem_ufrag, sdp.rem_pwd}, std::move(sdp.rem_candidates))) { |
| 1297 | if (config_->logger) |
Adrien Béraud | 2385246 | 2023-07-22 01:46:27 -0400 | [diff] [blame] | 1298 | config_->logger->error("[device {}] Start ICE failed", deviceId); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1299 | ice = nullptr; |
| 1300 | if (connReadyCb_) |
| 1301 | connReadyCb_(deviceId, "", nullptr); |
| 1302 | return false; |
| 1303 | } |
| 1304 | return true; |
| 1305 | } |
| 1306 | |
| 1307 | bool |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1308 | ConnectionManager::Impl::onRequestOnNegoDone(const std::weak_ptr<DeviceInfo>& dinfo, const std::shared_ptr<ConnectionInfo>& info, const PeerConnectionRequest& req) |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1309 | { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1310 | if (!info) |
| 1311 | return false; |
| 1312 | |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1313 | auto deviceId = req.owner->getLongId(); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1314 | std::unique_lock<std::mutex> lk {info->mutex_}; |
| 1315 | auto& ice = info->ice_; |
| 1316 | if (!ice) { |
| 1317 | if (config_->logger) |
Adrien Béraud | 2385246 | 2023-07-22 01:46:27 -0400 | [diff] [blame] | 1318 | config_->logger->error("[device {}] No ICE detected", deviceId); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1319 | return false; |
| 1320 | } |
| 1321 | |
| 1322 | // Build socket |
| 1323 | auto endpoint = std::make_unique<IceSocketEndpoint>(std::shared_ptr<IceTransport>( |
| 1324 | std::move(ice)), |
| 1325 | false); |
| 1326 | |
| 1327 | // init TLS session |
| 1328 | auto ph = req.from; |
| 1329 | if (config_->logger) |
Adrien Béraud | 2385246 | 2023-07-22 01:46:27 -0400 | [diff] [blame] | 1330 | config_->logger->debug("[device {}] Start TLS session - Initied by DHT request. vid: {}", |
| 1331 | deviceId, |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1332 | req.id); |
| 1333 | info->tls_ = std::make_unique<TlsSocketEndpoint>( |
| 1334 | std::move(endpoint), |
| 1335 | certStore(), |
Adrien Béraud | 3f93ddf | 2023-07-21 14:46:22 -0400 | [diff] [blame] | 1336 | config_->ioContext, |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1337 | identity(), |
| 1338 | dhParams(), |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1339 | [ph, deviceId, w=weak_from_this(), l=config_->logger](const dht::crypto::Certificate& cert) { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1340 | auto shared = w.lock(); |
| 1341 | if (!shared) |
| 1342 | return false; |
Adrien Béraud | 9efbd44 | 2023-08-27 12:38:07 -0400 | [diff] [blame] | 1343 | if (cert.getPublicKey().getId() != ph |
| 1344 | || deviceId != cert.getPublicKey().getLongId()) { |
| 1345 | if (l) l->warn("[device {}] TLS certificate with ID {} doesn't match the DHT request.", |
| 1346 | deviceId, |
| 1347 | cert.getPublicKey().getLongId()); |
| 1348 | return false; |
| 1349 | } |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1350 | auto crt = shared->certStore().getCertificate(cert.getLongId().toString()); |
| 1351 | if (!crt) |
| 1352 | return false; |
| 1353 | return crt->getPacked() == cert.getPacked(); |
| 1354 | }); |
| 1355 | |
| 1356 | info->tls_->setOnReady( |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1357 | [w = weak_from_this(), dinfo, winfo=std::weak_ptr(info), deviceId = std::move(deviceId), vid = std::move(req.id)](bool ok) { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1358 | if (auto shared = w.lock()) |
Andreas Traczyk | 8b6e99f | 2024-01-04 17:12:55 -0500 | [diff] [blame] | 1359 | if (auto info = winfo.lock()) { |
| 1360 | shared->onTlsNegotiationDone(dinfo.lock(), winfo.lock(), ok, deviceId, vid); |
| 1361 | // Make another reference to info to avoid destruction (could lead to a deadlock/crash). |
| 1362 | dht::ThreadPool::io().run([info = std::move(info)] {}); |
| 1363 | } |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1364 | }); |
| 1365 | return true; |
| 1366 | } |
| 1367 | |
| 1368 | void |
| 1369 | ConnectionManager::Impl::onDhtPeerRequest(const PeerConnectionRequest& req, |
| 1370 | const std::shared_ptr<dht::crypto::Certificate>& /*cert*/) |
| 1371 | { |
| 1372 | auto deviceId = req.owner->getLongId(); |
| 1373 | if (config_->logger) |
Adrien Béraud | 2385246 | 2023-07-22 01:46:27 -0400 | [diff] [blame] | 1374 | config_->logger->debug("[device {}] New connection request", deviceId); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1375 | if (!iceReqCb_ || !iceReqCb_(deviceId)) { |
| 1376 | if (config_->logger) |
Adrien Béraud | 2385246 | 2023-07-22 01:46:27 -0400 | [diff] [blame] | 1377 | config_->logger->debug("[device {}] Refusing connection", deviceId); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1378 | return; |
| 1379 | } |
| 1380 | |
| 1381 | // Because the connection is accepted, create an ICE socket. |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1382 | getIceOptions([w = weak_from_this(), req, deviceId](auto&& ice_config) { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1383 | auto shared = w.lock(); |
| 1384 | if (!shared) |
| 1385 | return; |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1386 | |
| 1387 | auto di = shared->infos_.createDeviceInfo(deviceId); |
| 1388 | auto info = std::make_shared<ConnectionInfo>(); |
| 1389 | auto wdi = std::weak_ptr(di); |
| 1390 | auto winfo = std::weak_ptr(info); |
| 1391 | |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1392 | // Note: used when the ice negotiation fails to erase |
| 1393 | // all stored structures. |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1394 | auto eraseInfo = [w, wdi, id = req.id] { |
| 1395 | auto shared = w.lock(); |
| 1396 | if (auto di = wdi.lock()) { |
| 1397 | std::unique_lock<std::mutex> lk(di->mtx_); |
| 1398 | di->info.erase(id); |
| 1399 | auto ops = di->extractPendingOperations(id, nullptr); |
| 1400 | if (di->empty()) { |
| 1401 | if (shared) |
| 1402 | shared->infos_.removeDeviceInfo(di->deviceId); |
| 1403 | } |
| 1404 | lk.unlock(); |
| 1405 | for (const auto& op: ops) |
| 1406 | op.cb(nullptr, di->deviceId); |
| 1407 | if (shared && shared->connReadyCb_) |
| 1408 | shared->connReadyCb_(di->deviceId, "", nullptr); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1409 | } |
| 1410 | }; |
| 1411 | |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1412 | ice_config.master = true; |
| 1413 | ice_config.streamsCount = 1; |
| 1414 | ice_config.compCountPerStream = 1; // TCP |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1415 | ice_config.tcpEnable = true; |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1416 | ice_config.onInitDone = [w, winfo, req, eraseInfo](bool ok) { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1417 | auto shared = w.lock(); |
| 1418 | if (!shared) |
| 1419 | return; |
| 1420 | if (!ok) { |
| 1421 | if (shared->config_->logger) |
Adrien Béraud | 2385246 | 2023-07-22 01:46:27 -0400 | [diff] [blame] | 1422 | shared->config_->logger->error("[device {}] Cannot initialize ICE session.", req.owner->getLongId()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1423 | dht::ThreadPool::io().run([eraseInfo = std::move(eraseInfo)] { eraseInfo(); }); |
| 1424 | return; |
| 1425 | } |
| 1426 | |
| 1427 | dht::ThreadPool::io().run( |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1428 | [w = std::move(w), winfo = std::move(winfo), req = std::move(req), eraseInfo = std::move(eraseInfo)] { |
| 1429 | if (auto shared = w.lock()) { |
| 1430 | if (!shared->onRequestStartIce(winfo.lock(), req)) |
| 1431 | eraseInfo(); |
| 1432 | } |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1433 | }); |
| 1434 | }; |
| 1435 | |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1436 | ice_config.onNegoDone = [w, wdi, winfo, req, eraseInfo](bool ok) { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1437 | auto shared = w.lock(); |
| 1438 | if (!shared) |
| 1439 | return; |
| 1440 | if (!ok) { |
| 1441 | if (shared->config_->logger) |
Adrien Béraud | 2385246 | 2023-07-22 01:46:27 -0400 | [diff] [blame] | 1442 | shared->config_->logger->error("[device {}] ICE negotiation failed.", req.owner->getLongId()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1443 | dht::ThreadPool::io().run([eraseInfo = std::move(eraseInfo)] { eraseInfo(); }); |
| 1444 | return; |
| 1445 | } |
| 1446 | |
| 1447 | dht::ThreadPool::io().run( |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1448 | [w = std::move(w), wdi = std::move(wdi), winfo = std::move(winfo), req = std::move(req), eraseInfo = std::move(eraseInfo)] { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1449 | if (auto shared = w.lock()) |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1450 | if (!shared->onRequestOnNegoDone(wdi.lock(), winfo.lock(), req)) |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1451 | eraseInfo(); |
| 1452 | }); |
| 1453 | }; |
| 1454 | |
| 1455 | // Negotiate a new ICE socket |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1456 | { |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1457 | std::lock_guard<std::mutex> lk(di->mtx_); |
| 1458 | di->info[req.id] = info; |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1459 | } |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1460 | |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1461 | if (shared->config_->logger) |
Adrien Béraud | 2385246 | 2023-07-22 01:46:27 -0400 | [diff] [blame] | 1462 | shared->config_->logger->debug("[device {}] Accepting connection", deviceId); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1463 | std::unique_lock<std::mutex> lk {info->mutex_}; |
Sébastien Blin | 3408651 | 2023-07-25 09:52:14 -0400 | [diff] [blame] | 1464 | info->ice_ = shared->config_->factory->createUTransport(""); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1465 | if (not info->ice_) { |
| 1466 | if (shared->config_->logger) |
Adrien Béraud | 2385246 | 2023-07-22 01:46:27 -0400 | [diff] [blame] | 1467 | shared->config_->logger->error("[device {}] Cannot initialize ICE session", deviceId); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1468 | eraseInfo(); |
| 1469 | return; |
| 1470 | } |
| 1471 | // We need to detect any shutdown if the ice session is destroyed before going to the TLS session; |
| 1472 | info->ice_->setOnShutdown([eraseInfo]() { |
| 1473 | dht::ThreadPool::io().run([eraseInfo = std::move(eraseInfo)] { eraseInfo(); }); |
| 1474 | }); |
Adrien Béraud | 4cda2d7 | 2023-06-01 15:44:43 -0400 | [diff] [blame] | 1475 | try { |
| 1476 | info->ice_->initIceInstance(ice_config); |
| 1477 | } catch (const std::exception& e) { |
| 1478 | if (shared->config_->logger) |
| 1479 | shared->config_->logger->error("{}", e.what()); |
| 1480 | dht::ThreadPool::io().run([eraseInfo = std::move(eraseInfo)] { eraseInfo(); }); |
| 1481 | } |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1482 | }); |
| 1483 | } |
| 1484 | |
| 1485 | void |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1486 | ConnectionManager::Impl::addNewMultiplexedSocket(const std::weak_ptr<DeviceInfo>& dinfo, const DeviceId& deviceId, const dht::Value::Id& vid, const std::shared_ptr<ConnectionInfo>& info) |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1487 | { |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1488 | info->socket_ = std::make_shared<MultiplexedSocket>(config_->ioContext, deviceId, std::move(info->tls_), config_->logger); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1489 | info->socket_->setOnReady( |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1490 | [w = weak_from_this()](const DeviceId& deviceId, const std::shared_ptr<ChannelSocket>& socket) { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1491 | if (auto sthis = w.lock()) |
| 1492 | if (sthis->connReadyCb_) |
| 1493 | sthis->connReadyCb_(deviceId, socket->name(), socket); |
| 1494 | }); |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1495 | info->socket_->setOnRequest([w = weak_from_this()](const std::shared_ptr<dht::crypto::Certificate>& peer, |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1496 | const uint16_t&, |
| 1497 | const std::string& name) { |
| 1498 | if (auto sthis = w.lock()) |
| 1499 | if (sthis->channelReqCb_) |
| 1500 | return sthis->channelReqCb_(peer, name); |
| 1501 | return false; |
| 1502 | }); |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1503 | info->socket_->onShutdown([dinfo, wi=std::weak_ptr(info), vid]() { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1504 | // Cancel current outgoing connections |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1505 | dht::ThreadPool::io().run([dinfo, wi, vid] { |
| 1506 | std::set<dht::Value::Id> ids; |
| 1507 | if (auto info = wi.lock()) { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1508 | std::lock_guard<std::mutex> lk(info->mutex_); |
| 1509 | if (info->socket_) { |
| 1510 | ids = std::move(info->cbIds_); |
| 1511 | info->socket_->shutdown(); |
| 1512 | } |
| 1513 | } |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1514 | if (auto deviceInfo = dinfo.lock()) { |
| 1515 | std::shared_ptr<ConnectionInfo> info; |
| 1516 | std::vector<PendingCb> ops; |
| 1517 | std::unique_lock<std::mutex> lk(deviceInfo->mtx_); |
| 1518 | auto it = deviceInfo->info.find(vid); |
| 1519 | if (it != deviceInfo->info.end()) { |
| 1520 | info = std::move(it->second); |
| 1521 | deviceInfo->info.erase(it); |
| 1522 | } |
| 1523 | for (const auto& cbId : ids) { |
| 1524 | auto po = deviceInfo->extractPendingOperations(cbId, nullptr); |
| 1525 | ops.insert(ops.end(), po.begin(), po.end()); |
| 1526 | } |
| 1527 | lk.unlock(); |
| 1528 | for (auto& op : ops) |
| 1529 | op.cb(nullptr, deviceInfo->deviceId); |
| 1530 | } |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1531 | }); |
| 1532 | }); |
| 1533 | } |
| 1534 | |
| 1535 | const std::shared_future<tls::DhParams> |
| 1536 | ConnectionManager::Impl::dhParams() const |
| 1537 | { |
| 1538 | return dht::ThreadPool::computation().get<tls::DhParams>( |
Adrien Béraud | 2a4e73d | 2023-08-27 12:53:55 -0400 | [diff] [blame] | 1539 | std::bind(tls::DhParams::loadDhParams, config_->cachePath / "dhParams")); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1540 | } |
| 1541 | |
| 1542 | template<typename ID = dht::Value::Id> |
| 1543 | std::set<ID, std::less<>> |
Adrien Béraud | 1299a0d | 2023-09-19 15:03:28 -0400 | [diff] [blame] | 1544 | loadIdList(const std::filesystem::path& path) |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1545 | { |
| 1546 | std::set<ID, std::less<>> ids; |
Adrien Béraud | 1299a0d | 2023-09-19 15:03:28 -0400 | [diff] [blame] | 1547 | std::ifstream file(path); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1548 | if (!file.is_open()) { |
| 1549 | //JAMI_DBG("Could not load %s", path.c_str()); |
| 1550 | return ids; |
| 1551 | } |
| 1552 | std::string line; |
| 1553 | while (std::getline(file, line)) { |
| 1554 | if constexpr (std::is_same<ID, std::string>::value) { |
| 1555 | ids.emplace(std::move(line)); |
| 1556 | } else if constexpr (std::is_integral<ID>::value) { |
| 1557 | ID vid; |
| 1558 | if (auto [p, ec] = std::from_chars(line.data(), line.data() + line.size(), vid, 16); |
| 1559 | ec == std::errc()) { |
| 1560 | ids.emplace(vid); |
| 1561 | } |
| 1562 | } |
| 1563 | } |
| 1564 | return ids; |
| 1565 | } |
| 1566 | |
| 1567 | template<typename List = std::set<dht::Value::Id>> |
| 1568 | void |
Adrien Béraud | 2a4e73d | 2023-08-27 12:53:55 -0400 | [diff] [blame] | 1569 | saveIdList(const std::filesystem::path& path, const List& ids) |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1570 | { |
Adrien Béraud | 1299a0d | 2023-09-19 15:03:28 -0400 | [diff] [blame] | 1571 | std::ofstream file(path, std::ios::trunc | std::ios::binary); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1572 | if (!file.is_open()) { |
| 1573 | //JAMI_ERR("Could not save to %s", path.c_str()); |
| 1574 | return; |
| 1575 | } |
| 1576 | for (auto& c : ids) |
| 1577 | file << std::hex << c << "\n"; |
| 1578 | } |
| 1579 | |
| 1580 | void |
| 1581 | ConnectionManager::Impl::loadTreatedMessages() |
| 1582 | { |
| 1583 | std::lock_guard<std::mutex> lock(messageMutex_); |
Adrien Béraud | 2a4e73d | 2023-08-27 12:53:55 -0400 | [diff] [blame] | 1584 | auto path = config_->cachePath / "treatedMessages"; |
Aline Gondim Santos | 406c0f4 | 2023-09-13 12:10:23 -0300 | [diff] [blame] | 1585 | treatedMessages_ = loadIdList<std::string>(path.string()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1586 | if (treatedMessages_.empty()) { |
Aline Gondim Santos | 406c0f4 | 2023-09-13 12:10:23 -0300 | [diff] [blame] | 1587 | auto messages = loadIdList(path.string()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1588 | for (const auto& m : messages) |
| 1589 | treatedMessages_.emplace(to_hex_string(m)); |
| 1590 | } |
| 1591 | } |
| 1592 | |
| 1593 | void |
| 1594 | ConnectionManager::Impl::saveTreatedMessages() const |
| 1595 | { |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1596 | dht::ThreadPool::io().run([w = weak_from_this()]() { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1597 | if (auto sthis = w.lock()) { |
| 1598 | auto& this_ = *sthis; |
| 1599 | std::lock_guard<std::mutex> lock(this_.messageMutex_); |
| 1600 | fileutils::check_dir(this_.config_->cachePath.c_str()); |
Adrien Béraud | 2a4e73d | 2023-08-27 12:53:55 -0400 | [diff] [blame] | 1601 | saveIdList<decltype(this_.treatedMessages_)>(this_.config_->cachePath / "treatedMessages", |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1602 | this_.treatedMessages_); |
| 1603 | } |
| 1604 | }); |
| 1605 | } |
| 1606 | |
| 1607 | bool |
| 1608 | ConnectionManager::Impl::isMessageTreated(std::string_view id) |
| 1609 | { |
| 1610 | std::lock_guard<std::mutex> lock(messageMutex_); |
| 1611 | auto res = treatedMessages_.emplace(id); |
| 1612 | if (res.second) { |
| 1613 | saveTreatedMessages(); |
| 1614 | return false; |
| 1615 | } |
| 1616 | return true; |
| 1617 | } |
| 1618 | |
| 1619 | /** |
| 1620 | * returns whether or not UPnP is enabled and active_ |
| 1621 | * ie: if it is able to make port mappings |
| 1622 | */ |
| 1623 | bool |
| 1624 | ConnectionManager::Impl::getUPnPActive() const |
| 1625 | { |
| 1626 | return config_->getUPnPActive(); |
| 1627 | } |
| 1628 | |
| 1629 | IpAddr |
| 1630 | ConnectionManager::Impl::getPublishedIpAddress(uint16_t family) const |
| 1631 | { |
| 1632 | if (family == AF_INET) |
| 1633 | return publishedIp_[0]; |
| 1634 | if (family == AF_INET6) |
| 1635 | return publishedIp_[1]; |
| 1636 | |
| 1637 | assert(family == AF_UNSPEC); |
| 1638 | |
| 1639 | // If family is not set, prefere IPv4 if available. It's more |
| 1640 | // likely to succeed behind NAT. |
| 1641 | if (publishedIp_[0]) |
| 1642 | return publishedIp_[0]; |
| 1643 | if (publishedIp_[1]) |
| 1644 | return publishedIp_[1]; |
| 1645 | return {}; |
| 1646 | } |
| 1647 | |
| 1648 | void |
| 1649 | ConnectionManager::Impl::setPublishedAddress(const IpAddr& ip_addr) |
| 1650 | { |
| 1651 | if (ip_addr.getFamily() == AF_INET) { |
| 1652 | publishedIp_[0] = ip_addr; |
| 1653 | } else { |
| 1654 | publishedIp_[1] = ip_addr; |
| 1655 | } |
| 1656 | } |
| 1657 | |
| 1658 | void |
| 1659 | ConnectionManager::Impl::storeActiveIpAddress(std::function<void()>&& cb) |
| 1660 | { |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1661 | dht()->getPublicAddress([w=weak_from_this(), cb = std::move(cb)](std::vector<dht::SockAddr>&& results) { |
Sébastien Blin | b650437 | 2023-10-12 10:35:35 -0400 | [diff] [blame] | 1662 | auto shared = w.lock(); |
| 1663 | if (!shared) |
| 1664 | return; |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1665 | bool hasIpv4 {false}, hasIpv6 {false}; |
| 1666 | for (auto& result : results) { |
| 1667 | auto family = result.getFamily(); |
| 1668 | if (family == AF_INET) { |
| 1669 | if (not hasIpv4) { |
| 1670 | hasIpv4 = true; |
Sébastien Blin | b650437 | 2023-10-12 10:35:35 -0400 | [diff] [blame] | 1671 | if (shared->config_->logger) |
| 1672 | shared->config_->logger->debug("Store DHT public IPv4 address: {}", result); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1673 | //JAMI_DBG("Store DHT public IPv4 address : %s", result.toString().c_str()); |
Sébastien Blin | b650437 | 2023-10-12 10:35:35 -0400 | [diff] [blame] | 1674 | shared->setPublishedAddress(*result.get()); |
| 1675 | if (shared->config_->upnpCtrl) { |
| 1676 | shared->config_->upnpCtrl->setPublicAddress(*result.get()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1677 | } |
| 1678 | } |
| 1679 | } else if (family == AF_INET6) { |
| 1680 | if (not hasIpv6) { |
| 1681 | hasIpv6 = true; |
Sébastien Blin | b650437 | 2023-10-12 10:35:35 -0400 | [diff] [blame] | 1682 | if (shared->config_->logger) |
| 1683 | shared->config_->logger->debug("Store DHT public IPv6 address: {}", result); |
| 1684 | shared->setPublishedAddress(*result.get()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1685 | } |
| 1686 | } |
| 1687 | if (hasIpv4 and hasIpv6) |
| 1688 | break; |
| 1689 | } |
| 1690 | if (cb) |
| 1691 | cb(); |
| 1692 | }); |
| 1693 | } |
| 1694 | |
| 1695 | void |
| 1696 | ConnectionManager::Impl::getIceOptions(std::function<void(IceTransportOptions&&)> cb) noexcept |
| 1697 | { |
| 1698 | storeActiveIpAddress([this, cb = std::move(cb)] { |
| 1699 | IceTransportOptions opts = ConnectionManager::Impl::getIceOptions(); |
| 1700 | auto publishedAddr = getPublishedIpAddress(); |
| 1701 | |
| 1702 | if (publishedAddr) { |
| 1703 | auto interfaceAddr = ip_utils::getInterfaceAddr(getLocalInterface(), |
| 1704 | publishedAddr.getFamily()); |
| 1705 | if (interfaceAddr) { |
| 1706 | opts.accountLocalAddr = interfaceAddr; |
| 1707 | opts.accountPublicAddr = publishedAddr; |
| 1708 | } |
| 1709 | } |
| 1710 | if (cb) |
| 1711 | cb(std::move(opts)); |
| 1712 | }); |
| 1713 | } |
| 1714 | |
| 1715 | IceTransportOptions |
| 1716 | ConnectionManager::Impl::getIceOptions() const noexcept |
| 1717 | { |
| 1718 | IceTransportOptions opts; |
Sébastien Blin | 3408651 | 2023-07-25 09:52:14 -0400 | [diff] [blame] | 1719 | opts.factory = config_->factory; |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1720 | opts.upnpEnable = getUPnPActive(); |
Adrien Béraud | 7b869d9 | 2023-08-21 09:02:35 -0400 | [diff] [blame] | 1721 | opts.upnpContext = config_->upnpCtrl ? config_->upnpCtrl->upnpContext() : nullptr; |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1722 | |
| 1723 | if (config_->stunEnabled) |
| 1724 | opts.stunServers.emplace_back(StunServerInfo().setUri(config_->stunServer)); |
| 1725 | if (config_->turnEnabled) { |
Sébastien Blin | 84bf418 | 2023-07-21 14:18:39 -0400 | [diff] [blame] | 1726 | if (config_->turnCache) { |
| 1727 | auto turnAddr = config_->turnCache->getResolvedTurn(); |
| 1728 | if (turnAddr != std::nullopt) { |
| 1729 | opts.turnServers.emplace_back(TurnServerInfo() |
| 1730 | .setUri(turnAddr->toString()) |
| 1731 | .setUsername(config_->turnServerUserName) |
| 1732 | .setPassword(config_->turnServerPwd) |
| 1733 | .setRealm(config_->turnServerRealm)); |
| 1734 | } |
| 1735 | } else { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1736 | opts.turnServers.emplace_back(TurnServerInfo() |
Sébastien Blin | 84bf418 | 2023-07-21 14:18:39 -0400 | [diff] [blame] | 1737 | .setUri(config_->turnServer) |
| 1738 | .setUsername(config_->turnServerUserName) |
| 1739 | .setPassword(config_->turnServerPwd) |
| 1740 | .setRealm(config_->turnServerRealm)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1741 | } |
| 1742 | // NOTE: first test with ipv6 turn was not concluant and resulted in multiple |
| 1743 | // co issues. So this needs some debug. for now just disable |
| 1744 | // if (cacheTurnV6 && *cacheTurnV6) { |
| 1745 | // opts.turnServers.emplace_back(TurnServerInfo() |
| 1746 | // .setUri(cacheTurnV6->toString(true)) |
| 1747 | // .setUsername(turnServerUserName_) |
| 1748 | // .setPassword(turnServerPwd_) |
| 1749 | // .setRealm(turnServerRealm_)); |
| 1750 | //} |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1751 | } |
| 1752 | return opts; |
| 1753 | } |
| 1754 | |
| 1755 | bool |
| 1756 | ConnectionManager::Impl::foundPeerDevice(const std::shared_ptr<dht::crypto::Certificate>& crt, |
| 1757 | dht::InfoHash& account_id, |
| 1758 | const std::shared_ptr<Logger>& logger) |
| 1759 | { |
| 1760 | if (not crt) |
| 1761 | return false; |
| 1762 | |
| 1763 | auto top_issuer = crt; |
| 1764 | while (top_issuer->issuer) |
| 1765 | top_issuer = top_issuer->issuer; |
| 1766 | |
| 1767 | // Device certificate can't be self-signed |
Adrien Béraud | c631a83 | 2023-07-26 22:19:00 -0400 | [diff] [blame] | 1768 | if (top_issuer == crt) { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1769 | if (logger) |
Adrien Béraud | 8b831a8 | 2023-07-21 14:13:06 -0400 | [diff] [blame] | 1770 | logger->warn("Found invalid (self-signed) peer device: {}", crt->getLongId()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1771 | return false; |
Adrien Béraud | c631a83 | 2023-07-26 22:19:00 -0400 | [diff] [blame] | 1772 | } |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1773 | |
| 1774 | // Check peer certificate chain |
| 1775 | // Trust store with top issuer as the only CA |
| 1776 | dht::crypto::TrustList peer_trust; |
| 1777 | peer_trust.add(*top_issuer); |
| 1778 | if (not peer_trust.verify(*crt)) { |
| 1779 | if (logger) |
| 1780 | logger->warn("Found invalid peer device: {}", crt->getLongId()); |
| 1781 | return false; |
| 1782 | } |
| 1783 | |
| 1784 | // Check cached OCSP response |
| 1785 | if (crt->ocspResponse and crt->ocspResponse->getCertificateStatus() != GNUTLS_OCSP_CERT_GOOD) { |
| 1786 | if (logger) |
Adrien Béraud | 8b831a8 | 2023-07-21 14:13:06 -0400 | [diff] [blame] | 1787 | logger->error("Certificate {} is disabled by cached OCSP response", crt->getLongId()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1788 | return false; |
| 1789 | } |
| 1790 | |
Adrien Béraud | c631a83 | 2023-07-26 22:19:00 -0400 | [diff] [blame] | 1791 | account_id = crt->issuer->getId(); |
| 1792 | if (logger) |
| 1793 | logger->warn("Found peer device: {} account:{} CA:{}", |
| 1794 | crt->getLongId(), |
| 1795 | account_id, |
| 1796 | top_issuer->getId()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1797 | return true; |
| 1798 | } |
| 1799 | |
| 1800 | bool |
| 1801 | ConnectionManager::Impl::findCertificate( |
| 1802 | const dht::PkId& id, std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb) |
| 1803 | { |
| 1804 | if (auto cert = certStore().getCertificate(id.toString())) { |
| 1805 | if (cb) |
| 1806 | cb(cert); |
| 1807 | } else if (cb) |
| 1808 | cb(nullptr); |
| 1809 | return true; |
| 1810 | } |
| 1811 | |
Sébastien Blin | 3408651 | 2023-07-25 09:52:14 -0400 | [diff] [blame] | 1812 | bool |
| 1813 | ConnectionManager::Impl::findCertificate(const dht::InfoHash& h, |
| 1814 | std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb) |
| 1815 | { |
| 1816 | if (auto cert = certStore().getCertificate(h.toString())) { |
| 1817 | if (cb) |
| 1818 | cb(cert); |
| 1819 | } else { |
| 1820 | dht()->findCertificate(h, |
| 1821 | [cb = std::move(cb), this]( |
| 1822 | const std::shared_ptr<dht::crypto::Certificate>& crt) { |
| 1823 | if (crt) |
| 1824 | certStore().pinCertificate(crt); |
| 1825 | if (cb) |
| 1826 | cb(crt); |
| 1827 | }); |
| 1828 | } |
| 1829 | return true; |
| 1830 | } |
| 1831 | |
Amna | 81221ad | 2023-09-14 17:33:26 -0400 | [diff] [blame] | 1832 | std::shared_ptr<ConnectionManager::Config> |
| 1833 | buildDefaultConfig(dht::crypto::Identity id){ |
| 1834 | auto conf = std::make_shared<ConnectionManager::Config>(); |
| 1835 | conf->id = std::move(id); |
| 1836 | return conf; |
| 1837 | } |
| 1838 | |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1839 | ConnectionManager::ConnectionManager(std::shared_ptr<ConnectionManager::Config> config_) |
| 1840 | : pimpl_ {std::make_shared<Impl>(config_)} |
| 1841 | {} |
| 1842 | |
Amna | 81221ad | 2023-09-14 17:33:26 -0400 | [diff] [blame] | 1843 | ConnectionManager::ConnectionManager(dht::crypto::Identity id) |
| 1844 | : ConnectionManager {buildDefaultConfig(id)} |
| 1845 | {} |
| 1846 | |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1847 | ConnectionManager::~ConnectionManager() |
| 1848 | { |
| 1849 | if (pimpl_) |
| 1850 | pimpl_->shutdown(); |
| 1851 | } |
| 1852 | |
| 1853 | void |
| 1854 | ConnectionManager::connectDevice(const DeviceId& deviceId, |
| 1855 | const std::string& name, |
| 1856 | ConnectCallback 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 | void |
Amna | 0cf544d | 2023-07-25 14:25:09 -0400 | [diff] [blame] | 1865 | ConnectionManager::connectDevice(const dht::InfoHash& deviceId, |
| 1866 | const std::string& name, |
| 1867 | ConnectCallbackLegacy cb, |
| 1868 | bool noNewSocket, |
| 1869 | bool forceNewSocket, |
| 1870 | const std::string& connType) |
| 1871 | { |
| 1872 | pimpl_->connectDevice(deviceId, name, std::move(cb), noNewSocket, forceNewSocket, connType); |
| 1873 | } |
| 1874 | |
| 1875 | |
| 1876 | void |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1877 | ConnectionManager::connectDevice(const std::shared_ptr<dht::crypto::Certificate>& cert, |
| 1878 | const std::string& name, |
| 1879 | ConnectCallback cb, |
| 1880 | bool noNewSocket, |
| 1881 | bool forceNewSocket, |
| 1882 | const std::string& connType) |
| 1883 | { |
| 1884 | pimpl_->connectDevice(cert, name, std::move(cb), noNewSocket, forceNewSocket, connType); |
| 1885 | } |
| 1886 | |
| 1887 | bool |
| 1888 | ConnectionManager::isConnecting(const DeviceId& deviceId, const std::string& name) const |
| 1889 | { |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1890 | if (auto dinfo = pimpl_->infos_.getDeviceInfo(deviceId)) { |
| 1891 | std::unique_lock<std::mutex> lk {dinfo->mtx_}; |
Adrien Béraud | b941e92 | 2023-10-16 12:56:14 -0400 | [diff] [blame] | 1892 | return dinfo->isConnecting(name); |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1893 | } |
| 1894 | return false; |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1895 | } |
| 1896 | |
Sébastien Blin | d0c92c7 | 2023-12-07 15:27:51 -0500 | [diff] [blame] | 1897 | bool |
| 1898 | ConnectionManager::isConnected(const DeviceId& deviceId) const |
| 1899 | { |
| 1900 | if (auto dinfo = pimpl_->infos_.getDeviceInfo(deviceId)) { |
| 1901 | std::unique_lock<std::mutex> lk {dinfo->mtx_}; |
| 1902 | return dinfo->getConnectedInfo() != nullptr; |
| 1903 | } |
| 1904 | return false; |
| 1905 | } |
| 1906 | |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1907 | void |
| 1908 | ConnectionManager::closeConnectionsWith(const std::string& peerUri) |
| 1909 | { |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1910 | std::vector<std::shared_ptr<DeviceInfo>> dInfos; |
| 1911 | for (const auto& dinfo: pimpl_->infos_.getDeviceInfos()) { |
| 1912 | std::unique_lock<std::mutex> lk(dinfo->mtx_); |
| 1913 | bool isPeer = false; |
| 1914 | for (auto const& [id, cinfo]: dinfo->info) { |
| 1915 | std::lock_guard<std::mutex> lkv {cinfo->mutex_}; |
| 1916 | auto tls = cinfo->tls_ ? cinfo->tls_.get() : (cinfo->socket_ ? cinfo->socket_->endpoint() : nullptr); |
Adrien Béraud | afa8e28 | 2023-09-24 12:53:20 -0400 | [diff] [blame] | 1917 | auto cert = tls ? tls->peerCertificate() : nullptr; |
| 1918 | if (not cert) |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1919 | cert = pimpl_->certStore().getCertificate(dinfo->deviceId.toString()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1920 | if (cert && cert->issuer && peerUri == cert->issuer->getId().toString()) { |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1921 | isPeer = true; |
| 1922 | break; |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1923 | } |
| 1924 | } |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1925 | lk.unlock(); |
| 1926 | if (isPeer) { |
| 1927 | dInfos.emplace_back(std::move(dinfo)); |
| 1928 | } |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1929 | } |
| 1930 | // Stop connections to all peers devices |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1931 | for (const auto& dinfo : dInfos) { |
| 1932 | std::unique_lock<std::mutex> lk {dinfo->mtx_}; |
| 1933 | auto unused = dinfo->extractUnusedConnections(); |
| 1934 | auto pending = dinfo->extractPendingOperations(0, nullptr); |
| 1935 | pimpl_->infos_.removeDeviceInfo(dinfo->deviceId); |
| 1936 | lk.unlock(); |
| 1937 | for (auto& op : unused) |
| 1938 | op->shutdown(); |
| 1939 | for (auto& op : pending) |
| 1940 | op.cb(nullptr, dinfo->deviceId); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1941 | } |
| 1942 | } |
| 1943 | |
| 1944 | void |
| 1945 | ConnectionManager::onDhtConnected(const dht::crypto::PublicKey& devicePk) |
| 1946 | { |
| 1947 | pimpl_->onDhtConnected(devicePk); |
| 1948 | } |
| 1949 | |
| 1950 | void |
| 1951 | ConnectionManager::onICERequest(onICERequestCallback&& cb) |
| 1952 | { |
| 1953 | pimpl_->iceReqCb_ = std::move(cb); |
| 1954 | } |
| 1955 | |
| 1956 | void |
| 1957 | ConnectionManager::onChannelRequest(ChannelRequestCallback&& cb) |
| 1958 | { |
| 1959 | pimpl_->channelReqCb_ = std::move(cb); |
| 1960 | } |
| 1961 | |
| 1962 | void |
| 1963 | ConnectionManager::onConnectionReady(ConnectionReadyCallback&& cb) |
| 1964 | { |
| 1965 | pimpl_->connReadyCb_ = std::move(cb); |
| 1966 | } |
| 1967 | |
| 1968 | void |
| 1969 | ConnectionManager::oniOSConnected(iOSConnectedCallback&& cb) |
| 1970 | { |
| 1971 | pimpl_->iOSConnectedCb_ = std::move(cb); |
| 1972 | } |
| 1973 | |
| 1974 | std::size_t |
| 1975 | ConnectionManager::activeSockets() const |
| 1976 | { |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1977 | return pimpl_->infos_.getConnectedInfos().size(); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1978 | } |
| 1979 | |
| 1980 | void |
| 1981 | ConnectionManager::monitor() const |
| 1982 | { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1983 | auto logger = pimpl_->config_->logger; |
| 1984 | if (!logger) |
| 1985 | return; |
| 1986 | logger->debug("ConnectionManager current status:"); |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1987 | for (const auto& ci : pimpl_->infos_.getConnectedInfos()) { |
| 1988 | std::lock_guard<std::mutex> lk(ci->mutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1989 | if (ci->socket_) |
| 1990 | ci->socket_->monitor(); |
| 1991 | } |
| 1992 | logger->debug("ConnectionManager end status."); |
| 1993 | } |
| 1994 | |
| 1995 | void |
| 1996 | ConnectionManager::connectivityChanged() |
| 1997 | { |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 1998 | for (const auto& ci : pimpl_->infos_.getConnectedInfos()) { |
| 1999 | std::lock_guard<std::mutex> lk(ci->mutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 2000 | if (ci->socket_) |
Adrien Béraud | 51a5471 | 2023-10-17 21:24:30 -0400 | [diff] [blame] | 2001 | dht::ThreadPool::io().run([s = ci->socket_] { s->sendBeacon(); }); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 2002 | } |
| 2003 | } |
| 2004 | |
| 2005 | void |
| 2006 | ConnectionManager::getIceOptions(std::function<void(IceTransportOptions&&)> cb) noexcept |
| 2007 | { |
| 2008 | return pimpl_->getIceOptions(std::move(cb)); |
| 2009 | } |
| 2010 | |
| 2011 | IceTransportOptions |
| 2012 | ConnectionManager::getIceOptions() const noexcept |
| 2013 | { |
| 2014 | return pimpl_->getIceOptions(); |
| 2015 | } |
| 2016 | |
| 2017 | IpAddr |
| 2018 | ConnectionManager::getPublishedIpAddress(uint16_t family) const |
| 2019 | { |
| 2020 | return pimpl_->getPublishedIpAddress(family); |
| 2021 | } |
| 2022 | |
| 2023 | void |
| 2024 | ConnectionManager::setPublishedAddress(const IpAddr& ip_addr) |
| 2025 | { |
| 2026 | return pimpl_->setPublishedAddress(ip_addr); |
| 2027 | } |
| 2028 | |
| 2029 | void |
| 2030 | ConnectionManager::storeActiveIpAddress(std::function<void()>&& cb) |
| 2031 | { |
| 2032 | return pimpl_->storeActiveIpAddress(std::move(cb)); |
| 2033 | } |
| 2034 | |
| 2035 | std::shared_ptr<ConnectionManager::Config> |
| 2036 | ConnectionManager::getConfig() |
| 2037 | { |
| 2038 | return pimpl_->config_; |
| 2039 | } |
| 2040 | |
Amna | 31791e5 | 2023-08-03 12:40:57 -0400 | [diff] [blame] | 2041 | std::vector<std::map<std::string, std::string>> |
| 2042 | ConnectionManager::getConnectionList(const DeviceId& device) const |
| 2043 | { |
| 2044 | std::vector<std::map<std::string, std::string>> connectionsList; |
Amna | 31791e5 | 2023-08-03 12:40:57 -0400 | [diff] [blame] | 2045 | if (device) { |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 2046 | if (auto deviceInfo = pimpl_->infos_.getDeviceInfo(device)) { |
| 2047 | connectionsList = deviceInfo->getConnectionList(pimpl_->certStore()); |
Amna | 31791e5 | 2023-08-03 12:40:57 -0400 | [diff] [blame] | 2048 | } |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 2049 | } else { |
| 2050 | for (const auto& deviceInfo : pimpl_->infos_.getDeviceInfos()) { |
| 2051 | auto cl = deviceInfo->getConnectionList(pimpl_->certStore()); |
| 2052 | connectionsList.insert(connectionsList.end(), std::make_move_iterator(cl.begin()), std::make_move_iterator(cl.end())); |
Amna | 31791e5 | 2023-08-03 12:40:57 -0400 | [diff] [blame] | 2053 | } |
| 2054 | } |
| 2055 | return connectionsList; |
| 2056 | } |
| 2057 | |
| 2058 | std::vector<std::map<std::string, std::string>> |
| 2059 | ConnectionManager::getChannelList(const std::string& connectionId) const |
| 2060 | { |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 2061 | auto [deviceId, valueId] = parseCallbackId(connectionId); |
| 2062 | if (auto info = pimpl_->infos_.getInfo(deviceId, valueId)) { |
| 2063 | std::lock_guard<std::mutex> lk(info->mutex_); |
| 2064 | if (info->socket_) |
| 2065 | return info->socket_->getChannelList(); |
Amna | 31791e5 | 2023-08-03 12:40:57 -0400 | [diff] [blame] | 2066 | } |
Adrien Béraud | 75754b2 | 2023-10-17 09:16:06 -0400 | [diff] [blame] | 2067 | return {}; |
Amna | 31791e5 | 2023-08-03 12:40:57 -0400 | [diff] [blame] | 2068 | } |
| 2069 | |
Sébastien Blin | 464bdff | 2023-07-19 08:02:53 -0400 | [diff] [blame] | 2070 | } // namespace dhtnet |