2 net.c -- most of the network code
3 Copyright (C) 1998-2005 Ivo Timmermans,
4 2000-2011 Guus Sliepen <guus@tinc-vpn.org>
5 2006 Scott Lamb <slamb@slamb.org>
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License along
18 with this program; if not, write to the Free Software Foundation, Inc.,
19 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 #include <openssl/rand.h>
29 #include "connection.h"
43 bool do_purge = false;
44 volatile bool running = false;
46 bool graph_dump = false;
50 int contradicting_add_edge = 0;
51 int contradicting_del_edge = 0;
53 /* Purge edges and subnets of unreachable nodes. Use carefully. */
55 static void purge(void) {
56 avl_node_t *nnode, *nnext, *enode, *enext, *snode, *snext;
61 ifdebug(PROTOCOL) logger(LOG_DEBUG, "Purging unreachable nodes");
63 /* Remove all edges and subnets owned by unreachable nodes. */
65 for(nnode = node_tree->head; nnode; nnode = nnext) {
69 if(!n->status.reachable) {
70 ifdebug(SCARY_THINGS) logger(LOG_DEBUG, "Purging node %s (%s)", n->name,
73 for(snode = n->subnet_tree->head; snode; snode = snext) {
76 send_del_subnet(broadcast, s);
81 for(enode = n->edge_tree->head; enode; enode = enext) {
85 send_del_edge(broadcast, e);
91 /* Check if anyone else claims to have an edge to an unreachable node. If not, delete node. */
93 for(nnode = node_tree->head; nnode; nnode = nnext) {
97 if(!n->status.reachable) {
98 for(enode = edge_weight_tree->head; enode; enode = enext) {
106 if(!enode && (!strictsubnets || !n->subnet_tree->head))
107 /* in strictsubnets mode do not delete nodes with subnets */
114 put all file descriptors in an fd_set array
115 While we're at it, purge stuff that needs to be removed.
117 static int build_fdset(fd_set *readset, fd_set *writeset) {
118 avl_node_t *node, *next;
125 for(node = connection_tree->head; node; node = next) {
129 if(c->status.remove) {
131 if(!connection_tree->head)
134 FD_SET(c->socket, readset);
136 FD_SET(c->socket, writeset);
142 for(i = 0; i < listen_sockets; i++) {
143 FD_SET(listen_socket[i].tcp, readset);
144 if(listen_socket[i].tcp > max)
145 max = listen_socket[i].tcp;
146 FD_SET(listen_socket[i].udp, readset);
147 if(listen_socket[i].udp > max)
148 max = listen_socket[i].udp;
152 FD_SET(device_fd, readset);
160 Terminate a connection:
162 - Remove associated edge and tell other connections about it if report = true
163 - Check if we need to retry making an outgoing connection
164 - Deactivate the host
166 void terminate_connection(connection_t *c, bool report) {
170 ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Closing connection with %s (%s)",
171 c->name, c->hostname);
173 c->status.remove = true;
174 c->status.active = false;
177 c->node->connection = NULL;
180 closesocket(c->socket);
183 if(report && !tunnelserver)
184 send_del_edge(broadcast, c->edge);
188 /* Run MST and SSSP algorithms */
192 /* If the node is not reachable anymore but we remember it had an edge to us, clean it up */
194 if(report && !c->node->status.reachable) {
196 e = lookup_edge(c->node, myself);
199 send_del_edge(broadcast, e);
205 /* Check if this was our outgoing connection */
208 retry_outgoing(c->outgoing);
220 Check if the other end is active.
221 If we have sent packets, but didn't receive any,
222 then possibly the other end is dead. We send a
223 PING request over the meta connection. If the other
224 end does not reply in time, we consider them dead
225 and close the connection.
227 static void check_dead_connections(void) {
228 avl_node_t *node, *next;
231 for(node = connection_tree->head; node; node = next) {
235 if(c->last_ping_time + pingtimeout <= now) {
236 if(c->status.active) {
237 if(c->status.pinged) {
238 ifdebug(CONNECTIONS) logger(LOG_INFO, "%s (%s) didn't respond to PING in %ld seconds",
239 c->name, c->hostname, now - c->last_ping_time);
240 c->status.timeout = true;
241 terminate_connection(c, true);
242 } else if(c->last_ping_time + pinginterval <= now) {
246 if(c->status.remove) {
247 logger(LOG_WARNING, "Old connection_t for %s (%s) status %04x still lingering, deleting...",
248 c->name, c->hostname, bitfield_to_int(&c->status, sizeof c->status));
252 ifdebug(CONNECTIONS) logger(LOG_WARNING, "Timeout from %s (%s) during authentication",
253 c->name, c->hostname);
254 if(c->status.connecting) {
255 c->status.connecting = false;
256 closesocket(c->socket);
257 do_outgoing_connection(c);
259 terminate_connection(c, false);
264 if(c->outbuflen > 0 && c->last_flushed_time + pingtimeout <= now) {
265 if(c->status.active) {
266 ifdebug(CONNECTIONS) logger(LOG_INFO,
267 "%s (%s) could not flush for %ld seconds (%d bytes remaining)",
268 c->name, c->hostname, now - c->last_flushed_time, c->outbuflen);
269 c->status.timeout = true;
270 terminate_connection(c, true);
277 check all connections to see if anything
278 happened on their sockets
280 static void check_network_activity(fd_set * readset, fd_set * writeset) {
284 socklen_t len = sizeof(result);
286 static int errors = 0;
288 /* check input from kernel */
289 if(device_fd >= 0 && FD_ISSET(device_fd, readset)) {
290 if(read_packet(&packet)) {
293 route(myself, &packet);
295 usleep(errors * 50000);
298 logger(LOG_ERR, "Too many errors from %s, exiting!", device);
304 /* check meta connections */
305 for(node = connection_tree->head; node; node = node->next) {
311 if(FD_ISSET(c->socket, readset)) {
312 if(c->status.connecting) {
313 c->status.connecting = false;
314 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&result, &len);
317 finish_connecting(c);
319 ifdebug(CONNECTIONS) logger(LOG_DEBUG,
320 "Error while connecting to %s (%s): %s",
321 c->name, c->hostname, sockstrerror(result));
322 closesocket(c->socket);
323 do_outgoing_connection(c);
328 if(!receive_meta(c)) {
329 terminate_connection(c, c->status.active);
334 if(FD_ISSET(c->socket, writeset)) {
336 terminate_connection(c, c->status.active);
342 for(i = 0; i < listen_sockets; i++) {
343 if(FD_ISSET(listen_socket[i].udp, readset))
344 handle_incoming_vpn_data(listen_socket[i].udp);
346 if(FD_ISSET(listen_socket[i].tcp, readset))
347 handle_new_meta_connection(listen_socket[i].tcp);
352 this is where it all happens...
354 int main_loop(void) {
355 fd_set readset, writeset;
358 sigset_t omask, block_mask;
364 time_t last_ping_check, last_config_check, last_graph_dump;
367 last_ping_check = now;
368 last_config_check = now;
369 last_graph_dump = now;
374 if(lookup_config(config_tree, "GraphDumpFile"))
376 /* Block SIGHUP & SIGALRM */
377 sigemptyset(&block_mask);
378 sigaddset(&block_mask, SIGHUP);
379 sigaddset(&block_mask, SIGALRM);
380 sigprocmask(SIG_BLOCK, &block_mask, &omask);
387 next_event = last_ping_check + pingtimeout;
388 if(graph_dump && next_event > last_graph_dump + 60)
389 next_event = last_graph_dump + 60;
391 if((event = peek_next_event()) && next_event > event->time)
392 next_event = event->time;
394 if(next_event <= now)
397 tv.tv_sec = next_event - now;
404 maxfd = build_fdset(&readset, &writeset);
407 LeaveCriticalSection(&mutex);
410 r = pselect(maxfd + 1, &readset, &writeset, NULL, &tv, &omask);
412 r = select(maxfd + 1, &readset, &writeset, NULL, &tv);
416 EnterCriticalSection(&mutex);
420 if(!sockwouldblock(sockerrno)) {
421 logger(LOG_ERR, "Error while waiting for input: %s", sockstrerror(sockerrno));
428 check_network_activity(&readset, &writeset);
435 /* Let's check if everybody is still alive */
437 if(last_ping_check + pingtimeout <= now) {
438 check_dead_connections();
439 last_ping_check = now;
441 if(routing_mode == RMODE_SWITCH)
446 /* Should we regenerate our key? */
448 if(keyexpires <= now) {
452 ifdebug(STATUS) logger(LOG_INFO, "Expiring symmetric keys");
454 for(node = node_tree->head; node; node = node->next) {
463 keyexpires = now + keylifetime;
466 if(contradicting_del_edge > 10 && contradicting_add_edge > 10) {
467 logger(LOG_WARNING, "Possible node with same Name as us!");
469 if(rand() % 3 == 0) {
470 logger(LOG_ERR, "Shutting down, check configuration of all nodes for duplicate Names!");
475 contradicting_add_edge = 0;
476 contradicting_del_edge = 0;
482 logger(LOG_INFO, "Flushing event queue");
484 for(node = connection_tree->head; node; node = node->next) {
485 connection_t *c = node->data;
491 while((event = get_expired_event())) {
492 event->handler(event->data);
498 avl_node_t *node, *next;
504 /* Reread our own configuration file */
506 exit_configuration(&config_tree);
507 init_configuration(&config_tree);
509 if(!read_server_config()) {
510 logger(LOG_ERR, "Unable to reread configuration file, exitting.");
514 /* Cancel non-active outgoing connections */
516 for(node = connection_tree->head; node; node = next) {
522 if(c->status.connecting) {
523 terminate_connection(c, false);
528 /* Wipe list of outgoing connections */
530 for(list_node_t *node = outgoing_list->head; node; node = node->next) {
531 outgoing_t *outgoing = node->data;
534 event_del(outgoing->event);
537 list_delete_list(outgoing_list);
539 /* Close connections to hosts that have a changed or deleted host config file */
541 for(node = connection_tree->head; node; node = node->next) {
544 xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
545 if(stat(fname, &s) || s.st_mtime > last_config_check)
546 terminate_connection(c, c->status.active);
550 last_config_check = now;
552 /* If StrictSubnet is set, expire deleted Subnets and read new ones in */
557 for(node = subnet_tree->head; node; node = node->next) {
564 for(node = subnet_tree->head; node; node = next) {
567 if(subnet->expires == 1) {
568 send_del_subnet(broadcast, subnet);
569 if(subnet->owner->status.reachable)
570 subnet_update(subnet->owner, subnet, false);
571 subnet_del(subnet->owner, subnet);
572 } else if(subnet->expires == -1) {
575 send_add_subnet(broadcast, subnet);
576 if(subnet->owner->status.reachable)
577 subnet_update(subnet->owner, subnet, true);
582 /* Try to make outgoing connections */
584 try_outgoing_connections();
587 /* Dump graph if wanted every 60 seconds*/
589 if(last_graph_dump + 60 <= now) {
591 last_graph_dump = now;
596 /* Restore SIGHUP & SIGALARM mask */
597 sigprocmask(SIG_SETMASK, &omask, NULL);