1682705da74153241b3a96571ab5f8b6f37bdf54
[tinc] / src / net.c
1 /*
2     net.c -- most of the network code
3     Copyright (C) 1998-2005 Ivo Timmermans,
4                   2000-2007 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         FD_SET(device_fd, readset);
153         if(device_fd > max)
154                 max = device_fd;
155         
156         return max;
157 }
158
159 /*
160   Terminate a connection:
161   - Close the socket
162   - Remove associated edge and tell other connections about it if report = true
163   - Check if we need to retry making an outgoing connection
164   - Deactivate the host
165 */
166 void terminate_connection(connection_t *c, bool report)
167 {
168         cp();
169
170         if(c->status.remove)
171                 return;
172
173         ifdebug(CONNECTIONS) logger(LOG_NOTICE, _("Closing connection with %s (%s)"),
174                            c->name, c->hostname);
175
176         c->status.remove = true;
177         c->status.active = false;
178
179         if(c->node)
180                 c->node->connection = NULL;
181
182         if(c->socket)
183                 closesocket(c->socket);
184
185         if(c->edge) {
186                 if(report && !tunnelserver)
187                         send_del_edge(broadcast, c->edge);
188
189                 edge_del(c->edge);
190
191                 /* Run MST and SSSP algorithms */
192
193                 graph();
194
195                 /* If the node is not reachable anymore but we remember it had an edge to us, clean it up */
196
197                 if(report && !c->node->status.reachable) {
198                         edge_t *e;
199                         e = lookup_edge(c->node, myself);
200                         if(e) {
201                                 if(!tunnelserver)
202                                         send_del_edge(broadcast, e);
203                                 edge_del(e);
204                         }
205                 }
206         }
207
208         /* Check if this was our outgoing connection */
209
210         if(c->outgoing) {
211                 retry_outgoing(c->outgoing);
212                 c->outgoing = NULL;
213         }
214
215         free(c->outbuf);
216         c->outbuf = NULL;
217         c->outbuflen = 0;
218         c->outbufsize = 0;
219         c->outbufstart = 0;
220 }
221
222 /*
223   Check if the other end is active.
224   If we have sent packets, but didn't receive any,
225   then possibly the other end is dead. We send a
226   PING request over the meta connection. If the other
227   end does not reply in time, we consider them dead
228   and close the connection.
229 */
230 static void check_dead_connections(void)
231 {
232         avl_node_t *node, *next;
233         connection_t *c;
234
235         cp();
236
237         for(node = connection_tree->head; node; node = next) {
238                 next = node->next;
239                 c = node->data;
240
241                 if(c->last_ping_time + pingtimeout < now) {
242                         if(c->status.active) {
243                                 if(c->status.pinged) {
244                                         ifdebug(CONNECTIONS) logger(LOG_INFO, _("%s (%s) didn't respond to PING in %ld seconds"),
245                                                            c->name, c->hostname, now - c->last_ping_time);
246                                         c->status.timeout = true;
247                                         terminate_connection(c, true);
248                                 } else if(c->last_ping_time + pinginterval < now) {
249                                         send_ping(c);
250                                 }
251                         } else {
252                                 if(c->status.remove) {
253                                         logger(LOG_WARNING, _("Old connection_t for %s (%s) status %04x still lingering, deleting..."),
254                                                    c->name, c->hostname, c->status.value);
255                                         connection_del(c);
256                                         continue;
257                                 }
258                                 ifdebug(CONNECTIONS) logger(LOG_WARNING, _("Timeout from %s (%s) during authentication"),
259                                                    c->name, c->hostname);
260                                 if(c->status.connecting) {
261                                         c->status.connecting = false;
262                                         closesocket(c->socket);
263                                         do_outgoing_connection(c);
264                                 } else {
265                                         terminate_connection(c, false);
266                                 }
267                         }
268                 }
269
270                 if(c->outbuflen > 0 && c->last_flushed_time + pingtimeout < now) {
271                         if(c->status.active) {
272                                 ifdebug(CONNECTIONS) logger(LOG_INFO,
273                                                 _("%s (%s) could not flush for %ld seconds (%d bytes remaining)"),
274                                                 c->name, c->hostname, now - c->last_flushed_time, c->outbuflen);
275                                 c->status.timeout = true;
276                                 terminate_connection(c, true);
277                         }
278                 }
279         }
280 }
281
282 /*
283   check all connections to see if anything
284   happened on their sockets
285 */
286 static void check_network_activity(fd_set * readset, fd_set * writeset)
287 {
288         connection_t *c;
289         avl_node_t *node;
290         int result, i;
291         socklen_t len = sizeof(result);
292         vpn_packet_t packet;
293
294         cp();
295
296         /* check input from kernel */
297         if(FD_ISSET(device_fd, readset)) {
298                 if(read_packet(&packet))
299                         route(myself, &packet);
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, &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, strerror(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(listen_socket[i].udp);
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 {
354         fd_set readset, writeset;
355         struct timeval tv;
356         int r, maxfd;
357         time_t last_ping_check, last_config_check, last_graph_dump;
358         event_t *event;
359
360         cp();
361
362         last_ping_check = now;
363         last_config_check = now;
364         last_graph_dump = now;
365         
366         srand(now);
367
368         running = true;
369
370         while(running) {
371                 now = time(NULL);
372
373         //      tv.tv_sec = 1 + (rand() & 7);   /* Approx. 5 seconds, randomized to prevent global synchronisation effects */
374                 tv.tv_sec = 1;
375                 tv.tv_usec = 0;
376
377                 maxfd = build_fdset(&readset, &writeset);
378
379                 r = select(maxfd + 1, &readset, &writeset, NULL, &tv);
380
381                 if(r < 0) {
382                         if(errno != EINTR && errno != EAGAIN) {
383                                 logger(LOG_ERR, _("Error while waiting for input: %s"),
384                                            strerror(errno));
385                                 cp_trace();
386                                 dump_connections();
387                                 return 1;
388                         }
389
390                         continue;
391                 }
392
393                 check_network_activity(&readset, &writeset);
394
395                 if(do_purge) {
396                         purge();
397                         do_purge = false;
398                 }
399
400                 /* Let's check if everybody is still alive */
401
402                 if(last_ping_check + pingtimeout < now) {
403                         check_dead_connections();
404                         last_ping_check = now;
405
406                         if(routing_mode == RMODE_SWITCH)
407                                 age_subnets();
408
409                         age_past_requests();
410
411                         /* Should we regenerate our key? */
412
413                         if(keyexpires < now) {
414                                 ifdebug(STATUS) logger(LOG_INFO, _("Regenerating symmetric key"));
415
416                                 RAND_pseudo_bytes((unsigned char *)myself->key, myself->keylength);
417                                 if(myself->cipher)
418                                         EVP_DecryptInit_ex(&packet_ctx, myself->cipher, NULL, (unsigned char *)myself->key, (unsigned char *)myself->key + myself->cipher->key_len);
419                                 send_key_changed(broadcast, myself);
420                                 keyexpires = now + keylifetime;
421                         }
422                 }
423
424
425                 while((event = get_expired_event())) {
426                         event->handler(event->data);
427                         free_event(event);
428                 }
429
430                 if(sigalrm) {
431                         logger(LOG_INFO, _("Flushing event queue"));
432                         flush_events();
433                         sigalrm = false;
434                 }
435
436                 if(sighup) {
437                         connection_t *c;
438                         avl_node_t *node;
439                         char *fname;
440                         struct stat s;
441                         
442                         sighup = false;
443                         
444                         /* Reread our own configuration file */
445
446                         exit_configuration(&config_tree);
447                         init_configuration(&config_tree);
448
449                         if(!read_server_config()) {
450                                 logger(LOG_ERR, _("Unable to reread configuration file, exitting."));
451                                 return 1;
452                         }
453
454                         /* Close connections to hosts that have a changed or deleted host config file */
455                         
456                         for(node = connection_tree->head; node; node = node->next) {
457                                 c = node->data;
458                                 
459                                 if(c->outgoing) {
460                                         free(c->outgoing->name);
461                                         if(c->outgoing->ai)
462                                                 freeaddrinfo(c->outgoing->ai);
463                                         free(c->outgoing);
464                                         c->outgoing = NULL;
465                                 }
466                                 
467                                 asprintf(&fname, "%s/hosts/%s", confbase, c->name);
468                                 if(stat(fname, &s) || s.st_mtime > last_config_check)
469                                         terminate_connection(c, c->status.active);
470                                 free(fname);
471                         }
472
473                         last_config_check = now;
474
475                         /* Try to make outgoing connections */
476                         
477                         try_outgoing_connections();
478                 }
479                 
480                 /* Dump graph if wanted every 60 seconds*/
481
482                 if(last_graph_dump + 60 < now) {
483                         dump_graph();
484                         last_graph_dump = now;
485                 }
486         }
487
488         return 0;
489 }