blob: b902e00576b46aa6e7f95d683429befa2f699f03 [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_);
114
115 int upnp_err = UpnpInit2(nullptr, 0);
116
117 if (upnp_err != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400118 if (logger_) logger_->error("PUPnP: Can't initialize libupnp: {}", UpnpGetErrorMessage(upnp_err));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400119 UpnpFinish();
120 initialized_ = false;
121 return;
122 }
123
124 // Disable embedded WebServer if any.
125 if (UpnpIsWebserverEnabled() == 1) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400126 if (logger_) logger_->warn("PUPnP: Web-server is enabled. Disabling");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400127 UpnpEnableWebserver(0);
128 if (UpnpIsWebserverEnabled() == 1) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400129 if (logger_) logger_->error("PUPnP: Could not disable Web-server!");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400130 } else {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400131 if (logger_) logger_->debug("PUPnP: Web-server successfully disabled");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400132 }
133 }
134
135 char* ip_address = UpnpGetServerIpAddress();
136 char* ip_address6 = nullptr;
137 unsigned short port = UpnpGetServerPort();
138 unsigned short port6 = 0;
139#if UPNP_ENABLE_IPV6
140 ip_address6 = UpnpGetServerIp6Address();
141 port6 = UpnpGetServerPort6();
142#endif
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400143 if (logger_) {
144 if (ip_address6 and port6)
145 logger_->debug("PUPnP: Initialized on {}:{:d} | {}:{:d}", ip_address, port, ip_address6, port6);
146 else
147 logger_->debug("PUPnP: Initialized on {}:{:d}", ip_address, port);
148 }
Adrien Béraud612b55b2023-05-29 10:42:04 -0400149
150 // Relax the parser to allow malformed XML text.
151 ixmlRelaxParser(1);
152
153 initialized_ = true;
154}
155
156bool
157PUPnP::isRunning() const
158{
159 std::unique_lock<std::mutex> lk(pupnpMutex_);
160 return not shutdownComplete_;
161}
162
163void
164PUPnP::registerClient()
165{
166 assert(not clientRegistered_);
167
Adrien Béraud612b55b2023-05-29 10:42:04 -0400168 // Register Upnp control point.
169 int upnp_err = UpnpRegisterClient(ctrlPtCallback, this, &ctrlptHandle_);
170 if (upnp_err != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400171 if (logger_) logger_->error("PUPnP: Can't register client: {}", UpnpGetErrorMessage(upnp_err));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400172 } else {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400173 if (logger_) logger_->debug("PUPnP: Successfully registered client");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400174 clientRegistered_ = true;
175 }
176}
177
178void
179PUPnP::setObserver(UpnpMappingObserver* obs)
180{
Adrien Béraud612b55b2023-05-29 10:42:04 -0400181 observer_ = obs;
182}
183
184const IpAddr
185PUPnP::getHostAddress() const
186{
187 std::lock_guard<std::mutex> lock(pupnpMutex_);
188 return hostAddress_;
189}
190
191void
192PUPnP::terminate(std::condition_variable& cv)
193{
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400194 if (logger_) logger_->debug("PUPnP: Terminate instance {}", fmt::ptr(this));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400195
196 clientRegistered_ = false;
197 observer_ = nullptr;
198
199 UpnpUnRegisterClient(ctrlptHandle_);
200
201 if (initialized_) {
202 if (UpnpFinish() != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400203 if (logger_) logger_->error("PUPnP: Failed to properly close lib-upnp");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400204 }
205
206 initialized_ = false;
207 }
208
209 // Clear all the lists.
210 discoveredIgdList_.clear();
211
212 {
213 std::lock_guard<std::mutex> lock(pupnpMutex_);
214 validIgdList_.clear();
215 shutdownComplete_ = true;
216 cv.notify_one();
217 }
218}
219
220void
221PUPnP::terminate()
222{
223 std::unique_lock<std::mutex> lk(pupnpMutex_);
224 std::condition_variable cv {};
225
Adrien Béraud370257c2023-08-15 20:53:09 -0400226 ioContext->dispatch([&] {
227 terminate(cv);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400228 });
229
230 if (cv.wait_for(lk, std::chrono::seconds(10), [this] { return shutdownComplete_; })) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400231 if (logger_) logger_->debug("PUPnP: Shutdown completed");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400232 } else {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400233 if (logger_) logger_->error("PUPnP: Shutdown timed-out");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400234 // Force stop if the shutdown take too much time.
235 shutdownComplete_ = true;
236 }
237}
238
239void
240PUPnP::searchForDevices()
241{
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400242 if (logger_) logger_->debug("PUPnP: Send IGD search request");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400243
244 // Send out search for multiple types of devices, as some routers may possibly
245 // only reply to one.
246
247 auto err = UpnpSearchAsync(ctrlptHandle_, SEARCH_TIMEOUT, UPNP_ROOT_DEVICE, this);
248 if (err != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400249 if (logger_) logger_->warn("PUPnP: Send search for UPNP_ROOT_DEVICE failed. Error {:d}: {}",
250 err,
251 UpnpGetErrorMessage(err));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400252 }
253
254 err = UpnpSearchAsync(ctrlptHandle_, SEARCH_TIMEOUT, UPNP_IGD_DEVICE, this);
255 if (err != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400256 if (logger_) logger_->warn("PUPnP: Send search for UPNP_IGD_DEVICE failed. Error {:d}: {}",
257 err,
258 UpnpGetErrorMessage(err));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400259 }
260
261 err = UpnpSearchAsync(ctrlptHandle_, SEARCH_TIMEOUT, UPNP_WANIP_SERVICE, this);
262 if (err != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400263 if (logger_) logger_->warn("PUPnP: Send search for UPNP_WANIP_SERVICE failed. Error {:d}: {}",
264 err,
265 UpnpGetErrorMessage(err));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400266 }
267
268 err = UpnpSearchAsync(ctrlptHandle_, SEARCH_TIMEOUT, UPNP_WANPPP_SERVICE, this);
269 if (err != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400270 if (logger_) logger_->warn("PUPnP: Send search for UPNP_WANPPP_SERVICE failed. Error {:d}: {}",
271 err,
272 UpnpGetErrorMessage(err));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400273 }
274}
275
276void
277PUPnP::clearIgds()
278{
Morteza Namvar5f639522023-07-04 17:08:58 -0400279 // JAMI_DBG("PUPnP: clearing IGDs and devices lists");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400280
Adrien Béraud370257c2023-08-15 20:53:09 -0400281 searchForIgdTimer_.cancel();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400282
283 igdSearchCounter_ = 0;
284
285 {
286 std::lock_guard<std::mutex> lock(pupnpMutex_);
287 for (auto const& igd : validIgdList_) {
288 igd->setValid(false);
289 }
290 validIgdList_.clear();
291 hostAddress_ = {};
292 }
293
294 discoveredIgdList_.clear();
295}
296
297void
298PUPnP::searchForIgd()
299{
Adrien Béraud612b55b2023-05-29 10:42:04 -0400300 // Update local address before searching.
301 updateHostAddress();
302
303 if (isReady()) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400304 if (logger_) logger_->debug("PUPnP: Already have a valid IGD. Skip the search request");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400305 return;
306 }
307
308 if (igdSearchCounter_++ >= PUPNP_MAX_RESTART_SEARCH_RETRIES) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400309 if (logger_) logger_->warn("PUPnP: Setup failed after {:d} trials. PUPnP will be disabled!",
310 PUPNP_MAX_RESTART_SEARCH_RETRIES);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400311 return;
312 }
313
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400314 if (logger_) logger_->debug("PUPnP: Start search for IGD: attempt {:d}", igdSearchCounter_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400315
316 // Do not init if the host is not valid. Otherwise, the init will fail
317 // anyway and may put libupnp in an unstable state (mainly deadlocks)
318 // even if the UpnpFinish() method is called.
319 if (not hasValidHostAddress()) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400320 if (logger_) logger_->warn("PUPnP: Host address is invalid. Skipping the IGD search");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400321 } else {
322 // Init and register if needed
323 if (not initialized_) {
324 initUpnpLib();
325 }
326 if (initialized_ and not clientRegistered_) {
327 registerClient();
328 }
329 // Start searching
330 if (clientRegistered_) {
331 assert(initialized_);
332 searchForDevices();
333 } else {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400334 if (logger_) logger_->warn("PUPnP: PUPNP not fully setup. Skipping the IGD search");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400335 }
336 }
337
338 // Cancel the current timer (if any) and re-schedule.
339 // The connectivity change may be received while the the local
340 // interface is not fully setup. The rescheduling typically
341 // usefull to mitigate this race.
Adrien Béraud370257c2023-08-15 20:53:09 -0400342 searchForIgdTimer_.expires_after(PUPNP_SEARCH_RETRY_UNIT * igdSearchCounter_);
343 searchForIgdTimer_.async_wait([w = weak()] (const asio::error_code& ec) {
344 if (not ec) {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400345 if (auto upnpThis = w.lock())
346 upnpThis->searchForIgd();
Adrien Béraud370257c2023-08-15 20:53:09 -0400347 }
348 });
Adrien Béraud612b55b2023-05-29 10:42:04 -0400349}
350
351std::list<std::shared_ptr<IGD>>
352PUPnP::getIgdList() const
353{
354 std::lock_guard<std::mutex> lock(pupnpMutex_);
355 std::list<std::shared_ptr<IGD>> igdList;
356 for (auto& it : validIgdList_) {
357 // Return only active IGDs.
358 if (it->isValid()) {
359 igdList.emplace_back(it);
360 }
361 }
362 return igdList;
363}
364
365bool
366PUPnP::isReady() const
367{
368 // Must at least have a valid local address.
369 if (not getHostAddress() or getHostAddress().isLoopback())
370 return false;
371
372 return hasValidIgd();
373}
374
375bool
376PUPnP::hasValidIgd() const
377{
378 std::lock_guard<std::mutex> lock(pupnpMutex_);
379 for (auto& it : validIgdList_) {
380 if (it->isValid()) {
381 return true;
382 }
383 }
384 return false;
385}
386
387void
388PUPnP::updateHostAddress()
389{
390 std::lock_guard<std::mutex> lock(pupnpMutex_);
391 hostAddress_ = ip_utils::getLocalAddr(AF_INET);
392}
393
394bool
395PUPnP::hasValidHostAddress()
396{
397 std::lock_guard<std::mutex> lock(pupnpMutex_);
398 return hostAddress_ and not hostAddress_.isLoopback();
399}
400
401void
402PUPnP::incrementErrorsCounter(const std::shared_ptr<IGD>& igd)
403{
404 if (not igd or not igd->isValid())
405 return;
406 if (not igd->incrementErrorsCounter()) {
407 // Disable this IGD.
408 igd->setValid(false);
409 // Notify the listener.
410 if (observer_)
411 observer_->onIgdUpdated(igd, UpnpIgdEvent::INVALID_STATE);
412 }
413}
414
415bool
416PUPnP::validateIgd(const std::string& location, IXML_Document* doc_container_ptr)
417{
Adrien Béraud612b55b2023-05-29 10:42:04 -0400418 assert(doc_container_ptr != nullptr);
419
420 XMLDocument document(doc_container_ptr, ixmlDocument_free);
421 auto descDoc = document.get();
422 // Check device type.
423 auto deviceType = getFirstDocItem(descDoc, "deviceType");
424 if (deviceType != UPNP_IGD_DEVICE) {
425 // Device type not IGD.
426 return false;
427 }
428
429 std::shared_ptr<UPnPIGD> igd_candidate = parseIgd(descDoc, location);
430 if (not igd_candidate) {
431 // No valid IGD candidate.
432 return false;
433 }
434
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400435 if (logger_) logger_->debug("PUPnP: Validating the IGD candidate [UDN: {}]\n"
436 " Name : {}\n"
437 " Service Type : {}\n"
438 " Service ID : {}\n"
439 " Base URL : {}\n"
440 " Location URL : {}\n"
441 " control URL : {}\n"
442 " Event URL : {}",
443 igd_candidate->getUID(),
444 igd_candidate->getFriendlyName(),
445 igd_candidate->getServiceType(),
446 igd_candidate->getServiceId(),
447 igd_candidate->getBaseURL(),
448 igd_candidate->getLocationURL(),
449 igd_candidate->getControlURL(),
450 igd_candidate->getEventSubURL());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400451
452 // Check if IGD is connected.
453 if (not actionIsIgdConnected(*igd_candidate)) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400454 if (logger_) logger_->warn("PUPnP: IGD candidate {} is not connected", igd_candidate->getUID().c_str());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400455 return false;
456 }
457
458 // Validate external Ip.
459 igd_candidate->setPublicIp(actionGetExternalIP(*igd_candidate));
460 if (igd_candidate->getPublicIp().toString().empty()) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400461 if (logger_) logger_->warn("PUPnP: IGD candidate {} has no valid external Ip",
462 igd_candidate->getUID().c_str());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400463 return false;
464 }
465
466 // Validate internal Ip.
467 if (igd_candidate->getBaseURL().empty()) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400468 if (logger_) logger_->warn("PUPnP: IGD candidate {} has no valid internal Ip",
469 igd_candidate->getUID().c_str());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400470 return false;
471 }
472
473 // Typically the IGD local address should be extracted from the XML
474 // document (e.g. parsing the base URL). For simplicity, we assume
475 // that it matches the gateway as seen by the local interface.
476 if (const auto& localGw = ip_utils::getLocalGateway()) {
477 igd_candidate->setLocalIp(localGw);
478 } else {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400479 if (logger_) logger_->warn("PUPnP: Could not set internal address for IGD candidate {}",
480 igd_candidate->getUID().c_str());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400481 return false;
482 }
483
484 // Store info for subscription.
485 std::string eventSub = igd_candidate->getEventSubURL();
486
487 {
488 // Add the IGD if not already present in the list.
489 std::lock_guard<std::mutex> lock(pupnpMutex_);
490 for (auto& igd : validIgdList_) {
491 // Must not be a null pointer
492 assert(igd.get() != nullptr);
493 if (*igd == *igd_candidate) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400494 if (logger_) logger_->debug("PUPnP: Device [{}] with int/ext addresses [{}:{}] is already in the list of valid IGDs",
495 igd_candidate->getUID(),
496 igd_candidate->toString(),
497 igd_candidate->getPublicIp().toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400498 return true;
499 }
500 }
501 }
502
503 // We have a valid IGD
504 igd_candidate->setValid(true);
505
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400506 if (logger_) logger_->debug("PUPnP: Added a new IGD [{}] to the list of valid IGDs",
507 igd_candidate->getUID());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400508
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400509 if (logger_) logger_->debug("PUPnP: New IGD addresses [int: {} - ext: {}]",
510 igd_candidate->toString(),
511 igd_candidate->getPublicIp().toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400512
513 // Subscribe to IGD events.
514 int upnp_err = UpnpSubscribeAsync(ctrlptHandle_,
515 eventSub.c_str(),
516 UPNP_INFINITE,
517 subEventCallback,
518 this);
519 if (upnp_err != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400520 if (logger_) logger_->warn("PUPnP: Failed to send subscribe request to {}: error %i - {}",
521 igd_candidate->getUID(),
522 upnp_err,
523 UpnpGetErrorMessage(upnp_err));
524 return false;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400525 } else {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400526 if (logger_) logger_->debug("PUPnP: Successfully subscribed to IGD {}", igd_candidate->getUID());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400527 }
528
529 {
530 // This is a new (and hopefully valid) IGD.
531 std::lock_guard<std::mutex> lock(pupnpMutex_);
532 validIgdList_.emplace_back(igd_candidate);
533 }
534
535 // Report to the listener.
Adrien Béraud370257c2023-08-15 20:53:09 -0400536 ioContext->post([w = weak(), igd_candidate] {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400537 if (auto upnpThis = w.lock()) {
538 if (upnpThis->observer_)
539 upnpThis->observer_->onIgdUpdated(igd_candidate, UpnpIgdEvent::ADDED);
540 }
541 });
542
543 return true;
544}
545
546void
547PUPnP::requestMappingAdd(const Mapping& mapping)
548{
Adrien Béraud370257c2023-08-15 20:53:09 -0400549 ioContext->post([w = weak(), mapping] {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400550 if (auto upnpThis = w.lock()) {
551 if (not upnpThis->isRunning())
552 return;
553 Mapping mapRes(mapping);
554 if (upnpThis->actionAddPortMapping(mapRes)) {
555 mapRes.setState(MappingState::OPEN);
556 mapRes.setInternalAddress(upnpThis->getHostAddress().toString());
557 upnpThis->processAddMapAction(mapRes);
558 } else {
559 upnpThis->incrementErrorsCounter(mapRes.getIgd());
560 mapRes.setState(MappingState::FAILED);
561 upnpThis->processRequestMappingFailure(mapRes);
562 }
563 }
564 });
565}
566
567void
568PUPnP::requestMappingRemove(const Mapping& mapping)
569{
570 // Send remove request using the matching IGD
Adrien Béraud370257c2023-08-15 20:53:09 -0400571 ioContext->dispatch([w = weak(), mapping] {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400572 if (auto upnpThis = w.lock()) {
573 // Abort if we are shutting down.
574 if (not upnpThis->isRunning())
575 return;
576 if (upnpThis->actionDeletePortMapping(mapping)) {
577 upnpThis->processRemoveMapAction(mapping);
578 } else {
579 assert(mapping.getIgd());
580 // Dont need to report in case of failure.
581 upnpThis->incrementErrorsCounter(mapping.getIgd());
582 }
583 }
584 });
585}
586
587std::shared_ptr<UPnPIGD>
588PUPnP::findMatchingIgd(const std::string& ctrlURL) const
589{
590 std::lock_guard<std::mutex> lock(pupnpMutex_);
591
592 auto iter = std::find_if(validIgdList_.begin(),
593 validIgdList_.end(),
594 [&ctrlURL](const std::shared_ptr<IGD>& igd) {
595 if (auto upnpIgd = std::dynamic_pointer_cast<UPnPIGD>(igd)) {
596 return upnpIgd->getControlURL() == ctrlURL;
597 }
598 return false;
599 });
600
601 if (iter == validIgdList_.end()) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400602 if (logger_) logger_->warn("PUPnP: Did not find the IGD matching ctrl URL [{}]", ctrlURL);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400603 return {};
604 }
605
606 return std::dynamic_pointer_cast<UPnPIGD>(*iter);
607}
608
609void
610PUPnP::processAddMapAction(const Mapping& map)
611{
Adrien Béraud612b55b2023-05-29 10:42:04 -0400612 if (observer_ == nullptr)
613 return;
614
Adrien Béraud370257c2023-08-15 20:53:09 -0400615 ioContext->post([w = weak(), map] {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400616 if (auto upnpThis = w.lock()) {
617 if (upnpThis->observer_)
618 upnpThis->observer_->onMappingAdded(map.getIgd(), std::move(map));
619 }
620 });
621}
622
623void
624PUPnP::processRequestMappingFailure(const Mapping& map)
625{
Adrien Béraud612b55b2023-05-29 10:42:04 -0400626 if (observer_ == nullptr)
627 return;
628
Adrien Béraud370257c2023-08-15 20:53:09 -0400629 ioContext->post([w = weak(), map] {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400630 if (auto upnpThis = w.lock()) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400631 if (upnpThis->logger_) upnpThis->logger_->warn("PUPnP: Closed mapping {}", map.toString());
Morteza Namvar5f639522023-07-04 17:08:58 -0400632 // JAMI_DBG("PUPnP: Failed to request mapping %s", map.toString().c_str());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400633 if (upnpThis->observer_)
634 upnpThis->observer_->onMappingRequestFailed(map);
635 }
636 });
637}
638
639void
640PUPnP::processRemoveMapAction(const Mapping& map)
641{
Adrien Béraud612b55b2023-05-29 10:42:04 -0400642 if (observer_ == nullptr)
643 return;
644
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400645 if (logger_) logger_->warn("PUPnP: Closed mapping {}", map.toString());
Adrien Béraud370257c2023-08-15 20:53:09 -0400646 ioContext->post([map, obs = observer_] {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400647 obs->onMappingRemoved(map.getIgd(), std::move(map));
648 });
649}
650
651const char*
652PUPnP::eventTypeToString(Upnp_EventType eventType)
653{
654 switch (eventType) {
655 case UPNP_CONTROL_ACTION_REQUEST:
656 return "UPNP_CONTROL_ACTION_REQUEST";
657 case UPNP_CONTROL_ACTION_COMPLETE:
658 return "UPNP_CONTROL_ACTION_COMPLETE";
659 case UPNP_CONTROL_GET_VAR_REQUEST:
660 return "UPNP_CONTROL_GET_VAR_REQUEST";
661 case UPNP_CONTROL_GET_VAR_COMPLETE:
662 return "UPNP_CONTROL_GET_VAR_COMPLETE";
663 case UPNP_DISCOVERY_ADVERTISEMENT_ALIVE:
664 return "UPNP_DISCOVERY_ADVERTISEMENT_ALIVE";
665 case UPNP_DISCOVERY_ADVERTISEMENT_BYEBYE:
666 return "UPNP_DISCOVERY_ADVERTISEMENT_BYEBYE";
667 case UPNP_DISCOVERY_SEARCH_RESULT:
668 return "UPNP_DISCOVERY_SEARCH_RESULT";
669 case UPNP_DISCOVERY_SEARCH_TIMEOUT:
670 return "UPNP_DISCOVERY_SEARCH_TIMEOUT";
671 case UPNP_EVENT_SUBSCRIPTION_REQUEST:
672 return "UPNP_EVENT_SUBSCRIPTION_REQUEST";
673 case UPNP_EVENT_RECEIVED:
674 return "UPNP_EVENT_RECEIVED";
675 case UPNP_EVENT_RENEWAL_COMPLETE:
676 return "UPNP_EVENT_RENEWAL_COMPLETE";
677 case UPNP_EVENT_SUBSCRIBE_COMPLETE:
678 return "UPNP_EVENT_SUBSCRIBE_COMPLETE";
679 case UPNP_EVENT_UNSUBSCRIBE_COMPLETE:
680 return "UPNP_EVENT_UNSUBSCRIBE_COMPLETE";
681 case UPNP_EVENT_AUTORENEWAL_FAILED:
682 return "UPNP_EVENT_AUTORENEWAL_FAILED";
683 case UPNP_EVENT_SUBSCRIPTION_EXPIRED:
684 return "UPNP_EVENT_SUBSCRIPTION_EXPIRED";
685 default:
686 return "Unknown UPNP Event";
687 }
688}
689
690int
691PUPnP::ctrlPtCallback(Upnp_EventType event_type, const void* event, void* user_data)
692{
693 auto pupnp = static_cast<PUPnP*>(user_data);
694
695 if (pupnp == nullptr) {
Morteza Namvar5f639522023-07-04 17:08:58 -0400696 // JAMI_WARN("PUPnP: Control point callback without PUPnP");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400697 return UPNP_E_SUCCESS;
698 }
699
700 auto upnpThis = pupnp->weak().lock();
701
702 if (not upnpThis)
703 return UPNP_E_SUCCESS;
704
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 Béraud4f7e8012023-08-16 15:28:18 -0400752 if (logger_) logger_->warn("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