2 net.c -- most of the network code
3 Copyright (C) 2014 Guus Sliepen <guus@meshlink.io>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 #include "connection.h"
27 #include "meshlink_internal.h"
37 static const int min(int a, int b) {
43 Terminate a connection:
45 - Remove the edge representing this connection
47 - Check if we need to retry making an outgoing connection
49 void terminate_connection(meshlink_handle_t *mesh, connection_t *c, bool report) {
50 logger(mesh, MESHLINK_INFO, "Closing connection with %s (%s)", c->name, c->hostname);
52 c->status.active = false;
54 if(c->node && c->node->connection == c)
55 c->node->connection = NULL;
59 send_del_edge(mesh, mesh->everyone, c->edge);
61 edge_del(mesh, c->edge);
64 /* Run MST and SSSP algorithms */
68 /* If the node is not reachable anymore but we remember it had an edge to us, clean it up */
70 if(report && !c->node->status.reachable) {
72 e = lookup_edge(c->node, mesh->self);
74 send_del_edge(mesh, mesh->everyone, e);
80 outgoing_t *outgoing = c->outgoing;
81 connection_del(mesh, c);
83 /* Check if this was our outgoing connection */
86 do_outgoing_connection(mesh, outgoing);
89 /* Clean up dead proxy processes */
91 while(waitpid(-1, NULL, WNOHANG) > 0);
96 Check if the other end is active.
97 If we have sent packets, but didn't receive any,
98 then possibly the other end is dead. We send a
99 PING request over the meta connection. If the other
100 end does not reply in time, we consider them dead
101 and close the connection.
103 static void timeout_handler(event_loop_t *loop, void *data) {
104 meshlink_handle_t *mesh = loop->data;
105 logger(mesh, MESHLINK_DEBUG, "timeout_handler()");
107 for list_each(connection_t, c, mesh->connections) {
108 // Also make sure that if outstanding key requests for the UDP counterpart of a connection has timed out, we restart it.
110 if(c->node->status.waitingforkey && c->node->last_req_key + mesh->pingtimeout <= mesh->loop.now.tv_sec)
111 send_req_key(mesh, c->node);
113 if(c->last_ping_time + mesh->pingtimeout <= mesh->loop.now.tv_sec) {
114 if(c->status.active) {
116 logger(mesh, MESHLINK_INFO, "%s (%s) didn't respond to PING in %ld seconds", c->name, c->hostname, (long)mesh->loop.now.tv_sec - c->last_ping_time);
117 else if(c->last_ping_time + mesh->pinginterval <= mesh->loop.now.tv_sec) {
123 if(c->status.connecting)
124 logger(mesh, MESHLINK_WARNING, "Timeout while connecting to %s (%s)", c->name, c->hostname);
126 logger(mesh, MESHLINK_WARNING, "Timeout from %s (%s) during authentication", c->name, c->hostname);
128 terminate_connection(mesh, c, c->status.active);
132 timeout_set(&mesh->loop, data, &(struct timeval) {
133 mesh->pingtimeout, rand() % 100000
137 // devclass asc, last_successfull_connection desc
138 static int node_compare_devclass_asc_lsc_desc(const void *a, const void *b) {
139 const node_t *na = a, *nb = b;
141 if(na->devclass < nb->devclass)
144 if(na->devclass > nb->devclass)
147 if(na->last_successfull_connection == nb->last_successfull_connection)
150 if(na->last_successfull_connection == 0 || na->last_successfull_connection > nb->last_successfull_connection)
153 if(nb->last_successfull_connection == 0 || na->last_successfull_connection < nb->last_successfull_connection)
165 // last_successfull_connection desc
166 static int node_compare_lsc_desc(const void *a, const void *b) {
167 const node_t *na = a, *nb = b;
169 if(na->last_successfull_connection == nb->last_successfull_connection)
172 if(na->last_successfull_connection == 0 || na->last_successfull_connection > nb->last_successfull_connection)
175 if(nb->last_successfull_connection == 0 || na->last_successfull_connection < nb->last_successfull_connection)
188 static int node_compare_devclass_desc(const void *a, const void *b) {
189 const node_t *na = a, *nb = b;
191 if(na->devclass < nb->devclass)
194 if(na->devclass > nb->devclass)
213 // find the best one for initial connect
218 where dclass <= my.dclass and !connection and (timestamp - last_retry) > retry_timeout
219 order by dclass asc, last_connection desc
225 // find better nodes to connect to: in case we have less than min connections within [BACKBONE, i] and there are nodes which we are not connected to within the range
229 for i = BACKBONE to my.dclass
230 j += count(from connections where node.dclass = i)
234 where dclass = i and !connection and (timestamp - last_retry) > retry_timeout
235 order by last_connection desc
247 where dclass <= my.dclass and !reachable and (timestamp - last_retry) > retry_timeout
248 order by dclass asc, last_connection desc
260 // disconnect outgoing connections in case we have more than min connections within [BACKBONE, i] and there are nodes which we are connected to within the range [i, PORTABLE]
264 for i = BACKBONE to my.dclass
265 j += count(from connections where node.dclass = i)
269 where dclass >= i and outgoing_connection
277 // disconnect connections in case we have more than enough connections
282 where outgoing_connection
294 next (timeout, autoconnect)
301 static void periodic_handler(event_loop_t *loop, void *data) {
302 meshlink_handle_t *mesh = loop->data;
304 /* Check if there are too many contradicting ADD_EDGE and DEL_EDGE messages.
305 This usually only happens when another node has the same Name as this node.
306 If so, sleep for a short while to prevent a storm of contradicting messages.
309 if(mesh->contradicting_del_edge > 100 && mesh->contradicting_add_edge > 100) {
310 logger(mesh, MESHLINK_WARNING, "Possible node with same Name as us! Sleeping %d seconds.", mesh->sleeptime);
311 usleep(mesh->sleeptime * 1000000LL);
312 mesh->sleeptime *= 2;
313 if(mesh->sleeptime < 0)
314 mesh->sleeptime = 3600;
316 mesh->sleeptime /= 2;
317 if(mesh->sleeptime < 10)
318 mesh->sleeptime = 10;
321 mesh->contradicting_add_edge = 0;
322 mesh->contradicting_del_edge = 0;
326 /* Check if we need to make or break connections. */
328 if(mesh->nodes->count > 1) {
330 logger(mesh, MESHLINK_DEBUG, "--- autoconnect begin ---");
332 int retry_timeout = min(mesh->nodes->count * 5, 60);
334 logger(mesh, MESHLINK_DEBUG, "* devclass = %d", mesh->devclass);
335 logger(mesh, MESHLINK_DEBUG, "* nodes = %d", mesh->nodes->count);
336 logger(mesh, MESHLINK_DEBUG, "* retry_timeout = %d", retry_timeout);
339 // connect disconnect nodes
341 node_t *connect_to = NULL;
342 node_t *disconnect_from = NULL;
347 int cur_connects = 0;
349 for list_each(connection_t, c, mesh->connections) {
354 logger(mesh, MESHLINK_DEBUG, "* cur_connects = %d", cur_connects);
355 logger(mesh, MESHLINK_DEBUG, "* outgoings = %d", mesh->outgoings->count);
357 // get min_connects and max_connects
359 assert(mesh->devclass >= 0 && mesh->devclass <= _DEV_CLASS_MAX);
361 int min_connects = dev_class_traits[mesh->devclass].min_connects;
362 int max_connects = dev_class_traits[mesh->devclass].max_connects;
364 logger(mesh, MESHLINK_DEBUG, "* min_connects = %d", min_connects);
365 logger(mesh, MESHLINK_DEBUG, "* max_connects = %d", max_connects);
368 // find the best one for initial connect
370 if(cur_connects < min_connects) {
371 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_asc_lsc_desc, NULL);
373 for splay_each(node_t, n, mesh->nodes) {
374 logger(mesh, MESHLINK_DEBUG, "* n->devclass = %d", n->devclass);
375 if(n != mesh->self && n->devclass <= mesh->devclass && !n->connection && (n->last_connect_try == 0 || (time(NULL) - n->last_connect_try) > retry_timeout))
376 splay_insert(nodes, n);
380 logger(mesh, MESHLINK_DEBUG, "* found best one for initial connect");
383 connect_to = (node_t *)nodes->head->data;
385 logger(mesh, MESHLINK_DEBUG, "* could not find node for initial connect");
387 splay_free_tree(nodes);
391 // find better nodes to connect to
393 if(!connect_to && min_connects <= cur_connects && cur_connects < max_connects) {
394 unsigned int connects = 0;
396 for(int devclass = 0; devclass <= mesh->devclass; ++devclass) {
397 for list_each(connection_t, c, mesh->connections) {
398 if(c->status.active && c->node && c->node->devclass == devclass)
402 if(connects < min_connects) {
403 splay_tree_t *nodes = splay_alloc_tree(node_compare_lsc_desc, NULL);
405 for splay_each(node_t, n, mesh->nodes) {
406 if(n != mesh->self && n->devclass == devclass && !n->connection && (n->last_connect_try == 0 || (time(NULL) - n->last_connect_try) > retry_timeout))
407 splay_insert(nodes, n);
411 logger(mesh, MESHLINK_DEBUG, "* found better node");
412 connect_to = (node_t *)nodes->head->data;
414 splay_free_tree(nodes);
418 splay_free_tree(nodes);
424 logger(mesh, MESHLINK_DEBUG, "* could not find better nodes");
430 if(!connect_to && min_connects <= cur_connects && cur_connects < max_connects) {
431 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_asc_lsc_desc, NULL);
433 for splay_each(node_t, n, mesh->nodes) {
434 if(n != mesh->self && n->devclass <= mesh->devclass && !n->status.reachable && (n->last_connect_try == 0 || (time(NULL) - n->last_connect_try) > retry_timeout))
435 splay_insert(nodes, n);
439 logger(mesh, MESHLINK_DEBUG, "* try to heal partition");
440 connect_to = (node_t *)nodes->head->data;
442 logger(mesh, MESHLINK_DEBUG, "* could not find nodes for partition healing");
444 splay_free_tree(nodes);
450 if(connect_to && !connect_to->connection) {
451 connect_to->last_connect_try = time(NULL);
453 /* check if there is already a connection attempt to this node */
455 for list_each(outgoing_t, outgoing, mesh->outgoings) {
456 if(!strcmp(outgoing->name, connect_to->name)) {
463 logger(mesh, MESHLINK_DEBUG, "Autoconnecting to %s", connect_to->name);
464 outgoing_t *outgoing = xzalloc(sizeof(outgoing_t));
465 outgoing->mesh = mesh;
466 outgoing->name = xstrdup(connect_to->name);
467 list_insert_tail(mesh->outgoings, outgoing);
468 setup_outgoing_connection(mesh, outgoing);
470 logger(mesh, MESHLINK_DEBUG, "* skip autoconnect since it is an outgoing connection already");
474 // disconnect suboptimal outgoing connections
476 if(min_connects < cur_connects /*&& cur_connects <= max_connects*/) {
477 unsigned int connects = 0;
479 for(int devclass = 0; devclass <= mesh->devclass; ++devclass) {
480 for list_each(connection_t, c, mesh->connections) {
481 if(c->status.active && c->node && c->node->devclass == devclass)
485 if(min_connects < connects) {
486 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_desc, NULL);
488 for list_each(connection_t, c, mesh->connections) {
489 if(c->outgoing && c->node && c->node->devclass >= devclass)
490 splay_insert(nodes, c->node);
494 logger(mesh, MESHLINK_DEBUG, "* disconnect suboptimal outgoing connection");
495 disconnect_from = (node_t *)nodes->head->data;
498 splay_free_tree(nodes);
504 logger(mesh, MESHLINK_DEBUG, "* no suboptimal outgoing connections");
508 // disconnect connections (too many connections)
510 if(!disconnect_from && max_connects < cur_connects) {
511 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_desc, NULL);
513 for list_each(connection_t, c, mesh->connections) {
514 if(c->status.active && c->node)
515 splay_insert(nodes, c->node);
519 logger(mesh, MESHLINK_DEBUG, "* disconnect connection (too many connections)");
522 disconnect_from = (node_t *)nodes->head->data;
524 logger(mesh, MESHLINK_DEBUG, "* no node we want to disconnect, even though we have too many connections");
526 splay_free_tree(nodes);
530 // perform disconnect
532 if(disconnect_from && disconnect_from->connection) {
533 logger(mesh, MESHLINK_DEBUG, "Autodisconnecting from %s", disconnect_from->connection->name);
534 list_delete(mesh->outgoings, disconnect_from->connection->outgoing);
535 disconnect_from->connection->outgoing = NULL;
536 terminate_connection(mesh, disconnect_from->connection, disconnect_from->connection->status.active);
542 logger(mesh, MESHLINK_DEBUG, "--- autoconnect end ---");
545 timeout_set(&mesh->loop, data, &(struct timeval) {
546 timeout, rand() % 100000
550 void handle_meta_connection_data(meshlink_handle_t *mesh, connection_t *c) {
551 if(!receive_meta(mesh, c)) {
552 terminate_connection(mesh, c, c->status.active);
557 void retry(meshlink_handle_t *mesh) {
558 /* Reset the reconnection timers for all outgoing connections */
559 for list_each(outgoing_t, outgoing, mesh->outgoings) {
560 outgoing->timeout = 0;
562 timeout_set(&mesh->loop, &outgoing->ev, &(struct timeval) {
567 /* Check for outgoing connections that are in progress, and reset their ping timers */
568 for list_each(connection_t, c, mesh->connections) {
569 if(c->outgoing && !c->node)
570 c->last_ping_time = 0;
573 /* Kick the ping timeout handler */
574 timeout_set(&mesh->loop, &mesh->pingtimer, &(struct timeval) {
580 this is where it all happens...
582 int main_loop(meshlink_handle_t *mesh) {
583 timeout_add(&mesh->loop, &mesh->pingtimer, timeout_handler, &mesh->pingtimer, &(struct timeval) {
584 mesh->pingtimeout, rand() % 100000
586 timeout_add(&mesh->loop, &mesh->periodictimer, periodic_handler, &mesh->periodictimer, &(struct timeval) {
591 mesh->datafromapp.signum = 0;
592 signal_add(&(mesh->loop), &(mesh->datafromapp), (signal_cb_t)meshlink_send_from_queue, mesh, mesh->datafromapp.signum);
594 if(!event_loop_run(&(mesh->loop), &(mesh->mesh_mutex))) {
595 logger(mesh, MESHLINK_ERROR, "Error while waiting for input: %s", strerror(errno));
599 timeout_del(&mesh->loop, &mesh->periodictimer);
600 timeout_del(&mesh->loop, &mesh->pingtimer);