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.154 2002/02/11 15:59:18 guus Exp $
28 #include <netinet/in.h>
30 #include <netinet/ip.h>
31 #include <netinet/tcp.h>
37 #include <sys/signal.h>
39 #include <sys/types.h>
42 #include <sys/ioctl.h>
43 /* SunOS really wants sys/socket.h BEFORE net/if.h,
44 and FreeBSD wants these lines below the rest. */
45 #include <arpa/inet.h>
46 #include <sys/socket.h>
49 #include <openssl/rand.h>
50 #include <openssl/evp.h>
51 #include <openssl/pem.h>
52 #include <openssl/hmac.h>
54 #ifndef HAVE_RAND_PSEUDO_BYTES
55 #define RAND_pseudo_bytes RAND_bytes
66 #include "connection.h"
82 int seconds_till_retry = 5;
95 #define MAX_SEQNO 1073741824
99 void receive_udppacket(node_t *n, vpn_packet_t *inpkt)
101 vpn_packet_t pkt1, pkt2;
102 vpn_packet_t *pkt[] = {&pkt1, &pkt2, &pkt1, &pkt2};
104 vpn_packet_t *outpkt = pkt[0];
106 long int complen = MTU + 12;
108 char hmac[EVP_MAX_MD_SIZE];
110 /* Check the message authentication code */
112 if(myself->digest && myself->maclength)
114 inpkt->len -= myself->maclength;
115 HMAC(myself->digest, myself->key, myself->keylength, (char *)&inpkt->seqno, inpkt->len, hmac, NULL);
116 if(memcmp(hmac, (char *)&inpkt->seqno + inpkt->len, myself->maclength))
118 syslog(LOG_DEBUG, _("Got unauthenticated packet from %s (%s)"), n->name, n->hostname);
123 /* Decrypt the packet */
127 outpkt = pkt[nextpkt++];
129 EVP_DecryptInit(&ctx, myself->cipher, myself->key, myself->key + myself->cipher->key_len);
130 EVP_DecryptUpdate(&ctx, (char *)&outpkt->seqno, &outlen, (char *)&inpkt->seqno, inpkt->len);
131 EVP_DecryptFinal(&ctx, (char *)&outpkt->seqno + outlen, &outpad);
133 outpkt->len = outlen + outpad;
137 /* Check the sequence number */
139 inpkt->len -= sizeof(inpkt->seqno);
140 inpkt->seqno = ntohl(inpkt->seqno);
142 if(inpkt->seqno <= n->received_seqno)
144 syslog(LOG_DEBUG, _("Got late or replayed packet from %s (%s), seqno %d"), n->name, n->hostname, inpkt->seqno);
148 n->received_seqno = inpkt->seqno;
150 if(n->received_seqno > MAX_SEQNO)
153 /* Decompress the packet */
155 if(myself->compression)
157 outpkt = pkt[nextpkt++];
159 if(uncompress(outpkt->data, &complen, inpkt->data, inpkt->len) != Z_OK)
161 syslog(LOG_ERR, _("Error while uncompressing packet from %s (%s)"), n->name, n->hostname);
165 outpkt->len = complen;
169 receive_packet(n, inpkt);
173 void receive_tcppacket(connection_t *c, char *buffer, int len)
178 memcpy(outpkt.data, buffer, len);
180 receive_packet(c->node, &outpkt);
184 void receive_packet(node_t *n, vpn_packet_t *packet)
187 if(debug_lvl >= DEBUG_TRAFFIC)
188 syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"), packet->len, n->name, n->hostname);
190 route_incoming(n, packet);
194 void send_udppacket(node_t *n, vpn_packet_t *inpkt)
196 vpn_packet_t pkt1, pkt2;
197 vpn_packet_t *pkt[] = {&pkt1, &pkt2, &pkt1, &pkt2};
199 vpn_packet_t *outpkt;
201 long int complen = MTU + 12;
203 struct sockaddr_in to;
204 socklen_t tolen = sizeof(to);
207 if(!n->status.validkey)
209 if(debug_lvl >= DEBUG_TRAFFIC)
210 syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
211 n->name, n->hostname);
213 /* Since packet is on the stack of handle_tap_input(),
214 we have to make a copy of it first. */
216 copy = xmalloc(sizeof(vpn_packet_t));
217 memcpy(copy, inpkt, sizeof(vpn_packet_t));
219 list_insert_tail(n->queue, copy);
221 if(!n->status.waitingforkey)
222 send_req_key(n->nexthop->connection, myself, n);
227 /* Compress the packet */
231 outpkt = pkt[nextpkt++];
233 if(compress2(outpkt->data, &complen, inpkt->data, inpkt->len, n->compression) != Z_OK)
235 syslog(LOG_ERR, _("Error while compressing packet to %s (%s)"), n->name, n->hostname);
239 outpkt->len = complen;
243 /* Add sequence number */
245 inpkt->seqno = htonl(++(n->sent_seqno));
246 inpkt->len += sizeof(inpkt->seqno);
248 /* Encrypt the packet */
252 outpkt = pkt[nextpkt++];
254 EVP_EncryptInit(&ctx, n->cipher, n->key, n->key + n->cipher->key_len);
255 EVP_EncryptUpdate(&ctx, (char *)&outpkt->seqno, &outlen, (char *)&inpkt->seqno, inpkt->len);
256 EVP_EncryptFinal(&ctx, (char *)&outpkt->seqno + outlen, &outpad);
258 outpkt->len = outlen + outpad;
262 /* Add the message authentication code */
264 if(n->digest && n->maclength)
266 HMAC(n->digest, n->key, n->keylength, (char *)&inpkt->seqno, inpkt->len, (char *)&inpkt->seqno + inpkt->len, &outlen);
267 inpkt->len += n->maclength;
270 /* Send the packet */
272 to.sin_family = AF_INET;
273 to.sin_addr.s_addr = htonl(n->address);
274 to.sin_port = htons(n->port);
276 if((sendto(udp_socket, (char *)&inpkt->seqno, inpkt->len, 0, (const struct sockaddr *)&to, tolen)) < 0)
278 syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
279 n->name, n->hostname);
286 send a packet to the given vpn ip.
288 void send_packet(node_t *n, vpn_packet_t *packet)
292 if(debug_lvl >= DEBUG_TRAFFIC)
293 syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
294 packet->len, n->name, n->hostname);
298 if(debug_lvl >= DEBUG_TRAFFIC)
300 syslog(LOG_NOTICE, _("Packet is looping back to us!"));
306 if(!n->status.reachable)
308 if(debug_lvl >= DEBUG_TRAFFIC)
309 syslog(LOG_INFO, _("Node %s (%s) is not reachable"),
310 n->name, n->hostname);
314 via = (n->via == myself)?n->nexthop:n->via;
316 if(via != n && debug_lvl >= DEBUG_TRAFFIC)
317 syslog(LOG_ERR, _("Sending packet to %s via %s (%s)"),
318 n->name, via->name, n->via->hostname);
320 if((myself->options | via->options) & OPTION_TCPONLY)
322 if(send_tcppacket(via->connection, packet))
323 terminate_connection(via->connection, 1);
326 send_udppacket(via, packet);
329 /* Broadcast a packet using the minimum spanning tree */
331 void broadcast_packet(node_t *from, vpn_packet_t *packet)
336 if(debug_lvl >= DEBUG_TRAFFIC)
337 syslog(LOG_INFO, _("Broadcasting packet of %d bytes from %s (%s)"),
338 packet->len, from->name, from->hostname);
340 for(node = connection_tree->head; node; node = node->next)
342 c = (connection_t *)node->data;
343 if(c->status.active && c->status.mst && c != from->nexthop->connection)
344 send_packet(c->node, packet);
349 void flush_queue(node_t *n)
351 list_node_t *node, *next;
353 if(debug_lvl >= DEBUG_TRAFFIC)
354 syslog(LOG_INFO, _("Flushing queue for %s (%s)"), n->name, n->hostname);
356 for(node = n->queue->head; node; node = next)
359 send_udppacket(n, (vpn_packet_t *)node->data);
360 list_delete_node(n->queue, node);
367 int setup_listen_socket(port_t port)
370 struct sockaddr_in a;
377 if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
379 syslog(LOG_ERR, _("Creating metasocket failed: %m"));
383 flags = fcntl(nfd, F_GETFL);
384 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
387 syslog(LOG_ERR, _("System call `%s' failed: %m"),
392 /* Optimize TCP settings */
395 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
396 setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
398 setsockopt(nfd, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
400 option = IPTOS_LOWDELAY;
401 setsockopt(nfd, SOL_IP, IP_TOS, &option, sizeof(option));
403 if(get_config_string(lookup_config(config_tree, "BindToInterface"), &interface))
404 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, interface, strlen(interface)))
407 syslog(LOG_ERR, _("Can't bind to interface %s: %m"), interface);
412 memset(&a, 0, sizeof(a));
413 a.sin_family = AF_INET;
414 a.sin_addr.s_addr = htonl(INADDR_ANY);
415 a.sin_port = htons(port);
417 if(get_config_address(lookup_config(config_tree, "BindToAddress"), &address))
419 a.sin_addr.s_addr = htonl(*address);
423 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
426 syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
433 syslog(LOG_ERR, _("System call `%s' failed: %m"),
441 int setup_vpn_in_socket(port_t port)
444 struct sockaddr_in a;
447 if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
450 syslog(LOG_ERR, _("Creating socket failed: %m"));
454 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
456 flags = fcntl(nfd, F_GETFL);
457 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
460 syslog(LOG_ERR, _("System call `%s' failed: %m"),
465 memset(&a, 0, sizeof(a));
466 a.sin_family = AF_INET;
467 a.sin_port = htons(port);
468 a.sin_addr.s_addr = htonl(INADDR_ANY);
470 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
473 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
480 void retry_outgoing(outgoing_t *outgoing)
484 outgoing->timeout += 5;
485 if(outgoing->timeout > maxtimeout)
486 outgoing->timeout = maxtimeout;
489 event->handler = (event_handler_t)setup_outgoing_connection;
490 event->time = time(NULL) + outgoing->timeout;
491 event->data = outgoing;
494 if(debug_lvl >= DEBUG_CONNECTIONS)
495 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), outgoing->timeout);
499 int setup_outgoing_socket(connection_t *c)
502 struct sockaddr_in a;
504 if(debug_lvl >= DEBUG_CONNECTIONS)
505 syslog(LOG_INFO, _("Trying to connect to %s (%s)"), c->name, c->hostname);
507 c->socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
511 syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
512 c->hostname, c->port);
516 /* Bind first to get a fix on our source port???
518 a.sin_family = AF_INET;
519 a.sin_port = htons(0);
520 a.sin_addr.s_addr = htonl(INADDR_ANY);
522 if(bind(c->socket, (struct sockaddr *)&a, sizeof(struct sockaddr)))
525 syslog(LOG_ERR, _("System call `%s' failed: %m"), "bind");
531 /* Optimize TCP settings?
534 setsockopt(c->socket, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
536 setsockopt(c->socket, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
538 option = IPTOS_LOWDELAY;
539 setsockopt(c->socket, SOL_IP, IP_TOS, &option, sizeof(option));
546 a.sin_family = AF_INET;
547 a.sin_port = htons(c->port);
548 a.sin_addr.s_addr = htonl(c->address);
550 if(connect(c->socket, (struct sockaddr *)&a, sizeof(a)) == -1)
553 syslog(LOG_ERR, _("%s port %hd: %m"), c->hostname, c->port);
557 flags = fcntl(c->socket, F_GETFL);
559 if(fcntl(c->socket, F_SETFL, flags | O_NONBLOCK) < 0)
562 syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
563 c->hostname, c->port);
567 if(debug_lvl >= DEBUG_CONNECTIONS)
568 syslog(LOG_INFO, _("Connected to %s port %hd"),
569 c->hostname, c->port);
574 void setup_outgoing_connection(outgoing_t *outgoing)
580 n = lookup_node(outgoing->name);
585 if(debug_lvl >= DEBUG_CONNECTIONS)
586 syslog(LOG_INFO, _("Already connected to %s"), outgoing->name);
587 n->connection->outgoing = outgoing;
591 c = new_connection();
592 c->name = xstrdup(outgoing->name);
594 init_configuration(&c->config_tree);
595 read_connection_config(c);
597 if(!get_config_string(lookup_config(c->config_tree, "Address"), &c->hostname))
599 syslog(LOG_ERR, _("No address specified for %s"), c->name);
601 free(outgoing->name);
606 if(!get_config_port(lookup_config(c->config_tree, "Port"), &c->port))
609 if(!(h = gethostbyname(c->hostname)))
611 syslog(LOG_ERR, _("Error looking up `%s': %m"), c->hostname);
613 retry_outgoing(outgoing);
617 c->address = ntohl(*((ipv4_t*)(h->h_addr_list[0])));
618 c->hostname = hostlookup(htonl(c->address));
620 if(setup_outgoing_socket(c) < 0)
622 syslog(LOG_ERR, _("Could not set up a meta connection to %s (%s)"),
623 c->name, c->hostname);
624 retry_outgoing(outgoing);
628 c->outgoing = outgoing;
629 c->last_ping_time = time(NULL);
637 int read_rsa_public_key(connection_t *c)
644 c->rsa_key = RSA_new();
646 /* First, check for simple PublicKey statement */
648 if(get_config_string(lookup_config(c->config_tree, "PublicKey"), &key))
650 BN_hex2bn(&c->rsa_key->n, key);
651 BN_hex2bn(&c->rsa_key->e, "FFFF");
656 /* Else, check for PublicKeyFile statement and read it */
658 if(get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &fname))
660 if(is_safe_path(fname))
662 if((fp = fopen(fname, "r")) == NULL)
664 syslog(LOG_ERR, _("Error reading RSA public key file `%s': %m"),
670 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
674 syslog(LOG_ERR, _("Reading RSA public key file `%s' failed: %m"),
687 /* Else, check if a harnessed public key is in the config file */
689 asprintf(&fname, "%s/hosts/%s", confbase, c->name);
690 if((fp = fopen(fname, "r")))
692 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
702 syslog(LOG_ERR, _("No public key for %s specified!"), c->name);
707 int read_rsa_private_key(void)
712 if(get_config_string(lookup_config(config_tree, "PrivateKey"), &key))
714 myself->connection->rsa_key = RSA_new();
715 BN_hex2bn(&myself->connection->rsa_key->d, key);
716 BN_hex2bn(&myself->connection->rsa_key->e, "FFFF");
721 if(!get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname))
722 asprintf(&fname, "%s/rsa_key.priv", confbase);
724 if(is_safe_path(fname))
726 if((fp = fopen(fname, "r")) == NULL)
728 syslog(LOG_ERR, _("Error reading RSA private key file `%s': %m"),
734 myself->connection->rsa_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
736 if(!myself->connection->rsa_key)
738 syslog(LOG_ERR, _("Reading RSA private key file `%s' failed: %m"),
749 int check_rsa_key(RSA *rsa_key)
751 char *test1, *test2, *test3;
753 if(rsa_key->p && rsa_key->q)
755 if(RSA_check_key(rsa_key) != 1)
760 test1 = xmalloc(RSA_size(rsa_key));
761 test2 = xmalloc(RSA_size(rsa_key));
762 test3 = xmalloc(RSA_size(rsa_key));
764 if(RSA_public_encrypt(RSA_size(rsa_key), test1, test2, rsa_key, RSA_NO_PADDING) != RSA_size(rsa_key))
767 if(RSA_private_decrypt(RSA_size(rsa_key), test2, test3, rsa_key, RSA_NO_PADDING) != RSA_size(rsa_key))
770 if(memcmp(test1, test3, RSA_size(rsa_key)))
778 Configure node_t myself and set up the local sockets (listen only)
780 int setup_myself(void)
784 char *name, *mode, *cipher, *digest;
788 myself->connection = new_connection();
789 init_configuration(&myself->connection->config_tree);
791 asprintf(&myself->hostname, _("MYSELF"));
792 asprintf(&myself->connection->hostname, _("MYSELF"));
794 myself->connection->options = 0;
795 myself->connection->protocol_version = PROT_CURRENT;
797 if(!get_config_string(lookup_config(config_tree, "Name"), &name)) /* Not acceptable */
799 syslog(LOG_ERR, _("Name for tinc daemon required!"));
805 syslog(LOG_ERR, _("Invalid name for myself!"));
811 myself->connection->name = xstrdup(name);
814 if(read_rsa_private_key())
817 if(read_connection_config(myself->connection))
819 syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
823 if(read_rsa_public_key(myself->connection))
827 if(check_rsa_key(myself->connection->rsa_key))
829 syslog(LOG_ERR, _("Invalid public/private keypair!"));
833 if(!get_config_port(lookup_config(myself->connection->config_tree, "Port"), &myself->port))
836 myself->connection->port = myself->port;
838 /* Read in all the subnets specified in the host configuration file */
840 cfg = lookup_config(myself->connection->config_tree, "Subnet");
844 if(!get_config_subnet(cfg, &subnet))
847 subnet_add(myself, subnet);
849 cfg = lookup_config_next(myself->connection->config_tree, cfg);
853 /* Check some options */
855 if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice))
857 myself->options |= OPTION_INDIRECT;
859 if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice))
861 myself->options |= OPTION_TCPONLY;
863 if(get_config_bool(lookup_config(myself->connection->config_tree, "IndirectData"), &choice))
865 myself->options |= OPTION_INDIRECT;
867 if(get_config_bool(lookup_config(myself->connection->config_tree, "TCPOnly"), &choice))
869 myself->options |= OPTION_TCPONLY;
871 if(myself->options & OPTION_TCPONLY)
872 myself->options |= OPTION_INDIRECT;
874 if(get_config_string(lookup_config(config_tree, "Mode"), &mode))
876 if(!strcasecmp(mode, "router"))
877 routing_mode = RMODE_ROUTER;
878 else if (!strcasecmp(mode, "switch"))
879 routing_mode = RMODE_SWITCH;
880 else if (!strcasecmp(mode, "hub"))
881 routing_mode = RMODE_HUB;
884 syslog(LOG_ERR, _("Invalid routing mode!"));
889 routing_mode = RMODE_ROUTER;
894 if((tcp_socket = setup_listen_socket(myself->port)) < 0)
896 syslog(LOG_ERR, _("Unable to set up a listening TCP socket!"));
900 if((udp_socket = setup_vpn_in_socket(myself->port)) < 0)
902 syslog(LOG_ERR, _("Unable to set up a listening UDP socket!"));
906 /* Generate packet encryption key */
908 if(get_config_string(lookup_config(myself->connection->config_tree, "Cipher"), &cipher))
910 if(!strcasecmp(cipher, "none"))
912 myself->cipher = NULL;
916 if(!(myself->cipher = EVP_get_cipherbyname(cipher)))
918 syslog(LOG_ERR, _("Unrecognized cipher type!"));
924 myself->cipher = EVP_bf_cbc();
927 myself->keylength = myself->cipher->key_len + myself->cipher->iv_len;
929 myself->keylength = 1;
931 myself->key = (char *)xmalloc(myself->keylength);
932 RAND_pseudo_bytes(myself->key, myself->keylength);
934 if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
937 keyexpires = time(NULL) + keylifetime;
939 /* Check if we want to use message authentication codes... */
941 if(get_config_string(lookup_config(myself->connection->config_tree, "Digest"), &digest))
943 if(!strcasecmp(digest, "none"))
945 myself->digest = NULL;
949 if(!(myself->digest = EVP_get_digestbyname(digest)))
951 syslog(LOG_ERR, _("Unrecognized digest type!"));
957 myself->digest = EVP_sha1();
959 if(get_config_int(lookup_config(myself->connection->config_tree, "MACLength"), &myself->maclength))
963 if(myself->maclength > myself->digest->md_size)
965 syslog(LOG_ERR, _("MAC length exceeds size of digest!"));
968 else if (myself->maclength < 0)
970 syslog(LOG_ERR, _("Bogus MAC length!"));
976 myself->maclength = 4;
980 if(get_config_int(lookup_config(myself->connection->config_tree, "Compression"), &myself->compression))
982 if(myself->compression < 0 || myself->compression > 9)
984 syslog(LOG_ERR, _("Bogus compression level!"));
989 myself->compression = 0;
993 myself->nexthop = myself;
994 myself->via = myself;
995 myself->status.active = 1;
1000 syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
1006 setup all initial network connections
1008 int setup_network_connections(void)
1017 if(get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
1021 pingtimeout = 86400;
1027 if(setup_device() < 0)
1030 /* Run tinc-up script to further initialize the tap interface */
1031 execute_script("tinc-up");
1033 if(setup_myself() < 0)
1036 try_outgoing_connections();
1042 close all open network connections
1044 void close_network_connections(void)
1046 avl_node_t *node, *next;
1049 for(node = connection_tree->head; node; node = next)
1052 c = (connection_t *)node->data;
1054 free(c->outgoing->name), free(c->outgoing);
1055 terminate_connection(c, 0);
1058 if(myself && myself->connection)
1059 terminate_connection(myself->connection, 0);
1070 execute_script("tinc-down");
1078 handle an incoming tcp connect call and open
1081 connection_t *create_new_connection(int sfd)
1084 struct sockaddr_in ci;
1085 int len = sizeof(ci);
1087 c = new_connection();
1089 if(getpeername(sfd, (struct sockaddr *) &ci, (socklen_t *) &len) < 0)
1091 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1097 c->address = ntohl(ci.sin_addr.s_addr);
1098 c->hostname = hostlookup(ci.sin_addr.s_addr);
1099 c->port = htons(ci.sin_port);
1101 c->last_ping_time = time(NULL);
1103 if(debug_lvl >= DEBUG_CONNECTIONS)
1104 syslog(LOG_NOTICE, _("Connection from %s port %d"),
1105 c->hostname, c->port);
1107 c->allow_request = ID;
1113 put all file descriptors in an fd_set array
1115 void build_fdset(fd_set *fs)
1122 for(node = connection_tree->head; node; node = node->next)
1124 c = (connection_t *)node->data;
1125 FD_SET(c->socket, fs);
1128 FD_SET(tcp_socket, fs);
1129 FD_SET(udp_socket, fs);
1130 FD_SET(device_fd, fs);
1135 receive incoming data from the listening
1136 udp socket and write it to the ethertap
1137 device after being decrypted
1139 void handle_incoming_vpn_data(void)
1142 int x, l = sizeof(x);
1143 struct sockaddr_in from;
1144 socklen_t fromlen = sizeof(from);
1147 if(getsockopt(udp_socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1149 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1150 __FILE__, __LINE__, udp_socket);
1155 syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1159 if((pkt.len = recvfrom(udp_socket, (char *)&pkt.seqno, MAXSIZE, 0, (struct sockaddr *)&from, &fromlen)) <= 0)
1161 syslog(LOG_ERR, _("Receiving packet failed: %m"));
1165 n = lookup_node_udp(ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
1169 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));
1175 n->connection->last_ping_time = time(NULL);
1177 receive_udppacket(n, &pkt);
1181 /* Purge edges and subnets of unreachable nodes. Use carefully. */
1185 avl_node_t *nnode, *nnext, *enode, *enext, *snode, *snext, *cnode;
1191 if(debug_lvl >= DEBUG_PROTOCOL)
1192 syslog(LOG_DEBUG, _("Purging unreachable nodes"));
1194 for(nnode = node_tree->head; nnode; nnode = nnext)
1196 nnext = nnode->next;
1197 n = (node_t *)nnode->data;
1199 if(!n->status.reachable)
1201 if(debug_lvl >= DEBUG_SCARY_THINGS)
1202 syslog(LOG_DEBUG, _("Purging node %s (%s)"), n->name, n->hostname);
1204 for(snode = n->subnet_tree->head; snode; snode = snext)
1206 snext = snode->next;
1207 s = (subnet_t *)snode->data;
1209 for(cnode = connection_tree->head; cnode; cnode = cnode->next)
1211 c = (connection_t *)cnode->data;
1212 if(c->status.active)
1213 send_del_subnet(c, s);
1219 for(enode = n->edge_tree->head; enode; enode = enext)
1221 enext = enode->next;
1222 e = (edge_t *)enode->data;
1224 for(cnode = connection_tree->head; cnode; cnode = cnode->next)
1226 c = (connection_t *)cnode->data;
1227 if(c->status.active)
1228 send_del_edge(c, e);
1241 Terminate a connection:
1243 - Remove associated edge and tell other connections about it if report = 1
1244 - Check if we need to retry making an outgoing connection
1245 - Deactivate the host
1247 void terminate_connection(connection_t *c, int report)
1250 connection_t *other;
1252 if(c->status.remove)
1255 if(debug_lvl >= DEBUG_CONNECTIONS)
1256 syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1257 c->name, c->hostname);
1259 c->status.remove = 1;
1268 for(node = connection_tree->head; node; node = node->next)
1270 other = (connection_t *)node->data;
1271 if(other->status.active && other != c)
1272 send_del_edge(other, c->edge);
1279 /* Run MST and SSSP algorithms */
1283 /* Check if this was our outgoing connection */
1287 retry_outgoing(c->outgoing);
1293 c->status.active = 0;
1295 c->node->connection = NULL;
1301 Check if the other end is active.
1302 If we have sent packets, but didn't receive any,
1303 then possibly the other end is dead. We send a
1304 PING request over the meta connection. If the other
1305 end does not reply in time, we consider them dead
1306 and close the connection.
1308 void check_dead_connections(void)
1311 avl_node_t *node, *next;
1316 for(node = connection_tree->head; node; node = next)
1319 c = (connection_t *)node->data;
1320 if(c->last_ping_time + pingtimeout < now)
1322 if(c->status.active)
1324 if(c->status.pinged)
1326 if(debug_lvl >= DEBUG_PROTOCOL)
1327 syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1328 c->name, c->hostname);
1329 c->status.timeout = 1;
1330 terminate_connection(c, 1);
1339 if(debug_lvl >= DEBUG_CONNECTIONS)
1340 syslog(LOG_WARNING, _("Timeout from %s (%s) during authentication"),
1341 c->name, c->hostname);
1342 terminate_connection(c, 0);
1350 accept a new tcp connect and create a
1353 int handle_new_meta_connection()
1356 struct sockaddr client;
1357 int fd, len = sizeof(client);
1359 if((fd = accept(tcp_socket, &client, &len)) < 0)
1361 syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1365 if(!(new = create_new_connection(fd)))
1369 syslog(LOG_NOTICE, _("Closed attempted connection"));
1373 connection_add(new);
1380 void try_outgoing_connections(void)
1382 static config_t *cfg = NULL;
1384 outgoing_t *outgoing;
1386 for(cfg = lookup_config(config_tree, "ConnectTo"); cfg; cfg = lookup_config_next(config_tree, cfg))
1388 get_config_string(cfg, &name);
1392 syslog(LOG_ERR, _("Invalid name for outgoing connection in %s line %d"), cfg->file, cfg->line);
1397 outgoing = xmalloc_and_zero(sizeof(*outgoing));
1398 outgoing->name = name;
1399 setup_outgoing_connection(outgoing);
1404 check all connections to see if anything
1405 happened on their sockets
1407 void check_network_activity(fd_set *f)
1412 if(FD_ISSET(udp_socket, f))
1413 handle_incoming_vpn_data();
1415 for(node = connection_tree->head; node; node = node->next)
1417 c = (connection_t *)node->data;
1419 if(c->status.remove)
1422 if(FD_ISSET(c->socket, f))
1423 if(receive_meta(c) < 0)
1425 terminate_connection(c, c->status.active);
1430 if(FD_ISSET(tcp_socket, f))
1431 handle_new_meta_connection();
1435 void prune_connections(void)
1438 avl_node_t *node, *next;
1440 for(node = connection_tree->head; node; node = next)
1443 c = (connection_t *)node->data;
1445 if(c->status.remove)
1449 if(!connection_tree->head)
1455 this is where it all happens...
1457 void main_loop(void)
1462 time_t last_ping_check;
1465 vpn_packet_t packet;
1467 last_ping_check = time(NULL);
1473 tv.tv_sec = 1 + (rand() & 7); /* Approx. 5 seconds, randomized to prevent global synchronisation effects */
1478 prune_connections();
1484 if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1486 if(errno != EINTR) /* because of a signal */
1488 syslog(LOG_ERR, _("Error while waiting for input: %m"));
1495 syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1497 close_network_connections();
1498 exit_configuration(&config_tree);
1500 if(read_server_config())
1502 syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1508 if(setup_network_connections())
1522 /* Let's check if everybody is still alive */
1524 if(last_ping_check + pingtimeout < t)
1526 check_dead_connections();
1527 last_ping_check = time(NULL);
1529 /* Should we regenerate our key? */
1533 if(debug_lvl >= DEBUG_STATUS)
1534 syslog(LOG_INFO, _("Regenerating symmetric key"));
1536 RAND_pseudo_bytes(myself->key, myself->keylength);
1537 send_key_changed(myself->connection, myself);
1538 keyexpires = time(NULL) + keylifetime;
1544 syslog(LOG_INFO, _("Flushing event queue"));
1546 while(event_tree->head)
1548 event = (event_t *)event_tree->head->data;
1549 event->handler(event->data);
1555 while((event = get_expired_event()))
1557 event->handler(event->data);
1563 check_network_activity(&fset);
1565 /* local tap data */
1566 if(FD_ISSET(device_fd, &fset))
1568 if(!read_packet(&packet))
1569 route_outgoing(&packet);