Update the address of the Free Software Foundation in all copyright headers.
[tinc] / src / net.c
1 /*
2     net.c -- most of the network code
3     Copyright (C) 1998-2005 Ivo Timmermans,
4                   2000-2009 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 along
17     with this program; if not, write to the Free Software Foundation, Inc.,
18     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
21 #include "system.h"
22
23 #include <openssl/rand.h>
24
25 #include "utils.h"
26 #include "avl_tree.h"
27 #include "conf.h"
28 #include "connection.h"
29 #include "device.h"
30 #include "event.h"
31 #include "graph.h"
32 #include "logger.h"
33 #include "meta.h"
34 #include "net.h"
35 #include "netutl.h"
36 #include "process.h"
37 #include "protocol.h"
38 #include "route.h"
39 #include "subnet.h"
40 #include "xalloc.h"
41
42 bool do_purge = false;
43 volatile bool running = 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         /* Remove all edges and subnets owned by unreachable nodes. */
61
62         for(nnode = node_tree->head; nnode; nnode = nnext) {
63                 nnext = nnode->next;
64                 n = 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 = snode->data;
73                                 if(!tunnelserver)
74                                         send_del_subnet(broadcast, s);
75                                 subnet_del(n, s);
76                         }
77
78                         for(enode = n->edge_tree->head; enode; enode = enext) {
79                                 enext = enode->next;
80                                 e = enode->data;
81                                 if(!tunnelserver)
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 = nnode->data;
93
94                 if(!n->status.reachable) {
95                         for(enode = edge_weight_tree->head; enode; enode = enext) {
96                                 enext = enode->next;
97                                 e = 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 *readset, fd_set *writeset)
114 {
115         avl_node_t *node, *next;
116         connection_t *c;
117         int i, max = 0;
118
119         cp();
120
121         FD_ZERO(readset);
122         FD_ZERO(writeset);
123
124         for(node = connection_tree->head; node; node = next) {
125                 next = node->next;
126                 c = node->data;
127
128                 if(c->status.remove) {
129                         connection_del(c);
130                         if(!connection_tree->head)
131                                 purge();
132                 } else {
133                         FD_SET(c->socket, readset);
134                         if(c->outbuflen > 0)
135                                 FD_SET(c->socket, writeset);
136                         if(c->socket > max)
137                                 max = c->socket;
138                 }
139         }
140
141         for(i = 0; i < listen_sockets; i++) {
142                 FD_SET(listen_socket[i].tcp, readset);
143                 if(listen_socket[i].tcp > max)
144                         max = listen_socket[i].tcp;
145                 FD_SET(listen_socket[i].udp, readset);
146                 if(listen_socket[i].udp > max)
147                         max = listen_socket[i].udp;
148         }
149
150         if(device_fd >= 0)
151                 FD_SET(device_fd, readset);
152         if(device_fd > max)
153                 max = device_fd;
154         
155         return max;
156 }
157
158 /*
159   Terminate a connection:
160   - Close the socket
161   - Remove associated edge and tell other connections about it if report = true
162   - Check if we need to retry making an outgoing connection
163   - Deactivate the host
164 */
165 void terminate_connection(connection_t *c, bool report)
166 {
167         cp();
168
169         if(c->status.remove)
170                 return;
171
172         ifdebug(CONNECTIONS) logger(LOG_NOTICE, _("Closing connection with %s (%s)"),
173                            c->name, c->hostname);
174
175         c->status.remove = true;
176         c->status.active = false;
177
178         if(c->node)
179                 c->node->connection = NULL;
180
181         if(c->socket)
182                 closesocket(c->socket);
183
184         if(c->edge) {
185                 if(report && !tunnelserver)
186                         send_del_edge(broadcast, c->edge);
187
188                 edge_del(c->edge);
189
190                 /* Run MST and SSSP algorithms */
191
192                 graph();
193
194                 /* If the node is not reachable anymore but we remember it had an edge to us, clean it up */
195
196                 if(report && !c->node->status.reachable) {
197                         edge_t *e;
198                         e = lookup_edge(c->node, myself);
199                         if(e) {
200                                 if(!tunnelserver)
201                                         send_del_edge(broadcast, e);
202                                 edge_del(e);
203                         }
204                 }
205         }
206
207         /* Check if this was our outgoing connection */
208
209         if(c->outgoing) {
210                 retry_outgoing(c->outgoing);
211                 c->outgoing = NULL;
212         }
213
214         free(c->outbuf);
215         c->outbuf = NULL;
216         c->outbuflen = 0;
217         c->outbufsize = 0;
218         c->outbufstart = 0;
219 }
220
221 /*
222   Check if the other end is active.
223   If we have sent packets, but didn't receive any,
224   then possibly the other end is dead. We send a
225   PING request over the meta connection. If the other
226   end does not reply in time, we consider them dead
227   and close the connection.
228 */
229 static void check_dead_connections(void)
230 {
231         avl_node_t *node, *next;
232         connection_t *c;
233
234         cp();
235
236         for(node = connection_tree->head; node; node = next) {
237                 next = node->next;
238                 c = node->data;
239
240                 if(c->last_ping_time + pingtimeout < now) {
241                         if(c->status.active) {
242                                 if(c->status.pinged) {
243                                         ifdebug(CONNECTIONS) logger(LOG_INFO, _("%s (%s) didn't respond to PING in %ld seconds"),
244                                                            c->name, c->hostname, now - c->last_ping_time);
245                                         c->status.timeout = true;
246                                         terminate_connection(c, true);
247                                 } else if(c->last_ping_time + pinginterval < now) {
248                                         send_ping(c);
249                                 }
250                         } else {
251                                 if(c->status.remove) {
252                                         logger(LOG_WARNING, _("Old connection_t for %s (%s) status %04x still lingering, deleting..."),
253                                                    c->name, c->hostname, bitfield_to_int(&c->status, sizeof c->status));
254                                         connection_del(c);
255                                         continue;
256                                 }
257                                 ifdebug(CONNECTIONS) logger(LOG_WARNING, _("Timeout from %s (%s) during authentication"),
258                                                    c->name, c->hostname);
259                                 if(c->status.connecting) {
260                                         c->status.connecting = false;
261                                         closesocket(c->socket);
262                                         do_outgoing_connection(c);
263                                 } else {
264                                         terminate_connection(c, false);
265                                 }
266                         }
267                 }
268
269                 if(c->outbuflen > 0 && c->last_flushed_time + pingtimeout < now) {
270                         if(c->status.active) {
271                                 ifdebug(CONNECTIONS) logger(LOG_INFO,
272                                                 _("%s (%s) could not flush for %ld seconds (%d bytes remaining)"),
273                                                 c->name, c->hostname, now - c->last_flushed_time, c->outbuflen);
274                                 c->status.timeout = true;
275                                 terminate_connection(c, true);
276                         }
277                 }
278         }
279 }
280
281 /*
282   check all connections to see if anything
283   happened on their sockets
284 */
285 static void check_network_activity(fd_set * readset, fd_set * writeset)
286 {
287         connection_t *c;
288         avl_node_t *node;
289         int result, i;
290         socklen_t len = sizeof(result);
291         vpn_packet_t packet;
292
293         cp();
294
295         /* check input from kernel */
296         if(device_fd >= 0 && FD_ISSET(device_fd, readset)) {
297                 if(read_packet(&packet)) {
298                         packet.priority = 0;
299                         route(myself, &packet);
300                 }
301         }
302
303         /* check meta connections */
304         for(node = connection_tree->head; node; node = node->next) {
305                 c = node->data;
306
307                 if(c->status.remove)
308                         continue;
309
310                 if(FD_ISSET(c->socket, readset)) {
311                         if(c->status.connecting) {
312                                 c->status.connecting = false;
313                                 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, &result, &len);
314
315                                 if(!result)
316                                         finish_connecting(c);
317                                 else {
318                                         ifdebug(CONNECTIONS) logger(LOG_DEBUG,
319                                                            _("Error while connecting to %s (%s): %s"),
320                                                            c->name, c->hostname, strerror(result));
321                                         closesocket(c->socket);
322                                         do_outgoing_connection(c);
323                                         continue;
324                                 }
325                         }
326
327                         if(!receive_meta(c)) {
328                                 terminate_connection(c, c->status.active);
329                                 continue;
330                         }
331                 }
332
333                 if(FD_ISSET(c->socket, writeset)) {
334                         if(!flush_meta(c)) {
335                                 terminate_connection(c, c->status.active);
336                                 continue;
337                         }
338                 }
339         }
340
341         for(i = 0; i < listen_sockets; i++) {
342                 if(FD_ISSET(listen_socket[i].udp, readset))
343                         handle_incoming_vpn_data(listen_socket[i].udp);
344
345                 if(FD_ISSET(listen_socket[i].tcp, readset))
346                         handle_new_meta_connection(listen_socket[i].tcp);
347         }
348 }
349
350 /*
351   this is where it all happens...
352 */
353 int main_loop(void)
354 {
355         fd_set readset, writeset;
356         struct timeval tv;
357         int r, maxfd;
358         time_t last_ping_check, last_config_check, last_graph_dump;
359         event_t *event;
360
361         cp();
362
363         last_ping_check = now;
364         last_config_check = now;
365         last_graph_dump = now;
366         
367         srand(now);
368
369         running = true;
370
371         while(running) {
372                 now = time(NULL);
373
374         //      tv.tv_sec = 1 + (rand() & 7);   /* Approx. 5 seconds, randomized to prevent global synchronisation effects */
375                 tv.tv_sec = 1;
376                 tv.tv_usec = 0;
377
378                 maxfd = build_fdset(&readset, &writeset);
379
380 #ifdef HAVE_MINGW
381                 LeaveCriticalSection(&mutex);
382 #endif
383                 r = select(maxfd + 1, &readset, &writeset, NULL, &tv);
384 #ifdef HAVE_MINGW
385                 EnterCriticalSection(&mutex);
386 #endif
387
388                 if(r < 0) {
389                         if(errno != EINTR && errno != EAGAIN) {
390                                 logger(LOG_ERR, _("Error while waiting for input: %s"),
391                                            strerror(errno));
392                                 cp_trace();
393                                 dump_connections();
394                                 return 1;
395                         }
396
397                         continue;
398                 }
399
400                 check_network_activity(&readset, &writeset);
401
402                 if(do_purge) {
403                         purge();
404                         do_purge = false;
405                 }
406
407                 /* Let's check if everybody is still alive */
408
409                 if(last_ping_check + pingtimeout < now) {
410                         check_dead_connections();
411                         last_ping_check = now;
412
413                         if(routing_mode == RMODE_SWITCH)
414                                 age_subnets();
415
416                         age_past_requests();
417
418                         /* Should we regenerate our key? */
419
420                         if(keyexpires < now) {
421                                 avl_node_t *node;
422                                 node_t *n;
423
424                                 ifdebug(STATUS) logger(LOG_INFO, _("Expiring symmetric keys"));
425
426                                 for(node = node_tree->head; node; node = node->next) {
427                                         n = node->data;
428                                         if(n->inkey) {
429                                                 free(n->inkey);
430                                                 n->inkey = NULL;
431                                         }
432                                 }
433
434                                 send_key_changed(broadcast, myself);
435                                 keyexpires = now + keylifetime;
436                         }
437                 }
438
439                 if(sigalrm) {
440                         logger(LOG_INFO, _("Flushing event queue"));
441                         expire_events();
442                         sigalrm = false;
443                 }
444
445                 while((event = get_expired_event())) {
446                         event->handler(event->data);
447                         free_event(event);
448                 }
449
450                 if(sighup) {
451                         connection_t *c;
452                         avl_node_t *node;
453                         char *fname;
454                         struct stat s;
455                         
456                         sighup = false;
457                         
458                         /* Reread our own configuration file */
459
460                         exit_configuration(&config_tree);
461                         init_configuration(&config_tree);
462
463                         if(!read_server_config()) {
464                                 logger(LOG_ERR, _("Unable to reread configuration file, exitting."));
465                                 return 1;
466                         }
467
468                         /* Close connections to hosts that have a changed or deleted host config file */
469                         
470                         for(node = connection_tree->head; node; node = node->next) {
471                                 c = node->data;
472                                 
473                                 xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
474                                 if(stat(fname, &s) || s.st_mtime > last_config_check)
475                                         terminate_connection(c, c->status.active);
476                                 free(fname);
477                         }
478
479                         last_config_check = now;
480
481                         /* Try to make outgoing connections */
482                         
483                         try_outgoing_connections();
484                 }
485                 
486                 /* Dump graph if wanted every 60 seconds*/
487
488                 if(last_graph_dump + 60 < now) {
489                         dump_graph();
490                         last_graph_dump = now;
491                 }
492         }
493
494         return 0;
495 }