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.150 2001/11/16 17:38:39 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)
91 struct hostent *host = NULL;
98 || ((cfg = get_config_val(config, resolve_dns)) == NULL
99 || cfg->data.val != stupid_true))
100 flags |= NI_NUMERICHOST;
102 hostname = xmalloc(NI_MAXHOST);
104 if((r = getnameinfo(addr, sizeof(*addr), &hostname, NI_MAXHOST, NULL, 0, flags)) != 0)
107 if(flags & NI_NUMERICHOST)
109 syslog(LOG_ERR, _("Address conversion failed: %s"),
114 return hostlookup(addr, 1);
120 void receive_udppacket(node_t *n, vpn_packet_t *inpkt)
126 /* Decrypt the packet */
128 EVP_DecryptInit(&ctx, myself->cipher, myself->key, myself->key + myself->cipher->key_len);
129 EVP_DecryptUpdate(&ctx, outpkt.salt, &outlen, inpkt->salt, inpkt->len);
130 EVP_DecryptFinal(&ctx, outpkt.salt + outlen, &outpad);
132 outpkt.len = outlen - sizeof(outpkt.salt);
134 receive_packet(n, &outpkt);
138 void receive_tcppacket(connection_t *c, char *buffer, int len)
143 memcpy(outpkt.data, buffer, len);
145 receive_packet(c->node, &outpkt);
149 void receive_packet(node_t *n, vpn_packet_t *packet)
152 if(debug_lvl >= DEBUG_TRAFFIC)
153 syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"), packet->len, n->name, n->hostname);
155 route_incoming(n, packet);
159 void send_udppacket(node_t *n, vpn_packet_t *inpkt)
164 struct sockaddr_in to;
165 socklen_t tolen = sizeof(to);
168 if(!n->status.validkey)
170 if(debug_lvl >= DEBUG_TRAFFIC)
171 syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
172 n->name, n->hostname);
174 /* Since packet is on the stack of handle_tap_input(),
175 we have to make a copy of it first. */
177 copy = xmalloc(sizeof(vpn_packet_t));
178 memcpy(copy, inpkt, sizeof(vpn_packet_t));
180 list_insert_tail(n->queue, copy);
182 if(!n->status.waitingforkey)
183 send_req_key(n->nexthop->connection, myself, n);
187 /* Encrypt the packet. */
189 RAND_pseudo_bytes(inpkt->salt, sizeof(inpkt->salt));
191 EVP_EncryptInit(&ctx, n->cipher, n->key, n->key + n->cipher->key_len);
192 EVP_EncryptUpdate(&ctx, outpkt.salt, &outlen, inpkt->salt, inpkt->len + sizeof(inpkt->salt));
193 EVP_EncryptFinal(&ctx, outpkt.salt + outlen, &outpad);
196 if((sendto(udp_socket, (char *) outpkt.salt, outlen, 0, n->address->ai_addr, n->address->ai_addrlen)) < 0)
198 syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
199 n->name, n->hostname);
206 send a packet to the given vpn ip.
208 void send_packet(node_t *n, vpn_packet_t *packet)
211 if(debug_lvl >= DEBUG_TRAFFIC)
212 syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
213 packet->len, n->name, n->hostname);
217 if(debug_lvl >= DEBUG_TRAFFIC)
219 syslog(LOG_NOTICE, _("Packet is looping back to us!"));
225 if(n->via != n && debug_lvl >= DEBUG_TRAFFIC)
226 syslog(LOG_ERR, _("Sending packet to %s via %s (%s)"),
227 n->name, n->via->name, n->via->hostname);
229 if((myself->options | n->via->options) & OPTION_TCPONLY)
231 if(send_tcppacket(n->via->connection, packet))
232 terminate_connection(n->via->connection, 1);
235 send_udppacket(n->via, packet);
238 /* Broadcast a packet to all active direct connections */
240 void broadcast_packet(node_t *from, vpn_packet_t *packet)
245 if(debug_lvl >= DEBUG_TRAFFIC)
246 syslog(LOG_INFO, _("Broadcasting packet of %d bytes from %s (%s)"),
247 packet->len, from->name, from->hostname);
249 for(node = connection_tree->head; node; node = node->next)
251 c = (connection_t *)node->data;
252 if(c->status.active && c != from->nexthop->connection)
253 send_packet(c->node, packet);
258 void flush_queue(node_t *n)
260 list_node_t *node, *next;
262 if(debug_lvl >= DEBUG_TRAFFIC)
263 syslog(LOG_INFO, _("Flushing queue for %s (%s)"), n->name, n->hostname);
265 for(node = n->queue->head; node; node = next)
268 send_udppacket(n, (vpn_packet_t *)node->data);
269 list_delete_node(n->queue, node);
276 int setup_listen_socket(node_t *n)
282 struct addrinfo hints, *ai, *aitop;
290 if(!get_config_string(lookup_config(config_tree, "BindToAddress"), &address))
295 hints.ai_socktype = SOCK_STREAM;
296 hints.ai_protocol = IPPROTO_TCP;
297 hints.ai_family = AF_INET;
298 if(get_config_bool(lookup_config(config_tree, "IPv6Preferred"), &ipv6preferred))
301 hints.ai_family = PF_UNSPEC;
303 if((r = getaddrinfo(address, n->port, &hints, &aitop)) != 0)
305 syslog(LOG_ERR, _("Looking up `%s' failed: %s\n"),
306 address, gai_strerror(r));
310 /* Try to create a listening socket for all alternatives we got from
312 for(ai = aitop; ai != NULL; ai = ai->ai_next)
314 if((nfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)) < 0)
316 syslog(LOG_ERR, _("Creating metasocket failed: %m"));
320 flags = fcntl(nfd, F_GETFL);
321 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
324 syslog(LOG_ERR, _("System call `%s' failed: %m"),
329 /* Optimize TCP settings */
332 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
333 setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
335 setsockopt(nfd, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
337 option = IPTOS_LOWDELAY;
338 setsockopt(nfd, SOL_IP, IP_TOS, &option, sizeof(option));
340 if(get_config_string(lookup_config(config_tree, "BindToInterface"), &interface))
341 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, interface, strlen(interface)))
344 syslog(LOG_ERR, _("Can't bind to interface %s: %m"), interface);
349 if(bind(nfd, ai->ai_addr, ai->ai_addrlen))
352 syslog(LOG_ERR, _("Can't bind to %s port %d/tcp: %m"),
353 ai->ai_canonname, n->port);
360 syslog(LOG_ERR, _("System call `%s' failed: %m"),
365 break; /* We have successfully bound to a socket */
368 if(ai == NULL) /* None of the alternatives succeeded */
370 syslog(LOG_ERR, _("Failed to open a listening socket."));
377 int setup_vpn_in_socket(node_t *n)
384 struct addrinfo hints, *ai, *aitop;
392 if(!get_config_string(lookup_config(config_tree, "BindToAddress"), &address))
397 hints.ai_socktype = SOCK_DGRAM;
398 hints.ai_protocol = IPPROTO_UDP;
399 hints.ai_family = AF_INET;
400 if(get_config_bool(lookup_config(config_tree, "IPv6Preferred"), &ipv6preferred))
403 hints.ai_family = PF_UNSPEC;
405 if((r = getaddrinfo(address, n->port, &hints, &aitop)) != 0)
407 syslog(LOG_ERR, _("Looking up `%s' failed: %s\n"),
408 address, gai_strerror(r));
412 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
414 /* Try to create a listening socket for all alternatives we got from
416 for(ai = aitop; ai != NULL; ai = ai->ai_next)
418 if((nfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)) < 0)
420 syslog(LOG_ERR, _("Creating metasocket failed: %m"));
424 flags = fcntl(nfd, F_GETFL);
425 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
428 syslog(LOG_ERR, _("System call `%s' failed: %m"),
433 /* Optimize UDP settings */
436 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
438 if(get_config_string(lookup_config(config_tree, "BindToInterface"), &interface))
439 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, interface, strlen(interface)))
442 syslog(LOG_ERR, _("Can't bind to interface %s: %m"), interface);
447 if(bind(nfd, ai->ai_addr, ai->ai_addrlen))
450 syslog(LOG_ERR, _("Can't bind to %s port %d/tcp: %m"),
451 ai->ai_canonname, n->port);
455 break; /* We have successfully bound to a socket */
458 if(ai == NULL) /* None of the alternatives succeeded */
460 syslog(LOG_ERR, _("Failed to open a listening socket."));
467 int setup_outgoing_socket(connection_t *c)
470 struct sockaddr_in a;
472 if(debug_lvl >= DEBUG_CONNECTIONS)
473 syslog(LOG_INFO, _("Trying to connect to %s (%s)"), c->name, c->hostname);
475 c->socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
479 syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
480 c->hostname, c->port);
484 /* Bind first to get a fix on our source port???
486 a.sin_family = AF_INET;
487 a.sin_port = htons(0);
488 a.sin_addr.s_addr = htonl(INADDR_ANY);
490 if(bind(c->socket, (struct sockaddr *)&a, sizeof(struct sockaddr)))
493 syslog(LOG_ERR, _("System call `%s' failed: %m"), "bind");
499 /* Optimize TCP settings?
502 setsockopt(c->socket, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
504 setsockopt(c->socket, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
506 option = IPTOS_LOWDELAY;
507 setsockopt(c->socket, SOL_IP, IP_TOS, &option, sizeof(option));
514 if(connect(c->socket, c->address->ai_addr, c->address->ai_addrlen) == -1)
517 syslog(LOG_ERR, _("%s port %s: %m"), c->hostname, c->port);
521 flags = fcntl(c->socket, F_GETFL);
523 if(fcntl(c->socket, F_SETFL, flags | O_NONBLOCK) < 0)
526 syslog(LOG_ERR, _("fcntl for %s port %s: %m"),
527 c->hostname, c->port);
531 if(debug_lvl >= DEBUG_CONNECTIONS)
532 syslog(LOG_INFO, _("Connected to %s port %s"),
533 c->hostname, c->port);
538 int setup_outgoing_connection(char *name)
542 struct addrinfo *ai, *aitop, hints;
543 int r, ipv6preferred;
546 n = lookup_node(name);
551 if(debug_lvl >= DEBUG_CONNECTIONS)
552 syslog(LOG_INFO, _("Already connected to %s"), name);
556 c = new_connection();
557 c->name = xstrdup(name);
559 init_configuration(&c->config_tree);
560 read_connection_config(c);
562 if(!get_config_string(lookup_config(c->config_tree, "Address"), &c->hostname))
564 syslog(LOG_ERR, _("No address specified for %s"), c->name);
569 if(!get_config_string(lookup_config(c->config_tree, "Port"), &c->port))
571 syslog(LOG_ERR, _("No port specified for %s"), c->name);
576 hints.ai_socktype = SOCK_STREAM;
577 hints.ai_family = AF_INET;
578 if(get_config_bool(lookup_config(c->config_tree, "IPv6Preferred"), &ipv6preferred))
581 hints.ai_family = PF_UNSPEC;
584 if((r = getaddrinfo(c->hostname, c->port, &hints, &aitop)) != 0)
586 syslog(LOG_ERR, _("Looking up %s failed: %s\n"),
587 c->hostname, gai_strerror(r));
591 for(ai = aitop; ai != NULL; ai = ai->ai_next)
593 if(setup_outgoing_socket(c) < 0)
599 /* No connection alternative succeeded */
604 c->status.outgoing = 1;
605 c->last_ping_time = time(NULL);
614 int read_rsa_public_key(connection_t *c)
621 c->rsa_key = RSA_new();
623 /* First, check for simple PublicKey statement */
625 if(get_config_string(lookup_config(c->config_tree, "PublicKey"), &key))
627 BN_hex2bn(&c->rsa_key->n, key);
628 BN_hex2bn(&c->rsa_key->e, "FFFF");
632 /* Else, check for PublicKeyFile statement and read it */
634 if(get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &fname))
636 if(is_safe_path(fname))
638 if((fp = fopen(fname, "r")) == NULL)
640 syslog(LOG_ERR, _("Error reading RSA public key file `%s': %m"),
644 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
648 syslog(LOG_ERR, _("Reading RSA public key file `%s' failed: %m"),
658 /* Else, check if a harnessed public key is in the config file */
660 asprintf(&fname, "%s/hosts/%s", confbase, c->name);
661 if((fp = fopen(fname, "r")))
663 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
673 syslog(LOG_ERR, _("No public key for %s specified!"), c->name);
678 int read_rsa_private_key(void)
683 if(get_config_string(lookup_config(config_tree, "PrivateKey"), &key))
685 myself->connection->rsa_key = RSA_new();
686 BN_hex2bn(&myself->connection->rsa_key->d, key);
687 BN_hex2bn(&myself->connection->rsa_key->e, "FFFF");
689 else if(get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname))
691 if((fp = fopen(fname, "r")) == NULL)
693 syslog(LOG_ERR, _("Error reading RSA private key file `%s': %m"),
697 myself->connection->rsa_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
699 if(!myself->connection->rsa_key)
701 syslog(LOG_ERR, _("Reading RSA private key file `%s' failed: %m"),
708 syslog(LOG_ERR, _("No private key for tinc daemon specified!"));
716 Configure node_t myself and set up the local sockets (listen only)
718 int setup_myself(void)
726 myself->connection = new_connection();
727 init_configuration(&myself->connection->config_tree);
729 asprintf(&myself->hostname, _("MYSELF"));
730 asprintf(&myself->connection->hostname, _("MYSELF"));
732 myself->connection->options = 0;
733 myself->connection->protocol_version = PROT_CURRENT;
735 if(!get_config_string(lookup_config(config_tree, "Name"), &name)) /* Not acceptable */
737 syslog(LOG_ERR, _("Name for tinc daemon required!"));
743 syslog(LOG_ERR, _("Invalid name for myself!"));
749 myself->connection->name = xstrdup(name);
752 if(read_rsa_private_key())
755 if(read_connection_config(myself->connection))
757 syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
761 if(read_rsa_public_key(myself->connection))
766 if(RSA_check_key(rsa_key) != 1)
768 syslog(LOG_ERR, _("Invalid public/private keypair!"));
772 if(!get_config_string(lookup_config(myself->connection->config_tree, "Port"), &myself->port))
773 myself->port = "655";
775 myself->connection->port = myself->port;
777 /* Read in all the subnets specified in the host configuration file */
779 cfg = lookup_config(myself->connection->config_tree, "Subnet");
783 if(!get_config_subnet(cfg, &subnet))
786 subnet_add(myself, subnet);
788 cfg = lookup_config_next(myself->connection->config_tree, cfg);
792 /* Check some options */
794 if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice))
796 myself->options |= OPTION_INDIRECT;
798 if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice))
800 myself->options |= OPTION_TCPONLY;
802 if(get_config_bool(lookup_config(myself->connection->config_tree, "IndirectData"), &choice))
804 myself->options |= OPTION_INDIRECT;
806 if(get_config_bool(lookup_config(myself->connection->config_tree, "TCPOnly"), &choice))
808 myself->options |= OPTION_TCPONLY;
810 if(myself->options & OPTION_TCPONLY)
811 myself->options |= OPTION_INDIRECT;
813 if(get_config_string(lookup_config(config_tree, "Mode"), &mode))
815 if(!strcasecmp(mode, "router"))
816 routing_mode = RMODE_ROUTER;
817 else if (!strcasecmp(mode, "switch"))
818 routing_mode = RMODE_SWITCH;
819 else if (!strcasecmp(mode, "hub"))
820 routing_mode = RMODE_HUB;
823 syslog(LOG_ERR, _("Invalid routing mode!"));
828 routing_mode = RMODE_ROUTER;
833 if((tcp_socket = setup_listen_socket(myself)) < 0)
835 syslog(LOG_ERR, _("Unable to set up a listening TCP socket!"));
839 if((udp_socket = setup_vpn_in_socket(myself)) < 0)
841 syslog(LOG_ERR, _("Unable to set up a listening UDP socket!"));
845 /* Generate packet encryption key */
847 myself->cipher = EVP_bf_cbc();
849 myself->keylength = myself->cipher->key_len + myself->cipher->iv_len;
851 myself->key = (char *)xmalloc(myself->keylength);
852 RAND_pseudo_bytes(myself->key, myself->keylength);
854 if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
857 keyexpires = time(NULL) + keylifetime;
861 myself->nexthop = myself;
862 myself->via = myself;
863 myself->status.active = 1;
866 syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
872 setup all initial network connections
874 int setup_network_connections(void)
882 if(get_config_int(lookup_config(config_tree, "PingTimeout"), &timeout))
892 if(setup_device() < 0)
895 /* Run tinc-up script to further initialize the tap interface */
896 execute_script("tinc-up");
898 if(setup_myself() < 0)
901 signal(SIGALRM, try_outgoing_connections);
908 close all open network connections
910 void close_network_connections(void)
912 avl_node_t *node, *next;
915 for(node = connection_tree->head; node; node = next)
918 c = (connection_t *)node->data;
919 c->status.outgoing = 0;
920 terminate_connection(c, 0);
923 terminate_connection(myself->connection, 0);
933 execute_script("tinc-down");
941 handle an incoming tcp connect call and open
944 connection_t *create_new_connection(int sfd)
947 struct sockaddr_in ci;
948 int len = sizeof(ci);
950 c = new_connection();
952 if(getpeername(sfd, (struct sockaddr *) &ci, (socklen_t *) &len) < 0)
954 syslog(LOG_ERR, _("System call `%s' failed: %m"),
960 asprintf(&(c->address), " = ntohl(ci.sin_addr.s_addr);
961 c->hostname = hostlookup(ci.sin_addr.s_addr);
962 asprintf(&(c->port), "%d", htons(ci.sin_port));
964 c->last_ping_time = time(NULL);
966 if(debug_lvl >= DEBUG_CONNECTIONS)
967 syslog(LOG_NOTICE, _("Connection from %s port %d"),
968 c->hostname, c->port);
970 c->allow_request = ID;
976 put all file descriptors in an fd_set array
978 void build_fdset(fd_set *fs)
985 for(node = connection_tree->head; node; node = node->next)
987 c = (connection_t *)node->data;
988 FD_SET(c->socket, fs);
991 FD_SET(tcp_socket, fs);
992 FD_SET(udp_socket, fs);
993 FD_SET(device_fd, fs);
998 receive incoming data from the listening
999 udp socket and write it to the ethertap
1000 device after being decrypted
1002 void handle_incoming_vpn_data(void)
1005 int x, l = sizeof(x);
1006 struct sockaddr_in from;
1007 socklen_t fromlen = sizeof(from);
1010 if(getsockopt(udp_socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1012 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1013 __FILE__, __LINE__, udp_socket);
1018 syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1022 if((pkt.len = recvfrom(udp_socket, (char *) pkt.salt, MTU, 0, (struct sockaddr *)&from, &fromlen)) <= 0)
1024 syslog(LOG_ERR, _("Receiving packet failed: %m"));
1028 n = lookup_node_udp(ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
1032 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));
1037 n->connection->last_ping_time = time(NULL);
1039 receive_udppacket(n, &pkt);
1044 Terminate a connection:
1046 - Remove associated edge and tell other connections about it if report = 1
1047 - Check if we need to retry making an outgoing connection
1048 - Deactivate the host
1050 void terminate_connection(connection_t *c, int report)
1053 connection_t *other;
1055 if(c->status.remove)
1058 if(debug_lvl >= DEBUG_CONNECTIONS)
1059 syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1060 c->name, c->hostname);
1062 c->status.remove = 1;
1071 for(node = connection_tree->head; node; node = node->next)
1073 other = (connection_t *)node->data;
1074 if(other->status.active && other != c)
1075 send_del_edge(other, c->edge);
1082 /* Check if this was our outgoing connection */
1084 if(c->status.outgoing)
1086 c->status.outgoing = 0;
1087 signal(SIGALRM, try_outgoing_connections);
1088 alarm(seconds_till_retry);
1089 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
1094 c->status.active = 0;
1096 c->node->connection = NULL;
1102 Check if the other end is active.
1103 If we have sent packets, but didn't receive any,
1104 then possibly the other end is dead. We send a
1105 PING request over the meta connection. If the other
1106 end does not reply in time, we consider them dead
1107 and close the connection.
1109 void check_dead_connections(void)
1112 avl_node_t *node, *next;
1117 for(node = connection_tree->head; node; node = next)
1120 c = (connection_t *)node->data;
1121 if(c->last_ping_time + timeout < now)
1123 if(c->status.active)
1125 if(c->status.pinged)
1127 if(debug_lvl >= DEBUG_PROTOCOL)
1128 syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1129 c->name, c->hostname);
1130 c->status.timeout = 1;
1131 terminate_connection(c, 1);
1140 if(debug_lvl >= DEBUG_CONNECTIONS)
1141 syslog(LOG_WARNING, _("Timeout from %s (%s) during authentication"),
1142 c->name, c->hostname);
1143 terminate_connection(c, 0);
1151 accept a new tcp connect and create a
1154 int handle_new_meta_connection()
1157 struct sockaddr client;
1158 int fd, len = sizeof(client);
1160 if((fd = accept(tcp_socket, &client, &len)) < 0)
1162 syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1166 if(!(new = create_new_connection(fd)))
1170 syslog(LOG_NOTICE, _("Closed attempted connection"));
1174 connection_add(new);
1181 void randomized_alarm(int seconds)
1184 RAND_pseudo_bytes(&r, 1);
1185 alarm((seconds * (int)r) / 128 + 1);
1188 /* This function is severely fucked up.
1189 We want to redesign it so the following rules apply:
1191 - Try all ConnectTo's in a row:
1192 - if a connect() fails, try next one immediately,
1193 - if it works, wait 5 seconds or so.
1194 - If none of them were succesful, increase delay and retry.
1195 - If all were succesful, don't try anymore.
1199 try_outgoing_connections(int a)
1201 static config_t *cfg = NULL;
1202 static int retry = 0;
1206 cfg = lookup_config(config_tree, "ConnectTo");
1213 get_config_string(cfg, &name);
1217 syslog(LOG_ERR, _("Invalid name for outgoing connection in %s line %d"), cfg->file, cfg->line);
1221 if(setup_outgoing_connection(name)) /* function returns 0 when there are no problems */
1224 cfg = lookup_config_next(config._tree, cfg); /* Next time skip to next ConnectTo line */
1227 get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout);
1231 seconds_till_retry += 5;
1232 if(seconds_till_retry > maxtimeout) /* Don't wait more than MAXTIMEOUT seconds. */
1233 seconds_till_retry = maxtimeout;
1235 syslog(LOG_ERR, _("Failed to setup any outgoing connection, will retry in %d seconds"),
1236 seconds_till_retry);
1238 /* Randomize timeout to avoid global synchronisation effects */
1239 randomized_alarm(seconds_till_retry);
1243 seconds_till_retry = 5;
1249 check all connections to see if anything
1250 happened on their sockets
1252 void check_network_activity(fd_set *f)
1257 if(FD_ISSET(udp_socket, f))
1258 handle_incoming_vpn_data();
1260 for(node = connection_tree->head; node; node = node->next)
1262 c = (connection_t *)node->data;
1264 if(c->status.remove)
1267 if(FD_ISSET(c->socket, f))
1268 if(receive_meta(c) < 0)
1270 terminate_connection(c, c->status.active);
1275 if(FD_ISSET(tcp_socket, f))
1276 handle_new_meta_connection();
1280 void prune_connections(void)
1283 avl_node_t *node, *next;
1285 for(node = connection_tree->head; node; node = next)
1288 c = (connection_t *)node->data;
1290 if(c->status.remove)
1297 this is where it all happens...
1299 void main_loop(void)
1304 time_t last_ping_check;
1306 vpn_packet_t packet;
1308 last_ping_check = time(NULL);
1312 tv.tv_sec = timeout;
1317 prune_connections();
1323 if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1325 if(errno != EINTR) /* because of alarm */
1327 syslog(LOG_ERR, _("Error while waiting for input: %m"));
1334 syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1336 close_network_connections();
1337 exit_configuration(&config_tree);
1339 if(read_server_config())
1341 syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1347 if(setup_network_connections())
1355 /* Let's check if everybody is still alive */
1357 if(last_ping_check + timeout < t)
1359 check_dead_connections();
1360 last_ping_check = time(NULL);
1362 /* Should we regenerate our key? */
1366 if(debug_lvl >= DEBUG_STATUS)
1367 syslog(LOG_INFO, _("Regenerating symmetric key"));
1369 RAND_pseudo_bytes(myself->key, myself->keylength);
1370 send_key_changed(myself->connection, myself);
1371 keyexpires = time(NULL) + keylifetime;
1377 check_network_activity(&fset);
1379 /* local tap data */
1380 if(FD_ISSET(device_fd, &fset))
1382 if(read_packet(&packet))
1385 route_outgoing(&packet);