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