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.64 2000/11/04 15:32:05 zarq Exp $
25 #include <arpa/inet.h>
28 #include <linux/sockios.h>
31 #include <netinet/in.h>
35 #include <sys/signal.h>
36 #include <sys/socket.h>
38 #include <sys/types.h>
41 #include <sys/ioctl.h>
42 #include <openssl/rand.h>
43 #include <openssl/evp.h>
44 #include <openssl/err.h>
47 #include LINUX_IF_TUN_H
64 int taptype = TAP_TYPE_ETHERTAP;
66 int total_tap_out = 0;
67 int total_socket_in = 0;
68 int total_socket_out = 0;
70 config_t *upstreamcfg;
71 static int seconds_till_retry;
77 char *interface_name = NULL; /* Contains the name of the interface */
82 Execute the given script.
83 This function doesn't really belong here.
85 int execute_script(const char* name)
91 if((pid = fork()) < 0)
93 syslog(LOG_ERR, _("System call `%s' failed: %m"),
105 asprintf(&scriptname, "%s/%s", confbase, name);
106 asprintf(&s, "IFNAME=%s", interface_name);
112 asprintf(&s, "NETNAME=%s", netname);
121 if(chdir(confbase) < 0)
123 syslog(LOG_ERR, _("Couldn't chdir to `%s': %m"),
127 execl(scriptname, NULL);
128 /* No return on success */
130 if(errno != ENOENT) /* Ignore if the file does not exist */
131 syslog(LOG_WARNING, _("Error executing `%s': %m"), scriptname);
133 /* No need to free things */
137 int xsend(conn_list_t *cl, vpn_packet_t *inpkt)
143 outpkt.len = inpkt->len;
145 /* Encrypt the packet */
147 EVP_EncryptInit(&ctx, cl->cipher_pkttype, cl->cipher_pktkey, cl->cipher_pktkey + cl->cipher_pkttype->key_len);
148 EVP_EncryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len);
149 EVP_EncryptFinal(&ctx, outpkt.data + outlen, &outpad);
150 outlen += outpad + 2;
153 outlen = outpkt.len + 2;
154 memcpy(&outpkt, inpkt, outlen);
157 if(debug_lvl >= DEBUG_TRAFFIC)
158 syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
159 outlen, cl->name, cl->hostname);
161 total_socket_out += outlen;
165 if((send(cl->socket, (char *) &(outpkt.len), outlen, 0)) < 0)
167 syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
168 cl->name, cl->hostname);
175 int xrecv(vpn_packet_t *inpkt)
181 outpkt.len = inpkt->len;
183 /* Decrypt the packet */
185 EVP_DecryptInit(&ctx, myself->cipher_pkttype, myself->cipher_pktkey, myself->cipher_pktkey + myself->cipher_pkttype->key_len);
186 EVP_DecryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len + 8);
187 EVP_DecryptFinal(&ctx, outpkt.data + outlen, &outpad);
191 outlen = outpkt.len+2;
192 memcpy(&outpkt, inpkt, outlen);
195 if(debug_lvl >= DEBUG_TRAFFIC)
196 syslog(LOG_ERR, _("Writing packet of %d bytes to tap device"),
199 /* Fix mac address */
201 memcpy(outpkt.data, mymac.net.mac.address.x, 6);
203 if(taptype == TAP_TYPE_TUNTAP)
205 if(write(tap_fd, outpkt.data, outpkt.len) < 0)
206 syslog(LOG_ERR, _("Can't write to tun/tap device: %m"));
208 total_tap_out += outpkt.len;
212 if(write(tap_fd, outpkt.data - 2, outpkt.len + 2) < 0)
213 syslog(LOG_ERR, _("Can't write to ethertap device: %m"));
215 total_tap_out += outpkt.len + 2;
222 add the given packet of size s to the
223 queue q, be it the send or receive queue
225 void add_queue(packet_queue_t **q, void *packet, size_t s)
229 e = xmalloc(sizeof(*e));
230 e->packet = xmalloc(s);
231 memcpy(e->packet, packet, s);
235 *q = xmalloc(sizeof(**q));
236 (*q)->head = (*q)->tail = NULL;
239 e->next = NULL; /* We insert at the tail */
241 if((*q)->tail) /* Do we have a tail? */
243 (*q)->tail->next = e;
244 e->prev = (*q)->tail;
246 else /* No tail -> no head too */
256 /* Remove a queue element */
257 void del_queue(packet_queue_t **q, queue_element_t *e)
262 if(e->next) /* There is a successor, so we are not tail */
264 if(e->prev) /* There is a predecessor, so we are not head */
266 e->next->prev = e->prev;
267 e->prev->next = e->next;
269 else /* We are head */
271 e->next->prev = NULL;
272 (*q)->head = e->next;
275 else /* We are tail (or all alone!) */
277 if(e->prev) /* We are not alone :) */
279 e->prev->next = NULL;
280 (*q)->tail = e->prev;
294 flush a queue by calling function for
295 each packet, and removing it when that
296 returned a zero exit code
298 void flush_queue(conn_list_t *cl, packet_queue_t **pq,
299 int (*function)(conn_list_t*,void*))
301 queue_element_t *p, *next = NULL;
303 for(p = (*pq)->head; p != NULL; )
307 if(!function(cl, p->packet))
313 if(debug_lvl >= DEBUG_TRAFFIC)
314 syslog(LOG_DEBUG, _("Queue flushed"));
319 flush the send&recv queues
320 void because nothing goes wrong here, packets
321 remain in the queue if something goes wrong
323 void flush_queues(conn_list_t *cl)
328 if(debug_lvl >= DEBUG_TRAFFIC)
329 syslog(LOG_DEBUG, _("Flushing send queue for %s (%s)"),
330 cl->name, cl->hostname);
331 flush_queue(cl, &(cl->sq), xsend);
336 if(debug_lvl >= DEBUG_TRAFFIC)
337 syslog(LOG_DEBUG, _("Flushing receive queue for %s (%s)"),
338 cl->name, cl->hostname);
339 flush_queue(cl, &(cl->rq), xrecv);
345 send a packet to the given vpn ip.
347 int send_packet(ip_t to, vpn_packet_t *packet)
352 if((subnet = lookup_subnet_ipv4(to)) == NULL)
354 if(debug_lvl >= DEBUG_TRAFFIC)
356 syslog(LOG_NOTICE, _("Trying to look up %d.%d.%d.%d in connection list failed!"),
365 /* If we ourselves have indirectdata flag set, we should send only to our uplink! */
367 /* FIXME - check for indirection and reprogram it The Right Way(tm) this time. */
369 if(!cl->status.dataopen)
370 if(setup_vpn_connection(cl) < 0)
372 syslog(LOG_ERR, _("Could not open UDP connection to %s (%s)"),
373 cl->name, cl->hostname);
377 if(!cl->status.validkey)
379 /* FIXME: Don't queue until everything else is fixed.
380 if(debug_lvl >= DEBUG_TRAFFIC)
381 syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
382 cl->name, cl->hostname);
383 add_queue(&(cl->sq), packet, packet->len + 2);
385 if(!cl->status.waitingforkey)
386 send_req_key(myself, cl); /* Keys should be sent to the host running the tincd */
390 if(!cl->status.active)
392 /* FIXME: Don't queue until everything else is fixed.
393 if(debug_lvl >= DEBUG_TRAFFIC)
394 syslog(LOG_INFO, _("%s (%s) is not ready, queueing packet"),
395 cl->name, cl->hostname);
396 add_queue(&(cl->sq), packet, packet->len + 2);
398 return 0; /* We don't want to mess up, do we? */
401 /* can we send it? can we? can we? huh? */
403 return xsend(cl, packet);
407 open the local ethertap device
409 int setup_tap_fd(void)
412 const char *tapfname;
417 if((cfg = get_config_val(config, tapdevice)))
418 tapfname = cfg->data.ptr;
421 tapfname = "/dev/misc/net/tun";
423 tapfname = "/dev/tap0";
426 if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
428 syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
434 /* Set default MAC address for ethertap devices */
436 taptype = TAP_TYPE_ETHERTAP;
437 mymac.type = SUBNET_MAC;
438 mymac.net.mac.address.x[0] = 0xfe;
439 mymac.net.mac.address.x[1] = 0xfd;
440 mymac.net.mac.address.x[2] = 0x00;
441 mymac.net.mac.address.x[3] = 0x00;
442 mymac.net.mac.address.x[4] = 0x00;
443 mymac.net.mac.address.x[5] = 0x00;
446 /* Ok now check if this is an old ethertap or a new tun/tap thingie */
447 memset(&ifr, 0, sizeof(ifr));
449 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
451 strncpy(ifr.ifr_name, netname, IFNAMSIZ);
453 if (!ioctl(tap_fd, TUNSETIFF, (void *) &ifr))
455 syslog(LOG_INFO, _("%s is a new style tun/tap device"), tapfname);
456 taptype = TAP_TYPE_TUNTAP;
460 /* Add name of network interface to environment (for scripts) */
462 ioctl(tap_fd, SIOCGIFNAME, (void *) &ifr);
463 interface_name = xmalloc(strlen(ifr.ifr_name));
464 strcpy(interface_name, ifr.ifr_name);
471 set up the socket that we listen on for incoming
474 int setup_listen_meta_socket(int port)
477 struct sockaddr_in a;
481 if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
483 syslog(LOG_ERR, _("Creating metasocket failed: %m"));
487 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
489 syslog(LOG_ERR, _("System call `%s' failed: %m"),
494 if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one)))
496 syslog(LOG_ERR, _("System call `%s' failed: %m"),
501 flags = fcntl(nfd, F_GETFL);
502 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
504 syslog(LOG_ERR, _("System call `%s' failed: %m"),
509 if((cfg = get_config_val(config, interface)))
511 if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, cfg->data.ptr, strlen(cfg->data.ptr)))
513 syslog(LOG_ERR, _("Unable to bind listen socket to interface %s: %m"), cfg->data.ptr);
518 memset(&a, 0, sizeof(a));
519 a.sin_family = AF_INET;
520 a.sin_port = htons(port);
522 if((cfg = get_config_val(config, interfaceip)))
523 a.sin_addr.s_addr = htonl(cfg->data.ip->address);
525 a.sin_addr.s_addr = htonl(INADDR_ANY);
527 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
529 syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
535 syslog(LOG_ERR, _("System call `%s' failed: %m"),
544 setup the socket for incoming encrypted
547 int setup_vpn_in_socket(int port)
550 struct sockaddr_in a;
553 if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
555 syslog(LOG_ERR, _("Creating socket failed: %m"));
559 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
561 syslog(LOG_ERR, _("System call `%s' failed: %m"),
566 flags = fcntl(nfd, F_GETFL);
567 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
569 syslog(LOG_ERR, _("System call `%s' failed: %m"),
574 memset(&a, 0, sizeof(a));
575 a.sin_family = AF_INET;
576 a.sin_port = htons(port);
577 a.sin_addr.s_addr = htonl(INADDR_ANY);
579 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
581 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
589 setup an outgoing meta (tcp) socket
591 int setup_outgoing_meta_socket(conn_list_t *cl)
594 struct sockaddr_in a;
597 if(debug_lvl >= DEBUG_CONNECTIONS)
598 syslog(LOG_INFO, _("Trying to connect to %s"), cl->hostname);
600 if((cfg = get_config_val(cl->config, port)) == NULL)
603 cl->port = cfg->data.val;
605 cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
606 if(cl->meta_socket == -1)
608 syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
609 cl->hostname, cl->port);
613 a.sin_family = AF_INET;
614 a.sin_port = htons(cl->port);
615 a.sin_addr.s_addr = htonl(cl->address);
617 if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
619 syslog(LOG_ERR, _("%s port %hd: %m"), cl->hostname, cl->port);
623 flags = fcntl(cl->meta_socket, F_GETFL);
624 if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
626 syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
627 cl->hostname, cl->port);
631 if(debug_lvl >= DEBUG_CONNECTIONS)
632 syslog(LOG_INFO, _("Connected to %s port %hd"),
633 cl->hostname, cl->port);
641 setup an outgoing connection. It's not
642 necessary to also open an udp socket as
643 well, because the other host will initiate
644 an authentication sequence during which
645 we will do just that.
647 int setup_outgoing_connection(char *name)
655 syslog(LOG_ERR, _("Invalid name for outgoing connection"));
659 ncn = new_conn_list();
660 asprintf(&ncn->name, "%s", name);
662 if(read_host_config(ncn))
664 syslog(LOG_ERR, _("Error reading host configuration file for %s"));
669 if(!(cfg = get_config_val(ncn->config, address)))
671 syslog(LOG_ERR, _("No address specified for %s"));
676 if(!(h = gethostbyname(cfg->data.ptr)))
678 syslog(LOG_ERR, _("Error looking up `%s': %m"), cfg->data.ptr);
683 ncn->address = ntohl(*((ip_t*)(h->h_addr_list[0])));
684 ncn->hostname = hostlookup(htonl(ncn->address));
686 if(setup_outgoing_meta_socket(ncn) < 0)
688 syslog(LOG_ERR, _("Could not set up a meta connection to %s"),
694 ncn->status.outgoing = 1;
695 ncn->buffer = xmalloc(MAXBUFSIZE);
697 ncn->last_ping_time = time(NULL);
708 Configure conn_list_t myself and set up the local sockets (listen only)
710 int setup_myself(void)
715 myself = new_conn_list();
717 asprintf(&myself->hostname, "MYSELF"); /* FIXME? Do hostlookup on ourselves? */
719 myself->protocol_version = PROT_CURRENT;
721 if(!(cfg = get_config_val(config, tincname))) /* Not acceptable */
723 syslog(LOG_ERR, _("Name for tinc daemon required!"));
727 asprintf(&myself->name, "%s", (char*)cfg->data.val);
729 if(check_id(myself->name))
731 syslog(LOG_ERR, _("Invalid name for myself!"));
735 if(!(cfg = get_config_val(config, privatekey)))
737 syslog(LOG_ERR, _("Private key for tinc daemon required!"));
742 myself->rsa_key = RSA_new();
743 BN_hex2bn(&myself->rsa_key->d, cfg->data.ptr);
744 BN_hex2bn(&myself->rsa_key->e, "FFFF");
747 if(read_host_config(myself))
749 syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
753 if(!(cfg = get_config_val(myself->config, publickey)))
755 syslog(LOG_ERR, _("Public key for tinc daemon required!"));
760 BN_hex2bn(&myself->rsa_key->n, cfg->data.ptr);
763 if(RSA_check_key(myself->rsa_key) != 1)
765 syslog(LOG_ERR, _("Invalid public/private keypair!"));
769 if(!(cfg = get_config_val(myself->config, port)))
772 myself->port = cfg->data.val;
774 if((cfg = get_config_val(myself->config, indirectdata)))
775 if(cfg->data.val == stupid_true)
776 myself->flags |= EXPORTINDIRECTDATA;
778 if((cfg = get_config_val(myself->config, tcponly)))
779 if(cfg->data.val == stupid_true)
780 myself->flags |= TCPONLY;
782 /* Read in all the subnets specified in the host configuration file */
784 for(cfg = myself->config; (cfg = get_config_val(cfg, subnet)); cfg = cfg->next)
787 net->type = SUBNET_IPV4;
788 net->net.ipv4.address = cfg->data.ip->address;
789 net->net.ipv4.mask = cfg->data.ip->mask;
791 /* Teach newbies what subnets are... */
793 if((net->net.ipv4.address & net->net.ipv4.mask) != net->net.ipv4.address)
795 syslog(LOG_ERR, _("Network address and subnet mask do not match!"));
799 subnet_add(myself, net);
802 if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
804 syslog(LOG_ERR, _("Unable to set up a listening socket!"));
808 if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
810 syslog(LOG_ERR, _("Unable to set up an incoming vpn data socket!"));
811 close(myself->meta_socket);
815 /* Generate packet encryption key */
817 myself->cipher_pkttype = EVP_bf_cfb();
819 myself->cipher_pktkeylength = myself->cipher_pkttype->key_len + myself->cipher_pkttype->iv_len;
821 myself->cipher_pktkey = (char *)xmalloc(myself->cipher_pktkeylength);
822 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
824 if(!(cfg = get_config_val(config, keyexpire)))
827 keylifetime = cfg->data.val;
829 keyexpires = time(NULL) + keylifetime;
831 /* Activate ourselves */
833 myself->status.active = 1;
835 syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
841 sigalrm_handler(int a)
845 cfg = get_config_val(upstreamcfg, connectto);
847 if(!cfg && upstreamcfg == config)
848 /* No upstream IP given, we're listen only. */
853 upstreamcfg = cfg->next;
854 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
856 signal(SIGALRM, SIG_IGN);
859 cfg = get_config_val(upstreamcfg, connectto); /* Or else we try the next ConnectTo line */
862 signal(SIGALRM, sigalrm_handler);
863 upstreamcfg = config;
864 seconds_till_retry += 5;
865 if(seconds_till_retry > MAXTIMEOUT) /* Don't wait more than MAXTIMEOUT seconds. */
866 seconds_till_retry = MAXTIMEOUT;
867 syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
869 alarm(seconds_till_retry);
874 setup all initial network connections
876 int setup_network_connections(void)
880 if((cfg = get_config_val(config, pingtimeout)) == NULL)
883 timeout = cfg->data.val;
885 if(setup_tap_fd() < 0)
888 if(setup_myself() < 0)
891 /* Run tinc-up script to further initialize the tap interface */
892 execute_script("tinc-up");
894 if(!(cfg = get_config_val(config, connectto)))
895 /* No upstream IP given, we're listen only. */
900 upstreamcfg = cfg->next;
901 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
903 cfg = get_config_val(upstreamcfg, connectto); /* Or else we try the next ConnectTo line */
906 signal(SIGALRM, sigalrm_handler);
907 upstreamcfg = config;
908 seconds_till_retry = MAXTIMEOUT;
909 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
910 alarm(seconds_till_retry);
916 close all open network connections
918 void close_network_connections(void)
922 for(p = conn_list; p != NULL; p = p->next)
924 p->status.active = 0;
925 terminate_connection(p);
929 if(myself->status.active)
931 close(myself->meta_socket);
932 close(myself->socket);
933 free_conn_list(myself);
939 /* Execute tinc-down script right after shutting down the interface */
940 execute_script("tinc-down");
944 syslog(LOG_NOTICE, _("Terminating"));
950 create a data (udp) socket
952 int setup_vpn_connection(conn_list_t *cl)
955 struct sockaddr_in a;
957 if(debug_lvl >= DEBUG_TRAFFIC)
958 syslog(LOG_DEBUG, _("Opening UDP socket to %s"), cl->hostname);
960 nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
963 syslog(LOG_ERR, _("Creating UDP socket failed: %m"));
967 a.sin_family = AF_INET;
968 a.sin_port = htons(cl->port);
969 a.sin_addr.s_addr = htonl(cl->address);
971 if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
973 syslog(LOG_ERR, _("Connecting to %s port %d failed: %m"),
974 cl->hostname, cl->port);
978 flags = fcntl(nfd, F_GETFL);
979 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
981 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m %s (%s)"), __FILE__, __LINE__, nfd,
982 cl->name, cl->hostname);
987 cl->status.dataopen = 1;
993 handle an incoming tcp connect call and open
996 conn_list_t *create_new_connection(int sfd)
999 struct sockaddr_in ci;
1000 int len = sizeof(ci);
1002 p = new_conn_list();
1004 if(getpeername(sfd, &ci, &len) < 0)
1006 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1012 p->address = ntohl(ci.sin_addr.s_addr);
1013 p->hostname = hostlookup(ci.sin_addr.s_addr);
1014 p->meta_socket = sfd;
1016 p->buffer = xmalloc(MAXBUFSIZE);
1018 p->last_ping_time = time(NULL);
1021 if(debug_lvl >= DEBUG_CONNECTIONS)
1022 syslog(LOG_NOTICE, _("Connection from %s port %d"),
1023 p->hostname, htons(ci.sin_port));
1025 p->allow_request = ID;
1031 put all file descriptors in an fd_set array
1033 void build_fdset(fd_set *fs)
1039 for(p = conn_list; p != NULL; p = p->next)
1042 FD_SET(p->meta_socket, fs);
1043 if(p->status.dataopen)
1044 FD_SET(p->socket, fs);
1047 FD_SET(myself->meta_socket, fs);
1048 FD_SET(myself->socket, fs);
1054 receive incoming data from the listening
1055 udp socket and write it to the ethertap
1056 device after being decrypted
1058 int handle_incoming_vpn_data()
1061 int x, l = sizeof(x);
1062 struct sockaddr from;
1064 socklen_t fromlen = sizeof(from);
1066 if(getsockopt(myself->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1068 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1069 __FILE__, __LINE__, myself->socket);
1074 syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1078 if((lenin = recvfrom(myself->socket, (char *) &(pkt.len), MTU, 0, &from, &fromlen)) <= 0)
1080 syslog(LOG_ERR, _("Receiving packet failed: %m"));
1084 if(debug_lvl >= DEBUG_TRAFFIC)
1086 syslog(LOG_DEBUG, _("Received packet of %d bytes"), lenin);
1094 terminate a connection and notify the other
1095 end before closing the sockets
1097 void terminate_connection(conn_list_t *cl)
1102 if(cl->status.remove)
1105 cl->status.remove = 1;
1107 if(debug_lvl >= DEBUG_CONNECTIONS)
1108 syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1109 cl->name, cl->hostname);
1114 close(cl->meta_socket);
1117 /* Find all connections that were lost because they were behind cl
1118 (the connection that was dropped). */
1121 for(p = conn_list; p != NULL; p = p->next)
1122 if((p->nexthop == cl) && (p != cl))
1123 terminate_connection(p); /* Sounds like recursion, but p does not have a meta connection :) */
1125 /* Inform others of termination if it was still active */
1127 if(cl->status.active)
1128 for(p = conn_list; p != NULL; p = p->next)
1129 if(p->status.meta && p->status.active && p!=cl)
1130 send_del_host(p, cl);
1132 /* Remove the associated subnets */
1134 for(s = cl->subnets; s; s = s->next)
1137 /* Check if this was our outgoing connection */
1139 if(cl->status.outgoing && cl->status.active)
1141 signal(SIGALRM, sigalrm_handler);
1142 seconds_till_retry = 5;
1143 alarm(seconds_till_retry);
1144 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
1149 cl->status.active = 0;
1154 Check if the other end is active.
1155 If we have sent packets, but didn't receive any,
1156 then possibly the other end is dead. We send a
1157 PING request over the meta connection. If the other
1158 end does not reply in time, we consider them dead
1159 and close the connection.
1161 int check_dead_connections(void)
1167 for(p = conn_list; p != NULL; p = p->next)
1169 if(p->status.active && p->status.meta)
1171 if(p->last_ping_time + timeout < now)
1173 if(p->status.pinged && !p->status.got_pong)
1175 if(debug_lvl >= DEBUG_PROTOCOL)
1176 syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1177 p->name, p->hostname);
1178 p->status.timeout = 1;
1179 terminate_connection(p);
1181 else if(p->want_ping)
1184 p->last_ping_time = now;
1185 p->status.pinged = 1;
1186 p->status.got_pong = 0;
1196 accept a new tcp connect and create a
1199 int handle_new_meta_connection()
1202 struct sockaddr client;
1203 int nfd, len = sizeof(client);
1205 if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
1207 syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1211 if(!(ncn = create_new_connection(nfd)))
1215 syslog(LOG_NOTICE, _("Closed attempted connection"));
1225 check all connections to see if anything
1226 happened on their sockets
1228 void check_network_activity(fd_set *f)
1231 int x, l = sizeof(x);
1233 for(p = conn_list; p != NULL; p = p->next)
1235 if(p->status.remove)
1238 if(p->status.dataopen)
1239 if(FD_ISSET(p->socket, f))
1242 The only thing that can happen to get us here is apparently an
1243 error on this outgoing(!) UDP socket that isn't immediate (i.e.
1244 something that will not trigger an error directly on send()).
1245 I've once got here when it said `No route to host'.
1247 getsockopt(p->socket, SOL_SOCKET, SO_ERROR, &x, &l);
1248 syslog(LOG_ERR, _("Outgoing data socket error for %s (%s): %s"),
1249 p->name, p->hostname, strerror(x));
1250 terminate_connection(p);
1255 if(FD_ISSET(p->meta_socket, f))
1256 if(receive_meta(p) < 0)
1258 terminate_connection(p);
1263 if(FD_ISSET(myself->socket, f))
1264 handle_incoming_vpn_data();
1266 if(FD_ISSET(myself->meta_socket, f))
1267 handle_new_meta_connection();
1272 read, encrypt and send data that is
1273 available through the ethertap device
1275 void handle_tap_input(void)
1280 if(taptype == TAP_TYPE_TUNTAP)
1282 if((lenin = read(tap_fd, vp.data, MTU)) <= 0)
1284 syslog(LOG_ERR, _("Error while reading from tun/tap device: %m"));
1291 if((lenin = read(tap_fd, vp.data - 2, MTU)) <= 0)
1293 syslog(LOG_ERR, _("Error while reading from ethertap device: %m"));
1299 total_tap_in += lenin;
1303 if(debug_lvl >= DEBUG_TRAFFIC)
1304 syslog(LOG_WARNING, _("Received short packet from tap device"));
1308 if(debug_lvl >= DEBUG_TRAFFIC)
1310 syslog(LOG_DEBUG, _("Read packet of length %d from tap device"), vp.len);
1313 send_packet(ntohl(*((unsigned long*)(&vp.data[30]))), &vp);
1318 this is where it all happens...
1320 void main_loop(void)
1325 time_t last_ping_check;
1328 last_ping_check = time(NULL);
1332 tv.tv_sec = timeout;
1338 if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1340 if(errno != EINTR) /* because of alarm */
1342 syslog(LOG_ERR, _("Error while waiting for input: %m"));
1349 syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1351 close_network_connections();
1352 clear_config(&config);
1354 if(read_server_config())
1356 syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1362 if(setup_network_connections())
1370 /* Let's check if everybody is still alive */
1372 if(last_ping_check + timeout < t)
1374 check_dead_connections();
1375 last_ping_check = time(NULL);
1377 /* Should we regenerate our key? */
1381 if(debug_lvl >= DEBUG_STATUS)
1382 syslog(LOG_INFO, _("Regenerating symmetric key"));
1384 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
1385 send_key_changed(myself, NULL);
1386 keyexpires = time(NULL) + keylifetime;
1392 check_network_activity(&fset);
1394 /* local tap data */
1395 if(FD_ISSET(tap_fd, &fset))