2 net.c -- most of the network code
3 Copyright (C) 1998,1999,2000 Ivo Timmermans <itimmermans@bigfoot.com>,
4 2000 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.85 2000/11/30 22:48:48 zarq 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
76 #include "connection.h"
88 int taptype = TAP_TYPE_ETHERTAP;
90 int total_tap_out = 0;
91 int total_socket_in = 0;
92 int total_socket_out = 0;
94 config_t *upstreamcfg;
95 static int seconds_till_retry;
100 char *unknown = NULL;
104 int xsend(connection_t *cl, vpn_packet_t *inpkt)
109 struct sockaddr_in to;
110 socklen_t tolen = sizeof(to);
112 outpkt.len = inpkt->len;
114 /* Encrypt the packet */
116 EVP_EncryptInit(&ctx, cl->cipher_pkttype, cl->cipher_pktkey, cl->cipher_pktkey + cl->cipher_pkttype->key_len);
117 EVP_EncryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len);
118 EVP_EncryptFinal(&ctx, outpkt.data + outlen, &outpad);
119 outlen += outpad + 2;
122 outlen = outpkt.len + 2;
123 memcpy(&outpkt, inpkt, outlen);
126 if(debug_lvl >= DEBUG_TRAFFIC)
127 syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
128 outlen, cl->name, cl->hostname);
130 total_socket_out += outlen;
132 to.sin_family = AF_INET;
133 to.sin_addr.s_addr = htonl(cl->address);
134 to.sin_port = htons(cl->port);
136 if((sendto(myself->socket, (char *) &(outpkt.len), outlen, 0, (const struct sockaddr *)&to, tolen)) < 0)
138 syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
139 cl->name, cl->hostname);
146 int xrecv(connection_t *cl, vpn_packet_t *inpkt)
152 outpkt.len = inpkt->len;
154 /* Decrypt the packet */
156 EVP_DecryptInit(&ctx, myself->cipher_pkttype, myself->cipher_pktkey, myself->cipher_pktkey + myself->cipher_pkttype->key_len);
157 EVP_DecryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len + 8);
158 EVP_DecryptFinal(&ctx, outpkt.data + outlen, &outpad);
162 outlen = outpkt.len+2;
163 memcpy(&outpkt, inpkt, outlen);
166 if(debug_lvl >= DEBUG_TRAFFIC)
167 syslog(LOG_ERR, _("Writing packet of %d bytes to tap device"),
170 /* Fix mac address */
172 memcpy(outpkt.data, mymac.net.mac.address.x, 6);
174 if(taptype == TAP_TYPE_TUNTAP)
176 if(write(tap_fd, outpkt.data, outpkt.len) < 0)
177 syslog(LOG_ERR, _("Can't write to tun/tap device: %m"));
179 total_tap_out += outpkt.len;
183 if(write(tap_fd, outpkt.data - 2, outpkt.len + 2) < 0)
184 syslog(LOG_ERR, _("Can't write to ethertap device: %m"));
186 total_tap_out += outpkt.len + 2;
193 add the given packet of size s to the
194 queue q, be it the send or receive queue
196 void add_queue(packet_queue_t **q, void *packet, size_t s)
200 e = xmalloc(sizeof(*e));
201 e->packet = xmalloc(s);
202 memcpy(e->packet, packet, s);
206 *q = xmalloc(sizeof(**q));
207 (*q)->head = (*q)->tail = NULL;
210 e->next = NULL; /* We insert at the tail */
212 if((*q)->tail) /* Do we have a tail? */
214 (*q)->tail->next = e;
215 e->prev = (*q)->tail;
217 else /* No tail -> no head too */
227 /* Remove a queue element */
228 void del_queue(packet_queue_t **q, queue_element_t *e)
233 if(e->next) /* There is a successor, so we are not tail */
235 if(e->prev) /* There is a predecessor, so we are not head */
237 e->next->prev = e->prev;
238 e->prev->next = e->next;
240 else /* We are head */
242 e->next->prev = NULL;
243 (*q)->head = e->next;
246 else /* We are tail (or all alone!) */
248 if(e->prev) /* We are not alone :) */
250 e->prev->next = NULL;
251 (*q)->tail = e->prev;
265 flush a queue by calling function for
266 each packet, and removing it when that
267 returned a zero exit code
269 void flush_queue(connection_t *cl, packet_queue_t **pq,
270 int (*function)(connection_t*,vpn_packet_t*))
272 queue_element_t *p, *next = NULL;
274 for(p = (*pq)->head; p != NULL; )
278 if(!function(cl, p->packet))
284 if(debug_lvl >= DEBUG_TRAFFIC)
285 syslog(LOG_DEBUG, _("Queue flushed"));
290 flush the send&recv queues
291 void because nothing goes wrong here, packets
292 remain in the queue if something goes wrong
294 void flush_queues(connection_t *cl)
299 if(debug_lvl >= DEBUG_TRAFFIC)
300 syslog(LOG_DEBUG, _("Flushing send queue for %s (%s)"),
301 cl->name, cl->hostname);
302 flush_queue(cl, &(cl->sq), xsend);
307 if(debug_lvl >= DEBUG_TRAFFIC)
308 syslog(LOG_DEBUG, _("Flushing receive queue for %s (%s)"),
309 cl->name, cl->hostname);
310 flush_queue(cl, &(cl->rq), xrecv);
316 send a packet to the given vpn ip.
318 int send_packet(ip_t to, vpn_packet_t *packet)
323 if((subnet = lookup_subnet_ipv4(to)) == NULL)
325 if(debug_lvl >= DEBUG_TRAFFIC)
327 syslog(LOG_NOTICE, _("Trying to look up %d.%d.%d.%d in connection list failed!"),
338 if(debug_lvl >= DEBUG_TRAFFIC)
340 syslog(LOG_NOTICE, _("Packet with destination %d.%d.%d.%d is looping back to us!"),
347 /* If we ourselves have indirectdata flag set, we should send only to our uplink! */
349 /* FIXME - check for indirection and reprogram it The Right Way(tm) this time. */
351 if(!cl->status.validkey)
353 /* FIXME: Don't queue until everything else is fixed.
354 if(debug_lvl >= DEBUG_TRAFFIC)
355 syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
356 cl->name, cl->hostname);
357 add_queue(&(cl->sq), packet, packet->len + 2);
359 if(!cl->status.waitingforkey)
360 send_req_key(myself, cl); /* Keys should be sent to the host running the tincd */
364 if(!cl->status.active)
366 /* FIXME: Don't queue until everything else is fixed.
367 if(debug_lvl >= DEBUG_TRAFFIC)
368 syslog(LOG_INFO, _("%s (%s) is not ready, queueing packet"),
369 cl->name, cl->hostname);
370 add_queue(&(cl->sq), packet, packet->len + 2);
372 return 0; /* We don't want to mess up, do we? */
375 /* can we send it? can we? can we? huh? */
377 return xsend(cl, packet);
381 open the local ethertap device
383 int setup_tap_fd(void)
386 const char *tapfname;
395 if((cfg = get_config_val(config, config_tapdevice)))
396 tapfname = cfg->data.ptr;
401 tapfname = "/dev/misc/net/tun";
403 tapfname = "/dev/tap0";
407 tapfname = "/dev/tap0";
410 tapfname = "/dev/tun";
414 if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
416 syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
422 taptype = TAP_TYPE_ETHERTAP;
424 /* Set default MAC address for ethertap devices */
426 mymac.type = SUBNET_MAC;
427 mymac.net.mac.address.x[0] = 0xfe;
428 mymac.net.mac.address.x[1] = 0xfd;
429 mymac.net.mac.address.x[2] = 0x00;
430 mymac.net.mac.address.x[3] = 0x00;
431 mymac.net.mac.address.x[4] = 0x00;
432 mymac.net.mac.address.x[5] = 0x00;
436 /* Ok now check if this is an old ethertap or a new tun/tap thingie */
437 memset(&ifr, 0, sizeof(ifr));
439 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
441 strncpy(ifr.ifr_name, netname, IFNAMSIZ);
443 if (!ioctl(tap_fd, TUNSETIFF, (void *) &ifr))
445 syslog(LOG_INFO, _("%s is a new style tun/tap device"), tapfname);
446 taptype = TAP_TYPE_TUNTAP;
451 taptype = TAP_TYPE_TUNTAP;
458 set up the socket that we listen on for incoming
461 int setup_listen_meta_socket(int port)
464 struct sockaddr_in a;
468 if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
470 syslog(LOG_ERR, _("Creating metasocket failed: %m"));
474 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
477 syslog(LOG_ERR, _("System call `%s' failed: %m"),
482 if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one)))
485 syslog(LOG_ERR, _("System call `%s' failed: %m"),
490 flags = fcntl(nfd, F_GETFL);
491 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
494 syslog(LOG_ERR, _("System call `%s' failed: %m"),
499 if((cfg = get_config_val(config, config_interface)))
501 if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, cfg->data.ptr, strlen(cfg->data.ptr)))
504 syslog(LOG_ERR, _("Unable to bind listen socket to interface %s: %m"), cfg->data.ptr);
509 memset(&a, 0, sizeof(a));
510 a.sin_family = AF_INET;
511 a.sin_port = htons(port);
513 if((cfg = get_config_val(config, config_interfaceip)))
514 a.sin_addr.s_addr = htonl(cfg->data.ip->address);
516 a.sin_addr.s_addr = htonl(INADDR_ANY);
518 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
521 syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
528 syslog(LOG_ERR, _("System call `%s' failed: %m"),
537 setup the socket for incoming encrypted
540 int setup_vpn_in_socket(int port)
543 struct sockaddr_in a;
546 if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
549 syslog(LOG_ERR, _("Creating socket failed: %m"));
553 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
556 syslog(LOG_ERR, _("System call `%s' failed: %m"),
561 flags = fcntl(nfd, F_GETFL);
562 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
565 syslog(LOG_ERR, _("System call `%s' failed: %m"),
570 memset(&a, 0, sizeof(a));
571 a.sin_family = AF_INET;
572 a.sin_port = htons(port);
573 a.sin_addr.s_addr = htonl(INADDR_ANY);
575 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
578 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
586 setup an outgoing meta (tcp) socket
588 int setup_outgoing_meta_socket(connection_t *cl)
591 struct sockaddr_in a;
594 if(debug_lvl >= DEBUG_CONNECTIONS)
595 syslog(LOG_INFO, _("Trying to connect to %s"), cl->hostname);
597 if((cfg = get_config_val(cl->config, config_port)) == NULL)
600 cl->port = cfg->data.val;
602 cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
603 if(cl->meta_socket == -1)
605 syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
606 cl->hostname, cl->port);
610 a.sin_family = AF_INET;
611 a.sin_port = htons(cl->port);
612 a.sin_addr.s_addr = htonl(cl->address);
614 if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
616 close(cl->meta_socket);
617 syslog(LOG_ERR, _("%s port %hd: %m"), cl->hostname, cl->port);
621 flags = fcntl(cl->meta_socket, F_GETFL);
622 if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
624 close(cl->meta_socket);
625 syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
626 cl->hostname, cl->port);
630 if(debug_lvl >= DEBUG_CONNECTIONS)
631 syslog(LOG_INFO, _("Connected to %s port %hd"),
632 cl->hostname, cl->port);
640 Setup an outgoing meta connection.
642 int setup_outgoing_connection(char *name)
650 syslog(LOG_ERR, _("Invalid name for outgoing connection"));
654 ncn = new_connection();
655 asprintf(&ncn->name, "%s", name);
657 if(read_host_config(ncn))
659 syslog(LOG_ERR, _("Error reading host configuration file for %s"));
660 free_connection(ncn);
664 if(!(cfg = get_config_val(ncn->config, config_address)))
666 syslog(LOG_ERR, _("No address specified for %s"));
667 free_connection(ncn);
671 if(!(h = gethostbyname(cfg->data.ptr)))
673 syslog(LOG_ERR, _("Error looking up `%s': %m"), cfg->data.ptr);
674 free_connection(ncn);
678 ncn->address = ntohl(*((ip_t*)(h->h_addr_list[0])));
679 ncn->hostname = hostlookup(htonl(ncn->address));
681 if(setup_outgoing_meta_socket(ncn) < 0)
683 syslog(LOG_ERR, _("Could not set up a meta connection to %s"),
685 free_connection(ncn);
689 ncn->status.outgoing = 1;
690 ncn->buffer = xmalloc(MAXBUFSIZE);
692 ncn->last_ping_time = time(NULL);
701 int read_rsa_private_key(RSA **key, const char *file)
705 if((fp = fopen(file, "r")) == NULL)
707 syslog(LOG_ERR, _("Error reading RSA key file `%s': %m"),
711 if(PEM_read_RSAPrivateKey(fp, key, NULL, NULL) == NULL)
713 syslog(LOG_ERR, _("Reading RSA private key file `%s' failed: %m"),
721 int read_rsa_keys(void)
725 if(!(cfg = get_config_val(config, config_privatekey)))
727 syslog(LOG_ERR, _("Private key for tinc daemon required!"));
731 myself->rsa_key = RSA_new();
733 return read_rsa_private_key(&(myself->rsa_key), cfg->data.ptr);
737 Configure connection_t myself and set up the local sockets (listen only)
739 int setup_myself(void)
745 myself = new_connection();
747 asprintf(&myself->hostname, "MYSELF"); /* FIXME? Do hostlookup on ourselves? */
749 myself->protocol_version = PROT_CURRENT;
751 if(!(cfg = get_config_val(config, config_name))) /* Not acceptable */
753 syslog(LOG_ERR, _("Name for tinc daemon required!"));
757 asprintf(&myself->name, "%s", (char*)cfg->data.val);
759 if(check_id(myself->name))
761 syslog(LOG_ERR, _("Invalid name for myself!"));
768 if(read_host_config(myself))
770 syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
774 if(!(cfg = get_config_val(myself->config, config_publickey)))
776 syslog(LOG_ERR, _("Public key for tinc daemon required!"));
781 BN_hex2bn(&myself->rsa_key->n, cfg->data.ptr);
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 if((cfg = get_config_val(myself->config, config_indirectdata)))
796 if(cfg->data.val == stupid_true)
797 myself->flags |= EXPORTINDIRECTDATA;
799 if((cfg = get_config_val(myself->config, config_tcponly)))
800 if(cfg->data.val == stupid_true)
801 myself->flags |= TCPONLY;
803 /* Read in all the subnets specified in the host configuration file */
805 for(next = myself->config; (cfg = get_config_val(next, config_subnet)); next = cfg->next)
808 net->type = SUBNET_IPV4;
809 net->net.ipv4.address = cfg->data.ip->address;
810 net->net.ipv4.mask = cfg->data.ip->mask;
812 /* Teach newbies what subnets are... */
814 if((net->net.ipv4.address & net->net.ipv4.mask) != net->net.ipv4.address)
816 syslog(LOG_ERR, _("Network address and subnet mask do not match!"));
820 subnet_add(myself, net);
823 if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
825 syslog(LOG_ERR, _("Unable to set up a listening TCP socket!"));
829 if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
831 syslog(LOG_ERR, _("Unable to set up a listening UDP socket!"));
835 /* Generate packet encryption key */
837 myself->cipher_pkttype = EVP_bf_cfb();
839 myself->cipher_pktkeylength = myself->cipher_pkttype->key_len + myself->cipher_pkttype->iv_len;
841 myself->cipher_pktkey = (char *)xmalloc(myself->cipher_pktkeylength);
842 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
844 if(!(cfg = get_config_val(config, config_keyexpire)))
847 keylifetime = cfg->data.val;
849 keyexpires = time(NULL) + keylifetime;
851 /* Activate ourselves */
853 myself->status.active = 1;
855 syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
861 sigalrm_handler(int a)
865 cfg = get_config_val(upstreamcfg, config_connectto);
867 if(!cfg && upstreamcfg == config)
868 /* No upstream IP given, we're listen only. */
873 upstreamcfg = cfg->next;
874 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
876 signal(SIGALRM, SIG_IGN);
879 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
882 signal(SIGALRM, sigalrm_handler);
883 upstreamcfg = config;
884 seconds_till_retry += 5;
885 if(seconds_till_retry > MAXTIMEOUT) /* Don't wait more than MAXTIMEOUT seconds. */
886 seconds_till_retry = MAXTIMEOUT;
887 syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
889 alarm(seconds_till_retry);
894 setup all initial network connections
896 int setup_network_connections(void)
903 if((cfg = get_config_val(config, config_pingtimeout)) == NULL)
907 timeout = cfg->data.val;
914 if(setup_tap_fd() < 0)
917 /* Run tinc-up script to further initialize the tap interface */
918 execute_script("tinc-up");
920 if(setup_myself() < 0)
923 if(!(cfg = get_config_val(config, config_connectto)))
924 /* No upstream IP given, we're listen only. */
929 upstreamcfg = cfg->next;
930 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
932 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
935 signal(SIGALRM, sigalrm_handler);
936 upstreamcfg = config;
937 seconds_till_retry = MAXTIMEOUT;
938 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
939 alarm(seconds_till_retry);
945 close all open network connections
947 void close_network_connections(void)
952 RBL_FOREACH(connection_tree, rbl)
954 p = (connection_t *)rbl->data;
955 p->status.active = 0;
956 terminate_connection(p);
960 if(myself->status.active)
962 close(myself->meta_socket);
963 free_connection(myself);
969 /* Execute tinc-down script right after shutting down the interface */
970 execute_script("tinc-down");
972 destroy_connection_tree();
978 create a data (udp) socket
979 OBSOLETED: use only one listening socket for compatibility with non-Linux operating systems
981 int setup_vpn_connection(connection_t *cl)
984 struct sockaddr_in a;
987 if(debug_lvl >= DEBUG_TRAFFIC)
988 syslog(LOG_DEBUG, _("Opening UDP socket to %s"), cl->hostname);
990 nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
993 syslog(LOG_ERR, _("Creating UDP socket failed: %m"));
997 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
1000 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1005 flags = fcntl(nfd, F_GETFL);
1006 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
1009 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1014 memset(&a, 0, sizeof(a));
1015 a.sin_family = AF_INET;
1016 a.sin_port = htons(myself->port);
1017 a.sin_addr.s_addr = htonl(INADDR_ANY);
1019 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
1022 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), myself->port);
1026 a.sin_family = AF_INET;
1027 a.sin_port = htons(cl->port);
1028 a.sin_addr.s_addr = htonl(cl->address);
1030 if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
1033 syslog(LOG_ERR, _("Connecting to %s port %d failed: %m"),
1034 cl->hostname, cl->port);
1038 flags = fcntl(nfd, F_GETFL);
1039 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
1042 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m %s (%s)"), __FILE__, __LINE__, nfd,
1043 cl->name, cl->hostname);
1048 cl->status.dataopen = 1;
1054 handle an incoming tcp connect call and open
1057 connection_t *create_new_connection(int sfd)
1060 struct sockaddr_in ci;
1061 int len = sizeof(ci);
1063 p = new_connection();
1065 if(getpeername(sfd, (struct sockaddr *) &ci, (socklen_t *) &len) < 0)
1067 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1073 p->address = ntohl(ci.sin_addr.s_addr);
1074 p->hostname = hostlookup(ci.sin_addr.s_addr);
1075 p->meta_socket = sfd;
1077 p->buffer = xmalloc(MAXBUFSIZE);
1079 p->last_ping_time = time(NULL);
1081 if(debug_lvl >= DEBUG_CONNECTIONS)
1082 syslog(LOG_NOTICE, _("Connection from %s port %d"),
1083 p->hostname, htons(ci.sin_port));
1085 p->allow_request = ID;
1091 put all file descriptors in an fd_set array
1093 void build_fdset(fd_set *fs)
1100 FD_SET(myself->socket, fs);
1102 RBL_FOREACH(connection_tree, rbl)
1104 p = (connection_t *)rbl->data;
1106 FD_SET(p->meta_socket, fs);
1109 FD_SET(myself->meta_socket, fs);
1115 receive incoming data from the listening
1116 udp socket and write it to the ethertap
1117 device after being decrypted
1119 int handle_incoming_vpn_data(void)
1122 int x, l = sizeof(x);
1124 struct sockaddr_in from;
1125 socklen_t fromlen = sizeof(from);
1128 if(getsockopt(myself->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1130 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1131 __FILE__, __LINE__, myself->socket);
1136 syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1140 if((lenin = recvfrom(myself->socket, (char *) &(pkt.len), MTU, 0, (struct sockaddr *)&from, &fromlen)) <= 0)
1142 syslog(LOG_ERR, _("Receiving packet failed: %m"));
1146 cl = lookup_connection(ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
1150 syslog(LOG_WARNING, _("Received UDP packets on port %d from unknown source %lx:%d"), ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
1154 if(debug_lvl >= DEBUG_TRAFFIC)
1156 syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"), lenin,
1157 cl->name, cl->hostname);
1161 return xrecv(cl, &pkt);
1165 terminate a connection and notify the other
1166 end before closing the sockets
1168 void terminate_connection(connection_t *cl)
1174 if(cl->status.remove)
1177 cl->status.remove = 1;
1179 if(debug_lvl >= DEBUG_CONNECTIONS)
1180 syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1181 cl->name, cl->hostname);
1186 close(cl->meta_socket);
1188 /* Find all connections that were lost because they were behind cl
1189 (the connection that was dropped). */
1192 RBL_FOREACH(connection_tree, rbl)
1194 p = (connection_t *)rbl->data;
1195 if(p->nexthop == cl && p != cl)
1196 terminate_connection(p);
1199 /* Inform others of termination if it was still active */
1201 if(cl->status.active)
1202 RBL_FOREACH(connection_tree, rbl)
1204 p = (connection_t *)rbl->data;
1205 if(p->status.meta && p->status.active && p!=cl)
1206 send_del_host(p, cl); /* Sounds like recursion, but p does not have a meta connection :) */
1209 /* Remove the associated subnets */
1211 RBL_FOREACH(cl->subnet_tree, rbl)
1213 subnet = (subnet_t *)rbl->data;
1217 /* Check if this was our outgoing connection */
1219 if(cl->status.outgoing && cl->status.active)
1221 signal(SIGALRM, sigalrm_handler);
1222 seconds_till_retry = 5;
1223 alarm(seconds_till_retry);
1224 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
1229 cl->status.active = 0;
1234 Check if the other end is active.
1235 If we have sent packets, but didn't receive any,
1236 then possibly the other end is dead. We send a
1237 PING request over the meta connection. If the other
1238 end does not reply in time, we consider them dead
1239 and close the connection.
1241 void check_dead_connections(void)
1249 RBL_FOREACH(connection_tree, rbl)
1251 cl = (connection_t *)rbl->data;
1252 if(cl->status.active && cl->status.meta)
1254 if(cl->last_ping_time + timeout < now)
1256 if(cl->status.pinged)
1258 if(debug_lvl >= DEBUG_PROTOCOL)
1259 syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1260 cl->name, cl->hostname);
1261 cl->status.timeout = 1;
1262 terminate_connection(cl);
1275 accept a new tcp connect and create a
1278 int handle_new_meta_connection()
1281 struct sockaddr client;
1282 int nfd, len = sizeof(client);
1284 if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
1286 syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1290 if(!(ncn = create_new_connection(nfd)))
1294 syslog(LOG_NOTICE, _("Closed attempted connection"));
1298 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 RBL_FOREACH(connection_tree, rbl)
1317 p = (connection_t *)rbl->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))