]> git.meshlink.io Git - meshlink/blob - src/net.c
Rename mesh_mutex to mutex.
[meshlink] / src / net.c
1 /*
2     net.c -- most of the network code
3     Copyright (C) 2014-2017 Guus Sliepen <guus@meshlink.io>
4
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.
9
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.
14
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.
18 */
19
20 #include "system.h"
21
22 #include "utils.h"
23 #include "conf.h"
24 #include "connection.h"
25 #include "graph.h"
26 #include "logger.h"
27 #include "meshlink_internal.h"
28 #include "meta.h"
29 #include "net.h"
30 #include "netutl.h"
31 #include "protocol.h"
32 #include "xalloc.h"
33
34 #include <assert.h>
35
36 #if !defined(min)
37 static inline int min(int a, int b) {
38         return a < b ? a : b;
39 }
40 #endif
41
42 static const int default_timeout = 5;
43 static const int default_interval = 60;
44
45 /*
46   Terminate a connection:
47   - Mark it as inactive
48   - Remove the edge representing this connection
49   - Kill it with fire
50   - Check if we need to retry making an outgoing connection
51 */
52 void terminate_connection(meshlink_handle_t *mesh, connection_t *c, bool report) {
53         logger(mesh, MESHLINK_INFO, "Closing connection with %s", c->name);
54
55         c->status.active = false;
56
57         if(c->node && c->node->connection == c) {
58                 c->node->connection = NULL;
59         }
60
61         if(c->edge) {
62                 if(report) {
63                         send_del_edge(mesh, mesh->everyone, c->edge, 0);
64                 }
65
66                 edge_del(mesh, c->edge);
67                 c->edge = NULL;
68
69                 /* Run MST and SSSP algorithms */
70
71                 graph(mesh);
72
73                 /* If the node is not reachable anymore but we remember it had an edge to us, clean it up */
74
75                 if(report && c->node && !c->node->status.reachable) {
76                         edge_t *e;
77                         e = lookup_edge(c->node, mesh->self);
78
79                         if(e) {
80                                 send_del_edge(mesh, mesh->everyone, e, 0);
81                                 edge_del(mesh, e);
82                         }
83                 }
84         }
85
86         outgoing_t *outgoing = c->outgoing;
87         connection_del(mesh, c);
88
89         /* Check if this was our outgoing connection */
90
91         if(outgoing) {
92                 do_outgoing_connection(mesh, outgoing);
93         }
94
95 #ifndef HAVE_MINGW
96         /* Clean up dead proxy processes */
97
98         while(waitpid(-1, NULL, WNOHANG) > 0);
99
100 #endif
101 }
102
103 /*
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.
110 */
111 static void timeout_handler(event_loop_t *loop, void *data) {
112         assert(data);
113
114         meshlink_handle_t *mesh = loop->data;
115         logger(mesh, MESHLINK_DEBUG, "timeout_handler()");
116
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;
120
121                 // Also make sure that if outstanding key requests for the UDP counterpart of a connection has timed out, we restart it.
122                 if(c->node) {
123                         if(c->node->status.waitingforkey && c->node->last_req_key + pingtimeout <= mesh->loop.now.tv_sec) {
124                                 send_req_key(mesh, c->node);
125                         }
126                 }
127
128                 if(c->last_ping_time + pingtimeout <= mesh->loop.now.tv_sec) {
129                         if(c->status.active) {
130                                 if(c->status.pinged) {
131                                         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);
132                                 } else if(c->last_ping_time + pinginterval <= mesh->loop.now.tv_sec) {
133                                         send_ping(mesh, c);
134                                         continue;
135                                 } else {
136                                         continue;
137                                 }
138                         } else {
139                                 if(c->status.connecting) {
140                                         logger(mesh, MESHLINK_WARNING, "Timeout while connecting to %s", c->name);
141                                 } else {
142                                         logger(mesh, MESHLINK_WARNING, "Timeout from %s during authentication", c->name);
143                                 }
144                         }
145
146                         terminate_connection(mesh, c, c->status.active);
147                 }
148         }
149
150         timeout_set(&mesh->loop, data, &(struct timeval) {
151                 default_timeout, prng(mesh, TIMER_FUDGE)
152         });
153 }
154
155 // devclass asc, last_successfull_connection desc
156 static int node_compare_devclass_asc_lsc_desc(const void *a, const void *b) {
157         const node_t *na = a, *nb = b;
158
159         if(na->devclass < nb->devclass) {
160                 return -1;
161         }
162
163         if(na->devclass > nb->devclass) {
164                 return 1;
165         }
166
167         if(na->last_successfull_connection == nb->last_successfull_connection) {
168                 return 0;
169         }
170
171         if(na->last_successfull_connection == 0 || na->last_successfull_connection > nb->last_successfull_connection) {
172                 return -1;
173         }
174
175         if(nb->last_successfull_connection == 0 || na->last_successfull_connection < nb->last_successfull_connection) {
176                 return 1;
177         }
178
179         if(na < nb) {
180                 return -1;
181         }
182
183         if(na > nb) {
184                 return 1;
185         }
186
187         return 0;
188 }
189
190 // last_successfull_connection desc
191 static int node_compare_lsc_desc(const void *a, const void *b) {
192         const node_t *na = a, *nb = b;
193
194         if(na->last_successfull_connection == nb->last_successfull_connection) {
195                 return 0;
196         }
197
198         if(na->last_successfull_connection == 0 || na->last_successfull_connection > nb->last_successfull_connection) {
199                 return -1;
200         }
201
202         if(nb->last_successfull_connection == 0 || na->last_successfull_connection < nb->last_successfull_connection) {
203                 return 1;
204         }
205
206         if(na < nb) {
207                 return -1;
208         }
209
210         if(na > nb) {
211                 return 1;
212         }
213
214         return 0;
215 }
216
217 // devclass desc
218 static int node_compare_devclass_desc(const void *a, const void *b) {
219         const node_t *na = a, *nb = b;
220
221         if(na->devclass < nb->devclass) {
222                 return -1;
223         }
224
225         if(na->devclass > nb->devclass) {
226                 return 1;
227         }
228
229         if(na < nb) {
230                 return -1;
231         }
232
233         if(na > nb) {
234                 return 1;
235         }
236
237         return 0;
238 }
239
240
241 /*
242
243 autoconnect()
244 {
245         timeout = 5
246
247         // find the best one for initial connect
248
249         if cur < min
250                 newcon =
251                         first from nodes
252                                 where dclass <= my.dclass and !connection and (timestamp - last_retry) > retry_timeout
253                                 order by dclass asc, last_connection desc
254                 if newcon
255                         timeout = 0
256                         goto connect
257
258
259         // 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
260
261         if min <= cur < max
262                 j = 0
263                 for i = BACKBONE to my.dclass
264                         j += count(from connections where node.dclass = i)
265                         if j < min
266                                 newcon =
267                                         first from nodes
268                                                 where dclass = i and !connection and (timestamp - last_retry) > retry_timeout
269                                                 order by last_connection desc
270                                 if newcon
271                                         goto connect
272                         else
273                                 break
274
275
276         // heal partitions
277
278         if min <= cur < max
279                 newcon =
280                         first from nodes
281                                 where dclass <= my.dclass and !reachable and (timestamp - last_retry) > retry_timeout
282                                 order by dclass asc, last_connection desc
283                 if newcon
284                         goto connect
285
286
287         // connect
288
289 connect:
290         if newcon
291                 connect newcon
292
293
294         // 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]
295
296         if min < cur <= max
297                 j = 0
298                 for i = BACKBONE to my.dclass
299                         j += count(from connections where node.dclass = i)
300                         if min < j
301                                 delcon =
302                                         first from nodes
303                                                 where dclass >= i and outgoing_connection
304                                                 order by dclass desc
305                                 if disconnect
306                                         goto disconnect
307                                 else
308                                         break
309
310
311         // disconnect connections in case we have more than enough connections
312
313         if max < cur
314                 delcon =
315                         first from nodes
316                                 where outgoing_connection
317                                 order by dclass desc
318                 goto disconnect
319
320         // disconnect
321
322 disconnect
323         if delcon
324                 disconnect delcon
325
326
327         // next iteration
328         next (timeout, autoconnect)
329
330 }
331
332 */
333
334
335 static void periodic_handler(event_loop_t *loop, void *data) {
336         meshlink_handle_t *mesh = loop->data;
337
338         /* Check if there are too many contradicting ADD_EDGE and DEL_EDGE messages.
339            This usually only happens when another node has the same Name as this node.
340            If so, sleep for a short while to prevent a storm of contradicting messages.
341         */
342
343         if(mesh->contradicting_del_edge > 100 && mesh->contradicting_add_edge > 100) {
344                 logger(mesh, MESHLINK_WARNING, "Possible node with same Name as us! Sleeping %d seconds.", mesh->sleeptime);
345                 usleep(mesh->sleeptime * 1000000LL);
346                 mesh->sleeptime *= 2;
347
348                 if(mesh->sleeptime < 0) {
349                         mesh->sleeptime = 3600;
350                 }
351         } else {
352                 mesh->sleeptime /= 2;
353
354                 if(mesh->sleeptime < 10) {
355                         mesh->sleeptime = 10;
356                 }
357         }
358
359         mesh->contradicting_add_edge = 0;
360         mesh->contradicting_del_edge = 0;
361
362         int timeout = default_timeout;
363
364         /* Check if we need to make or break connections. */
365
366         if(mesh->nodes->count > 1) {
367
368                 logger(mesh, MESHLINK_DEBUG, "--- autoconnect begin ---");
369
370                 int retry_timeout = min(mesh->nodes->count * default_timeout, 60);
371
372                 logger(mesh, MESHLINK_DEBUG, "* devclass = %d", mesh->devclass);
373                 logger(mesh, MESHLINK_DEBUG, "* nodes = %d", mesh->nodes->count);
374                 logger(mesh, MESHLINK_DEBUG, "* retry_timeout = %d", retry_timeout);
375
376
377                 // connect disconnect nodes
378
379                 node_t *connect_to = NULL;
380                 node_t *disconnect_from = NULL;
381
382
383                 // get cur_connects
384
385                 unsigned int cur_connects = 0;
386
387                 for list_each(connection_t, c, mesh->connections) {
388                         if(c->status.active) {
389                                 cur_connects += 1;
390                         }
391                 }
392
393                 logger(mesh, MESHLINK_DEBUG, "* cur_connects = %d", cur_connects);
394                 logger(mesh, MESHLINK_DEBUG, "* outgoings = %d", mesh->outgoings->count);
395
396                 // get min_connects and max_connects
397
398                 unsigned int min_connects = mesh->dev_class_traits[mesh->devclass].min_connects;
399                 unsigned int max_connects = mesh->dev_class_traits[mesh->devclass].max_connects;
400
401                 logger(mesh, MESHLINK_DEBUG, "* min_connects = %d", min_connects);
402                 logger(mesh, MESHLINK_DEBUG, "* max_connects = %d", max_connects);
403
404                 // find the best one for initial connect
405
406                 if(cur_connects < min_connects) {
407                         splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_asc_lsc_desc, NULL);
408
409                         for splay_each(node_t, n, mesh->nodes) {
410                                 logger(mesh, MESHLINK_DEBUG, "* %s->devclass = %d", n->name, n->devclass);
411
412                                 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)) {
413                                         splay_insert(nodes, n);
414                                 }
415                         }
416
417                         if(nodes->head) {
418                                 //timeout = 0;
419                                 connect_to = (node_t *)nodes->head->data;
420
421                                 logger(mesh, MESHLINK_DEBUG, "* found best one for initial connect: %s", connect_to->name);
422                         } else {
423                                 logger(mesh, MESHLINK_DEBUG, "* could not find node for initial connect");
424                         }
425
426                         splay_delete_tree(nodes);
427                 }
428
429
430                 // find better nodes to connect to
431
432                 if(!connect_to && min_connects <= cur_connects && cur_connects < max_connects) {
433                         unsigned int connects = 0;
434
435                         for(dev_class_t devclass = 0; devclass <= mesh->devclass; ++devclass) {
436                                 for list_each(connection_t, c, mesh->connections) {
437                                         if(c->status.active && c->node && c->node->devclass == devclass) {
438                                                 connects += 1;
439                                         }
440                                 }
441
442                                 if(connects < min_connects) {
443                                         splay_tree_t *nodes = splay_alloc_tree(node_compare_lsc_desc, NULL);
444
445                                         for splay_each(node_t, n, mesh->nodes) {
446                                                 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)) {
447                                                         splay_insert(nodes, n);
448                                                 }
449                                         }
450
451                                         if(nodes->head) {
452                                                 logger(mesh, MESHLINK_DEBUG, "* found better node");
453                                                 connect_to = (node_t *)nodes->head->data;
454
455                                                 splay_delete_tree(nodes);
456                                                 break;
457                                         }
458
459                                         splay_delete_tree(nodes);
460                                 } else {
461                                         break;
462                                 }
463                         }
464
465                         if(!connect_to) {
466                                 logger(mesh, MESHLINK_DEBUG, "* could not find better nodes");
467                         }
468                 }
469
470
471                 // heal partitions
472
473                 if(!connect_to && min_connects <= cur_connects && cur_connects < max_connects) {
474                         splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_asc_lsc_desc, NULL);
475
476                         for splay_each(node_t, n, mesh->nodes) {
477                                 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)) {
478                                         splay_insert(nodes, n);
479                                 }
480                         }
481
482                         if(nodes->head) {
483                                 logger(mesh, MESHLINK_DEBUG, "* try to heal partition");
484                                 connect_to = (node_t *)nodes->head->data;
485                         } else {
486                                 logger(mesh, MESHLINK_DEBUG, "* could not find nodes for partition healing");
487                         }
488
489                         splay_delete_tree(nodes);
490                 }
491
492
493                 // perform connect
494
495                 if(connect_to && !connect_to->connection) {
496                         connect_to->last_connect_try = mesh->loop.now.tv_sec;
497                         logger(mesh, MESHLINK_DEBUG, "Autoconnect trying to connect to %s", connect_to->name);
498
499                         /* check if there is already a connection attempt to this node */
500                         bool skip = false;
501
502                         for list_each(outgoing_t, outgoing, mesh->outgoings) {
503                                 if(outgoing->node == connect_to) {
504                                         logger(mesh, MESHLINK_DEBUG, "* skip autoconnect since it is an outgoing connection already");
505                                         skip = true;
506                                         break;
507                                 }
508                         }
509
510                         if(!connect_to->status.reachable && !node_read_public_key(mesh, connect_to)) {
511                                 logger(mesh, MESHLINK_DEBUG, "* skip autoconnect since we don't know this node's public key");
512                                 skip = true;
513                         }
514
515                         if(!skip) {
516                                 logger(mesh, MESHLINK_DEBUG, "Autoconnecting to %s", connect_to->name);
517                                 outgoing_t *outgoing = xzalloc(sizeof(outgoing_t));
518                                 outgoing->node = connect_to;
519                                 list_insert_tail(mesh->outgoings, outgoing);
520                                 setup_outgoing_connection(mesh, outgoing);
521                         }
522                 }
523
524
525                 // disconnect suboptimal outgoing connections
526
527                 if(min_connects < cur_connects /*&& cur_connects <= max_connects*/) {
528                         unsigned int connects = 0;
529
530                         for(dev_class_t devclass = 0; devclass <= mesh->devclass; ++devclass) {
531                                 for list_each(connection_t, c, mesh->connections) {
532                                         if(c->status.active && c->node && c->node->devclass == devclass) {
533                                                 connects += 1;
534                                         }
535                                 }
536
537                                 if(min_connects < connects) {
538                                         splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_desc, NULL);
539
540                                         for list_each(connection_t, c, mesh->connections) {
541                                                 if(c->outgoing && c->node && c->node->devclass >= devclass) {
542                                                         splay_insert(nodes, c->node);
543                                                 }
544                                         }
545
546                                         if(nodes->head) {
547                                                 logger(mesh, MESHLINK_DEBUG, "* disconnect suboptimal outgoing connection");
548                                                 disconnect_from = (node_t *)nodes->head->data;
549                                         }
550
551                                         splay_delete_tree(nodes);
552                                         break;
553                                 }
554                         }
555
556                         if(!disconnect_from) {
557                                 logger(mesh, MESHLINK_DEBUG, "* no suboptimal outgoing connections");
558                         }
559                 }
560
561
562                 // disconnect connections (too many connections)
563
564                 if(!disconnect_from && max_connects < cur_connects) {
565                         splay_tree_t *nodes = splay_alloc_tree(node_compare_devclass_desc, NULL);
566
567                         for list_each(connection_t, c, mesh->connections) {
568                                 if(c->status.active && c->node) {
569                                         splay_insert(nodes, c->node);
570                                 }
571                         }
572
573                         if(nodes->head) {
574                                 logger(mesh, MESHLINK_DEBUG, "* disconnect connection (too many connections)");
575
576                                 //timeout = 0;
577                                 disconnect_from = (node_t *)nodes->head->data;
578                         } else {
579                                 logger(mesh, MESHLINK_DEBUG, "* no node we want to disconnect, even though we have too many connections");
580                         }
581
582                         splay_delete_tree(nodes);
583                 }
584
585
586                 // perform disconnect
587
588                 if(disconnect_from && disconnect_from->connection) {
589                         logger(mesh, MESHLINK_DEBUG, "Autodisconnecting from %s", disconnect_from->connection->name);
590                         list_delete(mesh->outgoings, disconnect_from->connection->outgoing);
591                         disconnect_from->connection->outgoing = NULL;
592                         terminate_connection(mesh, disconnect_from->connection, disconnect_from->connection->status.active);
593                 }
594
595                 // reduce timeout if we don't have enough connections + outgoings
596                 if(cur_connects + mesh->outgoings->count < 3) {
597                         timeout = 1;
598                 }
599
600                 // done!
601
602                 logger(mesh, MESHLINK_DEBUG, "--- autoconnect end ---");
603         }
604
605         for splay_each(node_t, n, mesh->nodes) {
606                 if(n->status.dirty) {
607                         node_write_config(mesh, n);
608                         n->status.dirty = false;
609                 }
610         }
611
612         timeout_set(&mesh->loop, data, &(struct timeval) {
613                 timeout, prng(mesh, TIMER_FUDGE)
614         });
615 }
616
617 void handle_meta_connection_data(meshlink_handle_t *mesh, connection_t *c) {
618         if(!receive_meta(mesh, c)) {
619                 terminate_connection(mesh, c, c->status.active);
620                 return;
621         }
622 }
623
624 void retry(meshlink_handle_t *mesh) {
625         /* Reset the reconnection timers for all outgoing connections */
626         for list_each(outgoing_t, outgoing, mesh->outgoings) {
627                 outgoing->timeout = 0;
628
629                 if(outgoing->ev.cb)
630                         timeout_set(&mesh->loop, &outgoing->ev, &(struct timeval) {
631                         0, 0
632                 });
633         }
634
635 #ifdef HAVE_IFADDRS_H
636         struct ifaddrs *ifa = NULL;
637         getifaddrs(&ifa);
638 #endif
639
640         /* For active connections, check if their addresses are still valid.
641          * If yes, reset their ping timers, otherwise terminate them. */
642         for list_each(connection_t, c, mesh->connections) {
643                 if(!c->status.active) {
644                         continue;
645                 }
646
647                 if(!c->status.pinged) {
648                         c->last_ping_time = 0;
649                 }
650
651 #ifdef HAVE_IFADDRS_H
652
653                 if(!ifa) {
654                         continue;
655                 }
656
657                 sockaddr_t sa;
658                 socklen_t salen = sizeof(sa);
659
660                 if(getsockname(c->socket, &sa.sa, &salen)) {
661                         continue;
662                 }
663
664                 bool found = false;
665
666                 for(struct ifaddrs *ifap = ifa; ifap; ifap = ifap->ifa_next) {
667                         if(ifap->ifa_addr && !sockaddrcmp_noport(&sa, (sockaddr_t *)ifap->ifa_addr)) {
668                                 found = true;
669                                 break;
670                         }
671
672                 }
673
674                 if(!found) {
675                         logger(mesh, MESHLINK_DEBUG, "Local address for connection to %s no longer valid, terminating", c->name);
676                         terminate_connection(mesh, c, c->status.active);
677                 }
678
679 #endif
680         }
681
682 #ifdef HAVE_IFADDRS_H
683
684         if(ifa) {
685                 freeifaddrs(ifa);
686         }
687
688 #endif
689
690         /* Kick the ping timeout handler */
691         timeout_set(&mesh->loop, &mesh->pingtimer, &(struct timeval) {
692                 0, 0
693         });
694 }
695
696 /*
697   this is where it all happens...
698 */
699 int main_loop(meshlink_handle_t *mesh) {
700         timeout_add(&mesh->loop, &mesh->pingtimer, timeout_handler, &mesh->pingtimer, &(struct timeval) {
701                 default_timeout, prng(mesh, TIMER_FUDGE)
702         });
703         timeout_add(&mesh->loop, &mesh->periodictimer, periodic_handler, &mesh->periodictimer, &(struct timeval) {
704                 0, 0
705         });
706
707         //Add signal handler
708         mesh->datafromapp.signum = 0;
709         signal_add(&mesh->loop, &mesh->datafromapp, meshlink_send_from_queue, mesh, mesh->datafromapp.signum);
710
711         if(!event_loop_run(&mesh->loop, &mesh->mutex)) {
712                 logger(mesh, MESHLINK_ERROR, "Error while waiting for input: %s", strerror(errno));
713                 abort();
714                 signal_del(&mesh->loop, &mesh->datafromapp);
715                 timeout_del(&mesh->loop, &mesh->periodictimer);
716                 timeout_del(&mesh->loop, &mesh->pingtimer);
717
718                 return 1;
719         }
720
721         signal_del(&mesh->loop, &mesh->datafromapp);
722         timeout_del(&mesh->loop, &mesh->periodictimer);
723         timeout_del(&mesh->loop, &mesh->pingtimer);
724
725         return 0;
726 }