2 net.c -- most of the network code
3 Copyright (C) 2014-2017 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 inline 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", c->name);
52 c->status.active = false;
54 if(c->node && c->node->connection == c) {
55 c->node->connection = NULL;
60 send_del_edge(mesh, mesh->everyone, c->edge, 0);
63 edge_del(mesh, c->edge);
66 /* Run MST and SSSP algorithms */
70 /* If the node is not reachable anymore but we remember it had an edge to us, clean it up */
72 if(report && c->node && !c->node->status.reachable) {
74 e = lookup_edge(c->node, mesh->self);
77 send_del_edge(mesh, mesh->everyone, e, 0);
83 outgoing_t *outgoing = c->outgoing;
84 connection_del(mesh, c);
86 /* Check if this was our outgoing connection */
89 do_outgoing_connection(mesh, outgoing);
93 /* Clean up dead proxy processes */
95 while(waitpid(-1, NULL, WNOHANG) > 0);
101 Check if the other end is active.
102 If we have sent packets, but didn't receive any,
103 then possibly the other end is dead. We send a
104 PING request over the meta connection. If the other
105 end does not reply in time, we consider them dead
106 and close the connection.
108 static void timeout_handler(event_loop_t *loop, void *data) {
109 meshlink_handle_t *mesh = loop->data;
110 logger(mesh, MESHLINK_DEBUG, "timeout_handler()");
112 for list_each(connection_t, c, mesh->connections) {
113 // Also make sure that if outstanding key requests for the UDP counterpart of a connection has timed out, we restart it.
115 if(c->node->status.waitingforkey && c->node->last_req_key + mesh->pingtimeout <= mesh->loop.now.tv_sec) {
116 send_req_key(mesh, c->node);
120 if(c->last_ping_time + mesh->pingtimeout <= mesh->loop.now.tv_sec) {
121 if(c->status.active) {
122 if(c->status.pinged) {
123 logger(mesh, MESHLINK_INFO, "%s didn't respond to PING in %ld seconds", c->name, (long)mesh->loop.now.tv_sec - c->last_ping_time);
124 } else if(c->last_ping_time + mesh->pinginterval <= mesh->loop.now.tv_sec) {
131 if(c->status.connecting) {
132 logger(mesh, MESHLINK_WARNING, "Timeout while connecting to %s", c->name);
134 logger(mesh, MESHLINK_WARNING, "Timeout from %s during authentication", c->name);
138 terminate_connection(mesh, c, c->status.active);
142 timeout_set(&mesh->loop, data, &(struct timeval) {
143 mesh->pingtimeout, rand() % 100000
147 // devclass asc, last_successfull_connection desc
148 static int node_compare_devclass_asc_lsc_desc(const void *a, const void *b) {
149 const node_t *na = a, *nb = b;
151 if(na->devclass < nb->devclass) {
155 if(na->devclass > nb->devclass) {
159 if(na->last_successfull_connection == nb->last_successfull_connection) {
163 if(na->last_successfull_connection == 0 || na->last_successfull_connection > nb->last_successfull_connection) {
167 if(nb->last_successfull_connection == 0 || na->last_successfull_connection < nb->last_successfull_connection) {
182 // last_successfull_connection desc
183 static int node_compare_lsc_desc(const void *a, const void *b) {
184 const node_t *na = a, *nb = b;
186 if(na->last_successfull_connection == nb->last_successfull_connection) {
190 if(na->last_successfull_connection == 0 || na->last_successfull_connection > nb->last_successfull_connection) {
194 if(nb->last_successfull_connection == 0 || na->last_successfull_connection < nb->last_successfull_connection) {
210 static int node_compare_devclass_desc(const void *a, const void *b) {
211 const node_t *na = a, *nb = b;
213 if(na->devclass < nb->devclass) {
217 if(na->devclass > nb->devclass) {
239 // find the best one for initial connect
244 where dclass <= my.dclass and !connection and (timestamp - last_retry) > retry_timeout
245 order by dclass asc, last_connection desc
251 // 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
255 for i = BACKBONE to my.dclass
256 j += count(from connections where node.dclass = i)
260 where dclass = i and !connection and (timestamp - last_retry) > retry_timeout
261 order by last_connection desc
273 where dclass <= my.dclass and !reachable and (timestamp - last_retry) > retry_timeout
274 order by dclass asc, last_connection desc
286 // 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]
290 for i = BACKBONE to my.dclass
291 j += count(from connections where node.dclass = i)
295 where dclass >= i and outgoing_connection
303 // disconnect connections in case we have more than enough connections
308 where outgoing_connection
320 next (timeout, autoconnect)
327 static void periodic_handler(event_loop_t *loop, void *data) {
328 meshlink_handle_t *mesh = loop->data;
330 /* Check if there are too many contradicting ADD_EDGE and DEL_EDGE messages.
331 This usually only happens when another node has the same Name as this node.
332 If so, sleep for a short while to prevent a storm of contradicting messages.
335 if(mesh->contradicting_del_edge > 100 && mesh->contradicting_add_edge > 100) {
336 logger(mesh, MESHLINK_WARNING, "Possible node with same Name as us! Sleeping %d seconds.", mesh->sleeptime);
337 usleep(mesh->sleeptime * 1000000LL);
338 mesh->sleeptime *= 2;
340 if(mesh->sleeptime < 0) {
341 mesh->sleeptime = 3600;
344 mesh->sleeptime /= 2;
346 if(mesh->sleeptime < 10) {
347 mesh->sleeptime = 10;
351 mesh->contradicting_add_edge = 0;
352 mesh->contradicting_del_edge = 0;
356 /* Check if we need to make or break connections. */
358 if(mesh->nodes->count > 1) {
360 logger(mesh, MESHLINK_DEBUG, "--- autoconnect begin ---");
362 int retry_timeout = min(mesh->nodes->count * 5, 60);
364 logger(mesh, MESHLINK_DEBUG, "* devclass = %d", mesh->devclass);
365 logger(mesh, MESHLINK_DEBUG, "* nodes = %d", mesh->nodes->count);
366 logger(mesh, MESHLINK_DEBUG, "* retry_timeout = %d", retry_timeout);
369 // connect disconnect nodes
371 node_t *connect_to = NULL;
372 node_t *disconnect_from = NULL;
377 unsigned int cur_connects = 0;
379 for list_each(connection_t, c, mesh->connections) {
380 if(c->status.active) {
385 logger(mesh, MESHLINK_DEBUG, "* cur_connects = %d", cur_connects);
386 logger(mesh, MESHLINK_DEBUG, "* outgoings = %d", mesh->outgoings->count);
388 // get min_connects and max_connects
390 unsigned int min_connects = dev_class_traits[mesh->devclass].min_connects;
391 unsigned int max_connects = dev_class_traits[mesh->devclass].max_connects;
393 logger(mesh, MESHLINK_DEBUG, "* min_connects = %d", min_connects);
394 logger(mesh, MESHLINK_DEBUG, "* max_connects = %d", max_connects);
397 // find the best one for initial connect
399 if(cur_connects < min_connects) {
400 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_asc_lsc_desc, NULL);
402 for splay_each(node_t, n, mesh->nodes) {
403 logger(mesh, MESHLINK_DEBUG, "* %s->devclass = %d", n->name, n->devclass);
405 if(n != mesh->self && n->devclass <= mesh->devclass && !n->connection && !n->status.blacklisted && (n->last_connect_try == 0 || (time(NULL) - n->last_connect_try) > retry_timeout)) {
406 splay_insert(nodes, n);
412 connect_to = (node_t *)nodes->head->data;
414 logger(mesh, MESHLINK_DEBUG, "* found best one for initial connect: %s", connect_to->name);
416 logger(mesh, MESHLINK_DEBUG, "* could not find node for initial connect");
419 splay_free_tree(nodes);
423 // find better nodes to connect to
425 if(!connect_to && min_connects <= cur_connects && cur_connects < max_connects) {
426 unsigned int connects = 0;
428 for(int32_t devclass = 0; devclass <= mesh->devclass; ++devclass) {
429 for list_each(connection_t, c, mesh->connections) {
430 if(c->status.active && c->node && c->node->devclass == devclass) {
435 if(connects < min_connects) {
436 splay_tree_t *nodes = splay_alloc_tree(node_compare_lsc_desc, NULL);
438 for splay_each(node_t, n, mesh->nodes) {
439 if(n != mesh->self && n->devclass == devclass && !n->connection && !n->status.blacklisted && (n->last_connect_try == 0 || (time(NULL) - n->last_connect_try) > retry_timeout)) {
440 splay_insert(nodes, n);
445 logger(mesh, MESHLINK_DEBUG, "* found better node");
446 connect_to = (node_t *)nodes->head->data;
448 splay_free_tree(nodes);
452 splay_free_tree(nodes);
459 logger(mesh, MESHLINK_DEBUG, "* could not find better nodes");
466 if(!connect_to && min_connects <= cur_connects && cur_connects < max_connects) {
467 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_asc_lsc_desc, NULL);
469 for splay_each(node_t, n, mesh->nodes) {
470 if(n != mesh->self && n->devclass <= mesh->devclass && !n->status.reachable && !n->status.blacklisted && (n->last_connect_try == 0 || (time(NULL) - n->last_connect_try) > retry_timeout)) {
471 splay_insert(nodes, n);
476 logger(mesh, MESHLINK_DEBUG, "* try to heal partition");
477 connect_to = (node_t *)nodes->head->data;
479 logger(mesh, MESHLINK_DEBUG, "* could not find nodes for partition healing");
482 splay_free_tree(nodes);
488 if(connect_to && !connect_to->connection) {
489 connect_to->last_connect_try = time(NULL);
490 logger(mesh, MESHLINK_DEBUG, "Autoconnect trying to connect to %s", connect_to->name);
492 /* check if there is already a connection attempt to this node */
495 for list_each(outgoing_t, outgoing, mesh->outgoings) {
496 if(outgoing->node == connect_to) {
497 logger(mesh, MESHLINK_DEBUG, "* skip autoconnect since it is an outgoing connection already");
503 if(!connect_to->status.reachable && !node_read_public_key(mesh, connect_to)) {
504 logger(mesh, MESHLINK_DEBUG, "* skip autoconnect since we don't know this node's public key");
509 logger(mesh, MESHLINK_DEBUG, "Autoconnecting to %s", connect_to->name);
510 outgoing_t *outgoing = xzalloc(sizeof(outgoing_t));
511 outgoing->node = connect_to;
512 list_insert_tail(mesh->outgoings, outgoing);
513 setup_outgoing_connection(mesh, outgoing);
518 // disconnect suboptimal outgoing connections
520 if(min_connects < cur_connects /*&& cur_connects <= max_connects*/) {
521 unsigned int connects = 0;
523 for(int32_t devclass = 0; devclass <= mesh->devclass; ++devclass) {
524 for list_each(connection_t, c, mesh->connections) {
525 if(c->status.active && c->node && c->node->devclass == devclass) {
530 if(min_connects < connects) {
531 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_desc, NULL);
533 for list_each(connection_t, c, mesh->connections) {
534 if(c->outgoing && c->node && c->node->devclass >= devclass) {
535 splay_insert(nodes, c->node);
540 logger(mesh, MESHLINK_DEBUG, "* disconnect suboptimal outgoing connection");
541 disconnect_from = (node_t *)nodes->head->data;
544 splay_free_tree(nodes);
549 if(!disconnect_from) {
550 logger(mesh, MESHLINK_DEBUG, "* no suboptimal outgoing connections");
555 // disconnect connections (too many connections)
557 if(!disconnect_from && max_connects < cur_connects) {
558 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_desc, NULL);
560 for list_each(connection_t, c, mesh->connections) {
561 if(c->status.active && c->node) {
562 splay_insert(nodes, c->node);
567 logger(mesh, MESHLINK_DEBUG, "* disconnect connection (too many connections)");
570 disconnect_from = (node_t *)nodes->head->data;
572 logger(mesh, MESHLINK_DEBUG, "* no node we want to disconnect, even though we have too many connections");
575 splay_free_tree(nodes);
579 // perform disconnect
581 if(disconnect_from && disconnect_from->connection) {
582 logger(mesh, MESHLINK_DEBUG, "Autodisconnecting from %s", disconnect_from->connection->name);
583 list_delete(mesh->outgoings, disconnect_from->connection->outgoing);
584 disconnect_from->connection->outgoing = NULL;
585 terminate_connection(mesh, disconnect_from->connection, disconnect_from->connection->status.active);
588 // reduce timeout if we don't have enough connections + outgoings
589 if(cur_connects + mesh->outgoings->count < 3) {
595 logger(mesh, MESHLINK_DEBUG, "--- autoconnect end ---");
598 for splay_each(node_t, n, mesh->nodes) {
599 if(n->status.dirty) {
600 node_write_config(mesh, n);
601 n->status.dirty = false;
605 timeout_set(&mesh->loop, data, &(struct timeval) {
606 timeout, rand() % 100000
610 void handle_meta_connection_data(meshlink_handle_t *mesh, connection_t *c) {
611 if(!receive_meta(mesh, c)) {
612 terminate_connection(mesh, c, c->status.active);
617 void retry(meshlink_handle_t *mesh) {
618 /* Reset the reconnection timers for all outgoing connections */
619 for list_each(outgoing_t, outgoing, mesh->outgoings) {
620 outgoing->timeout = 0;
623 timeout_set(&mesh->loop, &outgoing->ev, &(struct timeval) {
628 /* Check for outgoing connections that are in progress, and reset their ping timers */
629 for list_each(connection_t, c, mesh->connections) {
630 if(c->outgoing && !c->node) {
631 c->last_ping_time = 0;
635 /* Kick the ping timeout handler */
636 timeout_set(&mesh->loop, &mesh->pingtimer, &(struct timeval) {
642 this is where it all happens...
644 int main_loop(meshlink_handle_t *mesh) {
645 timeout_add(&mesh->loop, &mesh->pingtimer, timeout_handler, &mesh->pingtimer, &(struct timeval) {
646 mesh->pingtimeout, rand() % 100000
648 timeout_add(&mesh->loop, &mesh->periodictimer, periodic_handler, &mesh->periodictimer, &(struct timeval) {
653 mesh->datafromapp.signum = 0;
654 signal_add(&(mesh->loop), &(mesh->datafromapp), (signal_cb_t)meshlink_send_from_queue, mesh, mesh->datafromapp.signum);
656 if(!event_loop_run(&(mesh->loop), &(mesh->mesh_mutex))) {
657 logger(mesh, MESHLINK_ERROR, "Error while waiting for input: %s", strerror(errno));
661 timeout_del(&mesh->loop, &mesh->periodictimer);
662 timeout_del(&mesh->loop, &mesh->pingtimer);