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