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.87 2000/12/05 08:59:29 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_public_key(RSA **key, const char *file)
705 if((fp = fopen(file, "r")) == NULL)
707 syslog(LOG_ERR, _("Error reading RSA public key file `%s': %m"),
711 if(PEM_read_RSAPublicKey(fp, key, NULL, NULL) == NULL)
713 syslog(LOG_ERR, _("Reading RSA private key file `%s' failed: %m"),
721 int read_rsa_private_key(RSA **key, const char *file)
725 if((fp = fopen(file, "r")) == NULL)
727 syslog(LOG_ERR, _("Error reading RSA private key file `%s': %m"),
731 if(PEM_read_RSAPrivateKey(fp, key, NULL, NULL) == NULL)
733 syslog(LOG_ERR, _("Reading RSA private key file `%s' failed: %m"),
741 int read_rsa_keys(void)
745 if(!(cfg = get_config_val(config, config_privatekey)))
747 syslog(LOG_ERR, _("Private key for tinc daemon required!"));
751 myself->rsa_key = RSA_new();
753 return read_rsa_private_key(&(myself->rsa_key), cfg->data.ptr);
757 Configure connection_t myself and set up the local sockets (listen only)
759 int setup_myself(void)
765 myself = new_connection();
767 asprintf(&myself->hostname, "MYSELF"); /* FIXME? Do hostlookup on ourselves? */
769 myself->protocol_version = PROT_CURRENT;
771 if(!(cfg = get_config_val(config, config_name))) /* Not acceptable */
773 syslog(LOG_ERR, _("Name for tinc daemon required!"));
777 asprintf(&myself->name, "%s", (char*)cfg->data.val);
779 if(check_id(myself->name))
781 syslog(LOG_ERR, _("Invalid name for myself!"));
788 if(read_host_config(myself))
790 syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
796 if(RSA_check_key(myself->rsa_key) != 1)
798 syslog(LOG_ERR, _("Invalid public/private keypair!"));
802 if(!(cfg = get_config_val(myself->config, config_port)))
805 myself->port = cfg->data.val;
807 if((cfg = get_config_val(myself->config, config_indirectdata)))
808 if(cfg->data.val == stupid_true)
809 myself->flags |= EXPORTINDIRECTDATA;
811 if((cfg = get_config_val(myself->config, config_tcponly)))
812 if(cfg->data.val == stupid_true)
813 myself->flags |= TCPONLY;
815 /* Read in all the subnets specified in the host configuration file */
817 for(next = myself->config; (cfg = get_config_val(next, config_subnet)); next = cfg->next)
820 net->type = SUBNET_IPV4;
821 net->net.ipv4.address = cfg->data.ip->address;
822 net->net.ipv4.mask = cfg->data.ip->mask;
824 /* Teach newbies what subnets are... */
826 if((net->net.ipv4.address & net->net.ipv4.mask) != net->net.ipv4.address)
828 syslog(LOG_ERR, _("Network address and subnet mask do not match!"));
832 subnet_add(myself, net);
835 if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
837 syslog(LOG_ERR, _("Unable to set up a listening TCP socket!"));
841 if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
843 syslog(LOG_ERR, _("Unable to set up a listening UDP socket!"));
847 /* Generate packet encryption key */
849 myself->cipher_pkttype = EVP_bf_cfb();
851 myself->cipher_pktkeylength = myself->cipher_pkttype->key_len + myself->cipher_pkttype->iv_len;
853 myself->cipher_pktkey = (char *)xmalloc(myself->cipher_pktkeylength);
854 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
856 if(!(cfg = get_config_val(config, config_keyexpire)))
859 keylifetime = cfg->data.val;
861 keyexpires = time(NULL) + keylifetime;
863 /* Activate ourselves */
865 myself->status.active = 1;
867 syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
873 sigalrm_handler(int a)
877 cfg = get_config_val(upstreamcfg, config_connectto);
879 if(!cfg && upstreamcfg == config)
880 /* No upstream IP given, we're listen only. */
885 upstreamcfg = cfg->next;
886 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
888 signal(SIGALRM, SIG_IGN);
891 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
894 signal(SIGALRM, sigalrm_handler);
895 upstreamcfg = config;
896 seconds_till_retry += 5;
897 if(seconds_till_retry > MAXTIMEOUT) /* Don't wait more than MAXTIMEOUT seconds. */
898 seconds_till_retry = MAXTIMEOUT;
899 syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
901 alarm(seconds_till_retry);
906 setup all initial network connections
908 int setup_network_connections(void)
915 if((cfg = get_config_val(config, config_pingtimeout)) == NULL)
919 timeout = cfg->data.val;
926 if(setup_tap_fd() < 0)
929 /* Run tinc-up script to further initialize the tap interface */
930 execute_script("tinc-up");
932 if(setup_myself() < 0)
935 if(!(cfg = get_config_val(config, config_connectto)))
936 /* No upstream IP given, we're listen only. */
941 upstreamcfg = cfg->next;
942 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
944 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
947 signal(SIGALRM, sigalrm_handler);
948 upstreamcfg = config;
949 seconds_till_retry = MAXTIMEOUT;
950 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
951 alarm(seconds_till_retry);
957 close all open network connections
959 void close_network_connections(void)
964 RBL_FOREACH(connection_tree, rbl)
966 p = (connection_t *)rbl->data;
967 p->status.active = 0;
968 terminate_connection(p);
972 if(myself->status.active)
974 close(myself->meta_socket);
975 free_connection(myself);
981 /* Execute tinc-down script right after shutting down the interface */
982 execute_script("tinc-down");
984 destroy_connection_tree();
990 create a data (udp) socket
991 OBSOLETED: use only one listening socket for compatibility with non-Linux operating systems
993 int setup_vpn_connection(connection_t *cl)
996 struct sockaddr_in a;
999 if(debug_lvl >= DEBUG_TRAFFIC)
1000 syslog(LOG_DEBUG, _("Opening UDP socket to %s"), cl->hostname);
1002 nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
1005 syslog(LOG_ERR, _("Creating UDP socket failed: %m"));
1009 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
1012 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1017 flags = fcntl(nfd, F_GETFL);
1018 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
1021 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1026 memset(&a, 0, sizeof(a));
1027 a.sin_family = AF_INET;
1028 a.sin_port = htons(myself->port);
1029 a.sin_addr.s_addr = htonl(INADDR_ANY);
1031 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
1034 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), myself->port);
1038 a.sin_family = AF_INET;
1039 a.sin_port = htons(cl->port);
1040 a.sin_addr.s_addr = htonl(cl->address);
1042 if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
1045 syslog(LOG_ERR, _("Connecting to %s port %d failed: %m"),
1046 cl->hostname, cl->port);
1050 flags = fcntl(nfd, F_GETFL);
1051 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
1054 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m %s (%s)"), __FILE__, __LINE__, nfd,
1055 cl->name, cl->hostname);
1060 cl->status.dataopen = 1;
1066 handle an incoming tcp connect call and open
1069 connection_t *create_new_connection(int sfd)
1072 struct sockaddr_in ci;
1073 int len = sizeof(ci);
1075 p = new_connection();
1077 if(getpeername(sfd, (struct sockaddr *) &ci, (socklen_t *) &len) < 0)
1079 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1085 p->address = ntohl(ci.sin_addr.s_addr);
1086 p->hostname = hostlookup(ci.sin_addr.s_addr);
1087 p->meta_socket = sfd;
1089 p->buffer = xmalloc(MAXBUFSIZE);
1091 p->last_ping_time = time(NULL);
1093 if(debug_lvl >= DEBUG_CONNECTIONS)
1094 syslog(LOG_NOTICE, _("Connection from %s port %d"),
1095 p->hostname, htons(ci.sin_port));
1097 p->allow_request = ID;
1103 put all file descriptors in an fd_set array
1105 void build_fdset(fd_set *fs)
1112 FD_SET(myself->socket, fs);
1114 RBL_FOREACH(connection_tree, rbl)
1116 p = (connection_t *)rbl->data;
1118 FD_SET(p->meta_socket, fs);
1121 FD_SET(myself->meta_socket, fs);
1127 receive incoming data from the listening
1128 udp socket and write it to the ethertap
1129 device after being decrypted
1131 int handle_incoming_vpn_data(void)
1134 int x, l = sizeof(x);
1136 struct sockaddr_in from;
1137 socklen_t fromlen = sizeof(from);
1140 if(getsockopt(myself->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1142 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1143 __FILE__, __LINE__, myself->socket);
1148 syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1152 if((lenin = recvfrom(myself->socket, (char *) &(pkt.len), MTU, 0, (struct sockaddr *)&from, &fromlen)) <= 0)
1154 syslog(LOG_ERR, _("Receiving packet failed: %m"));
1158 cl = lookup_connection(ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
1162 syslog(LOG_WARNING, _("Received UDP packets on port %d from unknown source %lx:%d"), ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
1166 if(debug_lvl >= DEBUG_TRAFFIC)
1168 syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"), lenin,
1169 cl->name, cl->hostname);
1173 return xrecv(cl, &pkt);
1177 terminate a connection and notify the other
1178 end before closing the sockets
1180 void terminate_connection(connection_t *cl)
1186 if(cl->status.remove)
1189 cl->status.remove = 1;
1191 if(debug_lvl >= DEBUG_CONNECTIONS)
1192 syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1193 cl->name, cl->hostname);
1198 close(cl->meta_socket);
1200 /* Find all connections that were lost because they were behind cl
1201 (the connection that was dropped). */
1204 RBL_FOREACH(connection_tree, rbl)
1206 p = (connection_t *)rbl->data;
1207 if(p->nexthop == cl && p != cl)
1208 terminate_connection(p);
1211 /* Inform others of termination if it was still active */
1213 if(cl->status.active)
1214 RBL_FOREACH(connection_tree, rbl)
1216 p = (connection_t *)rbl->data;
1217 if(p->status.meta && p->status.active && p!=cl)
1218 send_del_host(p, cl); /* Sounds like recursion, but p does not have a meta connection :) */
1221 /* Remove the associated subnets */
1223 RBL_FOREACH(cl->subnet_tree, rbl)
1225 subnet = (subnet_t *)rbl->data;
1229 /* Check if this was our outgoing connection */
1231 if(cl->status.outgoing && cl->status.active)
1233 signal(SIGALRM, sigalrm_handler);
1234 seconds_till_retry = 5;
1235 alarm(seconds_till_retry);
1236 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
1241 cl->status.active = 0;
1246 Check if the other end is active.
1247 If we have sent packets, but didn't receive any,
1248 then possibly the other end is dead. We send a
1249 PING request over the meta connection. If the other
1250 end does not reply in time, we consider them dead
1251 and close the connection.
1253 void check_dead_connections(void)
1261 RBL_FOREACH(connection_tree, rbl)
1263 cl = (connection_t *)rbl->data;
1264 if(cl->status.active && cl->status.meta)
1266 if(cl->last_ping_time + timeout < now)
1268 if(cl->status.pinged)
1270 if(debug_lvl >= DEBUG_PROTOCOL)
1271 syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1272 cl->name, cl->hostname);
1273 cl->status.timeout = 1;
1274 terminate_connection(cl);
1287 accept a new tcp connect and create a
1290 int handle_new_meta_connection()
1293 struct sockaddr client;
1294 int nfd, len = sizeof(client);
1296 if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
1298 syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1302 if(!(ncn = create_new_connection(nfd)))
1306 syslog(LOG_NOTICE, _("Closed attempted connection"));
1310 connection_add(ncn);
1316 check all connections to see if anything
1317 happened on their sockets
1319 void check_network_activity(fd_set *f)
1324 if(FD_ISSET(myself->socket, f))
1325 handle_incoming_vpn_data();
1327 RBL_FOREACH(connection_tree, rbl)
1329 p = (connection_t *)rbl->data;
1331 if(p->status.remove)
1335 if(FD_ISSET(p->meta_socket, f))
1336 if(receive_meta(p) < 0)
1338 terminate_connection(p);
1343 if(FD_ISSET(myself->meta_socket, f))
1344 handle_new_meta_connection();
1349 read, encrypt and send data that is
1350 available through the ethertap device
1352 void handle_tap_input(void)
1357 if(taptype == TAP_TYPE_TUNTAP)
1359 if((lenin = read(tap_fd, vp.data, MTU)) <= 0)
1361 syslog(LOG_ERR, _("Error while reading from tun/tap device: %m"));
1368 if((lenin = read(tap_fd, vp.data - 2, MTU)) <= 0)
1370 syslog(LOG_ERR, _("Error while reading from ethertap device: %m"));
1376 total_tap_in += lenin;
1380 if(debug_lvl >= DEBUG_TRAFFIC)
1381 syslog(LOG_WARNING, _("Received short packet from tap device"));
1385 if(debug_lvl >= DEBUG_TRAFFIC)
1387 syslog(LOG_DEBUG, _("Read packet of length %d from tap device"), vp.len);
1390 send_packet(ntohl(*((unsigned long*)(&vp.data[30]))), &vp);
1395 this is where it all happens...
1397 void main_loop(void)
1402 time_t last_ping_check;
1405 last_ping_check = time(NULL);
1409 tv.tv_sec = timeout;
1412 prune_connection_tree();
1415 if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1417 if(errno != EINTR) /* because of alarm */
1419 syslog(LOG_ERR, _("Error while waiting for input: %m"));
1426 syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1428 close_network_connections();
1429 clear_config(&config);
1431 if(read_server_config())
1433 syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1439 if(setup_network_connections())
1447 /* Let's check if everybody is still alive */
1449 if(last_ping_check + timeout < t)
1451 check_dead_connections();
1452 last_ping_check = time(NULL);
1454 /* Should we regenerate our key? */
1458 if(debug_lvl >= DEBUG_STATUS)
1459 syslog(LOG_INFO, _("Regenerating symmetric key"));
1461 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
1462 send_key_changed(myself, NULL);
1463 keyexpires = time(NULL) + keylifetime;
1469 check_network_activity(&fset);
1471 /* local tap data */
1472 if(FD_ISSET(tap_fd, &fset))