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.80 2000/11/20 23:29:46 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>
63 #include LINUX_IF_TUN_H
70 #include "connection.h"
82 int taptype = TAP_TYPE_ETHERTAP;
84 int total_tap_out = 0;
85 int total_socket_in = 0;
86 int total_socket_out = 0;
88 config_t *upstreamcfg;
89 static int seconds_till_retry;
98 int xsend(connection_t *cl, vpn_packet_t *inpkt)
104 outpkt.len = inpkt->len;
106 /* Encrypt the packet */
108 EVP_EncryptInit(&ctx, cl->cipher_pkttype, cl->cipher_pktkey, cl->cipher_pktkey + cl->cipher_pkttype->key_len);
109 EVP_EncryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len);
110 EVP_EncryptFinal(&ctx, outpkt.data + outlen, &outpad);
111 outlen += outpad + 2;
114 outlen = outpkt.len + 2;
115 memcpy(&outpkt, inpkt, outlen);
118 if(debug_lvl >= DEBUG_TRAFFIC)
119 syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
120 outlen, cl->name, cl->hostname);
122 total_socket_out += outlen;
124 if((send(cl->socket, (char *) &(outpkt.len), outlen, 0)) < 0)
126 syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
127 cl->name, cl->hostname);
134 int xrecv(connection_t *cl, vpn_packet_t *inpkt)
140 outpkt.len = inpkt->len;
142 /* Decrypt the packet */
144 EVP_DecryptInit(&ctx, myself->cipher_pkttype, myself->cipher_pktkey, myself->cipher_pktkey + myself->cipher_pkttype->key_len);
145 EVP_DecryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len + 8);
146 EVP_DecryptFinal(&ctx, outpkt.data + outlen, &outpad);
150 outlen = outpkt.len+2;
151 memcpy(&outpkt, inpkt, outlen);
154 if(debug_lvl >= DEBUG_TRAFFIC)
155 syslog(LOG_ERR, _("Writing packet of %d bytes to tap device"),
158 /* Fix mac address */
160 memcpy(outpkt.data, mymac.net.mac.address.x, 6);
162 if(taptype == TAP_TYPE_TUNTAP)
164 if(write(tap_fd, outpkt.data, outpkt.len) < 0)
165 syslog(LOG_ERR, _("Can't write to tun/tap device: %m"));
167 total_tap_out += outpkt.len;
171 if(write(tap_fd, outpkt.data - 2, outpkt.len + 2) < 0)
172 syslog(LOG_ERR, _("Can't write to ethertap device: %m"));
174 total_tap_out += outpkt.len + 2;
181 add the given packet of size s to the
182 queue q, be it the send or receive queue
184 void add_queue(packet_queue_t **q, void *packet, size_t s)
188 e = xmalloc(sizeof(*e));
189 e->packet = xmalloc(s);
190 memcpy(e->packet, packet, s);
194 *q = xmalloc(sizeof(**q));
195 (*q)->head = (*q)->tail = NULL;
198 e->next = NULL; /* We insert at the tail */
200 if((*q)->tail) /* Do we have a tail? */
202 (*q)->tail->next = e;
203 e->prev = (*q)->tail;
205 else /* No tail -> no head too */
215 /* Remove a queue element */
216 void del_queue(packet_queue_t **q, queue_element_t *e)
221 if(e->next) /* There is a successor, so we are not tail */
223 if(e->prev) /* There is a predecessor, so we are not head */
225 e->next->prev = e->prev;
226 e->prev->next = e->next;
228 else /* We are head */
230 e->next->prev = NULL;
231 (*q)->head = e->next;
234 else /* We are tail (or all alone!) */
236 if(e->prev) /* We are not alone :) */
238 e->prev->next = NULL;
239 (*q)->tail = e->prev;
253 flush a queue by calling function for
254 each packet, and removing it when that
255 returned a zero exit code
257 void flush_queue(connection_t *cl, packet_queue_t **pq,
258 int (*function)(connection_t*,vpn_packet_t*))
260 queue_element_t *p, *next = NULL;
262 for(p = (*pq)->head; p != NULL; )
266 if(!function(cl, p->packet))
272 if(debug_lvl >= DEBUG_TRAFFIC)
273 syslog(LOG_DEBUG, _("Queue flushed"));
278 flush the send&recv queues
279 void because nothing goes wrong here, packets
280 remain in the queue if something goes wrong
282 void flush_queues(connection_t *cl)
287 if(debug_lvl >= DEBUG_TRAFFIC)
288 syslog(LOG_DEBUG, _("Flushing send queue for %s (%s)"),
289 cl->name, cl->hostname);
290 flush_queue(cl, &(cl->sq), xsend);
295 if(debug_lvl >= DEBUG_TRAFFIC)
296 syslog(LOG_DEBUG, _("Flushing receive queue for %s (%s)"),
297 cl->name, cl->hostname);
298 flush_queue(cl, &(cl->rq), xrecv);
304 send a packet to the given vpn ip.
306 int send_packet(ip_t to, vpn_packet_t *packet)
311 if((subnet = lookup_subnet_ipv4(to)) == NULL)
313 if(debug_lvl >= DEBUG_TRAFFIC)
315 syslog(LOG_NOTICE, _("Trying to look up %d.%d.%d.%d in connection list failed!"),
326 if(debug_lvl >= DEBUG_TRAFFIC)
328 syslog(LOG_NOTICE, _("Packet with destination %d.%d.%d.%d is looping back to us!"),
335 /* If we ourselves have indirectdata flag set, we should send only to our uplink! */
337 /* FIXME - check for indirection and reprogram it The Right Way(tm) this time. */
339 /* Connections are now opened beforehand...
341 if(!cl->status.dataopen)
342 if(setup_vpn_connection(cl) < 0)
344 syslog(LOG_ERR, _("Could not open UDP connection to %s (%s)"),
345 cl->name, cl->hostname);
350 if(!cl->status.validkey)
352 /* FIXME: Don't queue until everything else is fixed.
353 if(debug_lvl >= DEBUG_TRAFFIC)
354 syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
355 cl->name, cl->hostname);
356 add_queue(&(cl->sq), packet, packet->len + 2);
358 if(!cl->status.waitingforkey)
359 send_req_key(myself, cl); /* Keys should be sent to the host running the tincd */
363 if(!cl->status.active)
365 /* FIXME: Don't queue until everything else is fixed.
366 if(debug_lvl >= DEBUG_TRAFFIC)
367 syslog(LOG_INFO, _("%s (%s) is not ready, queueing packet"),
368 cl->name, cl->hostname);
369 add_queue(&(cl->sq), packet, packet->len + 2);
371 return 0; /* We don't want to mess up, do we? */
374 /* can we send it? can we? can we? huh? */
376 return xsend(cl, packet);
380 open the local ethertap device
382 int setup_tap_fd(void)
385 const char *tapfname;
392 if((cfg = get_config_val(config, config_tapdevice)))
393 tapfname = cfg->data.ptr;
396 tapfname = "/dev/misc/net/tun";
398 tapfname = "/dev/tap0";
401 if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
403 syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
409 /* Set default MAC address for ethertap devices */
411 taptype = TAP_TYPE_ETHERTAP;
412 mymac.type = SUBNET_MAC;
413 mymac.net.mac.address.x[0] = 0xfe;
414 mymac.net.mac.address.x[1] = 0xfd;
415 mymac.net.mac.address.x[2] = 0x00;
416 mymac.net.mac.address.x[3] = 0x00;
417 mymac.net.mac.address.x[4] = 0x00;
418 mymac.net.mac.address.x[5] = 0x00;
421 /* Ok now check if this is an old ethertap or a new tun/tap thingie */
422 memset(&ifr, 0, sizeof(ifr));
424 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
426 strncpy(ifr.ifr_name, netname, IFNAMSIZ);
428 if (!ioctl(tap_fd, TUNSETIFF, (void *) &ifr))
430 syslog(LOG_INFO, _("%s is a new style tun/tap device"), tapfname);
431 taptype = TAP_TYPE_TUNTAP;
439 set up the socket that we listen on for incoming
442 int setup_listen_meta_socket(int port)
445 struct sockaddr_in a;
449 if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
451 syslog(LOG_ERR, _("Creating metasocket failed: %m"));
455 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
458 syslog(LOG_ERR, _("System call `%s' failed: %m"),
463 if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one)))
466 syslog(LOG_ERR, _("System call `%s' failed: %m"),
471 flags = fcntl(nfd, F_GETFL);
472 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
475 syslog(LOG_ERR, _("System call `%s' failed: %m"),
480 if((cfg = get_config_val(config, config_interface)))
482 if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, cfg->data.ptr, strlen(cfg->data.ptr)))
485 syslog(LOG_ERR, _("Unable to bind listen socket to interface %s: %m"), cfg->data.ptr);
490 memset(&a, 0, sizeof(a));
491 a.sin_family = AF_INET;
492 a.sin_port = htons(port);
494 if((cfg = get_config_val(config, config_interfaceip)))
495 a.sin_addr.s_addr = htonl(cfg->data.ip->address);
497 a.sin_addr.s_addr = htonl(INADDR_ANY);
499 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
502 syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
509 syslog(LOG_ERR, _("System call `%s' failed: %m"),
518 setup the socket for incoming encrypted
521 int setup_vpn_in_socket(int port)
524 struct sockaddr_in a;
527 if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
530 syslog(LOG_ERR, _("Creating socket failed: %m"));
534 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
537 syslog(LOG_ERR, _("System call `%s' failed: %m"),
542 flags = fcntl(nfd, F_GETFL);
543 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
546 syslog(LOG_ERR, _("System call `%s' failed: %m"),
551 memset(&a, 0, sizeof(a));
552 a.sin_family = AF_INET;
553 a.sin_port = htons(port);
554 a.sin_addr.s_addr = htonl(INADDR_ANY);
556 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
559 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
567 setup an outgoing meta (tcp) socket
569 int setup_outgoing_meta_socket(connection_t *cl)
572 struct sockaddr_in a;
575 if(debug_lvl >= DEBUG_CONNECTIONS)
576 syslog(LOG_INFO, _("Trying to connect to %s"), cl->hostname);
578 if((cfg = get_config_val(cl->config, config_port)) == NULL)
581 cl->port = cfg->data.val;
583 cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
584 if(cl->meta_socket == -1)
586 syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
587 cl->hostname, cl->port);
591 a.sin_family = AF_INET;
592 a.sin_port = htons(cl->port);
593 a.sin_addr.s_addr = htonl(cl->address);
595 if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
597 close(cl->meta_socket);
598 syslog(LOG_ERR, _("%s port %hd: %m"), cl->hostname, cl->port);
602 flags = fcntl(cl->meta_socket, F_GETFL);
603 if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
605 close(cl->meta_socket);
606 syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
607 cl->hostname, cl->port);
611 if(debug_lvl >= DEBUG_CONNECTIONS)
612 syslog(LOG_INFO, _("Connected to %s port %hd"),
613 cl->hostname, cl->port);
621 setup an outgoing connection. It's not
622 necessary to also open an udp socket as
623 well, because the other host will initiate
624 an authentication sequence during which
625 we will do just that.
627 int setup_outgoing_connection(char *name)
635 syslog(LOG_ERR, _("Invalid name for outgoing connection"));
639 ncn = new_connection();
640 asprintf(&ncn->name, "%s", name);
642 if(read_host_config(ncn))
644 syslog(LOG_ERR, _("Error reading host configuration file for %s"));
645 free_connection(ncn);
649 if(!(cfg = get_config_val(ncn->config, config_address)))
651 syslog(LOG_ERR, _("No address specified for %s"));
652 free_connection(ncn);
656 if(!(h = gethostbyname(cfg->data.ptr)))
658 syslog(LOG_ERR, _("Error looking up `%s': %m"), cfg->data.ptr);
659 free_connection(ncn);
663 ncn->address = ntohl(*((ip_t*)(h->h_addr_list[0])));
664 ncn->hostname = hostlookup(htonl(ncn->address));
666 if(setup_outgoing_meta_socket(ncn) < 0)
668 syslog(LOG_ERR, _("Could not set up a meta connection to %s"),
670 free_connection(ncn);
674 ncn->status.outgoing = 1;
675 ncn->buffer = xmalloc(MAXBUFSIZE);
677 ncn->last_ping_time = time(NULL);
687 Configure connection_t myself and set up the local sockets (listen only)
689 int setup_myself(void)
695 myself = new_connection();
697 asprintf(&myself->hostname, "MYSELF"); /* FIXME? Do hostlookup on ourselves? */
699 myself->protocol_version = PROT_CURRENT;
701 if(!(cfg = get_config_val(config, config_name))) /* Not acceptable */
703 syslog(LOG_ERR, _("Name for tinc daemon required!"));
707 asprintf(&myself->name, "%s", (char*)cfg->data.val);
709 if(check_id(myself->name))
711 syslog(LOG_ERR, _("Invalid name for myself!"));
715 if(!(cfg = get_config_val(config, config_privatekey)))
717 syslog(LOG_ERR, _("Private key for tinc daemon required!"));
722 myself->rsa_key = RSA_new();
723 BN_hex2bn(&myself->rsa_key->d, cfg->data.ptr);
724 BN_hex2bn(&myself->rsa_key->e, "FFFF");
727 if(read_host_config(myself))
729 syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
733 if(!(cfg = get_config_val(myself->config, config_publickey)))
735 syslog(LOG_ERR, _("Public key for tinc daemon required!"));
740 BN_hex2bn(&myself->rsa_key->n, cfg->data.ptr);
743 if(RSA_check_key(myself->rsa_key) != 1)
745 syslog(LOG_ERR, _("Invalid public/private keypair!"));
749 if(!(cfg = get_config_val(myself->config, config_port)))
752 myself->port = cfg->data.val;
754 if((cfg = get_config_val(myself->config, config_indirectdata)))
755 if(cfg->data.val == stupid_true)
756 myself->flags |= EXPORTINDIRECTDATA;
758 if((cfg = get_config_val(myself->config, config_tcponly)))
759 if(cfg->data.val == stupid_true)
760 myself->flags |= TCPONLY;
762 /* Read in all the subnets specified in the host configuration file */
764 for(next = myself->config; (cfg = get_config_val(next, config_subnet)); next = cfg->next)
767 net->type = SUBNET_IPV4;
768 net->net.ipv4.address = cfg->data.ip->address;
769 net->net.ipv4.mask = cfg->data.ip->mask;
771 /* Teach newbies what subnets are... */
773 if((net->net.ipv4.address & net->net.ipv4.mask) != net->net.ipv4.address)
775 syslog(LOG_ERR, _("Network address and subnet mask do not match!"));
779 subnet_add(myself, net);
782 if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
784 syslog(LOG_ERR, _("Unable to set up a listening socket!"));
788 /* Generate packet encryption key */
790 myself->cipher_pkttype = EVP_bf_cfb();
792 myself->cipher_pktkeylength = myself->cipher_pkttype->key_len + myself->cipher_pkttype->iv_len;
794 myself->cipher_pktkey = (char *)xmalloc(myself->cipher_pktkeylength);
795 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
797 if(!(cfg = get_config_val(config, config_keyexpire)))
800 keylifetime = cfg->data.val;
802 keyexpires = time(NULL) + keylifetime;
804 /* Activate ourselves */
806 myself->status.active = 1;
808 syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
810 child_pids = list_new();
816 sigalrm_handler(int a)
820 cfg = get_config_val(upstreamcfg, config_connectto);
822 if(!cfg && upstreamcfg == config)
823 /* No upstream IP given, we're listen only. */
828 upstreamcfg = cfg->next;
829 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
831 signal(SIGALRM, SIG_IGN);
834 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
837 signal(SIGALRM, sigalrm_handler);
838 upstreamcfg = config;
839 seconds_till_retry += 5;
840 if(seconds_till_retry > MAXTIMEOUT) /* Don't wait more than MAXTIMEOUT seconds. */
841 seconds_till_retry = MAXTIMEOUT;
842 syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
844 alarm(seconds_till_retry);
849 setup all initial network connections
851 int setup_network_connections(void)
858 if((cfg = get_config_val(config, config_pingtimeout)) == NULL)
862 timeout = cfg->data.val;
869 if(setup_tap_fd() < 0)
872 if(setup_myself() < 0)
875 /* Run tinc-up script to further initialize the tap interface */
876 execute_script("tinc-up");
878 if(!(cfg = get_config_val(config, config_connectto)))
879 /* No upstream IP given, we're listen only. */
884 upstreamcfg = cfg->next;
885 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
887 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
890 signal(SIGALRM, sigalrm_handler);
891 upstreamcfg = config;
892 seconds_till_retry = MAXTIMEOUT;
893 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
894 alarm(seconds_till_retry);
900 close all open network connections
902 void close_network_connections(void)
907 RBL_FOREACH(connection_tree, rbl)
909 p = (connection_t *)rbl->data;
910 p->status.active = 0;
911 terminate_connection(p);
915 if(myself->status.active)
917 close(myself->meta_socket);
918 free_connection(myself);
924 /* Execute tinc-down script right after shutting down the interface */
925 execute_script("tinc-down");
927 destroy_connection_tree();
929 syslog(LOG_NOTICE, _("Terminating"));
935 create a data (udp) socket
937 int setup_vpn_connection(connection_t *cl)
940 struct sockaddr_in a;
943 if(debug_lvl >= DEBUG_TRAFFIC)
944 syslog(LOG_DEBUG, _("Opening UDP socket to %s"), cl->hostname);
946 nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
949 syslog(LOG_ERR, _("Creating UDP socket failed: %m"));
953 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
956 syslog(LOG_ERR, _("System call `%s' failed: %m"),
961 flags = fcntl(nfd, F_GETFL);
962 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
965 syslog(LOG_ERR, _("System call `%s' failed: %m"),
970 memset(&a, 0, sizeof(a));
971 a.sin_family = AF_INET;
972 a.sin_port = htons(myself->port);
973 a.sin_addr.s_addr = htonl(INADDR_ANY);
975 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
978 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), myself->port);
982 a.sin_family = AF_INET;
983 a.sin_port = htons(cl->port);
984 a.sin_addr.s_addr = htonl(cl->address);
986 if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
989 syslog(LOG_ERR, _("Connecting to %s port %d failed: %m"),
990 cl->hostname, cl->port);
994 flags = fcntl(nfd, F_GETFL);
995 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
998 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m %s (%s)"), __FILE__, __LINE__, nfd,
999 cl->name, cl->hostname);
1004 cl->status.dataopen = 1;
1010 handle an incoming tcp connect call and open
1013 connection_t *create_new_connection(int sfd)
1016 struct sockaddr_in ci;
1017 int len = sizeof(ci);
1019 p = new_connection();
1021 if(getpeername(sfd, (struct sockaddr *) &ci, (socklen_t *) &len) < 0)
1023 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1029 p->address = ntohl(ci.sin_addr.s_addr);
1030 p->hostname = hostlookup(ci.sin_addr.s_addr);
1031 p->meta_socket = sfd;
1033 p->buffer = xmalloc(MAXBUFSIZE);
1035 p->last_ping_time = time(NULL);
1037 if(debug_lvl >= DEBUG_CONNECTIONS)
1038 syslog(LOG_NOTICE, _("Connection from %s port %d"),
1039 p->hostname, htons(ci.sin_port));
1041 p->allow_request = ID;
1047 put all file descriptors in an fd_set array
1049 void build_fdset(fd_set *fs)
1056 RBL_FOREACH(connection_tree, rbl)
1058 p = (connection_t *)rbl->data;
1060 FD_SET(p->meta_socket, fs);
1061 if(p->status.dataopen)
1062 FD_SET(p->socket, fs);
1065 FD_SET(myself->meta_socket, fs);
1071 receive incoming data from the listening
1072 udp socket and write it to the ethertap
1073 device after being decrypted
1075 int handle_incoming_vpn_data(connection_t *cl)
1078 int x, l = sizeof(x);
1081 if(getsockopt(cl->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1083 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1084 __FILE__, __LINE__, cl->socket);
1089 syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1093 if((lenin = recv(cl->socket, (char *) &(pkt.len), MTU, 0)) <= 0)
1095 syslog(LOG_ERR, _("Receiving packet failed: %m"));
1099 if(debug_lvl >= DEBUG_TRAFFIC)
1101 syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"), lenin,
1102 cl->name, cl->hostname);
1106 return xrecv(cl, &pkt);
1110 terminate a connection and notify the other
1111 end before closing the sockets
1113 void terminate_connection(connection_t *cl)
1119 if(cl->status.remove)
1122 cl->status.remove = 1;
1124 if(debug_lvl >= DEBUG_CONNECTIONS)
1125 syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1126 cl->name, cl->hostname);
1131 close(cl->meta_socket);
1133 /* Find all connections that were lost because they were behind cl
1134 (the connection that was dropped). */
1137 RBL_FOREACH(connection_tree, rbl)
1139 p = (connection_t *)rbl->data;
1140 if(p->nexthop == cl && p != cl)
1141 terminate_connection(p);
1144 /* Inform others of termination if it was still active */
1146 if(cl->status.active)
1147 RBL_FOREACH(connection_tree, rbl)
1149 p = (connection_t *)rbl->data;
1150 if(p->status.meta && p->status.active && p!=cl)
1151 send_del_host(p, cl); /* Sounds like recursion, but p does not have a meta connection :) */
1154 /* Remove the associated subnets */
1156 RBL_FOREACH(cl->subnet_tree, rbl)
1158 subnet = (subnet_t *)rbl->data;
1162 /* Check if this was our outgoing connection */
1164 if(cl->status.outgoing && cl->status.active)
1166 signal(SIGALRM, sigalrm_handler);
1167 seconds_till_retry = 5;
1168 alarm(seconds_till_retry);
1169 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
1174 cl->status.active = 0;
1179 Check if the other end is active.
1180 If we have sent packets, but didn't receive any,
1181 then possibly the other end is dead. We send a
1182 PING request over the meta connection. If the other
1183 end does not reply in time, we consider them dead
1184 and close the connection.
1186 void check_dead_connections(void)
1194 RBL_FOREACH(connection_tree, rbl)
1196 cl = (connection_t *)rbl->data;
1197 if(cl->status.active && cl->status.meta)
1199 if(cl->last_ping_time + timeout < now)
1201 if(cl->status.pinged)
1203 if(debug_lvl >= DEBUG_PROTOCOL)
1204 syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1205 cl->name, cl->hostname);
1206 cl->status.timeout = 1;
1207 terminate_connection(cl);
1220 accept a new tcp connect and create a
1223 int handle_new_meta_connection()
1226 struct sockaddr client;
1227 int nfd, len = sizeof(client);
1229 if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
1231 syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1235 if(!(ncn = create_new_connection(nfd)))
1239 syslog(LOG_NOTICE, _("Closed attempted connection"));
1243 connection_add(ncn);
1249 check all connections to see if anything
1250 happened on their sockets
1252 void check_network_activity(fd_set *f)
1257 RBL_FOREACH(connection_tree, rbl)
1259 p = (connection_t *)rbl->data;
1261 if(p->status.remove)
1264 if(p->status.dataopen)
1265 if(FD_ISSET(p->socket, f))
1267 handle_incoming_vpn_data(p);
1269 /* Old error stuff (FIXME: copy this to handle_incoming_vpn_data()
1271 getsockopt(p->socket, SOL_SOCKET, SO_ERROR, &x, &l);
1272 syslog(LOG_ERR, _("Outgoing data socket error for %s (%s): %s"),
1273 p->name, p->hostname, strerror(x));
1274 terminate_connection(p);
1280 if(FD_ISSET(p->meta_socket, f))
1281 if(receive_meta(p) < 0)
1283 terminate_connection(p);
1288 if(FD_ISSET(myself->meta_socket, f))
1289 handle_new_meta_connection();
1294 read, encrypt and send data that is
1295 available through the ethertap device
1297 void handle_tap_input(void)
1302 if(taptype == TAP_TYPE_TUNTAP)
1304 if((lenin = read(tap_fd, vp.data, MTU)) <= 0)
1306 syslog(LOG_ERR, _("Error while reading from tun/tap device: %m"));
1313 if((lenin = read(tap_fd, vp.data - 2, MTU)) <= 0)
1315 syslog(LOG_ERR, _("Error while reading from ethertap device: %m"));
1321 total_tap_in += lenin;
1325 if(debug_lvl >= DEBUG_TRAFFIC)
1326 syslog(LOG_WARNING, _("Received short packet from tap device"));
1330 if(debug_lvl >= DEBUG_TRAFFIC)
1332 syslog(LOG_DEBUG, _("Read packet of length %d from tap device"), vp.len);
1335 send_packet(ntohl(*((unsigned long*)(&vp.data[30]))), &vp);
1340 this is where it all happens...
1342 void main_loop(void)
1347 time_t last_ping_check;
1350 last_ping_check = time(NULL);
1354 tv.tv_sec = timeout;
1357 prune_connection_tree();
1360 if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1362 if(errno != EINTR) /* because of alarm */
1364 syslog(LOG_ERR, _("Error while waiting for input: %m"));
1371 syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1373 close_network_connections();
1374 clear_config(&config);
1376 if(read_server_config())
1378 syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1384 if(setup_network_connections())
1392 /* Let's check if everybody is still alive */
1394 if(last_ping_check + timeout < t)
1396 check_dead_connections();
1397 last_ping_check = time(NULL);
1399 /* Should we regenerate our key? */
1403 if(debug_lvl >= DEBUG_STATUS)
1404 syslog(LOG_INFO, _("Regenerating symmetric key"));
1406 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
1407 send_key_changed(myself, NULL);
1408 keyexpires = time(NULL) + keylifetime;
1414 check_network_activity(&fset);
1416 /* local tap data */
1417 if(FD_ISSET(tap_fd, &fset))