blob: e5e1a42b7a6484d0f15d363bd1cf5a8f8989d294 [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 */
Adrien Béraud612b55b2023-05-29 10:42:04 -040017#include "pupnp.h"
Adrien Béraud370257c2023-08-15 20:53:09 -040018#include "string_utils.h"
Adrien Béraud612b55b2023-05-29 10:42:04 -040019
20#include <opendht/thread_pool.h>
21#include <opendht/http.h>
22
Adrien Béraud1ae60aa2023-07-07 09:55:09 -040023namespace dhtnet {
Adrien Béraud612b55b2023-05-29 10:42:04 -040024namespace upnp {
25
26// Action identifiers.
27constexpr static const char* ACTION_ADD_PORT_MAPPING {"AddPortMapping"};
28constexpr static const char* ACTION_DELETE_PORT_MAPPING {"DeletePortMapping"};
29constexpr static const char* ACTION_GET_GENERIC_PORT_MAPPING_ENTRY {"GetGenericPortMappingEntry"};
30constexpr static const char* ACTION_GET_STATUS_INFO {"GetStatusInfo"};
31constexpr static const char* ACTION_GET_EXTERNAL_IP_ADDRESS {"GetExternalIPAddress"};
32
33// Error codes returned by router when trying to remove ports.
34constexpr static int ARRAY_IDX_INVALID = 713;
35constexpr static int CONFLICT_IN_MAPPING = 718;
36
37// Max number of IGD search attempts before failure.
38constexpr static unsigned int PUPNP_MAX_RESTART_SEARCH_RETRIES {3};
39// IGD search timeout (in seconds).
40constexpr static unsigned int SEARCH_TIMEOUT {60};
41// Base unit for the timeout between two successive IGD search.
42constexpr static auto PUPNP_SEARCH_RETRY_UNIT {std::chrono::seconds(10)};
43
44// Helper functions for xml parsing.
45static std::string_view
46getElementText(IXML_Node* node)
47{
48 if (node) {
49 if (IXML_Node* textNode = ixmlNode_getFirstChild(node))
50 if (const char* value = ixmlNode_getNodeValue(textNode))
51 return std::string_view(value);
52 }
53 return {};
54}
55
56static std::string_view
57getFirstDocItem(IXML_Document* doc, const char* item)
58{
59 std::unique_ptr<IXML_NodeList, decltype(ixmlNodeList_free)&>
60 nodeList(ixmlDocument_getElementsByTagName(doc, item), ixmlNodeList_free);
61 if (nodeList) {
62 // If there are several nodes which match the tag, we only want the first one.
63 return getElementText(ixmlNodeList_item(nodeList.get(), 0));
64 }
65 return {};
66}
67
68static std::string_view
69getFirstElementItem(IXML_Element* element, const char* item)
70{
71 std::unique_ptr<IXML_NodeList, decltype(ixmlNodeList_free)&>
72 nodeList(ixmlElement_getElementsByTagName(element, item), ixmlNodeList_free);
73 if (nodeList) {
74 // If there are several nodes which match the tag, we only want the first one.
75 return getElementText(ixmlNodeList_item(nodeList.get(), 0));
76 }
77 return {};
78}
79
80static bool
81errorOnResponse(IXML_Document* doc)
82{
83 if (not doc)
84 return true;
85
86 auto errorCode = getFirstDocItem(doc, "errorCode");
87 if (not errorCode.empty()) {
88 auto errorDescription = getFirstDocItem(doc, "errorDescription");
Adrien Béraud4f7e8012023-08-16 15:28:18 -040089 // if (logger_) logger_->warn("PUPnP: Response contains error: {:s}: {:s}",
Morteza Namvar5f639522023-07-04 17:08:58 -040090 // errorCode,
91 // errorDescription);
Adrien Béraud612b55b2023-05-29 10:42:04 -040092 return true;
93 }
94 return false;
95}
96
97// UPNP class implementation
98
Adrien Béraud370257c2023-08-15 20:53:09 -040099PUPnP::PUPnP(const std::shared_ptr<asio::io_context>& ctx, const std::shared_ptr<dht::log::Logger>& logger)
100 : UPnPProtocol(logger), ioContext(ctx), searchForIgdTimer_(*ctx)
Adrien Béraud612b55b2023-05-29 10:42:04 -0400101{
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400102 if (logger_) logger_->debug("PUPnP: Creating instance [{}] ...", fmt::ptr(this));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400103}
104
105PUPnP::~PUPnP()
106{
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400107 if (logger_) logger_->debug("PUPnP: Instance [{}] destroyed", fmt::ptr(this));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400108}
109
110void
111PUPnP::initUpnpLib()
112{
113 assert(not initialized_);
Adrien Bérauda61adb52023-08-23 09:31:02 -0400114 auto hostinfo = ip_utils::getHostName();
Adrien Bérauda61adb52023-08-23 09:31:02 -0400115 int upnp_err = UpnpInit2(hostinfo.interface.empty() ? nullptr : hostinfo.interface.c_str(), 0);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400116 if (upnp_err != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400117 if (logger_) logger_->error("PUPnP: Can't initialize libupnp: {}", UpnpGetErrorMessage(upnp_err));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400118 UpnpFinish();
119 initialized_ = false;
120 return;
121 }
122
123 // Disable embedded WebServer if any.
124 if (UpnpIsWebserverEnabled() == 1) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400125 if (logger_) logger_->warn("PUPnP: Web-server is enabled. Disabling");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400126 UpnpEnableWebserver(0);
127 if (UpnpIsWebserverEnabled() == 1) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400128 if (logger_) logger_->error("PUPnP: Could not disable Web-server!");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400129 } else {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400130 if (logger_) logger_->debug("PUPnP: Web-server successfully disabled");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400131 }
132 }
133
134 char* ip_address = UpnpGetServerIpAddress();
135 char* ip_address6 = nullptr;
136 unsigned short port = UpnpGetServerPort();
137 unsigned short port6 = 0;
138#if UPNP_ENABLE_IPV6
139 ip_address6 = UpnpGetServerIp6Address();
140 port6 = UpnpGetServerPort6();
141#endif
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400142 if (logger_) {
143 if (ip_address6 and port6)
144 logger_->debug("PUPnP: Initialized on {}:{:d} | {}:{:d}", ip_address, port, ip_address6, port6);
145 else
146 logger_->debug("PUPnP: Initialized on {}:{:d}", ip_address, port);
147 }
Adrien Béraud612b55b2023-05-29 10:42:04 -0400148
149 // Relax the parser to allow malformed XML text.
150 ixmlRelaxParser(1);
151
152 initialized_ = true;
153}
154
155bool
156PUPnP::isRunning() const
157{
158 std::unique_lock<std::mutex> lk(pupnpMutex_);
159 return not shutdownComplete_;
160}
161
162void
163PUPnP::registerClient()
164{
165 assert(not clientRegistered_);
166
Adrien Béraud612b55b2023-05-29 10:42:04 -0400167 // Register Upnp control point.
168 int upnp_err = UpnpRegisterClient(ctrlPtCallback, this, &ctrlptHandle_);
169 if (upnp_err != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400170 if (logger_) logger_->error("PUPnP: Can't register client: {}", UpnpGetErrorMessage(upnp_err));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400171 } else {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400172 if (logger_) logger_->debug("PUPnP: Successfully registered client");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400173 clientRegistered_ = true;
174 }
175}
176
177void
178PUPnP::setObserver(UpnpMappingObserver* obs)
179{
Adrien Béraud612b55b2023-05-29 10:42:04 -0400180 observer_ = obs;
181}
182
183const IpAddr
184PUPnP::getHostAddress() const
185{
186 std::lock_guard<std::mutex> lock(pupnpMutex_);
187 return hostAddress_;
188}
189
190void
191PUPnP::terminate(std::condition_variable& cv)
192{
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400193 if (logger_) logger_->debug("PUPnP: Terminate instance {}", fmt::ptr(this));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400194
195 clientRegistered_ = false;
196 observer_ = nullptr;
197
198 UpnpUnRegisterClient(ctrlptHandle_);
199
200 if (initialized_) {
201 if (UpnpFinish() != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400202 if (logger_) logger_->error("PUPnP: Failed to properly close lib-upnp");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400203 }
204
205 initialized_ = false;
206 }
207
208 // Clear all the lists.
209 discoveredIgdList_.clear();
210
211 {
212 std::lock_guard<std::mutex> lock(pupnpMutex_);
213 validIgdList_.clear();
214 shutdownComplete_ = true;
215 cv.notify_one();
216 }
217}
218
219void
220PUPnP::terminate()
221{
222 std::unique_lock<std::mutex> lk(pupnpMutex_);
223 std::condition_variable cv {};
224
Adrien Béraud370257c2023-08-15 20:53:09 -0400225 ioContext->dispatch([&] {
226 terminate(cv);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400227 });
228
229 if (cv.wait_for(lk, std::chrono::seconds(10), [this] { return shutdownComplete_; })) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400230 if (logger_) logger_->debug("PUPnP: Shutdown completed");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400231 } else {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400232 if (logger_) logger_->error("PUPnP: Shutdown timed-out");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400233 // Force stop if the shutdown take too much time.
234 shutdownComplete_ = true;
235 }
236}
237
238void
239PUPnP::searchForDevices()
240{
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400241 if (logger_) logger_->debug("PUPnP: Send IGD search request");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400242
243 // Send out search for multiple types of devices, as some routers may possibly
244 // only reply to one.
245
246 auto err = UpnpSearchAsync(ctrlptHandle_, SEARCH_TIMEOUT, UPNP_ROOT_DEVICE, this);
247 if (err != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400248 if (logger_) logger_->warn("PUPnP: Send search for UPNP_ROOT_DEVICE failed. Error {:d}: {}",
249 err,
250 UpnpGetErrorMessage(err));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400251 }
252
253 err = UpnpSearchAsync(ctrlptHandle_, SEARCH_TIMEOUT, UPNP_IGD_DEVICE, this);
254 if (err != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400255 if (logger_) logger_->warn("PUPnP: Send search for UPNP_IGD_DEVICE failed. Error {:d}: {}",
256 err,
257 UpnpGetErrorMessage(err));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400258 }
259
260 err = UpnpSearchAsync(ctrlptHandle_, SEARCH_TIMEOUT, UPNP_WANIP_SERVICE, this);
261 if (err != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400262 if (logger_) logger_->warn("PUPnP: Send search for UPNP_WANIP_SERVICE failed. Error {:d}: {}",
263 err,
264 UpnpGetErrorMessage(err));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400265 }
266
267 err = UpnpSearchAsync(ctrlptHandle_, SEARCH_TIMEOUT, UPNP_WANPPP_SERVICE, this);
268 if (err != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400269 if (logger_) logger_->warn("PUPnP: Send search for UPNP_WANPPP_SERVICE failed. Error {:d}: {}",
270 err,
271 UpnpGetErrorMessage(err));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400272 }
273}
274
275void
276PUPnP::clearIgds()
277{
Morteza Namvar5f639522023-07-04 17:08:58 -0400278 // JAMI_DBG("PUPnP: clearing IGDs and devices lists");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400279
Adrien Béraud370257c2023-08-15 20:53:09 -0400280 searchForIgdTimer_.cancel();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400281
282 igdSearchCounter_ = 0;
283
284 {
285 std::lock_guard<std::mutex> lock(pupnpMutex_);
286 for (auto const& igd : validIgdList_) {
287 igd->setValid(false);
288 }
289 validIgdList_.clear();
290 hostAddress_ = {};
291 }
292
293 discoveredIgdList_.clear();
294}
295
296void
297PUPnP::searchForIgd()
298{
Adrien Béraud612b55b2023-05-29 10:42:04 -0400299 // Update local address before searching.
300 updateHostAddress();
301
302 if (isReady()) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400303 if (logger_) logger_->debug("PUPnP: Already have a valid IGD. Skip the search request");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400304 return;
305 }
306
307 if (igdSearchCounter_++ >= PUPNP_MAX_RESTART_SEARCH_RETRIES) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400308 if (logger_) logger_->warn("PUPnP: Setup failed after {:d} trials. PUPnP will be disabled!",
309 PUPNP_MAX_RESTART_SEARCH_RETRIES);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400310 return;
311 }
312
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400313 if (logger_) logger_->debug("PUPnP: Start search for IGD: attempt {:d}", igdSearchCounter_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400314
315 // Do not init if the host is not valid. Otherwise, the init will fail
316 // anyway and may put libupnp in an unstable state (mainly deadlocks)
317 // even if the UpnpFinish() method is called.
318 if (not hasValidHostAddress()) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400319 if (logger_) logger_->warn("PUPnP: Host address is invalid. Skipping the IGD search");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400320 } else {
321 // Init and register if needed
322 if (not initialized_) {
323 initUpnpLib();
324 }
325 if (initialized_ and not clientRegistered_) {
326 registerClient();
327 }
328 // Start searching
329 if (clientRegistered_) {
330 assert(initialized_);
331 searchForDevices();
332 } else {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400333 if (logger_) logger_->warn("PUPnP: PUPNP not fully setup. Skipping the IGD search");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400334 }
335 }
336
337 // Cancel the current timer (if any) and re-schedule.
338 // The connectivity change may be received while the the local
339 // interface is not fully setup. The rescheduling typically
340 // usefull to mitigate this race.
Adrien Béraud370257c2023-08-15 20:53:09 -0400341 searchForIgdTimer_.expires_after(PUPNP_SEARCH_RETRY_UNIT * igdSearchCounter_);
342 searchForIgdTimer_.async_wait([w = weak()] (const asio::error_code& ec) {
343 if (not ec) {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400344 if (auto upnpThis = w.lock())
345 upnpThis->searchForIgd();
Adrien Béraud370257c2023-08-15 20:53:09 -0400346 }
347 });
Adrien Béraud612b55b2023-05-29 10:42:04 -0400348}
349
350std::list<std::shared_ptr<IGD>>
351PUPnP::getIgdList() const
352{
353 std::lock_guard<std::mutex> lock(pupnpMutex_);
354 std::list<std::shared_ptr<IGD>> igdList;
355 for (auto& it : validIgdList_) {
356 // Return only active IGDs.
357 if (it->isValid()) {
358 igdList.emplace_back(it);
359 }
360 }
361 return igdList;
362}
363
364bool
365PUPnP::isReady() const
366{
367 // Must at least have a valid local address.
368 if (not getHostAddress() or getHostAddress().isLoopback())
369 return false;
370
371 return hasValidIgd();
372}
373
374bool
375PUPnP::hasValidIgd() const
376{
377 std::lock_guard<std::mutex> lock(pupnpMutex_);
378 for (auto& it : validIgdList_) {
379 if (it->isValid()) {
380 return true;
381 }
382 }
383 return false;
384}
385
386void
387PUPnP::updateHostAddress()
388{
389 std::lock_guard<std::mutex> lock(pupnpMutex_);
390 hostAddress_ = ip_utils::getLocalAddr(AF_INET);
391}
392
393bool
394PUPnP::hasValidHostAddress()
395{
396 std::lock_guard<std::mutex> lock(pupnpMutex_);
397 return hostAddress_ and not hostAddress_.isLoopback();
398}
399
400void
401PUPnP::incrementErrorsCounter(const std::shared_ptr<IGD>& igd)
402{
403 if (not igd or not igd->isValid())
404 return;
405 if (not igd->incrementErrorsCounter()) {
406 // Disable this IGD.
407 igd->setValid(false);
408 // Notify the listener.
409 if (observer_)
410 observer_->onIgdUpdated(igd, UpnpIgdEvent::INVALID_STATE);
411 }
412}
413
414bool
415PUPnP::validateIgd(const std::string& location, IXML_Document* doc_container_ptr)
416{
Adrien Béraud612b55b2023-05-29 10:42:04 -0400417 assert(doc_container_ptr != nullptr);
418
419 XMLDocument document(doc_container_ptr, ixmlDocument_free);
420 auto descDoc = document.get();
421 // Check device type.
422 auto deviceType = getFirstDocItem(descDoc, "deviceType");
423 if (deviceType != UPNP_IGD_DEVICE) {
424 // Device type not IGD.
425 return false;
426 }
427
428 std::shared_ptr<UPnPIGD> igd_candidate = parseIgd(descDoc, location);
429 if (not igd_candidate) {
430 // No valid IGD candidate.
431 return false;
432 }
433
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400434 if (logger_) logger_->debug("PUPnP: Validating the IGD candidate [UDN: {}]\n"
435 " Name : {}\n"
436 " Service Type : {}\n"
437 " Service ID : {}\n"
438 " Base URL : {}\n"
439 " Location URL : {}\n"
440 " control URL : {}\n"
441 " Event URL : {}",
442 igd_candidate->getUID(),
443 igd_candidate->getFriendlyName(),
444 igd_candidate->getServiceType(),
445 igd_candidate->getServiceId(),
446 igd_candidate->getBaseURL(),
447 igd_candidate->getLocationURL(),
448 igd_candidate->getControlURL(),
449 igd_candidate->getEventSubURL());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400450
451 // Check if IGD is connected.
452 if (not actionIsIgdConnected(*igd_candidate)) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400453 if (logger_) logger_->warn("PUPnP: IGD candidate {} is not connected", igd_candidate->getUID().c_str());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400454 return false;
455 }
456
457 // Validate external Ip.
458 igd_candidate->setPublicIp(actionGetExternalIP(*igd_candidate));
459 if (igd_candidate->getPublicIp().toString().empty()) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400460 if (logger_) logger_->warn("PUPnP: IGD candidate {} has no valid external Ip",
461 igd_candidate->getUID().c_str());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400462 return false;
463 }
464
465 // Validate internal Ip.
466 if (igd_candidate->getBaseURL().empty()) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400467 if (logger_) logger_->warn("PUPnP: IGD candidate {} has no valid internal Ip",
468 igd_candidate->getUID().c_str());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400469 return false;
470 }
471
472 // Typically the IGD local address should be extracted from the XML
473 // document (e.g. parsing the base URL). For simplicity, we assume
474 // that it matches the gateway as seen by the local interface.
475 if (const auto& localGw = ip_utils::getLocalGateway()) {
476 igd_candidate->setLocalIp(localGw);
477 } else {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400478 if (logger_) logger_->warn("PUPnP: Could not set internal address for IGD candidate {}",
479 igd_candidate->getUID().c_str());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400480 return false;
481 }
482
483 // Store info for subscription.
484 std::string eventSub = igd_candidate->getEventSubURL();
485
486 {
487 // Add the IGD if not already present in the list.
488 std::lock_guard<std::mutex> lock(pupnpMutex_);
489 for (auto& igd : validIgdList_) {
490 // Must not be a null pointer
491 assert(igd.get() != nullptr);
492 if (*igd == *igd_candidate) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400493 if (logger_) logger_->debug("PUPnP: Device [{}] with int/ext addresses [{}:{}] is already in the list of valid IGDs",
494 igd_candidate->getUID(),
495 igd_candidate->toString(),
496 igd_candidate->getPublicIp().toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400497 return true;
498 }
499 }
500 }
501
502 // We have a valid IGD
503 igd_candidate->setValid(true);
504
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400505 if (logger_) logger_->debug("PUPnP: Added a new IGD [{}] to the list of valid IGDs",
506 igd_candidate->getUID());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400507
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400508 if (logger_) logger_->debug("PUPnP: New IGD addresses [int: {} - ext: {}]",
509 igd_candidate->toString(),
510 igd_candidate->getPublicIp().toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400511
512 // Subscribe to IGD events.
513 int upnp_err = UpnpSubscribeAsync(ctrlptHandle_,
514 eventSub.c_str(),
515 UPNP_INFINITE,
516 subEventCallback,
517 this);
518 if (upnp_err != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400519 if (logger_) logger_->warn("PUPnP: Failed to send subscribe request to {}: error %i - {}",
520 igd_candidate->getUID(),
521 upnp_err,
522 UpnpGetErrorMessage(upnp_err));
523 return false;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400524 } else {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400525 if (logger_) logger_->debug("PUPnP: Successfully subscribed to IGD {}", igd_candidate->getUID());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400526 }
527
528 {
529 // This is a new (and hopefully valid) IGD.
530 std::lock_guard<std::mutex> lock(pupnpMutex_);
531 validIgdList_.emplace_back(igd_candidate);
532 }
533
534 // Report to the listener.
Adrien Béraud370257c2023-08-15 20:53:09 -0400535 ioContext->post([w = weak(), igd_candidate] {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400536 if (auto upnpThis = w.lock()) {
537 if (upnpThis->observer_)
538 upnpThis->observer_->onIgdUpdated(igd_candidate, UpnpIgdEvent::ADDED);
539 }
540 });
541
542 return true;
543}
544
545void
546PUPnP::requestMappingAdd(const Mapping& mapping)
547{
Adrien Béraud370257c2023-08-15 20:53:09 -0400548 ioContext->post([w = weak(), mapping] {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400549 if (auto upnpThis = w.lock()) {
550 if (not upnpThis->isRunning())
551 return;
552 Mapping mapRes(mapping);
553 if (upnpThis->actionAddPortMapping(mapRes)) {
554 mapRes.setState(MappingState::OPEN);
555 mapRes.setInternalAddress(upnpThis->getHostAddress().toString());
556 upnpThis->processAddMapAction(mapRes);
557 } else {
558 upnpThis->incrementErrorsCounter(mapRes.getIgd());
559 mapRes.setState(MappingState::FAILED);
560 upnpThis->processRequestMappingFailure(mapRes);
561 }
562 }
563 });
564}
565
566void
567PUPnP::requestMappingRemove(const Mapping& mapping)
568{
569 // Send remove request using the matching IGD
Adrien Béraud370257c2023-08-15 20:53:09 -0400570 ioContext->dispatch([w = weak(), mapping] {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400571 if (auto upnpThis = w.lock()) {
572 // Abort if we are shutting down.
573 if (not upnpThis->isRunning())
574 return;
575 if (upnpThis->actionDeletePortMapping(mapping)) {
576 upnpThis->processRemoveMapAction(mapping);
577 } else {
578 assert(mapping.getIgd());
579 // Dont need to report in case of failure.
580 upnpThis->incrementErrorsCounter(mapping.getIgd());
581 }
582 }
583 });
584}
585
586std::shared_ptr<UPnPIGD>
587PUPnP::findMatchingIgd(const std::string& ctrlURL) const
588{
589 std::lock_guard<std::mutex> lock(pupnpMutex_);
590
591 auto iter = std::find_if(validIgdList_.begin(),
592 validIgdList_.end(),
593 [&ctrlURL](const std::shared_ptr<IGD>& igd) {
594 if (auto upnpIgd = std::dynamic_pointer_cast<UPnPIGD>(igd)) {
595 return upnpIgd->getControlURL() == ctrlURL;
596 }
597 return false;
598 });
599
600 if (iter == validIgdList_.end()) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400601 if (logger_) logger_->warn("PUPnP: Did not find the IGD matching ctrl URL [{}]", ctrlURL);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400602 return {};
603 }
604
605 return std::dynamic_pointer_cast<UPnPIGD>(*iter);
606}
607
608void
609PUPnP::processAddMapAction(const Mapping& map)
610{
Adrien Béraud612b55b2023-05-29 10:42:04 -0400611 if (observer_ == nullptr)
612 return;
613
Adrien Béraud370257c2023-08-15 20:53:09 -0400614 ioContext->post([w = weak(), map] {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400615 if (auto upnpThis = w.lock()) {
616 if (upnpThis->observer_)
617 upnpThis->observer_->onMappingAdded(map.getIgd(), std::move(map));
618 }
619 });
620}
621
622void
623PUPnP::processRequestMappingFailure(const Mapping& map)
624{
Adrien Béraud612b55b2023-05-29 10:42:04 -0400625 if (observer_ == nullptr)
626 return;
627
Adrien Béraud370257c2023-08-15 20:53:09 -0400628 ioContext->post([w = weak(), map] {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400629 if (auto upnpThis = w.lock()) {
Adrien Beraud64bb00f2023-08-23 19:06:46 -0400630 if (upnpThis->logger_) upnpThis->logger_->debug("PUPnP: Closed mapping {}", map.toString());
Morteza Namvar5f639522023-07-04 17:08:58 -0400631 // JAMI_DBG("PUPnP: Failed to request mapping %s", map.toString().c_str());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400632 if (upnpThis->observer_)
633 upnpThis->observer_->onMappingRequestFailed(map);
634 }
635 });
636}
637
638void
639PUPnP::processRemoveMapAction(const Mapping& map)
640{
Adrien Béraud612b55b2023-05-29 10:42:04 -0400641 if (observer_ == nullptr)
642 return;
643
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400644 if (logger_) logger_->warn("PUPnP: Closed mapping {}", map.toString());
Adrien Béraud370257c2023-08-15 20:53:09 -0400645 ioContext->post([map, obs = observer_] {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400646 obs->onMappingRemoved(map.getIgd(), std::move(map));
647 });
648}
649
650const char*
651PUPnP::eventTypeToString(Upnp_EventType eventType)
652{
653 switch (eventType) {
654 case UPNP_CONTROL_ACTION_REQUEST:
655 return "UPNP_CONTROL_ACTION_REQUEST";
656 case UPNP_CONTROL_ACTION_COMPLETE:
657 return "UPNP_CONTROL_ACTION_COMPLETE";
658 case UPNP_CONTROL_GET_VAR_REQUEST:
659 return "UPNP_CONTROL_GET_VAR_REQUEST";
660 case UPNP_CONTROL_GET_VAR_COMPLETE:
661 return "UPNP_CONTROL_GET_VAR_COMPLETE";
662 case UPNP_DISCOVERY_ADVERTISEMENT_ALIVE:
663 return "UPNP_DISCOVERY_ADVERTISEMENT_ALIVE";
664 case UPNP_DISCOVERY_ADVERTISEMENT_BYEBYE:
665 return "UPNP_DISCOVERY_ADVERTISEMENT_BYEBYE";
666 case UPNP_DISCOVERY_SEARCH_RESULT:
667 return "UPNP_DISCOVERY_SEARCH_RESULT";
668 case UPNP_DISCOVERY_SEARCH_TIMEOUT:
669 return "UPNP_DISCOVERY_SEARCH_TIMEOUT";
670 case UPNP_EVENT_SUBSCRIPTION_REQUEST:
671 return "UPNP_EVENT_SUBSCRIPTION_REQUEST";
672 case UPNP_EVENT_RECEIVED:
673 return "UPNP_EVENT_RECEIVED";
674 case UPNP_EVENT_RENEWAL_COMPLETE:
675 return "UPNP_EVENT_RENEWAL_COMPLETE";
676 case UPNP_EVENT_SUBSCRIBE_COMPLETE:
677 return "UPNP_EVENT_SUBSCRIBE_COMPLETE";
678 case UPNP_EVENT_UNSUBSCRIBE_COMPLETE:
679 return "UPNP_EVENT_UNSUBSCRIBE_COMPLETE";
680 case UPNP_EVENT_AUTORENEWAL_FAILED:
681 return "UPNP_EVENT_AUTORENEWAL_FAILED";
682 case UPNP_EVENT_SUBSCRIPTION_EXPIRED:
683 return "UPNP_EVENT_SUBSCRIPTION_EXPIRED";
684 default:
685 return "Unknown UPNP Event";
686 }
687}
688
689int
690PUPnP::ctrlPtCallback(Upnp_EventType event_type, const void* event, void* user_data)
691{
692 auto pupnp = static_cast<PUPnP*>(user_data);
693
694 if (pupnp == nullptr) {
Adrien Bérauda61adb52023-08-23 09:31:02 -0400695 fmt::print(stderr, "PUPnP: Control point callback without PUPnP");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400696 return UPNP_E_SUCCESS;
697 }
698
699 auto upnpThis = pupnp->weak().lock();
Adrien Bérauda61adb52023-08-23 09:31:02 -0400700 if (not upnpThis) {
701 fmt::print(stderr, "PUPnP: Control point callback without PUPnP");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400702 return UPNP_E_SUCCESS;
Adrien Bérauda61adb52023-08-23 09:31:02 -0400703 }
Adrien Béraud612b55b2023-05-29 10:42:04 -0400704
705 // Ignore if already unregistered.
706 if (not upnpThis->clientRegistered_)
707 return UPNP_E_SUCCESS;
708
709 // Process the callback.
710 return upnpThis->handleCtrlPtUPnPEvents(event_type, event);
711}
712
713PUPnP::CtrlAction
714PUPnP::getAction(const char* xmlNode)
715{
716 if (strstr(xmlNode, ACTION_ADD_PORT_MAPPING)) {
717 return CtrlAction::ADD_PORT_MAPPING;
718 } else if (strstr(xmlNode, ACTION_DELETE_PORT_MAPPING)) {
719 return CtrlAction::DELETE_PORT_MAPPING;
720 } else if (strstr(xmlNode, ACTION_GET_GENERIC_PORT_MAPPING_ENTRY)) {
721 return CtrlAction::GET_GENERIC_PORT_MAPPING_ENTRY;
722 } else if (strstr(xmlNode, ACTION_GET_STATUS_INFO)) {
723 return CtrlAction::GET_STATUS_INFO;
724 } else if (strstr(xmlNode, ACTION_GET_EXTERNAL_IP_ADDRESS)) {
725 return CtrlAction::GET_EXTERNAL_IP_ADDRESS;
726 } else {
727 return CtrlAction::UNKNOWN;
728 }
729}
730
731void
732PUPnP::processDiscoverySearchResult(const std::string& cpDeviceId,
733 const std::string& igdLocationUrl,
734 const IpAddr& dstAddr)
735{
Adrien Béraud612b55b2023-05-29 10:42:04 -0400736 // Update host address if needed.
737 if (not hasValidHostAddress())
738 updateHostAddress();
739
740 // The host address must be valid to proceed.
741 if (not hasValidHostAddress()) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400742 if (logger_) logger_->warn("PUPnP: Local address is invalid. Ignore search result for now!");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400743 return;
744 }
745
746 // Use the device ID and the URL as ID. This is necessary as some
747 // IGDs may have the same device ID but different URLs.
748
749 auto igdId = cpDeviceId + " url: " + igdLocationUrl;
750
751 if (not discoveredIgdList_.emplace(igdId).second) {
Adrien Beraud64bb00f2023-08-23 19:06:46 -0400752 //if (logger_) logger_->debug("PUPnP: IGD [{}] already in the list", igdId);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400753 return;
754 }
755
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400756 if (logger_) logger_->debug("PUPnP: Discovered a new IGD [{}]", igdId);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400757
758 // NOTE: here, we check if the location given is related to the source address.
759 // If it's not the case, it's certainly a router plugged in the network, but not
760 // related to this network. So the given location will be unreachable and this
761 // will cause some timeout.
762
763 // Only check the IP address (ignore the port number).
764 dht::http::Url url(igdLocationUrl);
765 if (IpAddr(url.host).toString(false) != dstAddr.toString(false)) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400766 if (logger_) logger_->debug("PUPnP: Returned location {} does not match the source address {}",
767 IpAddr(url.host).toString(true, true),
768 dstAddr.toString(true, true));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400769 return;
770 }
771
772 // Run a separate thread to prevent blocking this thread
773 // if the IGD HTTP server is not responsive.
Adrien Beraud3bd61c92023-08-17 16:57:37 -0400774 dht::ThreadPool::io().run([w = weak(), url=igdLocationUrl] {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400775 if (auto upnpThis = w.lock()) {
Adrien Beraud3bd61c92023-08-17 16:57:37 -0400776 upnpThis->downLoadIgdDescription(url);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400777 }
778 });
779}
780
781void
782PUPnP::downLoadIgdDescription(const std::string& locationUrl)
783{
Adrien Beraud3bd61c92023-08-17 16:57:37 -0400784 if(logger_) logger_->debug("PUPnP: downLoadIgdDescription {}", locationUrl);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400785 IXML_Document* doc_container_ptr = nullptr;
786 int upnp_err = UpnpDownloadXmlDoc(locationUrl.c_str(), &doc_container_ptr);
787
788 if (upnp_err != UPNP_E_SUCCESS or not doc_container_ptr) {
Adrien Béraud370257c2023-08-15 20:53:09 -0400789 if(logger_) logger_->warn("PUPnP: Error downloading device XML document from {} -> {}",
790 locationUrl,
791 UpnpGetErrorMessage(upnp_err));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400792 } else {
Adrien Béraud370257c2023-08-15 20:53:09 -0400793 if(logger_) logger_->debug("PUPnP: Succeeded to download device XML document from {}", locationUrl);
794 ioContext->post([w = weak(), url = locationUrl, doc_container_ptr] {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400795 if (auto upnpThis = w.lock()) {
796 upnpThis->validateIgd(url, doc_container_ptr);
797 }
798 });
799 }
800}
801
802void
803PUPnP::processDiscoveryAdvertisementByebye(const std::string& cpDeviceId)
804{
Adrien Béraud612b55b2023-05-29 10:42:04 -0400805 discoveredIgdList_.erase(cpDeviceId);
806
807 std::shared_ptr<IGD> igd;
808 {
809 std::lock_guard<std::mutex> lk(pupnpMutex_);
810 for (auto it = validIgdList_.begin(); it != validIgdList_.end();) {
811 if ((*it)->getUID() == cpDeviceId) {
812 igd = *it;
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400813 if (logger_) logger_->debug("PUPnP: Received [{}] for IGD [{}] {}. Will be removed.",
814 PUPnP::eventTypeToString(UPNP_DISCOVERY_ADVERTISEMENT_BYEBYE),
815 igd->getUID(),
816 igd->toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400817 igd->setValid(false);
818 // Remove the IGD.
819 it = validIgdList_.erase(it);
820 break;
821 } else {
822 it++;
823 }
824 }
825 }
826
827 // Notify the listener.
828 if (observer_ and igd) {
829 observer_->onIgdUpdated(igd, UpnpIgdEvent::REMOVED);
830 }
831}
832
833void
834PUPnP::processDiscoverySubscriptionExpired(Upnp_EventType event_type, const std::string& eventSubUrl)
835{
Adrien Béraud612b55b2023-05-29 10:42:04 -0400836 std::lock_guard<std::mutex> lk(pupnpMutex_);
837 for (auto& it : validIgdList_) {
838 if (auto igd = std::dynamic_pointer_cast<UPnPIGD>(it)) {
839 if (igd->getEventSubURL() == eventSubUrl) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400840 if (logger_) logger_->debug("PUPnP: Received [{}] event for IGD [{}] {}. Request a new subscribe.",
841 PUPnP::eventTypeToString(event_type),
842 igd->getUID(),
843 igd->toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400844 UpnpSubscribeAsync(ctrlptHandle_,
845 eventSubUrl.c_str(),
846 UPNP_INFINITE,
847 subEventCallback,
848 this);
849 break;
850 }
851 }
852 }
853}
854
855int
856PUPnP::handleCtrlPtUPnPEvents(Upnp_EventType event_type, const void* event)
857{
858 switch (event_type) {
859 // "ALIVE" events are processed as "SEARCH RESULT". It might be usefull
860 // if "SEARCH RESULT" was missed.
861 case UPNP_DISCOVERY_ADVERTISEMENT_ALIVE:
862 case UPNP_DISCOVERY_SEARCH_RESULT: {
863 const UpnpDiscovery* d_event = (const UpnpDiscovery*) event;
864
865 // First check the error code.
866 auto upnp_status = UpnpDiscovery_get_ErrCode(d_event);
867 if (upnp_status != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400868 if (logger_) logger_->error("PUPnP: UPNP discovery is in erroneous state: %s",
869 UpnpGetErrorMessage(upnp_status));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400870 break;
871 }
872
873 // Parse the event's data.
874 std::string deviceId {UpnpDiscovery_get_DeviceID_cstr(d_event)};
875 std::string location {UpnpDiscovery_get_Location_cstr(d_event)};
876 IpAddr dstAddr(*(const pj_sockaddr*) (UpnpDiscovery_get_DestAddr(d_event)));
Adrien Béraud370257c2023-08-15 20:53:09 -0400877 ioContext->post([w = weak(),
Adrien Béraud612b55b2023-05-29 10:42:04 -0400878 deviceId = std::move(deviceId),
879 location = std::move(location),
880 dstAddr = std::move(dstAddr)] {
881 if (auto upnpThis = w.lock()) {
882 upnpThis->processDiscoverySearchResult(deviceId, location, dstAddr);
883 }
884 });
885 break;
886 }
887 case UPNP_DISCOVERY_ADVERTISEMENT_BYEBYE: {
888 const UpnpDiscovery* d_event = (const UpnpDiscovery*) event;
889
890 std::string deviceId(UpnpDiscovery_get_DeviceID_cstr(d_event));
891
892 // Process the response on the main thread.
Adrien Béraud370257c2023-08-15 20:53:09 -0400893 ioContext->post([w = weak(), deviceId = std::move(deviceId)] {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400894 if (auto upnpThis = w.lock()) {
895 upnpThis->processDiscoveryAdvertisementByebye(deviceId);
896 }
897 });
898 break;
899 }
900 case UPNP_DISCOVERY_SEARCH_TIMEOUT: {
901 // Even if the discovery search is successful, it's normal to receive
902 // time-out events. This because we send search requests using various
903 // device types, which some of them may not return a response.
904 break;
905 }
906 case UPNP_EVENT_RECEIVED: {
907 // Nothing to do.
908 break;
909 }
910 // Treat failed autorenewal like an expired subscription.
911 case UPNP_EVENT_AUTORENEWAL_FAILED:
912 case UPNP_EVENT_SUBSCRIPTION_EXPIRED: // This event will occur only if autorenewal is disabled.
913 {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400914 if (logger_) logger_->warn("PUPnP: Received Subscription Event {}", eventTypeToString(event_type));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400915 const UpnpEventSubscribe* es_event = (const UpnpEventSubscribe*) event;
916 if (es_event == nullptr) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400917 if (logger_) logger_->warn("PUPnP: Received Subscription Event with null pointer");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400918 break;
919 }
920 std::string publisherUrl(UpnpEventSubscribe_get_PublisherUrl_cstr(es_event));
921
922 // Process the response on the main thread.
Adrien Béraud370257c2023-08-15 20:53:09 -0400923 ioContext->post([w = weak(), event_type, publisherUrl = std::move(publisherUrl)] {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400924 if (auto upnpThis = w.lock()) {
925 upnpThis->processDiscoverySubscriptionExpired(event_type, publisherUrl);
926 }
927 });
928 break;
929 }
930 case UPNP_EVENT_SUBSCRIBE_COMPLETE:
931 case UPNP_EVENT_UNSUBSCRIBE_COMPLETE: {
932 UpnpEventSubscribe* es_event = (UpnpEventSubscribe*) event;
933 if (es_event == nullptr) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400934 if (logger_) logger_->warn("PUPnP: Received Subscription Event with null pointer");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400935 } else {
936 UpnpEventSubscribe_delete(es_event);
937 }
938 break;
939 }
940 case UPNP_CONTROL_ACTION_COMPLETE: {
941 const UpnpActionComplete* a_event = (const UpnpActionComplete*) event;
942 if (a_event == nullptr) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400943 if (logger_) logger_->warn("PUPnP: Received Action Complete Event with null pointer");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400944 break;
945 }
946 auto res = UpnpActionComplete_get_ErrCode(a_event);
947 if (res != UPNP_E_SUCCESS and res != UPNP_E_TIMEDOUT) {
948 auto err = UpnpActionComplete_get_ErrCode(a_event);
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400949 if (logger_) logger_->warn("PUPnP: Received Action Complete error %i %s", err, UpnpGetErrorMessage(err));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400950 } else {
951 auto actionRequest = UpnpActionComplete_get_ActionRequest(a_event);
952 // Abort if there is no action to process.
953 if (actionRequest == nullptr) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400954 if (logger_) logger_->warn("PUPnP: Can't get the Action Request data from the event");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400955 break;
956 }
957
958 auto actionResult = UpnpActionComplete_get_ActionResult(a_event);
959 if (actionResult != nullptr) {
960 ixmlDocument_free(actionResult);
961 } else {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400962 if (logger_) logger_->warn("PUPnP: Action Result document not found");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400963 }
964 }
965 break;
966 }
967 default: {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400968 if (logger_) logger_->warn("PUPnP: Unhandled Control Point event");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400969 break;
970 }
971 }
972
973 return UPNP_E_SUCCESS;
974}
975
976int
977PUPnP::subEventCallback(Upnp_EventType event_type, const void* event, void* user_data)
978{
979 if (auto pupnp = static_cast<PUPnP*>(user_data))
980 return pupnp->handleSubscriptionUPnPEvent(event_type, event);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400981 return 0;
982}
983
984int
985PUPnP::handleSubscriptionUPnPEvent(Upnp_EventType, const void* event)
986{
987 UpnpEventSubscribe* es_event = static_cast<UpnpEventSubscribe*>(const_cast<void*>(event));
988
989 if (es_event == nullptr) {
Morteza Namvar5f639522023-07-04 17:08:58 -0400990 // JAMI_ERR("PUPnP: Unexpected null pointer!");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400991 return UPNP_E_INVALID_ARGUMENT;
992 }
993 std::string publisherUrl(UpnpEventSubscribe_get_PublisherUrl_cstr(es_event));
994 int upnp_err = UpnpEventSubscribe_get_ErrCode(es_event);
995 if (upnp_err != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400996 if (logger_) logger_->warn("PUPnP: Subscription error {} from {}",
997 UpnpGetErrorMessage(upnp_err),
998 publisherUrl);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400999 return upnp_err;
1000 }
1001
1002 return UPNP_E_SUCCESS;
1003}
1004
1005std::unique_ptr<UPnPIGD>
1006PUPnP::parseIgd(IXML_Document* doc, std::string locationUrl)
1007{
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001008 if (not(doc and !locationUrl.empty()))
Adrien Béraud612b55b2023-05-29 10:42:04 -04001009 return nullptr;
1010
1011 // Check the UDN to see if its already in our device list.
1012 std::string UDN(getFirstDocItem(doc, "UDN"));
1013 if (UDN.empty()) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001014 if (logger_) logger_->warn("PUPnP: could not find UDN in description document of device");
Adrien Béraud612b55b2023-05-29 10:42:04 -04001015 return nullptr;
1016 } else {
1017 std::lock_guard<std::mutex> lk(pupnpMutex_);
1018 for (auto& it : validIgdList_) {
1019 if (it->getUID() == UDN) {
1020 // We already have this device in our list.
1021 return nullptr;
1022 }
1023 }
1024 }
1025
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001026 if (logger_) logger_->debug("PUPnP: Found new device [{}]", UDN);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001027
1028 std::unique_ptr<UPnPIGD> new_igd;
1029 int upnp_err;
1030
1031 // Get friendly name.
1032 std::string friendlyName(getFirstDocItem(doc, "friendlyName"));
1033
1034 // Get base URL.
1035 std::string baseURL(getFirstDocItem(doc, "URLBase"));
1036 if (baseURL.empty())
1037 baseURL = locationUrl;
1038
1039 // Get list of services defined by serviceType.
1040 std::unique_ptr<IXML_NodeList, decltype(ixmlNodeList_free)&> serviceList(nullptr,
1041 ixmlNodeList_free);
1042 serviceList.reset(ixmlDocument_getElementsByTagName(doc, "serviceType"));
1043 unsigned long list_length = ixmlNodeList_length(serviceList.get());
1044
1045 // Go through the "serviceType" nodes until we find the the correct service type.
1046 for (unsigned long node_idx = 0; node_idx < list_length; node_idx++) {
1047 IXML_Node* serviceType_node = ixmlNodeList_item(serviceList.get(), node_idx);
1048 std::string serviceType(getElementText(serviceType_node));
1049
1050 // Only check serviceType of WANIPConnection or WANPPPConnection.
1051 if (serviceType != UPNP_WANIP_SERVICE
1052 && serviceType != UPNP_WANPPP_SERVICE) {
1053 // IGD is not WANIP or WANPPP service. Going to next node.
1054 continue;
1055 }
1056
1057 // Get parent node.
1058 IXML_Node* service_node = ixmlNode_getParentNode(serviceType_node);
1059 if (not service_node) {
1060 // IGD serviceType has no parent node. Going to next node.
1061 continue;
1062 }
1063
1064 // Perform sanity check. The parent node should be called "service".
1065 if (strcmp(ixmlNode_getNodeName(service_node), "service") != 0) {
1066 // IGD "serviceType" parent node is not called "service". Going to next node.
1067 continue;
1068 }
1069
1070 // Get serviceId.
1071 IXML_Element* service_element = (IXML_Element*) service_node;
1072 std::string serviceId(getFirstElementItem(service_element, "serviceId"));
1073 if (serviceId.empty()) {
1074 // IGD "serviceId" is empty. Going to next node.
1075 continue;
1076 }
1077
1078 // Get the relative controlURL and turn it into absolute address using the URLBase.
1079 std::string controlURL(getFirstElementItem(service_element, "controlURL"));
1080 if (controlURL.empty()) {
1081 // IGD control URL is empty. Going to next node.
1082 continue;
1083 }
1084
1085 char* absolute_control_url = nullptr;
1086 upnp_err = UpnpResolveURL2(baseURL.c_str(), controlURL.c_str(), &absolute_control_url);
1087 if (upnp_err == UPNP_E_SUCCESS)
1088 controlURL = absolute_control_url;
1089 else
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001090 if (logger_) logger_->warn("PUPnP: Error resolving absolute controlURL -> {}",
1091 UpnpGetErrorMessage(upnp_err));
Adrien Béraud612b55b2023-05-29 10:42:04 -04001092
1093 std::free(absolute_control_url);
1094
1095 // Get the relative eventSubURL and turn it into absolute address using the URLBase.
1096 std::string eventSubURL(getFirstElementItem(service_element, "eventSubURL"));
1097 if (eventSubURL.empty()) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001098 if (logger_) logger_->warn("PUPnP: IGD event sub URL is empty. Going to next node");
Adrien Béraud612b55b2023-05-29 10:42:04 -04001099 continue;
1100 }
1101
1102 char* absolute_event_sub_url = nullptr;
1103 upnp_err = UpnpResolveURL2(baseURL.c_str(), eventSubURL.c_str(), &absolute_event_sub_url);
1104 if (upnp_err == UPNP_E_SUCCESS)
1105 eventSubURL = absolute_event_sub_url;
1106 else
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001107 if (logger_) logger_->warn("PUPnP: Error resolving absolute eventSubURL -> {}",
1108 UpnpGetErrorMessage(upnp_err));
Adrien Béraud612b55b2023-05-29 10:42:04 -04001109
1110 std::free(absolute_event_sub_url);
1111
1112 new_igd.reset(new UPnPIGD(std::move(UDN),
1113 std::move(baseURL),
1114 std::move(friendlyName),
1115 std::move(serviceType),
1116 std::move(serviceId),
1117 std::move(locationUrl),
1118 std::move(controlURL),
1119 std::move(eventSubURL)));
1120
1121 return new_igd;
1122 }
1123
1124 return nullptr;
1125}
1126
1127bool
1128PUPnP::actionIsIgdConnected(const UPnPIGD& igd)
1129{
1130 if (not clientRegistered_)
1131 return false;
1132
1133 // Set action name.
1134 IXML_Document* action_container_ptr = UpnpMakeAction("GetStatusInfo",
1135 igd.getServiceType().c_str(),
1136 0,
1137 nullptr);
1138 if (not action_container_ptr) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001139 if (logger_) logger_->warn("PUPnP: Failed to make GetStatusInfo action");
Adrien Béraud612b55b2023-05-29 10:42:04 -04001140 return false;
1141 }
1142 XMLDocument action(action_container_ptr, ixmlDocument_free); // Action pointer.
1143
1144 IXML_Document* response_container_ptr = nullptr;
1145 int upnp_err = UpnpSendAction(ctrlptHandle_,
1146 igd.getControlURL().c_str(),
1147 igd.getServiceType().c_str(),
1148 nullptr,
1149 action.get(),
1150 &response_container_ptr);
1151 if (not response_container_ptr or upnp_err != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001152 if (logger_) logger_->warn("PUPnP: Failed to send GetStatusInfo action -> {}", UpnpGetErrorMessage(upnp_err));
Adrien Béraud612b55b2023-05-29 10:42:04 -04001153 return false;
1154 }
1155 XMLDocument response(response_container_ptr, ixmlDocument_free);
1156
1157 if (errorOnResponse(response.get())) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001158 if (logger_) logger_->warn("PUPnP: Failed to get GetStatusInfo from {} -> {:d}: {}",
1159 igd.getServiceType().c_str(),
1160 upnp_err,
1161 UpnpGetErrorMessage(upnp_err));
Adrien Béraud612b55b2023-05-29 10:42:04 -04001162 return false;
1163 }
1164
1165 // Parse response.
1166 auto status = getFirstDocItem(response.get(), "NewConnectionStatus");
1167 return status == "Connected";
1168}
1169
1170IpAddr
1171PUPnP::actionGetExternalIP(const UPnPIGD& igd)
1172{
1173 if (not clientRegistered_)
1174 return {};
1175
1176 // Action and response pointers.
1177 std::unique_ptr<IXML_Document, decltype(ixmlDocument_free)&>
1178 action(nullptr, ixmlDocument_free); // Action pointer.
1179 std::unique_ptr<IXML_Document, decltype(ixmlDocument_free)&>
1180 response(nullptr, ixmlDocument_free); // Response pointer.
1181
1182 // Set action name.
1183 static constexpr const char* action_name {"GetExternalIPAddress"};
1184
1185 IXML_Document* action_container_ptr = nullptr;
1186 action_container_ptr = UpnpMakeAction(action_name, igd.getServiceType().c_str(), 0, nullptr);
1187 action.reset(action_container_ptr);
1188
1189 if (not action) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001190 if (logger_) logger_->warn("PUPnP: Failed to make GetExternalIPAddress action");
Adrien Béraud612b55b2023-05-29 10:42:04 -04001191 return {};
1192 }
1193
1194 IXML_Document* response_container_ptr = nullptr;
1195 int upnp_err = UpnpSendAction(ctrlptHandle_,
1196 igd.getControlURL().c_str(),
1197 igd.getServiceType().c_str(),
1198 nullptr,
1199 action.get(),
1200 &response_container_ptr);
1201 response.reset(response_container_ptr);
1202
1203 if (not response or upnp_err != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001204 if (logger_) logger_->warn("PUPnP: Failed to send GetExternalIPAddress action -> {}",
1205 UpnpGetErrorMessage(upnp_err));
Adrien Béraud612b55b2023-05-29 10:42:04 -04001206 return {};
1207 }
1208
1209 if (errorOnResponse(response.get())) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001210 if (logger_) logger_->warn("PUPnP: Failed to get GetExternalIPAddress from {} -> {:d}: {}",
1211 igd.getServiceType(),
1212 upnp_err,
1213 UpnpGetErrorMessage(upnp_err));
Adrien Béraud612b55b2023-05-29 10:42:04 -04001214 return {};
1215 }
1216
1217 return {getFirstDocItem(response.get(), "NewExternalIPAddress")};
1218}
1219
1220std::map<Mapping::key_t, Mapping>
1221PUPnP::getMappingsListByDescr(const std::shared_ptr<IGD>& igd, const std::string& description) const
1222{
1223 auto upnpIgd = std::dynamic_pointer_cast<UPnPIGD>(igd);
1224 assert(upnpIgd);
1225
1226 std::map<Mapping::key_t, Mapping> mapList;
1227
1228 if (not clientRegistered_ or not upnpIgd->isValid() or not upnpIgd->getLocalIp())
1229 return mapList;
1230
1231 // Set action name.
1232 static constexpr const char* action_name {"GetGenericPortMappingEntry"};
1233
1234 for (int entry_idx = 0;; entry_idx++) {
1235 std::unique_ptr<IXML_Document, decltype(ixmlDocument_free)&>
1236 action(nullptr, ixmlDocument_free); // Action pointer.
1237 IXML_Document* action_container_ptr = nullptr;
1238
1239 std::unique_ptr<IXML_Document, decltype(ixmlDocument_free)&>
1240 response(nullptr, ixmlDocument_free); // Response pointer.
1241 IXML_Document* response_container_ptr = nullptr;
1242
1243 UpnpAddToAction(&action_container_ptr,
1244 action_name,
1245 upnpIgd->getServiceType().c_str(),
1246 "NewPortMappingIndex",
1247 std::to_string(entry_idx).c_str());
1248 action.reset(action_container_ptr);
1249
1250 if (not action) {
Morteza Namvar5f639522023-07-04 17:08:58 -04001251 // JAMI_WARN("PUPnP: Failed to add NewPortMappingIndex action");
Adrien Béraud612b55b2023-05-29 10:42:04 -04001252 break;
1253 }
1254
1255 int upnp_err = UpnpSendAction(ctrlptHandle_,
1256 upnpIgd->getControlURL().c_str(),
1257 upnpIgd->getServiceType().c_str(),
1258 nullptr,
1259 action.get(),
1260 &response_container_ptr);
1261 response.reset(response_container_ptr);
1262
1263 if (not response) {
1264 // No existing mapping. Abort silently.
1265 break;
1266 }
1267
1268 if (upnp_err != UPNP_E_SUCCESS) {
Morteza Namvar5f639522023-07-04 17:08:58 -04001269 // JAMI_ERR("PUPnP: GetGenericPortMappingEntry returned with error: %i", upnp_err);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001270 break;
1271 }
1272
1273 // Check error code.
1274 auto errorCode = getFirstDocItem(response.get(), "errorCode");
1275 if (not errorCode.empty()) {
1276 auto error = to_int<int>(errorCode);
1277 if (error == ARRAY_IDX_INVALID or error == CONFLICT_IN_MAPPING) {
1278 // No more port mapping entries in the response.
Morteza Namvar5f639522023-07-04 17:08:58 -04001279 // JAMI_DBG("PUPnP: No more mappings (found a total of %i mappings", entry_idx);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001280 break;
1281 } else {
1282 auto errorDescription = getFirstDocItem(response.get(), "errorDescription");
Adrien Béraud370257c2023-08-15 20:53:09 -04001283 if (logger_) logger_->error("PUPnP: GetGenericPortMappingEntry returned with error: {:s}: {:s}",
Adrien Béraud612b55b2023-05-29 10:42:04 -04001284 errorCode,
1285 errorDescription);
1286 break;
1287 }
1288 }
1289
1290 // Parse the response.
1291 auto desc_actual = getFirstDocItem(response.get(), "NewPortMappingDescription");
1292 auto client_ip = getFirstDocItem(response.get(), "NewInternalClient");
1293
1294 if (client_ip != getHostAddress().toString()) {
1295 // Silently ignore un-matching addresses.
1296 continue;
1297 }
1298
1299 if (desc_actual.find(description) == std::string::npos)
1300 continue;
1301
1302 auto port_internal = getFirstDocItem(response.get(), "NewInternalPort");
1303 auto port_external = getFirstDocItem(response.get(), "NewExternalPort");
1304 std::string transport(getFirstDocItem(response.get(), "NewProtocol"));
1305
1306 if (port_internal.empty() || port_external.empty() || transport.empty()) {
Adrien Béraud370257c2023-08-15 20:53:09 -04001307 // if (logger_) logger_->e("PUPnP: GetGenericPortMappingEntry returned an invalid entry at index %i",
Morteza Namvar5f639522023-07-04 17:08:58 -04001308 // entry_idx);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001309 continue;
1310 }
1311
1312 std::transform(transport.begin(), transport.end(), transport.begin(), ::toupper);
1313 PortType type = transport.find("TCP") != std::string::npos ? PortType::TCP : PortType::UDP;
1314 auto ePort = to_int<uint16_t>(port_external);
1315 auto iPort = to_int<uint16_t>(port_internal);
1316
1317 Mapping map(type, ePort, iPort);
1318 map.setIgd(igd);
1319
1320 mapList.emplace(map.getMapKey(), std::move(map));
1321 }
1322
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001323 if (logger_) logger_->debug("PUPnP: Found {:d} allocated mappings on IGD {:s}",
1324 mapList.size(),
1325 upnpIgd->toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001326
1327 return mapList;
1328}
1329
1330void
1331PUPnP::deleteMappingsByDescription(const std::shared_ptr<IGD>& igd, const std::string& description)
1332{
1333 if (not(clientRegistered_ and igd->getLocalIp()))
1334 return;
1335
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001336 if (logger_) logger_->debug("PUPnP: Remove all mappings (if any) on IGD {} matching descr prefix {}",
1337 igd->toString(),
1338 Mapping::UPNP_MAPPING_DESCRIPTION_PREFIX);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001339
Adrien Béraud370257c2023-08-15 20:53:09 -04001340 ioContext->post([w=weak(), igd, description]{
1341 if (auto sthis = w.lock()) {
1342 auto mapList = sthis->getMappingsListByDescr(igd, description);
1343 for (auto const& [_, map] : mapList) {
1344 sthis->requestMappingRemove(map);
1345 }
1346 }
1347 });
Adrien Béraud612b55b2023-05-29 10:42:04 -04001348}
1349
1350bool
1351PUPnP::actionAddPortMapping(const Mapping& mapping)
1352{
Adrien Béraud612b55b2023-05-29 10:42:04 -04001353 if (not clientRegistered_)
1354 return false;
1355
1356 auto igdIn = std::dynamic_pointer_cast<UPnPIGD>(mapping.getIgd());
1357 if (not igdIn)
1358 return false;
1359
1360 // The requested IGD must be present in the list of local valid IGDs.
1361 auto igd = findMatchingIgd(igdIn->getControlURL());
1362
1363 if (not igd or not igd->isValid())
1364 return false;
1365
1366 // Action and response pointers.
1367 XMLDocument action(nullptr, ixmlDocument_free);
1368 IXML_Document* action_container_ptr = nullptr;
1369 XMLDocument response(nullptr, ixmlDocument_free);
1370 IXML_Document* response_container_ptr = nullptr;
1371
1372 // Set action sequence.
1373 UpnpAddToAction(&action_container_ptr,
1374 ACTION_ADD_PORT_MAPPING,
1375 igd->getServiceType().c_str(),
1376 "NewRemoteHost",
1377 "");
1378 UpnpAddToAction(&action_container_ptr,
1379 ACTION_ADD_PORT_MAPPING,
1380 igd->getServiceType().c_str(),
1381 "NewExternalPort",
1382 mapping.getExternalPortStr().c_str());
1383 UpnpAddToAction(&action_container_ptr,
1384 ACTION_ADD_PORT_MAPPING,
1385 igd->getServiceType().c_str(),
1386 "NewProtocol",
1387 mapping.getTypeStr());
1388 UpnpAddToAction(&action_container_ptr,
1389 ACTION_ADD_PORT_MAPPING,
1390 igd->getServiceType().c_str(),
1391 "NewInternalPort",
1392 mapping.getInternalPortStr().c_str());
1393 UpnpAddToAction(&action_container_ptr,
1394 ACTION_ADD_PORT_MAPPING,
1395 igd->getServiceType().c_str(),
1396 "NewInternalClient",
1397 getHostAddress().toString().c_str());
1398 UpnpAddToAction(&action_container_ptr,
1399 ACTION_ADD_PORT_MAPPING,
1400 igd->getServiceType().c_str(),
1401 "NewEnabled",
1402 "1");
1403 UpnpAddToAction(&action_container_ptr,
1404 ACTION_ADD_PORT_MAPPING,
1405 igd->getServiceType().c_str(),
1406 "NewPortMappingDescription",
1407 mapping.toString().c_str());
1408 UpnpAddToAction(&action_container_ptr,
1409 ACTION_ADD_PORT_MAPPING,
1410 igd->getServiceType().c_str(),
1411 "NewLeaseDuration",
1412 "0");
1413
1414 action.reset(action_container_ptr);
1415
1416 int upnp_err = UpnpSendAction(ctrlptHandle_,
1417 igd->getControlURL().c_str(),
1418 igd->getServiceType().c_str(),
1419 nullptr,
1420 action.get(),
1421 &response_container_ptr);
1422 response.reset(response_container_ptr);
1423
1424 bool success = true;
1425
1426 if (upnp_err != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001427 if (logger_) {
1428 logger_->warn("PUPnP: Failed to send action {} for mapping {}. {:d}: {}",
1429 ACTION_ADD_PORT_MAPPING,
1430 mapping.toString(),
1431 upnp_err,
1432 UpnpGetErrorMessage(upnp_err));
1433 logger_->warn("PUPnP: IGD ctrlUrl {}", igd->getControlURL());
1434 logger_->warn("PUPnP: IGD service type {}", igd->getServiceType());
1435 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001436
1437 success = false;
1438 }
1439
1440 // Check if an error has occurred.
1441 auto errorCode = getFirstDocItem(response.get(), "errorCode");
1442 if (not errorCode.empty()) {
1443 success = false;
1444 // Try to get the error description.
1445 std::string errorDescription;
1446 if (response) {
1447 errorDescription = getFirstDocItem(response.get(), "errorDescription");
1448 }
1449
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001450 if (logger_) logger_->warn("PUPnP: {:s} returned with error: {:s} {:s}",
1451 ACTION_ADD_PORT_MAPPING,
1452 errorCode,
1453 errorDescription);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001454 }
1455 return success;
1456}
1457
1458bool
1459PUPnP::actionDeletePortMapping(const Mapping& mapping)
1460{
Adrien Béraud612b55b2023-05-29 10:42:04 -04001461 if (not clientRegistered_)
1462 return false;
1463
1464 auto igdIn = std::dynamic_pointer_cast<UPnPIGD>(mapping.getIgd());
1465 if (not igdIn)
1466 return false;
1467
1468 // The requested IGD must be present in the list of local valid IGDs.
1469 auto igd = findMatchingIgd(igdIn->getControlURL());
1470
1471 if (not igd or not igd->isValid())
1472 return false;
1473
1474 // Action and response pointers.
1475 XMLDocument action(nullptr, ixmlDocument_free);
1476 IXML_Document* action_container_ptr = nullptr;
1477 XMLDocument response(nullptr, ixmlDocument_free);
1478 IXML_Document* response_container_ptr = nullptr;
1479
1480 // Set action sequence.
1481 UpnpAddToAction(&action_container_ptr,
1482 ACTION_DELETE_PORT_MAPPING,
1483 igd->getServiceType().c_str(),
1484 "NewRemoteHost",
1485 "");
1486 UpnpAddToAction(&action_container_ptr,
1487 ACTION_DELETE_PORT_MAPPING,
1488 igd->getServiceType().c_str(),
1489 "NewExternalPort",
1490 mapping.getExternalPortStr().c_str());
1491 UpnpAddToAction(&action_container_ptr,
1492 ACTION_DELETE_PORT_MAPPING,
1493 igd->getServiceType().c_str(),
1494 "NewProtocol",
1495 mapping.getTypeStr());
1496
1497 action.reset(action_container_ptr);
1498
1499 int upnp_err = UpnpSendAction(ctrlptHandle_,
1500 igd->getControlURL().c_str(),
1501 igd->getServiceType().c_str(),
1502 nullptr,
1503 action.get(),
1504 &response_container_ptr);
1505 response.reset(response_container_ptr);
1506
1507 bool success = true;
1508
1509 if (upnp_err != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001510 if (logger_) {
1511 logger_->warn("PUPnP: Failed to send action {} for mapping from {}. {:d}: {}",
1512 ACTION_DELETE_PORT_MAPPING,
1513 mapping.toString(),
1514 upnp_err,
1515 UpnpGetErrorMessage(upnp_err));
1516 logger_->warn("PUPnP: IGD ctrlUrl {}", igd->getControlURL());
1517 logger_->warn("PUPnP: IGD service type {}", igd->getServiceType());
1518 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001519 success = false;
1520 }
1521
1522 if (not response) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001523 if (logger_) logger_->warn("PUPnP: Failed to get response for {}", ACTION_DELETE_PORT_MAPPING);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001524 success = false;
1525 }
1526
1527 // Check if there is an error code.
1528 auto errorCode = getFirstDocItem(response.get(), "errorCode");
1529 if (not errorCode.empty()) {
1530 auto errorDescription = getFirstDocItem(response.get(), "errorDescription");
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001531 if (logger_) logger_->warn("PUPnP: {:s} returned with error: {:s}: {:s}",
1532 ACTION_DELETE_PORT_MAPPING,
1533 errorCode,
1534 errorDescription);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001535 success = false;
1536 }
1537
1538 return success;
1539}
1540
1541} // namespace upnp
Sébastien Blin464bdff2023-07-19 08:02:53 -04001542} // namespace dhtnet