blob: 56fa607aa470cf3a2a0081453fc39fabeb340ee0 [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
26
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éraud95219ef2023-08-17 21:55:37 -040048 , mappingListUpdateTimer_(*ctx)
49 , connectivityChangedTimer_(*ctx)
Adrien Béraudc36965c2023-08-17 21:50:27 -040050 , logger_(logger)
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
91 {
92 std::lock_guard<std::mutex> lock(mappingMutex_);
93 mappingList_->clear();
Adrien Béraud25c30c42023-07-05 13:46:54 -040094 mappingListUpdateTimer_.cancel();
Adrien Béraud612b55b2023-05-29 10:42:04 -040095 controllerList_.clear();
96 protocolList_.clear();
97 shutdownComplete_ = true;
98 cv.notify_one();
99 }
Adrien Béraudb04fbd72023-08-17 19:56:11 -0400100
101 if (ioContextRunner_) {
102 if (logger_) logger_->debug("UPnPContext: stopping io_context thread");
103 ctx->stop();
104 ioContextRunner_->join();
105 ioContextRunner_.reset();
106 }
Adrien Béraud612b55b2023-05-29 10:42:04 -0400107}
108
109void
110UPnPContext::shutdown()
111{
112 std::unique_lock<std::mutex> lk(mappingMutex_);
113 std::condition_variable cv;
114
Adrien Béraud370257c2023-08-15 20:53:09 -0400115 ctx->post([&, this] { shutdown(cv); });
116
Adrien Beraud3bd61c92023-08-17 16:57:37 -0400117 if (logger_) logger_->debug("Waiting for shutdown ...");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400118
119 if (cv.wait_for(lk, std::chrono::seconds(30), [this] { return shutdownComplete_; })) {
Adrien Beraud3bd61c92023-08-17 16:57:37 -0400120 if (logger_) logger_->debug("Shutdown completed");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400121 } else {
Adrien Beraud3bd61c92023-08-17 16:57:37 -0400122 if (logger_) logger_->error("Shutdown timed-out");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400123 }
124}
125
126UPnPContext::~UPnPContext()
127{
Adrien Beraud3bd61c92023-08-17 16:57:37 -0400128 if (logger_) logger_->debug("UPnPContext instance [{}] destroyed", fmt::ptr(this));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400129}
130
131void
132UPnPContext::init()
133{
Adrien Béraud612b55b2023-05-29 10:42:04 -0400134#if HAVE_LIBNATPMP
Adrien Béraud370257c2023-08-15 20:53:09 -0400135 auto natPmp = std::make_shared<NatPmp>(ctx, logger_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400136 natPmp->setObserver(this);
137 protocolList_.emplace(NatProtocolType::NAT_PMP, std::move(natPmp));
138#endif
139
140#if HAVE_LIBUPNP
Adrien Béraud370257c2023-08-15 20:53:09 -0400141 auto pupnp = std::make_shared<PUPnP>(ctx, logger_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400142 pupnp->setObserver(this);
143 protocolList_.emplace(NatProtocolType::PUPNP, std::move(pupnp));
144#endif
145}
146
147void
148UPnPContext::startUpnp()
149{
150 assert(not controllerList_.empty());
151
Adrien Beraud3bd61c92023-08-17 16:57:37 -0400152 if (logger_) logger_->debug("Starting UPNP context");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400153
154 // Request a new IGD search.
155 for (auto const& [_, protocol] : protocolList_) {
Adrien Béraud370257c2023-08-15 20:53:09 -0400156 ctx->dispatch([p=protocol] { p->searchForIgd(); });
Adrien Béraud612b55b2023-05-29 10:42:04 -0400157 }
158
159 started_ = true;
160}
161
162void
163UPnPContext::stopUpnp(bool forceRelease)
164{
Adrien Béraud370257c2023-08-15 20:53:09 -0400165 /*if (not isValidThread()) {
166 ctx->post([this, forceRelease] { stopUpnp(forceRelease); });
Adrien Béraud612b55b2023-05-29 10:42:04 -0400167 return;
Adrien Béraud370257c2023-08-15 20:53:09 -0400168 }*/
Adrien Béraud612b55b2023-05-29 10:42:04 -0400169
Adrien Beraud3bd61c92023-08-17 16:57:37 -0400170 if (logger_) logger_->debug("Stopping UPNP context");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400171
172 // Clear all current mappings if any.
173
174 // Use a temporary list to avoid processing the mapping
175 // list while holding the lock.
176 std::list<Mapping::sharedPtr_t> toRemoveList;
177 {
178 std::lock_guard<std::mutex> lock(mappingMutex_);
179
180 PortType types[2] {PortType::TCP, PortType::UDP};
181 for (auto& type : types) {
182 auto& mappingList = getMappingList(type);
183 for (auto const& [_, map] : mappingList) {
184 toRemoveList.emplace_back(map);
185 }
186 }
187 // Invalidate the current IGDs.
188 preferredIgd_.reset();
189 validIgdList_.clear();
190 }
191 for (auto const& map : toRemoveList) {
192 requestRemoveMapping(map);
193
Adrien Béraud370257c2023-08-15 20:53:09 -0400194 // Notify is not needed in updateState when
Adrien Béraud612b55b2023-05-29 10:42:04 -0400195 // shutting down (hence set it to false). NotifyCallback
196 // would trigger a new SIP registration and create a
197 // false registered state upon program close.
198 // It's handled by upper layers.
Adrien Beraud3bd61c92023-08-17 16:57:37 -0400199 updateMappingState(map, MappingState::FAILED, false);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400200 // We dont remove mappings with auto-update enabled,
201 // unless forceRelease is true.
202 if (not map->getAutoUpdate() or forceRelease) {
203 map->enableAutoUpdate(false);
204 unregisterMapping(map);
205 }
206 }
207
208 // Clear all current IGDs.
209 for (auto const& [_, protocol] : protocolList_) {
Adrien Béraud370257c2023-08-15 20:53:09 -0400210 ctx->dispatch([p=protocol]{ p->clearIgds(); });
Adrien Béraud612b55b2023-05-29 10:42:04 -0400211 }
212
213 started_ = false;
214}
215
216uint16_t
217UPnPContext::generateRandomPort(PortType type, bool mustBeEven)
218{
219 auto minPort = type == PortType::TCP ? UPNP_TCP_PORT_MIN : UPNP_UDP_PORT_MIN;
220 auto maxPort = type == PortType::TCP ? UPNP_TCP_PORT_MAX : UPNP_UDP_PORT_MAX;
221
222 if (minPort >= maxPort) {
Adrien Beraud3bd61c92023-08-17 16:57:37 -0400223 // if (logger_) logger_->error("Max port number ({}) must be greater than min port number ({})", maxPort, minPort);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400224 // Must be called with valid range.
225 assert(false);
226 }
227
228 int fact = mustBeEven ? 2 : 1;
229 if (mustBeEven) {
230 minPort /= fact;
231 maxPort /= fact;
232 }
233
234 // Seed the generator.
235 static std::mt19937 gen(dht::crypto::getSeededRandomEngine());
236 // Define the range.
237 std::uniform_int_distribution<uint16_t> dist(minPort, maxPort);
238 return dist(gen) * fact;
239}
240
241void
242UPnPContext::connectivityChanged()
243{
Adrien Béraudc36965c2023-08-17 21:50:27 -0400244 // Debounce the connectivity change notification.
245 connectivityChangedTimer_.expires_after(std::chrono::milliseconds(50));
246 connectivityChangedTimer_.async_wait(std::bind(&UPnPContext::_connectivityChanged, this, std::placeholders::_1));
247}
248
249void
250UPnPContext::_connectivityChanged(const asio::error_code& ec)
251{
252 if (ec == asio::error::operation_aborted)
Adrien Béraud612b55b2023-05-29 10:42:04 -0400253 return;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400254
255 auto hostAddr = ip_utils::getLocalAddr(AF_INET);
256
Adrien Beraud3bd61c92023-08-17 16:57:37 -0400257 if (logger_) logger_->debug("Connectivity change check: host address {}", hostAddr.toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400258
259 auto restartUpnp = false;
260
261 // On reception of "connectivity change" notification, the UPNP search
262 // will be restarted if either there is no valid IGD, or the IGD address
263 // changed.
264
265 if (not isReady()) {
266 restartUpnp = true;
267 } else {
268 // Check if the host address changed.
269 for (auto const& [_, protocol] : protocolList_) {
270 if (protocol->isReady() and hostAddr != protocol->getHostAddress()) {
Adrien Beraud3bd61c92023-08-17 16:57:37 -0400271 if (logger_) logger_->warn("Host address changed from {} to {}",
272 protocol->getHostAddress().toString(),
273 hostAddr.toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400274 protocol->clearIgds();
275 restartUpnp = true;
276 break;
277 }
278 }
279 }
280
281 // We have at least one valid IGD and the host address did
282 // not change, so no need to restart.
283 if (not restartUpnp) {
284 return;
285 }
286
287 // No registered controller. A new search will be performed when
288 // a controller is registered.
289 if (controllerList_.empty())
290 return;
291
Adrien Beraud3bd61c92023-08-17 16:57:37 -0400292 if (logger_) logger_->debug("Connectivity changed. Clear the IGDs and restart");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400293
294 stopUpnp();
295 startUpnp();
296
297 // Mapping with auto update enabled must be processed first.
298 processMappingWithAutoUpdate();
299}
300
301void
302UPnPContext::setPublicAddress(const IpAddr& addr)
303{
304 if (not addr)
305 return;
306
307 std::lock_guard<std::mutex> lock(mappingMutex_);
308 if (knownPublicAddress_ != addr) {
309 knownPublicAddress_ = std::move(addr);
Adrien Beraud3bd61c92023-08-17 16:57:37 -0400310 if (logger_) logger_->debug("Setting the known public address to {}", addr.toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400311 }
312}
313
314bool
315UPnPContext::isReady() const
316{
317 std::lock_guard<std::mutex> lock(mappingMutex_);
318 return not validIgdList_.empty();
319}
320
321IpAddr
322UPnPContext::getExternalIP() const
323{
324 std::lock_guard<std::mutex> lock(mappingMutex_);
325 // Return the first IGD Ip available.
326 if (not validIgdList_.empty()) {
327 return (*validIgdList_.begin())->getPublicIp();
328 }
329 return {};
330}
331
332Mapping::sharedPtr_t
333UPnPContext::reserveMapping(Mapping& requestedMap)
334{
335 auto desiredPort = requestedMap.getExternalPort();
336
337 if (desiredPort == 0) {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400338 if (logger_) logger_->debug("Desired port is not set, will provide the first available port for [{}]",
339 requestedMap.getTypeStr());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400340 } else {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400341 if (logger_) logger_->debug("Try to find mapping for port {:d} [{}]", desiredPort, requestedMap.getTypeStr());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400342 }
343
344 Mapping::sharedPtr_t mapRes;
345
346 {
347 std::lock_guard<std::mutex> lock(mappingMutex_);
348 auto& mappingList = getMappingList(requestedMap.getType());
349
350 // We try to provide a mapping in "OPEN" state. If not found,
351 // we provide any available mapping. In this case, it's up to
352 // the caller to use it or not.
353 for (auto const& [_, map] : mappingList) {
354 // If the desired port is null, we pick the first available port.
355 if (map->isValid() and (desiredPort == 0 or map->getExternalPort() == desiredPort)
356 and map->isAvailable()) {
357 // Considere the first available mapping regardless of its
358 // state. A mapping with OPEN state will be used if found.
359 if (not mapRes)
360 mapRes = map;
361
362 if (map->getState() == MappingState::OPEN) {
363 // Found an "OPEN" mapping. We are done.
364 mapRes = map;
365 break;
366 }
367 }
368 }
369 }
370
371 // Create a mapping if none was available.
372 if (not mapRes) {
Morteza Namvar5f639522023-07-04 17:08:58 -0400373 // JAMI_WARN("Did not find any available mapping. Will request one now");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400374 mapRes = registerMapping(requestedMap);
375 }
376
377 if (mapRes) {
378 // Make the mapping unavailable
379 mapRes->setAvailable(false);
380 // Copy attributes.
381 mapRes->setNotifyCallback(requestedMap.getNotifyCallback());
382 mapRes->enableAutoUpdate(requestedMap.getAutoUpdate());
383 // Notify the listener.
384 if (auto cb = mapRes->getNotifyCallback())
385 cb(mapRes);
386 }
387
388 updateMappingList(true);
389
390 return mapRes;
391}
392
393void
394UPnPContext::releaseMapping(const Mapping& map)
395{
Adrien Béraudc36965c2023-08-17 21:50:27 -0400396 ctx->dispatch([this, map] {
397 auto mapPtr = getMappingWithKey(map.getMapKey());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400398
Adrien Béraudc36965c2023-08-17 21:50:27 -0400399 if (not mapPtr) {
400 // Might happen if the mapping failed or was never granted.
401 if (logger_) logger_->debug("Mapping {} does not exist or was already removed", map.toString());
402 return;
403 }
Adrien Béraud612b55b2023-05-29 10:42:04 -0400404
Adrien Béraudc36965c2023-08-17 21:50:27 -0400405 if (mapPtr->isAvailable()) {
406 if (logger_) logger_->warn("Trying to release an unused mapping {}", mapPtr->toString());
407 return;
408 }
Adrien Béraud612b55b2023-05-29 10:42:04 -0400409
Adrien Béraudc36965c2023-08-17 21:50:27 -0400410 // Remove it.
411 requestRemoveMapping(mapPtr);
412 unregisterMapping(mapPtr);
413 });
Adrien Béraud612b55b2023-05-29 10:42:04 -0400414}
415
416void
417UPnPContext::registerController(void* controller)
418{
419 {
420 std::lock_guard<std::mutex> lock(mappingMutex_);
421 if (shutdownComplete_) {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400422 if (logger_) logger_->warn("UPnPContext already shut down");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400423 return;
424 }
Adrien Béraudc36965c2023-08-17 21:50:27 -0400425 auto ret = controllerList_.emplace(controller);
426 if (not ret.second) {
427 if (logger_) logger_->warn("Controller {} is already registered", fmt::ptr(controller));
428 return;
429 }
Adrien Béraud612b55b2023-05-29 10:42:04 -0400430 }
431
Adrien Berauda8731ac2023-08-17 12:19:39 -0400432 if (logger_) logger_->debug("Successfully registered controller {}", fmt::ptr(controller));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400433 if (not started_)
434 startUpnp();
435}
436
437void
438UPnPContext::unregisterController(void* controller)
439{
Adrien Béraudc36965c2023-08-17 21:50:27 -0400440 std::unique_lock<std::mutex> lock(mappingMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400441 if (controllerList_.erase(controller) == 1) {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400442 if (logger_) logger_->debug("Successfully unregistered controller {}", fmt::ptr(controller));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400443 } else {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400444 if (logger_) logger_->debug("Controller {} was already removed", fmt::ptr(controller));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400445 }
446
447 if (controllerList_.empty()) {
Adrien Béraudc36965c2023-08-17 21:50:27 -0400448 lock.unlock();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400449 stopUpnp();
450 }
451}
452
453uint16_t
454UPnPContext::getAvailablePortNumber(PortType type)
455{
456 // Only return an availalable random port. No actual
457 // reservation is made here.
458
459 std::lock_guard<std::mutex> lock(mappingMutex_);
460 auto& mappingList = getMappingList(type);
461 int tryCount = 0;
462 while (tryCount++ < MAX_REQUEST_RETRIES) {
463 uint16_t port = generateRandomPort(type);
464 Mapping map(type, port, port);
465 if (mappingList.find(map.getMapKey()) == mappingList.end())
466 return port;
467 }
468
469 // Very unlikely to get here.
Adrien Berauda8731ac2023-08-17 12:19:39 -0400470 if (logger_) logger_->error("Could not find an available port after %i trials", MAX_REQUEST_RETRIES);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400471 return 0;
472}
473
474void
475UPnPContext::requestMapping(const Mapping::sharedPtr_t& map)
476{
477 assert(map);
478
Adrien Béraud370257c2023-08-15 20:53:09 -0400479 /*if (not isValidThread()) {
480 ctx->post([this, map] { requestMapping(map); });
Adrien Béraud612b55b2023-05-29 10:42:04 -0400481 return;
Adrien Béraud370257c2023-08-15 20:53:09 -0400482 }*/
Adrien Béraud612b55b2023-05-29 10:42:04 -0400483
484 auto const& igd = getPreferredIgd();
485 // We must have at least a valid IGD pointer if we get here.
486 // Not this method is called only if there were a valid IGD, however,
487 // because the processing is asynchronous, it's possible that the IGD
488 // was invalidated when the this code executed.
489 if (not igd) {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400490 if (logger_) logger_->debug("No valid IGDs available");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400491 return;
492 }
493
494 map->setIgd(igd);
495
Adrien Berauda8731ac2023-08-17 12:19:39 -0400496 if (logger_) logger_->debug("Request mapping {} using protocol [{}] IGD [{}]",
497 map->toString(),
498 igd->getProtocolName(),
499 igd->toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400500
Adrien Beraud3bd61c92023-08-17 16:57:37 -0400501 updateMappingState(map, MappingState::IN_PROGRESS);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400502
503 auto const& protocol = protocolList_.at(igd->getProtocol());
504 protocol->requestMappingAdd(*map);
505}
506
507bool
508UPnPContext::provisionNewMappings(PortType type, int portCount)
509{
Adrien Berauda8731ac2023-08-17 12:19:39 -0400510 if (logger_) logger_->debug("Provision {:d} new mappings of type [{}]", portCount, Mapping::getTypeStr(type));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400511
512 assert(portCount > 0);
513
514 while (portCount > 0) {
515 auto port = getAvailablePortNumber(type);
516 if (port > 0) {
517 // Found an available port number
518 portCount--;
519 Mapping map(type, port, port, true);
520 registerMapping(map);
521 } else {
522 // Very unlikely to get here!
Adrien Berauda8731ac2023-08-17 12:19:39 -0400523 if (logger_) logger_->error("Can not find any available port to provision!");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400524 return false;
525 }
526 }
527
528 return true;
529}
530
531bool
532UPnPContext::deleteUnneededMappings(PortType type, int portCount)
533{
Adrien Berauda8731ac2023-08-17 12:19:39 -0400534 if (logger_) logger_->debug("Remove {:d} unneeded mapping of type [{}]", portCount, Mapping::getTypeStr(type));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400535
536 assert(portCount > 0);
537
Adrien Béraud370257c2023-08-15 20:53:09 -0400538 //CHECK_VALID_THREAD();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400539
540 std::lock_guard<std::mutex> lock(mappingMutex_);
541 auto& mappingList = getMappingList(type);
542
543 for (auto it = mappingList.begin(); it != mappingList.end();) {
544 auto map = it->second;
545 assert(map);
546
547 if (not map->isAvailable()) {
548 it++;
549 continue;
550 }
551
552 if (map->getState() == MappingState::OPEN and portCount > 0) {
553 // Close portCount mappings in "OPEN" state.
554 requestRemoveMapping(map);
Adrien Béraud370257c2023-08-15 20:53:09 -0400555 it = mappingList.erase(it);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400556 portCount--;
557 } else if (map->getState() != MappingState::OPEN) {
558 // If this methods is called, it means there are more open
559 // mappings than required. So, all mappings in a state other
560 // than "OPEN" state (typically in in-progress state) will
561 // be deleted as well.
Adrien Béraud370257c2023-08-15 20:53:09 -0400562 it = mappingList.erase(it);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400563 } else {
564 it++;
565 }
566 }
567
568 return true;
569}
570
571void
572UPnPContext::updatePreferredIgd()
573{
Adrien Béraud370257c2023-08-15 20:53:09 -0400574 //CHECK_VALID_THREAD();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400575
576 if (preferredIgd_ and preferredIgd_->isValid())
577 return;
578
579 // Reset and search for the best IGD.
580 preferredIgd_.reset();
581
582 for (auto const& [_, protocol] : protocolList_) {
583 if (protocol->isReady()) {
584 auto igdList = protocol->getIgdList();
585 assert(not igdList.empty());
586 auto const& igd = igdList.front();
587 if (not igd->isValid())
588 continue;
589
590 // Prefer NAT-PMP over PUPNP.
591 if (preferredIgd_ and igd->getProtocol() != NatProtocolType::NAT_PMP)
592 continue;
593
594 // Update.
595 preferredIgd_ = igd;
596 }
597 }
598
599 if (preferredIgd_ and preferredIgd_->isValid()) {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400600 if (logger_) logger_->debug("Preferred IGD updated to [{}] IGD [{} {}] ",
601 preferredIgd_->getProtocolName(),
602 preferredIgd_->getUID(),
603 preferredIgd_->toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400604 }
605}
606
607std::shared_ptr<IGD>
608UPnPContext::getPreferredIgd() const
609{
Adrien Béraud370257c2023-08-15 20:53:09 -0400610 //CHECK_VALID_THREAD();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400611
612 return preferredIgd_;
613}
614
615void
616UPnPContext::updateMappingList(bool async)
617{
618 // Run async if requested.
619 if (async) {
Adrien Béraud370257c2023-08-15 20:53:09 -0400620 ctx->post([this] { updateMappingList(false); });
Adrien Béraud612b55b2023-05-29 10:42:04 -0400621 return;
622 }
623
Adrien Béraud370257c2023-08-15 20:53:09 -0400624 //CHECK_VALID_THREAD();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400625
626 // Update the preferred IGD.
627 updatePreferredIgd();
628
Adrien Béraud25c30c42023-07-05 13:46:54 -0400629 mappingListUpdateTimer_.cancel();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400630
631 // Skip if no controller registered.
632 if (controllerList_.empty())
633 return;
634
635 // Cancel the current timer (if any) and re-schedule.
636 std::shared_ptr<IGD> prefIgd = getPreferredIgd();
637 if (not prefIgd) {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400638 if (logger_) logger_->debug("UPNP/NAT-PMP enabled, but no valid IGDs available");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400639 // No valid IGD. Nothing to do.
640 return;
641 }
642
Adrien Berauda8731ac2023-08-17 12:19:39 -0400643 mappingListUpdateTimer_.expires_after(MAP_UPDATE_INTERVAL);
Adrien Béraud25c30c42023-07-05 13:46:54 -0400644 mappingListUpdateTimer_.async_wait([this](asio::error_code const& ec) {
645 if (ec != asio::error::operation_aborted)
646 updateMappingList(false);
647 });
Adrien Béraud612b55b2023-05-29 10:42:04 -0400648
649 // Process pending requests if any.
650 processPendingRequests(prefIgd);
651
652 // Make new requests for mappings that failed and have
653 // the auto-update option enabled.
654 processMappingWithAutoUpdate();
655
656 PortType typeArray[2] = {PortType::TCP, PortType::UDP};
657
658 for (auto idx : {0, 1}) {
659 auto type = typeArray[idx];
660
661 MappingStatus status;
662 getMappingStatus(type, status);
663
Adrien Berauda8731ac2023-08-17 12:19:39 -0400664 if (logger_) logger_->debug("Mapping status [{}] - overall {:d}: {:d} open ({:d} ready + {:d} in use), {:d} pending, {:d} "
665 "in-progress, {:d} failed",
666 Mapping::getTypeStr(type),
667 status.sum(),
668 status.openCount_,
669 status.readyCount_,
670 status.openCount_ - status.readyCount_,
671 status.pendingCount_,
672 status.inProgressCount_,
673 status.failedCount_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400674
675 if (status.failedCount_ > 0) {
676 std::lock_guard<std::mutex> lock(mappingMutex_);
677 auto const& mappingList = getMappingList(type);
678 for (auto const& [_, map] : mappingList) {
679 if (map->getState() == MappingState::FAILED) {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400680 if (logger_) logger_->debug("Mapping status [{}] - Available [{}]",
681 map->toString(true),
682 map->isAvailable() ? "YES" : "NO");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400683 }
684 }
685 }
686
687 int toRequestCount = (int) minOpenPortLimit_[idx]
688 - (int) (status.readyCount_ + status.inProgressCount_
689 + status.pendingCount_);
690
691 // Provision/release mappings accordingly.
692 if (toRequestCount > 0) {
693 // Take into account the request in-progress when making
694 // requests for new mappings.
695 provisionNewMappings(type, toRequestCount);
696 } else if (status.readyCount_ > maxOpenPortLimit_[idx]) {
697 deleteUnneededMappings(type, status.readyCount_ - maxOpenPortLimit_[idx]);
698 }
699 }
700
701 // Prune the mapping list if needed
702 if (protocolList_.at(NatProtocolType::PUPNP)->isReady()) {
703#if HAVE_LIBNATPMP
704 // Dont perform if NAT-PMP is valid.
705 if (not protocolList_.at(NatProtocolType::NAT_PMP)->isReady())
706#endif
707 {
708 pruneMappingList();
709 }
710 }
711
712#if HAVE_LIBNATPMP
713 // Renew nat-pmp allocations
714 if (protocolList_.at(NatProtocolType::NAT_PMP)->isReady())
715 renewAllocations();
716#endif
717}
718
719void
720UPnPContext::pruneMappingList()
721{
Adrien Béraud370257c2023-08-15 20:53:09 -0400722 //CHECK_VALID_THREAD();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400723
724 MappingStatus status;
725 getMappingStatus(status);
726
727 // Do not prune the list if there are pending/in-progress requests.
728 if (status.inProgressCount_ != 0 or status.pendingCount_ != 0) {
729 return;
730 }
731
732 auto const& igd = getPreferredIgd();
733 if (not igd or igd->getProtocol() != NatProtocolType::PUPNP) {
734 return;
735 }
736 auto protocol = protocolList_.at(NatProtocolType::PUPNP);
737
738 auto remoteMapList = protocol->getMappingsListByDescr(igd,
739 Mapping::UPNP_MAPPING_DESCRIPTION_PREFIX);
740 if (remoteMapList.empty()) {
741 std::lock_guard<std::mutex> lock(mappingMutex_);
742 if (not getMappingList(PortType::TCP).empty() or getMappingList(PortType::TCP).empty()) {
Morteza Namvar5f639522023-07-04 17:08:58 -0400743 // JAMI_WARN("We have provisionned mappings but the PUPNP IGD returned an empty list!");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400744 }
745 }
746
747 pruneUnMatchedMappings(igd, remoteMapList);
748 pruneUnTrackedMappings(igd, remoteMapList);
749}
750
751void
752UPnPContext::pruneUnMatchedMappings(const std::shared_ptr<IGD>& igd,
753 const std::map<Mapping::key_t, Mapping>& remoteMapList)
754{
755 // Check/synchronize local mapping list with the list
756 // returned by the IGD.
757
758 PortType types[2] {PortType::TCP, PortType::UDP};
759
760 for (auto& type : types) {
761 // Use a temporary list to avoid processing mappings while holding the lock.
762 std::list<Mapping::sharedPtr_t> toRemoveList;
763 {
764 std::lock_guard<std::mutex> lock(mappingMutex_);
765 auto& mappingList = getMappingList(type);
766 for (auto const& [_, map] : mappingList) {
767 // 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 {
799 std::lock_guard<std::mutex> lock(mappingMutex_);
800
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 {
833 std::lock_guard<std::mutex> lock(mappingMutex_);
834
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éraud370257c2023-08-15 20:53:09 -0400850 map->updateState(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 {
865 std::lock_guard<std::mutex> lock(mappingMutex_);
866 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 {
897 std::lock_guard<std::mutex> lock(mappingMutex_);
898 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éraud370257c2023-08-15 20:53:09 -0400936 /*if (not isValidThread()) {
937 ctx->post([this, igd, event] { onIgdUpdated(igd, event); });
Adrien Béraud612b55b2023-05-29 10:42:04 -0400938 return;
Adrien Béraud370257c2023-08-15 20:53:09 -0400939 }*/
Adrien Béraud612b55b2023-05-29 10:42:04 -0400940
941 // Reset to start search for a new best IGD.
942 preferredIgd_.reset();
943
944 char const* IgdState = event == UpnpIgdEvent::ADDED ? "ADDED"
945 : event == UpnpIgdEvent::REMOVED ? "REMOVED"
946 : "INVALID";
947
948 auto const& igdLocalAddr = igd->getLocalIp();
949 auto protocolName = igd->getProtocolName();
950
Adrien Berauda8731ac2023-08-17 12:19:39 -0400951 if (logger_) logger_->debug("New event for IGD [{} {}] [{}]: [{}]",
952 igd->getUID(),
953 igd->toString(),
954 protocolName,
955 IgdState);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400956
957 // Check if the IGD has valid addresses.
958 if (not igdLocalAddr) {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400959 if (logger_) logger_->warn("[{}] IGD has an invalid local address", protocolName);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400960 return;
961 }
962
963 if (not igd->getPublicIp()) {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400964 if (logger_) logger_->warn("[{}] IGD has an invalid public address", protocolName);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400965 return;
966 }
967
968 if (knownPublicAddress_ and igd->getPublicIp() != knownPublicAddress_) {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400969 if (logger_) logger_->warn("[{}] IGD external address [{}] does not match known public address [{}]."
970 " The mapped addresses might not be reachable",
971 protocolName,
972 igd->getPublicIp().toString(),
973 knownPublicAddress_.toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400974 }
975
976 // The IGD was removed or is invalid.
977 if (event == UpnpIgdEvent::REMOVED or event == UpnpIgdEvent::INVALID_STATE) {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400978 if (logger_) logger_->warn("State of IGD [{} {}] [{}] changed to [{}]. Pruning the mapping list",
979 igd->getUID(),
980 igd->toString(),
981 protocolName,
982 IgdState);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400983
984 pruneMappingsWithInvalidIgds(igd);
985
986 std::lock_guard<std::mutex> lock(mappingMutex_);
987 validIgdList_.erase(igd);
988 return;
989 }
990
991 // Update the IGD list.
992 {
993 std::lock_guard<std::mutex> lock(mappingMutex_);
994 auto ret = validIgdList_.emplace(igd);
995 if (ret.second) {
Adrien Berauda8731ac2023-08-17 12:19:39 -0400996 if (logger_) logger_->debug("IGD [{}] on address {} was added. Will process any pending requests",
997 protocolName,
998 igdLocalAddr.toString(true, true));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400999 } else {
1000 // Already in the list.
Adrien Berauda8731ac2023-08-17 12:19:39 -04001001 if (logger_) logger_->error("IGD [{}] on address {} already in the list",
1002 protocolName,
1003 igdLocalAddr.toString(true, true));
Adrien Béraud612b55b2023-05-29 10:42:04 -04001004 return;
1005 }
1006 }
1007
1008 // Update the provisionned mappings.
1009 updateMappingList(false);
1010}
1011
1012void
1013UPnPContext::onMappingAdded(const std::shared_ptr<IGD>& igd, const Mapping& mapRes)
1014{
Adrien Béraud370257c2023-08-15 20:53:09 -04001015 //CHECK_VALID_THREAD();
Adrien Béraud612b55b2023-05-29 10:42:04 -04001016
1017 // Check if we have a pending request for this response.
1018 auto map = getMappingWithKey(mapRes.getMapKey());
1019 if (not map) {
1020 // We may receive a response for a canceled request. Just ignore it.
Adrien Berauda8731ac2023-08-17 12:19:39 -04001021 if (logger_) logger_->debug("Response for mapping {} [IGD {}] [{}] does not have a local match",
1022 mapRes.toString(),
1023 igd->toString(),
1024 mapRes.getProtocolName());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001025 return;
1026 }
1027
1028 // The mapping request is new and successful. Update.
1029 map->setIgd(igd);
1030 map->setInternalAddress(mapRes.getInternalAddress());
1031 map->setExternalPort(mapRes.getExternalPort());
1032
1033 // Update the state and report to the owner.
Adrien Beraud3bd61c92023-08-17 16:57:37 -04001034 updateMappingState(map, MappingState::OPEN);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001035
Adrien Berauda8731ac2023-08-17 12:19:39 -04001036 if (logger_) logger_->debug("Mapping {} (on IGD {} [{}]) successfully performed",
1037 map->toString(),
1038 igd->toString(),
1039 map->getProtocolName());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001040
1041 // Call setValid() to reset the errors counter. We need
1042 // to reset the counter on each successful response.
1043 igd->setValid(true);
1044}
1045
1046#if HAVE_LIBNATPMP
1047void
1048UPnPContext::onMappingRenewed(const std::shared_ptr<IGD>& igd, const Mapping& map)
1049{
1050 auto mapPtr = getMappingWithKey(map.getMapKey());
1051
1052 if (not mapPtr) {
1053 // We may receive a notification for a canceled request. Ignore it.
Adrien Berauda8731ac2023-08-17 12:19:39 -04001054 if (logger_) logger_->warn("Renewed mapping {} from IGD {} [{}] does not have a match in local list",
1055 map.toString(),
1056 igd->toString(),
1057 map.getProtocolName());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001058 return;
1059 }
1060 if (mapPtr->getProtocol() != NatProtocolType::NAT_PMP or not mapPtr->isValid()
1061 or mapPtr->getState() != MappingState::OPEN) {
Adrien Berauda8731ac2023-08-17 12:19:39 -04001062 if (logger_) logger_->warn("Renewed mapping {} from IGD {} [{}] is in unexpected state",
1063 mapPtr->toString(),
1064 igd->toString(),
1065 mapPtr->getProtocolName());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001066 return;
1067 }
1068
1069 mapPtr->setRenewalTime(map.getRenewalTime());
1070}
1071#endif
1072
1073void
1074UPnPContext::requestRemoveMapping(const Mapping::sharedPtr_t& map)
1075{
Adrien Béraud370257c2023-08-15 20:53:09 -04001076 if (not map or not map->isValid()) {
Adrien Béraud612b55b2023-05-29 10:42:04 -04001077 // Silently ignore if the mapping is invalid
1078 return;
1079 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001080 auto protocol = protocolList_.at(map->getIgd()->getProtocol());
1081 protocol->requestMappingRemove(*map);
1082}
1083
1084void
1085UPnPContext::deleteAllMappings(PortType type)
1086{
Adrien Béraud370257c2023-08-15 20:53:09 -04001087 /*if (not isValidThread()) {
1088 ctx->post([this, type] { deleteAllMappings(type); });
Adrien Béraud612b55b2023-05-29 10:42:04 -04001089 return;
Adrien Béraud370257c2023-08-15 20:53:09 -04001090 }*/
Adrien Béraud612b55b2023-05-29 10:42:04 -04001091
1092 std::lock_guard<std::mutex> lock(mappingMutex_);
1093 auto& mappingList = getMappingList(type);
1094
1095 for (auto const& [_, map] : mappingList) {
1096 requestRemoveMapping(map);
1097 }
1098}
1099
1100void
1101UPnPContext::onMappingRemoved(const std::shared_ptr<IGD>& igd, const Mapping& mapRes)
1102{
1103 if (not mapRes.isValid())
1104 return;
1105
Adrien Béraud370257c2023-08-15 20:53:09 -04001106 /*if (not isValidThread()) {
1107 ctx->post([this, igd, mapRes] { onMappingRemoved(igd, mapRes); });
Adrien Béraud612b55b2023-05-29 10:42:04 -04001108 return;
Adrien Béraud370257c2023-08-15 20:53:09 -04001109 }*/
Adrien Béraud612b55b2023-05-29 10:42:04 -04001110
1111 auto map = getMappingWithKey(mapRes.getMapKey());
1112 // Notify the listener.
1113 if (map and map->getNotifyCallback())
1114 map->getNotifyCallback()(map);
1115}
1116
1117Mapping::sharedPtr_t
1118UPnPContext::registerMapping(Mapping& map)
1119{
1120 if (map.getExternalPort() == 0) {
Morteza Namvar5f639522023-07-04 17:08:58 -04001121 // JAMI_DBG("Port number not set. Will set a random port number");
Adrien Béraud612b55b2023-05-29 10:42:04 -04001122 auto port = getAvailablePortNumber(map.getType());
1123 map.setExternalPort(port);
1124 map.setInternalPort(port);
1125 }
1126
1127 // Newly added mapping must be in pending state by default.
1128 map.setState(MappingState::PENDING);
1129
1130 Mapping::sharedPtr_t mapPtr;
1131
1132 {
1133 std::lock_guard<std::mutex> lock(mappingMutex_);
1134 auto& mappingList = getMappingList(map.getType());
1135
1136 auto ret = mappingList.emplace(map.getMapKey(), std::make_shared<Mapping>(map));
1137 if (not ret.second) {
Adrien Berauda8731ac2023-08-17 12:19:39 -04001138 if (logger_) logger_->warn("Mapping request for {} already added!", map.toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001139 return {};
1140 }
1141 mapPtr = ret.first->second;
1142 assert(mapPtr);
1143 }
1144
1145 // No available IGD. The pending mapping requests will be processed
1146 // when a IGD becomes available (in onIgdAdded() method).
1147 if (not isReady()) {
Adrien Berauda8731ac2023-08-17 12:19:39 -04001148 if (logger_) logger_->warn("No IGD available. Mapping will be requested when an IGD becomes available");
Adrien Béraud612b55b2023-05-29 10:42:04 -04001149 } else {
1150 requestMapping(mapPtr);
1151 }
1152
1153 return mapPtr;
1154}
1155
Adrien Béraud612b55b2023-05-29 10:42:04 -04001156void
1157UPnPContext::unregisterMapping(const Mapping::sharedPtr_t& map)
1158{
Adrien Béraud370257c2023-08-15 20:53:09 -04001159 //CHECK_VALID_THREAD();
Adrien Béraud612b55b2023-05-29 10:42:04 -04001160
1161 if (not map) {
Morteza Namvar5f639522023-07-04 17:08:58 -04001162 // JAMI_ERR("Mapping pointer is null");
Adrien Béraud612b55b2023-05-29 10:42:04 -04001163 return;
1164 }
1165
1166 if (map->getAutoUpdate()) {
1167 // Dont unregister mappings with auto-update enabled.
1168 return;
1169 }
1170 auto& mappingList = getMappingList(map->getType());
1171
1172 if (mappingList.erase(map->getMapKey()) == 1) {
Adrien Berauda8731ac2023-08-17 12:19:39 -04001173 if (logger_) logger_->debug("Unregistered mapping {}", map->toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001174 } else {
1175 // The mapping may already be un-registered. Just ignore it.
Adrien Berauda8731ac2023-08-17 12:19:39 -04001176 if (logger_) logger_->debug("Mapping {} [{}] does not have a local match",
1177 map->toString(),
1178 map->getProtocolName());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001179 }
1180}
1181
1182std::map<Mapping::key_t, Mapping::sharedPtr_t>&
1183UPnPContext::getMappingList(PortType type)
1184{
1185 unsigned typeIdx = type == PortType::TCP ? 0 : 1;
1186 return mappingList_[typeIdx];
1187}
1188
1189Mapping::sharedPtr_t
1190UPnPContext::getMappingWithKey(Mapping::key_t key)
1191{
1192 std::lock_guard<std::mutex> lock(mappingMutex_);
1193 auto const& mappingList = getMappingList(Mapping::getTypeFromMapKey(key));
1194 auto it = mappingList.find(key);
1195 if (it == mappingList.end())
1196 return nullptr;
1197 return it->second;
1198}
1199
1200void
1201UPnPContext::getMappingStatus(PortType type, MappingStatus& status)
1202{
1203 std::lock_guard<std::mutex> lock(mappingMutex_);
1204 auto& mappingList = getMappingList(type);
1205
1206 for (auto const& [_, map] : mappingList) {
1207 switch (map->getState()) {
1208 case MappingState::PENDING: {
1209 status.pendingCount_++;
1210 break;
1211 }
1212 case MappingState::IN_PROGRESS: {
1213 status.inProgressCount_++;
1214 break;
1215 }
1216 case MappingState::FAILED: {
1217 status.failedCount_++;
1218 break;
1219 }
1220 case MappingState::OPEN: {
1221 status.openCount_++;
1222 if (map->isAvailable())
1223 status.readyCount_++;
1224 break;
1225 }
1226
1227 default:
1228 // Must not get here.
1229 assert(false);
1230 break;
1231 }
1232 }
1233}
1234
1235void
1236UPnPContext::getMappingStatus(MappingStatus& status)
1237{
1238 getMappingStatus(PortType::TCP, status);
1239 getMappingStatus(PortType::UDP, status);
1240}
1241
1242void
1243UPnPContext::onMappingRequestFailed(const Mapping& mapRes)
1244{
Adrien Béraud612b55b2023-05-29 10:42:04 -04001245 auto const& map = getMappingWithKey(mapRes.getMapKey());
1246 if (not map) {
1247 // We may receive a response for a removed request. Just ignore it.
Adrien Berauda8731ac2023-08-17 12:19:39 -04001248 if (logger_) logger_->debug("Mapping {} [IGD {}] does not have a local match",
1249 mapRes.toString(),
1250 mapRes.getProtocolName());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001251 return;
1252 }
1253
1254 auto igd = map->getIgd();
1255 if (not igd) {
Adrien Berauda8731ac2023-08-17 12:19:39 -04001256 if (logger_) logger_->error("IGD pointer is null");
Adrien Béraud612b55b2023-05-29 10:42:04 -04001257 return;
1258 }
1259
Adrien Beraud3bd61c92023-08-17 16:57:37 -04001260 updateMappingState(map, MappingState::FAILED);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001261 unregisterMapping(map);
1262
Adrien Berauda8731ac2023-08-17 12:19:39 -04001263 if (logger_) logger_->warn("Mapping request for {} failed on IGD {} [{}]",
1264 map->toString(),
1265 igd->toString(),
1266 igd->getProtocolName());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001267}
1268
Adrien Beraud3bd61c92023-08-17 16:57:37 -04001269void
1270UPnPContext::updateMappingState(const Mapping::sharedPtr_t& map, MappingState newState, bool notify)
1271{
1272 // CHECK_VALID_THREAD();
1273
1274 assert(map);
1275
1276 // Ignore if the state did not change.
1277 if (newState == map->getState()) {
1278 // JAMI_DBG("Mapping %s already in state %s", map->toString().c_str(), map->getStateStr());
1279 return;
1280 }
1281
1282 // Update the state.
1283 map->setState(newState);
1284
1285 // Notify the listener if set.
1286 if (notify and map->getNotifyCallback())
1287 map->getNotifyCallback()(map);
1288}
1289
Adrien Béraud612b55b2023-05-29 10:42:04 -04001290#if HAVE_LIBNATPMP
1291void
1292UPnPContext::renewAllocations()
1293{
Adrien Béraud370257c2023-08-15 20:53:09 -04001294 //CHECK_VALID_THREAD();
Adrien Béraud612b55b2023-05-29 10:42:04 -04001295
1296 // Check if the we have valid PMP IGD.
1297 auto pmpProto = protocolList_.at(NatProtocolType::NAT_PMP);
1298
1299 auto now = sys_clock::now();
1300 std::vector<Mapping::sharedPtr_t> toRenew;
1301
1302 for (auto type : {PortType::TCP, PortType::UDP}) {
1303 std::lock_guard<std::mutex> lock(mappingMutex_);
1304 auto mappingList = getMappingList(type);
1305 for (auto const& [_, map] : mappingList) {
1306 if (not map->isValid())
1307 continue;
1308 if (map->getProtocol() != NatProtocolType::NAT_PMP)
1309 continue;
1310 if (map->getState() != MappingState::OPEN)
1311 continue;
1312 if (now < map->getRenewalTime())
1313 continue;
1314
1315 toRenew.emplace_back(map);
1316 }
1317 }
1318
1319 // Quit if there are no mapping to renew
1320 if (toRenew.empty())
1321 return;
1322
1323 for (auto const& map : toRenew) {
1324 pmpProto->requestMappingRenew(*map);
1325 }
1326}
1327#endif
1328
1329} // namespace upnp
Sébastien Blin464bdff2023-07-19 08:02:53 -04001330} // namespace dhtnet