2 net.c -- most of the network code
3 Copyright (C) 1998-2005 Ivo Timmermans,
4 2000-2012 Guus Sliepen <guus@tinc-vpn.org>
5 2006 Scott Lamb <slamb@slamb.org>
6 2011 Loïc Grenié <loic.grenie@gmail.com>
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License along
19 with this program; if not, write to the Free Software Foundation, Inc.,
20 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 #include <openssl/rand.h>
30 #include "connection.h"
44 bool do_purge = false;
45 volatile bool running = false;
47 bool graph_dump = false;
51 int contradicting_add_edge = 0;
52 int contradicting_del_edge = 0;
53 static int sleeptime = 10;
55 /* Purge edges and subnets of unreachable nodes. Use carefully. */
57 static void purge(void) {
58 avl_node_t *nnode, *nnext, *enode, *enext, *snode, *snext;
63 ifdebug(PROTOCOL) logger(LOG_DEBUG, "Purging unreachable nodes");
65 /* Remove all edges and subnets owned by unreachable nodes. */
67 for(nnode = node_tree->head; nnode; nnode = nnext) {
71 if(!n->status.reachable) {
72 ifdebug(SCARY_THINGS) logger(LOG_DEBUG, "Purging node %s (%s)", n->name,
75 for(snode = n->subnet_tree->head; snode; snode = snext) {
78 send_del_subnet(everyone, s);
83 for(enode = n->edge_tree->head; enode; enode = enext) {
87 send_del_edge(everyone, e);
93 /* Check if anyone else claims to have an edge to an unreachable node. If not, delete node. */
95 for(nnode = node_tree->head; nnode; nnode = nnext) {
99 if(!n->status.reachable) {
100 for(enode = edge_weight_tree->head; enode; enode = enext) {
108 if(!enode && (!strictsubnets || !n->subnet_tree->head))
109 /* in strictsubnets mode do not delete nodes with subnets */
116 put all file descriptors in an fd_set array
117 While we're at it, purge stuff that needs to be removed.
119 static int build_fdset(fd_set *readset, fd_set *writeset) {
120 avl_node_t *node, *next;
127 for(node = connection_tree->head; node; node = next) {
131 if(c->status.remove) {
133 if(!connection_tree->head)
136 FD_SET(c->socket, readset);
138 FD_SET(c->socket, writeset);
144 for(i = 0; i < listen_sockets; i++) {
145 FD_SET(listen_socket[i].tcp, readset);
146 if(listen_socket[i].tcp > max)
147 max = listen_socket[i].tcp;
148 FD_SET(listen_socket[i].udp, readset);
149 if(listen_socket[i].udp > max)
150 max = listen_socket[i].udp;
154 FD_SET(device_fd, readset);
162 Terminate a connection:
164 - Remove associated edge and tell other connections about it if report = true
165 - Check if we need to retry making an outgoing connection
166 - Deactivate the host
168 void terminate_connection(connection_t *c, bool report) {
172 ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Closing connection with %s (%s)",
173 c->name, c->hostname);
175 c->status.remove = true;
176 c->status.active = false;
179 c->node->connection = NULL;
182 closesocket(c->socket);
185 if(report && !tunnelserver)
186 send_del_edge(everyone, c->edge);
190 /* Run MST and SSSP algorithms */
194 /* If the node is not reachable anymore but we remember it had an edge to us, clean it up */
196 if(report && !c->node->status.reachable) {
198 e = lookup_edge(c->node, myself);
201 send_del_edge(everyone, e);
207 free_connection_partially(c);
209 /* Check if this was our outgoing connection */
212 c->status.remove = false;
213 do_outgoing_connection(c);
218 Check if the other end is active.
219 If we have sent packets, but didn't receive any,
220 then possibly the other end is dead. We send a
221 PING request over the meta connection. If the other
222 end does not reply in time, we consider them dead
223 and close the connection.
225 static void check_dead_connections(void) {
226 avl_node_t *node, *next;
229 for(node = connection_tree->head; node; node = next) {
233 if(c->last_ping_time + pingtimeout <= now) {
234 if(c->status.active) {
235 if(c->status.pinged) {
236 ifdebug(CONNECTIONS) logger(LOG_INFO, "%s (%s) didn't respond to PING in %ld seconds",
237 c->name, c->hostname, now - c->last_ping_time);
238 c->status.timeout = true;
239 terminate_connection(c, true);
240 } else if(c->last_ping_time + pinginterval <= now) {
244 if(c->status.remove) {
245 logger(LOG_WARNING, "Old connection_t for %s (%s) status %04x still lingering, deleting...",
246 c->name, c->hostname, bitfield_to_int(&c->status, sizeof c->status));
250 ifdebug(CONNECTIONS) logger(LOG_WARNING, "Timeout from %s (%s) during authentication",
251 c->name, c->hostname);
252 if(c->status.connecting) {
253 c->status.connecting = false;
254 closesocket(c->socket);
255 do_outgoing_connection(c);
257 terminate_connection(c, false);
262 if(c->outbuflen > 0 && c->last_flushed_time + pingtimeout <= now) {
263 if(c->status.active) {
264 ifdebug(CONNECTIONS) logger(LOG_INFO,
265 "%s (%s) could not flush for %ld seconds (%d bytes remaining)",
266 c->name, c->hostname, now - c->last_flushed_time, c->outbuflen);
267 c->status.timeout = true;
268 terminate_connection(c, true);
275 check all connections to see if anything
276 happened on their sockets
278 static void check_network_activity(fd_set * readset, fd_set * writeset) {
282 socklen_t len = sizeof(result);
284 static int errors = 0;
286 /* check input from kernel */
287 if(device_fd >= 0 && FD_ISSET(device_fd, readset)) {
288 if(devops.read(&packet)) {
291 route(myself, &packet);
293 usleep(errors * 50000);
296 logger(LOG_ERR, "Too many errors from %s, exiting!", device);
302 /* check meta connections */
303 for(node = connection_tree->head; node; node = node->next) {
309 if(FD_ISSET(c->socket, readset)) {
310 if(c->status.connecting) {
311 c->status.connecting = false;
312 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&result, &len);
315 finish_connecting(c);
317 ifdebug(CONNECTIONS) logger(LOG_DEBUG,
318 "Error while connecting to %s (%s): %s",
319 c->name, c->hostname, sockstrerror(result));
320 closesocket(c->socket);
321 do_outgoing_connection(c);
326 if(!receive_meta(c)) {
327 terminate_connection(c, c->status.active);
332 if(FD_ISSET(c->socket, writeset)) {
334 terminate_connection(c, c->status.active);
340 for(i = 0; i < listen_sockets; i++) {
341 if(FD_ISSET(listen_socket[i].udp, readset))
342 handle_incoming_vpn_data(i);
344 if(FD_ISSET(listen_socket[i].tcp, readset))
345 handle_new_meta_connection(listen_socket[i].tcp);
350 this is where it all happens...
352 int main_loop(void) {
353 fd_set readset, writeset;
356 sigset_t omask, block_mask;
362 time_t last_ping_check, last_config_check, last_graph_dump;
365 last_ping_check = now;
366 last_config_check = now;
367 last_graph_dump = now;
372 if(lookup_config(config_tree, "GraphDumpFile"))
374 /* Block SIGHUP & SIGALRM */
375 sigemptyset(&block_mask);
376 sigaddset(&block_mask, SIGHUP);
377 sigaddset(&block_mask, SIGALRM);
378 sigprocmask(SIG_BLOCK, &block_mask, &omask);
385 next_event = last_ping_check + pingtimeout;
386 if(graph_dump && next_event > last_graph_dump + 60)
387 next_event = last_graph_dump + 60;
389 if((event = peek_next_event()) && next_event > event->time)
390 next_event = event->time;
392 if(next_event <= now)
395 tv.tv_sec = next_event - now;
402 maxfd = build_fdset(&readset, &writeset);
405 LeaveCriticalSection(&mutex);
408 r = pselect(maxfd + 1, &readset, &writeset, NULL, &tv, &omask);
410 r = select(maxfd + 1, &readset, &writeset, NULL, &tv);
414 EnterCriticalSection(&mutex);
418 if(!sockwouldblock(sockerrno)) {
419 logger(LOG_ERR, "Error while waiting for input: %s", sockstrerror(sockerrno));
426 check_network_activity(&readset, &writeset);
433 /* Let's check if everybody is still alive */
435 if(last_ping_check + pingtimeout <= now) {
436 check_dead_connections();
437 last_ping_check = now;
439 if(routing_mode == RMODE_SWITCH)
444 /* Should we regenerate our key? */
446 if(keyexpires <= now) {
450 ifdebug(STATUS) logger(LOG_INFO, "Expiring symmetric keys");
452 for(node = node_tree->head; node; node = node->next) {
461 keyexpires = now + keylifetime;
464 /* Detect ADD_EDGE/DEL_EDGE storms that are caused when
465 * two tinc daemons with the same name are on the VPN.
466 * If so, sleep a while. If this happens multiple times
467 * in a row, sleep longer. */
469 if(contradicting_del_edge > 100 && contradicting_add_edge > 100) {
470 logger(LOG_WARNING, "Possible node with same Name as us! Sleeping %d seconds.", sleeptime);
471 usleep(sleeptime * 1000000LL);
481 contradicting_add_edge = 0;
482 contradicting_del_edge = 0;
487 logger(LOG_INFO, "Flushing event queue");
489 for(node = connection_tree->head; node; node = node->next) {
490 connection_t *c = node->data;
496 while((event = get_expired_event())) {
497 event->handler(event->data);
503 avl_node_t *node, *next;
511 /* Reread our own configuration file */
513 exit_configuration(&config_tree);
514 init_configuration(&config_tree);
516 if(!read_server_config()) {
517 logger(LOG_ERR, "Unable to reread configuration file, exitting.");
521 /* Cancel non-active outgoing connections */
523 for(node = connection_tree->head; node; node = next) {
529 if(c->status.connecting) {
530 terminate_connection(c, false);
535 /* Wipe list of outgoing connections */
537 for(list_node_t *node = outgoing_list->head; node; node = node->next) {
538 outgoing_t *outgoing = node->data;
541 event_del(outgoing->event);
544 list_delete_list(outgoing_list);
546 /* Close connections to hosts that have a changed or deleted host config file */
548 for(node = connection_tree->head; node; node = node->next) {
551 xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
552 if(stat(fname, &s) || s.st_mtime > last_config_check)
553 terminate_connection(c, c->status.active);
557 last_config_check = now;
559 /* If StrictSubnet is set, expire deleted Subnets and read new ones in */
564 for(node = subnet_tree->head; node; node = node->next) {
571 for(node = subnet_tree->head; node; node = next) {
574 if(subnet->expires == 1) {
575 send_del_subnet(everyone, subnet);
576 if(subnet->owner->status.reachable)
577 subnet_update(subnet->owner, subnet, false);
578 subnet_del(subnet->owner, subnet);
579 } else if(subnet->expires == -1) {
582 send_add_subnet(everyone, subnet);
583 if(subnet->owner->status.reachable)
584 subnet_update(subnet->owner, subnet, true);
589 /* Try to make outgoing connections */
591 try_outgoing_connections();
594 /* Dump graph if wanted every 60 seconds*/
596 if(last_graph_dump + 60 <= now) {
598 last_graph_dump = now;
603 /* Restore SIGHUP & SIGALARM mask */
604 sigprocmask(SIG_SETMASK, &omask, NULL);