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 | |
| 20 | #include <opendht/thread_pool.h> |
| 21 | #include <opendht/http.h> |
| 22 | |
Adrien Béraud | 1ae60aa | 2023-07-07 09:55:09 -0400 | [diff] [blame] | 23 | namespace dhtnet { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 24 | namespace upnp { |
| 25 | |
| 26 | // Action identifiers. |
| 27 | constexpr static const char* ACTION_ADD_PORT_MAPPING {"AddPortMapping"}; |
| 28 | constexpr static const char* ACTION_DELETE_PORT_MAPPING {"DeletePortMapping"}; |
| 29 | constexpr static const char* ACTION_GET_GENERIC_PORT_MAPPING_ENTRY {"GetGenericPortMappingEntry"}; |
| 30 | constexpr static const char* ACTION_GET_STATUS_INFO {"GetStatusInfo"}; |
| 31 | constexpr static const char* ACTION_GET_EXTERNAL_IP_ADDRESS {"GetExternalIPAddress"}; |
| 32 | |
| 33 | // Error codes returned by router when trying to remove ports. |
| 34 | constexpr static int ARRAY_IDX_INVALID = 713; |
| 35 | constexpr static int CONFLICT_IN_MAPPING = 718; |
| 36 | |
| 37 | // Max number of IGD search attempts before failure. |
| 38 | constexpr static unsigned int PUPNP_MAX_RESTART_SEARCH_RETRIES {3}; |
| 39 | // IGD search timeout (in seconds). |
| 40 | constexpr static unsigned int SEARCH_TIMEOUT {60}; |
| 41 | // Base unit for the timeout between two successive IGD search. |
| 42 | constexpr static auto PUPNP_SEARCH_RETRY_UNIT {std::chrono::seconds(10)}; |
| 43 | |
| 44 | // Helper functions for xml parsing. |
| 45 | static std::string_view |
| 46 | getElementText(IXML_Node* node) |
| 47 | { |
| 48 | if (node) { |
| 49 | if (IXML_Node* textNode = ixmlNode_getFirstChild(node)) |
| 50 | if (const char* value = ixmlNode_getNodeValue(textNode)) |
| 51 | return std::string_view(value); |
| 52 | } |
| 53 | return {}; |
| 54 | } |
| 55 | |
| 56 | static std::string_view |
| 57 | getFirstDocItem(IXML_Document* doc, const char* item) |
| 58 | { |
| 59 | std::unique_ptr<IXML_NodeList, decltype(ixmlNodeList_free)&> |
| 60 | nodeList(ixmlDocument_getElementsByTagName(doc, item), ixmlNodeList_free); |
| 61 | if (nodeList) { |
| 62 | // If there are several nodes which match the tag, we only want the first one. |
| 63 | return getElementText(ixmlNodeList_item(nodeList.get(), 0)); |
| 64 | } |
| 65 | return {}; |
| 66 | } |
| 67 | |
| 68 | static std::string_view |
| 69 | getFirstElementItem(IXML_Element* element, const char* item) |
| 70 | { |
| 71 | std::unique_ptr<IXML_NodeList, decltype(ixmlNodeList_free)&> |
| 72 | nodeList(ixmlElement_getElementsByTagName(element, item), ixmlNodeList_free); |
| 73 | if (nodeList) { |
| 74 | // If there are several nodes which match the tag, we only want the first one. |
| 75 | return getElementText(ixmlNodeList_item(nodeList.get(), 0)); |
| 76 | } |
| 77 | return {}; |
| 78 | } |
| 79 | |
| 80 | static bool |
Adrien Béraud | d78d1ac | 2023-08-25 10:43:33 -0400 | [diff] [blame] | 81 | 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] | 82 | { |
| 83 | if (not doc) |
| 84 | return true; |
| 85 | |
| 86 | auto errorCode = getFirstDocItem(doc, "errorCode"); |
| 87 | if (not errorCode.empty()) { |
| 88 | auto errorDescription = getFirstDocItem(doc, "errorDescription"); |
Adrien Béraud | d78d1ac | 2023-08-25 10:43:33 -0400 | [diff] [blame] | 89 | if (logger) logger->warn("PUPnP: Response contains error: {:s}: {:s}", |
| 90 | errorCode, |
| 91 | errorDescription); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 92 | return true; |
| 93 | } |
| 94 | return false; |
| 95 | } |
| 96 | |
| 97 | // UPNP class implementation |
| 98 | |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 99 | PUPnP::PUPnP(const std::shared_ptr<asio::io_context>& ctx, const std::shared_ptr<dht::log::Logger>& logger) |
| 100 | : UPnPProtocol(logger), ioContext(ctx), searchForIgdTimer_(*ctx) |
Adrien Bé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 |
| 178 | PUPnP::setObserver(UpnpMappingObserver* obs) |
| 179 | { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 180 | observer_ = obs; |
| 181 | } |
| 182 | |
| 183 | const IpAddr |
| 184 | PUPnP::getHostAddress() const |
| 185 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 186 | std::lock_guard lock(pupnpMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 187 | return hostAddress_; |
| 188 | } |
| 189 | |
| 190 | void |
| 191 | PUPnP::terminate(std::condition_variable& cv) |
| 192 | { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 193 | if (logger_) logger_->debug("PUPnP: Terminate instance {}", fmt::ptr(this)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 194 | |
| 195 | clientRegistered_ = false; |
| 196 | observer_ = nullptr; |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 197 | std::unique_lock lk(ongoingOpsMtx_); |
Sébastien Blin | d14fc35 | 2023-10-06 15:21:53 -0400 | [diff] [blame] | 198 | destroying_ = true; |
| 199 | cvOngoing_.wait(lk, [&]() { return ongoingOps_ == 0; }); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 200 | |
| 201 | UpnpUnRegisterClient(ctrlptHandle_); |
| 202 | |
| 203 | if (initialized_) { |
| 204 | if (UpnpFinish() != UPNP_E_SUCCESS) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 205 | if (logger_) logger_->error("PUPnP: Failed to properly close lib-upnp"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 206 | } |
| 207 | |
| 208 | initialized_ = false; |
| 209 | } |
| 210 | |
| 211 | // Clear all the lists. |
| 212 | discoveredIgdList_.clear(); |
| 213 | |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 214 | std::lock_guard lock(pupnpMutex_); |
Adrien Béraud | 7a82bee | 2023-08-30 10:26:45 -0400 | [diff] [blame] | 215 | validIgdList_.clear(); |
| 216 | shutdownComplete_ = true; |
| 217 | cv.notify_one(); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 218 | } |
| 219 | |
| 220 | void |
| 221 | PUPnP::terminate() |
| 222 | { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 223 | std::condition_variable cv {}; |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 224 | ioContext->dispatch([&] { |
| 225 | terminate(cv); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 226 | }); |
| 227 | |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 228 | std::unique_lock lk(pupnpMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 229 | if (cv.wait_for(lk, std::chrono::seconds(10), [this] { return shutdownComplete_; })) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 230 | if (logger_) logger_->debug("PUPnP: Shutdown completed"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 231 | } else { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 232 | if (logger_) logger_->error("PUPnP: Shutdown timed-out"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 233 | // Force stop if the shutdown take too much time. |
| 234 | shutdownComplete_ = true; |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | void |
| 239 | PUPnP::searchForDevices() |
| 240 | { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 241 | if (logger_) logger_->debug("PUPnP: Send IGD search request"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 242 | |
| 243 | // Send out search for multiple types of devices, as some routers may possibly |
| 244 | // only reply to one. |
| 245 | |
| 246 | auto err = UpnpSearchAsync(ctrlptHandle_, SEARCH_TIMEOUT, UPNP_ROOT_DEVICE, this); |
| 247 | if (err != UPNP_E_SUCCESS) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 248 | if (logger_) logger_->warn("PUPnP: Send search for UPNP_ROOT_DEVICE failed. Error {:d}: {}", |
| 249 | err, |
| 250 | UpnpGetErrorMessage(err)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 251 | } |
| 252 | |
| 253 | err = UpnpSearchAsync(ctrlptHandle_, SEARCH_TIMEOUT, UPNP_IGD_DEVICE, this); |
| 254 | if (err != UPNP_E_SUCCESS) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 255 | if (logger_) logger_->warn("PUPnP: Send search for UPNP_IGD_DEVICE failed. Error {:d}: {}", |
| 256 | err, |
| 257 | UpnpGetErrorMessage(err)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 258 | } |
| 259 | |
| 260 | err = UpnpSearchAsync(ctrlptHandle_, SEARCH_TIMEOUT, UPNP_WANIP_SERVICE, this); |
| 261 | if (err != UPNP_E_SUCCESS) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 262 | if (logger_) logger_->warn("PUPnP: Send search for UPNP_WANIP_SERVICE failed. Error {:d}: {}", |
| 263 | err, |
| 264 | UpnpGetErrorMessage(err)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 265 | } |
| 266 | |
| 267 | err = UpnpSearchAsync(ctrlptHandle_, SEARCH_TIMEOUT, UPNP_WANPPP_SERVICE, this); |
| 268 | if (err != UPNP_E_SUCCESS) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 269 | if (logger_) logger_->warn("PUPnP: Send search for UPNP_WANPPP_SERVICE failed. Error {:d}: {}", |
| 270 | err, |
| 271 | UpnpGetErrorMessage(err)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 272 | } |
| 273 | } |
| 274 | |
| 275 | void |
| 276 | PUPnP::clearIgds() |
| 277 | { |
Morteza Namvar | 5f63952 | 2023-07-04 17:08:58 -0400 | [diff] [blame] | 278 | // JAMI_DBG("PUPnP: clearing IGDs and devices lists"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 279 | |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 280 | searchForIgdTimer_.cancel(); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 281 | |
| 282 | igdSearchCounter_ = 0; |
| 283 | |
| 284 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 285 | std::lock_guard lock(pupnpMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 286 | for (auto const& igd : validIgdList_) { |
| 287 | igd->setValid(false); |
| 288 | } |
| 289 | validIgdList_.clear(); |
| 290 | hostAddress_ = {}; |
| 291 | } |
| 292 | |
| 293 | discoveredIgdList_.clear(); |
| 294 | } |
| 295 | |
| 296 | void |
| 297 | PUPnP::searchForIgd() |
| 298 | { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 299 | // Update local address before searching. |
| 300 | updateHostAddress(); |
| 301 | |
| 302 | if (isReady()) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 303 | 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] | 304 | return; |
| 305 | } |
| 306 | |
| 307 | if (igdSearchCounter_++ >= PUPNP_MAX_RESTART_SEARCH_RETRIES) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 308 | if (logger_) logger_->warn("PUPnP: Setup failed after {:d} trials. PUPnP will be disabled!", |
| 309 | PUPNP_MAX_RESTART_SEARCH_RETRIES); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 310 | return; |
| 311 | } |
| 312 | |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 313 | 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] | 314 | |
| 315 | // Do not init if the host is not valid. Otherwise, the init will fail |
| 316 | // anyway and may put libupnp in an unstable state (mainly deadlocks) |
| 317 | // even if the UpnpFinish() method is called. |
| 318 | if (not hasValidHostAddress()) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 319 | 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] | 320 | } else { |
| 321 | // Init and register if needed |
| 322 | if (not initialized_) { |
| 323 | initUpnpLib(); |
| 324 | } |
| 325 | if (initialized_ and not clientRegistered_) { |
| 326 | registerClient(); |
| 327 | } |
| 328 | // Start searching |
| 329 | if (clientRegistered_) { |
| 330 | assert(initialized_); |
| 331 | searchForDevices(); |
| 332 | } else { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 333 | 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] | 334 | } |
| 335 | } |
| 336 | |
| 337 | // Cancel the current timer (if any) and re-schedule. |
| 338 | // The connectivity change may be received while the the local |
| 339 | // interface is not fully setup. The rescheduling typically |
| 340 | // usefull to mitigate this race. |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 341 | searchForIgdTimer_.expires_after(PUPNP_SEARCH_RETRY_UNIT * igdSearchCounter_); |
| 342 | searchForIgdTimer_.async_wait([w = weak()] (const asio::error_code& ec) { |
| 343 | if (not ec) { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 344 | if (auto upnpThis = w.lock()) |
| 345 | upnpThis->searchForIgd(); |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 346 | } |
| 347 | }); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 348 | } |
| 349 | |
| 350 | std::list<std::shared_ptr<IGD>> |
| 351 | PUPnP::getIgdList() const |
| 352 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 353 | std::lock_guard lock(pupnpMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 354 | std::list<std::shared_ptr<IGD>> igdList; |
| 355 | for (auto& it : validIgdList_) { |
| 356 | // Return only active IGDs. |
| 357 | if (it->isValid()) { |
| 358 | igdList.emplace_back(it); |
| 359 | } |
| 360 | } |
| 361 | return igdList; |
| 362 | } |
| 363 | |
| 364 | bool |
| 365 | PUPnP::isReady() const |
| 366 | { |
| 367 | // Must at least have a valid local address. |
| 368 | if (not getHostAddress() or getHostAddress().isLoopback()) |
| 369 | return false; |
| 370 | |
| 371 | return hasValidIgd(); |
| 372 | } |
| 373 | |
| 374 | bool |
| 375 | PUPnP::hasValidIgd() const |
| 376 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 377 | std::lock_guard lock(pupnpMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 378 | for (auto& it : validIgdList_) { |
| 379 | if (it->isValid()) { |
| 380 | return true; |
| 381 | } |
| 382 | } |
| 383 | return false; |
| 384 | } |
| 385 | |
| 386 | void |
| 387 | PUPnP::updateHostAddress() |
| 388 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 389 | std::lock_guard lock(pupnpMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 390 | hostAddress_ = ip_utils::getLocalAddr(AF_INET); |
| 391 | } |
| 392 | |
| 393 | bool |
| 394 | PUPnP::hasValidHostAddress() |
| 395 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 396 | std::lock_guard lock(pupnpMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 397 | return hostAddress_ and not hostAddress_.isLoopback(); |
| 398 | } |
| 399 | |
| 400 | void |
| 401 | PUPnP::incrementErrorsCounter(const std::shared_ptr<IGD>& igd) |
| 402 | { |
| 403 | if (not igd or not igd->isValid()) |
| 404 | return; |
| 405 | if (not igd->incrementErrorsCounter()) { |
| 406 | // Disable this IGD. |
| 407 | igd->setValid(false); |
| 408 | // Notify the listener. |
| 409 | if (observer_) |
| 410 | observer_->onIgdUpdated(igd, UpnpIgdEvent::INVALID_STATE); |
| 411 | } |
| 412 | } |
| 413 | |
| 414 | bool |
| 415 | PUPnP::validateIgd(const std::string& location, IXML_Document* doc_container_ptr) |
| 416 | { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 417 | assert(doc_container_ptr != nullptr); |
| 418 | |
| 419 | XMLDocument document(doc_container_ptr, ixmlDocument_free); |
| 420 | auto descDoc = document.get(); |
| 421 | // Check device type. |
| 422 | auto deviceType = getFirstDocItem(descDoc, "deviceType"); |
| 423 | if (deviceType != UPNP_IGD_DEVICE) { |
| 424 | // Device type not IGD. |
| 425 | return false; |
| 426 | } |
| 427 | |
| 428 | std::shared_ptr<UPnPIGD> igd_candidate = parseIgd(descDoc, location); |
| 429 | if (not igd_candidate) { |
| 430 | // No valid IGD candidate. |
| 431 | return false; |
| 432 | } |
| 433 | |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 434 | if (logger_) logger_->debug("PUPnP: Validating the IGD candidate [UDN: {}]\n" |
| 435 | " Name : {}\n" |
| 436 | " Service Type : {}\n" |
| 437 | " Service ID : {}\n" |
| 438 | " Base URL : {}\n" |
| 439 | " Location URL : {}\n" |
| 440 | " control URL : {}\n" |
| 441 | " Event URL : {}", |
| 442 | igd_candidate->getUID(), |
| 443 | igd_candidate->getFriendlyName(), |
| 444 | igd_candidate->getServiceType(), |
| 445 | igd_candidate->getServiceId(), |
| 446 | igd_candidate->getBaseURL(), |
| 447 | igd_candidate->getLocationURL(), |
| 448 | igd_candidate->getControlURL(), |
| 449 | igd_candidate->getEventSubURL()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 450 | |
| 451 | // Check if IGD is connected. |
| 452 | if (not actionIsIgdConnected(*igd_candidate)) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 453 | 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] | 454 | return false; |
| 455 | } |
| 456 | |
| 457 | // Validate external Ip. |
| 458 | igd_candidate->setPublicIp(actionGetExternalIP(*igd_candidate)); |
| 459 | if (igd_candidate->getPublicIp().toString().empty()) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 460 | if (logger_) logger_->warn("PUPnP: IGD candidate {} has no valid external Ip", |
| 461 | igd_candidate->getUID().c_str()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 462 | return false; |
| 463 | } |
| 464 | |
| 465 | // Validate internal Ip. |
| 466 | if (igd_candidate->getBaseURL().empty()) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 467 | if (logger_) logger_->warn("PUPnP: IGD candidate {} has no valid internal Ip", |
| 468 | igd_candidate->getUID().c_str()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 469 | return false; |
| 470 | } |
| 471 | |
| 472 | // Typically the IGD local address should be extracted from the XML |
| 473 | // document (e.g. parsing the base URL). For simplicity, we assume |
| 474 | // that it matches the gateway as seen by the local interface. |
| 475 | if (const auto& localGw = ip_utils::getLocalGateway()) { |
| 476 | igd_candidate->setLocalIp(localGw); |
| 477 | } else { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 478 | if (logger_) logger_->warn("PUPnP: Could not set internal address for IGD candidate {}", |
| 479 | igd_candidate->getUID().c_str()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 480 | return false; |
| 481 | } |
| 482 | |
| 483 | // Store info for subscription. |
| 484 | std::string eventSub = igd_candidate->getEventSubURL(); |
| 485 | |
| 486 | { |
| 487 | // Add the IGD if not already present in the list. |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 488 | std::lock_guard lock(pupnpMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 489 | for (auto& igd : validIgdList_) { |
| 490 | // Must not be a null pointer |
| 491 | assert(igd.get() != nullptr); |
| 492 | if (*igd == *igd_candidate) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 493 | if (logger_) logger_->debug("PUPnP: Device [{}] with int/ext addresses [{}:{}] is already in the list of valid IGDs", |
| 494 | igd_candidate->getUID(), |
| 495 | igd_candidate->toString(), |
| 496 | igd_candidate->getPublicIp().toString()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 497 | return true; |
| 498 | } |
| 499 | } |
| 500 | } |
| 501 | |
| 502 | // We have a valid IGD |
| 503 | igd_candidate->setValid(true); |
| 504 | |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 505 | if (logger_) logger_->debug("PUPnP: Added a new IGD [{}] to the list of valid IGDs", |
| 506 | igd_candidate->getUID()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 507 | |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 508 | if (logger_) logger_->debug("PUPnP: New IGD addresses [int: {} - ext: {}]", |
| 509 | igd_candidate->toString(), |
| 510 | igd_candidate->getPublicIp().toString()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 511 | |
| 512 | // Subscribe to IGD events. |
| 513 | int upnp_err = UpnpSubscribeAsync(ctrlptHandle_, |
| 514 | eventSub.c_str(), |
| 515 | UPNP_INFINITE, |
| 516 | subEventCallback, |
| 517 | this); |
| 518 | if (upnp_err != UPNP_E_SUCCESS) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 519 | if (logger_) logger_->warn("PUPnP: Failed to send subscribe request to {}: error %i - {}", |
| 520 | igd_candidate->getUID(), |
| 521 | upnp_err, |
| 522 | UpnpGetErrorMessage(upnp_err)); |
| 523 | return false; |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 524 | } else { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 525 | 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] | 526 | } |
| 527 | |
| 528 | { |
| 529 | // This is a new (and hopefully valid) IGD. |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 530 | std::lock_guard lock(pupnpMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 531 | validIgdList_.emplace_back(igd_candidate); |
| 532 | } |
| 533 | |
| 534 | // Report to the listener. |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 535 | ioContext->post([w = weak(), igd_candidate] { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 536 | if (auto upnpThis = w.lock()) { |
| 537 | if (upnpThis->observer_) |
| 538 | upnpThis->observer_->onIgdUpdated(igd_candidate, UpnpIgdEvent::ADDED); |
| 539 | } |
| 540 | }); |
| 541 | |
| 542 | return true; |
| 543 | } |
| 544 | |
| 545 | void |
| 546 | PUPnP::requestMappingAdd(const Mapping& mapping) |
| 547 | { |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 548 | ioContext->post([w = weak(), mapping] { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 549 | if (auto upnpThis = w.lock()) { |
| 550 | if (not upnpThis->isRunning()) |
| 551 | return; |
| 552 | Mapping mapRes(mapping); |
| 553 | if (upnpThis->actionAddPortMapping(mapRes)) { |
| 554 | mapRes.setState(MappingState::OPEN); |
| 555 | mapRes.setInternalAddress(upnpThis->getHostAddress().toString()); |
| 556 | upnpThis->processAddMapAction(mapRes); |
| 557 | } else { |
| 558 | upnpThis->incrementErrorsCounter(mapRes.getIgd()); |
| 559 | mapRes.setState(MappingState::FAILED); |
| 560 | upnpThis->processRequestMappingFailure(mapRes); |
| 561 | } |
| 562 | } |
| 563 | }); |
| 564 | } |
| 565 | |
| 566 | void |
| 567 | PUPnP::requestMappingRemove(const Mapping& mapping) |
| 568 | { |
| 569 | // Send remove request using the matching IGD |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 570 | ioContext->dispatch([w = weak(), mapping] { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 571 | if (auto upnpThis = w.lock()) { |
| 572 | // Abort if we are shutting down. |
| 573 | if (not upnpThis->isRunning()) |
| 574 | return; |
| 575 | if (upnpThis->actionDeletePortMapping(mapping)) { |
| 576 | upnpThis->processRemoveMapAction(mapping); |
| 577 | } else { |
| 578 | assert(mapping.getIgd()); |
| 579 | // Dont need to report in case of failure. |
| 580 | upnpThis->incrementErrorsCounter(mapping.getIgd()); |
| 581 | } |
| 582 | } |
| 583 | }); |
| 584 | } |
| 585 | |
| 586 | std::shared_ptr<UPnPIGD> |
| 587 | PUPnP::findMatchingIgd(const std::string& ctrlURL) const |
| 588 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 589 | std::lock_guard lock(pupnpMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 590 | |
| 591 | auto iter = std::find_if(validIgdList_.begin(), |
| 592 | validIgdList_.end(), |
| 593 | [&ctrlURL](const std::shared_ptr<IGD>& igd) { |
| 594 | if (auto upnpIgd = std::dynamic_pointer_cast<UPnPIGD>(igd)) { |
| 595 | return upnpIgd->getControlURL() == ctrlURL; |
| 596 | } |
| 597 | return false; |
| 598 | }); |
| 599 | |
| 600 | if (iter == validIgdList_.end()) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 601 | 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] | 602 | return {}; |
| 603 | } |
| 604 | |
| 605 | return std::dynamic_pointer_cast<UPnPIGD>(*iter); |
| 606 | } |
| 607 | |
| 608 | void |
| 609 | PUPnP::processAddMapAction(const Mapping& map) |
| 610 | { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 611 | if (observer_ == nullptr) |
| 612 | return; |
| 613 | |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 614 | ioContext->post([w = weak(), map] { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 615 | if (auto upnpThis = w.lock()) { |
| 616 | if (upnpThis->observer_) |
| 617 | upnpThis->observer_->onMappingAdded(map.getIgd(), std::move(map)); |
| 618 | } |
| 619 | }); |
| 620 | } |
| 621 | |
| 622 | void |
| 623 | PUPnP::processRequestMappingFailure(const Mapping& map) |
| 624 | { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 625 | if (observer_ == nullptr) |
| 626 | return; |
| 627 | |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 628 | ioContext->post([w = weak(), map] { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 629 | if (auto upnpThis = w.lock()) { |
Adrien Beraud | 64bb00f | 2023-08-23 19:06:46 -0400 | [diff] [blame] | 630 | if (upnpThis->logger_) upnpThis->logger_->debug("PUPnP: Closed mapping {}", map.toString()); |
Morteza Namvar | 5f63952 | 2023-07-04 17:08:58 -0400 | [diff] [blame] | 631 | // 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] | 632 | if (upnpThis->observer_) |
| 633 | upnpThis->observer_->onMappingRequestFailed(map); |
| 634 | } |
| 635 | }); |
| 636 | } |
| 637 | |
| 638 | void |
| 639 | PUPnP::processRemoveMapAction(const Mapping& map) |
| 640 | { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 641 | if (observer_ == nullptr) |
| 642 | return; |
| 643 | |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 644 | if (logger_) logger_->warn("PUPnP: Closed mapping {}", map.toString()); |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 645 | ioContext->post([map, obs = observer_] { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 646 | obs->onMappingRemoved(map.getIgd(), std::move(map)); |
| 647 | }); |
| 648 | } |
| 649 | |
| 650 | const char* |
| 651 | PUPnP::eventTypeToString(Upnp_EventType eventType) |
| 652 | { |
| 653 | switch (eventType) { |
| 654 | case UPNP_CONTROL_ACTION_REQUEST: |
| 655 | return "UPNP_CONTROL_ACTION_REQUEST"; |
| 656 | case UPNP_CONTROL_ACTION_COMPLETE: |
| 657 | return "UPNP_CONTROL_ACTION_COMPLETE"; |
| 658 | case UPNP_CONTROL_GET_VAR_REQUEST: |
| 659 | return "UPNP_CONTROL_GET_VAR_REQUEST"; |
| 660 | case UPNP_CONTROL_GET_VAR_COMPLETE: |
| 661 | return "UPNP_CONTROL_GET_VAR_COMPLETE"; |
| 662 | case UPNP_DISCOVERY_ADVERTISEMENT_ALIVE: |
| 663 | return "UPNP_DISCOVERY_ADVERTISEMENT_ALIVE"; |
| 664 | case UPNP_DISCOVERY_ADVERTISEMENT_BYEBYE: |
| 665 | return "UPNP_DISCOVERY_ADVERTISEMENT_BYEBYE"; |
| 666 | case UPNP_DISCOVERY_SEARCH_RESULT: |
| 667 | return "UPNP_DISCOVERY_SEARCH_RESULT"; |
| 668 | case UPNP_DISCOVERY_SEARCH_TIMEOUT: |
| 669 | return "UPNP_DISCOVERY_SEARCH_TIMEOUT"; |
| 670 | case UPNP_EVENT_SUBSCRIPTION_REQUEST: |
| 671 | return "UPNP_EVENT_SUBSCRIPTION_REQUEST"; |
| 672 | case UPNP_EVENT_RECEIVED: |
| 673 | return "UPNP_EVENT_RECEIVED"; |
| 674 | case UPNP_EVENT_RENEWAL_COMPLETE: |
| 675 | return "UPNP_EVENT_RENEWAL_COMPLETE"; |
| 676 | case UPNP_EVENT_SUBSCRIBE_COMPLETE: |
| 677 | return "UPNP_EVENT_SUBSCRIBE_COMPLETE"; |
| 678 | case UPNP_EVENT_UNSUBSCRIBE_COMPLETE: |
| 679 | return "UPNP_EVENT_UNSUBSCRIBE_COMPLETE"; |
| 680 | case UPNP_EVENT_AUTORENEWAL_FAILED: |
| 681 | return "UPNP_EVENT_AUTORENEWAL_FAILED"; |
| 682 | case UPNP_EVENT_SUBSCRIPTION_EXPIRED: |
| 683 | return "UPNP_EVENT_SUBSCRIPTION_EXPIRED"; |
| 684 | default: |
| 685 | return "Unknown UPNP Event"; |
| 686 | } |
| 687 | } |
| 688 | |
| 689 | int |
| 690 | PUPnP::ctrlPtCallback(Upnp_EventType event_type, const void* event, void* user_data) |
| 691 | { |
| 692 | auto pupnp = static_cast<PUPnP*>(user_data); |
| 693 | |
| 694 | if (pupnp == nullptr) { |
Adrien Béraud | a61adb5 | 2023-08-23 09:31:02 -0400 | [diff] [blame] | 695 | fmt::print(stderr, "PUPnP: Control point callback without PUPnP"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 696 | return UPNP_E_SUCCESS; |
| 697 | } |
| 698 | |
| 699 | auto upnpThis = pupnp->weak().lock(); |
Adrien Béraud | a61adb5 | 2023-08-23 09:31:02 -0400 | [diff] [blame] | 700 | if (not upnpThis) { |
| 701 | fmt::print(stderr, "PUPnP: Control point callback without PUPnP"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 702 | return UPNP_E_SUCCESS; |
Adrien Béraud | a61adb5 | 2023-08-23 09:31:02 -0400 | [diff] [blame] | 703 | } |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 704 | |
| 705 | // Ignore if already unregistered. |
| 706 | if (not upnpThis->clientRegistered_) |
| 707 | return UPNP_E_SUCCESS; |
| 708 | |
| 709 | // Process the callback. |
| 710 | return upnpThis->handleCtrlPtUPnPEvents(event_type, event); |
| 711 | } |
| 712 | |
| 713 | PUPnP::CtrlAction |
| 714 | PUPnP::getAction(const char* xmlNode) |
| 715 | { |
| 716 | if (strstr(xmlNode, ACTION_ADD_PORT_MAPPING)) { |
| 717 | return CtrlAction::ADD_PORT_MAPPING; |
| 718 | } else if (strstr(xmlNode, ACTION_DELETE_PORT_MAPPING)) { |
| 719 | return CtrlAction::DELETE_PORT_MAPPING; |
| 720 | } else if (strstr(xmlNode, ACTION_GET_GENERIC_PORT_MAPPING_ENTRY)) { |
| 721 | return CtrlAction::GET_GENERIC_PORT_MAPPING_ENTRY; |
| 722 | } else if (strstr(xmlNode, ACTION_GET_STATUS_INFO)) { |
| 723 | return CtrlAction::GET_STATUS_INFO; |
| 724 | } else if (strstr(xmlNode, ACTION_GET_EXTERNAL_IP_ADDRESS)) { |
| 725 | return CtrlAction::GET_EXTERNAL_IP_ADDRESS; |
| 726 | } else { |
| 727 | return CtrlAction::UNKNOWN; |
| 728 | } |
| 729 | } |
| 730 | |
| 731 | void |
| 732 | PUPnP::processDiscoverySearchResult(const std::string& cpDeviceId, |
| 733 | const std::string& igdLocationUrl, |
| 734 | const IpAddr& dstAddr) |
| 735 | { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 736 | // Update host address if needed. |
| 737 | if (not hasValidHostAddress()) |
| 738 | updateHostAddress(); |
| 739 | |
| 740 | // The host address must be valid to proceed. |
| 741 | if (not hasValidHostAddress()) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 742 | 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] | 743 | return; |
| 744 | } |
| 745 | |
| 746 | // Use the device ID and the URL as ID. This is necessary as some |
| 747 | // IGDs may have the same device ID but different URLs. |
| 748 | |
| 749 | auto igdId = cpDeviceId + " url: " + igdLocationUrl; |
| 750 | |
| 751 | if (not discoveredIgdList_.emplace(igdId).second) { |
Adrien Beraud | 64bb00f | 2023-08-23 19:06:46 -0400 | [diff] [blame] | 752 | //if (logger_) logger_->debug("PUPnP: IGD [{}] already in the list", igdId); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 753 | return; |
| 754 | } |
| 755 | |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 756 | if (logger_) logger_->debug("PUPnP: Discovered a new IGD [{}]", igdId); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 757 | |
| 758 | // NOTE: here, we check if the location given is related to the source address. |
| 759 | // If it's not the case, it's certainly a router plugged in the network, but not |
| 760 | // related to this network. So the given location will be unreachable and this |
| 761 | // will cause some timeout. |
| 762 | |
| 763 | // Only check the IP address (ignore the port number). |
| 764 | dht::http::Url url(igdLocationUrl); |
| 765 | if (IpAddr(url.host).toString(false) != dstAddr.toString(false)) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 766 | if (logger_) logger_->debug("PUPnP: Returned location {} does not match the source address {}", |
| 767 | IpAddr(url.host).toString(true, true), |
| 768 | dstAddr.toString(true, true)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 769 | return; |
| 770 | } |
| 771 | |
| 772 | // Run a separate thread to prevent blocking this thread |
| 773 | // if the IGD HTTP server is not responsive. |
Adrien Beraud | 3bd61c9 | 2023-08-17 16:57:37 -0400 | [diff] [blame] | 774 | dht::ThreadPool::io().run([w = weak(), url=igdLocationUrl] { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 775 | if (auto upnpThis = w.lock()) { |
Adrien Beraud | 3bd61c9 | 2023-08-17 16:57:37 -0400 | [diff] [blame] | 776 | upnpThis->downLoadIgdDescription(url); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 777 | } |
| 778 | }); |
| 779 | } |
| 780 | |
| 781 | void |
| 782 | PUPnP::downLoadIgdDescription(const std::string& locationUrl) |
| 783 | { |
Adrien Beraud | 3bd61c9 | 2023-08-17 16:57:37 -0400 | [diff] [blame] | 784 | if(logger_) logger_->debug("PUPnP: downLoadIgdDescription {}", locationUrl); |
Sébastien Blin | d14fc35 | 2023-10-06 15:21:53 -0400 | [diff] [blame] | 785 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 786 | std::lock_guard lk(ongoingOpsMtx_); |
Sébastien Blin | d14fc35 | 2023-10-06 15:21:53 -0400 | [diff] [blame] | 787 | if (destroying_) |
| 788 | return; |
| 789 | ongoingOps_++; |
| 790 | } |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 791 | IXML_Document* doc_container_ptr = nullptr; |
| 792 | int upnp_err = UpnpDownloadXmlDoc(locationUrl.c_str(), &doc_container_ptr); |
| 793 | |
| 794 | if (upnp_err != UPNP_E_SUCCESS or not doc_container_ptr) { |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 795 | if(logger_) logger_->warn("PUPnP: Error downloading device XML document from {} -> {}", |
| 796 | locationUrl, |
| 797 | UpnpGetErrorMessage(upnp_err)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 798 | } else { |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 799 | if(logger_) logger_->debug("PUPnP: Succeeded to download device XML document from {}", locationUrl); |
| 800 | ioContext->post([w = weak(), url = locationUrl, doc_container_ptr] { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 801 | if (auto upnpThis = w.lock()) { |
| 802 | upnpThis->validateIgd(url, doc_container_ptr); |
| 803 | } |
| 804 | }); |
| 805 | } |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 806 | std::lock_guard lk(ongoingOpsMtx_); |
Sébastien Blin | d14fc35 | 2023-10-06 15:21:53 -0400 | [diff] [blame] | 807 | ongoingOps_--; |
| 808 | cvOngoing_.notify_one(); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 809 | } |
| 810 | |
| 811 | void |
| 812 | PUPnP::processDiscoveryAdvertisementByebye(const std::string& cpDeviceId) |
| 813 | { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 814 | discoveredIgdList_.erase(cpDeviceId); |
| 815 | |
| 816 | std::shared_ptr<IGD> igd; |
| 817 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 818 | std::lock_guard lk(pupnpMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 819 | for (auto it = validIgdList_.begin(); it != validIgdList_.end();) { |
| 820 | if ((*it)->getUID() == cpDeviceId) { |
| 821 | igd = *it; |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 822 | if (logger_) logger_->debug("PUPnP: Received [{}] for IGD [{}] {}. Will be removed.", |
| 823 | PUPnP::eventTypeToString(UPNP_DISCOVERY_ADVERTISEMENT_BYEBYE), |
| 824 | igd->getUID(), |
| 825 | igd->toString()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 826 | igd->setValid(false); |
| 827 | // Remove the IGD. |
| 828 | it = validIgdList_.erase(it); |
| 829 | break; |
| 830 | } else { |
| 831 | it++; |
| 832 | } |
| 833 | } |
| 834 | } |
| 835 | |
| 836 | // Notify the listener. |
| 837 | if (observer_ and igd) { |
| 838 | observer_->onIgdUpdated(igd, UpnpIgdEvent::REMOVED); |
| 839 | } |
| 840 | } |
| 841 | |
| 842 | void |
| 843 | PUPnP::processDiscoverySubscriptionExpired(Upnp_EventType event_type, const std::string& eventSubUrl) |
| 844 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 845 | std::lock_guard lk(pupnpMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 846 | for (auto& it : validIgdList_) { |
| 847 | if (auto igd = std::dynamic_pointer_cast<UPnPIGD>(it)) { |
| 848 | if (igd->getEventSubURL() == eventSubUrl) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 849 | if (logger_) logger_->debug("PUPnP: Received [{}] event for IGD [{}] {}. Request a new subscribe.", |
| 850 | PUPnP::eventTypeToString(event_type), |
| 851 | igd->getUID(), |
| 852 | igd->toString()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 853 | UpnpSubscribeAsync(ctrlptHandle_, |
| 854 | eventSubUrl.c_str(), |
| 855 | UPNP_INFINITE, |
| 856 | subEventCallback, |
| 857 | this); |
| 858 | break; |
| 859 | } |
| 860 | } |
| 861 | } |
| 862 | } |
| 863 | |
| 864 | int |
| 865 | PUPnP::handleCtrlPtUPnPEvents(Upnp_EventType event_type, const void* event) |
| 866 | { |
| 867 | switch (event_type) { |
| 868 | // "ALIVE" events are processed as "SEARCH RESULT". It might be usefull |
| 869 | // if "SEARCH RESULT" was missed. |
| 870 | case UPNP_DISCOVERY_ADVERTISEMENT_ALIVE: |
| 871 | case UPNP_DISCOVERY_SEARCH_RESULT: { |
| 872 | const UpnpDiscovery* d_event = (const UpnpDiscovery*) event; |
| 873 | |
| 874 | // First check the error code. |
| 875 | auto upnp_status = UpnpDiscovery_get_ErrCode(d_event); |
| 876 | if (upnp_status != UPNP_E_SUCCESS) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 877 | if (logger_) logger_->error("PUPnP: UPNP discovery is in erroneous state: %s", |
| 878 | UpnpGetErrorMessage(upnp_status)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 879 | break; |
| 880 | } |
| 881 | |
| 882 | // Parse the event's data. |
| 883 | std::string deviceId {UpnpDiscovery_get_DeviceID_cstr(d_event)}; |
| 884 | std::string location {UpnpDiscovery_get_Location_cstr(d_event)}; |
| 885 | IpAddr dstAddr(*(const pj_sockaddr*) (UpnpDiscovery_get_DestAddr(d_event))); |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 886 | ioContext->post([w = weak(), |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 887 | deviceId = std::move(deviceId), |
| 888 | location = std::move(location), |
| 889 | dstAddr = std::move(dstAddr)] { |
| 890 | if (auto upnpThis = w.lock()) { |
| 891 | upnpThis->processDiscoverySearchResult(deviceId, location, dstAddr); |
| 892 | } |
| 893 | }); |
| 894 | break; |
| 895 | } |
| 896 | case UPNP_DISCOVERY_ADVERTISEMENT_BYEBYE: { |
| 897 | const UpnpDiscovery* d_event = (const UpnpDiscovery*) event; |
| 898 | |
| 899 | std::string deviceId(UpnpDiscovery_get_DeviceID_cstr(d_event)); |
| 900 | |
| 901 | // Process the response on the main thread. |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 902 | ioContext->post([w = weak(), deviceId = std::move(deviceId)] { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 903 | if (auto upnpThis = w.lock()) { |
| 904 | upnpThis->processDiscoveryAdvertisementByebye(deviceId); |
| 905 | } |
| 906 | }); |
| 907 | break; |
| 908 | } |
| 909 | case UPNP_DISCOVERY_SEARCH_TIMEOUT: { |
| 910 | // Even if the discovery search is successful, it's normal to receive |
| 911 | // time-out events. This because we send search requests using various |
| 912 | // device types, which some of them may not return a response. |
| 913 | break; |
| 914 | } |
| 915 | case UPNP_EVENT_RECEIVED: { |
| 916 | // Nothing to do. |
| 917 | break; |
| 918 | } |
| 919 | // Treat failed autorenewal like an expired subscription. |
| 920 | case UPNP_EVENT_AUTORENEWAL_FAILED: |
| 921 | case UPNP_EVENT_SUBSCRIPTION_EXPIRED: // This event will occur only if autorenewal is disabled. |
| 922 | { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 923 | if (logger_) logger_->warn("PUPnP: Received Subscription Event {}", eventTypeToString(event_type)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 924 | const UpnpEventSubscribe* es_event = (const UpnpEventSubscribe*) event; |
| 925 | if (es_event == nullptr) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 926 | if (logger_) logger_->warn("PUPnP: Received Subscription Event with null pointer"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 927 | break; |
| 928 | } |
| 929 | std::string publisherUrl(UpnpEventSubscribe_get_PublisherUrl_cstr(es_event)); |
| 930 | |
| 931 | // Process the response on the main thread. |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 932 | ioContext->post([w = weak(), event_type, publisherUrl = std::move(publisherUrl)] { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 933 | if (auto upnpThis = w.lock()) { |
| 934 | upnpThis->processDiscoverySubscriptionExpired(event_type, publisherUrl); |
| 935 | } |
| 936 | }); |
| 937 | break; |
| 938 | } |
| 939 | case UPNP_EVENT_SUBSCRIBE_COMPLETE: |
| 940 | case UPNP_EVENT_UNSUBSCRIBE_COMPLETE: { |
| 941 | UpnpEventSubscribe* es_event = (UpnpEventSubscribe*) event; |
| 942 | if (es_event == nullptr) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 943 | if (logger_) logger_->warn("PUPnP: Received Subscription Event with null pointer"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 944 | } else { |
| 945 | UpnpEventSubscribe_delete(es_event); |
| 946 | } |
| 947 | break; |
| 948 | } |
| 949 | case UPNP_CONTROL_ACTION_COMPLETE: { |
| 950 | const UpnpActionComplete* a_event = (const UpnpActionComplete*) event; |
| 951 | if (a_event == nullptr) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 952 | 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] | 953 | break; |
| 954 | } |
| 955 | auto res = UpnpActionComplete_get_ErrCode(a_event); |
| 956 | if (res != UPNP_E_SUCCESS and res != UPNP_E_TIMEDOUT) { |
| 957 | auto err = UpnpActionComplete_get_ErrCode(a_event); |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 958 | 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] | 959 | } else { |
| 960 | auto actionRequest = UpnpActionComplete_get_ActionRequest(a_event); |
| 961 | // Abort if there is no action to process. |
| 962 | if (actionRequest == nullptr) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 963 | 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] | 964 | break; |
| 965 | } |
| 966 | |
| 967 | auto actionResult = UpnpActionComplete_get_ActionResult(a_event); |
| 968 | if (actionResult != nullptr) { |
| 969 | ixmlDocument_free(actionResult); |
| 970 | } else { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 971 | if (logger_) logger_->warn("PUPnP: Action Result document not found"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 972 | } |
| 973 | } |
| 974 | break; |
| 975 | } |
| 976 | default: { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 977 | if (logger_) logger_->warn("PUPnP: Unhandled Control Point event"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 978 | break; |
| 979 | } |
| 980 | } |
| 981 | |
| 982 | return UPNP_E_SUCCESS; |
| 983 | } |
| 984 | |
| 985 | int |
| 986 | PUPnP::subEventCallback(Upnp_EventType event_type, const void* event, void* user_data) |
| 987 | { |
| 988 | if (auto pupnp = static_cast<PUPnP*>(user_data)) |
| 989 | return pupnp->handleSubscriptionUPnPEvent(event_type, event); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 990 | return 0; |
| 991 | } |
| 992 | |
| 993 | int |
| 994 | PUPnP::handleSubscriptionUPnPEvent(Upnp_EventType, const void* event) |
| 995 | { |
| 996 | UpnpEventSubscribe* es_event = static_cast<UpnpEventSubscribe*>(const_cast<void*>(event)); |
| 997 | |
| 998 | if (es_event == nullptr) { |
Morteza Namvar | 5f63952 | 2023-07-04 17:08:58 -0400 | [diff] [blame] | 999 | // JAMI_ERR("PUPnP: Unexpected null pointer!"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1000 | return UPNP_E_INVALID_ARGUMENT; |
| 1001 | } |
| 1002 | std::string publisherUrl(UpnpEventSubscribe_get_PublisherUrl_cstr(es_event)); |
| 1003 | int upnp_err = UpnpEventSubscribe_get_ErrCode(es_event); |
| 1004 | if (upnp_err != UPNP_E_SUCCESS) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1005 | if (logger_) logger_->warn("PUPnP: Subscription error {} from {}", |
| 1006 | UpnpGetErrorMessage(upnp_err), |
| 1007 | publisherUrl); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1008 | return upnp_err; |
| 1009 | } |
| 1010 | |
| 1011 | return UPNP_E_SUCCESS; |
| 1012 | } |
| 1013 | |
| 1014 | std::unique_ptr<UPnPIGD> |
| 1015 | PUPnP::parseIgd(IXML_Document* doc, std::string locationUrl) |
| 1016 | { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1017 | if (not(doc and !locationUrl.empty())) |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1018 | return nullptr; |
| 1019 | |
| 1020 | // Check the UDN to see if its already in our device list. |
| 1021 | std::string UDN(getFirstDocItem(doc, "UDN")); |
| 1022 | if (UDN.empty()) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1023 | 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] | 1024 | return nullptr; |
| 1025 | } else { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 1026 | std::lock_guard lk(pupnpMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1027 | for (auto& it : validIgdList_) { |
| 1028 | if (it->getUID() == UDN) { |
| 1029 | // We already have this device in our list. |
| 1030 | return nullptr; |
| 1031 | } |
| 1032 | } |
| 1033 | } |
| 1034 | |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1035 | if (logger_) logger_->debug("PUPnP: Found new device [{}]", UDN); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1036 | |
| 1037 | std::unique_ptr<UPnPIGD> new_igd; |
| 1038 | int upnp_err; |
| 1039 | |
| 1040 | // Get friendly name. |
| 1041 | std::string friendlyName(getFirstDocItem(doc, "friendlyName")); |
| 1042 | |
| 1043 | // Get base URL. |
| 1044 | std::string baseURL(getFirstDocItem(doc, "URLBase")); |
| 1045 | if (baseURL.empty()) |
| 1046 | baseURL = locationUrl; |
| 1047 | |
| 1048 | // Get list of services defined by serviceType. |
| 1049 | std::unique_ptr<IXML_NodeList, decltype(ixmlNodeList_free)&> serviceList(nullptr, |
| 1050 | ixmlNodeList_free); |
| 1051 | serviceList.reset(ixmlDocument_getElementsByTagName(doc, "serviceType")); |
| 1052 | unsigned long list_length = ixmlNodeList_length(serviceList.get()); |
| 1053 | |
| 1054 | // Go through the "serviceType" nodes until we find the the correct service type. |
| 1055 | for (unsigned long node_idx = 0; node_idx < list_length; node_idx++) { |
| 1056 | IXML_Node* serviceType_node = ixmlNodeList_item(serviceList.get(), node_idx); |
| 1057 | std::string serviceType(getElementText(serviceType_node)); |
| 1058 | |
| 1059 | // Only check serviceType of WANIPConnection or WANPPPConnection. |
| 1060 | if (serviceType != UPNP_WANIP_SERVICE |
| 1061 | && serviceType != UPNP_WANPPP_SERVICE) { |
| 1062 | // IGD is not WANIP or WANPPP service. Going to next node. |
| 1063 | continue; |
| 1064 | } |
| 1065 | |
| 1066 | // Get parent node. |
| 1067 | IXML_Node* service_node = ixmlNode_getParentNode(serviceType_node); |
| 1068 | if (not service_node) { |
| 1069 | // IGD serviceType has no parent node. Going to next node. |
| 1070 | continue; |
| 1071 | } |
| 1072 | |
| 1073 | // Perform sanity check. The parent node should be called "service". |
| 1074 | if (strcmp(ixmlNode_getNodeName(service_node), "service") != 0) { |
| 1075 | // IGD "serviceType" parent node is not called "service". Going to next node. |
| 1076 | continue; |
| 1077 | } |
| 1078 | |
| 1079 | // Get serviceId. |
| 1080 | IXML_Element* service_element = (IXML_Element*) service_node; |
| 1081 | std::string serviceId(getFirstElementItem(service_element, "serviceId")); |
| 1082 | if (serviceId.empty()) { |
| 1083 | // IGD "serviceId" is empty. Going to next node. |
| 1084 | continue; |
| 1085 | } |
| 1086 | |
| 1087 | // Get the relative controlURL and turn it into absolute address using the URLBase. |
| 1088 | std::string controlURL(getFirstElementItem(service_element, "controlURL")); |
| 1089 | if (controlURL.empty()) { |
| 1090 | // IGD control URL is empty. Going to next node. |
| 1091 | continue; |
| 1092 | } |
| 1093 | |
| 1094 | char* absolute_control_url = nullptr; |
| 1095 | upnp_err = UpnpResolveURL2(baseURL.c_str(), controlURL.c_str(), &absolute_control_url); |
| 1096 | if (upnp_err == UPNP_E_SUCCESS) |
| 1097 | controlURL = absolute_control_url; |
| 1098 | else |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1099 | if (logger_) logger_->warn("PUPnP: Error resolving absolute controlURL -> {}", |
| 1100 | UpnpGetErrorMessage(upnp_err)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1101 | |
| 1102 | std::free(absolute_control_url); |
| 1103 | |
| 1104 | // Get the relative eventSubURL and turn it into absolute address using the URLBase. |
| 1105 | std::string eventSubURL(getFirstElementItem(service_element, "eventSubURL")); |
| 1106 | if (eventSubURL.empty()) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1107 | 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] | 1108 | continue; |
| 1109 | } |
| 1110 | |
| 1111 | char* absolute_event_sub_url = nullptr; |
| 1112 | upnp_err = UpnpResolveURL2(baseURL.c_str(), eventSubURL.c_str(), &absolute_event_sub_url); |
| 1113 | if (upnp_err == UPNP_E_SUCCESS) |
| 1114 | eventSubURL = absolute_event_sub_url; |
| 1115 | else |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1116 | if (logger_) logger_->warn("PUPnP: Error resolving absolute eventSubURL -> {}", |
| 1117 | UpnpGetErrorMessage(upnp_err)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1118 | |
| 1119 | std::free(absolute_event_sub_url); |
| 1120 | |
| 1121 | new_igd.reset(new UPnPIGD(std::move(UDN), |
| 1122 | std::move(baseURL), |
| 1123 | std::move(friendlyName), |
| 1124 | std::move(serviceType), |
| 1125 | std::move(serviceId), |
| 1126 | std::move(locationUrl), |
| 1127 | std::move(controlURL), |
| 1128 | std::move(eventSubURL))); |
| 1129 | |
| 1130 | return new_igd; |
| 1131 | } |
| 1132 | |
| 1133 | return nullptr; |
| 1134 | } |
| 1135 | |
| 1136 | bool |
| 1137 | PUPnP::actionIsIgdConnected(const UPnPIGD& igd) |
| 1138 | { |
| 1139 | if (not clientRegistered_) |
| 1140 | return false; |
| 1141 | |
| 1142 | // Set action name. |
| 1143 | IXML_Document* action_container_ptr = UpnpMakeAction("GetStatusInfo", |
| 1144 | igd.getServiceType().c_str(), |
| 1145 | 0, |
| 1146 | nullptr); |
| 1147 | if (not action_container_ptr) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1148 | if (logger_) logger_->warn("PUPnP: Failed to make GetStatusInfo action"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1149 | return false; |
| 1150 | } |
| 1151 | XMLDocument action(action_container_ptr, ixmlDocument_free); // Action pointer. |
| 1152 | |
| 1153 | IXML_Document* response_container_ptr = nullptr; |
| 1154 | int upnp_err = UpnpSendAction(ctrlptHandle_, |
| 1155 | igd.getControlURL().c_str(), |
| 1156 | igd.getServiceType().c_str(), |
| 1157 | nullptr, |
| 1158 | action.get(), |
| 1159 | &response_container_ptr); |
Sébastien Blin | 45b5069 | 2024-03-06 11:18:50 -0500 | [diff] [blame] | 1160 | if (upnp_err == 401) { |
| 1161 | // YET ANOTHER UPNP HACK: MiniUpnp on some routers seems to not recognize this action, sending a 401: Invalid Action. |
| 1162 | // So even if mapping succeeds, the router was considered as not connected. |
| 1163 | // Returning true here works around this issue. |
| 1164 | // E.g. https://community.tp-link.com/us/home/forum/topic/577840 |
| 1165 | return true; |
| 1166 | } |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1167 | if (not response_container_ptr or upnp_err != UPNP_E_SUCCESS) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1168 | 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] | 1169 | return false; |
| 1170 | } |
| 1171 | XMLDocument response(response_container_ptr, ixmlDocument_free); |
| 1172 | |
Adrien Béraud | d78d1ac | 2023-08-25 10:43:33 -0400 | [diff] [blame] | 1173 | if (errorOnResponse(response.get(), logger_)) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1174 | if (logger_) logger_->warn("PUPnP: Failed to get GetStatusInfo from {} -> {:d}: {}", |
| 1175 | igd.getServiceType().c_str(), |
| 1176 | upnp_err, |
| 1177 | UpnpGetErrorMessage(upnp_err)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1178 | return false; |
| 1179 | } |
| 1180 | |
| 1181 | // Parse response. |
| 1182 | auto status = getFirstDocItem(response.get(), "NewConnectionStatus"); |
| 1183 | return status == "Connected"; |
| 1184 | } |
| 1185 | |
| 1186 | IpAddr |
| 1187 | PUPnP::actionGetExternalIP(const UPnPIGD& igd) |
| 1188 | { |
| 1189 | if (not clientRegistered_) |
| 1190 | return {}; |
| 1191 | |
| 1192 | // Action and response pointers. |
| 1193 | std::unique_ptr<IXML_Document, decltype(ixmlDocument_free)&> |
| 1194 | action(nullptr, ixmlDocument_free); // Action pointer. |
| 1195 | std::unique_ptr<IXML_Document, decltype(ixmlDocument_free)&> |
| 1196 | response(nullptr, ixmlDocument_free); // Response pointer. |
| 1197 | |
| 1198 | // Set action name. |
| 1199 | static constexpr const char* action_name {"GetExternalIPAddress"}; |
| 1200 | |
| 1201 | IXML_Document* action_container_ptr = nullptr; |
| 1202 | action_container_ptr = UpnpMakeAction(action_name, igd.getServiceType().c_str(), 0, nullptr); |
| 1203 | action.reset(action_container_ptr); |
| 1204 | |
| 1205 | if (not action) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1206 | if (logger_) logger_->warn("PUPnP: Failed to make GetExternalIPAddress action"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1207 | return {}; |
| 1208 | } |
| 1209 | |
| 1210 | IXML_Document* response_container_ptr = nullptr; |
| 1211 | int upnp_err = UpnpSendAction(ctrlptHandle_, |
| 1212 | igd.getControlURL().c_str(), |
| 1213 | igd.getServiceType().c_str(), |
| 1214 | nullptr, |
| 1215 | action.get(), |
| 1216 | &response_container_ptr); |
| 1217 | response.reset(response_container_ptr); |
| 1218 | |
| 1219 | if (not response or upnp_err != UPNP_E_SUCCESS) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1220 | if (logger_) logger_->warn("PUPnP: Failed to send GetExternalIPAddress action -> {}", |
| 1221 | UpnpGetErrorMessage(upnp_err)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1222 | return {}; |
| 1223 | } |
| 1224 | |
Adrien Béraud | d78d1ac | 2023-08-25 10:43:33 -0400 | [diff] [blame] | 1225 | if (errorOnResponse(response.get(), logger_)) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1226 | if (logger_) logger_->warn("PUPnP: Failed to get GetExternalIPAddress from {} -> {:d}: {}", |
| 1227 | igd.getServiceType(), |
| 1228 | upnp_err, |
| 1229 | UpnpGetErrorMessage(upnp_err)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1230 | return {}; |
| 1231 | } |
| 1232 | |
| 1233 | return {getFirstDocItem(response.get(), "NewExternalIPAddress")}; |
| 1234 | } |
| 1235 | |
| 1236 | std::map<Mapping::key_t, Mapping> |
| 1237 | PUPnP::getMappingsListByDescr(const std::shared_ptr<IGD>& igd, const std::string& description) const |
| 1238 | { |
| 1239 | auto upnpIgd = std::dynamic_pointer_cast<UPnPIGD>(igd); |
| 1240 | assert(upnpIgd); |
| 1241 | |
| 1242 | std::map<Mapping::key_t, Mapping> mapList; |
| 1243 | |
| 1244 | if (not clientRegistered_ or not upnpIgd->isValid() or not upnpIgd->getLocalIp()) |
| 1245 | return mapList; |
| 1246 | |
| 1247 | // Set action name. |
| 1248 | static constexpr const char* action_name {"GetGenericPortMappingEntry"}; |
| 1249 | |
| 1250 | for (int entry_idx = 0;; entry_idx++) { |
| 1251 | std::unique_ptr<IXML_Document, decltype(ixmlDocument_free)&> |
| 1252 | action(nullptr, ixmlDocument_free); // Action pointer. |
| 1253 | IXML_Document* action_container_ptr = nullptr; |
| 1254 | |
| 1255 | std::unique_ptr<IXML_Document, decltype(ixmlDocument_free)&> |
| 1256 | response(nullptr, ixmlDocument_free); // Response pointer. |
| 1257 | IXML_Document* response_container_ptr = nullptr; |
| 1258 | |
| 1259 | UpnpAddToAction(&action_container_ptr, |
| 1260 | action_name, |
| 1261 | upnpIgd->getServiceType().c_str(), |
| 1262 | "NewPortMappingIndex", |
| 1263 | std::to_string(entry_idx).c_str()); |
| 1264 | action.reset(action_container_ptr); |
| 1265 | |
| 1266 | if (not action) { |
Morteza Namvar | 5f63952 | 2023-07-04 17:08:58 -0400 | [diff] [blame] | 1267 | // JAMI_WARN("PUPnP: Failed to add NewPortMappingIndex action"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1268 | break; |
| 1269 | } |
| 1270 | |
| 1271 | int upnp_err = UpnpSendAction(ctrlptHandle_, |
| 1272 | upnpIgd->getControlURL().c_str(), |
| 1273 | upnpIgd->getServiceType().c_str(), |
| 1274 | nullptr, |
| 1275 | action.get(), |
| 1276 | &response_container_ptr); |
| 1277 | response.reset(response_container_ptr); |
| 1278 | |
| 1279 | if (not response) { |
| 1280 | // No existing mapping. Abort silently. |
| 1281 | break; |
| 1282 | } |
| 1283 | |
| 1284 | if (upnp_err != UPNP_E_SUCCESS) { |
Morteza Namvar | 5f63952 | 2023-07-04 17:08:58 -0400 | [diff] [blame] | 1285 | // JAMI_ERR("PUPnP: GetGenericPortMappingEntry returned with error: %i", upnp_err); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1286 | break; |
| 1287 | } |
| 1288 | |
| 1289 | // Check error code. |
| 1290 | auto errorCode = getFirstDocItem(response.get(), "errorCode"); |
| 1291 | if (not errorCode.empty()) { |
| 1292 | auto error = to_int<int>(errorCode); |
| 1293 | if (error == ARRAY_IDX_INVALID or error == CONFLICT_IN_MAPPING) { |
| 1294 | // No more port mapping entries in the response. |
Morteza Namvar | 5f63952 | 2023-07-04 17:08:58 -0400 | [diff] [blame] | 1295 | // 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] | 1296 | break; |
| 1297 | } else { |
| 1298 | auto errorDescription = getFirstDocItem(response.get(), "errorDescription"); |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 1299 | if (logger_) logger_->error("PUPnP: GetGenericPortMappingEntry returned with error: {:s}: {:s}", |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1300 | errorCode, |
| 1301 | errorDescription); |
| 1302 | break; |
| 1303 | } |
| 1304 | } |
| 1305 | |
| 1306 | // Parse the response. |
| 1307 | auto desc_actual = getFirstDocItem(response.get(), "NewPortMappingDescription"); |
| 1308 | auto client_ip = getFirstDocItem(response.get(), "NewInternalClient"); |
| 1309 | |
| 1310 | if (client_ip != getHostAddress().toString()) { |
| 1311 | // Silently ignore un-matching addresses. |
| 1312 | continue; |
| 1313 | } |
| 1314 | |
| 1315 | if (desc_actual.find(description) == std::string::npos) |
| 1316 | continue; |
| 1317 | |
| 1318 | auto port_internal = getFirstDocItem(response.get(), "NewInternalPort"); |
| 1319 | auto port_external = getFirstDocItem(response.get(), "NewExternalPort"); |
| 1320 | std::string transport(getFirstDocItem(response.get(), "NewProtocol")); |
| 1321 | |
| 1322 | if (port_internal.empty() || port_external.empty() || transport.empty()) { |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 1323 | // 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] | 1324 | // entry_idx); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1325 | continue; |
| 1326 | } |
| 1327 | |
| 1328 | std::transform(transport.begin(), transport.end(), transport.begin(), ::toupper); |
| 1329 | PortType type = transport.find("TCP") != std::string::npos ? PortType::TCP : PortType::UDP; |
| 1330 | auto ePort = to_int<uint16_t>(port_external); |
| 1331 | auto iPort = to_int<uint16_t>(port_internal); |
| 1332 | |
| 1333 | Mapping map(type, ePort, iPort); |
| 1334 | map.setIgd(igd); |
| 1335 | |
| 1336 | mapList.emplace(map.getMapKey(), std::move(map)); |
| 1337 | } |
| 1338 | |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1339 | if (logger_) logger_->debug("PUPnP: Found {:d} allocated mappings on IGD {:s}", |
| 1340 | mapList.size(), |
| 1341 | upnpIgd->toString()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1342 | |
| 1343 | return mapList; |
| 1344 | } |
| 1345 | |
| 1346 | void |
| 1347 | PUPnP::deleteMappingsByDescription(const std::shared_ptr<IGD>& igd, const std::string& description) |
| 1348 | { |
| 1349 | if (not(clientRegistered_ and igd->getLocalIp())) |
| 1350 | return; |
| 1351 | |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1352 | if (logger_) logger_->debug("PUPnP: Remove all mappings (if any) on IGD {} matching descr prefix {}", |
| 1353 | igd->toString(), |
| 1354 | Mapping::UPNP_MAPPING_DESCRIPTION_PREFIX); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1355 | |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 1356 | ioContext->post([w=weak(), igd, description]{ |
| 1357 | if (auto sthis = w.lock()) { |
| 1358 | auto mapList = sthis->getMappingsListByDescr(igd, description); |
| 1359 | for (auto const& [_, map] : mapList) { |
| 1360 | sthis->requestMappingRemove(map); |
| 1361 | } |
| 1362 | } |
| 1363 | }); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1364 | } |
| 1365 | |
| 1366 | bool |
| 1367 | PUPnP::actionAddPortMapping(const Mapping& mapping) |
| 1368 | { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1369 | if (not clientRegistered_) |
| 1370 | return false; |
| 1371 | |
| 1372 | auto igdIn = std::dynamic_pointer_cast<UPnPIGD>(mapping.getIgd()); |
| 1373 | if (not igdIn) |
| 1374 | return false; |
| 1375 | |
| 1376 | // The requested IGD must be present in the list of local valid IGDs. |
| 1377 | auto igd = findMatchingIgd(igdIn->getControlURL()); |
| 1378 | |
| 1379 | if (not igd or not igd->isValid()) |
| 1380 | return false; |
| 1381 | |
| 1382 | // Action and response pointers. |
| 1383 | XMLDocument action(nullptr, ixmlDocument_free); |
| 1384 | IXML_Document* action_container_ptr = nullptr; |
| 1385 | XMLDocument response(nullptr, ixmlDocument_free); |
| 1386 | IXML_Document* response_container_ptr = nullptr; |
| 1387 | |
| 1388 | // Set action sequence. |
| 1389 | UpnpAddToAction(&action_container_ptr, |
| 1390 | ACTION_ADD_PORT_MAPPING, |
| 1391 | igd->getServiceType().c_str(), |
| 1392 | "NewRemoteHost", |
| 1393 | ""); |
| 1394 | UpnpAddToAction(&action_container_ptr, |
| 1395 | ACTION_ADD_PORT_MAPPING, |
| 1396 | igd->getServiceType().c_str(), |
| 1397 | "NewExternalPort", |
| 1398 | mapping.getExternalPortStr().c_str()); |
| 1399 | UpnpAddToAction(&action_container_ptr, |
| 1400 | ACTION_ADD_PORT_MAPPING, |
| 1401 | igd->getServiceType().c_str(), |
| 1402 | "NewProtocol", |
| 1403 | mapping.getTypeStr()); |
| 1404 | UpnpAddToAction(&action_container_ptr, |
| 1405 | ACTION_ADD_PORT_MAPPING, |
| 1406 | igd->getServiceType().c_str(), |
| 1407 | "NewInternalPort", |
| 1408 | mapping.getInternalPortStr().c_str()); |
| 1409 | UpnpAddToAction(&action_container_ptr, |
| 1410 | ACTION_ADD_PORT_MAPPING, |
| 1411 | igd->getServiceType().c_str(), |
| 1412 | "NewInternalClient", |
| 1413 | getHostAddress().toString().c_str()); |
| 1414 | UpnpAddToAction(&action_container_ptr, |
| 1415 | ACTION_ADD_PORT_MAPPING, |
| 1416 | igd->getServiceType().c_str(), |
| 1417 | "NewEnabled", |
| 1418 | "1"); |
| 1419 | UpnpAddToAction(&action_container_ptr, |
| 1420 | ACTION_ADD_PORT_MAPPING, |
| 1421 | igd->getServiceType().c_str(), |
| 1422 | "NewPortMappingDescription", |
| 1423 | mapping.toString().c_str()); |
| 1424 | UpnpAddToAction(&action_container_ptr, |
| 1425 | ACTION_ADD_PORT_MAPPING, |
| 1426 | igd->getServiceType().c_str(), |
| 1427 | "NewLeaseDuration", |
| 1428 | "0"); |
| 1429 | |
| 1430 | action.reset(action_container_ptr); |
| 1431 | |
| 1432 | int upnp_err = UpnpSendAction(ctrlptHandle_, |
| 1433 | igd->getControlURL().c_str(), |
| 1434 | igd->getServiceType().c_str(), |
| 1435 | nullptr, |
| 1436 | action.get(), |
| 1437 | &response_container_ptr); |
| 1438 | response.reset(response_container_ptr); |
| 1439 | |
| 1440 | bool success = true; |
| 1441 | |
| 1442 | if (upnp_err != UPNP_E_SUCCESS) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1443 | if (logger_) { |
| 1444 | logger_->warn("PUPnP: Failed to send action {} for mapping {}. {:d}: {}", |
| 1445 | ACTION_ADD_PORT_MAPPING, |
| 1446 | mapping.toString(), |
| 1447 | upnp_err, |
| 1448 | UpnpGetErrorMessage(upnp_err)); |
| 1449 | logger_->warn("PUPnP: IGD ctrlUrl {}", igd->getControlURL()); |
| 1450 | logger_->warn("PUPnP: IGD service type {}", igd->getServiceType()); |
| 1451 | } |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1452 | |
| 1453 | success = false; |
| 1454 | } |
| 1455 | |
| 1456 | // Check if an error has occurred. |
| 1457 | auto errorCode = getFirstDocItem(response.get(), "errorCode"); |
| 1458 | if (not errorCode.empty()) { |
| 1459 | success = false; |
| 1460 | // Try to get the error description. |
| 1461 | std::string errorDescription; |
| 1462 | if (response) { |
| 1463 | errorDescription = getFirstDocItem(response.get(), "errorDescription"); |
| 1464 | } |
| 1465 | |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1466 | if (logger_) logger_->warn("PUPnP: {:s} returned with error: {:s} {:s}", |
| 1467 | ACTION_ADD_PORT_MAPPING, |
| 1468 | errorCode, |
| 1469 | errorDescription); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1470 | } |
| 1471 | return success; |
| 1472 | } |
| 1473 | |
| 1474 | bool |
| 1475 | PUPnP::actionDeletePortMapping(const Mapping& mapping) |
| 1476 | { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1477 | if (not clientRegistered_) |
| 1478 | return false; |
| 1479 | |
| 1480 | auto igdIn = std::dynamic_pointer_cast<UPnPIGD>(mapping.getIgd()); |
| 1481 | if (not igdIn) |
| 1482 | return false; |
| 1483 | |
| 1484 | // The requested IGD must be present in the list of local valid IGDs. |
| 1485 | auto igd = findMatchingIgd(igdIn->getControlURL()); |
| 1486 | |
| 1487 | if (not igd or not igd->isValid()) |
| 1488 | return false; |
| 1489 | |
| 1490 | // Action and response pointers. |
| 1491 | XMLDocument action(nullptr, ixmlDocument_free); |
| 1492 | IXML_Document* action_container_ptr = nullptr; |
| 1493 | XMLDocument response(nullptr, ixmlDocument_free); |
| 1494 | IXML_Document* response_container_ptr = nullptr; |
| 1495 | |
| 1496 | // Set action sequence. |
| 1497 | UpnpAddToAction(&action_container_ptr, |
| 1498 | ACTION_DELETE_PORT_MAPPING, |
| 1499 | igd->getServiceType().c_str(), |
| 1500 | "NewRemoteHost", |
| 1501 | ""); |
| 1502 | UpnpAddToAction(&action_container_ptr, |
| 1503 | ACTION_DELETE_PORT_MAPPING, |
| 1504 | igd->getServiceType().c_str(), |
| 1505 | "NewExternalPort", |
| 1506 | mapping.getExternalPortStr().c_str()); |
| 1507 | UpnpAddToAction(&action_container_ptr, |
| 1508 | ACTION_DELETE_PORT_MAPPING, |
| 1509 | igd->getServiceType().c_str(), |
| 1510 | "NewProtocol", |
| 1511 | mapping.getTypeStr()); |
| 1512 | |
| 1513 | action.reset(action_container_ptr); |
| 1514 | |
| 1515 | int upnp_err = UpnpSendAction(ctrlptHandle_, |
| 1516 | igd->getControlURL().c_str(), |
| 1517 | igd->getServiceType().c_str(), |
| 1518 | nullptr, |
| 1519 | action.get(), |
| 1520 | &response_container_ptr); |
| 1521 | response.reset(response_container_ptr); |
| 1522 | |
| 1523 | bool success = true; |
| 1524 | |
| 1525 | if (upnp_err != UPNP_E_SUCCESS) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1526 | if (logger_) { |
| 1527 | logger_->warn("PUPnP: Failed to send action {} for mapping from {}. {:d}: {}", |
| 1528 | ACTION_DELETE_PORT_MAPPING, |
| 1529 | mapping.toString(), |
| 1530 | upnp_err, |
| 1531 | UpnpGetErrorMessage(upnp_err)); |
| 1532 | logger_->warn("PUPnP: IGD ctrlUrl {}", igd->getControlURL()); |
| 1533 | logger_->warn("PUPnP: IGD service type {}", igd->getServiceType()); |
| 1534 | } |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1535 | success = false; |
| 1536 | } |
| 1537 | |
| 1538 | if (not response) { |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1539 | 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] | 1540 | success = false; |
| 1541 | } |
| 1542 | |
| 1543 | // Check if there is an error code. |
| 1544 | auto errorCode = getFirstDocItem(response.get(), "errorCode"); |
| 1545 | if (not errorCode.empty()) { |
| 1546 | auto errorDescription = getFirstDocItem(response.get(), "errorDescription"); |
Adrien Béraud | 4f7e801 | 2023-08-16 15:28:18 -0400 | [diff] [blame] | 1547 | if (logger_) logger_->warn("PUPnP: {:s} returned with error: {:s}: {:s}", |
| 1548 | ACTION_DELETE_PORT_MAPPING, |
| 1549 | errorCode, |
| 1550 | errorDescription); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 1551 | success = false; |
| 1552 | } |
| 1553 | |
| 1554 | return success; |
| 1555 | } |
| 1556 | |
| 1557 | } // namespace upnp |
Sébastien Blin | 464bdff | 2023-07-19 08:02:53 -0400 | [diff] [blame] | 1558 | } // namespace dhtnet |