1fecd88fd00d0038e0020124cc303680022e5a33
[oweals/tinc.git] / src / net.c
1 /*
2     net.c -- most of the network code
3     Copyright (C) 1998-2005 Ivo Timmermans,
4                   2000-2015 Guus Sliepen <guus@tinc-vpn.org>
5                   2006      Scott Lamb <slamb@slamb.org>
6                   2011      Loïc Grenié <loic.grenie@gmail.com>
7
8     This program is free software; you can redistribute it and/or modify
9     it under the terms of the GNU General Public License as published by
10     the Free Software Foundation; either version 2 of the License, or
11     (at your option) any later version.
12
13     This program is distributed in the hope that it will be useful,
14     but WITHOUT ANY WARRANTY; without even the implied warranty of
15     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16     GNU General Public License for more details.
17
18     You should have received a copy of the GNU General Public License along
19     with this program; if not, write to the Free Software Foundation, Inc.,
20     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 */
22
23 #include "system.h"
24
25 #include <openssl/rand.h>
26
27 #include "utils.h"
28 #include "avl_tree.h"
29 #include "conf.h"
30 #include "connection.h"
31 #include "device.h"
32 #include "event.h"
33 #include "graph.h"
34 #include "logger.h"
35 #include "meta.h"
36 #include "net.h"
37 #include "netutl.h"
38 #include "process.h"
39 #include "protocol.h"
40 #include "route.h"
41 #include "subnet.h"
42 #include "xalloc.h"
43
44 bool do_purge = false;
45 volatile bool running = false;
46 #ifdef HAVE_PSELECT
47 bool graph_dump = false;
48 #endif
49
50 time_t now = 0;
51 int contradicting_add_edge = 0;
52 int contradicting_del_edge = 0;
53 static int sleeptime = 10;
54
55 /* Purge edges and subnets of unreachable nodes. Use carefully. */
56
57 static void purge(void) {
58         avl_node_t *nnode, *nnext, *enode, *enext, *snode, *snext;
59         node_t *n;
60         edge_t *e;
61         subnet_t *s;
62
63         ifdebug(PROTOCOL) logger(LOG_DEBUG, "Purging unreachable nodes");
64
65         /* Remove all edges and subnets owned by unreachable nodes. */
66
67         for(nnode = node_tree->head; nnode; nnode = nnext) {
68                 nnext = nnode->next;
69                 n = nnode->data;
70
71                 if(!n->status.reachable) {
72                         ifdebug(SCARY_THINGS) logger(LOG_DEBUG, "Purging node %s (%s)", n->name,
73                                                      n->hostname);
74
75                         for(snode = n->subnet_tree->head; snode; snode = snext) {
76                                 snext = snode->next;
77                                 s = snode->data;
78                                 send_del_subnet(everyone, s);
79
80                                 if(!strictsubnets) {
81                                         subnet_del(n, s);
82                                 }
83                         }
84
85                         for(enode = n->edge_tree->head; enode; enode = enext) {
86                                 enext = enode->next;
87                                 e = enode->data;
88
89                                 if(!tunnelserver) {
90                                         send_del_edge(everyone, e);
91                                 }
92
93                                 edge_del(e);
94                         }
95                 }
96         }
97
98         /* Check if anyone else claims to have an edge to an unreachable node. If not, delete node. */
99
100         for(nnode = node_tree->head; nnode; nnode = nnext) {
101                 nnext = nnode->next;
102                 n = nnode->data;
103
104                 if(!n->status.reachable) {
105                         for(enode = edge_weight_tree->head; enode; enode = enext) {
106                                 enext = enode->next;
107                                 e = enode->data;
108
109                                 if(e->to == n) {
110                                         break;
111                                 }
112                         }
113
114                         if(!enode && (!strictsubnets || !n->subnet_tree->head))
115                                 /* in strictsubnets mode do not delete nodes with subnets */
116                         {
117                                 node_del(n);
118                         }
119                 }
120         }
121 }
122
123 /*
124   put all file descriptors in an fd_set array
125   While we're at it, purge stuff that needs to be removed.
126 */
127 static int build_fdset(fd_set *readset, fd_set *writeset) {
128         avl_node_t *node, *next;
129         connection_t *c;
130         int i, max = 0;
131
132         FD_ZERO(readset);
133         FD_ZERO(writeset);
134
135         for(node = connection_tree->head; node; node = next) {
136                 next = node->next;
137                 c = node->data;
138
139                 if(c->status.remove) {
140                         connection_del(c);
141
142                         if(!connection_tree->head) {
143                                 purge();
144                         }
145                 } else {
146                         FD_SET(c->socket, readset);
147
148                         if(c->outbuflen > 0 || c->status.connecting) {
149                                 FD_SET(c->socket, writeset);
150                         }
151
152                         if(c->socket > max) {
153                                 max = c->socket;
154                         }
155                 }
156         }
157
158         for(i = 0; i < listen_sockets; i++) {
159                 FD_SET(listen_socket[i].tcp, readset);
160
161                 if(listen_socket[i].tcp > max) {
162                         max = listen_socket[i].tcp;
163                 }
164
165                 FD_SET(listen_socket[i].udp, readset);
166
167                 if(listen_socket[i].udp > max) {
168                         max = listen_socket[i].udp;
169                 }
170         }
171
172         if(device_fd >= 0) {
173                 FD_SET(device_fd, readset);
174         }
175
176         if(device_fd > max) {
177                 max = device_fd;
178         }
179
180         return max;
181 }
182
183 /*
184   Terminate a connection:
185   - Close the socket
186   - Remove associated edge and tell other connections about it if report = true
187   - Check if we need to retry making an outgoing connection
188   - Deactivate the host
189 */
190 void terminate_connection(connection_t *c, bool report) {
191         if(c->status.remove) {
192                 return;
193         }
194
195         ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Closing connection with %s (%s)",
196                                     c->name, c->hostname);
197
198         c->status.remove = true;
199         c->status.active = false;
200
201         if(c->node) {
202                 c->node->connection = NULL;
203         }
204
205         if(c->socket) {
206                 closesocket(c->socket);
207         }
208
209         if(c->edge) {
210                 if(!c->node) {
211                         logger(LOG_ERR, "Connection to %s (%s) has an edge but node is NULL!", c->name, c->hostname);
212                         // And that should never happen.
213                         abort();
214                 }
215
216                 if(report && !tunnelserver) {
217                         send_del_edge(everyone, c->edge);
218                 }
219
220                 edge_del(c->edge);
221                 c->edge = NULL;
222
223                 /* Run MST and SSSP algorithms */
224
225                 graph();
226
227                 /* If the node is not reachable anymore but we remember it had an edge to us, clean it up */
228
229                 if(report && !c->node->status.reachable) {
230                         edge_t *e;
231                         e = lookup_edge(c->node, myself);
232
233                         if(e) {
234                                 if(!tunnelserver) {
235                                         send_del_edge(everyone, e);
236                                 }
237
238                                 edge_del(e);
239                         }
240                 }
241         }
242
243         free_connection_partially(c);
244
245         /* Check if this was our outgoing connection */
246
247         if(c->outgoing) {
248                 c->status.remove = false;
249                 do_outgoing_connection(c);
250         }
251
252 #ifndef HAVE_MINGW
253         /* Clean up dead proxy processes */
254
255         while(waitpid(-1, NULL, WNOHANG) > 0);
256
257 #endif
258 }
259
260 /*
261   Check if the other end is active.
262   If we have sent packets, but didn't receive any,
263   then possibly the other end is dead. We send a
264   PING request over the meta connection. If the other
265   end does not reply in time, we consider them dead
266   and close the connection.
267 */
268 static void check_dead_connections(void) {
269         avl_node_t *node, *next;
270         connection_t *c;
271
272         for(node = connection_tree->head; node; node = next) {
273                 next = node->next;
274                 c = node->data;
275
276                 if(c->last_ping_time + pingtimeout <= now) {
277                         if(c->status.active) {
278                                 if(c->status.pinged) {
279                                         ifdebug(CONNECTIONS) logger(LOG_INFO, "%s (%s) didn't respond to PING in %ld seconds",
280                                                                     c->name, c->hostname, (long)(now - c->last_ping_time));
281                                         c->status.timeout = true;
282                                         terminate_connection(c, true);
283                                 } else if(c->last_ping_time + pinginterval <= now) {
284                                         send_ping(c);
285                                 }
286                         } else {
287                                 if(c->status.remove) {
288                                         logger(LOG_WARNING, "Old connection_t for %s (%s) status %04x still lingering, deleting...",
289                                                c->name, c->hostname, bitfield_to_int(&c->status, sizeof(c->status)));
290                                         connection_del(c);
291                                         continue;
292                                 }
293
294                                 ifdebug(CONNECTIONS) logger(LOG_WARNING, "Timeout from %s (%s) during authentication",
295                                                             c->name, c->hostname);
296
297                                 if(c->status.connecting) {
298                                         c->status.connecting = false;
299                                         closesocket(c->socket);
300                                         do_outgoing_connection(c);
301                                 } else {
302                                         terminate_connection(c, false);
303                                 }
304                         }
305                 }
306
307                 if(c->outbuflen > 0 && c->last_flushed_time + pingtimeout <= now) {
308                         if(c->status.active) {
309                                 ifdebug(CONNECTIONS) logger(LOG_INFO,
310                                                             "%s (%s) could not flush for %ld seconds (%d bytes remaining)",
311                                                             c->name, c->hostname, (long)(now - c->last_flushed_time), c->outbuflen);
312                                 c->status.timeout = true;
313                                 terminate_connection(c, true);
314                         }
315                 }
316         }
317 }
318
319 /*
320   check all connections to see if anything
321   happened on their sockets
322 */
323 static void check_network_activity(fd_set *readset, fd_set *writeset) {
324         connection_t *c;
325         avl_node_t *node;
326         int result, i;
327         socklen_t len = sizeof(result);
328         vpn_packet_t packet;
329         static int errors = 0;
330
331         /* check input from kernel */
332         if(device_fd >= 0 && FD_ISSET(device_fd, readset)) {
333                 if(devops.read(&packet)) {
334                         if(packet.len) {
335                                 errors = 0;
336                                 packet.priority = 0;
337                                 route(myself, &packet);
338                         }
339                 } else {
340                         usleep(errors * 50000);
341                         errors++;
342
343                         if(errors > 10) {
344                                 logger(LOG_ERR, "Too many errors from %s, exiting!", device);
345                                 running = false;
346                         }
347                 }
348         }
349
350         /* check meta connections */
351         for(node = connection_tree->head; node; node = node->next) {
352                 c = node->data;
353
354                 if(c->status.remove) {
355                         continue;
356                 }
357
358                 if(FD_ISSET(c->socket, writeset)) {
359                         if(c->status.connecting) {
360                                 c->status.connecting = false;
361                                 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&result, &len);
362
363                                 if(!result) {
364                                         finish_connecting(c);
365                                 } else {
366                                         ifdebug(CONNECTIONS) logger(LOG_DEBUG,
367                                                                     "Error while connecting to %s (%s): %s",
368                                                                     c->name, c->hostname, sockstrerror(result));
369                                         closesocket(c->socket);
370                                         do_outgoing_connection(c);
371                                         continue;
372                                 }
373                         }
374
375                         if(!flush_meta(c)) {
376                                 terminate_connection(c, c->status.active);
377                                 continue;
378                         }
379                 }
380
381                 if(FD_ISSET(c->socket, readset)) {
382                         if(!receive_meta(c)) {
383                                 terminate_connection(c, c->status.active);
384                                 continue;
385                         }
386                 }
387         }
388
389         for(i = 0; i < listen_sockets; i++) {
390                 if(FD_ISSET(listen_socket[i].udp, readset)) {
391                         handle_incoming_vpn_data(i);
392                 }
393
394                 if(FD_ISSET(listen_socket[i].tcp, readset)) {
395                         handle_new_meta_connection(listen_socket[i].tcp);
396                 }
397         }
398 }
399
400 /*
401   this is where it all happens...
402 */
403 int main_loop(void) {
404         fd_set readset, writeset;
405 #ifdef HAVE_PSELECT
406         struct timespec tv;
407         sigset_t omask, block_mask;
408         time_t next_event;
409 #else
410         struct timeval tv;
411 #endif
412         int r, maxfd;
413         time_t last_ping_check, last_config_check, last_graph_dump;
414         event_t *event;
415
416         last_ping_check = now;
417         last_config_check = now;
418         last_graph_dump = now;
419
420         srand(now);
421
422 #ifdef HAVE_PSELECT
423
424         if(lookup_config(config_tree, "GraphDumpFile")) {
425                 graph_dump = true;
426         }
427
428         /* Block SIGHUP & SIGALRM */
429         sigemptyset(&block_mask);
430         sigaddset(&block_mask, SIGHUP);
431         sigaddset(&block_mask, SIGALRM);
432         sigprocmask(SIG_BLOCK, &block_mask, &omask);
433 #endif
434
435         running = true;
436
437         while(running) {
438 #ifdef HAVE_PSELECT
439                 next_event = last_ping_check + pingtimeout;
440
441                 if(graph_dump && next_event > last_graph_dump + 60) {
442                         next_event = last_graph_dump + 60;
443                 }
444
445                 if((event = peek_next_event()) && next_event > event->time) {
446                         next_event = event->time;
447                 }
448
449                 if(next_event <= now) {
450                         tv.tv_sec = 0;
451                 } else {
452                         tv.tv_sec = next_event - now;
453                 }
454
455                 tv.tv_nsec = 0;
456 #else
457                 tv.tv_sec = 1;
458                 tv.tv_usec = 0;
459 #endif
460
461                 maxfd = build_fdset(&readset, &writeset);
462
463 #ifdef HAVE_MINGW
464                 LeaveCriticalSection(&mutex);
465 #endif
466 #ifdef HAVE_PSELECT
467                 r = pselect(maxfd + 1, &readset, &writeset, NULL, &tv, &omask);
468 #else
469                 r = select(maxfd + 1, &readset, &writeset, NULL, &tv);
470 #endif
471                 now = time(NULL);
472 #ifdef HAVE_MINGW
473                 EnterCriticalSection(&mutex);
474 #endif
475
476                 if(r < 0) {
477                         if(!sockwouldblock(sockerrno)) {
478                                 logger(LOG_ERR, "Error while waiting for input: %s", sockstrerror(sockerrno));
479                                 dump_connections();
480                                 return 1;
481                         }
482                 }
483
484                 if(r > 0) {
485                         check_network_activity(&readset, &writeset);
486                 }
487
488                 if(do_purge) {
489                         purge();
490                         do_purge = false;
491                 }
492
493                 /* Let's check if everybody is still alive */
494
495                 if(last_ping_check + pingtimeout <= now) {
496                         check_dead_connections();
497                         last_ping_check = now;
498
499                         if(routing_mode == RMODE_SWITCH) {
500                                 age_subnets();
501                         }
502
503                         age_past_requests();
504
505                         /* Should we regenerate our key? */
506
507                         if(keyexpires <= now) {
508                                 avl_node_t *node;
509                                 node_t *n;
510
511                                 ifdebug(STATUS) logger(LOG_INFO, "Expiring symmetric keys");
512
513                                 for(node = node_tree->head; node; node = node->next) {
514                                         n = node->data;
515
516                                         if(n->inkey) {
517                                                 free(n->inkey);
518                                                 n->inkey = NULL;
519                                         }
520                                 }
521
522                                 send_key_changed();
523                                 keyexpires = now + keylifetime;
524                         }
525
526                         /* Detect ADD_EDGE/DEL_EDGE storms that are caused when
527                          * two tinc daemons with the same name are on the VPN.
528                          * If so, sleep a while. If this happens multiple times
529                          * in a row, sleep longer. */
530
531                         if(contradicting_del_edge > 100 && contradicting_add_edge > 100) {
532                                 logger(LOG_WARNING, "Possible node with same Name as us! Sleeping %d seconds.", sleeptime);
533                                 usleep(sleeptime * 1000000LL);
534                                 sleeptime *= 2;
535
536                                 if(sleeptime < 0) {
537                                         sleeptime = 3600;
538                                 }
539                         } else {
540                                 sleeptime /= 2;
541
542                                 if(sleeptime < 10) {
543                                         sleeptime = 10;
544                                 }
545                         }
546
547                         contradicting_add_edge = 0;
548                         contradicting_del_edge = 0;
549                 }
550
551                 if(sigalrm) {
552                         avl_node_t *node;
553                         logger(LOG_INFO, "Flushing event queue");
554                         expire_events();
555
556                         for(node = connection_tree->head; node; node = node->next) {
557                                 connection_t *c = node->data;
558
559                                 if(c->status.active) {
560                                         send_ping(c);
561                                 }
562                         }
563
564                         sigalrm = false;
565                 }
566
567                 while((event = get_expired_event())) {
568                         event->handler(event->data);
569                         free_event(event);
570                 }
571
572                 if(sighup) {
573                         connection_t *c;
574                         avl_node_t *node, *next;
575                         char *fname;
576                         struct stat s;
577
578                         sighup = false;
579
580                         reopenlogger();
581
582                         /* Reread our own configuration file */
583
584                         exit_configuration(&config_tree);
585                         init_configuration(&config_tree);
586
587                         if(!read_server_config()) {
588                                 logger(LOG_ERR, "Unable to reread configuration file, exitting.");
589                                 return 1;
590                         }
591
592                         /* Cancel non-active outgoing connections */
593
594                         for(node = connection_tree->head; node; node = next) {
595                                 next = node->next;
596                                 c = node->data;
597
598                                 c->outgoing = NULL;
599
600                                 if(c->status.connecting) {
601                                         terminate_connection(c, false);
602                                         connection_del(c);
603                                 }
604                         }
605
606                         /* Wipe list of outgoing connections */
607
608                         for(list_node_t *node = outgoing_list->head; node; node = node->next) {
609                                 outgoing_t *outgoing = node->data;
610
611                                 if(outgoing->event) {
612                                         event_del(outgoing->event);
613                                 }
614                         }
615
616                         list_delete_list(outgoing_list);
617
618                         /* Close connections to hosts that have a changed or deleted host config file */
619
620                         for(node = connection_tree->head; node; node = node->next) {
621                                 c = node->data;
622
623                                 xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
624
625                                 if(stat(fname, &s) || s.st_mtime > last_config_check) {
626                                         terminate_connection(c, c->status.active);
627                                 }
628
629                                 free(fname);
630                         }
631
632                         last_config_check = now;
633
634                         /* If StrictSubnet is set, expire deleted Subnets and read new ones in */
635
636                         if(strictsubnets) {
637                                 subnet_t *subnet;
638
639                                 for(node = subnet_tree->head; node; node = node->next) {
640                                         subnet = node->data;
641                                         subnet->expires = 1;
642                                 }
643
644                                 load_all_subnets();
645
646                                 for(node = subnet_tree->head; node; node = next) {
647                                         next = node->next;
648                                         subnet = node->data;
649
650                                         if(subnet->expires == 1) {
651                                                 send_del_subnet(everyone, subnet);
652
653                                                 if(subnet->owner->status.reachable) {
654                                                         subnet_update(subnet->owner, subnet, false);
655                                                 }
656
657                                                 subnet_del(subnet->owner, subnet);
658                                         } else if(subnet->expires == -1) {
659                                                 subnet->expires = 0;
660                                         } else {
661                                                 send_add_subnet(everyone, subnet);
662
663                                                 if(subnet->owner->status.reachable) {
664                                                         subnet_update(subnet->owner, subnet, true);
665                                                 }
666                                         }
667                                 }
668                         }
669
670                         /* Try to make outgoing connections */
671
672                         try_outgoing_connections();
673                 }
674
675                 /* Dump graph if wanted every 60 seconds*/
676
677                 if(last_graph_dump + 60 <= now) {
678                         dump_graph();
679                         last_graph_dump = now;
680                 }
681         }
682
683 #ifdef HAVE_PSELECT
684         /* Restore SIGHUP & SIGALARM mask */
685         sigprocmask(SIG_SETMASK, &omask, NULL);
686 #endif
687
688         return 0;
689 }