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 "nat_pmp.h" |
| 18 | |
| 19 | #if HAVE_LIBNATPMP |
Andreas Traczyk | 8f7e1bd | 2024-04-04 16:26:58 -0400 | [diff] [blame] | 20 | #ifdef _WIN32 |
| 21 | // On Windows we assume WSAStartup is called during DHT initialization |
| 22 | #include <winsock2.h> |
| 23 | #include <ws2tcpip.h> |
| 24 | #else |
Sébastien Blin | baa52d9 | 2024-03-25 13:28:30 -0400 | [diff] [blame] | 25 | #include <poll.h> |
Andreas Traczyk | 8f7e1bd | 2024-04-04 16:26:58 -0400 | [diff] [blame] | 26 | #endif |
| 27 | |
| 28 | #ifdef _WIN32 |
| 29 | #define _poll(fds, nfds, timeout) WSAPoll(fds, nfds, timeout) |
| 30 | #else |
| 31 | #define _poll(fds, nfds, timeout) poll(fds, nfds, timeout) |
| 32 | #endif |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 33 | |
Adrien Béraud | 1ae60aa | 2023-07-07 09:55:09 -0400 | [diff] [blame] | 34 | namespace dhtnet { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 35 | namespace upnp { |
| 36 | |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 37 | NatPmp::NatPmp(const std::shared_ptr<asio::io_context>& ctx, const std::shared_ptr<dht::log::Logger>& logger) |
| 38 | : UPnPProtocol(logger), ioContext(ctx), searchForIgdTimer_(*ctx) |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 39 | { |
Morteza Namvar | 5f63952 | 2023-07-04 17:08:58 -0400 | [diff] [blame] | 40 | // JAMI_DBG("NAT-PMP: Instance [%p] created", this); |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 41 | ioContext->dispatch([this] { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 42 | igd_ = std::make_shared<PMPIGD>(); |
| 43 | }); |
| 44 | } |
| 45 | |
| 46 | NatPmp::~NatPmp() |
| 47 | { |
Morteza Namvar | 5f63952 | 2023-07-04 17:08:58 -0400 | [diff] [blame] | 48 | // JAMI_DBG("NAT-PMP: Instance [%p] destroyed", this); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 49 | } |
| 50 | |
| 51 | void |
| 52 | NatPmp::initNatPmp() |
| 53 | { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 54 | initialized_ = false; |
| 55 | |
| 56 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 57 | std::lock_guard lock(natpmpMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 58 | hostAddress_ = ip_utils::getLocalAddr(AF_INET); |
| 59 | } |
| 60 | |
| 61 | // Local address must be valid. |
| 62 | if (not getHostAddress() or getHostAddress().isLoopback()) { |
Adrien Béraud | 17765bd | 2023-08-22 21:02:38 -0400 | [diff] [blame] | 63 | if (logger_) logger_->warn("NAT-PMP: Does not have a valid local address!"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 64 | return; |
| 65 | } |
| 66 | |
| 67 | assert(igd_); |
| 68 | if (igd_->isValid()) { |
| 69 | igd_->setValid(false); |
| 70 | processIgdUpdate(UpnpIgdEvent::REMOVED); |
| 71 | } |
| 72 | |
| 73 | igd_->setLocalIp(IpAddr()); |
| 74 | igd_->setPublicIp(IpAddr()); |
| 75 | igd_->setUID(""); |
| 76 | |
Adrien Béraud | 17765bd | 2023-08-22 21:02:38 -0400 | [diff] [blame] | 77 | if (logger_) logger_->debug("NAT-PMP: Trying to initialize IGD"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 78 | |
| 79 | int err = initnatpmp(&natpmpHdl_, 0, 0); |
| 80 | |
| 81 | if (err < 0) { |
Adrien Béraud | 17765bd | 2023-08-22 21:02:38 -0400 | [diff] [blame] | 82 | if (logger_) logger_->warn("NAT-PMP: Initializing IGD using default gateway failed!"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 83 | const auto& localGw = ip_utils::getLocalGateway(); |
| 84 | if (not localGw) { |
Adrien Béraud | 17765bd | 2023-08-22 21:02:38 -0400 | [diff] [blame] | 85 | if (logger_) logger_->warn("NAT-PMP: Couldn't find valid gateway on local host"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 86 | err = NATPMP_ERR_CANNOTGETGATEWAY; |
| 87 | } else { |
Adrien Béraud | 17765bd | 2023-08-22 21:02:38 -0400 | [diff] [blame] | 88 | if (logger_) logger_->warn("NAT-PMP: Trying to initialize using detected gateway {}", |
| 89 | localGw.toString()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 90 | struct in_addr inaddr; |
| 91 | inet_pton(AF_INET, localGw.toString().c_str(), &inaddr); |
| 92 | err = initnatpmp(&natpmpHdl_, 1, inaddr.s_addr); |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | if (err < 0) { |
Adrien Béraud | 17765bd | 2023-08-22 21:02:38 -0400 | [diff] [blame] | 97 | if (logger_) logger_->error("NAT-PMP: Can't initialize libnatpmp -> {}", getNatPmpErrorStr(err)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 98 | return; |
| 99 | } |
| 100 | |
| 101 | char addrbuf[INET_ADDRSTRLEN]; |
| 102 | inet_ntop(AF_INET, &natpmpHdl_.gateway, addrbuf, sizeof(addrbuf)); |
| 103 | IpAddr igdAddr(addrbuf); |
Adrien Béraud | 17765bd | 2023-08-22 21:02:38 -0400 | [diff] [blame] | 104 | if (logger_) logger_->debug("NAT-PMP: Initialized on gateway {}", igdAddr.toString()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 105 | |
| 106 | // Set the local (gateway) address. |
| 107 | igd_->setLocalIp(igdAddr); |
| 108 | // NAT-PMP protocol does not have UID, but we will set generic |
| 109 | // one debugging purposes. |
| 110 | igd_->setUID("NAT-PMP Gateway"); |
| 111 | |
| 112 | // Search and set the public address. |
| 113 | getIgdPublicAddress(); |
| 114 | |
| 115 | // Update and notify. |
| 116 | if (igd_->isValid()) { |
| 117 | initialized_ = true; |
| 118 | processIgdUpdate(UpnpIgdEvent::ADDED); |
| 119 | }; |
| 120 | } |
| 121 | |
| 122 | void |
| 123 | NatPmp::setObserver(UpnpMappingObserver* obs) |
| 124 | { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 125 | observer_ = obs; |
| 126 | } |
| 127 | |
| 128 | void |
| 129 | NatPmp::terminate(std::condition_variable& cv) |
| 130 | { |
Adrien Béraud | 7a82bee | 2023-08-30 10:26:45 -0400 | [diff] [blame] | 131 | if (logger_) logger_->debug("NAT-PMP: Terminate instance {}", fmt::ptr(this)); |
| 132 | |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 133 | initialized_ = false; |
| 134 | observer_ = nullptr; |
| 135 | |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 136 | std::lock_guard lock(natpmpMutex_); |
Adrien Béraud | 7a82bee | 2023-08-30 10:26:45 -0400 | [diff] [blame] | 137 | shutdownComplete_ = true; |
| 138 | cv.notify_one(); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 139 | } |
| 140 | |
| 141 | void |
| 142 | NatPmp::terminate() |
| 143 | { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 144 | std::condition_variable cv {}; |
| 145 | |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 146 | ioContext->dispatch([&] { |
| 147 | terminate(cv); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 148 | }); |
| 149 | |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 150 | std::unique_lock lk(natpmpMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 151 | if (cv.wait_for(lk, std::chrono::seconds(10), [this] { return shutdownComplete_; })) { |
Adrien Béraud | 17765bd | 2023-08-22 21:02:38 -0400 | [diff] [blame] | 152 | if (logger_) logger_->debug("NAT-PMP: Shutdown completed"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 153 | } else { |
Adrien Béraud | 17765bd | 2023-08-22 21:02:38 -0400 | [diff] [blame] | 154 | if (logger_) logger_->error("NAT-PMP: Shutdown timed-out"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 155 | } |
| 156 | } |
| 157 | |
| 158 | const IpAddr |
| 159 | NatPmp::getHostAddress() const |
| 160 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 161 | std::lock_guard lock(natpmpMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 162 | return hostAddress_; |
| 163 | } |
| 164 | |
| 165 | void |
| 166 | NatPmp::clearIgds() |
| 167 | { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 168 | bool do_close = false; |
| 169 | |
| 170 | if (igd_) { |
| 171 | if (igd_->isValid()) { |
| 172 | do_close = true; |
| 173 | } |
| 174 | igd_->setValid(false); |
| 175 | } |
| 176 | |
| 177 | initialized_ = false; |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 178 | searchForIgdTimer_.cancel(); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 179 | |
| 180 | igdSearchCounter_ = 0; |
| 181 | |
| 182 | if (do_close) { |
| 183 | closenatpmp(&natpmpHdl_); |
| 184 | memset(&natpmpHdl_, 0, sizeof(natpmpHdl_)); |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | void |
| 189 | NatPmp::searchForIgd() |
| 190 | { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 191 | if (not initialized_) { |
| 192 | initNatPmp(); |
| 193 | } |
| 194 | |
| 195 | // Schedule a retry in case init failed. |
| 196 | if (not initialized_) { |
| 197 | if (igdSearchCounter_++ < MAX_RESTART_SEARCH_RETRIES) { |
Adrien Béraud | 17765bd | 2023-08-22 21:02:38 -0400 | [diff] [blame] | 198 | if (logger_) logger_->debug("NAT-PMP: Start search for IGDs. Attempt {}", igdSearchCounter_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 199 | |
| 200 | // Cancel the current timer (if any) and re-schedule. |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 201 | searchForIgdTimer_.expires_after(NATPMP_SEARCH_RETRY_UNIT * igdSearchCounter_); |
Sébastien Blin | d1e018c | 2023-09-01 09:15:12 -0400 | [diff] [blame] | 202 | searchForIgdTimer_.async_wait([w=weak()](const asio::error_code& ec) { |
| 203 | if (!ec) { |
| 204 | if (auto shared = w.lock()) |
| 205 | shared->searchForIgd(); |
| 206 | } |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 207 | }); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 208 | } else { |
Adrien Béraud | 17765bd | 2023-08-22 21:02:38 -0400 | [diff] [blame] | 209 | if (logger_) logger_->warn("NAT-PMP: Setup failed after {} trials. NAT-PMP will be disabled!", |
| 210 | MAX_RESTART_SEARCH_RETRIES); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 211 | } |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | std::list<std::shared_ptr<IGD>> |
| 216 | NatPmp::getIgdList() const |
| 217 | { |
Adrien Béraud | 024c46f | 2024-03-02 23:53:18 -0500 | [diff] [blame] | 218 | std::lock_guard lock(natpmpMutex_); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 219 | std::list<std::shared_ptr<IGD>> igdList; |
| 220 | if (igd_->isValid()) |
| 221 | igdList.emplace_back(igd_); |
| 222 | return igdList; |
| 223 | } |
| 224 | |
| 225 | bool |
| 226 | NatPmp::isReady() const |
| 227 | { |
| 228 | if (observer_ == nullptr) { |
Adrien Béraud | 17765bd | 2023-08-22 21:02:38 -0400 | [diff] [blame] | 229 | if (logger_) logger_->error("NAT-PMP: the observer is not set!"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 230 | return false; |
| 231 | } |
| 232 | |
| 233 | // Must at least have a valid local address. |
| 234 | if (not getHostAddress() or getHostAddress().isLoopback()) |
| 235 | return false; |
| 236 | |
| 237 | return igd_ and igd_->isValid(); |
| 238 | } |
| 239 | |
| 240 | void |
| 241 | NatPmp::incrementErrorsCounter(const std::shared_ptr<IGD>& igdIn) |
| 242 | { |
| 243 | if (not validIgdInstance(igdIn)) { |
| 244 | return; |
| 245 | } |
| 246 | |
| 247 | if (not igd_->isValid()) { |
| 248 | // Already invalid. Nothing to do. |
| 249 | return; |
| 250 | } |
| 251 | |
| 252 | if (not igd_->incrementErrorsCounter()) { |
| 253 | // Disable this IGD. |
| 254 | igd_->setValid(false); |
| 255 | // Notify the listener. |
Adrien Béraud | 17765bd | 2023-08-22 21:02:38 -0400 | [diff] [blame] | 256 | if (logger_) logger_->warn("NAT-PMP: No more valid IGD!"); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 257 | |
| 258 | processIgdUpdate(UpnpIgdEvent::INVALID_STATE); |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | void |
| 263 | NatPmp::requestMappingAdd(const Mapping& mapping) |
| 264 | { |
| 265 | // Process on nat-pmp thread. |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 266 | /*if (not isValidThread()) { |
| 267 | ioContext->post([w = weak(), mapping] { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 268 | if (auto pmpThis = w.lock()) { |
| 269 | pmpThis->requestMappingAdd(mapping); |
| 270 | } |
| 271 | }); |
| 272 | return; |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 273 | }*/ |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 274 | |
| 275 | Mapping map(mapping); |
| 276 | assert(map.getIgd()); |
| 277 | auto err = addPortMapping(map); |
| 278 | if (err < 0) { |
Adrien Béraud | 17765bd | 2023-08-22 21:02:38 -0400 | [diff] [blame] | 279 | if (logger_) logger_->warn("NAT-PMP: Request for mapping {} on {} failed with error {:d}: {}", |
| 280 | map.toString(), |
| 281 | igd_->toString(), |
| 282 | err, |
| 283 | getNatPmpErrorStr(err)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 284 | |
| 285 | if (isErrorFatal(err)) { |
| 286 | // Fatal error, increment the counter. |
| 287 | incrementErrorsCounter(igd_); |
| 288 | } |
| 289 | // Notify the listener. |
| 290 | processMappingRequestFailed(std::move(map)); |
| 291 | } else { |
Adrien Béraud | 17765bd | 2023-08-22 21:02:38 -0400 | [diff] [blame] | 292 | if (logger_) logger_->debug("NAT-PMP: Request for mapping {:s} on {:s} succeeded", |
| 293 | map.toString(), |
| 294 | igd_->toString()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 295 | // Notify the listener. |
| 296 | processMappingAdded(std::move(map)); |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | void |
| 301 | NatPmp::requestMappingRenew(const Mapping& mapping) |
| 302 | { |
| 303 | // Process on nat-pmp thread. |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 304 | /*if (not isValidThread()) { |
| 305 | ioContext->post([w = weak(), mapping] { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 306 | if (auto pmpThis = w.lock()) { |
| 307 | pmpThis->requestMappingRenew(mapping); |
| 308 | } |
| 309 | }); |
| 310 | return; |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 311 | }*/ |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 312 | |
| 313 | Mapping map(mapping); |
| 314 | auto err = addPortMapping(map); |
| 315 | if (err < 0) { |
Adrien Béraud | 17765bd | 2023-08-22 21:02:38 -0400 | [diff] [blame] | 316 | if (logger_) logger_->warn("NAT-PMP: Renewal request for mapping {} on {} failed with error {:d}: {}", |
| 317 | map.toString().c_str(), |
| 318 | igd_->toString().c_str(), |
| 319 | err, |
| 320 | getNatPmpErrorStr(err)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 321 | // Notify the listener. |
| 322 | processMappingRequestFailed(std::move(map)); |
| 323 | |
| 324 | if (isErrorFatal(err)) { |
| 325 | // Fatal error, increment the counter. |
| 326 | incrementErrorsCounter(igd_); |
| 327 | } |
| 328 | } else { |
Adrien Béraud | 17765bd | 2023-08-22 21:02:38 -0400 | [diff] [blame] | 329 | if (logger_) logger_->debug("NAT-PMP: Renewal request for mapping {} on {} succeeded", |
| 330 | map.toString().c_str(), |
| 331 | igd_->toString().c_str()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 332 | // Notify the listener. |
| 333 | processMappingRenewed(map); |
| 334 | } |
| 335 | } |
| 336 | |
| 337 | int |
| 338 | NatPmp::readResponse(natpmp_t& handle, natpmpresp_t& response) |
| 339 | { |
| 340 | int err = 0; |
| 341 | unsigned readRetriesCounter = 0; |
| 342 | |
| 343 | while (true) { |
| 344 | if (readRetriesCounter++ > MAX_READ_RETRIES) { |
| 345 | err = NATPMP_ERR_SOCKETERROR; |
| 346 | break; |
| 347 | } |
| 348 | |
Sébastien Blin | 4cf587e | 2024-03-08 16:00:18 -0500 | [diff] [blame] | 349 | struct pollfd fds; |
| 350 | fds.fd = handle.s; |
| 351 | fds.events = POLLIN; |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 352 | struct timeval timeout; |
Sébastien Blin | 7733109 | 2024-05-17 10:58:23 -0400 | [diff] [blame] | 353 | err = getnatpmprequesttimeout(&handle, &timeout); |
| 354 | int millis = (timeout.tv_sec * 1000) + (timeout.tv_usec / 1000); |
| 355 | // Note, getnatpmprequesttimeout can be negative if previous deadline is passed. |
| 356 | if (err != 0 || millis < 0) |
| 357 | millis = 50; |
Andreas Traczyk | 8f7e1bd | 2024-04-04 16:26:58 -0400 | [diff] [blame] | 358 | |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 359 | // Wait for data. |
Andreas Traczyk | 8f7e1bd | 2024-04-04 16:26:58 -0400 | [diff] [blame] | 360 | if (_poll(&fds, 1, millis) == -1) { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 361 | err = NATPMP_ERR_SOCKETERROR; |
| 362 | break; |
| 363 | } |
| 364 | |
| 365 | // Read the data. |
| 366 | err = readnatpmpresponseorretry(&handle, &response); |
| 367 | |
| 368 | if (err == NATPMP_TRYAGAIN) { |
| 369 | std::this_thread::sleep_for(std::chrono::milliseconds(TIMEOUT_BEFORE_READ_RETRY)); |
| 370 | } else { |
| 371 | break; |
| 372 | } |
| 373 | } |
| 374 | |
| 375 | return err; |
| 376 | } |
| 377 | |
| 378 | int |
| 379 | NatPmp::sendMappingRequest(const Mapping& mapping, uint32_t& lifetime) |
| 380 | { |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 381 | //CHECK_VALID_THREAD(); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 382 | |
| 383 | int err = sendnewportmappingrequest(&natpmpHdl_, |
| 384 | mapping.getType() == PortType::UDP ? NATPMP_PROTOCOL_UDP |
| 385 | : NATPMP_PROTOCOL_TCP, |
| 386 | mapping.getInternalPort(), |
| 387 | mapping.getExternalPort(), |
| 388 | lifetime); |
| 389 | |
| 390 | if (err < 0) { |
Adrien Béraud | 17765bd | 2023-08-22 21:02:38 -0400 | [diff] [blame] | 391 | if (logger_) logger_->error("NAT-PMP: Send mapping request failed with error {} {:d}", |
| 392 | getNatPmpErrorStr(err), |
| 393 | errno); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 394 | return err; |
| 395 | } |
| 396 | |
| 397 | unsigned readRetriesCounter = 0; |
| 398 | |
| 399 | while (readRetriesCounter++ < MAX_READ_RETRIES) { |
| 400 | // Read the response |
| 401 | natpmpresp_t response; |
| 402 | err = readResponse(natpmpHdl_, response); |
| 403 | |
| 404 | if (err < 0) { |
Adrien Béraud | 17765bd | 2023-08-22 21:02:38 -0400 | [diff] [blame] | 405 | if (logger_) logger_->warn("NAT-PMP: Read response on IGD {} failed with error {}", |
| 406 | igd_->toString(), |
| 407 | getNatPmpErrorStr(err)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 408 | } else if (response.type != NATPMP_RESPTYPE_TCPPORTMAPPING |
| 409 | and response.type != NATPMP_RESPTYPE_UDPPORTMAPPING) { |
Adrien Béraud | 17765bd | 2023-08-22 21:02:38 -0400 | [diff] [blame] | 410 | if (logger_) logger_->error("NAT-PMP: Unexpected response type ({:d}) for mapping {} from IGD {}.", |
| 411 | response.type, |
| 412 | mapping.toString(), |
| 413 | igd_->toString()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 414 | // Try to read again. |
| 415 | continue; |
| 416 | } |
| 417 | |
| 418 | lifetime = response.pnu.newportmapping.lifetime; |
| 419 | // Done. |
| 420 | break; |
| 421 | } |
| 422 | |
| 423 | return err; |
| 424 | } |
| 425 | |
| 426 | int |
| 427 | NatPmp::addPortMapping(Mapping& mapping) |
| 428 | { |
| 429 | auto const& igdIn = mapping.getIgd(); |
| 430 | assert(igdIn); |
| 431 | assert(igdIn->getProtocol() == NatProtocolType::NAT_PMP); |
| 432 | |
| 433 | if (not igdIn->isValid() or not validIgdInstance(igdIn)) { |
| 434 | mapping.setState(MappingState::FAILED); |
| 435 | return NATPMP_ERR_INVALIDARGS; |
| 436 | } |
| 437 | |
| 438 | mapping.setInternalAddress(getHostAddress().toString()); |
| 439 | |
| 440 | uint32_t lifetime = MAPPING_ALLOCATION_LIFETIME; |
| 441 | int err = sendMappingRequest(mapping, lifetime); |
| 442 | |
| 443 | if (err < 0) { |
| 444 | mapping.setState(MappingState::FAILED); |
| 445 | return err; |
| 446 | } |
| 447 | |
| 448 | // Set the renewal time and update. |
| 449 | mapping.setRenewalTime(sys_clock::now() + std::chrono::seconds(lifetime * 4 / 5)); |
| 450 | mapping.setState(MappingState::OPEN); |
| 451 | |
| 452 | return 0; |
| 453 | } |
| 454 | |
| 455 | void |
| 456 | NatPmp::requestMappingRemove(const Mapping& mapping) |
| 457 | { |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 458 | ioContext->dispatch([w = weak(), mapping] { |
| 459 | if (auto pmpThis = w.lock()) { |
| 460 | Mapping map {mapping}; |
| 461 | pmpThis->removePortMapping(map); |
| 462 | } |
| 463 | }); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 464 | } |
| 465 | |
| 466 | void |
| 467 | NatPmp::removePortMapping(Mapping& mapping) |
| 468 | { |
| 469 | auto igdIn = mapping.getIgd(); |
| 470 | assert(igdIn); |
| 471 | if (not igdIn->isValid()) { |
| 472 | return; |
| 473 | } |
| 474 | |
| 475 | if (not validIgdInstance(igdIn)) { |
| 476 | return; |
| 477 | } |
| 478 | |
| 479 | Mapping mapToRemove(mapping); |
| 480 | |
| 481 | uint32_t lifetime = 0; |
| 482 | int err = sendMappingRequest(mapping, lifetime); |
| 483 | |
| 484 | if (err < 0) { |
| 485 | // Nothing to do if the request fails, just log the error. |
Adrien Béraud | 17765bd | 2023-08-22 21:02:38 -0400 | [diff] [blame] | 486 | if (logger_) logger_->warn("NAT-PMP: Send remove request failed with error {}. Ignoring", |
| 487 | getNatPmpErrorStr(err)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 488 | } |
| 489 | |
| 490 | // Update and notify the listener. |
| 491 | mapToRemove.setState(MappingState::FAILED); |
| 492 | processMappingRemoved(std::move(mapToRemove)); |
| 493 | } |
| 494 | |
| 495 | void |
| 496 | NatPmp::getIgdPublicAddress() |
| 497 | { |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 498 | //CHECK_VALID_THREAD(); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 499 | |
| 500 | // Set the public address for this IGD if it does not |
| 501 | // have one already. |
| 502 | if (igd_->getPublicIp()) { |
Adrien Béraud | 17765bd | 2023-08-22 21:02:38 -0400 | [diff] [blame] | 503 | if (logger_) logger_->warn("NAT-PMP: IGD {} already have a public address ({})", |
| 504 | igd_->toString(), |
| 505 | igd_->getPublicIp().toString()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 506 | return; |
| 507 | } |
| 508 | assert(igd_->getProtocol() == NatProtocolType::NAT_PMP); |
| 509 | |
| 510 | int err = sendpublicaddressrequest(&natpmpHdl_); |
| 511 | |
| 512 | if (err < 0) { |
Adrien Béraud | 17765bd | 2023-08-22 21:02:38 -0400 | [diff] [blame] | 513 | if (logger_) logger_->error("NAT-PMP: send public address request on IGD {} failed with error: {}", |
| 514 | igd_->toString(), |
| 515 | getNatPmpErrorStr(err)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 516 | |
| 517 | if (isErrorFatal(err)) { |
| 518 | // Fatal error, increment the counter. |
| 519 | incrementErrorsCounter(igd_); |
| 520 | } |
| 521 | return; |
| 522 | } |
| 523 | |
| 524 | natpmpresp_t response; |
| 525 | err = readResponse(natpmpHdl_, response); |
| 526 | |
| 527 | if (err < 0) { |
Adrien Béraud | 17765bd | 2023-08-22 21:02:38 -0400 | [diff] [blame] | 528 | if (logger_) logger_->warn("NAT-PMP: Read response on IGD {} failed - {}", |
| 529 | igd_->toString(), |
| 530 | getNatPmpErrorStr(err)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 531 | return; |
| 532 | } |
| 533 | |
| 534 | if (response.type != NATPMP_RESPTYPE_PUBLICADDRESS) { |
Adrien Béraud | 17765bd | 2023-08-22 21:02:38 -0400 | [diff] [blame] | 535 | if (logger_) logger_->error("NAT-PMP: Unexpected response type ({:d}) for public address request from IGD {}.", |
| 536 | response.type, |
| 537 | igd_->toString()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 538 | return; |
| 539 | } |
| 540 | |
| 541 | IpAddr publicAddr(response.pnu.publicaddress.addr); |
| 542 | |
| 543 | if (not publicAddr) { |
Adrien Béraud | 17765bd | 2023-08-22 21:02:38 -0400 | [diff] [blame] | 544 | if (logger_) logger_->error("NAT-PMP: IGD {} returned an invalid public address {}", |
| 545 | igd_->toString(), |
| 546 | publicAddr.toString()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 547 | } |
| 548 | |
| 549 | // Update. |
| 550 | igd_->setPublicIp(publicAddr); |
| 551 | igd_->setValid(true); |
| 552 | |
Adrien Béraud | 17765bd | 2023-08-22 21:02:38 -0400 | [diff] [blame] | 553 | if (logger_) logger_->debug("NAT-PMP: Setting IGD {} public address to {}", |
| 554 | igd_->toString(), |
| 555 | igd_->getPublicIp().toString()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 556 | } |
| 557 | |
| 558 | void |
| 559 | NatPmp::removeAllMappings() |
| 560 | { |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 561 | //CHECK_VALID_THREAD(); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 562 | |
Adrien Béraud | 17765bd | 2023-08-22 21:02:38 -0400 | [diff] [blame] | 563 | if (logger_) logger_->warn("NAT-PMP: Send request to close all existing mappings to IGD {}", |
| 564 | igd_->toString().c_str()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 565 | |
| 566 | int err = sendnewportmappingrequest(&natpmpHdl_, NATPMP_PROTOCOL_TCP, 0, 0, 0); |
| 567 | if (err < 0) { |
Adrien Béraud | 17765bd | 2023-08-22 21:02:38 -0400 | [diff] [blame] | 568 | if (logger_) logger_->warn("NAT-PMP: Send close all TCP mappings request failed with error {}", |
| 569 | getNatPmpErrorStr(err)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 570 | } |
| 571 | err = sendnewportmappingrequest(&natpmpHdl_, NATPMP_PROTOCOL_UDP, 0, 0, 0); |
| 572 | if (err < 0) { |
Adrien Béraud | 17765bd | 2023-08-22 21:02:38 -0400 | [diff] [blame] | 573 | if (logger_) logger_->warn("NAT-PMP: Send close all UDP mappings request failed with error {}", |
| 574 | getNatPmpErrorStr(err)); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 575 | } |
| 576 | } |
| 577 | |
| 578 | const char* |
| 579 | NatPmp::getNatPmpErrorStr(int errorCode) const |
| 580 | { |
| 581 | #ifdef ENABLE_STRNATPMPERR |
| 582 | return strnatpmperr(errorCode); |
| 583 | #else |
| 584 | switch (errorCode) { |
| 585 | case NATPMP_ERR_INVALIDARGS: |
| 586 | return "INVALIDARGS"; |
| 587 | break; |
| 588 | case NATPMP_ERR_SOCKETERROR: |
| 589 | return "SOCKETERROR"; |
| 590 | break; |
| 591 | case NATPMP_ERR_CANNOTGETGATEWAY: |
| 592 | return "CANNOTGETGATEWAY"; |
| 593 | break; |
| 594 | case NATPMP_ERR_CLOSEERR: |
| 595 | return "CLOSEERR"; |
| 596 | break; |
| 597 | case NATPMP_ERR_RECVFROM: |
| 598 | return "RECVFROM"; |
| 599 | break; |
| 600 | case NATPMP_ERR_NOPENDINGREQ: |
| 601 | return "NOPENDINGREQ"; |
| 602 | break; |
| 603 | case NATPMP_ERR_NOGATEWAYSUPPORT: |
| 604 | return "NOGATEWAYSUPPORT"; |
| 605 | break; |
| 606 | case NATPMP_ERR_CONNECTERR: |
| 607 | return "CONNECTERR"; |
| 608 | break; |
| 609 | case NATPMP_ERR_WRONGPACKETSOURCE: |
| 610 | return "WRONGPACKETSOURCE"; |
| 611 | break; |
| 612 | case NATPMP_ERR_SENDERR: |
| 613 | return "SENDERR"; |
| 614 | break; |
| 615 | case NATPMP_ERR_FCNTLERROR: |
| 616 | return "FCNTLERROR"; |
| 617 | break; |
| 618 | case NATPMP_ERR_GETTIMEOFDAYERR: |
| 619 | return "GETTIMEOFDAYERR"; |
| 620 | break; |
| 621 | case NATPMP_ERR_UNSUPPORTEDVERSION: |
| 622 | return "UNSUPPORTEDVERSION"; |
| 623 | break; |
| 624 | case NATPMP_ERR_UNSUPPORTEDOPCODE: |
| 625 | return "UNSUPPORTEDOPCODE"; |
| 626 | break; |
| 627 | case NATPMP_ERR_UNDEFINEDERROR: |
| 628 | return "UNDEFINEDERROR"; |
| 629 | break; |
| 630 | case NATPMP_ERR_NOTAUTHORIZED: |
| 631 | return "NOTAUTHORIZED"; |
| 632 | break; |
| 633 | case NATPMP_ERR_NETWORKFAILURE: |
| 634 | return "NETWORKFAILURE"; |
| 635 | break; |
| 636 | case NATPMP_ERR_OUTOFRESOURCES: |
| 637 | return "OUTOFRESOURCES"; |
| 638 | break; |
| 639 | case NATPMP_TRYAGAIN: |
| 640 | return "TRYAGAIN"; |
| 641 | break; |
| 642 | default: |
| 643 | return "UNKNOWNERR"; |
| 644 | break; |
| 645 | } |
| 646 | #endif |
| 647 | } |
| 648 | |
| 649 | bool |
| 650 | NatPmp::isErrorFatal(int error) |
| 651 | { |
| 652 | switch (error) { |
| 653 | case NATPMP_ERR_INVALIDARGS: |
| 654 | case NATPMP_ERR_SOCKETERROR: |
| 655 | case NATPMP_ERR_CANNOTGETGATEWAY: |
| 656 | case NATPMP_ERR_CLOSEERR: |
| 657 | case NATPMP_ERR_RECVFROM: |
| 658 | case NATPMP_ERR_NOGATEWAYSUPPORT: |
| 659 | case NATPMP_ERR_CONNECTERR: |
| 660 | case NATPMP_ERR_SENDERR: |
| 661 | case NATPMP_ERR_UNDEFINEDERROR: |
| 662 | case NATPMP_ERR_UNSUPPORTEDVERSION: |
| 663 | case NATPMP_ERR_UNSUPPORTEDOPCODE: |
| 664 | case NATPMP_ERR_NOTAUTHORIZED: |
| 665 | case NATPMP_ERR_NETWORKFAILURE: |
| 666 | case NATPMP_ERR_OUTOFRESOURCES: |
| 667 | return true; |
| 668 | default: |
| 669 | return false; |
| 670 | } |
| 671 | } |
| 672 | |
| 673 | bool |
| 674 | NatPmp::validIgdInstance(const std::shared_ptr<IGD>& igdIn) |
| 675 | { |
| 676 | if (igd_.get() != igdIn.get()) { |
Adrien Béraud | 17765bd | 2023-08-22 21:02:38 -0400 | [diff] [blame] | 677 | if (logger_) logger_->error("NAT-PMP: IGD ({}) does not match local instance ({})", |
| 678 | igdIn->toString(), |
| 679 | igd_->toString()); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 680 | return false; |
| 681 | } |
| 682 | |
| 683 | return true; |
| 684 | } |
| 685 | |
| 686 | void |
| 687 | NatPmp::processIgdUpdate(UpnpIgdEvent event) |
| 688 | { |
| 689 | if (igd_->isValid()) { |
| 690 | // Remove all current mappings if any. |
| 691 | removeAllMappings(); |
| 692 | } |
| 693 | |
| 694 | if (observer_ == nullptr) |
| 695 | return; |
| 696 | // Process the response on the context thread. |
Sébastien Blin | f6baf4b | 2024-01-03 15:51:36 -0500 | [diff] [blame] | 697 | ioContext->post([w = weak(), event] { |
| 698 | if (auto shared = w.lock()) { |
| 699 | if (!shared->shutdownComplete_) { |
| 700 | shared->observer_->onIgdUpdated(shared->igd_, event); |
| 701 | } |
| 702 | } |
| 703 | }); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 704 | } |
| 705 | |
| 706 | void |
| 707 | NatPmp::processMappingAdded(const Mapping& map) |
| 708 | { |
| 709 | if (observer_ == nullptr) |
| 710 | return; |
| 711 | |
| 712 | // Process the response on the context thread. |
Sébastien Blin | f6baf4b | 2024-01-03 15:51:36 -0500 | [diff] [blame] | 713 | ioContext->post([w=weak(), map] { |
| 714 | if (auto shared = w.lock()) { |
| 715 | if (!shared->shutdownComplete_) { |
| 716 | shared->observer_->onMappingAdded(shared->igd_, map); |
| 717 | } |
| 718 | } |
| 719 | }); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 720 | } |
| 721 | |
| 722 | void |
| 723 | NatPmp::processMappingRequestFailed(const Mapping& map) |
| 724 | { |
| 725 | if (observer_ == nullptr) |
| 726 | return; |
| 727 | |
| 728 | // Process the response on the context thread. |
Sébastien Blin | f6baf4b | 2024-01-03 15:51:36 -0500 | [diff] [blame] | 729 | ioContext->post([w=weak(), map] { |
| 730 | if (auto shared = w.lock()) { |
| 731 | if (!shared->shutdownComplete_) { |
| 732 | shared->observer_->onMappingRequestFailed(map); |
| 733 | } |
| 734 | } |
| 735 | }); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 736 | } |
| 737 | |
| 738 | void |
| 739 | NatPmp::processMappingRenewed(const Mapping& map) |
| 740 | { |
| 741 | if (observer_ == nullptr) |
| 742 | return; |
| 743 | |
| 744 | // Process the response on the context thread. |
Sébastien Blin | f6baf4b | 2024-01-03 15:51:36 -0500 | [diff] [blame] | 745 | ioContext->post([w=weak(), map] { |
| 746 | if (auto shared = w.lock()) { |
| 747 | if (!shared->shutdownComplete_) { |
| 748 | shared->observer_->onMappingRenewed(shared->igd_, map); |
| 749 | } |
| 750 | } |
| 751 | }); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 752 | } |
| 753 | |
| 754 | void |
| 755 | NatPmp::processMappingRemoved(const Mapping& map) |
| 756 | { |
| 757 | if (observer_ == nullptr) |
| 758 | return; |
| 759 | |
| 760 | // Process the response on the context thread. |
Sébastien Blin | f6baf4b | 2024-01-03 15:51:36 -0500 | [diff] [blame] | 761 | ioContext->post([w=weak(), map] { |
| 762 | if (auto shared = w.lock()) { |
| 763 | if (!shared->shutdownComplete_) { |
| 764 | shared->observer_->onMappingRemoved(shared->igd_, map); |
| 765 | } |
| 766 | } |
| 767 | }); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 768 | } |
| 769 | |
| 770 | } // namespace upnp |
Sébastien Blin | 464bdff | 2023-07-19 08:02:53 -0400 | [diff] [blame] | 771 | } // namespace dhtnet |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 772 | |
| 773 | #endif //-- #if HAVE_LIBNATPMP |