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 if(c->status.active) {
56 logger(mesh, MESHLINK_INFO, "Closing connection with %s", c->name);
59 if(c->node && c->node->connection == c) {
60 if(c->status.active && mesh->meta_status_cb) {
61 mesh->meta_status_cb(mesh, (meshlink_node_t *)c->node, false);
64 c->node->connection = NULL;
67 c->status.active = false;
71 send_del_edge(mesh, mesh->everyone, c->edge, 0);
74 edge_del(mesh, c->edge);
77 /* Run MST and SSSP algorithms */
81 /* If the node is not reachable anymore but we remember it had an edge to us, clean it up */
83 if(report && c->node && !c->node->status.reachable) {
85 e = lookup_edge(c->node, mesh->self);
88 send_del_edge(mesh, mesh->everyone, e, 0);
94 outgoing_t *outgoing = c->outgoing;
95 connection_del(mesh, c);
97 /* Check if this was our outgoing connection */
100 do_outgoing_connection(mesh, outgoing);
105 Check if the other end is active.
106 If we have sent packets, but didn't receive any,
107 then possibly the other end is dead. We send a
108 PING request over the meta connection. If the other
109 end does not reply in time, we consider them dead
110 and close the connection.
112 static void timeout_handler(event_loop_t *loop, void *data) {
115 meshlink_handle_t *mesh = loop->data;
116 logger(mesh, MESHLINK_DEBUG, "timeout_handler()");
118 for list_each(connection_t, c, mesh->connections) {
119 int pingtimeout = c->node ? mesh->dev_class_traits[c->node->devclass].pingtimeout : default_timeout;
120 int pinginterval = c->node ? mesh->dev_class_traits[c->node->devclass].pinginterval : default_interval;
122 if(c->outgoing && !c->status.active && c->outgoing->timeout < 5) {
126 // Also make sure that if outstanding key requests for the UDP counterpart of a connection has timed out, we restart it.
128 if(c->node->status.waitingforkey && c->node->last_req_key + pingtimeout < mesh->loop.now.tv_sec) {
129 send_req_key(mesh, c->node);
133 if(c->status.active && c->last_key_renewal + 3600 < mesh->loop.now.tv_sec) {
134 devtool_sptps_renewal_probe((meshlink_node_t *)c->node);
136 if(!sptps_force_kex(&c->sptps)) {
137 logger(mesh, MESHLINK_ERROR, "SPTPS key renewal for connection with %s failed", c->name);
138 terminate_connection(mesh, c, true);
141 c->last_key_renewal = mesh->loop.now.tv_sec;
145 if(c->last_ping_time + pingtimeout < mesh->loop.now.tv_sec) {
146 if(c->status.active) {
147 if(c->status.pinged) {
148 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);
149 } else if(c->last_ping_time + pinginterval <= mesh->loop.now.tv_sec) {
156 if(c->status.connecting) {
157 logger(mesh, MESHLINK_WARNING, "Timeout while connecting to %s", c->name);
159 logger(mesh, MESHLINK_WARNING, "Timeout from %s during authentication", c->name);
163 terminate_connection(mesh, c, c->status.active);
167 timeout_set(&mesh->loop, data, &(struct timespec) {
168 1, prng(mesh, TIMER_FUDGE)
172 // devclass asc, last_successfull_connection desc
173 static int node_compare_devclass_asc_lsc_desc(const void *a, const void *b) {
174 const node_t *na = a, *nb = b;
176 if(na->devclass < nb->devclass) {
180 if(na->devclass > nb->devclass) {
184 if(na->last_successfull_connection == nb->last_successfull_connection) {
188 if(na->last_successfull_connection == 0 || na->last_successfull_connection > nb->last_successfull_connection) {
192 if(nb->last_successfull_connection == 0 || na->last_successfull_connection < nb->last_successfull_connection) {
207 // last_successfull_connection desc
208 static int node_compare_lsc_desc(const void *a, const void *b) {
209 const node_t *na = a, *nb = b;
211 if(na->last_successfull_connection == nb->last_successfull_connection) {
215 if(na->last_successfull_connection == 0 || na->last_successfull_connection > nb->last_successfull_connection) {
219 if(nb->last_successfull_connection == 0 || na->last_successfull_connection < nb->last_successfull_connection) {
235 static int node_compare_devclass_desc(const void *a, const void *b) {
236 const node_t *na = a, *nb = b;
238 if(na->devclass < nb->devclass) {
242 if(na->devclass > nb->devclass) {
264 // find the best one for initial connect
269 where dclass <= my.dclass and !connection and (timestamp - last_retry) > retry_timeout
270 order by dclass asc, last_connection desc
276 // 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
280 for i = BACKBONE to my.dclass
281 j += count(from connections where node.dclass = i)
285 where dclass = i and !connection and (timestamp - last_retry) > retry_timeout
286 order by last_connection desc
298 where dclass <= my.dclass and !reachable and (timestamp - last_retry) > retry_timeout
299 order by dclass asc, last_connection desc
311 // 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]
315 for i = BACKBONE to my.dclass
316 j += count(from connections where node.dclass = i)
320 where dclass >= i and outgoing_connection
328 // disconnect connections in case we have more than enough connections
333 where outgoing_connection
345 next (timeout, autoconnect)
352 static void periodic_handler(event_loop_t *loop, void *data) {
353 meshlink_handle_t *mesh = loop->data;
355 /* Check if there are too many contradicting ADD_EDGE and DEL_EDGE messages.
356 This usually only happens when another node has the same Name as this node.
357 If so, sleep for a short while to prevent a storm of contradicting messages.
360 if(mesh->contradicting_del_edge > 100 && mesh->contradicting_add_edge > 100) {
361 logger(mesh, MESHLINK_WARNING, "Possible node with same Name as us! Sleeping %d seconds.", mesh->sleeptime);
362 struct timespec ts = {mesh->sleeptime, 0};
363 nanosleep(&ts, NULL);
364 mesh->sleeptime *= 2;
366 if(mesh->sleeptime < 0) {
367 mesh->sleeptime = 3600;
370 mesh->sleeptime /= 2;
372 if(mesh->sleeptime < 10) {
373 mesh->sleeptime = 10;
377 mesh->contradicting_add_edge = 0;
378 mesh->contradicting_del_edge = 0;
380 int timeout = default_timeout;
382 /* Check if we need to make or break connections. */
384 if(mesh->nodes->count > 1) {
386 logger(mesh, MESHLINK_DEBUG, "--- autoconnect begin ---");
388 int retry_timeout = min(mesh->nodes->count * default_timeout, 60);
390 logger(mesh, MESHLINK_DEBUG, "* devclass = %d", mesh->devclass);
391 logger(mesh, MESHLINK_DEBUG, "* nodes = %d", mesh->nodes->count);
392 logger(mesh, MESHLINK_DEBUG, "* retry_timeout = %d", retry_timeout);
395 // connect disconnect nodes
397 node_t *connect_to = NULL;
398 node_t *disconnect_from = NULL;
403 unsigned int cur_connects = 0;
405 for list_each(connection_t, c, mesh->connections) {
406 if(c->status.active) {
411 logger(mesh, MESHLINK_DEBUG, "* cur_connects = %d", cur_connects);
412 logger(mesh, MESHLINK_DEBUG, "* outgoings = %d", mesh->outgoings->count);
414 // get min_connects and max_connects
416 unsigned int min_connects = mesh->dev_class_traits[mesh->devclass].min_connects;
417 unsigned int max_connects = mesh->dev_class_traits[mesh->devclass].max_connects;
419 logger(mesh, MESHLINK_DEBUG, "* min_connects = %d", min_connects);
420 logger(mesh, MESHLINK_DEBUG, "* max_connects = %d", max_connects);
422 // find the best one for initial connect
424 if(cur_connects < min_connects) {
425 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_asc_lsc_desc, NULL);
427 for splay_each(node_t, n, mesh->nodes) {
428 logger(mesh, MESHLINK_DEBUG, "* %s->devclass = %d", n->name, n->devclass);
430 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)) {
431 splay_insert(nodes, n);
437 connect_to = (node_t *)nodes->head->data;
439 logger(mesh, MESHLINK_DEBUG, "* found best one for initial connect: %s", connect_to->name);
441 logger(mesh, MESHLINK_DEBUG, "* could not find node for initial connect");
444 splay_delete_tree(nodes);
448 // find better nodes to connect to
450 if(!connect_to && min_connects <= cur_connects && cur_connects < max_connects) {
451 unsigned int connects = 0;
453 for(dev_class_t devclass = 0; devclass <= mesh->devclass; ++devclass) {
454 for list_each(connection_t, c, mesh->connections) {
455 if(c->status.active && c->node && c->node->devclass == devclass) {
460 if(connects < min_connects) {
461 splay_tree_t *nodes = splay_alloc_tree(node_compare_lsc_desc, NULL);
463 for splay_each(node_t, n, mesh->nodes) {
464 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)) {
465 splay_insert(nodes, n);
470 logger(mesh, MESHLINK_DEBUG, "* found better node");
471 connect_to = (node_t *)nodes->head->data;
473 splay_delete_tree(nodes);
477 splay_delete_tree(nodes);
484 logger(mesh, MESHLINK_DEBUG, "* could not find better nodes");
491 if(!connect_to && min_connects <= cur_connects && cur_connects < max_connects) {
492 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_asc_lsc_desc, NULL);
494 for splay_each(node_t, n, mesh->nodes) {
495 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)) {
496 splay_insert(nodes, n);
501 logger(mesh, MESHLINK_DEBUG, "* try to heal partition");
502 connect_to = (node_t *)nodes->head->data;
504 logger(mesh, MESHLINK_DEBUG, "* could not find nodes for partition healing");
507 splay_delete_tree(nodes);
513 if(connect_to && !connect_to->connection) {
514 connect_to->last_connect_try = mesh->loop.now.tv_sec;
515 logger(mesh, MESHLINK_DEBUG, "Autoconnect trying to connect to %s", connect_to->name);
517 /* check if there is already a connection attempt to this node */
520 for list_each(outgoing_t, outgoing, mesh->outgoings) {
521 if(outgoing->node == connect_to) {
522 logger(mesh, MESHLINK_DEBUG, "* skip autoconnect since it is an outgoing connection already");
528 if(!connect_to->status.reachable && !node_read_public_key(mesh, connect_to)) {
529 logger(mesh, MESHLINK_DEBUG, "* skip autoconnect since we don't know this node's public key");
534 logger(mesh, MESHLINK_DEBUG, "Autoconnecting to %s", connect_to->name);
535 outgoing_t *outgoing = xzalloc(sizeof(outgoing_t));
536 outgoing->node = connect_to;
537 list_insert_tail(mesh->outgoings, outgoing);
538 setup_outgoing_connection(mesh, outgoing);
543 // disconnect suboptimal outgoing connections
545 if(min_connects < cur_connects /*&& cur_connects <= max_connects*/) {
546 unsigned int connects = 0;
548 for(dev_class_t devclass = 0; devclass <= mesh->devclass; ++devclass) {
549 for list_each(connection_t, c, mesh->connections) {
550 if(c->status.active && c->node && c->node->devclass == devclass) {
555 if(min_connects < connects) {
556 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_desc, NULL);
558 for list_each(connection_t, c, mesh->connections) {
559 if(c->outgoing && c->node && c->node->devclass >= devclass) {
560 splay_insert(nodes, c->node);
565 logger(mesh, MESHLINK_DEBUG, "* disconnect suboptimal outgoing connection");
566 disconnect_from = (node_t *)nodes->head->data;
569 splay_delete_tree(nodes);
574 if(!disconnect_from) {
575 logger(mesh, MESHLINK_DEBUG, "* no suboptimal outgoing connections");
580 // disconnect connections (too many connections)
582 if(!disconnect_from && max_connects < cur_connects) {
583 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_desc, NULL);
585 for list_each(connection_t, c, mesh->connections) {
586 if(c->status.active && c->node) {
587 splay_insert(nodes, c->node);
592 logger(mesh, MESHLINK_DEBUG, "* disconnect connection (too many connections)");
595 disconnect_from = (node_t *)nodes->head->data;
597 logger(mesh, MESHLINK_DEBUG, "* no node we want to disconnect, even though we have too many connections");
600 splay_delete_tree(nodes);
604 // perform disconnect
606 if(disconnect_from && disconnect_from->connection) {
607 logger(mesh, MESHLINK_DEBUG, "Autodisconnecting from %s", disconnect_from->connection->name);
608 list_delete(mesh->outgoings, disconnect_from->connection->outgoing);
609 disconnect_from->connection->outgoing = NULL;
610 terminate_connection(mesh, disconnect_from->connection, disconnect_from->connection->status.active);
613 // reduce timeout if we don't have enough connections + outgoings
614 if(cur_connects + mesh->outgoings->count < 3) {
620 logger(mesh, MESHLINK_DEBUG, "--- autoconnect end ---");
623 for splay_each(node_t, n, mesh->nodes) {
624 if(n->status.dirty) {
625 if(!node_write_config(mesh, n, false)) {
626 logger(mesh, MESHLINK_DEBUG, "Could not update %s", n->name);
630 if(n->status.reachable && 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 if(mesh->pingtimer.cb) {
717 timeout_set(&mesh->loop, &mesh->pingtimer, &(struct timespec) {
724 this is where it all happens...
726 void main_loop(meshlink_handle_t *mesh) {
727 timeout_add(&mesh->loop, &mesh->pingtimer, timeout_handler, &mesh->pingtimer, &(struct timespec) {
728 1, prng(mesh, TIMER_FUDGE)
730 timeout_add(&mesh->loop, &mesh->periodictimer, periodic_handler, &mesh->periodictimer, &(struct timespec) {
735 mesh->datafromapp.signum = 0;
736 signal_add(&mesh->loop, &mesh->datafromapp, meshlink_send_from_queue, mesh, mesh->datafromapp.signum);
738 if(!event_loop_run(&mesh->loop, mesh)) {
739 logger(mesh, MESHLINK_ERROR, "Error while waiting for input: %s", strerror(errno));
740 call_error_cb(mesh, MESHLINK_ENETWORK);
743 signal_del(&mesh->loop, &mesh->datafromapp);
744 timeout_del(&mesh->loop, &mesh->periodictimer);
745 timeout_del(&mesh->loop, &mesh->pingtimer);