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"
37 static inline int min(int a, int b) {
42 static const int default_timeout = 5;
43 static const int default_interval = 60;
46 Terminate a connection:
48 - Remove the edge representing this connection
50 - Check if we need to retry making an outgoing connection
52 void terminate_connection(meshlink_handle_t *mesh, connection_t *c, bool report) {
53 logger(mesh, MESHLINK_INFO, "Closing connection with %s", c->name);
55 c->status.active = false;
57 if(c->node && c->node->connection == c) {
58 c->node->connection = NULL;
63 send_del_edge(mesh, mesh->everyone, c->edge, 0);
66 edge_del(mesh, c->edge);
69 /* Run MST and SSSP algorithms */
73 /* If the node is not reachable anymore but we remember it had an edge to us, clean it up */
75 if(report && c->node && !c->node->status.reachable) {
77 e = lookup_edge(c->node, mesh->self);
80 send_del_edge(mesh, mesh->everyone, e, 0);
86 outgoing_t *outgoing = c->outgoing;
87 connection_del(mesh, c);
89 /* Check if this was our outgoing connection */
92 do_outgoing_connection(mesh, outgoing);
96 /* Clean up dead proxy processes */
98 while(waitpid(-1, NULL, WNOHANG) > 0);
104 Check if the other end is active.
105 If we have sent packets, but didn't receive any,
106 then possibly the other end is dead. We send a
107 PING request over the meta connection. If the other
108 end does not reply in time, we consider them dead
109 and close the connection.
111 static void timeout_handler(event_loop_t *loop, void *data) {
114 meshlink_handle_t *mesh = loop->data;
115 logger(mesh, MESHLINK_DEBUG, "timeout_handler()");
117 for list_each(connection_t, c, mesh->connections) {
118 int pingtimeout = c->node ? mesh->dev_class_traits[c->node->devclass].pingtimeout : default_timeout;
119 int pinginterval = c->node ? mesh->dev_class_traits[c->node->devclass].pinginterval : default_interval;
121 if(c->outgoing && c->outgoing->timeout < 5) {
125 // Also make sure that if outstanding key requests for the UDP counterpart of a connection has timed out, we restart it.
127 if(c->node->status.waitingforkey && c->node->last_req_key + pingtimeout <= mesh->loop.now.tv_sec) {
128 send_req_key(mesh, c->node);
132 if(c->last_ping_time + pingtimeout <= mesh->loop.now.tv_sec) {
133 if(c->status.active) {
134 if(c->status.pinged) {
135 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);
136 } else if(c->last_ping_time + pinginterval <= mesh->loop.now.tv_sec) {
143 if(c->status.connecting) {
144 logger(mesh, MESHLINK_WARNING, "Timeout while connecting to %s", c->name);
146 logger(mesh, MESHLINK_WARNING, "Timeout from %s during authentication", c->name);
150 terminate_connection(mesh, c, c->status.active);
154 timeout_set(&mesh->loop, data, &(struct timeval) {
155 1, prng(mesh, TIMER_FUDGE)
159 // devclass asc, last_successfull_connection desc
160 static int node_compare_devclass_asc_lsc_desc(const void *a, const void *b) {
161 const node_t *na = a, *nb = b;
163 if(na->devclass < nb->devclass) {
167 if(na->devclass > nb->devclass) {
171 if(na->last_successfull_connection == nb->last_successfull_connection) {
175 if(na->last_successfull_connection == 0 || na->last_successfull_connection > nb->last_successfull_connection) {
179 if(nb->last_successfull_connection == 0 || na->last_successfull_connection < nb->last_successfull_connection) {
194 // last_successfull_connection desc
195 static int node_compare_lsc_desc(const void *a, const void *b) {
196 const node_t *na = a, *nb = b;
198 if(na->last_successfull_connection == nb->last_successfull_connection) {
202 if(na->last_successfull_connection == 0 || na->last_successfull_connection > nb->last_successfull_connection) {
206 if(nb->last_successfull_connection == 0 || na->last_successfull_connection < nb->last_successfull_connection) {
222 static int node_compare_devclass_desc(const void *a, const void *b) {
223 const node_t *na = a, *nb = b;
225 if(na->devclass < nb->devclass) {
229 if(na->devclass > nb->devclass) {
251 // find the best one for initial connect
256 where dclass <= my.dclass and !connection and (timestamp - last_retry) > retry_timeout
257 order by dclass asc, last_connection desc
263 // 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
267 for i = BACKBONE to my.dclass
268 j += count(from connections where node.dclass = i)
272 where dclass = i and !connection and (timestamp - last_retry) > retry_timeout
273 order by last_connection desc
285 where dclass <= my.dclass and !reachable and (timestamp - last_retry) > retry_timeout
286 order by dclass asc, last_connection desc
298 // 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]
302 for i = BACKBONE to my.dclass
303 j += count(from connections where node.dclass = i)
307 where dclass >= i and outgoing_connection
315 // disconnect connections in case we have more than enough connections
320 where outgoing_connection
332 next (timeout, autoconnect)
339 static void periodic_handler(event_loop_t *loop, void *data) {
340 meshlink_handle_t *mesh = loop->data;
342 /* Check if there are too many contradicting ADD_EDGE and DEL_EDGE messages.
343 This usually only happens when another node has the same Name as this node.
344 If so, sleep for a short while to prevent a storm of contradicting messages.
347 if(mesh->contradicting_del_edge > 100 && mesh->contradicting_add_edge > 100) {
348 logger(mesh, MESHLINK_WARNING, "Possible node with same Name as us! Sleeping %d seconds.", mesh->sleeptime);
349 usleep(mesh->sleeptime * 1000000LL);
350 mesh->sleeptime *= 2;
352 if(mesh->sleeptime < 0) {
353 mesh->sleeptime = 3600;
356 mesh->sleeptime /= 2;
358 if(mesh->sleeptime < 10) {
359 mesh->sleeptime = 10;
363 mesh->contradicting_add_edge = 0;
364 mesh->contradicting_del_edge = 0;
366 int timeout = default_timeout;
368 /* Check if we need to make or break connections. */
370 if(mesh->nodes->count > 1) {
372 logger(mesh, MESHLINK_DEBUG, "--- autoconnect begin ---");
374 int retry_timeout = min(mesh->nodes->count * default_timeout, 60);
376 logger(mesh, MESHLINK_DEBUG, "* devclass = %d", mesh->devclass);
377 logger(mesh, MESHLINK_DEBUG, "* nodes = %d", mesh->nodes->count);
378 logger(mesh, MESHLINK_DEBUG, "* retry_timeout = %d", retry_timeout);
381 // connect disconnect nodes
383 node_t *connect_to = NULL;
384 node_t *disconnect_from = NULL;
389 unsigned int cur_connects = 0;
391 for list_each(connection_t, c, mesh->connections) {
392 if(c->status.active) {
397 logger(mesh, MESHLINK_DEBUG, "* cur_connects = %d", cur_connects);
398 logger(mesh, MESHLINK_DEBUG, "* outgoings = %d", mesh->outgoings->count);
400 // get min_connects and max_connects
402 unsigned int min_connects = mesh->dev_class_traits[mesh->devclass].min_connects;
403 unsigned int max_connects = mesh->dev_class_traits[mesh->devclass].max_connects;
405 logger(mesh, MESHLINK_DEBUG, "* min_connects = %d", min_connects);
406 logger(mesh, MESHLINK_DEBUG, "* max_connects = %d", max_connects);
408 // find the best one for initial connect
410 if(cur_connects < min_connects) {
411 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_asc_lsc_desc, NULL);
413 for splay_each(node_t, n, mesh->nodes) {
414 logger(mesh, MESHLINK_DEBUG, "* %s->devclass = %d", n->name, n->devclass);
416 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)) {
417 splay_insert(nodes, n);
423 connect_to = (node_t *)nodes->head->data;
425 logger(mesh, MESHLINK_DEBUG, "* found best one for initial connect: %s", connect_to->name);
427 logger(mesh, MESHLINK_DEBUG, "* could not find node for initial connect");
430 splay_delete_tree(nodes);
434 // find better nodes to connect to
436 if(!connect_to && min_connects <= cur_connects && cur_connects < max_connects) {
437 unsigned int connects = 0;
439 for(dev_class_t devclass = 0; devclass <= mesh->devclass; ++devclass) {
440 for list_each(connection_t, c, mesh->connections) {
441 if(c->status.active && c->node && c->node->devclass == devclass) {
446 if(connects < min_connects) {
447 splay_tree_t *nodes = splay_alloc_tree(node_compare_lsc_desc, NULL);
449 for splay_each(node_t, n, mesh->nodes) {
450 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)) {
451 splay_insert(nodes, n);
456 logger(mesh, MESHLINK_DEBUG, "* found better node");
457 connect_to = (node_t *)nodes->head->data;
459 splay_delete_tree(nodes);
463 splay_delete_tree(nodes);
470 logger(mesh, MESHLINK_DEBUG, "* could not find better nodes");
477 if(!connect_to && min_connects <= cur_connects && cur_connects < max_connects) {
478 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_asc_lsc_desc, NULL);
480 for splay_each(node_t, n, mesh->nodes) {
481 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)) {
482 splay_insert(nodes, n);
487 logger(mesh, MESHLINK_DEBUG, "* try to heal partition");
488 connect_to = (node_t *)nodes->head->data;
490 logger(mesh, MESHLINK_DEBUG, "* could not find nodes for partition healing");
493 splay_delete_tree(nodes);
499 if(connect_to && !connect_to->connection) {
500 connect_to->last_connect_try = mesh->loop.now.tv_sec;
501 logger(mesh, MESHLINK_DEBUG, "Autoconnect trying to connect to %s", connect_to->name);
503 /* check if there is already a connection attempt to this node */
506 for list_each(outgoing_t, outgoing, mesh->outgoings) {
507 if(outgoing->node == connect_to) {
508 logger(mesh, MESHLINK_DEBUG, "* skip autoconnect since it is an outgoing connection already");
514 if(!connect_to->status.reachable && !node_read_public_key(mesh, connect_to)) {
515 logger(mesh, MESHLINK_DEBUG, "* skip autoconnect since we don't know this node's public key");
520 logger(mesh, MESHLINK_DEBUG, "Autoconnecting to %s", connect_to->name);
521 outgoing_t *outgoing = xzalloc(sizeof(outgoing_t));
522 outgoing->node = connect_to;
523 list_insert_tail(mesh->outgoings, outgoing);
524 setup_outgoing_connection(mesh, outgoing);
529 // disconnect suboptimal outgoing connections
531 if(min_connects < cur_connects /*&& cur_connects <= max_connects*/) {
532 unsigned int connects = 0;
534 for(dev_class_t devclass = 0; devclass <= mesh->devclass; ++devclass) {
535 for list_each(connection_t, c, mesh->connections) {
536 if(c->status.active && c->node && c->node->devclass == devclass) {
541 if(min_connects < connects) {
542 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_desc, NULL);
544 for list_each(connection_t, c, mesh->connections) {
545 if(c->outgoing && c->node && c->node->devclass >= devclass) {
546 splay_insert(nodes, c->node);
551 logger(mesh, MESHLINK_DEBUG, "* disconnect suboptimal outgoing connection");
552 disconnect_from = (node_t *)nodes->head->data;
555 splay_delete_tree(nodes);
560 if(!disconnect_from) {
561 logger(mesh, MESHLINK_DEBUG, "* no suboptimal outgoing connections");
566 // disconnect connections (too many connections)
568 if(!disconnect_from && max_connects < cur_connects) {
569 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_desc, NULL);
571 for list_each(connection_t, c, mesh->connections) {
572 if(c->status.active && c->node) {
573 splay_insert(nodes, c->node);
578 logger(mesh, MESHLINK_DEBUG, "* disconnect connection (too many connections)");
581 disconnect_from = (node_t *)nodes->head->data;
583 logger(mesh, MESHLINK_DEBUG, "* no node we want to disconnect, even though we have too many connections");
586 splay_delete_tree(nodes);
590 // perform disconnect
592 if(disconnect_from && disconnect_from->connection) {
593 logger(mesh, MESHLINK_DEBUG, "Autodisconnecting from %s", disconnect_from->connection->name);
594 list_delete(mesh->outgoings, disconnect_from->connection->outgoing);
595 disconnect_from->connection->outgoing = NULL;
596 terminate_connection(mesh, disconnect_from->connection, disconnect_from->connection->status.active);
599 // reduce timeout if we don't have enough connections + outgoings
600 if(cur_connects + mesh->outgoings->count < 3) {
606 logger(mesh, MESHLINK_DEBUG, "--- autoconnect end ---");
609 for splay_each(node_t, n, mesh->nodes) {
610 if(n->status.dirty) {
611 if(node_write_config(mesh, n)) {
612 logger(mesh, MESHLINK_DEBUG, "Could not update %s", n->name);
615 n->status.dirty = false;
619 timeout_set(&mesh->loop, data, &(struct timeval) {
620 timeout, prng(mesh, TIMER_FUDGE)
624 void handle_meta_connection_data(meshlink_handle_t *mesh, connection_t *c) {
625 if(!receive_meta(mesh, c)) {
626 terminate_connection(mesh, c, c->status.active);
631 void retry(meshlink_handle_t *mesh) {
632 /* Reset the reconnection timers for all outgoing connections */
633 for list_each(outgoing_t, outgoing, mesh->outgoings) {
634 outgoing->timeout = 0;
637 timeout_set(&mesh->loop, &outgoing->ev, &(struct timeval) {
642 /* For active connections, check if their addresses are still valid.
643 * If yes, reset their ping timers, otherwise terminate them. */
644 for list_each(connection_t, c, mesh->connections) {
645 if(!c->status.active) {
649 if(!c->status.pinged) {
650 c->last_ping_time = 0;
654 socklen_t salen = sizeof(sa);
656 if(getsockname(c->socket, &sa.sa, &salen)) {
660 switch(sa.sa.sa_family) {
666 sa.in6.sin6_port = 0;
673 int sock = socket(sa.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
679 if(bind(sock, &sa.sa, salen) && errno == EADDRNOTAVAIL) {
680 logger(mesh, MESHLINK_DEBUG, "Local address for connection to %s no longer valid, terminating", c->name);
681 terminate_connection(mesh, c, c->status.active);
687 /* Kick the ping timeout handler */
688 timeout_set(&mesh->loop, &mesh->pingtimer, &(struct timeval) {
694 this is where it all happens...
696 void main_loop(meshlink_handle_t *mesh) {
697 timeout_add(&mesh->loop, &mesh->pingtimer, timeout_handler, &mesh->pingtimer, &(struct timeval) {
698 1, prng(mesh, TIMER_FUDGE)
700 timeout_add(&mesh->loop, &mesh->periodictimer, periodic_handler, &mesh->periodictimer, &(struct timeval) {
705 mesh->datafromapp.signum = 0;
706 signal_add(&mesh->loop, &mesh->datafromapp, meshlink_send_from_queue, mesh, mesh->datafromapp.signum);
708 if(!event_loop_run(&mesh->loop, &mesh->mutex)) {
709 logger(mesh, MESHLINK_ERROR, "Error while waiting for input: %s", strerror(errno));
710 call_error_cb(mesh, MESHLINK_ENETWORK);
713 signal_del(&mesh->loop, &mesh->datafromapp);
714 timeout_del(&mesh->loop, &mesh->periodictimer);
715 timeout_del(&mesh->loop, &mesh->pingtimer);