59dd39b30c327b8f15f5deb6360148a043deb466
[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                   2006      Scott Lamb <slamb@slamb.org>
6
7     This program is free software; you can redistribute it and/or modify
8     it under the terms of the GNU General Public License as published by
9     the Free Software Foundation; either version 2 of the License, or
10     (at your option) any later version.
11
12     This program is distributed in the hope that it will be useful,
13     but WITHOUT ANY WARRANTY; without even the implied warranty of
14     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15     GNU General Public License for more details.
16
17     You should have received a copy of the GNU General Public License along
18     with this program; if not, write to the Free Software Foundation, Inc.,
19     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 */
21
22 #include "system.h"
23
24 #include <openssl/rand.h>
25
26 #include "utils.h"
27 #include "avl_tree.h"
28 #include "conf.h"
29 #include "connection.h"
30 #include "device.h"
31 #include "event.h"
32 #include "graph.h"
33 #include "logger.h"
34 #include "meta.h"
35 #include "net.h"
36 #include "netutl.h"
37 #include "process.h"
38 #include "protocol.h"
39 #include "route.h"
40 #include "subnet.h"
41 #include "xalloc.h"
42
43 bool do_purge = false;
44 volatile bool running = false;
45
46 time_t now = 0;
47
48 /* Purge edges and subnets of unreachable nodes. Use carefully. */
49
50 static void purge(void) {
51         avl_node_t *nnode, *nnext, *enode, *enext, *snode, *snext;
52         node_t *n;
53         edge_t *e;
54         subnet_t *s;
55
56         ifdebug(PROTOCOL) logger(LOG_DEBUG, "Purging unreachable nodes");
57
58         /* Remove all edges and subnets owned by unreachable nodes. */
59
60         for(nnode = node_tree->head; nnode; nnode = nnext) {
61                 nnext = nnode->next;
62                 n = 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 = snode->data;
71                                 if(!tunnelserver)
72                                         send_del_subnet(broadcast, s);
73                                 subnet_del(n, s);
74                         }
75
76                         for(enode = n->edge_tree->head; enode; enode = enext) {
77                                 enext = enode->next;
78                                 e = enode->data;
79                                 if(!tunnelserver)
80                                         send_del_edge(broadcast, e);
81                                 edge_del(e);
82                         }
83                 }
84         }
85
86         /* Check if anyone else claims to have an edge to an unreachable node. If not, delete node. */
87
88         for(nnode = node_tree->head; nnode; nnode = nnext) {
89                 nnext = nnode->next;
90                 n = nnode->data;
91
92                 if(!n->status.reachable) {
93                         for(enode = edge_weight_tree->head; enode; enode = enext) {
94                                 enext = enode->next;
95                                 e = enode->data;
96
97                                 if(e->to == n)
98                                         break;
99                         }
100
101                         if(!enode)
102                                 node_del(n);
103                 }
104         }
105 }
106
107 /*
108   put all file descriptors in an fd_set array
109   While we're at it, purge stuff that needs to be removed.
110 */
111 static int build_fdset(fd_set *readset, fd_set *writeset) {
112         avl_node_t *node, *next;
113         connection_t *c;
114         int i, max = 0;
115
116         FD_ZERO(readset);
117         FD_ZERO(writeset);
118
119         for(node = connection_tree->head; node; node = next) {
120                 next = node->next;
121                 c = node->data;
122
123                 if(c->status.remove) {
124                         connection_del(c);
125                         if(!connection_tree->head)
126                                 purge();
127                 } else {
128                         FD_SET(c->socket, readset);
129                         if(c->outbuflen > 0)
130                                 FD_SET(c->socket, writeset);
131                         if(c->socket > max)
132                                 max = c->socket;
133                 }
134         }
135
136         for(i = 0; i < listen_sockets; i++) {
137                 FD_SET(listen_socket[i].tcp, readset);
138                 if(listen_socket[i].tcp > max)
139                         max = listen_socket[i].tcp;
140                 FD_SET(listen_socket[i].udp, readset);
141                 if(listen_socket[i].udp > max)
142                         max = listen_socket[i].udp;
143         }
144
145         if(device_fd >= 0)
146                 FD_SET(device_fd, readset);
147         if(device_fd > max)
148                 max = device_fd;
149         
150         return max;
151 }
152
153 /*
154   Terminate a connection:
155   - Close the socket
156   - Remove associated edge and tell other connections about it if report = true
157   - Check if we need to retry making an outgoing connection
158   - Deactivate the host
159 */
160 void terminate_connection(connection_t *c, bool report) {
161         if(c->status.remove)
162                 return;
163
164         ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Closing connection with %s (%s)",
165                            c->name, c->hostname);
166
167         c->status.remove = true;
168         c->status.active = false;
169
170         if(c->node)
171                 c->node->connection = NULL;
172
173         if(c->socket)
174                 closesocket(c->socket);
175
176         if(c->edge) {
177                 if(report && !tunnelserver)
178                         send_del_edge(broadcast, c->edge);
179
180                 edge_del(c->edge);
181
182                 /* Run MST and SSSP algorithms */
183
184                 graph();
185
186                 /* If the node is not reachable anymore but we remember it had an edge to us, clean it up */
187
188                 if(report && !c->node->status.reachable) {
189                         edge_t *e;
190                         e = lookup_edge(c->node, myself);
191                         if(e) {
192                                 if(!tunnelserver)
193                                         send_del_edge(broadcast, e);
194                                 edge_del(e);
195                         }
196                 }
197         }
198
199         /* Check if this was our outgoing connection */
200
201         if(c->outgoing) {
202                 retry_outgoing(c->outgoing);
203                 c->outgoing = NULL;
204         }
205
206         free(c->outbuf);
207         c->outbuf = NULL;
208         c->outbuflen = 0;
209         c->outbufsize = 0;
210         c->outbufstart = 0;
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         avl_node_t *node, *next;
223         connection_t *c;
224
225         for(node = connection_tree->head; node; node = next) {
226                 next = node->next;
227                 c = node->data;
228
229                 if(c->last_ping_time + pingtimeout < now) {
230                         if(c->status.active) {
231                                 if(c->status.pinged) {
232                                         ifdebug(CONNECTIONS) logger(LOG_INFO, "%s (%s) didn't respond to PING in %ld seconds",
233                                                            c->name, c->hostname, now - c->last_ping_time);
234                                         c->status.timeout = true;
235                                         terminate_connection(c, true);
236                                 } else if(c->last_ping_time + pinginterval < now) {
237                                         send_ping(c);
238                                 }
239                         } else {
240                                 if(c->status.remove) {
241                                         logger(LOG_WARNING, "Old connection_t for %s (%s) status %04x still lingering, deleting...",
242                                                    c->name, c->hostname, bitfield_to_int(&c->status, sizeof c->status));
243                                         connection_del(c);
244                                         continue;
245                                 }
246                                 ifdebug(CONNECTIONS) logger(LOG_WARNING, "Timeout from %s (%s) during authentication",
247                                                    c->name, c->hostname);
248                                 if(c->status.connecting) {
249                                         c->status.connecting = false;
250                                         closesocket(c->socket);
251                                         do_outgoing_connection(c);
252                                 } else {
253                                         terminate_connection(c, false);
254                                 }
255                         }
256                 }
257
258                 if(c->outbuflen > 0 && c->last_flushed_time + pingtimeout < now) {
259                         if(c->status.active) {
260                                 ifdebug(CONNECTIONS) logger(LOG_INFO,
261                                                 "%s (%s) could not flush for %ld seconds (%d bytes remaining)",
262                                                 c->name, c->hostname, now - c->last_flushed_time, c->outbuflen);
263                                 c->status.timeout = true;
264                                 terminate_connection(c, true);
265                         }
266                 }
267         }
268 }
269
270 /*
271   check all connections to see if anything
272   happened on their sockets
273 */
274 static void check_network_activity(fd_set * readset, fd_set * writeset) {
275         connection_t *c;
276         avl_node_t *node;
277         int result, i;
278         socklen_t len = sizeof(result);
279         vpn_packet_t packet;
280
281         /* check input from kernel */
282         if(device_fd >= 0 && FD_ISSET(device_fd, readset)) {
283                 if(read_packet(&packet)) {
284                         packet.priority = 0;
285                         route(myself, &packet);
286                 }
287         }
288
289         /* check meta connections */
290         for(node = connection_tree->head; node; node = node->next) {
291                 c = node->data;
292
293                 if(c->status.remove)
294                         continue;
295
296                 if(FD_ISSET(c->socket, readset)) {
297                         if(c->status.connecting) {
298                                 c->status.connecting = false;
299                                 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, &result, &len);
300
301                                 if(!result)
302                                         finish_connecting(c);
303                                 else {
304                                         ifdebug(CONNECTIONS) logger(LOG_DEBUG,
305                                                            "Error while connecting to %s (%s): %s",
306                                                            c->name, c->hostname, strerror(result));
307                                         closesocket(c->socket);
308                                         do_outgoing_connection(c);
309                                         continue;
310                                 }
311                         }
312
313                         if(!receive_meta(c)) {
314                                 terminate_connection(c, c->status.active);
315                                 continue;
316                         }
317                 }
318
319                 if(FD_ISSET(c->socket, writeset)) {
320                         if(!flush_meta(c)) {
321                                 terminate_connection(c, c->status.active);
322                                 continue;
323                         }
324                 }
325         }
326
327         for(i = 0; i < listen_sockets; i++) {
328                 if(FD_ISSET(listen_socket[i].udp, readset))
329                         handle_incoming_vpn_data(listen_socket[i].udp);
330
331                 if(FD_ISSET(listen_socket[i].tcp, readset))
332                         handle_new_meta_connection(listen_socket[i].tcp);
333         }
334 }
335
336 /*
337   this is where it all happens...
338 */
339 int main_loop(void) {
340         fd_set readset, writeset;
341         struct timeval tv;
342         int r, maxfd;
343         time_t last_ping_check, last_config_check, last_graph_dump;
344         event_t *event;
345
346         last_ping_check = now;
347         last_config_check = now;
348         last_graph_dump = now;
349         
350         srand(now);
351
352         running = true;
353
354         while(running) {
355                 now = time(NULL);
356
357         //      tv.tv_sec = 1 + (rand() & 7);   /* Approx. 5 seconds, randomized to prevent global synchronisation effects */
358                 tv.tv_sec = 1;
359                 tv.tv_usec = 0;
360
361                 maxfd = build_fdset(&readset, &writeset);
362
363 #ifdef HAVE_MINGW
364                 LeaveCriticalSection(&mutex);
365 #endif
366                 r = select(maxfd + 1, &readset, &writeset, NULL, &tv);
367 #ifdef HAVE_MINGW
368                 EnterCriticalSection(&mutex);
369 #endif
370
371                 if(r < 0) {
372                         if(errno != EINTR && errno != EAGAIN) {
373                                 logger(LOG_ERR, "Error while waiting for input: %s",
374                                            strerror(errno));
375                                 dump_connections();
376                                 return 1;
377                         }
378
379                         continue;
380                 }
381
382                 check_network_activity(&readset, &writeset);
383
384                 if(do_purge) {
385                         purge();
386                         do_purge = false;
387                 }
388
389                 /* Let's check if everybody is still alive */
390
391                 if(last_ping_check + pingtimeout < now) {
392                         check_dead_connections();
393                         last_ping_check = now;
394
395                         if(routing_mode == RMODE_SWITCH)
396                                 age_subnets();
397
398                         age_past_requests();
399
400                         /* Should we regenerate our key? */
401
402                         if(keyexpires < now) {
403                                 avl_node_t *node;
404                                 node_t *n;
405
406                                 ifdebug(STATUS) logger(LOG_INFO, "Expiring symmetric keys");
407
408                                 for(node = node_tree->head; node; node = node->next) {
409                                         n = node->data;
410                                         if(n->inkey) {
411                                                 free(n->inkey);
412                                                 n->inkey = NULL;
413                                         }
414                                 }
415
416                                 send_key_changed(broadcast, myself);
417                                 keyexpires = now + keylifetime;
418                         }
419                 }
420
421                 if(sigalrm) {
422                         logger(LOG_INFO, "Flushing event queue");
423                         expire_events();
424                         sigalrm = false;
425                 }
426
427                 while((event = get_expired_event())) {
428                         event->handler(event->data);
429                         free_event(event);
430                 }
431
432                 if(sighup) {
433                         connection_t *c;
434                         avl_node_t *node, *next;
435                         char *fname;
436                         struct stat s;
437                         
438                         sighup = false;
439                         
440                         /* Reread our own configuration file */
441
442                         exit_configuration(&config_tree);
443                         init_configuration(&config_tree);
444
445                         if(!read_server_config()) {
446                                 logger(LOG_ERR, "Unable to reread configuration file, exitting.");
447                                 return 1;
448                         }
449
450                         /* Cancel non-active outgoing connections */
451
452                         for(node = connection_tree->head; node; node = next) {
453                                 next = node->next;
454                                 c = node->data;
455
456                                 c->outgoing = NULL;
457
458                                 if(c->status.connecting) {
459                                         terminate_connection(c, false);
460                                         connection_del(c);
461                                 }
462                         }
463
464                         /* Wipe list of outgoing connections */
465
466                         for(list_node_t *node = outgoing_list->head; node; node = node->next) {
467                                 outgoing_t *outgoing = node->data;
468
469                                 if(outgoing->event)
470                                         event_del(outgoing->event);
471                         }
472
473                         list_delete_list(outgoing_list);
474
475                         /* Close connections to hosts that have a changed or deleted host config file */
476                         
477                         for(node = connection_tree->head; node; node = node->next) {
478                                 c = node->data;
479                                 
480                                 xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
481                                 if(stat(fname, &s) || s.st_mtime > last_config_check)
482                                         terminate_connection(c, c->status.active);
483                                 free(fname);
484                         }
485
486                         last_config_check = now;
487
488                         /* Try to make outgoing connections */
489                         
490                         try_outgoing_connections();
491                 }
492                 
493                 /* Dump graph if wanted every 60 seconds*/
494
495                 if(last_graph_dump + 60 < now) {
496                         dump_graph();
497                         last_graph_dump = now;
498                 }
499         }
500
501         return 0;
502 }