Line data Source code
1 : /*
2 : * Copyright (C) 2004-2025 Savoir-faire Linux Inc.
3 : *
4 : * This program is free software: you can redistribute it and/or modify
5 : * it under the terms of the GNU General Public License as published by
6 : * the Free Software Foundation, either version 3 of the License, or
7 : * (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
11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 : * 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 :
18 : #include "swarm_manager.h"
19 : #include <dhtnet/multiplexed_socket.h>
20 : #include <opendht/thread_pool.h>
21 :
22 : namespace jami {
23 :
24 : using namespace swarm_protocol;
25 :
26 494 : SwarmManager::SwarmManager(const NodeId& id, const std::mt19937_64& rand, ToConnectCb&& toConnectCb)
27 494 : : id_(id)
28 494 : , rd(rand)
29 494 : , toConnectCb_(toConnectCb)
30 : {
31 494 : routing_table.setId(id);
32 494 : }
33 :
34 493 : SwarmManager::~SwarmManager()
35 : {
36 493 : if (!isShutdown_)
37 227 : shutdown();
38 493 : }
39 :
40 : bool
41 1732 : SwarmManager::setKnownNodes(const std::vector<NodeId>& known_nodes)
42 : {
43 1732 : isShutdown_ = false;
44 1732 : std::vector<NodeId> newNodes;
45 : {
46 1732 : std::lock_guard lock(mutex);
47 4816 : for (const auto& nodeId : known_nodes) {
48 3084 : if (addKnownNode(nodeId)) {
49 986 : newNodes.emplace_back(nodeId);
50 : }
51 : }
52 1732 : }
53 :
54 1732 : if (newNodes.empty())
55 1195 : return false;
56 :
57 537 : dht::ThreadPool::io().run([w = weak(), newNodes = std::move(newNodes)] {
58 537 : auto shared = w.lock();
59 537 : if (!shared)
60 0 : return;
61 : // If we detect a new node which already got a TCP link
62 : // we can use it to speed-up the bootstrap (because opening
63 : // a new channel will be easy)
64 537 : std::set<NodeId> toConnect;
65 1523 : for (const auto& nodeId : newNodes) {
66 986 : if (shared->toConnectCb_ && shared->toConnectCb_(nodeId))
67 231 : toConnect.emplace(nodeId);
68 : }
69 537 : shared->maintainBuckets(toConnect);
70 537 : });
71 537 : return true;
72 1732 : }
73 :
74 : void
75 1024 : SwarmManager::setMobileNodes(const std::vector<NodeId>& mobile_nodes)
76 : {
77 : {
78 1024 : std::lock_guard lock(mutex);
79 1037 : for (const auto& nodeId : mobile_nodes)
80 13 : addMobileNodes(nodeId);
81 1024 : }
82 1024 : }
83 :
84 : void
85 1467 : SwarmManager::addChannel(const std::shared_ptr<dhtnet::ChannelSocketInterface>& channel)
86 : {
87 : // JAMI_WARNING("[SwarmManager {}] addChannel! with {}", fmt::ptr(this), channel->deviceId().to_view());
88 1467 : if (channel) {
89 1467 : auto emit = false;
90 : {
91 1467 : std::lock_guard lock(mutex);
92 1467 : emit = routing_table.findBucket(getId())->isEmpty();
93 1467 : auto bucket = routing_table.findBucket(channel->deviceId());
94 1467 : if (routing_table.addNode(channel, bucket)) {
95 1050 : std::error_code ec;
96 1050 : resetNodeExpiry(ec, channel, id_);
97 : }
98 1467 : }
99 1467 : receiveMessage(channel);
100 1467 : if (emit && onConnectionChanged_) {
101 : // If it's the first channel we add, we're now connected!
102 834 : JAMI_DEBUG("[SwarmManager {}] Bootstrap: Connected!", fmt::ptr(this));
103 278 : onConnectionChanged_(true);
104 : }
105 : }
106 1467 : }
107 :
108 : void
109 417 : SwarmManager::removeNode(const NodeId& nodeId)
110 : {
111 417 : std::unique_lock lk(mutex);
112 417 : if (isConnectedWith(nodeId)) {
113 392 : removeNodeInternal(nodeId);
114 392 : lk.unlock();
115 392 : maintainBuckets();
116 : }
117 417 : }
118 :
119 : void
120 194 : SwarmManager::changeMobility(const NodeId& nodeId, bool isMobile)
121 : {
122 194 : std::lock_guard lock(mutex);
123 194 : auto bucket = routing_table.findBucket(nodeId);
124 194 : bucket->changeMobility(nodeId, isMobile);
125 194 : }
126 :
127 : bool
128 417 : SwarmManager::isConnectedWith(const NodeId& deviceId)
129 : {
130 417 : return routing_table.hasNode(deviceId);
131 : }
132 :
133 : void
134 538 : SwarmManager::shutdown()
135 : {
136 538 : if (isShutdown_) {
137 17 : return;
138 : }
139 521 : isShutdown_ = true;
140 521 : std::lock_guard lock(mutex);
141 521 : routing_table.shutdownAllNodes();
142 521 : }
143 :
144 : void
145 18 : SwarmManager::restart()
146 : {
147 18 : isShutdown_ = false;
148 18 : }
149 :
150 : bool
151 3084 : SwarmManager::addKnownNode(const NodeId& nodeId)
152 : {
153 3084 : return routing_table.addKnownNode(nodeId);
154 : }
155 :
156 : void
157 13 : SwarmManager::addMobileNodes(const NodeId& nodeId)
158 : {
159 13 : if (id_ != nodeId) {
160 12 : routing_table.addMobileNode(nodeId);
161 : }
162 13 : }
163 :
164 : void
165 963 : SwarmManager::maintainBuckets(const std::set<NodeId>& toConnect)
166 : {
167 963 : std::set<NodeId> nodes = toConnect;
168 963 : std::unique_lock lock(mutex);
169 963 : auto& buckets = routing_table.getBuckets();
170 3227 : for (auto it = buckets.begin(); it != buckets.end(); ++it) {
171 2264 : auto& bucket = *it;
172 2264 : bool myBucket = routing_table.contains(it, id_);
173 3565 : auto connecting_nodes = myBucket ? bucket.getConnectingNodesSize()
174 1301 : : bucket.getConnectingNodesSize() + bucket.getNodesSize();
175 2264 : if (connecting_nodes < Bucket::BUCKET_MAX_SIZE) {
176 : auto nodesToTry = bucket.getKnownNodesRandom(Bucket::BUCKET_MAX_SIZE - connecting_nodes,
177 1219 : rd);
178 2107 : for (auto& node : nodesToTry)
179 888 : routing_table.addConnectingNode(node);
180 :
181 1219 : nodes.insert(nodesToTry.begin(), nodesToTry.end());
182 1219 : }
183 : }
184 963 : lock.unlock();
185 1916 : for (auto& node : nodes)
186 953 : tryConnect(node);
187 963 : }
188 :
189 : void
190 1050 : SwarmManager::sendRequest(const std::shared_ptr<dhtnet::ChannelSocketInterface>& socket,
191 : const NodeId& nodeId,
192 : Query q,
193 : int numberNodes)
194 : {
195 1050 : dht::ThreadPool::io().run([socket, isMobile=isMobile_, nodeId, q, numberNodes] {
196 1050 : msgpack::sbuffer buffer;
197 1050 : msgpack::packer<msgpack::sbuffer> pk(&buffer);
198 1050 : Message msg;
199 1050 : msg.is_mobile = isMobile;
200 1050 : msg.request = Request {q, numberNodes, nodeId};
201 1050 : pk.pack(msg);
202 :
203 1050 : std::error_code ec;
204 1050 : socket->write(reinterpret_cast<const unsigned char*>(buffer.data()), buffer.size(), ec);
205 1050 : if (ec) {
206 3 : JAMI_ERROR("{}", ec.message());
207 : }
208 1050 : });
209 1050 : }
210 :
211 : void
212 1029 : SwarmManager::sendAnswer(const std::shared_ptr<dhtnet::ChannelSocketInterface>& socket,
213 : const Message& msg_)
214 : {
215 1029 : std::lock_guard lock(mutex);
216 :
217 1029 : if (msg_.request->q == Query::FIND) {
218 1029 : auto nodes = routing_table.closestNodes(msg_.request->nodeId, msg_.request->num);
219 1029 : auto bucket = routing_table.findBucket(msg_.request->nodeId);
220 1029 : const auto& m_nodes = bucket->getMobileNodes();
221 1029 : Response toResponse {Query::FOUND, nodes, {m_nodes.begin(), m_nodes.end()}};
222 :
223 1029 : Message msg;
224 1029 : msg.is_mobile = isMobile_;
225 1029 : msg.response = std::move(toResponse);
226 :
227 1029 : msgpack::sbuffer buffer((size_t) 60000);
228 1029 : msgpack::packer<msgpack::sbuffer> pk(&buffer);
229 1029 : pk.pack(msg);
230 :
231 1029 : std::error_code ec;
232 1029 : socket->write(reinterpret_cast<const unsigned char*>(buffer.data()), buffer.size(), ec);
233 1029 : if (ec) {
234 3 : JAMI_ERROR("{}", ec.message());
235 1 : return;
236 : }
237 1032 : }
238 1029 : }
239 :
240 : void
241 1467 : SwarmManager::receiveMessage(const std::shared_ptr<dhtnet::ChannelSocketInterface>& socket)
242 : {
243 : struct DecodingContext
244 : {
245 16756 : msgpack::unpacker pac {[](msgpack::type::object_type, std::size_t, void*) { return true; },
246 : nullptr,
247 : 512};
248 : };
249 :
250 1467 : socket->setOnRecv([w = weak(),
251 : wsocket = std::weak_ptr<dhtnet::ChannelSocketInterface>(socket),
252 : ctx = std::make_shared<DecodingContext>()](const uint8_t* buf, size_t len) {
253 2051 : ctx->pac.reserve_buffer(len);
254 2051 : std::copy_n(buf, len, ctx->pac.buffer());
255 2051 : ctx->pac.buffer_consumed(len);
256 :
257 2051 : msgpack::object_handle oh;
258 4102 : while (ctx->pac.next(oh)) {
259 2051 : auto shared = w.lock();
260 2051 : auto socket = wsocket.lock();
261 2051 : if (!shared || !socket)
262 0 : return size_t {0};
263 :
264 : try {
265 2051 : Message msg;
266 2051 : oh.get().convert(msg);
267 :
268 2051 : if (msg.is_mobile)
269 194 : shared->changeMobility(socket->deviceId(), msg.is_mobile);
270 :
271 2051 : if (msg.request) {
272 1029 : shared->sendAnswer(socket, msg);
273 :
274 1022 : } else if (msg.response) {
275 1022 : shared->setKnownNodes(msg.response->nodes);
276 1022 : shared->setMobileNodes(msg.response->mobile_nodes);
277 : }
278 :
279 2051 : } catch (const std::exception& e) {
280 0 : JAMI_WARNING("Error DRT recv: {}", e.what());
281 0 : return len;
282 0 : }
283 2051 : }
284 :
285 2051 : return len;
286 2051 : });
287 :
288 1467 : socket->onShutdown([w = weak(), deviceId = socket->deviceId()] {
289 1050 : dht::ThreadPool::io().run([w, deviceId] {
290 738 : auto shared = w.lock();
291 738 : if (shared && !shared->isShutdown_) {
292 417 : shared->removeNode(deviceId);
293 : }
294 738 : });
295 1050 : });
296 1467 : }
297 :
298 : void
299 1050 : SwarmManager::resetNodeExpiry(const asio::error_code& ec,
300 : const std::shared_ptr<dhtnet::ChannelSocketInterface>& socket,
301 : NodeId node)
302 : {
303 1050 : NodeId idToFind;
304 1050 : std::list<Bucket>::iterator bucket;
305 :
306 1050 : if (ec == asio::error::operation_aborted)
307 0 : return;
308 :
309 1050 : if (!node) {
310 0 : bucket = routing_table.findBucket(socket->deviceId());
311 0 : idToFind = bucket->randomId(rd);
312 : } else {
313 1050 : bucket = routing_table.findBucket(node);
314 1050 : idToFind = node;
315 : }
316 :
317 1050 : sendRequest(socket, idToFind, Query::FIND, Bucket::BUCKET_MAX_SIZE);
318 :
319 1050 : if (!node) {
320 0 : auto& nodeTimer = bucket->getNodeTimer(socket);
321 0 : nodeTimer.expires_after(FIND_PERIOD);
322 0 : nodeTimer.async_wait(std::bind(&jami::SwarmManager::resetNodeExpiry,
323 0 : shared_from_this(),
324 : std::placeholders::_1,
325 : socket,
326 0 : NodeId {}));
327 : }
328 : }
329 :
330 : void
331 953 : SwarmManager::tryConnect(const NodeId& nodeId)
332 : {
333 953 : if (needSocketCb_)
334 948 : needSocketCb_(nodeId.toString(),
335 867 : [w = weak(),
336 : nodeId](const std::shared_ptr<dhtnet::ChannelSocketInterface>& socket) {
337 867 : auto shared = w.lock();
338 867 : if (!shared || shared->isShutdown_)
339 223 : return true;
340 644 : if (socket) {
341 577 : shared->addChannel(socket);
342 577 : return true;
343 : }
344 67 : std::unique_lock lk(shared->mutex);
345 67 : auto bucket = shared->routing_table.findBucket(nodeId);
346 67 : bucket->removeConnectingNode(nodeId);
347 67 : bucket->addKnownNode(nodeId);
348 67 : bucket = shared->routing_table.findBucket(shared->getId());
349 120 : if (bucket->getConnectingNodesSize() == 0 && bucket->isEmpty()
350 120 : && shared->onConnectionChanged_) {
351 38 : lk.unlock();
352 114 : JAMI_LOG("[SwarmManager {:p}] Bootstrap: all connections failed",
353 : fmt::ptr(shared.get()));
354 38 : shared->onConnectionChanged_(false);
355 : }
356 67 : return true;
357 867 : });
358 953 : }
359 :
360 : void
361 392 : SwarmManager::removeNodeInternal(const NodeId& nodeId)
362 : {
363 392 : routing_table.removeNode(nodeId);
364 392 : }
365 :
366 : std::vector<NodeId>
367 0 : SwarmManager::getAllNodes() const
368 : {
369 0 : std::lock_guard lock(mutex);
370 0 : return routing_table.getAllNodes();
371 0 : }
372 :
373 : void
374 16 : SwarmManager::deleteNode(std::vector<NodeId> nodes)
375 : {
376 : {
377 16 : std::lock_guard lock(mutex);
378 26 : for (const auto& node : nodes) {
379 10 : routing_table.deleteNode(node);
380 : }
381 16 : }
382 16 : maintainBuckets();
383 16 : }
384 :
385 : } // namespace jami
|