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.99 2001/02/27 16:17:04 guus Exp $
28 #include <netinet/in.h>
29 #include <netinet/ip.h>
30 #include <netinet/tcp.h>
34 #include <sys/signal.h>
36 #include <sys/types.h>
39 #include <sys/ioctl.h>
40 /* SunOS really wants sys/socket.h BEFORE net/if.h,
41 and FreeBSD wants these lines below the rest. */
42 #include <arpa/inet.h>
43 #include <sys/socket.h>
46 #ifdef HAVE_OPENSSL_RAND_H
47 # include <openssl/rand.h>
52 #ifdef HAVE_OPENSSL_EVP_H
53 # include <openssl/evp.h>
58 #ifdef HAVE_OPENSSL_ERR_H
59 # include <openssl/err.h>
64 #ifdef HAVE_OPENSSL_PEM_H
65 # include <openssl/pem.h>
71 #include LINUX_IF_TUN_H
80 #include "connection.h"
91 int taptype = TAP_TYPE_ETHERTAP;
93 int total_tap_out = 0;
94 int total_socket_in = 0;
95 int total_socket_out = 0;
97 config_t *upstreamcfg;
98 static int seconds_till_retry;
103 char *unknown = NULL;
107 int xsend(connection_t *cl, vpn_packet_t *inpkt)
112 struct sockaddr_in to;
113 socklen_t tolen = sizeof(to);
115 outpkt.len = inpkt->len;
117 /* Encrypt the packet. */
119 EVP_EncryptInit(&ctx, cl->cipher_pkttype, cl->cipher_pktkey, cl->cipher_pktkey + cl->cipher_pkttype->key_len);
120 EVP_EncryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len);
121 EVP_EncryptFinal(&ctx, outpkt.data + outlen, &outpad);
122 outlen += outpad + 2;
125 outlen = outpkt.len + 2;
126 memcpy(&outpkt, inpkt, outlen);
129 if(debug_lvl >= DEBUG_TRAFFIC)
130 syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
131 outlen, cl->name, cl->hostname);
133 total_socket_out += outlen;
135 to.sin_family = AF_INET;
136 to.sin_addr.s_addr = htonl(cl->address);
137 to.sin_port = htons(cl->port);
139 if((sendto(myself->socket, (char *) &(outpkt.len), outlen, 0, (const struct sockaddr *)&to, tolen)) < 0)
141 syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
142 cl->name, cl->hostname);
149 int xrecv(connection_t *cl, vpn_packet_t *inpkt)
155 outpkt.len = inpkt->len;
157 /* Decrypt the packet */
159 EVP_DecryptInit(&ctx, myself->cipher_pkttype, myself->cipher_pktkey, myself->cipher_pktkey + myself->cipher_pkttype->key_len);
160 EVP_DecryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len + 8);
161 EVP_DecryptFinal(&ctx, outpkt.data + outlen, &outpad);
165 outlen = outpkt.len+2;
166 memcpy(&outpkt, inpkt, outlen);
169 return receive_packet(cl, &outpkt);
172 int receive_packet(connection_t *cl, vpn_packet_t *packet)
174 if(debug_lvl >= DEBUG_TRAFFIC)
175 syslog(LOG_ERR, _("Writing packet of %d bytes to tap device"),
178 /* Fix mac address */
180 memcpy(packet->data, mymac.net.mac.address.x, 6);
182 if(taptype == TAP_TYPE_TUNTAP)
184 if(write(tap_fd, packet->data, packet->len) < 0)
185 syslog(LOG_ERR, _("Can't write to tun/tap device: %m"));
187 total_tap_out += packet->len;
191 if(write(tap_fd, packet->data - 2, packet->len + 2) < 0)
192 syslog(LOG_ERR, _("Can't write to ethertap device: %m"));
194 total_tap_out += packet->len + 2;
201 send a packet to the given vpn ip.
203 int send_packet(ip_t to, vpn_packet_t *packet)
209 if((subnet = lookup_subnet_ipv4(&to)) == NULL)
211 if(debug_lvl >= DEBUG_TRAFFIC)
213 syslog(LOG_NOTICE, _("Trying to look up %d.%d.%d.%d in connection list failed!"),
224 if(debug_lvl >= DEBUG_TRAFFIC)
226 syslog(LOG_NOTICE, _("Packet with destination %d.%d.%d.%d is looping back to us!"),
233 if(!cl->status.active)
235 if(debug_lvl >= DEBUG_TRAFFIC)
236 syslog(LOG_INFO, _("%s (%s) is not active, dropping packet"),
237 cl->name, cl->hostname);
242 if(!cl->status.validkey)
244 if(debug_lvl >= DEBUG_TRAFFIC)
245 syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
246 cl->name, cl->hostname);
248 /* Since packet is on the stack of handle_tap_input(),
249 we have to make a copy of it first. */
251 copy = xmalloc(sizeof(vpn_packet_t));
252 memcpy(copy, packet, sizeof(vpn_packet_t));
254 list_insert_tail(cl->queue, copy);
256 if(!cl->status.waitingforkey)
257 send_req_key(myself, cl); /* Keys should be sent to the host running the tincd */
261 /* Check if it has to go via UDP or TCP... */
263 if(cl->options & OPTION_TCPONLY)
264 return send_tcppacket(cl, packet);
266 return xsend(cl, packet);
269 void flush_queue(connection_t *cl)
271 list_node_t *node, *next;
273 if(debug_lvl >= DEBUG_TRAFFIC)
274 syslog(LOG_INFO, _("Flushing queue for %s (%s)"), cl->name, cl->hostname);
276 for(node = cl->queue->head; node; node = next)
279 xsend(cl, (vpn_packet_t *)node->data);
280 list_delete_node(cl->queue, node);
286 open the local ethertap device
288 int setup_tap_fd(void)
291 const char *tapfname;
300 if((cfg = get_config_val(config, config_tapdevice)))
301 tapfname = cfg->data.ptr;
306 tapfname = "/dev/misc/net/tun";
308 tapfname = "/dev/tap0";
312 tapfname = "/dev/tap0";
315 tapfname = "/dev/tun";
319 if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
321 syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
327 taptype = TAP_TYPE_ETHERTAP;
329 /* Set default MAC address for ethertap devices */
331 mymac.type = SUBNET_MAC;
332 mymac.net.mac.address.x[0] = 0xfe;
333 mymac.net.mac.address.x[1] = 0xfd;
334 mymac.net.mac.address.x[2] = 0x00;
335 mymac.net.mac.address.x[3] = 0x00;
336 mymac.net.mac.address.x[4] = 0x00;
337 mymac.net.mac.address.x[5] = 0x00;
341 /* Ok now check if this is an old ethertap or a new tun/tap thingie */
342 memset(&ifr, 0, sizeof(ifr));
344 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
346 strncpy(ifr.ifr_name, netname, IFNAMSIZ);
348 if (!ioctl(tap_fd, TUNSETIFF, (void *) &ifr))
350 syslog(LOG_INFO, _("%s is a new style tun/tap device"), tapfname);
351 taptype = TAP_TYPE_TUNTAP;
356 taptype = TAP_TYPE_TUNTAP;
363 set up the socket that we listen on for incoming
366 int setup_listen_meta_socket(int port)
369 struct sockaddr_in a;
373 if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
375 syslog(LOG_ERR, _("Creating metasocket failed: %m"));
379 flags = fcntl(nfd, F_GETFL);
380 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
383 syslog(LOG_ERR, _("System call `%s' failed: %m"),
388 /* Optimize TCP settings */
391 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
392 setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
393 setsockopt(nfd, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
395 option = IPTOS_LOWDELAY;
396 setsockopt(nfd, SOL_IP, IP_TOS, &option, sizeof(option));
398 if((cfg = get_config_val(config, config_interface)))
400 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, cfg->data.ptr, strlen(cfg->data.ptr)))
403 syslog(LOG_ERR, _("Unable to bind listen socket to interface %s: %m"), cfg->data.ptr);
408 memset(&a, 0, sizeof(a));
409 a.sin_family = AF_INET;
410 a.sin_port = htons(port);
412 if((cfg = get_config_val(config, config_interfaceip)))
413 a.sin_addr.s_addr = htonl(cfg->data.ip->address);
415 a.sin_addr.s_addr = htonl(INADDR_ANY);
417 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
420 syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
427 syslog(LOG_ERR, _("System call `%s' failed: %m"),
436 setup the socket for incoming encrypted
439 int setup_vpn_in_socket(int port)
442 struct sockaddr_in a;
445 if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
448 syslog(LOG_ERR, _("Creating socket failed: %m"));
452 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
454 flags = fcntl(nfd, F_GETFL);
455 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
458 syslog(LOG_ERR, _("System call `%s' failed: %m"),
463 memset(&a, 0, sizeof(a));
464 a.sin_family = AF_INET;
465 a.sin_port = htons(port);
466 a.sin_addr.s_addr = htonl(INADDR_ANY);
468 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
471 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
479 setup an outgoing meta (tcp) socket
481 int setup_outgoing_meta_socket(connection_t *cl)
484 struct sockaddr_in a;
488 if(debug_lvl >= DEBUG_CONNECTIONS)
489 syslog(LOG_INFO, _("Trying to connect to %s"), cl->hostname);
491 if((cfg = get_config_val(cl->config, config_port)) == NULL)
494 cl->port = cfg->data.val;
496 cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
497 if(cl->meta_socket == -1)
499 syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
500 cl->hostname, cl->port);
504 /* Bind first to get a fix on our source port */
506 a.sin_family = AF_INET;
507 a.sin_port = htons(0);
508 a.sin_addr.s_addr = htonl(INADDR_ANY);
510 if(bind(cl->meta_socket, (struct sockaddr *)&a, sizeof(struct sockaddr)))
512 close(cl->meta_socket);
513 syslog(LOG_ERR, _("System call `%s' failed: %m"), "bind");
517 /* Optimize TCP settings */
520 setsockopt(cl->meta_socket, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
521 setsockopt(cl->meta_socket, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
523 option = IPTOS_LOWDELAY;
524 setsockopt(cl->meta_socket, SOL_IP, IP_TOS, &option, sizeof(option));
528 a.sin_family = AF_INET;
529 a.sin_port = htons(cl->port);
530 a.sin_addr.s_addr = htonl(cl->address);
532 if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
534 close(cl->meta_socket);
535 syslog(LOG_ERR, _("%s port %hd: %m"), cl->hostname, cl->port);
539 flags = fcntl(cl->meta_socket, F_GETFL);
540 if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
542 close(cl->meta_socket);
543 syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
544 cl->hostname, cl->port);
548 if(debug_lvl >= DEBUG_CONNECTIONS)
549 syslog(LOG_INFO, _("Connected to %s port %hd"),
550 cl->hostname, cl->port);
558 Setup an outgoing meta connection.
560 int setup_outgoing_connection(char *name)
568 syslog(LOG_ERR, _("Invalid name for outgoing connection"));
572 ncn = new_connection();
573 asprintf(&ncn->name, "%s", name);
575 if(read_host_config(ncn))
577 syslog(LOG_ERR, _("Error reading host configuration file for %s"), ncn->name);
578 free_connection(ncn);
582 if(!(cfg = get_config_val(ncn->config, config_address)))
584 syslog(LOG_ERR, _("No address specified for %s"), ncn->name);
585 free_connection(ncn);
589 if(!(h = gethostbyname(cfg->data.ptr)))
591 syslog(LOG_ERR, _("Error looking up `%s': %m"), cfg->data.ptr);
592 free_connection(ncn);
596 ncn->address = ntohl(*((ip_t*)(h->h_addr_list[0])));
597 ncn->hostname = hostlookup(htonl(ncn->address));
599 if(setup_outgoing_meta_socket(ncn) < 0)
601 syslog(LOG_ERR, _("Could not set up a meta connection to %s"),
603 free_connection(ncn);
607 ncn->status.outgoing = 1;
608 ncn->buffer = xmalloc(MAXBUFSIZE);
610 ncn->last_ping_time = time(NULL);
619 int read_rsa_public_key(connection_t *cl)
627 cl->rsa_key = RSA_new();
629 /* First, check for simple PublicKey statement */
631 if((cfg = get_config_val(cl->config, config_publickey)))
633 BN_hex2bn(&cl->rsa_key->n, cfg->data.ptr);
634 BN_hex2bn(&cl->rsa_key->e, "FFFF");
638 /* Else, check for PublicKeyFile statement and read it */
640 if((cfg = get_config_val(cl->config, config_publickeyfile)))
642 if(is_safe_path(cfg->data.ptr))
644 if((fp = fopen(cfg->data.ptr, "r")) == NULL)
646 syslog(LOG_ERR, _("Error reading RSA public key file `%s': %m"),
650 result = PEM_read_RSAPublicKey(fp, &cl->rsa_key, NULL, NULL);
654 syslog(LOG_ERR, _("Reading RSA public key file `%s' failed: %m"),
664 /* Else, check if a harnessed public key is in the config file */
666 asprintf(&fname, "%s/hosts/%s", confbase, cl->name);
667 if((fp = fopen(fname, "r")))
669 result = PEM_read_RSAPublicKey(fp, &cl->rsa_key, NULL, NULL);
678 /* Nothing worked. */
680 syslog(LOG_ERR, _("No public key for %s specified!"), cl->name);
685 int read_rsa_private_key(void)
692 myself->rsa_key = RSA_new();
694 if((cfg = get_config_val(config, config_privatekey)))
696 BN_hex2bn(&myself->rsa_key->d, cfg->data.ptr);
697 BN_hex2bn(&myself->rsa_key->e, "FFFF");
699 else if((cfg = get_config_val(config, config_privatekeyfile)))
701 if((fp = fopen(cfg->data.ptr, "r")) == NULL)
703 syslog(LOG_ERR, _("Error reading RSA private key file `%s': %m"),
707 result = PEM_read_RSAPrivateKey(fp, &myself->rsa_key, NULL, NULL);
711 syslog(LOG_ERR, _("Reading RSA private key file `%s' failed: %m"),
718 syslog(LOG_ERR, _("No private key for tinc daemon specified!"));
726 Configure connection_t myself and set up the local sockets (listen only)
728 int setup_myself(void)
734 myself = new_connection();
736 asprintf(&myself->hostname, "MYSELF");
738 myself->protocol_version = PROT_CURRENT;
740 if(!(cfg = get_config_val(config, config_name))) /* Not acceptable */
742 syslog(LOG_ERR, _("Name for tinc daemon required!"));
746 asprintf(&myself->name, "%s", (char*)cfg->data.val);
748 if(check_id(myself->name))
750 syslog(LOG_ERR, _("Invalid name for myself!"));
754 if(read_rsa_private_key())
757 if(read_host_config(myself))
759 syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
763 if(read_rsa_public_key(myself))
768 if(RSA_check_key(myself->rsa_key) != 1)
770 syslog(LOG_ERR, _("Invalid public/private keypair!"));
774 if(!(cfg = get_config_val(myself->config, config_port)))
777 myself->port = cfg->data.val;
779 if((cfg = get_config_val(myself->config, config_indirectdata)))
780 if(cfg->data.val == stupid_true)
781 myself->flags |= EXPORTINDIRECTDATA;
783 if((cfg = get_config_val(myself->config, config_tcponly)))
784 if(cfg->data.val == stupid_true)
785 myself->flags |= TCPONLY;
787 /* Read in all the subnets specified in the host configuration file */
789 for(next = myself->config; (cfg = get_config_val(next, config_subnet)); next = cfg->next)
792 net->type = SUBNET_IPV4;
793 net->net.ipv4.address = cfg->data.ip->address;
794 net->net.ipv4.mask = cfg->data.ip->mask;
796 /* Teach newbies what subnets are... */
798 if((net->net.ipv4.address & net->net.ipv4.mask) != net->net.ipv4.address)
800 syslog(LOG_ERR, _("Network address and subnet mask do not match!"));
804 subnet_add(myself, net);
807 if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
809 syslog(LOG_ERR, _("Unable to set up a listening TCP socket!"));
813 if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
815 syslog(LOG_ERR, _("Unable to set up a listening UDP socket!"));
819 /* Generate packet encryption key */
821 myself->cipher_pkttype = EVP_bf_cbc();
823 myself->cipher_pktkeylength = myself->cipher_pkttype->key_len + myself->cipher_pkttype->iv_len;
825 myself->cipher_pktkey = (char *)xmalloc(myself->cipher_pktkeylength);
826 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
828 if(!(cfg = get_config_val(config, config_keyexpire)))
831 keylifetime = cfg->data.val;
833 keyexpires = time(NULL) + keylifetime;
835 /* Check some options */
837 if((cfg = get_config_val(config, config_indirectdata)))
839 if(cfg->data.val == stupid_true)
840 myself->options |= OPTION_INDIRECT;
843 if((cfg = get_config_val(config, config_tcponly)))
845 if(cfg->data.val == stupid_true)
846 myself->options |= OPTION_TCPONLY;
848 /* Activate ourselves */
850 myself->status.active = 1;
852 syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
858 sigalrm_handler(int a)
862 cfg = get_config_val(upstreamcfg, config_connectto);
864 if(!cfg && upstreamcfg == config)
865 /* No upstream IP given, we're listen only. */
870 upstreamcfg = cfg->next;
871 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
873 signal(SIGALRM, SIG_IGN);
876 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
879 signal(SIGALRM, sigalrm_handler);
880 upstreamcfg = config;
881 seconds_till_retry += 5;
882 if(seconds_till_retry > MAXTIMEOUT) /* Don't wait more than MAXTIMEOUT seconds. */
883 seconds_till_retry = MAXTIMEOUT;
884 syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
886 alarm(seconds_till_retry);
891 setup all initial network connections
893 int setup_network_connections(void)
900 if((cfg = get_config_val(config, config_pingtimeout)) == NULL)
904 timeout = cfg->data.val;
911 if(setup_tap_fd() < 0)
914 /* Run tinc-up script to further initialize the tap interface */
915 execute_script("tinc-up");
917 if(setup_myself() < 0)
920 if(!(cfg = get_config_val(config, config_connectto)))
921 /* No upstream IP given, we're listen only. */
926 upstreamcfg = cfg->next;
927 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
929 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
932 signal(SIGALRM, sigalrm_handler);
933 upstreamcfg = config;
934 seconds_till_retry = MAXTIMEOUT;
935 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
936 alarm(seconds_till_retry);
942 close all open network connections
944 void close_network_connections(void)
949 for(node = connection_tree->head; node; node = node->next)
951 p = (connection_t *)node->data;
952 p->status.active = 0;
953 terminate_connection(p);
957 if(myself->status.active)
959 close(myself->meta_socket);
960 free_connection(myself);
966 /* Execute tinc-down script right after shutting down the interface */
967 execute_script("tinc-down");
969 destroy_connection_tree();
975 create a data (udp) socket
976 OBSOLETED: use only one listening socket for compatibility with non-Linux operating systems
978 int setup_vpn_connection(connection_t *cl)
981 struct sockaddr_in a;
984 if(debug_lvl >= DEBUG_TRAFFIC)
985 syslog(LOG_DEBUG, _("Opening UDP socket to %s"), cl->hostname);
987 nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
990 syslog(LOG_ERR, _("Creating UDP socket failed: %m"));
994 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
996 flags = fcntl(nfd, F_GETFL);
997 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
1000 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1005 memset(&a, 0, sizeof(a));
1006 a.sin_family = AF_INET;
1007 a.sin_port = htons(myself->port);
1008 a.sin_addr.s_addr = htonl(INADDR_ANY);
1010 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
1013 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), myself->port);
1017 a.sin_family = AF_INET;
1018 a.sin_port = htons(cl->port);
1019 a.sin_addr.s_addr = htonl(cl->address);
1021 if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
1024 syslog(LOG_ERR, _("Connecting to %s port %d failed: %m"),
1025 cl->hostname, cl->port);
1029 flags = fcntl(nfd, F_GETFL);
1030 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
1033 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m %s (%s)"), __FILE__, __LINE__, nfd,
1034 cl->name, cl->hostname);
1039 cl->status.dataopen = 1;
1045 handle an incoming tcp connect call and open
1048 connection_t *create_new_connection(int sfd)
1051 struct sockaddr_in ci;
1052 int len = sizeof(ci);
1054 p = new_connection();
1056 if(getpeername(sfd, (struct sockaddr *) &ci, (socklen_t *) &len) < 0)
1058 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1065 p->address = ntohl(ci.sin_addr.s_addr);
1066 p->hostname = hostlookup(ci.sin_addr.s_addr);
1067 p->port = htons(ci.sin_port); /* This one will be overwritten later */
1068 p->meta_socket = sfd;
1070 p->buffer = xmalloc(MAXBUFSIZE);
1072 p->last_ping_time = time(NULL);
1074 if(debug_lvl >= DEBUG_CONNECTIONS)
1075 syslog(LOG_NOTICE, _("Connection from %s port %d"),
1076 p->hostname, htons(ci.sin_port));
1078 p->allow_request = ID;
1084 put all file descriptors in an fd_set array
1086 void build_fdset(fd_set *fs)
1093 FD_SET(myself->socket, fs);
1095 for(node = connection_tree->head; node; node = node->next)
1097 p = (connection_t *)node->data;
1099 FD_SET(p->meta_socket, fs);
1102 FD_SET(myself->meta_socket, fs);
1108 receive incoming data from the listening
1109 udp socket and write it to the ethertap
1110 device after being decrypted
1112 int handle_incoming_vpn_data(void)
1115 int x, l = sizeof(x);
1117 struct sockaddr_in from;
1118 socklen_t fromlen = sizeof(from);
1121 if(getsockopt(myself->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1123 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1124 __FILE__, __LINE__, myself->socket);
1129 syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1133 if((lenin = recvfrom(myself->socket, (char *) &(pkt.len), MTU, 0, (struct sockaddr *)&from, &fromlen)) <= 0)
1135 syslog(LOG_ERR, _("Receiving packet failed: %m"));
1139 cl = lookup_connection(ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
1143 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));
1147 if(debug_lvl >= DEBUG_TRAFFIC)
1149 syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"), lenin,
1150 cl->name, cl->hostname);
1154 return xrecv(cl, &pkt);
1158 terminate a connection and notify the other
1159 end before closing the sockets
1161 void terminate_connection(connection_t *cl)
1165 avl_node_t *node, *next;
1167 if(cl->status.remove)
1170 if(debug_lvl >= DEBUG_CONNECTIONS)
1171 syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1172 cl->name, cl->hostname);
1174 cl->status.remove = 1;
1179 close(cl->meta_socket);
1184 /* Find all connections that were lost because they were behind cl
1185 (the connection that was dropped). */
1187 for(node = connection_tree->head; node; node = node->next)
1189 p = (connection_t *)node->data;
1190 if(p->nexthop == cl && p != cl)
1191 terminate_connection(p);
1194 /* Inform others of termination if it was still active */
1196 if(cl->status.active)
1197 for(node = connection_tree->head; node; node = node->next)
1199 p = (connection_t *)node->data;
1200 if(p->status.meta && p->status.active && p != cl)
1201 send_del_host(p, cl); /* Sounds like recursion, but p does not have a meta connection :) */
1205 /* Remove the associated subnets */
1207 for(node = cl->subnet_tree->head; node; node = next)
1210 subnet = (subnet_t *)node->data;
1214 /* Check if this was our outgoing connection */
1216 if(cl->status.outgoing)
1218 cl->status.outgoing = 0;
1219 signal(SIGALRM, sigalrm_handler);
1220 seconds_till_retry = 5;
1221 alarm(seconds_till_retry);
1222 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
1227 cl->status.active = 0;
1232 Check if the other end is active.
1233 If we have sent packets, but didn't receive any,
1234 then possibly the other end is dead. We send a
1235 PING request over the meta connection. If the other
1236 end does not reply in time, we consider them dead
1237 and close the connection.
1239 void check_dead_connections(void)
1247 for(node = connection_tree->head; node; node = node->next)
1249 cl = (connection_t *)node->data;
1250 if(cl->status.active && cl->status.meta)
1252 if(cl->last_ping_time + timeout < now)
1254 if(cl->status.pinged)
1256 if(debug_lvl >= DEBUG_PROTOCOL)
1257 syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1258 cl->name, cl->hostname);
1259 cl->status.timeout = 1;
1260 terminate_connection(cl);
1273 accept a new tcp connect and create a
1276 int handle_new_meta_connection()
1279 struct sockaddr client;
1280 int nfd, len = sizeof(client);
1282 if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
1284 syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1288 if(!(ncn = create_new_connection(nfd)))
1292 syslog(LOG_NOTICE, _("Closed attempted connection"));
1296 connection_add(ncn);
1304 check all connections to see if anything
1305 happened on their sockets
1307 void check_network_activity(fd_set *f)
1312 if(FD_ISSET(myself->socket, f))
1313 handle_incoming_vpn_data();
1315 for(node = connection_tree->head; node; node = node->next)
1317 p = (connection_t *)node->data;
1319 if(p->status.remove)
1323 if(FD_ISSET(p->meta_socket, f))
1324 if(receive_meta(p) < 0)
1326 terminate_connection(p);
1331 if(FD_ISSET(myself->meta_socket, f))
1332 handle_new_meta_connection();
1337 read, encrypt and send data that is
1338 available through the ethertap device
1340 void handle_tap_input(void)
1345 if(taptype == TAP_TYPE_TUNTAP)
1347 if((lenin = read(tap_fd, vp.data, MTU)) <= 0)
1349 syslog(LOG_ERR, _("Error while reading from tun/tap device: %m"));
1356 if((lenin = read(tap_fd, vp.data - 2, MTU)) <= 0)
1358 syslog(LOG_ERR, _("Error while reading from ethertap device: %m"));
1364 total_tap_in += lenin;
1368 if(debug_lvl >= DEBUG_TRAFFIC)
1369 syslog(LOG_WARNING, _("Received short packet from tap device"));
1373 if(debug_lvl >= DEBUG_TRAFFIC)
1375 syslog(LOG_DEBUG, _("Read packet of length %d from tap device"), vp.len);
1378 send_packet(ntohl(*((unsigned long*)(&vp.data[30]))), &vp);
1383 this is where it all happens...
1385 void main_loop(void)
1390 time_t last_ping_check;
1393 last_ping_check = time(NULL);
1397 tv.tv_sec = timeout;
1400 prune_connection_tree();
1403 if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1405 if(errno != EINTR) /* because of alarm */
1407 syslog(LOG_ERR, _("Error while waiting for input: %m"));
1414 syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1416 close_network_connections();
1417 clear_config(&config);
1419 if(read_server_config())
1421 syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1427 if(setup_network_connections())
1435 /* Let's check if everybody is still alive */
1437 if(last_ping_check + timeout < t)
1439 check_dead_connections();
1440 last_ping_check = time(NULL);
1442 /* Should we regenerate our key? */
1446 if(debug_lvl >= DEBUG_STATUS)
1447 syslog(LOG_INFO, _("Regenerating symmetric key"));
1449 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
1450 send_key_changed(myself, NULL);
1451 keyexpires = time(NULL) + keylifetime;
1457 check_network_activity(&fset);
1459 /* local tap data */
1460 if(FD_ISSET(tap_fd, &fset))