blob: fca38a530b7df0fc1795aade85db5cb6469186be [file] [log] [blame]
Adrien Béraud612b55b2023-05-29 10:42:04 -04001/*
2 * Copyright (C) 2004-2023 Savoir-faire Linux Inc.
3 *
Adrien Béraudcb753622023-07-17 22:32:49 -04004 * This program is free software: you can redistribute it and/or modify
Adrien Béraud612b55b2023-05-29 10:42:04 -04005 * it under the terms of the GNU General Public License as published by
Adrien Béraudcb753622023-07-17 22:32:49 -04006 * the Free Software Foundation, either version 3 of the License, or
Adrien Béraud612b55b2023-05-29 10:42:04 -04007 * (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éraudcb753622023-07-17 22:32:49 -040011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
Adrien Béraud612b55b2023-05-29 10:42:04 -040012 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
Adrien Béraudcb753622023-07-17 22:32:49 -040015 * along with this program. If not, see <https://www.gnu.org/licenses/>.
Adrien Béraud612b55b2023-05-29 10:42:04 -040016 */
Adrien Béraud612b55b2023-05-29 10:42:04 -040017#pragma once
18
Adrien Bérauddbb06862023-07-08 09:18:39 -040019#include "../ip_utils.h"
Adrien Béraud612b55b2023-05-29 10:42:04 -040020
Adrien Bérauddbb06862023-07-08 09:18:39 -040021#include "mapping.h"
Morteza Namvar5f639522023-07-04 17:08:58 -040022
Adrien Béraud612b55b2023-05-29 10:42:04 -040023#include <opendht/rng.h>
Adrien Béraud25c30c42023-07-05 13:46:54 -040024#include <opendht/logger.h>
Adrien Béraud612b55b2023-05-29 10:42:04 -040025#include <asio/steady_timer.hpp>
François-Simon Fauteux-Chapleaufd29c1d2024-05-30 16:48:26 -040026#include <asio/system_timer.hpp>
Adrien Béraud612b55b2023-05-29 10:42:04 -040027
28#include <set>
29#include <map>
30#include <mutex>
31#include <memory>
32#include <string>
33#include <chrono>
34#include <random>
35#include <atomic>
Morteza Namvar5f639522023-07-04 17:08:58 -040036#include <condition_variable>
Adrien Béraud612b55b2023-05-29 10:42:04 -040037
Morteza Namvar5f639522023-07-04 17:08:58 -040038#include <cstdlib>
Adrien Béraud612b55b2023-05-29 10:42:04 -040039
Adrien Béraud612b55b2023-05-29 10:42:04 -040040using IgdFoundCallback = std::function<void()>;
41
Adrien Béraud1ae60aa2023-07-07 09:55:09 -040042namespace dhtnet {
Adrien Béraud612b55b2023-05-29 10:42:04 -040043class IpAddr;
44}
45
Adrien Béraud1ae60aa2023-07-07 09:55:09 -040046namespace dhtnet {
Adrien Béraud612b55b2023-05-29 10:42:04 -040047namespace upnp {
48
Morteza Namvar5f639522023-07-04 17:08:58 -040049class UPnPProtocol;
50class IGD;
51
François-Simon Fauteux-Chapleau826f0ba2024-05-29 15:22:21 -040052struct IGDInfo
53{
54 std::string uid;
55 IpAddr localIp;
56 IpAddr publicIp;
57 std::vector<MappingInfo> mappingInfoList;
58};
59
Morteza Namvar5f639522023-07-04 17:08:58 -040060enum class UpnpIgdEvent { ADDED, REMOVED, INVALID_STATE };
61
62// Interface used to report mapping event from the protocol implementations.
François-Simon Fauteux-Chapleaufd29c1d2024-05-30 16:48:26 -040063// This interface is meant to be implemented only by UPnPContext class. Since
64// this class is a singleton, it's assumed that it outlives the protocol
Morteza Namvar5f639522023-07-04 17:08:58 -040065// implementations. In other words, the observer is always assumed to point to a
66// valid instance.
67class UpnpMappingObserver
68{
69public:
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;
Morteza Namvar5f639522023-07-04 17:08:58 -040076 virtual void onMappingRenewed(const std::shared_ptr<IGD>& igd, const Mapping& map) = 0;
Morteza Namvar5f639522023-07-04 17:08:58 -040077 virtual void onMappingRemoved(const std::shared_ptr<IGD>& igd, const Mapping& map) = 0;
78};
79
Adrien Béraud370257c2023-08-15 20:53:09 -040080class UPnPContext : public UpnpMappingObserver
Adrien Béraud612b55b2023-05-29 10:42:04 -040081{
Adrien Béraud612b55b2023-05-29 10:42:04 -040082public:
Sébastien Blin55abf072023-07-19 10:21:21 -040083 UPnPContext(const std::shared_ptr<asio::io_context>& ctx, const std::shared_ptr<dht::log::Logger>& logger);
Adrien Béraud612b55b2023-05-29 10:42:04 -040084 ~UPnPContext();
85
Adrien Béraudb04fbd72023-08-17 19:56:11 -040086 std::shared_ptr<asio::io_context> createIoContext(const std::shared_ptr<asio::io_context>& ctx, const std::shared_ptr<dht::log::Logger>& logger);
87
Adrien Béraud612b55b2023-05-29 10:42:04 -040088 // Terminate the instance.
89 void shutdown();
90
91 // Set the known public address
92 void setPublicAddress(const IpAddr& addr);
93
94 // Check if there is a valid IGD in the IGD list.
95 bool isReady() const;
96
97 // Get external Ip of a chosen IGD.
98 IpAddr getExternalIP() const;
99
François-Simon Fauteux-Chapleaufd29c1d2024-05-30 16:48:26 -0400100 // Inform the UPnP context that the network status has changed.
Adrien Béraud612b55b2023-05-29 10:42:04 -0400101 void connectivityChanged();
102
103 // Returns a shared pointer of the mapping.
104 Mapping::sharedPtr_t reserveMapping(Mapping& requestedMap);
105
François-Simon Fauteux-Chapleaufd29c1d2024-05-30 16:48:26 -0400106 // Release a used mapping (make it available for future use).
107 // TODO: The current implementation doesn't seem to do the "make it available for future use" part... fix this.
Adrien Béraud612b55b2023-05-29 10:42:04 -0400108 void releaseMapping(const Mapping& map);
109
110 // Register a controller
111 void registerController(void* controller);
112 // Unregister a controller
113 void unregisterController(void* controller);
114
115 // Generate random port numbers
François-Simon Fauteux-Chapleaufd29c1d2024-05-30 16:48:26 -0400116 static uint16_t generateRandomPort(PortType type);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400117
François-Simon Fauteux-Chapleau826f0ba2024-05-29 15:22:21 -0400118 // Return information about the UPnPContext's valid IGDs, including the list
119 // of all existing port mappings (for IGDs which support a protocol that allows
120 // querying that information -- UPnP does, but NAT-PMP doesn't for example)
121 std::vector<IGDInfo> getIgdsInfo() const;
122
Adrien Berauda8731ac2023-08-17 12:19:39 -0400123 template <typename T>
124 inline void dispatch(T&& f) {
125 ctx->dispatch(std::move(f));
126 }
127
François-Simon Fauteux-Chapleaufd29c1d2024-05-30 16:48:26 -0400128 void restart()
129 {
130 ctx->dispatch([this]{
131 stopUpnp();
132 startUpnp();
133 });
134 }
135
Adrien Béraud612b55b2023-05-29 10:42:04 -0400136private:
137 // Initialization
138 void init();
139
140 /**
141 * @brief start the search for IGDs activate the mapping
142 * list update.
143 *
144 */
145 void startUpnp();
146
147 /**
148 * @brief Clear all IGDs and release/delete current mappings
149 *
150 * @param forceRelease If true, also delete mappings with enabled
151 * auto-update feature.
152 *
153 */
154 void stopUpnp(bool forceRelease = false);
155
156 void shutdown(std::condition_variable& cv);
157
François-Simon Fauteux-Chapleaufd29c1d2024-05-30 16:48:26 -0400158 // Add a new mapping to the local list and
159 // send a request to the IGD to create it.
Adrien Béraud612b55b2023-05-29 10:42:04 -0400160 Mapping::sharedPtr_t registerMapping(Mapping& map);
161
François-Simon Fauteux-Chapleaufd29c1d2024-05-30 16:48:26 -0400162 // Remove the given mapping from the local list.
163 //
164 // If the mapping has auto-update enabled, then a new mapping of the same
165 // type will be reserved unless ignoreAutoUpdate is true.
166 void unregisterMapping(const Mapping::sharedPtr_t& map, bool ignoreAutoUpdate = false);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400167
168 // Perform the request on the provided IGD.
169 void requestMapping(const Mapping::sharedPtr_t& map);
170
171 // Request a mapping remove from the IGD.
172 void requestRemoveMapping(const Mapping::sharedPtr_t& map);
173
Adrien Beraud3bd61c92023-08-17 16:57:37 -0400174 // Update the state and notify the listener
175 void updateMappingState(const Mapping::sharedPtr_t& map,
176 MappingState newState,
177 bool notify = true);
178
Adrien Béraud612b55b2023-05-29 10:42:04 -0400179 // Provision ports.
180 uint16_t getAvailablePortNumber(PortType type);
181
François-Simon Fauteux-Chapleaufd29c1d2024-05-30 16:48:26 -0400182 // If the current IGD is still valid, do nothing.
183 // If not, then replace it with a valid one (if possible) or set it to null.
184 void updateCurrentIgd();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400185
François-Simon Fauteux-Chapleaufd29c1d2024-05-30 16:48:26 -0400186 // Get the current IGD
187 std::shared_ptr<IGD> getCurrentIgd() const;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400188
François-Simon Fauteux-Chapleaufd29c1d2024-05-30 16:48:26 -0400189 // Send a renewal request to the IGD for each mapping which is past its renewal time.
190 void renewMappings();
191
192 // Set a timer so that renewMappings is called when needed
193 void scheduleMappingsRenewal();
194 void _scheduleMappingsRenewal();
195
196 // Add or remove mappings to maintain the number of available mappings
197 // within the limits set by minAvailableMappings_ and maxAvailableMappings_.
198 void enforceAvailableMappingsLimits();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400199
200 // Provision (pre-allocate) the requested number of mappings.
François-Simon Fauteux-Chapleaufd29c1d2024-05-30 16:48:26 -0400201 void provisionNewMappings(PortType type, int portCount);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400202
203 // Close unused mappings.
François-Simon Fauteux-Chapleaufd29c1d2024-05-30 16:48:26 -0400204 void deleteUnneededMappings(PortType type, int portCount);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400205
François-Simon Fauteux-Chapleaufd29c1d2024-05-30 16:48:26 -0400206 // Get information from the current IGD about the mappings it currently has
207 // and update the local list accordingly. (Only called if the current IGD
208 // uses the UPnP protocol -- NAT-PMP doesn't support doing this.)
209 void syncLocalMappingListWithIgd();
210 void _syncLocalMappingListWithIgd();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400211
212 void pruneMappingsWithInvalidIgds(const std::shared_ptr<IGD>& igd);
213
214 /**
215 * @brief Get the mapping list
216 *
217 * @param type transport type (TCP/UDP)
218 * @return a reference on the map
219 * @warning concurrency protection done by the caller
220 */
221 std::map<Mapping::key_t, Mapping::sharedPtr_t>& getMappingList(PortType type);
222
223 // Get the mapping from the key.
224 Mapping::sharedPtr_t getMappingWithKey(Mapping::key_t key);
225
Adrien Béraud612b55b2023-05-29 10:42:04 -0400226 // Process requests with pending status.
François-Simon Fauteux-Chapleaufd29c1d2024-05-30 16:48:26 -0400227 void processPendingRequests();
Adrien Béraud612b55b2023-05-29 10:42:04 -0400228
229 // Implementation of UpnpMappingObserver interface.
230
231 // Callback used to report changes in IGD status.
232 void onIgdUpdated(const std::shared_ptr<IGD>& igd, UpnpIgdEvent event) override;
233 // Callback used to report add request status.
234 void onMappingAdded(const std::shared_ptr<IGD>& igd, const Mapping& map) override;
235 // Callback invoked when a request fails. Reported on failures for both
François-Simon Fauteux-Chapleaufd29c1d2024-05-30 16:48:26 -0400236 // new requests and renewal requests.
Adrien Béraud612b55b2023-05-29 10:42:04 -0400237 void onMappingRequestFailed(const Mapping& map) override;
François-Simon Fauteux-Chapleaufd29c1d2024-05-30 16:48:26 -0400238
Adrien Béraud612b55b2023-05-29 10:42:04 -0400239 // Callback used to report renew request status.
240 void onMappingRenewed(const std::shared_ptr<IGD>& igd, const Mapping& map) override;
François-Simon Fauteux-Chapleaufd29c1d2024-05-30 16:48:26 -0400241
Adrien Béraud612b55b2023-05-29 10:42:04 -0400242 // Callback used to report remove request status.
243 void onMappingRemoved(const std::shared_ptr<IGD>& igd, const Mapping& map) override;
244
245private:
246 UPnPContext(const UPnPContext&) = delete;
247 UPnPContext(UPnPContext&&) = delete;
248 UPnPContext& operator=(UPnPContext&&) = delete;
249 UPnPContext& operator=(const UPnPContext&) = delete;
250
Adrien Béraudc36965c2023-08-17 21:50:27 -0400251 void _connectivityChanged(const asio::error_code& ec);
252
253 // Thread (io_context), destroyed last
254 std::unique_ptr<std::thread> ioContextRunner_ {};
255
Adrien Béraud612b55b2023-05-29 10:42:04 -0400256 bool started_ {false};
257
258 // The known public address. The external addresses returned by
259 // the IGDs will be checked against this address.
260 IpAddr knownPublicAddress_ {};
François-Simon Fauteux-Chapleaufd29c1d2024-05-30 16:48:26 -0400261 std::mutex publicAddressMutex_;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400262
263 // Map of available protocols.
264 std::map<NatProtocolType, std::shared_ptr<UPnPProtocol>> protocolList_;
265
266 // Port ranges for TCP and UDP (in that order).
267 std::map<PortType, std::pair<uint16_t, uint16_t>> portRange_ {};
268
François-Simon Fauteux-Chapleaufd29c1d2024-05-30 16:48:26 -0400269 // Minimum and maximum limits on the number of available
270 // mappings to keep in the list at any given time
271 static constexpr unsigned minAvailableMappings_[2] {4, 8};
272 static constexpr unsigned maxAvailableMappings_[2] {8, 12};
273 unsigned getMinAvailableMappings(PortType type) {
274 unsigned index = (type == PortType::TCP) ? 0 : 1;
275 return minAvailableMappings_[index];
276 }
277 unsigned getMaxAvailableMappings(PortType type) {
278 unsigned index = (type == PortType::TCP) ? 0 : 1;
279 return maxAvailableMappings_[index];
280 }
Adrien Béraud612b55b2023-05-29 10:42:04 -0400281
Adrien Béraud370257c2023-08-15 20:53:09 -0400282 std::shared_ptr<asio::io_context> ctx;
283 std::shared_ptr<dht::log::Logger> logger_;
Adrien Béraudc36965c2023-08-17 21:50:27 -0400284 asio::steady_timer connectivityChangedTimer_;
François-Simon Fauteux-Chapleaufd29c1d2024-05-30 16:48:26 -0400285 asio::system_timer mappingRenewalTimer_;
286 asio::steady_timer renewalSchedulingTimer_;
287 asio::steady_timer syncTimer_;
288 std::mutex syncMutex_;
289 bool syncRequested_ {false};
Adrien Béraud612b55b2023-05-29 10:42:04 -0400290
François-Simon Fauteux-Chapleaufd29c1d2024-05-30 16:48:26 -0400291 // This mutex must lock only the members below. All other
292 // members must be accessed only from the UPnP context thread.
Adrien Béraud612b55b2023-05-29 10:42:04 -0400293 std::mutex mutable mappingMutex_;
François-Simon Fauteux-Chapleaufd29c1d2024-05-30 16:48:26 -0400294
Adrien Béraud612b55b2023-05-29 10:42:04 -0400295 // List of mappings.
296 std::map<Mapping::key_t, Mapping::sharedPtr_t> mappingList_[2] {};
François-Simon Fauteux-Chapleaufd29c1d2024-05-30 16:48:26 -0400297
298 // Current IGD. Can be null if there is no valid IGD.
299 std::shared_ptr<IGD> currentIgd_;
300
301 // Set of registered controllers
302 std::set<void*> controllerList_;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400303
304 // Shutdown synchronization
305 bool shutdownComplete_ {false};
François-Simon Fauteux-Chapleau808db4f2024-04-19 11:39:47 -0400306 bool shutdownTimedOut_ {false};
Adrien Béraud612b55b2023-05-29 10:42:04 -0400307};
308
309} // namespace upnp
Sébastien Blin464bdff2023-07-19 08:02:53 -0400310} // namespace dhtnet