blob: 78488dce959d44cfd7a09f09e33034233e05d3c4 [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
462uint16_t
463UPnPContext::getAvailablePortNumber(PortType type)
464{
465 // Only return an availalable random port. No actual
466 // reservation is made here.
467
Adrien Béraud024c46f2024-03-02 23:53:18 -0500468 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400469 auto& mappingList = getMappingList(type);
470 int tryCount = 0;
471 while (tryCount++ < MAX_REQUEST_RETRIES) {
472 uint16_t port = generateRandomPort(type);
473 Mapping map(type, port, port);
474 if (mappingList.find(map.getMapKey()) == mappingList.end())
475 return port;
476 }
477
478 // Very unlikely to get here.
Adrien Berauda8731ac2023-08-17 12:19:39 -0400479 if (logger_) logger_->error("Could not find an available port after %i trials", MAX_REQUEST_RETRIES);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400480 return 0;
481}
482
483void
484UPnPContext::requestMapping(const Mapping::sharedPtr_t& map)
485{
486 assert(map);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400487 auto const& igd = getPreferredIgd();
488 // We must have at least a valid IGD pointer if we get here.
489 // Not this method is called only if there were a valid IGD, however,
490 // because the processing is asynchronous, it's possible that the IGD
491 // was invalidated when the this code executed.
492 if (not igd) {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400493 if (logger_) logger_->debug("No valid IGDs available");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400494 return;
495 }
496
497 map->setIgd(igd);
498
Adrien Berauda8731ac2023-08-17 12:19:39 -0400499 if (logger_) logger_->debug("Request mapping {} using protocol [{}] IGD [{}]",
500 map->toString(),
501 igd->getProtocolName(),
502 igd->toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400503
Adrien Beraud3bd61c92023-08-17 16:57:37 -0400504 updateMappingState(map, MappingState::IN_PROGRESS);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400505
506 auto const& protocol = protocolList_.at(igd->getProtocol());
507 protocol->requestMappingAdd(*map);
508}
509
510bool
511UPnPContext::provisionNewMappings(PortType type, int portCount)
512{
Adrien Berauda8731ac2023-08-17 12:19:39 -0400513 if (logger_) logger_->debug("Provision {:d} new mappings of type [{}]", portCount, Mapping::getTypeStr(type));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400514
515 assert(portCount > 0);
516
517 while (portCount > 0) {
518 auto port = getAvailablePortNumber(type);
519 if (port > 0) {
520 // Found an available port number
521 portCount--;
522 Mapping map(type, port, port, true);
523 registerMapping(map);
524 } else {
525 // Very unlikely to get here!
Adrien Berauda8731ac2023-08-17 12:19:39 -0400526 if (logger_) logger_->error("Can not find any available port to provision!");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400527 return false;
528 }
529 }
530
531 return true;
532}
533
534bool
535UPnPContext::deleteUnneededMappings(PortType type, int portCount)
536{
Adrien Berauda8731ac2023-08-17 12:19:39 -0400537 if (logger_) logger_->debug("Remove {:d} unneeded mapping of type [{}]", portCount, Mapping::getTypeStr(type));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400538
539 assert(portCount > 0);
540
Adrien Béraud370257c2023-08-15 20:53:09 -0400541 //CHECK_VALID_THREAD();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400542
Adrien Béraud024c46f2024-03-02 23:53:18 -0500543 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400544 auto& mappingList = getMappingList(type);
545
546 for (auto it = mappingList.begin(); it != mappingList.end();) {
547 auto map = it->second;
548 assert(map);
549
550 if (not map->isAvailable()) {
551 it++;
552 continue;
553 }
554
555 if (map->getState() == MappingState::OPEN and portCount > 0) {
556 // Close portCount mappings in "OPEN" state.
557 requestRemoveMapping(map);
Adrien Béraud370257c2023-08-15 20:53:09 -0400558 it = mappingList.erase(it);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400559 portCount--;
560 } else if (map->getState() != MappingState::OPEN) {
561 // If this methods is called, it means there are more open
562 // mappings than required. So, all mappings in a state other
563 // than "OPEN" state (typically in in-progress state) will
564 // be deleted as well.
Adrien Béraud370257c2023-08-15 20:53:09 -0400565 it = mappingList.erase(it);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400566 } else {
567 it++;
568 }
569 }
570
571 return true;
572}
573
574void
575UPnPContext::updatePreferredIgd()
576{
Adrien Béraud370257c2023-08-15 20:53:09 -0400577 //CHECK_VALID_THREAD();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400578
579 if (preferredIgd_ and preferredIgd_->isValid())
580 return;
581
582 // Reset and search for the best IGD.
583 preferredIgd_.reset();
584
585 for (auto const& [_, protocol] : protocolList_) {
586 if (protocol->isReady()) {
587 auto igdList = protocol->getIgdList();
588 assert(not igdList.empty());
589 auto const& igd = igdList.front();
590 if (not igd->isValid())
591 continue;
592
593 // Prefer NAT-PMP over PUPNP.
594 if (preferredIgd_ and igd->getProtocol() != NatProtocolType::NAT_PMP)
595 continue;
596
597 // Update.
598 preferredIgd_ = igd;
599 }
600 }
601
602 if (preferredIgd_ and preferredIgd_->isValid()) {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400603 if (logger_) logger_->debug("Preferred IGD updated to [{}] IGD [{} {}] ",
604 preferredIgd_->getProtocolName(),
605 preferredIgd_->getUID(),
606 preferredIgd_->toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400607 }
608}
609
610std::shared_ptr<IGD>
611UPnPContext::getPreferredIgd() const
612{
Adrien Béraud370257c2023-08-15 20:53:09 -0400613 //CHECK_VALID_THREAD();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400614
615 return preferredIgd_;
616}
617
618void
619UPnPContext::updateMappingList(bool async)
620{
621 // Run async if requested.
622 if (async) {
Adrien Béraud370257c2023-08-15 20:53:09 -0400623 ctx->post([this] { updateMappingList(false); });
Adrien Béraud612b55b2023-05-29 10:42:04 -0400624 return;
625 }
626
Adrien Béraud370257c2023-08-15 20:53:09 -0400627 //CHECK_VALID_THREAD();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400628
629 // Update the preferred IGD.
630 updatePreferredIgd();
631
Adrien Béraud25c30c42023-07-05 13:46:54 -0400632 mappingListUpdateTimer_.cancel();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400633
634 // Skip if no controller registered.
635 if (controllerList_.empty())
636 return;
637
638 // Cancel the current timer (if any) and re-schedule.
639 std::shared_ptr<IGD> prefIgd = getPreferredIgd();
640 if (not prefIgd) {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400641 if (logger_) logger_->debug("UPNP/NAT-PMP enabled, but no valid IGDs available");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400642 // No valid IGD. Nothing to do.
643 return;
644 }
645
Adrien Berauda8731ac2023-08-17 12:19:39 -0400646 mappingListUpdateTimer_.expires_after(MAP_UPDATE_INTERVAL);
Adrien Béraud25c30c42023-07-05 13:46:54 -0400647 mappingListUpdateTimer_.async_wait([this](asio::error_code const& ec) {
648 if (ec != asio::error::operation_aborted)
649 updateMappingList(false);
650 });
Adrien Béraud612b55b2023-05-29 10:42:04 -0400651
652 // Process pending requests if any.
653 processPendingRequests(prefIgd);
654
655 // Make new requests for mappings that failed and have
656 // the auto-update option enabled.
657 processMappingWithAutoUpdate();
658
659 PortType typeArray[2] = {PortType::TCP, PortType::UDP};
660
661 for (auto idx : {0, 1}) {
662 auto type = typeArray[idx];
663
664 MappingStatus status;
665 getMappingStatus(type, status);
666
Adrien Berauda8731ac2023-08-17 12:19:39 -0400667 if (logger_) logger_->debug("Mapping status [{}] - overall {:d}: {:d} open ({:d} ready + {:d} in use), {:d} pending, {:d} "
668 "in-progress, {:d} failed",
669 Mapping::getTypeStr(type),
670 status.sum(),
671 status.openCount_,
672 status.readyCount_,
673 status.openCount_ - status.readyCount_,
674 status.pendingCount_,
675 status.inProgressCount_,
676 status.failedCount_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400677
678 if (status.failedCount_ > 0) {
Adrien Béraud024c46f2024-03-02 23:53:18 -0500679 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400680 auto const& mappingList = getMappingList(type);
681 for (auto const& [_, map] : mappingList) {
682 if (map->getState() == MappingState::FAILED) {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400683 if (logger_) logger_->debug("Mapping status [{}] - Available [{}]",
684 map->toString(true),
685 map->isAvailable() ? "YES" : "NO");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400686 }
687 }
688 }
689
690 int toRequestCount = (int) minOpenPortLimit_[idx]
691 - (int) (status.readyCount_ + status.inProgressCount_
692 + status.pendingCount_);
693
694 // Provision/release mappings accordingly.
695 if (toRequestCount > 0) {
696 // Take into account the request in-progress when making
697 // requests for new mappings.
698 provisionNewMappings(type, toRequestCount);
699 } else if (status.readyCount_ > maxOpenPortLimit_[idx]) {
700 deleteUnneededMappings(type, status.readyCount_ - maxOpenPortLimit_[idx]);
701 }
702 }
703
704 // Prune the mapping list if needed
705 if (protocolList_.at(NatProtocolType::PUPNP)->isReady()) {
706#if HAVE_LIBNATPMP
707 // Dont perform if NAT-PMP is valid.
708 if (not protocolList_.at(NatProtocolType::NAT_PMP)->isReady())
709#endif
710 {
711 pruneMappingList();
712 }
713 }
714
715#if HAVE_LIBNATPMP
716 // Renew nat-pmp allocations
717 if (protocolList_.at(NatProtocolType::NAT_PMP)->isReady())
718 renewAllocations();
719#endif
720}
721
722void
723UPnPContext::pruneMappingList()
724{
Adrien Béraud370257c2023-08-15 20:53:09 -0400725 //CHECK_VALID_THREAD();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400726
727 MappingStatus status;
728 getMappingStatus(status);
729
730 // Do not prune the list if there are pending/in-progress requests.
731 if (status.inProgressCount_ != 0 or status.pendingCount_ != 0) {
732 return;
733 }
734
735 auto const& igd = getPreferredIgd();
736 if (not igd or igd->getProtocol() != NatProtocolType::PUPNP) {
737 return;
738 }
739 auto protocol = protocolList_.at(NatProtocolType::PUPNP);
740
741 auto remoteMapList = protocol->getMappingsListByDescr(igd,
742 Mapping::UPNP_MAPPING_DESCRIPTION_PREFIX);
Adrien Berauda0683d12023-08-22 18:09:02 -0400743 /*if (remoteMapList.empty()) {
Adrien Béraud024c46f2024-03-02 23:53:18 -0500744 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400745 if (not getMappingList(PortType::TCP).empty() or getMappingList(PortType::TCP).empty()) {
Morteza Namvar5f639522023-07-04 17:08:58 -0400746 // JAMI_WARN("We have provisionned mappings but the PUPNP IGD returned an empty list!");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400747 }
Adrien Berauda0683d12023-08-22 18:09:02 -0400748 }*/
Adrien Béraud612b55b2023-05-29 10:42:04 -0400749
750 pruneUnMatchedMappings(igd, remoteMapList);
751 pruneUnTrackedMappings(igd, remoteMapList);
752}
753
754void
755UPnPContext::pruneUnMatchedMappings(const std::shared_ptr<IGD>& igd,
756 const std::map<Mapping::key_t, Mapping>& remoteMapList)
757{
758 // Check/synchronize local mapping list with the list
759 // returned by the IGD.
760
Adrien Berauda0683d12023-08-22 18:09:02 -0400761 for (auto type: {PortType::TCP, PortType::UDP}) {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400762 // Use a temporary list to avoid processing mappings while holding the lock.
763 std::list<Mapping::sharedPtr_t> toRemoveList;
764 {
Adrien Béraud024c46f2024-03-02 23:53:18 -0500765 std::lock_guard lock(mappingMutex_);
Adrien Berauda0683d12023-08-22 18:09:02 -0400766 for (auto const& [_, map] : getMappingList(type)) {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400767 // Only check mappings allocated by UPNP protocol.
768 if (map->getProtocol() != NatProtocolType::PUPNP) {
769 continue;
770 }
771 // Set mapping as failed if not found in the list
772 // returned by the IGD.
773 if (map->getState() == MappingState::OPEN
774 and remoteMapList.find(map->getMapKey()) == remoteMapList.end()) {
775 toRemoveList.emplace_back(map);
776
Adrien Berauda8731ac2023-08-17 12:19:39 -0400777 if (logger_) logger_->warn("Mapping {} (IGD {}) marked as \"OPEN\" but not found in the "
778 "remote list. Mark as failed!",
779 map->toString(),
780 igd->toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400781 }
782 }
783 }
784
785 for (auto const& map : toRemoveList) {
Adrien Beraud3bd61c92023-08-17 16:57:37 -0400786 updateMappingState(map, MappingState::FAILED);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400787 unregisterMapping(map);
788 }
789 }
790}
791
792void
793UPnPContext::pruneUnTrackedMappings(const std::shared_ptr<IGD>& igd,
794 const std::map<Mapping::key_t, Mapping>& remoteMapList)
795{
796 // Use a temporary list to avoid processing mappings while holding the lock.
797 std::list<Mapping> toRemoveList;
798 {
Adrien Béraud024c46f2024-03-02 23:53:18 -0500799 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400800
801 for (auto const& [_, map] : remoteMapList) {
802 // Must has valid IGD pointer and use UPNP protocol.
803 assert(map.getIgd());
804 assert(map.getIgd()->getProtocol() == NatProtocolType::PUPNP);
805 auto& mappingList = getMappingList(map.getType());
806 auto it = mappingList.find(map.getMapKey());
807 if (it == mappingList.end()) {
808 // Not present, request mapping remove.
809 toRemoveList.emplace_back(std::move(map));
810 // Make only few remove requests at once.
811 if (toRemoveList.size() >= MAX_REQUEST_REMOVE_COUNT)
812 break;
813 }
814 }
815 }
816
817 // Remove un-tracked mappings.
818 auto protocol = protocolList_.at(NatProtocolType::PUPNP);
819 for (auto const& map : toRemoveList) {
820 protocol->requestMappingRemove(map);
821 }
822}
823
824void
825UPnPContext::pruneMappingsWithInvalidIgds(const std::shared_ptr<IGD>& igd)
826{
Adrien Béraud370257c2023-08-15 20:53:09 -0400827 //CHECK_VALID_THREAD();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400828
829 // Use temporary list to avoid holding the lock while
830 // processing the mapping list.
831 std::list<Mapping::sharedPtr_t> toRemoveList;
832 {
Adrien Béraud024c46f2024-03-02 23:53:18 -0500833 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400834
835 PortType types[2] {PortType::TCP, PortType::UDP};
836 for (auto& type : types) {
837 auto& mappingList = getMappingList(type);
838 for (auto const& [_, map] : mappingList) {
839 if (map->getIgd() == igd)
840 toRemoveList.emplace_back(map);
841 }
842 }
843 }
844
845 for (auto const& map : toRemoveList) {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400846 if (logger_) logger_->debug("Remove mapping {} (has an invalid IGD {} [{}])",
847 map->toString(),
848 igd->toString(),
849 igd->getProtocolName());
Adrien Béraud56740312023-08-23 08:38:28 -0400850 updateMappingState(map, MappingState::FAILED);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400851 unregisterMapping(map);
852 }
853}
854
855void
856UPnPContext::processPendingRequests(const std::shared_ptr<IGD>& igd)
857{
858 // This list holds the mappings to be requested. This is
859 // needed to avoid performing the requests while holding
860 // the lock.
861 std::list<Mapping::sharedPtr_t> requestsList;
862
863 // Populate the list of requests to perform.
864 {
Adrien Béraud024c46f2024-03-02 23:53:18 -0500865 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400866 PortType typeArray[2] {PortType::TCP, PortType::UDP};
867
868 for (auto type : typeArray) {
869 auto& mappingList = getMappingList(type);
870 for (auto& [_, map] : mappingList) {
871 if (map->getState() == MappingState::PENDING) {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400872 if (logger_) logger_->debug("Send pending request for mapping {} to IGD {}",
873 map->toString(),
874 igd->toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400875 requestsList.emplace_back(map);
876 }
877 }
878 }
879 }
880
881 // Process the pending requests.
882 for (auto const& map : requestsList) {
883 requestMapping(map);
884 }
885}
886
887void
888UPnPContext::processMappingWithAutoUpdate()
889{
890 // This list holds the mappings to be requested. This is
891 // needed to avoid performing the requests while holding
892 // the lock.
893 std::list<Mapping::sharedPtr_t> requestsList;
894
895 // Populate the list of requests for mappings with auto-update enabled.
896 {
Adrien Béraud024c46f2024-03-02 23:53:18 -0500897 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400898 PortType typeArray[2] {PortType::TCP, PortType::UDP};
899
900 for (auto type : typeArray) {
901 auto& mappingList = getMappingList(type);
902 for (auto const& [_, map] : mappingList) {
903 if (map->getState() == MappingState::FAILED and map->getAutoUpdate()) {
904 requestsList.emplace_back(map);
905 }
906 }
907 }
908 }
909
910 for (auto const& oldMap : requestsList) {
911 // Request a new mapping if auto-update is enabled.
Adrien Berauda8731ac2023-08-17 12:19:39 -0400912 if (logger_) logger_->debug("Mapping {} has auto-update enabled, a new mapping will be requested",
913 oldMap->toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400914
915 // Reserve a new mapping.
916 Mapping newMapping(oldMap->getType());
917 newMapping.enableAutoUpdate(true);
918 newMapping.setNotifyCallback(oldMap->getNotifyCallback());
919
920 auto const& mapPtr = reserveMapping(newMapping);
921 assert(mapPtr);
922
923 // Release the old one.
924 oldMap->setAvailable(true);
925 oldMap->enableAutoUpdate(false);
926 oldMap->setNotifyCallback(nullptr);
927 unregisterMapping(oldMap);
928 }
929}
930
931void
932UPnPContext::onIgdUpdated(const std::shared_ptr<IGD>& igd, UpnpIgdEvent event)
933{
934 assert(igd);
935
Adrien Béraud612b55b2023-05-29 10:42:04 -0400936 // Reset to start search for a new best IGD.
937 preferredIgd_.reset();
938
939 char const* IgdState = event == UpnpIgdEvent::ADDED ? "ADDED"
940 : event == UpnpIgdEvent::REMOVED ? "REMOVED"
941 : "INVALID";
942
943 auto const& igdLocalAddr = igd->getLocalIp();
944 auto protocolName = igd->getProtocolName();
945
Adrien Berauda8731ac2023-08-17 12:19:39 -0400946 if (logger_) logger_->debug("New event for IGD [{} {}] [{}]: [{}]",
947 igd->getUID(),
948 igd->toString(),
949 protocolName,
950 IgdState);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400951
952 // Check if the IGD has valid addresses.
953 if (not igdLocalAddr) {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400954 if (logger_) logger_->warn("[{}] IGD has an invalid local address", protocolName);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400955 return;
956 }
957
958 if (not igd->getPublicIp()) {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400959 if (logger_) logger_->warn("[{}] IGD has an invalid public address", protocolName);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400960 return;
961 }
962
963 if (knownPublicAddress_ and igd->getPublicIp() != knownPublicAddress_) {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400964 if (logger_) logger_->warn("[{}] IGD external address [{}] does not match known public address [{}]."
965 " The mapped addresses might not be reachable",
966 protocolName,
967 igd->getPublicIp().toString(),
968 knownPublicAddress_.toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400969 }
970
971 // The IGD was removed or is invalid.
972 if (event == UpnpIgdEvent::REMOVED or event == UpnpIgdEvent::INVALID_STATE) {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400973 if (logger_) logger_->warn("State of IGD [{} {}] [{}] changed to [{}]. Pruning the mapping list",
974 igd->getUID(),
975 igd->toString(),
976 protocolName,
977 IgdState);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400978
979 pruneMappingsWithInvalidIgds(igd);
980
Adrien Béraud024c46f2024-03-02 23:53:18 -0500981 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400982 validIgdList_.erase(igd);
983 return;
984 }
985
986 // Update the IGD list.
987 {
Adrien Béraud024c46f2024-03-02 23:53:18 -0500988 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400989 auto ret = validIgdList_.emplace(igd);
990 if (ret.second) {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400991 if (logger_) logger_->debug("IGD [{}] on address {} was added. Will process any pending requests",
992 protocolName,
993 igdLocalAddr.toString(true, true));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400994 } else {
995 // Already in the list.
Adrien Berauda8731ac2023-08-17 12:19:39 -0400996 if (logger_) logger_->error("IGD [{}] on address {} already in the list",
997 protocolName,
998 igdLocalAddr.toString(true, true));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400999 return;
1000 }
1001 }
1002
1003 // Update the provisionned mappings.
1004 updateMappingList(false);
1005}
1006
1007void
1008UPnPContext::onMappingAdded(const std::shared_ptr<IGD>& igd, const Mapping& mapRes)
1009{
Adrien Béraud370257c2023-08-15 20:53:09 -04001010 //CHECK_VALID_THREAD();
Adrien Béraud612b55b2023-05-29 10:42:04 -04001011
1012 // Check if we have a pending request for this response.
1013 auto map = getMappingWithKey(mapRes.getMapKey());
1014 if (not map) {
1015 // We may receive a response for a canceled request. Just ignore it.
Adrien Berauda8731ac2023-08-17 12:19:39 -04001016 if (logger_) logger_->debug("Response for mapping {} [IGD {}] [{}] does not have a local match",
1017 mapRes.toString(),
1018 igd->toString(),
1019 mapRes.getProtocolName());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001020 return;
1021 }
1022
1023 // The mapping request is new and successful. Update.
1024 map->setIgd(igd);
1025 map->setInternalAddress(mapRes.getInternalAddress());
1026 map->setExternalPort(mapRes.getExternalPort());
1027
1028 // Update the state and report to the owner.
Adrien Beraud3bd61c92023-08-17 16:57:37 -04001029 updateMappingState(map, MappingState::OPEN);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001030
Adrien Berauda8731ac2023-08-17 12:19:39 -04001031 if (logger_) logger_->debug("Mapping {} (on IGD {} [{}]) successfully performed",
1032 map->toString(),
1033 igd->toString(),
1034 map->getProtocolName());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001035
1036 // Call setValid() to reset the errors counter. We need
1037 // to reset the counter on each successful response.
1038 igd->setValid(true);
1039}
1040
1041#if HAVE_LIBNATPMP
1042void
1043UPnPContext::onMappingRenewed(const std::shared_ptr<IGD>& igd, const Mapping& map)
1044{
1045 auto mapPtr = getMappingWithKey(map.getMapKey());
1046
1047 if (not mapPtr) {
1048 // We may receive a notification for a canceled request. Ignore it.
Adrien Berauda8731ac2023-08-17 12:19:39 -04001049 if (logger_) logger_->warn("Renewed mapping {} from IGD {} [{}] does not have a match in local list",
1050 map.toString(),
1051 igd->toString(),
1052 map.getProtocolName());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001053 return;
1054 }
1055 if (mapPtr->getProtocol() != NatProtocolType::NAT_PMP or not mapPtr->isValid()
1056 or mapPtr->getState() != MappingState::OPEN) {
Adrien Berauda8731ac2023-08-17 12:19:39 -04001057 if (logger_) logger_->warn("Renewed mapping {} from IGD {} [{}] is in unexpected state",
1058 mapPtr->toString(),
1059 igd->toString(),
1060 mapPtr->getProtocolName());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001061 return;
1062 }
1063
1064 mapPtr->setRenewalTime(map.getRenewalTime());
1065}
1066#endif
1067
1068void
1069UPnPContext::requestRemoveMapping(const Mapping::sharedPtr_t& map)
1070{
Adrien Béraud370257c2023-08-15 20:53:09 -04001071 if (not map or not map->isValid()) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001072 // Silently ignore if the mapping is invalid
1073 return;
1074 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001075 auto protocol = protocolList_.at(map->getIgd()->getProtocol());
1076 protocol->requestMappingRemove(*map);
1077}
1078
1079void
1080UPnPContext::deleteAllMappings(PortType type)
1081{
Adrien Béraud024c46f2024-03-02 23:53:18 -05001082 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001083 auto& mappingList = getMappingList(type);
1084
1085 for (auto const& [_, map] : mappingList) {
1086 requestRemoveMapping(map);
1087 }
1088}
1089
1090void
1091UPnPContext::onMappingRemoved(const std::shared_ptr<IGD>& igd, const Mapping& mapRes)
1092{
1093 if (not mapRes.isValid())
1094 return;
1095
Adrien Béraud612b55b2023-05-29 10:42:04 -04001096 auto map = getMappingWithKey(mapRes.getMapKey());
1097 // Notify the listener.
1098 if (map and map->getNotifyCallback())
1099 map->getNotifyCallback()(map);
1100}
1101
1102Mapping::sharedPtr_t
1103UPnPContext::registerMapping(Mapping& map)
1104{
1105 if (map.getExternalPort() == 0) {
Morteza Namvar5f639522023-07-04 17:08:58 -04001106 // JAMI_DBG("Port number not set. Will set a random port number");
Adrien Béraud612b55b2023-05-29 10:42:04 -04001107 auto port = getAvailablePortNumber(map.getType());
1108 map.setExternalPort(port);
1109 map.setInternalPort(port);
1110 }
1111
1112 // Newly added mapping must be in pending state by default.
1113 map.setState(MappingState::PENDING);
1114
1115 Mapping::sharedPtr_t mapPtr;
1116
1117 {
Adrien Béraud024c46f2024-03-02 23:53:18 -05001118 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001119 auto& mappingList = getMappingList(map.getType());
1120
1121 auto ret = mappingList.emplace(map.getMapKey(), std::make_shared<Mapping>(map));
1122 if (not ret.second) {
Adrien Berauda8731ac2023-08-17 12:19:39 -04001123 if (logger_) logger_->warn("Mapping request for {} already added!", map.toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001124 return {};
1125 }
1126 mapPtr = ret.first->second;
1127 assert(mapPtr);
1128 }
1129
1130 // No available IGD. The pending mapping requests will be processed
1131 // when a IGD becomes available (in onIgdAdded() method).
1132 if (not isReady()) {
Adrien Berauda8731ac2023-08-17 12:19:39 -04001133 if (logger_) logger_->warn("No IGD available. Mapping will be requested when an IGD becomes available");
Adrien Béraud612b55b2023-05-29 10:42:04 -04001134 } else {
1135 requestMapping(mapPtr);
1136 }
1137
1138 return mapPtr;
1139}
1140
Adrien Béraud612b55b2023-05-29 10:42:04 -04001141void
1142UPnPContext::unregisterMapping(const Mapping::sharedPtr_t& map)
1143{
Adrien Béraud370257c2023-08-15 20:53:09 -04001144 //CHECK_VALID_THREAD();
Adrien Béraud612b55b2023-05-29 10:42:04 -04001145
1146 if (not map) {
Morteza Namvar5f639522023-07-04 17:08:58 -04001147 // JAMI_ERR("Mapping pointer is null");
Adrien Béraud612b55b2023-05-29 10:42:04 -04001148 return;
1149 }
1150
1151 if (map->getAutoUpdate()) {
1152 // Dont unregister mappings with auto-update enabled.
1153 return;
1154 }
1155 auto& mappingList = getMappingList(map->getType());
1156
1157 if (mappingList.erase(map->getMapKey()) == 1) {
Adrien Berauda8731ac2023-08-17 12:19:39 -04001158 if (logger_) logger_->debug("Unregistered mapping {}", map->toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001159 } else {
1160 // The mapping may already be un-registered. Just ignore it.
Adrien Berauda8731ac2023-08-17 12:19:39 -04001161 if (logger_) logger_->debug("Mapping {} [{}] does not have a local match",
1162 map->toString(),
1163 map->getProtocolName());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001164 }
1165}
1166
1167std::map<Mapping::key_t, Mapping::sharedPtr_t>&
1168UPnPContext::getMappingList(PortType type)
1169{
1170 unsigned typeIdx = type == PortType::TCP ? 0 : 1;
1171 return mappingList_[typeIdx];
1172}
1173
1174Mapping::sharedPtr_t
1175UPnPContext::getMappingWithKey(Mapping::key_t key)
1176{
Adrien Béraud024c46f2024-03-02 23:53:18 -05001177 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001178 auto const& mappingList = getMappingList(Mapping::getTypeFromMapKey(key));
1179 auto it = mappingList.find(key);
1180 if (it == mappingList.end())
1181 return nullptr;
1182 return it->second;
1183}
1184
1185void
1186UPnPContext::getMappingStatus(PortType type, MappingStatus& status)
1187{
Adrien Béraud024c46f2024-03-02 23:53:18 -05001188 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001189 auto& mappingList = getMappingList(type);
1190
1191 for (auto const& [_, map] : mappingList) {
1192 switch (map->getState()) {
1193 case MappingState::PENDING: {
1194 status.pendingCount_++;
1195 break;
1196 }
1197 case MappingState::IN_PROGRESS: {
1198 status.inProgressCount_++;
1199 break;
1200 }
1201 case MappingState::FAILED: {
1202 status.failedCount_++;
1203 break;
1204 }
1205 case MappingState::OPEN: {
1206 status.openCount_++;
1207 if (map->isAvailable())
1208 status.readyCount_++;
1209 break;
1210 }
1211
1212 default:
1213 // Must not get here.
1214 assert(false);
1215 break;
1216 }
1217 }
1218}
1219
1220void
1221UPnPContext::getMappingStatus(MappingStatus& status)
1222{
1223 getMappingStatus(PortType::TCP, status);
1224 getMappingStatus(PortType::UDP, status);
1225}
1226
1227void
1228UPnPContext::onMappingRequestFailed(const Mapping& mapRes)
1229{
Adrien Béraud612b55b2023-05-29 10:42:04 -04001230 auto const& map = getMappingWithKey(mapRes.getMapKey());
1231 if (not map) {
1232 // We may receive a response for a removed request. Just ignore it.
Adrien Berauda8731ac2023-08-17 12:19:39 -04001233 if (logger_) logger_->debug("Mapping {} [IGD {}] does not have a local match",
1234 mapRes.toString(),
1235 mapRes.getProtocolName());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001236 return;
1237 }
1238
1239 auto igd = map->getIgd();
1240 if (not igd) {
Adrien Berauda8731ac2023-08-17 12:19:39 -04001241 if (logger_) logger_->error("IGD pointer is null");
Adrien Béraud612b55b2023-05-29 10:42:04 -04001242 return;
1243 }
1244
Adrien Beraud3bd61c92023-08-17 16:57:37 -04001245 updateMappingState(map, MappingState::FAILED);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001246 unregisterMapping(map);
1247
Adrien Berauda8731ac2023-08-17 12:19:39 -04001248 if (logger_) logger_->warn("Mapping request for {} failed on IGD {} [{}]",
1249 map->toString(),
1250 igd->toString(),
1251 igd->getProtocolName());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001252}
1253
Adrien Beraud3bd61c92023-08-17 16:57:37 -04001254void
1255UPnPContext::updateMappingState(const Mapping::sharedPtr_t& map, MappingState newState, bool notify)
1256{
1257 // CHECK_VALID_THREAD();
1258
1259 assert(map);
1260
1261 // Ignore if the state did not change.
1262 if (newState == map->getState()) {
1263 // JAMI_DBG("Mapping %s already in state %s", map->toString().c_str(), map->getStateStr());
1264 return;
1265 }
1266
1267 // Update the state.
1268 map->setState(newState);
1269
1270 // Notify the listener if set.
1271 if (notify and map->getNotifyCallback())
1272 map->getNotifyCallback()(map);
1273}
1274
Adrien Béraud612b55b2023-05-29 10:42:04 -04001275#if HAVE_LIBNATPMP
1276void
1277UPnPContext::renewAllocations()
1278{
Adrien Béraud370257c2023-08-15 20:53:09 -04001279 //CHECK_VALID_THREAD();
Adrien Béraud612b55b2023-05-29 10:42:04 -04001280
1281 // Check if the we have valid PMP IGD.
1282 auto pmpProto = protocolList_.at(NatProtocolType::NAT_PMP);
1283
1284 auto now = sys_clock::now();
1285 std::vector<Mapping::sharedPtr_t> toRenew;
1286
1287 for (auto type : {PortType::TCP, PortType::UDP}) {
Adrien Béraud024c46f2024-03-02 23:53:18 -05001288 std::lock_guard lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001289 auto mappingList = getMappingList(type);
1290 for (auto const& [_, map] : mappingList) {
1291 if (not map->isValid())
1292 continue;
1293 if (map->getProtocol() != NatProtocolType::NAT_PMP)
1294 continue;
1295 if (map->getState() != MappingState::OPEN)
1296 continue;
1297 if (now < map->getRenewalTime())
1298 continue;
1299
1300 toRenew.emplace_back(map);
1301 }
1302 }
1303
1304 // Quit if there are no mapping to renew
1305 if (toRenew.empty())
1306 return;
1307
1308 for (auto const& map : toRenew) {
1309 pmpProto->requestMappingRenew(*map);
1310 }
1311}
1312#endif
1313
1314} // namespace upnp
Sébastien Blin464bdff2023-07-19 08:02:53 -04001315} // namespace dhtnet