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.55 2000/10/29 22:10:42 guus 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;
81 strip off the MAC adresses of an ethernet frame
83 void strip_mac_addresses(vpn_packet_t *p)
86 memmove(p->data, p->data + 12, p->len -= 12);
91 reassemble MAC addresses
93 void add_mac_addresses(vpn_packet_t *p)
96 memcpy(p->data + 12, p->data, p->len);
98 p->data[0] = p->data[6] = 0xfe;
99 p->data[1] = p->data[7] = 0xfd;
100 /* Really evil pointer stuff just below! */
101 *((ip_t*)(&p->data[2])) = (ip_t)(htonl(myself->address));
102 *((ip_t*)(&p->data[8])) = *((ip_t*)(&p->data[26]));
106 int xsend(conn_list_t *cl, vpn_packet_t *inpkt)
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;
134 if((send(cl->socket, (char *) &(outpkt.len), outlen, 0)) < 0)
136 syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
137 cl->name, cl->hostname);
144 int xrecv(vpn_packet_t *inpkt)
150 outpkt.len = inpkt->len;
152 /* Decrypt the packet */
154 EVP_DecryptInit(&ctx, myself->cipher_pkttype, myself->cipher_pktkey, myself->cipher_pktkey + myself->cipher_pkttype->key_len);
155 EVP_DecryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len + 8);
156 EVP_DecryptFinal(&ctx, outpkt.data + outlen, &outpad);
160 outlen = outpkt.len+2;
161 memcpy(&outpkt, inpkt, outlen);
164 if(debug_lvl >= DEBUG_TRAFFIC)
165 syslog(LOG_ERR, _("Writing packet of %d (%d) bytes to tap device"),
168 /* Fix mac address */
170 memcpy(outpkt.data, mymac.net.mac.address.x, 6);
172 if(taptype == TAP_TYPE_TUNTAP)
174 if(write(tap_fd, outpkt.data, outpkt.len) < 0)
175 syslog(LOG_ERR, _("Can't write to tun/tap device: %m"));
177 total_tap_out += outpkt.len;
181 if(write(tap_fd, outpkt.data - 2, outpkt.len + 2) < 0)
182 syslog(LOG_ERR, _("Can't write to ethertap device: %m"));
184 total_tap_out += outpkt.len + 2;
191 add the given packet of size s to the
192 queue q, be it the send or receive queue
194 void add_queue(packet_queue_t **q, void *packet, size_t s)
198 e = xmalloc(sizeof(*e));
199 e->packet = xmalloc(s);
200 memcpy(e->packet, packet, s);
204 *q = xmalloc(sizeof(**q));
205 (*q)->head = (*q)->tail = NULL;
208 e->next = NULL; /* We insert at the tail */
210 if((*q)->tail) /* Do we have a tail? */
212 (*q)->tail->next = e;
213 e->prev = (*q)->tail;
215 else /* No tail -> no head too */
225 /* Remove a queue element */
226 void del_queue(packet_queue_t **q, queue_element_t *e)
231 if(e->next) /* There is a successor, so we are not tail */
233 if(e->prev) /* There is a predecessor, so we are not head */
235 e->next->prev = e->prev;
236 e->prev->next = e->next;
238 else /* We are head */
240 e->next->prev = NULL;
241 (*q)->head = e->next;
244 else /* We are tail (or all alone!) */
246 if(e->prev) /* We are not alone :) */
248 e->prev->next = NULL;
249 (*q)->tail = e->prev;
263 flush a queue by calling function for
264 each packet, and removing it when that
265 returned a zero exit code
267 void flush_queue(conn_list_t *cl, packet_queue_t **pq,
268 int (*function)(conn_list_t*,void*))
270 queue_element_t *p, *next = NULL;
272 for(p = (*pq)->head; p != NULL; )
276 if(!function(cl, p->packet))
282 if(debug_lvl >= DEBUG_TRAFFIC)
283 syslog(LOG_DEBUG, _("Queue flushed"));
288 flush the send&recv queues
289 void because nothing goes wrong here, packets
290 remain in the queue if something goes wrong
292 void flush_queues(conn_list_t *cl)
297 if(debug_lvl >= DEBUG_TRAFFIC)
298 syslog(LOG_DEBUG, _("Flushing send queue for %s (%s)"),
299 cl->name, cl->hostname);
300 flush_queue(cl, &(cl->sq), xsend);
305 if(debug_lvl >= DEBUG_TRAFFIC)
306 syslog(LOG_DEBUG, _("Flushing receive queue for %s (%s)"),
307 cl->name, cl->hostname);
308 flush_queue(cl, &(cl->rq), xrecv);
314 send a packet to the given vpn ip.
316 int send_packet(ip_t to, vpn_packet_t *packet)
321 if((subnet = lookup_subnet_ipv4(to)) == NULL)
323 if(debug_lvl >= DEBUG_TRAFFIC)
325 syslog(LOG_NOTICE, _("Trying to look up %d.%d.%d.%d in connection list failed!"),
334 /* If we ourselves have indirectdata flag set, we should send only to our uplink! */
336 /* FIXME - check for indirection and reprogram it The Right Way(tm) this time. */
338 if(!cl->status.dataopen)
339 if(setup_vpn_connection(cl) < 0)
341 syslog(LOG_ERR, _("Could not open UDP connection to %s (%s)"),
342 cl->name, cl->hostname);
346 if(!cl->status.validkey)
348 /* FIXME: Don't queue until everything else is fixed.
349 if(debug_lvl >= DEBUG_TRAFFIC)
350 syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
351 cl->name, cl->hostname);
352 add_queue(&(cl->sq), packet, packet->len + 2);
354 if(!cl->status.waitingforkey)
355 send_req_key(myself, cl); /* Keys should be sent to the host running the tincd */
359 if(!cl->status.active)
361 /* FIXME: Don't queue until everything else is fixed.
362 if(debug_lvl >= DEBUG_TRAFFIC)
363 syslog(LOG_INFO, _("%s (%s) is not ready, queueing packet"),
364 cl->name, cl->hostname);
365 add_queue(&(cl->sq), packet, packet->len + 2);
367 return 0; /* We don't want to mess up, do we? */
370 /* can we send it? can we? can we? huh? */
372 return xsend(cl, packet);
376 open the local ethertap device
378 int setup_tap_fd(void)
381 const char *tapfname;
387 if((cfg = get_config_val(config, tapdevice)))
388 tapfname = cfg->data.ptr;
391 tapfname = "/dev/misc/net/tun";
393 tapfname = "/dev/tap0";
396 if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
398 syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
404 /* Set default MAC address for ethertap devices */
406 taptype = TAP_TYPE_ETHERTAP;
407 mymac.type = SUBNET_MAC;
408 mymac.net.mac.address.x[0] = 0xfe;
409 mymac.net.mac.address.x[1] = 0xfd;
410 mymac.net.mac.address.x[2] = 0x00;
411 mymac.net.mac.address.x[3] = 0x00;
412 mymac.net.mac.address.x[4] = 0x00;
413 mymac.net.mac.address.x[5] = 0x00;
416 /* Ok now check if this is an old ethertap or a new tun/tap thingie */
417 memset(&ifr, 0, sizeof(ifr));
419 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
421 strncpy(ifr.ifr_name, netname, IFNAMSIZ);
423 if (!ioctl(tap_fd, TUNSETIFF, (void *) &ifr))
425 syslog(LOG_INFO, _("%s is a new style tun/tap device"), tapfname);
426 taptype = TAP_TYPE_TUNTAP;
430 /* Add name of network interface to environment (for scripts) */
432 ioctl(tap_fd, SIOCGIFNAME, (void *) &ifr);
433 asprintf(&envvar, "IFNAME=%s", ifr.ifr_name);
442 set up the socket that we listen on for incoming
445 int setup_listen_meta_socket(int port)
448 struct sockaddr_in a;
452 if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
454 syslog(LOG_ERR, _("Creating metasocket failed: %m"));
458 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
460 syslog(LOG_ERR, _("setsockopt: %m"));
464 if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one)))
466 syslog(LOG_ERR, _("setsockopt: %m"));
470 flags = fcntl(nfd, F_GETFL);
471 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
473 syslog(LOG_ERR, _("fcntl: %m"));
477 if((cfg = get_config_val(config, interface)))
479 if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, cfg->data.ptr, strlen(cfg->data.ptr)))
481 syslog(LOG_ERR, _("Unable to bind listen socket to interface %s: %m"), cfg->data.ptr);
486 memset(&a, 0, sizeof(a));
487 a.sin_family = AF_INET;
488 a.sin_port = htons(port);
490 if((cfg = get_config_val(config, interfaceip)))
491 a.sin_addr.s_addr = htonl(cfg->data.ip->address);
493 a.sin_addr.s_addr = htonl(INADDR_ANY);
495 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
497 syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
503 syslog(LOG_ERR, _("listen: %m"));
511 setup the socket for incoming encrypted
514 int setup_vpn_in_socket(int port)
517 struct sockaddr_in a;
520 if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
522 syslog(LOG_ERR, _("Creating socket failed: %m"));
526 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
528 syslog(LOG_ERR, _("setsockopt: %m"));
532 flags = fcntl(nfd, F_GETFL);
533 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
535 syslog(LOG_ERR, _("fcntl: %m"));
539 memset(&a, 0, sizeof(a));
540 a.sin_family = AF_INET;
541 a.sin_port = htons(port);
542 a.sin_addr.s_addr = htonl(INADDR_ANY);
544 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
546 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
554 setup an outgoing meta (tcp) socket
556 int setup_outgoing_meta_socket(conn_list_t *cl)
559 struct sockaddr_in a;
562 if(debug_lvl >= DEBUG_CONNECTIONS)
563 syslog(LOG_INFO, _("Trying to connect to %s"), cl->hostname);
565 if((cfg = get_config_val(cl->config, port)) == NULL)
568 cl->port = cfg->data.val;
570 cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
571 if(cl->meta_socket == -1)
573 syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
574 cl->hostname, cl->port);
578 a.sin_family = AF_INET;
579 a.sin_port = htons(cl->port);
580 a.sin_addr.s_addr = htonl(cl->address);
582 if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
584 syslog(LOG_ERR, _("%s port %hd: %m"), cl->hostname, cl->port);
588 flags = fcntl(cl->meta_socket, F_GETFL);
589 if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
591 syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
592 cl->hostname, cl->port);
596 if(debug_lvl >= DEBUG_CONNECTIONS)
597 syslog(LOG_INFO, _("Connected to %s port %hd"),
598 cl->hostname, cl->port);
606 setup an outgoing connection. It's not
607 necessary to also open an udp socket as
608 well, because the other host will initiate
609 an authentication sequence during which
610 we will do just that.
612 int setup_outgoing_connection(char *name)
620 syslog(LOG_ERR, _("Invalid name for outgoing connection"));
624 ncn = new_conn_list();
625 asprintf(&ncn->name, "%s", name);
627 if(read_host_config(ncn))
629 syslog(LOG_ERR, _("Error reading host configuration file for %s"));
634 if(!(cfg = get_config_val(ncn->config, address)))
636 syslog(LOG_ERR, _("No address specified for %s"));
641 if(!(h = gethostbyname(cfg->data.ptr)))
643 syslog(LOG_ERR, _("Error looking up `%s': %m"), cfg->data.ptr);
648 ncn->address = ntohl(*((ip_t*)(h->h_addr_list[0])));
649 ncn->hostname = hostlookup(htonl(ncn->address));
651 if(setup_outgoing_meta_socket(ncn) < 0)
653 syslog(LOG_ERR, _("Could not set up a meta connection to %s"),
659 ncn->status.outgoing = 1;
660 ncn->buffer = xmalloc(MAXBUFSIZE);
662 ncn->last_ping_time = time(NULL);
673 Configure conn_list_t myself and set up the local sockets (listen only)
675 int setup_myself(void)
680 myself = new_conn_list();
682 asprintf(&myself->hostname, "MYSELF"); /* FIXME? Do hostlookup on ourselves? */
684 myself->protocol_version = PROT_CURRENT;
686 if(!(cfg = get_config_val(config, tincname))) /* Not acceptable */
688 syslog(LOG_ERR, _("Name for tinc daemon required!"));
692 asprintf(&myself->name, "%s", (char*)cfg->data.val);
694 if(check_id(myself->name))
696 syslog(LOG_ERR, _("Invalid name for myself!"));
700 if(!(cfg = get_config_val(config, privatekey)))
702 syslog(LOG_ERR, _("Private key for tinc daemon required!"));
707 myself->rsa_key = RSA_new();
708 BN_hex2bn(&myself->rsa_key->d, cfg->data.ptr);
709 BN_hex2bn(&myself->rsa_key->e, "FFFF");
712 if(read_host_config(myself))
714 syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
718 if(!(cfg = get_config_val(myself->config, publickey)))
720 syslog(LOG_ERR, _("Public key for tinc daemon required!"));
725 BN_hex2bn(&myself->rsa_key->n, cfg->data.ptr);
728 if(RSA_check_key(myself->rsa_key) != 1)
730 syslog(LOG_ERR, _("Invalid public/private keypair!"));
734 if(!(cfg = get_config_val(myself->config, port)))
737 myself->port = cfg->data.val;
739 if((cfg = get_config_val(myself->config, indirectdata)))
740 if(cfg->data.val == stupid_true)
741 myself->flags |= EXPORTINDIRECTDATA;
743 if((cfg = get_config_val(myself->config, tcponly)))
744 if(cfg->data.val == stupid_true)
745 myself->flags |= TCPONLY;
747 /* Read in all the subnets specified in the host configuration file */
749 for(cfg = myself->config; (cfg = get_config_val(cfg, subnet)); cfg = cfg->next)
752 net->type = SUBNET_IPV4;
753 net->net.ipv4.address = cfg->data.ip->address;
754 net->net.ipv4.mask = cfg->data.ip->mask;
756 /* Teach newbies what subnets are... */
758 if((net->net.ipv4.address & net->net.ipv4.mask) != net->net.ipv4.address)
760 syslog(LOG_ERR, _("Network address and subnet mask do not match!"));
764 subnet_add(myself, net);
767 if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
769 syslog(LOG_ERR, _("Unable to set up a listening socket!"));
773 if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
775 syslog(LOG_ERR, _("Unable to set up an incoming vpn data socket!"));
776 close(myself->meta_socket);
780 /* Generate packet encryption key */
782 myself->cipher_pkttype = EVP_bf_cfb();
784 myself->cipher_pktkeylength = myself->cipher_pkttype->key_len + myself->cipher_pkttype->iv_len;
786 myself->cipher_pktkey = (char *)xmalloc(myself->cipher_pktkeylength);
787 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
789 if(!(cfg = get_config_val(config, keyexpire)))
792 keylifetime = cfg->data.val;
794 keyexpires = time(NULL) + keylifetime;
796 /* Activate ourselves */
798 myself->status.active = 1;
800 syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
806 sigalrm_handler(int a)
810 cfg = get_config_val(upstreamcfg, connectto);
812 if(!cfg && upstreamcfg == config)
813 /* No upstream IP given, we're listen only. */
818 upstreamcfg = cfg->next;
819 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
821 signal(SIGALRM, SIG_IGN);
824 cfg = get_config_val(upstreamcfg, connectto); /* Or else we try the next ConnectTo line */
827 signal(SIGALRM, sigalrm_handler);
828 upstreamcfg = config;
829 seconds_till_retry += 5;
830 if(seconds_till_retry > MAXTIMEOUT) /* Don't wait more than MAXTIMEOUT seconds. */
831 seconds_till_retry = MAXTIMEOUT;
832 syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
834 alarm(seconds_till_retry);
839 setup all initial network connections
841 int setup_network_connections(void)
846 if((cfg = get_config_val(config, pingtimeout)) == NULL)
849 timeout = cfg->data.val;
851 if(setup_tap_fd() < 0)
854 if(setup_myself() < 0)
857 /* Run tinc-up script to further initialize the tap interface */
859 asprintf(&scriptname, "%s/tinc-up", confbase);
864 execl(scriptname, NULL);
867 syslog(LOG_WARNING, _("Error while executing %s: %m"), scriptname);
874 if(!(cfg = get_config_val(config, connectto)))
875 /* No upstream IP given, we're listen only. */
880 upstreamcfg = cfg->next;
881 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
883 cfg = get_config_val(upstreamcfg, connectto); /* Or else we try the next ConnectTo line */
886 signal(SIGALRM, sigalrm_handler);
887 upstreamcfg = config;
888 seconds_till_retry = MAXTIMEOUT;
889 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
890 alarm(seconds_till_retry);
896 close all open network connections
898 void close_network_connections(void)
903 for(p = conn_list; p != NULL; p = p->next)
905 p->status.active = 0;
906 terminate_connection(p);
910 if(myself->status.active)
912 close(myself->meta_socket);
913 close(myself->socket);
914 free_conn_list(myself);
918 /* Execute tinc-down script right before shutting down the interface */
920 asprintf(&scriptname, "%s/tinc-down", confbase);
924 execl(scriptname, NULL);
927 syslog(LOG_WARNING, _("Error while executing %s: %m"), scriptname);
937 syslog(LOG_NOTICE, _("Terminating"));
943 create a data (udp) socket
945 int setup_vpn_connection(conn_list_t *cl)
948 struct sockaddr_in a;
950 if(debug_lvl >= DEBUG_TRAFFIC)
951 syslog(LOG_DEBUG, _("Opening UDP socket to %s"), cl->hostname);
953 nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
956 syslog(LOG_ERR, _("Creating UDP socket failed: %m"));
960 a.sin_family = AF_INET;
961 a.sin_port = htons(cl->port);
962 a.sin_addr.s_addr = htonl(cl->address);
964 if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
966 syslog(LOG_ERR, _("Connecting to %s port %d failed: %m"),
967 cl->hostname, cl->port);
971 flags = fcntl(nfd, F_GETFL);
972 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
974 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m %s (%s)"), __FILE__, __LINE__, nfd,
975 cl->name, cl->hostname);
980 cl->status.dataopen = 1;
986 handle an incoming tcp connect call and open
989 conn_list_t *create_new_connection(int sfd)
992 struct sockaddr_in ci;
993 int len = sizeof(ci);
997 if(getpeername(sfd, &ci, &len) < 0)
999 syslog(LOG_ERR, _("Error: getpeername: %m"));
1004 p->address = ntohl(ci.sin_addr.s_addr);
1005 p->hostname = hostlookup(ci.sin_addr.s_addr);
1006 p->meta_socket = sfd;
1008 p->buffer = xmalloc(MAXBUFSIZE);
1010 p->last_ping_time = time(NULL);
1013 if(debug_lvl >= DEBUG_CONNECTIONS)
1014 syslog(LOG_NOTICE, _("Connection from %s port %d"),
1015 p->hostname, htons(ci.sin_port));
1017 p->allow_request = ID;
1023 put all file descriptors in an fd_set array
1025 void build_fdset(fd_set *fs)
1031 for(p = conn_list; p != NULL; p = p->next)
1034 FD_SET(p->meta_socket, fs);
1035 if(p->status.dataopen)
1036 FD_SET(p->socket, fs);
1039 FD_SET(myself->meta_socket, fs);
1040 FD_SET(myself->socket, fs);
1046 receive incoming data from the listening
1047 udp socket and write it to the ethertap
1048 device after being decrypted
1050 int handle_incoming_vpn_data()
1053 int x, l = sizeof(x);
1054 struct sockaddr from;
1056 socklen_t fromlen = sizeof(from);
1058 if(getsockopt(myself->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1060 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1061 __FILE__, __LINE__, myself->socket);
1066 syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1070 if((lenin = recvfrom(myself->socket, (char *) &(pkt.len), MTU, 0, &from, &fromlen)) <= 0)
1072 syslog(LOG_ERR, _("Receiving packet failed: %m"));
1076 if(debug_lvl >= DEBUG_TRAFFIC)
1078 syslog(LOG_DEBUG, _("Received packet of %d bytes"), lenin);
1086 terminate a connection and notify the other
1087 end before closing the sockets
1089 void terminate_connection(conn_list_t *cl)
1094 if(cl->status.remove)
1097 cl->status.remove = 1;
1099 if(debug_lvl >= DEBUG_CONNECTIONS)
1100 syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1101 cl->name, cl->hostname);
1106 close(cl->meta_socket);
1109 /* Find all connections that were lost because they were behind cl
1110 (the connection that was dropped). */
1113 for(p = conn_list; p != NULL; p = p->next)
1114 if((p->nexthop == cl) && (p != cl))
1115 terminate_connection(p); /* Sounds like recursion, but p does not have a meta connection :) */
1117 /* Inform others of termination if it was still active */
1119 if(cl->status.active)
1120 for(p = conn_list; p != NULL; p = p->next)
1121 if(p->status.meta && p->status.active && p!=cl)
1122 send_del_host(p, cl);
1124 /* Remove the associated subnets */
1126 for(s = cl->subnets; s; s = s->next)
1129 /* Check if this was our outgoing connection */
1131 if(cl->status.outgoing && cl->status.active)
1133 signal(SIGALRM, sigalrm_handler);
1134 seconds_till_retry = 5;
1135 alarm(seconds_till_retry);
1136 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
1141 cl->status.active = 0;
1146 Check if the other end is active.
1147 If we have sent packets, but didn't receive any,
1148 then possibly the other end is dead. We send a
1149 PING request over the meta connection. If the other
1150 end does not reply in time, we consider them dead
1151 and close the connection.
1153 int check_dead_connections(void)
1159 for(p = conn_list; p != NULL; p = p->next)
1161 if(p->status.active && p->status.meta)
1163 if(p->last_ping_time + timeout < now)
1165 if(p->status.pinged && !p->status.got_pong)
1167 if(debug_lvl >= DEBUG_PROTOCOL)
1168 syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1169 p->name, p->hostname);
1170 p->status.timeout = 1;
1171 terminate_connection(p);
1173 else if(p->want_ping)
1176 p->last_ping_time = now;
1177 p->status.pinged = 1;
1178 p->status.got_pong = 0;
1188 accept a new tcp connect and create a
1191 int handle_new_meta_connection()
1194 struct sockaddr client;
1195 int nfd, len = sizeof(client);
1197 if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
1199 syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1203 if(!(ncn = create_new_connection(nfd)))
1207 syslog(LOG_NOTICE, _("Closed attempted connection"));
1217 check all connections to see if anything
1218 happened on their sockets
1220 void check_network_activity(fd_set *f)
1223 int x, l = sizeof(x);
1225 for(p = conn_list; p != NULL; p = p->next)
1227 if(p->status.remove)
1230 if(p->status.dataopen)
1231 if(FD_ISSET(p->socket, f))
1234 The only thing that can happen to get us here is apparently an
1235 error on this outgoing(!) UDP socket that isn't immediate (i.e.
1236 something that will not trigger an error directly on send()).
1237 I've once got here when it said `No route to host'.
1239 getsockopt(p->socket, SOL_SOCKET, SO_ERROR, &x, &l);
1240 syslog(LOG_ERR, _("Outgoing data socket error for %s (%s): %s"),
1241 p->name, p->hostname, strerror(x));
1242 terminate_connection(p);
1247 if(FD_ISSET(p->meta_socket, f))
1248 if(receive_meta(p) < 0)
1250 terminate_connection(p);
1255 if(FD_ISSET(myself->socket, f))
1256 handle_incoming_vpn_data();
1258 if(FD_ISSET(myself->meta_socket, f))
1259 handle_new_meta_connection();
1264 read, encrypt and send data that is
1265 available through the ethertap device
1267 void handle_tap_input(void)
1272 if(taptype == TAP_TYPE_TUNTAP)
1274 if((lenin = read(tap_fd, vp.data, MTU)) <= 0)
1276 syslog(LOG_ERR, _("Error while reading from tun/tap device: %m"));
1283 if((lenin = read(tap_fd, vp.data - 2, MTU)) <= 0)
1285 syslog(LOG_ERR, _("Error while reading from ethertap device: %m"));
1291 total_tap_in += lenin;
1295 if(debug_lvl >= DEBUG_TRAFFIC)
1296 syslog(LOG_WARNING, _("Received short packet from tap device"));
1300 if(debug_lvl >= DEBUG_TRAFFIC)
1302 syslog(LOG_DEBUG, _("Read packet of length %d from tap device"), vp.len);
1305 send_packet(ntohl(*((unsigned long*)(&vp.data[30]))), &vp);
1310 this is where it all happens...
1312 void main_loop(void)
1317 time_t last_ping_check;
1320 last_ping_check = time(NULL);
1324 tv.tv_sec = timeout;
1330 if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1332 if(errno != EINTR) /* because of alarm */
1334 syslog(LOG_ERR, _("Error while waiting for input: %m"));
1341 syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1343 close_network_connections();
1344 clear_config(&config);
1346 if(read_server_config())
1348 syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1354 if(setup_network_connections())
1362 /* Let's check if everybody is still alive */
1364 if(last_ping_check + timeout < t)
1366 check_dead_connections();
1367 last_ping_check = time(NULL);
1369 /* Should we regenerate our key? */
1373 if(debug_lvl >= DEBUG_STATUS)
1374 syslog(LOG_INFO, _("Regenerating symmetric key"));
1376 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
1377 send_key_changed(myself, NULL);
1378 keyexpires = time(NULL) + keylifetime;
1384 check_network_activity(&fset);
1386 /* local tap data */
1387 if(FD_ISSET(tap_fd, &fset))