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"
28 #include "meshlink_internal.h"
39 static inline int min(int a, int b) {
44 static const int default_timeout = 5;
45 static const int default_interval = 60;
48 Terminate a connection:
50 - Remove the edge representing this connection
52 - Check if we need to retry making an outgoing connection
54 void terminate_connection(meshlink_handle_t *mesh, connection_t *c, bool report) {
55 logger(mesh, MESHLINK_INFO, "Closing connection with %s", c->name);
57 if(c->node && c->node->connection == c) {
58 if(c->status.active && mesh->meta_status_cb) {
59 mesh->meta_status_cb(mesh, (meshlink_node_t *)c->node, false);
62 c->node->connection = NULL;
65 c->status.active = false;
69 send_del_edge(mesh, mesh->everyone, c->edge, 0);
72 edge_del(mesh, c->edge);
75 /* Run MST and SSSP algorithms */
79 /* If the node is not reachable anymore but we remember it had an edge to us, clean it up */
81 if(report && c->node && !c->node->status.reachable) {
83 e = lookup_edge(c->node, mesh->self);
86 send_del_edge(mesh, mesh->everyone, e, 0);
92 outgoing_t *outgoing = c->outgoing;
93 connection_del(mesh, c);
95 /* Check if this was our outgoing connection */
98 do_outgoing_connection(mesh, outgoing);
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) {
113 meshlink_handle_t *mesh = loop->data;
114 logger(mesh, MESHLINK_DEBUG, "timeout_handler()");
116 for list_each(connection_t, c, mesh->connections) {
117 int pingtimeout = c->node ? mesh->dev_class_traits[c->node->devclass].pingtimeout : default_timeout;
118 int pinginterval = c->node ? mesh->dev_class_traits[c->node->devclass].pinginterval : default_interval;
120 if(c->outgoing && c->outgoing->timeout < 5) {
124 // Also make sure that if outstanding key requests for the UDP counterpart of a connection has timed out, we restart it.
126 if(c->node->status.waitingforkey && c->node->last_req_key + pingtimeout <= mesh->loop.now.tv_sec) {
127 send_req_key(mesh, c->node);
131 if(c->status.active && c->last_key_renewal + 3600 < mesh->loop.now.tv_sec) {
132 devtool_sptps_renewal_probe((meshlink_node_t *)c->node);
134 if(!sptps_force_kex(&c->sptps)) {
135 logger(mesh, MESHLINK_ERROR, "SPTPS key renewal for connection with %s failed", c->name);
136 terminate_connection(mesh, c, true);
139 c->last_key_renewal = mesh->loop.now.tv_sec;
143 if(c->last_ping_time + pingtimeout <= mesh->loop.now.tv_sec) {
144 if(c->status.active) {
145 if(c->status.pinged) {
146 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);
147 } else if(c->last_ping_time + pinginterval <= mesh->loop.now.tv_sec) {
154 if(c->status.connecting) {
155 logger(mesh, MESHLINK_WARNING, "Timeout while connecting to %s", c->name);
157 logger(mesh, MESHLINK_WARNING, "Timeout from %s during authentication", c->name);
161 terminate_connection(mesh, c, c->status.active);
165 timeout_set(&mesh->loop, data, &(struct timespec) {
166 1, prng(mesh, TIMER_FUDGE)
170 // devclass asc, last_successfull_connection desc
171 static int node_compare_devclass_asc_lsc_desc(const void *a, const void *b) {
172 const node_t *na = a, *nb = b;
174 if(na->devclass < nb->devclass) {
178 if(na->devclass > nb->devclass) {
182 if(na->last_successfull_connection == nb->last_successfull_connection) {
186 if(na->last_successfull_connection == 0 || na->last_successfull_connection > nb->last_successfull_connection) {
190 if(nb->last_successfull_connection == 0 || na->last_successfull_connection < nb->last_successfull_connection) {
205 // last_successfull_connection desc
206 static int node_compare_lsc_desc(const void *a, const void *b) {
207 const node_t *na = a, *nb = b;
209 if(na->last_successfull_connection == nb->last_successfull_connection) {
213 if(na->last_successfull_connection == 0 || na->last_successfull_connection > nb->last_successfull_connection) {
217 if(nb->last_successfull_connection == 0 || na->last_successfull_connection < nb->last_successfull_connection) {
233 static int node_compare_devclass_desc(const void *a, const void *b) {
234 const node_t *na = a, *nb = b;
236 if(na->devclass < nb->devclass) {
240 if(na->devclass > nb->devclass) {
262 // find the best one for initial connect
267 where dclass <= my.dclass and !connection and (timestamp - last_retry) > retry_timeout
268 order by dclass asc, last_connection desc
274 // 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
278 for i = BACKBONE to my.dclass
279 j += count(from connections where node.dclass = i)
283 where dclass = i and !connection and (timestamp - last_retry) > retry_timeout
284 order by last_connection desc
296 where dclass <= my.dclass and !reachable and (timestamp - last_retry) > retry_timeout
297 order by dclass asc, last_connection desc
309 // 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]
313 for i = BACKBONE to my.dclass
314 j += count(from connections where node.dclass = i)
318 where dclass >= i and outgoing_connection
326 // disconnect connections in case we have more than enough connections
331 where outgoing_connection
343 next (timeout, autoconnect)
350 static void periodic_handler(event_loop_t *loop, void *data) {
351 meshlink_handle_t *mesh = loop->data;
353 /* Check if there are too many contradicting ADD_EDGE and DEL_EDGE messages.
354 This usually only happens when another node has the same Name as this node.
355 If so, sleep for a short while to prevent a storm of contradicting messages.
358 if(mesh->contradicting_del_edge > 100 && mesh->contradicting_add_edge > 100) {
359 logger(mesh, MESHLINK_WARNING, "Possible node with same Name as us! Sleeping %d seconds.", mesh->sleeptime);
360 struct timespec ts = {mesh->sleeptime, 0};
361 nanosleep(&ts, NULL);
362 mesh->sleeptime *= 2;
364 if(mesh->sleeptime < 0) {
365 mesh->sleeptime = 3600;
368 mesh->sleeptime /= 2;
370 if(mesh->sleeptime < 10) {
371 mesh->sleeptime = 10;
375 mesh->contradicting_add_edge = 0;
376 mesh->contradicting_del_edge = 0;
378 int timeout = default_timeout;
380 /* Check if we need to make or break connections. */
382 if(mesh->nodes->count > 1) {
384 logger(mesh, MESHLINK_DEBUG, "--- autoconnect begin ---");
386 int retry_timeout = min(mesh->nodes->count * default_timeout, 60);
388 logger(mesh, MESHLINK_DEBUG, "* devclass = %d", mesh->devclass);
389 logger(mesh, MESHLINK_DEBUG, "* nodes = %d", mesh->nodes->count);
390 logger(mesh, MESHLINK_DEBUG, "* retry_timeout = %d", retry_timeout);
393 // connect disconnect nodes
395 node_t *connect_to = NULL;
396 node_t *disconnect_from = NULL;
401 unsigned int cur_connects = 0;
403 for list_each(connection_t, c, mesh->connections) {
404 if(c->status.active) {
409 logger(mesh, MESHLINK_DEBUG, "* cur_connects = %d", cur_connects);
410 logger(mesh, MESHLINK_DEBUG, "* outgoings = %d", mesh->outgoings->count);
412 // get min_connects and max_connects
414 unsigned int min_connects = mesh->dev_class_traits[mesh->devclass].min_connects;
415 unsigned int max_connects = mesh->dev_class_traits[mesh->devclass].max_connects;
417 logger(mesh, MESHLINK_DEBUG, "* min_connects = %d", min_connects);
418 logger(mesh, MESHLINK_DEBUG, "* max_connects = %d", max_connects);
420 // find the best one for initial connect
422 if(cur_connects < min_connects) {
423 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_asc_lsc_desc, NULL);
425 for splay_each(node_t, n, mesh->nodes) {
426 logger(mesh, MESHLINK_DEBUG, "* %s->devclass = %d", n->name, n->devclass);
428 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)) {
429 splay_insert(nodes, n);
435 connect_to = (node_t *)nodes->head->data;
437 logger(mesh, MESHLINK_DEBUG, "* found best one for initial connect: %s", connect_to->name);
439 logger(mesh, MESHLINK_DEBUG, "* could not find node for initial connect");
442 splay_delete_tree(nodes);
446 // find better nodes to connect to
448 if(!connect_to && min_connects <= cur_connects && cur_connects < max_connects) {
449 unsigned int connects = 0;
451 for(dev_class_t devclass = 0; devclass <= mesh->devclass; ++devclass) {
452 for list_each(connection_t, c, mesh->connections) {
453 if(c->status.active && c->node && c->node->devclass == devclass) {
458 if(connects < min_connects) {
459 splay_tree_t *nodes = splay_alloc_tree(node_compare_lsc_desc, NULL);
461 for splay_each(node_t, n, mesh->nodes) {
462 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)) {
463 splay_insert(nodes, n);
468 logger(mesh, MESHLINK_DEBUG, "* found better node");
469 connect_to = (node_t *)nodes->head->data;
471 splay_delete_tree(nodes);
475 splay_delete_tree(nodes);
482 logger(mesh, MESHLINK_DEBUG, "* could not find better nodes");
489 if(!connect_to && min_connects <= cur_connects && cur_connects < max_connects) {
490 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_asc_lsc_desc, NULL);
492 for splay_each(node_t, n, mesh->nodes) {
493 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)) {
494 splay_insert(nodes, n);
499 logger(mesh, MESHLINK_DEBUG, "* try to heal partition");
500 connect_to = (node_t *)nodes->head->data;
502 logger(mesh, MESHLINK_DEBUG, "* could not find nodes for partition healing");
505 splay_delete_tree(nodes);
511 if(connect_to && !connect_to->connection) {
512 connect_to->last_connect_try = mesh->loop.now.tv_sec;
513 logger(mesh, MESHLINK_DEBUG, "Autoconnect trying to connect to %s", connect_to->name);
515 /* check if there is already a connection attempt to this node */
518 for list_each(outgoing_t, outgoing, mesh->outgoings) {
519 if(outgoing->node == connect_to) {
520 logger(mesh, MESHLINK_DEBUG, "* skip autoconnect since it is an outgoing connection already");
526 if(!connect_to->status.reachable && !node_read_public_key(mesh, connect_to)) {
527 logger(mesh, MESHLINK_DEBUG, "* skip autoconnect since we don't know this node's public key");
532 logger(mesh, MESHLINK_DEBUG, "Autoconnecting to %s", connect_to->name);
533 outgoing_t *outgoing = xzalloc(sizeof(outgoing_t));
534 outgoing->node = connect_to;
535 list_insert_tail(mesh->outgoings, outgoing);
536 setup_outgoing_connection(mesh, outgoing);
541 // disconnect suboptimal outgoing connections
543 if(min_connects < cur_connects /*&& cur_connects <= max_connects*/) {
544 unsigned int connects = 0;
546 for(dev_class_t devclass = 0; devclass <= mesh->devclass; ++devclass) {
547 for list_each(connection_t, c, mesh->connections) {
548 if(c->status.active && c->node && c->node->devclass == devclass) {
553 if(min_connects < connects) {
554 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_desc, NULL);
556 for list_each(connection_t, c, mesh->connections) {
557 if(c->outgoing && c->node && c->node->devclass >= devclass) {
558 splay_insert(nodes, c->node);
563 logger(mesh, MESHLINK_DEBUG, "* disconnect suboptimal outgoing connection");
564 disconnect_from = (node_t *)nodes->head->data;
567 splay_delete_tree(nodes);
572 if(!disconnect_from) {
573 logger(mesh, MESHLINK_DEBUG, "* no suboptimal outgoing connections");
578 // disconnect connections (too many connections)
580 if(!disconnect_from && max_connects < cur_connects) {
581 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_desc, NULL);
583 for list_each(connection_t, c, mesh->connections) {
584 if(c->status.active && c->node) {
585 splay_insert(nodes, c->node);
590 logger(mesh, MESHLINK_DEBUG, "* disconnect connection (too many connections)");
593 disconnect_from = (node_t *)nodes->head->data;
595 logger(mesh, MESHLINK_DEBUG, "* no node we want to disconnect, even though we have too many connections");
598 splay_delete_tree(nodes);
602 // perform disconnect
604 if(disconnect_from && disconnect_from->connection) {
605 logger(mesh, MESHLINK_DEBUG, "Autodisconnecting from %s", disconnect_from->connection->name);
606 list_delete(mesh->outgoings, disconnect_from->connection->outgoing);
607 disconnect_from->connection->outgoing = NULL;
608 terminate_connection(mesh, disconnect_from->connection, disconnect_from->connection->status.active);
611 // reduce timeout if we don't have enough connections + outgoings
612 if(cur_connects + mesh->outgoings->count < 3) {
618 logger(mesh, MESHLINK_DEBUG, "--- autoconnect end ---");
621 for splay_each(node_t, n, mesh->nodes) {
622 if(n->status.dirty) {
623 if(!node_write_config(mesh, n)) {
624 logger(mesh, MESHLINK_DEBUG, "Could not update %s", n->name);
627 n->status.dirty = false;
630 if(n->status.validkey && n->last_req_key + 3600 < mesh->loop.now.tv_sec) {
631 logger(mesh, MESHLINK_DEBUG, "SPTPS key renewal for node %s", n->name);
632 devtool_sptps_renewal_probe((meshlink_node_t *)n);
634 if(!sptps_force_kex(&n->sptps)) {
635 logger(mesh, MESHLINK_ERROR, "SPTPS key renewal for node %s failed", n->name);
636 n->status.validkey = false;
637 sptps_stop(&n->sptps);
638 n->status.waitingforkey = false;
639 n->last_req_key = -3600;
641 n->last_req_key = mesh->loop.now.tv_sec;
646 timeout_set(&mesh->loop, data, &(struct timespec) {
647 timeout, prng(mesh, TIMER_FUDGE)
651 void handle_meta_connection_data(meshlink_handle_t *mesh, connection_t *c) {
652 if(!receive_meta(mesh, c)) {
653 terminate_connection(mesh, c, c->status.active);
658 void retry(meshlink_handle_t *mesh) {
659 /* Reset the reconnection timers for all outgoing connections */
660 for list_each(outgoing_t, outgoing, mesh->outgoings) {
661 outgoing->timeout = 0;
663 if(outgoing->ev.cb) {
664 timeout_set(&mesh->loop, &outgoing->ev, &(struct timespec) {
670 /* For active connections, check if their addresses are still valid.
671 * If yes, reset their ping timers, otherwise terminate them. */
672 for list_each(connection_t, c, mesh->connections) {
673 if(!c->status.active) {
677 if(!c->status.pinged) {
678 c->last_ping_time = -3600;
682 socklen_t salen = sizeof(sa);
684 if(getsockname(c->socket, &sa.sa, &salen)) {
688 switch(sa.sa.sa_family) {
694 sa.in6.sin6_port = 0;
701 int sock = socket(sa.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
707 if(bind(sock, &sa.sa, salen) && errno == EADDRNOTAVAIL) {
708 logger(mesh, MESHLINK_DEBUG, "Local address for connection to %s no longer valid, terminating", c->name);
709 terminate_connection(mesh, c, c->status.active);
715 /* Kick the ping timeout handler */
716 timeout_set(&mesh->loop, &mesh->pingtimer, &(struct timespec) {
722 this is where it all happens...
724 void main_loop(meshlink_handle_t *mesh) {
725 timeout_add(&mesh->loop, &mesh->pingtimer, timeout_handler, &mesh->pingtimer, &(struct timespec) {
726 1, prng(mesh, TIMER_FUDGE)
728 timeout_add(&mesh->loop, &mesh->periodictimer, periodic_handler, &mesh->periodictimer, &(struct timespec) {
733 mesh->datafromapp.signum = 0;
734 signal_add(&mesh->loop, &mesh->datafromapp, meshlink_send_from_queue, mesh, mesh->datafromapp.signum);
736 if(!event_loop_run(&mesh->loop, &mesh->mutex)) {
737 logger(mesh, MESHLINK_ERROR, "Error while waiting for input: %s", strerror(errno));
738 call_error_cb(mesh, MESHLINK_ENETWORK);
741 signal_del(&mesh->loop, &mesh->datafromapp);
742 timeout_del(&mesh->loop, &mesh->periodictimer);
743 timeout_del(&mesh->loop, &mesh->pingtimer);