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