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.153 2002/02/11 14:20:21 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
64 #include "connection.h"
80 int seconds_till_retry = 5;
93 #define MAX_SEQNO 1073741824
97 void receive_udppacket(node_t *n, vpn_packet_t *inpkt)
102 char hmac[EVP_MAX_MD_SIZE];
105 if(myself->digest && myself->maclength)
107 inpkt->len -= myself->maclength;
108 HMAC(myself->digest, myself->key, myself->keylength, (char *)&inpkt->seqno, inpkt->len, hmac, NULL);
109 if(memcmp(hmac, (char *)&inpkt->seqno + inpkt->len, myself->maclength))
111 syslog(LOG_DEBUG, _("Got unauthenticated packet from %s (%s)"), n->name, n->hostname);
116 /* Decrypt the packet */
120 EVP_DecryptInit(&ctx, myself->cipher, myself->key, myself->key + myself->cipher->key_len);
121 EVP_DecryptUpdate(&ctx, (char *)&outpkt.seqno, &outlen, (char *)&inpkt->seqno, inpkt->len);
122 EVP_DecryptFinal(&ctx, (char *)&outpkt.seqno + outlen, &outpad);
124 outpkt.len = outlen - sizeof(outpkt.seqno);
128 memcpy((char *)&outpkt.seqno, (char *)&inpkt->seqno, inpkt->len);
129 outpkt.len = inpkt->len - sizeof(outpkt.seqno);
132 if (ntohl(outpkt.seqno) <= n->received_seqno)
134 syslog(LOG_DEBUG, _("Got late or replayed packet from %s (%s), seqno %d"), n->name, n->hostname, ntohl(*(unsigned int *)&outpkt.seqno));
138 n->received_seqno = ntohl(outpkt.seqno);
140 if(n->received_seqno > MAX_SEQNO)
143 receive_packet(n, &outpkt);
147 void receive_tcppacket(connection_t *c, char *buffer, int len)
152 memcpy(outpkt.data, buffer, len);
154 receive_packet(c->node, &outpkt);
158 void receive_packet(node_t *n, vpn_packet_t *packet)
161 if(debug_lvl >= DEBUG_TRAFFIC)
162 syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"), packet->len, n->name, n->hostname);
164 route_incoming(n, packet);
168 void send_udppacket(node_t *n, vpn_packet_t *inpkt)
173 struct sockaddr_in to;
174 socklen_t tolen = sizeof(to);
177 if(!n->status.validkey)
179 if(debug_lvl >= DEBUG_TRAFFIC)
180 syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
181 n->name, n->hostname);
183 /* Since packet is on the stack of handle_tap_input(),
184 we have to make a copy of it first. */
186 copy = xmalloc(sizeof(vpn_packet_t));
187 memcpy(copy, inpkt, sizeof(vpn_packet_t));
189 list_insert_tail(n->queue, copy);
191 if(!n->status.waitingforkey)
192 send_req_key(n->nexthop->connection, myself, n);
196 /* Encrypt the packet. */
198 inpkt->seqno = htonl(++(n->sent_seqno));
202 EVP_EncryptInit(&ctx, n->cipher, n->key, n->key + n->cipher->key_len);
203 EVP_EncryptUpdate(&ctx, (char *)&outpkt.seqno, &outlen, (char *)&inpkt->seqno, inpkt->len + sizeof(inpkt->seqno));
204 EVP_EncryptFinal(&ctx, (char *)&outpkt.seqno + outlen, &outpad);
209 memcpy((char *)&outpkt.seqno, (char *)&inpkt->seqno, inpkt->len + sizeof(inpkt->seqno));
210 outlen = inpkt->len + sizeof(inpkt->seqno);
213 if(n->digest && n->maclength)
215 HMAC(n->digest, n->key, n->keylength, (char *)&outpkt.seqno, outlen, (char *)&outpkt.seqno + outlen, &outpad);
216 outlen += n->maclength;
219 to.sin_family = AF_INET;
220 to.sin_addr.s_addr = htonl(n->address);
221 to.sin_port = htons(n->port);
223 if((sendto(udp_socket, (char *)&outpkt.seqno, outlen, 0, (const struct sockaddr *)&to, tolen)) < 0)
225 syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
226 n->name, n->hostname);
233 send a packet to the given vpn ip.
235 void send_packet(node_t *n, vpn_packet_t *packet)
239 if(debug_lvl >= DEBUG_TRAFFIC)
240 syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
241 packet->len, n->name, n->hostname);
245 if(debug_lvl >= DEBUG_TRAFFIC)
247 syslog(LOG_NOTICE, _("Packet is looping back to us!"));
253 if(!n->status.reachable)
255 if(debug_lvl >= DEBUG_TRAFFIC)
256 syslog(LOG_INFO, _("Node %s (%s) is not reachable"),
257 n->name, n->hostname);
261 via = (n->via == myself)?n->nexthop:n->via;
263 if(via != n && debug_lvl >= DEBUG_TRAFFIC)
264 syslog(LOG_ERR, _("Sending packet to %s via %s (%s)"),
265 n->name, via->name, n->via->hostname);
267 if((myself->options | via->options) & OPTION_TCPONLY)
269 if(send_tcppacket(via->connection, packet))
270 terminate_connection(via->connection, 1);
273 send_udppacket(via, packet);
276 /* Broadcast a packet using the minimum spanning tree */
278 void broadcast_packet(node_t *from, vpn_packet_t *packet)
283 if(debug_lvl >= DEBUG_TRAFFIC)
284 syslog(LOG_INFO, _("Broadcasting packet of %d bytes from %s (%s)"),
285 packet->len, from->name, from->hostname);
287 for(node = connection_tree->head; node; node = node->next)
289 c = (connection_t *)node->data;
290 if(c->status.active && c->status.mst && c != from->nexthop->connection)
291 send_packet(c->node, packet);
296 void flush_queue(node_t *n)
298 list_node_t *node, *next;
300 if(debug_lvl >= DEBUG_TRAFFIC)
301 syslog(LOG_INFO, _("Flushing queue for %s (%s)"), n->name, n->hostname);
303 for(node = n->queue->head; node; node = next)
306 send_udppacket(n, (vpn_packet_t *)node->data);
307 list_delete_node(n->queue, node);
314 int setup_listen_socket(port_t port)
317 struct sockaddr_in a;
324 if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
326 syslog(LOG_ERR, _("Creating metasocket failed: %m"));
330 flags = fcntl(nfd, F_GETFL);
331 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
334 syslog(LOG_ERR, _("System call `%s' failed: %m"),
339 /* Optimize TCP settings */
342 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
343 setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
345 setsockopt(nfd, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
347 option = IPTOS_LOWDELAY;
348 setsockopt(nfd, SOL_IP, IP_TOS, &option, sizeof(option));
350 if(get_config_string(lookup_config(config_tree, "BindToInterface"), &interface))
351 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, interface, strlen(interface)))
354 syslog(LOG_ERR, _("Can't bind to interface %s: %m"), interface);
359 memset(&a, 0, sizeof(a));
360 a.sin_family = AF_INET;
361 a.sin_addr.s_addr = htonl(INADDR_ANY);
362 a.sin_port = htons(port);
364 if(get_config_address(lookup_config(config_tree, "BindToAddress"), &address))
366 a.sin_addr.s_addr = htonl(*address);
370 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
373 syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
380 syslog(LOG_ERR, _("System call `%s' failed: %m"),
388 int setup_vpn_in_socket(port_t port)
391 struct sockaddr_in a;
394 if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
397 syslog(LOG_ERR, _("Creating socket failed: %m"));
401 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
403 flags = fcntl(nfd, F_GETFL);
404 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
407 syslog(LOG_ERR, _("System call `%s' failed: %m"),
412 memset(&a, 0, sizeof(a));
413 a.sin_family = AF_INET;
414 a.sin_port = htons(port);
415 a.sin_addr.s_addr = htonl(INADDR_ANY);
417 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
420 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
427 void retry_outgoing(outgoing_t *outgoing)
431 outgoing->timeout += 5;
432 if(outgoing->timeout > maxtimeout)
433 outgoing->timeout = maxtimeout;
436 event->handler = (event_handler_t)setup_outgoing_connection;
437 event->time = time(NULL) + outgoing->timeout;
438 event->data = outgoing;
441 if(debug_lvl >= DEBUG_CONNECTIONS)
442 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), outgoing->timeout);
446 int setup_outgoing_socket(connection_t *c)
449 struct sockaddr_in a;
451 if(debug_lvl >= DEBUG_CONNECTIONS)
452 syslog(LOG_INFO, _("Trying to connect to %s (%s)"), c->name, c->hostname);
454 c->socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
458 syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
459 c->hostname, c->port);
463 /* Bind first to get a fix on our source port???
465 a.sin_family = AF_INET;
466 a.sin_port = htons(0);
467 a.sin_addr.s_addr = htonl(INADDR_ANY);
469 if(bind(c->socket, (struct sockaddr *)&a, sizeof(struct sockaddr)))
472 syslog(LOG_ERR, _("System call `%s' failed: %m"), "bind");
478 /* Optimize TCP settings?
481 setsockopt(c->socket, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
483 setsockopt(c->socket, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
485 option = IPTOS_LOWDELAY;
486 setsockopt(c->socket, SOL_IP, IP_TOS, &option, sizeof(option));
493 a.sin_family = AF_INET;
494 a.sin_port = htons(c->port);
495 a.sin_addr.s_addr = htonl(c->address);
497 if(connect(c->socket, (struct sockaddr *)&a, sizeof(a)) == -1)
500 syslog(LOG_ERR, _("%s port %hd: %m"), c->hostname, c->port);
504 flags = fcntl(c->socket, F_GETFL);
506 if(fcntl(c->socket, F_SETFL, flags | O_NONBLOCK) < 0)
509 syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
510 c->hostname, c->port);
514 if(debug_lvl >= DEBUG_CONNECTIONS)
515 syslog(LOG_INFO, _("Connected to %s port %hd"),
516 c->hostname, c->port);
521 void setup_outgoing_connection(outgoing_t *outgoing)
527 n = lookup_node(outgoing->name);
532 if(debug_lvl >= DEBUG_CONNECTIONS)
533 syslog(LOG_INFO, _("Already connected to %s"), outgoing->name);
534 n->connection->outgoing = outgoing;
538 c = new_connection();
539 c->name = xstrdup(outgoing->name);
541 init_configuration(&c->config_tree);
542 read_connection_config(c);
544 if(!get_config_string(lookup_config(c->config_tree, "Address"), &c->hostname))
546 syslog(LOG_ERR, _("No address specified for %s"), c->name);
548 free(outgoing->name);
553 if(!get_config_port(lookup_config(c->config_tree, "Port"), &c->port))
556 if(!(h = gethostbyname(c->hostname)))
558 syslog(LOG_ERR, _("Error looking up `%s': %m"), c->hostname);
560 retry_outgoing(outgoing);
564 c->address = ntohl(*((ipv4_t*)(h->h_addr_list[0])));
565 c->hostname = hostlookup(htonl(c->address));
567 if(setup_outgoing_socket(c) < 0)
569 syslog(LOG_ERR, _("Could not set up a meta connection to %s (%s)"),
570 c->name, c->hostname);
571 retry_outgoing(outgoing);
575 c->outgoing = outgoing;
576 c->last_ping_time = time(NULL);
584 int read_rsa_public_key(connection_t *c)
591 c->rsa_key = RSA_new();
593 /* First, check for simple PublicKey statement */
595 if(get_config_string(lookup_config(c->config_tree, "PublicKey"), &key))
597 BN_hex2bn(&c->rsa_key->n, key);
598 BN_hex2bn(&c->rsa_key->e, "FFFF");
603 /* Else, check for PublicKeyFile statement and read it */
605 if(get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &fname))
607 if(is_safe_path(fname))
609 if((fp = fopen(fname, "r")) == NULL)
611 syslog(LOG_ERR, _("Error reading RSA public key file `%s': %m"),
617 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
621 syslog(LOG_ERR, _("Reading RSA public key file `%s' failed: %m"),
634 /* Else, check if a harnessed public key is in the config file */
636 asprintf(&fname, "%s/hosts/%s", confbase, c->name);
637 if((fp = fopen(fname, "r")))
639 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
649 syslog(LOG_ERR, _("No public key for %s specified!"), c->name);
654 int read_rsa_private_key(void)
659 if(get_config_string(lookup_config(config_tree, "PrivateKey"), &key))
661 myself->connection->rsa_key = RSA_new();
662 BN_hex2bn(&myself->connection->rsa_key->d, key);
663 BN_hex2bn(&myself->connection->rsa_key->e, "FFFF");
668 if(!get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname))
669 asprintf(&fname, "%s/rsa_key.priv", confbase);
671 if(is_safe_path(fname))
673 if((fp = fopen(fname, "r")) == NULL)
675 syslog(LOG_ERR, _("Error reading RSA private key file `%s': %m"),
681 myself->connection->rsa_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
683 if(!myself->connection->rsa_key)
685 syslog(LOG_ERR, _("Reading RSA private key file `%s' failed: %m"),
696 int check_rsa_key(RSA *rsa_key)
698 char *test1, *test2, *test3;
700 if(rsa_key->p && rsa_key->q)
702 if(RSA_check_key(rsa_key) != 1)
707 test1 = xmalloc(RSA_size(rsa_key));
708 test2 = xmalloc(RSA_size(rsa_key));
709 test3 = xmalloc(RSA_size(rsa_key));
711 if(RSA_public_encrypt(RSA_size(rsa_key), test1, test2, rsa_key, RSA_NO_PADDING) != RSA_size(rsa_key))
714 if(RSA_private_decrypt(RSA_size(rsa_key), test2, test3, rsa_key, RSA_NO_PADDING) != RSA_size(rsa_key))
717 if(memcmp(test1, test3, RSA_size(rsa_key)))
725 Configure node_t myself and set up the local sockets (listen only)
727 int setup_myself(void)
731 char *name, *mode, *cipher, *digest;
735 myself->connection = new_connection();
736 init_configuration(&myself->connection->config_tree);
738 asprintf(&myself->hostname, _("MYSELF"));
739 asprintf(&myself->connection->hostname, _("MYSELF"));
741 myself->connection->options = 0;
742 myself->connection->protocol_version = PROT_CURRENT;
744 if(!get_config_string(lookup_config(config_tree, "Name"), &name)) /* Not acceptable */
746 syslog(LOG_ERR, _("Name for tinc daemon required!"));
752 syslog(LOG_ERR, _("Invalid name for myself!"));
758 myself->connection->name = xstrdup(name);
761 if(read_rsa_private_key())
764 if(read_connection_config(myself->connection))
766 syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
770 if(read_rsa_public_key(myself->connection))
774 if(check_rsa_key(myself->connection->rsa_key))
776 syslog(LOG_ERR, _("Invalid public/private keypair!"));
780 if(!get_config_port(lookup_config(myself->connection->config_tree, "Port"), &myself->port))
783 myself->connection->port = myself->port;
785 /* Read in all the subnets specified in the host configuration file */
787 cfg = lookup_config(myself->connection->config_tree, "Subnet");
791 if(!get_config_subnet(cfg, &subnet))
794 subnet_add(myself, subnet);
796 cfg = lookup_config_next(myself->connection->config_tree, cfg);
800 /* Check some options */
802 if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice))
804 myself->options |= OPTION_INDIRECT;
806 if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice))
808 myself->options |= OPTION_TCPONLY;
810 if(get_config_bool(lookup_config(myself->connection->config_tree, "IndirectData"), &choice))
812 myself->options |= OPTION_INDIRECT;
814 if(get_config_bool(lookup_config(myself->connection->config_tree, "TCPOnly"), &choice))
816 myself->options |= OPTION_TCPONLY;
818 if(myself->options & OPTION_TCPONLY)
819 myself->options |= OPTION_INDIRECT;
821 if(get_config_string(lookup_config(config_tree, "Mode"), &mode))
823 if(!strcasecmp(mode, "router"))
824 routing_mode = RMODE_ROUTER;
825 else if (!strcasecmp(mode, "switch"))
826 routing_mode = RMODE_SWITCH;
827 else if (!strcasecmp(mode, "hub"))
828 routing_mode = RMODE_HUB;
831 syslog(LOG_ERR, _("Invalid routing mode!"));
836 routing_mode = RMODE_ROUTER;
841 if((tcp_socket = setup_listen_socket(myself->port)) < 0)
843 syslog(LOG_ERR, _("Unable to set up a listening TCP socket!"));
847 if((udp_socket = setup_vpn_in_socket(myself->port)) < 0)
849 syslog(LOG_ERR, _("Unable to set up a listening UDP socket!"));
853 /* Generate packet encryption key */
855 if(get_config_string(lookup_config(myself->connection->config_tree, "Cipher"), &cipher))
857 if(!strcasecmp(cipher, "none"))
859 myself->cipher = NULL;
863 if(!(myself->cipher = EVP_get_cipherbyname(cipher)))
865 syslog(LOG_ERR, _("Unrecognized cipher type!"));
871 myself->cipher = EVP_bf_cbc();
874 myself->keylength = myself->cipher->key_len + myself->cipher->iv_len;
876 myself->keylength = 1;
878 myself->key = (char *)xmalloc(myself->keylength);
879 RAND_pseudo_bytes(myself->key, myself->keylength);
881 if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
884 keyexpires = time(NULL) + keylifetime;
886 /* Check if we want to use message authentication codes... */
888 if(get_config_string(lookup_config(myself->connection->config_tree, "Digest"), &digest))
890 if(!strcasecmp(digest, "none"))
892 myself->digest = NULL;
896 if(!(myself->digest = EVP_get_digestbyname(digest)))
898 syslog(LOG_ERR, _("Unrecognized digest type!"));
904 myself->digest = EVP_sha1();
906 if(get_config_int(lookup_config(myself->connection->config_tree, "MACLength"), &myself->maclength))
910 if(myself->maclength > myself->digest->md_size)
912 syslog(LOG_ERR, _("MAC length exceeds size of digest!"));
915 else if (myself->maclength < 0)
917 syslog(LOG_ERR, _("Bogus MAC length!"));
923 myself->maclength = 4;
927 myself->nexthop = myself;
928 myself->via = myself;
929 myself->status.active = 1;
934 syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
940 setup all initial network connections
942 int setup_network_connections(void)
951 if(get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
961 if(setup_device() < 0)
964 /* Run tinc-up script to further initialize the tap interface */
965 execute_script("tinc-up");
967 if(setup_myself() < 0)
970 try_outgoing_connections();
976 close all open network connections
978 void close_network_connections(void)
980 avl_node_t *node, *next;
983 for(node = connection_tree->head; node; node = next)
986 c = (connection_t *)node->data;
988 free(c->outgoing->name), free(c->outgoing);
989 terminate_connection(c, 0);
992 if(myself && myself->connection)
993 terminate_connection(myself->connection, 0);
1004 execute_script("tinc-down");
1012 handle an incoming tcp connect call and open
1015 connection_t *create_new_connection(int sfd)
1018 struct sockaddr_in ci;
1019 int len = sizeof(ci);
1021 c = new_connection();
1023 if(getpeername(sfd, (struct sockaddr *) &ci, (socklen_t *) &len) < 0)
1025 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1031 c->address = ntohl(ci.sin_addr.s_addr);
1032 c->hostname = hostlookup(ci.sin_addr.s_addr);
1033 c->port = htons(ci.sin_port);
1035 c->last_ping_time = time(NULL);
1037 if(debug_lvl >= DEBUG_CONNECTIONS)
1038 syslog(LOG_NOTICE, _("Connection from %s port %d"),
1039 c->hostname, c->port);
1041 c->allow_request = ID;
1047 put all file descriptors in an fd_set array
1049 void build_fdset(fd_set *fs)
1056 for(node = connection_tree->head; node; node = node->next)
1058 c = (connection_t *)node->data;
1059 FD_SET(c->socket, fs);
1062 FD_SET(tcp_socket, fs);
1063 FD_SET(udp_socket, fs);
1064 FD_SET(device_fd, fs);
1069 receive incoming data from the listening
1070 udp socket and write it to the ethertap
1071 device after being decrypted
1073 void handle_incoming_vpn_data(void)
1076 int x, l = sizeof(x);
1077 struct sockaddr_in from;
1078 socklen_t fromlen = sizeof(from);
1081 if(getsockopt(udp_socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1083 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1084 __FILE__, __LINE__, udp_socket);
1089 syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1093 if((pkt.len = recvfrom(udp_socket, (char *)&pkt.seqno, MAXSIZE, 0, (struct sockaddr *)&from, &fromlen)) <= 0)
1095 syslog(LOG_ERR, _("Receiving packet failed: %m"));
1099 n = lookup_node_udp(ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
1103 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));
1109 n->connection->last_ping_time = time(NULL);
1111 receive_udppacket(n, &pkt);
1115 /* Purge edges and subnets of unreachable nodes. Use carefully. */
1119 avl_node_t *nnode, *nnext, *enode, *enext, *snode, *snext, *cnode;
1125 if(debug_lvl >= DEBUG_PROTOCOL)
1126 syslog(LOG_DEBUG, _("Purging unreachable nodes"));
1128 for(nnode = node_tree->head; nnode; nnode = nnext)
1130 nnext = nnode->next;
1131 n = (node_t *)nnode->data;
1133 if(!n->status.reachable)
1135 if(debug_lvl >= DEBUG_SCARY_THINGS)
1136 syslog(LOG_DEBUG, _("Purging node %s (%s)"), n->name, n->hostname);
1138 for(snode = n->subnet_tree->head; snode; snode = snext)
1140 snext = snode->next;
1141 s = (subnet_t *)snode->data;
1143 for(cnode = connection_tree->head; cnode; cnode = cnode->next)
1145 c = (connection_t *)cnode->data;
1146 if(c->status.active)
1147 send_del_subnet(c, s);
1153 for(enode = n->edge_tree->head; enode; enode = enext)
1155 enext = enode->next;
1156 e = (edge_t *)enode->data;
1158 for(cnode = connection_tree->head; cnode; cnode = cnode->next)
1160 c = (connection_t *)cnode->data;
1161 if(c->status.active)
1162 send_del_edge(c, e);
1175 Terminate a connection:
1177 - Remove associated edge and tell other connections about it if report = 1
1178 - Check if we need to retry making an outgoing connection
1179 - Deactivate the host
1181 void terminate_connection(connection_t *c, int report)
1184 connection_t *other;
1186 if(c->status.remove)
1189 if(debug_lvl >= DEBUG_CONNECTIONS)
1190 syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1191 c->name, c->hostname);
1193 c->status.remove = 1;
1202 for(node = connection_tree->head; node; node = node->next)
1204 other = (connection_t *)node->data;
1205 if(other->status.active && other != c)
1206 send_del_edge(other, c->edge);
1213 /* Run MST and SSSP algorithms */
1217 /* Check if this was our outgoing connection */
1221 retry_outgoing(c->outgoing);
1227 c->status.active = 0;
1229 c->node->connection = NULL;
1235 Check if the other end is active.
1236 If we have sent packets, but didn't receive any,
1237 then possibly the other end is dead. We send a
1238 PING request over the meta connection. If the other
1239 end does not reply in time, we consider them dead
1240 and close the connection.
1242 void check_dead_connections(void)
1245 avl_node_t *node, *next;
1250 for(node = connection_tree->head; node; node = next)
1253 c = (connection_t *)node->data;
1254 if(c->last_ping_time + pingtimeout < now)
1256 if(c->status.active)
1258 if(c->status.pinged)
1260 if(debug_lvl >= DEBUG_PROTOCOL)
1261 syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1262 c->name, c->hostname);
1263 c->status.timeout = 1;
1264 terminate_connection(c, 1);
1273 if(debug_lvl >= DEBUG_CONNECTIONS)
1274 syslog(LOG_WARNING, _("Timeout from %s (%s) during authentication"),
1275 c->name, c->hostname);
1276 terminate_connection(c, 0);
1284 accept a new tcp connect and create a
1287 int handle_new_meta_connection()
1290 struct sockaddr client;
1291 int fd, len = sizeof(client);
1293 if((fd = accept(tcp_socket, &client, &len)) < 0)
1295 syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1299 if(!(new = create_new_connection(fd)))
1303 syslog(LOG_NOTICE, _("Closed attempted connection"));
1307 connection_add(new);
1314 void try_outgoing_connections(void)
1316 static config_t *cfg = NULL;
1318 outgoing_t *outgoing;
1320 for(cfg = lookup_config(config_tree, "ConnectTo"); cfg; cfg = lookup_config_next(config_tree, cfg))
1322 get_config_string(cfg, &name);
1326 syslog(LOG_ERR, _("Invalid name for outgoing connection in %s line %d"), cfg->file, cfg->line);
1331 outgoing = xmalloc_and_zero(sizeof(*outgoing));
1332 outgoing->name = name;
1333 setup_outgoing_connection(outgoing);
1338 check all connections to see if anything
1339 happened on their sockets
1341 void check_network_activity(fd_set *f)
1346 if(FD_ISSET(udp_socket, f))
1347 handle_incoming_vpn_data();
1349 for(node = connection_tree->head; node; node = node->next)
1351 c = (connection_t *)node->data;
1353 if(c->status.remove)
1356 if(FD_ISSET(c->socket, f))
1357 if(receive_meta(c) < 0)
1359 terminate_connection(c, c->status.active);
1364 if(FD_ISSET(tcp_socket, f))
1365 handle_new_meta_connection();
1369 void prune_connections(void)
1372 avl_node_t *node, *next;
1374 for(node = connection_tree->head; node; node = next)
1377 c = (connection_t *)node->data;
1379 if(c->status.remove)
1383 if(!connection_tree->head)
1389 this is where it all happens...
1391 void main_loop(void)
1396 time_t last_ping_check;
1399 vpn_packet_t packet;
1401 last_ping_check = time(NULL);
1407 tv.tv_sec = 1 + (rand() & 7); /* Approx. 5 seconds, randomized to prevent global synchronisation effects */
1412 prune_connections();
1418 if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1420 if(errno != EINTR) /* because of a signal */
1422 syslog(LOG_ERR, _("Error while waiting for input: %m"));
1429 syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1431 close_network_connections();
1432 exit_configuration(&config_tree);
1434 if(read_server_config())
1436 syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1442 if(setup_network_connections())
1456 /* Let's check if everybody is still alive */
1458 if(last_ping_check + pingtimeout < t)
1460 check_dead_connections();
1461 last_ping_check = time(NULL);
1463 /* Should we regenerate our key? */
1467 if(debug_lvl >= DEBUG_STATUS)
1468 syslog(LOG_INFO, _("Regenerating symmetric key"));
1470 RAND_pseudo_bytes(myself->key, myself->keylength);
1471 send_key_changed(myself->connection, myself);
1472 keyexpires = time(NULL) + keylifetime;
1478 syslog(LOG_INFO, _("Flushing event queue"));
1480 while(event_tree->head)
1482 event = (event_t *)event_tree->head->data;
1483 event->handler(event->data);
1489 while((event = get_expired_event()))
1491 event->handler(event->data);
1497 check_network_activity(&fset);
1499 /* local tap data */
1500 if(FD_ISSET(device_fd, &fset))
1502 if(!read_packet(&packet))
1503 route_outgoing(&packet);