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.83 2000/11/30 20:08:41 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>
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)
103 struct sockaddr_in to;
104 socklen_t tolen = sizeof(to);
106 outpkt.len = inpkt->len;
108 /* Encrypt the packet */
110 EVP_EncryptInit(&ctx, cl->cipher_pkttype, cl->cipher_pktkey, cl->cipher_pktkey + cl->cipher_pkttype->key_len);
111 EVP_EncryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len);
112 EVP_EncryptFinal(&ctx, outpkt.data + outlen, &outpad);
113 outlen += outpad + 2;
116 outlen = outpkt.len + 2;
117 memcpy(&outpkt, inpkt, outlen);
120 if(debug_lvl >= DEBUG_TRAFFIC)
121 syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
122 outlen, cl->name, cl->hostname);
124 total_socket_out += outlen;
126 to.sin_family = AF_INET;
127 to.sin_addr.s_addr = htonl(cl->address);
128 to.sin_port = htons(cl->port);
130 if((sendto(myself->socket, (char *) &(outpkt.len), outlen, 0, (const struct sockaddr *)&to, tolen)) < 0)
132 syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
133 cl->name, cl->hostname);
140 int xrecv(connection_t *cl, vpn_packet_t *inpkt)
146 outpkt.len = inpkt->len;
148 /* Decrypt the packet */
150 EVP_DecryptInit(&ctx, myself->cipher_pkttype, myself->cipher_pktkey, myself->cipher_pktkey + myself->cipher_pkttype->key_len);
151 EVP_DecryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len + 8);
152 EVP_DecryptFinal(&ctx, outpkt.data + outlen, &outpad);
156 outlen = outpkt.len+2;
157 memcpy(&outpkt, inpkt, outlen);
160 if(debug_lvl >= DEBUG_TRAFFIC)
161 syslog(LOG_ERR, _("Writing packet of %d bytes to tap device"),
164 /* Fix mac address */
166 memcpy(outpkt.data, mymac.net.mac.address.x, 6);
168 if(taptype == TAP_TYPE_TUNTAP)
170 if(write(tap_fd, outpkt.data, outpkt.len) < 0)
171 syslog(LOG_ERR, _("Can't write to tun/tap device: %m"));
173 total_tap_out += outpkt.len;
177 if(write(tap_fd, outpkt.data - 2, outpkt.len + 2) < 0)
178 syslog(LOG_ERR, _("Can't write to ethertap device: %m"));
180 total_tap_out += outpkt.len + 2;
187 add the given packet of size s to the
188 queue q, be it the send or receive queue
190 void add_queue(packet_queue_t **q, void *packet, size_t s)
194 e = xmalloc(sizeof(*e));
195 e->packet = xmalloc(s);
196 memcpy(e->packet, packet, s);
200 *q = xmalloc(sizeof(**q));
201 (*q)->head = (*q)->tail = NULL;
204 e->next = NULL; /* We insert at the tail */
206 if((*q)->tail) /* Do we have a tail? */
208 (*q)->tail->next = e;
209 e->prev = (*q)->tail;
211 else /* No tail -> no head too */
221 /* Remove a queue element */
222 void del_queue(packet_queue_t **q, queue_element_t *e)
227 if(e->next) /* There is a successor, so we are not tail */
229 if(e->prev) /* There is a predecessor, so we are not head */
231 e->next->prev = e->prev;
232 e->prev->next = e->next;
234 else /* We are head */
236 e->next->prev = NULL;
237 (*q)->head = e->next;
240 else /* We are tail (or all alone!) */
242 if(e->prev) /* We are not alone :) */
244 e->prev->next = NULL;
245 (*q)->tail = e->prev;
259 flush a queue by calling function for
260 each packet, and removing it when that
261 returned a zero exit code
263 void flush_queue(connection_t *cl, packet_queue_t **pq,
264 int (*function)(connection_t*,vpn_packet_t*))
266 queue_element_t *p, *next = NULL;
268 for(p = (*pq)->head; p != NULL; )
272 if(!function(cl, p->packet))
278 if(debug_lvl >= DEBUG_TRAFFIC)
279 syslog(LOG_DEBUG, _("Queue flushed"));
284 flush the send&recv queues
285 void because nothing goes wrong here, packets
286 remain in the queue if something goes wrong
288 void flush_queues(connection_t *cl)
293 if(debug_lvl >= DEBUG_TRAFFIC)
294 syslog(LOG_DEBUG, _("Flushing send queue for %s (%s)"),
295 cl->name, cl->hostname);
296 flush_queue(cl, &(cl->sq), xsend);
301 if(debug_lvl >= DEBUG_TRAFFIC)
302 syslog(LOG_DEBUG, _("Flushing receive queue for %s (%s)"),
303 cl->name, cl->hostname);
304 flush_queue(cl, &(cl->rq), xrecv);
310 send a packet to the given vpn ip.
312 int send_packet(ip_t to, vpn_packet_t *packet)
317 if((subnet = lookup_subnet_ipv4(to)) == NULL)
319 if(debug_lvl >= DEBUG_TRAFFIC)
321 syslog(LOG_NOTICE, _("Trying to look up %d.%d.%d.%d in connection list failed!"),
332 if(debug_lvl >= DEBUG_TRAFFIC)
334 syslog(LOG_NOTICE, _("Packet with destination %d.%d.%d.%d is looping back to us!"),
341 /* If we ourselves have indirectdata flag set, we should send only to our uplink! */
343 /* FIXME - check for indirection and reprogram it The Right Way(tm) this time. */
345 if(!cl->status.validkey)
347 /* FIXME: Don't queue until everything else is fixed.
348 if(debug_lvl >= DEBUG_TRAFFIC)
349 syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
350 cl->name, cl->hostname);
351 add_queue(&(cl->sq), packet, packet->len + 2);
353 if(!cl->status.waitingforkey)
354 send_req_key(myself, cl); /* Keys should be sent to the host running the tincd */
358 if(!cl->status.active)
360 /* FIXME: Don't queue until everything else is fixed.
361 if(debug_lvl >= DEBUG_TRAFFIC)
362 syslog(LOG_INFO, _("%s (%s) is not ready, queueing packet"),
363 cl->name, cl->hostname);
364 add_queue(&(cl->sq), packet, packet->len + 2);
366 return 0; /* We don't want to mess up, do we? */
369 /* can we send it? can we? can we? huh? */
371 return xsend(cl, packet);
375 open the local ethertap device
377 int setup_tap_fd(void)
380 const char *tapfname;
389 if((cfg = get_config_val(config, config_tapdevice)))
390 tapfname = cfg->data.ptr;
395 tapfname = "/dev/misc/net/tun";
397 tapfname = "/dev/tap0";
401 tapfname = "/dev/tap0";
404 tapfname = "/dev/tun";
408 if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
410 syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
416 taptype = TAP_TYPE_ETHERTAP;
418 /* Set default MAC address for ethertap devices */
420 mymac.type = SUBNET_MAC;
421 mymac.net.mac.address.x[0] = 0xfe;
422 mymac.net.mac.address.x[1] = 0xfd;
423 mymac.net.mac.address.x[2] = 0x00;
424 mymac.net.mac.address.x[3] = 0x00;
425 mymac.net.mac.address.x[4] = 0x00;
426 mymac.net.mac.address.x[5] = 0x00;
430 /* Ok now check if this is an old ethertap or a new tun/tap thingie */
431 memset(&ifr, 0, sizeof(ifr));
433 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
435 strncpy(ifr.ifr_name, netname, IFNAMSIZ);
437 if (!ioctl(tap_fd, TUNSETIFF, (void *) &ifr))
439 syslog(LOG_INFO, _("%s is a new style tun/tap device"), tapfname);
440 taptype = TAP_TYPE_TUNTAP;
445 taptype = TAP_TYPE_TUNTAP;
452 set up the socket that we listen on for incoming
455 int setup_listen_meta_socket(int port)
458 struct sockaddr_in a;
462 if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
464 syslog(LOG_ERR, _("Creating metasocket failed: %m"));
468 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
471 syslog(LOG_ERR, _("System call `%s' failed: %m"),
476 if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one)))
479 syslog(LOG_ERR, _("System call `%s' failed: %m"),
484 flags = fcntl(nfd, F_GETFL);
485 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
488 syslog(LOG_ERR, _("System call `%s' failed: %m"),
493 if((cfg = get_config_val(config, config_interface)))
495 if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, cfg->data.ptr, strlen(cfg->data.ptr)))
498 syslog(LOG_ERR, _("Unable to bind listen socket to interface %s: %m"), cfg->data.ptr);
503 memset(&a, 0, sizeof(a));
504 a.sin_family = AF_INET;
505 a.sin_port = htons(port);
507 if((cfg = get_config_val(config, config_interfaceip)))
508 a.sin_addr.s_addr = htonl(cfg->data.ip->address);
510 a.sin_addr.s_addr = htonl(INADDR_ANY);
512 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
515 syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
522 syslog(LOG_ERR, _("System call `%s' failed: %m"),
531 setup the socket for incoming encrypted
534 int setup_vpn_in_socket(int port)
537 struct sockaddr_in a;
540 if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
543 syslog(LOG_ERR, _("Creating socket failed: %m"));
547 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
550 syslog(LOG_ERR, _("System call `%s' failed: %m"),
555 flags = fcntl(nfd, F_GETFL);
556 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
559 syslog(LOG_ERR, _("System call `%s' failed: %m"),
564 memset(&a, 0, sizeof(a));
565 a.sin_family = AF_INET;
566 a.sin_port = htons(port);
567 a.sin_addr.s_addr = htonl(INADDR_ANY);
569 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
572 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
580 setup an outgoing meta (tcp) socket
582 int setup_outgoing_meta_socket(connection_t *cl)
585 struct sockaddr_in a;
588 if(debug_lvl >= DEBUG_CONNECTIONS)
589 syslog(LOG_INFO, _("Trying to connect to %s"), cl->hostname);
591 if((cfg = get_config_val(cl->config, config_port)) == NULL)
594 cl->port = cfg->data.val;
596 cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
597 if(cl->meta_socket == -1)
599 syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
600 cl->hostname, cl->port);
604 a.sin_family = AF_INET;
605 a.sin_port = htons(cl->port);
606 a.sin_addr.s_addr = htonl(cl->address);
608 if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
610 close(cl->meta_socket);
611 syslog(LOG_ERR, _("%s port %hd: %m"), cl->hostname, cl->port);
615 flags = fcntl(cl->meta_socket, F_GETFL);
616 if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
618 close(cl->meta_socket);
619 syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
620 cl->hostname, cl->port);
624 if(debug_lvl >= DEBUG_CONNECTIONS)
625 syslog(LOG_INFO, _("Connected to %s port %hd"),
626 cl->hostname, cl->port);
634 Setup an outgoing meta connection.
636 int setup_outgoing_connection(char *name)
644 syslog(LOG_ERR, _("Invalid name for outgoing connection"));
648 ncn = new_connection();
649 asprintf(&ncn->name, "%s", name);
651 if(read_host_config(ncn))
653 syslog(LOG_ERR, _("Error reading host configuration file for %s"));
654 free_connection(ncn);
658 if(!(cfg = get_config_val(ncn->config, config_address)))
660 syslog(LOG_ERR, _("No address specified for %s"));
661 free_connection(ncn);
665 if(!(h = gethostbyname(cfg->data.ptr)))
667 syslog(LOG_ERR, _("Error looking up `%s': %m"), cfg->data.ptr);
668 free_connection(ncn);
672 ncn->address = ntohl(*((ip_t*)(h->h_addr_list[0])));
673 ncn->hostname = hostlookup(htonl(ncn->address));
675 if(setup_outgoing_meta_socket(ncn) < 0)
677 syslog(LOG_ERR, _("Could not set up a meta connection to %s"),
679 free_connection(ncn);
683 ncn->status.outgoing = 1;
684 ncn->buffer = xmalloc(MAXBUFSIZE);
686 ncn->last_ping_time = time(NULL);
695 int read_rsa_private_key(RSA **key, const char *file)
699 if((fp = fopen(file, "r")) == NULL)
701 syslog(LOG_ERR, _("Error reading file `%s': %m"),
705 PEM_read_RSAPrivateKey(fp, key, NULL, NULL);
708 int read_rsa_keys(void)
712 if(!(cfg = get_config_val(config, config_privatekey)))
714 syslog(LOG_ERR, _("Private key for tinc daemon required!"));
718 myself->rsa_key = RSA_new();
719 return read_rsa_private_key(&(myself->rsa_key), cfg->data.ptr);
723 Configure connection_t myself and set up the local sockets (listen only)
725 int setup_myself(void)
731 myself = new_connection();
733 asprintf(&myself->hostname, "MYSELF"); /* FIXME? Do hostlookup on ourselves? */
735 myself->protocol_version = PROT_CURRENT;
737 if(!(cfg = get_config_val(config, config_name))) /* Not acceptable */
739 syslog(LOG_ERR, _("Name for tinc daemon required!"));
743 asprintf(&myself->name, "%s", (char*)cfg->data.val);
745 if(check_id(myself->name))
747 syslog(LOG_ERR, _("Invalid name for myself!"));
754 if(read_host_config(myself))
756 syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
760 if(!(cfg = get_config_val(myself->config, config_publickey)))
762 syslog(LOG_ERR, _("Public key for tinc daemon required!"));
767 BN_hex2bn(&myself->rsa_key->n, cfg->data.ptr);
770 if(RSA_check_key(myself->rsa_key) != 1)
772 syslog(LOG_ERR, _("Invalid public/private keypair!"));
776 if(!(cfg = get_config_val(myself->config, config_port)))
779 myself->port = cfg->data.val;
781 if((cfg = get_config_val(myself->config, config_indirectdata)))
782 if(cfg->data.val == stupid_true)
783 myself->flags |= EXPORTINDIRECTDATA;
785 if((cfg = get_config_val(myself->config, config_tcponly)))
786 if(cfg->data.val == stupid_true)
787 myself->flags |= TCPONLY;
789 /* Read in all the subnets specified in the host configuration file */
791 for(next = myself->config; (cfg = get_config_val(next, config_subnet)); next = cfg->next)
794 net->type = SUBNET_IPV4;
795 net->net.ipv4.address = cfg->data.ip->address;
796 net->net.ipv4.mask = cfg->data.ip->mask;
798 /* Teach newbies what subnets are... */
800 if((net->net.ipv4.address & net->net.ipv4.mask) != net->net.ipv4.address)
802 syslog(LOG_ERR, _("Network address and subnet mask do not match!"));
806 subnet_add(myself, net);
809 if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
811 syslog(LOG_ERR, _("Unable to set up a listening TCP socket!"));
815 if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
817 syslog(LOG_ERR, _("Unable to set up a listening UDP socket!"));
821 /* Generate packet encryption key */
823 myself->cipher_pkttype = EVP_bf_cfb();
825 myself->cipher_pktkeylength = myself->cipher_pkttype->key_len + myself->cipher_pkttype->iv_len;
827 myself->cipher_pktkey = (char *)xmalloc(myself->cipher_pktkeylength);
828 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
830 if(!(cfg = get_config_val(config, config_keyexpire)))
833 keylifetime = cfg->data.val;
835 keyexpires = time(NULL) + keylifetime;
837 /* Activate ourselves */
839 myself->status.active = 1;
841 syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
847 sigalrm_handler(int a)
851 cfg = get_config_val(upstreamcfg, config_connectto);
853 if(!cfg && upstreamcfg == config)
854 /* No upstream IP given, we're listen only. */
859 upstreamcfg = cfg->next;
860 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
862 signal(SIGALRM, SIG_IGN);
865 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
868 signal(SIGALRM, sigalrm_handler);
869 upstreamcfg = config;
870 seconds_till_retry += 5;
871 if(seconds_till_retry > MAXTIMEOUT) /* Don't wait more than MAXTIMEOUT seconds. */
872 seconds_till_retry = MAXTIMEOUT;
873 syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
875 alarm(seconds_till_retry);
880 setup all initial network connections
882 int setup_network_connections(void)
889 if((cfg = get_config_val(config, config_pingtimeout)) == NULL)
893 timeout = cfg->data.val;
900 if(setup_tap_fd() < 0)
903 /* Run tinc-up script to further initialize the tap interface */
904 execute_script("tinc-up");
906 if(setup_myself() < 0)
909 if(!(cfg = get_config_val(config, config_connectto)))
910 /* No upstream IP given, we're listen only. */
915 upstreamcfg = cfg->next;
916 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
918 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
921 signal(SIGALRM, sigalrm_handler);
922 upstreamcfg = config;
923 seconds_till_retry = MAXTIMEOUT;
924 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
925 alarm(seconds_till_retry);
931 close all open network connections
933 void close_network_connections(void)
938 RBL_FOREACH(connection_tree, rbl)
940 p = (connection_t *)rbl->data;
941 p->status.active = 0;
942 terminate_connection(p);
946 if(myself->status.active)
948 close(myself->meta_socket);
949 free_connection(myself);
955 /* Execute tinc-down script right after shutting down the interface */
956 execute_script("tinc-down");
958 destroy_connection_tree();
964 create a data (udp) socket
965 OBSOLETED: use only one listening socket for compatibility with non-Linux operating systems
967 int setup_vpn_connection(connection_t *cl)
970 struct sockaddr_in a;
973 if(debug_lvl >= DEBUG_TRAFFIC)
974 syslog(LOG_DEBUG, _("Opening UDP socket to %s"), cl->hostname);
976 nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
979 syslog(LOG_ERR, _("Creating UDP socket failed: %m"));
983 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
986 syslog(LOG_ERR, _("System call `%s' failed: %m"),
991 flags = fcntl(nfd, F_GETFL);
992 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
995 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1000 memset(&a, 0, sizeof(a));
1001 a.sin_family = AF_INET;
1002 a.sin_port = htons(myself->port);
1003 a.sin_addr.s_addr = htonl(INADDR_ANY);
1005 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
1008 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), myself->port);
1012 a.sin_family = AF_INET;
1013 a.sin_port = htons(cl->port);
1014 a.sin_addr.s_addr = htonl(cl->address);
1016 if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
1019 syslog(LOG_ERR, _("Connecting to %s port %d failed: %m"),
1020 cl->hostname, cl->port);
1024 flags = fcntl(nfd, F_GETFL);
1025 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
1028 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m %s (%s)"), __FILE__, __LINE__, nfd,
1029 cl->name, cl->hostname);
1034 cl->status.dataopen = 1;
1040 handle an incoming tcp connect call and open
1043 connection_t *create_new_connection(int sfd)
1046 struct sockaddr_in ci;
1047 int len = sizeof(ci);
1049 p = new_connection();
1051 if(getpeername(sfd, (struct sockaddr *) &ci, (socklen_t *) &len) < 0)
1053 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1059 p->address = ntohl(ci.sin_addr.s_addr);
1060 p->hostname = hostlookup(ci.sin_addr.s_addr);
1061 p->meta_socket = sfd;
1063 p->buffer = xmalloc(MAXBUFSIZE);
1065 p->last_ping_time = time(NULL);
1067 if(debug_lvl >= DEBUG_CONNECTIONS)
1068 syslog(LOG_NOTICE, _("Connection from %s port %d"),
1069 p->hostname, htons(ci.sin_port));
1071 p->allow_request = ID;
1077 put all file descriptors in an fd_set array
1079 void build_fdset(fd_set *fs)
1086 FD_SET(myself->socket, fs);
1088 RBL_FOREACH(connection_tree, rbl)
1090 p = (connection_t *)rbl->data;
1092 FD_SET(p->meta_socket, fs);
1095 FD_SET(myself->meta_socket, fs);
1101 receive incoming data from the listening
1102 udp socket and write it to the ethertap
1103 device after being decrypted
1105 int handle_incoming_vpn_data(void)
1108 int x, l = sizeof(x);
1110 struct sockaddr_in from;
1111 socklen_t fromlen = sizeof(from);
1114 if(getsockopt(myself->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1116 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1117 __FILE__, __LINE__, myself->socket);
1122 syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1126 if((lenin = recvfrom(myself->socket, (char *) &(pkt.len), MTU, 0, (struct sockaddr *)&from, &fromlen)) <= 0)
1128 syslog(LOG_ERR, _("Receiving packet failed: %m"));
1132 cl = lookup_connection(ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
1136 syslog(LOG_WARNING, _("Received UDP packets on port %d from unknown source %lx:%d"), ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
1140 if(debug_lvl >= DEBUG_TRAFFIC)
1142 syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"), lenin,
1143 cl->name, cl->hostname);
1147 return xrecv(cl, &pkt);
1151 terminate a connection and notify the other
1152 end before closing the sockets
1154 void terminate_connection(connection_t *cl)
1160 if(cl->status.remove)
1163 cl->status.remove = 1;
1165 if(debug_lvl >= DEBUG_CONNECTIONS)
1166 syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1167 cl->name, cl->hostname);
1172 close(cl->meta_socket);
1174 /* Find all connections that were lost because they were behind cl
1175 (the connection that was dropped). */
1178 RBL_FOREACH(connection_tree, rbl)
1180 p = (connection_t *)rbl->data;
1181 if(p->nexthop == cl && p != cl)
1182 terminate_connection(p);
1185 /* Inform others of termination if it was still active */
1187 if(cl->status.active)
1188 RBL_FOREACH(connection_tree, rbl)
1190 p = (connection_t *)rbl->data;
1191 if(p->status.meta && p->status.active && p!=cl)
1192 send_del_host(p, cl); /* Sounds like recursion, but p does not have a meta connection :) */
1195 /* Remove the associated subnets */
1197 RBL_FOREACH(cl->subnet_tree, rbl)
1199 subnet = (subnet_t *)rbl->data;
1203 /* Check if this was our outgoing connection */
1205 if(cl->status.outgoing && cl->status.active)
1207 signal(SIGALRM, sigalrm_handler);
1208 seconds_till_retry = 5;
1209 alarm(seconds_till_retry);
1210 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
1215 cl->status.active = 0;
1220 Check if the other end is active.
1221 If we have sent packets, but didn't receive any,
1222 then possibly the other end is dead. We send a
1223 PING request over the meta connection. If the other
1224 end does not reply in time, we consider them dead
1225 and close the connection.
1227 void check_dead_connections(void)
1235 RBL_FOREACH(connection_tree, rbl)
1237 cl = (connection_t *)rbl->data;
1238 if(cl->status.active && cl->status.meta)
1240 if(cl->last_ping_time + timeout < now)
1242 if(cl->status.pinged)
1244 if(debug_lvl >= DEBUG_PROTOCOL)
1245 syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1246 cl->name, cl->hostname);
1247 cl->status.timeout = 1;
1248 terminate_connection(cl);
1261 accept a new tcp connect and create a
1264 int handle_new_meta_connection()
1267 struct sockaddr client;
1268 int nfd, len = sizeof(client);
1270 if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
1272 syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1276 if(!(ncn = create_new_connection(nfd)))
1280 syslog(LOG_NOTICE, _("Closed attempted connection"));
1284 connection_add(ncn);
1290 check all connections to see if anything
1291 happened on their sockets
1293 void check_network_activity(fd_set *f)
1298 if(FD_ISSET(myself->socket, f))
1299 handle_incoming_vpn_data();
1301 RBL_FOREACH(connection_tree, rbl)
1303 p = (connection_t *)rbl->data;
1305 if(p->status.remove)
1309 if(FD_ISSET(p->meta_socket, f))
1310 if(receive_meta(p) < 0)
1312 terminate_connection(p);
1317 if(FD_ISSET(myself->meta_socket, f))
1318 handle_new_meta_connection();
1323 read, encrypt and send data that is
1324 available through the ethertap device
1326 void handle_tap_input(void)
1331 if(taptype == TAP_TYPE_TUNTAP)
1333 if((lenin = read(tap_fd, vp.data, MTU)) <= 0)
1335 syslog(LOG_ERR, _("Error while reading from tun/tap device: %m"));
1342 if((lenin = read(tap_fd, vp.data - 2, MTU)) <= 0)
1344 syslog(LOG_ERR, _("Error while reading from ethertap device: %m"));
1350 total_tap_in += lenin;
1354 if(debug_lvl >= DEBUG_TRAFFIC)
1355 syslog(LOG_WARNING, _("Received short packet from tap device"));
1359 if(debug_lvl >= DEBUG_TRAFFIC)
1361 syslog(LOG_DEBUG, _("Read packet of length %d from tap device"), vp.len);
1364 send_packet(ntohl(*((unsigned long*)(&vp.data[30]))), &vp);
1369 this is where it all happens...
1371 void main_loop(void)
1376 time_t last_ping_check;
1379 last_ping_check = time(NULL);
1383 tv.tv_sec = timeout;
1386 prune_connection_tree();
1389 if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1391 if(errno != EINTR) /* because of alarm */
1393 syslog(LOG_ERR, _("Error while waiting for input: %m"));
1400 syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1402 close_network_connections();
1403 clear_config(&config);
1405 if(read_server_config())
1407 syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1413 if(setup_network_connections())
1421 /* Let's check if everybody is still alive */
1423 if(last_ping_check + timeout < t)
1425 check_dead_connections();
1426 last_ping_check = time(NULL);
1428 /* Should we regenerate our key? */
1432 if(debug_lvl >= DEBUG_STATUS)
1433 syslog(LOG_INFO, _("Regenerating symmetric key"));
1435 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
1436 send_key_changed(myself, NULL);
1437 keyexpires = time(NULL) + keylifetime;
1443 check_network_activity(&fset);
1445 /* local tap data */
1446 if(FD_ISSET(tap_fd, &fset))