2 net.c -- most of the network code
3 Copyright (C) 2014 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 const int min(int a, int b) {
43 Terminate a connection:
45 - Remove the edge representing this connection
47 - Check if we need to retry making an outgoing connection
49 void terminate_connection(meshlink_handle_t *mesh, connection_t *c, bool report) {
50 logger(mesh, MESHLINK_INFO, "Closing connection with %s (%s)", c->name, c->hostname);
52 c->status.active = false;
54 if(c->node && c->node->connection == c)
55 c->node->connection = NULL;
59 send_del_edge(mesh, mesh->everyone, c->edge);
61 edge_del(mesh, c->edge);
64 /* Run MST and SSSP algorithms */
68 /* If the node is not reachable anymore but we remember it had an edge to us, clean it up */
70 if(report && !c->node->status.reachable) {
72 e = lookup_edge(c->node, mesh->self);
74 send_del_edge(mesh, mesh->everyone, e);
80 outgoing_t *outgoing = c->outgoing;
81 connection_del(mesh, c);
83 /* Check if this was our outgoing connection */
86 do_outgoing_connection(mesh, outgoing);
89 /* Clean up dead proxy processes */
91 while(waitpid(-1, NULL, WNOHANG) > 0);
96 Check if the other end is active.
97 If we have sent packets, but didn't receive any,
98 then possibly the other end is dead. We send a
99 PING request over the meta connection. If the other
100 end does not reply in time, we consider them dead
101 and close the connection.
103 static void timeout_handler(event_loop_t *loop, void *data) {
104 meshlink_handle_t *mesh = loop->data;
105 logger(mesh, MESHLINK_DEBUG, "timeout_handler()");
107 for list_each(connection_t, c, mesh->connections) {
108 // Also make sure that if outstanding key requests for the UDP counterpart of a connection has timed out, we restart it.
110 if(c->node->status.waitingforkey && c->node->last_req_key + mesh->pingtimeout <= mesh->loop.now.tv_sec)
111 send_req_key(mesh, c->node);
113 if(c->last_ping_time + mesh->pingtimeout <= mesh->loop.now.tv_sec) {
114 if(c->status.active) {
115 if(c->status.pinged) {
116 logger(mesh, MESHLINK_INFO, "%s (%s) didn't respond to PING in %ld seconds", c->name, c->hostname, (long)mesh->loop.now.tv_sec - c->last_ping_time);
117 } else if(c->last_ping_time + mesh->pinginterval <= mesh->loop.now.tv_sec) {
124 if(c->status.connecting)
125 logger(mesh, MESHLINK_WARNING, "Timeout while connecting to %s (%s)", c->name, c->hostname);
127 logger(mesh, MESHLINK_WARNING, "Timeout from %s (%s) during authentication", c->name, c->hostname);
129 terminate_connection(mesh, c, c->status.active);
133 timeout_set(&mesh->loop, data, &(struct timeval){mesh->pingtimeout, rand() % 100000});
136 // devclass asc, last_successfull_connection desc
137 static int node_compare_devclass_asc_lsc_desc(const void *a, const void *b)
139 const node_t *na = a, *nb = b;
141 if(na->devclass < nb->devclass)
144 if(na->devclass > nb->devclass)
147 if(na->last_successfull_connection == nb->last_successfull_connection)
150 if(na->last_successfull_connection == 0 || na->last_successfull_connection > nb->last_successfull_connection)
153 if(nb->last_successfull_connection == 0 || na->last_successfull_connection < nb->last_successfull_connection)
165 // last_successfull_connection desc
166 static int node_compare_lsc_desc(const void *a, const void *b)
168 const node_t *na = a, *nb = b;
170 if(na->last_successfull_connection == nb->last_successfull_connection)
173 if(na->last_successfull_connection == 0 || na->last_successfull_connection > nb->last_successfull_connection)
176 if(nb->last_successfull_connection == 0 || na->last_successfull_connection < nb->last_successfull_connection)
189 static int node_compare_devclass_desc(const void *a, const void *b)
191 const node_t *na = a, *nb = b;
193 if(na->devclass < nb->devclass)
196 if(na->devclass > nb->devclass)
215 // find the best one for initial connect
220 where dclass <= my.dclass and !connection and (timestamp - last_retry) > retry_timeout
221 order by dclass asc, last_connection desc
227 // 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
231 for i = BACKBONE to my.dclass
232 j += count(from connections where node.dclass = i)
236 where dclass = i and !connection and (timestamp - last_retry) > retry_timeout
237 order by last_connection desc
249 where dclass <= my.dclass and !reachable and (timestamp - last_retry) > retry_timeout
250 order by dclass asc, last_connection desc
262 // 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]
266 for i = BACKBONE to my.dclass
267 j += count(from connections where node.dclass = i)
271 where dclass >= i and outgoing_connection
279 // disconnect connections in case we have more than enough connections
284 where outgoing_connection
296 next (timeout, autoconnect)
303 static void periodic_handler(event_loop_t *loop, void *data) {
304 meshlink_handle_t *mesh = loop->data;
306 /* Check if there are too many contradicting ADD_EDGE and DEL_EDGE messages.
307 This usually only happens when another node has the same Name as this node.
308 If so, sleep for a short while to prevent a storm of contradicting messages.
311 if(mesh->contradicting_del_edge > 100 && mesh->contradicting_add_edge > 100) {
312 logger(mesh, MESHLINK_WARNING, "Possible node with same Name as us! Sleeping %d seconds.", mesh->sleeptime);
313 usleep(mesh->sleeptime * 1000000LL);
314 mesh->sleeptime *= 2;
315 if(mesh->sleeptime < 0)
316 mesh->sleeptime = 3600;
318 mesh->sleeptime /= 2;
319 if(mesh->sleeptime < 10)
320 mesh->sleeptime = 10;
323 mesh->contradicting_add_edge = 0;
324 mesh->contradicting_del_edge = 0;
328 /* Check if we need to make or break connections. */
330 if(mesh->nodes->count > 1) {
332 logger(mesh, MESHLINK_DEBUG, "--- autoconnect begin ---");
334 int retry_timeout = min(mesh->nodes->count * 5, 60);
336 logger(mesh, MESHLINK_DEBUG, "* devclass = %d", mesh->devclass);
337 logger(mesh, MESHLINK_DEBUG, "* nodes = %d", mesh->nodes->count);
338 logger(mesh, MESHLINK_DEBUG, "* retry_timeout = %d", retry_timeout);
341 // connect disconnect nodes
343 node_t* connect_to = NULL;
344 node_t* disconnect_from = NULL;
349 int cur_connects = 0;
351 for list_each(connection_t, c, mesh->connections)
359 logger(mesh, MESHLINK_DEBUG, "* cur_connects = %d", cur_connects);
360 logger(mesh, MESHLINK_DEBUG, "* outgoings = %d", mesh->outgoings->count);
362 // get min_connects and max_connects
364 assert(mesh->devclass >= 0 && mesh->devclass <= _DEV_CLASS_MAX);
366 int min_connects = dev_class_traits[mesh->devclass].min_connects;
367 int max_connects = dev_class_traits[mesh->devclass].max_connects;
369 logger(mesh, MESHLINK_DEBUG, "* min_connects = %d", min_connects);
370 logger(mesh, MESHLINK_DEBUG, "* max_connects = %d", max_connects);
373 // find the best one for initial connect
375 if(cur_connects < min_connects)
377 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_asc_lsc_desc, NULL);
379 for splay_each(node_t, n, mesh->nodes)
381 logger(mesh, MESHLINK_DEBUG, "* n->devclass = %d", n->devclass);
382 if(n != mesh->self && n->devclass <= mesh->devclass && !n->connection && (n->last_connect_try == 0 || (time(NULL) - n->last_connect_try) > retry_timeout))
383 { splay_insert(nodes, n); }
388 logger(mesh, MESHLINK_DEBUG, "* found best one for initial connect");
391 connect_to = (node_t*)nodes->head->data;
394 { logger(mesh, MESHLINK_DEBUG, "* could not find node for initial connect"); }
396 splay_free_tree(nodes);
400 // find better nodes to connect to
402 if(!connect_to && min_connects <= cur_connects && cur_connects < max_connects)
404 unsigned int connects = 0;
406 for(int devclass = 0; devclass <= mesh->devclass; ++devclass)
408 for list_each(connection_t, c, mesh->connections)
410 if(c->status.active && c->node && c->node->devclass == devclass)
414 if( connects < min_connects )
416 splay_tree_t *nodes = splay_alloc_tree(node_compare_lsc_desc, NULL);
418 for splay_each(node_t, n, mesh->nodes)
420 if(n != mesh->self && n->devclass == devclass && !n->connection && (n->last_connect_try == 0 || (time(NULL) - n->last_connect_try) > retry_timeout))
421 { splay_insert(nodes, n); }
426 logger(mesh, MESHLINK_DEBUG, "* found better node");
427 connect_to = (node_t*)nodes->head->data;
429 splay_free_tree(nodes);
433 splay_free_tree(nodes);
440 { logger(mesh, MESHLINK_DEBUG, "* could not find better nodes"); }
446 if(!connect_to && min_connects <= cur_connects && cur_connects < max_connects)
448 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_asc_lsc_desc, NULL);
450 for splay_each(node_t, n, mesh->nodes)
452 if(n != mesh->self && n->devclass <= mesh->devclass && !n->status.reachable && (n->last_connect_try == 0 || (time(NULL) - n->last_connect_try) > retry_timeout))
453 { splay_insert(nodes, n); }
458 logger(mesh, MESHLINK_DEBUG, "* try to heal partition");
459 connect_to = (node_t*)nodes->head->data;
462 { logger(mesh, MESHLINK_DEBUG, "* could not find nodes for partition healing"); }
464 splay_free_tree(nodes);
470 if(connect_to && !connect_to->connection)
472 connect_to->last_connect_try = time(NULL);
474 /* check if there is already a connection attempt to this node */
476 for list_each(outgoing_t, outgoing, mesh->outgoings)
478 if(!strcmp(outgoing->name, connect_to->name))
487 logger(mesh, MESHLINK_DEBUG, "Autoconnecting to %s", connect_to->name);
488 outgoing_t *outgoing = xzalloc(sizeof(outgoing_t));
489 outgoing->mesh = mesh;
490 outgoing->name = xstrdup(connect_to->name);
491 list_insert_tail(mesh->outgoings, outgoing);
492 setup_outgoing_connection(mesh, outgoing);
495 { logger(mesh, MESHLINK_DEBUG, "* skip autoconnect since it is an outgoing connection already"); }
499 // disconnect suboptimal outgoing connections
501 if(min_connects < cur_connects /*&& cur_connects <= max_connects*/)
503 unsigned int connects = 0;
505 for(int devclass = 0; devclass <= mesh->devclass; ++devclass)
507 for list_each(connection_t, c, mesh->connections)
509 if(c->status.active && c->node && c->node->devclass == devclass)
513 if( min_connects < connects )
515 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_desc, NULL);
517 for list_each(connection_t, c, mesh->connections)
519 if(c->outgoing && c->node && c->node->devclass >= devclass)
520 { splay_insert(nodes, c->node); }
525 logger(mesh, MESHLINK_DEBUG, "* disconnect suboptimal outgoing connection");
526 disconnect_from = (node_t*)nodes->head->data;
529 splay_free_tree(nodes);
535 { logger(mesh, MESHLINK_DEBUG, "* no suboptimal outgoing connections"); }
539 // disconnect connections (too many connections)
541 if(!disconnect_from && max_connects < cur_connects)
543 splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_desc, NULL);
545 for list_each(connection_t, c, mesh->connections)
547 if(c->status.active && c->node)
548 { splay_insert(nodes, c->node); }
553 logger(mesh, MESHLINK_DEBUG, "* disconnect connection (too many connections)");
556 disconnect_from = (node_t*)nodes->head->data;
559 { logger(mesh, MESHLINK_DEBUG, "* no node we want to disconnect, even though we have too many connections"); }
561 splay_free_tree(nodes);
565 // perform disconnect
567 if(disconnect_from && disconnect_from->connection)
569 logger(mesh, MESHLINK_DEBUG, "Autodisconnecting from %s", disconnect_from->connection->name);
570 list_delete(mesh->outgoings, disconnect_from->connection->outgoing);
571 disconnect_from->connection->outgoing = NULL;
572 terminate_connection(mesh, disconnect_from->connection, disconnect_from->connection->status.active);
578 logger(mesh, MESHLINK_DEBUG, "--- autoconnect end ---");
581 timeout_set(&mesh->loop, data, &(struct timeval){timeout, rand() % 100000});
584 void handle_meta_connection_data(meshlink_handle_t *mesh, connection_t *c) {
585 if (!receive_meta(mesh, c)) {
586 terminate_connection(mesh, c, c->status.active);
591 void retry(meshlink_handle_t *mesh) {
592 /* Reset the reconnection timers for all outgoing connections */
593 for list_each(outgoing_t, outgoing, mesh->outgoings) {
594 outgoing->timeout = 0;
596 timeout_set(&mesh->loop, &outgoing->ev, &(struct timeval){0, 0});
599 /* Check for outgoing connections that are in progress, and reset their ping timers */
600 for list_each(connection_t, c, mesh->connections) {
601 if(c->outgoing && !c->node)
602 c->last_ping_time = 0;
605 /* Kick the ping timeout handler */
606 timeout_set(&mesh->loop, &mesh->pingtimer, &(struct timeval){0, 0});
610 this is where it all happens...
612 int main_loop(meshlink_handle_t *mesh) {
613 timeout_add(&mesh->loop, &mesh->pingtimer, timeout_handler, &mesh->pingtimer, &(struct timeval){mesh->pingtimeout, rand() % 100000});
614 timeout_add(&mesh->loop, &mesh->periodictimer, periodic_handler, &mesh->periodictimer, &(struct timeval){0, 0});
617 mesh->datafromapp.signum = 0;
618 signal_add(&(mesh->loop),&(mesh->datafromapp), (signal_cb_t)meshlink_send_from_queue,mesh, mesh->datafromapp.signum);
620 if(!event_loop_run(&(mesh->loop), &(mesh->mesh_mutex))) {
621 logger(mesh, MESHLINK_ERROR, "Error while waiting for input: %s", strerror(errno));
625 timeout_del(&mesh->loop, &mesh->periodictimer);
626 timeout_del(&mesh->loop, &mesh->pingtimer);