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 c->status.active = false;
59 if(c->node && c->node->connection == c) {
60 c->node->connection = NULL;
65 send_del_edge(mesh, mesh->everyone, c->edge, 0);
68 edge_del(mesh, c->edge);
71 /* Run MST and SSSP algorithms */
75 /* If the node is not reachable anymore but we remember it had an edge to us, clean it up */
77 if(report && c->node && !c->node->status.reachable) {
79 e = lookup_edge(c->node, mesh->self);
82 send_del_edge(mesh, mesh->everyone, e, 0);
88 outgoing_t *outgoing = c->outgoing;
89 connection_del(mesh, c);
91 /* Check if this was our outgoing connection */
94 do_outgoing_connection(mesh, outgoing);
99 Check if the other end is active.
100 If we have sent packets, but didn't receive any,
101 then possibly the other end is dead. We send a
102 PING request over the meta connection. If the other
103 end does not reply in time, we consider them dead
104 and close the connection.
106 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 int pingtimeout = c->node ? mesh->dev_class_traits[c->node->devclass].pingtimeout : default_timeout;
114 int pinginterval = c->node ? mesh->dev_class_traits[c->node->devclass].pinginterval : default_interval;
116 if(c->outgoing && c->outgoing->timeout < 5) {
120 // Also make sure that if outstanding key requests for the UDP counterpart of a connection has timed out, we restart it.
122 if(c->node->status.waitingforkey && c->node->last_req_key + pingtimeout <= mesh->loop.now.tv_sec) {
123 send_req_key(mesh, c->node);
127 if(c->status.active && c->last_key_renewal + 3600 < mesh->loop.now.tv_sec) {
128 devtool_sptps_renewal_probe((meshlink_node_t *)c->node);
130 if(!sptps_force_kex(&c->sptps)) {
131 logger(mesh, MESHLINK_ERROR, "SPTPS key renewal for connection with %s failed", c->name);
132 terminate_connection(mesh, c, true);
135 c->last_key_renewal = mesh->loop.now.tv_sec;
139 if(c->last_ping_time + pingtimeout <= mesh->loop.now.tv_sec) {
140 if(c->status.active) {
141 if(c->status.pinged) {
142 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);
143 } else if(c->last_ping_time + pinginterval <= mesh->loop.now.tv_sec) {
150 if(c->status.connecting) {
151 logger(mesh, MESHLINK_WARNING, "Timeout while connecting to %s", c->name);
153 logger(mesh, MESHLINK_WARNING, "Timeout from %s during authentication", c->name);
157 terminate_connection(mesh, c, c->status.active);
161 timeout_set(&mesh->loop, data, &(struct timespec) {
162 1, prng(mesh, TIMER_FUDGE)
166 // devclass asc, last_successfull_connection desc
167 static int node_compare_devclass_asc_lsc_desc(const void *a, const void *b) {
168 const node_t *na = a, *nb = b;
170 if(na->devclass < nb->devclass) {
174 if(na->devclass > nb->devclass) {
178 if(na->last_successfull_connection == nb->last_successfull_connection) {
182 if(na->last_successfull_connection == 0 || na->last_successfull_connection > nb->last_successfull_connection) {
186 if(nb->last_successfull_connection == 0 || na->last_successfull_connection < nb->last_successfull_connection) {
201 // last_successfull_connection desc
202 static int node_compare_lsc_desc(const void *a, const void *b) {
203 const node_t *na = a, *nb = b;
205 if(na->last_successfull_connection == nb->last_successfull_connection) {
209 if(na->last_successfull_connection == 0 || na->last_successfull_connection > nb->last_successfull_connection) {
213 if(nb->last_successfull_connection == 0 || na->last_successfull_connection < nb->last_successfull_connection) {
229 static int node_compare_devclass_desc(const void *a, const void *b) {
230 const node_t *na = a, *nb = b;
232 if(na->devclass < nb->devclass) {
236 if(na->devclass > nb->devclass) {
258 // find the best one for initial connect
263 where dclass <= my.dclass and !connection and (timestamp - last_retry) > retry_timeout
264 order by dclass asc, last_connection desc
270 // 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
274 for i = BACKBONE to my.dclass
275 j += count(from connections where node.dclass = i)
279 where dclass = i and !connection and (timestamp - last_retry) > retry_timeout
280 order by last_connection desc
292 where dclass <= my.dclass and !reachable and (timestamp - last_retry) > retry_timeout
293 order by dclass asc, last_connection desc
305 // 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]
309 for i = BACKBONE to my.dclass
310 j += count(from connections where node.dclass = i)
314 where dclass >= i and outgoing_connection
322 // disconnect connections in case we have more than enough connections
327 where outgoing_connection
339 next (timeout, autoconnect)
346 static void periodic_handler(event_loop_t *loop, void *data) {
347 meshlink_handle_t *mesh = loop->data;
349 /* Check if there are too many contradicting ADD_EDGE and DEL_EDGE messages.
350 This usually only happens when another node has the same Name as this node.
351 If so, sleep for a short while to prevent a storm of contradicting messages.
354 if(mesh->contradicting_del_edge > 100 && mesh->contradicting_add_edge > 100) {
355 logger(mesh, MESHLINK_WARNING, "Possible node with same Name as us! Sleeping %d seconds.", mesh->sleeptime);
356 struct timespec ts = {mesh->sleeptime, 0};
357 nanosleep(&ts, NULL);
358 mesh->sleeptime *= 2;
360 if(mesh->sleeptime < 0) {
361 mesh->sleeptime = 3600;
364 mesh->sleeptime /= 2;
366 if(mesh->sleeptime < 10) {
367 mesh->sleeptime = 10;
371 mesh->contradicting_add_edge = 0;
372 mesh->contradicting_del_edge = 0;
374 int timeout = default_timeout;
376 /* Check if we need to make or break connections. */
378 if(mesh->nodes->count > 1) {
380 logger(mesh, MESHLINK_DEBUG, "--- autoconnect begin ---");
382 int retry_timeout = min(mesh->nodes->count * default_timeout, 60);
384 logger(mesh, MESHLINK_DEBUG, "* devclass = %d", mesh->devclass);
385 logger(mesh, MESHLINK_DEBUG, "* nodes = %d", mesh->nodes->count);
386 logger(mesh, MESHLINK_DEBUG, "* retry_timeout = %d", retry_timeout);
389 // connect disconnect nodes
391 node_t *connect_to = NULL;
392 node_t *disconnect_from = NULL;
397 unsigned int cur_connects = 0;
399 for list_each(connection_t, c, mesh->connections) {
400 if(c->status.active) {
405 logger(mesh, MESHLINK_DEBUG, "* cur_connects = %d", cur_connects);
406 logger(mesh, MESHLINK_DEBUG, "* outgoings = %d", mesh->outgoings->count);
408 // get min_connects and max_connects
410 unsigned int min_connects = mesh->dev_class_traits[mesh->devclass].min_connects;
411 unsigned int max_connects = mesh->dev_class_traits[mesh->devclass].max_connects;
413 logger(mesh, MESHLINK_DEBUG, "* min_connects = %d", min_connects);
414 logger(mesh, MESHLINK_DEBUG, "* max_connects = %d", max_connects);
416 // find the best one for initial connect
418 if(cur_connects < min_connects) {
419 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_asc_lsc_desc, NULL);
421 for splay_each(node_t, n, mesh->nodes) {
422 logger(mesh, MESHLINK_DEBUG, "* %s->devclass = %d", n->name, n->devclass);
424 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)) {
425 splay_insert(nodes, n);
431 connect_to = (node_t *)nodes->head->data;
433 logger(mesh, MESHLINK_DEBUG, "* found best one for initial connect: %s", connect_to->name);
435 logger(mesh, MESHLINK_DEBUG, "* could not find node for initial connect");
438 splay_delete_tree(nodes);
442 // find better nodes to connect to
444 if(!connect_to && min_connects <= cur_connects && cur_connects < max_connects) {
445 unsigned int connects = 0;
447 for(dev_class_t devclass = 0; devclass <= mesh->devclass; ++devclass) {
448 for list_each(connection_t, c, mesh->connections) {
449 if(c->status.active && c->node && c->node->devclass == devclass) {
454 if(connects < min_connects) {
455 splay_tree_t *nodes = splay_alloc_tree(node_compare_lsc_desc, NULL);
457 for splay_each(node_t, n, mesh->nodes) {
458 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)) {
459 splay_insert(nodes, n);
464 logger(mesh, MESHLINK_DEBUG, "* found better node");
465 connect_to = (node_t *)nodes->head->data;
467 splay_delete_tree(nodes);
471 splay_delete_tree(nodes);
478 logger(mesh, MESHLINK_DEBUG, "* could not find better nodes");
485 if(!connect_to && min_connects <= cur_connects && cur_connects < max_connects) {
486 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_asc_lsc_desc, NULL);
488 for splay_each(node_t, n, mesh->nodes) {
489 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)) {
490 splay_insert(nodes, n);
495 logger(mesh, MESHLINK_DEBUG, "* try to heal partition");
496 connect_to = (node_t *)nodes->head->data;
498 logger(mesh, MESHLINK_DEBUG, "* could not find nodes for partition healing");
501 splay_delete_tree(nodes);
507 if(connect_to && !connect_to->connection) {
508 connect_to->last_connect_try = mesh->loop.now.tv_sec;
509 logger(mesh, MESHLINK_DEBUG, "Autoconnect trying to connect to %s", connect_to->name);
511 /* check if there is already a connection attempt to this node */
514 for list_each(outgoing_t, outgoing, mesh->outgoings) {
515 if(outgoing->node == connect_to) {
516 logger(mesh, MESHLINK_DEBUG, "* skip autoconnect since it is an outgoing connection already");
522 if(!connect_to->status.reachable && !node_read_public_key(mesh, connect_to)) {
523 logger(mesh, MESHLINK_DEBUG, "* skip autoconnect since we don't know this node's public key");
528 logger(mesh, MESHLINK_DEBUG, "Autoconnecting to %s", connect_to->name);
529 outgoing_t *outgoing = xzalloc(sizeof(outgoing_t));
530 outgoing->node = connect_to;
531 list_insert_tail(mesh->outgoings, outgoing);
532 setup_outgoing_connection(mesh, outgoing);
537 // disconnect suboptimal outgoing connections
539 if(min_connects < cur_connects /*&& cur_connects <= max_connects*/) {
540 unsigned int connects = 0;
542 for(dev_class_t devclass = 0; devclass <= mesh->devclass; ++devclass) {
543 for list_each(connection_t, c, mesh->connections) {
544 if(c->status.active && c->node && c->node->devclass == devclass) {
549 if(min_connects < connects) {
550 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_desc, NULL);
552 for list_each(connection_t, c, mesh->connections) {
553 if(c->outgoing && c->node && c->node->devclass >= devclass) {
554 splay_insert(nodes, c->node);
559 logger(mesh, MESHLINK_DEBUG, "* disconnect suboptimal outgoing connection");
560 disconnect_from = (node_t *)nodes->head->data;
563 splay_delete_tree(nodes);
568 if(!disconnect_from) {
569 logger(mesh, MESHLINK_DEBUG, "* no suboptimal outgoing connections");
574 // disconnect connections (too many connections)
576 if(!disconnect_from && max_connects < cur_connects) {
577 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_desc, NULL);
579 for list_each(connection_t, c, mesh->connections) {
580 if(c->status.active && c->node) {
581 splay_insert(nodes, c->node);
586 logger(mesh, MESHLINK_DEBUG, "* disconnect connection (too many connections)");
589 disconnect_from = (node_t *)nodes->head->data;
591 logger(mesh, MESHLINK_DEBUG, "* no node we want to disconnect, even though we have too many connections");
594 splay_delete_tree(nodes);
598 // perform disconnect
600 if(disconnect_from && disconnect_from->connection) {
601 logger(mesh, MESHLINK_DEBUG, "Autodisconnecting from %s", disconnect_from->connection->name);
602 list_delete(mesh->outgoings, disconnect_from->connection->outgoing);
603 disconnect_from->connection->outgoing = NULL;
604 terminate_connection(mesh, disconnect_from->connection, disconnect_from->connection->status.active);
607 // reduce timeout if we don't have enough connections + outgoings
608 if(cur_connects + mesh->outgoings->count < 3) {
614 logger(mesh, MESHLINK_DEBUG, "--- autoconnect end ---");
617 for splay_each(node_t, n, mesh->nodes) {
618 if(n->status.dirty) {
619 if(!node_write_config(mesh, n)) {
620 logger(mesh, MESHLINK_DEBUG, "Could not update %s", n->name);
623 n->status.dirty = false;
626 if(n->status.validkey && n->last_req_key + 3600 < mesh->loop.now.tv_sec) {
627 logger(mesh, MESHLINK_DEBUG, "SPTPS key renewal for node %s", n->name);
628 devtool_sptps_renewal_probe((meshlink_node_t *)n);
630 if(!sptps_force_kex(&n->sptps)) {
631 logger(mesh, MESHLINK_ERROR, "SPTPS key renewal for node %s failed", n->name);
632 n->status.validkey = false;
633 sptps_stop(&n->sptps);
634 n->status.waitingforkey = false;
635 n->last_req_key = -3600;
637 n->last_req_key = mesh->loop.now.tv_sec;
642 timeout_set(&mesh->loop, data, &(struct timespec) {
643 timeout, prng(mesh, TIMER_FUDGE)
647 void handle_meta_connection_data(meshlink_handle_t *mesh, connection_t *c) {
648 if(!receive_meta(mesh, c)) {
649 terminate_connection(mesh, c, c->status.active);
654 void retry(meshlink_handle_t *mesh) {
655 /* Reset the reconnection timers for all outgoing connections */
656 for list_each(outgoing_t, outgoing, mesh->outgoings) {
657 outgoing->timeout = 0;
659 if(outgoing->ev.cb) {
660 timeout_set(&mesh->loop, &outgoing->ev, &(struct timespec) {
666 /* For active connections, check if their addresses are still valid.
667 * If yes, reset their ping timers, otherwise terminate them. */
668 for list_each(connection_t, c, mesh->connections) {
669 if(!c->status.active) {
673 if(!c->status.pinged) {
674 c->last_ping_time = -3600;
678 socklen_t salen = sizeof(sa);
680 if(getsockname(c->socket, &sa.sa, &salen)) {
684 switch(sa.sa.sa_family) {
690 sa.in6.sin6_port = 0;
697 int sock = socket(sa.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
703 if(bind(sock, &sa.sa, salen) && errno == EADDRNOTAVAIL) {
704 logger(mesh, MESHLINK_DEBUG, "Local address for connection to %s no longer valid, terminating", c->name);
705 terminate_connection(mesh, c, c->status.active);
711 /* Kick the ping timeout handler */
712 timeout_set(&mesh->loop, &mesh->pingtimer, &(struct timespec) {
718 this is where it all happens...
720 void main_loop(meshlink_handle_t *mesh) {
721 timeout_add(&mesh->loop, &mesh->pingtimer, timeout_handler, &mesh->pingtimer, &(struct timespec) {
722 1, prng(mesh, TIMER_FUDGE)
724 timeout_add(&mesh->loop, &mesh->periodictimer, periodic_handler, &mesh->periodictimer, &(struct timespec) {
729 mesh->datafromapp.signum = 0;
730 signal_add(&mesh->loop, &mesh->datafromapp, meshlink_send_from_queue, mesh, mesh->datafromapp.signum);
732 if(!event_loop_run(&mesh->loop, &mesh->mutex)) {
733 logger(mesh, MESHLINK_ERROR, "Error while waiting for input: %s", strerror(errno));
734 call_error_cb(mesh, MESHLINK_ENETWORK);
737 signal_del(&mesh->loop, &mesh->datafromapp);
738 timeout_del(&mesh->loop, &mesh->periodictimer);
739 timeout_del(&mesh->loop, &mesh->pingtimer);