Raise default RSA key length to 2048 bits.
[tinc] / src / net.c
1 /*
2     net.c -- most of the network code
3     Copyright (C) 1998-2005 Ivo Timmermans,
4                   2000-2009 Guus Sliepen <guus@tinc-vpn.org>
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20     $Id$
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
47 time_t now = 0;
48
49 /* Purge edges and subnets of unreachable nodes. Use carefully. */
50
51 static void purge(void)
52 {
53         avl_node_t *nnode, *nnext, *enode, *enext, *snode, *snext;
54         node_t *n;
55         edge_t *e;
56         subnet_t *s;
57
58         cp();
59
60         ifdebug(PROTOCOL) logger(LOG_DEBUG, _("Purging unreachable nodes"));
61
62         /* Remove all edges and subnets owned by unreachable nodes. */
63
64         for(nnode = node_tree->head; nnode; nnode = nnext) {
65                 nnext = nnode->next;
66                 n = nnode->data;
67
68                 if(!n->status.reachable) {
69                         ifdebug(SCARY_THINGS) logger(LOG_DEBUG, _("Purging node %s (%s)"), n->name,
70                                            n->hostname);
71
72                         for(snode = n->subnet_tree->head; snode; snode = snext) {
73                                 snext = snode->next;
74                                 s = snode->data;
75                                 if(!tunnelserver)
76                                         send_del_subnet(broadcast, s);
77                                 subnet_del(n, s);
78                         }
79
80                         for(enode = n->edge_tree->head; enode; enode = enext) {
81                                 enext = enode->next;
82                                 e = enode->data;
83                                 if(!tunnelserver)
84                                         send_del_edge(broadcast, e);
85                                 edge_del(e);
86                         }
87                 }
88         }
89
90         /* Check if anyone else claims to have an edge to an unreachable node. If not, delete node. */
91
92         for(nnode = node_tree->head; nnode; nnode = nnext) {
93                 nnext = nnode->next;
94                 n = nnode->data;
95
96                 if(!n->status.reachable) {
97                         for(enode = edge_weight_tree->head; enode; enode = enext) {
98                                 enext = enode->next;
99                                 e = enode->data;
100
101                                 if(e->to == n)
102                                         break;
103                         }
104
105                         if(!enode)
106                                 node_del(n);
107                 }
108         }
109 }
110
111 /*
112   put all file descriptors in an fd_set array
113   While we're at it, purge stuff that needs to be removed.
114 */
115 static int build_fdset(fd_set *readset, fd_set *writeset)
116 {
117         avl_node_t *node, *next;
118         connection_t *c;
119         int i, max = 0;
120
121         cp();
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 {
169         cp();
170
171         if(c->status.remove)
172                 return;
173
174         ifdebug(CONNECTIONS) logger(LOG_NOTICE, _("Closing connection with %s (%s)"),
175                            c->name, c->hostname);
176
177         c->status.remove = true;
178         c->status.active = false;
179
180         if(c->node)
181                 c->node->connection = NULL;
182
183         if(c->socket)
184                 closesocket(c->socket);
185
186         if(c->edge) {
187                 if(report && !tunnelserver)
188                         send_del_edge(broadcast, c->edge);
189
190                 edge_del(c->edge);
191
192                 /* Run MST and SSSP algorithms */
193
194                 graph();
195
196                 /* If the node is not reachable anymore but we remember it had an edge to us, clean it up */
197
198                 if(report && !c->node->status.reachable) {
199                         edge_t *e;
200                         e = lookup_edge(c->node, myself);
201                         if(e) {
202                                 if(!tunnelserver)
203                                         send_del_edge(broadcast, e);
204                                 edge_del(e);
205                         }
206                 }
207         }
208
209         /* Check if this was our outgoing connection */
210
211         if(c->outgoing) {
212                 retry_outgoing(c->outgoing);
213                 c->outgoing = NULL;
214         }
215
216         free(c->outbuf);
217         c->outbuf = NULL;
218         c->outbuflen = 0;
219         c->outbufsize = 0;
220         c->outbufstart = 0;
221 }
222
223 /*
224   Check if the other end is active.
225   If we have sent packets, but didn't receive any,
226   then possibly the other end is dead. We send a
227   PING request over the meta connection. If the other
228   end does not reply in time, we consider them dead
229   and close the connection.
230 */
231 static void check_dead_connections(void)
232 {
233         avl_node_t *node, *next;
234         connection_t *c;
235
236         cp();
237
238         for(node = connection_tree->head; node; node = next) {
239                 next = node->next;
240                 c = node->data;
241
242                 if(c->last_ping_time + pingtimeout < now) {
243                         if(c->status.active) {
244                                 if(c->status.pinged) {
245                                         ifdebug(CONNECTIONS) logger(LOG_INFO, _("%s (%s) didn't respond to PING in %ld seconds"),
246                                                            c->name, c->hostname, now - c->last_ping_time);
247                                         c->status.timeout = true;
248                                         terminate_connection(c, true);
249                                 } else if(c->last_ping_time + pinginterval < now) {
250                                         send_ping(c);
251                                 }
252                         } else {
253                                 if(c->status.remove) {
254                                         logger(LOG_WARNING, _("Old connection_t for %s (%s) status %04x still lingering, deleting..."),
255                                                    c->name, c->hostname, bitfield_to_int(&c->status, sizeof c->status));
256                                         connection_del(c);
257                                         continue;
258                                 }
259                                 ifdebug(CONNECTIONS) logger(LOG_WARNING, _("Timeout from %s (%s) during authentication"),
260                                                    c->name, c->hostname);
261                                 if(c->status.connecting) {
262                                         c->status.connecting = false;
263                                         closesocket(c->socket);
264                                         do_outgoing_connection(c);
265                                 } else {
266                                         terminate_connection(c, false);
267                                 }
268                         }
269                 }
270
271                 if(c->outbuflen > 0 && c->last_flushed_time + pingtimeout < now) {
272                         if(c->status.active) {
273                                 ifdebug(CONNECTIONS) logger(LOG_INFO,
274                                                 _("%s (%s) could not flush for %ld seconds (%d bytes remaining)"),
275                                                 c->name, c->hostname, now - c->last_flushed_time, c->outbuflen);
276                                 c->status.timeout = true;
277                                 terminate_connection(c, true);
278                         }
279                 }
280         }
281 }
282
283 /*
284   check all connections to see if anything
285   happened on their sockets
286 */
287 static void check_network_activity(fd_set * readset, fd_set * writeset)
288 {
289         connection_t *c;
290         avl_node_t *node;
291         int result, i;
292         socklen_t len = sizeof(result);
293         vpn_packet_t packet;
294
295         cp();
296
297         /* check input from kernel */
298         if(device_fd >= 0 && FD_ISSET(device_fd, readset)) {
299                 if(read_packet(&packet)) {
300                         packet.priority = 0;
301                         route(myself, &packet);
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, &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, strerror(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 {
357         fd_set readset, writeset;
358         struct timeval tv;
359         int r, maxfd;
360         time_t last_ping_check, last_config_check, last_graph_dump;
361         event_t *event;
362
363         cp();
364
365         last_ping_check = now;
366         last_config_check = now;
367         last_graph_dump = now;
368         
369         srand(now);
370
371         running = true;
372
373         while(running) {
374                 now = time(NULL);
375
376         //      tv.tv_sec = 1 + (rand() & 7);   /* Approx. 5 seconds, randomized to prevent global synchronisation effects */
377                 tv.tv_sec = 1;
378                 tv.tv_usec = 0;
379
380                 maxfd = build_fdset(&readset, &writeset);
381
382 #ifdef HAVE_MINGW
383                 LeaveCriticalSection(&mutex);
384 #endif
385                 r = select(maxfd + 1, &readset, &writeset, NULL, &tv);
386 #ifdef HAVE_MINGW
387                 EnterCriticalSection(&mutex);
388 #endif
389
390                 if(r < 0) {
391                         if(errno != EINTR && errno != EAGAIN) {
392                                 logger(LOG_ERR, _("Error while waiting for input: %s"),
393                                            strerror(errno));
394                                 cp_trace();
395                                 dump_connections();
396                                 return 1;
397                         }
398
399                         continue;
400                 }
401
402                 check_network_activity(&readset, &writeset);
403
404                 if(do_purge) {
405                         purge();
406                         do_purge = false;
407                 }
408
409                 /* Let's check if everybody is still alive */
410
411                 if(last_ping_check + pingtimeout < now) {
412                         check_dead_connections();
413                         last_ping_check = now;
414
415                         if(routing_mode == RMODE_SWITCH)
416                                 age_subnets();
417
418                         age_past_requests();
419
420                         /* Should we regenerate our key? */
421
422                         if(keyexpires < now) {
423                                 avl_node_t *node;
424                                 node_t *n;
425
426                                 ifdebug(STATUS) logger(LOG_INFO, _("Expiring symmetric keys"));
427
428                                 for(node = node_tree->head; node; node = node->next) {
429                                         n = node->data;
430                                         if(n->inkey) {
431                                                 free(n->inkey);
432                                                 n->inkey = NULL;
433                                         }
434                                 }
435
436                                 send_key_changed(broadcast, myself);
437                                 keyexpires = now + keylifetime;
438                         }
439                 }
440
441                 if(sigalrm) {
442                         logger(LOG_INFO, _("Flushing event queue"));
443                         expire_events();
444                         sigalrm = false;
445                 }
446
447                 while((event = get_expired_event())) {
448                         event->handler(event->data);
449                         free_event(event);
450                 }
451
452                 if(sighup) {
453                         connection_t *c;
454                         avl_node_t *node;
455                         char *fname;
456                         struct stat s;
457                         
458                         sighup = false;
459                         
460                         /* Reread our own configuration file */
461
462                         exit_configuration(&config_tree);
463                         init_configuration(&config_tree);
464
465                         if(!read_server_config()) {
466                                 logger(LOG_ERR, _("Unable to reread configuration file, exitting."));
467                                 return 1;
468                         }
469
470                         /* Close connections to hosts that have a changed or deleted host config file */
471                         
472                         for(node = connection_tree->head; node; node = node->next) {
473                                 c = node->data;
474                                 
475                                 xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
476                                 if(stat(fname, &s) || s.st_mtime > last_config_check)
477                                         terminate_connection(c, c->status.active);
478                                 free(fname);
479                         }
480
481                         last_config_check = now;
482
483                         /* Try to make outgoing connections */
484                         
485                         try_outgoing_connections();
486                 }
487                 
488                 /* Dump graph if wanted every 60 seconds*/
489
490                 if(last_graph_dump + 60 < now) {
491                         dump_graph();
492                         last_graph_dump = now;
493                 }
494         }
495
496         return 0;
497 }