0496a864e4dd4c028a07ab7bf4f52c353471c02e
[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                         errors = 0;
290                         packet.priority = 0;
291                         route(myself, &packet);
292                 } else {
293                         usleep(errors * 50000);
294                         errors++;
295                         if(errors > 10) {
296                                 logger(LOG_ERR, "Too many errors from %s, exiting!", device);
297                                 running = false;
298                         }
299                 }
300         }
301
302         /* check meta connections */
303         for(node = connection_tree->head; node; node = node->next) {
304                 c = node->data;
305
306                 if(c->status.remove)
307                         continue;
308
309                 if(FD_ISSET(c->socket, readset)) {
310                         if(c->status.connecting) {
311                                 c->status.connecting = false;
312                                 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&result, &len);
313
314                                 if(!result)
315                                         finish_connecting(c);
316                                 else {
317                                         ifdebug(CONNECTIONS) logger(LOG_DEBUG,
318                                                            "Error while connecting to %s (%s): %s",
319                                                            c->name, c->hostname, sockstrerror(result));
320                                         closesocket(c->socket);
321                                         do_outgoing_connection(c);
322                                         continue;
323                                 }
324                         }
325
326                         if(!receive_meta(c)) {
327                                 terminate_connection(c, c->status.active);
328                                 continue;
329                         }
330                 }
331
332                 if(FD_ISSET(c->socket, writeset)) {
333                         if(!flush_meta(c)) {
334                                 terminate_connection(c, c->status.active);
335                                 continue;
336                         }
337                 }
338         }
339
340         for(i = 0; i < listen_sockets; i++) {
341                 if(FD_ISSET(listen_socket[i].udp, readset))
342                         handle_incoming_vpn_data(i);
343
344                 if(FD_ISSET(listen_socket[i].tcp, readset))
345                         handle_new_meta_connection(listen_socket[i].tcp);
346         }
347 }
348
349 /*
350   this is where it all happens...
351 */
352 int main_loop(void) {
353         fd_set readset, writeset;
354 #ifdef HAVE_PSELECT
355         struct timespec tv;
356         sigset_t omask, block_mask;
357         time_t next_event;
358 #else
359         struct timeval tv;
360 #endif
361         int r, maxfd;
362         time_t last_ping_check, last_config_check, last_graph_dump;
363         event_t *event;
364
365         last_ping_check = now;
366         last_config_check = now;
367         last_graph_dump = now;
368         
369         srand(now);
370
371 #ifdef HAVE_PSELECT
372         if(lookup_config(config_tree, "GraphDumpFile"))
373                 graph_dump = true;
374         /* Block SIGHUP & SIGALRM */
375         sigemptyset(&block_mask);
376         sigaddset(&block_mask, SIGHUP);
377         sigaddset(&block_mask, SIGALRM);
378         sigprocmask(SIG_BLOCK, &block_mask, &omask);
379 #endif
380
381         running = true;
382
383         while(running) {
384 #ifdef HAVE_PSELECT
385                 next_event = last_ping_check + pingtimeout;
386                 if(graph_dump && next_event > last_graph_dump + 60)
387                         next_event = last_graph_dump + 60;
388
389                 if((event = peek_next_event()) && next_event > event->time)
390                         next_event = event->time;
391
392                 if(next_event <= now)
393                         tv.tv_sec = 0;
394                 else
395                         tv.tv_sec = next_event - now;
396                 tv.tv_nsec = 0;
397 #else
398                 tv.tv_sec = 1;
399                 tv.tv_usec = 0;
400 #endif
401
402                 maxfd = build_fdset(&readset, &writeset);
403
404 #ifdef HAVE_MINGW
405                 LeaveCriticalSection(&mutex);
406 #endif
407 #ifdef HAVE_PSELECT
408                 r = pselect(maxfd + 1, &readset, &writeset, NULL, &tv, &omask);
409 #else
410                 r = select(maxfd + 1, &readset, &writeset, NULL, &tv);
411 #endif
412                 now = time(NULL);
413 #ifdef HAVE_MINGW
414                 EnterCriticalSection(&mutex);
415 #endif
416
417                 if(r < 0) {
418                         if(!sockwouldblock(sockerrno)) {
419                                 logger(LOG_ERR, "Error while waiting for input: %s", sockstrerror(sockerrno));
420                                 dump_connections();
421                                 return 1;
422                         }
423                 }
424
425                 if(r > 0)
426                         check_network_activity(&readset, &writeset);
427
428                 if(do_purge) {
429                         purge();
430                         do_purge = false;
431                 }
432
433                 /* Let's check if everybody is still alive */
434
435                 if(last_ping_check + pingtimeout <= now) {
436                         check_dead_connections();
437                         last_ping_check = now;
438
439                         if(routing_mode == RMODE_SWITCH)
440                                 age_subnets();
441
442                         age_past_requests();
443
444                         /* Should we regenerate our key? */
445
446                         if(keyexpires <= now) {
447                                 avl_node_t *node;
448                                 node_t *n;
449
450                                 ifdebug(STATUS) logger(LOG_INFO, "Expiring symmetric keys");
451
452                                 for(node = node_tree->head; node; node = node->next) {
453                                         n = node->data;
454                                         if(n->inkey) {
455                                                 free(n->inkey);
456                                                 n->inkey = NULL;
457                                         }
458                                 }
459
460                                 send_key_changed();
461                                 keyexpires = now + keylifetime;
462                         }
463
464                         /* Detect ADD_EDGE/DEL_EDGE storms that are caused when
465                          * two tinc daemons with the same name are on the VPN.
466                          * If so, sleep a while. If this happens multiple times
467                          * in a row, sleep longer. */
468
469                         if(contradicting_del_edge > 100 && contradicting_add_edge > 100) {
470                                 logger(LOG_WARNING, "Possible node with same Name as us! Sleeping %d seconds.", sleeptime);
471                                 usleep(sleeptime * 1000000LL);
472                                 sleeptime *= 2;
473                                 if(sleeptime < 0)
474                                         sleeptime = 3600;
475                         } else {
476                                 sleeptime /= 2;
477                                 if(sleeptime < 10)
478                                         sleeptime = 10;
479                         }
480
481                         contradicting_add_edge = 0;
482                         contradicting_del_edge = 0;
483                 }
484
485                 if(sigalrm) {
486                         avl_node_t *node;
487                         logger(LOG_INFO, "Flushing event queue");
488                         expire_events();
489                         for(node = connection_tree->head; node; node = node->next) {
490                                 connection_t *c = node->data;
491                                 send_ping(c);
492                         }
493                         sigalrm = false;
494                 }
495
496                 while((event = get_expired_event())) {
497                         event->handler(event->data);
498                         free_event(event);
499                 }
500
501                 if(sighup) {
502                         connection_t *c;
503                         avl_node_t *node, *next;
504                         char *fname;
505                         struct stat s;
506                         
507                         sighup = false;
508
509                         reopenlogger();
510                         
511                         /* Reread our own configuration file */
512
513                         exit_configuration(&config_tree);
514                         init_configuration(&config_tree);
515
516                         if(!read_server_config()) {
517                                 logger(LOG_ERR, "Unable to reread configuration file, exitting.");
518                                 return 1;
519                         }
520
521                         /* Cancel non-active outgoing connections */
522
523                         for(node = connection_tree->head; node; node = next) {
524                                 next = node->next;
525                                 c = node->data;
526
527                                 c->outgoing = NULL;
528
529                                 if(c->status.connecting) {
530                                         terminate_connection(c, false);
531                                         connection_del(c);
532                                 }
533                         }
534
535                         /* Wipe list of outgoing connections */
536
537                         for(list_node_t *node = outgoing_list->head; node; node = node->next) {
538                                 outgoing_t *outgoing = node->data;
539
540                                 if(outgoing->event)
541                                         event_del(outgoing->event);
542                         }
543
544                         list_delete_list(outgoing_list);
545
546                         /* Close connections to hosts that have a changed or deleted host config file */
547                         
548                         for(node = connection_tree->head; node; node = node->next) {
549                                 c = node->data;
550                                 
551                                 xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
552                                 if(stat(fname, &s) || s.st_mtime > last_config_check)
553                                         terminate_connection(c, c->status.active);
554                                 free(fname);
555                         }
556
557                         last_config_check = now;
558
559                         /* If StrictSubnet is set, expire deleted Subnets and read new ones in */
560
561                         if(strictsubnets) {
562                                 subnet_t *subnet;
563
564                                 for(node = subnet_tree->head; node; node = node->next) {
565                                         subnet = node->data;
566                                         subnet->expires = 1;
567                                 }
568
569                                 load_all_subnets();
570
571                                 for(node = subnet_tree->head; node; node = next) {
572                                         next = node->next;
573                                         subnet = node->data;
574                                         if(subnet->expires == 1) {
575                                                 send_del_subnet(everyone, subnet);
576                                                 if(subnet->owner->status.reachable)
577                                                         subnet_update(subnet->owner, subnet, false);
578                                                 subnet_del(subnet->owner, subnet);
579                                         } else if(subnet->expires == -1) {
580                                                 subnet->expires = 0;
581                                         } else {
582                                                 send_add_subnet(everyone, subnet);
583                                                 if(subnet->owner->status.reachable)
584                                                         subnet_update(subnet->owner, subnet, true);
585                                         }
586                                 }
587                         }
588
589                         /* Try to make outgoing connections */
590                         
591                         try_outgoing_connections();
592                 }
593                 
594                 /* Dump graph if wanted every 60 seconds*/
595
596                 if(last_graph_dump + 60 <= now) {
597                         dump_graph();
598                         last_graph_dump = now;
599                 }
600         }
601
602 #ifdef HAVE_PSELECT
603         /* Restore SIGHUP & SIGALARM mask */
604         sigprocmask(SIG_SETMASK, &omask, NULL);
605 #endif
606
607         return 0;
608 }