blob: 5bba6dcf6d16d2bdf07a2251f83a6bce8cac2640 [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
96 // Request a new mapping.
97 void requestMappingAdd(const Mapping& mapping) override;
98
99 // Renew an allocated mapping.
100 // Not implemented. Currently, UPNP allocations do not have expiration time.
101 void requestMappingRenew([[maybe_unused]] const Mapping& mapping) override { assert(false); };
102
103 // Removes a mapping.
104 void requestMappingRemove(const Mapping& igdMapping) override;
105
106 // Get the host (local) address.
107 const IpAddr getHostAddress() const override;
108
109 // Terminate the instance.
110 void terminate() override;
111
112private:
Adrien Béraud370257c2023-08-15 20:53:09 -0400113 PUPnP& operator=(const PUPnP&) = delete;
114 PUPnP(const PUPnP&) = delete;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400115
116 void terminate(std::condition_variable& cv);
117
118 // Init lib-upnp
119 void initUpnpLib();
120
121 // Return true if running.
122 bool isRunning() const;
123
124 // Register the client
125 void registerClient();
126
François-Simon Fauteux-Chapleaud7976982024-04-26 16:06:23 -0400127 // Unregister the client
128 void unregisterClient();
129
Adrien Béraud612b55b2023-05-29 10:42:04 -0400130 // Start search for UPNP devices
131 void searchForDevices();
132
133 // Return true if it has at least one valid IGD.
134 bool hasValidIgd() const;
135
136 // Update the host (local) address.
137 void updateHostAddress();
138
139 // Check the host (local) address.
140 // Returns true if the address is valid.
141 bool hasValidHostAddress();
142
143 // Delete mappings matching the description
144 void deleteMappingsByDescription(const std::shared_ptr<IGD>& igd,
145 const std::string& description);
146
147 // Search for the IGD in the local list of known IGDs.
148 std::shared_ptr<UPnPIGD> findMatchingIgd(const std::string& ctrlURL) const;
149
150 // Process the reception of an add mapping action answer.
151 void processAddMapAction(const Mapping& map);
152
153 // Process the a mapping request failure.
154 void processRequestMappingFailure(const Mapping& map);
155
156 // Process the reception of a remove mapping action answer.
157 void processRemoveMapAction(const Mapping& map);
158
159 // Increment IGD errors counter.
160 void incrementErrorsCounter(const std::shared_ptr<IGD>& igd);
161
162 // Download XML document.
163 void downLoadIgdDescription(const std::string& url);
164
165 // Validate IGD from the xml document received from the router.
166 bool validateIgd(const std::string& location, IXML_Document* doc_container_ptr);
167
168 // Returns control point action callback based on xml node.
169 static CtrlAction getAction(const char* xmlNode);
170
171 // Control point callback.
172 static int ctrlPtCallback(Upnp_EventType event_type, const void* event, void* user_data);
173#if UPNP_VERSION < 10800
174 static inline int ctrlPtCallback(Upnp_EventType event_type, void* event, void* user_data)
175 {
176 return ctrlPtCallback(event_type, (const void*) event, user_data);
177 };
178#endif
179 // Process IGD responses.
180 void processDiscoverySearchResult(const std::string& deviceId,
181 const std::string& igdUrl,
182 const IpAddr& dstAddr);
183 void processDiscoveryAdvertisementByebye(const std::string& deviceId);
184 void processDiscoverySubscriptionExpired(Upnp_EventType event_type,
185 const std::string& eventSubUrl);
186
187 // Callback event handler function for the UPnP client (control point).
188 int handleCtrlPtUPnPEvents(Upnp_EventType event_type, const void* event);
189
190 // Subscription event callback.
191 static int subEventCallback(Upnp_EventType event_type, const void* event, void* user_data);
192#if UPNP_VERSION < 10800
193 static inline int subEventCallback(Upnp_EventType event_type, void* event, void* user_data)
194 {
195 return subEventCallback(event_type, (const void*) event, user_data);
196 };
197#endif
198
199 // Callback subscription event function for handling subscription request.
200 int handleSubscriptionUPnPEvent(Upnp_EventType event_type, const void* event);
201
202 // Parses the IGD candidate.
203 std::unique_ptr<UPnPIGD> parseIgd(IXML_Document* doc, std::string locationUrl);
204
205 // These functions directly create UPnP actions and make synchronous UPnP
206 // control point calls. Must be run on the PUPNP internal execution queue.
207 bool actionIsIgdConnected(const UPnPIGD& igd);
208 IpAddr actionGetExternalIP(const UPnPIGD& igd);
209 bool actionAddPortMapping(const Mapping& mapping);
210 bool actionDeletePortMapping(const Mapping& mapping);
211
212 // Event type to string
213 static const char* eventTypeToString(Upnp_EventType eventType);
214
215 std::weak_ptr<PUPnP> weak() { return std::static_pointer_cast<PUPnP>(shared_from_this()); }
216
Adrien Béraud612b55b2023-05-29 10:42:04 -0400217 // Initialization status.
218 std::atomic_bool initialized_ {false};
219 // Client registration status.
220 std::atomic_bool clientRegistered_ {false};
221
Adrien Béraud370257c2023-08-15 20:53:09 -0400222 std::shared_ptr<asio::io_context> ioContext;
223 asio::steady_timer searchForIgdTimer_;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400224 unsigned int igdSearchCounter_ {0};
225
226 // List of discovered IGDs.
227 std::set<std::string> discoveredIgdList_;
228
229 // Control point handle.
230 UpnpClient_Handle ctrlptHandle_ {-1};
231
232 // Observer to report the results.
233 UpnpMappingObserver* observer_ {nullptr};
234
235 // List of valid IGDs.
236 std::list<std::shared_ptr<IGD>> validIgdList_;
237
238 // Current host address.
239 IpAddr hostAddress_ {};
240
241 // Calls from other threads that does not need synchronous access are
242 // rescheduled on the UPNP private queue. This will avoid the need to
243 // protect most of the data members of this class.
244 // For some internal members (namely the validIgdList and the hostAddress)
245 // that need to be synchronously accessed, are protected by this mutex.
246 mutable std::mutex pupnpMutex_;
247
248 // Shutdown synchronization
249 bool shutdownComplete_ {false};
Sébastien Blind14fc352023-10-06 15:21:53 -0400250
251 // Count ongoing operations
252 std::mutex ongoingOpsMtx_;
Sébastien Blind14fc352023-10-06 15:21:53 -0400253 int ongoingOps_ {0};
254 bool destroying_ {false};
François-Simon Fauteux-Chapleau808db4f2024-04-19 11:39:47 -0400255 dht::ThreadPool ongoingOpsThreadPool_;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400256};
257
258} // namespace upnp
Sébastien Blin464bdff2023-07-19 08:02:53 -0400259} // namespace dhtnet