Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2004-2023 Savoir-faire Linux Inc. |
| 3 | * |
Adrien Béraud | cb75362 | 2023-07-17 22:32:49 -0400 | [diff] [blame] | 4 | * This program is free software: you can redistribute it and/or modify |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 5 | * it under the terms of the GNU General Public License as published by |
Adrien Béraud | cb75362 | 2023-07-17 22:32:49 -0400 | [diff] [blame] | 6 | * the Free Software Foundation, either version 3 of the License, or |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 7 | * (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éraud | cb75362 | 2023-07-17 22:32:49 -0400 | [diff] [blame] | 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 12 | * GNU General Public License for more details. |
| 13 | * |
| 14 | * You should have received a copy of the GNU General Public License |
Adrien Béraud | cb75362 | 2023-07-17 22:32:49 -0400 | [diff] [blame] | 15 | * along with this program. If not, see <https://www.gnu.org/licenses/>. |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 16 | */ |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 17 | #include "pupnp.h" |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 18 | #include "string_utils.h" |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 19 | |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 20 | #include <opendht/http.h> |
| 21 | |
Adrien Béraud | 1ae60aa | 2023-07-07 09:55:09 -0400 | [diff] [blame] | 22 | namespace dhtnet { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 23 | namespace upnp { |
| 24 | |
| 25 | // Action identifiers. |
| 26 | constexpr static const char* ACTION_ADD_PORT_MAPPING {"AddPortMapping"}; |
| 27 | constexpr static const char* ACTION_DELETE_PORT_MAPPING {"DeletePortMapping"}; |
| 28 | constexpr static const char* ACTION_GET_GENERIC_PORT_MAPPING_ENTRY {"GetGenericPortMappingEntry"}; |
| 29 | constexpr static const char* ACTION_GET_STATUS_INFO {"GetStatusInfo"}; |
| 30 | constexpr static const char* ACTION_GET_EXTERNAL_IP_ADDRESS {"GetExternalIPAddress"}; |
| 31 | |
| 32 | // Error codes returned by router when trying to remove ports. |
| 33 | constexpr static int ARRAY_IDX_INVALID = 713; |
| 34 | constexpr static int CONFLICT_IN_MAPPING = 718; |
| 35 | |
| 36 | // Max number of IGD search attempts before failure. |
| 37 | constexpr static unsigned int PUPNP_MAX_RESTART_SEARCH_RETRIES {3}; |
| 38 | // IGD search timeout (in seconds). |
| 39 | constexpr static unsigned int SEARCH_TIMEOUT {60}; |
| 40 | // Base unit for the timeout between two successive IGD search. |
| 41 | constexpr static auto PUPNP_SEARCH_RETRY_UNIT {std::chrono::seconds(10)}; |
| 42 | |
| 43 | // Helper functions for xml parsing. |
| 44 | static std::string_view |
| 45 | getElementText(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 | |
| 55 | static std::string_view |
| 56 | getFirstDocItem(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 | |
| 67 | static std::string_view |
| 68 | getFirstElementItem(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 | |
| 79 | static bool |
Adrien Béraud | d78d1ac | 2023-08-25 10:43:33 -0400 | [diff] [blame] | 80 | errorOnResponse(IXML_Document* doc, const std::shared_ptr<dht::log::Logger>& logger) |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 81 | { |
| 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éraud | d78d1ac | 2023-08-25 10:43:33 -0400 | [diff] [blame] | 88 | if (logger) logger->warn("PUPnP: Response contains error: {:s}: {:s}", |
| 89 | errorCode, |
| 90 | errorDescription); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 91 | return true; |
| 92 | } |
| 93 | return false; |
| 94 | } |
| 95 | |
| 96 | // UPNP class implementation |
| 97 | |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 98 | PUPnP::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-Chapleau | 808db4f | 2024-04-19 11:39:47 -0400 | [diff] [blame] | 100 | , ongoingOpsThreadPool_(1, 64) |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 101 | { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 102 | if (logger_) logger_->debug("PUPnP: Creating instance [{}] ...", fmt::ptr(this)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 103 | } |
| 104 | |
| 105 | PUPnP::~PUPnP() |
| 106 | { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 107 | if (logger_) logger_->debug("PUPnP: Instance [{}] destroyed", fmt::ptr(this)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 108 | } |
| 109 | |
| 110 | void |
| 111 | PUPnP::initUpnpLib() |
| 112 | { |
| 113 | assert(not initialized_); |
Adrien Béraud | a61adb5 | 2023-08-23 09:31:02 -0400 | [diff] [blame] | 114 | auto hostinfo = ip_utils::getHostName(); |
Adrien Béraud | a61adb5 | 2023-08-23 09:31:02 -0400 | [diff] [blame] | 115 | int upnp_err = UpnpInit2(hostinfo.interface.empty() ? nullptr : hostinfo.interface.c_str(), 0); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 116 | if (upnp_err != UPNP_E_SUCCESS) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 117 | if (logger_) logger_->error("PUPnP: Can't initialize libupnp: {}", UpnpGetErrorMessage(upnp_err)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 118 | UpnpFinish(); |
| 119 | initialized_ = false; |
| 120 | return; |
| 121 | } |
| 122 | |
| 123 | // Disable embedded WebServer if any. |
| 124 | if (UpnpIsWebserverEnabled() == 1) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 125 | if (logger_) logger_->warn("PUPnP: Web-server is enabled. Disabling"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 126 | UpnpEnableWebserver(0); |
| 127 | if (UpnpIsWebserverEnabled() == 1) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 128 | if (logger_) logger_->error("PUPnP: Could not disable Web-server!"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 129 | } else { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 130 | if (logger_) logger_->debug("PUPnP: Web-server successfully disabled"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 131 | } |
| 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éraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 142 | 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éraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 148 | |
| 149 | // Relax the parser to allow malformed XML text. |
| 150 | ixmlRelaxParser(1); |
| 151 | |
| 152 | initialized_ = true; |
| 153 | } |
| 154 | |
| 155 | bool |
| 156 | PUPnP::isRunning() const |
| 157 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 158 | std::unique_lock lk(pupnpMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 159 | return not shutdownComplete_; |
| 160 | } |
| 161 | |
| 162 | void |
| 163 | PUPnP::registerClient() |
| 164 | { |
| 165 | assert(not clientRegistered_); |
| 166 | |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 167 | // Register Upnp control point. |
| 168 | int upnp_err = UpnpRegisterClient(ctrlPtCallback, this, &ctrlptHandle_); |
| 169 | if (upnp_err != UPNP_E_SUCCESS) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 170 | if (logger_) logger_->error("PUPnP: Can't register client: {}", UpnpGetErrorMessage(upnp_err)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 171 | } else { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 172 | if (logger_) logger_->debug("PUPnP: Successfully registered client"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 173 | clientRegistered_ = true; |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | void |
François-Simon Fauteux-Chapleau | d797698 | 2024-04-26 16:06:23 -0400 | [diff] [blame] | 178 | PUPnP::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 | |
| 189 | void |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 190 | PUPnP::setObserver(UpnpMappingObserver* obs) |
| 191 | { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 192 | observer_ = obs; |
| 193 | } |
| 194 | |
| 195 | const IpAddr |
| 196 | PUPnP::getHostAddress() const |
| 197 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 198 | std::lock_guard lock(pupnpMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 199 | return hostAddress_; |
| 200 | } |
| 201 | |
| 202 | void |
François-Simon Fauteux-Chapleau | 808db4f | 2024-04-19 11:39:47 -0400 | [diff] [blame] | 203 | PUPnP::terminate() |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 204 | { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 205 | if (logger_) logger_->debug("PUPnP: Terminate instance {}", fmt::ptr(this)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 206 | |
| 207 | clientRegistered_ = false; |
| 208 | observer_ = nullptr; |
François-Simon Fauteux-Chapleau | 808db4f | 2024-04-19 11:39:47 -0400 | [diff] [blame] | 209 | { |
| 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éraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 217 | |
| 218 | UpnpUnRegisterClient(ctrlptHandle_); |
| 219 | |
| 220 | if (initialized_) { |
| 221 | if (UpnpFinish() != UPNP_E_SUCCESS) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 222 | if (logger_) logger_->error("PUPnP: Failed to properly close lib-upnp"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 223 | } |
| 224 | |
| 225 | initialized_ = false; |
| 226 | } |
| 227 | |
| 228 | // Clear all the lists. |
| 229 | discoveredIgdList_.clear(); |
| 230 | |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 231 | std::lock_guard lock(pupnpMutex_); |
Adrien Béraud | 7a82bee | 2023-08-30 10:26:45 -0400 | [diff] [blame] | 232 | validIgdList_.clear(); |
| 233 | shutdownComplete_ = true; |
François-Simon Fauteux-Chapleau | 808db4f | 2024-04-19 11:39:47 -0400 | [diff] [blame] | 234 | if (logger_) logger_->debug("PUPnP: Instance {} terminated", fmt::ptr(this)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 235 | } |
| 236 | |
| 237 | void |
| 238 | PUPnP::searchForDevices() |
| 239 | { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 240 | if (logger_) logger_->debug("PUPnP: Send IGD search request"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 241 | |
| 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éraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 247 | if (logger_) logger_->warn("PUPnP: Send search for UPNP_ROOT_DEVICE failed. Error {:d}: {}", |
| 248 | err, |
| 249 | UpnpGetErrorMessage(err)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 250 | } |
| 251 | |
| 252 | err = UpnpSearchAsync(ctrlptHandle_, SEARCH_TIMEOUT, UPNP_IGD_DEVICE, this); |
| 253 | if (err != UPNP_E_SUCCESS) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 254 | if (logger_) logger_->warn("PUPnP: Send search for UPNP_IGD_DEVICE failed. Error {:d}: {}", |
| 255 | err, |
| 256 | UpnpGetErrorMessage(err)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 257 | } |
| 258 | |
| 259 | err = UpnpSearchAsync(ctrlptHandle_, SEARCH_TIMEOUT, UPNP_WANIP_SERVICE, this); |
| 260 | if (err != UPNP_E_SUCCESS) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 261 | if (logger_) logger_->warn("PUPnP: Send search for UPNP_WANIP_SERVICE failed. Error {:d}: {}", |
| 262 | err, |
| 263 | UpnpGetErrorMessage(err)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 264 | } |
| 265 | |
| 266 | err = UpnpSearchAsync(ctrlptHandle_, SEARCH_TIMEOUT, UPNP_WANPPP_SERVICE, this); |
| 267 | if (err != UPNP_E_SUCCESS) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 268 | if (logger_) logger_->warn("PUPnP: Send search for UPNP_WANPPP_SERVICE failed. Error {:d}: {}", |
| 269 | err, |
| 270 | UpnpGetErrorMessage(err)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 271 | } |
| 272 | } |
| 273 | |
| 274 | void |
| 275 | PUPnP::clearIgds() |
| 276 | { |
Morteza Namvar | 5f63952 | 2023-07-04 17:08:58 -0400 | [diff] [blame] | 277 | // JAMI_DBG("PUPnP: clearing IGDs and devices lists"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 278 | |
François-Simon Fauteux-Chapleau | d797698 | 2024-04-26 16:06:23 -0400 | [diff] [blame] | 279 | // 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éraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 285 | searchForIgdTimer_.cancel(); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 286 | |
| 287 | igdSearchCounter_ = 0; |
| 288 | |
| 289 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 290 | std::lock_guard lock(pupnpMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 291 | for (auto const& igd : validIgdList_) { |
| 292 | igd->setValid(false); |
| 293 | } |
| 294 | validIgdList_.clear(); |
| 295 | hostAddress_ = {}; |
| 296 | } |
| 297 | |
| 298 | discoveredIgdList_.clear(); |
| 299 | } |
| 300 | |
| 301 | void |
| 302 | PUPnP::searchForIgd() |
| 303 | { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 304 | // Update local address before searching. |
| 305 | updateHostAddress(); |
| 306 | |
| 307 | if (isReady()) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 308 | if (logger_) logger_->debug("PUPnP: Already have a valid IGD. Skip the search request"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 309 | return; |
| 310 | } |
| 311 | |
| 312 | if (igdSearchCounter_++ >= PUPNP_MAX_RESTART_SEARCH_RETRIES) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 313 | if (logger_) logger_->warn("PUPnP: Setup failed after {:d} trials. PUPnP will be disabled!", |
| 314 | PUPNP_MAX_RESTART_SEARCH_RETRIES); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 315 | return; |
| 316 | } |
| 317 | |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 318 | if (logger_) logger_->debug("PUPnP: Start search for IGD: attempt {:d}", igdSearchCounter_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 319 | |
| 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éraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 324 | if (logger_) logger_->warn("PUPnP: Host address is invalid. Skipping the IGD search"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 325 | } 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éraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 338 | if (logger_) logger_->warn("PUPnP: PUPNP not fully setup. Skipping the IGD search"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 339 | } |
| 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éraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 346 | 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éraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 349 | if (auto upnpThis = w.lock()) |
| 350 | upnpThis->searchForIgd(); |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 351 | } |
| 352 | }); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 353 | } |
| 354 | |
| 355 | std::list<std::shared_ptr<IGD>> |
| 356 | PUPnP::getIgdList() const |
| 357 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 358 | std::lock_guard lock(pupnpMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 359 | 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 | |
| 369 | bool |
| 370 | PUPnP::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 | |
| 379 | bool |
| 380 | PUPnP::hasValidIgd() const |
| 381 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 382 | std::lock_guard lock(pupnpMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 383 | for (auto& it : validIgdList_) { |
| 384 | if (it->isValid()) { |
| 385 | return true; |
| 386 | } |
| 387 | } |
| 388 | return false; |
| 389 | } |
| 390 | |
| 391 | void |
| 392 | PUPnP::updateHostAddress() |
| 393 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 394 | std::lock_guard lock(pupnpMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 395 | hostAddress_ = ip_utils::getLocalAddr(AF_INET); |
| 396 | } |
| 397 | |
| 398 | bool |
| 399 | PUPnP::hasValidHostAddress() |
| 400 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 401 | std::lock_guard lock(pupnpMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 402 | return hostAddress_ and not hostAddress_.isLoopback(); |
| 403 | } |
| 404 | |
| 405 | void |
| 406 | PUPnP::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 | |
| 419 | bool |
| 420 | PUPnP::validateIgd(const std::string& location, IXML_Document* doc_container_ptr) |
| 421 | { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 422 | 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éraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 439 | 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éraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 455 | |
| 456 | // Check if IGD is connected. |
| 457 | if (not actionIsIgdConnected(*igd_candidate)) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 458 | if (logger_) logger_->warn("PUPnP: IGD candidate {} is not connected", igd_candidate->getUID().c_str()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 459 | return false; |
| 460 | } |
| 461 | |
| 462 | // Validate external Ip. |
| 463 | igd_candidate->setPublicIp(actionGetExternalIP(*igd_candidate)); |
| 464 | if (igd_candidate->getPublicIp().toString().empty()) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 465 | if (logger_) logger_->warn("PUPnP: IGD candidate {} has no valid external Ip", |
| 466 | igd_candidate->getUID().c_str()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 467 | return false; |
| 468 | } |
| 469 | |
| 470 | // Validate internal Ip. |
| 471 | if (igd_candidate->getBaseURL().empty()) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 472 | if (logger_) logger_->warn("PUPnP: IGD candidate {} has no valid internal Ip", |
| 473 | igd_candidate->getUID().c_str()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 474 | 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éraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 483 | if (logger_) logger_->warn("PUPnP: Could not set internal address for IGD candidate {}", |
| 484 | igd_candidate->getUID().c_str()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 485 | 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éraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 493 | std::lock_guard lock(pupnpMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 494 | for (auto& igd : validIgdList_) { |
| 495 | // Must not be a null pointer |
| 496 | assert(igd.get() != nullptr); |
| 497 | if (*igd == *igd_candidate) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 498 | 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éraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 502 | return true; |
| 503 | } |
| 504 | } |
| 505 | } |
| 506 | |
| 507 | // We have a valid IGD |
| 508 | igd_candidate->setValid(true); |
| 509 | |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 510 | if (logger_) logger_->debug("PUPnP: Added a new IGD [{}] to the list of valid IGDs", |
| 511 | igd_candidate->getUID()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 512 | |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 513 | if (logger_) logger_->debug("PUPnP: New IGD addresses [int: {} - ext: {}]", |
| 514 | igd_candidate->toString(), |
| 515 | igd_candidate->getPublicIp().toString()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 516 | |
| 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éraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 524 | 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éraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 529 | } else { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 530 | if (logger_) logger_->debug("PUPnP: Successfully subscribed to IGD {}", igd_candidate->getUID()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 531 | } |
| 532 | |
| 533 | { |
| 534 | // This is a new (and hopefully valid) IGD. |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 535 | std::lock_guard lock(pupnpMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 536 | validIgdList_.emplace_back(igd_candidate); |
| 537 | } |
| 538 | |
| 539 | // Report to the listener. |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 540 | ioContext->post([w = weak(), igd_candidate] { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 541 | 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 | |
| 550 | void |
| 551 | PUPnP::requestMappingAdd(const Mapping& mapping) |
| 552 | { |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 553 | ioContext->post([w = weak(), mapping] { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 554 | 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 | |
| 571 | void |
| 572 | PUPnP::requestMappingRemove(const Mapping& mapping) |
| 573 | { |
| 574 | // Send remove request using the matching IGD |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 575 | ioContext->dispatch([w = weak(), mapping] { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 576 | 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 | |
| 591 | std::shared_ptr<UPnPIGD> |
| 592 | PUPnP::findMatchingIgd(const std::string& ctrlURL) const |
| 593 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 594 | std::lock_guard lock(pupnpMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 595 | |
| 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éraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 606 | if (logger_) logger_->warn("PUPnP: Did not find the IGD matching ctrl URL [{}]", ctrlURL); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 607 | return {}; |
| 608 | } |
| 609 | |
| 610 | return std::dynamic_pointer_cast<UPnPIGD>(*iter); |
| 611 | } |
| 612 | |
| 613 | void |
| 614 | PUPnP::processAddMapAction(const Mapping& map) |
| 615 | { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 616 | if (observer_ == nullptr) |
| 617 | return; |
| 618 | |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 619 | ioContext->post([w = weak(), map] { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 620 | if (auto upnpThis = w.lock()) { |
| 621 | if (upnpThis->observer_) |
| 622 | upnpThis->observer_->onMappingAdded(map.getIgd(), std::move(map)); |
| 623 | } |
| 624 | }); |
| 625 | } |
| 626 | |
| 627 | void |
| 628 | PUPnP::processRequestMappingFailure(const Mapping& map) |
| 629 | { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 630 | if (observer_ == nullptr) |
| 631 | return; |
| 632 | |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 633 | ioContext->post([w = weak(), map] { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 634 | if (auto upnpThis = w.lock()) { |
Adrien Beraud | 64bb00f | 2023-08-23 19:06:46 -0400 | [diff] [blame] | 635 | if (upnpThis->logger_) upnpThis->logger_->debug("PUPnP: Closed mapping {}", map.toString()); |
Morteza Namvar | 5f63952 | 2023-07-04 17:08:58 -0400 | [diff] [blame] | 636 | // JAMI_DBG("PUPnP: Failed to request mapping %s", map.toString().c_str()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 637 | if (upnpThis->observer_) |
| 638 | upnpThis->observer_->onMappingRequestFailed(map); |
| 639 | } |
| 640 | }); |
| 641 | } |
| 642 | |
| 643 | void |
| 644 | PUPnP::processRemoveMapAction(const Mapping& map) |
| 645 | { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 646 | if (observer_ == nullptr) |
| 647 | return; |
| 648 | |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 649 | if (logger_) logger_->warn("PUPnP: Closed mapping {}", map.toString()); |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 650 | ioContext->post([map, obs = observer_] { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 651 | obs->onMappingRemoved(map.getIgd(), std::move(map)); |
| 652 | }); |
| 653 | } |
| 654 | |
| 655 | const char* |
| 656 | PUPnP::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 | |
| 694 | int |
| 695 | PUPnP::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éraud | a61adb5 | 2023-08-23 09:31:02 -0400 | [diff] [blame] | 700 | fmt::print(stderr, "PUPnP: Control point callback without PUPnP"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 701 | return UPNP_E_SUCCESS; |
| 702 | } |
| 703 | |
| 704 | auto upnpThis = pupnp->weak().lock(); |
Adrien Béraud | a61adb5 | 2023-08-23 09:31:02 -0400 | [diff] [blame] | 705 | if (not upnpThis) { |
| 706 | fmt::print(stderr, "PUPnP: Control point callback without PUPnP"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 707 | return UPNP_E_SUCCESS; |
Adrien Béraud | a61adb5 | 2023-08-23 09:31:02 -0400 | [diff] [blame] | 708 | } |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 709 | |
| 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 | |
| 718 | PUPnP::CtrlAction |
| 719 | PUPnP::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 | |
| 736 | void |
| 737 | PUPnP::processDiscoverySearchResult(const std::string& cpDeviceId, |
| 738 | const std::string& igdLocationUrl, |
| 739 | const IpAddr& dstAddr) |
| 740 | { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 741 | // 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éraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 747 | if (logger_) logger_->warn("PUPnP: Local address is invalid. Ignore search result for now!"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 748 | 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 Beraud | 64bb00f | 2023-08-23 19:06:46 -0400 | [diff] [blame] | 757 | //if (logger_) logger_->debug("PUPnP: IGD [{}] already in the list", igdId); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 758 | return; |
| 759 | } |
| 760 | |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 761 | if (logger_) logger_->debug("PUPnP: Discovered a new IGD [{}]", igdId); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 762 | |
| 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éraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 771 | 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éraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 774 | 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-Chapleau | 808db4f | 2024-04-19 11:39:47 -0400 | [diff] [blame] | 779 | ongoingOpsThreadPool_.run([w = weak(), url=igdLocationUrl] { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 780 | if (auto upnpThis = w.lock()) { |
Adrien Beraud | 3bd61c9 | 2023-08-17 16:57:37 -0400 | [diff] [blame] | 781 | upnpThis->downLoadIgdDescription(url); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 782 | } |
| 783 | }); |
| 784 | } |
| 785 | |
| 786 | void |
| 787 | PUPnP::downLoadIgdDescription(const std::string& locationUrl) |
| 788 | { |
Adrien Beraud | 3bd61c9 | 2023-08-17 16:57:37 -0400 | [diff] [blame] | 789 | if(logger_) logger_->debug("PUPnP: downLoadIgdDescription {}", locationUrl); |
Sébastien Blin | d14fc35 | 2023-10-06 15:21:53 -0400 | [diff] [blame] | 790 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 791 | std::lock_guard lk(ongoingOpsMtx_); |
Sébastien Blin | d14fc35 | 2023-10-06 15:21:53 -0400 | [diff] [blame] | 792 | if (destroying_) |
| 793 | return; |
| 794 | ongoingOps_++; |
| 795 | } |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 796 | IXML_Document* doc_container_ptr = nullptr; |
| 797 | int upnp_err = UpnpDownloadXmlDoc(locationUrl.c_str(), &doc_container_ptr); |
| 798 | |
François-Simon Fauteux-Chapleau | 808db4f | 2024-04-19 11:39:47 -0400 | [diff] [blame] | 799 | 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éraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 806 | if (upnp_err != UPNP_E_SUCCESS or not doc_container_ptr) { |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 807 | if(logger_) logger_->warn("PUPnP: Error downloading device XML document from {} -> {}", |
| 808 | locationUrl, |
| 809 | UpnpGetErrorMessage(upnp_err)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 810 | } else { |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 811 | 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éraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 813 | if (auto upnpThis = w.lock()) { |
| 814 | upnpThis->validateIgd(url, doc_container_ptr); |
| 815 | } |
| 816 | }); |
| 817 | } |
Sébastien Blin | d14fc35 | 2023-10-06 15:21:53 -0400 | [diff] [blame] | 818 | ongoingOps_--; |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 819 | } |
| 820 | |
| 821 | void |
| 822 | PUPnP::processDiscoveryAdvertisementByebye(const std::string& cpDeviceId) |
| 823 | { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 824 | discoveredIgdList_.erase(cpDeviceId); |
| 825 | |
| 826 | std::shared_ptr<IGD> igd; |
| 827 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 828 | std::lock_guard lk(pupnpMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 829 | for (auto it = validIgdList_.begin(); it != validIgdList_.end();) { |
| 830 | if ((*it)->getUID() == cpDeviceId) { |
| 831 | igd = *it; |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 832 | 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éraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 836 | 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 | |
| 852 | void |
| 853 | PUPnP::processDiscoverySubscriptionExpired(Upnp_EventType event_type, const std::string& eventSubUrl) |
| 854 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 855 | std::lock_guard lk(pupnpMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 856 | for (auto& it : validIgdList_) { |
| 857 | if (auto igd = std::dynamic_pointer_cast<UPnPIGD>(it)) { |
| 858 | if (igd->getEventSubURL() == eventSubUrl) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 859 | 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éraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 863 | UpnpSubscribeAsync(ctrlptHandle_, |
| 864 | eventSubUrl.c_str(), |
| 865 | UPNP_INFINITE, |
| 866 | subEventCallback, |
| 867 | this); |
| 868 | break; |
| 869 | } |
| 870 | } |
| 871 | } |
| 872 | } |
| 873 | |
| 874 | int |
| 875 | PUPnP::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éraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 887 | if (logger_) logger_->error("PUPnP: UPNP discovery is in erroneous state: %s", |
| 888 | UpnpGetErrorMessage(upnp_status)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 889 | 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éraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 896 | ioContext->post([w = weak(), |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 897 | 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éraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 912 | ioContext->post([w = weak(), deviceId = std::move(deviceId)] { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 913 | 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éraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 933 | if (logger_) logger_->warn("PUPnP: Received Subscription Event {}", eventTypeToString(event_type)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 934 | const UpnpEventSubscribe* es_event = (const UpnpEventSubscribe*) event; |
| 935 | if (es_event == nullptr) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 936 | if (logger_) logger_->warn("PUPnP: Received Subscription Event with null pointer"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 937 | break; |
| 938 | } |
| 939 | std::string publisherUrl(UpnpEventSubscribe_get_PublisherUrl_cstr(es_event)); |
| 940 | |
| 941 | // Process the response on the main thread. |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 942 | ioContext->post([w = weak(), event_type, publisherUrl = std::move(publisherUrl)] { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 943 | 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éraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 953 | if (logger_) logger_->warn("PUPnP: Received Subscription Event with null pointer"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 954 | } 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éraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 962 | if (logger_) logger_->warn("PUPnP: Received Action Complete Event with null pointer"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 963 | 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éraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 968 | if (logger_) logger_->warn("PUPnP: Received Action Complete error %i %s", err, UpnpGetErrorMessage(err)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 969 | } else { |
| 970 | auto actionRequest = UpnpActionComplete_get_ActionRequest(a_event); |
| 971 | // Abort if there is no action to process. |
| 972 | if (actionRequest == nullptr) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 973 | if (logger_) logger_->warn("PUPnP: Can't get the Action Request data from the event"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 974 | break; |
| 975 | } |
| 976 | |
| 977 | auto actionResult = UpnpActionComplete_get_ActionResult(a_event); |
| 978 | if (actionResult != nullptr) { |
| 979 | ixmlDocument_free(actionResult); |
| 980 | } else { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 981 | if (logger_) logger_->warn("PUPnP: Action Result document not found"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 982 | } |
| 983 | } |
| 984 | break; |
| 985 | } |
| 986 | default: { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 987 | if (logger_) logger_->warn("PUPnP: Unhandled Control Point event"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 988 | break; |
| 989 | } |
| 990 | } |
| 991 | |
| 992 | return UPNP_E_SUCCESS; |
| 993 | } |
| 994 | |
| 995 | int |
| 996 | PUPnP::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éraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1000 | return 0; |
| 1001 | } |
| 1002 | |
| 1003 | int |
| 1004 | PUPnP::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 Namvar | 5f63952 | 2023-07-04 17:08:58 -0400 | [diff] [blame] | 1009 | // JAMI_ERR("PUPnP: Unexpected null pointer!"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1010 | 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éraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1015 | if (logger_) logger_->warn("PUPnP: Subscription error {} from {}", |
| 1016 | UpnpGetErrorMessage(upnp_err), |
| 1017 | publisherUrl); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1018 | return upnp_err; |
| 1019 | } |
| 1020 | |
| 1021 | return UPNP_E_SUCCESS; |
| 1022 | } |
| 1023 | |
| 1024 | std::unique_ptr<UPnPIGD> |
| 1025 | PUPnP::parseIgd(IXML_Document* doc, std::string locationUrl) |
| 1026 | { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1027 | if (not(doc and !locationUrl.empty())) |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1028 | 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éraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1033 | if (logger_) logger_->warn("PUPnP: could not find UDN in description document of device"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1034 | return nullptr; |
| 1035 | } else { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 1036 | std::lock_guard lk(pupnpMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1037 | 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éraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1045 | if (logger_) logger_->debug("PUPnP: Found new device [{}]", UDN); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1046 | |
| 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éraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1109 | if (logger_) logger_->warn("PUPnP: Error resolving absolute controlURL -> {}", |
| 1110 | UpnpGetErrorMessage(upnp_err)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1111 | |
| 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éraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1117 | if (logger_) logger_->warn("PUPnP: IGD event sub URL is empty. Going to next node"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1118 | 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éraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1126 | if (logger_) logger_->warn("PUPnP: Error resolving absolute eventSubURL -> {}", |
| 1127 | UpnpGetErrorMessage(upnp_err)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1128 | |
| 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 | |
| 1146 | bool |
| 1147 | PUPnP::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éraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1158 | if (logger_) logger_->warn("PUPnP: Failed to make GetStatusInfo action"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1159 | 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 Blin | 45b5069 | 2024-03-06 11:18:50 -0500 | [diff] [blame] | 1170 | 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éraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1177 | if (not response_container_ptr or upnp_err != UPNP_E_SUCCESS) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1178 | if (logger_) logger_->warn("PUPnP: Failed to send GetStatusInfo action -> {}", UpnpGetErrorMessage(upnp_err)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1179 | return false; |
| 1180 | } |
| 1181 | XMLDocument response(response_container_ptr, ixmlDocument_free); |
| 1182 | |
Adrien Béraud | d78d1ac | 2023-08-25 10:43:33 -0400 | [diff] [blame] | 1183 | if (errorOnResponse(response.get(), logger_)) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1184 | 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éraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1188 | return false; |
| 1189 | } |
| 1190 | |
| 1191 | // Parse response. |
| 1192 | auto status = getFirstDocItem(response.get(), "NewConnectionStatus"); |
| 1193 | return status == "Connected"; |
| 1194 | } |
| 1195 | |
| 1196 | IpAddr |
| 1197 | PUPnP::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éraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1216 | if (logger_) logger_->warn("PUPnP: Failed to make GetExternalIPAddress action"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1217 | 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éraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1230 | if (logger_) logger_->warn("PUPnP: Failed to send GetExternalIPAddress action -> {}", |
| 1231 | UpnpGetErrorMessage(upnp_err)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1232 | return {}; |
| 1233 | } |
| 1234 | |
Adrien Béraud | d78d1ac | 2023-08-25 10:43:33 -0400 | [diff] [blame] | 1235 | if (errorOnResponse(response.get(), logger_)) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1236 | if (logger_) logger_->warn("PUPnP: Failed to get GetExternalIPAddress from {} -> {:d}: {}", |
| 1237 | igd.getServiceType(), |
| 1238 | upnp_err, |
| 1239 | UpnpGetErrorMessage(upnp_err)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1240 | return {}; |
| 1241 | } |
| 1242 | |
| 1243 | return {getFirstDocItem(response.get(), "NewExternalIPAddress")}; |
| 1244 | } |
| 1245 | |
| 1246 | std::map<Mapping::key_t, Mapping> |
| 1247 | PUPnP::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 Namvar | 5f63952 | 2023-07-04 17:08:58 -0400 | [diff] [blame] | 1277 | // JAMI_WARN("PUPnP: Failed to add NewPortMappingIndex action"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1278 | 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 Namvar | 5f63952 | 2023-07-04 17:08:58 -0400 | [diff] [blame] | 1295 | // JAMI_ERR("PUPnP: GetGenericPortMappingEntry returned with error: %i", upnp_err); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1296 | 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 Namvar | 5f63952 | 2023-07-04 17:08:58 -0400 | [diff] [blame] | 1305 | // JAMI_DBG("PUPnP: No more mappings (found a total of %i mappings", entry_idx); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1306 | break; |
| 1307 | } else { |
| 1308 | auto errorDescription = getFirstDocItem(response.get(), "errorDescription"); |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 1309 | if (logger_) logger_->error("PUPnP: GetGenericPortMappingEntry returned with error: {:s}: {:s}", |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1310 | 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éraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 1333 | // if (logger_) logger_->e("PUPnP: GetGenericPortMappingEntry returned an invalid entry at index %i", |
Morteza Namvar | 5f63952 | 2023-07-04 17:08:58 -0400 | [diff] [blame] | 1334 | // entry_idx); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1335 | 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éraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1349 | if (logger_) logger_->debug("PUPnP: Found {:d} allocated mappings on IGD {:s}", |
| 1350 | mapList.size(), |
| 1351 | upnpIgd->toString()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1352 | |
| 1353 | return mapList; |
| 1354 | } |
| 1355 | |
François-Simon Fauteux-Chapleau | 826f0ba | 2024-05-29 15:22:21 -0400 | [diff] [blame] | 1356 | std::vector<MappingInfo> |
| 1357 | PUPnP::getMappingsInfo(const std::shared_ptr<IGD>& igd) const |
| 1358 | { |
| 1359 | auto upnpIgd = std::dynamic_pointer_cast<UPnPIGD>(igd); |
| 1360 | assert(upnpIgd); |
| 1361 | |
| 1362 | std::vector<MappingInfo> mappingInfoList; |
| 1363 | |
| 1364 | if (not clientRegistered_ or not upnpIgd->isValid() or not upnpIgd->getLocalIp()) |
| 1365 | return mappingInfoList; |
| 1366 | |
| 1367 | static constexpr const char* action_name {"GetGenericPortMappingEntry"}; |
| 1368 | |
| 1369 | for (int entry_idx = 0;; entry_idx++) { |
| 1370 | std::unique_ptr<IXML_Document, decltype(ixmlDocument_free)&> |
| 1371 | action(nullptr, ixmlDocument_free); // Action pointer. |
| 1372 | IXML_Document* action_container_ptr = nullptr; |
| 1373 | |
| 1374 | std::unique_ptr<IXML_Document, decltype(ixmlDocument_free)&> |
| 1375 | response(nullptr, ixmlDocument_free); // Response pointer. |
| 1376 | IXML_Document* response_container_ptr = nullptr; |
| 1377 | |
| 1378 | UpnpAddToAction(&action_container_ptr, |
| 1379 | action_name, |
| 1380 | upnpIgd->getServiceType().c_str(), |
| 1381 | "NewPortMappingIndex", |
| 1382 | std::to_string(entry_idx).c_str()); |
| 1383 | action.reset(action_container_ptr); |
| 1384 | |
| 1385 | int upnp_err = UpnpSendAction(ctrlptHandle_, |
| 1386 | upnpIgd->getControlURL().c_str(), |
| 1387 | upnpIgd->getServiceType().c_str(), |
| 1388 | nullptr, |
| 1389 | action.get(), |
| 1390 | &response_container_ptr); |
| 1391 | response.reset(response_container_ptr); |
| 1392 | |
| 1393 | if (!response || upnp_err != UPNP_E_SUCCESS) { |
| 1394 | break; |
| 1395 | } |
| 1396 | |
| 1397 | auto errorCode = getFirstDocItem(response.get(), "errorCode"); |
| 1398 | if (not errorCode.empty()) { |
| 1399 | auto error = to_int<int>(errorCode); |
| 1400 | if (error == ARRAY_IDX_INVALID or error == CONFLICT_IN_MAPPING) { |
| 1401 | // No more port mapping entries in the response. |
| 1402 | break; |
| 1403 | } else { |
| 1404 | auto errorDescription = getFirstDocItem(response.get(), "errorDescription"); |
| 1405 | if (logger_) logger_->error("PUPnP: GetGenericPortMappingEntry returned with error: {:s}: {:s}", |
| 1406 | errorCode, |
| 1407 | errorDescription); |
| 1408 | break; |
| 1409 | } |
| 1410 | } |
| 1411 | |
| 1412 | // Parse the response. |
| 1413 | MappingInfo info; |
| 1414 | info.remoteHost = getFirstDocItem(response.get(), "NewRemoteHost"); |
| 1415 | info.protocol = getFirstDocItem(response.get(), "NewProtocol"); |
| 1416 | info.internalClient = getFirstDocItem(response.get(), "NewInternalClient"); |
| 1417 | info.enabled = getFirstDocItem(response.get(), "NewEnabled"); |
| 1418 | info.description = getFirstDocItem(response.get(), "NewPortMappingDescription"); |
| 1419 | |
| 1420 | auto externalPort = getFirstDocItem(response.get(), "NewExternalPort"); |
| 1421 | info.externalPort = to_int<uint16_t>(externalPort); |
| 1422 | |
| 1423 | auto internalPort = getFirstDocItem(response.get(), "NewInternalPort"); |
| 1424 | info.internalPort = to_int<uint16_t>(internalPort); |
| 1425 | |
| 1426 | auto leaseDuration = getFirstDocItem(response.get(), "NewLeaseDuration"); |
| 1427 | info.leaseDuration = to_int<uint32_t>(leaseDuration); |
| 1428 | |
| 1429 | mappingInfoList.push_back(std::move(info)); |
| 1430 | } |
| 1431 | |
| 1432 | return mappingInfoList; |
| 1433 | } |
| 1434 | |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1435 | void |
| 1436 | PUPnP::deleteMappingsByDescription(const std::shared_ptr<IGD>& igd, const std::string& description) |
| 1437 | { |
| 1438 | if (not(clientRegistered_ and igd->getLocalIp())) |
| 1439 | return; |
| 1440 | |
François-Simon Fauteux-Chapleau | 1b3aba2 | 2024-05-23 11:51:48 -0400 | [diff] [blame] | 1441 | if (logger_) logger_->debug("PUPnP: Remove all mappings (if any) on IGD {} matching description prefix {}", |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1442 | igd->toString(), |
François-Simon Fauteux-Chapleau | 1b3aba2 | 2024-05-23 11:51:48 -0400 | [diff] [blame] | 1443 | description); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1444 | |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 1445 | ioContext->post([w=weak(), igd, description]{ |
| 1446 | if (auto sthis = w.lock()) { |
| 1447 | auto mapList = sthis->getMappingsListByDescr(igd, description); |
| 1448 | for (auto const& [_, map] : mapList) { |
| 1449 | sthis->requestMappingRemove(map); |
| 1450 | } |
| 1451 | } |
| 1452 | }); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1453 | } |
| 1454 | |
| 1455 | bool |
| 1456 | PUPnP::actionAddPortMapping(const Mapping& mapping) |
| 1457 | { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1458 | if (not clientRegistered_) |
| 1459 | return false; |
| 1460 | |
| 1461 | auto igdIn = std::dynamic_pointer_cast<UPnPIGD>(mapping.getIgd()); |
| 1462 | if (not igdIn) |
| 1463 | return false; |
| 1464 | |
| 1465 | // The requested IGD must be present in the list of local valid IGDs. |
| 1466 | auto igd = findMatchingIgd(igdIn->getControlURL()); |
| 1467 | |
| 1468 | if (not igd or not igd->isValid()) |
| 1469 | return false; |
| 1470 | |
| 1471 | // Action and response pointers. |
| 1472 | XMLDocument action(nullptr, ixmlDocument_free); |
| 1473 | IXML_Document* action_container_ptr = nullptr; |
| 1474 | XMLDocument response(nullptr, ixmlDocument_free); |
| 1475 | IXML_Document* response_container_ptr = nullptr; |
| 1476 | |
| 1477 | // Set action sequence. |
| 1478 | UpnpAddToAction(&action_container_ptr, |
| 1479 | ACTION_ADD_PORT_MAPPING, |
| 1480 | igd->getServiceType().c_str(), |
| 1481 | "NewRemoteHost", |
| 1482 | ""); |
| 1483 | UpnpAddToAction(&action_container_ptr, |
| 1484 | ACTION_ADD_PORT_MAPPING, |
| 1485 | igd->getServiceType().c_str(), |
| 1486 | "NewExternalPort", |
| 1487 | mapping.getExternalPortStr().c_str()); |
| 1488 | UpnpAddToAction(&action_container_ptr, |
| 1489 | ACTION_ADD_PORT_MAPPING, |
| 1490 | igd->getServiceType().c_str(), |
| 1491 | "NewProtocol", |
| 1492 | mapping.getTypeStr()); |
| 1493 | UpnpAddToAction(&action_container_ptr, |
| 1494 | ACTION_ADD_PORT_MAPPING, |
| 1495 | igd->getServiceType().c_str(), |
| 1496 | "NewInternalPort", |
| 1497 | mapping.getInternalPortStr().c_str()); |
| 1498 | UpnpAddToAction(&action_container_ptr, |
| 1499 | ACTION_ADD_PORT_MAPPING, |
| 1500 | igd->getServiceType().c_str(), |
| 1501 | "NewInternalClient", |
| 1502 | getHostAddress().toString().c_str()); |
| 1503 | UpnpAddToAction(&action_container_ptr, |
| 1504 | ACTION_ADD_PORT_MAPPING, |
| 1505 | igd->getServiceType().c_str(), |
| 1506 | "NewEnabled", |
| 1507 | "1"); |
| 1508 | UpnpAddToAction(&action_container_ptr, |
| 1509 | ACTION_ADD_PORT_MAPPING, |
| 1510 | igd->getServiceType().c_str(), |
| 1511 | "NewPortMappingDescription", |
| 1512 | mapping.toString().c_str()); |
| 1513 | UpnpAddToAction(&action_container_ptr, |
| 1514 | ACTION_ADD_PORT_MAPPING, |
| 1515 | igd->getServiceType().c_str(), |
| 1516 | "NewLeaseDuration", |
| 1517 | "0"); |
| 1518 | |
| 1519 | action.reset(action_container_ptr); |
| 1520 | |
| 1521 | int upnp_err = UpnpSendAction(ctrlptHandle_, |
| 1522 | igd->getControlURL().c_str(), |
| 1523 | igd->getServiceType().c_str(), |
| 1524 | nullptr, |
| 1525 | action.get(), |
| 1526 | &response_container_ptr); |
| 1527 | response.reset(response_container_ptr); |
| 1528 | |
| 1529 | bool success = true; |
| 1530 | |
| 1531 | if (upnp_err != UPNP_E_SUCCESS) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1532 | if (logger_) { |
| 1533 | logger_->warn("PUPnP: Failed to send action {} for mapping {}. {:d}: {}", |
| 1534 | ACTION_ADD_PORT_MAPPING, |
| 1535 | mapping.toString(), |
| 1536 | upnp_err, |
| 1537 | UpnpGetErrorMessage(upnp_err)); |
| 1538 | logger_->warn("PUPnP: IGD ctrlUrl {}", igd->getControlURL()); |
| 1539 | logger_->warn("PUPnP: IGD service type {}", igd->getServiceType()); |
| 1540 | } |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1541 | |
| 1542 | success = false; |
| 1543 | } |
| 1544 | |
| 1545 | // Check if an error has occurred. |
| 1546 | auto errorCode = getFirstDocItem(response.get(), "errorCode"); |
| 1547 | if (not errorCode.empty()) { |
| 1548 | success = false; |
| 1549 | // Try to get the error description. |
| 1550 | std::string errorDescription; |
| 1551 | if (response) { |
| 1552 | errorDescription = getFirstDocItem(response.get(), "errorDescription"); |
| 1553 | } |
| 1554 | |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1555 | if (logger_) logger_->warn("PUPnP: {:s} returned with error: {:s} {:s}", |
| 1556 | ACTION_ADD_PORT_MAPPING, |
| 1557 | errorCode, |
| 1558 | errorDescription); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1559 | } |
| 1560 | return success; |
| 1561 | } |
| 1562 | |
| 1563 | bool |
| 1564 | PUPnP::actionDeletePortMapping(const Mapping& mapping) |
| 1565 | { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1566 | if (not clientRegistered_) |
| 1567 | return false; |
| 1568 | |
| 1569 | auto igdIn = std::dynamic_pointer_cast<UPnPIGD>(mapping.getIgd()); |
| 1570 | if (not igdIn) |
| 1571 | return false; |
| 1572 | |
| 1573 | // The requested IGD must be present in the list of local valid IGDs. |
| 1574 | auto igd = findMatchingIgd(igdIn->getControlURL()); |
| 1575 | |
| 1576 | if (not igd or not igd->isValid()) |
| 1577 | return false; |
| 1578 | |
| 1579 | // Action and response pointers. |
| 1580 | XMLDocument action(nullptr, ixmlDocument_free); |
| 1581 | IXML_Document* action_container_ptr = nullptr; |
| 1582 | XMLDocument response(nullptr, ixmlDocument_free); |
| 1583 | IXML_Document* response_container_ptr = nullptr; |
| 1584 | |
| 1585 | // Set action sequence. |
| 1586 | UpnpAddToAction(&action_container_ptr, |
| 1587 | ACTION_DELETE_PORT_MAPPING, |
| 1588 | igd->getServiceType().c_str(), |
| 1589 | "NewRemoteHost", |
| 1590 | ""); |
| 1591 | UpnpAddToAction(&action_container_ptr, |
| 1592 | ACTION_DELETE_PORT_MAPPING, |
| 1593 | igd->getServiceType().c_str(), |
| 1594 | "NewExternalPort", |
| 1595 | mapping.getExternalPortStr().c_str()); |
| 1596 | UpnpAddToAction(&action_container_ptr, |
| 1597 | ACTION_DELETE_PORT_MAPPING, |
| 1598 | igd->getServiceType().c_str(), |
| 1599 | "NewProtocol", |
| 1600 | mapping.getTypeStr()); |
| 1601 | |
| 1602 | action.reset(action_container_ptr); |
| 1603 | |
| 1604 | int upnp_err = UpnpSendAction(ctrlptHandle_, |
| 1605 | igd->getControlURL().c_str(), |
| 1606 | igd->getServiceType().c_str(), |
| 1607 | nullptr, |
| 1608 | action.get(), |
| 1609 | &response_container_ptr); |
| 1610 | response.reset(response_container_ptr); |
| 1611 | |
| 1612 | bool success = true; |
| 1613 | |
| 1614 | if (upnp_err != UPNP_E_SUCCESS) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1615 | if (logger_) { |
| 1616 | logger_->warn("PUPnP: Failed to send action {} for mapping from {}. {:d}: {}", |
| 1617 | ACTION_DELETE_PORT_MAPPING, |
| 1618 | mapping.toString(), |
| 1619 | upnp_err, |
| 1620 | UpnpGetErrorMessage(upnp_err)); |
| 1621 | logger_->warn("PUPnP: IGD ctrlUrl {}", igd->getControlURL()); |
| 1622 | logger_->warn("PUPnP: IGD service type {}", igd->getServiceType()); |
| 1623 | } |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1624 | success = false; |
| 1625 | } |
| 1626 | |
| 1627 | if (not response) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1628 | if (logger_) logger_->warn("PUPnP: Failed to get response for {}", ACTION_DELETE_PORT_MAPPING); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1629 | success = false; |
| 1630 | } |
| 1631 | |
| 1632 | // Check if there is an error code. |
| 1633 | auto errorCode = getFirstDocItem(response.get(), "errorCode"); |
| 1634 | if (not errorCode.empty()) { |
| 1635 | auto errorDescription = getFirstDocItem(response.get(), "errorDescription"); |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1636 | if (logger_) logger_->warn("PUPnP: {:s} returned with error: {:s}: {:s}", |
| 1637 | ACTION_DELETE_PORT_MAPPING, |
| 1638 | errorCode, |
| 1639 | errorDescription); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1640 | success = false; |
| 1641 | } |
| 1642 | |
| 1643 | return success; |
| 1644 | } |
| 1645 | |
| 1646 | } // namespace upnp |
Sébastien Blin | 464bdff | 2023-07-19 08:02:53 -0400 | [diff] [blame] | 1647 | } // namespace dhtnet |