2 net.c -- most of the network code
3 Copyright (C) 1998-2001 Ivo Timmermans <itimmermans@bigfoot.com>,
4 2000,2001 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.104 2001/05/04 18:45:02 guus Exp $
28 #include <netinet/in.h>
29 #include <netinet/ip.h>
30 #include <netinet/tcp.h>
34 #include <sys/signal.h>
36 #include <sys/types.h>
39 #include <sys/ioctl.h>
40 /* SunOS really wants sys/socket.h BEFORE net/if.h,
41 and FreeBSD wants these lines below the rest. */
42 #include <arpa/inet.h>
43 #include <sys/socket.h>
46 #ifdef HAVE_OPENSSL_RAND_H
47 # include <openssl/rand.h>
52 #ifdef HAVE_OPENSSL_EVP_H
53 # include <openssl/evp.h>
58 #ifdef HAVE_OPENSSL_ERR_H
59 # include <openssl/err.h>
64 #ifdef HAVE_OPENSSL_PEM_H
65 # include <openssl/pem.h>
71 #include LINUX_IF_TUN_H
80 #include "connection.h"
93 int taptype = TAP_TYPE_ETHERTAP;
95 int total_tap_out = 0;
96 int total_socket_in = 0;
97 int total_socket_out = 0;
99 config_t *upstreamcfg;
100 static int seconds_till_retry;
105 char *unknown = NULL;
107 void send_udppacket(connection_t *cl, vpn_packet_t *inpkt)
112 struct sockaddr_in to;
113 socklen_t tolen = sizeof(to);
116 if(!cl->status.validkey)
118 if(debug_lvl >= DEBUG_TRAFFIC)
119 syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
120 cl->name, cl->hostname);
122 /* Since packet is on the stack of handle_tap_input(),
123 we have to make a copy of it first. */
125 copy = xmalloc(sizeof(vpn_packet_t));
126 memcpy(copy, inpkt, sizeof(vpn_packet_t));
128 list_insert_tail(cl->queue, copy);
130 if(!cl->status.waitingforkey)
131 send_req_key(myself, cl);
135 /* Encrypt the packet. */
137 outpkt.len = inpkt->len;
139 EVP_EncryptInit(&ctx, cl->cipher_pkttype, cl->cipher_pktkey, cl->cipher_pktkey + cl->cipher_pkttype->key_len);
140 EVP_EncryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len);
141 EVP_EncryptFinal(&ctx, outpkt.data + outlen, &outpad);
142 outlen += outpad + 2;
144 total_socket_out += outlen;
146 to.sin_family = AF_INET;
147 to.sin_addr.s_addr = htonl(cl->address);
148 to.sin_port = htons(cl->port);
150 if((sendto(myself->socket, (char *) &(outpkt.len), outlen, 0, (const struct sockaddr *)&to, tolen)) < 0)
152 syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
153 cl->name, cl->hostname);
159 void receive_packet(connection_t *cl, vpn_packet_t *packet)
162 if(debug_lvl >= DEBUG_TRAFFIC)
163 syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"), packet->len, cl->name, cl->hostname);
165 route_incoming(cl, packet);
169 void receive_udppacket(connection_t *cl, vpn_packet_t *inpkt)
175 outpkt.len = inpkt->len;
177 /* Decrypt the packet */
179 EVP_DecryptInit(&ctx, myself->cipher_pkttype, myself->cipher_pktkey, myself->cipher_pktkey + myself->cipher_pkttype->key_len);
180 EVP_DecryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len + 8);
181 EVP_DecryptFinal(&ctx, outpkt.data + outlen, &outpad);
184 receive_packet(cl, &outpkt);
188 void accept_packet(vpn_packet_t *packet)
191 if(debug_lvl >= DEBUG_TRAFFIC)
192 syslog(LOG_DEBUG, _("Writing packet of %d bytes to tap device"),
195 if(taptype == TAP_TYPE_TUNTAP)
197 if(write(tap_fd, packet->data, packet->len) < 0)
198 syslog(LOG_ERR, _("Can't write to tun/tap device: %m"));
200 total_tap_out += packet->len;
204 if(write(tap_fd, packet->data - 2, packet->len + 2) < 0)
205 syslog(LOG_ERR, _("Can't write to ethertap device: %m"));
207 total_tap_out += packet->len + 2;
213 send a packet to the given vpn ip.
215 void send_packet(connection_t *cl, vpn_packet_t *packet)
218 if(debug_lvl >= DEBUG_TRAFFIC)
219 syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
220 packet->len, cl->name, cl->hostname);
224 if(debug_lvl >= DEBUG_TRAFFIC)
226 syslog(LOG_NOTICE, _("Packet is looping back to us!"));
232 if(!cl->status.active)
234 if(debug_lvl >= DEBUG_TRAFFIC)
235 syslog(LOG_INFO, _("%s (%s) is not active, dropping packet"),
236 cl->name, cl->hostname);
241 /* Check if it has to go via TCP or UDP... */
243 if((cl->options | myself->options) & OPTION_TCPONLY)
245 if(send_tcppacket(cl, packet))
246 terminate_connection(cl);
249 send_udppacket(cl, packet);
252 void flush_queue(connection_t *cl)
254 list_node_t *node, *next;
256 if(debug_lvl >= DEBUG_TRAFFIC)
257 syslog(LOG_INFO, _("Flushing queue for %s (%s)"), cl->name, cl->hostname);
259 for(node = cl->queue->head; node; node = next)
262 send_udppacket(cl, (vpn_packet_t *)node->data);
263 list_delete_node(cl->queue, node);
269 open the local ethertap device
271 int setup_tap_fd(void)
274 const char *tapfname;
283 if((cfg = get_config_val(config, config_tapdevice)))
284 tapfname = cfg->data.ptr;
289 tapfname = "/dev/misc/net/tun";
291 tapfname = "/dev/tap0";
295 tapfname = "/dev/tap0";
298 tapfname = "/dev/tun";
302 if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
304 syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
310 taptype = TAP_TYPE_ETHERTAP;
312 /* Set default MAC address for ethertap devices */
314 mymac.type = SUBNET_MAC;
315 mymac.net.mac.address.x[0] = 0xfe;
316 mymac.net.mac.address.x[1] = 0xfd;
317 mymac.net.mac.address.x[2] = 0x00;
318 mymac.net.mac.address.x[3] = 0x00;
319 mymac.net.mac.address.x[4] = 0x00;
320 mymac.net.mac.address.x[5] = 0x00;
324 /* Ok now check if this is an old ethertap or a new tun/tap thingie */
325 memset(&ifr, 0, sizeof(ifr));
327 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
329 strncpy(ifr.ifr_name, netname, IFNAMSIZ);
331 if (!ioctl(tap_fd, TUNSETIFF, (void *) &ifr))
333 syslog(LOG_INFO, _("%s is a new style tun/tap device"), tapfname);
334 taptype = TAP_TYPE_TUNTAP;
339 taptype = TAP_TYPE_TUNTAP;
346 set up the socket that we listen on for incoming
349 int setup_listen_meta_socket(int port)
352 struct sockaddr_in a;
356 if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
358 syslog(LOG_ERR, _("Creating metasocket failed: %m"));
362 flags = fcntl(nfd, F_GETFL);
363 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
366 syslog(LOG_ERR, _("System call `%s' failed: %m"),
371 /* Optimize TCP settings */
374 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
375 setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
376 setsockopt(nfd, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
378 option = IPTOS_LOWDELAY;
379 setsockopt(nfd, SOL_IP, IP_TOS, &option, sizeof(option));
381 if((cfg = get_config_val(config, config_interface)))
383 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, cfg->data.ptr, strlen(cfg->data.ptr)))
386 syslog(LOG_ERR, _("Unable to bind listen socket to interface %s: %m"), cfg->data.ptr);
391 memset(&a, 0, sizeof(a));
392 a.sin_family = AF_INET;
393 a.sin_port = htons(port);
395 if((cfg = get_config_val(config, config_interfaceip)))
396 a.sin_addr.s_addr = htonl(cfg->data.ip->address);
398 a.sin_addr.s_addr = htonl(INADDR_ANY);
400 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
403 syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
410 syslog(LOG_ERR, _("System call `%s' failed: %m"),
419 setup the socket for incoming encrypted
422 int setup_vpn_in_socket(int port)
425 struct sockaddr_in a;
428 if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
431 syslog(LOG_ERR, _("Creating socket failed: %m"));
435 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
437 flags = fcntl(nfd, F_GETFL);
438 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
441 syslog(LOG_ERR, _("System call `%s' failed: %m"),
446 memset(&a, 0, sizeof(a));
447 a.sin_family = AF_INET;
448 a.sin_port = htons(port);
449 a.sin_addr.s_addr = htonl(INADDR_ANY);
451 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
454 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
462 setup an outgoing meta (tcp) socket
464 int setup_outgoing_meta_socket(connection_t *cl)
467 struct sockaddr_in a;
471 if(debug_lvl >= DEBUG_CONNECTIONS)
472 syslog(LOG_INFO, _("Trying to connect to %s"), cl->hostname);
474 if((cfg = get_config_val(cl->config, config_port)) == NULL)
477 cl->port = cfg->data.val;
479 cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
480 if(cl->meta_socket == -1)
482 syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
483 cl->hostname, cl->port);
487 /* Bind first to get a fix on our source port */
489 a.sin_family = AF_INET;
490 a.sin_port = htons(0);
491 a.sin_addr.s_addr = htonl(INADDR_ANY);
493 if(bind(cl->meta_socket, (struct sockaddr *)&a, sizeof(struct sockaddr)))
495 close(cl->meta_socket);
496 syslog(LOG_ERR, _("System call `%s' failed: %m"), "bind");
500 /* Optimize TCP settings */
503 setsockopt(cl->meta_socket, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
504 setsockopt(cl->meta_socket, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
506 option = IPTOS_LOWDELAY;
507 setsockopt(cl->meta_socket, SOL_IP, IP_TOS, &option, sizeof(option));
511 a.sin_family = AF_INET;
512 a.sin_port = htons(cl->port);
513 a.sin_addr.s_addr = htonl(cl->address);
515 if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
517 close(cl->meta_socket);
518 syslog(LOG_ERR, _("%s port %hd: %m"), cl->hostname, cl->port);
522 flags = fcntl(cl->meta_socket, F_GETFL);
523 if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
525 close(cl->meta_socket);
526 syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
527 cl->hostname, cl->port);
531 if(debug_lvl >= DEBUG_CONNECTIONS)
532 syslog(LOG_INFO, _("Connected to %s port %hd"),
533 cl->hostname, cl->port);
541 Setup an outgoing meta connection.
543 int setup_outgoing_connection(char *name)
551 syslog(LOG_ERR, _("Invalid name for outgoing connection"));
555 ncn = new_connection();
556 asprintf(&ncn->name, "%s", name);
558 if(read_host_config(ncn))
560 syslog(LOG_ERR, _("Error reading host configuration file for %s"), ncn->name);
561 free_connection(ncn);
565 if(!(cfg = get_config_val(ncn->config, config_address)))
567 syslog(LOG_ERR, _("No address specified for %s"), ncn->name);
568 free_connection(ncn);
572 if(!(h = gethostbyname(cfg->data.ptr)))
574 syslog(LOG_ERR, _("Error looking up `%s': %m"), cfg->data.ptr);
575 free_connection(ncn);
579 ncn->address = ntohl(*((ip_t*)(h->h_addr_list[0])));
580 ncn->hostname = hostlookup(htonl(ncn->address));
582 if(setup_outgoing_meta_socket(ncn) < 0)
584 syslog(LOG_ERR, _("Could not set up a meta connection to %s"),
586 free_connection(ncn);
590 ncn->status.outgoing = 1;
591 ncn->buffer = xmalloc(MAXBUFSIZE);
593 ncn->last_ping_time = time(NULL);
602 int read_rsa_public_key(connection_t *cl)
610 cl->rsa_key = RSA_new();
612 /* First, check for simple PublicKey statement */
614 if((cfg = get_config_val(cl->config, config_publickey)))
616 BN_hex2bn(&cl->rsa_key->n, cfg->data.ptr);
617 BN_hex2bn(&cl->rsa_key->e, "FFFF");
621 /* Else, check for PublicKeyFile statement and read it */
623 if((cfg = get_config_val(cl->config, config_publickeyfile)))
625 if(is_safe_path(cfg->data.ptr))
627 if((fp = fopen(cfg->data.ptr, "r")) == NULL)
629 syslog(LOG_ERR, _("Error reading RSA public key file `%s': %m"),
633 result = PEM_read_RSAPublicKey(fp, &cl->rsa_key, NULL, NULL);
637 syslog(LOG_ERR, _("Reading RSA public key file `%s' failed: %m"),
647 /* Else, check if a harnessed public key is in the config file */
649 asprintf(&fname, "%s/hosts/%s", confbase, cl->name);
650 if((fp = fopen(fname, "r")))
652 result = PEM_read_RSAPublicKey(fp, &cl->rsa_key, NULL, NULL);
661 /* Nothing worked. */
663 syslog(LOG_ERR, _("No public key for %s specified!"), cl->name);
668 int read_rsa_private_key(void)
675 myself->rsa_key = RSA_new();
677 if((cfg = get_config_val(config, config_privatekey)))
679 BN_hex2bn(&myself->rsa_key->d, cfg->data.ptr);
680 BN_hex2bn(&myself->rsa_key->e, "FFFF");
682 else if((cfg = get_config_val(config, config_privatekeyfile)))
684 if((fp = fopen(cfg->data.ptr, "r")) == NULL)
686 syslog(LOG_ERR, _("Error reading RSA private key file `%s': %m"),
690 result = PEM_read_RSAPrivateKey(fp, &myself->rsa_key, NULL, NULL);
694 syslog(LOG_ERR, _("Reading RSA private key file `%s' failed: %m"),
701 syslog(LOG_ERR, _("No private key for tinc daemon specified!"));
709 Configure connection_t myself and set up the local sockets (listen only)
711 int setup_myself(void)
717 myself = new_connection();
719 asprintf(&myself->hostname, "MYSELF");
721 myself->protocol_version = PROT_CURRENT;
723 if(!(cfg = get_config_val(config, config_name))) /* Not acceptable */
725 syslog(LOG_ERR, _("Name for tinc daemon required!"));
729 asprintf(&myself->name, "%s", (char*)cfg->data.val);
731 if(check_id(myself->name))
733 syslog(LOG_ERR, _("Invalid name for myself!"));
737 if(read_rsa_private_key())
740 if(read_host_config(myself))
742 syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
746 if(read_rsa_public_key(myself))
751 if(RSA_check_key(myself->rsa_key) != 1)
753 syslog(LOG_ERR, _("Invalid public/private keypair!"));
757 if(!(cfg = get_config_val(myself->config, config_port)))
760 myself->port = cfg->data.val;
762 if((cfg = get_config_val(myself->config, config_indirectdata)))
763 if(cfg->data.val == stupid_true)
764 myself->options |= OPTION_INDIRECT;
766 if((cfg = get_config_val(myself->config, config_tcponly)))
767 if(cfg->data.val == stupid_true)
768 myself->options |= OPTION_TCPONLY;
770 /* Read in all the subnets specified in the host configuration file */
772 for(next = myself->config; (cfg = get_config_val(next, config_subnet)); next = cfg->next)
775 net->type = SUBNET_IPV4;
776 net->net.ipv4.address = cfg->data.ip->address;
777 net->net.ipv4.mask = cfg->data.ip->mask;
779 /* Teach newbies what subnets are... */
781 if((net->net.ipv4.address & net->net.ipv4.mask) != net->net.ipv4.address)
783 syslog(LOG_ERR, _("Network address and subnet mask do not match!"));
787 subnet_add(myself, net);
790 if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
792 syslog(LOG_ERR, _("Unable to set up a listening TCP socket!"));
796 if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
798 syslog(LOG_ERR, _("Unable to set up a listening UDP socket!"));
802 /* Generate packet encryption key */
804 myself->cipher_pkttype = EVP_bf_cbc();
806 myself->cipher_pktkeylength = myself->cipher_pkttype->key_len + myself->cipher_pkttype->iv_len;
808 myself->cipher_pktkey = (char *)xmalloc(myself->cipher_pktkeylength);
809 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
811 if(!(cfg = get_config_val(config, config_keyexpire)))
814 keylifetime = cfg->data.val;
816 keyexpires = time(NULL) + keylifetime;
818 /* Check some options */
820 if((cfg = get_config_val(config, config_indirectdata)))
822 if(cfg->data.val == stupid_true)
823 myself->options |= OPTION_INDIRECT;
826 if((cfg = get_config_val(config, config_tcponly)))
828 if(cfg->data.val == stupid_true)
829 myself->options |= OPTION_TCPONLY;
832 if(myself->options & OPTION_TCPONLY)
833 myself->options |= OPTION_INDIRECT;
835 /* Activate ourselves */
837 myself->status.active = 1;
839 syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
845 sigalrm_handler(int a)
849 cfg = get_config_val(upstreamcfg, config_connectto);
852 if(upstreamcfg == config)
854 /* No upstream IP given, we're listen only. */
855 signal(SIGALRM, SIG_IGN);
860 /* We previously tried all the ConnectTo lines. Now wrap back to the first. */
861 cfg = get_config_val(config, config_connectto);
866 upstreamcfg = cfg->next;
867 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
869 signal(SIGALRM, SIG_IGN);
872 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
875 signal(SIGALRM, sigalrm_handler);
876 upstreamcfg = config;
877 seconds_till_retry += 5;
878 if(seconds_till_retry > MAXTIMEOUT) /* Don't wait more than MAXTIMEOUT seconds. */
879 seconds_till_retry = MAXTIMEOUT;
880 syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
882 alarm(seconds_till_retry);
887 setup all initial network connections
889 int setup_network_connections(void)
896 if((cfg = get_config_val(config, config_pingtimeout)) == NULL)
900 timeout = cfg->data.val;
907 if(setup_tap_fd() < 0)
910 /* Run tinc-up script to further initialize the tap interface */
911 execute_script("tinc-up");
913 if(setup_myself() < 0)
916 if(!(cfg = get_config_val(config, config_connectto)))
917 /* No upstream IP given, we're listen only. */
922 upstreamcfg = cfg->next;
923 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
925 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
930 signal(SIGALRM, sigalrm_handler);
931 upstreamcfg = config;
932 seconds_till_retry = MAXTIMEOUT;
933 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
934 alarm(seconds_till_retry);
944 close all open network connections
946 void close_network_connections(void)
951 for(node = connection_tree->head; node; node = node->next)
953 p = (connection_t *)node->data;
954 p->status.outgoing = 0;
955 p->status.active = 0;
956 terminate_connection(p);
960 if(myself->status.active)
962 close(myself->meta_socket);
963 free_connection(myself);
969 /* Execute tinc-down script right after shutting down the interface */
970 execute_script("tinc-down");
972 destroy_connection_tree();
978 handle an incoming tcp connect call and open
981 connection_t *create_new_connection(int sfd)
984 struct sockaddr_in ci;
985 int len = sizeof(ci);
987 p = new_connection();
989 if(getpeername(sfd, (struct sockaddr *) &ci, (socklen_t *) &len) < 0)
991 syslog(LOG_ERR, _("System call `%s' failed: %m"),
998 p->address = ntohl(ci.sin_addr.s_addr);
999 p->hostname = hostlookup(ci.sin_addr.s_addr);
1000 p->port = htons(ci.sin_port); /* This one will be overwritten later */
1001 p->meta_socket = sfd;
1003 p->buffer = xmalloc(MAXBUFSIZE);
1005 p->last_ping_time = time(NULL);
1007 if(debug_lvl >= DEBUG_CONNECTIONS)
1008 syslog(LOG_NOTICE, _("Connection from %s port %d"),
1009 p->hostname, htons(ci.sin_port));
1011 p->allow_request = ID;
1017 put all file descriptors in an fd_set array
1019 void build_fdset(fd_set *fs)
1026 FD_SET(myself->socket, fs);
1028 for(node = connection_tree->head; node; node = node->next)
1030 p = (connection_t *)node->data;
1032 FD_SET(p->meta_socket, fs);
1035 FD_SET(myself->meta_socket, fs);
1041 receive incoming data from the listening
1042 udp socket and write it to the ethertap
1043 device after being decrypted
1045 void handle_incoming_vpn_data(void)
1048 int x, l = sizeof(x);
1050 struct sockaddr_in from;
1051 socklen_t fromlen = sizeof(from);
1054 if(getsockopt(myself->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1056 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1057 __FILE__, __LINE__, myself->socket);
1062 syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1066 if((lenin = recvfrom(myself->socket, (char *) &(pkt.len), MTU, 0, (struct sockaddr *)&from, &fromlen)) <= 0)
1068 syslog(LOG_ERR, _("Receiving packet failed: %m"));
1072 cl = lookup_connection(ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
1076 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));
1080 receive_udppacket(cl, &pkt);
1085 terminate a connection and notify the other
1086 end before closing the sockets
1088 void terminate_connection(connection_t *cl)
1092 avl_node_t *node, *next;
1094 if(cl->status.remove)
1097 if(debug_lvl >= DEBUG_CONNECTIONS)
1098 syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1099 cl->name, cl->hostname);
1101 cl->status.remove = 1;
1106 close(cl->meta_socket);
1111 /* Find all connections that were lost because they were behind cl
1112 (the connection that was dropped). */
1114 for(node = connection_tree->head; node; node = node->next)
1116 p = (connection_t *)node->data;
1117 if(p->nexthop == cl && p != cl)
1118 terminate_connection(p);
1121 /* Inform others of termination if it was still active */
1123 if(cl->status.active)
1124 for(node = connection_tree->head; node; node = node->next)
1126 p = (connection_t *)node->data;
1127 if(p->status.meta && p->status.active && p != cl)
1128 send_del_host(p, cl); /* Sounds like recursion, but p does not have a meta connection :) */
1132 /* Remove the associated subnets */
1134 for(node = cl->subnet_tree->head; node; node = next)
1137 subnet = (subnet_t *)node->data;
1141 /* Check if this was our outgoing connection */
1143 if(cl->status.outgoing)
1145 cl->status.outgoing = 0;
1146 signal(SIGALRM, sigalrm_handler);
1147 seconds_till_retry = 5;
1148 alarm(seconds_till_retry);
1149 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
1154 cl->status.active = 0;
1159 Check if the other end is active.
1160 If we have sent packets, but didn't receive any,
1161 then possibly the other end is dead. We send a
1162 PING request over the meta connection. If the other
1163 end does not reply in time, we consider them dead
1164 and close the connection.
1166 void check_dead_connections(void)
1174 for(node = connection_tree->head; node; node = node->next)
1176 cl = (connection_t *)node->data;
1177 if(cl->status.active && cl->status.meta)
1179 if(cl->last_ping_time + timeout < now)
1181 if(cl->status.pinged)
1183 if(debug_lvl >= DEBUG_PROTOCOL)
1184 syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1185 cl->name, cl->hostname);
1186 cl->status.timeout = 1;
1187 terminate_connection(cl);
1200 accept a new tcp connect and create a
1203 int handle_new_meta_connection()
1206 struct sockaddr client;
1207 int nfd, len = sizeof(client);
1209 if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
1211 syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1215 if(!(ncn = create_new_connection(nfd)))
1219 syslog(LOG_NOTICE, _("Closed attempted connection"));
1223 connection_add(ncn);
1231 check all connections to see if anything
1232 happened on their sockets
1234 void check_network_activity(fd_set *f)
1239 if(FD_ISSET(myself->socket, f))
1240 handle_incoming_vpn_data();
1242 for(node = connection_tree->head; node; node = node->next)
1244 p = (connection_t *)node->data;
1246 if(p->status.remove)
1250 if(FD_ISSET(p->meta_socket, f))
1251 if(receive_meta(p) < 0)
1253 terminate_connection(p);
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 route_outgoing(&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;
1327 prune_connection_tree();
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))