2 net.c -- most of the network code
3 Copyright (C) 1998-2001 Ivo Timmermans <itimmermans@bigfoot.com>,
4 2000,2001 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.151 2001/11/16 22:41:38 zarq 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>
53 #ifndef HAVE_RAND_PSEUDO_BYTES
54 #define RAND_pseudo_bytes RAND_bytes
63 #include "connection.h"
76 int seconds_till_retry = 5;
88 char *hostlookup(struct sockaddr *addr, int numericonly)
96 || (get_config_bool(lookup_config(config_tree, "ResolveDNS"), &r)
98 flags |= NI_NUMERICHOST;
100 hostname = xmalloc(NI_MAXHOST);
102 if((r = getnameinfo(addr, sizeof(*addr), hostname, NI_MAXHOST, NULL, 0, flags)) != 0)
105 if(flags & NI_NUMERICHOST)
107 syslog(LOG_ERR, _("Address conversion failed: %s"),
112 return hostlookup(addr, 1);
118 void receive_udppacket(node_t *n, vpn_packet_t *inpkt)
124 /* Decrypt the packet */
126 EVP_DecryptInit(&ctx, myself->cipher, myself->key, myself->key + myself->cipher->key_len);
127 EVP_DecryptUpdate(&ctx, outpkt.salt, &outlen, inpkt->salt, inpkt->len);
128 EVP_DecryptFinal(&ctx, outpkt.salt + outlen, &outpad);
130 outpkt.len = outlen - sizeof(outpkt.salt);
132 receive_packet(n, &outpkt);
136 void receive_tcppacket(connection_t *c, char *buffer, int len)
141 memcpy(outpkt.data, buffer, len);
143 receive_packet(c->node, &outpkt);
147 void receive_packet(node_t *n, vpn_packet_t *packet)
150 if(debug_lvl >= DEBUG_TRAFFIC)
151 syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"), packet->len, n->name, n->hostname);
153 route_incoming(n, packet);
157 void send_udppacket(node_t *n, vpn_packet_t *inpkt)
164 if(!n->status.validkey)
166 if(debug_lvl >= DEBUG_TRAFFIC)
167 syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
168 n->name, n->hostname);
170 /* Since packet is on the stack of handle_tap_input(),
171 we have to make a copy of it first. */
173 copy = xmalloc(sizeof(vpn_packet_t));
174 memcpy(copy, inpkt, sizeof(vpn_packet_t));
176 list_insert_tail(n->queue, copy);
178 if(!n->status.waitingforkey)
179 send_req_key(n->nexthop->connection, myself, n);
183 /* Encrypt the packet. */
185 RAND_pseudo_bytes(inpkt->salt, sizeof(inpkt->salt));
187 EVP_EncryptInit(&ctx, n->cipher, n->key, n->key + n->cipher->key_len);
188 EVP_EncryptUpdate(&ctx, outpkt.salt, &outlen, inpkt->salt, inpkt->len + sizeof(inpkt->salt));
189 EVP_EncryptFinal(&ctx, outpkt.salt + outlen, &outpad);
192 if((sendto(udp_socket, (char *) outpkt.salt, outlen, 0, n->address->ai_addr, n->address->ai_addrlen)) < 0)
194 syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
195 n->name, n->hostname);
202 send a packet to the given vpn ip.
204 void send_packet(node_t *n, vpn_packet_t *packet)
207 if(debug_lvl >= DEBUG_TRAFFIC)
208 syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
209 packet->len, n->name, n->hostname);
213 if(debug_lvl >= DEBUG_TRAFFIC)
215 syslog(LOG_NOTICE, _("Packet is looping back to us!"));
221 if(n->via != n && debug_lvl >= DEBUG_TRAFFIC)
222 syslog(LOG_ERR, _("Sending packet to %s via %s (%s)"),
223 n->name, n->via->name, n->via->hostname);
225 if((myself->options | n->via->options) & OPTION_TCPONLY)
227 if(send_tcppacket(n->via->connection, packet))
228 terminate_connection(n->via->connection, 1);
231 send_udppacket(n->via, packet);
234 /* Broadcast a packet to all active direct connections */
236 void broadcast_packet(node_t *from, vpn_packet_t *packet)
241 if(debug_lvl >= DEBUG_TRAFFIC)
242 syslog(LOG_INFO, _("Broadcasting packet of %d bytes from %s (%s)"),
243 packet->len, from->name, from->hostname);
245 for(node = connection_tree->head; node; node = node->next)
247 c = (connection_t *)node->data;
248 if(c->status.active && c != from->nexthop->connection)
249 send_packet(c->node, packet);
254 void flush_queue(node_t *n)
256 list_node_t *node, *next;
258 if(debug_lvl >= DEBUG_TRAFFIC)
259 syslog(LOG_INFO, _("Flushing queue for %s (%s)"), n->name, n->hostname);
261 for(node = n->queue->head; node; node = next)
264 send_udppacket(n, (vpn_packet_t *)node->data);
265 list_delete_node(n->queue, node);
272 int setup_listen_socket(node_t *n)
278 struct addrinfo hints, *ai, *aitop;
286 if(!get_config_string(lookup_config(config_tree, "BindToAddress"), &address))
291 hints.ai_socktype = SOCK_STREAM;
292 hints.ai_protocol = IPPROTO_TCP;
293 hints.ai_family = AF_INET;
294 if(get_config_bool(lookup_config(config_tree, "IPv6Preferred"), &ipv6preferred))
297 hints.ai_family = PF_UNSPEC;
299 if((r = getaddrinfo(address, n->port, &hints, &aitop)) != 0)
301 syslog(LOG_ERR, _("Looking up `%s' failed: %s\n"),
302 address, gai_strerror(r));
306 /* Try to create a listening socket for all alternatives we got from
308 for(ai = aitop; ai != NULL; ai = ai->ai_next)
310 if((nfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)) < 0)
312 syslog(LOG_ERR, _("Creating metasocket failed: %m"));
316 flags = fcntl(nfd, F_GETFL);
317 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
320 syslog(LOG_ERR, _("System call `%s' failed: %m"),
325 /* Optimize TCP settings */
328 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
329 setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
331 setsockopt(nfd, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
333 option = IPTOS_LOWDELAY;
334 setsockopt(nfd, SOL_IP, IP_TOS, &option, sizeof(option));
336 if(get_config_string(lookup_config(config_tree, "BindToInterface"), &interface))
337 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, interface, strlen(interface)))
340 syslog(LOG_ERR, _("Can't bind to interface %s: %m"), interface);
345 if(bind(nfd, ai->ai_addr, ai->ai_addrlen))
348 syslog(LOG_ERR, _("Can't bind to %s port %s/tcp: %m"),
349 ai->ai_canonname, n->port);
356 syslog(LOG_ERR, _("System call `%s' failed: %m"),
361 break; /* We have successfully bound to a socket */
364 if(ai == NULL) /* None of the alternatives succeeded */
366 syslog(LOG_ERR, _("Failed to open a listening socket."));
373 int setup_vpn_in_socket(node_t *n)
380 struct addrinfo hints, *ai, *aitop;
388 if(!get_config_string(lookup_config(config_tree, "BindToAddress"), &address))
393 hints.ai_socktype = SOCK_DGRAM;
394 hints.ai_protocol = IPPROTO_UDP;
395 hints.ai_family = AF_INET;
396 if(get_config_bool(lookup_config(config_tree, "IPv6Preferred"), &ipv6preferred))
399 hints.ai_family = PF_UNSPEC;
401 if((r = getaddrinfo(address, n->port, &hints, &aitop)) != 0)
403 syslog(LOG_ERR, _("Looking up `%s' failed: %s\n"),
404 address, gai_strerror(r));
408 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
410 /* Try to create a listening socket for all alternatives we got from
412 for(ai = aitop; ai != NULL; ai = ai->ai_next)
414 if((nfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)) < 0)
416 syslog(LOG_ERR, _("Creating metasocket failed: %m"));
420 flags = fcntl(nfd, F_GETFL);
421 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
424 syslog(LOG_ERR, _("System call `%s' failed: %m"),
429 /* Optimize UDP settings */
432 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
434 if(get_config_string(lookup_config(config_tree, "BindToInterface"), &interface))
435 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, interface, strlen(interface)))
438 syslog(LOG_ERR, _("Can't bind to interface %s: %m"), interface);
443 if(bind(nfd, ai->ai_addr, ai->ai_addrlen))
446 syslog(LOG_ERR, _("Can't bind to %s port %s/tcp: %m"),
447 ai->ai_canonname, n->port);
451 break; /* We have successfully bound to a socket */
454 if(ai == NULL) /* None of the alternatives succeeded */
456 syslog(LOG_ERR, _("Failed to open a listening socket."));
463 int setup_outgoing_socket(connection_t *c)
467 if(debug_lvl >= DEBUG_CONNECTIONS)
468 syslog(LOG_INFO, _("Trying to connect to %s (%s)"), c->name, c->hostname);
470 c->socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
474 syslog(LOG_ERR, _("Creating socket for %s port %s failed: %m"),
475 c->hostname, c->port);
479 /* Bind first to get a fix on our source port???
481 a.sin_family = AF_INET;
482 a.sin_port = htons(0);
483 a.sin_addr.s_addr = htonl(INADDR_ANY);
485 if(bind(c->socket, (struct sockaddr *)&a, sizeof(struct sockaddr)))
488 syslog(LOG_ERR, _("System call `%s' failed: %m"), "bind");
494 /* Optimize TCP settings?
497 setsockopt(c->socket, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
499 setsockopt(c->socket, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
501 option = IPTOS_LOWDELAY;
502 setsockopt(c->socket, SOL_IP, IP_TOS, &option, sizeof(option));
509 if(connect(c->socket, c->address->ai_addr, c->address->ai_addrlen) == -1)
512 syslog(LOG_ERR, _("%s port %s: %m"), c->hostname, c->port);
516 flags = fcntl(c->socket, F_GETFL);
518 if(fcntl(c->socket, F_SETFL, flags | O_NONBLOCK) < 0)
521 syslog(LOG_ERR, _("fcntl for %s port %s: %m"),
522 c->hostname, c->port);
526 if(debug_lvl >= DEBUG_CONNECTIONS)
527 syslog(LOG_INFO, _("Connected to %s port %s"),
528 c->hostname, c->port);
533 int setup_outgoing_connection(char *name)
537 struct addrinfo *ai, *aitop, hints;
538 int r, ipv6preferred;
541 n = lookup_node(name);
546 if(debug_lvl >= DEBUG_CONNECTIONS)
547 syslog(LOG_INFO, _("Already connected to %s"), name);
551 c = new_connection();
552 c->name = xstrdup(name);
554 init_configuration(&c->config_tree);
555 read_connection_config(c);
557 if(!get_config_string(lookup_config(c->config_tree, "Address"), &c->hostname))
559 syslog(LOG_ERR, _("No address specified for %s"), c->name);
564 if(!get_config_string(lookup_config(c->config_tree, "Port"), &c->port))
566 syslog(LOG_ERR, _("No port specified for %s"), c->name);
571 hints.ai_socktype = SOCK_STREAM;
572 hints.ai_family = AF_INET;
573 if(get_config_bool(lookup_config(c->config_tree, "IPv6Preferred"), &ipv6preferred))
576 hints.ai_family = PF_UNSPEC;
579 if((r = getaddrinfo(c->hostname, c->port, &hints, &aitop)) != 0)
581 syslog(LOG_ERR, _("Looking up %s failed: %s\n"),
582 c->hostname, gai_strerror(r));
586 for(ai = aitop; ai != NULL; ai = ai->ai_next)
588 if(setup_outgoing_socket(c) < 0)
594 /* No connection alternative succeeded */
599 c->status.outgoing = 1;
600 c->last_ping_time = time(NULL);
609 int read_rsa_public_key(connection_t *c)
616 c->rsa_key = RSA_new();
618 /* First, check for simple PublicKey statement */
620 if(get_config_string(lookup_config(c->config_tree, "PublicKey"), &key))
622 BN_hex2bn(&c->rsa_key->n, key);
623 BN_hex2bn(&c->rsa_key->e, "FFFF");
627 /* Else, check for PublicKeyFile statement and read it */
629 if(get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &fname))
631 if(is_safe_path(fname))
633 if((fp = fopen(fname, "r")) == NULL)
635 syslog(LOG_ERR, _("Error reading RSA public key file `%s': %m"),
639 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
643 syslog(LOG_ERR, _("Reading RSA public key file `%s' failed: %m"),
653 /* Else, check if a harnessed public key is in the config file */
655 asprintf(&fname, "%s/hosts/%s", confbase, c->name);
656 if((fp = fopen(fname, "r")))
658 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
668 syslog(LOG_ERR, _("No public key for %s specified!"), c->name);
673 int read_rsa_private_key(void)
678 if(get_config_string(lookup_config(config_tree, "PrivateKey"), &key))
680 myself->connection->rsa_key = RSA_new();
681 BN_hex2bn(&myself->connection->rsa_key->d, key);
682 BN_hex2bn(&myself->connection->rsa_key->e, "FFFF");
684 else if(get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname))
686 if((fp = fopen(fname, "r")) == NULL)
688 syslog(LOG_ERR, _("Error reading RSA private key file `%s': %m"),
692 myself->connection->rsa_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
694 if(!myself->connection->rsa_key)
696 syslog(LOG_ERR, _("Reading RSA private key file `%s' failed: %m"),
703 syslog(LOG_ERR, _("No private key for tinc daemon specified!"));
711 Configure node_t myself and set up the local sockets (listen only)
713 int setup_myself(void)
721 myself->connection = new_connection();
722 init_configuration(&myself->connection->config_tree);
724 asprintf(&myself->hostname, _("MYSELF"));
725 asprintf(&myself->connection->hostname, _("MYSELF"));
727 myself->connection->options = 0;
728 myself->connection->protocol_version = PROT_CURRENT;
730 if(!get_config_string(lookup_config(config_tree, "Name"), &name)) /* Not acceptable */
732 syslog(LOG_ERR, _("Name for tinc daemon required!"));
738 syslog(LOG_ERR, _("Invalid name for myself!"));
744 myself->connection->name = xstrdup(name);
747 if(read_rsa_private_key())
750 if(read_connection_config(myself->connection))
752 syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
756 if(read_rsa_public_key(myself->connection))
761 if(RSA_check_key(rsa_key) != 1)
763 syslog(LOG_ERR, _("Invalid public/private keypair!"));
767 if(!get_config_string(lookup_config(myself->connection->config_tree, "Port"), &myself->port))
768 myself->port = "655";
770 myself->connection->port = myself->port;
772 /* Read in all the subnets specified in the host configuration file */
774 cfg = lookup_config(myself->connection->config_tree, "Subnet");
778 if(!get_config_subnet(cfg, &subnet))
781 subnet_add(myself, subnet);
783 cfg = lookup_config_next(myself->connection->config_tree, cfg);
787 /* Check some options */
789 if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice))
791 myself->options |= OPTION_INDIRECT;
793 if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice))
795 myself->options |= OPTION_TCPONLY;
797 if(get_config_bool(lookup_config(myself->connection->config_tree, "IndirectData"), &choice))
799 myself->options |= OPTION_INDIRECT;
801 if(get_config_bool(lookup_config(myself->connection->config_tree, "TCPOnly"), &choice))
803 myself->options |= OPTION_TCPONLY;
805 if(myself->options & OPTION_TCPONLY)
806 myself->options |= OPTION_INDIRECT;
808 if(get_config_string(lookup_config(config_tree, "Mode"), &mode))
810 if(!strcasecmp(mode, "router"))
811 routing_mode = RMODE_ROUTER;
812 else if (!strcasecmp(mode, "switch"))
813 routing_mode = RMODE_SWITCH;
814 else if (!strcasecmp(mode, "hub"))
815 routing_mode = RMODE_HUB;
818 syslog(LOG_ERR, _("Invalid routing mode!"));
823 routing_mode = RMODE_ROUTER;
828 if((tcp_socket = setup_listen_socket(myself)) < 0)
830 syslog(LOG_ERR, _("Unable to set up a listening TCP socket!"));
834 if((udp_socket = setup_vpn_in_socket(myself)) < 0)
836 syslog(LOG_ERR, _("Unable to set up a listening UDP socket!"));
840 /* Generate packet encryption key */
842 myself->cipher = EVP_bf_cbc();
844 myself->keylength = myself->cipher->key_len + myself->cipher->iv_len;
846 myself->key = (char *)xmalloc(myself->keylength);
847 RAND_pseudo_bytes(myself->key, myself->keylength);
849 if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
852 keyexpires = time(NULL) + keylifetime;
856 myself->nexthop = myself;
857 myself->via = myself;
858 myself->status.active = 1;
861 syslog(LOG_NOTICE, _("Ready: listening on port %s"), myself->port);
867 setup all initial network connections
869 int setup_network_connections(void)
877 if(get_config_int(lookup_config(config_tree, "PingTimeout"), &timeout))
887 if(setup_device() < 0)
890 /* Run tinc-up script to further initialize the tap interface */
891 execute_script("tinc-up");
893 if(setup_myself() < 0)
896 signal(SIGALRM, try_outgoing_connections);
903 close all open network connections
905 void close_network_connections(void)
907 avl_node_t *node, *next;
910 for(node = connection_tree->head; node; node = next)
913 c = (connection_t *)node->data;
914 c->status.outgoing = 0;
915 terminate_connection(c, 0);
918 terminate_connection(myself->connection, 0);
928 execute_script("tinc-down");
936 handle an incoming tcp connect call and open
939 connection_t *create_new_connection(int sfd)
942 struct sockaddr_in ci;
943 int len = sizeof(ci);
945 c = new_connection();
947 if(getpeername(sfd, (struct sockaddr *) &ci, (socklen_t *) &len) < 0)
949 syslog(LOG_ERR, _("System call `%s' failed: %m"),
955 c->address = sockaddr_to_addrinfo(ci);
957 c->hostname = xmalloc(INET6_ADDRSTRLEN);
958 if((inet_ntop(ci.sin_family, &(ci.sin_addr), c->hostname, INET6_ADDRSTRLEN)) == NULL)
960 syslog(LOG_ERR, _("Couldn't convert address to string: %m"));
964 asprintf(&(c->port), "%d", htons(ci.sin_port));
966 c->last_ping_time = time(NULL);
968 if(debug_lvl >= DEBUG_CONNECTIONS)
969 syslog(LOG_NOTICE, _("Connection from %s port %s"),
970 c->hostname, c->port);
972 c->allow_request = ID;
978 put all file descriptors in an fd_set array
980 void build_fdset(fd_set *fs)
987 for(node = connection_tree->head; node; node = node->next)
989 c = (connection_t *)node->data;
990 FD_SET(c->socket, fs);
993 FD_SET(tcp_socket, fs);
994 FD_SET(udp_socket, fs);
995 FD_SET(device_fd, fs);
1000 receive incoming data from the listening
1001 udp socket and write it to the ethertap
1002 device after being decrypted
1004 void handle_incoming_vpn_data(void)
1007 int x, l = sizeof(x);
1008 struct sockaddr_in from;
1009 socklen_t fromlen = sizeof(from);
1012 if(getsockopt(udp_socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1014 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1015 __FILE__, __LINE__, udp_socket);
1020 syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1024 if((pkt.len = recvfrom(udp_socket, (char *) pkt.salt, MTU, 0, (struct sockaddr *)&from, &fromlen)) <= 0)
1026 syslog(LOG_ERR, _("Receiving packet failed: %m"));
1030 n = lookup_node_udp(sockaddr_to_addrinfo(&from));
1034 syslog(LOG_WARNING, _("Received UDP packet on port %s from unknown source %x:%hd"), myself->port, ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
1039 n->connection->last_ping_time = time(NULL);
1041 receive_udppacket(n, &pkt);
1046 Terminate a connection:
1048 - Remove associated edge and tell other connections about it if report = 1
1049 - Check if we need to retry making an outgoing connection
1050 - Deactivate the host
1052 void terminate_connection(connection_t *c, int report)
1055 connection_t *other;
1057 if(c->status.remove)
1060 if(debug_lvl >= DEBUG_CONNECTIONS)
1061 syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1062 c->name, c->hostname);
1064 c->status.remove = 1;
1073 for(node = connection_tree->head; node; node = node->next)
1075 other = (connection_t *)node->data;
1076 if(other->status.active && other != c)
1077 send_del_edge(other, c->edge);
1084 /* Check if this was our outgoing connection */
1086 if(c->status.outgoing)
1088 c->status.outgoing = 0;
1089 signal(SIGALRM, try_outgoing_connections);
1090 alarm(seconds_till_retry);
1091 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
1096 c->status.active = 0;
1098 c->node->connection = NULL;
1104 Check if the other end is active.
1105 If we have sent packets, but didn't receive any,
1106 then possibly the other end is dead. We send a
1107 PING request over the meta connection. If the other
1108 end does not reply in time, we consider them dead
1109 and close the connection.
1111 void check_dead_connections(void)
1114 avl_node_t *node, *next;
1119 for(node = connection_tree->head; node; node = next)
1122 c = (connection_t *)node->data;
1123 if(c->last_ping_time + timeout < now)
1125 if(c->status.active)
1127 if(c->status.pinged)
1129 if(debug_lvl >= DEBUG_PROTOCOL)
1130 syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1131 c->name, c->hostname);
1132 c->status.timeout = 1;
1133 terminate_connection(c, 1);
1142 if(debug_lvl >= DEBUG_CONNECTIONS)
1143 syslog(LOG_WARNING, _("Timeout from %s (%s) during authentication"),
1144 c->name, c->hostname);
1145 terminate_connection(c, 0);
1153 accept a new tcp connect and create a
1156 int handle_new_meta_connection()
1159 struct sockaddr client;
1160 int fd, len = sizeof(client);
1162 if((fd = accept(tcp_socket, &client, &len)) < 0)
1164 syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1168 if(!(new = create_new_connection(fd)))
1172 syslog(LOG_NOTICE, _("Closed attempted connection"));
1176 connection_add(new);
1183 void randomized_alarm(int seconds)
1186 RAND_pseudo_bytes(&r, 1);
1187 alarm((seconds * (int)r) / 128 + 1);
1190 /* This function is severely fucked up.
1191 We want to redesign it so the following rules apply:
1193 - Try all ConnectTo's in a row:
1194 - if a connect() fails, try next one immediately,
1195 - if it works, wait 5 seconds or so.
1196 - If none of them were succesful, increase delay and retry.
1197 - If all were succesful, don't try anymore.
1201 try_outgoing_connections(int a)
1203 static config_t *cfg = NULL;
1204 static int retry = 0;
1208 cfg = lookup_config(config_tree, "ConnectTo");
1215 get_config_string(cfg, &name);
1219 syslog(LOG_ERR, _("Invalid name for outgoing connection in %s line %d"), cfg->file, cfg->line);
1223 if(setup_outgoing_connection(name)) /* function returns 0 when there are no problems */
1226 cfg = lookup_config_next(config_tree, cfg); /* Next time skip to next ConnectTo line */
1229 get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout);
1233 seconds_till_retry += 5;
1234 if(seconds_till_retry > maxtimeout) /* Don't wait more than MAXTIMEOUT seconds. */
1235 seconds_till_retry = maxtimeout;
1237 syslog(LOG_ERR, _("Failed to setup any outgoing connection, will retry in %d seconds"),
1238 seconds_till_retry);
1240 /* Randomize timeout to avoid global synchronisation effects */
1241 randomized_alarm(seconds_till_retry);
1245 seconds_till_retry = 5;
1251 check all connections to see if anything
1252 happened on their sockets
1254 void check_network_activity(fd_set *f)
1259 if(FD_ISSET(udp_socket, f))
1260 handle_incoming_vpn_data();
1262 for(node = connection_tree->head; node; node = node->next)
1264 c = (connection_t *)node->data;
1266 if(c->status.remove)
1269 if(FD_ISSET(c->socket, f))
1270 if(receive_meta(c) < 0)
1272 terminate_connection(c, c->status.active);
1277 if(FD_ISSET(tcp_socket, f))
1278 handle_new_meta_connection();
1282 void prune_connections(void)
1285 avl_node_t *node, *next;
1287 for(node = connection_tree->head; node; node = next)
1290 c = (connection_t *)node->data;
1292 if(c->status.remove)
1299 this is where it all happens...
1301 void main_loop(void)
1306 time_t last_ping_check;
1308 vpn_packet_t packet;
1310 last_ping_check = time(NULL);
1314 tv.tv_sec = timeout;
1319 prune_connections();
1325 if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1327 if(errno != EINTR) /* because of alarm */
1329 syslog(LOG_ERR, _("Error while waiting for input: %m"));
1336 syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1338 close_network_connections();
1339 exit_configuration(&config_tree);
1341 if(read_server_config())
1343 syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1349 if(setup_network_connections())
1357 /* Let's check if everybody is still alive */
1359 if(last_ping_check + timeout < t)
1361 check_dead_connections();
1362 last_ping_check = time(NULL);
1364 /* Should we regenerate our key? */
1368 if(debug_lvl >= DEBUG_STATUS)
1369 syslog(LOG_INFO, _("Regenerating symmetric key"));
1371 RAND_pseudo_bytes(myself->key, myself->keylength);
1372 send_key_changed(myself->connection, myself);
1373 keyexpires = time(NULL) + keylifetime;
1379 check_network_activity(&fset);
1381 /* local tap data */
1382 if(FD_ISSET(device_fd, &fset))
1384 if(read_packet(&packet))
1387 route_outgoing(&packet);