If we're not in main_loop() and the service is stopped, exit immediately.
[tinc] / src / net.c
1 /*
2     net.c -- most of the network code
3     Copyright (C) 1998-2003 Ivo Timmermans <ivo@o2w.nl>,
4                   2000-2003 Guus Sliepen <guus@sliepen.eu.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: net.c,v 1.35.4.197 2003/08/17 12:05:08 guus Exp $
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 "event.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         for(nnode = node_tree->head; nnode; nnode = nnext) {
63                 nnext = nnode->next;
64                 n = (node_t *) nnode->data;
65
66                 if(!n->status.reachable) {
67                         ifdebug(SCARY_THINGS) logger(LOG_DEBUG, _("Purging node %s (%s)"), n->name,
68                                            n->hostname);
69
70                         for(snode = n->subnet_tree->head; snode; snode = snext) {
71                                 snext = snode->next;
72                                 s = (subnet_t *) snode->data;
73                                 send_del_subnet(broadcast, s);
74                                 subnet_del(n, s);
75                         }
76
77                         for(enode = n->edge_tree->head; enode; enode = enext) {
78                                 enext = enode->next;
79                                 e = (edge_t *) enode->data;
80                                 send_del_edge(broadcast, e);
81                                 edge_del(e);
82                         }
83
84                         node_del(n);
85                 }
86         }
87 }
88
89 /*
90   put all file descriptors in an fd_set array
91   While we're at it, purge stuff that needs to be removed.
92 */
93 static int build_fdset(fd_set * fs)
94 {
95         avl_node_t *node, *next;
96         connection_t *c;
97         int i, max = 0;
98
99         cp();
100
101         FD_ZERO(fs);
102
103         for(node = connection_tree->head; node; node = next) {
104                 next = node->next;
105                 c = (connection_t *) node->data;
106
107                 if(c->status.remove) {
108                         connection_del(c);
109                         if(!connection_tree->head)
110                                 purge();
111                 } else {
112                         FD_SET(c->socket, fs);
113                         if(c->socket > max)
114                                 max = c->socket;
115                 }
116         }
117
118         for(i = 0; i < listen_sockets; i++) {
119                 FD_SET(listen_socket[i].tcp, fs);
120                 if(listen_socket[i].tcp > max)
121                         max = listen_socket[i].tcp;
122                 FD_SET(listen_socket[i].udp, fs);
123                 if(listen_socket[i].udp > max)
124                         max = listen_socket[i].udp;
125         }
126
127         FD_SET(device_fd, fs);
128         if(device_fd > max)
129                 max = device_fd;
130         
131         return max;
132 }
133
134 /*
135   Terminate a connection:
136   - Close the socket
137   - Remove associated edge and tell other connections about it if report = true
138   - Check if we need to retry making an outgoing connection
139   - Deactivate the host
140 */
141 void terminate_connection(connection_t *c, bool report)
142 {
143         cp();
144
145         if(c->status.remove)
146                 return;
147
148         ifdebug(CONNECTIONS) logger(LOG_NOTICE, _("Closing connection with %s (%s)"),
149                            c->name, c->hostname);
150
151         c->status.remove = true;
152         c->status.active = false;
153
154         if(c->node)
155                 c->node->connection = NULL;
156
157         if(c->socket)
158                 closesocket(c->socket);
159
160         if(c->edge) {
161                 if(report)
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
171         /* Check if this was our outgoing connection */
172
173         if(c->outgoing) {
174                 retry_outgoing(c->outgoing);
175                 c->outgoing = NULL;
176         }
177 }
178
179 /*
180   Check if the other end is active.
181   If we have sent packets, but didn't receive any,
182   then possibly the other end is dead. We send a
183   PING request over the meta connection. If the other
184   end does not reply in time, we consider them dead
185   and close the connection.
186 */
187 static void check_dead_connections(void)
188 {
189         avl_node_t *node, *next;
190         connection_t *c;
191
192         cp();
193
194         for(node = connection_tree->head; node; node = next) {
195                 next = node->next;
196                 c = (connection_t *) node->data;
197
198                 if(c->last_ping_time + pingtimeout < now) {
199                         if(c->status.active) {
200                                 if(c->status.pinged) {
201                                         ifdebug(CONNECTIONS) logger(LOG_INFO, _("%s (%s) didn't respond to PING"),
202                                                            c->name, c->hostname);
203                                         c->status.timeout = true;
204                                         terminate_connection(c, true);
205                                 } else {
206                                         send_ping(c);
207                                 }
208                         } else {
209                                 if(c->status.remove) {
210                                         logger(LOG_WARNING, _("Old connection_t for %s (%s) status %04x still lingering, deleting..."),
211                                                    c->name, c->hostname, *(uint32_t *)&c->status);
212                                         connection_del(c);
213                                         continue;
214                                 }
215                                 ifdebug(CONNECTIONS) logger(LOG_WARNING, _("Timeout from %s (%s) during authentication"),
216                                                    c->name, c->hostname);
217                                 terminate_connection(c, false);
218                         }
219                 }
220         }
221 }
222
223 /*
224   check all connections to see if anything
225   happened on their sockets
226 */
227 static void check_network_activity(fd_set * f)
228 {
229         connection_t *c;
230         avl_node_t *node;
231         int result, i;
232         int len = sizeof(result);
233         vpn_packet_t packet;
234
235         cp();
236
237         if(FD_ISSET(device_fd, f)) {
238                 if(read_packet(&packet))
239                         route_outgoing(&packet);
240         }
241
242         for(node = connection_tree->head; node; node = node->next) {
243                 c = (connection_t *) node->data;
244
245                 if(c->status.remove)
246                         continue;
247
248                 if(FD_ISSET(c->socket, f)) {
249                         if(c->status.connecting) {
250                                 c->status.connecting = false;
251                                 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, &result, &len);
252
253                                 if(!result)
254                                         finish_connecting(c);
255                                 else {
256                                         ifdebug(CONNECTIONS) logger(LOG_DEBUG,
257                                                            _("Error while connecting to %s (%s): %s"),
258                                                            c->name, c->hostname, strerror(result));
259                                         closesocket(c->socket);
260                                         do_outgoing_connection(c);
261                                         continue;
262                                 }
263                         }
264
265                         if(!receive_meta(c)) {
266                                 terminate_connection(c, c->status.active);
267                                 continue;
268                         }
269                 }
270         }
271
272         for(i = 0; i < listen_sockets; i++) {
273                 if(FD_ISSET(listen_socket[i].udp, f))
274                         handle_incoming_vpn_data(listen_socket[i].udp);
275
276                 if(FD_ISSET(listen_socket[i].tcp, f))
277                         handle_new_meta_connection(listen_socket[i].tcp);
278         }
279 }
280
281 /*
282   this is where it all happens...
283 */
284 int main_loop(void)
285 {
286         fd_set fset;
287         struct timeval tv;
288         int r, maxfd;
289         time_t last_ping_check, last_config_check;
290         event_t *event;
291
292         cp();
293
294         last_ping_check = now;
295         last_config_check = now;
296         srand(now);
297
298         running = true;
299
300         while(running) {
301                 now = time(NULL);
302
303                 tv.tv_sec = 1 + (rand() & 7);   /* Approx. 5 seconds, randomized to prevent global synchronisation effects */
304                 tv.tv_usec = 0;
305
306                 maxfd = build_fdset(&fset);
307
308                 r = select(maxfd + 1, &fset, NULL, NULL, &tv);
309
310                 if(r < 0) {
311                         if(errno != EINTR && errno != EAGAIN) {
312                                 logger(LOG_ERR, _("Error while waiting for input: %s"),
313                                            strerror(errno));
314                                 cp_trace();
315                                 dump_connections();
316                                 return 1;
317                         }
318
319                         continue;
320                 }
321
322                 check_network_activity(&fset);
323
324                 if(do_purge) {
325                         purge();
326                         do_purge = false;
327                 }
328
329                 /* Let's check if everybody is still alive */
330
331                 if(last_ping_check + pingtimeout < now) {
332                         check_dead_connections();
333                         last_ping_check = now;
334
335                         if(routing_mode == RMODE_SWITCH)
336                                 age_mac();
337
338                         age_past_requests();
339
340                         /* Should we regenerate our key? */
341
342                         if(keyexpires < now) {
343                                 ifdebug(STATUS) logger(LOG_INFO, _("Regenerating symmetric key"));
344
345                                 RAND_pseudo_bytes(myself->key, myself->keylength);
346                                 if(myself->cipher)
347                                         EVP_DecryptInit_ex(&packet_ctx, myself->cipher, NULL, myself->key, myself->key + myself->cipher->key_len);
348                                 send_key_changed(broadcast, myself);
349                                 keyexpires = now + keylifetime;
350                         }
351                 }
352
353
354                 while((event = get_expired_event())) {
355                         event->handler(event->data);
356                         free(event);
357                 }
358
359                 if(sigalrm) {
360                         logger(LOG_INFO, _("Flushing event queue"));
361
362                         while(event_tree->head) {
363                                 event = (event_t *) event_tree->head->data;
364                                 event->handler(event->data);
365                                 event_del(event);
366                         }
367                         sigalrm = false;
368                 }
369
370                 if(sighup) {
371                         connection_t *c;
372                         avl_node_t *node;
373                         char *fname;
374                         struct stat s;
375                         
376                         sighup = false;
377                         
378                         /* Reread our own configuration file */
379
380                         exit_configuration(&config_tree);
381                         init_configuration(&config_tree);
382
383                         if(!read_server_config()) {
384                                 logger(LOG_ERR, _("Unable to reread configuration file, exitting."));
385                                 return 1;
386                         }
387
388                         /* Close connections to hosts that have a changed or deleted host config file */
389                         
390                         for(node = connection_tree->head; node; node = node->next) {
391                                 c = (connection_t *) node->data;
392                                 
393                                 if(c->outgoing) {
394                                         free(c->outgoing->name);
395                                         freeaddrinfo(c->outgoing->ai);
396                                         free(c->outgoing);
397                                         c->outgoing = NULL;
398                                 }
399                                 
400                                 asprintf(&fname, "%s/hosts/%s", confbase, c->name);
401                                 if(stat(fname, &s) || s.st_mtime > last_config_check)
402                                         terminate_connection(c, c->status.active);
403                                 free(fname);
404                         }
405
406                         last_config_check = now;
407
408                         /* Try to make outgoing connections */
409                         
410                         try_outgoing_connections();
411                 }
412         }
413
414         return 0;
415 }