Use libevent to handle HUP signal.
[tinc] / src / net.c
1 /*
2     net.c -- most of the network code
3     Copyright (C) 1998-2005 Ivo Timmermans,
4                   2000-2006 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 "tevent.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 into events
113   While we're at it, purge stuf that needs to be removed.
114 */
115 static int build_fdset(void)
116 {
117         avl_node_t *node, *next;
118         connection_t *c;
119         int i, max = 0;
120
121         cp();
122
123         for(node = connection_tree->head; node; node = next) {
124                 next = node->next;
125                 c = node->data;
126
127                 if(c->status.remove) {
128                         connection_del(c);
129                         if(!connection_tree->head)
130                                 purge();
131                 }
132         }
133
134         return 0;
135 }
136
137 /*
138   Terminate a connection:
139   - Close the socket
140   - Remove associated edge and tell other connections about it if report = true
141   - Check if we need to retry making an outgoing connection
142   - Deactivate the host
143 */
144 void terminate_connection(connection_t *c, bool report)
145 {
146         cp();
147
148         if(c->status.remove)
149                 return;
150
151         ifdebug(CONNECTIONS) logger(LOG_NOTICE, _("Closing connection with %s (%s)"),
152                            c->name, c->hostname);
153
154         c->status.remove = true;
155         c->status.active = false;
156
157         if(c->node)
158                 c->node->connection = NULL;
159
160         if(c->socket)
161                 closesocket(c->socket);
162
163         event_del(&c->ev);
164
165         if(c->edge) {
166                 if(report && !tunnelserver)
167                         send_del_edge(broadcast, c->edge);
168
169                 edge_del(c->edge);
170
171                 /* Run MST and SSSP algorithms */
172
173                 graph();
174
175                 /* If the node is not reachable anymore but we remember it had an edge to us, clean it up */
176
177                 if(report && !c->node->status.reachable) {
178                         edge_t *e;
179                         e = lookup_edge(c->node, myself);
180                         if(e) {
181                                 if(!tunnelserver)
182                                         send_del_edge(broadcast, e);
183                                 edge_del(e);
184                         }
185                 }
186         }
187
188         /* Check if this was our outgoing connection */
189
190         if(c->outgoing) {
191                 retry_outgoing(c->outgoing);
192                 c->outgoing = NULL;
193         }
194
195         free(c->outbuf);
196         c->outbuf = NULL;
197         c->outbuflen = 0;
198         c->outbufsize = 0;
199         c->outbufstart = 0;
200 }
201
202 /*
203   Check if the other end is active.
204   If we have sent packets, but didn't receive any,
205   then possibly the other end is dead. We send a
206   PING request over the meta connection. If the other
207   end does not reply in time, we consider them dead
208   and close the connection.
209 */
210 static void check_dead_connections(void)
211 {
212         avl_node_t *node, *next;
213         connection_t *c;
214
215         cp();
216
217         for(node = connection_tree->head; node; node = next) {
218                 next = node->next;
219                 c = node->data;
220
221                 if(c->last_ping_time + pingtimeout < now) {
222                         if(c->status.active) {
223                                 if(c->status.pinged) {
224                                         ifdebug(CONNECTIONS) logger(LOG_INFO, _("%s (%s) didn't respond to PING in %ld seconds"),
225                                                            c->name, c->hostname, now - c->last_ping_time);
226                                         c->status.timeout = true;
227                                         terminate_connection(c, true);
228                                 } else if(c->last_ping_time + pinginterval < now) {
229                                         send_ping(c);
230                                 }
231                         } else {
232                                 if(c->status.remove) {
233                                         logger(LOG_WARNING, _("Old connection_t for %s (%s) status %04x still lingering, deleting..."),
234                                                    c->name, c->hostname, c->status.value);
235                                         connection_del(c);
236                                         continue;
237                                 }
238                                 ifdebug(CONNECTIONS) logger(LOG_WARNING, _("Timeout from %s (%s) during authentication"),
239                                                    c->name, c->hostname);
240                                 if(c->status.connecting) {
241                                         c->status.connecting = false;
242                                         closesocket(c->socket);
243                                         do_outgoing_connection(c);
244                                 } else {
245                                         terminate_connection(c, false);
246                                 }
247                         }
248                 }
249
250                 if(c->outbuflen > 0 && c->last_flushed_time + pingtimeout < now) {
251                         if(c->status.active) {
252                                 ifdebug(CONNECTIONS) logger(LOG_INFO,
253                                                 _("%s (%s) could not flush for %ld seconds (%d bytes remaining)"),
254                                                 c->name, c->hostname, now - c->last_flushed_time, c->outbuflen);
255                                 c->status.timeout = true;
256                                 terminate_connection(c, true);
257                         }
258                 }
259         }
260 }
261
262 void handle_meta_connection_data(int fd, short events, void *data)
263 {
264         connection_t *c = data;
265         int result;
266         socklen_t len = sizeof(result);
267
268         if (c->status.remove)
269                 return;
270
271         if(c->status.connecting) {
272                 c->status.connecting = false;
273                 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, &result, &len);
274
275                 if(!result)
276                         finish_connecting(c);
277                 else {
278                         ifdebug(CONNECTIONS) logger(LOG_DEBUG,
279                                            _("Error while connecting to %s (%s): %s"),
280                                            c->name, c->hostname, strerror(result));
281                         closesocket(c->socket);
282                         do_outgoing_connection(c);
283                         return;
284                 }
285         }
286
287         if (!receive_meta(c)) {
288                 terminate_connection(c, c->status.active);
289                 return;
290         }
291 }
292
293 static void dummy(int a, short b, void *c)
294 {
295 }
296
297 void sighup_handler(int signal, short events, void *data) {
298         connection_t *c;
299         avl_node_t *node;
300         char *fname;
301         struct stat s;
302         static time_t last_config_check = 0;
303         
304         /* Reread our own configuration file */
305
306         exit_configuration(&config_tree);
307         init_configuration(&config_tree);
308
309         if(!read_server_config()) {
310                 logger(LOG_ERR, _("Unable to reread configuration file, exitting."));
311                 event_loopexit(NULL);
312                 return;
313         }
314
315         /* Close connections to hosts that have a changed or deleted host config file */
316         
317         for(node = connection_tree->head; node; node = node->next) {
318                 c = node->data;
319                 
320                 if(c->outgoing) {
321                         free(c->outgoing->name);
322                         if(c->outgoing->ai)
323                                 freeaddrinfo(c->outgoing->ai);
324                         free(c->outgoing);
325                         c->outgoing = NULL;
326                 }
327                 
328                 asprintf(&fname, "%s/hosts/%s", confbase, c->name);
329                 if(stat(fname, &s) || s.st_mtime > last_config_check)
330                         terminate_connection(c, c->status.active);
331                 free(fname);
332         }
333
334         last_config_check = time(NULL);
335
336         /* Try to make outgoing connections */
337         
338         try_outgoing_connections();
339 }
340
341 /*
342   this is where it all happens...
343 */
344 int main_loop(void)
345 {
346         struct timeval tv;
347         int r;
348         time_t last_ping_check;
349         tevent_t *event;
350         struct event timeout;
351         struct event sighup_event;
352
353         cp();
354
355         signal_set(&sighup_event, SIGHUP, sighup_handler, NULL);
356         signal_add(&sighup_event, NULL);
357
358         last_ping_check = now;
359         
360         srand(now);
361
362         running = true;
363
364         while(running) {
365                 now = time(NULL);
366
367         //      tv.tv_sec = 1 + (rand() & 7);   /* Approx. 5 seconds, randomized to prevent global synchronisation effects */
368                 tv.tv_sec = 1;
369                 tv.tv_usec = 0;
370
371                 /* XXX: libevent transition: old timeout code in this loop */
372                 timeout_set(&timeout, dummy, NULL);
373                 timeout_add(&timeout, &tv);
374
375                 r = build_fdset();
376                 if(r < 0) {
377                         logger(LOG_ERR, _("Error building fdset: %s"), strerror(errno));
378                         cp_trace();
379                         dump_connections();
380                         return 1;
381                 }
382
383                 r = event_loop(EVLOOP_ONCE);
384                 now = time(NULL);
385                 if(r < 0) {
386                         logger(LOG_ERR, _("Error while waiting for input: %s"),
387                                    strerror(errno));
388                         cp_trace();
389                         dump_connections();
390                         return 1;
391                 }
392
393                 /* XXX: more libevent transition */
394                 timeout_del(&timeout);
395
396                 if(do_purge) {
397                         purge();
398                         do_purge = false;
399                 }
400
401                 /* Let's check if everybody is still alive */
402
403                 if(last_ping_check + pingtimeout < now) {
404                         check_dead_connections();
405                         last_ping_check = now;
406
407                         if(routing_mode == RMODE_SWITCH)
408                                 age_subnets();
409
410                         age_past_requests();
411
412                         /* Should we regenerate our key? */
413
414                         if(keyexpires < now) {
415                                 ifdebug(STATUS) logger(LOG_INFO, _("Regenerating symmetric key"));
416
417                                 RAND_pseudo_bytes((unsigned char *)myself->key, myself->keylength);
418                                 if(myself->cipher)
419                                         EVP_DecryptInit_ex(&packet_ctx, myself->cipher, NULL, (unsigned char *)myself->key, (unsigned char *)myself->key + myself->cipher->key_len);
420                                 send_key_changed(broadcast, myself);
421                                 keyexpires = now + keylifetime;
422                         }
423                 }
424
425
426                 while((event = get_expired_tevent())) {
427                         event->handler(event->data);
428                         free_tevent(event);
429                 }
430
431                 if(sigalrm) {
432                         logger(LOG_INFO, _("Flushing event queue"));
433                         flush_tevents();
434                         sigalrm = false;
435                 }
436
437         }
438
439         signal_del(&sighup_event);
440
441         return 0;
442 }