2 net.c -- most of the network code
3 Copyright (C) 1998-2002 Ivo Timmermans <itimmermans@bigfoot.com>,
4 2000-2002 Guus Sliepen <guus@sliepen.warande.net>
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 $Id: net.c,v 1.35.4.155 2002/02/12 14:36:45 guus Exp $
28 #include <netinet/in.h>
30 #include <netinet/ip.h>
31 #include <netinet/tcp.h>
38 #include <sys/types.h>
41 #include <sys/ioctl.h>
42 /* SunOS really wants sys/socket.h BEFORE net/if.h,
43 and FreeBSD wants these lines below the rest. */
44 #include <arpa/inet.h>
45 #include <sys/socket.h>
48 #include <openssl/rand.h>
49 #include <openssl/evp.h>
50 #include <openssl/pem.h>
51 #include <openssl/hmac.h>
53 #ifndef HAVE_RAND_PSEUDO_BYTES
54 #define RAND_pseudo_bytes RAND_bytes
65 #include "connection.h"
81 int seconds_till_retry = 5;
94 #define MAX_SEQNO 1073741824
98 void receive_udppacket(node_t *n, vpn_packet_t *inpkt)
100 vpn_packet_t pkt1, pkt2;
101 vpn_packet_t *pkt[] = {&pkt1, &pkt2, &pkt1, &pkt2};
103 vpn_packet_t *outpkt = pkt[0];
105 long int complen = MTU + 12;
107 char hmac[EVP_MAX_MD_SIZE];
109 /* Check the message authentication code */
111 if(myself->digest && myself->maclength)
113 inpkt->len -= myself->maclength;
114 HMAC(myself->digest, myself->key, myself->keylength, (char *)&inpkt->seqno, inpkt->len, hmac, NULL);
115 if(memcmp(hmac, (char *)&inpkt->seqno + inpkt->len, myself->maclength))
117 syslog(LOG_DEBUG, _("Got unauthenticated packet from %s (%s)"), n->name, n->hostname);
122 /* Decrypt the packet */
126 outpkt = pkt[nextpkt++];
128 EVP_DecryptInit(&ctx, myself->cipher, myself->key, myself->key + myself->cipher->key_len);
129 EVP_DecryptUpdate(&ctx, (char *)&outpkt->seqno, &outlen, (char *)&inpkt->seqno, inpkt->len);
130 EVP_DecryptFinal(&ctx, (char *)&outpkt->seqno + outlen, &outpad);
132 outpkt->len = outlen + outpad;
136 /* Check the sequence number */
138 inpkt->len -= sizeof(inpkt->seqno);
139 inpkt->seqno = ntohl(inpkt->seqno);
141 if(inpkt->seqno <= n->received_seqno)
143 syslog(LOG_DEBUG, _("Got late or replayed packet from %s (%s), seqno %d"), n->name, n->hostname, inpkt->seqno);
147 n->received_seqno = inpkt->seqno;
149 if(n->received_seqno > MAX_SEQNO)
152 /* Decompress the packet */
154 if(myself->compression)
156 outpkt = pkt[nextpkt++];
158 if(uncompress(outpkt->data, &complen, inpkt->data, inpkt->len) != Z_OK)
160 syslog(LOG_ERR, _("Error while uncompressing packet from %s (%s)"), n->name, n->hostname);
164 outpkt->len = complen;
168 receive_packet(n, inpkt);
172 void receive_tcppacket(connection_t *c, char *buffer, int len)
177 memcpy(outpkt.data, buffer, len);
179 receive_packet(c->node, &outpkt);
183 void receive_packet(node_t *n, vpn_packet_t *packet)
186 if(debug_lvl >= DEBUG_TRAFFIC)
187 syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"), packet->len, n->name, n->hostname);
189 route_incoming(n, packet);
193 void send_udppacket(node_t *n, vpn_packet_t *inpkt)
195 vpn_packet_t pkt1, pkt2;
196 vpn_packet_t *pkt[] = {&pkt1, &pkt2, &pkt1, &pkt2};
198 vpn_packet_t *outpkt;
200 long int complen = MTU + 12;
202 struct sockaddr_in to;
203 socklen_t tolen = sizeof(to);
206 if(!n->status.validkey)
208 if(debug_lvl >= DEBUG_TRAFFIC)
209 syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
210 n->name, n->hostname);
212 /* Since packet is on the stack of handle_tap_input(),
213 we have to make a copy of it first. */
215 copy = xmalloc(sizeof(vpn_packet_t));
216 memcpy(copy, inpkt, sizeof(vpn_packet_t));
218 list_insert_tail(n->queue, copy);
220 if(!n->status.waitingforkey)
221 send_req_key(n->nexthop->connection, myself, n);
226 /* Compress the packet */
230 outpkt = pkt[nextpkt++];
232 if(compress2(outpkt->data, &complen, inpkt->data, inpkt->len, n->compression) != Z_OK)
234 syslog(LOG_ERR, _("Error while compressing packet to %s (%s)"), n->name, n->hostname);
238 outpkt->len = complen;
242 /* Add sequence number */
244 inpkt->seqno = htonl(++(n->sent_seqno));
245 inpkt->len += sizeof(inpkt->seqno);
247 /* Encrypt the packet */
251 outpkt = pkt[nextpkt++];
253 EVP_EncryptInit(&ctx, n->cipher, n->key, n->key + n->cipher->key_len);
254 EVP_EncryptUpdate(&ctx, (char *)&outpkt->seqno, &outlen, (char *)&inpkt->seqno, inpkt->len);
255 EVP_EncryptFinal(&ctx, (char *)&outpkt->seqno + outlen, &outpad);
257 outpkt->len = outlen + outpad;
261 /* Add the message authentication code */
263 if(n->digest && n->maclength)
265 HMAC(n->digest, n->key, n->keylength, (char *)&inpkt->seqno, inpkt->len, (char *)&inpkt->seqno + inpkt->len, &outlen);
266 inpkt->len += n->maclength;
269 /* Send the packet */
271 to.sin_family = AF_INET;
272 to.sin_addr.s_addr = htonl(n->address);
273 to.sin_port = htons(n->port);
275 if((sendto(udp_socket, (char *)&inpkt->seqno, inpkt->len, 0, (const struct sockaddr *)&to, tolen)) < 0)
277 syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
278 n->name, n->hostname);
285 send a packet to the given vpn ip.
287 void send_packet(node_t *n, vpn_packet_t *packet)
291 if(debug_lvl >= DEBUG_TRAFFIC)
292 syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
293 packet->len, n->name, n->hostname);
297 if(debug_lvl >= DEBUG_TRAFFIC)
299 syslog(LOG_NOTICE, _("Packet is looping back to us!"));
305 if(!n->status.reachable)
307 if(debug_lvl >= DEBUG_TRAFFIC)
308 syslog(LOG_INFO, _("Node %s (%s) is not reachable"),
309 n->name, n->hostname);
313 via = (n->via == myself)?n->nexthop:n->via;
315 if(via != n && debug_lvl >= DEBUG_TRAFFIC)
316 syslog(LOG_ERR, _("Sending packet to %s via %s (%s)"),
317 n->name, via->name, n->via->hostname);
319 if((myself->options | via->options) & OPTION_TCPONLY)
321 if(send_tcppacket(via->connection, packet))
322 terminate_connection(via->connection, 1);
325 send_udppacket(via, packet);
328 /* Broadcast a packet using the minimum spanning tree */
330 void broadcast_packet(node_t *from, vpn_packet_t *packet)
335 if(debug_lvl >= DEBUG_TRAFFIC)
336 syslog(LOG_INFO, _("Broadcasting packet of %d bytes from %s (%s)"),
337 packet->len, from->name, from->hostname);
339 for(node = connection_tree->head; node; node = node->next)
341 c = (connection_t *)node->data;
342 if(c->status.active && c->status.mst && c != from->nexthop->connection)
343 send_packet(c->node, packet);
348 void flush_queue(node_t *n)
350 list_node_t *node, *next;
352 if(debug_lvl >= DEBUG_TRAFFIC)
353 syslog(LOG_INFO, _("Flushing queue for %s (%s)"), n->name, n->hostname);
355 for(node = n->queue->head; node; node = next)
358 send_udppacket(n, (vpn_packet_t *)node->data);
359 list_delete_node(n->queue, node);
366 int setup_listen_socket(port_t port)
369 struct sockaddr_in a;
376 if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
378 syslog(LOG_ERR, _("Creating metasocket failed: %m"));
382 flags = fcntl(nfd, F_GETFL);
383 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
386 syslog(LOG_ERR, _("System call `%s' failed: %m"),
391 /* Optimize TCP settings */
394 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
395 setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
397 setsockopt(nfd, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
399 option = IPTOS_LOWDELAY;
400 setsockopt(nfd, SOL_IP, IP_TOS, &option, sizeof(option));
402 if(get_config_string(lookup_config(config_tree, "BindToInterface"), &interface))
403 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, interface, strlen(interface)))
406 syslog(LOG_ERR, _("Can't bind to interface %s: %m"), interface);
411 memset(&a, 0, sizeof(a));
412 a.sin_family = AF_INET;
413 a.sin_addr.s_addr = htonl(INADDR_ANY);
414 a.sin_port = htons(port);
416 if(get_config_address(lookup_config(config_tree, "BindToAddress"), &address))
418 a.sin_addr.s_addr = htonl(*address);
422 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
425 syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
432 syslog(LOG_ERR, _("System call `%s' failed: %m"),
440 int setup_vpn_in_socket(port_t port)
443 struct sockaddr_in a;
446 if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
449 syslog(LOG_ERR, _("Creating socket failed: %m"));
453 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
455 flags = fcntl(nfd, F_GETFL);
456 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
459 syslog(LOG_ERR, _("System call `%s' failed: %m"),
464 memset(&a, 0, sizeof(a));
465 a.sin_family = AF_INET;
466 a.sin_port = htons(port);
467 a.sin_addr.s_addr = htonl(INADDR_ANY);
469 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
472 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
479 void retry_outgoing(outgoing_t *outgoing)
483 outgoing->timeout += 5;
484 if(outgoing->timeout > maxtimeout)
485 outgoing->timeout = maxtimeout;
488 event->handler = (event_handler_t)setup_outgoing_connection;
489 event->time = time(NULL) + outgoing->timeout;
490 event->data = outgoing;
493 if(debug_lvl >= DEBUG_CONNECTIONS)
494 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), outgoing->timeout);
498 int setup_outgoing_socket(connection_t *c)
501 struct sockaddr_in a;
503 if(debug_lvl >= DEBUG_CONNECTIONS)
504 syslog(LOG_INFO, _("Trying to connect to %s (%s)"), c->name, c->hostname);
506 c->socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
510 syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
511 c->hostname, c->port);
515 /* Bind first to get a fix on our source port???
517 a.sin_family = AF_INET;
518 a.sin_port = htons(0);
519 a.sin_addr.s_addr = htonl(INADDR_ANY);
521 if(bind(c->socket, (struct sockaddr *)&a, sizeof(struct sockaddr)))
524 syslog(LOG_ERR, _("System call `%s' failed: %m"), "bind");
530 /* Optimize TCP settings?
533 setsockopt(c->socket, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
535 setsockopt(c->socket, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
537 option = IPTOS_LOWDELAY;
538 setsockopt(c->socket, SOL_IP, IP_TOS, &option, sizeof(option));
545 a.sin_family = AF_INET;
546 a.sin_port = htons(c->port);
547 a.sin_addr.s_addr = htonl(c->address);
549 if(connect(c->socket, (struct sockaddr *)&a, sizeof(a)) == -1)
552 syslog(LOG_ERR, _("%s port %hd: %m"), c->hostname, c->port);
556 flags = fcntl(c->socket, F_GETFL);
558 if(fcntl(c->socket, F_SETFL, flags | O_NONBLOCK) < 0)
561 syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
562 c->hostname, c->port);
566 if(debug_lvl >= DEBUG_CONNECTIONS)
567 syslog(LOG_INFO, _("Connected to %s port %hd"),
568 c->hostname, c->port);
573 void setup_outgoing_connection(outgoing_t *outgoing)
579 n = lookup_node(outgoing->name);
584 if(debug_lvl >= DEBUG_CONNECTIONS)
585 syslog(LOG_INFO, _("Already connected to %s"), outgoing->name);
586 n->connection->outgoing = outgoing;
590 c = new_connection();
591 c->name = xstrdup(outgoing->name);
593 init_configuration(&c->config_tree);
594 read_connection_config(c);
596 if(!get_config_string(lookup_config(c->config_tree, "Address"), &c->hostname))
598 syslog(LOG_ERR, _("No address specified for %s"), c->name);
600 free(outgoing->name);
605 if(!get_config_port(lookup_config(c->config_tree, "Port"), &c->port))
608 if(!(h = gethostbyname(c->hostname)))
610 syslog(LOG_ERR, _("Error looking up `%s': %m"), c->hostname);
612 retry_outgoing(outgoing);
616 c->address = ntohl(*((ipv4_t*)(h->h_addr_list[0])));
617 c->hostname = hostlookup(htonl(c->address));
619 if(setup_outgoing_socket(c) < 0)
621 syslog(LOG_ERR, _("Could not set up a meta connection to %s (%s)"),
622 c->name, c->hostname);
623 retry_outgoing(outgoing);
627 c->outgoing = outgoing;
628 c->last_ping_time = time(NULL);
636 int read_rsa_public_key(connection_t *c)
643 c->rsa_key = RSA_new();
645 /* First, check for simple PublicKey statement */
647 if(get_config_string(lookup_config(c->config_tree, "PublicKey"), &key))
649 BN_hex2bn(&c->rsa_key->n, key);
650 BN_hex2bn(&c->rsa_key->e, "FFFF");
655 /* Else, check for PublicKeyFile statement and read it */
657 if(get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &fname))
659 if(is_safe_path(fname))
661 if((fp = fopen(fname, "r")) == NULL)
663 syslog(LOG_ERR, _("Error reading RSA public key file `%s': %m"),
669 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
673 syslog(LOG_ERR, _("Reading RSA public key file `%s' failed: %m"),
686 /* Else, check if a harnessed public key is in the config file */
688 asprintf(&fname, "%s/hosts/%s", confbase, c->name);
689 if((fp = fopen(fname, "r")))
691 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
701 syslog(LOG_ERR, _("No public key for %s specified!"), c->name);
706 int read_rsa_private_key(void)
711 if(get_config_string(lookup_config(config_tree, "PrivateKey"), &key))
713 myself->connection->rsa_key = RSA_new();
714 BN_hex2bn(&myself->connection->rsa_key->d, key);
715 BN_hex2bn(&myself->connection->rsa_key->e, "FFFF");
720 if(!get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname))
721 asprintf(&fname, "%s/rsa_key.priv", confbase);
723 if(is_safe_path(fname))
725 if((fp = fopen(fname, "r")) == NULL)
727 syslog(LOG_ERR, _("Error reading RSA private key file `%s': %m"),
733 myself->connection->rsa_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
735 if(!myself->connection->rsa_key)
737 syslog(LOG_ERR, _("Reading RSA private key file `%s' failed: %m"),
748 int check_rsa_key(RSA *rsa_key)
750 char *test1, *test2, *test3;
752 if(rsa_key->p && rsa_key->q)
754 if(RSA_check_key(rsa_key) != 1)
759 test1 = xmalloc(RSA_size(rsa_key));
760 test2 = xmalloc(RSA_size(rsa_key));
761 test3 = xmalloc(RSA_size(rsa_key));
763 if(RSA_public_encrypt(RSA_size(rsa_key), test1, test2, rsa_key, RSA_NO_PADDING) != RSA_size(rsa_key))
766 if(RSA_private_decrypt(RSA_size(rsa_key), test2, test3, rsa_key, RSA_NO_PADDING) != RSA_size(rsa_key))
769 if(memcmp(test1, test3, RSA_size(rsa_key)))
777 Configure node_t myself and set up the local sockets (listen only)
779 int setup_myself(void)
783 char *name, *mode, *cipher, *digest;
787 myself->connection = new_connection();
788 init_configuration(&myself->connection->config_tree);
790 asprintf(&myself->hostname, _("MYSELF"));
791 asprintf(&myself->connection->hostname, _("MYSELF"));
793 myself->connection->options = 0;
794 myself->connection->protocol_version = PROT_CURRENT;
796 if(!get_config_string(lookup_config(config_tree, "Name"), &name)) /* Not acceptable */
798 syslog(LOG_ERR, _("Name for tinc daemon required!"));
804 syslog(LOG_ERR, _("Invalid name for myself!"));
810 myself->connection->name = xstrdup(name);
813 if(read_rsa_private_key())
816 if(read_connection_config(myself->connection))
818 syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
822 if(read_rsa_public_key(myself->connection))
826 if(check_rsa_key(myself->connection->rsa_key))
828 syslog(LOG_ERR, _("Invalid public/private keypair!"));
832 if(!get_config_port(lookup_config(myself->connection->config_tree, "Port"), &myself->port))
835 myself->connection->port = myself->port;
837 /* Read in all the subnets specified in the host configuration file */
839 cfg = lookup_config(myself->connection->config_tree, "Subnet");
843 if(!get_config_subnet(cfg, &subnet))
846 subnet_add(myself, subnet);
848 cfg = lookup_config_next(myself->connection->config_tree, cfg);
852 /* Check some options */
854 if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice))
856 myself->options |= OPTION_INDIRECT;
858 if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice))
860 myself->options |= OPTION_TCPONLY;
862 if(get_config_bool(lookup_config(myself->connection->config_tree, "IndirectData"), &choice))
864 myself->options |= OPTION_INDIRECT;
866 if(get_config_bool(lookup_config(myself->connection->config_tree, "TCPOnly"), &choice))
868 myself->options |= OPTION_TCPONLY;
870 if(myself->options & OPTION_TCPONLY)
871 myself->options |= OPTION_INDIRECT;
873 if(get_config_string(lookup_config(config_tree, "Mode"), &mode))
875 if(!strcasecmp(mode, "router"))
876 routing_mode = RMODE_ROUTER;
877 else if (!strcasecmp(mode, "switch"))
878 routing_mode = RMODE_SWITCH;
879 else if (!strcasecmp(mode, "hub"))
880 routing_mode = RMODE_HUB;
883 syslog(LOG_ERR, _("Invalid routing mode!"));
888 routing_mode = RMODE_ROUTER;
893 if((tcp_socket = setup_listen_socket(myself->port)) < 0)
895 syslog(LOG_ERR, _("Unable to set up a listening TCP socket!"));
899 if((udp_socket = setup_vpn_in_socket(myself->port)) < 0)
901 syslog(LOG_ERR, _("Unable to set up a listening UDP socket!"));
905 /* Generate packet encryption key */
907 if(get_config_string(lookup_config(myself->connection->config_tree, "Cipher"), &cipher))
909 if(!strcasecmp(cipher, "none"))
911 myself->cipher = NULL;
915 if(!(myself->cipher = EVP_get_cipherbyname(cipher)))
917 syslog(LOG_ERR, _("Unrecognized cipher type!"));
923 myself->cipher = EVP_bf_cbc();
926 myself->keylength = myself->cipher->key_len + myself->cipher->iv_len;
928 myself->keylength = 1;
930 myself->key = (char *)xmalloc(myself->keylength);
931 RAND_pseudo_bytes(myself->key, myself->keylength);
933 if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
936 keyexpires = time(NULL) + keylifetime;
938 /* Check if we want to use message authentication codes... */
940 if(get_config_string(lookup_config(myself->connection->config_tree, "Digest"), &digest))
942 if(!strcasecmp(digest, "none"))
944 myself->digest = NULL;
948 if(!(myself->digest = EVP_get_digestbyname(digest)))
950 syslog(LOG_ERR, _("Unrecognized digest type!"));
956 myself->digest = EVP_sha1();
958 if(get_config_int(lookup_config(myself->connection->config_tree, "MACLength"), &myself->maclength))
962 if(myself->maclength > myself->digest->md_size)
964 syslog(LOG_ERR, _("MAC length exceeds size of digest!"));
967 else if (myself->maclength < 0)
969 syslog(LOG_ERR, _("Bogus MAC length!"));
975 myself->maclength = 4;
979 if(get_config_int(lookup_config(myself->connection->config_tree, "Compression"), &myself->compression))
981 if(myself->compression < 0 || myself->compression > 9)
983 syslog(LOG_ERR, _("Bogus compression level!"));
988 myself->compression = 0;
992 myself->nexthop = myself;
993 myself->via = myself;
994 myself->status.active = 1;
999 syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
1005 setup all initial network connections
1007 int setup_network_connections(void)
1016 if(get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
1020 pingtimeout = 86400;
1026 if(setup_device() < 0)
1029 /* Run tinc-up script to further initialize the tap interface */
1030 execute_script("tinc-up");
1032 if(setup_myself() < 0)
1035 try_outgoing_connections();
1041 close all open network connections
1043 void close_network_connections(void)
1045 avl_node_t *node, *next;
1048 for(node = connection_tree->head; node; node = next)
1051 c = (connection_t *)node->data;
1053 free(c->outgoing->name), free(c->outgoing);
1054 terminate_connection(c, 0);
1057 if(myself && myself->connection)
1058 terminate_connection(myself->connection, 0);
1069 execute_script("tinc-down");
1077 handle an incoming tcp connect call and open
1080 connection_t *create_new_connection(int sfd)
1083 struct sockaddr_in ci;
1084 int len = sizeof(ci);
1086 c = new_connection();
1088 if(getpeername(sfd, (struct sockaddr *) &ci, (socklen_t *) &len) < 0)
1090 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1096 c->address = ntohl(ci.sin_addr.s_addr);
1097 c->hostname = hostlookup(ci.sin_addr.s_addr);
1098 c->port = htons(ci.sin_port);
1100 c->last_ping_time = time(NULL);
1102 if(debug_lvl >= DEBUG_CONNECTIONS)
1103 syslog(LOG_NOTICE, _("Connection from %s port %d"),
1104 c->hostname, c->port);
1106 c->allow_request = ID;
1112 put all file descriptors in an fd_set array
1114 void build_fdset(fd_set *fs)
1121 for(node = connection_tree->head; node; node = node->next)
1123 c = (connection_t *)node->data;
1124 FD_SET(c->socket, fs);
1127 FD_SET(tcp_socket, fs);
1128 FD_SET(udp_socket, fs);
1129 FD_SET(device_fd, fs);
1134 receive incoming data from the listening
1135 udp socket and write it to the ethertap
1136 device after being decrypted
1138 void handle_incoming_vpn_data(void)
1141 int x, l = sizeof(x);
1142 struct sockaddr_in from;
1143 socklen_t fromlen = sizeof(from);
1146 if(getsockopt(udp_socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1148 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1149 __FILE__, __LINE__, udp_socket);
1154 syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1158 if((pkt.len = recvfrom(udp_socket, (char *)&pkt.seqno, MAXSIZE, 0, (struct sockaddr *)&from, &fromlen)) <= 0)
1160 syslog(LOG_ERR, _("Receiving packet failed: %m"));
1164 n = lookup_node_udp(ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
1168 syslog(LOG_WARNING, _("Received UDP packet on port %hd from unknown source %x:%hd"), myself->port, ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
1174 n->connection->last_ping_time = time(NULL);
1176 receive_udppacket(n, &pkt);
1180 /* Purge edges and subnets of unreachable nodes. Use carefully. */
1184 avl_node_t *nnode, *nnext, *enode, *enext, *snode, *snext, *cnode;
1190 if(debug_lvl >= DEBUG_PROTOCOL)
1191 syslog(LOG_DEBUG, _("Purging unreachable nodes"));
1193 for(nnode = node_tree->head; nnode; nnode = nnext)
1195 nnext = nnode->next;
1196 n = (node_t *)nnode->data;
1198 if(!n->status.reachable)
1200 if(debug_lvl >= DEBUG_SCARY_THINGS)
1201 syslog(LOG_DEBUG, _("Purging node %s (%s)"), n->name, n->hostname);
1203 for(snode = n->subnet_tree->head; snode; snode = snext)
1205 snext = snode->next;
1206 s = (subnet_t *)snode->data;
1208 for(cnode = connection_tree->head; cnode; cnode = cnode->next)
1210 c = (connection_t *)cnode->data;
1211 if(c->status.active)
1212 send_del_subnet(c, s);
1218 for(enode = n->edge_tree->head; enode; enode = enext)
1220 enext = enode->next;
1221 e = (edge_t *)enode->data;
1223 for(cnode = connection_tree->head; cnode; cnode = cnode->next)
1225 c = (connection_t *)cnode->data;
1226 if(c->status.active)
1227 send_del_edge(c, e);
1240 Terminate a connection:
1242 - Remove associated edge and tell other connections about it if report = 1
1243 - Check if we need to retry making an outgoing connection
1244 - Deactivate the host
1246 void terminate_connection(connection_t *c, int report)
1249 connection_t *other;
1251 if(c->status.remove)
1254 if(debug_lvl >= DEBUG_CONNECTIONS)
1255 syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1256 c->name, c->hostname);
1258 c->status.remove = 1;
1267 for(node = connection_tree->head; node; node = node->next)
1269 other = (connection_t *)node->data;
1270 if(other->status.active && other != c)
1271 send_del_edge(other, c->edge);
1278 /* Run MST and SSSP algorithms */
1282 /* Check if this was our outgoing connection */
1286 retry_outgoing(c->outgoing);
1292 c->status.active = 0;
1294 c->node->connection = NULL;
1300 Check if the other end is active.
1301 If we have sent packets, but didn't receive any,
1302 then possibly the other end is dead. We send a
1303 PING request over the meta connection. If the other
1304 end does not reply in time, we consider them dead
1305 and close the connection.
1307 void check_dead_connections(void)
1310 avl_node_t *node, *next;
1315 for(node = connection_tree->head; node; node = next)
1318 c = (connection_t *)node->data;
1319 if(c->last_ping_time + pingtimeout < now)
1321 if(c->status.active)
1323 if(c->status.pinged)
1325 if(debug_lvl >= DEBUG_PROTOCOL)
1326 syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1327 c->name, c->hostname);
1328 c->status.timeout = 1;
1329 terminate_connection(c, 1);
1338 if(debug_lvl >= DEBUG_CONNECTIONS)
1339 syslog(LOG_WARNING, _("Timeout from %s (%s) during authentication"),
1340 c->name, c->hostname);
1341 terminate_connection(c, 0);
1349 accept a new tcp connect and create a
1352 int handle_new_meta_connection()
1355 struct sockaddr client;
1356 int fd, len = sizeof(client);
1358 if((fd = accept(tcp_socket, &client, &len)) < 0)
1360 syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1364 if(!(new = create_new_connection(fd)))
1368 syslog(LOG_NOTICE, _("Closed attempted connection"));
1372 connection_add(new);
1379 void try_outgoing_connections(void)
1381 static config_t *cfg = NULL;
1383 outgoing_t *outgoing;
1385 for(cfg = lookup_config(config_tree, "ConnectTo"); cfg; cfg = lookup_config_next(config_tree, cfg))
1387 get_config_string(cfg, &name);
1391 syslog(LOG_ERR, _("Invalid name for outgoing connection in %s line %d"), cfg->file, cfg->line);
1396 outgoing = xmalloc_and_zero(sizeof(*outgoing));
1397 outgoing->name = name;
1398 setup_outgoing_connection(outgoing);
1403 check all connections to see if anything
1404 happened on their sockets
1406 void check_network_activity(fd_set *f)
1411 if(FD_ISSET(udp_socket, f))
1412 handle_incoming_vpn_data();
1414 for(node = connection_tree->head; node; node = node->next)
1416 c = (connection_t *)node->data;
1418 if(c->status.remove)
1421 if(FD_ISSET(c->socket, f))
1422 if(receive_meta(c) < 0)
1424 terminate_connection(c, c->status.active);
1429 if(FD_ISSET(tcp_socket, f))
1430 handle_new_meta_connection();
1434 void prune_connections(void)
1437 avl_node_t *node, *next;
1439 for(node = connection_tree->head; node; node = next)
1442 c = (connection_t *)node->data;
1444 if(c->status.remove)
1448 if(!connection_tree->head)
1454 this is where it all happens...
1456 void main_loop(void)
1461 time_t last_ping_check;
1464 vpn_packet_t packet;
1466 last_ping_check = time(NULL);
1472 tv.tv_sec = 1 + (rand() & 7); /* Approx. 5 seconds, randomized to prevent global synchronisation effects */
1477 prune_connections();
1483 if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1485 if(errno != EINTR) /* because of a signal */
1487 syslog(LOG_ERR, _("Error while waiting for input: %m"));
1494 syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1496 close_network_connections();
1497 exit_configuration(&config_tree);
1499 if(read_server_config())
1501 syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1507 if(setup_network_connections())
1521 /* Let's check if everybody is still alive */
1523 if(last_ping_check + pingtimeout < t)
1525 check_dead_connections();
1526 last_ping_check = time(NULL);
1528 /* Should we regenerate our key? */
1532 if(debug_lvl >= DEBUG_STATUS)
1533 syslog(LOG_INFO, _("Regenerating symmetric key"));
1535 RAND_pseudo_bytes(myself->key, myself->keylength);
1536 send_key_changed(myself->connection, myself);
1537 keyexpires = time(NULL) + keylifetime;
1543 syslog(LOG_INFO, _("Flushing event queue"));
1545 while(event_tree->head)
1547 event = (event_t *)event_tree->head->data;
1548 event->handler(event->data);
1554 while((event = get_expired_event()))
1556 event->handler(event->data);
1562 check_network_activity(&fset);
1564 /* local tap data */
1565 if(FD_ISSET(device_fd, &fset))
1567 if(!read_packet(&packet))
1568 route_outgoing(&packet);