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