blob: e29e01d969a9cb12450184697c62485dd1d4c9c4 [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
19#ifdef _WIN32
20#define UPNP_USE_MSVCPP
21#define UPNP_STATIC_LIB
22#endif
23
24#include "../upnp_protocol.h"
25#include "../igd.h"
26#include "upnp_igd.h"
Adrien Béraud370257c2023-08-15 20:53:09 -040027#include "ip_utils.h"
Adrien Béraud612b55b2023-05-29 10:42:04 -040028
François-Simon Fauteux-Chapleau808db4f2024-04-19 11:39:47 -040029#include <opendht/thread_pool.h>
Adrien Béraud612b55b2023-05-29 10:42:04 -040030#include <upnp/upnp.h>
31#include <upnp/upnptools.h>
32
33#ifdef _WIN32
34#include <windows.h>
35#include <wincrypt.h>
36#endif
37
38#include <atomic>
39#include <thread>
40#include <list>
41#include <map>
42#include <set>
43#include <string>
44#include <memory>
45#include <future>
46
Adrien Béraud1ae60aa2023-07-07 09:55:09 -040047namespace dhtnet {
Adrien Béraud612b55b2023-05-29 10:42:04 -040048class IpAddr;
49}
50
Adrien Béraud1ae60aa2023-07-07 09:55:09 -040051namespace dhtnet {
Adrien Béraud612b55b2023-05-29 10:42:04 -040052namespace upnp {
53
54class PUPnP : public UPnPProtocol
55{
56public:
57 using XMLDocument = std::unique_ptr<IXML_Document, decltype(ixmlDocument_free)&>;
58
59 enum class CtrlAction {
60 UNKNOWN,
61 ADD_PORT_MAPPING,
62 DELETE_PORT_MAPPING,
63 GET_GENERIC_PORT_MAPPING_ENTRY,
64 GET_STATUS_INFO,
65 GET_EXTERNAL_IP_ADDRESS
66 };
67
Adrien Béraud370257c2023-08-15 20:53:09 -040068 PUPnP(const std::shared_ptr<asio::io_context>& ctx, const std::shared_ptr<dht::log::Logger>& logger);
Adrien Béraud612b55b2023-05-29 10:42:04 -040069 ~PUPnP();
70
71 // Set the observer
72 void setObserver(UpnpMappingObserver* obs) override;
73
74 // Returns the protocol type.
75 NatProtocolType getProtocol() const override { return NatProtocolType::PUPNP; }
76
77 // Get protocol type as string.
78 char const* getProtocolName() const override { return "PUPNP"; }
79
80 // Notifies a change in network.
81 void clearIgds() override;
82
83 // Sends out async search for IGD.
84 void searchForIgd() override;
85
86 // Get the IGD list.
87 std::list<std::shared_ptr<IGD>> getIgdList() const override;
88
89 // Return true if the it's fully setup.
90 bool isReady() const override;
91
92 // Get from the IGD the list of already allocated mappings if any.
93 std::map<Mapping::key_t, Mapping> getMappingsListByDescr(
94 const std::shared_ptr<IGD>& igd, const std::string& descr) const override;
95
François-Simon Fauteux-Chapleau826f0ba2024-05-29 15:22:21 -040096 // Get information about all existing port mappings on the given IGD
97 std::vector<MappingInfo> getMappingsInfo(const std::shared_ptr<IGD>& igd) const override;
98
Adrien Béraud612b55b2023-05-29 10:42:04 -040099 // Request a new mapping.
100 void requestMappingAdd(const Mapping& mapping) override;
101
102 // Renew an allocated mapping.
103 // Not implemented. Currently, UPNP allocations do not have expiration time.
104 void requestMappingRenew([[maybe_unused]] const Mapping& mapping) override { assert(false); };
105
106 // Removes a mapping.
107 void requestMappingRemove(const Mapping& igdMapping) override;
108
109 // Get the host (local) address.
110 const IpAddr getHostAddress() const override;
111
112 // Terminate the instance.
113 void terminate() override;
114
115private:
Adrien Béraud370257c2023-08-15 20:53:09 -0400116 PUPnP& operator=(const PUPnP&) = delete;
117 PUPnP(const PUPnP&) = delete;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400118
119 void terminate(std::condition_variable& cv);
120
121 // Init lib-upnp
122 void initUpnpLib();
123
124 // Return true if running.
125 bool isRunning() const;
126
127 // Register the client
128 void registerClient();
129
François-Simon Fauteux-Chapleaud7976982024-04-26 16:06:23 -0400130 // Unregister the client
131 void unregisterClient();
132
Adrien Béraud612b55b2023-05-29 10:42:04 -0400133 // Start search for UPNP devices
134 void searchForDevices();
135
136 // Return true if it has at least one valid IGD.
137 bool hasValidIgd() const;
138
139 // Update the host (local) address.
140 void updateHostAddress();
141
142 // Check the host (local) address.
143 // Returns true if the address is valid.
144 bool hasValidHostAddress();
145
146 // Delete mappings matching the description
147 void deleteMappingsByDescription(const std::shared_ptr<IGD>& igd,
148 const std::string& description);
149
150 // Search for the IGD in the local list of known IGDs.
151 std::shared_ptr<UPnPIGD> findMatchingIgd(const std::string& ctrlURL) const;
152
153 // Process the reception of an add mapping action answer.
154 void processAddMapAction(const Mapping& map);
155
156 // Process the a mapping request failure.
157 void processRequestMappingFailure(const Mapping& map);
158
159 // Process the reception of a remove mapping action answer.
160 void processRemoveMapAction(const Mapping& map);
161
162 // Increment IGD errors counter.
163 void incrementErrorsCounter(const std::shared_ptr<IGD>& igd);
164
165 // Download XML document.
166 void downLoadIgdDescription(const std::string& url);
167
168 // Validate IGD from the xml document received from the router.
169 bool validateIgd(const std::string& location, IXML_Document* doc_container_ptr);
170
171 // Returns control point action callback based on xml node.
172 static CtrlAction getAction(const char* xmlNode);
173
174 // Control point callback.
175 static int ctrlPtCallback(Upnp_EventType event_type, const void* event, void* user_data);
176#if UPNP_VERSION < 10800
177 static inline int ctrlPtCallback(Upnp_EventType event_type, void* event, void* user_data)
178 {
179 return ctrlPtCallback(event_type, (const void*) event, user_data);
180 };
181#endif
182 // Process IGD responses.
183 void processDiscoverySearchResult(const std::string& deviceId,
184 const std::string& igdUrl,
185 const IpAddr& dstAddr);
186 void processDiscoveryAdvertisementByebye(const std::string& deviceId);
187 void processDiscoverySubscriptionExpired(Upnp_EventType event_type,
188 const std::string& eventSubUrl);
189
190 // Callback event handler function for the UPnP client (control point).
191 int handleCtrlPtUPnPEvents(Upnp_EventType event_type, const void* event);
192
193 // Subscription event callback.
194 static int subEventCallback(Upnp_EventType event_type, const void* event, void* user_data);
195#if UPNP_VERSION < 10800
196 static inline int subEventCallback(Upnp_EventType event_type, void* event, void* user_data)
197 {
198 return subEventCallback(event_type, (const void*) event, user_data);
199 };
200#endif
201
202 // Callback subscription event function for handling subscription request.
203 int handleSubscriptionUPnPEvent(Upnp_EventType event_type, const void* event);
204
205 // Parses the IGD candidate.
206 std::unique_ptr<UPnPIGD> parseIgd(IXML_Document* doc, std::string locationUrl);
207
208 // These functions directly create UPnP actions and make synchronous UPnP
209 // control point calls. Must be run on the PUPNP internal execution queue.
210 bool actionIsIgdConnected(const UPnPIGD& igd);
211 IpAddr actionGetExternalIP(const UPnPIGD& igd);
212 bool actionAddPortMapping(const Mapping& mapping);
213 bool actionDeletePortMapping(const Mapping& mapping);
214
215 // Event type to string
216 static const char* eventTypeToString(Upnp_EventType eventType);
217
218 std::weak_ptr<PUPnP> weak() { return std::static_pointer_cast<PUPnP>(shared_from_this()); }
219
Adrien Béraud612b55b2023-05-29 10:42:04 -0400220 // Initialization status.
221 std::atomic_bool initialized_ {false};
222 // Client registration status.
223 std::atomic_bool clientRegistered_ {false};
224
Adrien Béraud370257c2023-08-15 20:53:09 -0400225 std::shared_ptr<asio::io_context> ioContext;
226 asio::steady_timer searchForIgdTimer_;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400227 unsigned int igdSearchCounter_ {0};
228
229 // List of discovered IGDs.
230 std::set<std::string> discoveredIgdList_;
231
232 // Control point handle.
233 UpnpClient_Handle ctrlptHandle_ {-1};
234
235 // Observer to report the results.
236 UpnpMappingObserver* observer_ {nullptr};
237
238 // List of valid IGDs.
239 std::list<std::shared_ptr<IGD>> validIgdList_;
240
241 // Current host address.
242 IpAddr hostAddress_ {};
243
244 // Calls from other threads that does not need synchronous access are
245 // rescheduled on the UPNP private queue. This will avoid the need to
246 // protect most of the data members of this class.
247 // For some internal members (namely the validIgdList and the hostAddress)
248 // that need to be synchronously accessed, are protected by this mutex.
249 mutable std::mutex pupnpMutex_;
250
251 // Shutdown synchronization
252 bool shutdownComplete_ {false};
Sébastien Blind14fc352023-10-06 15:21:53 -0400253
254 // Count ongoing operations
255 std::mutex ongoingOpsMtx_;
Sébastien Blind14fc352023-10-06 15:21:53 -0400256 int ongoingOps_ {0};
257 bool destroying_ {false};
François-Simon Fauteux-Chapleau808db4f2024-04-19 11:39:47 -0400258 dht::ThreadPool ongoingOpsThreadPool_;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400259};
260
261} // namespace upnp
Sébastien Blin464bdff2023-07-19 08:02:53 -0400262} // namespace dhtnet