blob: 03086ddc1f5ec09cd8106bebc1f60439104b96e3 [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
127 // Start search for UPNP devices
128 void searchForDevices();
129
130 // Return true if it has at least one valid IGD.
131 bool hasValidIgd() const;
132
133 // Update the host (local) address.
134 void updateHostAddress();
135
136 // Check the host (local) address.
137 // Returns true if the address is valid.
138 bool hasValidHostAddress();
139
140 // Delete mappings matching the description
141 void deleteMappingsByDescription(const std::shared_ptr<IGD>& igd,
142 const std::string& description);
143
144 // Search for the IGD in the local list of known IGDs.
145 std::shared_ptr<UPnPIGD> findMatchingIgd(const std::string& ctrlURL) const;
146
147 // Process the reception of an add mapping action answer.
148 void processAddMapAction(const Mapping& map);
149
150 // Process the a mapping request failure.
151 void processRequestMappingFailure(const Mapping& map);
152
153 // Process the reception of a remove mapping action answer.
154 void processRemoveMapAction(const Mapping& map);
155
156 // Increment IGD errors counter.
157 void incrementErrorsCounter(const std::shared_ptr<IGD>& igd);
158
159 // Download XML document.
160 void downLoadIgdDescription(const std::string& url);
161
162 // Validate IGD from the xml document received from the router.
163 bool validateIgd(const std::string& location, IXML_Document* doc_container_ptr);
164
165 // Returns control point action callback based on xml node.
166 static CtrlAction getAction(const char* xmlNode);
167
168 // Control point callback.
169 static int ctrlPtCallback(Upnp_EventType event_type, const void* event, void* user_data);
170#if UPNP_VERSION < 10800
171 static inline int ctrlPtCallback(Upnp_EventType event_type, void* event, void* user_data)
172 {
173 return ctrlPtCallback(event_type, (const void*) event, user_data);
174 };
175#endif
176 // Process IGD responses.
177 void processDiscoverySearchResult(const std::string& deviceId,
178 const std::string& igdUrl,
179 const IpAddr& dstAddr);
180 void processDiscoveryAdvertisementByebye(const std::string& deviceId);
181 void processDiscoverySubscriptionExpired(Upnp_EventType event_type,
182 const std::string& eventSubUrl);
183
184 // Callback event handler function for the UPnP client (control point).
185 int handleCtrlPtUPnPEvents(Upnp_EventType event_type, const void* event);
186
187 // Subscription event callback.
188 static int subEventCallback(Upnp_EventType event_type, const void* event, void* user_data);
189#if UPNP_VERSION < 10800
190 static inline int subEventCallback(Upnp_EventType event_type, void* event, void* user_data)
191 {
192 return subEventCallback(event_type, (const void*) event, user_data);
193 };
194#endif
195
196 // Callback subscription event function for handling subscription request.
197 int handleSubscriptionUPnPEvent(Upnp_EventType event_type, const void* event);
198
199 // Parses the IGD candidate.
200 std::unique_ptr<UPnPIGD> parseIgd(IXML_Document* doc, std::string locationUrl);
201
202 // These functions directly create UPnP actions and make synchronous UPnP
203 // control point calls. Must be run on the PUPNP internal execution queue.
204 bool actionIsIgdConnected(const UPnPIGD& igd);
205 IpAddr actionGetExternalIP(const UPnPIGD& igd);
206 bool actionAddPortMapping(const Mapping& mapping);
207 bool actionDeletePortMapping(const Mapping& mapping);
208
209 // Event type to string
210 static const char* eventTypeToString(Upnp_EventType eventType);
211
212 std::weak_ptr<PUPnP> weak() { return std::static_pointer_cast<PUPnP>(shared_from_this()); }
213
Adrien Béraud612b55b2023-05-29 10:42:04 -0400214 // Initialization status.
215 std::atomic_bool initialized_ {false};
216 // Client registration status.
217 std::atomic_bool clientRegistered_ {false};
218
Adrien Béraud370257c2023-08-15 20:53:09 -0400219 std::shared_ptr<asio::io_context> ioContext;
220 asio::steady_timer searchForIgdTimer_;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400221 unsigned int igdSearchCounter_ {0};
222
223 // List of discovered IGDs.
224 std::set<std::string> discoveredIgdList_;
225
226 // Control point handle.
227 UpnpClient_Handle ctrlptHandle_ {-1};
228
229 // Observer to report the results.
230 UpnpMappingObserver* observer_ {nullptr};
231
232 // List of valid IGDs.
233 std::list<std::shared_ptr<IGD>> validIgdList_;
234
235 // Current host address.
236 IpAddr hostAddress_ {};
237
238 // Calls from other threads that does not need synchronous access are
239 // rescheduled on the UPNP private queue. This will avoid the need to
240 // protect most of the data members of this class.
241 // For some internal members (namely the validIgdList and the hostAddress)
242 // that need to be synchronously accessed, are protected by this mutex.
243 mutable std::mutex pupnpMutex_;
244
245 // Shutdown synchronization
246 bool shutdownComplete_ {false};
Sébastien Blind14fc352023-10-06 15:21:53 -0400247
248 // Count ongoing operations
249 std::mutex ongoingOpsMtx_;
Sébastien Blind14fc352023-10-06 15:21:53 -0400250 int ongoingOps_ {0};
251 bool destroying_ {false};
François-Simon Fauteux-Chapleau808db4f2024-04-19 11:39:47 -0400252 dht::ThreadPool ongoingOpsThreadPool_;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400253};
254
255} // namespace upnp
Sébastien Blin464bdff2023-07-19 08:02:53 -0400256} // namespace dhtnet