blob: ead135f2179b85e7807ab35fdf0988ed2dda7792 [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
Morteza Namvar5f639522023-07-04 17:08:58 -040019/*#include "upnp_protocol.h"
Adrien Béraud612b55b2023-05-29 10:42:04 -040020#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 Namvar5f639522023-07-04 17:08:58 -040026#include "igd.h"*/
Adrien Béraud612b55b2023-05-29 10:42:04 -040027
Adrien Bérauddbb06862023-07-08 09:18:39 -040028#include "../ip_utils.h"
Adrien Béraud612b55b2023-05-29 10:42:04 -040029
Adrien Bérauddbb06862023-07-08 09:18:39 -040030#include "mapping.h"
Morteza Namvar5f639522023-07-04 17:08:58 -040031
Adrien Béraud612b55b2023-05-29 10:42:04 -040032#include <opendht/rng.h>
Adrien Béraud25c30c42023-07-05 13:46:54 -040033#include <opendht/logger.h>
Adrien Béraud612b55b2023-05-29 10:42:04 -040034#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 Namvar5f639522023-07-04 17:08:58 -040044#include <condition_variable>
Adrien Béraud612b55b2023-05-29 10:42:04 -040045
Morteza Namvar5f639522023-07-04 17:08:58 -040046#include <cstdlib>
Adrien Béraud612b55b2023-05-29 10:42:04 -040047
Adrien Béraud612b55b2023-05-29 10:42:04 -040048using IgdFoundCallback = std::function<void()>;
49
Adrien Béraud1ae60aa2023-07-07 09:55:09 -040050namespace dhtnet {
Adrien Béraud612b55b2023-05-29 10:42:04 -040051class IpAddr;
52}
53
Adrien Béraud1ae60aa2023-07-07 09:55:09 -040054namespace dhtnet {
Adrien Béraud612b55b2023-05-29 10:42:04 -040055namespace upnp {
56
Morteza Namvar5f639522023-07-04 17:08:58 -040057class UPnPProtocol;
58class IGD;
59
60enum 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.
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;
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éraud370257c2023-08-15 20:53:09 -040082class UPnPContext : public UpnpMappingObserver
Adrien Béraud612b55b2023-05-29 10:42:04 -040083{
84private:
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
104public:
Sébastien Blin55abf072023-07-19 10:21:21 -0400105 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 -0400106 ~UPnPContext();
107
Adrien Béraudb04fbd72023-08-17 19:56:11 -0400108 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éraud612b55b2023-05-29 10:42:04 -0400110 // 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 Berauda8731ac2023-08-17 12:19:39 -0400139 template <typename T>
140 inline void dispatch(T&& f) {
141 ctx->dispatch(std::move(f));
142 }
143
Adrien Béraud612b55b2023-05-29 10:42:04 -0400144private:
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éraud612b55b2023-05-29 10:42:04 -0400170 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 Beraud3bd61c92023-08-17 16:57:37 -0400181 // 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éraud612b55b2023-05-29 10:42:04 -0400186 // 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
272private:
273 UPnPContext(const UPnPContext&) = delete;
274 UPnPContext(UPnPContext&&) = delete;
275 UPnPContext& operator=(UPnPContext&&) = delete;
276 UPnPContext& operator=(const UPnPContext&) = delete;
277
Adrien Béraudc36965c2023-08-17 21:50:27 -0400278 void _connectivityChanged(const asio::error_code& ec);
279
280 // Thread (io_context), destroyed last
281 std::unique_ptr<std::thread> ioContextRunner_ {};
282
Adrien Béraud612b55b2023-05-29 10:42:04 -0400283 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éraudc36965c2023-08-17 21:50:27 -0400290 std::mutex mutable controllerMutex_;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400291 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éraud370257c2023-08-15 20:53:09 -0400304 std::shared_ptr<asio::io_context> ctx;
305 std::shared_ptr<dht::log::Logger> logger_;
Adrien Berauda8731ac2023-08-17 12:19:39 -0400306 asio::steady_timer mappingListUpdateTimer_;
Adrien Béraudc36965c2023-08-17 21:50:27 -0400307 asio::steady_timer connectivityChangedTimer_;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400308
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};
321};
322
323} // namespace upnp
Sébastien Blin464bdff2023-07-19 08:02:53 -0400324} // namespace dhtnet