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);
97 /* Clean up dead proxy processes */
99 while(waitpid(-1, NULL, WNOHANG) > 0);
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->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->last_ping_time + pingtimeout <= mesh->loop.now.tv_sec) {
134 if(c->status.active) {
135 if(c->status.pinged) {
136 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);
137 } else if(c->last_ping_time + pinginterval <= mesh->loop.now.tv_sec) {
144 if(c->status.connecting) {
145 logger(mesh, MESHLINK_WARNING, "Timeout while connecting to %s", c->name);
147 logger(mesh, MESHLINK_WARNING, "Timeout from %s during authentication", c->name);
151 terminate_connection(mesh, c, c->status.active);
155 timeout_set(&mesh->loop, data, &(struct timespec) {
156 1, prng(mesh, TIMER_FUDGE)
160 // devclass asc, last_successfull_connection desc
161 static int node_compare_devclass_asc_lsc_desc(const void *a, const void *b) {
162 const node_t *na = a, *nb = b;
164 if(na->devclass < nb->devclass) {
168 if(na->devclass > nb->devclass) {
172 if(na->last_successfull_connection == nb->last_successfull_connection) {
176 if(na->last_successfull_connection == 0 || na->last_successfull_connection > nb->last_successfull_connection) {
180 if(nb->last_successfull_connection == 0 || na->last_successfull_connection < nb->last_successfull_connection) {
195 // last_successfull_connection desc
196 static int node_compare_lsc_desc(const void *a, const void *b) {
197 const node_t *na = a, *nb = b;
199 if(na->last_successfull_connection == nb->last_successfull_connection) {
203 if(na->last_successfull_connection == 0 || na->last_successfull_connection > nb->last_successfull_connection) {
207 if(nb->last_successfull_connection == 0 || na->last_successfull_connection < nb->last_successfull_connection) {
223 static int node_compare_devclass_desc(const void *a, const void *b) {
224 const node_t *na = a, *nb = b;
226 if(na->devclass < nb->devclass) {
230 if(na->devclass > nb->devclass) {
252 // find the best one for initial connect
257 where dclass <= my.dclass and !connection and (timestamp - last_retry) > retry_timeout
258 order by dclass asc, last_connection desc
264 // 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
268 for i = BACKBONE to my.dclass
269 j += count(from connections where node.dclass = i)
273 where dclass = i and !connection and (timestamp - last_retry) > retry_timeout
274 order by last_connection desc
286 where dclass <= my.dclass and !reachable and (timestamp - last_retry) > retry_timeout
287 order by dclass asc, last_connection desc
299 // 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]
303 for i = BACKBONE to my.dclass
304 j += count(from connections where node.dclass = i)
308 where dclass >= i and outgoing_connection
316 // disconnect connections in case we have more than enough connections
321 where outgoing_connection
333 next (timeout, autoconnect)
340 static void periodic_handler(event_loop_t *loop, void *data) {
341 meshlink_handle_t *mesh = loop->data;
343 /* Check if there are too many contradicting ADD_EDGE and DEL_EDGE messages.
344 This usually only happens when another node has the same Name as this node.
345 If so, sleep for a short while to prevent a storm of contradicting messages.
348 if(mesh->contradicting_del_edge > 100 && mesh->contradicting_add_edge > 100) {
349 logger(mesh, MESHLINK_WARNING, "Possible node with same Name as us! Sleeping %d seconds.", mesh->sleeptime);
350 struct timespec ts = {mesh->sleeptime, 0};
351 clock_nanosleep(CLOCK_MONOTONIC, 0, &ts, NULL);
352 mesh->sleeptime *= 2;
354 if(mesh->sleeptime < 0) {
355 mesh->sleeptime = 3600;
358 mesh->sleeptime /= 2;
360 if(mesh->sleeptime < 10) {
361 mesh->sleeptime = 10;
365 mesh->contradicting_add_edge = 0;
366 mesh->contradicting_del_edge = 0;
368 int timeout = default_timeout;
370 /* Check if we need to make or break connections. */
372 if(mesh->nodes->count > 1) {
374 logger(mesh, MESHLINK_DEBUG, "--- autoconnect begin ---");
376 int retry_timeout = min(mesh->nodes->count * default_timeout, 60);
378 logger(mesh, MESHLINK_DEBUG, "* devclass = %d", mesh->devclass);
379 logger(mesh, MESHLINK_DEBUG, "* nodes = %d", mesh->nodes->count);
380 logger(mesh, MESHLINK_DEBUG, "* retry_timeout = %d", retry_timeout);
383 // connect disconnect nodes
385 node_t *connect_to = NULL;
386 node_t *disconnect_from = NULL;
391 unsigned int cur_connects = 0;
393 for list_each(connection_t, c, mesh->connections) {
394 if(c->status.active) {
399 logger(mesh, MESHLINK_DEBUG, "* cur_connects = %d", cur_connects);
400 logger(mesh, MESHLINK_DEBUG, "* outgoings = %d", mesh->outgoings->count);
402 // get min_connects and max_connects
404 unsigned int min_connects = mesh->dev_class_traits[mesh->devclass].min_connects;
405 unsigned int max_connects = mesh->dev_class_traits[mesh->devclass].max_connects;
407 logger(mesh, MESHLINK_DEBUG, "* min_connects = %d", min_connects);
408 logger(mesh, MESHLINK_DEBUG, "* max_connects = %d", max_connects);
410 // find the best one for initial connect
412 if(cur_connects < min_connects) {
413 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_asc_lsc_desc, NULL);
415 for splay_each(node_t, n, mesh->nodes) {
416 logger(mesh, MESHLINK_DEBUG, "* %s->devclass = %d", n->name, n->devclass);
418 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)) {
419 splay_insert(nodes, n);
425 connect_to = (node_t *)nodes->head->data;
427 logger(mesh, MESHLINK_DEBUG, "* found best one for initial connect: %s", connect_to->name);
429 logger(mesh, MESHLINK_DEBUG, "* could not find node for initial connect");
432 splay_delete_tree(nodes);
436 // find better nodes to connect to
438 if(!connect_to && min_connects <= cur_connects && cur_connects < max_connects) {
439 unsigned int connects = 0;
441 for(dev_class_t devclass = 0; devclass <= mesh->devclass; ++devclass) {
442 for list_each(connection_t, c, mesh->connections) {
443 if(c->status.active && c->node && c->node->devclass == devclass) {
448 if(connects < min_connects) {
449 splay_tree_t *nodes = splay_alloc_tree(node_compare_lsc_desc, NULL);
451 for splay_each(node_t, n, mesh->nodes) {
452 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)) {
453 splay_insert(nodes, n);
458 logger(mesh, MESHLINK_DEBUG, "* found better node");
459 connect_to = (node_t *)nodes->head->data;
461 splay_delete_tree(nodes);
465 splay_delete_tree(nodes);
472 logger(mesh, MESHLINK_DEBUG, "* could not find better nodes");
479 if(!connect_to && min_connects <= cur_connects && cur_connects < max_connects) {
480 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_asc_lsc_desc, NULL);
482 for splay_each(node_t, n, mesh->nodes) {
483 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)) {
484 splay_insert(nodes, n);
489 logger(mesh, MESHLINK_DEBUG, "* try to heal partition");
490 connect_to = (node_t *)nodes->head->data;
492 logger(mesh, MESHLINK_DEBUG, "* could not find nodes for partition healing");
495 splay_delete_tree(nodes);
501 if(connect_to && !connect_to->connection) {
502 connect_to->last_connect_try = mesh->loop.now.tv_sec;
503 logger(mesh, MESHLINK_DEBUG, "Autoconnect trying to connect to %s", connect_to->name);
505 /* check if there is already a connection attempt to this node */
508 for list_each(outgoing_t, outgoing, mesh->outgoings) {
509 if(outgoing->node == connect_to) {
510 logger(mesh, MESHLINK_DEBUG, "* skip autoconnect since it is an outgoing connection already");
516 if(!connect_to->status.reachable && !node_read_public_key(mesh, connect_to)) {
517 logger(mesh, MESHLINK_DEBUG, "* skip autoconnect since we don't know this node's public key");
522 logger(mesh, MESHLINK_DEBUG, "Autoconnecting to %s", connect_to->name);
523 outgoing_t *outgoing = xzalloc(sizeof(outgoing_t));
524 outgoing->node = connect_to;
525 list_insert_tail(mesh->outgoings, outgoing);
526 setup_outgoing_connection(mesh, outgoing);
531 // disconnect suboptimal outgoing connections
533 if(min_connects < cur_connects /*&& cur_connects <= max_connects*/) {
534 unsigned int connects = 0;
536 for(dev_class_t devclass = 0; devclass <= mesh->devclass; ++devclass) {
537 for list_each(connection_t, c, mesh->connections) {
538 if(c->status.active && c->node && c->node->devclass == devclass) {
543 if(min_connects < connects) {
544 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_desc, NULL);
546 for list_each(connection_t, c, mesh->connections) {
547 if(c->outgoing && c->node && c->node->devclass >= devclass) {
548 splay_insert(nodes, c->node);
553 logger(mesh, MESHLINK_DEBUG, "* disconnect suboptimal outgoing connection");
554 disconnect_from = (node_t *)nodes->head->data;
557 splay_delete_tree(nodes);
562 if(!disconnect_from) {
563 logger(mesh, MESHLINK_DEBUG, "* no suboptimal outgoing connections");
568 // disconnect connections (too many connections)
570 if(!disconnect_from && max_connects < cur_connects) {
571 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_desc, NULL);
573 for list_each(connection_t, c, mesh->connections) {
574 if(c->status.active && c->node) {
575 splay_insert(nodes, c->node);
580 logger(mesh, MESHLINK_DEBUG, "* disconnect connection (too many connections)");
583 disconnect_from = (node_t *)nodes->head->data;
585 logger(mesh, MESHLINK_DEBUG, "* no node we want to disconnect, even though we have too many connections");
588 splay_delete_tree(nodes);
592 // perform disconnect
594 if(disconnect_from && disconnect_from->connection) {
595 logger(mesh, MESHLINK_DEBUG, "Autodisconnecting from %s", disconnect_from->connection->name);
596 list_delete(mesh->outgoings, disconnect_from->connection->outgoing);
597 disconnect_from->connection->outgoing = NULL;
598 terminate_connection(mesh, disconnect_from->connection, disconnect_from->connection->status.active);
601 // reduce timeout if we don't have enough connections + outgoings
602 if(cur_connects + mesh->outgoings->count < 3) {
608 logger(mesh, MESHLINK_DEBUG, "--- autoconnect end ---");
611 for splay_each(node_t, n, mesh->nodes) {
612 if(n->status.dirty) {
613 if(node_write_config(mesh, n)) {
614 logger(mesh, MESHLINK_DEBUG, "Could not update %s", n->name);
617 n->status.dirty = false;
620 if(n->status.validkey && n->last_req_key + 3600 < mesh->loop.now.tv_sec) {
621 logger(mesh, MESHLINK_DEBUG, "SPTPS key renewal for node %s", n->name);
623 if(!sptps_force_kex(&n->sptps)) {
624 logger(mesh, MESHLINK_ERROR, "SPTPS key renewal for node %s failed", n->name);
625 n->status.validkey = false;
626 sptps_stop(&n->sptps);
627 n->status.waitingforkey = false;
630 n->last_req_key = mesh->loop.now.tv_sec;
635 timeout_set(&mesh->loop, data, &(struct timespec) {
636 timeout, prng(mesh, TIMER_FUDGE)
640 void handle_meta_connection_data(meshlink_handle_t *mesh, connection_t *c) {
641 if(!receive_meta(mesh, c)) {
642 terminate_connection(mesh, c, c->status.active);
647 void retry(meshlink_handle_t *mesh) {
648 /* Reset the reconnection timers for all outgoing connections */
649 for list_each(outgoing_t, outgoing, mesh->outgoings) {
650 outgoing->timeout = 0;
652 if(outgoing->ev.cb) {
653 timeout_set(&mesh->loop, &outgoing->ev, &(struct timespec) {
659 /* For active connections, check if their addresses are still valid.
660 * If yes, reset their ping timers, otherwise terminate them. */
661 for list_each(connection_t, c, mesh->connections) {
662 if(!c->status.active) {
666 if(!c->status.pinged) {
667 c->last_ping_time = 0;
671 socklen_t salen = sizeof(sa);
673 if(getsockname(c->socket, &sa.sa, &salen)) {
677 switch(sa.sa.sa_family) {
683 sa.in6.sin6_port = 0;
690 int sock = socket(sa.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
696 if(bind(sock, &sa.sa, salen) && errno == EADDRNOTAVAIL) {
697 logger(mesh, MESHLINK_DEBUG, "Local address for connection to %s no longer valid, terminating", c->name);
698 terminate_connection(mesh, c, c->status.active);
704 /* Kick the ping timeout handler */
705 timeout_set(&mesh->loop, &mesh->pingtimer, &(struct timespec) {
711 this is where it all happens...
713 void main_loop(meshlink_handle_t *mesh) {
714 timeout_add(&mesh->loop, &mesh->pingtimer, timeout_handler, &mesh->pingtimer, &(struct timespec) {
715 1, prng(mesh, TIMER_FUDGE)
717 timeout_add(&mesh->loop, &mesh->periodictimer, periodic_handler, &mesh->periodictimer, &(struct timespec) {
722 mesh->datafromapp.signum = 0;
723 signal_add(&mesh->loop, &mesh->datafromapp, meshlink_send_from_queue, mesh, mesh->datafromapp.signum);
725 if(!event_loop_run(&mesh->loop, &mesh->mutex)) {
726 logger(mesh, MESHLINK_ERROR, "Error while waiting for input: %s", strerror(errno));
727 call_error_cb(mesh, MESHLINK_ENETWORK);
730 signal_del(&mesh->loop, &mesh->datafromapp);
731 timeout_del(&mesh->loop, &mesh->periodictimer);
732 timeout_del(&mesh->loop, &mesh->pingtimer);