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