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;
43 static const int default_interval = 60;
46 Terminate a connection:
48 - Remove the edge representing this connection
50 - Check if we need to retry making an outgoing connection
52 void terminate_connection(meshlink_handle_t *mesh, connection_t *c, bool report) {
53 logger(mesh, MESHLINK_INFO, "Closing connection with %s", c->name);
55 c->status.active = false;
57 if(c->node && c->node->connection == c) {
58 c->node->connection = NULL;
63 send_del_edge(mesh, mesh->everyone, c->edge, 0);
66 edge_del(mesh, c->edge);
69 /* Run MST and SSSP algorithms */
73 /* If the node is not reachable anymore but we remember it had an edge to us, clean it up */
75 if(report && c->node && !c->node->status.reachable) {
77 e = lookup_edge(c->node, mesh->self);
80 send_del_edge(mesh, mesh->everyone, e, 0);
86 outgoing_t *outgoing = c->outgoing;
87 connection_del(mesh, c);
89 /* Check if this was our outgoing connection */
92 do_outgoing_connection(mesh, outgoing);
96 /* Clean up dead proxy processes */
98 while(waitpid(-1, NULL, WNOHANG) > 0);
104 Check if the other end is active.
105 If we have sent packets, but didn't receive any,
106 then possibly the other end is dead. We send a
107 PING request over the meta connection. If the other
108 end does not reply in time, we consider them dead
109 and close the connection.
111 static void timeout_handler(event_loop_t *loop, void *data) {
112 meshlink_handle_t *mesh = loop->data;
113 logger(mesh, MESHLINK_DEBUG, "timeout_handler()");
115 for list_each(connection_t, c, mesh->connections) {
116 int pingtimeout = c->node ? mesh->dev_class_traits[c->node->devclass].pingtimeout : default_timeout;
117 int pinginterval = c->node ? mesh->dev_class_traits[c->node->devclass].pinginterval : default_interval;
119 // Also make sure that if outstanding key requests for the UDP counterpart of a connection has timed out, we restart it.
121 if(c->node->status.waitingforkey && c->node->last_req_key + pingtimeout <= mesh->loop.now.tv_sec) {
122 send_req_key(mesh, c->node);
126 if(c->last_ping_time + pingtimeout <= mesh->loop.now.tv_sec) {
127 if(c->status.active) {
128 if(c->status.pinged) {
129 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);
130 } else if(c->last_ping_time + pinginterval <= mesh->loop.now.tv_sec) {
137 if(c->status.connecting) {
138 logger(mesh, MESHLINK_WARNING, "Timeout while connecting to %s", c->name);
140 logger(mesh, MESHLINK_WARNING, "Timeout from %s during authentication", c->name);
144 terminate_connection(mesh, c, c->status.active);
148 timeout_set(&mesh->loop, data, &(struct timeval) {
149 default_timeout, rand() % 100000
153 // devclass asc, last_successfull_connection desc
154 static int node_compare_devclass_asc_lsc_desc(const void *a, const void *b) {
155 const node_t *na = a, *nb = b;
157 if(na->devclass < nb->devclass) {
161 if(na->devclass > nb->devclass) {
165 if(na->last_successfull_connection == nb->last_successfull_connection) {
169 if(na->last_successfull_connection == 0 || na->last_successfull_connection > nb->last_successfull_connection) {
173 if(nb->last_successfull_connection == 0 || na->last_successfull_connection < nb->last_successfull_connection) {
188 // last_successfull_connection desc
189 static int node_compare_lsc_desc(const void *a, const void *b) {
190 const node_t *na = a, *nb = b;
192 if(na->last_successfull_connection == nb->last_successfull_connection) {
196 if(na->last_successfull_connection == 0 || na->last_successfull_connection > nb->last_successfull_connection) {
200 if(nb->last_successfull_connection == 0 || na->last_successfull_connection < nb->last_successfull_connection) {
216 static int node_compare_devclass_desc(const void *a, const void *b) {
217 const node_t *na = a, *nb = b;
219 if(na->devclass < nb->devclass) {
223 if(na->devclass > nb->devclass) {
245 // find the best one for initial connect
250 where dclass <= my.dclass and !connection and (timestamp - last_retry) > retry_timeout
251 order by dclass asc, last_connection desc
257 // 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
261 for i = BACKBONE to my.dclass
262 j += count(from connections where node.dclass = i)
266 where dclass = i and !connection and (timestamp - last_retry) > retry_timeout
267 order by last_connection desc
279 where dclass <= my.dclass and !reachable and (timestamp - last_retry) > retry_timeout
280 order by dclass asc, last_connection desc
292 // 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]
296 for i = BACKBONE to my.dclass
297 j += count(from connections where node.dclass = i)
301 where dclass >= i and outgoing_connection
309 // disconnect connections in case we have more than enough connections
314 where outgoing_connection
326 next (timeout, autoconnect)
333 static void periodic_handler(event_loop_t *loop, void *data) {
334 meshlink_handle_t *mesh = loop->data;
336 /* Check if there are too many contradicting ADD_EDGE and DEL_EDGE messages.
337 This usually only happens when another node has the same Name as this node.
338 If so, sleep for a short while to prevent a storm of contradicting messages.
341 if(mesh->contradicting_del_edge > 100 && mesh->contradicting_add_edge > 100) {
342 logger(mesh, MESHLINK_WARNING, "Possible node with same Name as us! Sleeping %d seconds.", mesh->sleeptime);
343 usleep(mesh->sleeptime * 1000000LL);
344 mesh->sleeptime *= 2;
346 if(mesh->sleeptime < 0) {
347 mesh->sleeptime = 3600;
350 mesh->sleeptime /= 2;
352 if(mesh->sleeptime < 10) {
353 mesh->sleeptime = 10;
357 mesh->contradicting_add_edge = 0;
358 mesh->contradicting_del_edge = 0;
360 int timeout = default_timeout;
362 /* Check if we need to make or break connections. */
364 if(mesh->nodes->count > 1) {
366 logger(mesh, MESHLINK_DEBUG, "--- autoconnect begin ---");
368 int retry_timeout = min(mesh->nodes->count * default_timeout, 60);
370 logger(mesh, MESHLINK_DEBUG, "* devclass = %d", mesh->devclass);
371 logger(mesh, MESHLINK_DEBUG, "* nodes = %d", mesh->nodes->count);
372 logger(mesh, MESHLINK_DEBUG, "* retry_timeout = %d", retry_timeout);
375 // connect disconnect nodes
377 node_t *connect_to = NULL;
378 node_t *disconnect_from = NULL;
383 unsigned int cur_connects = 0;
385 for list_each(connection_t, c, mesh->connections) {
386 if(c->status.active) {
391 logger(mesh, MESHLINK_DEBUG, "* cur_connects = %d", cur_connects);
392 logger(mesh, MESHLINK_DEBUG, "* outgoings = %d", mesh->outgoings->count);
394 // get min_connects and max_connects
396 unsigned int min_connects = mesh->dev_class_traits[mesh->devclass].min_connects;
397 unsigned int max_connects = mesh->dev_class_traits[mesh->devclass].max_connects;
399 logger(mesh, MESHLINK_DEBUG, "* min_connects = %d", min_connects);
400 logger(mesh, MESHLINK_DEBUG, "* max_connects = %d", max_connects);
402 // find the best one for initial connect
404 if(cur_connects < min_connects) {
405 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_asc_lsc_desc, NULL);
407 for splay_each(node_t, n, mesh->nodes) {
408 logger(mesh, MESHLINK_DEBUG, "* %s->devclass = %d", n->name, n->devclass);
410 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)) {
411 splay_insert(nodes, n);
417 connect_to = (node_t *)nodes->head->data;
419 logger(mesh, MESHLINK_DEBUG, "* found best one for initial connect: %s", connect_to->name);
421 logger(mesh, MESHLINK_DEBUG, "* could not find node for initial connect");
424 splay_free_tree(nodes);
428 // find better nodes to connect to
430 if(!connect_to && min_connects <= cur_connects && cur_connects < max_connects) {
431 unsigned int connects = 0;
433 for(dev_class_t devclass = 0; devclass <= mesh->devclass; ++devclass) {
434 for list_each(connection_t, c, mesh->connections) {
435 if(c->status.active && c->node && c->node->devclass == devclass) {
440 if(connects < min_connects) {
441 splay_tree_t *nodes = splay_alloc_tree(node_compare_lsc_desc, NULL);
443 for splay_each(node_t, n, mesh->nodes) {
444 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)) {
445 splay_insert(nodes, n);
450 logger(mesh, MESHLINK_DEBUG, "* found better node");
451 connect_to = (node_t *)nodes->head->data;
453 splay_free_tree(nodes);
457 splay_free_tree(nodes);
464 logger(mesh, MESHLINK_DEBUG, "* could not find better nodes");
471 if(!connect_to && min_connects <= cur_connects && cur_connects < max_connects) {
472 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_asc_lsc_desc, NULL);
474 for splay_each(node_t, n, mesh->nodes) {
475 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)) {
476 splay_insert(nodes, n);
481 logger(mesh, MESHLINK_DEBUG, "* try to heal partition");
482 connect_to = (node_t *)nodes->head->data;
484 logger(mesh, MESHLINK_DEBUG, "* could not find nodes for partition healing");
487 splay_free_tree(nodes);
493 if(connect_to && !connect_to->connection) {
494 connect_to->last_connect_try = mesh->loop.now.tv_sec;
495 logger(mesh, MESHLINK_DEBUG, "Autoconnect trying to connect to %s", connect_to->name);
497 /* check if there is already a connection attempt to this node */
500 for list_each(outgoing_t, outgoing, mesh->outgoings) {
501 if(outgoing->node == connect_to) {
502 logger(mesh, MESHLINK_DEBUG, "* skip autoconnect since it is an outgoing connection already");
508 if(!connect_to->status.reachable && !node_read_public_key(mesh, connect_to)) {
509 logger(mesh, MESHLINK_DEBUG, "* skip autoconnect since we don't know this node's public key");
514 logger(mesh, MESHLINK_DEBUG, "Autoconnecting to %s", connect_to->name);
515 outgoing_t *outgoing = xzalloc(sizeof(outgoing_t));
516 outgoing->node = connect_to;
517 list_insert_tail(mesh->outgoings, outgoing);
518 setup_outgoing_connection(mesh, outgoing);
523 // disconnect suboptimal outgoing connections
525 if(min_connects < cur_connects /*&& cur_connects <= max_connects*/) {
526 unsigned int connects = 0;
528 for(dev_class_t devclass = 0; devclass <= mesh->devclass; ++devclass) {
529 for list_each(connection_t, c, mesh->connections) {
530 if(c->status.active && c->node && c->node->devclass == devclass) {
535 if(min_connects < connects) {
536 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_desc, NULL);
538 for list_each(connection_t, c, mesh->connections) {
539 if(c->outgoing && c->node && c->node->devclass >= devclass) {
540 splay_insert(nodes, c->node);
545 logger(mesh, MESHLINK_DEBUG, "* disconnect suboptimal outgoing connection");
546 disconnect_from = (node_t *)nodes->head->data;
549 splay_free_tree(nodes);
554 if(!disconnect_from) {
555 logger(mesh, MESHLINK_DEBUG, "* no suboptimal outgoing connections");
560 // disconnect connections (too many connections)
562 if(!disconnect_from && max_connects < cur_connects) {
563 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_desc, NULL);
565 for list_each(connection_t, c, mesh->connections) {
566 if(c->status.active && c->node) {
567 splay_insert(nodes, c->node);
572 logger(mesh, MESHLINK_DEBUG, "* disconnect connection (too many connections)");
575 disconnect_from = (node_t *)nodes->head->data;
577 logger(mesh, MESHLINK_DEBUG, "* no node we want to disconnect, even though we have too many connections");
580 splay_free_tree(nodes);
584 // perform disconnect
586 if(disconnect_from && disconnect_from->connection) {
587 logger(mesh, MESHLINK_DEBUG, "Autodisconnecting from %s", disconnect_from->connection->name);
588 list_delete(mesh->outgoings, disconnect_from->connection->outgoing);
589 disconnect_from->connection->outgoing = NULL;
590 terminate_connection(mesh, disconnect_from->connection, disconnect_from->connection->status.active);
593 // reduce timeout if we don't have enough connections + outgoings
594 if(cur_connects + mesh->outgoings->count < 3) {
600 logger(mesh, MESHLINK_DEBUG, "--- autoconnect end ---");
603 for splay_each(node_t, n, mesh->nodes) {
604 if(n->status.dirty) {
605 node_write_config(mesh, n);
606 n->status.dirty = false;
610 timeout_set(&mesh->loop, data, &(struct timeval) {
611 timeout, rand() % 100000
615 void handle_meta_connection_data(meshlink_handle_t *mesh, connection_t *c) {
616 if(!receive_meta(mesh, c)) {
617 terminate_connection(mesh, c, c->status.active);
622 void retry(meshlink_handle_t *mesh) {
623 /* Reset the reconnection timers for all outgoing connections */
624 for list_each(outgoing_t, outgoing, mesh->outgoings) {
625 outgoing->timeout = 0;
628 timeout_set(&mesh->loop, &outgoing->ev, &(struct timeval) {
633 #ifdef HAVE_IFADDRS_H
634 struct ifaddrs *ifa = NULL;
638 /* For active connections, check if their addresses are still valid.
639 * If yes, reset their ping timers, otherwise terminate them. */
640 for list_each(connection_t, c, mesh->connections) {
641 if(!c->status.active) {
645 if(!c->status.pinged) {
646 c->last_ping_time = 0;
649 #ifdef HAVE_IFADDRS_H
656 socklen_t salen = sizeof(sa);
658 if(getsockname(c->socket, &sa.sa, &salen)) {
664 for(struct ifaddrs *ifap = ifa; ifap; ifap = ifap->ifa_next) {
665 if(ifap->ifa_addr && !sockaddrcmp_noport(&sa, (sockaddr_t *)ifap->ifa_addr)) {
673 logger(mesh, MESHLINK_DEBUG, "Local address for connection to %s no longer valid, terminating", c->name);
674 terminate_connection(mesh, c, c->status.active);
680 #ifdef HAVE_IFADDRS_H
688 /* Kick the ping timeout handler */
689 timeout_set(&mesh->loop, &mesh->pingtimer, &(struct timeval) {
695 this is where it all happens...
697 int main_loop(meshlink_handle_t *mesh) {
698 timeout_add(&mesh->loop, &mesh->pingtimer, timeout_handler, &mesh->pingtimer, &(struct timeval) {
699 default_timeout, rand() % 100000
701 timeout_add(&mesh->loop, &mesh->periodictimer, periodic_handler, &mesh->periodictimer, &(struct timeval) {
706 mesh->datafromapp.signum = 0;
707 signal_add(&mesh->loop, &mesh->datafromapp, meshlink_send_from_queue, mesh, mesh->datafromapp.signum);
709 if(!event_loop_run(&mesh->loop, &mesh->mesh_mutex)) {
710 logger(mesh, MESHLINK_ERROR, "Error while waiting for input: %s", strerror(errno));
712 signal_del(&mesh->loop, &mesh->datafromapp);
713 timeout_del(&mesh->loop, &mesh->periodictimer);
714 timeout_del(&mesh->loop, &mesh->pingtimer);
719 signal_del(&mesh->loop, &mesh->datafromapp);
720 timeout_del(&mesh->loop, &mesh->periodictimer);
721 timeout_del(&mesh->loop, &mesh->pingtimer);