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);
190 logger(LOG_ERR, "Connection to %s (%s) has an edge but node is NULL!", c->name, c->hostname);
191 // And that should never happen.
195 if(report && !tunnelserver)
196 send_del_edge(everyone, c->edge);
200 /* Run MST and SSSP algorithms */
204 /* If the node is not reachable anymore but we remember it had an edge to us, clean it up */
206 if(report && !c->node->status.reachable) {
208 e = lookup_edge(c->node, myself);
211 send_del_edge(everyone, e);
217 free_connection_partially(c);
219 /* Check if this was our outgoing connection */
222 c->status.remove = false;
223 do_outgoing_connection(c);
227 /* Clean up dead proxy processes */
229 while(waitpid(-1, NULL, WNOHANG) > 0);
234 Check if the other end is active.
235 If we have sent packets, but didn't receive any,
236 then possibly the other end is dead. We send a
237 PING request over the meta connection. If the other
238 end does not reply in time, we consider them dead
239 and close the connection.
241 static void check_dead_connections(void) {
242 avl_node_t *node, *next;
245 for(node = connection_tree->head; node; node = next) {
249 if(c->last_ping_time + pingtimeout <= now) {
250 if(c->status.active) {
251 if(c->status.pinged) {
252 ifdebug(CONNECTIONS) logger(LOG_INFO, "%s (%s) didn't respond to PING in %ld seconds",
253 c->name, c->hostname, (long)now - c->last_ping_time);
254 c->status.timeout = true;
255 terminate_connection(c, true);
256 } else if(c->last_ping_time + pinginterval <= now) {
260 if(c->status.remove) {
261 logger(LOG_WARNING, "Old connection_t for %s (%s) status %04x still lingering, deleting...",
262 c->name, c->hostname, bitfield_to_int(&c->status, sizeof c->status));
266 ifdebug(CONNECTIONS) logger(LOG_WARNING, "Timeout from %s (%s) during authentication",
267 c->name, c->hostname);
268 if(c->status.connecting) {
269 c->status.connecting = false;
270 closesocket(c->socket);
271 do_outgoing_connection(c);
273 terminate_connection(c, false);
278 if(c->outbuflen > 0 && c->last_flushed_time + pingtimeout <= now) {
279 if(c->status.active) {
280 ifdebug(CONNECTIONS) logger(LOG_INFO,
281 "%s (%s) could not flush for %ld seconds (%d bytes remaining)",
282 c->name, c->hostname, (long)now - c->last_flushed_time, c->outbuflen);
283 c->status.timeout = true;
284 terminate_connection(c, true);
291 check all connections to see if anything
292 happened on their sockets
294 static void check_network_activity(fd_set * readset, fd_set * writeset) {
298 socklen_t len = sizeof(result);
300 static int errors = 0;
302 /* check input from kernel */
303 if(device_fd >= 0 && FD_ISSET(device_fd, readset)) {
304 if(devops.read(&packet)) {
308 route(myself, &packet);
311 usleep(errors * 50000);
314 logger(LOG_ERR, "Too many errors from %s, exiting!", device);
320 /* check meta connections */
321 for(node = connection_tree->head; node; node = node->next) {
327 if(FD_ISSET(c->socket, writeset)) {
328 if(c->status.connecting) {
329 c->status.connecting = false;
330 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&result, &len);
333 finish_connecting(c);
335 ifdebug(CONNECTIONS) logger(LOG_DEBUG,
336 "Error while connecting to %s (%s): %s",
337 c->name, c->hostname, sockstrerror(result));
338 closesocket(c->socket);
339 do_outgoing_connection(c);
345 terminate_connection(c, c->status.active);
350 if(FD_ISSET(c->socket, readset)) {
351 if(!receive_meta(c)) {
352 terminate_connection(c, c->status.active);
358 for(i = 0; i < listen_sockets; i++) {
359 if(FD_ISSET(listen_socket[i].udp, readset))
360 handle_incoming_vpn_data(i);
362 if(FD_ISSET(listen_socket[i].tcp, readset))
363 handle_new_meta_connection(listen_socket[i].tcp);
368 this is where it all happens...
370 int main_loop(void) {
371 fd_set readset, writeset;
374 sigset_t omask, block_mask;
380 time_t last_ping_check, last_config_check, last_graph_dump;
383 last_ping_check = now;
384 last_config_check = now;
385 last_graph_dump = now;
390 if(lookup_config(config_tree, "GraphDumpFile"))
392 /* Block SIGHUP & SIGALRM */
393 sigemptyset(&block_mask);
394 sigaddset(&block_mask, SIGHUP);
395 sigaddset(&block_mask, SIGALRM);
396 sigprocmask(SIG_BLOCK, &block_mask, &omask);
403 next_event = last_ping_check + pingtimeout;
404 if(graph_dump && next_event > last_graph_dump + 60)
405 next_event = last_graph_dump + 60;
407 if((event = peek_next_event()) && next_event > event->time)
408 next_event = event->time;
410 if(next_event <= now)
413 tv.tv_sec = next_event - now;
420 maxfd = build_fdset(&readset, &writeset);
423 LeaveCriticalSection(&mutex);
426 r = pselect(maxfd + 1, &readset, &writeset, NULL, &tv, &omask);
428 r = select(maxfd + 1, &readset, &writeset, NULL, &tv);
432 EnterCriticalSection(&mutex);
436 if(!sockwouldblock(sockerrno)) {
437 logger(LOG_ERR, "Error while waiting for input: %s", sockstrerror(sockerrno));
444 check_network_activity(&readset, &writeset);
451 /* Let's check if everybody is still alive */
453 if(last_ping_check + pingtimeout <= now) {
454 check_dead_connections();
455 last_ping_check = now;
457 if(routing_mode == RMODE_SWITCH)
462 /* Should we regenerate our key? */
464 if(keyexpires <= now) {
468 ifdebug(STATUS) logger(LOG_INFO, "Expiring symmetric keys");
470 for(node = node_tree->head; node; node = node->next) {
479 keyexpires = now + keylifetime;
482 /* Detect ADD_EDGE/DEL_EDGE storms that are caused when
483 * two tinc daemons with the same name are on the VPN.
484 * If so, sleep a while. If this happens multiple times
485 * in a row, sleep longer. */
487 if(contradicting_del_edge > 100 && contradicting_add_edge > 100) {
488 logger(LOG_WARNING, "Possible node with same Name as us! Sleeping %d seconds.", sleeptime);
489 usleep(sleeptime * 1000000LL);
499 contradicting_add_edge = 0;
500 contradicting_del_edge = 0;
505 logger(LOG_INFO, "Flushing event queue");
507 #ifdef HAVE_DECL_RES_INIT
510 for(node = connection_tree->head; node; node = node->next) {
511 connection_t *c = node->data;
518 while((event = get_expired_event())) {
519 event->handler(event->data);
525 avl_node_t *node, *next;
533 /* Reread our own configuration file */
535 exit_configuration(&config_tree);
536 init_configuration(&config_tree);
538 if(!read_server_config()) {
539 logger(LOG_ERR, "Unable to reread configuration file, exitting.");
543 /* Cancel non-active outgoing connections */
545 for(node = connection_tree->head; node; node = next) {
551 if(c->status.connecting) {
552 terminate_connection(c, false);
557 /* Wipe list of outgoing connections */
559 for(list_node_t *node = outgoing_list->head; node; node = node->next) {
560 outgoing_t *outgoing = node->data;
563 event_del(outgoing->event);
566 list_delete_list(outgoing_list);
568 /* Close connections to hosts that have a changed or deleted host config file */
570 for(node = connection_tree->head; node; node = node->next) {
573 xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
574 if(stat(fname, &s) || s.st_mtime > last_config_check)
575 terminate_connection(c, c->status.active);
579 last_config_check = now;
581 /* If StrictSubnet is set, expire deleted Subnets and read new ones in */
586 for(node = subnet_tree->head; node; node = node->next) {
593 for(node = subnet_tree->head; node; node = next) {
596 if(subnet->expires == 1) {
597 send_del_subnet(everyone, subnet);
598 if(subnet->owner->status.reachable)
599 subnet_update(subnet->owner, subnet, false);
600 subnet_del(subnet->owner, subnet);
601 } else if(subnet->expires == -1) {
604 send_add_subnet(everyone, subnet);
605 if(subnet->owner->status.reachable)
606 subnet_update(subnet->owner, subnet, true);
611 /* Try to make outgoing connections */
613 try_outgoing_connections();
616 /* Dump graph if wanted every 60 seconds*/
618 if(last_graph_dump + 60 <= now) {
620 last_graph_dump = now;
625 /* Restore SIGHUP & SIGALARM mask */
626 sigprocmask(SIG_SETMASK, &omask, NULL);