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