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.112 2001/06/05 19:39:54 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>
73 #include LINUX_IF_TUN_H
82 #include "connection.h"
95 int taptype = TAP_TYPE_ETHERTAP;
97 int total_tap_out = 0;
98 int total_socket_in = 0;
99 int total_socket_out = 0;
101 config_t *upstreamcfg;
102 static int seconds_till_retry;
107 void send_udppacket(connection_t *cl, vpn_packet_t *inpkt)
112 struct sockaddr_in to;
113 socklen_t tolen = sizeof(to);
116 if(!cl->status.validkey)
118 if(debug_lvl >= DEBUG_TRAFFIC)
119 syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
120 cl->name, cl->hostname);
122 /* Since packet is on the stack of handle_tap_input(),
123 we have to make a copy of it first. */
125 copy = xmalloc(sizeof(vpn_packet_t));
126 memcpy(copy, inpkt, sizeof(vpn_packet_t));
128 list_insert_tail(cl->queue, copy);
130 if(!cl->status.waitingforkey)
131 send_req_key(myself, cl);
135 /* Encrypt the packet. */
137 RAND_bytes(inpkt->salt, sizeof(inpkt->salt));
139 EVP_EncryptInit(&ctx, cl->cipher_pkttype, cl->cipher_pktkey, cl->cipher_pktkey + cl->cipher_pkttype->key_len);
140 EVP_EncryptUpdate(&ctx, outpkt.salt, &outlen, inpkt->salt, inpkt->len + sizeof(inpkt->salt));
141 EVP_EncryptFinal(&ctx, outpkt.salt + outlen, &outpad);
144 total_socket_out += outlen;
146 to.sin_family = AF_INET;
147 to.sin_addr.s_addr = htonl(cl->address);
148 to.sin_port = htons(cl->port);
150 if((sendto(myself->socket, (char *) outpkt.salt, outlen, 0, (const struct sockaddr *)&to, tolen)) < 0)
152 syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
153 cl->name, cl->hostname);
159 void receive_packet(connection_t *cl, vpn_packet_t *packet)
162 if(debug_lvl >= DEBUG_TRAFFIC)
163 syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"), packet->len, cl->name, cl->hostname);
165 route_incoming(cl, packet);
169 void receive_udppacket(connection_t *cl, vpn_packet_t *inpkt)
175 /* Decrypt the packet */
177 EVP_DecryptInit(&ctx, myself->cipher_pkttype, myself->cipher_pktkey, myself->cipher_pktkey + myself->cipher_pkttype->key_len);
178 EVP_DecryptUpdate(&ctx, outpkt.salt, &outlen, inpkt->salt, inpkt->len);
179 EVP_DecryptFinal(&ctx, outpkt.salt + outlen, &outpad);
181 outpkt.len = outlen - sizeof(outpkt.salt);
183 receive_packet(cl, &outpkt);
187 void receive_tcppacket(connection_t *cl, char *buffer, int len)
192 memcpy(outpkt.data, buffer, len);
194 receive_packet(cl, &outpkt);
198 void accept_packet(vpn_packet_t *packet)
201 if(debug_lvl >= DEBUG_TRAFFIC)
202 syslog(LOG_DEBUG, _("Writing packet of %d bytes to tap device"),
205 if(taptype == TAP_TYPE_TUNTAP)
207 if(write(tap_fd, packet->data, packet->len) < 0)
208 syslog(LOG_ERR, _("Can't write to tun/tap device: %m"));
210 total_tap_out += packet->len;
214 if(write(tap_fd, packet->data - 2, packet->len + 2) < 0)
215 syslog(LOG_ERR, _("Can't write to ethertap device: %m"));
217 total_tap_out += packet->len;
223 send a packet to the given vpn ip.
225 void send_packet(connection_t *cl, vpn_packet_t *packet)
228 if(debug_lvl >= DEBUG_TRAFFIC)
229 syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
230 packet->len, cl->name, cl->hostname);
234 if(debug_lvl >= DEBUG_TRAFFIC)
236 syslog(LOG_NOTICE, _("Packet is looping back to us!"));
242 if(!cl->status.active)
244 if(debug_lvl >= DEBUG_TRAFFIC)
245 syslog(LOG_INFO, _("%s (%s) is not active, dropping packet"),
246 cl->name, cl->hostname);
251 /* Check if it has to go via TCP or UDP... */
253 if((cl->options | myself->options) & OPTION_TCPONLY)
255 if(send_tcppacket(cl, packet))
256 terminate_connection(cl);
259 send_udppacket(cl, packet);
262 /* Broadcast a packet to all active connections */
264 void broadcast_packet(connection_t *from, vpn_packet_t *packet)
269 if(debug_lvl >= DEBUG_TRAFFIC)
270 syslog(LOG_INFO, _("Broadcasting packet of %d bytes from %s (%s)"),
271 packet->len, from->name, from->hostname);
273 for(node = connection_tree->head; node; node = node->next)
275 cl = (connection_t *)node->data;
276 if(cl->status.meta && cl != from)
277 send_packet(cl, packet);
282 void flush_queue(connection_t *cl)
284 list_node_t *node, *next;
286 if(debug_lvl >= DEBUG_TRAFFIC)
287 syslog(LOG_INFO, _("Flushing queue for %s (%s)"), cl->name, cl->hostname);
289 for(node = cl->queue->head; node; node = next)
292 send_udppacket(cl, (vpn_packet_t *)node->data);
293 list_delete_node(cl->queue, node);
299 open the local ethertap device
301 int setup_tap_fd(void)
304 const char *tapfname;
313 if((cfg = get_config_val(config, config_tapdevice)))
314 tapfname = cfg->data.ptr;
319 tapfname = "/dev/net/tun";
321 tapfname = "/dev/tap0";
325 tapfname = "/dev/tap0";
328 tapfname = "/dev/tun";
332 if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
334 syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
340 taptype = TAP_TYPE_ETHERTAP;
342 /* Set default MAC address for ethertap devices */
344 mymac.type = SUBNET_MAC;
345 mymac.net.mac.address.x[0] = 0xfe;
346 mymac.net.mac.address.x[1] = 0xfd;
347 mymac.net.mac.address.x[2] = 0x00;
348 mymac.net.mac.address.x[3] = 0x00;
349 mymac.net.mac.address.x[4] = 0x00;
350 mymac.net.mac.address.x[5] = 0x00;
354 /* Ok now check if this is an old ethertap or a new tun/tap thingie */
355 memset(&ifr, 0, sizeof(ifr));
357 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
359 strncpy(ifr.ifr_name, netname, IFNAMSIZ);
361 if (!ioctl(tap_fd, TUNSETIFF, (void *) &ifr))
363 syslog(LOG_INFO, _("%s is a new style tun/tap device"), tapfname);
364 taptype = TAP_TYPE_TUNTAP;
369 taptype = TAP_TYPE_TUNTAP;
376 set up the socket that we listen on for incoming
379 int setup_listen_meta_socket(int port)
382 struct sockaddr_in a;
386 if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
388 syslog(LOG_ERR, _("Creating metasocket failed: %m"));
392 flags = fcntl(nfd, F_GETFL);
393 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
396 syslog(LOG_ERR, _("System call `%s' failed: %m"),
401 /* Optimize TCP settings */
404 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
405 setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
407 setsockopt(nfd, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
409 option = IPTOS_LOWDELAY;
410 setsockopt(nfd, SOL_IP, IP_TOS, &option, sizeof(option));
412 if((cfg = get_config_val(config, config_interface)))
414 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, cfg->data.ptr, strlen(cfg->data.ptr)))
417 syslog(LOG_ERR, _("Unable to bind listen socket to interface %s: %m"), cfg->data.ptr);
423 memset(&a, 0, sizeof(a));
424 a.sin_family = AF_INET;
425 a.sin_port = htons(port);
427 if((cfg = get_config_val(config, config_interfaceip)))
428 a.sin_addr.s_addr = htonl(cfg->data.ip->address);
430 a.sin_addr.s_addr = htonl(INADDR_ANY);
432 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
435 syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
442 syslog(LOG_ERR, _("System call `%s' failed: %m"),
451 setup the socket for incoming encrypted
454 int setup_vpn_in_socket(int port)
457 struct sockaddr_in a;
460 if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
463 syslog(LOG_ERR, _("Creating socket failed: %m"));
467 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
469 flags = fcntl(nfd, F_GETFL);
470 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
473 syslog(LOG_ERR, _("System call `%s' failed: %m"),
478 memset(&a, 0, sizeof(a));
479 a.sin_family = AF_INET;
480 a.sin_port = htons(port);
481 a.sin_addr.s_addr = htonl(INADDR_ANY);
483 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
486 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
494 setup an outgoing meta (tcp) socket
496 int setup_outgoing_meta_socket(connection_t *cl)
499 struct sockaddr_in a;
503 if(debug_lvl >= DEBUG_CONNECTIONS)
504 syslog(LOG_INFO, _("Trying to connect to %s"), cl->hostname);
506 if((cfg = get_config_val(cl->config, config_port)) == NULL)
509 cl->port = cfg->data.val;
511 cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
512 if(cl->meta_socket == -1)
514 syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
515 cl->hostname, cl->port);
519 /* Bind first to get a fix on our source port */
521 a.sin_family = AF_INET;
522 a.sin_port = htons(0);
523 a.sin_addr.s_addr = htonl(INADDR_ANY);
525 if(bind(cl->meta_socket, (struct sockaddr *)&a, sizeof(struct sockaddr)))
527 close(cl->meta_socket);
528 syslog(LOG_ERR, _("System call `%s' failed: %m"), "bind");
532 /* Optimize TCP settings */
535 setsockopt(cl->meta_socket, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
537 setsockopt(cl->meta_socket, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
539 option = IPTOS_LOWDELAY;
540 setsockopt(cl->meta_socket, SOL_IP, IP_TOS, &option, sizeof(option));
544 a.sin_family = AF_INET;
545 a.sin_port = htons(cl->port);
546 a.sin_addr.s_addr = htonl(cl->address);
548 if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
550 close(cl->meta_socket);
551 syslog(LOG_ERR, _("%s port %hd: %m"), cl->hostname, cl->port);
555 flags = fcntl(cl->meta_socket, F_GETFL);
556 if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
558 close(cl->meta_socket);
559 syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
560 cl->hostname, cl->port);
564 if(debug_lvl >= DEBUG_CONNECTIONS)
565 syslog(LOG_INFO, _("Connected to %s port %hd"),
566 cl->hostname, cl->port);
574 Setup an outgoing meta connection.
576 int setup_outgoing_connection(char *name)
584 syslog(LOG_ERR, _("Invalid name for outgoing connection"));
588 ncn = new_connection();
589 asprintf(&ncn->name, "%s", name);
591 if(read_host_config(ncn))
593 syslog(LOG_ERR, _("Error reading host configuration file for %s"), ncn->name);
594 free_connection(ncn);
598 if(!(cfg = get_config_val(ncn->config, config_address)))
600 syslog(LOG_ERR, _("No address specified for %s"), ncn->name);
601 free_connection(ncn);
605 if(!(h = gethostbyname(cfg->data.ptr)))
607 syslog(LOG_ERR, _("Error looking up `%s': %m"), cfg->data.ptr);
608 free_connection(ncn);
612 ncn->address = ntohl(*((ipv4_t*)(h->h_addr_list[0])));
613 ncn->hostname = hostlookup(htonl(ncn->address));
615 if(setup_outgoing_meta_socket(ncn) < 0)
617 syslog(LOG_ERR, _("Could not set up a meta connection to %s"),
619 free_connection(ncn);
623 ncn->status.outgoing = 1;
624 ncn->buffer = xmalloc(MAXBUFSIZE);
626 ncn->last_ping_time = time(NULL);
635 int read_rsa_public_key(connection_t *cl)
643 cl->rsa_key = RSA_new();
645 /* First, check for simple PublicKey statement */
647 if((cfg = get_config_val(cl->config, config_publickey)))
649 BN_hex2bn(&cl->rsa_key->n, cfg->data.ptr);
650 BN_hex2bn(&cl->rsa_key->e, "FFFF");
654 /* Else, check for PublicKeyFile statement and read it */
656 if((cfg = get_config_val(cl->config, config_publickeyfile)))
658 if(is_safe_path(cfg->data.ptr))
660 if((fp = fopen(cfg->data.ptr, "r")) == NULL)
662 syslog(LOG_ERR, _("Error reading RSA public key file `%s': %m"),
666 result = PEM_read_RSAPublicKey(fp, &cl->rsa_key, NULL, NULL);
670 syslog(LOG_ERR, _("Reading RSA public key file `%s' failed: %m"),
680 /* Else, check if a harnessed public key is in the config file */
682 asprintf(&fname, "%s/hosts/%s", confbase, cl->name);
683 if((fp = fopen(fname, "r")))
685 result = PEM_read_RSAPublicKey(fp, &cl->rsa_key, NULL, NULL);
694 /* Nothing worked. */
696 syslog(LOG_ERR, _("No public key for %s specified!"), cl->name);
701 int read_rsa_private_key(void)
708 myself->rsa_key = RSA_new();
710 if((cfg = get_config_val(config, config_privatekey)))
712 BN_hex2bn(&myself->rsa_key->d, cfg->data.ptr);
713 BN_hex2bn(&myself->rsa_key->e, "FFFF");
715 else if((cfg = get_config_val(config, config_privatekeyfile)))
717 if((fp = fopen(cfg->data.ptr, "r")) == NULL)
719 syslog(LOG_ERR, _("Error reading RSA private key file `%s': %m"),
723 result = PEM_read_RSAPrivateKey(fp, &myself->rsa_key, NULL, NULL);
727 syslog(LOG_ERR, _("Reading RSA private key file `%s' failed: %m"),
734 syslog(LOG_ERR, _("No private key for tinc daemon specified!"));
742 Configure connection_t myself and set up the local sockets (listen only)
744 int setup_myself(void)
750 myself = new_connection();
752 asprintf(&myself->hostname, _("MYSELF"));
754 myself->protocol_version = PROT_CURRENT;
756 if(!(cfg = get_config_val(config, config_name))) /* Not acceptable */
758 syslog(LOG_ERR, _("Name for tinc daemon required!"));
762 asprintf(&myself->name, "%s", (char*)cfg->data.val);
764 if(check_id(myself->name))
766 syslog(LOG_ERR, _("Invalid name for myself!"));
770 if(read_rsa_private_key())
773 if(read_host_config(myself))
775 syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
779 if(read_rsa_public_key(myself))
784 if(RSA_check_key(myself->rsa_key) != 1)
786 syslog(LOG_ERR, _("Invalid public/private keypair!"));
790 if(!(cfg = get_config_val(myself->config, config_port)))
793 myself->port = cfg->data.val;
795 /* Read in all the subnets specified in the host configuration file */
797 for(next = myself->config; (cfg = get_config_val(next, config_subnet)); next = cfg->next)
800 net->type = SUBNET_IPV4;
801 net->net.ipv4.address = cfg->data.ip->address;
802 net->net.ipv4.mask = cfg->data.ip->mask;
804 /* Teach newbies what subnets are... */
806 if((net->net.ipv4.address & net->net.ipv4.mask) != net->net.ipv4.address)
808 syslog(LOG_ERR, _("Network address and subnet mask do not match!"));
812 subnet_add(myself, net);
816 /* Check some options */
818 if((cfg = get_config_val(config, config_indirectdata)))
819 if(cfg->data.val == stupid_true)
820 myself->options |= OPTION_INDIRECT;
822 if((cfg = get_config_val(config, config_tcponly)))
823 if(cfg->data.val == stupid_true)
824 myself->options |= OPTION_TCPONLY;
826 if((cfg = get_config_val(myself->config, config_indirectdata)))
827 if(cfg->data.val == stupid_true)
828 myself->options |= OPTION_INDIRECT;
830 if((cfg = get_config_val(myself->config, config_tcponly)))
831 if(cfg->data.val == stupid_true)
832 myself->options |= OPTION_TCPONLY;
834 if(myself->options & OPTION_TCPONLY)
835 myself->options |= OPTION_INDIRECT;
837 if((cfg = get_config_val(config, config_mode)))
839 if(!strcasecmp(cfg->data.ptr, "router"))
840 routing_mode = RMODE_ROUTER;
841 else if (!strcasecmp(cfg->data.ptr, "switch"))
842 routing_mode = RMODE_SWITCH;
843 else if (!strcasecmp(cfg->data.ptr, "hub"))
844 routing_mode = RMODE_HUB;
847 syslog(LOG_ERR, _("Invalid routing mode!"));
852 routing_mode = RMODE_ROUTER;
857 if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
859 syslog(LOG_ERR, _("Unable to set up a listening TCP socket!"));
863 if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
865 syslog(LOG_ERR, _("Unable to set up a listening UDP socket!"));
869 /* Generate packet encryption key */
871 myself->cipher_pkttype = EVP_bf_cbc();
873 myself->cipher_pktkeylength = myself->cipher_pkttype->key_len + myself->cipher_pkttype->iv_len;
875 myself->cipher_pktkey = (char *)xmalloc(myself->cipher_pktkeylength);
876 RAND_pseudo_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
878 if(!(cfg = get_config_val(config, config_keyexpire)))
881 keylifetime = cfg->data.val;
883 keyexpires = time(NULL) + keylifetime;
886 /* Activate ourselves */
888 myself->status.active = 1;
890 syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
896 sigalrm_handler(int a)
900 cfg = get_config_val(upstreamcfg, config_connectto);
904 if(upstreamcfg == config)
906 /* No upstream IP given, we're listen only. */
907 signal(SIGALRM, SIG_IGN);
913 /* We previously tried all the ConnectTo lines. Now wrap back to the first. */
914 cfg = get_config_val(config, config_connectto);
919 upstreamcfg = cfg->next;
920 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
922 signal(SIGALRM, SIG_IGN);
925 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
928 signal(SIGALRM, sigalrm_handler);
929 upstreamcfg = config;
930 seconds_till_retry += 5;
931 if(seconds_till_retry > MAXTIMEOUT) /* Don't wait more than MAXTIMEOUT seconds. */
932 seconds_till_retry = MAXTIMEOUT;
933 syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
935 alarm(seconds_till_retry);
940 setup all initial network connections
942 int setup_network_connections(void)
949 if((cfg = get_config_val(config, config_pingtimeout)) == NULL)
953 timeout = cfg->data.val;
960 if(setup_tap_fd() < 0)
963 /* Run tinc-up script to further initialize the tap interface */
964 execute_script("tinc-up");
966 if(setup_myself() < 0)
969 if(!(cfg = get_config_val(config, config_connectto)))
970 /* No upstream IP given, we're listen only. */
975 upstreamcfg = cfg->next;
976 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
978 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
983 signal(SIGALRM, sigalrm_handler);
984 upstreamcfg = config;
985 seconds_till_retry = MAXTIMEOUT;
986 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
987 alarm(seconds_till_retry);
997 close all open network connections
999 void close_network_connections(void)
1004 for(node = connection_tree->head; node; node = node->next)
1006 p = (connection_t *)node->data;
1007 p->status.outgoing = 0;
1008 p->status.active = 0;
1009 terminate_connection(p);
1013 if(myself->status.active)
1015 close(myself->meta_socket);
1016 free_connection(myself);
1022 /* Execute tinc-down script right after shutting down the interface */
1023 execute_script("tinc-down");
1025 destroy_connection_tree();
1031 handle an incoming tcp connect call and open
1034 connection_t *create_new_connection(int sfd)
1037 struct sockaddr_in ci;
1038 int len = sizeof(ci);
1040 p = new_connection();
1042 if(getpeername(sfd, (struct sockaddr *) &ci, (socklen_t *) &len) < 0)
1044 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1050 asprintf(&p->name, _("UNKNOWN"));
1051 p->address = ntohl(ci.sin_addr.s_addr);
1052 p->hostname = hostlookup(ci.sin_addr.s_addr);
1053 p->port = htons(ci.sin_port); /* This one will be overwritten later */
1054 p->meta_socket = sfd;
1056 p->buffer = xmalloc(MAXBUFSIZE);
1058 p->last_ping_time = time(NULL);
1060 if(debug_lvl >= DEBUG_CONNECTIONS)
1061 syslog(LOG_NOTICE, _("Connection from %s port %d"),
1062 p->hostname, htons(ci.sin_port));
1064 p->allow_request = ID;
1070 put all file descriptors in an fd_set array
1072 void build_fdset(fd_set *fs)
1079 FD_SET(myself->socket, fs);
1081 for(node = connection_tree->head; node; node = node->next)
1083 p = (connection_t *)node->data;
1085 FD_SET(p->meta_socket, fs);
1088 FD_SET(myself->meta_socket, fs);
1094 receive incoming data from the listening
1095 udp socket and write it to the ethertap
1096 device after being decrypted
1098 void handle_incoming_vpn_data(void)
1101 int x, l = sizeof(x);
1102 struct sockaddr_in from;
1103 socklen_t fromlen = sizeof(from);
1106 if(getsockopt(myself->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1108 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1109 __FILE__, __LINE__, myself->socket);
1114 syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1118 if((pkt.len = recvfrom(myself->socket, (char *) pkt.salt, MTU, 0, (struct sockaddr *)&from, &fromlen)) <= 0)
1120 syslog(LOG_ERR, _("Receiving packet failed: %m"));
1124 cl = lookup_connection(ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
1128 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));
1132 cl->last_ping_time = time(NULL);
1134 receive_udppacket(cl, &pkt);
1139 terminate a connection and notify the other
1140 end before closing the sockets
1142 void terminate_connection(connection_t *cl)
1146 avl_node_t *node, *next;
1148 if(cl->status.remove)
1151 if(debug_lvl >= DEBUG_CONNECTIONS)
1152 syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1153 cl->name, cl->hostname);
1155 cl->status.remove = 1;
1160 close(cl->meta_socket);
1165 /* Find all connections that were lost because they were behind cl
1166 (the connection that was dropped). */
1168 for(node = connection_tree->head; node; node = node->next)
1170 p = (connection_t *)node->data;
1171 if(p->nexthop == cl && p != cl)
1172 terminate_connection(p);
1175 /* Inform others of termination if it was still active */
1177 if(cl->status.active)
1178 for(node = connection_tree->head; node; node = node->next)
1180 p = (connection_t *)node->data;
1181 if(p->status.meta && p->status.active && p != cl)
1182 send_del_host(p, cl); /* Sounds like recursion, but p does not have a meta connection :) */
1186 /* Remove the associated subnets */
1188 for(node = cl->subnet_tree->head; node; node = next)
1191 subnet = (subnet_t *)node->data;
1195 /* Check if this was our outgoing connection */
1197 if(cl->status.outgoing)
1199 cl->status.outgoing = 0;
1200 signal(SIGALRM, sigalrm_handler);
1201 seconds_till_retry = 5;
1202 alarm(seconds_till_retry);
1203 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
1208 cl->status.active = 0;
1213 Check if the other end is active.
1214 If we have sent packets, but didn't receive any,
1215 then possibly the other end is dead. We send a
1216 PING request over the meta connection. If the other
1217 end does not reply in time, we consider them dead
1218 and close the connection.
1220 void check_dead_connections(void)
1228 for(node = connection_tree->head; node; node = node->next)
1230 cl = (connection_t *)node->data;
1231 if(cl->status.active && cl->status.meta)
1233 if(cl->last_ping_time + timeout < now)
1235 if(cl->status.pinged)
1237 if(debug_lvl >= DEBUG_PROTOCOL)
1238 syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1239 cl->name, cl->hostname);
1240 cl->status.timeout = 1;
1241 terminate_connection(cl);
1254 accept a new tcp connect and create a
1257 int handle_new_meta_connection()
1260 struct sockaddr client;
1261 int nfd, len = sizeof(client);
1263 if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
1265 syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1269 if(!(ncn = create_new_connection(nfd)))
1273 syslog(LOG_NOTICE, _("Closed attempted connection"));
1277 connection_add(ncn);
1285 check all connections to see if anything
1286 happened on their sockets
1288 void check_network_activity(fd_set *f)
1293 if(FD_ISSET(myself->socket, f))
1294 handle_incoming_vpn_data();
1296 for(node = connection_tree->head; node; node = node->next)
1298 p = (connection_t *)node->data;
1300 if(p->status.remove)
1304 if(FD_ISSET(p->meta_socket, f))
1305 if(receive_meta(p) < 0)
1307 terminate_connection(p);
1312 if(FD_ISSET(myself->meta_socket, f))
1313 handle_new_meta_connection();
1318 read, encrypt and send data that is
1319 available through the ethertap device
1321 void handle_tap_input(void)
1326 if(taptype == TAP_TYPE_TUNTAP)
1328 if((lenin = read(tap_fd, vp.data, MTU)) <= 0)
1330 syslog(LOG_ERR, _("Error while reading from tun/tap device: %m"));
1337 if((lenin = read(tap_fd, vp.data - 2, MTU)) <= 0)
1339 syslog(LOG_ERR, _("Error while reading from ethertap device: %m"));
1345 total_tap_in += vp.len;
1349 if(debug_lvl >= DEBUG_TRAFFIC)
1350 syslog(LOG_WARNING, _("Received short packet from tap device"));
1354 if(debug_lvl >= DEBUG_TRAFFIC)
1356 syslog(LOG_DEBUG, _("Read packet of length %d from tap device"), vp.len);
1359 route_outgoing(&vp);
1364 this is where it all happens...
1366 void main_loop(void)
1371 time_t last_ping_check;
1374 last_ping_check = time(NULL);
1378 tv.tv_sec = timeout;
1381 prune_connection_tree();
1384 if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1386 if(errno != EINTR) /* because of alarm */
1388 syslog(LOG_ERR, _("Error while waiting for input: %m"));
1395 syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1397 close_network_connections();
1398 clear_config(&config);
1400 if(read_server_config())
1402 syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1408 if(setup_network_connections())
1416 /* Let's check if everybody is still alive */
1418 if(last_ping_check + timeout < t)
1420 check_dead_connections();
1421 last_ping_check = time(NULL);
1423 /* Should we regenerate our key? */
1427 if(debug_lvl >= DEBUG_STATUS)
1428 syslog(LOG_INFO, _("Regenerating symmetric key"));
1430 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
1431 send_key_changed(myself, NULL);
1432 keyexpires = time(NULL) + keylifetime;
1438 check_network_activity(&fset);
1440 /* local tap data */
1441 if(FD_ISSET(tap_fd, &fset))