Use a separate event structure to handle meta data writes.
[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 /*
298   this is where it all happens...
299 */
300 int main_loop(void)
301 {
302         struct timeval tv;
303         int r;
304         time_t last_ping_check, last_config_check, last_graph_dump;
305         tevent_t *event;
306         struct event timeout;
307
308         cp();
309
310         last_ping_check = now;
311         last_config_check = now;
312         last_graph_dump = now;
313         
314         srand(now);
315
316         running = true;
317
318         while(running) {
319                 now = time(NULL);
320
321         //      tv.tv_sec = 1 + (rand() & 7);   /* Approx. 5 seconds, randomized to prevent global synchronisation effects */
322                 tv.tv_sec = 1;
323                 tv.tv_usec = 0;
324
325                 /* XXX: libevent transition: old timeout code in this loop */
326                 timeout_set(&timeout, dummy, NULL);
327                 timeout_add(&timeout, &tv);
328
329                 r = build_fdset();
330                 if(r < 0) {
331                         logger(LOG_ERR, _("Error building fdset: %s"), strerror(errno));
332                         cp_trace();
333                         dump_connections();
334                         return 1;
335                 }
336
337                 r = event_loop(EVLOOP_ONCE);
338                 now = time(NULL);
339                 if(r < 0) {
340                         logger(LOG_ERR, _("Error while waiting for input: %s"),
341                                    strerror(errno));
342                         cp_trace();
343                         dump_connections();
344                         return 1;
345                 }
346
347                 /* XXX: more libevent transition */
348                 timeout_del(&timeout);
349
350                 if(do_purge) {
351                         purge();
352                         do_purge = false;
353                 }
354
355                 /* Let's check if everybody is still alive */
356
357                 if(last_ping_check + pingtimeout < now) {
358                         check_dead_connections();
359                         last_ping_check = now;
360
361                         if(routing_mode == RMODE_SWITCH)
362                                 age_subnets();
363
364                         age_past_requests();
365
366                         /* Should we regenerate our key? */
367
368                         if(keyexpires < now) {
369                                 ifdebug(STATUS) logger(LOG_INFO, _("Regenerating symmetric key"));
370
371                                 RAND_pseudo_bytes((unsigned char *)myself->key, myself->keylength);
372                                 if(myself->cipher)
373                                         EVP_DecryptInit_ex(&packet_ctx, myself->cipher, NULL, (unsigned char *)myself->key, (unsigned char *)myself->key + myself->cipher->key_len);
374                                 send_key_changed(broadcast, myself);
375                                 keyexpires = now + keylifetime;
376                         }
377                 }
378
379
380                 while((event = get_expired_tevent())) {
381                         event->handler(event->data);
382                         free_tevent(event);
383                 }
384
385                 if(sigalrm) {
386                         logger(LOG_INFO, _("Flushing event queue"));
387                         flush_tevents();
388                         sigalrm = false;
389                 }
390
391                 if(sighup) {
392                         connection_t *c;
393                         avl_node_t *node;
394                         char *fname;
395                         struct stat s;
396                         
397                         sighup = false;
398                         
399                         /* Reread our own configuration file */
400
401                         exit_configuration(&config_tree);
402                         init_configuration(&config_tree);
403
404                         if(!read_server_config()) {
405                                 logger(LOG_ERR, _("Unable to reread configuration file, exitting."));
406                                 return 1;
407                         }
408
409                         /* Close connections to hosts that have a changed or deleted host config file */
410                         
411                         for(node = connection_tree->head; node; node = node->next) {
412                                 c = node->data;
413                                 
414                                 if(c->outgoing) {
415                                         free(c->outgoing->name);
416                                         if(c->outgoing->ai)
417                                                 freeaddrinfo(c->outgoing->ai);
418                                         free(c->outgoing);
419                                         c->outgoing = NULL;
420                                 }
421                                 
422                                 asprintf(&fname, "%s/hosts/%s", confbase, c->name);
423                                 if(stat(fname, &s) || s.st_mtime > last_config_check)
424                                         terminate_connection(c, c->status.active);
425                                 free(fname);
426                         }
427
428                         last_config_check = now;
429
430                         /* Try to make outgoing connections */
431                         
432                         try_outgoing_connections();
433                 }
434                 
435                 /* Dump graph if wanted every 60 seconds*/
436
437                 if(last_graph_dump + 60 < now) {
438                         dump_graph();
439                         last_graph_dump = now;
440                 }
441         }
442
443         return 0;
444 }