blob: e11c27a46da2b78f8372f65042372651d4f43980 [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_);
Amna81221ad2023-09-14 17:33:26 -040097 ConnectionManager(dht::crypto::Identity id);
98
Adrien Béraud612b55b2023-05-29 10:42:04 -040099 ~ConnectionManager();
100
101 /**
102 * Open a new channel between the account's device and another device
103 * This method will send a message on the account's DHT, wait a reply
104 * and then, create a Tls socket with remote peer.
105 * @param deviceId Remote device
106 * @param name Name of the channel
107 * @param cb Callback called when socket is ready ready
108 * @param noNewSocket Do not negotiate a new socket if there is none
109 * @param forceNewSocket Negotiate a new socket even if there is one // todo group with previous
110 * (enum)
111 * @param connType Type of the connection
112 */
113 void connectDevice(const DeviceId& deviceId,
114 const std::string& name,
115 ConnectCallback cb,
116 bool noNewSocket = false,
117 bool forceNewSocket = false,
118 const std::string& connType = "");
Amna0cf544d2023-07-25 14:25:09 -0400119 void connectDevice(const dht::InfoHash& deviceId,
120 const std::string& name,
121 ConnectCallbackLegacy cb,
122 bool noNewSocket = false,
123 bool forceNewSocket = false,
124 const std::string& connType = "");
125
Adrien Béraud612b55b2023-05-29 10:42:04 -0400126 void connectDevice(const std::shared_ptr<dht::crypto::Certificate>& cert,
127 const std::string& name,
128 ConnectCallback cb,
129 bool noNewSocket = false,
130 bool forceNewSocket = false,
131 const std::string& connType = "");
132
133 /**
134 * Check if we are already connecting to a device with a specific name
135 * @param deviceId Remote device
136 * @param name Name of the channel
137 * @return if connecting
138 * @note isConnecting is not true just after connectDevice() as connectDevice is full async
139 */
140 bool isConnecting(const DeviceId& deviceId, const std::string& name) const;
141
142 /**
143 * Close all connections with a current device
144 * @param peerUri Peer URI
145 */
146 void closeConnectionsWith(const std::string& peerUri);
147
148 /**
149 * Method to call to listen to incoming requests
150 * @param deviceId Account's device
151 */
152 void onDhtConnected(const dht::crypto::PublicKey& devicePk);
153
154 /**
155 * Add a callback to decline or accept incoming ICE connections
156 * @param cb Callback to trigger
157 */
158 void onICERequest(onICERequestCallback&& cb);
159
160 /**
161 * Trigger cb on incoming peer channel
162 * @param cb Callback to trigger
163 * @note The callback is used to validate
164 * if the incoming request is accepted or not.
165 */
166 void onChannelRequest(ChannelRequestCallback&& cb);
167
168 /**
169 * Trigger cb when connection with peer is ready
170 * @param cb Callback to trigger
171 */
172 void onConnectionReady(ConnectionReadyCallback&& cb);
173
174 /**
175 * Trigger cb when connection with peer is ready for iOS devices
176 * @param cb Callback to trigger
177 */
178 void oniOSConnected(iOSConnectedCallback&& cb);
179
180 /**
181 * @return the number of active sockets
182 */
183 std::size_t activeSockets() const;
184
185 /**
186 * Log informations for all sockets
187 */
188 void monitor() const;
189
190 /**
191 * Send beacon on peers supporting it
192 */
193 void connectivityChanged();
194
195 /**
196 * Create and return ICE options.
197 */
198 void getIceOptions(std::function<void(IceTransportOptions&&)> cb) noexcept;
199 IceTransportOptions getIceOptions() const noexcept;
200
201 /**
202 * Get the published IP address, fallbacks to NAT if family is unspecified
203 * Prefers the usage of IPv4 if possible.
204 */
205 IpAddr getPublishedIpAddress(uint16_t family = PF_UNSPEC) const;
206
207 /**
208 * Set published IP address according to given family
209 */
210 void setPublishedAddress(const IpAddr& ip_addr);
211
212 /**
213 * Store the local/public addresses used to register
214 */
215 void storeActiveIpAddress(std::function<void()>&& cb = {});
216
Amna31791e52023-08-03 12:40:57 -0400217 /**
218 * Retrieve the list of connections.
219 *
220 * @param device The device ID to filter the connections (optional).
221 * @return The list of connections as a vector of maps, where each map represents a connection.
222 *
223 * Note: The connections are represented as maps with string keys and string values. The map
224 * contains the following key-value pairs:
225 * - "id": The unique identifier of the connection.
Amna6c999d82023-08-15 15:19:41 -0400226 * - "device": The device URI associated with the connection.
Amna31791e52023-08-03 12:40:57 -0400227 * - "status": The status of the connection, represented as an integer:
228 * - 0: ConnectionStatus::Connected
229 * - 1: ConnectionStatus::TLS
230 * - 2: ConnectionStatus::ICE
231 * - 3: ConnectionStatus::Connecting (for pending operations)
232 * - 4: ConnectionStatus::Waiting (for pending operations)
233 * - "remoteAddress": The remote IP address of the connection (if available).
234 * - "remotePort": The remote port of the connection (if available).
235 *
236 * If a specific device ID is provided, the returned list will only include connections
237 * associated with that device. Otherwise, connections from all devices will be included.
238 */
239 std::vector<std::map<std::string, std::string>> getConnectionList(
240 const DeviceId& device = {}) const;
241
242 /**
243 * Retrieve the list of channels associated with a connection.
244 *
245 * @param connectionId The ID of the connection to fetch the channels from.
246 * @return The list of channels as a vector of maps, where each map represents a channel
247 * and contains key-value pairs of channel ID and channel name.
248 *
249 * If the specified connection ID is valid and associated with a connection,
250 * the method returns the list of channels associated with that connection.
251 * Otherwise, an empty vector is returned.
252 */
253 std::vector<std::map<std::string, std::string>> getChannelList(
254 const std::string& connectionId) const;
255
256
Adrien Béraud612b55b2023-05-29 10:42:04 -0400257 std::shared_ptr<Config> getConfig();
258
259private:
260 ConnectionManager() = delete;
261 class Impl;
262 std::shared_ptr<Impl> pimpl_;
263};
264
265struct ConnectionManager::Config
266{
267 /**
268 * Determine if STUN public address resolution is required to register this account. In this
269 * case a STUN server hostname must be specified.
270 */
271 bool stunEnabled {false};
272
273 /**
274 * The STUN server hostname (optional), used to provide the public IP address in case the
275 * softphone stay behind a NAT.
276 */
277 std::string stunServer {};
278
279 /**
280 * Determine if TURN public address resolution is required to register this account. In this
281 * case a TURN server hostname must be specified.
282 */
283 bool turnEnabled {false};
284
285 /**
286 * The TURN server hostname (optional), used to provide the public IP address in case the
287 * softphone stay behind a NAT.
288 */
289 std::string turnServer;
290 std::string turnServerUserName;
291 std::string turnServerPwd;
292 std::string turnServerRealm;
293
Sébastien Blin84bf4182023-07-21 14:18:39 -0400294 std::shared_ptr<TurnCache> turnCache;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400295
Adrien Béraud2a4e73d2023-08-27 12:53:55 -0400296 std::filesystem::path cachePath {};
Adrien Béraud612b55b2023-05-29 10:42:04 -0400297 std::shared_ptr<asio::io_context> ioContext;
298 std::shared_ptr<dht::DhtRunner> dht;
Amna81221ad2023-09-14 17:33:26 -0400299 dht::crypto::Identity id {};
Adrien Béraud612b55b2023-05-29 10:42:04 -0400300
Amna81221ad2023-09-14 17:33:26 -0400301 std::shared_ptr<tls::CertificateStore> certStore {nullptr};
302 std::shared_ptr<dhtnet::IceTransportFactory> factory {nullptr};
Sébastien Blin34086512023-07-25 09:52:14 -0400303
Adrien Béraud612b55b2023-05-29 10:42:04 -0400304 /**
305 * UPnP IGD controller and the mutex to access it
Sébastien Blin464bdff2023-07-19 08:02:53 -0400306 */
Amna81221ad2023-09-14 17:33:26 -0400307 bool upnpEnabled {true};
Adrien Béraud1ae60aa2023-07-07 09:55:09 -0400308 std::shared_ptr<dhtnet::upnp::Controller> upnpCtrl;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400309 std::shared_ptr<dht::log::Logger> logger;
310
311 /**
312 * returns whether or not UPnP is enabled and active
313 * ie: if it is able to make port mappings
314 */
315 bool getUPnPActive() const;
Amna31791e52023-08-03 12:40:57 -0400316
Adrien Béraud612b55b2023-05-29 10:42:04 -0400317};
318
Sébastien Blin464bdff2023-07-19 08:02:53 -0400319} // namespace dhtnet