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 | #pragma once |
| 18 | |
Morteza Namvar | 5f63952 | 2023-07-04 17:08:58 -0400 | [diff] [blame] | 19 | /*#include "upnp_protocol.h" |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 20 | #if HAVE_LIBNATPMP |
| 21 | #include "protocol/natpmp/nat_pmp.h" |
| 22 | #endif |
| 23 | #if HAVE_LIBUPNP |
| 24 | #include "protocol/pupnp/pupnp.h" |
| 25 | #endif |
Morteza Namvar | 5f63952 | 2023-07-04 17:08:58 -0400 | [diff] [blame] | 26 | #include "igd.h"*/ |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 27 | |
Adrien Béraud | dbb0686 | 2023-07-08 09:18:39 -0400 | [diff] [blame] | 28 | #include "../ip_utils.h" |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 29 | |
Adrien Béraud | dbb0686 | 2023-07-08 09:18:39 -0400 | [diff] [blame] | 30 | #include "mapping.h" |
Morteza Namvar | 5f63952 | 2023-07-04 17:08:58 -0400 | [diff] [blame] | 31 | |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 32 | #include <opendht/rng.h> |
Adrien Béraud | 25c30c4 | 2023-07-05 13:46:54 -0400 | [diff] [blame] | 33 | #include <opendht/logger.h> |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 34 | #include <asio/steady_timer.hpp> |
| 35 | |
| 36 | #include <set> |
| 37 | #include <map> |
| 38 | #include <mutex> |
| 39 | #include <memory> |
| 40 | #include <string> |
| 41 | #include <chrono> |
| 42 | #include <random> |
| 43 | #include <atomic> |
Morteza Namvar | 5f63952 | 2023-07-04 17:08:58 -0400 | [diff] [blame] | 44 | #include <condition_variable> |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 45 | |
Morteza Namvar | 5f63952 | 2023-07-04 17:08:58 -0400 | [diff] [blame] | 46 | #include <cstdlib> |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 47 | |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 48 | using IgdFoundCallback = std::function<void()>; |
| 49 | |
Adrien Béraud | 1ae60aa | 2023-07-07 09:55:09 -0400 | [diff] [blame] | 50 | namespace dhtnet { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 51 | class IpAddr; |
| 52 | } |
| 53 | |
Adrien Béraud | 1ae60aa | 2023-07-07 09:55:09 -0400 | [diff] [blame] | 54 | namespace dhtnet { |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 55 | namespace upnp { |
| 56 | |
Morteza Namvar | 5f63952 | 2023-07-04 17:08:58 -0400 | [diff] [blame] | 57 | class UPnPProtocol; |
| 58 | class IGD; |
| 59 | |
| 60 | enum class UpnpIgdEvent { ADDED, REMOVED, INVALID_STATE }; |
| 61 | |
| 62 | // Interface used to report mapping event from the protocol implementations. |
| 63 | // This interface is meant to be implemented only by UPnPConext class. Sincce |
| 64 | // this class is a singleton, it's assumed that it out-lives the protocol |
| 65 | // implementations. In other words, the observer is always assumed to point to a |
| 66 | // valid instance. |
| 67 | class UpnpMappingObserver |
| 68 | { |
| 69 | public: |
| 70 | UpnpMappingObserver() {}; |
| 71 | virtual ~UpnpMappingObserver() {}; |
| 72 | |
| 73 | virtual void onIgdUpdated(const std::shared_ptr<IGD>& igd, UpnpIgdEvent event) = 0; |
| 74 | virtual void onMappingAdded(const std::shared_ptr<IGD>& igd, const Mapping& map) = 0; |
| 75 | virtual void onMappingRequestFailed(const Mapping& map) = 0; |
| 76 | #if HAVE_LIBNATPMP |
| 77 | virtual void onMappingRenewed(const std::shared_ptr<IGD>& igd, const Mapping& map) = 0; |
| 78 | #endif |
| 79 | virtual void onMappingRemoved(const std::shared_ptr<IGD>& igd, const Mapping& map) = 0; |
| 80 | }; |
| 81 | |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 82 | class UPnPContext : public UpnpMappingObserver |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 83 | { |
| 84 | private: |
| 85 | struct MappingStatus |
| 86 | { |
| 87 | int openCount_ {0}; |
| 88 | int readyCount_ {0}; |
| 89 | int pendingCount_ {0}; |
| 90 | int inProgressCount_ {0}; |
| 91 | int failedCount_ {0}; |
| 92 | |
| 93 | void reset() |
| 94 | { |
| 95 | openCount_ = 0; |
| 96 | readyCount_ = 0; |
| 97 | pendingCount_ = 0; |
| 98 | inProgressCount_ = 0; |
| 99 | failedCount_ = 0; |
| 100 | }; |
| 101 | int sum() { return openCount_ + pendingCount_ + inProgressCount_ + failedCount_; } |
| 102 | }; |
| 103 | |
| 104 | public: |
Sébastien Blin | 55abf07 | 2023-07-19 10:21:21 -0400 | [diff] [blame] | 105 | UPnPContext(const std::shared_ptr<asio::io_context>& ctx, const std::shared_ptr<dht::log::Logger>& logger); |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 106 | ~UPnPContext(); |
| 107 | |
Adrien Béraud | b04fbd7 | 2023-08-17 19:56:11 -0400 | [diff] [blame] | 108 | std::shared_ptr<asio::io_context> createIoContext(const std::shared_ptr<asio::io_context>& ctx, const std::shared_ptr<dht::log::Logger>& logger); |
| 109 | |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 110 | // Terminate the instance. |
| 111 | void shutdown(); |
| 112 | |
| 113 | // Set the known public address |
| 114 | void setPublicAddress(const IpAddr& addr); |
| 115 | |
| 116 | // Check if there is a valid IGD in the IGD list. |
| 117 | bool isReady() const; |
| 118 | |
| 119 | // Get external Ip of a chosen IGD. |
| 120 | IpAddr getExternalIP() const; |
| 121 | |
| 122 | // Inform the UPnP context that the network status has changed. This clears the list of known |
| 123 | void connectivityChanged(); |
| 124 | |
| 125 | // Returns a shared pointer of the mapping. |
| 126 | Mapping::sharedPtr_t reserveMapping(Mapping& requestedMap); |
| 127 | |
| 128 | // Release an used mapping (make it available for future use). |
| 129 | void releaseMapping(const Mapping& map); |
| 130 | |
| 131 | // Register a controller |
| 132 | void registerController(void* controller); |
| 133 | // Unregister a controller |
| 134 | void unregisterController(void* controller); |
| 135 | |
| 136 | // Generate random port numbers |
| 137 | static uint16_t generateRandomPort(PortType type, bool mustBeEven = false); |
| 138 | |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 139 | template <typename T> |
| 140 | inline void dispatch(T&& f) { |
| 141 | ctx->dispatch(std::move(f)); |
| 142 | } |
| 143 | |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 144 | private: |
| 145 | // Initialization |
| 146 | void init(); |
| 147 | |
| 148 | /** |
| 149 | * @brief start the search for IGDs activate the mapping |
| 150 | * list update. |
| 151 | * |
| 152 | */ |
| 153 | void startUpnp(); |
| 154 | |
| 155 | /** |
| 156 | * @brief Clear all IGDs and release/delete current mappings |
| 157 | * |
| 158 | * @param forceRelease If true, also delete mappings with enabled |
| 159 | * auto-update feature. |
| 160 | * |
| 161 | */ |
| 162 | void stopUpnp(bool forceRelease = false); |
| 163 | |
| 164 | void shutdown(std::condition_variable& cv); |
| 165 | |
| 166 | // Create and register a new mapping. |
| 167 | Mapping::sharedPtr_t registerMapping(Mapping& map); |
| 168 | |
| 169 | // Removes the mapping from the list. |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 170 | void unregisterMapping(const Mapping::sharedPtr_t& map); |
| 171 | |
| 172 | // Perform the request on the provided IGD. |
| 173 | void requestMapping(const Mapping::sharedPtr_t& map); |
| 174 | |
| 175 | // Request a mapping remove from the IGD. |
| 176 | void requestRemoveMapping(const Mapping::sharedPtr_t& map); |
| 177 | |
| 178 | // Remove all mappings of the given type. |
| 179 | void deleteAllMappings(PortType type); |
| 180 | |
Adrien Beraud | 3bd61c9 | 2023-08-17 16:57:37 -0400 | [diff] [blame] | 181 | // Update the state and notify the listener |
| 182 | void updateMappingState(const Mapping::sharedPtr_t& map, |
| 183 | MappingState newState, |
| 184 | bool notify = true); |
| 185 | |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 186 | // Provision ports. |
| 187 | uint16_t getAvailablePortNumber(PortType type); |
| 188 | |
| 189 | // Update preferred IGD |
| 190 | void updatePreferredIgd(); |
| 191 | |
| 192 | // Get preferred IGD |
| 193 | std::shared_ptr<IGD> getPreferredIgd() const; |
| 194 | |
| 195 | // Check and prune the mapping list. Called periodically. |
| 196 | void updateMappingList(bool async); |
| 197 | |
| 198 | // Provision (pre-allocate) the requested number of mappings. |
| 199 | bool provisionNewMappings(PortType type, int portCount); |
| 200 | |
| 201 | // Close unused mappings. |
| 202 | bool deleteUnneededMappings(PortType type, int portCount); |
| 203 | |
| 204 | /** |
| 205 | * Prune the mapping list.To avoid competing with allocation |
| 206 | * requests, the pruning is performed only if there are no |
| 207 | * requests in progress. |
| 208 | */ |
| 209 | void pruneMappingList(); |
| 210 | |
| 211 | /** |
| 212 | * Check if there are allocated mappings from previous instances, |
| 213 | * and try to close them. |
| 214 | * Only done for UPNP protocol. NAT-PMP allocations will expire |
| 215 | * anyway if not renewed. |
| 216 | */ |
| 217 | void pruneUnMatchedMappings(const std::shared_ptr<IGD>& igd, |
| 218 | const std::map<Mapping::key_t, Mapping>& remoteMapList); |
| 219 | |
| 220 | /** |
| 221 | * Check the local mapping list against the list returned by the |
| 222 | * IGD and remove all mappings which do not have a match. |
| 223 | * Only done for UPNP protocol. |
| 224 | */ |
| 225 | void pruneUnTrackedMappings(const std::shared_ptr<IGD>& igd, |
| 226 | const std::map<Mapping::key_t, Mapping>& remoteMapList); |
| 227 | |
| 228 | void pruneMappingsWithInvalidIgds(const std::shared_ptr<IGD>& igd); |
| 229 | |
| 230 | /** |
| 231 | * @brief Get the mapping list |
| 232 | * |
| 233 | * @param type transport type (TCP/UDP) |
| 234 | * @return a reference on the map |
| 235 | * @warning concurrency protection done by the caller |
| 236 | */ |
| 237 | std::map<Mapping::key_t, Mapping::sharedPtr_t>& getMappingList(PortType type); |
| 238 | |
| 239 | // Get the mapping from the key. |
| 240 | Mapping::sharedPtr_t getMappingWithKey(Mapping::key_t key); |
| 241 | |
| 242 | // Get the number of mappings per state. |
| 243 | void getMappingStatus(PortType type, MappingStatus& status); |
| 244 | void getMappingStatus(MappingStatus& status); |
| 245 | |
| 246 | #if HAVE_LIBNATPMP |
| 247 | void renewAllocations(); |
| 248 | #endif |
| 249 | |
| 250 | // Process requests with pending status. |
| 251 | void processPendingRequests(const std::shared_ptr<IGD>& igd); |
| 252 | |
| 253 | // Process mapping with auto-update flag enabled. |
| 254 | void processMappingWithAutoUpdate(); |
| 255 | |
| 256 | // Implementation of UpnpMappingObserver interface. |
| 257 | |
| 258 | // Callback used to report changes in IGD status. |
| 259 | void onIgdUpdated(const std::shared_ptr<IGD>& igd, UpnpIgdEvent event) override; |
| 260 | // Callback used to report add request status. |
| 261 | void onMappingAdded(const std::shared_ptr<IGD>& igd, const Mapping& map) override; |
| 262 | // Callback invoked when a request fails. Reported on failures for both |
| 263 | // new requests and renewal requests (if supported by the the protocol). |
| 264 | void onMappingRequestFailed(const Mapping& map) override; |
| 265 | #if HAVE_LIBNATPMP |
| 266 | // Callback used to report renew request status. |
| 267 | void onMappingRenewed(const std::shared_ptr<IGD>& igd, const Mapping& map) override; |
| 268 | #endif |
| 269 | // Callback used to report remove request status. |
| 270 | void onMappingRemoved(const std::shared_ptr<IGD>& igd, const Mapping& map) override; |
| 271 | |
| 272 | private: |
| 273 | UPnPContext(const UPnPContext&) = delete; |
| 274 | UPnPContext(UPnPContext&&) = delete; |
| 275 | UPnPContext& operator=(UPnPContext&&) = delete; |
| 276 | UPnPContext& operator=(const UPnPContext&) = delete; |
| 277 | |
Adrien Béraud | c36965c | 2023-08-17 21:50:27 -0400 | [diff] [blame] | 278 | void _connectivityChanged(const asio::error_code& ec); |
| 279 | |
| 280 | // Thread (io_context), destroyed last |
| 281 | std::unique_ptr<std::thread> ioContextRunner_ {}; |
| 282 | |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 283 | bool started_ {false}; |
| 284 | |
| 285 | // The known public address. The external addresses returned by |
| 286 | // the IGDs will be checked against this address. |
| 287 | IpAddr knownPublicAddress_ {}; |
| 288 | |
| 289 | // Set of registered controllers |
Adrien Béraud | c36965c | 2023-08-17 21:50:27 -0400 | [diff] [blame] | 290 | std::mutex mutable controllerMutex_; |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 291 | std::set<void*> controllerList_; |
| 292 | |
| 293 | // Map of available protocols. |
| 294 | std::map<NatProtocolType, std::shared_ptr<UPnPProtocol>> protocolList_; |
| 295 | |
| 296 | // Port ranges for TCP and UDP (in that order). |
| 297 | std::map<PortType, std::pair<uint16_t, uint16_t>> portRange_ {}; |
| 298 | |
| 299 | // Min open ports limit |
| 300 | int minOpenPortLimit_[2] {4, 8}; |
| 301 | // Max open ports limit |
| 302 | int maxOpenPortLimit_[2] {8, 12}; |
| 303 | |
Adrien Béraud | 370257c | 2023-08-15 20:53:09 -0400 | [diff] [blame] | 304 | std::shared_ptr<asio::io_context> ctx; |
| 305 | std::shared_ptr<dht::log::Logger> logger_; |
Adrien Beraud | a8731ac | 2023-08-17 12:19:39 -0400 | [diff] [blame] | 306 | asio::steady_timer mappingListUpdateTimer_; |
Adrien Béraud | c36965c | 2023-08-17 21:50:27 -0400 | [diff] [blame] | 307 | asio::steady_timer connectivityChangedTimer_; |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 308 | |
| 309 | // Current preferred IGD. Can be null if there is no valid IGD. |
| 310 | std::shared_ptr<IGD> preferredIgd_; |
| 311 | |
| 312 | // This mutex must lock only these two members. All other |
| 313 | // members must be accessed only from the UPNP context thread. |
| 314 | std::mutex mutable mappingMutex_; |
| 315 | // List of mappings. |
| 316 | std::map<Mapping::key_t, Mapping::sharedPtr_t> mappingList_[2] {}; |
| 317 | std::set<std::shared_ptr<IGD>> validIgdList_ {}; |
| 318 | |
| 319 | // Shutdown synchronization |
| 320 | bool shutdownComplete_ {false}; |
François-Simon Fauteux-Chapleau | 808db4f | 2024-04-19 11:39:47 -0400 | [diff] [blame] | 321 | bool shutdownTimedOut_ {false}; |
Adrien Béraud | 612b55b | 2023-05-29 10:42:04 -0400 | [diff] [blame] | 322 | }; |
| 323 | |
| 324 | } // namespace upnp |
Sébastien Blin | 464bdff | 2023-07-19 08:02:53 -0400 | [diff] [blame] | 325 | } // namespace dhtnet |