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.115 2001/06/21 16:16:31 guus Exp $
28 #include <netinet/in.h>
30 #include <netinet/ip.h>
31 #include <netinet/tcp.h>
36 #include <sys/signal.h>
38 #include <sys/types.h>
41 #include <sys/ioctl.h>
42 /* SunOS really wants sys/socket.h BEFORE net/if.h,
43 and FreeBSD wants these lines below the rest. */
44 #include <arpa/inet.h>
45 #include <sys/socket.h>
48 #ifdef HAVE_OPENSSL_RAND_H
49 # include <openssl/rand.h>
54 #ifdef HAVE_OPENSSL_EVP_H
55 # include <openssl/evp.h>
60 #ifdef HAVE_OPENSSL_ERR_H
61 # include <openssl/err.h>
66 #ifdef HAVE_OPENSSL_PEM_H
67 # include <openssl/pem.h>
75 #include LINUX_IF_TUN_H
85 #include "connection.h"
98 int taptype = TAP_TYPE_ETHERTAP;
100 int total_tap_out = 0;
101 int total_socket_in = 0;
102 int total_socket_out = 0;
104 config_t *upstreamcfg;
105 int seconds_till_retry = 5;
110 void send_udppacket(connection_t *cl, vpn_packet_t *inpkt)
115 struct sockaddr_in to;
116 socklen_t tolen = sizeof(to);
119 if(!cl->status.validkey)
121 if(debug_lvl >= DEBUG_TRAFFIC)
122 syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
123 cl->name, cl->hostname);
125 /* Since packet is on the stack of handle_tap_input(),
126 we have to make a copy of it first. */
128 copy = xmalloc(sizeof(vpn_packet_t));
129 memcpy(copy, inpkt, sizeof(vpn_packet_t));
131 list_insert_tail(cl->queue, copy);
133 if(!cl->status.waitingforkey)
134 send_req_key(myself, cl);
138 /* Encrypt the packet. */
140 RAND_bytes(inpkt->salt, sizeof(inpkt->salt));
142 EVP_EncryptInit(&ctx, cl->cipher_pkttype, cl->cipher_pktkey, cl->cipher_pktkey + cl->cipher_pkttype->key_len);
143 EVP_EncryptUpdate(&ctx, outpkt.salt, &outlen, inpkt->salt, inpkt->len + sizeof(inpkt->salt));
144 EVP_EncryptFinal(&ctx, outpkt.salt + outlen, &outpad);
147 total_socket_out += outlen;
149 to.sin_family = AF_INET;
150 to.sin_addr.s_addr = htonl(cl->address);
151 to.sin_port = htons(cl->port);
153 if((sendto(myself->socket, (char *) outpkt.salt, outlen, 0, (const struct sockaddr *)&to, tolen)) < 0)
155 syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
156 cl->name, cl->hostname);
162 void receive_packet(connection_t *cl, vpn_packet_t *packet)
165 if(debug_lvl >= DEBUG_TRAFFIC)
166 syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"), packet->len, cl->name, cl->hostname);
168 route_incoming(cl, packet);
172 void receive_udppacket(connection_t *cl, vpn_packet_t *inpkt)
178 /* Decrypt the packet */
180 EVP_DecryptInit(&ctx, myself->cipher_pkttype, myself->cipher_pktkey, myself->cipher_pktkey + myself->cipher_pkttype->key_len);
181 EVP_DecryptUpdate(&ctx, outpkt.salt, &outlen, inpkt->salt, inpkt->len);
182 EVP_DecryptFinal(&ctx, outpkt.salt + outlen, &outpad);
184 outpkt.len = outlen - sizeof(outpkt.salt);
186 total_socket_in += outlen;
188 receive_packet(cl, &outpkt);
192 void receive_tcppacket(connection_t *cl, char *buffer, int len)
197 memcpy(outpkt.data, buffer, len);
199 receive_packet(cl, &outpkt);
203 void accept_packet(vpn_packet_t *packet)
206 if(debug_lvl >= DEBUG_TRAFFIC)
207 syslog(LOG_DEBUG, _("Writing packet of %d bytes to tap device"),
210 if(taptype == TAP_TYPE_TUNTAP)
212 if(write(tap_fd, packet->data, packet->len) < 0)
213 syslog(LOG_ERR, _("Can't write to tun/tap device: %m"));
215 total_tap_out += packet->len;
219 if(write(tap_fd, packet->data - 2, packet->len + 2) < 0)
220 syslog(LOG_ERR, _("Can't write to ethertap device: %m"));
222 total_tap_out += packet->len;
228 send a packet to the given vpn ip.
230 void send_packet(connection_t *cl, vpn_packet_t *packet)
233 if(debug_lvl >= DEBUG_TRAFFIC)
234 syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
235 packet->len, cl->name, cl->hostname);
239 if(debug_lvl >= DEBUG_TRAFFIC)
241 syslog(LOG_NOTICE, _("Packet is looping back to us!"));
247 if(!cl->status.active)
249 if(debug_lvl >= DEBUG_TRAFFIC)
250 syslog(LOG_INFO, _("%s (%s) is not active, dropping packet"),
251 cl->name, cl->hostname);
256 /* Check if it has to go via TCP or UDP... */
258 if((cl->options | myself->options) & OPTION_TCPONLY)
260 if(send_tcppacket(cl, packet))
261 terminate_connection(cl);
264 send_udppacket(cl, packet);
267 /* Broadcast a packet to all active connections */
269 void broadcast_packet(connection_t *from, vpn_packet_t *packet)
274 if(debug_lvl >= DEBUG_TRAFFIC)
275 syslog(LOG_INFO, _("Broadcasting packet of %d bytes from %s (%s)"),
276 packet->len, from->name, from->hostname);
278 for(node = connection_tree->head; node; node = node->next)
280 cl = (connection_t *)node->data;
281 if(cl->status.meta && cl != from)
282 send_packet(cl, packet);
287 void flush_queue(connection_t *cl)
289 list_node_t *node, *next;
291 if(debug_lvl >= DEBUG_TRAFFIC)
292 syslog(LOG_INFO, _("Flushing queue for %s (%s)"), cl->name, cl->hostname);
294 for(node = cl->queue->head; node; node = next)
297 send_udppacket(cl, (vpn_packet_t *)node->data);
298 list_delete_node(cl->queue, node);
304 open the local ethertap device
306 int setup_tap_fd(void)
309 const char *tapfname;
318 if((cfg = get_config_val(config, config_tapdevice)))
319 tapfname = cfg->data.ptr;
324 tapfname = "/dev/net/tun";
326 tapfname = "/dev/tap0";
330 tapfname = "/dev/tap0";
333 tapfname = "/dev/tun";
337 if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
339 syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
345 taptype = TAP_TYPE_ETHERTAP;
347 /* Set default MAC address for ethertap devices */
349 mymac.type = SUBNET_MAC;
350 mymac.net.mac.address.x[0] = 0xff;
351 mymac.net.mac.address.x[1] = 0xff;
352 mymac.net.mac.address.x[2] = 0xff;
353 mymac.net.mac.address.x[3] = 0xff;
354 mymac.net.mac.address.x[4] = 0xff;
355 mymac.net.mac.address.x[5] = 0xff;
359 /* Ok now check if this is an old ethertap or a new tun/tap thingie */
360 memset(&ifr, 0, sizeof(ifr));
362 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
364 strncpy(ifr.ifr_name, netname, IFNAMSIZ);
366 if (!ioctl(tap_fd, TUNSETIFF, (void *) &ifr))
368 syslog(LOG_INFO, _("%s is a new style tun/tap device"), tapfname);
369 taptype = TAP_TYPE_TUNTAP;
374 taptype = TAP_TYPE_TUNTAP;
381 set up the socket that we listen on for incoming
384 int setup_listen_meta_socket(int port)
387 struct sockaddr_in a;
391 if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
393 syslog(LOG_ERR, _("Creating metasocket failed: %m"));
397 flags = fcntl(nfd, F_GETFL);
398 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
401 syslog(LOG_ERR, _("System call `%s' failed: %m"),
406 /* Optimize TCP settings */
409 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
410 setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
412 setsockopt(nfd, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
414 option = IPTOS_LOWDELAY;
415 setsockopt(nfd, SOL_IP, IP_TOS, &option, sizeof(option));
417 if((cfg = get_config_val(config, config_interface)))
419 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, cfg->data.ptr, strlen(cfg->data.ptr)))
422 syslog(LOG_ERR, _("Unable to bind listen socket to interface %s: %m"), cfg->data.ptr);
428 memset(&a, 0, sizeof(a));
429 a.sin_family = AF_INET;
430 a.sin_port = htons(port);
432 if((cfg = get_config_val(config, config_interfaceip)))
433 a.sin_addr.s_addr = htonl(cfg->data.ip->address);
435 a.sin_addr.s_addr = htonl(INADDR_ANY);
437 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
440 syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
447 syslog(LOG_ERR, _("System call `%s' failed: %m"),
456 setup the socket for incoming encrypted
459 int setup_vpn_in_socket(int port)
462 struct sockaddr_in a;
465 if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
468 syslog(LOG_ERR, _("Creating socket failed: %m"));
472 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
474 flags = fcntl(nfd, F_GETFL);
475 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
478 syslog(LOG_ERR, _("System call `%s' failed: %m"),
483 memset(&a, 0, sizeof(a));
484 a.sin_family = AF_INET;
485 a.sin_port = htons(port);
486 a.sin_addr.s_addr = htonl(INADDR_ANY);
488 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
491 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
499 setup an outgoing meta (tcp) socket
501 int setup_outgoing_meta_socket(connection_t *cl)
504 struct sockaddr_in a;
508 if(debug_lvl >= DEBUG_CONNECTIONS)
509 syslog(LOG_INFO, _("Trying to connect to %s"), cl->hostname);
511 if((cfg = get_config_val(cl->config, config_port)) == NULL)
514 cl->port = cfg->data.val;
516 cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
517 if(cl->meta_socket == -1)
519 syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
520 cl->hostname, cl->port);
524 /* Bind first to get a fix on our source port */
526 a.sin_family = AF_INET;
527 a.sin_port = htons(0);
528 a.sin_addr.s_addr = htonl(INADDR_ANY);
530 if(bind(cl->meta_socket, (struct sockaddr *)&a, sizeof(struct sockaddr)))
532 close(cl->meta_socket);
533 syslog(LOG_ERR, _("System call `%s' failed: %m"), "bind");
537 /* Optimize TCP settings */
540 setsockopt(cl->meta_socket, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
542 setsockopt(cl->meta_socket, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
544 option = IPTOS_LOWDELAY;
545 setsockopt(cl->meta_socket, SOL_IP, IP_TOS, &option, sizeof(option));
549 a.sin_family = AF_INET;
550 a.sin_port = htons(cl->port);
551 a.sin_addr.s_addr = htonl(cl->address);
553 if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
555 close(cl->meta_socket);
556 syslog(LOG_ERR, _("%s port %hd: %m"), cl->hostname, cl->port);
560 flags = fcntl(cl->meta_socket, F_GETFL);
561 if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
563 close(cl->meta_socket);
564 syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
565 cl->hostname, cl->port);
569 if(debug_lvl >= DEBUG_CONNECTIONS)
570 syslog(LOG_INFO, _("Connected to %s port %hd"),
571 cl->hostname, cl->port);
579 Setup an outgoing meta connection.
581 int setup_outgoing_connection(char *name)
589 syslog(LOG_ERR, _("Invalid name for outgoing connection"));
593 ncn = new_connection();
594 asprintf(&ncn->name, "%s", name);
596 if(read_host_config(ncn))
598 syslog(LOG_ERR, _("Error reading host configuration file for %s"), ncn->name);
599 free_connection(ncn);
603 if(!(cfg = get_config_val(ncn->config, config_address)))
605 syslog(LOG_ERR, _("No address specified for %s"), ncn->name);
606 free_connection(ncn);
610 if(!(h = gethostbyname(cfg->data.ptr)))
612 syslog(LOG_ERR, _("Error looking up `%s': %m"), cfg->data.ptr);
613 free_connection(ncn);
617 ncn->address = ntohl(*((ipv4_t*)(h->h_addr_list[0])));
618 ncn->hostname = hostlookup(htonl(ncn->address));
620 if(setup_outgoing_meta_socket(ncn) < 0)
622 syslog(LOG_ERR, _("Could not set up a meta connection to %s"),
624 free_connection(ncn);
628 ncn->status.outgoing = 1;
629 ncn->buffer = xmalloc(MAXBUFSIZE);
631 ncn->last_ping_time = time(NULL);
640 int read_rsa_public_key(connection_t *cl)
648 cl->rsa_key = RSA_new();
650 /* First, check for simple PublicKey statement */
652 if((cfg = get_config_val(cl->config, config_publickey)))
654 BN_hex2bn(&cl->rsa_key->n, cfg->data.ptr);
655 BN_hex2bn(&cl->rsa_key->e, "FFFF");
659 /* Else, check for PublicKeyFile statement and read it */
661 if((cfg = get_config_val(cl->config, config_publickeyfile)))
663 if(is_safe_path(cfg->data.ptr))
665 if((fp = fopen(cfg->data.ptr, "r")) == NULL)
667 syslog(LOG_ERR, _("Error reading RSA public key file `%s': %m"),
671 result = PEM_read_RSAPublicKey(fp, &cl->rsa_key, NULL, NULL);
675 syslog(LOG_ERR, _("Reading RSA public key file `%s' failed: %m"),
685 /* Else, check if a harnessed public key is in the config file */
687 asprintf(&fname, "%s/hosts/%s", confbase, cl->name);
688 if((fp = fopen(fname, "r")))
690 result = PEM_read_RSAPublicKey(fp, &cl->rsa_key, NULL, NULL);
699 /* Nothing worked. */
701 syslog(LOG_ERR, _("No public key for %s specified!"), cl->name);
706 int read_rsa_private_key(void)
713 myself->rsa_key = RSA_new();
715 if((cfg = get_config_val(config, config_privatekey)))
717 BN_hex2bn(&myself->rsa_key->d, cfg->data.ptr);
718 BN_hex2bn(&myself->rsa_key->e, "FFFF");
720 else if((cfg = get_config_val(config, config_privatekeyfile)))
722 if((fp = fopen(cfg->data.ptr, "r")) == NULL)
724 syslog(LOG_ERR, _("Error reading RSA private key file `%s': %m"),
728 result = PEM_read_RSAPrivateKey(fp, &myself->rsa_key, NULL, NULL);
732 syslog(LOG_ERR, _("Reading RSA private key file `%s' failed: %m"),
739 syslog(LOG_ERR, _("No private key for tinc daemon specified!"));
747 Configure connection_t myself and set up the local sockets (listen only)
749 int setup_myself(void)
755 myself = new_connection();
757 asprintf(&myself->hostname, _("MYSELF"));
759 myself->protocol_version = PROT_CURRENT;
761 if(!(cfg = get_config_val(config, config_name))) /* Not acceptable */
763 syslog(LOG_ERR, _("Name for tinc daemon required!"));
767 asprintf(&myself->name, "%s", (char*)cfg->data.val);
769 if(check_id(myself->name))
771 syslog(LOG_ERR, _("Invalid name for myself!"));
775 if(read_rsa_private_key())
778 if(read_host_config(myself))
780 syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
784 if(read_rsa_public_key(myself))
789 if(RSA_check_key(myself->rsa_key) != 1)
791 syslog(LOG_ERR, _("Invalid public/private keypair!"));
795 if(!(cfg = get_config_val(myself->config, config_port)))
798 myself->port = cfg->data.val;
800 /* Read in all the subnets specified in the host configuration file */
802 for(next = myself->config; (cfg = get_config_val(next, config_subnet)); next = cfg->next)
805 net->type = SUBNET_IPV4;
806 net->net.ipv4.address = cfg->data.ip->address;
807 net->net.ipv4.mask = cfg->data.ip->mask;
809 /* Teach newbies what subnets are... */
811 if((net->net.ipv4.address & net->net.ipv4.mask) != net->net.ipv4.address)
813 syslog(LOG_ERR, _("Network address and subnet mask do not match!"));
817 subnet_add(myself, net);
821 /* Check some options */
823 if((cfg = get_config_val(config, config_indirectdata)))
824 if(cfg->data.val == stupid_true)
825 myself->options |= OPTION_INDIRECT;
827 if((cfg = get_config_val(config, config_tcponly)))
828 if(cfg->data.val == stupid_true)
829 myself->options |= OPTION_TCPONLY;
831 if((cfg = get_config_val(myself->config, config_indirectdata)))
832 if(cfg->data.val == stupid_true)
833 myself->options |= OPTION_INDIRECT;
835 if((cfg = get_config_val(myself->config, config_tcponly)))
836 if(cfg->data.val == stupid_true)
837 myself->options |= OPTION_TCPONLY;
839 if(myself->options & OPTION_TCPONLY)
840 myself->options |= OPTION_INDIRECT;
842 if((cfg = get_config_val(config, config_mode)))
844 if(!strcasecmp(cfg->data.ptr, "router"))
845 routing_mode = RMODE_ROUTER;
846 else if (!strcasecmp(cfg->data.ptr, "switch"))
847 routing_mode = RMODE_SWITCH;
848 else if (!strcasecmp(cfg->data.ptr, "hub"))
849 routing_mode = RMODE_HUB;
852 syslog(LOG_ERR, _("Invalid routing mode!"));
857 routing_mode = RMODE_ROUTER;
862 if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
864 syslog(LOG_ERR, _("Unable to set up a listening TCP socket!"));
868 if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
870 syslog(LOG_ERR, _("Unable to set up a listening UDP socket!"));
874 /* Generate packet encryption key */
876 myself->cipher_pkttype = EVP_bf_cbc();
878 myself->cipher_pktkeylength = myself->cipher_pkttype->key_len + myself->cipher_pkttype->iv_len;
880 myself->cipher_pktkey = (char *)xmalloc(myself->cipher_pktkeylength);
881 RAND_pseudo_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
883 if(!(cfg = get_config_val(config, config_keyexpire)))
886 keylifetime = cfg->data.val;
888 keyexpires = time(NULL) + keylifetime;
891 /* Activate ourselves */
893 myself->status.active = 1;
895 syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
901 sigalrm_handler(int a)
905 cfg = get_config_val(upstreamcfg, config_connectto);
909 if(upstreamcfg == config)
911 /* No upstream IP given, we're listen only. */
912 signal(SIGALRM, SIG_IGN);
918 /* We previously tried all the ConnectTo lines. Now wrap back to the first. */
919 cfg = get_config_val(config, config_connectto);
924 upstreamcfg = cfg->next;
925 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
927 signal(SIGALRM, SIG_IGN);
930 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
933 signal(SIGALRM, sigalrm_handler);
934 upstreamcfg = config;
935 seconds_till_retry += 5;
936 if(seconds_till_retry > MAXTIMEOUT) /* Don't wait more than MAXTIMEOUT seconds. */
937 seconds_till_retry = MAXTIMEOUT;
938 syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
940 alarm(seconds_till_retry);
945 setup all initial network connections
947 int setup_network_connections(void)
954 if((cfg = get_config_val(config, config_pingtimeout)) == NULL)
958 timeout = cfg->data.val;
965 if(setup_tap_fd() < 0)
968 /* Run tinc-up script to further initialize the tap interface */
969 execute_script("tinc-up");
971 if(setup_myself() < 0)
974 if(!(cfg = get_config_val(config, config_connectto)))
975 /* No upstream IP given, we're listen only. */
980 upstreamcfg = cfg->next;
981 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
983 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
988 signal(SIGALRM, sigalrm_handler);
989 upstreamcfg = config;
990 seconds_till_retry = MAXTIMEOUT;
991 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
992 alarm(seconds_till_retry);
1002 close all open network connections
1004 void close_network_connections(void)
1009 for(node = connection_tree->head; node; node = node->next)
1011 p = (connection_t *)node->data;
1012 p->status.outgoing = 0;
1013 p->status.active = 0;
1014 terminate_connection(p);
1018 if(myself->status.active)
1020 close(myself->meta_socket);
1021 free_connection(myself);
1027 /* Execute tinc-down script right after shutting down the interface */
1028 execute_script("tinc-down");
1030 destroy_connection_tree();
1036 handle an incoming tcp connect call and open
1039 connection_t *create_new_connection(int sfd)
1042 struct sockaddr_in ci;
1043 int len = sizeof(ci);
1045 p = new_connection();
1047 if(getpeername(sfd, (struct sockaddr *) &ci, (socklen_t *) &len) < 0)
1049 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1055 asprintf(&p->name, _("UNKNOWN"));
1056 p->address = ntohl(ci.sin_addr.s_addr);
1057 p->hostname = hostlookup(ci.sin_addr.s_addr);
1058 p->port = htons(ci.sin_port); /* This one will be overwritten later */
1059 p->meta_socket = sfd;
1061 p->buffer = xmalloc(MAXBUFSIZE);
1063 p->last_ping_time = time(NULL);
1065 if(debug_lvl >= DEBUG_CONNECTIONS)
1066 syslog(LOG_NOTICE, _("Connection from %s port %d"),
1067 p->hostname, htons(ci.sin_port));
1069 p->allow_request = ID;
1075 put all file descriptors in an fd_set array
1077 void build_fdset(fd_set *fs)
1084 FD_SET(myself->socket, fs);
1086 for(node = connection_tree->head; node; node = node->next)
1088 p = (connection_t *)node->data;
1090 FD_SET(p->meta_socket, fs);
1093 FD_SET(myself->meta_socket, fs);
1099 receive incoming data from the listening
1100 udp socket and write it to the ethertap
1101 device after being decrypted
1103 void handle_incoming_vpn_data(void)
1106 int x, l = sizeof(x);
1107 struct sockaddr_in from;
1108 socklen_t fromlen = sizeof(from);
1111 if(getsockopt(myself->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1113 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1114 __FILE__, __LINE__, myself->socket);
1119 syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1123 if((pkt.len = recvfrom(myself->socket, (char *) pkt.salt, MTU, 0, (struct sockaddr *)&from, &fromlen)) <= 0)
1125 syslog(LOG_ERR, _("Receiving packet failed: %m"));
1129 cl = lookup_connection(ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
1133 syslog(LOG_WARNING, _("Received UDP packets on port %hd from unknown source %x:%hd"), myself->port, ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
1137 cl->last_ping_time = time(NULL);
1139 receive_udppacket(cl, &pkt);
1144 terminate a connection and notify the other
1145 end before closing the sockets
1147 void terminate_connection(connection_t *cl)
1151 avl_node_t *node, *next;
1153 if(cl->status.remove)
1156 if(debug_lvl >= DEBUG_CONNECTIONS)
1157 syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1158 cl->name, cl->hostname);
1160 cl->status.remove = 1;
1165 close(cl->meta_socket);
1170 /* Find all connections that were lost because they were behind cl
1171 (the connection that was dropped). */
1173 for(node = connection_tree->head; node; node = node->next)
1175 p = (connection_t *)node->data;
1176 if(p->nexthop == cl && p != cl)
1177 terminate_connection(p);
1180 /* Inform others of termination if it was still active */
1182 if(cl->status.active)
1183 for(node = connection_tree->head; node; node = node->next)
1185 p = (connection_t *)node->data;
1186 if(p->status.meta && p->status.active && p != cl)
1187 send_del_host(p, cl); /* Sounds like recursion, but p does not have a meta connection :) */
1191 /* Remove the associated subnets */
1193 for(node = cl->subnet_tree->head; node; node = next)
1196 subnet = (subnet_t *)node->data;
1200 /* Check if this was our outgoing connection */
1202 if(cl->status.outgoing)
1204 cl->status.outgoing = 0;
1205 signal(SIGALRM, sigalrm_handler);
1206 alarm(seconds_till_retry);
1207 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
1212 cl->status.active = 0;
1217 Check if the other end is active.
1218 If we have sent packets, but didn't receive any,
1219 then possibly the other end is dead. We send a
1220 PING request over the meta connection. If the other
1221 end does not reply in time, we consider them dead
1222 and close the connection.
1224 void check_dead_connections(void)
1232 for(node = connection_tree->head; node; node = node->next)
1234 cl = (connection_t *)node->data;
1235 if(cl->status.active && cl->status.meta)
1237 if(cl->last_ping_time + timeout < now)
1239 if(cl->status.pinged)
1241 if(debug_lvl >= DEBUG_PROTOCOL)
1242 syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1243 cl->name, cl->hostname);
1244 cl->status.timeout = 1;
1245 terminate_connection(cl);
1258 accept a new tcp connect and create a
1261 int handle_new_meta_connection()
1264 struct sockaddr client;
1265 int nfd, len = sizeof(client);
1267 if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
1269 syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1273 if(!(ncn = create_new_connection(nfd)))
1277 syslog(LOG_NOTICE, _("Closed attempted connection"));
1281 connection_add(ncn);
1289 check all connections to see if anything
1290 happened on their sockets
1292 void check_network_activity(fd_set *f)
1297 if(FD_ISSET(myself->socket, f))
1298 handle_incoming_vpn_data();
1300 for(node = connection_tree->head; node; node = node->next)
1302 p = (connection_t *)node->data;
1304 if(p->status.remove)
1308 if(FD_ISSET(p->meta_socket, f))
1309 if(receive_meta(p) < 0)
1311 terminate_connection(p);
1316 if(FD_ISSET(myself->meta_socket, f))
1317 handle_new_meta_connection();
1322 read, encrypt and send data that is
1323 available through the ethertap device
1325 void handle_tap_input(void)
1330 if(taptype == TAP_TYPE_TUNTAP)
1332 if((lenin = read(tap_fd, vp.data, MTU)) <= 0)
1334 syslog(LOG_ERR, _("Error while reading from tun/tap device: %m"));
1341 if((lenin = read(tap_fd, vp.data - 2, MTU)) <= 0)
1343 syslog(LOG_ERR, _("Error while reading from ethertap device: %m"));
1349 total_tap_in += vp.len;
1353 if(debug_lvl >= DEBUG_TRAFFIC)
1354 syslog(LOG_WARNING, _("Received short packet from tap device"));
1358 if(debug_lvl >= DEBUG_TRAFFIC)
1360 syslog(LOG_DEBUG, _("Read packet of length %d from tap device"), vp.len);
1363 route_outgoing(&vp);
1368 this is where it all happens...
1370 void main_loop(void)
1375 time_t last_ping_check;
1378 last_ping_check = time(NULL);
1382 tv.tv_sec = timeout;
1385 prune_connection_tree();
1388 if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1390 if(errno != EINTR) /* because of alarm */
1392 syslog(LOG_ERR, _("Error while waiting for input: %m"));
1399 syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1401 close_network_connections();
1402 clear_config(&config);
1404 if(read_server_config())
1406 syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1412 if(setup_network_connections())
1420 /* Let's check if everybody is still alive */
1422 if(last_ping_check + timeout < t)
1424 check_dead_connections();
1425 last_ping_check = time(NULL);
1427 /* Should we regenerate our key? */
1431 if(debug_lvl >= DEBUG_STATUS)
1432 syslog(LOG_INFO, _("Regenerating symmetric key"));
1434 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
1435 send_key_changed(myself, NULL);
1436 keyexpires = time(NULL) + keylifetime;
1442 check_network_activity(&fset);
1444 /* local tap data */
1445 if(FD_ISSET(tap_fd, &fset))