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"
38 static inline int min(int a, int b) {
43 static const int default_timeout = 5;
44 static const int default_interval = 60;
47 Terminate a connection:
49 - Remove the edge representing this connection
51 - Check if we need to retry making an outgoing connection
53 void terminate_connection(meshlink_handle_t *mesh, connection_t *c, bool report) {
54 logger(mesh, MESHLINK_INFO, "Closing connection with %s", c->name);
56 c->status.active = false;
58 if(c->node && c->node->connection == c) {
59 c->node->connection = NULL;
64 send_del_edge(mesh, mesh->everyone, c->edge, 0);
67 edge_del(mesh, c->edge);
70 /* Run MST and SSSP algorithms */
74 /* If the node is not reachable anymore but we remember it had an edge to us, clean it up */
76 if(report && c->node && !c->node->status.reachable) {
78 e = lookup_edge(c->node, mesh->self);
81 send_del_edge(mesh, mesh->everyone, e, 0);
87 outgoing_t *outgoing = c->outgoing;
88 connection_del(mesh, c);
90 /* Check if this was our outgoing connection */
93 do_outgoing_connection(mesh, outgoing);
98 Check if the other end is active.
99 If we have sent packets, but didn't receive any,
100 then possibly the other end is dead. We send a
101 PING request over the meta connection. If the other
102 end does not reply in time, we consider them dead
103 and close the connection.
105 static void timeout_handler(event_loop_t *loop, void *data) {
108 meshlink_handle_t *mesh = loop->data;
109 logger(mesh, MESHLINK_DEBUG, "timeout_handler()");
111 for list_each(connection_t, c, mesh->connections) {
112 int pingtimeout = c->node ? mesh->dev_class_traits[c->node->devclass].pingtimeout : default_timeout;
113 int pinginterval = c->node ? mesh->dev_class_traits[c->node->devclass].pinginterval : default_interval;
115 if(c->outgoing && c->outgoing->timeout < 5) {
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->status.active && c->last_key_renewal + 3600 < mesh->loop.now.tv_sec) {
127 if(!sptps_force_kex(&c->sptps)) {
128 logger(mesh, MESHLINK_ERROR, "SPTPS key renewal for connection with %s failed", c->name);
129 terminate_connection(mesh, c, true);
132 c->last_key_renewal = mesh->loop.now.tv_sec;
136 if(c->last_ping_time + pingtimeout <= mesh->loop.now.tv_sec) {
137 if(c->status.active) {
138 if(c->status.pinged) {
139 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);
140 } else if(c->last_ping_time + pinginterval <= mesh->loop.now.tv_sec) {
147 if(c->status.connecting) {
148 logger(mesh, MESHLINK_WARNING, "Timeout while connecting to %s", c->name);
150 logger(mesh, MESHLINK_WARNING, "Timeout from %s during authentication", c->name);
154 terminate_connection(mesh, c, c->status.active);
158 timeout_set(&mesh->loop, data, &(struct timespec) {
159 1, prng(mesh, TIMER_FUDGE)
163 // devclass asc, last_successfull_connection desc
164 static int node_compare_devclass_asc_lsc_desc(const void *a, const void *b) {
165 const node_t *na = a, *nb = b;
167 if(na->devclass < nb->devclass) {
171 if(na->devclass > nb->devclass) {
175 if(na->last_successfull_connection == nb->last_successfull_connection) {
179 if(na->last_successfull_connection == 0 || na->last_successfull_connection > nb->last_successfull_connection) {
183 if(nb->last_successfull_connection == 0 || na->last_successfull_connection < nb->last_successfull_connection) {
198 // last_successfull_connection desc
199 static int node_compare_lsc_desc(const void *a, const void *b) {
200 const node_t *na = a, *nb = b;
202 if(na->last_successfull_connection == nb->last_successfull_connection) {
206 if(na->last_successfull_connection == 0 || na->last_successfull_connection > nb->last_successfull_connection) {
210 if(nb->last_successfull_connection == 0 || na->last_successfull_connection < nb->last_successfull_connection) {
226 static int node_compare_devclass_desc(const void *a, const void *b) {
227 const node_t *na = a, *nb = b;
229 if(na->devclass < nb->devclass) {
233 if(na->devclass > nb->devclass) {
255 // find the best one for initial connect
260 where dclass <= my.dclass and !connection and (timestamp - last_retry) > retry_timeout
261 order by dclass asc, last_connection desc
267 // 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
271 for i = BACKBONE to my.dclass
272 j += count(from connections where node.dclass = i)
276 where dclass = i and !connection and (timestamp - last_retry) > retry_timeout
277 order by last_connection desc
289 where dclass <= my.dclass and !reachable and (timestamp - last_retry) > retry_timeout
290 order by dclass asc, last_connection desc
302 // 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]
306 for i = BACKBONE to my.dclass
307 j += count(from connections where node.dclass = i)
311 where dclass >= i and outgoing_connection
319 // disconnect connections in case we have more than enough connections
324 where outgoing_connection
336 next (timeout, autoconnect)
343 static void periodic_handler(event_loop_t *loop, void *data) {
344 meshlink_handle_t *mesh = loop->data;
346 /* Check if there are too many contradicting ADD_EDGE and DEL_EDGE messages.
347 This usually only happens when another node has the same Name as this node.
348 If so, sleep for a short while to prevent a storm of contradicting messages.
351 if(mesh->contradicting_del_edge > 100 && mesh->contradicting_add_edge > 100) {
352 logger(mesh, MESHLINK_WARNING, "Possible node with same Name as us! Sleeping %d seconds.", mesh->sleeptime);
353 struct timespec ts = {mesh->sleeptime, 0};
354 clock_nanosleep(CLOCK_MONOTONIC, 0, &ts, NULL);
355 mesh->sleeptime *= 2;
357 if(mesh->sleeptime < 0) {
358 mesh->sleeptime = 3600;
361 mesh->sleeptime /= 2;
363 if(mesh->sleeptime < 10) {
364 mesh->sleeptime = 10;
368 mesh->contradicting_add_edge = 0;
369 mesh->contradicting_del_edge = 0;
371 int timeout = default_timeout;
373 /* Check if we need to make or break connections. */
375 if(mesh->nodes->count > 1) {
377 logger(mesh, MESHLINK_DEBUG, "--- autoconnect begin ---");
379 int retry_timeout = min(mesh->nodes->count * default_timeout, 60);
381 logger(mesh, MESHLINK_DEBUG, "* devclass = %d", mesh->devclass);
382 logger(mesh, MESHLINK_DEBUG, "* nodes = %d", mesh->nodes->count);
383 logger(mesh, MESHLINK_DEBUG, "* retry_timeout = %d", retry_timeout);
386 // connect disconnect nodes
388 node_t *connect_to = NULL;
389 node_t *disconnect_from = NULL;
394 unsigned int cur_connects = 0;
396 for list_each(connection_t, c, mesh->connections) {
397 if(c->status.active) {
402 logger(mesh, MESHLINK_DEBUG, "* cur_connects = %d", cur_connects);
403 logger(mesh, MESHLINK_DEBUG, "* outgoings = %d", mesh->outgoings->count);
405 // get min_connects and max_connects
407 unsigned int min_connects = mesh->dev_class_traits[mesh->devclass].min_connects;
408 unsigned int max_connects = mesh->dev_class_traits[mesh->devclass].max_connects;
410 logger(mesh, MESHLINK_DEBUG, "* min_connects = %d", min_connects);
411 logger(mesh, MESHLINK_DEBUG, "* max_connects = %d", max_connects);
413 // find the best one for initial connect
415 if(cur_connects < min_connects) {
416 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_asc_lsc_desc, NULL);
418 for splay_each(node_t, n, mesh->nodes) {
419 logger(mesh, MESHLINK_DEBUG, "* %s->devclass = %d", n->name, n->devclass);
421 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)) {
422 splay_insert(nodes, n);
428 connect_to = (node_t *)nodes->head->data;
430 logger(mesh, MESHLINK_DEBUG, "* found best one for initial connect: %s", connect_to->name);
432 logger(mesh, MESHLINK_DEBUG, "* could not find node for initial connect");
435 splay_delete_tree(nodes);
439 // find better nodes to connect to
441 if(!connect_to && min_connects <= cur_connects && cur_connects < max_connects) {
442 unsigned int connects = 0;
444 for(dev_class_t devclass = 0; devclass <= mesh->devclass; ++devclass) {
445 for list_each(connection_t, c, mesh->connections) {
446 if(c->status.active && c->node && c->node->devclass == devclass) {
451 if(connects < min_connects) {
452 splay_tree_t *nodes = splay_alloc_tree(node_compare_lsc_desc, NULL);
454 for splay_each(node_t, n, mesh->nodes) {
455 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)) {
456 splay_insert(nodes, n);
461 logger(mesh, MESHLINK_DEBUG, "* found better node");
462 connect_to = (node_t *)nodes->head->data;
464 splay_delete_tree(nodes);
468 splay_delete_tree(nodes);
475 logger(mesh, MESHLINK_DEBUG, "* could not find better nodes");
482 if(!connect_to && min_connects <= cur_connects && cur_connects < max_connects) {
483 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_asc_lsc_desc, NULL);
485 for splay_each(node_t, n, mesh->nodes) {
486 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)) {
487 splay_insert(nodes, n);
492 logger(mesh, MESHLINK_DEBUG, "* try to heal partition");
493 connect_to = (node_t *)nodes->head->data;
495 logger(mesh, MESHLINK_DEBUG, "* could not find nodes for partition healing");
498 splay_delete_tree(nodes);
504 if(connect_to && !connect_to->connection) {
505 connect_to->last_connect_try = mesh->loop.now.tv_sec;
506 logger(mesh, MESHLINK_DEBUG, "Autoconnect trying to connect to %s", connect_to->name);
508 /* check if there is already a connection attempt to this node */
511 for list_each(outgoing_t, outgoing, mesh->outgoings) {
512 if(outgoing->node == connect_to) {
513 logger(mesh, MESHLINK_DEBUG, "* skip autoconnect since it is an outgoing connection already");
519 if(!connect_to->status.reachable && !node_read_public_key(mesh, connect_to)) {
520 logger(mesh, MESHLINK_DEBUG, "* skip autoconnect since we don't know this node's public key");
525 logger(mesh, MESHLINK_DEBUG, "Autoconnecting to %s", connect_to->name);
526 outgoing_t *outgoing = xzalloc(sizeof(outgoing_t));
527 outgoing->node = connect_to;
528 list_insert_tail(mesh->outgoings, outgoing);
529 setup_outgoing_connection(mesh, outgoing);
534 // disconnect suboptimal outgoing connections
536 if(min_connects < cur_connects /*&& cur_connects <= max_connects*/) {
537 unsigned int connects = 0;
539 for(dev_class_t devclass = 0; devclass <= mesh->devclass; ++devclass) {
540 for list_each(connection_t, c, mesh->connections) {
541 if(c->status.active && c->node && c->node->devclass == devclass) {
546 if(min_connects < connects) {
547 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_desc, NULL);
549 for list_each(connection_t, c, mesh->connections) {
550 if(c->outgoing && c->node && c->node->devclass >= devclass) {
551 splay_insert(nodes, c->node);
556 logger(mesh, MESHLINK_DEBUG, "* disconnect suboptimal outgoing connection");
557 disconnect_from = (node_t *)nodes->head->data;
560 splay_delete_tree(nodes);
565 if(!disconnect_from) {
566 logger(mesh, MESHLINK_DEBUG, "* no suboptimal outgoing connections");
571 // disconnect connections (too many connections)
573 if(!disconnect_from && max_connects < cur_connects) {
574 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_desc, NULL);
576 for list_each(connection_t, c, mesh->connections) {
577 if(c->status.active && c->node) {
578 splay_insert(nodes, c->node);
583 logger(mesh, MESHLINK_DEBUG, "* disconnect connection (too many connections)");
586 disconnect_from = (node_t *)nodes->head->data;
588 logger(mesh, MESHLINK_DEBUG, "* no node we want to disconnect, even though we have too many connections");
591 splay_delete_tree(nodes);
595 // perform disconnect
597 if(disconnect_from && disconnect_from->connection) {
598 logger(mesh, MESHLINK_DEBUG, "Autodisconnecting from %s", disconnect_from->connection->name);
599 list_delete(mesh->outgoings, disconnect_from->connection->outgoing);
600 disconnect_from->connection->outgoing = NULL;
601 terminate_connection(mesh, disconnect_from->connection, disconnect_from->connection->status.active);
604 // reduce timeout if we don't have enough connections + outgoings
605 if(cur_connects + mesh->outgoings->count < 3) {
611 logger(mesh, MESHLINK_DEBUG, "--- autoconnect end ---");
614 for splay_each(node_t, n, mesh->nodes) {
615 if(n->status.dirty) {
616 if(!node_write_config(mesh, n)) {
617 logger(mesh, MESHLINK_DEBUG, "Could not update %s", n->name);
620 n->status.dirty = false;
623 if(n->status.validkey && n->last_req_key + 3600 < mesh->loop.now.tv_sec) {
624 logger(mesh, MESHLINK_DEBUG, "SPTPS key renewal for node %s", n->name);
626 if(!sptps_force_kex(&n->sptps)) {
627 logger(mesh, MESHLINK_ERROR, "SPTPS key renewal for node %s failed", n->name);
628 n->status.validkey = false;
629 sptps_stop(&n->sptps);
630 n->status.waitingforkey = false;
633 n->last_req_key = mesh->loop.now.tv_sec;
638 timeout_set(&mesh->loop, data, &(struct timespec) {
639 timeout, prng(mesh, TIMER_FUDGE)
643 void handle_meta_connection_data(meshlink_handle_t *mesh, connection_t *c) {
644 if(!receive_meta(mesh, c)) {
645 terminate_connection(mesh, c, c->status.active);
650 void retry(meshlink_handle_t *mesh) {
651 /* Reset the reconnection timers for all outgoing connections */
652 for list_each(outgoing_t, outgoing, mesh->outgoings) {
653 outgoing->timeout = 0;
655 if(outgoing->ev.cb) {
656 timeout_set(&mesh->loop, &outgoing->ev, &(struct timespec) {
662 /* For active connections, check if their addresses are still valid.
663 * If yes, reset their ping timers, otherwise terminate them. */
664 for list_each(connection_t, c, mesh->connections) {
665 if(!c->status.active) {
669 if(!c->status.pinged) {
670 c->last_ping_time = 0;
674 socklen_t salen = sizeof(sa);
676 if(getsockname(c->socket, &sa.sa, &salen)) {
680 switch(sa.sa.sa_family) {
686 sa.in6.sin6_port = 0;
693 int sock = socket(sa.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
699 if(bind(sock, &sa.sa, salen) && errno == EADDRNOTAVAIL) {
700 logger(mesh, MESHLINK_DEBUG, "Local address for connection to %s no longer valid, terminating", c->name);
701 terminate_connection(mesh, c, c->status.active);
707 /* Kick the ping timeout handler */
708 timeout_set(&mesh->loop, &mesh->pingtimer, &(struct timespec) {
714 this is where it all happens...
716 void main_loop(meshlink_handle_t *mesh) {
717 timeout_add(&mesh->loop, &mesh->pingtimer, timeout_handler, &mesh->pingtimer, &(struct timespec) {
718 1, prng(mesh, TIMER_FUDGE)
720 timeout_add(&mesh->loop, &mesh->periodictimer, periodic_handler, &mesh->periodictimer, &(struct timespec) {
725 mesh->datafromapp.signum = 0;
726 signal_add(&mesh->loop, &mesh->datafromapp, meshlink_send_from_queue, mesh, mesh->datafromapp.signum);
728 if(!event_loop_run(&mesh->loop, &mesh->mutex)) {
729 logger(mesh, MESHLINK_ERROR, "Error while waiting for input: %s", strerror(errno));
730 call_error_cb(mesh, MESHLINK_ENETWORK);
733 signal_del(&mesh->loop, &mesh->datafromapp);
734 timeout_del(&mesh->loop, &mesh->periodictimer);
735 timeout_del(&mesh->loop, &mesh->pingtimer);