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