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