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"
48 bool do_purge = false;
49 volatile bool running = false;
51 bool graph_dump = false;
55 int contradicting_add_edge = 0;
56 int contradicting_del_edge = 0;
57 static int sleeptime = 10;
59 /* Purge edges and subnets of unreachable nodes. Use carefully. */
61 static void purge(void) {
62 avl_node_t *nnode, *nnext, *enode, *enext, *snode, *snext;
67 ifdebug(PROTOCOL) logger(LOG_DEBUG, "Purging unreachable nodes");
69 /* Remove all edges and subnets owned by unreachable nodes. */
71 for(nnode = node_tree->head; nnode; nnode = nnext) {
75 if(!n->status.reachable) {
76 ifdebug(SCARY_THINGS) logger(LOG_DEBUG, "Purging node %s (%s)", n->name,
79 for(snode = n->subnet_tree->head; snode; snode = snext) {
82 send_del_subnet(everyone, s);
87 for(enode = n->edge_tree->head; enode; enode = enext) {
91 send_del_edge(everyone, e);
97 /* Check if anyone else claims to have an edge to an unreachable node. If not, delete node. */
99 for(nnode = node_tree->head; nnode; nnode = nnext) {
103 if(!n->status.reachable) {
104 for(enode = edge_weight_tree->head; enode; enode = enext) {
112 if(!enode && (!strictsubnets || !n->subnet_tree->head))
113 /* in strictsubnets mode do not delete nodes with subnets */
120 put all file descriptors in an fd_set array
121 While we're at it, purge stuff that needs to be removed.
123 static int build_fdset(fd_set *readset, fd_set *writeset) {
124 avl_node_t *node, *next;
131 for(node = connection_tree->head; node; node = next) {
135 if(c->status.remove) {
137 if(!connection_tree->head)
140 FD_SET(c->socket, readset);
141 if(c->outbuflen > 0 || c->status.connecting)
142 FD_SET(c->socket, writeset);
148 for(i = 0; i < listen_sockets; i++) {
149 FD_SET(listen_socket[i].tcp, readset);
150 if(listen_socket[i].tcp > max)
151 max = listen_socket[i].tcp;
152 FD_SET(listen_socket[i].udp, readset);
153 if(listen_socket[i].udp > max)
154 max = listen_socket[i].udp;
158 FD_SET(device_fd, readset);
166 Terminate a connection:
168 - Remove associated edge and tell other connections about it if report = true
169 - Check if we need to retry making an outgoing connection
170 - Deactivate the host
172 void terminate_connection(connection_t *c, bool report) {
176 ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Closing connection with %s (%s)",
177 c->name, c->hostname);
179 c->status.remove = true;
180 c->status.active = false;
183 c->node->connection = NULL;
186 closesocket(c->socket);
189 if(report && !tunnelserver)
190 send_del_edge(everyone, c->edge);
194 /* Run MST and SSSP algorithms */
198 /* If the node is not reachable anymore but we remember it had an edge to us, clean it up */
200 if(report && !c->node->status.reachable) {
202 e = lookup_edge(c->node, myself);
205 send_del_edge(everyone, e);
211 free_connection_partially(c);
213 /* Check if this was our outgoing connection */
216 c->status.remove = false;
217 do_outgoing_connection(c);
221 /* Clean up dead proxy processes */
223 while(waitpid(-1, NULL, WNOHANG) > 0);
228 Check if the other end is active.
229 If we have sent packets, but didn't receive any,
230 then possibly the other end is dead. We send a
231 PING request over the meta connection. If the other
232 end does not reply in time, we consider them dead
233 and close the connection.
235 static void check_dead_connections(void) {
236 avl_node_t *node, *next;
239 for(node = connection_tree->head; node; node = next) {
243 if(c->last_ping_time + pingtimeout <= now) {
244 if(c->status.active) {
245 if(c->status.pinged) {
246 ifdebug(CONNECTIONS) logger(LOG_INFO, "%s (%s) didn't respond to PING in %ld seconds",
247 c->name, c->hostname, (long)now - c->last_ping_time);
248 c->status.timeout = true;
249 terminate_connection(c, true);
250 } else if(c->last_ping_time + pinginterval <= now) {
254 if(c->status.remove) {
255 logger(LOG_WARNING, "Old connection_t for %s (%s) status %04x still lingering, deleting...",
256 c->name, c->hostname, bitfield_to_int(&c->status, sizeof c->status));
260 ifdebug(CONNECTIONS) logger(LOG_WARNING, "Timeout from %s (%s) during authentication",
261 c->name, c->hostname);
262 if(c->status.connecting) {
263 c->status.connecting = false;
264 closesocket(c->socket);
265 do_outgoing_connection(c);
267 terminate_connection(c, false);
272 if(c->outbuflen > 0 && c->last_flushed_time + pingtimeout <= now) {
273 if(c->status.active) {
274 ifdebug(CONNECTIONS) logger(LOG_INFO,
275 "%s (%s) could not flush for %ld seconds (%d bytes remaining)",
276 c->name, c->hostname, (long)now - c->last_flushed_time, c->outbuflen);
277 c->status.timeout = true;
278 terminate_connection(c, true);
285 check all connections to see if anything
286 happened on their sockets
288 static void check_network_activity(fd_set * readset, fd_set * writeset) {
292 socklen_t len = sizeof(result);
294 static int errors = 0;
296 /* check input from kernel */
297 if(device_fd >= 0 && FD_ISSET(device_fd, readset)) {
298 if(devops.read(&packet)) {
302 route(myself, &packet);
305 usleep(errors * 50000);
308 logger(LOG_ERR, "Too many errors from %s, exiting!", device);
314 /* check meta connections */
315 for(node = connection_tree->head; node; node = node->next) {
321 if(FD_ISSET(c->socket, writeset)) {
322 if(c->status.connecting) {
323 c->status.connecting = false;
324 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&result, &len);
327 finish_connecting(c);
329 ifdebug(CONNECTIONS) logger(LOG_DEBUG,
330 "Error while connecting to %s (%s): %s",
331 c->name, c->hostname, sockstrerror(result));
332 closesocket(c->socket);
333 do_outgoing_connection(c);
339 terminate_connection(c, c->status.active);
344 if(FD_ISSET(c->socket, readset)) {
345 if(!receive_meta(c)) {
346 terminate_connection(c, c->status.active);
352 for(i = 0; i < listen_sockets; i++) {
353 if(FD_ISSET(listen_socket[i].udp, readset))
354 handle_incoming_vpn_data(i);
356 if(FD_ISSET(listen_socket[i].tcp, readset))
357 handle_new_meta_connection(listen_socket[i].tcp);
362 this is where it all happens...
364 int main_loop(void) {
365 fd_set readset, writeset;
368 sigset_t omask, block_mask;
374 time_t last_ping_check, last_config_check, last_graph_dump;
377 last_ping_check = now;
378 last_config_check = now;
379 last_graph_dump = now;
384 if(lookup_config(config_tree, "GraphDumpFile"))
386 /* Block SIGHUP & SIGALRM */
387 sigemptyset(&block_mask);
388 sigaddset(&block_mask, SIGHUP);
389 sigaddset(&block_mask, SIGALRM);
390 sigprocmask(SIG_BLOCK, &block_mask, &omask);
397 next_event = last_ping_check + pingtimeout;
398 if(graph_dump && next_event > last_graph_dump + 60)
399 next_event = last_graph_dump + 60;
401 if((event = peek_next_event()) && next_event > event->time)
402 next_event = event->time;
404 if(next_event <= now)
407 tv.tv_sec = next_event - now;
414 maxfd = build_fdset(&readset, &writeset);
417 LeaveCriticalSection(&mutex);
420 r = pselect(maxfd + 1, &readset, &writeset, NULL, &tv, &omask);
422 r = select(maxfd + 1, &readset, &writeset, NULL, &tv);
426 EnterCriticalSection(&mutex);
430 if(!sockwouldblock(sockerrno)) {
431 logger(LOG_ERR, "Error while waiting for input: %s", sockstrerror(sockerrno));
438 check_network_activity(&readset, &writeset);
445 /* Let's check if everybody is still alive */
447 if(last_ping_check + pingtimeout <= now) {
448 check_dead_connections();
449 last_ping_check = now;
451 if(routing_mode == RMODE_SWITCH)
456 /* Should we regenerate our key? */
458 if(keyexpires <= now) {
462 ifdebug(STATUS) logger(LOG_INFO, "Expiring symmetric keys");
464 for(node = node_tree->head; node; node = node->next) {
473 keyexpires = now + keylifetime;
476 /* Detect ADD_EDGE/DEL_EDGE storms that are caused when
477 * two tinc daemons with the same name are on the VPN.
478 * If so, sleep a while. If this happens multiple times
479 * in a row, sleep longer. */
481 if(contradicting_del_edge > 100 && contradicting_add_edge > 100) {
482 logger(LOG_WARNING, "Possible node with same Name as us! Sleeping %d seconds.", sleeptime);
483 usleep(sleeptime * 1000000LL);
493 contradicting_add_edge = 0;
494 contradicting_del_edge = 0;
499 logger(LOG_INFO, "Flushing event queue");
501 #ifdef HAVE_DECL_RES_INIT
504 for(node = connection_tree->head; node; node = node->next) {
505 connection_t *c = node->data;
512 while((event = get_expired_event())) {
513 event->handler(event->data);
519 avl_node_t *node, *next;
527 /* Reread our own configuration file */
529 exit_configuration(&config_tree);
530 init_configuration(&config_tree);
532 if(!read_server_config()) {
533 logger(LOG_ERR, "Unable to reread configuration file, exitting.");
537 /* Cancel non-active outgoing connections */
539 for(node = connection_tree->head; node; node = next) {
545 if(c->status.connecting) {
546 terminate_connection(c, false);
551 /* Wipe list of outgoing connections */
553 for(list_node_t *node = outgoing_list->head; node; node = node->next) {
554 outgoing_t *outgoing = node->data;
557 event_del(outgoing->event);
560 list_delete_list(outgoing_list);
562 /* Close connections to hosts that have a changed or deleted host config file */
564 for(node = connection_tree->head; node; node = node->next) {
567 xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
568 if(stat(fname, &s) || s.st_mtime > last_config_check)
569 terminate_connection(c, c->status.active);
573 last_config_check = now;
575 /* If StrictSubnet is set, expire deleted Subnets and read new ones in */
580 for(node = subnet_tree->head; node; node = node->next) {
587 for(node = subnet_tree->head; node; node = next) {
590 if(subnet->expires == 1) {
591 send_del_subnet(everyone, subnet);
592 if(subnet->owner->status.reachable)
593 subnet_update(subnet->owner, subnet, false);
594 subnet_del(subnet->owner, subnet);
595 } else if(subnet->expires == -1) {
598 send_add_subnet(everyone, subnet);
599 if(subnet->owner->status.reachable)
600 subnet_update(subnet->owner, subnet, true);
605 /* Try to make outgoing connections */
607 try_outgoing_connections();
610 /* Dump graph if wanted every 60 seconds*/
612 if(last_graph_dump + 60 <= now) {
614 last_graph_dump = now;
619 /* Restore SIGHUP & SIGALARM mask */
620 sigprocmask(SIG_SETMASK, &omask, NULL);