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.73 2000/11/15 13:33:26 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
80 int taptype = TAP_TYPE_ETHERTAP;
82 int total_tap_out = 0;
83 int total_socket_in = 0;
84 int total_socket_out = 0;
86 config_t *upstreamcfg;
87 static int seconds_till_retry;
97 Execute the given script.
98 This function doesn't really belong here.
100 int execute_script(const char *name)
107 if((pid = fork()) < 0)
109 syslog(LOG_ERR, _("System call `%s' failed: %m"),
125 asprintf(&s, "NETNAME=%s", netname);
126 putenv(s); /* Don't free s! see man 3 putenv */
135 if(chdir(confbase) < 0)
136 /* This cannot fail since we already read config files from this
138 /* Yes this can fail, somebody could have removed this directory
139 when we didn't pay attention. - Ivo */
142 /* Now if THIS fails, something wicked is going on. - Ivo */
143 syslog(LOG_ERR, _("Couldn't chdir to `/': %m"));
145 /* Continue anyway. */
148 asprintf(&scriptname, "%s/%s", confbase, name);
150 /* Close all file descriptors */
154 /* Open standard input */
155 if(open("/dev/null", O_RDONLY) < 0)
157 syslog(LOG_ERR, _("Opening `/dev/null' failed: %m"));
163 /* Standard output directly goes to syslog */
164 openlog(name, LOG_CONS | LOG_PID, LOG_DAEMON);
165 /* Standard error as well */
168 syslog(LOG_ERR, _("System call `%s' failed: %m"),
174 if(error && debug_lvl > 1)
175 syslog(LOG_INFO, _("This means that any output the script generates will not be shown in syslog."));
177 execl(scriptname, NULL);
178 /* No return on success */
180 if(errno != ENOENT) /* Ignore if the file does not exist */
181 syslog(LOG_WARNING, _("Error executing `%s': %m"), scriptname);
183 /* No need to free things */
187 int xsend(conn_list_t *cl, vpn_packet_t *inpkt)
193 outpkt.len = inpkt->len;
195 /* Encrypt the packet */
197 EVP_EncryptInit(&ctx, cl->cipher_pkttype, cl->cipher_pktkey, cl->cipher_pktkey + cl->cipher_pkttype->key_len);
198 EVP_EncryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len);
199 EVP_EncryptFinal(&ctx, outpkt.data + outlen, &outpad);
200 outlen += outpad + 2;
203 outlen = outpkt.len + 2;
204 memcpy(&outpkt, inpkt, outlen);
207 if(debug_lvl >= DEBUG_TRAFFIC)
208 syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
209 outlen, cl->name, cl->hostname);
211 total_socket_out += outlen;
213 if((send(cl->socket, (char *) &(outpkt.len), outlen, 0)) < 0)
215 syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
216 cl->name, cl->hostname);
223 int xrecv(conn_list_t *cl, vpn_packet_t *inpkt)
229 outpkt.len = inpkt->len;
231 /* Decrypt the packet */
233 EVP_DecryptInit(&ctx, myself->cipher_pkttype, myself->cipher_pktkey, myself->cipher_pktkey + myself->cipher_pkttype->key_len);
234 EVP_DecryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len + 8);
235 EVP_DecryptFinal(&ctx, outpkt.data + outlen, &outpad);
239 outlen = outpkt.len+2;
240 memcpy(&outpkt, inpkt, outlen);
243 if(debug_lvl >= DEBUG_TRAFFIC)
244 syslog(LOG_ERR, _("Writing packet of %d bytes to tap device"),
247 /* Fix mac address */
249 memcpy(outpkt.data, mymac.net.mac.address.x, 6);
251 if(taptype == TAP_TYPE_TUNTAP)
253 if(write(tap_fd, outpkt.data, outpkt.len) < 0)
254 syslog(LOG_ERR, _("Can't write to tun/tap device: %m"));
256 total_tap_out += outpkt.len;
260 if(write(tap_fd, outpkt.data - 2, outpkt.len + 2) < 0)
261 syslog(LOG_ERR, _("Can't write to ethertap device: %m"));
263 total_tap_out += outpkt.len + 2;
270 add the given packet of size s to the
271 queue q, be it the send or receive queue
273 void add_queue(packet_queue_t **q, void *packet, size_t s)
277 e = xmalloc(sizeof(*e));
278 e->packet = xmalloc(s);
279 memcpy(e->packet, packet, s);
283 *q = xmalloc(sizeof(**q));
284 (*q)->head = (*q)->tail = NULL;
287 e->next = NULL; /* We insert at the tail */
289 if((*q)->tail) /* Do we have a tail? */
291 (*q)->tail->next = e;
292 e->prev = (*q)->tail;
294 else /* No tail -> no head too */
304 /* Remove a queue element */
305 void del_queue(packet_queue_t **q, queue_element_t *e)
310 if(e->next) /* There is a successor, so we are not tail */
312 if(e->prev) /* There is a predecessor, so we are not head */
314 e->next->prev = e->prev;
315 e->prev->next = e->next;
317 else /* We are head */
319 e->next->prev = NULL;
320 (*q)->head = e->next;
323 else /* We are tail (or all alone!) */
325 if(e->prev) /* We are not alone :) */
327 e->prev->next = NULL;
328 (*q)->tail = e->prev;
342 flush a queue by calling function for
343 each packet, and removing it when that
344 returned a zero exit code
346 void flush_queue(conn_list_t *cl, packet_queue_t **pq,
347 int (*function)(conn_list_t*,vpn_packet_t*))
349 queue_element_t *p, *next = NULL;
351 for(p = (*pq)->head; p != NULL; )
355 if(!function(cl, p->packet))
361 if(debug_lvl >= DEBUG_TRAFFIC)
362 syslog(LOG_DEBUG, _("Queue flushed"));
367 flush the send&recv queues
368 void because nothing goes wrong here, packets
369 remain in the queue if something goes wrong
371 void flush_queues(conn_list_t *cl)
376 if(debug_lvl >= DEBUG_TRAFFIC)
377 syslog(LOG_DEBUG, _("Flushing send queue for %s (%s)"),
378 cl->name, cl->hostname);
379 flush_queue(cl, &(cl->sq), xsend);
384 if(debug_lvl >= DEBUG_TRAFFIC)
385 syslog(LOG_DEBUG, _("Flushing receive queue for %s (%s)"),
386 cl->name, cl->hostname);
387 flush_queue(cl, &(cl->rq), xrecv);
393 send a packet to the given vpn ip.
395 int send_packet(ip_t to, vpn_packet_t *packet)
400 if((subnet = lookup_subnet_ipv4(to)) == NULL)
402 if(debug_lvl >= DEBUG_TRAFFIC)
404 syslog(LOG_NOTICE, _("Trying to look up %d.%d.%d.%d in connection list failed!"),
415 if(debug_lvl >= DEBUG_TRAFFIC)
417 syslog(LOG_NOTICE, _("Packet with destination %d.%d.%d.%d is looping back to us!"),
424 /* If we ourselves have indirectdata flag set, we should send only to our uplink! */
426 /* FIXME - check for indirection and reprogram it The Right Way(tm) this time. */
428 /* Connections are now opened beforehand...
430 if(!cl->status.dataopen)
431 if(setup_vpn_connection(cl) < 0)
433 syslog(LOG_ERR, _("Could not open UDP connection to %s (%s)"),
434 cl->name, cl->hostname);
439 if(!cl->status.validkey)
441 /* FIXME: Don't queue until everything else is fixed.
442 if(debug_lvl >= DEBUG_TRAFFIC)
443 syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
444 cl->name, cl->hostname);
445 add_queue(&(cl->sq), packet, packet->len + 2);
447 if(!cl->status.waitingforkey)
448 send_req_key(myself, cl); /* Keys should be sent to the host running the tincd */
452 if(!cl->status.active)
454 /* FIXME: Don't queue until everything else is fixed.
455 if(debug_lvl >= DEBUG_TRAFFIC)
456 syslog(LOG_INFO, _("%s (%s) is not ready, queueing packet"),
457 cl->name, cl->hostname);
458 add_queue(&(cl->sq), packet, packet->len + 2);
460 return 0; /* We don't want to mess up, do we? */
463 /* can we send it? can we? can we? huh? */
465 return xsend(cl, packet);
469 open the local ethertap device
471 int setup_tap_fd(void)
474 const char *tapfname;
479 if((cfg = get_config_val(config, config_tapdevice)))
480 tapfname = cfg->data.ptr;
483 tapfname = "/dev/misc/net/tun";
485 tapfname = "/dev/tap0";
488 if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
490 syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
496 /* Set default MAC address for ethertap devices */
498 taptype = TAP_TYPE_ETHERTAP;
499 mymac.type = SUBNET_MAC;
500 mymac.net.mac.address.x[0] = 0xfe;
501 mymac.net.mac.address.x[1] = 0xfd;
502 mymac.net.mac.address.x[2] = 0x00;
503 mymac.net.mac.address.x[3] = 0x00;
504 mymac.net.mac.address.x[4] = 0x00;
505 mymac.net.mac.address.x[5] = 0x00;
508 /* Ok now check if this is an old ethertap or a new tun/tap thingie */
509 memset(&ifr, 0, sizeof(ifr));
511 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
513 strncpy(ifr.ifr_name, netname, IFNAMSIZ);
515 if (!ioctl(tap_fd, TUNSETIFF, (void *) &ifr))
517 syslog(LOG_INFO, _("%s is a new style tun/tap device"), tapfname);
518 taptype = TAP_TYPE_TUNTAP;
526 set up the socket that we listen on for incoming
529 int setup_listen_meta_socket(int port)
532 struct sockaddr_in a;
536 if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
538 syslog(LOG_ERR, _("Creating metasocket failed: %m"));
542 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
545 syslog(LOG_ERR, _("System call `%s' failed: %m"),
550 if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one)))
553 syslog(LOG_ERR, _("System call `%s' failed: %m"),
558 flags = fcntl(nfd, F_GETFL);
559 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
562 syslog(LOG_ERR, _("System call `%s' failed: %m"),
567 if((cfg = get_config_val(config, config_interface)))
569 if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, cfg->data.ptr, strlen(cfg->data.ptr)))
572 syslog(LOG_ERR, _("Unable to bind listen socket to interface %s: %m"), cfg->data.ptr);
577 memset(&a, 0, sizeof(a));
578 a.sin_family = AF_INET;
579 a.sin_port = htons(port);
581 if((cfg = get_config_val(config, config_interfaceip)))
582 a.sin_addr.s_addr = htonl(cfg->data.ip->address);
584 a.sin_addr.s_addr = htonl(INADDR_ANY);
586 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
589 syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
596 syslog(LOG_ERR, _("System call `%s' failed: %m"),
605 setup the socket for incoming encrypted
608 int setup_vpn_in_socket(int port)
611 struct sockaddr_in a;
614 if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
617 syslog(LOG_ERR, _("Creating socket failed: %m"));
621 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
624 syslog(LOG_ERR, _("System call `%s' failed: %m"),
629 flags = fcntl(nfd, F_GETFL);
630 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
633 syslog(LOG_ERR, _("System call `%s' failed: %m"),
638 memset(&a, 0, sizeof(a));
639 a.sin_family = AF_INET;
640 a.sin_port = htons(port);
641 a.sin_addr.s_addr = htonl(INADDR_ANY);
643 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
646 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
654 setup an outgoing meta (tcp) socket
656 int setup_outgoing_meta_socket(conn_list_t *cl)
659 struct sockaddr_in a;
662 if(debug_lvl >= DEBUG_CONNECTIONS)
663 syslog(LOG_INFO, _("Trying to connect to %s"), cl->hostname);
665 if((cfg = get_config_val(cl->config, config_port)) == NULL)
668 cl->port = cfg->data.val;
670 cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
671 if(cl->meta_socket == -1)
673 syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
674 cl->hostname, cl->port);
678 a.sin_family = AF_INET;
679 a.sin_port = htons(cl->port);
680 a.sin_addr.s_addr = htonl(cl->address);
682 if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
684 close(cl->meta_socket);
685 syslog(LOG_ERR, _("%s port %hd: %m"), cl->hostname, cl->port);
689 flags = fcntl(cl->meta_socket, F_GETFL);
690 if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
692 close(cl->meta_socket);
693 syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
694 cl->hostname, cl->port);
698 if(debug_lvl >= DEBUG_CONNECTIONS)
699 syslog(LOG_INFO, _("Connected to %s port %hd"),
700 cl->hostname, cl->port);
708 setup an outgoing connection. It's not
709 necessary to also open an udp socket as
710 well, because the other host will initiate
711 an authentication sequence during which
712 we will do just that.
714 int setup_outgoing_connection(char *name)
722 syslog(LOG_ERR, _("Invalid name for outgoing connection"));
726 ncn = new_conn_list();
727 asprintf(&ncn->name, "%s", name);
729 if(read_host_config(ncn))
731 syslog(LOG_ERR, _("Error reading host configuration file for %s"));
736 if(!(cfg = get_config_val(ncn->config, config_address)))
738 syslog(LOG_ERR, _("No address specified for %s"));
743 if(!(h = gethostbyname(cfg->data.ptr)))
745 syslog(LOG_ERR, _("Error looking up `%s': %m"), cfg->data.ptr);
750 ncn->address = ntohl(*((ip_t*)(h->h_addr_list[0])));
751 ncn->hostname = hostlookup(htonl(ncn->address));
753 if(setup_outgoing_meta_socket(ncn) < 0)
755 syslog(LOG_ERR, _("Could not set up a meta connection to %s"),
761 ncn->status.outgoing = 1;
762 ncn->buffer = xmalloc(MAXBUFSIZE);
764 ncn->last_ping_time = time(NULL);
774 Configure conn_list_t myself and set up the local sockets (listen only)
776 int setup_myself(void)
782 myself = new_conn_list();
784 asprintf(&myself->hostname, "MYSELF"); /* FIXME? Do hostlookup on ourselves? */
786 myself->protocol_version = PROT_CURRENT;
788 if(!(cfg = get_config_val(config, config_name))) /* Not acceptable */
790 syslog(LOG_ERR, _("Name for tinc daemon required!"));
794 asprintf(&myself->name, "%s", (char*)cfg->data.val);
796 if(check_id(myself->name))
798 syslog(LOG_ERR, _("Invalid name for myself!"));
802 if(!(cfg = get_config_val(config, config_privatekey)))
804 syslog(LOG_ERR, _("Private key for tinc daemon required!"));
809 myself->rsa_key = RSA_new();
810 BN_hex2bn(&myself->rsa_key->d, cfg->data.ptr);
811 BN_hex2bn(&myself->rsa_key->e, "FFFF");
814 if(read_host_config(myself))
816 syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
820 if(!(cfg = get_config_val(myself->config, config_publickey)))
822 syslog(LOG_ERR, _("Public key for tinc daemon required!"));
827 BN_hex2bn(&myself->rsa_key->n, cfg->data.ptr);
830 if(RSA_check_key(myself->rsa_key) != 1)
832 syslog(LOG_ERR, _("Invalid public/private keypair!"));
836 if(!(cfg = get_config_val(myself->config, config_port)))
839 myself->port = cfg->data.val;
841 if((cfg = get_config_val(myself->config, config_indirectdata)))
842 if(cfg->data.val == stupid_true)
843 myself->flags |= EXPORTINDIRECTDATA;
845 if((cfg = get_config_val(myself->config, config_tcponly)))
846 if(cfg->data.val == stupid_true)
847 myself->flags |= TCPONLY;
849 /* Read in all the subnets specified in the host configuration file */
851 for(next = myself->config; (cfg = get_config_val(next, config_subnet)); next = cfg->next)
854 net->type = SUBNET_IPV4;
855 net->net.ipv4.address = cfg->data.ip->address;
856 net->net.ipv4.mask = cfg->data.ip->mask;
858 /* Teach newbies what subnets are... */
860 if((net->net.ipv4.address & net->net.ipv4.mask) != net->net.ipv4.address)
862 syslog(LOG_ERR, _("Network address and subnet mask do not match!"));
866 subnet_add(myself, net);
869 if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
871 syslog(LOG_ERR, _("Unable to set up a listening socket!"));
875 /* Generate packet encryption key */
877 myself->cipher_pkttype = EVP_bf_cfb();
879 myself->cipher_pktkeylength = myself->cipher_pkttype->key_len + myself->cipher_pkttype->iv_len;
881 myself->cipher_pktkey = (char *)xmalloc(myself->cipher_pktkeylength);
882 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
884 if(!(cfg = get_config_val(config, config_keyexpire)))
887 keylifetime = cfg->data.val;
889 keyexpires = time(NULL) + keylifetime;
891 /* Activate ourselves */
893 myself->status.active = 1;
895 syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
901 sigalrm_handler(int a)
905 cfg = get_config_val(upstreamcfg, config_connectto);
907 if(!cfg && upstreamcfg == config)
908 /* No upstream IP given, we're listen only. */
913 upstreamcfg = cfg->next;
914 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
916 signal(SIGALRM, SIG_IGN);
919 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
922 signal(SIGALRM, sigalrm_handler);
923 upstreamcfg = config;
924 seconds_till_retry += 5;
925 if(seconds_till_retry > MAXTIMEOUT) /* Don't wait more than MAXTIMEOUT seconds. */
926 seconds_till_retry = MAXTIMEOUT;
927 syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
929 alarm(seconds_till_retry);
934 setup all initial network connections
936 int setup_network_connections(void)
940 if((cfg = get_config_val(config, config_pingtimeout)) == NULL)
944 timeout = cfg->data.val;
951 if(setup_tap_fd() < 0)
954 if(setup_myself() < 0)
957 /* Run tinc-up script to further initialize the tap interface */
958 execute_script("tinc-up");
960 if(!(cfg = get_config_val(config, config_connectto)))
961 /* No upstream IP given, we're listen only. */
966 upstreamcfg = cfg->next;
967 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
969 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
972 signal(SIGALRM, sigalrm_handler);
973 upstreamcfg = config;
974 seconds_till_retry = MAXTIMEOUT;
975 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
976 alarm(seconds_till_retry);
982 close all open network connections
984 void close_network_connections(void)
988 for(p = conn_list; p != NULL; p = p->next)
990 p->status.active = 0;
991 terminate_connection(p);
995 if(myself->status.active)
997 close(myself->meta_socket);
998 free_conn_list(myself);
1004 /* Execute tinc-down script right after shutting down the interface */
1005 execute_script("tinc-down");
1007 destroy_conn_list();
1009 syslog(LOG_NOTICE, _("Terminating"));
1015 create a data (udp) socket
1017 int setup_vpn_connection(conn_list_t *cl)
1020 struct sockaddr_in a;
1023 if(debug_lvl >= DEBUG_TRAFFIC)
1024 syslog(LOG_DEBUG, _("Opening UDP socket to %s"), cl->hostname);
1026 nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
1029 syslog(LOG_ERR, _("Creating UDP socket failed: %m"));
1033 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
1036 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1041 flags = fcntl(nfd, F_GETFL);
1042 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
1045 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1050 memset(&a, 0, sizeof(a));
1051 a.sin_family = AF_INET;
1052 a.sin_port = htons(myself->port);
1053 a.sin_addr.s_addr = htonl(INADDR_ANY);
1055 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
1058 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), myself->port);
1062 a.sin_family = AF_INET;
1063 a.sin_port = htons(cl->port);
1064 a.sin_addr.s_addr = htonl(cl->address);
1066 if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
1069 syslog(LOG_ERR, _("Connecting to %s port %d failed: %m"),
1070 cl->hostname, cl->port);
1074 flags = fcntl(nfd, F_GETFL);
1075 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
1078 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m %s (%s)"), __FILE__, __LINE__, nfd,
1079 cl->name, cl->hostname);
1084 cl->status.dataopen = 1;
1090 handle an incoming tcp connect call and open
1093 conn_list_t *create_new_connection(int sfd)
1096 struct sockaddr_in ci;
1097 int len = sizeof(ci);
1099 p = new_conn_list();
1101 if(getpeername(sfd, (struct sockaddr *) &ci, (socklen_t *) &len) < 0)
1103 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1109 p->address = ntohl(ci.sin_addr.s_addr);
1110 p->hostname = hostlookup(ci.sin_addr.s_addr);
1111 p->meta_socket = sfd;
1113 p->buffer = xmalloc(MAXBUFSIZE);
1115 p->last_ping_time = time(NULL);
1117 if(debug_lvl >= DEBUG_CONNECTIONS)
1118 syslog(LOG_NOTICE, _("Connection from %s port %d"),
1119 p->hostname, htons(ci.sin_port));
1121 p->allow_request = ID;
1127 put all file descriptors in an fd_set array
1129 void build_fdset(fd_set *fs)
1135 for(p = conn_list; p != NULL; p = p->next)
1138 FD_SET(p->meta_socket, fs);
1139 if(p->status.dataopen)
1140 FD_SET(p->socket, fs);
1143 FD_SET(myself->meta_socket, fs);
1149 receive incoming data from the listening
1150 udp socket and write it to the ethertap
1151 device after being decrypted
1153 int handle_incoming_vpn_data(conn_list_t *cl)
1156 int x, l = sizeof(x);
1159 if(getsockopt(cl->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1161 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1162 __FILE__, __LINE__, cl->socket);
1167 syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1171 if((lenin = recv(cl->socket, (char *) &(pkt.len), MTU, 0)) <= 0)
1173 syslog(LOG_ERR, _("Receiving packet failed: %m"));
1177 if(debug_lvl >= DEBUG_TRAFFIC)
1179 syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"), lenin,
1180 cl->name, cl->hostname);
1184 return xrecv(cl, &pkt);
1188 terminate a connection and notify the other
1189 end before closing the sockets
1191 void terminate_connection(conn_list_t *cl)
1196 if(cl->status.remove)
1199 cl->status.remove = 1;
1201 if(debug_lvl >= DEBUG_CONNECTIONS)
1202 syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1203 cl->name, cl->hostname);
1208 close(cl->meta_socket);
1211 /* Find all connections that were lost because they were behind cl
1212 (the connection that was dropped). */
1215 for(p = conn_list; p != NULL; p = p->next)
1216 if((p->nexthop == cl) && (p != cl))
1217 terminate_connection(p); /* Sounds like recursion, but p does not have a meta connection :) */
1219 /* Inform others of termination if it was still active */
1221 if(cl->status.active)
1222 for(p = conn_list; p != NULL; p = p->next)
1223 if(p->status.meta && p->status.active && p!=cl)
1224 send_del_host(p, cl);
1226 /* Remove the associated subnets */
1228 for(s = cl->subnets; s; s = s->next)
1231 /* Check if this was our outgoing connection */
1233 if(cl->status.outgoing && cl->status.active)
1235 signal(SIGALRM, sigalrm_handler);
1236 seconds_till_retry = 5;
1237 alarm(seconds_till_retry);
1238 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
1243 cl->status.active = 0;
1248 Check if the other end is active.
1249 If we have sent packets, but didn't receive any,
1250 then possibly the other end is dead. We send a
1251 PING request over the meta connection. If the other
1252 end does not reply in time, we consider them dead
1253 and close the connection.
1255 int check_dead_connections(void)
1261 for(p = conn_list; p != NULL; p = p->next)
1263 if(p->status.active && p->status.meta)
1265 if(p->last_ping_time + timeout < now)
1267 if(p->status.pinged)
1269 if(debug_lvl >= DEBUG_PROTOCOL)
1270 syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1271 p->name, p->hostname);
1272 p->status.timeout = 1;
1273 terminate_connection(p);
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"));
1316 check all connections to see if anything
1317 happened on their sockets
1319 void check_network_activity(fd_set *f)
1323 for(p = conn_list; p != NULL; p = p->next)
1325 if(p->status.remove)
1328 if(p->status.dataopen)
1329 if(FD_ISSET(p->socket, f))
1331 handle_incoming_vpn_data(p);
1333 /* Old error stuff (FIXME: copy this to handle_incoming_vpn_data()
1335 getsockopt(p->socket, SOL_SOCKET, SO_ERROR, &x, &l);
1336 syslog(LOG_ERR, _("Outgoing data socket error for %s (%s): %s"),
1337 p->name, p->hostname, strerror(x));
1338 terminate_connection(p);
1344 if(FD_ISSET(p->meta_socket, f))
1345 if(receive_meta(p) < 0)
1347 terminate_connection(p);
1352 if(FD_ISSET(myself->meta_socket, f))
1353 handle_new_meta_connection();
1358 read, encrypt and send data that is
1359 available through the ethertap device
1361 void handle_tap_input(void)
1366 if(taptype == TAP_TYPE_TUNTAP)
1368 if((lenin = read(tap_fd, vp.data, MTU)) <= 0)
1370 syslog(LOG_ERR, _("Error while reading from tun/tap device: %m"));
1377 if((lenin = read(tap_fd, vp.data - 2, MTU)) <= 0)
1379 syslog(LOG_ERR, _("Error while reading from ethertap device: %m"));
1385 total_tap_in += lenin;
1389 if(debug_lvl >= DEBUG_TRAFFIC)
1390 syslog(LOG_WARNING, _("Received short packet from tap device"));
1394 if(debug_lvl >= DEBUG_TRAFFIC)
1396 syslog(LOG_DEBUG, _("Read packet of length %d from tap device"), vp.len);
1399 send_packet(ntohl(*((unsigned long*)(&vp.data[30]))), &vp);
1404 this is where it all happens...
1406 void main_loop(void)
1411 time_t last_ping_check;
1414 last_ping_check = time(NULL);
1418 tv.tv_sec = timeout;
1424 if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1426 if(errno != EINTR) /* because of alarm */
1428 syslog(LOG_ERR, _("Error while waiting for input: %m"));
1435 syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1437 close_network_connections();
1438 clear_config(&config);
1440 if(read_server_config())
1442 syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1448 if(setup_network_connections())
1456 /* Let's check if everybody is still alive */
1458 if(last_ping_check + timeout < t)
1460 check_dead_connections();
1461 last_ping_check = time(NULL);
1463 /* Should we regenerate our key? */
1467 if(debug_lvl >= DEBUG_STATUS)
1468 syslog(LOG_INFO, _("Regenerating symmetric key"));
1470 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
1471 send_key_changed(myself, NULL);
1472 keyexpires = time(NULL) + keylifetime;
1478 check_network_activity(&fset);
1480 /* local tap data */
1481 if(FD_ISSET(tap_fd, &fset))