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