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