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->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 timespec) {
149 1, prng(mesh, TIMER_FUDGE)
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 struct timespec ts = {mesh->sleeptime, 0};
344 clock_nanosleep(CLOCK_MONOTONIC, 0, &ts, NULL);
345 mesh->sleeptime *= 2;
347 if(mesh->sleeptime < 0) {
348 mesh->sleeptime = 3600;
351 mesh->sleeptime /= 2;
353 if(mesh->sleeptime < 10) {
354 mesh->sleeptime = 10;
358 mesh->contradicting_add_edge = 0;
359 mesh->contradicting_del_edge = 0;
361 int timeout = default_timeout;
363 /* Check if we need to make or break connections. */
365 if(mesh->nodes->count > 1) {
367 logger(mesh, MESHLINK_DEBUG, "--- autoconnect begin ---");
369 int retry_timeout = min(mesh->nodes->count * default_timeout, 60);
371 logger(mesh, MESHLINK_DEBUG, "* devclass = %d", mesh->devclass);
372 logger(mesh, MESHLINK_DEBUG, "* nodes = %d", mesh->nodes->count);
373 logger(mesh, MESHLINK_DEBUG, "* retry_timeout = %d", retry_timeout);
376 // connect disconnect nodes
378 node_t *connect_to = NULL;
379 node_t *disconnect_from = NULL;
384 unsigned int cur_connects = 0;
386 for list_each(connection_t, c, mesh->connections) {
387 if(c->status.active) {
392 logger(mesh, MESHLINK_DEBUG, "* cur_connects = %d", cur_connects);
393 logger(mesh, MESHLINK_DEBUG, "* outgoings = %d", mesh->outgoings->count);
395 // get min_connects and max_connects
397 unsigned int min_connects = mesh->dev_class_traits[mesh->devclass].min_connects;
398 unsigned int max_connects = mesh->dev_class_traits[mesh->devclass].max_connects;
400 logger(mesh, MESHLINK_DEBUG, "* min_connects = %d", min_connects);
401 logger(mesh, MESHLINK_DEBUG, "* max_connects = %d", max_connects);
403 // find the best one for initial connect
405 if(cur_connects < min_connects) {
406 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_asc_lsc_desc, NULL);
408 for splay_each(node_t, n, mesh->nodes) {
409 logger(mesh, MESHLINK_DEBUG, "* %s->devclass = %d", n->name, n->devclass);
411 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)) {
412 splay_insert(nodes, n);
418 connect_to = (node_t *)nodes->head->data;
420 logger(mesh, MESHLINK_DEBUG, "* found best one for initial connect: %s", connect_to->name);
422 logger(mesh, MESHLINK_DEBUG, "* could not find node for initial connect");
425 splay_delete_tree(nodes);
429 // find better nodes to connect to
431 if(!connect_to && min_connects <= cur_connects && cur_connects < max_connects) {
432 unsigned int connects = 0;
434 for(dev_class_t devclass = 0; devclass <= mesh->devclass; ++devclass) {
435 for list_each(connection_t, c, mesh->connections) {
436 if(c->status.active && c->node && c->node->devclass == devclass) {
441 if(connects < min_connects) {
442 splay_tree_t *nodes = splay_alloc_tree(node_compare_lsc_desc, NULL);
444 for splay_each(node_t, n, mesh->nodes) {
445 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)) {
446 splay_insert(nodes, n);
451 logger(mesh, MESHLINK_DEBUG, "* found better node");
452 connect_to = (node_t *)nodes->head->data;
454 splay_delete_tree(nodes);
458 splay_delete_tree(nodes);
465 logger(mesh, MESHLINK_DEBUG, "* could not find better nodes");
472 if(!connect_to && min_connects <= cur_connects && cur_connects < max_connects) {
473 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_asc_lsc_desc, NULL);
475 for splay_each(node_t, n, mesh->nodes) {
476 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)) {
477 splay_insert(nodes, n);
482 logger(mesh, MESHLINK_DEBUG, "* try to heal partition");
483 connect_to = (node_t *)nodes->head->data;
485 logger(mesh, MESHLINK_DEBUG, "* could not find nodes for partition healing");
488 splay_delete_tree(nodes);
494 if(connect_to && !connect_to->connection) {
495 connect_to->last_connect_try = mesh->loop.now.tv_sec;
496 logger(mesh, MESHLINK_DEBUG, "Autoconnect trying to connect to %s", connect_to->name);
498 /* check if there is already a connection attempt to this node */
501 for list_each(outgoing_t, outgoing, mesh->outgoings) {
502 if(outgoing->node == connect_to) {
503 logger(mesh, MESHLINK_DEBUG, "* skip autoconnect since it is an outgoing connection already");
509 if(!connect_to->status.reachable && !node_read_public_key(mesh, connect_to)) {
510 logger(mesh, MESHLINK_DEBUG, "* skip autoconnect since we don't know this node's public key");
515 logger(mesh, MESHLINK_DEBUG, "Autoconnecting to %s", connect_to->name);
516 outgoing_t *outgoing = xzalloc(sizeof(outgoing_t));
517 outgoing->node = connect_to;
518 list_insert_tail(mesh->outgoings, outgoing);
519 setup_outgoing_connection(mesh, outgoing);
524 // disconnect suboptimal outgoing connections
526 if(min_connects < cur_connects /*&& cur_connects <= max_connects*/) {
527 unsigned int connects = 0;
529 for(dev_class_t devclass = 0; devclass <= mesh->devclass; ++devclass) {
530 for list_each(connection_t, c, mesh->connections) {
531 if(c->status.active && c->node && c->node->devclass == devclass) {
536 if(min_connects < connects) {
537 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_desc, NULL);
539 for list_each(connection_t, c, mesh->connections) {
540 if(c->outgoing && c->node && c->node->devclass >= devclass) {
541 splay_insert(nodes, c->node);
546 logger(mesh, MESHLINK_DEBUG, "* disconnect suboptimal outgoing connection");
547 disconnect_from = (node_t *)nodes->head->data;
550 splay_delete_tree(nodes);
555 if(!disconnect_from) {
556 logger(mesh, MESHLINK_DEBUG, "* no suboptimal outgoing connections");
561 // disconnect connections (too many connections)
563 if(!disconnect_from && max_connects < cur_connects) {
564 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_desc, NULL);
566 for list_each(connection_t, c, mesh->connections) {
567 if(c->status.active && c->node) {
568 splay_insert(nodes, c->node);
573 logger(mesh, MESHLINK_DEBUG, "* disconnect connection (too many connections)");
576 disconnect_from = (node_t *)nodes->head->data;
578 logger(mesh, MESHLINK_DEBUG, "* no node we want to disconnect, even though we have too many connections");
581 splay_delete_tree(nodes);
585 // perform disconnect
587 if(disconnect_from && disconnect_from->connection) {
588 logger(mesh, MESHLINK_DEBUG, "Autodisconnecting from %s", disconnect_from->connection->name);
589 list_delete(mesh->outgoings, disconnect_from->connection->outgoing);
590 disconnect_from->connection->outgoing = NULL;
591 terminate_connection(mesh, disconnect_from->connection, disconnect_from->connection->status.active);
594 // reduce timeout if we don't have enough connections + outgoings
595 if(cur_connects + mesh->outgoings->count < 3) {
601 logger(mesh, MESHLINK_DEBUG, "--- autoconnect end ---");
604 for splay_each(node_t, n, mesh->nodes) {
605 if(n->status.dirty) {
606 if(!node_write_config(mesh, n)) {
607 logger(mesh, MESHLINK_DEBUG, "Could not update %s", n->name);
610 n->status.dirty = false;
613 if(n->status.validkey && n->last_req_key + 3600 < mesh->loop.now.tv_sec) {
614 logger(mesh, MESHLINK_DEBUG, "SPTPS key renewal for node %s", n->name);
616 if(!sptps_force_kex(&n->sptps)) {
617 logger(mesh, MESHLINK_ERROR, "SPTPS key renewal for node %s failed", n->name);
618 n->status.validkey = false;
619 sptps_stop(&n->sptps);
620 n->status.waitingforkey = false;
623 n->last_req_key = mesh->loop.now.tv_sec;
628 timeout_set(&mesh->loop, data, &(struct timespec) {
629 timeout, prng(mesh, TIMER_FUDGE)
633 void handle_meta_connection_data(meshlink_handle_t *mesh, connection_t *c) {
634 if(!receive_meta(mesh, c)) {
635 terminate_connection(mesh, c, c->status.active);
640 void retry(meshlink_handle_t *mesh) {
641 /* Reset the reconnection timers for all outgoing connections */
642 for list_each(outgoing_t, outgoing, mesh->outgoings) {
643 outgoing->timeout = 0;
645 if(outgoing->ev.cb) {
646 timeout_set(&mesh->loop, &outgoing->ev, &(struct timespec) {
652 /* For active connections, check if their addresses are still valid.
653 * If yes, reset their ping timers, otherwise terminate them. */
654 for list_each(connection_t, c, mesh->connections) {
655 if(!c->status.active) {
659 if(!c->status.pinged) {
660 c->last_ping_time = 0;
664 socklen_t salen = sizeof(sa);
666 if(getsockname(c->socket, &sa.sa, &salen)) {
670 switch(sa.sa.sa_family) {
676 sa.in6.sin6_port = 0;
683 int sock = socket(sa.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
689 if(bind(sock, &sa.sa, salen) && errno == EADDRNOTAVAIL) {
690 logger(mesh, MESHLINK_DEBUG, "Local address for connection to %s no longer valid, terminating", c->name);
691 terminate_connection(mesh, c, c->status.active);
697 /* Kick the ping timeout handler */
698 timeout_set(&mesh->loop, &mesh->pingtimer, &(struct timespec) {
704 this is where it all happens...
706 void main_loop(meshlink_handle_t *mesh) {
707 timeout_add(&mesh->loop, &mesh->pingtimer, timeout_handler, &mesh->pingtimer, &(struct timespec) {
708 1, prng(mesh, TIMER_FUDGE)
710 timeout_add(&mesh->loop, &mesh->periodictimer, periodic_handler, &mesh->periodictimer, &(struct timespec) {
715 mesh->datafromapp.signum = 0;
716 signal_add(&mesh->loop, &mesh->datafromapp, meshlink_send_from_queue, mesh, mesh->datafromapp.signum);
718 if(!event_loop_run(&mesh->loop, &mesh->mutex)) {
719 logger(mesh, MESHLINK_ERROR, "Error while waiting for input: %s", strerror(errno));
720 call_error_cb(mesh, MESHLINK_ENETWORK);
723 signal_del(&mesh->loop, &mesh->datafromapp);
724 timeout_del(&mesh->loop, &mesh->periodictimer);
725 timeout_del(&mesh->loop, &mesh->pingtimer);