Remove legacy event system.
[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 "graph.h"
33 #include "logger.h"
34 #include "meta.h"
35 #include "net.h"
36 #include "netutl.h"
37 #include "process.h"
38 #include "protocol.h"
39 #include "route.h"
40 #include "subnet.h"
41 #include "xalloc.h"
42
43 bool do_purge = false;
44 volatile bool running = false;
45
46 time_t now = 0;
47
48 /* Purge edges and subnets of unreachable nodes. Use carefully. */
49
50 static void purge(void)
51 {
52         avl_node_t *nnode, *nnext, *enode, *enext, *snode, *snext;
53         node_t *n;
54         edge_t *e;
55         subnet_t *s;
56
57         cp();
58
59         ifdebug(PROTOCOL) logger(LOG_DEBUG, _("Purging unreachable nodes"));
60
61         /* Remove all edges and subnets owned by unreachable nodes. */
62
63         for(nnode = node_tree->head; nnode; nnode = nnext) {
64                 nnext = nnode->next;
65                 n = nnode->data;
66
67                 if(!n->status.reachable) {
68                         ifdebug(SCARY_THINGS) logger(LOG_DEBUG, _("Purging node %s (%s)"), n->name,
69                                            n->hostname);
70
71                         for(snode = n->subnet_tree->head; snode; snode = snext) {
72                                 snext = snode->next;
73                                 s = snode->data;
74                                 if(!tunnelserver)
75                                         send_del_subnet(broadcast, s);
76                                 subnet_del(n, s);
77                         }
78
79                         for(enode = n->edge_tree->head; enode; enode = enext) {
80                                 enext = enode->next;
81                                 e = enode->data;
82                                 if(!tunnelserver)
83                                         send_del_edge(broadcast, e);
84                                 edge_del(e);
85                         }
86                 }
87         }
88
89         /* Check if anyone else claims to have an edge to an unreachable node. If not, delete node. */
90
91         for(nnode = node_tree->head; nnode; nnode = nnext) {
92                 nnext = nnode->next;
93                 n = nnode->data;
94
95                 if(!n->status.reachable) {
96                         for(enode = edge_weight_tree->head; enode; enode = enext) {
97                                 enext = enode->next;
98                                 e = enode->data;
99
100                                 if(e->to == n)
101                                         break;
102                         }
103
104                         if(!enode)
105                                 node_del(n);
106                 }
107         }
108 }
109
110 /*
111   put all file descriptors into events
112   While we're at it, purge stuf that needs to be removed.
113 */
114 static int build_fdset(void)
115 {
116         avl_node_t *node, *next;
117         connection_t *c;
118         int i, max = 0;
119
120         cp();
121
122         for(node = connection_tree->head; node; node = next) {
123                 next = node->next;
124                 c = node->data;
125
126                 if(c->status.remove) {
127                         connection_del(c);
128                         if(!connection_tree->head)
129                                 purge();
130                 }
131         }
132
133         return 0;
134 }
135
136 /*
137   Terminate a connection:
138   - Close the socket
139   - Remove associated edge and tell other connections about it if report = true
140   - Check if we need to retry making an outgoing connection
141   - Deactivate the host
142 */
143 void terminate_connection(connection_t *c, bool report)
144 {
145         cp();
146
147         if(c->status.remove)
148                 return;
149
150         ifdebug(CONNECTIONS) logger(LOG_NOTICE, _("Closing connection with %s (%s)"),
151                            c->name, c->hostname);
152
153         c->status.remove = true;
154         c->status.active = false;
155
156         if(c->node)
157                 c->node->connection = NULL;
158
159         if(c->socket)
160                 closesocket(c->socket);
161
162         event_del(&c->ev);
163
164         if(c->edge) {
165                 if(report && !tunnelserver)
166                         send_del_edge(broadcast, c->edge);
167
168                 edge_del(c->edge);
169
170                 /* Run MST and SSSP algorithms */
171
172                 graph();
173
174                 /* If the node is not reachable anymore but we remember it had an edge to us, clean it up */
175
176                 if(report && !c->node->status.reachable) {
177                         edge_t *e;
178                         e = lookup_edge(c->node, myself);
179                         if(e) {
180                                 if(!tunnelserver)
181                                         send_del_edge(broadcast, e);
182                                 edge_del(e);
183                         }
184                 }
185         }
186
187         /* Check if this was our outgoing connection */
188
189         if(c->outgoing) {
190                 retry_outgoing(c->outgoing);
191                 c->outgoing = NULL;
192         }
193
194         free(c->outbuf);
195         c->outbuf = NULL;
196         c->outbuflen = 0;
197         c->outbufsize = 0;
198         c->outbufstart = 0;
199 }
200
201 /*
202   Check if the other end is active.
203   If we have sent packets, but didn't receive any,
204   then possibly the other end is dead. We send a
205   PING request over the meta connection. If the other
206   end does not reply in time, we consider them dead
207   and close the connection.
208 */
209 static void check_dead_connections(void)
210 {
211         avl_node_t *node, *next;
212         connection_t *c;
213
214         cp();
215
216         for(node = connection_tree->head; node; node = next) {
217                 next = node->next;
218                 c = node->data;
219
220                 if(c->last_ping_time + pingtimeout < now) {
221                         if(c->status.active) {
222                                 if(c->status.pinged) {
223                                         ifdebug(CONNECTIONS) logger(LOG_INFO, _("%s (%s) didn't respond to PING in %ld seconds"),
224                                                            c->name, c->hostname, now - c->last_ping_time);
225                                         c->status.timeout = true;
226                                         terminate_connection(c, true);
227                                 } else if(c->last_ping_time + pinginterval < now) {
228                                         send_ping(c);
229                                 }
230                         } else {
231                                 if(c->status.remove) {
232                                         logger(LOG_WARNING, _("Old connection_t for %s (%s) status %04x still lingering, deleting..."),
233                                                    c->name, c->hostname, c->status.value);
234                                         connection_del(c);
235                                         continue;
236                                 }
237                                 ifdebug(CONNECTIONS) logger(LOG_WARNING, _("Timeout from %s (%s) during authentication"),
238                                                    c->name, c->hostname);
239                                 if(c->status.connecting) {
240                                         c->status.connecting = false;
241                                         closesocket(c->socket);
242                                         do_outgoing_connection(c);
243                                 } else {
244                                         terminate_connection(c, false);
245                                 }
246                         }
247                 }
248
249                 if(c->outbuflen > 0 && c->last_flushed_time + pingtimeout < now) {
250                         if(c->status.active) {
251                                 ifdebug(CONNECTIONS) logger(LOG_INFO,
252                                                 _("%s (%s) could not flush for %ld seconds (%d bytes remaining)"),
253                                                 c->name, c->hostname, now - c->last_flushed_time, c->outbuflen);
254                                 c->status.timeout = true;
255                                 terminate_connection(c, true);
256                         }
257                 }
258         }
259 }
260
261 void handle_meta_connection_data(int fd, short events, void *data)
262 {
263         connection_t *c = data;
264         int result;
265         socklen_t len = sizeof(result);
266
267         if (c->status.remove)
268                 return;
269
270         if(c->status.connecting) {
271                 c->status.connecting = false;
272                 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, &result, &len);
273
274                 if(!result)
275                         finish_connecting(c);
276                 else {
277                         ifdebug(CONNECTIONS) logger(LOG_DEBUG,
278                                            _("Error while connecting to %s (%s): %s"),
279                                            c->name, c->hostname, strerror(result));
280                         closesocket(c->socket);
281                         do_outgoing_connection(c);
282                         return;
283                 }
284         }
285
286         if (!receive_meta(c)) {
287                 terminate_connection(c, c->status.active);
288                 return;
289         }
290 }
291
292 static void dummy(int a, short b, void *c)
293 {
294 }
295
296 void sighup_handler(int signal, short events, void *data) {
297         connection_t *c;
298         avl_node_t *node;
299         char *fname;
300         struct stat s;
301         static time_t last_config_check = 0;
302         
303         /* Reread our own configuration file */
304
305         exit_configuration(&config_tree);
306         init_configuration(&config_tree);
307
308         if(!read_server_config()) {
309                 logger(LOG_ERR, _("Unable to reread configuration file, exitting."));
310                 event_loopexit(NULL);
311                 return;
312         }
313
314         /* Close connections to hosts that have a changed or deleted host config file */
315         
316         for(node = connection_tree->head; node; node = node->next) {
317                 c = node->data;
318                 
319                 if(c->outgoing) {
320                         free(c->outgoing->name);
321                         if(c->outgoing->ai)
322                                 freeaddrinfo(c->outgoing->ai);
323                         free(c->outgoing);
324                         c->outgoing = NULL;
325                 }
326                 
327                 asprintf(&fname, "%s/hosts/%s", confbase, c->name);
328                 if(stat(fname, &s) || s.st_mtime > last_config_check)
329                         terminate_connection(c, c->status.active);
330                 free(fname);
331         }
332
333         last_config_check = time(NULL);
334
335         /* Try to make outgoing connections */
336         
337         try_outgoing_connections();
338 }
339
340 /*
341   this is where it all happens...
342 */
343 int main_loop(void)
344 {
345         struct timeval tv;
346         int r;
347         time_t last_ping_check;
348         struct event timeout;
349         struct event sighup_event;
350
351         cp();
352
353         signal_set(&sighup_event, SIGHUP, sighup_handler, NULL);
354         signal_add(&sighup_event, NULL);
355
356         last_ping_check = now;
357         
358         srand(now);
359
360         running = true;
361
362         while(running) {
363                 now = time(NULL);
364
365         //      tv.tv_sec = 1 + (rand() & 7);   /* Approx. 5 seconds, randomized to prevent global synchronisation effects */
366                 tv.tv_sec = 1;
367                 tv.tv_usec = 0;
368
369                 /* XXX: libevent transition: old timeout code in this loop */
370                 timeout_set(&timeout, dummy, NULL);
371                 timeout_add(&timeout, &tv);
372
373                 r = build_fdset();
374                 if(r < 0) {
375                         logger(LOG_ERR, _("Error building fdset: %s"), strerror(errno));
376                         cp_trace();
377                         dump_connections();
378                         return 1;
379                 }
380
381                 r = event_loop(EVLOOP_ONCE);
382                 now = time(NULL);
383                 if(r < 0) {
384                         logger(LOG_ERR, _("Error while waiting for input: %s"),
385                                    strerror(errno));
386                         cp_trace();
387                         dump_connections();
388                         return 1;
389                 }
390
391                 /* XXX: more libevent transition */
392                 timeout_del(&timeout);
393
394                 if(do_purge) {
395                         purge();
396                         do_purge = false;
397                 }
398
399                 /* Let's check if everybody is still alive */
400
401                 if(last_ping_check + pingtimeout < now) {
402                         check_dead_connections();
403                         last_ping_check = now;
404
405                         if(routing_mode == RMODE_SWITCH)
406                                 age_subnets();
407
408                         age_past_requests();
409
410                         /* Should we regenerate our key? */
411
412                         if(keyexpires < now) {
413                                 ifdebug(STATUS) logger(LOG_INFO, _("Regenerating symmetric key"));
414
415                                 RAND_pseudo_bytes((unsigned char *)myself->key, myself->keylength);
416                                 if(myself->cipher)
417                                         EVP_DecryptInit_ex(&packet_ctx, myself->cipher, NULL, (unsigned char *)myself->key, (unsigned char *)myself->key + myself->cipher->key_len);
418                                 send_key_changed(broadcast, myself);
419                                 keyexpires = now + keylifetime;
420                         }
421                 }
422
423                 if(sigalrm) {
424                         logger(LOG_INFO, _("Flushing event queue"));
425                         // TODO: do this another way
426                         sigalrm = false;
427                 }
428         }
429
430         signal_del(&sighup_event);
431
432         return 0;
433 }