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.89 2001/01/05 23:53:49 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>
62 #ifdef HAVE_OPENSSL_PEM_H
63 # include <openssl/pem.h>
69 #include LINUX_IF_TUN_H
77 #include "connection.h"
89 int taptype = TAP_TYPE_ETHERTAP;
91 int total_tap_out = 0;
92 int total_socket_in = 0;
93 int total_socket_out = 0;
95 config_t *upstreamcfg;
96 static int seconds_till_retry;
101 char *unknown = NULL;
105 int xsend(connection_t *cl, vpn_packet_t *inpkt)
110 struct sockaddr_in to;
111 socklen_t tolen = sizeof(to);
113 outpkt.len = inpkt->len;
115 /* Encrypt the packet */
117 EVP_EncryptInit(&ctx, cl->cipher_pkttype, cl->cipher_pktkey, cl->cipher_pktkey + cl->cipher_pkttype->key_len);
118 EVP_EncryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len);
119 EVP_EncryptFinal(&ctx, outpkt.data + outlen, &outpad);
120 outlen += outpad + 2;
123 outlen = outpkt.len + 2;
124 memcpy(&outpkt, inpkt, outlen);
127 if(debug_lvl >= DEBUG_TRAFFIC)
128 syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
129 outlen, cl->name, cl->hostname);
131 total_socket_out += outlen;
133 to.sin_family = AF_INET;
134 to.sin_addr.s_addr = htonl(cl->address);
135 to.sin_port = htons(cl->port);
137 if((sendto(myself->socket, (char *) &(outpkt.len), outlen, 0, (const struct sockaddr *)&to, tolen)) < 0)
139 syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
140 cl->name, cl->hostname);
147 int xrecv(connection_t *cl, vpn_packet_t *inpkt)
153 outpkt.len = inpkt->len;
155 /* Decrypt the packet */
157 EVP_DecryptInit(&ctx, myself->cipher_pkttype, myself->cipher_pktkey, myself->cipher_pktkey + myself->cipher_pkttype->key_len);
158 EVP_DecryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len + 8);
159 EVP_DecryptFinal(&ctx, outpkt.data + outlen, &outpad);
163 outlen = outpkt.len+2;
164 memcpy(&outpkt, inpkt, outlen);
167 if(debug_lvl >= DEBUG_TRAFFIC)
168 syslog(LOG_ERR, _("Writing packet of %d bytes to tap device"),
171 /* Fix mac address */
173 memcpy(outpkt.data, mymac.net.mac.address.x, 6);
175 if(taptype == TAP_TYPE_TUNTAP)
177 if(write(tap_fd, outpkt.data, outpkt.len) < 0)
178 syslog(LOG_ERR, _("Can't write to tun/tap device: %m"));
180 total_tap_out += outpkt.len;
184 if(write(tap_fd, outpkt.data - 2, outpkt.len + 2) < 0)
185 syslog(LOG_ERR, _("Can't write to ethertap device: %m"));
187 total_tap_out += outpkt.len + 2;
194 add the given packet of size s to the
195 queue q, be it the send or receive queue
197 void add_queue(packet_queue_t **q, void *packet, size_t s)
201 e = xmalloc(sizeof(*e));
202 e->packet = xmalloc(s);
203 memcpy(e->packet, packet, s);
207 *q = xmalloc(sizeof(**q));
208 (*q)->head = (*q)->tail = NULL;
211 e->next = NULL; /* We insert at the tail */
213 if((*q)->tail) /* Do we have a tail? */
215 (*q)->tail->next = e;
216 e->prev = (*q)->tail;
218 else /* No tail -> no head too */
228 /* Remove a queue element */
229 void del_queue(packet_queue_t **q, queue_element_t *e)
234 if(e->next) /* There is a successor, so we are not tail */
236 if(e->prev) /* There is a predecessor, so we are not head */
238 e->next->prev = e->prev;
239 e->prev->next = e->next;
241 else /* We are head */
243 e->next->prev = NULL;
244 (*q)->head = e->next;
247 else /* We are tail (or all alone!) */
249 if(e->prev) /* We are not alone :) */
251 e->prev->next = NULL;
252 (*q)->tail = e->prev;
266 flush a queue by calling function for
267 each packet, and removing it when that
268 returned a zero exit code
270 void flush_queue(connection_t *cl, packet_queue_t **pq,
271 int (*function)(connection_t*,vpn_packet_t*))
273 queue_element_t *p, *next = NULL;
275 for(p = (*pq)->head; p != NULL; )
279 if(!function(cl, p->packet))
285 if(debug_lvl >= DEBUG_TRAFFIC)
286 syslog(LOG_DEBUG, _("Queue flushed"));
291 flush the send&recv queues
292 void because nothing goes wrong here, packets
293 remain in the queue if something goes wrong
295 void flush_queues(connection_t *cl)
300 if(debug_lvl >= DEBUG_TRAFFIC)
301 syslog(LOG_DEBUG, _("Flushing send queue for %s (%s)"),
302 cl->name, cl->hostname);
303 flush_queue(cl, &(cl->sq), xsend);
308 if(debug_lvl >= DEBUG_TRAFFIC)
309 syslog(LOG_DEBUG, _("Flushing receive queue for %s (%s)"),
310 cl->name, cl->hostname);
311 flush_queue(cl, &(cl->rq), xrecv);
317 send a packet to the given vpn ip.
319 int send_packet(ip_t to, vpn_packet_t *packet)
324 if((subnet = lookup_subnet_ipv4(&to)) == NULL)
326 if(debug_lvl >= DEBUG_TRAFFIC)
328 syslog(LOG_NOTICE, _("Trying to look up %d.%d.%d.%d in connection list failed!"),
339 if(debug_lvl >= DEBUG_TRAFFIC)
341 syslog(LOG_NOTICE, _("Packet with destination %d.%d.%d.%d is looping back to us!"),
348 /* If we ourselves have indirectdata flag set, we should send only to our uplink! */
350 /* FIXME - check for indirection and reprogram it The Right Way(tm) this time. */
352 if(!cl->status.validkey)
354 /* FIXME: Don't queue until everything else is fixed.
355 if(debug_lvl >= DEBUG_TRAFFIC)
356 syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
357 cl->name, cl->hostname);
358 add_queue(&(cl->sq), packet, packet->len + 2);
360 if(!cl->status.waitingforkey)
361 send_req_key(myself, cl); /* Keys should be sent to the host running the tincd */
365 if(!cl->status.active)
367 /* FIXME: Don't queue until everything else is fixed.
368 if(debug_lvl >= DEBUG_TRAFFIC)
369 syslog(LOG_INFO, _("%s (%s) is not ready, queueing packet"),
370 cl->name, cl->hostname);
371 add_queue(&(cl->sq), packet, packet->len + 2);
373 return 0; /* We don't want to mess up, do we? */
376 /* can we send it? can we? can we? huh? */
378 return xsend(cl, packet);
382 open the local ethertap device
384 int setup_tap_fd(void)
387 const char *tapfname;
396 if((cfg = get_config_val(config, config_tapdevice)))
397 tapfname = cfg->data.ptr;
402 tapfname = "/dev/misc/net/tun";
404 tapfname = "/dev/tap0";
408 tapfname = "/dev/tap0";
411 tapfname = "/dev/tun";
415 if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
417 syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
423 taptype = TAP_TYPE_ETHERTAP;
425 /* Set default MAC address for ethertap devices */
427 mymac.type = SUBNET_MAC;
428 mymac.net.mac.address.x[0] = 0xfe;
429 mymac.net.mac.address.x[1] = 0xfd;
430 mymac.net.mac.address.x[2] = 0x00;
431 mymac.net.mac.address.x[3] = 0x00;
432 mymac.net.mac.address.x[4] = 0x00;
433 mymac.net.mac.address.x[5] = 0x00;
437 /* Ok now check if this is an old ethertap or a new tun/tap thingie */
438 memset(&ifr, 0, sizeof(ifr));
440 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
442 strncpy(ifr.ifr_name, netname, IFNAMSIZ);
444 if (!ioctl(tap_fd, TUNSETIFF, (void *) &ifr))
446 syslog(LOG_INFO, _("%s is a new style tun/tap device"), tapfname);
447 taptype = TAP_TYPE_TUNTAP;
452 taptype = TAP_TYPE_TUNTAP;
459 set up the socket that we listen on for incoming
462 int setup_listen_meta_socket(int port)
465 struct sockaddr_in a;
469 if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
471 syslog(LOG_ERR, _("Creating metasocket failed: %m"));
475 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
478 syslog(LOG_ERR, _("System call `%s' failed: %m"),
483 if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one)))
486 syslog(LOG_ERR, _("System call `%s' failed: %m"),
491 flags = fcntl(nfd, F_GETFL);
492 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
495 syslog(LOG_ERR, _("System call `%s' failed: %m"),
500 if((cfg = get_config_val(config, config_interface)))
502 if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, cfg->data.ptr, strlen(cfg->data.ptr)))
505 syslog(LOG_ERR, _("Unable to bind listen socket to interface %s: %m"), cfg->data.ptr);
510 memset(&a, 0, sizeof(a));
511 a.sin_family = AF_INET;
512 a.sin_port = htons(port);
514 if((cfg = get_config_val(config, config_interfaceip)))
515 a.sin_addr.s_addr = htonl(cfg->data.ip->address);
517 a.sin_addr.s_addr = htonl(INADDR_ANY);
519 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
522 syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
529 syslog(LOG_ERR, _("System call `%s' failed: %m"),
538 setup the socket for incoming encrypted
541 int setup_vpn_in_socket(int port)
544 struct sockaddr_in a;
547 if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
550 syslog(LOG_ERR, _("Creating socket failed: %m"));
554 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
557 syslog(LOG_ERR, _("System call `%s' failed: %m"),
562 flags = fcntl(nfd, F_GETFL);
563 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
566 syslog(LOG_ERR, _("System call `%s' failed: %m"),
571 memset(&a, 0, sizeof(a));
572 a.sin_family = AF_INET;
573 a.sin_port = htons(port);
574 a.sin_addr.s_addr = htonl(INADDR_ANY);
576 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
579 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
587 setup an outgoing meta (tcp) socket
589 int setup_outgoing_meta_socket(connection_t *cl)
592 struct sockaddr_in a;
595 if(debug_lvl >= DEBUG_CONNECTIONS)
596 syslog(LOG_INFO, _("Trying to connect to %s"), cl->hostname);
598 if((cfg = get_config_val(cl->config, config_port)) == NULL)
601 cl->port = cfg->data.val;
603 cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
604 if(cl->meta_socket == -1)
606 syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
607 cl->hostname, cl->port);
611 /* Bind first to get a fix on our source port */
613 a.sin_family = AF_INET;
614 a.sin_port = htons(0);
615 a.sin_addr.s_addr = htonl(INADDR_ANY);
617 if(bind(cl->meta_socket, (struct sockaddr *)&a, sizeof(struct sockaddr)))
619 close(cl->meta_socket);
620 syslog(LOG_ERR, _("System call `%s' failed: %m"), "bind");
624 a.sin_family = AF_INET;
625 a.sin_port = htons(cl->port);
626 a.sin_addr.s_addr = htonl(cl->address);
628 if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
630 close(cl->meta_socket);
631 syslog(LOG_ERR, _("%s port %hd: %m"), cl->hostname, cl->port);
635 flags = fcntl(cl->meta_socket, F_GETFL);
636 if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
638 close(cl->meta_socket);
639 syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
640 cl->hostname, cl->port);
644 if(debug_lvl >= DEBUG_CONNECTIONS)
645 syslog(LOG_INFO, _("Connected to %s port %hd"),
646 cl->hostname, cl->port);
654 Setup an outgoing meta connection.
656 int setup_outgoing_connection(char *name)
664 syslog(LOG_ERR, _("Invalid name for outgoing connection"));
668 ncn = new_connection();
669 asprintf(&ncn->name, "%s", name);
671 if(read_host_config(ncn))
673 syslog(LOG_ERR, _("Error reading host configuration file for %s"), ncn->name);
674 free_connection(ncn);
678 if(!(cfg = get_config_val(ncn->config, config_address)))
680 syslog(LOG_ERR, _("No address specified for %s"), ncn->name);
681 free_connection(ncn);
685 if(!(h = gethostbyname(cfg->data.ptr)))
687 syslog(LOG_ERR, _("Error looking up `%s': %m"), cfg->data.ptr);
688 free_connection(ncn);
692 ncn->address = ntohl(*((ip_t*)(h->h_addr_list[0])));
693 ncn->hostname = hostlookup(htonl(ncn->address));
695 if(setup_outgoing_meta_socket(ncn) < 0)
697 syslog(LOG_ERR, _("Could not set up a meta connection to %s"),
699 free_connection(ncn);
703 ncn->status.outgoing = 1;
704 ncn->buffer = xmalloc(MAXBUFSIZE);
706 ncn->last_ping_time = time(NULL);
715 int read_rsa_public_key(connection_t *cl)
722 cl->rsa_key = RSA_new();
724 if((cfg = get_config_val(cl->config, config_publickey)))
726 BN_hex2bn(&cl->rsa_key->n, cfg->data.ptr);
727 BN_hex2bn(&cl->rsa_key->e, "FFFF");
729 else if((cfg = get_config_val(cl->config, config_publickeyfile)))
731 if(is_safe_path(cfg->data.ptr))
733 if((fp = fopen(cfg->data.ptr, "r")) == NULL)
735 syslog(LOG_ERR, _("Error reading RSA public key file `%s': %m"),
739 result = PEM_read_RSAPublicKey(fp, &cl->rsa_key, NULL, NULL);
743 syslog(LOG_ERR, _("Reading RSA public key file `%s' failed: %m"),
753 syslog(LOG_ERR, _("No public key for %s specified!"), cl->name);
760 int read_rsa_private_key(void)
767 myself->rsa_key = RSA_new();
769 if((cfg = get_config_val(config, config_privatekey)))
771 BN_hex2bn(&myself->rsa_key->d, cfg->data.ptr);
772 BN_hex2bn(&myself->rsa_key->e, "FFFF");
774 else if((cfg = get_config_val(config, config_privatekeyfile)))
776 if((fp = fopen(cfg->data.ptr, "r")) == NULL)
778 syslog(LOG_ERR, _("Error reading RSA private key file `%s': %m"),
782 result = PEM_read_RSAPrivateKey(fp, &myself->rsa_key, NULL, NULL);
786 syslog(LOG_ERR, _("Reading RSA private key file `%s' failed: %m"),
793 syslog(LOG_ERR, _("No private key for tinc daemon specified!"));
801 Configure connection_t myself and set up the local sockets (listen only)
803 int setup_myself(void)
809 myself = new_connection();
811 asprintf(&myself->hostname, "MYSELF"); /* FIXME? Do hostlookup on ourselves? */
813 myself->protocol_version = PROT_CURRENT;
815 if(!(cfg = get_config_val(config, config_name))) /* Not acceptable */
817 syslog(LOG_ERR, _("Name for tinc daemon required!"));
821 asprintf(&myself->name, "%s", (char*)cfg->data.val);
823 if(check_id(myself->name))
825 syslog(LOG_ERR, _("Invalid name for myself!"));
829 if(read_rsa_private_key())
832 if(read_host_config(myself))
834 syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
838 if(read_rsa_public_key(myself))
843 if(RSA_check_key(myself->rsa_key) != 1)
845 syslog(LOG_ERR, _("Invalid public/private keypair!"));
849 if(!(cfg = get_config_val(myself->config, config_port)))
852 myself->port = cfg->data.val;
854 if((cfg = get_config_val(myself->config, config_indirectdata)))
855 if(cfg->data.val == stupid_true)
856 myself->flags |= EXPORTINDIRECTDATA;
858 if((cfg = get_config_val(myself->config, config_tcponly)))
859 if(cfg->data.val == stupid_true)
860 myself->flags |= TCPONLY;
862 /* Read in all the subnets specified in the host configuration file */
864 for(next = myself->config; (cfg = get_config_val(next, config_subnet)); next = cfg->next)
867 net->type = SUBNET_IPV4;
868 net->net.ipv4.address = cfg->data.ip->address;
869 net->net.ipv4.mask = cfg->data.ip->mask;
871 /* Teach newbies what subnets are... */
873 if((net->net.ipv4.address & net->net.ipv4.mask) != net->net.ipv4.address)
875 syslog(LOG_ERR, _("Network address and subnet mask do not match!"));
879 subnet_add(myself, net);
882 if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
884 syslog(LOG_ERR, _("Unable to set up a listening TCP socket!"));
888 if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
890 syslog(LOG_ERR, _("Unable to set up a listening UDP socket!"));
894 /* Generate packet encryption key */
896 myself->cipher_pkttype = EVP_bf_cfb();
898 myself->cipher_pktkeylength = myself->cipher_pkttype->key_len + myself->cipher_pkttype->iv_len;
900 myself->cipher_pktkey = (char *)xmalloc(myself->cipher_pktkeylength);
901 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
903 if(!(cfg = get_config_val(config, config_keyexpire)))
906 keylifetime = cfg->data.val;
908 keyexpires = time(NULL) + keylifetime;
910 /* Activate ourselves */
912 myself->status.active = 1;
914 syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
920 sigalrm_handler(int a)
924 cfg = get_config_val(upstreamcfg, config_connectto);
926 if(!cfg && upstreamcfg == config)
927 /* No upstream IP given, we're listen only. */
932 upstreamcfg = cfg->next;
933 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
935 signal(SIGALRM, SIG_IGN);
938 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
941 signal(SIGALRM, sigalrm_handler);
942 upstreamcfg = config;
943 seconds_till_retry += 5;
944 if(seconds_till_retry > MAXTIMEOUT) /* Don't wait more than MAXTIMEOUT seconds. */
945 seconds_till_retry = MAXTIMEOUT;
946 syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
948 alarm(seconds_till_retry);
953 setup all initial network connections
955 int setup_network_connections(void)
962 if((cfg = get_config_val(config, config_pingtimeout)) == NULL)
966 timeout = cfg->data.val;
973 if(setup_tap_fd() < 0)
976 /* Run tinc-up script to further initialize the tap interface */
977 execute_script("tinc-up");
979 if(setup_myself() < 0)
982 if(!(cfg = get_config_val(config, config_connectto)))
983 /* No upstream IP given, we're listen only. */
988 upstreamcfg = cfg->next;
989 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
991 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
994 signal(SIGALRM, sigalrm_handler);
995 upstreamcfg = config;
996 seconds_till_retry = MAXTIMEOUT;
997 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
998 alarm(seconds_till_retry);
1004 close all open network connections
1006 void close_network_connections(void)
1011 for(node = connection_tree->head; node; node = node->next)
1013 p = (connection_t *)node->data;
1014 p->status.active = 0;
1015 terminate_connection(p);
1019 if(myself->status.active)
1021 close(myself->meta_socket);
1022 free_connection(myself);
1028 /* Execute tinc-down script right after shutting down the interface */
1029 execute_script("tinc-down");
1031 destroy_connection_tree();
1037 create a data (udp) socket
1038 OBSOLETED: use only one listening socket for compatibility with non-Linux operating systems
1040 int setup_vpn_connection(connection_t *cl)
1043 struct sockaddr_in a;
1046 if(debug_lvl >= DEBUG_TRAFFIC)
1047 syslog(LOG_DEBUG, _("Opening UDP socket to %s"), cl->hostname);
1049 nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
1052 syslog(LOG_ERR, _("Creating UDP socket failed: %m"));
1056 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
1059 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1064 flags = fcntl(nfd, F_GETFL);
1065 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
1068 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1073 memset(&a, 0, sizeof(a));
1074 a.sin_family = AF_INET;
1075 a.sin_port = htons(myself->port);
1076 a.sin_addr.s_addr = htonl(INADDR_ANY);
1078 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
1081 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), myself->port);
1085 a.sin_family = AF_INET;
1086 a.sin_port = htons(cl->port);
1087 a.sin_addr.s_addr = htonl(cl->address);
1089 if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
1092 syslog(LOG_ERR, _("Connecting to %s port %d failed: %m"),
1093 cl->hostname, cl->port);
1097 flags = fcntl(nfd, F_GETFL);
1098 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
1101 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m %s (%s)"), __FILE__, __LINE__, nfd,
1102 cl->name, cl->hostname);
1107 cl->status.dataopen = 1;
1113 handle an incoming tcp connect call and open
1116 connection_t *create_new_connection(int sfd)
1119 struct sockaddr_in ci;
1120 int len = sizeof(ci);
1122 p = new_connection();
1124 if(getpeername(sfd, (struct sockaddr *) &ci, (socklen_t *) &len) < 0)
1126 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1132 p->address = ntohl(ci.sin_addr.s_addr);
1133 p->hostname = hostlookup(ci.sin_addr.s_addr);
1134 p->port = htons(ci.sin_port); /* This one will be overwritten later */
1135 p->meta_socket = sfd;
1137 p->buffer = xmalloc(MAXBUFSIZE);
1139 p->last_ping_time = time(NULL);
1141 if(debug_lvl >= DEBUG_CONNECTIONS)
1142 syslog(LOG_NOTICE, _("Connection from %s port %d"),
1143 p->hostname, htons(ci.sin_port));
1145 p->allow_request = ID;
1151 put all file descriptors in an fd_set array
1153 void build_fdset(fd_set *fs)
1160 FD_SET(myself->socket, fs);
1162 for(node = connection_tree->head; node; node = node->next)
1164 p = (connection_t *)node->data;
1166 FD_SET(p->meta_socket, fs);
1169 FD_SET(myself->meta_socket, fs);
1175 receive incoming data from the listening
1176 udp socket and write it to the ethertap
1177 device after being decrypted
1179 int handle_incoming_vpn_data(void)
1182 int x, l = sizeof(x);
1184 struct sockaddr_in from;
1185 socklen_t fromlen = sizeof(from);
1188 if(getsockopt(myself->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1190 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1191 __FILE__, __LINE__, myself->socket);
1196 syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1200 if((lenin = recvfrom(myself->socket, (char *) &(pkt.len), MTU, 0, (struct sockaddr *)&from, &fromlen)) <= 0)
1202 syslog(LOG_ERR, _("Receiving packet failed: %m"));
1206 cl = lookup_connection(ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
1210 syslog(LOG_WARNING, _("Received UDP packets on port %hd from unknown source %x:%hd"), myself->port, ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
1214 if(debug_lvl >= DEBUG_TRAFFIC)
1216 syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"), lenin,
1217 cl->name, cl->hostname);
1221 return xrecv(cl, &pkt);
1225 terminate a connection and notify the other
1226 end before closing the sockets
1228 void terminate_connection(connection_t *cl)
1232 avl_node_t *node, *next;
1234 if(cl->status.remove)
1237 cl->status.remove = 1;
1239 if(debug_lvl >= DEBUG_CONNECTIONS)
1240 syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1241 cl->name, cl->hostname);
1246 close(cl->meta_socket);
1248 /* Find all connections that were lost because they were behind cl
1249 (the connection that was dropped). */
1252 for(node = connection_tree->head; node; node = node->next)
1254 p = (connection_t *)node->data;
1255 if(p->nexthop == cl && p != cl)
1256 terminate_connection(p);
1259 /* Inform others of termination if it was still active */
1261 if(cl->status.active)
1262 for(node = connection_tree->head; node; node = node->next)
1264 p = (connection_t *)node->data;
1265 if(p->status.meta && p->status.active && p!=cl)
1266 send_del_host(p, cl); /* Sounds like recursion, but p does not have a meta connection :) */
1269 /* Remove the associated subnets */
1271 for(node = cl->subnet_tree->head; node; node = next)
1274 subnet = (subnet_t *)node->data;
1278 /* Check if this was our outgoing connection */
1280 if(cl->status.outgoing && cl->status.active)
1282 signal(SIGALRM, sigalrm_handler);
1283 seconds_till_retry = 5;
1284 alarm(seconds_till_retry);
1285 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
1290 cl->status.active = 0;
1295 Check if the other end is active.
1296 If we have sent packets, but didn't receive any,
1297 then possibly the other end is dead. We send a
1298 PING request over the meta connection. If the other
1299 end does not reply in time, we consider them dead
1300 and close the connection.
1302 void check_dead_connections(void)
1310 for(node = connection_tree->head; node; node = node->next)
1312 cl = (connection_t *)node->data;
1313 if(cl->status.active && cl->status.meta)
1315 if(cl->last_ping_time + timeout < now)
1317 if(cl->status.pinged)
1319 if(debug_lvl >= DEBUG_PROTOCOL)
1320 syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1321 cl->name, cl->hostname);
1322 cl->status.timeout = 1;
1323 terminate_connection(cl);
1336 accept a new tcp connect and create a
1339 int handle_new_meta_connection()
1342 struct sockaddr client;
1343 int nfd, len = sizeof(client);
1345 if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
1347 syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1351 if(!(ncn = create_new_connection(nfd)))
1355 syslog(LOG_NOTICE, _("Closed attempted connection"));
1359 connection_add(ncn);
1365 check all connections to see if anything
1366 happened on their sockets
1368 void check_network_activity(fd_set *f)
1373 if(FD_ISSET(myself->socket, f))
1374 handle_incoming_vpn_data();
1376 for(node = connection_tree->head; node; node = node->next)
1378 p = (connection_t *)node->data;
1380 if(p->status.remove)
1384 if(FD_ISSET(p->meta_socket, f))
1385 if(receive_meta(p) < 0)
1387 terminate_connection(p);
1392 if(FD_ISSET(myself->meta_socket, f))
1393 handle_new_meta_connection();
1398 read, encrypt and send data that is
1399 available through the ethertap device
1401 void handle_tap_input(void)
1406 if(taptype == TAP_TYPE_TUNTAP)
1408 if((lenin = read(tap_fd, vp.data, MTU)) <= 0)
1410 syslog(LOG_ERR, _("Error while reading from tun/tap device: %m"));
1417 if((lenin = read(tap_fd, vp.data - 2, MTU)) <= 0)
1419 syslog(LOG_ERR, _("Error while reading from ethertap device: %m"));
1425 total_tap_in += lenin;
1429 if(debug_lvl >= DEBUG_TRAFFIC)
1430 syslog(LOG_WARNING, _("Received short packet from tap device"));
1434 if(debug_lvl >= DEBUG_TRAFFIC)
1436 syslog(LOG_DEBUG, _("Read packet of length %d from tap device"), vp.len);
1439 send_packet(ntohl(*((unsigned long*)(&vp.data[30]))), &vp);
1444 this is where it all happens...
1446 void main_loop(void)
1451 time_t last_ping_check;
1454 last_ping_check = time(NULL);
1458 tv.tv_sec = timeout;
1461 prune_connection_tree();
1464 if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1466 if(errno != EINTR) /* because of alarm */
1468 syslog(LOG_ERR, _("Error while waiting for input: %m"));
1475 syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1477 close_network_connections();
1478 clear_config(&config);
1480 if(read_server_config())
1482 syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1488 if(setup_network_connections())
1496 /* Let's check if everybody is still alive */
1498 if(last_ping_check + timeout < t)
1500 check_dead_connections();
1501 last_ping_check = time(NULL);
1503 /* Should we regenerate our key? */
1507 if(debug_lvl >= DEBUG_STATUS)
1508 syslog(LOG_INFO, _("Regenerating symmetric key"));
1510 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
1511 send_key_changed(myself, NULL);
1512 keyexpires = time(NULL) + keylifetime;
1518 check_network_activity(&fset);
1520 /* local tap data */
1521 if(FD_ISSET(tap_fd, &fset))