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.94 2001/01/13 16:36:21 guus Exp $
28 #include <netinet/in.h>
32 #include <sys/signal.h>
34 #include <sys/types.h>
37 #include <sys/ioctl.h>
38 /* SunOS really wants sys/socket.h BEFORE net/if.h,
39 and FreeBSD wants these lines below the rest. */
40 #include <arpa/inet.h>
41 #include <sys/socket.h>
44 #ifdef HAVE_OPENSSL_RAND_H
45 # include <openssl/rand.h>
50 #ifdef HAVE_OPENSSL_EVP_H
51 # include <openssl/evp.h>
56 #ifdef HAVE_OPENSSL_ERR_H
57 # include <openssl/err.h>
62 #ifdef HAVE_OPENSSL_PEM_H
63 # include <openssl/pem.h>
69 #include LINUX_IF_TUN_H
78 #include "connection.h"
89 int taptype = TAP_TYPE_ETHERTAP;
91 int total_tap_out = 0;
92 int total_socket_in = 0;
93 int total_socket_out = 0;
95 config_t *upstreamcfg;
96 static int seconds_till_retry;
101 char *unknown = NULL;
105 int xsend(connection_t *cl, vpn_packet_t *inpkt)
110 struct sockaddr_in to;
111 socklen_t tolen = sizeof(to);
113 outpkt.len = inpkt->len;
115 /* Encrypt the packet. FIXME: we should use CBC, not CFB. */
117 EVP_EncryptInit(&ctx, cl->cipher_pkttype, cl->cipher_pktkey, cl->cipher_pktkey + cl->cipher_pkttype->key_len);
118 EVP_EncryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len);
119 EVP_EncryptFinal(&ctx, outpkt.data + outlen, &outpad);
120 outlen += outpad + 2;
123 outlen = outpkt.len + 2;
124 memcpy(&outpkt, inpkt, outlen);
127 if(debug_lvl >= DEBUG_TRAFFIC)
128 syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
129 outlen, cl->name, cl->hostname);
131 total_socket_out += outlen;
133 to.sin_family = AF_INET;
134 to.sin_addr.s_addr = htonl(cl->address);
135 to.sin_port = htons(cl->port);
137 if((sendto(myself->socket, (char *) &(outpkt.len), outlen, 0, (const struct sockaddr *)&to, tolen)) < 0)
139 syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
140 cl->name, cl->hostname);
147 int xrecv(connection_t *cl, vpn_packet_t *inpkt)
153 outpkt.len = inpkt->len;
155 /* Decrypt the packet */
157 EVP_DecryptInit(&ctx, myself->cipher_pkttype, myself->cipher_pktkey, myself->cipher_pktkey + myself->cipher_pkttype->key_len);
158 EVP_DecryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len + 8);
159 EVP_DecryptFinal(&ctx, outpkt.data + outlen, &outpad);
163 outlen = outpkt.len+2;
164 memcpy(&outpkt, inpkt, outlen);
167 return receive_packet(cl, &outpkt);
170 int receive_packet(connection_t *cl, vpn_packet_t *packet)
172 if(debug_lvl >= DEBUG_TRAFFIC)
173 syslog(LOG_ERR, _("Writing packet of %d bytes to tap device"),
176 /* Fix mac address */
178 memcpy(packet->data, mymac.net.mac.address.x, 6);
180 if(taptype == TAP_TYPE_TUNTAP)
182 if(write(tap_fd, packet->data, packet->len) < 0)
183 syslog(LOG_ERR, _("Can't write to tun/tap device: %m"));
185 total_tap_out += packet->len;
189 if(write(tap_fd, packet->data - 2, packet->len + 2) < 0)
190 syslog(LOG_ERR, _("Can't write to ethertap device: %m"));
192 total_tap_out += packet->len + 2;
199 send a packet to the given vpn ip.
201 int send_packet(ip_t to, vpn_packet_t *packet)
206 if((subnet = lookup_subnet_ipv4(&to)) == NULL)
208 if(debug_lvl >= DEBUG_TRAFFIC)
210 syslog(LOG_NOTICE, _("Trying to look up %d.%d.%d.%d in connection list failed!"),
221 if(debug_lvl >= DEBUG_TRAFFIC)
223 syslog(LOG_NOTICE, _("Packet with destination %d.%d.%d.%d is looping back to us!"),
230 if(!cl->status.active)
232 if(debug_lvl >= DEBUG_TRAFFIC)
233 syslog(LOG_INFO, _("%s (%s) is not active, dropping packet"),
234 cl->name, cl->hostname);
239 if(!cl->status.validkey)
241 if(debug_lvl >= DEBUG_TRAFFIC)
242 syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
243 cl->name, cl->hostname);
245 list_insert_tail(cl->queue, packet);
247 if(!cl->status.waitingforkey)
248 send_req_key(myself, cl); /* Keys should be sent to the host running the tincd */
252 /* Check if it has to go via UDP or TCP... */
254 if(cl->options & OPTION_TCPONLY)
255 return send_tcppacket(cl, packet);
257 return xsend(cl, packet);
260 void flush_queue(connection_t *cl)
262 list_node_t *node, *next;
264 if(debug_lvl >= DEBUG_TRAFFIC)
265 syslog(LOG_INFO, _("Flushing queue for %s (%s)"), cl->name, cl->hostname);
267 for(node = cl->queue->head; node; node = next)
270 xsend(cl, (vpn_packet_t *)node->data);
271 list_delete_node(cl->queue, node);
276 open the local ethertap device
278 int setup_tap_fd(void)
281 const char *tapfname;
290 if((cfg = get_config_val(config, config_tapdevice)))
291 tapfname = cfg->data.ptr;
296 tapfname = "/dev/misc/net/tun";
298 tapfname = "/dev/tap0";
302 tapfname = "/dev/tap0";
305 tapfname = "/dev/tun";
309 if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
311 syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
317 taptype = TAP_TYPE_ETHERTAP;
319 /* Set default MAC address for ethertap devices */
321 mymac.type = SUBNET_MAC;
322 mymac.net.mac.address.x[0] = 0xfe;
323 mymac.net.mac.address.x[1] = 0xfd;
324 mymac.net.mac.address.x[2] = 0x00;
325 mymac.net.mac.address.x[3] = 0x00;
326 mymac.net.mac.address.x[4] = 0x00;
327 mymac.net.mac.address.x[5] = 0x00;
331 /* Ok now check if this is an old ethertap or a new tun/tap thingie */
332 memset(&ifr, 0, sizeof(ifr));
334 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
336 strncpy(ifr.ifr_name, netname, IFNAMSIZ);
338 if (!ioctl(tap_fd, TUNSETIFF, (void *) &ifr))
340 syslog(LOG_INFO, _("%s is a new style tun/tap device"), tapfname);
341 taptype = TAP_TYPE_TUNTAP;
346 taptype = TAP_TYPE_TUNTAP;
353 set up the socket that we listen on for incoming
356 int setup_listen_meta_socket(int port)
359 struct sockaddr_in a;
363 if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
365 syslog(LOG_ERR, _("Creating metasocket failed: %m"));
369 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
372 syslog(LOG_ERR, _("System call `%s' failed: %m"),
377 if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one)))
380 syslog(LOG_ERR, _("System call `%s' failed: %m"),
385 flags = fcntl(nfd, F_GETFL);
386 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
389 syslog(LOG_ERR, _("System call `%s' failed: %m"),
394 if((cfg = get_config_val(config, config_interface)))
396 if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, cfg->data.ptr, strlen(cfg->data.ptr)))
399 syslog(LOG_ERR, _("Unable to bind listen socket to interface %s: %m"), cfg->data.ptr);
404 memset(&a, 0, sizeof(a));
405 a.sin_family = AF_INET;
406 a.sin_port = htons(port);
408 if((cfg = get_config_val(config, config_interfaceip)))
409 a.sin_addr.s_addr = htonl(cfg->data.ip->address);
411 a.sin_addr.s_addr = htonl(INADDR_ANY);
413 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
416 syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
423 syslog(LOG_ERR, _("System call `%s' failed: %m"),
432 setup the socket for incoming encrypted
435 int setup_vpn_in_socket(int port)
438 struct sockaddr_in a;
441 if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
444 syslog(LOG_ERR, _("Creating socket failed: %m"));
448 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
451 syslog(LOG_ERR, _("System call `%s' failed: %m"),
456 flags = fcntl(nfd, F_GETFL);
457 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
460 syslog(LOG_ERR, _("System call `%s' failed: %m"),
465 memset(&a, 0, sizeof(a));
466 a.sin_family = AF_INET;
467 a.sin_port = htons(port);
468 a.sin_addr.s_addr = htonl(INADDR_ANY);
470 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
473 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
481 setup an outgoing meta (tcp) socket
483 int setup_outgoing_meta_socket(connection_t *cl)
486 struct sockaddr_in a;
489 if(debug_lvl >= DEBUG_CONNECTIONS)
490 syslog(LOG_INFO, _("Trying to connect to %s"), cl->hostname);
492 if((cfg = get_config_val(cl->config, config_port)) == NULL)
495 cl->port = cfg->data.val;
497 cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
498 if(cl->meta_socket == -1)
500 syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
501 cl->hostname, cl->port);
505 /* Bind first to get a fix on our source port */
507 a.sin_family = AF_INET;
508 a.sin_port = htons(0);
509 a.sin_addr.s_addr = htonl(INADDR_ANY);
511 if(bind(cl->meta_socket, (struct sockaddr *)&a, sizeof(struct sockaddr)))
513 close(cl->meta_socket);
514 syslog(LOG_ERR, _("System call `%s' failed: %m"), "bind");
518 a.sin_family = AF_INET;
519 a.sin_port = htons(cl->port);
520 a.sin_addr.s_addr = htonl(cl->address);
522 if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
524 close(cl->meta_socket);
525 syslog(LOG_ERR, _("%s port %hd: %m"), cl->hostname, cl->port);
529 flags = fcntl(cl->meta_socket, F_GETFL);
530 if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
532 close(cl->meta_socket);
533 syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
534 cl->hostname, cl->port);
538 if(debug_lvl >= DEBUG_CONNECTIONS)
539 syslog(LOG_INFO, _("Connected to %s port %hd"),
540 cl->hostname, cl->port);
548 Setup an outgoing meta connection.
550 int setup_outgoing_connection(char *name)
558 syslog(LOG_ERR, _("Invalid name for outgoing connection"));
562 ncn = new_connection();
563 asprintf(&ncn->name, "%s", name);
565 if(read_host_config(ncn))
567 syslog(LOG_ERR, _("Error reading host configuration file for %s"), ncn->name);
568 free_connection(ncn);
572 if(!(cfg = get_config_val(ncn->config, config_address)))
574 syslog(LOG_ERR, _("No address specified for %s"), ncn->name);
575 free_connection(ncn);
579 if(!(h = gethostbyname(cfg->data.ptr)))
581 syslog(LOG_ERR, _("Error looking up `%s': %m"), cfg->data.ptr);
582 free_connection(ncn);
586 ncn->address = ntohl(*((ip_t*)(h->h_addr_list[0])));
587 ncn->hostname = hostlookup(htonl(ncn->address));
589 if(setup_outgoing_meta_socket(ncn) < 0)
591 syslog(LOG_ERR, _("Could not set up a meta connection to %s"),
593 free_connection(ncn);
597 ncn->status.outgoing = 1;
598 ncn->buffer = xmalloc(MAXBUFSIZE);
600 ncn->last_ping_time = time(NULL);
609 int read_rsa_public_key(connection_t *cl)
617 cl->rsa_key = RSA_new();
619 /* First, check for simple PublicKey statement */
621 if((cfg = get_config_val(cl->config, config_publickey)))
623 BN_hex2bn(&cl->rsa_key->n, cfg->data.ptr);
624 BN_hex2bn(&cl->rsa_key->e, "FFFF");
628 /* Else, check for PublicKeyFile statement and read it */
630 if((cfg = get_config_val(cl->config, config_publickeyfile)))
632 if(is_safe_path(cfg->data.ptr))
634 if((fp = fopen(cfg->data.ptr, "r")) == NULL)
636 syslog(LOG_ERR, _("Error reading RSA public key file `%s': %m"),
640 result = PEM_read_RSAPublicKey(fp, &cl->rsa_key, NULL, NULL);
644 syslog(LOG_ERR, _("Reading RSA public key file `%s' failed: %m"),
654 /* Else, check if a harnessed public key is in the config file */
656 asprintf(&fname, "%s/hosts/%s", confbase, cl->name);
657 if((fp = fopen(fname, "r")))
659 result = PEM_read_RSAPublicKey(fp, &cl->rsa_key, NULL, NULL);
668 /* Nothing worked. */
670 syslog(LOG_ERR, _("No public key for %s specified!"), cl->name);
675 int read_rsa_private_key(void)
682 myself->rsa_key = RSA_new();
684 if((cfg = get_config_val(config, config_privatekey)))
686 BN_hex2bn(&myself->rsa_key->d, cfg->data.ptr);
687 BN_hex2bn(&myself->rsa_key->e, "FFFF");
689 else if((cfg = get_config_val(config, config_privatekeyfile)))
691 if((fp = fopen(cfg->data.ptr, "r")) == NULL)
693 syslog(LOG_ERR, _("Error reading RSA private key file `%s': %m"),
697 result = PEM_read_RSAPrivateKey(fp, &myself->rsa_key, NULL, NULL);
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 connection_t myself and set up the local sockets (listen only)
718 int setup_myself(void)
724 myself = new_connection();
726 asprintf(&myself->hostname, "MYSELF");
728 myself->protocol_version = PROT_CURRENT;
730 if(!(cfg = get_config_val(config, config_name))) /* Not acceptable */
732 syslog(LOG_ERR, _("Name for tinc daemon required!"));
736 asprintf(&myself->name, "%s", (char*)cfg->data.val);
738 if(check_id(myself->name))
740 syslog(LOG_ERR, _("Invalid name for myself!"));
744 if(read_rsa_private_key())
747 if(read_host_config(myself))
749 syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
753 if(read_rsa_public_key(myself))
758 if(RSA_check_key(myself->rsa_key) != 1)
760 syslog(LOG_ERR, _("Invalid public/private keypair!"));
764 if(!(cfg = get_config_val(myself->config, config_port)))
767 myself->port = cfg->data.val;
769 if((cfg = get_config_val(myself->config, config_indirectdata)))
770 if(cfg->data.val == stupid_true)
771 myself->flags |= EXPORTINDIRECTDATA;
773 if((cfg = get_config_val(myself->config, config_tcponly)))
774 if(cfg->data.val == stupid_true)
775 myself->flags |= TCPONLY;
777 /* Read in all the subnets specified in the host configuration file */
779 for(next = myself->config; (cfg = get_config_val(next, config_subnet)); next = cfg->next)
782 net->type = SUBNET_IPV4;
783 net->net.ipv4.address = cfg->data.ip->address;
784 net->net.ipv4.mask = cfg->data.ip->mask;
786 /* Teach newbies what subnets are... */
788 if((net->net.ipv4.address & net->net.ipv4.mask) != net->net.ipv4.address)
790 syslog(LOG_ERR, _("Network address and subnet mask do not match!"));
794 subnet_add(myself, net);
797 if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
799 syslog(LOG_ERR, _("Unable to set up a listening TCP socket!"));
803 if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
805 syslog(LOG_ERR, _("Unable to set up a listening UDP socket!"));
809 /* Generate packet encryption key */
811 myself->cipher_pkttype = EVP_bf_cfb();
813 myself->cipher_pktkeylength = myself->cipher_pkttype->key_len + myself->cipher_pkttype->iv_len;
815 myself->cipher_pktkey = (char *)xmalloc(myself->cipher_pktkeylength);
816 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
818 if(!(cfg = get_config_val(config, config_keyexpire)))
821 keylifetime = cfg->data.val;
823 keyexpires = time(NULL) + keylifetime;
825 /* Check some options */
827 if((cfg = get_config_val(config, config_indirectdata)))
829 if(cfg->data.val == stupid_true)
830 myself->options |= OPTION_INDIRECT;
833 if((cfg = get_config_val(config, config_tcponly)))
835 if(cfg->data.val == stupid_true)
836 myself->options |= OPTION_TCPONLY;
838 /* Activate ourselves */
840 myself->status.active = 1;
842 syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
848 sigalrm_handler(int a)
852 cfg = get_config_val(upstreamcfg, config_connectto);
854 if(!cfg && upstreamcfg == config)
855 /* No upstream IP given, we're listen only. */
860 upstreamcfg = cfg->next;
861 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
863 signal(SIGALRM, SIG_IGN);
866 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
869 signal(SIGALRM, sigalrm_handler);
870 upstreamcfg = config;
871 seconds_till_retry += 5;
872 if(seconds_till_retry > MAXTIMEOUT) /* Don't wait more than MAXTIMEOUT seconds. */
873 seconds_till_retry = MAXTIMEOUT;
874 syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
876 alarm(seconds_till_retry);
881 setup all initial network connections
883 int setup_network_connections(void)
890 if((cfg = get_config_val(config, config_pingtimeout)) == NULL)
894 timeout = cfg->data.val;
901 if(setup_tap_fd() < 0)
904 /* Run tinc-up script to further initialize the tap interface */
905 execute_script("tinc-up");
907 if(setup_myself() < 0)
910 if(!(cfg = get_config_val(config, config_connectto)))
911 /* No upstream IP given, we're listen only. */
916 upstreamcfg = cfg->next;
917 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
919 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
922 signal(SIGALRM, sigalrm_handler);
923 upstreamcfg = config;
924 seconds_till_retry = MAXTIMEOUT;
925 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
926 alarm(seconds_till_retry);
932 close all open network connections
934 void close_network_connections(void)
939 for(node = connection_tree->head; node; node = node->next)
941 p = (connection_t *)node->data;
942 p->status.active = 0;
943 terminate_connection(p);
947 if(myself->status.active)
949 close(myself->meta_socket);
950 free_connection(myself);
956 /* Execute tinc-down script right after shutting down the interface */
957 execute_script("tinc-down");
959 destroy_connection_tree();
965 create a data (udp) socket
966 OBSOLETED: use only one listening socket for compatibility with non-Linux operating systems
968 int setup_vpn_connection(connection_t *cl)
971 struct sockaddr_in a;
974 if(debug_lvl >= DEBUG_TRAFFIC)
975 syslog(LOG_DEBUG, _("Opening UDP socket to %s"), cl->hostname);
977 nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
980 syslog(LOG_ERR, _("Creating UDP socket failed: %m"));
984 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
987 syslog(LOG_ERR, _("System call `%s' failed: %m"),
992 flags = fcntl(nfd, F_GETFL);
993 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
996 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1001 memset(&a, 0, sizeof(a));
1002 a.sin_family = AF_INET;
1003 a.sin_port = htons(myself->port);
1004 a.sin_addr.s_addr = htonl(INADDR_ANY);
1006 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
1009 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), myself->port);
1013 a.sin_family = AF_INET;
1014 a.sin_port = htons(cl->port);
1015 a.sin_addr.s_addr = htonl(cl->address);
1017 if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
1020 syslog(LOG_ERR, _("Connecting to %s port %d failed: %m"),
1021 cl->hostname, cl->port);
1025 flags = fcntl(nfd, F_GETFL);
1026 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
1029 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m %s (%s)"), __FILE__, __LINE__, nfd,
1030 cl->name, cl->hostname);
1035 cl->status.dataopen = 1;
1041 handle an incoming tcp connect call and open
1044 connection_t *create_new_connection(int sfd)
1047 struct sockaddr_in ci;
1048 int len = sizeof(ci);
1050 p = new_connection();
1052 if(getpeername(sfd, (struct sockaddr *) &ci, (socklen_t *) &len) < 0)
1054 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1061 p->address = ntohl(ci.sin_addr.s_addr);
1062 p->hostname = hostlookup(ci.sin_addr.s_addr);
1063 p->port = htons(ci.sin_port); /* This one will be overwritten later */
1064 p->meta_socket = sfd;
1066 p->buffer = xmalloc(MAXBUFSIZE);
1068 p->last_ping_time = time(NULL);
1070 if(debug_lvl >= DEBUG_CONNECTIONS)
1071 syslog(LOG_NOTICE, _("Connection from %s port %d"),
1072 p->hostname, htons(ci.sin_port));
1074 p->allow_request = ID;
1080 put all file descriptors in an fd_set array
1082 void build_fdset(fd_set *fs)
1089 FD_SET(myself->socket, fs);
1091 for(node = connection_tree->head; node; node = node->next)
1093 p = (connection_t *)node->data;
1095 FD_SET(p->meta_socket, fs);
1098 FD_SET(myself->meta_socket, fs);
1104 receive incoming data from the listening
1105 udp socket and write it to the ethertap
1106 device after being decrypted
1108 int handle_incoming_vpn_data(void)
1111 int x, l = sizeof(x);
1113 struct sockaddr_in from;
1114 socklen_t fromlen = sizeof(from);
1117 if(getsockopt(myself->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1119 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1120 __FILE__, __LINE__, myself->socket);
1125 syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1129 if((lenin = recvfrom(myself->socket, (char *) &(pkt.len), MTU, 0, (struct sockaddr *)&from, &fromlen)) <= 0)
1131 syslog(LOG_ERR, _("Receiving packet failed: %m"));
1135 cl = lookup_connection(ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
1139 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));
1143 if(debug_lvl >= DEBUG_TRAFFIC)
1145 syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"), lenin,
1146 cl->name, cl->hostname);
1150 return xrecv(cl, &pkt);
1154 terminate a connection and notify the other
1155 end before closing the sockets
1157 void terminate_connection(connection_t *cl)
1161 avl_node_t *node, *next;
1163 if(cl->status.remove)
1166 if(debug_lvl >= DEBUG_CONNECTIONS)
1167 syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1168 cl->name, cl->hostname);
1170 cl->status.remove = 1;
1175 close(cl->meta_socket);
1180 /* Find all connections that were lost because they were behind cl
1181 (the connection that was dropped). */
1183 for(node = connection_tree->head; node; node = node->next)
1185 p = (connection_t *)node->data;
1186 if(p->nexthop == cl && p != cl)
1187 terminate_connection(p);
1190 /* Inform others of termination if it was still active */
1192 if(cl->status.active)
1193 for(node = connection_tree->head; node; node = node->next)
1195 p = (connection_t *)node->data;
1196 if(p->status.meta && p->status.active && p != cl)
1197 send_del_host(p, cl); /* Sounds like recursion, but p does not have a meta connection :) */
1201 /* Remove the associated subnets */
1203 for(node = cl->subnet_tree->head; node; node = next)
1206 subnet = (subnet_t *)node->data;
1210 /* Check if this was our outgoing connection */
1212 if(cl->status.outgoing && cl->status.active)
1214 signal(SIGALRM, sigalrm_handler);
1215 seconds_till_retry = 5;
1216 alarm(seconds_till_retry);
1217 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
1222 cl->status.active = 0;
1227 Check if the other end is active.
1228 If we have sent packets, but didn't receive any,
1229 then possibly the other end is dead. We send a
1230 PING request over the meta connection. If the other
1231 end does not reply in time, we consider them dead
1232 and close the connection.
1234 void check_dead_connections(void)
1242 for(node = connection_tree->head; node; node = node->next)
1244 cl = (connection_t *)node->data;
1245 if(cl->status.active && cl->status.meta)
1247 if(cl->last_ping_time + timeout < now)
1249 if(cl->status.pinged)
1251 if(debug_lvl >= DEBUG_PROTOCOL)
1252 syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1253 cl->name, cl->hostname);
1254 cl->status.timeout = 1;
1255 terminate_connection(cl);
1268 accept a new tcp connect and create a
1271 int handle_new_meta_connection()
1274 struct sockaddr client;
1275 int nfd, len = sizeof(client);
1277 if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
1279 syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1283 if(!(ncn = create_new_connection(nfd)))
1287 syslog(LOG_NOTICE, _("Closed attempted connection"));
1291 connection_add(ncn);
1297 check all connections to see if anything
1298 happened on their sockets
1300 void check_network_activity(fd_set *f)
1305 if(FD_ISSET(myself->socket, f))
1306 handle_incoming_vpn_data();
1308 for(node = connection_tree->head; node; node = node->next)
1310 p = (connection_t *)node->data;
1312 if(p->status.remove)
1316 if(FD_ISSET(p->meta_socket, f))
1317 if(receive_meta(p) < 0)
1319 terminate_connection(p);
1324 if(FD_ISSET(myself->meta_socket, f))
1325 handle_new_meta_connection();
1330 read, encrypt and send data that is
1331 available through the ethertap device
1333 void handle_tap_input(void)
1338 if(taptype == TAP_TYPE_TUNTAP)
1340 if((lenin = read(tap_fd, vp.data, MTU)) <= 0)
1342 syslog(LOG_ERR, _("Error while reading from tun/tap device: %m"));
1349 if((lenin = read(tap_fd, vp.data - 2, MTU)) <= 0)
1351 syslog(LOG_ERR, _("Error while reading from ethertap device: %m"));
1357 total_tap_in += lenin;
1361 if(debug_lvl >= DEBUG_TRAFFIC)
1362 syslog(LOG_WARNING, _("Received short packet from tap device"));
1366 if(debug_lvl >= DEBUG_TRAFFIC)
1368 syslog(LOG_DEBUG, _("Read packet of length %d from tap device"), vp.len);
1371 send_packet(ntohl(*((unsigned long*)(&vp.data[30]))), &vp);
1376 this is where it all happens...
1378 void main_loop(void)
1383 time_t last_ping_check;
1386 last_ping_check = time(NULL);
1390 tv.tv_sec = timeout;
1393 prune_connection_tree();
1396 if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1398 if(errno != EINTR) /* because of alarm */
1400 syslog(LOG_ERR, _("Error while waiting for input: %m"));
1407 syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1409 close_network_connections();
1410 clear_config(&config);
1412 if(read_server_config())
1414 syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1420 if(setup_network_connections())
1428 /* Let's check if everybody is still alive */
1430 if(last_ping_check + timeout < t)
1432 check_dead_connections();
1433 last_ping_check = time(NULL);
1435 /* Should we regenerate our key? */
1439 if(debug_lvl >= DEBUG_STATUS)
1440 syslog(LOG_INFO, _("Regenerating symmetric key"));
1442 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
1443 send_key_changed(myself, NULL);
1444 keyexpires = time(NULL) + keylifetime;
1450 check_network_activity(&fset);
1452 /* local tap data */
1453 if(FD_ISSET(tap_fd, &fset))