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