blob: e161a4394a67cf858250381c8bb244e1bc2017aa [file] [log] [blame]
Adrien Béraud612b55b2023-05-29 10:42:04 -04001/*
2 * Copyright (C) 2004-2023 Savoir-faire Linux Inc.
3 *
Adrien Béraudcb753622023-07-17 22:32:49 -04004 * This program is free software: you can redistribute it and/or modify
Adrien Béraud612b55b2023-05-29 10:42:04 -04005 * it under the terms of the GNU General Public License as published by
Adrien Béraudcb753622023-07-17 22:32:49 -04006 * the Free Software Foundation, either version 3 of the License, or
Adrien Béraud612b55b2023-05-29 10:42:04 -04007 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
Adrien Béraudcb753622023-07-17 22:32:49 -040011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
Adrien Béraud612b55b2023-05-29 10:42:04 -040012 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
Adrien Béraudcb753622023-07-17 22:32:49 -040015 * along with this program. If not, see <https://www.gnu.org/licenses/>.
Adrien Béraud612b55b2023-05-29 10:42:04 -040016 */
Morteza Namvar5f639522023-07-04 17:08:58 -040017#include "upnp/upnp_context.h"
Adrien Béraud25c30c42023-07-05 13:46:54 -040018#include "protocol/upnp_protocol.h"
19
Adrien Béraud370257c2023-08-15 20:53:09 -040020#if HAVE_LIBNATPMP
21#include "protocol/natpmp/nat_pmp.h"
22#endif
23#if HAVE_LIBUPNP
24#include "protocol/pupnp/pupnp.h"
25#endif
Amna7cd813c2023-10-02 18:15:47 -040026#include <asio.hpp>
Morteza Namvar5f639522023-07-04 17:08:58 -040027#include <asio/steady_timer.hpp>
Adrien Béraud9d350962023-07-13 15:36:32 -040028#if __has_include(<fmt/std.h>)
Adrien Béraud25c30c42023-07-05 13:46:54 -040029#include <fmt/std.h>
Adrien Béraud9d350962023-07-13 15:36:32 -040030#else
31#include <fmt/ostream.h>
32#endif
Adrien Béraud612b55b2023-05-29 10:42:04 -040033
Adrien Béraud1ae60aa2023-07-07 09:55:09 -040034namespace dhtnet {
Adrien Béraud612b55b2023-05-29 10:42:04 -040035namespace upnp {
36
37constexpr static auto MAP_UPDATE_INTERVAL = std::chrono::seconds(30);
38constexpr static int MAX_REQUEST_RETRIES = 20;
39constexpr static int MAX_REQUEST_REMOVE_COUNT = 5;
40
41constexpr static uint16_t UPNP_TCP_PORT_MIN {10000};
42constexpr static uint16_t UPNP_TCP_PORT_MAX {UPNP_TCP_PORT_MIN + 5000};
43constexpr static uint16_t UPNP_UDP_PORT_MIN {20000};
44constexpr static uint16_t UPNP_UDP_PORT_MAX {UPNP_UDP_PORT_MIN + 5000};
45
Sébastien Blin55abf072023-07-19 10:21:21 -040046UPnPContext::UPnPContext(const std::shared_ptr<asio::io_context>& ioContext, const std::shared_ptr<dht::log::Logger>& logger)
Adrien Béraudc36965c2023-08-17 21:50:27 -040047 : ctx(createIoContext(ioContext, logger))
Adrien Béraud91fd4b62023-08-29 20:50:01 -040048 , logger_(logger)
Adrien Béraud95219ef2023-08-17 21:55:37 -040049 , mappingListUpdateTimer_(*ctx)
50 , connectivityChangedTimer_(*ctx)
Adrien Béraud612b55b2023-05-29 10:42:04 -040051{
Adrien Beraud3bd61c92023-08-17 16:57:37 -040052 if (logger_) logger_->debug("Creating UPnPContext instance [{}]", fmt::ptr(this));
Adrien Béraud612b55b2023-05-29 10:42:04 -040053
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éraud370257c2023-08-15 20:53:09 -040058 ctx->post([this] { init(); });
Adrien Béraud612b55b2023-05-29 10:42:04 -040059}
60
Adrien Béraudb04fbd72023-08-17 19:56:11 -040061std::shared_ptr<asio::io_context>
62UPnPContext::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éraud612b55b2023-05-29 10:42:04 -040080void
81UPnPContext::shutdown(std::condition_variable& cv)
82{
Adrien Beraud3bd61c92023-08-17 16:57:37 -040083 if (logger_) logger_->debug("Shutdown UPnPContext instance [{}]", fmt::ptr(this));
Adrien Béraud612b55b2023-05-29 10:42:04 -040084
85 stopUpnp(true);
86
87 for (auto const& [_, proto] : protocolList_) {
88 proto->terminate();
89 }
90
Adrien Béraud024c46f2024-03-02 23:53:18 -050091 std::lock_guard lock(mappingMutex_);
Adrien Béraud91fd4b62023-08-29 20:50:01 -040092 mappingList_->clear();
93 mappingListUpdateTimer_.cancel();
94 controllerList_.clear();
95 protocolList_.clear();
96 shutdownComplete_ = true;
François-Simon Fauteux-Chapleau808db4f2024-04-19 11:39:47 -040097 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éraud91fd4b62023-08-29 20:50:01 -0400103 cv.notify_one();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400104}
105
106void
107UPnPContext::shutdown()
108{
Adrien Béraud024c46f2024-03-02 23:53:18 -0500109 std::unique_lock lk(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400110 std::condition_variable cv;
111
Adrien Béraud370257c2023-08-15 20:53:09 -0400112 ctx->post([&, this] { shutdown(cv); });
Sébastien Blin91cda3c2024-01-10 16:21:18 -0500113
Adrien Beraud3bd61c92023-08-17 16:57:37 -0400114 if (logger_) logger_->debug("Waiting for shutdown ...");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400115
116 if (cv.wait_for(lk, std::chrono::seconds(30), [this] { return shutdownComplete_; })) {
Adrien Beraud3bd61c92023-08-17 16:57:37 -0400117 if (logger_) logger_->debug("Shutdown completed");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400118 } else {
François-Simon Fauteux-Chapleau808db4f2024-04-19 11:39:47 -0400119 if (logger_) logger_->error("Shutdown timed out");
120 shutdownTimedOut_ = true;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400121 }
François-Simon Fauteux-Chapleau648907c2024-02-06 15:16:48 -0500122 // 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éraud91fd4b62023-08-29 20:50:01 -0400126
127 if (ioContextRunner_) {
Sébastien Blin91cda3c2024-01-10 16:21:18 -0500128 if (logger_) logger_->debug("UPnPContext: stopping io_context thread {}", fmt::ptr(this));
Adrien Béraud91fd4b62023-08-29 20:50:01 -0400129 ctx->stop();
130 ioContextRunner_->join();
131 ioContextRunner_.reset();
Sébastien Blin91cda3c2024-01-10 16:21:18 -0500132 if (logger_) logger_->debug("UPnPContext: stopping io_context thread - finished {}", fmt::ptr(this));
Adrien Béraud91fd4b62023-08-29 20:50:01 -0400133 }
Adrien Béraud612b55b2023-05-29 10:42:04 -0400134}
135
136UPnPContext::~UPnPContext()
137{
Adrien Beraud3bd61c92023-08-17 16:57:37 -0400138 if (logger_) logger_->debug("UPnPContext instance [{}] destroyed", fmt::ptr(this));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400139}
140
141void
142UPnPContext::init()
143{
Adrien Béraud612b55b2023-05-29 10:42:04 -0400144#if HAVE_LIBNATPMP
Adrien Béraud370257c2023-08-15 20:53:09 -0400145 auto natPmp = std::make_shared<NatPmp>(ctx, logger_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400146 natPmp->setObserver(this);
147 protocolList_.emplace(NatProtocolType::NAT_PMP, std::move(natPmp));
148#endif
149
150#if HAVE_LIBUPNP
Adrien Béraud370257c2023-08-15 20:53:09 -0400151 auto pupnp = std::make_shared<PUPnP>(ctx, logger_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400152 pupnp->setObserver(this);
153 protocolList_.emplace(NatProtocolType::PUPNP, std::move(pupnp));
154#endif
155}
156
157void
158UPnPContext::startUpnp()
159{
160 assert(not controllerList_.empty());
161
Adrien Beraud3bd61c92023-08-17 16:57:37 -0400162 if (logger_) logger_->debug("Starting UPNP context");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400163
164 // Request a new IGD search.
165 for (auto const& [_, protocol] : protocolList_) {
Adrien Béraud370257c2023-08-15 20:53:09 -0400166 ctx->dispatch([p=protocol] { p->searchForIgd(); });
Adrien Béraud612b55b2023-05-29 10:42:04 -0400167 }
168
169 started_ = true;
170}
171
172void
173UPnPContext::stopUpnp(bool forceRelease)
174{
François-Simon Fauteux-Chapleau808db4f2024-04-19 11:39:47 -0400175 if (logger_) logger_->debug("Stopping UPnP context");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400176
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éraud024c46f2024-03-02 23:53:18 -0500183 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400184
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éraud370257c2023-08-15 20:53:09 -0400199 // Notify is not needed in updateState when
Adrien Béraud612b55b2023-05-29 10:42:04 -0400200 // 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 Beraud3bd61c92023-08-17 16:57:37 -0400204 updateMappingState(map, MappingState::FAILED, false);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400205 // 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éraud370257c2023-08-15 20:53:09 -0400215 ctx->dispatch([p=protocol]{ p->clearIgds(); });
Adrien Béraud612b55b2023-05-29 10:42:04 -0400216 }
217
218 started_ = false;
219}
220
221uint16_t
222UPnPContext::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 Beraud3bd61c92023-08-17 16:57:37 -0400228 // if (logger_) logger_->error("Max port number ({}) must be greater than min port number ({})", maxPort, minPort);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400229 // 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
246void
247UPnPContext::connectivityChanged()
248{
Adrien Béraudc36965c2023-08-17 21:50:27 -0400249 // 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
254void
255UPnPContext::_connectivityChanged(const asio::error_code& ec)
256{
257 if (ec == asio::error::operation_aborted)
Adrien Béraud612b55b2023-05-29 10:42:04 -0400258 return;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400259
260 auto hostAddr = ip_utils::getLocalAddr(AF_INET);
261
Adrien Beraud3bd61c92023-08-17 16:57:37 -0400262 if (logger_) logger_->debug("Connectivity change check: host address {}", hostAddr.toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400263
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 Beraud3bd61c92023-08-17 16:57:37 -0400276 if (logger_) logger_->warn("Host address changed from {} to {}",
277 protocol->getHostAddress().toString(),
278 hostAddr.toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400279 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 Beraud3bd61c92023-08-17 16:57:37 -0400297 if (logger_) logger_->debug("Connectivity changed. Clear the IGDs and restart");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400298
299 stopUpnp();
300 startUpnp();
301
302 // Mapping with auto update enabled must be processed first.
303 processMappingWithAutoUpdate();
304}
305
306void
307UPnPContext::setPublicAddress(const IpAddr& addr)
308{
309 if (not addr)
310 return;
311
Adrien Béraud024c46f2024-03-02 23:53:18 -0500312 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400313 if (knownPublicAddress_ != addr) {
314 knownPublicAddress_ = std::move(addr);
Adrien Beraud3bd61c92023-08-17 16:57:37 -0400315 if (logger_) logger_->debug("Setting the known public address to {}", addr.toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400316 }
317}
318
319bool
320UPnPContext::isReady() const
321{
Adrien Béraud024c46f2024-03-02 23:53:18 -0500322 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400323 return not validIgdList_.empty();
324}
325
326IpAddr
327UPnPContext::getExternalIP() const
328{
Adrien Béraud024c46f2024-03-02 23:53:18 -0500329 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400330 // Return the first IGD Ip available.
331 if (not validIgdList_.empty()) {
332 return (*validIgdList_.begin())->getPublicIp();
333 }
334 return {};
335}
336
337Mapping::sharedPtr_t
338UPnPContext::reserveMapping(Mapping& requestedMap)
339{
340 auto desiredPort = requestedMap.getExternalPort();
341
342 if (desiredPort == 0) {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400343 if (logger_) logger_->debug("Desired port is not set, will provide the first available port for [{}]",
344 requestedMap.getTypeStr());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400345 } else {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400346 if (logger_) logger_->debug("Try to find mapping for port {:d} [{}]", desiredPort, requestedMap.getTypeStr());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400347 }
348
349 Mapping::sharedPtr_t mapRes;
350
351 {
Adrien Béraud024c46f2024-03-02 23:53:18 -0500352 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400353 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 Namvar5f639522023-07-04 17:08:58 -0400378 // JAMI_WARN("Did not find any available mapping. Will request one now");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400379 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
398void
399UPnPContext::releaseMapping(const Mapping& map)
400{
Adrien Béraudc36965c2023-08-17 21:50:27 -0400401 ctx->dispatch([this, map] {
Sébastien Blin91cda3c2024-01-10 16:21:18 -0500402 if (shutdownComplete_)
403 return;
Adrien Béraudc36965c2023-08-17 21:50:27 -0400404 auto mapPtr = getMappingWithKey(map.getMapKey());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400405
Adrien Béraudc36965c2023-08-17 21:50:27 -0400406 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éraud612b55b2023-05-29 10:42:04 -0400411
Adrien Béraudc36965c2023-08-17 21:50:27 -0400412 if (mapPtr->isAvailable()) {
413 if (logger_) logger_->warn("Trying to release an unused mapping {}", mapPtr->toString());
414 return;
415 }
Adrien Béraud612b55b2023-05-29 10:42:04 -0400416
Adrien Béraudc36965c2023-08-17 21:50:27 -0400417 // Remove it.
418 requestRemoveMapping(mapPtr);
419 unregisterMapping(mapPtr);
420 });
Adrien Béraud612b55b2023-05-29 10:42:04 -0400421}
422
423void
424UPnPContext::registerController(void* controller)
425{
426 {
Adrien Béraud024c46f2024-03-02 23:53:18 -0500427 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400428 if (shutdownComplete_) {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400429 if (logger_) logger_->warn("UPnPContext already shut down");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400430 return;
431 }
Adrien Béraudc36965c2023-08-17 21:50:27 -0400432 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éraud612b55b2023-05-29 10:42:04 -0400437 }
438
Adrien Berauda8731ac2023-08-17 12:19:39 -0400439 if (logger_) logger_->debug("Successfully registered controller {}", fmt::ptr(controller));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400440 if (not started_)
441 startUpnp();
442}
443
444void
445UPnPContext::unregisterController(void* controller)
446{
Sébastien Blin91cda3c2024-01-10 16:21:18 -0500447 if (shutdownComplete_)
448 return;
Adrien Béraud024c46f2024-03-02 23:53:18 -0500449 std::unique_lock lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400450 if (controllerList_.erase(controller) == 1) {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400451 if (logger_) logger_->debug("Successfully unregistered controller {}", fmt::ptr(controller));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400452 } else {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400453 if (logger_) logger_->debug("Controller {} was already removed", fmt::ptr(controller));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400454 }
455
456 if (controllerList_.empty()) {
Adrien Béraudc36965c2023-08-17 21:50:27 -0400457 lock.unlock();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400458 stopUpnp();
459 }
460}
461
François-Simon Fauteux-Chapleau826f0ba2024-05-29 15:22:21 -0400462std::vector<IGDInfo>
463UPnPContext::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éraud612b55b2023-05-29 10:42:04 -0400483uint16_t
484UPnPContext::getAvailablePortNumber(PortType type)
485{
486 // Only return an availalable random port. No actual
487 // reservation is made here.
488
Adrien Béraud024c46f2024-03-02 23:53:18 -0500489 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400490 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 Berauda8731ac2023-08-17 12:19:39 -0400500 if (logger_) logger_->error("Could not find an available port after %i trials", MAX_REQUEST_RETRIES);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400501 return 0;
502}
503
504void
505UPnPContext::requestMapping(const Mapping::sharedPtr_t& map)
506{
507 assert(map);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400508 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 Berauda8731ac2023-08-17 12:19:39 -0400514 if (logger_) logger_->debug("No valid IGDs available");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400515 return;
516 }
517
518 map->setIgd(igd);
519
Adrien Berauda8731ac2023-08-17 12:19:39 -0400520 if (logger_) logger_->debug("Request mapping {} using protocol [{}] IGD [{}]",
521 map->toString(),
522 igd->getProtocolName(),
523 igd->toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400524
Adrien Beraud3bd61c92023-08-17 16:57:37 -0400525 updateMappingState(map, MappingState::IN_PROGRESS);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400526
527 auto const& protocol = protocolList_.at(igd->getProtocol());
528 protocol->requestMappingAdd(*map);
529}
530
531bool
532UPnPContext::provisionNewMappings(PortType type, int portCount)
533{
Adrien Berauda8731ac2023-08-17 12:19:39 -0400534 if (logger_) logger_->debug("Provision {:d} new mappings of type [{}]", portCount, Mapping::getTypeStr(type));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400535
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 Berauda8731ac2023-08-17 12:19:39 -0400547 if (logger_) logger_->error("Can not find any available port to provision!");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400548 return false;
549 }
550 }
551
552 return true;
553}
554
555bool
556UPnPContext::deleteUnneededMappings(PortType type, int portCount)
557{
Adrien Berauda8731ac2023-08-17 12:19:39 -0400558 if (logger_) logger_->debug("Remove {:d} unneeded mapping of type [{}]", portCount, Mapping::getTypeStr(type));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400559
560 assert(portCount > 0);
561
Adrien Béraud370257c2023-08-15 20:53:09 -0400562 //CHECK_VALID_THREAD();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400563
Adrien Béraud024c46f2024-03-02 23:53:18 -0500564 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400565 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éraud370257c2023-08-15 20:53:09 -0400579 it = mappingList.erase(it);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400580 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éraud370257c2023-08-15 20:53:09 -0400586 it = mappingList.erase(it);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400587 } else {
588 it++;
589 }
590 }
591
592 return true;
593}
594
595void
596UPnPContext::updatePreferredIgd()
597{
Adrien Béraud612b55b2023-05-29 10:42:04 -0400598 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 Berauda8731ac2023-08-17 12:19:39 -0400622 if (logger_) logger_->debug("Preferred IGD updated to [{}] IGD [{} {}] ",
623 preferredIgd_->getProtocolName(),
624 preferredIgd_->getUID(),
625 preferredIgd_->toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400626 }
627}
628
629std::shared_ptr<IGD>
630UPnPContext::getPreferredIgd() const
631{
Adrien Béraud370257c2023-08-15 20:53:09 -0400632 //CHECK_VALID_THREAD();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400633
634 return preferredIgd_;
635}
636
637void
638UPnPContext::updateMappingList(bool async)
639{
640 // Run async if requested.
641 if (async) {
Adrien Béraud370257c2023-08-15 20:53:09 -0400642 ctx->post([this] { updateMappingList(false); });
Adrien Béraud612b55b2023-05-29 10:42:04 -0400643 return;
644 }
645
Adrien Béraud25c30c42023-07-05 13:46:54 -0400646 mappingListUpdateTimer_.cancel();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400647
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 Berauda8731ac2023-08-17 12:19:39 -0400655 if (logger_) logger_->debug("UPNP/NAT-PMP enabled, but no valid IGDs available");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400656 // No valid IGD. Nothing to do.
657 return;
658 }
659
Adrien Berauda8731ac2023-08-17 12:19:39 -0400660 mappingListUpdateTimer_.expires_after(MAP_UPDATE_INTERVAL);
Adrien Béraud25c30c42023-07-05 13:46:54 -0400661 mappingListUpdateTimer_.async_wait([this](asio::error_code const& ec) {
662 if (ec != asio::error::operation_aborted)
663 updateMappingList(false);
664 });
Adrien Béraud612b55b2023-05-29 10:42:04 -0400665
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 Berauda8731ac2023-08-17 12:19:39 -0400681 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éraud612b55b2023-05-29 10:42:04 -0400691
692 if (status.failedCount_ > 0) {
Adrien Béraud024c46f2024-03-02 23:53:18 -0500693 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400694 auto const& mappingList = getMappingList(type);
695 for (auto const& [_, map] : mappingList) {
696 if (map->getState() == MappingState::FAILED) {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400697 if (logger_) logger_->debug("Mapping status [{}] - Available [{}]",
698 map->toString(true),
699 map->isAvailable() ? "YES" : "NO");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400700 }
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
736void
737UPnPContext::pruneMappingList()
738{
Adrien Béraud370257c2023-08-15 20:53:09 -0400739 //CHECK_VALID_THREAD();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400740
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 Berauda0683d12023-08-22 18:09:02 -0400757 /*if (remoteMapList.empty()) {
Adrien Béraud024c46f2024-03-02 23:53:18 -0500758 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400759 if (not getMappingList(PortType::TCP).empty() or getMappingList(PortType::TCP).empty()) {
Morteza Namvar5f639522023-07-04 17:08:58 -0400760 // JAMI_WARN("We have provisionned mappings but the PUPNP IGD returned an empty list!");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400761 }
Adrien Berauda0683d12023-08-22 18:09:02 -0400762 }*/
Adrien Béraud612b55b2023-05-29 10:42:04 -0400763
764 pruneUnMatchedMappings(igd, remoteMapList);
765 pruneUnTrackedMappings(igd, remoteMapList);
766}
767
768void
769UPnPContext::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 Berauda0683d12023-08-22 18:09:02 -0400775 for (auto type: {PortType::TCP, PortType::UDP}) {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400776 // Use a temporary list to avoid processing mappings while holding the lock.
777 std::list<Mapping::sharedPtr_t> toRemoveList;
778 {
Adrien Béraud024c46f2024-03-02 23:53:18 -0500779 std::lock_guard lock(mappingMutex_);
Adrien Berauda0683d12023-08-22 18:09:02 -0400780 for (auto const& [_, map] : getMappingList(type)) {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400781 // 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 Berauda8731ac2023-08-17 12:19:39 -0400791 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éraud612b55b2023-05-29 10:42:04 -0400795 }
796 }
797 }
798
799 for (auto const& map : toRemoveList) {
Adrien Beraud3bd61c92023-08-17 16:57:37 -0400800 updateMappingState(map, MappingState::FAILED);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400801 unregisterMapping(map);
802 }
803 }
804}
805
806void
807UPnPContext::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éraud024c46f2024-03-02 23:53:18 -0500813 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400814
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
838void
839UPnPContext::pruneMappingsWithInvalidIgds(const std::shared_ptr<IGD>& igd)
840{
Adrien Béraud370257c2023-08-15 20:53:09 -0400841 //CHECK_VALID_THREAD();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400842
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éraud024c46f2024-03-02 23:53:18 -0500847 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400848
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 Berauda8731ac2023-08-17 12:19:39 -0400860 if (logger_) logger_->debug("Remove mapping {} (has an invalid IGD {} [{}])",
861 map->toString(),
862 igd->toString(),
863 igd->getProtocolName());
Adrien Béraud56740312023-08-23 08:38:28 -0400864 updateMappingState(map, MappingState::FAILED);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400865 unregisterMapping(map);
866 }
867}
868
869void
870UPnPContext::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éraud024c46f2024-03-02 23:53:18 -0500879 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400880 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 Berauda8731ac2023-08-17 12:19:39 -0400886 if (logger_) logger_->debug("Send pending request for mapping {} to IGD {}",
887 map->toString(),
888 igd->toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400889 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
901void
902UPnPContext::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éraud024c46f2024-03-02 23:53:18 -0500911 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400912 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 Berauda8731ac2023-08-17 12:19:39 -0400926 if (logger_) logger_->debug("Mapping {} has auto-update enabled, a new mapping will be requested",
927 oldMap->toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400928
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
945void
946UPnPContext::onIgdUpdated(const std::shared_ptr<IGD>& igd, UpnpIgdEvent event)
947{
948 assert(igd);
949
Adrien Béraud612b55b2023-05-29 10:42:04 -0400950 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 Berauda8731ac2023-08-17 12:19:39 -0400957 if (logger_) logger_->debug("New event for IGD [{} {}] [{}]: [{}]",
958 igd->getUID(),
959 igd->toString(),
960 protocolName,
961 IgdState);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400962
963 // Check if the IGD has valid addresses.
964 if (not igdLocalAddr) {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400965 if (logger_) logger_->warn("[{}] IGD has an invalid local address", protocolName);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400966 return;
967 }
968
969 if (not igd->getPublicIp()) {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400970 if (logger_) logger_->warn("[{}] IGD has an invalid public address", protocolName);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400971 return;
972 }
973
974 if (knownPublicAddress_ and igd->getPublicIp() != knownPublicAddress_) {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400975 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éraud612b55b2023-05-29 10:42:04 -0400980 }
981
François-Simon Fauteux-Chapleau5a9e8012024-06-04 11:39:17 -0400982 // Update the IGD list.
Adrien Béraud612b55b2023-05-29 10:42:04 -0400983 if (event == UpnpIgdEvent::REMOVED or event == UpnpIgdEvent::INVALID_STATE) {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400984 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éraud612b55b2023-05-29 10:42:04 -0400989
990 pruneMappingsWithInvalidIgds(igd);
991
Adrien Béraud024c46f2024-03-02 23:53:18 -0500992 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400993 validIgdList_.erase(igd);
François-Simon Fauteux-Chapleau5a9e8012024-06-04 11:39:17 -0400994 } else {
Adrien Béraud024c46f2024-03-02 23:53:18 -0500995 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400996 auto ret = validIgdList_.emplace(igd);
997 if (ret.second) {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400998 if (logger_) logger_->debug("IGD [{}] on address {} was added. Will process any pending requests",
999 protocolName,
1000 igdLocalAddr.toString(true, true));
Adrien Béraud612b55b2023-05-29 10:42:04 -04001001 } else {
1002 // Already in the list.
Adrien Berauda8731ac2023-08-17 12:19:39 -04001003 if (logger_) logger_->error("IGD [{}] on address {} already in the list",
1004 protocolName,
1005 igdLocalAddr.toString(true, true));
Adrien Béraud612b55b2023-05-29 10:42:04 -04001006 return;
1007 }
1008 }
1009
François-Simon Fauteux-Chapleau5a9e8012024-06-04 11:39:17 -04001010 updatePreferredIgd();
1011
Adrien Béraud612b55b2023-05-29 10:42:04 -04001012 // Update the provisionned mappings.
1013 updateMappingList(false);
1014}
1015
1016void
1017UPnPContext::onMappingAdded(const std::shared_ptr<IGD>& igd, const Mapping& mapRes)
1018{
Adrien Béraud370257c2023-08-15 20:53:09 -04001019 //CHECK_VALID_THREAD();
Adrien Béraud612b55b2023-05-29 10:42:04 -04001020
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 Berauda8731ac2023-08-17 12:19:39 -04001025 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éraud612b55b2023-05-29 10:42:04 -04001029 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 Beraud3bd61c92023-08-17 16:57:37 -04001038 updateMappingState(map, MappingState::OPEN);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001039
Adrien Berauda8731ac2023-08-17 12:19:39 -04001040 if (logger_) logger_->debug("Mapping {} (on IGD {} [{}]) successfully performed",
1041 map->toString(),
1042 igd->toString(),
1043 map->getProtocolName());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001044
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
1051void
1052UPnPContext::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 Berauda8731ac2023-08-17 12:19:39 -04001058 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éraud612b55b2023-05-29 10:42:04 -04001062 return;
1063 }
1064 if (mapPtr->getProtocol() != NatProtocolType::NAT_PMP or not mapPtr->isValid()
1065 or mapPtr->getState() != MappingState::OPEN) {
Adrien Berauda8731ac2023-08-17 12:19:39 -04001066 if (logger_) logger_->warn("Renewed mapping {} from IGD {} [{}] is in unexpected state",
1067 mapPtr->toString(),
1068 igd->toString(),
1069 mapPtr->getProtocolName());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001070 return;
1071 }
1072
1073 mapPtr->setRenewalTime(map.getRenewalTime());
1074}
1075#endif
1076
1077void
1078UPnPContext::requestRemoveMapping(const Mapping::sharedPtr_t& map)
1079{
Adrien Béraud370257c2023-08-15 20:53:09 -04001080 if (not map or not map->isValid()) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001081 // Silently ignore if the mapping is invalid
1082 return;
1083 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001084 auto protocol = protocolList_.at(map->getIgd()->getProtocol());
1085 protocol->requestMappingRemove(*map);
1086}
1087
1088void
1089UPnPContext::deleteAllMappings(PortType type)
1090{
Adrien Béraud024c46f2024-03-02 23:53:18 -05001091 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001092 auto& mappingList = getMappingList(type);
1093
1094 for (auto const& [_, map] : mappingList) {
1095 requestRemoveMapping(map);
1096 }
1097}
1098
1099void
1100UPnPContext::onMappingRemoved(const std::shared_ptr<IGD>& igd, const Mapping& mapRes)
1101{
1102 if (not mapRes.isValid())
1103 return;
1104
Adrien Béraud612b55b2023-05-29 10:42:04 -04001105 auto map = getMappingWithKey(mapRes.getMapKey());
1106 // Notify the listener.
1107 if (map and map->getNotifyCallback())
1108 map->getNotifyCallback()(map);
1109}
1110
1111Mapping::sharedPtr_t
1112UPnPContext::registerMapping(Mapping& map)
1113{
1114 if (map.getExternalPort() == 0) {
Morteza Namvar5f639522023-07-04 17:08:58 -04001115 // JAMI_DBG("Port number not set. Will set a random port number");
Adrien Béraud612b55b2023-05-29 10:42:04 -04001116 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éraud024c46f2024-03-02 23:53:18 -05001127 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001128 auto& mappingList = getMappingList(map.getType());
1129
1130 auto ret = mappingList.emplace(map.getMapKey(), std::make_shared<Mapping>(map));
1131 if (not ret.second) {
Adrien Berauda8731ac2023-08-17 12:19:39 -04001132 if (logger_) logger_->warn("Mapping request for {} already added!", map.toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001133 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 Berauda8731ac2023-08-17 12:19:39 -04001142 if (logger_) logger_->warn("No IGD available. Mapping will be requested when an IGD becomes available");
Adrien Béraud612b55b2023-05-29 10:42:04 -04001143 } else {
1144 requestMapping(mapPtr);
1145 }
1146
1147 return mapPtr;
1148}
1149
Adrien Béraud612b55b2023-05-29 10:42:04 -04001150void
1151UPnPContext::unregisterMapping(const Mapping::sharedPtr_t& map)
1152{
Adrien Béraud370257c2023-08-15 20:53:09 -04001153 //CHECK_VALID_THREAD();
Adrien Béraud612b55b2023-05-29 10:42:04 -04001154
1155 if (not map) {
Morteza Namvar5f639522023-07-04 17:08:58 -04001156 // JAMI_ERR("Mapping pointer is null");
Adrien Béraud612b55b2023-05-29 10:42:04 -04001157 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 Berauda8731ac2023-08-17 12:19:39 -04001167 if (logger_) logger_->debug("Unregistered mapping {}", map->toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001168 } else {
1169 // The mapping may already be un-registered. Just ignore it.
Adrien Berauda8731ac2023-08-17 12:19:39 -04001170 if (logger_) logger_->debug("Mapping {} [{}] does not have a local match",
1171 map->toString(),
1172 map->getProtocolName());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001173 }
1174}
1175
1176std::map<Mapping::key_t, Mapping::sharedPtr_t>&
1177UPnPContext::getMappingList(PortType type)
1178{
1179 unsigned typeIdx = type == PortType::TCP ? 0 : 1;
1180 return mappingList_[typeIdx];
1181}
1182
1183Mapping::sharedPtr_t
1184UPnPContext::getMappingWithKey(Mapping::key_t key)
1185{
Adrien Béraud024c46f2024-03-02 23:53:18 -05001186 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001187 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
1194void
1195UPnPContext::getMappingStatus(PortType type, MappingStatus& status)
1196{
Adrien Béraud024c46f2024-03-02 23:53:18 -05001197 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001198 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
1229void
1230UPnPContext::getMappingStatus(MappingStatus& status)
1231{
1232 getMappingStatus(PortType::TCP, status);
1233 getMappingStatus(PortType::UDP, status);
1234}
1235
1236void
1237UPnPContext::onMappingRequestFailed(const Mapping& mapRes)
1238{
Adrien Béraud612b55b2023-05-29 10:42:04 -04001239 auto const& map = getMappingWithKey(mapRes.getMapKey());
1240 if (not map) {
1241 // We may receive a response for a removed request. Just ignore it.
Adrien Berauda8731ac2023-08-17 12:19:39 -04001242 if (logger_) logger_->debug("Mapping {} [IGD {}] does not have a local match",
1243 mapRes.toString(),
1244 mapRes.getProtocolName());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001245 return;
1246 }
1247
1248 auto igd = map->getIgd();
1249 if (not igd) {
Adrien Berauda8731ac2023-08-17 12:19:39 -04001250 if (logger_) logger_->error("IGD pointer is null");
Adrien Béraud612b55b2023-05-29 10:42:04 -04001251 return;
1252 }
1253
Adrien Beraud3bd61c92023-08-17 16:57:37 -04001254 updateMappingState(map, MappingState::FAILED);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001255 unregisterMapping(map);
1256
Adrien Berauda8731ac2023-08-17 12:19:39 -04001257 if (logger_) logger_->warn("Mapping request for {} failed on IGD {} [{}]",
1258 map->toString(),
1259 igd->toString(),
1260 igd->getProtocolName());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001261}
1262
Adrien Beraud3bd61c92023-08-17 16:57:37 -04001263void
1264UPnPContext::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éraud612b55b2023-05-29 10:42:04 -04001284#if HAVE_LIBNATPMP
1285void
1286UPnPContext::renewAllocations()
1287{
Adrien Béraud370257c2023-08-15 20:53:09 -04001288 //CHECK_VALID_THREAD();
Adrien Béraud612b55b2023-05-29 10:42:04 -04001289
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éraud024c46f2024-03-02 23:53:18 -05001297 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001298 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 Blin464bdff2023-07-19 08:02:53 -04001324} // namespace dhtnet