blob: b03c345fe8666c6e89da42050b52e96dce72bb7c [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
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17#pragma once
18
19#include "ice_options.h"
20#include "multiplexed_socket.h"
Sébastien Blin34086512023-07-25 09:52:14 -040021#include "ice_transport_factory.h"
Sébastien Blin84bf4182023-07-21 14:18:39 -040022#include "turn_cache.h"
Adrien Béraud612b55b2023-05-29 10:42:04 -040023
24#include <opendht/dhtrunner.h>
25#include <opendht/infohash.h>
26#include <opendht/value.h>
27#include <opendht/default_types.h>
28#include <opendht/sockaddr.h>
29#include <opendht/logger.h>
30
31#include <memory>
32#include <vector>
33#include <string>
34
Adrien Béraud1ae60aa2023-07-07 09:55:09 -040035namespace dhtnet {
Adrien Béraud612b55b2023-05-29 10:42:04 -040036
37class ChannelSocket;
38class ConnectionManager;
39namespace upnp {
40class Controller;
41}
42namespace tls {
43class CertificateStore;
44}
Amna31791e52023-08-03 12:40:57 -040045enum class ConnectionStatus : int { Connected, TLS, ICE, Connecting, Waiting };
Adrien Béraud612b55b2023-05-29 10:42:04 -040046
47/**
48 * A PeerConnectionRequest is a request which ask for an initial connection
49 * It contains the ICE request an ID and if it's an answer
50 * Transmitted via the UDP DHT
51 */
52struct PeerConnectionRequest : public dht::EncryptedValue<PeerConnectionRequest>
53{
54 static const constexpr dht::ValueType& TYPE = dht::ValueType::USER_DATA;
55 static constexpr const char* key_prefix = "peer:"; ///< base to compute the DHT listen key
56 dht::Value::Id id = dht::Value::INVALID_ID;
57 std::string ice_msg {};
58 bool isAnswer {false};
59 std::string connType {}; // Used for push notifications to know why we open a new connection
60 MSGPACK_DEFINE_MAP(id, ice_msg, isAnswer, connType)
61};
62
63/**
64 * Used to accept or not an incoming ICE connection (default accept)
65 */
66using onICERequestCallback = std::function<bool(const DeviceId&)>;
67/**
68 * Used to accept or decline an incoming channel request
69 */
70using ChannelRequestCallback = std::function<bool(const std::shared_ptr<dht::crypto::Certificate>&,
71 const std::string& /* name */)>;
72/**
73 * Used by connectDevice, when the socket is ready
74 */
75using ConnectCallback = std::function<void(const std::shared_ptr<ChannelSocket>&, const DeviceId&)>;
Amna0cf544d2023-07-25 14:25:09 -040076using ConnectCallbackLegacy = std::function<void(const std::shared_ptr<ChannelSocket>&, const dht::InfoHash&)>;
77
Adrien Béraud612b55b2023-05-29 10:42:04 -040078/**
79 * Used when an incoming connection is ready
80 */
81using ConnectionReadyCallback = std::function<
82 void(const DeviceId&, const std::string& /* channel_name */, std::shared_ptr<ChannelSocket>)>;
83
84using iOSConnectedCallback
85 = std::function<bool(const std::string& /* connType */, dht::InfoHash /* peer_h */)>;
86
87/**
88 * Manages connections to other devices
89 * @note the account MUST be valid if ConnectionManager lives
90 */
91class ConnectionManager
92{
93public:
Adrien Béraudc8cd2c72023-07-21 13:15:58 -040094 struct Config;
Adrien Béraud612b55b2023-05-29 10:42:04 -040095
96 ConnectionManager(std::shared_ptr<Config> config_);
97 ~ConnectionManager();
98
99 /**
100 * Open a new channel between the account's device and another device
101 * This method will send a message on the account's DHT, wait a reply
102 * and then, create a Tls socket with remote peer.
103 * @param deviceId Remote device
104 * @param name Name of the channel
105 * @param cb Callback called when socket is ready ready
106 * @param noNewSocket Do not negotiate a new socket if there is none
107 * @param forceNewSocket Negotiate a new socket even if there is one // todo group with previous
108 * (enum)
109 * @param connType Type of the connection
110 */
111 void connectDevice(const DeviceId& deviceId,
112 const std::string& name,
113 ConnectCallback cb,
114 bool noNewSocket = false,
115 bool forceNewSocket = false,
116 const std::string& connType = "");
Amna0cf544d2023-07-25 14:25:09 -0400117 void connectDevice(const dht::InfoHash& deviceId,
118 const std::string& name,
119 ConnectCallbackLegacy cb,
120 bool noNewSocket = false,
121 bool forceNewSocket = false,
122 const std::string& connType = "");
123
Adrien Béraud612b55b2023-05-29 10:42:04 -0400124 void connectDevice(const std::shared_ptr<dht::crypto::Certificate>& cert,
125 const std::string& name,
126 ConnectCallback cb,
127 bool noNewSocket = false,
128 bool forceNewSocket = false,
129 const std::string& connType = "");
130
131 /**
132 * Check if we are already connecting to a device with a specific name
133 * @param deviceId Remote device
134 * @param name Name of the channel
135 * @return if connecting
136 * @note isConnecting is not true just after connectDevice() as connectDevice is full async
137 */
138 bool isConnecting(const DeviceId& deviceId, const std::string& name) const;
139
140 /**
141 * Close all connections with a current device
142 * @param peerUri Peer URI
143 */
144 void closeConnectionsWith(const std::string& peerUri);
145
146 /**
147 * Method to call to listen to incoming requests
148 * @param deviceId Account's device
149 */
150 void onDhtConnected(const dht::crypto::PublicKey& devicePk);
151
152 /**
153 * Add a callback to decline or accept incoming ICE connections
154 * @param cb Callback to trigger
155 */
156 void onICERequest(onICERequestCallback&& cb);
157
158 /**
159 * Trigger cb on incoming peer channel
160 * @param cb Callback to trigger
161 * @note The callback is used to validate
162 * if the incoming request is accepted or not.
163 */
164 void onChannelRequest(ChannelRequestCallback&& cb);
165
166 /**
167 * Trigger cb when connection with peer is ready
168 * @param cb Callback to trigger
169 */
170 void onConnectionReady(ConnectionReadyCallback&& cb);
171
172 /**
173 * Trigger cb when connection with peer is ready for iOS devices
174 * @param cb Callback to trigger
175 */
176 void oniOSConnected(iOSConnectedCallback&& cb);
177
178 /**
179 * @return the number of active sockets
180 */
181 std::size_t activeSockets() const;
182
183 /**
184 * Log informations for all sockets
185 */
186 void monitor() const;
187
188 /**
189 * Send beacon on peers supporting it
190 */
191 void connectivityChanged();
192
193 /**
194 * Create and return ICE options.
195 */
196 void getIceOptions(std::function<void(IceTransportOptions&&)> cb) noexcept;
197 IceTransportOptions getIceOptions() const noexcept;
198
199 /**
200 * Get the published IP address, fallbacks to NAT if family is unspecified
201 * Prefers the usage of IPv4 if possible.
202 */
203 IpAddr getPublishedIpAddress(uint16_t family = PF_UNSPEC) const;
204
205 /**
206 * Set published IP address according to given family
207 */
208 void setPublishedAddress(const IpAddr& ip_addr);
209
210 /**
211 * Store the local/public addresses used to register
212 */
213 void storeActiveIpAddress(std::function<void()>&& cb = {});
214
Amna31791e52023-08-03 12:40:57 -0400215 /**
216 * Retrieve the list of connections.
217 *
218 * @param device The device ID to filter the connections (optional).
219 * @return The list of connections as a vector of maps, where each map represents a connection.
220 *
221 * Note: The connections are represented as maps with string keys and string values. The map
222 * contains the following key-value pairs:
223 * - "id": The unique identifier of the connection.
Amna6c999d82023-08-15 15:19:41 -0400224 * - "peer": The contact URI associated with the connection (if available).
225 * - "device": The device URI associated with the connection.
Amna31791e52023-08-03 12:40:57 -0400226 * - "status": The status of the connection, represented as an integer:
227 * - 0: ConnectionStatus::Connected
228 * - 1: ConnectionStatus::TLS
229 * - 2: ConnectionStatus::ICE
230 * - 3: ConnectionStatus::Connecting (for pending operations)
231 * - 4: ConnectionStatus::Waiting (for pending operations)
232 * - "remoteAddress": The remote IP address of the connection (if available).
233 * - "remotePort": The remote port of the connection (if available).
234 *
235 * If a specific device ID is provided, the returned list will only include connections
236 * associated with that device. Otherwise, connections from all devices will be included.
237 */
238 std::vector<std::map<std::string, std::string>> getConnectionList(
239 const DeviceId& device = {}) const;
240
241 /**
242 * Retrieve the list of channels associated with a connection.
243 *
244 * @param connectionId The ID of the connection to fetch the channels from.
245 * @return The list of channels as a vector of maps, where each map represents a channel
246 * and contains key-value pairs of channel ID and channel name.
247 *
248 * If the specified connection ID is valid and associated with a connection,
249 * the method returns the list of channels associated with that connection.
250 * Otherwise, an empty vector is returned.
251 */
252 std::vector<std::map<std::string, std::string>> getChannelList(
253 const std::string& connectionId) const;
254
255
Adrien Béraud612b55b2023-05-29 10:42:04 -0400256 std::shared_ptr<Config> getConfig();
257
258private:
259 ConnectionManager() = delete;
260 class Impl;
261 std::shared_ptr<Impl> pimpl_;
262};
263
264struct ConnectionManager::Config
265{
266 /**
267 * Determine if STUN public address resolution is required to register this account. In this
268 * case a STUN server hostname must be specified.
269 */
270 bool stunEnabled {false};
271
272 /**
273 * The STUN server hostname (optional), used to provide the public IP address in case the
274 * softphone stay behind a NAT.
275 */
276 std::string stunServer {};
277
278 /**
279 * Determine if TURN public address resolution is required to register this account. In this
280 * case a TURN server hostname must be specified.
281 */
282 bool turnEnabled {false};
283
284 /**
285 * The TURN server hostname (optional), used to provide the public IP address in case the
286 * softphone stay behind a NAT.
287 */
288 std::string turnServer;
289 std::string turnServerUserName;
290 std::string turnServerPwd;
291 std::string turnServerRealm;
292
Sébastien Blin84bf4182023-07-21 14:18:39 -0400293 std::shared_ptr<TurnCache> turnCache;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400294
295 std::string cachePath {};
296
297 std::shared_ptr<asio::io_context> ioContext;
298 std::shared_ptr<dht::DhtRunner> dht;
299 dht::crypto::Identity id;
300
301 tls::CertificateStore* certStore;
302
Sébastien Blin34086512023-07-25 09:52:14 -0400303 dhtnet::IceTransportFactory* factory;
304
Adrien Béraud612b55b2023-05-29 10:42:04 -0400305 /**
306 * UPnP IGD controller and the mutex to access it
Sébastien Blin464bdff2023-07-19 08:02:53 -0400307 */
Adrien Béraud612b55b2023-05-29 10:42:04 -0400308 bool upnpEnabled;
Adrien Béraud1ae60aa2023-07-07 09:55:09 -0400309 std::shared_ptr<dhtnet::upnp::Controller> upnpCtrl;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400310
311 std::shared_ptr<dht::log::Logger> logger;
312
313 /**
314 * returns whether or not UPnP is enabled and active
315 * ie: if it is able to make port mappings
316 */
317 bool getUPnPActive() const;
Amna31791e52023-08-03 12:40:57 -0400318
Adrien Béraud612b55b2023-05-29 10:42:04 -0400319};
320
Sébastien Blin464bdff2023-07-19 08:02:53 -0400321} // namespace dhtnet