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>
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 bool do_purge = false;
45 volatile bool running = false;
47 bool graph_dump = false;
51 int contradicting_add_edge = 0;
52 int contradicting_del_edge = 0;
54 /* Purge edges and subnets of unreachable nodes. Use carefully. */
56 static void purge(void) {
57 avl_node_t *nnode, *nnext, *enode, *enext, *snode, *snext;
62 ifdebug(PROTOCOL) logger(LOG_DEBUG, "Purging unreachable nodes");
64 /* Remove all edges and subnets owned by unreachable nodes. */
66 for(nnode = node_tree->head; nnode; nnode = nnext) {
70 if(!n->status.reachable) {
71 ifdebug(SCARY_THINGS) logger(LOG_DEBUG, "Purging node %s (%s)", n->name,
74 for(snode = n->subnet_tree->head; snode; snode = snext) {
77 send_del_subnet(broadcast, s);
82 for(enode = n->edge_tree->head; enode; enode = enext) {
86 send_del_edge(broadcast, e);
92 /* Check if anyone else claims to have an edge to an unreachable node. If not, delete node. */
94 for(nnode = node_tree->head; nnode; nnode = nnext) {
98 if(!n->status.reachable) {
99 for(enode = edge_weight_tree->head; enode; enode = enext) {
107 if(!enode && (!strictsubnets || !n->subnet_tree->head))
108 /* in strictsubnets mode do not delete nodes with subnets */
115 put all file descriptors in an fd_set array
116 While we're at it, purge stuff that needs to be removed.
118 static int build_fdset(fd_set *readset, fd_set *writeset) {
119 avl_node_t *node, *next;
126 for(node = connection_tree->head; node; node = next) {
130 if(c->status.remove) {
132 if(!connection_tree->head)
135 FD_SET(c->socket, readset);
137 FD_SET(c->socket, writeset);
143 for(i = 0; i < listen_sockets; i++) {
144 FD_SET(listen_socket[i].tcp, readset);
145 if(listen_socket[i].tcp > max)
146 max = listen_socket[i].tcp;
147 FD_SET(listen_socket[i].udp, readset);
148 if(listen_socket[i].udp > max)
149 max = listen_socket[i].udp;
153 FD_SET(device_fd, readset);
161 Terminate a connection:
163 - Remove associated edge and tell other connections about it if report = true
164 - Check if we need to retry making an outgoing connection
165 - Deactivate the host
167 void terminate_connection(connection_t *c, bool report) {
171 ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Closing connection with %s (%s)",
172 c->name, c->hostname);
174 c->status.remove = true;
175 c->status.active = false;
178 c->node->connection = NULL;
181 closesocket(c->socket);
184 if(report && !tunnelserver)
185 send_del_edge(broadcast, c->edge);
189 /* Run MST and SSSP algorithms */
193 /* If the node is not reachable anymore but we remember it had an edge to us, clean it up */
195 if(report && !c->node->status.reachable) {
197 e = lookup_edge(c->node, myself);
200 send_del_edge(broadcast, e);
206 /* Check if this was our outgoing connection */
209 retry_outgoing(c->outgoing);
221 Check if the other end is active.
222 If we have sent packets, but didn't receive any,
223 then possibly the other end is dead. We send a
224 PING request over the meta connection. If the other
225 end does not reply in time, we consider them dead
226 and close the connection.
228 static void check_dead_connections(void) {
229 avl_node_t *node, *next;
232 for(node = connection_tree->head; node; node = next) {
236 if(c->last_ping_time + pingtimeout <= now) {
237 if(c->status.active) {
238 if(c->status.pinged) {
239 ifdebug(CONNECTIONS) logger(LOG_INFO, "%s (%s) didn't respond to PING in %ld seconds",
240 c->name, c->hostname, now - c->last_ping_time);
241 c->status.timeout = true;
242 terminate_connection(c, true);
243 } else if(c->last_ping_time + pinginterval <= now) {
247 if(c->status.remove) {
248 logger(LOG_WARNING, "Old connection_t for %s (%s) status %04x still lingering, deleting...",
249 c->name, c->hostname, bitfield_to_int(&c->status, sizeof c->status));
253 ifdebug(CONNECTIONS) logger(LOG_WARNING, "Timeout from %s (%s) during authentication",
254 c->name, c->hostname);
255 if(c->status.connecting) {
256 c->status.connecting = false;
257 closesocket(c->socket);
258 do_outgoing_connection(c);
260 terminate_connection(c, false);
265 if(c->outbuflen > 0 && c->last_flushed_time + pingtimeout <= now) {
266 if(c->status.active) {
267 ifdebug(CONNECTIONS) logger(LOG_INFO,
268 "%s (%s) could not flush for %ld seconds (%d bytes remaining)",
269 c->name, c->hostname, now - c->last_flushed_time, c->outbuflen);
270 c->status.timeout = true;
271 terminate_connection(c, true);
278 check all connections to see if anything
279 happened on their sockets
281 static void check_network_activity(fd_set * readset, fd_set * writeset) {
285 socklen_t len = sizeof(result);
287 static int errors = 0;
289 /* check input from kernel */
290 if(device_fd >= 0 && FD_ISSET(device_fd, readset)) {
291 if(read_packet(&packet)) {
294 route(myself, &packet);
296 usleep(errors * 50000);
299 logger(LOG_ERR, "Too many errors from %s, exiting!", device);
305 /* check meta connections */
306 for(node = connection_tree->head; node; node = node->next) {
312 if(FD_ISSET(c->socket, readset)) {
313 if(c->status.connecting) {
314 c->status.connecting = false;
315 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&result, &len);
318 finish_connecting(c);
320 ifdebug(CONNECTIONS) logger(LOG_DEBUG,
321 "Error while connecting to %s (%s): %s",
322 c->name, c->hostname, sockstrerror(result));
323 closesocket(c->socket);
324 do_outgoing_connection(c);
329 if(!receive_meta(c)) {
330 terminate_connection(c, c->status.active);
335 if(FD_ISSET(c->socket, writeset)) {
337 terminate_connection(c, c->status.active);
343 for(i = 0; i < listen_sockets; i++) {
344 if(FD_ISSET(listen_socket[i].udp, readset))
345 handle_incoming_vpn_data(listen_socket[i].udp);
347 if(FD_ISSET(listen_socket[i].tcp, readset))
348 handle_new_meta_connection(listen_socket[i].tcp);
353 this is where it all happens...
355 int main_loop(void) {
356 fd_set readset, writeset;
359 sigset_t omask, block_mask;
365 time_t last_ping_check, last_config_check, last_graph_dump;
368 last_ping_check = now;
369 last_config_check = now;
370 last_graph_dump = now;
375 if(lookup_config(config_tree, "GraphDumpFile"))
377 /* Block SIGHUP & SIGALRM */
378 sigemptyset(&block_mask);
379 sigaddset(&block_mask, SIGHUP);
380 sigaddset(&block_mask, SIGALRM);
381 sigprocmask(SIG_BLOCK, &block_mask, &omask);
388 next_event = last_ping_check + pingtimeout;
389 if(graph_dump && next_event > last_graph_dump + 60)
390 next_event = last_graph_dump + 60;
392 if((event = peek_next_event()) && next_event > event->time)
393 next_event = event->time;
395 if(next_event <= now)
398 tv.tv_sec = next_event - now;
405 maxfd = build_fdset(&readset, &writeset);
408 LeaveCriticalSection(&mutex);
411 r = pselect(maxfd + 1, &readset, &writeset, NULL, &tv, &omask);
413 r = select(maxfd + 1, &readset, &writeset, NULL, &tv);
417 EnterCriticalSection(&mutex);
421 if(!sockwouldblock(sockerrno)) {
422 logger(LOG_ERR, "Error while waiting for input: %s", sockstrerror(sockerrno));
429 check_network_activity(&readset, &writeset);
436 /* Let's check if everybody is still alive */
438 if(last_ping_check + pingtimeout <= now) {
439 check_dead_connections();
440 last_ping_check = now;
442 if(routing_mode == RMODE_SWITCH)
447 /* Should we regenerate our key? */
449 if(keyexpires <= now) {
453 ifdebug(STATUS) logger(LOG_INFO, "Expiring symmetric keys");
455 for(node = node_tree->head; node; node = node->next) {
464 keyexpires = now + keylifetime;
467 if(contradicting_del_edge > 10 && contradicting_add_edge > 10) {
468 logger(LOG_WARNING, "Possible node with same Name as us!");
470 if(rand() % 3 == 0) {
471 logger(LOG_ERR, "Shutting down, check configuration of all nodes for duplicate Names!");
476 contradicting_add_edge = 0;
477 contradicting_del_edge = 0;
483 logger(LOG_INFO, "Flushing event queue");
485 for(node = connection_tree->head; node; node = node->next) {
486 connection_t *c = node->data;
492 while((event = get_expired_event())) {
493 event->handler(event->data);
499 avl_node_t *node, *next;
505 /* Reread our own configuration file */
507 exit_configuration(&config_tree);
508 init_configuration(&config_tree);
510 if(!read_server_config()) {
511 logger(LOG_ERR, "Unable to reread configuration file, exitting.");
515 /* Cancel non-active outgoing connections */
517 for(node = connection_tree->head; node; node = next) {
523 if(c->status.connecting) {
524 terminate_connection(c, false);
529 /* Wipe list of outgoing connections */
531 for(list_node_t *node = outgoing_list->head; node; node = node->next) {
532 outgoing_t *outgoing = node->data;
535 event_del(outgoing->event);
538 list_delete_list(outgoing_list);
540 /* Close connections to hosts that have a changed or deleted host config file */
542 for(node = connection_tree->head; node; node = node->next) {
545 xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
546 if(stat(fname, &s) || s.st_mtime > last_config_check)
547 terminate_connection(c, c->status.active);
551 last_config_check = now;
553 /* If StrictSubnet is set, expire deleted Subnets and read new ones in */
558 for(node = subnet_tree->head; node; node = node->next) {
565 for(node = subnet_tree->head; node; node = next) {
568 if(subnet->expires == 1) {
569 send_del_subnet(broadcast, subnet);
570 if(subnet->owner->status.reachable)
571 subnet_update(subnet->owner, subnet, false);
572 subnet_del(subnet->owner, subnet);
573 } else if(subnet->expires == -1) {
576 send_add_subnet(broadcast, subnet);
577 if(subnet->owner->status.reachable)
578 subnet_update(subnet->owner, subnet, true);
583 /* Try to make outgoing connections */
585 try_outgoing_connections();
588 /* Dump graph if wanted every 60 seconds*/
590 if(last_graph_dump + 60 <= now) {
592 last_graph_dump = now;
597 /* Restore SIGHUP & SIGALARM mask */
598 sigprocmask(SIG_SETMASK, &omask, NULL);