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) {
42 static const int default_timeout = 5;
45 Terminate a connection:
47 - Remove the edge representing this connection
49 - Check if we need to retry making an outgoing connection
51 void terminate_connection(meshlink_handle_t *mesh, connection_t *c, bool report) {
52 logger(mesh, MESHLINK_INFO, "Closing connection with %s", c->name);
54 c->status.active = false;
56 if(c->node && c->node->connection == c) {
57 c->node->connection = NULL;
62 send_del_edge(mesh, mesh->everyone, c->edge, 0);
65 edge_del(mesh, c->edge);
68 /* Run MST and SSSP algorithms */
72 /* If the node is not reachable anymore but we remember it had an edge to us, clean it up */
74 if(report && c->node && !c->node->status.reachable) {
76 e = lookup_edge(c->node, mesh->self);
79 send_del_edge(mesh, mesh->everyone, e, 0);
85 outgoing_t *outgoing = c->outgoing;
86 connection_del(mesh, c);
88 /* Check if this was our outgoing connection */
91 do_outgoing_connection(mesh, outgoing);
95 /* Clean up dead proxy processes */
97 while(waitpid(-1, NULL, WNOHANG) > 0);
103 Check if the other end is active.
104 If we have sent packets, but didn't receive any,
105 then possibly the other end is dead. We send a
106 PING request over the meta connection. If the other
107 end does not reply in time, we consider them dead
108 and close the connection.
110 static void timeout_handler(event_loop_t *loop, void *data) {
111 meshlink_handle_t *mesh = loop->data;
112 logger(mesh, MESHLINK_DEBUG, "timeout_handler()");
114 for list_each(connection_t, c, mesh->connections) {
115 int pingtimeout = c->node ? mesh->dev_class_traits[c->node->devclass].pingtimeout : default_timeout;
117 // Also make sure that if outstanding key requests for the UDP counterpart of a connection has timed out, we restart it.
119 if(c->node->status.waitingforkey && c->node->last_req_key + pingtimeout <= mesh->loop.now.tv_sec) {
120 send_req_key(mesh, c->node);
124 if(c->last_ping_time + pingtimeout <= mesh->loop.now.tv_sec) {
125 if(c->status.active) {
126 if(c->status.pinged) {
127 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);
128 } else if(c->last_ping_time + mesh->dev_class_traits[c->node->devclass].pinginterval <= mesh->loop.now.tv_sec) {
135 if(c->status.connecting) {
136 logger(mesh, MESHLINK_WARNING, "Timeout while connecting to %s", c->name);
138 logger(mesh, MESHLINK_WARNING, "Timeout from %s during authentication", c->name);
142 terminate_connection(mesh, c, c->status.active);
146 timeout_set(&mesh->loop, data, &(struct timeval) {
147 default_timeout, rand() % 100000
151 // devclass asc, last_successfull_connection desc
152 static int node_compare_devclass_asc_lsc_desc(const void *a, const void *b) {
153 const node_t *na = a, *nb = b;
155 if(na->devclass < nb->devclass) {
159 if(na->devclass > nb->devclass) {
163 if(na->last_successfull_connection == nb->last_successfull_connection) {
167 if(na->last_successfull_connection == 0 || na->last_successfull_connection > nb->last_successfull_connection) {
171 if(nb->last_successfull_connection == 0 || na->last_successfull_connection < nb->last_successfull_connection) {
186 // last_successfull_connection desc
187 static int node_compare_lsc_desc(const void *a, const void *b) {
188 const node_t *na = a, *nb = b;
190 if(na->last_successfull_connection == nb->last_successfull_connection) {
194 if(na->last_successfull_connection == 0 || na->last_successfull_connection > nb->last_successfull_connection) {
198 if(nb->last_successfull_connection == 0 || na->last_successfull_connection < nb->last_successfull_connection) {
214 static int node_compare_devclass_desc(const void *a, const void *b) {
215 const node_t *na = a, *nb = b;
217 if(na->devclass < nb->devclass) {
221 if(na->devclass > nb->devclass) {
243 // find the best one for initial connect
248 where dclass <= my.dclass and !connection and (timestamp - last_retry) > retry_timeout
249 order by dclass asc, last_connection desc
255 // 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
259 for i = BACKBONE to my.dclass
260 j += count(from connections where node.dclass = i)
264 where dclass = i and !connection and (timestamp - last_retry) > retry_timeout
265 order by last_connection desc
277 where dclass <= my.dclass and !reachable and (timestamp - last_retry) > retry_timeout
278 order by dclass asc, last_connection desc
290 // 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]
294 for i = BACKBONE to my.dclass
295 j += count(from connections where node.dclass = i)
299 where dclass >= i and outgoing_connection
307 // disconnect connections in case we have more than enough connections
312 where outgoing_connection
324 next (timeout, autoconnect)
331 static void periodic_handler(event_loop_t *loop, void *data) {
332 meshlink_handle_t *mesh = loop->data;
334 /* Check if there are too many contradicting ADD_EDGE and DEL_EDGE messages.
335 This usually only happens when another node has the same Name as this node.
336 If so, sleep for a short while to prevent a storm of contradicting messages.
339 if(mesh->contradicting_del_edge > 100 && mesh->contradicting_add_edge > 100) {
340 logger(mesh, MESHLINK_WARNING, "Possible node with same Name as us! Sleeping %d seconds.", mesh->sleeptime);
341 usleep(mesh->sleeptime * 1000000LL);
342 mesh->sleeptime *= 2;
344 if(mesh->sleeptime < 0) {
345 mesh->sleeptime = 3600;
348 mesh->sleeptime /= 2;
350 if(mesh->sleeptime < 10) {
351 mesh->sleeptime = 10;
355 mesh->contradicting_add_edge = 0;
356 mesh->contradicting_del_edge = 0;
358 int timeout = default_timeout;
360 /* Check if we need to make or break connections. */
362 if(mesh->nodes->count > 1) {
364 logger(mesh, MESHLINK_DEBUG, "--- autoconnect begin ---");
366 int retry_timeout = min(mesh->nodes->count * default_timeout, 60);
368 logger(mesh, MESHLINK_DEBUG, "* devclass = %d", mesh->devclass);
369 logger(mesh, MESHLINK_DEBUG, "* nodes = %d", mesh->nodes->count);
370 logger(mesh, MESHLINK_DEBUG, "* retry_timeout = %d", retry_timeout);
373 // connect disconnect nodes
375 node_t *connect_to = NULL;
376 node_t *disconnect_from = NULL;
381 unsigned int cur_connects = 0;
383 for list_each(connection_t, c, mesh->connections) {
384 if(c->status.active) {
389 logger(mesh, MESHLINK_DEBUG, "* cur_connects = %d", cur_connects);
390 logger(mesh, MESHLINK_DEBUG, "* outgoings = %d", mesh->outgoings->count);
392 // get min_connects and max_connects
394 unsigned int min_connects = mesh->dev_class_traits[mesh->devclass].min_connects;
395 unsigned int max_connects = mesh->dev_class_traits[mesh->devclass].max_connects;
397 logger(mesh, MESHLINK_DEBUG, "* min_connects = %d", min_connects);
398 logger(mesh, MESHLINK_DEBUG, "* max_connects = %d", max_connects);
400 // find the best one for initial connect
402 if(cur_connects < min_connects) {
403 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_asc_lsc_desc, NULL);
405 for splay_each(node_t, n, mesh->nodes) {
406 logger(mesh, MESHLINK_DEBUG, "* %s->devclass = %d", n->name, n->devclass);
408 if(n != mesh->self && n->devclass <= mesh->devclass && !n->connection && !n->status.blacklisted && (n->last_connect_try == 0 || (mesh->loop.now.tv_sec - n->last_connect_try) > retry_timeout)) {
409 splay_insert(nodes, n);
415 connect_to = (node_t *)nodes->head->data;
417 logger(mesh, MESHLINK_DEBUG, "* found best one for initial connect: %s", connect_to->name);
419 logger(mesh, MESHLINK_DEBUG, "* could not find node for initial connect");
422 splay_free_tree(nodes);
426 // find better nodes to connect to
428 if(!connect_to && min_connects <= cur_connects && cur_connects < max_connects) {
429 unsigned int connects = 0;
431 for(dev_class_t devclass = 0; devclass <= mesh->devclass; ++devclass) {
432 for list_each(connection_t, c, mesh->connections) {
433 if(c->status.active && c->node && c->node->devclass == devclass) {
438 if(connects < min_connects) {
439 splay_tree_t *nodes = splay_alloc_tree(node_compare_lsc_desc, NULL);
441 for splay_each(node_t, n, mesh->nodes) {
442 if(n != mesh->self && n->devclass == devclass && !n->connection && !n->status.blacklisted && (n->last_connect_try == 0 || (mesh->loop.now.tv_sec - n->last_connect_try) > retry_timeout)) {
443 splay_insert(nodes, n);
448 logger(mesh, MESHLINK_DEBUG, "* found better node");
449 connect_to = (node_t *)nodes->head->data;
451 splay_free_tree(nodes);
455 splay_free_tree(nodes);
462 logger(mesh, MESHLINK_DEBUG, "* could not find better nodes");
469 if(!connect_to && min_connects <= cur_connects && cur_connects < max_connects) {
470 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_asc_lsc_desc, NULL);
472 for splay_each(node_t, n, mesh->nodes) {
473 if(n != mesh->self && n->devclass <= mesh->devclass && !n->status.reachable && !n->status.blacklisted && (n->last_connect_try == 0 || (mesh->loop.now.tv_sec - n->last_connect_try) > retry_timeout)) {
474 splay_insert(nodes, n);
479 logger(mesh, MESHLINK_DEBUG, "* try to heal partition");
480 connect_to = (node_t *)nodes->head->data;
482 logger(mesh, MESHLINK_DEBUG, "* could not find nodes for partition healing");
485 splay_free_tree(nodes);
491 if(connect_to && !connect_to->connection) {
492 connect_to->last_connect_try = mesh->loop.now.tv_sec;
493 logger(mesh, MESHLINK_DEBUG, "Autoconnect trying to connect to %s", connect_to->name);
495 /* check if there is already a connection attempt to this node */
498 for list_each(outgoing_t, outgoing, mesh->outgoings) {
499 if(outgoing->node == connect_to) {
500 logger(mesh, MESHLINK_DEBUG, "* skip autoconnect since it is an outgoing connection already");
506 if(!connect_to->status.reachable && !node_read_public_key(mesh, connect_to)) {
507 logger(mesh, MESHLINK_DEBUG, "* skip autoconnect since we don't know this node's public key");
512 logger(mesh, MESHLINK_DEBUG, "Autoconnecting to %s", connect_to->name);
513 outgoing_t *outgoing = xzalloc(sizeof(outgoing_t));
514 outgoing->node = connect_to;
515 list_insert_tail(mesh->outgoings, outgoing);
516 setup_outgoing_connection(mesh, outgoing);
521 // disconnect suboptimal outgoing connections
523 if(min_connects < cur_connects /*&& cur_connects <= max_connects*/) {
524 unsigned int connects = 0;
526 for(dev_class_t devclass = 0; devclass <= mesh->devclass; ++devclass) {
527 for list_each(connection_t, c, mesh->connections) {
528 if(c->status.active && c->node && c->node->devclass == devclass) {
533 if(min_connects < connects) {
534 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_desc, NULL);
536 for list_each(connection_t, c, mesh->connections) {
537 if(c->outgoing && c->node && c->node->devclass >= devclass) {
538 splay_insert(nodes, c->node);
543 logger(mesh, MESHLINK_DEBUG, "* disconnect suboptimal outgoing connection");
544 disconnect_from = (node_t *)nodes->head->data;
547 splay_free_tree(nodes);
552 if(!disconnect_from) {
553 logger(mesh, MESHLINK_DEBUG, "* no suboptimal outgoing connections");
558 // disconnect connections (too many connections)
560 if(!disconnect_from && max_connects < cur_connects) {
561 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_desc, NULL);
563 for list_each(connection_t, c, mesh->connections) {
564 if(c->status.active && c->node) {
565 splay_insert(nodes, c->node);
570 logger(mesh, MESHLINK_DEBUG, "* disconnect connection (too many connections)");
573 disconnect_from = (node_t *)nodes->head->data;
575 logger(mesh, MESHLINK_DEBUG, "* no node we want to disconnect, even though we have too many connections");
578 splay_free_tree(nodes);
582 // perform disconnect
584 if(disconnect_from && disconnect_from->connection) {
585 logger(mesh, MESHLINK_DEBUG, "Autodisconnecting from %s", disconnect_from->connection->name);
586 list_delete(mesh->outgoings, disconnect_from->connection->outgoing);
587 disconnect_from->connection->outgoing = NULL;
588 terminate_connection(mesh, disconnect_from->connection, disconnect_from->connection->status.active);
591 // reduce timeout if we don't have enough connections + outgoings
592 if(cur_connects + mesh->outgoings->count < 3) {
598 logger(mesh, MESHLINK_DEBUG, "--- autoconnect end ---");
601 for splay_each(node_t, n, mesh->nodes) {
602 if(n->status.dirty) {
603 node_write_config(mesh, n);
604 n->status.dirty = false;
608 timeout_set(&mesh->loop, data, &(struct timeval) {
609 timeout, rand() % 100000
613 void handle_meta_connection_data(meshlink_handle_t *mesh, connection_t *c) {
614 if(!receive_meta(mesh, c)) {
615 terminate_connection(mesh, c, c->status.active);
620 void retry(meshlink_handle_t *mesh) {
621 /* Reset the reconnection timers for all outgoing connections */
622 for list_each(outgoing_t, outgoing, mesh->outgoings) {
623 outgoing->timeout = 0;
626 timeout_set(&mesh->loop, &outgoing->ev, &(struct timeval) {
631 #ifdef HAVE_IFADDRS_H
632 struct ifaddrs *ifa = NULL;
636 /* For active connections, check if their addresses are still valid.
637 * If yes, reset their ping timers, otherwise terminate them. */
638 for list_each(connection_t, c, mesh->connections) {
639 if(!c->status.active) {
643 if(!c->status.pinged) {
644 c->last_ping_time = 0;
647 #ifdef HAVE_IFADDRS_H
654 socklen_t salen = sizeof(sa);
656 if(getsockname(c->socket, &sa.sa, &salen)) {
662 for(struct ifaddrs *ifap = ifa; ifap; ifap = ifap->ifa_next) {
663 if(ifap->ifa_addr && !sockaddrcmp_noport(&sa, (sockaddr_t *)ifap->ifa_addr)) {
671 logger(mesh, MESHLINK_DEBUG, "Local address for connection to %s no longer valid, terminating", c->name);
672 terminate_connection(mesh, c, c->status.active);
678 #ifdef HAVE_IFADDRS_H
686 /* Kick the ping timeout handler */
687 timeout_set(&mesh->loop, &mesh->pingtimer, &(struct timeval) {
693 this is where it all happens...
695 int main_loop(meshlink_handle_t *mesh) {
696 timeout_add(&mesh->loop, &mesh->pingtimer, timeout_handler, &mesh->pingtimer, &(struct timeval) {
697 default_timeout, rand() % 100000
699 timeout_add(&mesh->loop, &mesh->periodictimer, periodic_handler, &mesh->periodictimer, &(struct timeval) {
704 mesh->datafromapp.signum = 0;
705 signal_add(&(mesh->loop), &(mesh->datafromapp), (signal_cb_t)meshlink_send_from_queue, mesh, mesh->datafromapp.signum);
707 if(!event_loop_run(&(mesh->loop), &(mesh->mesh_mutex))) {
708 logger(mesh, MESHLINK_ERROR, "Error while waiting for input: %s", strerror(errno));
710 timeout_del(&mesh->loop, &mesh->periodictimer);
711 timeout_del(&mesh->loop, &mesh->pingtimer);
716 timeout_del(&mesh->loop, &mesh->periodictimer);
717 timeout_del(&mesh->loop, &mesh->pingtimer);