blob: 432ea607cc55414d39a581c829750bc9534b5921 [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
Adrien Béraud612b55b2023-05-29 10:42:04 -040020#include <opendht/http.h>
21
Adrien Béraud1ae60aa2023-07-07 09:55:09 -040022namespace dhtnet {
Adrien Béraud612b55b2023-05-29 10:42:04 -040023namespace upnp {
24
25// Action identifiers.
26constexpr static const char* ACTION_ADD_PORT_MAPPING {"AddPortMapping"};
27constexpr static const char* ACTION_DELETE_PORT_MAPPING {"DeletePortMapping"};
28constexpr static const char* ACTION_GET_GENERIC_PORT_MAPPING_ENTRY {"GetGenericPortMappingEntry"};
29constexpr static const char* ACTION_GET_STATUS_INFO {"GetStatusInfo"};
30constexpr static const char* ACTION_GET_EXTERNAL_IP_ADDRESS {"GetExternalIPAddress"};
31
32// Error codes returned by router when trying to remove ports.
33constexpr static int ARRAY_IDX_INVALID = 713;
34constexpr static int CONFLICT_IN_MAPPING = 718;
35
36// Max number of IGD search attempts before failure.
37constexpr static unsigned int PUPNP_MAX_RESTART_SEARCH_RETRIES {3};
38// IGD search timeout (in seconds).
39constexpr static unsigned int SEARCH_TIMEOUT {60};
40// Base unit for the timeout between two successive IGD search.
41constexpr static auto PUPNP_SEARCH_RETRY_UNIT {std::chrono::seconds(10)};
42
43// Helper functions for xml parsing.
44static std::string_view
45getElementText(IXML_Node* node)
46{
47 if (node) {
48 if (IXML_Node* textNode = ixmlNode_getFirstChild(node))
49 if (const char* value = ixmlNode_getNodeValue(textNode))
50 return std::string_view(value);
51 }
52 return {};
53}
54
55static std::string_view
56getFirstDocItem(IXML_Document* doc, const char* item)
57{
58 std::unique_ptr<IXML_NodeList, decltype(ixmlNodeList_free)&>
59 nodeList(ixmlDocument_getElementsByTagName(doc, item), ixmlNodeList_free);
60 if (nodeList) {
61 // If there are several nodes which match the tag, we only want the first one.
62 return getElementText(ixmlNodeList_item(nodeList.get(), 0));
63 }
64 return {};
65}
66
67static std::string_view
68getFirstElementItem(IXML_Element* element, const char* item)
69{
70 std::unique_ptr<IXML_NodeList, decltype(ixmlNodeList_free)&>
71 nodeList(ixmlElement_getElementsByTagName(element, item), ixmlNodeList_free);
72 if (nodeList) {
73 // If there are several nodes which match the tag, we only want the first one.
74 return getElementText(ixmlNodeList_item(nodeList.get(), 0));
75 }
76 return {};
77}
78
79static bool
Adrien Béraudd78d1ac2023-08-25 10:43:33 -040080errorOnResponse(IXML_Document* doc, const std::shared_ptr<dht::log::Logger>& logger)
Adrien Béraud612b55b2023-05-29 10:42:04 -040081{
82 if (not doc)
83 return true;
84
85 auto errorCode = getFirstDocItem(doc, "errorCode");
86 if (not errorCode.empty()) {
87 auto errorDescription = getFirstDocItem(doc, "errorDescription");
Adrien Béraudd78d1ac2023-08-25 10:43:33 -040088 if (logger) logger->warn("PUPnP: Response contains error: {:s}: {:s}",
89 errorCode,
90 errorDescription);
Adrien Béraud612b55b2023-05-29 10:42:04 -040091 return true;
92 }
93 return false;
94}
95
96// UPNP class implementation
97
Adrien Béraud370257c2023-08-15 20:53:09 -040098PUPnP::PUPnP(const std::shared_ptr<asio::io_context>& ctx, const std::shared_ptr<dht::log::Logger>& logger)
99 : UPnPProtocol(logger), ioContext(ctx), searchForIgdTimer_(*ctx)
François-Simon Fauteux-Chapleau808db4f2024-04-19 11:39:47 -0400100 , ongoingOpsThreadPool_(1, 64)
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{
Adrien Béraud024c46f2024-03-02 23:53:18 -0500158 std::unique_lock lk(pupnpMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400159 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
François-Simon Fauteux-Chapleaud7976982024-04-26 16:06:23 -0400178PUPnP::unregisterClient()
179{
180 int upnp_err = UpnpUnRegisterClient(ctrlptHandle_);
181 if (upnp_err != UPNP_E_SUCCESS) {
182 if (logger_) logger_->error("PUPnP: Failed to unregister client: {}", UpnpGetErrorMessage(upnp_err));
183 } else {
184 if (logger_) logger_->debug("PUPnP: Successfully unregistered client");
185 clientRegistered_ = false;
186 }
187}
188
189void
Adrien Béraud612b55b2023-05-29 10:42:04 -0400190PUPnP::setObserver(UpnpMappingObserver* obs)
191{
Adrien Béraud612b55b2023-05-29 10:42:04 -0400192 observer_ = obs;
193}
194
195const IpAddr
196PUPnP::getHostAddress() const
197{
Adrien Béraud024c46f2024-03-02 23:53:18 -0500198 std::lock_guard lock(pupnpMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400199 return hostAddress_;
200}
201
202void
François-Simon Fauteux-Chapleau808db4f2024-04-19 11:39:47 -0400203PUPnP::terminate()
Adrien Béraud612b55b2023-05-29 10:42:04 -0400204{
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400205 if (logger_) logger_->debug("PUPnP: Terminate instance {}", fmt::ptr(this));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400206
207 clientRegistered_ = false;
208 observer_ = nullptr;
François-Simon Fauteux-Chapleau808db4f2024-04-19 11:39:47 -0400209 {
210 std::lock_guard lk(ongoingOpsMtx_);
211 destroying_ = true;
212 if (ongoingOps_ > 0) {
213 if (logger_) logger_->debug("PUPnP: {} ongoing operations, detaching corresponding threads", ongoingOps_);
214 ongoingOpsThreadPool_.detach();
215 }
216 }
Adrien Béraud612b55b2023-05-29 10:42:04 -0400217
218 UpnpUnRegisterClient(ctrlptHandle_);
219
220 if (initialized_) {
221 if (UpnpFinish() != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400222 if (logger_) logger_->error("PUPnP: Failed to properly close lib-upnp");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400223 }
224
225 initialized_ = false;
226 }
227
228 // Clear all the lists.
229 discoveredIgdList_.clear();
230
Adrien Béraud024c46f2024-03-02 23:53:18 -0500231 std::lock_guard lock(pupnpMutex_);
Adrien Béraud7a82bee2023-08-30 10:26:45 -0400232 validIgdList_.clear();
233 shutdownComplete_ = true;
François-Simon Fauteux-Chapleau808db4f2024-04-19 11:39:47 -0400234 if (logger_) logger_->debug("PUPnP: Instance {} terminated", fmt::ptr(this));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400235}
236
237void
238PUPnP::searchForDevices()
239{
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400240 if (logger_) logger_->debug("PUPnP: Send IGD search request");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400241
242 // Send out search for multiple types of devices, as some routers may possibly
243 // only reply to one.
244
245 auto err = UpnpSearchAsync(ctrlptHandle_, SEARCH_TIMEOUT, UPNP_ROOT_DEVICE, this);
246 if (err != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400247 if (logger_) logger_->warn("PUPnP: Send search for UPNP_ROOT_DEVICE failed. Error {:d}: {}",
248 err,
249 UpnpGetErrorMessage(err));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400250 }
251
252 err = UpnpSearchAsync(ctrlptHandle_, SEARCH_TIMEOUT, UPNP_IGD_DEVICE, this);
253 if (err != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400254 if (logger_) logger_->warn("PUPnP: Send search for UPNP_IGD_DEVICE failed. Error {:d}: {}",
255 err,
256 UpnpGetErrorMessage(err));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400257 }
258
259 err = UpnpSearchAsync(ctrlptHandle_, SEARCH_TIMEOUT, UPNP_WANIP_SERVICE, this);
260 if (err != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400261 if (logger_) logger_->warn("PUPnP: Send search for UPNP_WANIP_SERVICE failed. Error {:d}: {}",
262 err,
263 UpnpGetErrorMessage(err));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400264 }
265
266 err = UpnpSearchAsync(ctrlptHandle_, SEARCH_TIMEOUT, UPNP_WANPPP_SERVICE, this);
267 if (err != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400268 if (logger_) logger_->warn("PUPnP: Send search for UPNP_WANPPP_SERVICE failed. Error {:d}: {}",
269 err,
270 UpnpGetErrorMessage(err));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400271 }
272}
273
274void
275PUPnP::clearIgds()
276{
Morteza Namvar5f639522023-07-04 17:08:58 -0400277 // JAMI_DBG("PUPnP: clearing IGDs and devices lists");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400278
François-Simon Fauteux-Chapleaud7976982024-04-26 16:06:23 -0400279 // We need to unregister the client to make sure that we don't keep receiving and
280 // processing IGD-related events unnecessarily, see:
281 // https://git.jami.net/savoirfairelinux/dhtnet/-/issues/29
282 if (clientRegistered_)
283 unregisterClient();
284
Adrien Béraud370257c2023-08-15 20:53:09 -0400285 searchForIgdTimer_.cancel();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400286
287 igdSearchCounter_ = 0;
288
289 {
Adrien Béraud024c46f2024-03-02 23:53:18 -0500290 std::lock_guard lock(pupnpMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400291 for (auto const& igd : validIgdList_) {
292 igd->setValid(false);
293 }
294 validIgdList_.clear();
295 hostAddress_ = {};
296 }
297
298 discoveredIgdList_.clear();
299}
300
301void
302PUPnP::searchForIgd()
303{
Adrien Béraud612b55b2023-05-29 10:42:04 -0400304 // Update local address before searching.
305 updateHostAddress();
306
307 if (isReady()) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400308 if (logger_) logger_->debug("PUPnP: Already have a valid IGD. Skip the search request");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400309 return;
310 }
311
312 if (igdSearchCounter_++ >= PUPNP_MAX_RESTART_SEARCH_RETRIES) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400313 if (logger_) logger_->warn("PUPnP: Setup failed after {:d} trials. PUPnP will be disabled!",
314 PUPNP_MAX_RESTART_SEARCH_RETRIES);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400315 return;
316 }
317
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400318 if (logger_) logger_->debug("PUPnP: Start search for IGD: attempt {:d}", igdSearchCounter_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400319
320 // Do not init if the host is not valid. Otherwise, the init will fail
321 // anyway and may put libupnp in an unstable state (mainly deadlocks)
322 // even if the UpnpFinish() method is called.
323 if (not hasValidHostAddress()) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400324 if (logger_) logger_->warn("PUPnP: Host address is invalid. Skipping the IGD search");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400325 } else {
326 // Init and register if needed
327 if (not initialized_) {
328 initUpnpLib();
329 }
330 if (initialized_ and not clientRegistered_) {
331 registerClient();
332 }
333 // Start searching
334 if (clientRegistered_) {
335 assert(initialized_);
336 searchForDevices();
337 } else {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400338 if (logger_) logger_->warn("PUPnP: PUPNP not fully setup. Skipping the IGD search");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400339 }
340 }
341
342 // Cancel the current timer (if any) and re-schedule.
343 // The connectivity change may be received while the the local
344 // interface is not fully setup. The rescheduling typically
345 // usefull to mitigate this race.
Adrien Béraud370257c2023-08-15 20:53:09 -0400346 searchForIgdTimer_.expires_after(PUPNP_SEARCH_RETRY_UNIT * igdSearchCounter_);
347 searchForIgdTimer_.async_wait([w = weak()] (const asio::error_code& ec) {
348 if (not ec) {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400349 if (auto upnpThis = w.lock())
350 upnpThis->searchForIgd();
Adrien Béraud370257c2023-08-15 20:53:09 -0400351 }
352 });
Adrien Béraud612b55b2023-05-29 10:42:04 -0400353}
354
355std::list<std::shared_ptr<IGD>>
356PUPnP::getIgdList() const
357{
Adrien Béraud024c46f2024-03-02 23:53:18 -0500358 std::lock_guard lock(pupnpMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400359 std::list<std::shared_ptr<IGD>> igdList;
360 for (auto& it : validIgdList_) {
361 // Return only active IGDs.
362 if (it->isValid()) {
363 igdList.emplace_back(it);
364 }
365 }
366 return igdList;
367}
368
369bool
370PUPnP::isReady() const
371{
372 // Must at least have a valid local address.
373 if (not getHostAddress() or getHostAddress().isLoopback())
374 return false;
375
376 return hasValidIgd();
377}
378
379bool
380PUPnP::hasValidIgd() const
381{
Adrien Béraud024c46f2024-03-02 23:53:18 -0500382 std::lock_guard lock(pupnpMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400383 for (auto& it : validIgdList_) {
384 if (it->isValid()) {
385 return true;
386 }
387 }
388 return false;
389}
390
391void
392PUPnP::updateHostAddress()
393{
Adrien Béraud024c46f2024-03-02 23:53:18 -0500394 std::lock_guard lock(pupnpMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400395 hostAddress_ = ip_utils::getLocalAddr(AF_INET);
396}
397
398bool
399PUPnP::hasValidHostAddress()
400{
Adrien Béraud024c46f2024-03-02 23:53:18 -0500401 std::lock_guard lock(pupnpMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400402 return hostAddress_ and not hostAddress_.isLoopback();
403}
404
405void
406PUPnP::incrementErrorsCounter(const std::shared_ptr<IGD>& igd)
407{
408 if (not igd or not igd->isValid())
409 return;
410 if (not igd->incrementErrorsCounter()) {
411 // Disable this IGD.
412 igd->setValid(false);
413 // Notify the listener.
414 if (observer_)
415 observer_->onIgdUpdated(igd, UpnpIgdEvent::INVALID_STATE);
416 }
417}
418
419bool
420PUPnP::validateIgd(const std::string& location, IXML_Document* doc_container_ptr)
421{
Adrien Béraud612b55b2023-05-29 10:42:04 -0400422 assert(doc_container_ptr != nullptr);
423
424 XMLDocument document(doc_container_ptr, ixmlDocument_free);
425 auto descDoc = document.get();
426 // Check device type.
427 auto deviceType = getFirstDocItem(descDoc, "deviceType");
428 if (deviceType != UPNP_IGD_DEVICE) {
429 // Device type not IGD.
430 return false;
431 }
432
433 std::shared_ptr<UPnPIGD> igd_candidate = parseIgd(descDoc, location);
434 if (not igd_candidate) {
435 // No valid IGD candidate.
436 return false;
437 }
438
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400439 if (logger_) logger_->debug("PUPnP: Validating the IGD candidate [UDN: {}]\n"
440 " Name : {}\n"
441 " Service Type : {}\n"
442 " Service ID : {}\n"
443 " Base URL : {}\n"
444 " Location URL : {}\n"
445 " control URL : {}\n"
446 " Event URL : {}",
447 igd_candidate->getUID(),
448 igd_candidate->getFriendlyName(),
449 igd_candidate->getServiceType(),
450 igd_candidate->getServiceId(),
451 igd_candidate->getBaseURL(),
452 igd_candidate->getLocationURL(),
453 igd_candidate->getControlURL(),
454 igd_candidate->getEventSubURL());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400455
456 // Check if IGD is connected.
457 if (not actionIsIgdConnected(*igd_candidate)) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400458 if (logger_) logger_->warn("PUPnP: IGD candidate {} is not connected", igd_candidate->getUID().c_str());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400459 return false;
460 }
461
462 // Validate external Ip.
463 igd_candidate->setPublicIp(actionGetExternalIP(*igd_candidate));
464 if (igd_candidate->getPublicIp().toString().empty()) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400465 if (logger_) logger_->warn("PUPnP: IGD candidate {} has no valid external Ip",
466 igd_candidate->getUID().c_str());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400467 return false;
468 }
469
470 // Validate internal Ip.
471 if (igd_candidate->getBaseURL().empty()) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400472 if (logger_) logger_->warn("PUPnP: IGD candidate {} has no valid internal Ip",
473 igd_candidate->getUID().c_str());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400474 return false;
475 }
476
477 // Typically the IGD local address should be extracted from the XML
478 // document (e.g. parsing the base URL). For simplicity, we assume
479 // that it matches the gateway as seen by the local interface.
480 if (const auto& localGw = ip_utils::getLocalGateway()) {
481 igd_candidate->setLocalIp(localGw);
482 } else {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400483 if (logger_) logger_->warn("PUPnP: Could not set internal address for IGD candidate {}",
484 igd_candidate->getUID().c_str());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400485 return false;
486 }
487
488 // Store info for subscription.
489 std::string eventSub = igd_candidate->getEventSubURL();
490
491 {
492 // Add the IGD if not already present in the list.
Adrien Béraud024c46f2024-03-02 23:53:18 -0500493 std::lock_guard lock(pupnpMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400494 for (auto& igd : validIgdList_) {
495 // Must not be a null pointer
496 assert(igd.get() != nullptr);
497 if (*igd == *igd_candidate) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400498 if (logger_) logger_->debug("PUPnP: Device [{}] with int/ext addresses [{}:{}] is already in the list of valid IGDs",
499 igd_candidate->getUID(),
500 igd_candidate->toString(),
501 igd_candidate->getPublicIp().toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400502 return true;
503 }
504 }
505 }
506
507 // We have a valid IGD
508 igd_candidate->setValid(true);
509
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400510 if (logger_) logger_->debug("PUPnP: Added a new IGD [{}] to the list of valid IGDs",
511 igd_candidate->getUID());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400512
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400513 if (logger_) logger_->debug("PUPnP: New IGD addresses [int: {} - ext: {}]",
514 igd_candidate->toString(),
515 igd_candidate->getPublicIp().toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400516
517 // Subscribe to IGD events.
518 int upnp_err = UpnpSubscribeAsync(ctrlptHandle_,
519 eventSub.c_str(),
520 UPNP_INFINITE,
521 subEventCallback,
522 this);
523 if (upnp_err != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400524 if (logger_) logger_->warn("PUPnP: Failed to send subscribe request to {}: error %i - {}",
525 igd_candidate->getUID(),
526 upnp_err,
527 UpnpGetErrorMessage(upnp_err));
528 return false;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400529 } else {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400530 if (logger_) logger_->debug("PUPnP: Successfully subscribed to IGD {}", igd_candidate->getUID());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400531 }
532
533 {
534 // This is a new (and hopefully valid) IGD.
Adrien Béraud024c46f2024-03-02 23:53:18 -0500535 std::lock_guard lock(pupnpMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400536 validIgdList_.emplace_back(igd_candidate);
537 }
538
539 // Report to the listener.
Adrien Béraud370257c2023-08-15 20:53:09 -0400540 ioContext->post([w = weak(), igd_candidate] {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400541 if (auto upnpThis = w.lock()) {
542 if (upnpThis->observer_)
543 upnpThis->observer_->onIgdUpdated(igd_candidate, UpnpIgdEvent::ADDED);
544 }
545 });
546
547 return true;
548}
549
550void
551PUPnP::requestMappingAdd(const Mapping& mapping)
552{
Adrien Béraud370257c2023-08-15 20:53:09 -0400553 ioContext->post([w = weak(), mapping] {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400554 if (auto upnpThis = w.lock()) {
555 if (not upnpThis->isRunning())
556 return;
557 Mapping mapRes(mapping);
558 if (upnpThis->actionAddPortMapping(mapRes)) {
559 mapRes.setState(MappingState::OPEN);
560 mapRes.setInternalAddress(upnpThis->getHostAddress().toString());
561 upnpThis->processAddMapAction(mapRes);
562 } else {
563 upnpThis->incrementErrorsCounter(mapRes.getIgd());
564 mapRes.setState(MappingState::FAILED);
565 upnpThis->processRequestMappingFailure(mapRes);
566 }
567 }
568 });
569}
570
571void
572PUPnP::requestMappingRemove(const Mapping& mapping)
573{
574 // Send remove request using the matching IGD
Adrien Béraud370257c2023-08-15 20:53:09 -0400575 ioContext->dispatch([w = weak(), mapping] {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400576 if (auto upnpThis = w.lock()) {
577 // Abort if we are shutting down.
578 if (not upnpThis->isRunning())
579 return;
580 if (upnpThis->actionDeletePortMapping(mapping)) {
581 upnpThis->processRemoveMapAction(mapping);
582 } else {
583 assert(mapping.getIgd());
584 // Dont need to report in case of failure.
585 upnpThis->incrementErrorsCounter(mapping.getIgd());
586 }
587 }
588 });
589}
590
591std::shared_ptr<UPnPIGD>
592PUPnP::findMatchingIgd(const std::string& ctrlURL) const
593{
Adrien Béraud024c46f2024-03-02 23:53:18 -0500594 std::lock_guard lock(pupnpMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400595
596 auto iter = std::find_if(validIgdList_.begin(),
597 validIgdList_.end(),
598 [&ctrlURL](const std::shared_ptr<IGD>& igd) {
599 if (auto upnpIgd = std::dynamic_pointer_cast<UPnPIGD>(igd)) {
600 return upnpIgd->getControlURL() == ctrlURL;
601 }
602 return false;
603 });
604
605 if (iter == validIgdList_.end()) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400606 if (logger_) logger_->warn("PUPnP: Did not find the IGD matching ctrl URL [{}]", ctrlURL);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400607 return {};
608 }
609
610 return std::dynamic_pointer_cast<UPnPIGD>(*iter);
611}
612
613void
614PUPnP::processAddMapAction(const Mapping& map)
615{
Adrien Béraud612b55b2023-05-29 10:42:04 -0400616 if (observer_ == nullptr)
617 return;
618
Adrien Béraud370257c2023-08-15 20:53:09 -0400619 ioContext->post([w = weak(), map] {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400620 if (auto upnpThis = w.lock()) {
621 if (upnpThis->observer_)
622 upnpThis->observer_->onMappingAdded(map.getIgd(), std::move(map));
623 }
624 });
625}
626
627void
628PUPnP::processRequestMappingFailure(const Mapping& map)
629{
Adrien Béraud612b55b2023-05-29 10:42:04 -0400630 if (observer_ == nullptr)
631 return;
632
Adrien Béraud370257c2023-08-15 20:53:09 -0400633 ioContext->post([w = weak(), map] {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400634 if (auto upnpThis = w.lock()) {
Adrien Beraud64bb00f2023-08-23 19:06:46 -0400635 if (upnpThis->logger_) upnpThis->logger_->debug("PUPnP: Closed mapping {}", map.toString());
Morteza Namvar5f639522023-07-04 17:08:58 -0400636 // JAMI_DBG("PUPnP: Failed to request mapping %s", map.toString().c_str());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400637 if (upnpThis->observer_)
638 upnpThis->observer_->onMappingRequestFailed(map);
639 }
640 });
641}
642
643void
644PUPnP::processRemoveMapAction(const Mapping& map)
645{
Adrien Béraud612b55b2023-05-29 10:42:04 -0400646 if (observer_ == nullptr)
647 return;
648
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400649 if (logger_) logger_->warn("PUPnP: Closed mapping {}", map.toString());
Adrien Béraud370257c2023-08-15 20:53:09 -0400650 ioContext->post([map, obs = observer_] {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400651 obs->onMappingRemoved(map.getIgd(), std::move(map));
652 });
653}
654
655const char*
656PUPnP::eventTypeToString(Upnp_EventType eventType)
657{
658 switch (eventType) {
659 case UPNP_CONTROL_ACTION_REQUEST:
660 return "UPNP_CONTROL_ACTION_REQUEST";
661 case UPNP_CONTROL_ACTION_COMPLETE:
662 return "UPNP_CONTROL_ACTION_COMPLETE";
663 case UPNP_CONTROL_GET_VAR_REQUEST:
664 return "UPNP_CONTROL_GET_VAR_REQUEST";
665 case UPNP_CONTROL_GET_VAR_COMPLETE:
666 return "UPNP_CONTROL_GET_VAR_COMPLETE";
667 case UPNP_DISCOVERY_ADVERTISEMENT_ALIVE:
668 return "UPNP_DISCOVERY_ADVERTISEMENT_ALIVE";
669 case UPNP_DISCOVERY_ADVERTISEMENT_BYEBYE:
670 return "UPNP_DISCOVERY_ADVERTISEMENT_BYEBYE";
671 case UPNP_DISCOVERY_SEARCH_RESULT:
672 return "UPNP_DISCOVERY_SEARCH_RESULT";
673 case UPNP_DISCOVERY_SEARCH_TIMEOUT:
674 return "UPNP_DISCOVERY_SEARCH_TIMEOUT";
675 case UPNP_EVENT_SUBSCRIPTION_REQUEST:
676 return "UPNP_EVENT_SUBSCRIPTION_REQUEST";
677 case UPNP_EVENT_RECEIVED:
678 return "UPNP_EVENT_RECEIVED";
679 case UPNP_EVENT_RENEWAL_COMPLETE:
680 return "UPNP_EVENT_RENEWAL_COMPLETE";
681 case UPNP_EVENT_SUBSCRIBE_COMPLETE:
682 return "UPNP_EVENT_SUBSCRIBE_COMPLETE";
683 case UPNP_EVENT_UNSUBSCRIBE_COMPLETE:
684 return "UPNP_EVENT_UNSUBSCRIBE_COMPLETE";
685 case UPNP_EVENT_AUTORENEWAL_FAILED:
686 return "UPNP_EVENT_AUTORENEWAL_FAILED";
687 case UPNP_EVENT_SUBSCRIPTION_EXPIRED:
688 return "UPNP_EVENT_SUBSCRIPTION_EXPIRED";
689 default:
690 return "Unknown UPNP Event";
691 }
692}
693
694int
695PUPnP::ctrlPtCallback(Upnp_EventType event_type, const void* event, void* user_data)
696{
697 auto pupnp = static_cast<PUPnP*>(user_data);
698
699 if (pupnp == nullptr) {
Adrien Bérauda61adb52023-08-23 09:31:02 -0400700 fmt::print(stderr, "PUPnP: Control point callback without PUPnP");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400701 return UPNP_E_SUCCESS;
702 }
703
704 auto upnpThis = pupnp->weak().lock();
Adrien Bérauda61adb52023-08-23 09:31:02 -0400705 if (not upnpThis) {
706 fmt::print(stderr, "PUPnP: Control point callback without PUPnP");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400707 return UPNP_E_SUCCESS;
Adrien Bérauda61adb52023-08-23 09:31:02 -0400708 }
Adrien Béraud612b55b2023-05-29 10:42:04 -0400709
710 // Ignore if already unregistered.
711 if (not upnpThis->clientRegistered_)
712 return UPNP_E_SUCCESS;
713
714 // Process the callback.
715 return upnpThis->handleCtrlPtUPnPEvents(event_type, event);
716}
717
718PUPnP::CtrlAction
719PUPnP::getAction(const char* xmlNode)
720{
721 if (strstr(xmlNode, ACTION_ADD_PORT_MAPPING)) {
722 return CtrlAction::ADD_PORT_MAPPING;
723 } else if (strstr(xmlNode, ACTION_DELETE_PORT_MAPPING)) {
724 return CtrlAction::DELETE_PORT_MAPPING;
725 } else if (strstr(xmlNode, ACTION_GET_GENERIC_PORT_MAPPING_ENTRY)) {
726 return CtrlAction::GET_GENERIC_PORT_MAPPING_ENTRY;
727 } else if (strstr(xmlNode, ACTION_GET_STATUS_INFO)) {
728 return CtrlAction::GET_STATUS_INFO;
729 } else if (strstr(xmlNode, ACTION_GET_EXTERNAL_IP_ADDRESS)) {
730 return CtrlAction::GET_EXTERNAL_IP_ADDRESS;
731 } else {
732 return CtrlAction::UNKNOWN;
733 }
734}
735
736void
737PUPnP::processDiscoverySearchResult(const std::string& cpDeviceId,
738 const std::string& igdLocationUrl,
739 const IpAddr& dstAddr)
740{
Adrien Béraud612b55b2023-05-29 10:42:04 -0400741 // Update host address if needed.
742 if (not hasValidHostAddress())
743 updateHostAddress();
744
745 // The host address must be valid to proceed.
746 if (not hasValidHostAddress()) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400747 if (logger_) logger_->warn("PUPnP: Local address is invalid. Ignore search result for now!");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400748 return;
749 }
750
751 // Use the device ID and the URL as ID. This is necessary as some
752 // IGDs may have the same device ID but different URLs.
753
754 auto igdId = cpDeviceId + " url: " + igdLocationUrl;
755
756 if (not discoveredIgdList_.emplace(igdId).second) {
Adrien Beraud64bb00f2023-08-23 19:06:46 -0400757 //if (logger_) logger_->debug("PUPnP: IGD [{}] already in the list", igdId);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400758 return;
759 }
760
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400761 if (logger_) logger_->debug("PUPnP: Discovered a new IGD [{}]", igdId);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400762
763 // NOTE: here, we check if the location given is related to the source address.
764 // If it's not the case, it's certainly a router plugged in the network, but not
765 // related to this network. So the given location will be unreachable and this
766 // will cause some timeout.
767
768 // Only check the IP address (ignore the port number).
769 dht::http::Url url(igdLocationUrl);
770 if (IpAddr(url.host).toString(false) != dstAddr.toString(false)) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400771 if (logger_) logger_->debug("PUPnP: Returned location {} does not match the source address {}",
772 IpAddr(url.host).toString(true, true),
773 dstAddr.toString(true, true));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400774 return;
775 }
776
777 // Run a separate thread to prevent blocking this thread
778 // if the IGD HTTP server is not responsive.
François-Simon Fauteux-Chapleau808db4f2024-04-19 11:39:47 -0400779 ongoingOpsThreadPool_.run([w = weak(), url=igdLocationUrl] {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400780 if (auto upnpThis = w.lock()) {
Adrien Beraud3bd61c92023-08-17 16:57:37 -0400781 upnpThis->downLoadIgdDescription(url);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400782 }
783 });
784}
785
786void
787PUPnP::downLoadIgdDescription(const std::string& locationUrl)
788{
Adrien Beraud3bd61c92023-08-17 16:57:37 -0400789 if(logger_) logger_->debug("PUPnP: downLoadIgdDescription {}", locationUrl);
Sébastien Blind14fc352023-10-06 15:21:53 -0400790 {
Adrien Béraud024c46f2024-03-02 23:53:18 -0500791 std::lock_guard lk(ongoingOpsMtx_);
Sébastien Blind14fc352023-10-06 15:21:53 -0400792 if (destroying_)
793 return;
794 ongoingOps_++;
795 }
Adrien Béraud612b55b2023-05-29 10:42:04 -0400796 IXML_Document* doc_container_ptr = nullptr;
797 int upnp_err = UpnpDownloadXmlDoc(locationUrl.c_str(), &doc_container_ptr);
798
François-Simon Fauteux-Chapleau808db4f2024-04-19 11:39:47 -0400799 std::lock_guard lk(ongoingOpsMtx_);
800 // Trying to use libupnp functions after UpnpFinish has been called (which may
801 // be the case if destroying_ is true) can cause errors. It's probably not a
802 // problem here, but return early just in case.
803 if (destroying_)
804 return;
805
Adrien Béraud612b55b2023-05-29 10:42:04 -0400806 if (upnp_err != UPNP_E_SUCCESS or not doc_container_ptr) {
Adrien Béraud370257c2023-08-15 20:53:09 -0400807 if(logger_) logger_->warn("PUPnP: Error downloading device XML document from {} -> {}",
808 locationUrl,
809 UpnpGetErrorMessage(upnp_err));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400810 } else {
Adrien Béraud370257c2023-08-15 20:53:09 -0400811 if(logger_) logger_->debug("PUPnP: Succeeded to download device XML document from {}", locationUrl);
812 ioContext->post([w = weak(), url = locationUrl, doc_container_ptr] {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400813 if (auto upnpThis = w.lock()) {
814 upnpThis->validateIgd(url, doc_container_ptr);
815 }
816 });
817 }
Sébastien Blind14fc352023-10-06 15:21:53 -0400818 ongoingOps_--;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400819}
820
821void
822PUPnP::processDiscoveryAdvertisementByebye(const std::string& cpDeviceId)
823{
Adrien Béraud612b55b2023-05-29 10:42:04 -0400824 discoveredIgdList_.erase(cpDeviceId);
825
826 std::shared_ptr<IGD> igd;
827 {
Adrien Béraud024c46f2024-03-02 23:53:18 -0500828 std::lock_guard lk(pupnpMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400829 for (auto it = validIgdList_.begin(); it != validIgdList_.end();) {
830 if ((*it)->getUID() == cpDeviceId) {
831 igd = *it;
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400832 if (logger_) logger_->debug("PUPnP: Received [{}] for IGD [{}] {}. Will be removed.",
833 PUPnP::eventTypeToString(UPNP_DISCOVERY_ADVERTISEMENT_BYEBYE),
834 igd->getUID(),
835 igd->toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400836 igd->setValid(false);
837 // Remove the IGD.
838 it = validIgdList_.erase(it);
839 break;
840 } else {
841 it++;
842 }
843 }
844 }
845
846 // Notify the listener.
847 if (observer_ and igd) {
848 observer_->onIgdUpdated(igd, UpnpIgdEvent::REMOVED);
849 }
850}
851
852void
853PUPnP::processDiscoverySubscriptionExpired(Upnp_EventType event_type, const std::string& eventSubUrl)
854{
Adrien Béraud024c46f2024-03-02 23:53:18 -0500855 std::lock_guard lk(pupnpMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400856 for (auto& it : validIgdList_) {
857 if (auto igd = std::dynamic_pointer_cast<UPnPIGD>(it)) {
858 if (igd->getEventSubURL() == eventSubUrl) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400859 if (logger_) logger_->debug("PUPnP: Received [{}] event for IGD [{}] {}. Request a new subscribe.",
860 PUPnP::eventTypeToString(event_type),
861 igd->getUID(),
862 igd->toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400863 UpnpSubscribeAsync(ctrlptHandle_,
864 eventSubUrl.c_str(),
865 UPNP_INFINITE,
866 subEventCallback,
867 this);
868 break;
869 }
870 }
871 }
872}
873
874int
875PUPnP::handleCtrlPtUPnPEvents(Upnp_EventType event_type, const void* event)
876{
877 switch (event_type) {
878 // "ALIVE" events are processed as "SEARCH RESULT". It might be usefull
879 // if "SEARCH RESULT" was missed.
880 case UPNP_DISCOVERY_ADVERTISEMENT_ALIVE:
881 case UPNP_DISCOVERY_SEARCH_RESULT: {
882 const UpnpDiscovery* d_event = (const UpnpDiscovery*) event;
883
884 // First check the error code.
885 auto upnp_status = UpnpDiscovery_get_ErrCode(d_event);
886 if (upnp_status != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400887 if (logger_) logger_->error("PUPnP: UPNP discovery is in erroneous state: %s",
888 UpnpGetErrorMessage(upnp_status));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400889 break;
890 }
891
892 // Parse the event's data.
893 std::string deviceId {UpnpDiscovery_get_DeviceID_cstr(d_event)};
894 std::string location {UpnpDiscovery_get_Location_cstr(d_event)};
895 IpAddr dstAddr(*(const pj_sockaddr*) (UpnpDiscovery_get_DestAddr(d_event)));
Adrien Béraud370257c2023-08-15 20:53:09 -0400896 ioContext->post([w = weak(),
Adrien Béraud612b55b2023-05-29 10:42:04 -0400897 deviceId = std::move(deviceId),
898 location = std::move(location),
899 dstAddr = std::move(dstAddr)] {
900 if (auto upnpThis = w.lock()) {
901 upnpThis->processDiscoverySearchResult(deviceId, location, dstAddr);
902 }
903 });
904 break;
905 }
906 case UPNP_DISCOVERY_ADVERTISEMENT_BYEBYE: {
907 const UpnpDiscovery* d_event = (const UpnpDiscovery*) event;
908
909 std::string deviceId(UpnpDiscovery_get_DeviceID_cstr(d_event));
910
911 // Process the response on the main thread.
Adrien Béraud370257c2023-08-15 20:53:09 -0400912 ioContext->post([w = weak(), deviceId = std::move(deviceId)] {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400913 if (auto upnpThis = w.lock()) {
914 upnpThis->processDiscoveryAdvertisementByebye(deviceId);
915 }
916 });
917 break;
918 }
919 case UPNP_DISCOVERY_SEARCH_TIMEOUT: {
920 // Even if the discovery search is successful, it's normal to receive
921 // time-out events. This because we send search requests using various
922 // device types, which some of them may not return a response.
923 break;
924 }
925 case UPNP_EVENT_RECEIVED: {
926 // Nothing to do.
927 break;
928 }
929 // Treat failed autorenewal like an expired subscription.
930 case UPNP_EVENT_AUTORENEWAL_FAILED:
931 case UPNP_EVENT_SUBSCRIPTION_EXPIRED: // This event will occur only if autorenewal is disabled.
932 {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400933 if (logger_) logger_->warn("PUPnP: Received Subscription Event {}", eventTypeToString(event_type));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400934 const UpnpEventSubscribe* es_event = (const UpnpEventSubscribe*) event;
935 if (es_event == nullptr) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400936 if (logger_) logger_->warn("PUPnP: Received Subscription Event with null pointer");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400937 break;
938 }
939 std::string publisherUrl(UpnpEventSubscribe_get_PublisherUrl_cstr(es_event));
940
941 // Process the response on the main thread.
Adrien Béraud370257c2023-08-15 20:53:09 -0400942 ioContext->post([w = weak(), event_type, publisherUrl = std::move(publisherUrl)] {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400943 if (auto upnpThis = w.lock()) {
944 upnpThis->processDiscoverySubscriptionExpired(event_type, publisherUrl);
945 }
946 });
947 break;
948 }
949 case UPNP_EVENT_SUBSCRIBE_COMPLETE:
950 case UPNP_EVENT_UNSUBSCRIBE_COMPLETE: {
951 UpnpEventSubscribe* es_event = (UpnpEventSubscribe*) event;
952 if (es_event == nullptr) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400953 if (logger_) logger_->warn("PUPnP: Received Subscription Event with null pointer");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400954 } else {
955 UpnpEventSubscribe_delete(es_event);
956 }
957 break;
958 }
959 case UPNP_CONTROL_ACTION_COMPLETE: {
960 const UpnpActionComplete* a_event = (const UpnpActionComplete*) event;
961 if (a_event == nullptr) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400962 if (logger_) logger_->warn("PUPnP: Received Action Complete Event with null pointer");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400963 break;
964 }
965 auto res = UpnpActionComplete_get_ErrCode(a_event);
966 if (res != UPNP_E_SUCCESS and res != UPNP_E_TIMEDOUT) {
967 auto err = UpnpActionComplete_get_ErrCode(a_event);
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400968 if (logger_) logger_->warn("PUPnP: Received Action Complete error %i %s", err, UpnpGetErrorMessage(err));
Adrien Béraud612b55b2023-05-29 10:42:04 -0400969 } else {
970 auto actionRequest = UpnpActionComplete_get_ActionRequest(a_event);
971 // Abort if there is no action to process.
972 if (actionRequest == nullptr) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400973 if (logger_) logger_->warn("PUPnP: Can't get the Action Request data from the event");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400974 break;
975 }
976
977 auto actionResult = UpnpActionComplete_get_ActionResult(a_event);
978 if (actionResult != nullptr) {
979 ixmlDocument_free(actionResult);
980 } else {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400981 if (logger_) logger_->warn("PUPnP: Action Result document not found");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400982 }
983 }
984 break;
985 }
986 default: {
Adrien Béraud4f7e8012023-08-16 15:28:18 -0400987 if (logger_) logger_->warn("PUPnP: Unhandled Control Point event");
Adrien Béraud612b55b2023-05-29 10:42:04 -0400988 break;
989 }
990 }
991
992 return UPNP_E_SUCCESS;
993}
994
995int
996PUPnP::subEventCallback(Upnp_EventType event_type, const void* event, void* user_data)
997{
998 if (auto pupnp = static_cast<PUPnP*>(user_data))
999 return pupnp->handleSubscriptionUPnPEvent(event_type, event);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001000 return 0;
1001}
1002
1003int
1004PUPnP::handleSubscriptionUPnPEvent(Upnp_EventType, const void* event)
1005{
1006 UpnpEventSubscribe* es_event = static_cast<UpnpEventSubscribe*>(const_cast<void*>(event));
1007
1008 if (es_event == nullptr) {
Morteza Namvar5f639522023-07-04 17:08:58 -04001009 // JAMI_ERR("PUPnP: Unexpected null pointer!");
Adrien Béraud612b55b2023-05-29 10:42:04 -04001010 return UPNP_E_INVALID_ARGUMENT;
1011 }
1012 std::string publisherUrl(UpnpEventSubscribe_get_PublisherUrl_cstr(es_event));
1013 int upnp_err = UpnpEventSubscribe_get_ErrCode(es_event);
1014 if (upnp_err != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001015 if (logger_) logger_->warn("PUPnP: Subscription error {} from {}",
1016 UpnpGetErrorMessage(upnp_err),
1017 publisherUrl);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001018 return upnp_err;
1019 }
1020
1021 return UPNP_E_SUCCESS;
1022}
1023
1024std::unique_ptr<UPnPIGD>
1025PUPnP::parseIgd(IXML_Document* doc, std::string locationUrl)
1026{
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001027 if (not(doc and !locationUrl.empty()))
Adrien Béraud612b55b2023-05-29 10:42:04 -04001028 return nullptr;
1029
1030 // Check the UDN to see if its already in our device list.
1031 std::string UDN(getFirstDocItem(doc, "UDN"));
1032 if (UDN.empty()) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001033 if (logger_) logger_->warn("PUPnP: could not find UDN in description document of device");
Adrien Béraud612b55b2023-05-29 10:42:04 -04001034 return nullptr;
1035 } else {
Adrien Béraud024c46f2024-03-02 23:53:18 -05001036 std::lock_guard lk(pupnpMutex_);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001037 for (auto& it : validIgdList_) {
1038 if (it->getUID() == UDN) {
1039 // We already have this device in our list.
1040 return nullptr;
1041 }
1042 }
1043 }
1044
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001045 if (logger_) logger_->debug("PUPnP: Found new device [{}]", UDN);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001046
1047 std::unique_ptr<UPnPIGD> new_igd;
1048 int upnp_err;
1049
1050 // Get friendly name.
1051 std::string friendlyName(getFirstDocItem(doc, "friendlyName"));
1052
1053 // Get base URL.
1054 std::string baseURL(getFirstDocItem(doc, "URLBase"));
1055 if (baseURL.empty())
1056 baseURL = locationUrl;
1057
1058 // Get list of services defined by serviceType.
1059 std::unique_ptr<IXML_NodeList, decltype(ixmlNodeList_free)&> serviceList(nullptr,
1060 ixmlNodeList_free);
1061 serviceList.reset(ixmlDocument_getElementsByTagName(doc, "serviceType"));
1062 unsigned long list_length = ixmlNodeList_length(serviceList.get());
1063
1064 // Go through the "serviceType" nodes until we find the the correct service type.
1065 for (unsigned long node_idx = 0; node_idx < list_length; node_idx++) {
1066 IXML_Node* serviceType_node = ixmlNodeList_item(serviceList.get(), node_idx);
1067 std::string serviceType(getElementText(serviceType_node));
1068
1069 // Only check serviceType of WANIPConnection or WANPPPConnection.
1070 if (serviceType != UPNP_WANIP_SERVICE
1071 && serviceType != UPNP_WANPPP_SERVICE) {
1072 // IGD is not WANIP or WANPPP service. Going to next node.
1073 continue;
1074 }
1075
1076 // Get parent node.
1077 IXML_Node* service_node = ixmlNode_getParentNode(serviceType_node);
1078 if (not service_node) {
1079 // IGD serviceType has no parent node. Going to next node.
1080 continue;
1081 }
1082
1083 // Perform sanity check. The parent node should be called "service".
1084 if (strcmp(ixmlNode_getNodeName(service_node), "service") != 0) {
1085 // IGD "serviceType" parent node is not called "service". Going to next node.
1086 continue;
1087 }
1088
1089 // Get serviceId.
1090 IXML_Element* service_element = (IXML_Element*) service_node;
1091 std::string serviceId(getFirstElementItem(service_element, "serviceId"));
1092 if (serviceId.empty()) {
1093 // IGD "serviceId" is empty. Going to next node.
1094 continue;
1095 }
1096
1097 // Get the relative controlURL and turn it into absolute address using the URLBase.
1098 std::string controlURL(getFirstElementItem(service_element, "controlURL"));
1099 if (controlURL.empty()) {
1100 // IGD control URL is empty. Going to next node.
1101 continue;
1102 }
1103
1104 char* absolute_control_url = nullptr;
1105 upnp_err = UpnpResolveURL2(baseURL.c_str(), controlURL.c_str(), &absolute_control_url);
1106 if (upnp_err == UPNP_E_SUCCESS)
1107 controlURL = absolute_control_url;
1108 else
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001109 if (logger_) logger_->warn("PUPnP: Error resolving absolute controlURL -> {}",
1110 UpnpGetErrorMessage(upnp_err));
Adrien Béraud612b55b2023-05-29 10:42:04 -04001111
1112 std::free(absolute_control_url);
1113
1114 // Get the relative eventSubURL and turn it into absolute address using the URLBase.
1115 std::string eventSubURL(getFirstElementItem(service_element, "eventSubURL"));
1116 if (eventSubURL.empty()) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001117 if (logger_) logger_->warn("PUPnP: IGD event sub URL is empty. Going to next node");
Adrien Béraud612b55b2023-05-29 10:42:04 -04001118 continue;
1119 }
1120
1121 char* absolute_event_sub_url = nullptr;
1122 upnp_err = UpnpResolveURL2(baseURL.c_str(), eventSubURL.c_str(), &absolute_event_sub_url);
1123 if (upnp_err == UPNP_E_SUCCESS)
1124 eventSubURL = absolute_event_sub_url;
1125 else
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001126 if (logger_) logger_->warn("PUPnP: Error resolving absolute eventSubURL -> {}",
1127 UpnpGetErrorMessage(upnp_err));
Adrien Béraud612b55b2023-05-29 10:42:04 -04001128
1129 std::free(absolute_event_sub_url);
1130
1131 new_igd.reset(new UPnPIGD(std::move(UDN),
1132 std::move(baseURL),
1133 std::move(friendlyName),
1134 std::move(serviceType),
1135 std::move(serviceId),
1136 std::move(locationUrl),
1137 std::move(controlURL),
1138 std::move(eventSubURL)));
1139
1140 return new_igd;
1141 }
1142
1143 return nullptr;
1144}
1145
1146bool
1147PUPnP::actionIsIgdConnected(const UPnPIGD& igd)
1148{
1149 if (not clientRegistered_)
1150 return false;
1151
1152 // Set action name.
1153 IXML_Document* action_container_ptr = UpnpMakeAction("GetStatusInfo",
1154 igd.getServiceType().c_str(),
1155 0,
1156 nullptr);
1157 if (not action_container_ptr) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001158 if (logger_) logger_->warn("PUPnP: Failed to make GetStatusInfo action");
Adrien Béraud612b55b2023-05-29 10:42:04 -04001159 return false;
1160 }
1161 XMLDocument action(action_container_ptr, ixmlDocument_free); // Action pointer.
1162
1163 IXML_Document* response_container_ptr = nullptr;
1164 int upnp_err = UpnpSendAction(ctrlptHandle_,
1165 igd.getControlURL().c_str(),
1166 igd.getServiceType().c_str(),
1167 nullptr,
1168 action.get(),
1169 &response_container_ptr);
Sébastien Blin45b50692024-03-06 11:18:50 -05001170 if (upnp_err == 401) {
1171 // YET ANOTHER UPNP HACK: MiniUpnp on some routers seems to not recognize this action, sending a 401: Invalid Action.
1172 // So even if mapping succeeds, the router was considered as not connected.
1173 // Returning true here works around this issue.
1174 // E.g. https://community.tp-link.com/us/home/forum/topic/577840
1175 return true;
1176 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001177 if (not response_container_ptr or upnp_err != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001178 if (logger_) logger_->warn("PUPnP: Failed to send GetStatusInfo action -> {}", UpnpGetErrorMessage(upnp_err));
Adrien Béraud612b55b2023-05-29 10:42:04 -04001179 return false;
1180 }
1181 XMLDocument response(response_container_ptr, ixmlDocument_free);
1182
Adrien Béraudd78d1ac2023-08-25 10:43:33 -04001183 if (errorOnResponse(response.get(), logger_)) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001184 if (logger_) logger_->warn("PUPnP: Failed to get GetStatusInfo from {} -> {:d}: {}",
1185 igd.getServiceType().c_str(),
1186 upnp_err,
1187 UpnpGetErrorMessage(upnp_err));
Adrien Béraud612b55b2023-05-29 10:42:04 -04001188 return false;
1189 }
1190
1191 // Parse response.
1192 auto status = getFirstDocItem(response.get(), "NewConnectionStatus");
1193 return status == "Connected";
1194}
1195
1196IpAddr
1197PUPnP::actionGetExternalIP(const UPnPIGD& igd)
1198{
1199 if (not clientRegistered_)
1200 return {};
1201
1202 // Action and response pointers.
1203 std::unique_ptr<IXML_Document, decltype(ixmlDocument_free)&>
1204 action(nullptr, ixmlDocument_free); // Action pointer.
1205 std::unique_ptr<IXML_Document, decltype(ixmlDocument_free)&>
1206 response(nullptr, ixmlDocument_free); // Response pointer.
1207
1208 // Set action name.
1209 static constexpr const char* action_name {"GetExternalIPAddress"};
1210
1211 IXML_Document* action_container_ptr = nullptr;
1212 action_container_ptr = UpnpMakeAction(action_name, igd.getServiceType().c_str(), 0, nullptr);
1213 action.reset(action_container_ptr);
1214
1215 if (not action) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001216 if (logger_) logger_->warn("PUPnP: Failed to make GetExternalIPAddress action");
Adrien Béraud612b55b2023-05-29 10:42:04 -04001217 return {};
1218 }
1219
1220 IXML_Document* response_container_ptr = nullptr;
1221 int upnp_err = UpnpSendAction(ctrlptHandle_,
1222 igd.getControlURL().c_str(),
1223 igd.getServiceType().c_str(),
1224 nullptr,
1225 action.get(),
1226 &response_container_ptr);
1227 response.reset(response_container_ptr);
1228
1229 if (not response or upnp_err != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001230 if (logger_) logger_->warn("PUPnP: Failed to send GetExternalIPAddress action -> {}",
1231 UpnpGetErrorMessage(upnp_err));
Adrien Béraud612b55b2023-05-29 10:42:04 -04001232 return {};
1233 }
1234
Adrien Béraudd78d1ac2023-08-25 10:43:33 -04001235 if (errorOnResponse(response.get(), logger_)) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001236 if (logger_) logger_->warn("PUPnP: Failed to get GetExternalIPAddress from {} -> {:d}: {}",
1237 igd.getServiceType(),
1238 upnp_err,
1239 UpnpGetErrorMessage(upnp_err));
Adrien Béraud612b55b2023-05-29 10:42:04 -04001240 return {};
1241 }
1242
1243 return {getFirstDocItem(response.get(), "NewExternalIPAddress")};
1244}
1245
1246std::map<Mapping::key_t, Mapping>
1247PUPnP::getMappingsListByDescr(const std::shared_ptr<IGD>& igd, const std::string& description) const
1248{
1249 auto upnpIgd = std::dynamic_pointer_cast<UPnPIGD>(igd);
1250 assert(upnpIgd);
1251
1252 std::map<Mapping::key_t, Mapping> mapList;
1253
1254 if (not clientRegistered_ or not upnpIgd->isValid() or not upnpIgd->getLocalIp())
1255 return mapList;
1256
1257 // Set action name.
1258 static constexpr const char* action_name {"GetGenericPortMappingEntry"};
1259
1260 for (int entry_idx = 0;; entry_idx++) {
1261 std::unique_ptr<IXML_Document, decltype(ixmlDocument_free)&>
1262 action(nullptr, ixmlDocument_free); // Action pointer.
1263 IXML_Document* action_container_ptr = nullptr;
1264
1265 std::unique_ptr<IXML_Document, decltype(ixmlDocument_free)&>
1266 response(nullptr, ixmlDocument_free); // Response pointer.
1267 IXML_Document* response_container_ptr = nullptr;
1268
1269 UpnpAddToAction(&action_container_ptr,
1270 action_name,
1271 upnpIgd->getServiceType().c_str(),
1272 "NewPortMappingIndex",
1273 std::to_string(entry_idx).c_str());
1274 action.reset(action_container_ptr);
1275
1276 if (not action) {
Morteza Namvar5f639522023-07-04 17:08:58 -04001277 // JAMI_WARN("PUPnP: Failed to add NewPortMappingIndex action");
Adrien Béraud612b55b2023-05-29 10:42:04 -04001278 break;
1279 }
1280
1281 int upnp_err = UpnpSendAction(ctrlptHandle_,
1282 upnpIgd->getControlURL().c_str(),
1283 upnpIgd->getServiceType().c_str(),
1284 nullptr,
1285 action.get(),
1286 &response_container_ptr);
1287 response.reset(response_container_ptr);
1288
1289 if (not response) {
1290 // No existing mapping. Abort silently.
1291 break;
1292 }
1293
1294 if (upnp_err != UPNP_E_SUCCESS) {
Morteza Namvar5f639522023-07-04 17:08:58 -04001295 // JAMI_ERR("PUPnP: GetGenericPortMappingEntry returned with error: %i", upnp_err);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001296 break;
1297 }
1298
1299 // Check error code.
1300 auto errorCode = getFirstDocItem(response.get(), "errorCode");
1301 if (not errorCode.empty()) {
1302 auto error = to_int<int>(errorCode);
1303 if (error == ARRAY_IDX_INVALID or error == CONFLICT_IN_MAPPING) {
1304 // No more port mapping entries in the response.
Morteza Namvar5f639522023-07-04 17:08:58 -04001305 // JAMI_DBG("PUPnP: No more mappings (found a total of %i mappings", entry_idx);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001306 break;
1307 } else {
1308 auto errorDescription = getFirstDocItem(response.get(), "errorDescription");
Adrien Béraud370257c2023-08-15 20:53:09 -04001309 if (logger_) logger_->error("PUPnP: GetGenericPortMappingEntry returned with error: {:s}: {:s}",
Adrien Béraud612b55b2023-05-29 10:42:04 -04001310 errorCode,
1311 errorDescription);
1312 break;
1313 }
1314 }
1315
1316 // Parse the response.
1317 auto desc_actual = getFirstDocItem(response.get(), "NewPortMappingDescription");
1318 auto client_ip = getFirstDocItem(response.get(), "NewInternalClient");
1319
1320 if (client_ip != getHostAddress().toString()) {
1321 // Silently ignore un-matching addresses.
1322 continue;
1323 }
1324
1325 if (desc_actual.find(description) == std::string::npos)
1326 continue;
1327
1328 auto port_internal = getFirstDocItem(response.get(), "NewInternalPort");
1329 auto port_external = getFirstDocItem(response.get(), "NewExternalPort");
1330 std::string transport(getFirstDocItem(response.get(), "NewProtocol"));
1331
1332 if (port_internal.empty() || port_external.empty() || transport.empty()) {
Adrien Béraud370257c2023-08-15 20:53:09 -04001333 // if (logger_) logger_->e("PUPnP: GetGenericPortMappingEntry returned an invalid entry at index %i",
Morteza Namvar5f639522023-07-04 17:08:58 -04001334 // entry_idx);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001335 continue;
1336 }
1337
1338 std::transform(transport.begin(), transport.end(), transport.begin(), ::toupper);
1339 PortType type = transport.find("TCP") != std::string::npos ? PortType::TCP : PortType::UDP;
1340 auto ePort = to_int<uint16_t>(port_external);
1341 auto iPort = to_int<uint16_t>(port_internal);
1342
1343 Mapping map(type, ePort, iPort);
1344 map.setIgd(igd);
1345
1346 mapList.emplace(map.getMapKey(), std::move(map));
1347 }
1348
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001349 if (logger_) logger_->debug("PUPnP: Found {:d} allocated mappings on IGD {:s}",
1350 mapList.size(),
1351 upnpIgd->toString());
Adrien Béraud612b55b2023-05-29 10:42:04 -04001352
1353 return mapList;
1354}
1355
1356void
1357PUPnP::deleteMappingsByDescription(const std::shared_ptr<IGD>& igd, const std::string& description)
1358{
1359 if (not(clientRegistered_ and igd->getLocalIp()))
1360 return;
1361
François-Simon Fauteux-Chapleau1b3aba22024-05-23 11:51:48 -04001362 if (logger_) logger_->debug("PUPnP: Remove all mappings (if any) on IGD {} matching description prefix {}",
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001363 igd->toString(),
François-Simon Fauteux-Chapleau1b3aba22024-05-23 11:51:48 -04001364 description);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001365
Adrien Béraud370257c2023-08-15 20:53:09 -04001366 ioContext->post([w=weak(), igd, description]{
1367 if (auto sthis = w.lock()) {
1368 auto mapList = sthis->getMappingsListByDescr(igd, description);
1369 for (auto const& [_, map] : mapList) {
1370 sthis->requestMappingRemove(map);
1371 }
1372 }
1373 });
Adrien Béraud612b55b2023-05-29 10:42:04 -04001374}
1375
1376bool
1377PUPnP::actionAddPortMapping(const Mapping& mapping)
1378{
Adrien Béraud612b55b2023-05-29 10:42:04 -04001379 if (not clientRegistered_)
1380 return false;
1381
1382 auto igdIn = std::dynamic_pointer_cast<UPnPIGD>(mapping.getIgd());
1383 if (not igdIn)
1384 return false;
1385
1386 // The requested IGD must be present in the list of local valid IGDs.
1387 auto igd = findMatchingIgd(igdIn->getControlURL());
1388
1389 if (not igd or not igd->isValid())
1390 return false;
1391
1392 // Action and response pointers.
1393 XMLDocument action(nullptr, ixmlDocument_free);
1394 IXML_Document* action_container_ptr = nullptr;
1395 XMLDocument response(nullptr, ixmlDocument_free);
1396 IXML_Document* response_container_ptr = nullptr;
1397
1398 // Set action sequence.
1399 UpnpAddToAction(&action_container_ptr,
1400 ACTION_ADD_PORT_MAPPING,
1401 igd->getServiceType().c_str(),
1402 "NewRemoteHost",
1403 "");
1404 UpnpAddToAction(&action_container_ptr,
1405 ACTION_ADD_PORT_MAPPING,
1406 igd->getServiceType().c_str(),
1407 "NewExternalPort",
1408 mapping.getExternalPortStr().c_str());
1409 UpnpAddToAction(&action_container_ptr,
1410 ACTION_ADD_PORT_MAPPING,
1411 igd->getServiceType().c_str(),
1412 "NewProtocol",
1413 mapping.getTypeStr());
1414 UpnpAddToAction(&action_container_ptr,
1415 ACTION_ADD_PORT_MAPPING,
1416 igd->getServiceType().c_str(),
1417 "NewInternalPort",
1418 mapping.getInternalPortStr().c_str());
1419 UpnpAddToAction(&action_container_ptr,
1420 ACTION_ADD_PORT_MAPPING,
1421 igd->getServiceType().c_str(),
1422 "NewInternalClient",
1423 getHostAddress().toString().c_str());
1424 UpnpAddToAction(&action_container_ptr,
1425 ACTION_ADD_PORT_MAPPING,
1426 igd->getServiceType().c_str(),
1427 "NewEnabled",
1428 "1");
1429 UpnpAddToAction(&action_container_ptr,
1430 ACTION_ADD_PORT_MAPPING,
1431 igd->getServiceType().c_str(),
1432 "NewPortMappingDescription",
1433 mapping.toString().c_str());
1434 UpnpAddToAction(&action_container_ptr,
1435 ACTION_ADD_PORT_MAPPING,
1436 igd->getServiceType().c_str(),
1437 "NewLeaseDuration",
1438 "0");
1439
1440 action.reset(action_container_ptr);
1441
1442 int upnp_err = UpnpSendAction(ctrlptHandle_,
1443 igd->getControlURL().c_str(),
1444 igd->getServiceType().c_str(),
1445 nullptr,
1446 action.get(),
1447 &response_container_ptr);
1448 response.reset(response_container_ptr);
1449
1450 bool success = true;
1451
1452 if (upnp_err != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001453 if (logger_) {
1454 logger_->warn("PUPnP: Failed to send action {} for mapping {}. {:d}: {}",
1455 ACTION_ADD_PORT_MAPPING,
1456 mapping.toString(),
1457 upnp_err,
1458 UpnpGetErrorMessage(upnp_err));
1459 logger_->warn("PUPnP: IGD ctrlUrl {}", igd->getControlURL());
1460 logger_->warn("PUPnP: IGD service type {}", igd->getServiceType());
1461 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001462
1463 success = false;
1464 }
1465
1466 // Check if an error has occurred.
1467 auto errorCode = getFirstDocItem(response.get(), "errorCode");
1468 if (not errorCode.empty()) {
1469 success = false;
1470 // Try to get the error description.
1471 std::string errorDescription;
1472 if (response) {
1473 errorDescription = getFirstDocItem(response.get(), "errorDescription");
1474 }
1475
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001476 if (logger_) logger_->warn("PUPnP: {:s} returned with error: {:s} {:s}",
1477 ACTION_ADD_PORT_MAPPING,
1478 errorCode,
1479 errorDescription);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001480 }
1481 return success;
1482}
1483
1484bool
1485PUPnP::actionDeletePortMapping(const Mapping& mapping)
1486{
Adrien Béraud612b55b2023-05-29 10:42:04 -04001487 if (not clientRegistered_)
1488 return false;
1489
1490 auto igdIn = std::dynamic_pointer_cast<UPnPIGD>(mapping.getIgd());
1491 if (not igdIn)
1492 return false;
1493
1494 // The requested IGD must be present in the list of local valid IGDs.
1495 auto igd = findMatchingIgd(igdIn->getControlURL());
1496
1497 if (not igd or not igd->isValid())
1498 return false;
1499
1500 // Action and response pointers.
1501 XMLDocument action(nullptr, ixmlDocument_free);
1502 IXML_Document* action_container_ptr = nullptr;
1503 XMLDocument response(nullptr, ixmlDocument_free);
1504 IXML_Document* response_container_ptr = nullptr;
1505
1506 // Set action sequence.
1507 UpnpAddToAction(&action_container_ptr,
1508 ACTION_DELETE_PORT_MAPPING,
1509 igd->getServiceType().c_str(),
1510 "NewRemoteHost",
1511 "");
1512 UpnpAddToAction(&action_container_ptr,
1513 ACTION_DELETE_PORT_MAPPING,
1514 igd->getServiceType().c_str(),
1515 "NewExternalPort",
1516 mapping.getExternalPortStr().c_str());
1517 UpnpAddToAction(&action_container_ptr,
1518 ACTION_DELETE_PORT_MAPPING,
1519 igd->getServiceType().c_str(),
1520 "NewProtocol",
1521 mapping.getTypeStr());
1522
1523 action.reset(action_container_ptr);
1524
1525 int upnp_err = UpnpSendAction(ctrlptHandle_,
1526 igd->getControlURL().c_str(),
1527 igd->getServiceType().c_str(),
1528 nullptr,
1529 action.get(),
1530 &response_container_ptr);
1531 response.reset(response_container_ptr);
1532
1533 bool success = true;
1534
1535 if (upnp_err != UPNP_E_SUCCESS) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001536 if (logger_) {
1537 logger_->warn("PUPnP: Failed to send action {} for mapping from {}. {:d}: {}",
1538 ACTION_DELETE_PORT_MAPPING,
1539 mapping.toString(),
1540 upnp_err,
1541 UpnpGetErrorMessage(upnp_err));
1542 logger_->warn("PUPnP: IGD ctrlUrl {}", igd->getControlURL());
1543 logger_->warn("PUPnP: IGD service type {}", igd->getServiceType());
1544 }
Adrien Béraud612b55b2023-05-29 10:42:04 -04001545 success = false;
1546 }
1547
1548 if (not response) {
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001549 if (logger_) logger_->warn("PUPnP: Failed to get response for {}", ACTION_DELETE_PORT_MAPPING);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001550 success = false;
1551 }
1552
1553 // Check if there is an error code.
1554 auto errorCode = getFirstDocItem(response.get(), "errorCode");
1555 if (not errorCode.empty()) {
1556 auto errorDescription = getFirstDocItem(response.get(), "errorDescription");
Adrien Béraud4f7e8012023-08-16 15:28:18 -04001557 if (logger_) logger_->warn("PUPnP: {:s} returned with error: {:s}: {:s}",
1558 ACTION_DELETE_PORT_MAPPING,
1559 errorCode,
1560 errorDescription);
Adrien Béraud612b55b2023-05-29 10:42:04 -04001561 success = false;
1562 }
1563
1564 return success;
1565}
1566
1567} // namespace upnp
Sébastien Blin464bdff2023-07-19 08:02:53 -04001568} // namespace dhtnet