Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2004-2023 Savoir-faire Linux Inc. |
| 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 |
Adrien Béraud | cb75362 | 2023-07-17 22:32:49 -0400 | [diff] [blame] | 15 | * along with this program. If not, see <https://www.gnu.org/licenses/>. |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 16 | */ |
Morteza Namvar | 5f63952 | 2023-07-04 17:08:58 -0400 | [diff] [blame] | 17 | #include "upnp/upnp_context.h" |
Adrien Béraud | 25c30c4 | 2023-07-05 13:46:54 -0400 | [diff] [blame] | 18 | #include "protocol/upnp_protocol.h" |
| 19 | |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 20 | #if HAVE_LIBNATPMP |
| 21 | #include "protocol/natpmp/nat_pmp.h" |
| 22 | #endif |
| 23 | #if HAVE_LIBUPNP |
| 24 | #include "protocol/pupnp/pupnp.h" |
| 25 | #endif |
Amna | 7cd813c | 2023-10-02 18:15:47 -0400 | [diff] [blame] | 26 | #include <asio.hpp> |
Morteza Namvar | 5f63952 | 2023-07-04 17:08:58 -0400 | [diff] [blame] | 27 | #include <asio/steady_timer.hpp> |
Adrien Béraud | 9d35096 | 2023-07-13 15:36:32 -0400 | [diff] [blame] | 28 | #if __has_include(<fmt/std.h>) |
Adrien Béraud | 25c30c4 | 2023-07-05 13:46:54 -0400 | [diff] [blame] | 29 | #include <fmt/std.h> |
Adrien Béraud | 9d35096 | 2023-07-13 15:36:32 -0400 | [diff] [blame] | 30 | #else |
| 31 | #include <fmt/ostream.h> |
| 32 | #endif |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 33 | |
Adrien Béraud | 1ae60aa | 2023-07-07 09:55:09 -0400 | [diff] [blame] | 34 | namespace dhtnet { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 35 | namespace upnp { |
| 36 | |
| 37 | constexpr static auto MAP_UPDATE_INTERVAL = std::chrono::seconds(30); |
| 38 | constexpr static int MAX_REQUEST_RETRIES = 20; |
| 39 | constexpr static int MAX_REQUEST_REMOVE_COUNT = 5; |
| 40 | |
| 41 | constexpr static uint16_t UPNP_TCP_PORT_MIN {10000}; |
| 42 | constexpr static uint16_t UPNP_TCP_PORT_MAX {UPNP_TCP_PORT_MIN + 5000}; |
| 43 | constexpr static uint16_t UPNP_UDP_PORT_MIN {20000}; |
| 44 | constexpr static uint16_t UPNP_UDP_PORT_MAX {UPNP_UDP_PORT_MIN + 5000}; |
| 45 | |
Sébastien Blin | 55abf07 | 2023-07-19 10:21:21 -0400 | [diff] [blame] | 46 | UPnPContext::UPnPContext(const std::shared_ptr<asio::io_context>& ioContext, const std::shared_ptr<dht::log::Logger>& logger) |
Adrien Béraud | c36965c | 2023-08-17 21:50:27 -0400 | [diff] [blame] | 47 | : ctx(createIoContext(ioContext, logger)) |
Adrien Béraud | 91fd4b6 | 2023-08-29 20:50:01 -0400 | [diff] [blame] | 48 | , logger_(logger) |
Adrien Béraud | 95219ef | 2023-08-17 21:55:37 -0400 | [diff] [blame] | 49 | , mappingListUpdateTimer_(*ctx) |
| 50 | , connectivityChangedTimer_(*ctx) |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 51 | { |
Adrien Beraud | 3bd61c9 | 2023-08-17 16:57:37 -0400 | [diff] [blame] | 52 | if (logger_) logger_->debug("Creating UPnPContext instance [{}]", fmt::ptr(this)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 53 | |
| 54 | // Set port ranges |
| 55 | portRange_.emplace(PortType::TCP, std::make_pair(UPNP_TCP_PORT_MIN, UPNP_TCP_PORT_MAX)); |
| 56 | portRange_.emplace(PortType::UDP, std::make_pair(UPNP_UDP_PORT_MIN, UPNP_UDP_PORT_MAX)); |
| 57 | |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 58 | ctx->post([this] { init(); }); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 59 | } |
| 60 | |
Adrien Béraud | b04fbd7 | 2023-08-17 19:56:11 -0400 | [diff] [blame] | 61 | std::shared_ptr<asio::io_context> |
| 62 | UPnPContext::createIoContext(const std::shared_ptr<asio::io_context>& ctx, const std::shared_ptr<dht::log::Logger>& logger) { |
| 63 | if (ctx) { |
| 64 | return ctx; |
| 65 | } else { |
| 66 | if (logger) logger->debug("UPnPContext: starting dedicated io_context thread"); |
| 67 | auto ioCtx = std::make_shared<asio::io_context>(); |
| 68 | ioContextRunner_ = std::make_unique<std::thread>([ioCtx, l=logger]() { |
| 69 | try { |
| 70 | auto work = asio::make_work_guard(*ioCtx); |
| 71 | ioCtx->run(); |
| 72 | } catch (const std::exception& ex) { |
| 73 | if (l) l->error("Unexpected io_context thread exception: {}", ex.what()); |
| 74 | } |
| 75 | }); |
| 76 | return ioCtx; |
| 77 | } |
| 78 | } |
| 79 | |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 80 | void |
| 81 | UPnPContext::shutdown(std::condition_variable& cv) |
| 82 | { |
Adrien Beraud | 3bd61c9 | 2023-08-17 16:57:37 -0400 | [diff] [blame] | 83 | if (logger_) logger_->debug("Shutdown UPnPContext instance [{}]", fmt::ptr(this)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 84 | |
| 85 | stopUpnp(true); |
| 86 | |
| 87 | for (auto const& [_, proto] : protocolList_) { |
| 88 | proto->terminate(); |
| 89 | } |
| 90 | |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 91 | std::lock_guard lock(mappingMutex_); |
Adrien Béraud | 91fd4b6 | 2023-08-29 20:50:01 -0400 | [diff] [blame] | 92 | mappingList_->clear(); |
| 93 | mappingListUpdateTimer_.cancel(); |
| 94 | controllerList_.clear(); |
| 95 | protocolList_.clear(); |
| 96 | shutdownComplete_ = true; |
François-Simon Fauteux-Chapleau | 808db4f | 2024-04-19 11:39:47 -0400 | [diff] [blame] | 97 | if (shutdownTimedOut_) { |
| 98 | // If we timed out in shutdown(), then calling notify_one is not necessary, |
| 99 | // and doing so anyway can cause bugs, see: |
| 100 | // https://git.jami.net/savoirfairelinux/dhtnet/-/issues/28 |
| 101 | return; |
| 102 | } |
Adrien Béraud | 91fd4b6 | 2023-08-29 20:50:01 -0400 | [diff] [blame] | 103 | cv.notify_one(); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 104 | } |
| 105 | |
| 106 | void |
| 107 | UPnPContext::shutdown() |
| 108 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 109 | std::unique_lock lk(mappingMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 110 | std::condition_variable cv; |
| 111 | |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 112 | ctx->post([&, this] { shutdown(cv); }); |
Sébastien Blin | 91cda3c | 2024-01-10 16:21:18 -0500 | [diff] [blame] | 113 | |
Adrien Beraud | 3bd61c9 | 2023-08-17 16:57:37 -0400 | [diff] [blame] | 114 | if (logger_) logger_->debug("Waiting for shutdown ..."); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 115 | |
| 116 | if (cv.wait_for(lk, std::chrono::seconds(30), [this] { return shutdownComplete_; })) { |
Adrien Beraud | 3bd61c9 | 2023-08-17 16:57:37 -0400 | [diff] [blame] | 117 | if (logger_) logger_->debug("Shutdown completed"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 118 | } else { |
François-Simon Fauteux-Chapleau | 808db4f | 2024-04-19 11:39:47 -0400 | [diff] [blame] | 119 | if (logger_) logger_->error("Shutdown timed out"); |
| 120 | shutdownTimedOut_ = true; |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 121 | } |
François-Simon Fauteux-Chapleau | 648907c | 2024-02-06 15:16:48 -0500 | [diff] [blame] | 122 | // NOTE: It's important to unlock mappingMutex_ here, otherwise we get a |
| 123 | // deadlock when the call to cv.wait_for() above times out before we return |
| 124 | // from proto->terminate() in shutdown(cv). |
| 125 | lk.unlock(); |
Adrien Béraud | 91fd4b6 | 2023-08-29 20:50:01 -0400 | [diff] [blame] | 126 | |
| 127 | if (ioContextRunner_) { |
Sébastien Blin | 91cda3c | 2024-01-10 16:21:18 -0500 | [diff] [blame] | 128 | if (logger_) logger_->debug("UPnPContext: stopping io_context thread {}", fmt::ptr(this)); |
Adrien Béraud | 91fd4b6 | 2023-08-29 20:50:01 -0400 | [diff] [blame] | 129 | ctx->stop(); |
| 130 | ioContextRunner_->join(); |
| 131 | ioContextRunner_.reset(); |
Sébastien Blin | 91cda3c | 2024-01-10 16:21:18 -0500 | [diff] [blame] | 132 | if (logger_) logger_->debug("UPnPContext: stopping io_context thread - finished {}", fmt::ptr(this)); |
Adrien Béraud | 91fd4b6 | 2023-08-29 20:50:01 -0400 | [diff] [blame] | 133 | } |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 134 | } |
| 135 | |
| 136 | UPnPContext::~UPnPContext() |
| 137 | { |
Adrien Beraud | 3bd61c9 | 2023-08-17 16:57:37 -0400 | [diff] [blame] | 138 | if (logger_) logger_->debug("UPnPContext instance [{}] destroyed", fmt::ptr(this)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 139 | } |
| 140 | |
| 141 | void |
| 142 | UPnPContext::init() |
| 143 | { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 144 | #if HAVE_LIBNATPMP |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 145 | auto natPmp = std::make_shared<NatPmp>(ctx, logger_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 146 | natPmp->setObserver(this); |
| 147 | protocolList_.emplace(NatProtocolType::NAT_PMP, std::move(natPmp)); |
| 148 | #endif |
| 149 | |
| 150 | #if HAVE_LIBUPNP |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 151 | auto pupnp = std::make_shared<PUPnP>(ctx, logger_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 152 | pupnp->setObserver(this); |
| 153 | protocolList_.emplace(NatProtocolType::PUPNP, std::move(pupnp)); |
| 154 | #endif |
| 155 | } |
| 156 | |
| 157 | void |
| 158 | UPnPContext::startUpnp() |
| 159 | { |
| 160 | assert(not controllerList_.empty()); |
| 161 | |
Adrien Beraud | 3bd61c9 | 2023-08-17 16:57:37 -0400 | [diff] [blame] | 162 | if (logger_) logger_->debug("Starting UPNP context"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 163 | |
| 164 | // Request a new IGD search. |
| 165 | for (auto const& [_, protocol] : protocolList_) { |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 166 | ctx->dispatch([p=protocol] { p->searchForIgd(); }); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 167 | } |
| 168 | |
| 169 | started_ = true; |
| 170 | } |
| 171 | |
| 172 | void |
| 173 | UPnPContext::stopUpnp(bool forceRelease) |
| 174 | { |
François-Simon Fauteux-Chapleau | 808db4f | 2024-04-19 11:39:47 -0400 | [diff] [blame] | 175 | if (logger_) logger_->debug("Stopping UPnP context"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 176 | |
| 177 | // Clear all current mappings if any. |
| 178 | |
| 179 | // Use a temporary list to avoid processing the mapping |
| 180 | // list while holding the lock. |
| 181 | std::list<Mapping::sharedPtr_t> toRemoveList; |
| 182 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 183 | std::lock_guard lock(mappingMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 184 | |
| 185 | PortType types[2] {PortType::TCP, PortType::UDP}; |
| 186 | for (auto& type : types) { |
| 187 | auto& mappingList = getMappingList(type); |
| 188 | for (auto const& [_, map] : mappingList) { |
| 189 | toRemoveList.emplace_back(map); |
| 190 | } |
| 191 | } |
| 192 | // Invalidate the current IGDs. |
| 193 | preferredIgd_.reset(); |
| 194 | validIgdList_.clear(); |
| 195 | } |
| 196 | for (auto const& map : toRemoveList) { |
| 197 | requestRemoveMapping(map); |
| 198 | |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 199 | // Notify is not needed in updateState when |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 200 | // shutting down (hence set it to false). NotifyCallback |
| 201 | // would trigger a new SIP registration and create a |
| 202 | // false registered state upon program close. |
| 203 | // It's handled by upper layers. |
Adrien Beraud | 3bd61c9 | 2023-08-17 16:57:37 -0400 | [diff] [blame] | 204 | updateMappingState(map, MappingState::FAILED, false); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 205 | // We dont remove mappings with auto-update enabled, |
| 206 | // unless forceRelease is true. |
| 207 | if (not map->getAutoUpdate() or forceRelease) { |
| 208 | map->enableAutoUpdate(false); |
| 209 | unregisterMapping(map); |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | // Clear all current IGDs. |
| 214 | for (auto const& [_, protocol] : protocolList_) { |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 215 | ctx->dispatch([p=protocol]{ p->clearIgds(); }); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 216 | } |
| 217 | |
| 218 | started_ = false; |
| 219 | } |
| 220 | |
| 221 | uint16_t |
| 222 | UPnPContext::generateRandomPort(PortType type, bool mustBeEven) |
| 223 | { |
| 224 | auto minPort = type == PortType::TCP ? UPNP_TCP_PORT_MIN : UPNP_UDP_PORT_MIN; |
| 225 | auto maxPort = type == PortType::TCP ? UPNP_TCP_PORT_MAX : UPNP_UDP_PORT_MAX; |
| 226 | |
| 227 | if (minPort >= maxPort) { |
Adrien Beraud | 3bd61c9 | 2023-08-17 16:57:37 -0400 | [diff] [blame] | 228 | // if (logger_) logger_->error("Max port number ({}) must be greater than min port number ({})", maxPort, minPort); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 229 | // Must be called with valid range. |
| 230 | assert(false); |
| 231 | } |
| 232 | |
| 233 | int fact = mustBeEven ? 2 : 1; |
| 234 | if (mustBeEven) { |
| 235 | minPort /= fact; |
| 236 | maxPort /= fact; |
| 237 | } |
| 238 | |
| 239 | // Seed the generator. |
| 240 | static std::mt19937 gen(dht::crypto::getSeededRandomEngine()); |
| 241 | // Define the range. |
| 242 | std::uniform_int_distribution<uint16_t> dist(minPort, maxPort); |
| 243 | return dist(gen) * fact; |
| 244 | } |
| 245 | |
| 246 | void |
| 247 | UPnPContext::connectivityChanged() |
| 248 | { |
Adrien Béraud | c36965c | 2023-08-17 21:50:27 -0400 | [diff] [blame] | 249 | // Debounce the connectivity change notification. |
| 250 | connectivityChangedTimer_.expires_after(std::chrono::milliseconds(50)); |
| 251 | connectivityChangedTimer_.async_wait(std::bind(&UPnPContext::_connectivityChanged, this, std::placeholders::_1)); |
| 252 | } |
| 253 | |
| 254 | void |
| 255 | UPnPContext::_connectivityChanged(const asio::error_code& ec) |
| 256 | { |
| 257 | if (ec == asio::error::operation_aborted) |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 258 | return; |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 259 | |
| 260 | auto hostAddr = ip_utils::getLocalAddr(AF_INET); |
| 261 | |
Adrien Beraud | 3bd61c9 | 2023-08-17 16:57:37 -0400 | [diff] [blame] | 262 | if (logger_) logger_->debug("Connectivity change check: host address {}", hostAddr.toString()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 263 | |
| 264 | auto restartUpnp = false; |
| 265 | |
| 266 | // On reception of "connectivity change" notification, the UPNP search |
| 267 | // will be restarted if either there is no valid IGD, or the IGD address |
| 268 | // changed. |
| 269 | |
| 270 | if (not isReady()) { |
| 271 | restartUpnp = true; |
| 272 | } else { |
| 273 | // Check if the host address changed. |
| 274 | for (auto const& [_, protocol] : protocolList_) { |
| 275 | if (protocol->isReady() and hostAddr != protocol->getHostAddress()) { |
Adrien Beraud | 3bd61c9 | 2023-08-17 16:57:37 -0400 | [diff] [blame] | 276 | if (logger_) logger_->warn("Host address changed from {} to {}", |
| 277 | protocol->getHostAddress().toString(), |
| 278 | hostAddr.toString()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 279 | protocol->clearIgds(); |
| 280 | restartUpnp = true; |
| 281 | break; |
| 282 | } |
| 283 | } |
| 284 | } |
| 285 | |
| 286 | // We have at least one valid IGD and the host address did |
| 287 | // not change, so no need to restart. |
| 288 | if (not restartUpnp) { |
| 289 | return; |
| 290 | } |
| 291 | |
| 292 | // No registered controller. A new search will be performed when |
| 293 | // a controller is registered. |
| 294 | if (controllerList_.empty()) |
| 295 | return; |
| 296 | |
Adrien Beraud | 3bd61c9 | 2023-08-17 16:57:37 -0400 | [diff] [blame] | 297 | if (logger_) logger_->debug("Connectivity changed. Clear the IGDs and restart"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 298 | |
| 299 | stopUpnp(); |
| 300 | startUpnp(); |
| 301 | |
| 302 | // Mapping with auto update enabled must be processed first. |
| 303 | processMappingWithAutoUpdate(); |
| 304 | } |
| 305 | |
| 306 | void |
| 307 | UPnPContext::setPublicAddress(const IpAddr& addr) |
| 308 | { |
| 309 | if (not addr) |
| 310 | return; |
| 311 | |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 312 | std::lock_guard lock(mappingMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 313 | if (knownPublicAddress_ != addr) { |
| 314 | knownPublicAddress_ = std::move(addr); |
Adrien Beraud | 3bd61c9 | 2023-08-17 16:57:37 -0400 | [diff] [blame] | 315 | if (logger_) logger_->debug("Setting the known public address to {}", addr.toString()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 316 | } |
| 317 | } |
| 318 | |
| 319 | bool |
| 320 | UPnPContext::isReady() const |
| 321 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 322 | std::lock_guard lock(mappingMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 323 | return not validIgdList_.empty(); |
| 324 | } |
| 325 | |
| 326 | IpAddr |
| 327 | UPnPContext::getExternalIP() const |
| 328 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 329 | std::lock_guard lock(mappingMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 330 | // Return the first IGD Ip available. |
| 331 | if (not validIgdList_.empty()) { |
| 332 | return (*validIgdList_.begin())->getPublicIp(); |
| 333 | } |
| 334 | return {}; |
| 335 | } |
| 336 | |
| 337 | Mapping::sharedPtr_t |
| 338 | UPnPContext::reserveMapping(Mapping& requestedMap) |
| 339 | { |
| 340 | auto desiredPort = requestedMap.getExternalPort(); |
| 341 | |
| 342 | if (desiredPort == 0) { |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 343 | if (logger_) logger_->debug("Desired port is not set, will provide the first available port for [{}]", |
| 344 | requestedMap.getTypeStr()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 345 | } else { |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 346 | if (logger_) logger_->debug("Try to find mapping for port {:d} [{}]", desiredPort, requestedMap.getTypeStr()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 347 | } |
| 348 | |
| 349 | Mapping::sharedPtr_t mapRes; |
| 350 | |
| 351 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 352 | std::lock_guard lock(mappingMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 353 | auto& mappingList = getMappingList(requestedMap.getType()); |
| 354 | |
| 355 | // We try to provide a mapping in "OPEN" state. If not found, |
| 356 | // we provide any available mapping. In this case, it's up to |
| 357 | // the caller to use it or not. |
| 358 | for (auto const& [_, map] : mappingList) { |
| 359 | // If the desired port is null, we pick the first available port. |
| 360 | if (map->isValid() and (desiredPort == 0 or map->getExternalPort() == desiredPort) |
| 361 | and map->isAvailable()) { |
| 362 | // Considere the first available mapping regardless of its |
| 363 | // state. A mapping with OPEN state will be used if found. |
| 364 | if (not mapRes) |
| 365 | mapRes = map; |
| 366 | |
| 367 | if (map->getState() == MappingState::OPEN) { |
| 368 | // Found an "OPEN" mapping. We are done. |
| 369 | mapRes = map; |
| 370 | break; |
| 371 | } |
| 372 | } |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | // Create a mapping if none was available. |
| 377 | if (not mapRes) { |
Morteza Namvar | 5f63952 | 2023-07-04 17:08:58 -0400 | [diff] [blame] | 378 | // JAMI_WARN("Did not find any available mapping. Will request one now"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 379 | mapRes = registerMapping(requestedMap); |
| 380 | } |
| 381 | |
| 382 | if (mapRes) { |
| 383 | // Make the mapping unavailable |
| 384 | mapRes->setAvailable(false); |
| 385 | // Copy attributes. |
| 386 | mapRes->setNotifyCallback(requestedMap.getNotifyCallback()); |
| 387 | mapRes->enableAutoUpdate(requestedMap.getAutoUpdate()); |
| 388 | // Notify the listener. |
| 389 | if (auto cb = mapRes->getNotifyCallback()) |
| 390 | cb(mapRes); |
| 391 | } |
| 392 | |
| 393 | updateMappingList(true); |
| 394 | |
| 395 | return mapRes; |
| 396 | } |
| 397 | |
| 398 | void |
| 399 | UPnPContext::releaseMapping(const Mapping& map) |
| 400 | { |
Adrien Béraud | c36965c | 2023-08-17 21:50:27 -0400 | [diff] [blame] | 401 | ctx->dispatch([this, map] { |
Sébastien Blin | 91cda3c | 2024-01-10 16:21:18 -0500 | [diff] [blame] | 402 | if (shutdownComplete_) |
| 403 | return; |
Adrien Béraud | c36965c | 2023-08-17 21:50:27 -0400 | [diff] [blame] | 404 | auto mapPtr = getMappingWithKey(map.getMapKey()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 405 | |
Adrien Béraud | c36965c | 2023-08-17 21:50:27 -0400 | [diff] [blame] | 406 | if (not mapPtr) { |
| 407 | // Might happen if the mapping failed or was never granted. |
| 408 | if (logger_) logger_->debug("Mapping {} does not exist or was already removed", map.toString()); |
| 409 | return; |
| 410 | } |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 411 | |
Adrien Béraud | c36965c | 2023-08-17 21:50:27 -0400 | [diff] [blame] | 412 | if (mapPtr->isAvailable()) { |
| 413 | if (logger_) logger_->warn("Trying to release an unused mapping {}", mapPtr->toString()); |
| 414 | return; |
| 415 | } |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 416 | |
Adrien Béraud | c36965c | 2023-08-17 21:50:27 -0400 | [diff] [blame] | 417 | // Remove it. |
| 418 | requestRemoveMapping(mapPtr); |
| 419 | unregisterMapping(mapPtr); |
| 420 | }); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 421 | } |
| 422 | |
| 423 | void |
| 424 | UPnPContext::registerController(void* controller) |
| 425 | { |
| 426 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 427 | std::lock_guard lock(mappingMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 428 | if (shutdownComplete_) { |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 429 | if (logger_) logger_->warn("UPnPContext already shut down"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 430 | return; |
| 431 | } |
Adrien Béraud | c36965c | 2023-08-17 21:50:27 -0400 | [diff] [blame] | 432 | auto ret = controllerList_.emplace(controller); |
| 433 | if (not ret.second) { |
| 434 | if (logger_) logger_->warn("Controller {} is already registered", fmt::ptr(controller)); |
| 435 | return; |
| 436 | } |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 437 | } |
| 438 | |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 439 | if (logger_) logger_->debug("Successfully registered controller {}", fmt::ptr(controller)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 440 | if (not started_) |
| 441 | startUpnp(); |
| 442 | } |
| 443 | |
| 444 | void |
| 445 | UPnPContext::unregisterController(void* controller) |
| 446 | { |
Sébastien Blin | 91cda3c | 2024-01-10 16:21:18 -0500 | [diff] [blame] | 447 | if (shutdownComplete_) |
| 448 | return; |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 449 | std::unique_lock lock(mappingMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 450 | if (controllerList_.erase(controller) == 1) { |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 451 | if (logger_) logger_->debug("Successfully unregistered controller {}", fmt::ptr(controller)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 452 | } else { |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 453 | if (logger_) logger_->debug("Controller {} was already removed", fmt::ptr(controller)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 454 | } |
| 455 | |
| 456 | if (controllerList_.empty()) { |
Adrien Béraud | c36965c | 2023-08-17 21:50:27 -0400 | [diff] [blame] | 457 | lock.unlock(); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 458 | stopUpnp(); |
| 459 | } |
| 460 | } |
| 461 | |
François-Simon Fauteux-Chapleau | 826f0ba | 2024-05-29 15:22:21 -0400 | [diff] [blame] | 462 | std::vector<IGDInfo> |
| 463 | UPnPContext::getIgdsInfo() const |
| 464 | { |
| 465 | std::vector<IGDInfo> igdInfoList; |
| 466 | |
| 467 | std::lock_guard lk(mappingMutex_); |
| 468 | for (auto& igd : validIgdList_) { |
| 469 | auto protocol = protocolList_.at(igd->getProtocol()); |
| 470 | |
| 471 | IGDInfo info; |
| 472 | info.uid = igd->getUID(); |
| 473 | info.localIp = igd->getLocalIp(); |
| 474 | info.publicIp = igd->getPublicIp(); |
| 475 | info.mappingInfoList = protocol->getMappingsInfo(igd); |
| 476 | |
| 477 | igdInfoList.push_back(std::move(info)); |
| 478 | } |
| 479 | |
| 480 | return igdInfoList; |
| 481 | } |
| 482 | |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 483 | uint16_t |
| 484 | UPnPContext::getAvailablePortNumber(PortType type) |
| 485 | { |
| 486 | // Only return an availalable random port. No actual |
| 487 | // reservation is made here. |
| 488 | |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 489 | std::lock_guard lock(mappingMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 490 | auto& mappingList = getMappingList(type); |
| 491 | int tryCount = 0; |
| 492 | while (tryCount++ < MAX_REQUEST_RETRIES) { |
| 493 | uint16_t port = generateRandomPort(type); |
| 494 | Mapping map(type, port, port); |
| 495 | if (mappingList.find(map.getMapKey()) == mappingList.end()) |
| 496 | return port; |
| 497 | } |
| 498 | |
| 499 | // Very unlikely to get here. |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 500 | if (logger_) logger_->error("Could not find an available port after %i trials", MAX_REQUEST_RETRIES); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 501 | return 0; |
| 502 | } |
| 503 | |
| 504 | void |
| 505 | UPnPContext::requestMapping(const Mapping::sharedPtr_t& map) |
| 506 | { |
| 507 | assert(map); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 508 | auto const& igd = getPreferredIgd(); |
| 509 | // We must have at least a valid IGD pointer if we get here. |
| 510 | // Not this method is called only if there were a valid IGD, however, |
| 511 | // because the processing is asynchronous, it's possible that the IGD |
| 512 | // was invalidated when the this code executed. |
| 513 | if (not igd) { |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 514 | if (logger_) logger_->debug("No valid IGDs available"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 515 | return; |
| 516 | } |
| 517 | |
| 518 | map->setIgd(igd); |
| 519 | |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 520 | if (logger_) logger_->debug("Request mapping {} using protocol [{}] IGD [{}]", |
| 521 | map->toString(), |
| 522 | igd->getProtocolName(), |
| 523 | igd->toString()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 524 | |
Adrien Beraud | 3bd61c9 | 2023-08-17 16:57:37 -0400 | [diff] [blame] | 525 | updateMappingState(map, MappingState::IN_PROGRESS); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 526 | |
| 527 | auto const& protocol = protocolList_.at(igd->getProtocol()); |
| 528 | protocol->requestMappingAdd(*map); |
| 529 | } |
| 530 | |
| 531 | bool |
| 532 | UPnPContext::provisionNewMappings(PortType type, int portCount) |
| 533 | { |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 534 | if (logger_) logger_->debug("Provision {:d} new mappings of type [{}]", portCount, Mapping::getTypeStr(type)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 535 | |
| 536 | assert(portCount > 0); |
| 537 | |
| 538 | while (portCount > 0) { |
| 539 | auto port = getAvailablePortNumber(type); |
| 540 | if (port > 0) { |
| 541 | // Found an available port number |
| 542 | portCount--; |
| 543 | Mapping map(type, port, port, true); |
| 544 | registerMapping(map); |
| 545 | } else { |
| 546 | // Very unlikely to get here! |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 547 | if (logger_) logger_->error("Can not find any available port to provision!"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 548 | return false; |
| 549 | } |
| 550 | } |
| 551 | |
| 552 | return true; |
| 553 | } |
| 554 | |
| 555 | bool |
| 556 | UPnPContext::deleteUnneededMappings(PortType type, int portCount) |
| 557 | { |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 558 | if (logger_) logger_->debug("Remove {:d} unneeded mapping of type [{}]", portCount, Mapping::getTypeStr(type)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 559 | |
| 560 | assert(portCount > 0); |
| 561 | |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 562 | //CHECK_VALID_THREAD(); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 563 | |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 564 | std::lock_guard lock(mappingMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 565 | auto& mappingList = getMappingList(type); |
| 566 | |
| 567 | for (auto it = mappingList.begin(); it != mappingList.end();) { |
| 568 | auto map = it->second; |
| 569 | assert(map); |
| 570 | |
| 571 | if (not map->isAvailable()) { |
| 572 | it++; |
| 573 | continue; |
| 574 | } |
| 575 | |
| 576 | if (map->getState() == MappingState::OPEN and portCount > 0) { |
| 577 | // Close portCount mappings in "OPEN" state. |
| 578 | requestRemoveMapping(map); |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 579 | it = mappingList.erase(it); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 580 | portCount--; |
| 581 | } else if (map->getState() != MappingState::OPEN) { |
| 582 | // If this methods is called, it means there are more open |
| 583 | // mappings than required. So, all mappings in a state other |
| 584 | // than "OPEN" state (typically in in-progress state) will |
| 585 | // be deleted as well. |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 586 | it = mappingList.erase(it); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 587 | } else { |
| 588 | it++; |
| 589 | } |
| 590 | } |
| 591 | |
| 592 | return true; |
| 593 | } |
| 594 | |
| 595 | void |
| 596 | UPnPContext::updatePreferredIgd() |
| 597 | { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 598 | if (preferredIgd_ and preferredIgd_->isValid()) |
| 599 | return; |
| 600 | |
| 601 | // Reset and search for the best IGD. |
| 602 | preferredIgd_.reset(); |
| 603 | |
| 604 | for (auto const& [_, protocol] : protocolList_) { |
| 605 | if (protocol->isReady()) { |
| 606 | auto igdList = protocol->getIgdList(); |
| 607 | assert(not igdList.empty()); |
| 608 | auto const& igd = igdList.front(); |
| 609 | if (not igd->isValid()) |
| 610 | continue; |
| 611 | |
| 612 | // Prefer NAT-PMP over PUPNP. |
| 613 | if (preferredIgd_ and igd->getProtocol() != NatProtocolType::NAT_PMP) |
| 614 | continue; |
| 615 | |
| 616 | // Update. |
| 617 | preferredIgd_ = igd; |
| 618 | } |
| 619 | } |
| 620 | |
| 621 | if (preferredIgd_ and preferredIgd_->isValid()) { |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 622 | if (logger_) logger_->debug("Preferred IGD updated to [{}] IGD [{} {}] ", |
| 623 | preferredIgd_->getProtocolName(), |
| 624 | preferredIgd_->getUID(), |
| 625 | preferredIgd_->toString()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 626 | } |
| 627 | } |
| 628 | |
| 629 | std::shared_ptr<IGD> |
| 630 | UPnPContext::getPreferredIgd() const |
| 631 | { |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 632 | //CHECK_VALID_THREAD(); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 633 | |
| 634 | return preferredIgd_; |
| 635 | } |
| 636 | |
| 637 | void |
| 638 | UPnPContext::updateMappingList(bool async) |
| 639 | { |
| 640 | // Run async if requested. |
| 641 | if (async) { |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 642 | ctx->post([this] { updateMappingList(false); }); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 643 | return; |
| 644 | } |
| 645 | |
Adrien Béraud | 25c30c4 | 2023-07-05 13:46:54 -0400 | [diff] [blame] | 646 | mappingListUpdateTimer_.cancel(); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 647 | |
| 648 | // Skip if no controller registered. |
| 649 | if (controllerList_.empty()) |
| 650 | return; |
| 651 | |
| 652 | // Cancel the current timer (if any) and re-schedule. |
| 653 | std::shared_ptr<IGD> prefIgd = getPreferredIgd(); |
| 654 | if (not prefIgd) { |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 655 | if (logger_) logger_->debug("UPNP/NAT-PMP enabled, but no valid IGDs available"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 656 | // No valid IGD. Nothing to do. |
| 657 | return; |
| 658 | } |
| 659 | |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 660 | mappingListUpdateTimer_.expires_after(MAP_UPDATE_INTERVAL); |
Adrien Béraud | 25c30c4 | 2023-07-05 13:46:54 -0400 | [diff] [blame] | 661 | mappingListUpdateTimer_.async_wait([this](asio::error_code const& ec) { |
| 662 | if (ec != asio::error::operation_aborted) |
| 663 | updateMappingList(false); |
| 664 | }); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 665 | |
| 666 | // Process pending requests if any. |
| 667 | processPendingRequests(prefIgd); |
| 668 | |
| 669 | // Make new requests for mappings that failed and have |
| 670 | // the auto-update option enabled. |
| 671 | processMappingWithAutoUpdate(); |
| 672 | |
| 673 | PortType typeArray[2] = {PortType::TCP, PortType::UDP}; |
| 674 | |
| 675 | for (auto idx : {0, 1}) { |
| 676 | auto type = typeArray[idx]; |
| 677 | |
| 678 | MappingStatus status; |
| 679 | getMappingStatus(type, status); |
| 680 | |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 681 | if (logger_) logger_->debug("Mapping status [{}] - overall {:d}: {:d} open ({:d} ready + {:d} in use), {:d} pending, {:d} " |
| 682 | "in-progress, {:d} failed", |
| 683 | Mapping::getTypeStr(type), |
| 684 | status.sum(), |
| 685 | status.openCount_, |
| 686 | status.readyCount_, |
| 687 | status.openCount_ - status.readyCount_, |
| 688 | status.pendingCount_, |
| 689 | status.inProgressCount_, |
| 690 | status.failedCount_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 691 | |
| 692 | if (status.failedCount_ > 0) { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 693 | std::lock_guard lock(mappingMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 694 | auto const& mappingList = getMappingList(type); |
| 695 | for (auto const& [_, map] : mappingList) { |
| 696 | if (map->getState() == MappingState::FAILED) { |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 697 | if (logger_) logger_->debug("Mapping status [{}] - Available [{}]", |
| 698 | map->toString(true), |
| 699 | map->isAvailable() ? "YES" : "NO"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 700 | } |
| 701 | } |
| 702 | } |
| 703 | |
| 704 | int toRequestCount = (int) minOpenPortLimit_[idx] |
| 705 | - (int) (status.readyCount_ + status.inProgressCount_ |
| 706 | + status.pendingCount_); |
| 707 | |
| 708 | // Provision/release mappings accordingly. |
| 709 | if (toRequestCount > 0) { |
| 710 | // Take into account the request in-progress when making |
| 711 | // requests for new mappings. |
| 712 | provisionNewMappings(type, toRequestCount); |
| 713 | } else if (status.readyCount_ > maxOpenPortLimit_[idx]) { |
| 714 | deleteUnneededMappings(type, status.readyCount_ - maxOpenPortLimit_[idx]); |
| 715 | } |
| 716 | } |
| 717 | |
| 718 | // Prune the mapping list if needed |
| 719 | if (protocolList_.at(NatProtocolType::PUPNP)->isReady()) { |
| 720 | #if HAVE_LIBNATPMP |
| 721 | // Dont perform if NAT-PMP is valid. |
| 722 | if (not protocolList_.at(NatProtocolType::NAT_PMP)->isReady()) |
| 723 | #endif |
| 724 | { |
| 725 | pruneMappingList(); |
| 726 | } |
| 727 | } |
| 728 | |
| 729 | #if HAVE_LIBNATPMP |
| 730 | // Renew nat-pmp allocations |
| 731 | if (protocolList_.at(NatProtocolType::NAT_PMP)->isReady()) |
| 732 | renewAllocations(); |
| 733 | #endif |
| 734 | } |
| 735 | |
| 736 | void |
| 737 | UPnPContext::pruneMappingList() |
| 738 | { |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 739 | //CHECK_VALID_THREAD(); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 740 | |
| 741 | MappingStatus status; |
| 742 | getMappingStatus(status); |
| 743 | |
| 744 | // Do not prune the list if there are pending/in-progress requests. |
| 745 | if (status.inProgressCount_ != 0 or status.pendingCount_ != 0) { |
| 746 | return; |
| 747 | } |
| 748 | |
| 749 | auto const& igd = getPreferredIgd(); |
| 750 | if (not igd or igd->getProtocol() != NatProtocolType::PUPNP) { |
| 751 | return; |
| 752 | } |
| 753 | auto protocol = protocolList_.at(NatProtocolType::PUPNP); |
| 754 | |
| 755 | auto remoteMapList = protocol->getMappingsListByDescr(igd, |
| 756 | Mapping::UPNP_MAPPING_DESCRIPTION_PREFIX); |
Adrien Beraud | a0683d1 | 2023-08-22 18:09:02 -0400 | [diff] [blame] | 757 | /*if (remoteMapList.empty()) { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 758 | std::lock_guard lock(mappingMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 759 | if (not getMappingList(PortType::TCP).empty() or getMappingList(PortType::TCP).empty()) { |
Morteza Namvar | 5f63952 | 2023-07-04 17:08:58 -0400 | [diff] [blame] | 760 | // JAMI_WARN("We have provisionned mappings but the PUPNP IGD returned an empty list!"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 761 | } |
Adrien Beraud | a0683d1 | 2023-08-22 18:09:02 -0400 | [diff] [blame] | 762 | }*/ |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 763 | |
| 764 | pruneUnMatchedMappings(igd, remoteMapList); |
| 765 | pruneUnTrackedMappings(igd, remoteMapList); |
| 766 | } |
| 767 | |
| 768 | void |
| 769 | UPnPContext::pruneUnMatchedMappings(const std::shared_ptr<IGD>& igd, |
| 770 | const std::map<Mapping::key_t, Mapping>& remoteMapList) |
| 771 | { |
| 772 | // Check/synchronize local mapping list with the list |
| 773 | // returned by the IGD. |
| 774 | |
Adrien Beraud | a0683d1 | 2023-08-22 18:09:02 -0400 | [diff] [blame] | 775 | for (auto type: {PortType::TCP, PortType::UDP}) { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 776 | // Use a temporary list to avoid processing mappings while holding the lock. |
| 777 | std::list<Mapping::sharedPtr_t> toRemoveList; |
| 778 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 779 | std::lock_guard lock(mappingMutex_); |
Adrien Beraud | a0683d1 | 2023-08-22 18:09:02 -0400 | [diff] [blame] | 780 | for (auto const& [_, map] : getMappingList(type)) { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 781 | // Only check mappings allocated by UPNP protocol. |
| 782 | if (map->getProtocol() != NatProtocolType::PUPNP) { |
| 783 | continue; |
| 784 | } |
| 785 | // Set mapping as failed if not found in the list |
| 786 | // returned by the IGD. |
| 787 | if (map->getState() == MappingState::OPEN |
| 788 | and remoteMapList.find(map->getMapKey()) == remoteMapList.end()) { |
| 789 | toRemoveList.emplace_back(map); |
| 790 | |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 791 | if (logger_) logger_->warn("Mapping {} (IGD {}) marked as \"OPEN\" but not found in the " |
| 792 | "remote list. Mark as failed!", |
| 793 | map->toString(), |
| 794 | igd->toString()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 795 | } |
| 796 | } |
| 797 | } |
| 798 | |
| 799 | for (auto const& map : toRemoveList) { |
Adrien Beraud | 3bd61c9 | 2023-08-17 16:57:37 -0400 | [diff] [blame] | 800 | updateMappingState(map, MappingState::FAILED); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 801 | unregisterMapping(map); |
| 802 | } |
| 803 | } |
| 804 | } |
| 805 | |
| 806 | void |
| 807 | UPnPContext::pruneUnTrackedMappings(const std::shared_ptr<IGD>& igd, |
| 808 | const std::map<Mapping::key_t, Mapping>& remoteMapList) |
| 809 | { |
| 810 | // Use a temporary list to avoid processing mappings while holding the lock. |
| 811 | std::list<Mapping> toRemoveList; |
| 812 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 813 | std::lock_guard lock(mappingMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 814 | |
| 815 | for (auto const& [_, map] : remoteMapList) { |
| 816 | // Must has valid IGD pointer and use UPNP protocol. |
| 817 | assert(map.getIgd()); |
| 818 | assert(map.getIgd()->getProtocol() == NatProtocolType::PUPNP); |
| 819 | auto& mappingList = getMappingList(map.getType()); |
| 820 | auto it = mappingList.find(map.getMapKey()); |
| 821 | if (it == mappingList.end()) { |
| 822 | // Not present, request mapping remove. |
| 823 | toRemoveList.emplace_back(std::move(map)); |
| 824 | // Make only few remove requests at once. |
| 825 | if (toRemoveList.size() >= MAX_REQUEST_REMOVE_COUNT) |
| 826 | break; |
| 827 | } |
| 828 | } |
| 829 | } |
| 830 | |
| 831 | // Remove un-tracked mappings. |
| 832 | auto protocol = protocolList_.at(NatProtocolType::PUPNP); |
| 833 | for (auto const& map : toRemoveList) { |
| 834 | protocol->requestMappingRemove(map); |
| 835 | } |
| 836 | } |
| 837 | |
| 838 | void |
| 839 | UPnPContext::pruneMappingsWithInvalidIgds(const std::shared_ptr<IGD>& igd) |
| 840 | { |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 841 | //CHECK_VALID_THREAD(); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 842 | |
| 843 | // Use temporary list to avoid holding the lock while |
| 844 | // processing the mapping list. |
| 845 | std::list<Mapping::sharedPtr_t> toRemoveList; |
| 846 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 847 | std::lock_guard lock(mappingMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 848 | |
| 849 | PortType types[2] {PortType::TCP, PortType::UDP}; |
| 850 | for (auto& type : types) { |
| 851 | auto& mappingList = getMappingList(type); |
| 852 | for (auto const& [_, map] : mappingList) { |
| 853 | if (map->getIgd() == igd) |
| 854 | toRemoveList.emplace_back(map); |
| 855 | } |
| 856 | } |
| 857 | } |
| 858 | |
| 859 | for (auto const& map : toRemoveList) { |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 860 | if (logger_) logger_->debug("Remove mapping {} (has an invalid IGD {} [{}])", |
| 861 | map->toString(), |
| 862 | igd->toString(), |
| 863 | igd->getProtocolName()); |
Adrien Béraud | 5674031 | 2023-08-23 08:38:28 -0400 | [diff] [blame] | 864 | updateMappingState(map, MappingState::FAILED); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 865 | unregisterMapping(map); |
| 866 | } |
| 867 | } |
| 868 | |
| 869 | void |
| 870 | UPnPContext::processPendingRequests(const std::shared_ptr<IGD>& igd) |
| 871 | { |
| 872 | // This list holds the mappings to be requested. This is |
| 873 | // needed to avoid performing the requests while holding |
| 874 | // the lock. |
| 875 | std::list<Mapping::sharedPtr_t> requestsList; |
| 876 | |
| 877 | // Populate the list of requests to perform. |
| 878 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 879 | std::lock_guard lock(mappingMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 880 | PortType typeArray[2] {PortType::TCP, PortType::UDP}; |
| 881 | |
| 882 | for (auto type : typeArray) { |
| 883 | auto& mappingList = getMappingList(type); |
| 884 | for (auto& [_, map] : mappingList) { |
| 885 | if (map->getState() == MappingState::PENDING) { |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 886 | if (logger_) logger_->debug("Send pending request for mapping {} to IGD {}", |
| 887 | map->toString(), |
| 888 | igd->toString()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 889 | requestsList.emplace_back(map); |
| 890 | } |
| 891 | } |
| 892 | } |
| 893 | } |
| 894 | |
| 895 | // Process the pending requests. |
| 896 | for (auto const& map : requestsList) { |
| 897 | requestMapping(map); |
| 898 | } |
| 899 | } |
| 900 | |
| 901 | void |
| 902 | UPnPContext::processMappingWithAutoUpdate() |
| 903 | { |
| 904 | // This list holds the mappings to be requested. This is |
| 905 | // needed to avoid performing the requests while holding |
| 906 | // the lock. |
| 907 | std::list<Mapping::sharedPtr_t> requestsList; |
| 908 | |
| 909 | // Populate the list of requests for mappings with auto-update enabled. |
| 910 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 911 | std::lock_guard lock(mappingMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 912 | PortType typeArray[2] {PortType::TCP, PortType::UDP}; |
| 913 | |
| 914 | for (auto type : typeArray) { |
| 915 | auto& mappingList = getMappingList(type); |
| 916 | for (auto const& [_, map] : mappingList) { |
| 917 | if (map->getState() == MappingState::FAILED and map->getAutoUpdate()) { |
| 918 | requestsList.emplace_back(map); |
| 919 | } |
| 920 | } |
| 921 | } |
| 922 | } |
| 923 | |
| 924 | for (auto const& oldMap : requestsList) { |
| 925 | // Request a new mapping if auto-update is enabled. |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 926 | if (logger_) logger_->debug("Mapping {} has auto-update enabled, a new mapping will be requested", |
| 927 | oldMap->toString()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 928 | |
| 929 | // Reserve a new mapping. |
| 930 | Mapping newMapping(oldMap->getType()); |
| 931 | newMapping.enableAutoUpdate(true); |
| 932 | newMapping.setNotifyCallback(oldMap->getNotifyCallback()); |
| 933 | |
| 934 | auto const& mapPtr = reserveMapping(newMapping); |
| 935 | assert(mapPtr); |
| 936 | |
| 937 | // Release the old one. |
| 938 | oldMap->setAvailable(true); |
| 939 | oldMap->enableAutoUpdate(false); |
| 940 | oldMap->setNotifyCallback(nullptr); |
| 941 | unregisterMapping(oldMap); |
| 942 | } |
| 943 | } |
| 944 | |
| 945 | void |
| 946 | UPnPContext::onIgdUpdated(const std::shared_ptr<IGD>& igd, UpnpIgdEvent event) |
| 947 | { |
| 948 | assert(igd); |
| 949 | |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 950 | char const* IgdState = event == UpnpIgdEvent::ADDED ? "ADDED" |
| 951 | : event == UpnpIgdEvent::REMOVED ? "REMOVED" |
| 952 | : "INVALID"; |
| 953 | |
| 954 | auto const& igdLocalAddr = igd->getLocalIp(); |
| 955 | auto protocolName = igd->getProtocolName(); |
| 956 | |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 957 | if (logger_) logger_->debug("New event for IGD [{} {}] [{}]: [{}]", |
| 958 | igd->getUID(), |
| 959 | igd->toString(), |
| 960 | protocolName, |
| 961 | IgdState); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 962 | |
| 963 | // Check if the IGD has valid addresses. |
| 964 | if (not igdLocalAddr) { |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 965 | if (logger_) logger_->warn("[{}] IGD has an invalid local address", protocolName); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 966 | return; |
| 967 | } |
| 968 | |
| 969 | if (not igd->getPublicIp()) { |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 970 | if (logger_) logger_->warn("[{}] IGD has an invalid public address", protocolName); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 971 | return; |
| 972 | } |
| 973 | |
| 974 | if (knownPublicAddress_ and igd->getPublicIp() != knownPublicAddress_) { |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 975 | if (logger_) logger_->warn("[{}] IGD external address [{}] does not match known public address [{}]." |
| 976 | " The mapped addresses might not be reachable", |
| 977 | protocolName, |
| 978 | igd->getPublicIp().toString(), |
| 979 | knownPublicAddress_.toString()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 980 | } |
| 981 | |
François-Simon Fauteux-Chapleau | 5a9e801 | 2024-06-04 11:39:17 -0400 | [diff] [blame^] | 982 | // Update the IGD list. |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 983 | if (event == UpnpIgdEvent::REMOVED or event == UpnpIgdEvent::INVALID_STATE) { |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 984 | if (logger_) logger_->warn("State of IGD [{} {}] [{}] changed to [{}]. Pruning the mapping list", |
| 985 | igd->getUID(), |
| 986 | igd->toString(), |
| 987 | protocolName, |
| 988 | IgdState); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 989 | |
| 990 | pruneMappingsWithInvalidIgds(igd); |
| 991 | |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 992 | std::lock_guard lock(mappingMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 993 | validIgdList_.erase(igd); |
François-Simon Fauteux-Chapleau | 5a9e801 | 2024-06-04 11:39:17 -0400 | [diff] [blame^] | 994 | } else { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 995 | std::lock_guard lock(mappingMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 996 | auto ret = validIgdList_.emplace(igd); |
| 997 | if (ret.second) { |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 998 | if (logger_) logger_->debug("IGD [{}] on address {} was added. Will process any pending requests", |
| 999 | protocolName, |
| 1000 | igdLocalAddr.toString(true, true)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1001 | } else { |
| 1002 | // Already in the list. |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 1003 | if (logger_) logger_->error("IGD [{}] on address {} already in the list", |
| 1004 | protocolName, |
| 1005 | igdLocalAddr.toString(true, true)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1006 | return; |
| 1007 | } |
| 1008 | } |
| 1009 | |
François-Simon Fauteux-Chapleau | 5a9e801 | 2024-06-04 11:39:17 -0400 | [diff] [blame^] | 1010 | updatePreferredIgd(); |
| 1011 | |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1012 | // Update the provisionned mappings. |
| 1013 | updateMappingList(false); |
| 1014 | } |
| 1015 | |
| 1016 | void |
| 1017 | UPnPContext::onMappingAdded(const std::shared_ptr<IGD>& igd, const Mapping& mapRes) |
| 1018 | { |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 1019 | //CHECK_VALID_THREAD(); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1020 | |
| 1021 | // Check if we have a pending request for this response. |
| 1022 | auto map = getMappingWithKey(mapRes.getMapKey()); |
| 1023 | if (not map) { |
| 1024 | // We may receive a response for a canceled request. Just ignore it. |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 1025 | if (logger_) logger_->debug("Response for mapping {} [IGD {}] [{}] does not have a local match", |
| 1026 | mapRes.toString(), |
| 1027 | igd->toString(), |
| 1028 | mapRes.getProtocolName()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1029 | return; |
| 1030 | } |
| 1031 | |
| 1032 | // The mapping request is new and successful. Update. |
| 1033 | map->setIgd(igd); |
| 1034 | map->setInternalAddress(mapRes.getInternalAddress()); |
| 1035 | map->setExternalPort(mapRes.getExternalPort()); |
| 1036 | |
| 1037 | // Update the state and report to the owner. |
Adrien Beraud | 3bd61c9 | 2023-08-17 16:57:37 -0400 | [diff] [blame] | 1038 | updateMappingState(map, MappingState::OPEN); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1039 | |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 1040 | if (logger_) logger_->debug("Mapping {} (on IGD {} [{}]) successfully performed", |
| 1041 | map->toString(), |
| 1042 | igd->toString(), |
| 1043 | map->getProtocolName()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1044 | |
| 1045 | // Call setValid() to reset the errors counter. We need |
| 1046 | // to reset the counter on each successful response. |
| 1047 | igd->setValid(true); |
| 1048 | } |
| 1049 | |
| 1050 | #if HAVE_LIBNATPMP |
| 1051 | void |
| 1052 | UPnPContext::onMappingRenewed(const std::shared_ptr<IGD>& igd, const Mapping& map) |
| 1053 | { |
| 1054 | auto mapPtr = getMappingWithKey(map.getMapKey()); |
| 1055 | |
| 1056 | if (not mapPtr) { |
| 1057 | // We may receive a notification for a canceled request. Ignore it. |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 1058 | if (logger_) logger_->warn("Renewed mapping {} from IGD {} [{}] does not have a match in local list", |
| 1059 | map.toString(), |
| 1060 | igd->toString(), |
| 1061 | map.getProtocolName()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1062 | return; |
| 1063 | } |
| 1064 | if (mapPtr->getProtocol() != NatProtocolType::NAT_PMP or not mapPtr->isValid() |
| 1065 | or mapPtr->getState() != MappingState::OPEN) { |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 1066 | if (logger_) logger_->warn("Renewed mapping {} from IGD {} [{}] is in unexpected state", |
| 1067 | mapPtr->toString(), |
| 1068 | igd->toString(), |
| 1069 | mapPtr->getProtocolName()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1070 | return; |
| 1071 | } |
| 1072 | |
| 1073 | mapPtr->setRenewalTime(map.getRenewalTime()); |
| 1074 | } |
| 1075 | #endif |
| 1076 | |
| 1077 | void |
| 1078 | UPnPContext::requestRemoveMapping(const Mapping::sharedPtr_t& map) |
| 1079 | { |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 1080 | if (not map or not map->isValid()) { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1081 | // Silently ignore if the mapping is invalid |
| 1082 | return; |
| 1083 | } |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1084 | auto protocol = protocolList_.at(map->getIgd()->getProtocol()); |
| 1085 | protocol->requestMappingRemove(*map); |
| 1086 | } |
| 1087 | |
| 1088 | void |
| 1089 | UPnPContext::deleteAllMappings(PortType type) |
| 1090 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 1091 | std::lock_guard lock(mappingMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1092 | auto& mappingList = getMappingList(type); |
| 1093 | |
| 1094 | for (auto const& [_, map] : mappingList) { |
| 1095 | requestRemoveMapping(map); |
| 1096 | } |
| 1097 | } |
| 1098 | |
| 1099 | void |
| 1100 | UPnPContext::onMappingRemoved(const std::shared_ptr<IGD>& igd, const Mapping& mapRes) |
| 1101 | { |
| 1102 | if (not mapRes.isValid()) |
| 1103 | return; |
| 1104 | |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1105 | auto map = getMappingWithKey(mapRes.getMapKey()); |
| 1106 | // Notify the listener. |
| 1107 | if (map and map->getNotifyCallback()) |
| 1108 | map->getNotifyCallback()(map); |
| 1109 | } |
| 1110 | |
| 1111 | Mapping::sharedPtr_t |
| 1112 | UPnPContext::registerMapping(Mapping& map) |
| 1113 | { |
| 1114 | if (map.getExternalPort() == 0) { |
Morteza Namvar | 5f63952 | 2023-07-04 17:08:58 -0400 | [diff] [blame] | 1115 | // JAMI_DBG("Port number not set. Will set a random port number"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1116 | auto port = getAvailablePortNumber(map.getType()); |
| 1117 | map.setExternalPort(port); |
| 1118 | map.setInternalPort(port); |
| 1119 | } |
| 1120 | |
| 1121 | // Newly added mapping must be in pending state by default. |
| 1122 | map.setState(MappingState::PENDING); |
| 1123 | |
| 1124 | Mapping::sharedPtr_t mapPtr; |
| 1125 | |
| 1126 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 1127 | std::lock_guard lock(mappingMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1128 | auto& mappingList = getMappingList(map.getType()); |
| 1129 | |
| 1130 | auto ret = mappingList.emplace(map.getMapKey(), std::make_shared<Mapping>(map)); |
| 1131 | if (not ret.second) { |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 1132 | if (logger_) logger_->warn("Mapping request for {} already added!", map.toString()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1133 | return {}; |
| 1134 | } |
| 1135 | mapPtr = ret.first->second; |
| 1136 | assert(mapPtr); |
| 1137 | } |
| 1138 | |
| 1139 | // No available IGD. The pending mapping requests will be processed |
| 1140 | // when a IGD becomes available (in onIgdAdded() method). |
| 1141 | if (not isReady()) { |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 1142 | if (logger_) logger_->warn("No IGD available. Mapping will be requested when an IGD becomes available"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1143 | } else { |
| 1144 | requestMapping(mapPtr); |
| 1145 | } |
| 1146 | |
| 1147 | return mapPtr; |
| 1148 | } |
| 1149 | |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1150 | void |
| 1151 | UPnPContext::unregisterMapping(const Mapping::sharedPtr_t& map) |
| 1152 | { |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 1153 | //CHECK_VALID_THREAD(); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1154 | |
| 1155 | if (not map) { |
Morteza Namvar | 5f63952 | 2023-07-04 17:08:58 -0400 | [diff] [blame] | 1156 | // JAMI_ERR("Mapping pointer is null"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1157 | return; |
| 1158 | } |
| 1159 | |
| 1160 | if (map->getAutoUpdate()) { |
| 1161 | // Dont unregister mappings with auto-update enabled. |
| 1162 | return; |
| 1163 | } |
| 1164 | auto& mappingList = getMappingList(map->getType()); |
| 1165 | |
| 1166 | if (mappingList.erase(map->getMapKey()) == 1) { |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 1167 | if (logger_) logger_->debug("Unregistered mapping {}", map->toString()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1168 | } else { |
| 1169 | // The mapping may already be un-registered. Just ignore it. |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 1170 | if (logger_) logger_->debug("Mapping {} [{}] does not have a local match", |
| 1171 | map->toString(), |
| 1172 | map->getProtocolName()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1173 | } |
| 1174 | } |
| 1175 | |
| 1176 | std::map<Mapping::key_t, Mapping::sharedPtr_t>& |
| 1177 | UPnPContext::getMappingList(PortType type) |
| 1178 | { |
| 1179 | unsigned typeIdx = type == PortType::TCP ? 0 : 1; |
| 1180 | return mappingList_[typeIdx]; |
| 1181 | } |
| 1182 | |
| 1183 | Mapping::sharedPtr_t |
| 1184 | UPnPContext::getMappingWithKey(Mapping::key_t key) |
| 1185 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 1186 | std::lock_guard lock(mappingMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1187 | auto const& mappingList = getMappingList(Mapping::getTypeFromMapKey(key)); |
| 1188 | auto it = mappingList.find(key); |
| 1189 | if (it == mappingList.end()) |
| 1190 | return nullptr; |
| 1191 | return it->second; |
| 1192 | } |
| 1193 | |
| 1194 | void |
| 1195 | UPnPContext::getMappingStatus(PortType type, MappingStatus& status) |
| 1196 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 1197 | std::lock_guard lock(mappingMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1198 | auto& mappingList = getMappingList(type); |
| 1199 | |
| 1200 | for (auto const& [_, map] : mappingList) { |
| 1201 | switch (map->getState()) { |
| 1202 | case MappingState::PENDING: { |
| 1203 | status.pendingCount_++; |
| 1204 | break; |
| 1205 | } |
| 1206 | case MappingState::IN_PROGRESS: { |
| 1207 | status.inProgressCount_++; |
| 1208 | break; |
| 1209 | } |
| 1210 | case MappingState::FAILED: { |
| 1211 | status.failedCount_++; |
| 1212 | break; |
| 1213 | } |
| 1214 | case MappingState::OPEN: { |
| 1215 | status.openCount_++; |
| 1216 | if (map->isAvailable()) |
| 1217 | status.readyCount_++; |
| 1218 | break; |
| 1219 | } |
| 1220 | |
| 1221 | default: |
| 1222 | // Must not get here. |
| 1223 | assert(false); |
| 1224 | break; |
| 1225 | } |
| 1226 | } |
| 1227 | } |
| 1228 | |
| 1229 | void |
| 1230 | UPnPContext::getMappingStatus(MappingStatus& status) |
| 1231 | { |
| 1232 | getMappingStatus(PortType::TCP, status); |
| 1233 | getMappingStatus(PortType::UDP, status); |
| 1234 | } |
| 1235 | |
| 1236 | void |
| 1237 | UPnPContext::onMappingRequestFailed(const Mapping& mapRes) |
| 1238 | { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1239 | auto const& map = getMappingWithKey(mapRes.getMapKey()); |
| 1240 | if (not map) { |
| 1241 | // We may receive a response for a removed request. Just ignore it. |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 1242 | if (logger_) logger_->debug("Mapping {} [IGD {}] does not have a local match", |
| 1243 | mapRes.toString(), |
| 1244 | mapRes.getProtocolName()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1245 | return; |
| 1246 | } |
| 1247 | |
| 1248 | auto igd = map->getIgd(); |
| 1249 | if (not igd) { |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 1250 | if (logger_) logger_->error("IGD pointer is null"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1251 | return; |
| 1252 | } |
| 1253 | |
Adrien Beraud | 3bd61c9 | 2023-08-17 16:57:37 -0400 | [diff] [blame] | 1254 | updateMappingState(map, MappingState::FAILED); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1255 | unregisterMapping(map); |
| 1256 | |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 1257 | if (logger_) logger_->warn("Mapping request for {} failed on IGD {} [{}]", |
| 1258 | map->toString(), |
| 1259 | igd->toString(), |
| 1260 | igd->getProtocolName()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1261 | } |
| 1262 | |
Adrien Beraud | 3bd61c9 | 2023-08-17 16:57:37 -0400 | [diff] [blame] | 1263 | void |
| 1264 | UPnPContext::updateMappingState(const Mapping::sharedPtr_t& map, MappingState newState, bool notify) |
| 1265 | { |
| 1266 | // CHECK_VALID_THREAD(); |
| 1267 | |
| 1268 | assert(map); |
| 1269 | |
| 1270 | // Ignore if the state did not change. |
| 1271 | if (newState == map->getState()) { |
| 1272 | // JAMI_DBG("Mapping %s already in state %s", map->toString().c_str(), map->getStateStr()); |
| 1273 | return; |
| 1274 | } |
| 1275 | |
| 1276 | // Update the state. |
| 1277 | map->setState(newState); |
| 1278 | |
| 1279 | // Notify the listener if set. |
| 1280 | if (notify and map->getNotifyCallback()) |
| 1281 | map->getNotifyCallback()(map); |
| 1282 | } |
| 1283 | |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1284 | #if HAVE_LIBNATPMP |
| 1285 | void |
| 1286 | UPnPContext::renewAllocations() |
| 1287 | { |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 1288 | //CHECK_VALID_THREAD(); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1289 | |
| 1290 | // Check if the we have valid PMP IGD. |
| 1291 | auto pmpProto = protocolList_.at(NatProtocolType::NAT_PMP); |
| 1292 | |
| 1293 | auto now = sys_clock::now(); |
| 1294 | std::vector<Mapping::sharedPtr_t> toRenew; |
| 1295 | |
| 1296 | for (auto type : {PortType::TCP, PortType::UDP}) { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 1297 | std::lock_guard lock(mappingMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1298 | auto mappingList = getMappingList(type); |
| 1299 | for (auto const& [_, map] : mappingList) { |
| 1300 | if (not map->isValid()) |
| 1301 | continue; |
| 1302 | if (map->getProtocol() != NatProtocolType::NAT_PMP) |
| 1303 | continue; |
| 1304 | if (map->getState() != MappingState::OPEN) |
| 1305 | continue; |
| 1306 | if (now < map->getRenewalTime()) |
| 1307 | continue; |
| 1308 | |
| 1309 | toRenew.emplace_back(map); |
| 1310 | } |
| 1311 | } |
| 1312 | |
| 1313 | // Quit if there are no mapping to renew |
| 1314 | if (toRenew.empty()) |
| 1315 | return; |
| 1316 | |
| 1317 | for (auto const& map : toRenew) { |
| 1318 | pmpProto->requestMappingRenew(*map); |
| 1319 | } |
| 1320 | } |
| 1321 | #endif |
| 1322 | |
| 1323 | } // namespace upnp |
Sébastien Blin | 464bdff | 2023-07-19 08:02:53 -0400 | [diff] [blame] | 1324 | } // namespace dhtnet |