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"
45 bool do_purge = false;
46 volatile bool running = false;
48 bool graph_dump = false;
52 int contradicting_add_edge = 0;
53 int contradicting_del_edge = 0;
54 static int sleeptime = 10;
56 /* Purge edges and subnets of unreachable nodes. Use carefully. */
58 static void purge(void) {
59 avl_node_t *nnode, *nnext, *enode, *enext, *snode, *snext;
64 ifdebug(PROTOCOL) logger(LOG_DEBUG, "Purging unreachable nodes");
66 /* Remove all edges and subnets owned by unreachable nodes. */
68 for(nnode = node_tree->head; nnode; nnode = nnext) {
72 if(!n->status.reachable) {
73 ifdebug(SCARY_THINGS) logger(LOG_DEBUG, "Purging node %s (%s)", n->name,
76 for(snode = n->subnet_tree->head; snode; snode = snext) {
79 send_del_subnet(everyone, s);
84 for(enode = n->edge_tree->head; enode; enode = enext) {
88 send_del_edge(everyone, e);
94 /* Check if anyone else claims to have an edge to an unreachable node. If not, delete node. */
96 for(nnode = node_tree->head; nnode; nnode = nnext) {
100 if(!n->status.reachable) {
101 for(enode = edge_weight_tree->head; enode; enode = enext) {
109 if(!enode && (!strictsubnets || !n->subnet_tree->head))
110 /* in strictsubnets mode do not delete nodes with subnets */
117 put all file descriptors in an fd_set array
118 While we're at it, purge stuff that needs to be removed.
120 static int build_fdset(fd_set *readset, fd_set *writeset) {
121 avl_node_t *node, *next;
128 for(node = connection_tree->head; node; node = next) {
132 if(c->status.remove) {
134 if(!connection_tree->head)
137 FD_SET(c->socket, readset);
138 if(c->outbuflen > 0 || c->status.connecting)
139 FD_SET(c->socket, writeset);
145 for(i = 0; i < listen_sockets; i++) {
146 FD_SET(listen_socket[i].tcp, readset);
147 if(listen_socket[i].tcp > max)
148 max = listen_socket[i].tcp;
149 FD_SET(listen_socket[i].udp, readset);
150 if(listen_socket[i].udp > max)
151 max = listen_socket[i].udp;
155 FD_SET(device_fd, readset);
163 Terminate a connection:
165 - Remove associated edge and tell other connections about it if report = true
166 - Check if we need to retry making an outgoing connection
167 - Deactivate the host
169 void terminate_connection(connection_t *c, bool report) {
173 ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Closing connection with %s (%s)",
174 c->name, c->hostname);
176 c->status.remove = true;
177 c->status.active = false;
180 c->node->connection = NULL;
183 closesocket(c->socket);
186 if(report && !tunnelserver)
187 send_del_edge(everyone, c->edge);
191 /* Run MST and SSSP algorithms */
195 /* If the node is not reachable anymore but we remember it had an edge to us, clean it up */
197 if(report && !c->node->status.reachable) {
199 e = lookup_edge(c->node, myself);
202 send_del_edge(everyone, e);
208 free_connection_partially(c);
210 /* Check if this was our outgoing connection */
213 c->status.remove = false;
214 do_outgoing_connection(c);
218 /* Clean up dead proxy processes */
220 while(waitpid(-1, NULL, WNOHANG) > 0);
225 Check if the other end is active.
226 If we have sent packets, but didn't receive any,
227 then possibly the other end is dead. We send a
228 PING request over the meta connection. If the other
229 end does not reply in time, we consider them dead
230 and close the connection.
232 static void check_dead_connections(void) {
233 avl_node_t *node, *next;
236 for(node = connection_tree->head; node; node = next) {
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, (long)now - c->last_ping_time);
245 c->status.timeout = true;
246 terminate_connection(c, true);
247 } else if(c->last_ping_time + pinginterval <= now) {
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));
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);
264 terminate_connection(c, false);
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, (long)now - c->last_flushed_time, c->outbuflen);
274 c->status.timeout = true;
275 terminate_connection(c, true);
282 check all connections to see if anything
283 happened on their sockets
285 static void check_network_activity(fd_set * readset, fd_set * writeset) {
289 socklen_t len = sizeof(result);
291 static int errors = 0;
293 /* check input from kernel */
294 if(device_fd >= 0 && FD_ISSET(device_fd, readset)) {
295 if(devops.read(&packet)) {
299 route(myself, &packet);
302 usleep(errors * 50000);
305 logger(LOG_ERR, "Too many errors from %s, exiting!", device);
311 /* check meta connections */
312 for(node = connection_tree->head; node; node = node->next) {
318 if(FD_ISSET(c->socket, writeset)) {
319 if(c->status.connecting) {
320 c->status.connecting = false;
321 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&result, &len);
324 finish_connecting(c);
326 ifdebug(CONNECTIONS) logger(LOG_DEBUG,
327 "Error while connecting to %s (%s): %s",
328 c->name, c->hostname, sockstrerror(result));
329 closesocket(c->socket);
330 do_outgoing_connection(c);
336 terminate_connection(c, c->status.active);
341 if(FD_ISSET(c->socket, readset)) {
342 if(!receive_meta(c)) {
343 terminate_connection(c, c->status.active);
349 for(i = 0; i < listen_sockets; i++) {
350 if(FD_ISSET(listen_socket[i].udp, readset))
351 handle_incoming_vpn_data(i);
353 if(FD_ISSET(listen_socket[i].tcp, readset))
354 handle_new_meta_connection(listen_socket[i].tcp);
359 this is where it all happens...
361 int main_loop(void) {
362 fd_set readset, writeset;
365 sigset_t omask, block_mask;
371 time_t last_ping_check, last_config_check, last_graph_dump;
374 last_ping_check = now;
375 last_config_check = now;
376 last_graph_dump = now;
381 if(lookup_config(config_tree, "GraphDumpFile"))
383 /* Block SIGHUP & SIGALRM */
384 sigemptyset(&block_mask);
385 sigaddset(&block_mask, SIGHUP);
386 sigaddset(&block_mask, SIGALRM);
387 sigprocmask(SIG_BLOCK, &block_mask, &omask);
394 next_event = last_ping_check + pingtimeout;
395 if(graph_dump && next_event > last_graph_dump + 60)
396 next_event = last_graph_dump + 60;
398 if((event = peek_next_event()) && next_event > event->time)
399 next_event = event->time;
401 if(next_event <= now)
404 tv.tv_sec = next_event - now;
411 maxfd = build_fdset(&readset, &writeset);
414 LeaveCriticalSection(&mutex);
417 r = pselect(maxfd + 1, &readset, &writeset, NULL, &tv, &omask);
419 r = select(maxfd + 1, &readset, &writeset, NULL, &tv);
423 EnterCriticalSection(&mutex);
427 if(!sockwouldblock(sockerrno)) {
428 logger(LOG_ERR, "Error while waiting for input: %s", sockstrerror(sockerrno));
435 check_network_activity(&readset, &writeset);
442 /* Let's check if everybody is still alive */
444 if(last_ping_check + pingtimeout <= now) {
445 check_dead_connections();
446 last_ping_check = now;
448 if(routing_mode == RMODE_SWITCH)
453 /* Should we regenerate our key? */
455 if(keyexpires <= now) {
459 ifdebug(STATUS) logger(LOG_INFO, "Expiring symmetric keys");
461 for(node = node_tree->head; node; node = node->next) {
470 keyexpires = now + keylifetime;
473 /* Detect ADD_EDGE/DEL_EDGE storms that are caused when
474 * two tinc daemons with the same name are on the VPN.
475 * If so, sleep a while. If this happens multiple times
476 * in a row, sleep longer. */
478 if(contradicting_del_edge > 100 && contradicting_add_edge > 100) {
479 logger(LOG_WARNING, "Possible node with same Name as us! Sleeping %d seconds.", sleeptime);
480 usleep(sleeptime * 1000000LL);
490 contradicting_add_edge = 0;
491 contradicting_del_edge = 0;
496 logger(LOG_INFO, "Flushing event queue");
499 for(node = connection_tree->head; node; node = node->next) {
500 connection_t *c = node->data;
507 while((event = get_expired_event())) {
508 event->handler(event->data);
514 avl_node_t *node, *next;
522 /* Reread our own configuration file */
524 exit_configuration(&config_tree);
525 init_configuration(&config_tree);
527 if(!read_server_config()) {
528 logger(LOG_ERR, "Unable to reread configuration file, exitting.");
532 /* Cancel non-active outgoing connections */
534 for(node = connection_tree->head; node; node = next) {
540 if(c->status.connecting) {
541 terminate_connection(c, false);
546 /* Wipe list of outgoing connections */
548 for(list_node_t *node = outgoing_list->head; node; node = node->next) {
549 outgoing_t *outgoing = node->data;
552 event_del(outgoing->event);
555 list_delete_list(outgoing_list);
557 /* Close connections to hosts that have a changed or deleted host config file */
559 for(node = connection_tree->head; node; node = node->next) {
562 xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
563 if(stat(fname, &s) || s.st_mtime > last_config_check)
564 terminate_connection(c, c->status.active);
568 last_config_check = now;
570 /* If StrictSubnet is set, expire deleted Subnets and read new ones in */
575 for(node = subnet_tree->head; node; node = node->next) {
582 for(node = subnet_tree->head; node; node = next) {
585 if(subnet->expires == 1) {
586 send_del_subnet(everyone, subnet);
587 if(subnet->owner->status.reachable)
588 subnet_update(subnet->owner, subnet, false);
589 subnet_del(subnet->owner, subnet);
590 } else if(subnet->expires == -1) {
593 send_add_subnet(everyone, subnet);
594 if(subnet->owner->status.reachable)
595 subnet_update(subnet->owner, subnet, true);
600 /* Try to make outgoing connections */
602 try_outgoing_connections();
605 /* Dump graph if wanted every 60 seconds*/
607 if(last_graph_dump + 60 <= now) {
609 last_graph_dump = now;
614 /* Restore SIGHUP & SIGALARM mask */
615 sigprocmask(SIG_SETMASK, &omask, NULL);