2 net.c -- most of the network code
3 Copyright (C) 1998-2005 Ivo Timmermans,
4 2000-2014 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 #ifdef HAVE_ARPA_NAMESER_H
45 #include <arpa/nameser.h>
52 bool do_purge = false;
53 volatile bool running = false;
55 bool graph_dump = false;
59 int contradicting_add_edge = 0;
60 int contradicting_del_edge = 0;
61 static int sleeptime = 10;
63 /* Purge edges and subnets of unreachable nodes. Use carefully. */
65 static void purge(void) {
66 avl_node_t *nnode, *nnext, *enode, *enext, *snode, *snext;
71 ifdebug(PROTOCOL) logger(LOG_DEBUG, "Purging unreachable nodes");
73 /* Remove all edges and subnets owned by unreachable nodes. */
75 for(nnode = node_tree->head; nnode; nnode = nnext) {
79 if(!n->status.reachable) {
80 ifdebug(SCARY_THINGS) logger(LOG_DEBUG, "Purging node %s (%s)", n->name,
83 for(snode = n->subnet_tree->head; snode; snode = snext) {
86 send_del_subnet(everyone, s);
91 for(enode = n->edge_tree->head; enode; enode = enext) {
95 send_del_edge(everyone, e);
101 /* Check if anyone else claims to have an edge to an unreachable node. If not, delete node. */
103 for(nnode = node_tree->head; nnode; nnode = nnext) {
107 if(!n->status.reachable) {
108 for(enode = edge_weight_tree->head; enode; enode = enext) {
116 if(!enode && (!strictsubnets || !n->subnet_tree->head))
117 /* in strictsubnets mode do not delete nodes with subnets */
124 put all file descriptors in an fd_set array
125 While we're at it, purge stuff that needs to be removed.
127 static int build_fdset(fd_set *readset, fd_set *writeset) {
128 avl_node_t *node, *next;
135 for(node = connection_tree->head; node; node = next) {
139 if(c->status.remove) {
141 if(!connection_tree->head)
144 FD_SET(c->socket, readset);
145 if(c->outbuflen > 0 || c->status.connecting)
146 FD_SET(c->socket, writeset);
152 for(i = 0; i < listen_sockets; i++) {
153 FD_SET(listen_socket[i].tcp, readset);
154 if(listen_socket[i].tcp > max)
155 max = listen_socket[i].tcp;
156 FD_SET(listen_socket[i].udp, readset);
157 if(listen_socket[i].udp > max)
158 max = listen_socket[i].udp;
162 FD_SET(device_fd, readset);
170 Terminate a connection:
172 - Remove associated edge and tell other connections about it if report = true
173 - Check if we need to retry making an outgoing connection
174 - Deactivate the host
176 void terminate_connection(connection_t *c, bool report) {
180 ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Closing connection with %s (%s)",
181 c->name, c->hostname);
183 c->status.remove = true;
184 c->status.active = false;
187 c->node->connection = NULL;
190 closesocket(c->socket);
194 logger(LOG_ERR, "Connection to %s (%s) has an edge but node is NULL!", c->name, c->hostname);
195 // And that should never happen.
199 if(report && !tunnelserver)
200 send_del_edge(everyone, c->edge);
204 /* Run MST and SSSP algorithms */
208 /* If the node is not reachable anymore but we remember it had an edge to us, clean it up */
210 if(report && !c->node->status.reachable) {
212 e = lookup_edge(c->node, myself);
215 send_del_edge(everyone, e);
221 free_connection_partially(c);
223 /* Check if this was our outgoing connection */
226 c->status.remove = false;
227 do_outgoing_connection(c);
231 /* Clean up dead proxy processes */
233 while(waitpid(-1, NULL, WNOHANG) > 0);
238 Check if the other end is active.
239 If we have sent packets, but didn't receive any,
240 then possibly the other end is dead. We send a
241 PING request over the meta connection. If the other
242 end does not reply in time, we consider them dead
243 and close the connection.
245 static void check_dead_connections(void) {
246 avl_node_t *node, *next;
249 for(node = connection_tree->head; node; node = next) {
253 if(c->last_ping_time + pingtimeout <= now) {
254 if(c->status.active) {
255 if(c->status.pinged) {
256 ifdebug(CONNECTIONS) logger(LOG_INFO, "%s (%s) didn't respond to PING in %ld seconds",
257 c->name, c->hostname, (long)now - c->last_ping_time);
258 c->status.timeout = true;
259 terminate_connection(c, true);
260 } else if(c->last_ping_time + pinginterval <= now) {
264 if(c->status.remove) {
265 logger(LOG_WARNING, "Old connection_t for %s (%s) status %04x still lingering, deleting...",
266 c->name, c->hostname, bitfield_to_int(&c->status, sizeof c->status));
270 ifdebug(CONNECTIONS) logger(LOG_WARNING, "Timeout from %s (%s) during authentication",
271 c->name, c->hostname);
272 if(c->status.connecting) {
273 c->status.connecting = false;
274 closesocket(c->socket);
275 do_outgoing_connection(c);
277 terminate_connection(c, false);
282 if(c->outbuflen > 0 && c->last_flushed_time + pingtimeout <= now) {
283 if(c->status.active) {
284 ifdebug(CONNECTIONS) logger(LOG_INFO,
285 "%s (%s) could not flush for %ld seconds (%d bytes remaining)",
286 c->name, c->hostname, (long)now - c->last_flushed_time, c->outbuflen);
287 c->status.timeout = true;
288 terminate_connection(c, true);
295 check all connections to see if anything
296 happened on their sockets
298 static void check_network_activity(fd_set * readset, fd_set * writeset) {
302 socklen_t len = sizeof(result);
304 static int errors = 0;
306 /* check input from kernel */
307 if(device_fd >= 0 && FD_ISSET(device_fd, readset)) {
308 if(devops.read(&packet)) {
312 route(myself, &packet);
315 usleep(errors * 50000);
318 logger(LOG_ERR, "Too many errors from %s, exiting!", device);
324 /* check meta connections */
325 for(node = connection_tree->head; node; node = node->next) {
331 if(FD_ISSET(c->socket, writeset)) {
332 if(c->status.connecting) {
333 c->status.connecting = false;
334 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&result, &len);
337 finish_connecting(c);
339 ifdebug(CONNECTIONS) logger(LOG_DEBUG,
340 "Error while connecting to %s (%s): %s",
341 c->name, c->hostname, sockstrerror(result));
342 closesocket(c->socket);
343 do_outgoing_connection(c);
349 terminate_connection(c, c->status.active);
354 if(FD_ISSET(c->socket, readset)) {
355 if(!receive_meta(c)) {
356 terminate_connection(c, c->status.active);
362 for(i = 0; i < listen_sockets; i++) {
363 if(FD_ISSET(listen_socket[i].udp, readset))
364 handle_incoming_vpn_data(i);
366 if(FD_ISSET(listen_socket[i].tcp, readset))
367 handle_new_meta_connection(listen_socket[i].tcp);
372 this is where it all happens...
374 int main_loop(void) {
375 fd_set readset, writeset;
378 sigset_t omask, block_mask;
384 time_t last_ping_check, last_config_check, last_graph_dump;
387 last_ping_check = now;
388 last_config_check = now;
389 last_graph_dump = now;
394 if(lookup_config(config_tree, "GraphDumpFile"))
396 /* Block SIGHUP & SIGALRM */
397 sigemptyset(&block_mask);
398 sigaddset(&block_mask, SIGHUP);
399 sigaddset(&block_mask, SIGALRM);
400 sigprocmask(SIG_BLOCK, &block_mask, &omask);
407 next_event = last_ping_check + pingtimeout;
408 if(graph_dump && next_event > last_graph_dump + 60)
409 next_event = last_graph_dump + 60;
411 if((event = peek_next_event()) && next_event > event->time)
412 next_event = event->time;
414 if(next_event <= now)
417 tv.tv_sec = next_event - now;
424 maxfd = build_fdset(&readset, &writeset);
427 LeaveCriticalSection(&mutex);
430 r = pselect(maxfd + 1, &readset, &writeset, NULL, &tv, &omask);
432 r = select(maxfd + 1, &readset, &writeset, NULL, &tv);
436 EnterCriticalSection(&mutex);
440 if(!sockwouldblock(sockerrno)) {
441 logger(LOG_ERR, "Error while waiting for input: %s", sockstrerror(sockerrno));
448 check_network_activity(&readset, &writeset);
455 /* Let's check if everybody is still alive */
457 if(last_ping_check + pingtimeout <= now) {
458 check_dead_connections();
459 last_ping_check = now;
461 if(routing_mode == RMODE_SWITCH)
466 /* Should we regenerate our key? */
468 if(keyexpires <= now) {
472 ifdebug(STATUS) logger(LOG_INFO, "Expiring symmetric keys");
474 for(node = node_tree->head; node; node = node->next) {
483 keyexpires = now + keylifetime;
486 /* Detect ADD_EDGE/DEL_EDGE storms that are caused when
487 * two tinc daemons with the same name are on the VPN.
488 * If so, sleep a while. If this happens multiple times
489 * in a row, sleep longer. */
491 if(contradicting_del_edge > 100 && contradicting_add_edge > 100) {
492 logger(LOG_WARNING, "Possible node with same Name as us! Sleeping %d seconds.", sleeptime);
493 usleep(sleeptime * 1000000LL);
503 contradicting_add_edge = 0;
504 contradicting_del_edge = 0;
509 logger(LOG_INFO, "Flushing event queue");
511 #if HAVE_DECL_RES_INIT
514 for(node = connection_tree->head; node; node = node->next) {
515 connection_t *c = node->data;
522 while((event = get_expired_event())) {
523 event->handler(event->data);
529 avl_node_t *node, *next;
537 /* Reread our own configuration file */
539 exit_configuration(&config_tree);
540 init_configuration(&config_tree);
542 if(!read_server_config()) {
543 logger(LOG_ERR, "Unable to reread configuration file, exitting.");
547 /* Cancel non-active outgoing connections */
549 for(node = connection_tree->head; node; node = next) {
555 if(c->status.connecting) {
556 terminate_connection(c, false);
561 /* Wipe list of outgoing connections */
563 for(list_node_t *node = outgoing_list->head; node; node = node->next) {
564 outgoing_t *outgoing = node->data;
567 event_del(outgoing->event);
570 list_delete_list(outgoing_list);
572 /* Close connections to hosts that have a changed or deleted host config file */
574 for(node = connection_tree->head; node; node = node->next) {
577 xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
578 if(stat(fname, &s) || s.st_mtime > last_config_check)
579 terminate_connection(c, c->status.active);
583 last_config_check = now;
585 /* If StrictSubnet is set, expire deleted Subnets and read new ones in */
590 for(node = subnet_tree->head; node; node = node->next) {
597 for(node = subnet_tree->head; node; node = next) {
600 if(subnet->expires == 1) {
601 send_del_subnet(everyone, subnet);
602 if(subnet->owner->status.reachable)
603 subnet_update(subnet->owner, subnet, false);
604 subnet_del(subnet->owner, subnet);
605 } else if(subnet->expires == -1) {
608 send_add_subnet(everyone, subnet);
609 if(subnet->owner->status.reachable)
610 subnet_update(subnet->owner, subnet, true);
615 /* Try to make outgoing connections */
617 try_outgoing_connections();
620 /* Dump graph if wanted every 60 seconds*/
622 if(last_graph_dump + 60 <= now) {
624 last_graph_dump = now;
629 /* Restore SIGHUP & SIGALARM mask */
630 sigprocmask(SIG_SETMASK, &omask, NULL);