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.105 2001/05/07 19:08:43 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 RAND_bytes(inpkt->salt, sizeof(inpkt->salt));
139 EVP_EncryptInit(&ctx, cl->cipher_pkttype, cl->cipher_pktkey, cl->cipher_pktkey + cl->cipher_pkttype->key_len);
140 EVP_EncryptUpdate(&ctx, outpkt.salt, &outlen, inpkt->salt, inpkt->len + sizeof(inpkt->salt));
141 EVP_EncryptFinal(&ctx, outpkt.salt + outlen, &outpad);
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.salt, 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 /* Decrypt the packet */
177 EVP_DecryptInit(&ctx, myself->cipher_pkttype, myself->cipher_pktkey, myself->cipher_pktkey + myself->cipher_pkttype->key_len);
178 EVP_DecryptUpdate(&ctx, outpkt.salt, &outlen, inpkt->salt, inpkt->len);
179 EVP_DecryptFinal(&ctx, outpkt.salt + outlen, &outpad);
181 outpkt.len = outlen - sizeof(outpkt.salt);
183 receive_packet(cl, &outpkt);
187 void accept_packet(vpn_packet_t *packet)
190 if(debug_lvl >= DEBUG_TRAFFIC)
191 syslog(LOG_DEBUG, _("Writing packet of %d bytes to tap device"),
194 if(taptype == TAP_TYPE_TUNTAP)
196 if(write(tap_fd, packet->data, packet->len) < 0)
197 syslog(LOG_ERR, _("Can't write to tun/tap device: %m"));
199 total_tap_out += packet->len;
203 if(write(tap_fd, packet->data - 2, packet->len + 2) < 0)
204 syslog(LOG_ERR, _("Can't write to ethertap device: %m"));
206 total_tap_out += packet->len + 2;
212 send a packet to the given vpn ip.
214 void send_packet(connection_t *cl, vpn_packet_t *packet)
217 if(debug_lvl >= DEBUG_TRAFFIC)
218 syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
219 packet->len, cl->name, cl->hostname);
223 if(debug_lvl >= DEBUG_TRAFFIC)
225 syslog(LOG_NOTICE, _("Packet is looping back to us!"));
231 if(!cl->status.active)
233 if(debug_lvl >= DEBUG_TRAFFIC)
234 syslog(LOG_INFO, _("%s (%s) is not active, dropping packet"),
235 cl->name, cl->hostname);
240 /* Check if it has to go via TCP or UDP... */
242 if((cl->options | myself->options) & OPTION_TCPONLY)
244 if(send_tcppacket(cl, packet))
245 terminate_connection(cl);
248 send_udppacket(cl, packet);
251 void flush_queue(connection_t *cl)
253 list_node_t *node, *next;
255 if(debug_lvl >= DEBUG_TRAFFIC)
256 syslog(LOG_INFO, _("Flushing queue for %s (%s)"), cl->name, cl->hostname);
258 for(node = cl->queue->head; node; node = next)
261 send_udppacket(cl, (vpn_packet_t *)node->data);
262 list_delete_node(cl->queue, node);
268 open the local ethertap device
270 int setup_tap_fd(void)
273 const char *tapfname;
282 if((cfg = get_config_val(config, config_tapdevice)))
283 tapfname = cfg->data.ptr;
288 tapfname = "/dev/misc/net/tun";
290 tapfname = "/dev/tap0";
294 tapfname = "/dev/tap0";
297 tapfname = "/dev/tun";
301 if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
303 syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
309 taptype = TAP_TYPE_ETHERTAP;
311 /* Set default MAC address for ethertap devices */
313 mymac.type = SUBNET_MAC;
314 mymac.net.mac.address.x[0] = 0xfe;
315 mymac.net.mac.address.x[1] = 0xfd;
316 mymac.net.mac.address.x[2] = 0x00;
317 mymac.net.mac.address.x[3] = 0x00;
318 mymac.net.mac.address.x[4] = 0x00;
319 mymac.net.mac.address.x[5] = 0x00;
323 /* Ok now check if this is an old ethertap or a new tun/tap thingie */
324 memset(&ifr, 0, sizeof(ifr));
326 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
328 strncpy(ifr.ifr_name, netname, IFNAMSIZ);
330 if (!ioctl(tap_fd, TUNSETIFF, (void *) &ifr))
332 syslog(LOG_INFO, _("%s is a new style tun/tap device"), tapfname);
333 taptype = TAP_TYPE_TUNTAP;
338 taptype = TAP_TYPE_TUNTAP;
345 set up the socket that we listen on for incoming
348 int setup_listen_meta_socket(int port)
351 struct sockaddr_in a;
355 if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
357 syslog(LOG_ERR, _("Creating metasocket failed: %m"));
361 flags = fcntl(nfd, F_GETFL);
362 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
365 syslog(LOG_ERR, _("System call `%s' failed: %m"),
370 /* Optimize TCP settings */
373 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
374 setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
375 setsockopt(nfd, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
377 option = IPTOS_LOWDELAY;
378 setsockopt(nfd, SOL_IP, IP_TOS, &option, sizeof(option));
380 if((cfg = get_config_val(config, config_interface)))
382 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, cfg->data.ptr, strlen(cfg->data.ptr)))
385 syslog(LOG_ERR, _("Unable to bind listen socket to interface %s: %m"), cfg->data.ptr);
390 memset(&a, 0, sizeof(a));
391 a.sin_family = AF_INET;
392 a.sin_port = htons(port);
394 if((cfg = get_config_val(config, config_interfaceip)))
395 a.sin_addr.s_addr = htonl(cfg->data.ip->address);
397 a.sin_addr.s_addr = htonl(INADDR_ANY);
399 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
402 syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
409 syslog(LOG_ERR, _("System call `%s' failed: %m"),
418 setup the socket for incoming encrypted
421 int setup_vpn_in_socket(int port)
424 struct sockaddr_in a;
427 if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
430 syslog(LOG_ERR, _("Creating socket failed: %m"));
434 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
436 flags = fcntl(nfd, F_GETFL);
437 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
440 syslog(LOG_ERR, _("System call `%s' failed: %m"),
445 memset(&a, 0, sizeof(a));
446 a.sin_family = AF_INET;
447 a.sin_port = htons(port);
448 a.sin_addr.s_addr = htonl(INADDR_ANY);
450 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
453 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
461 setup an outgoing meta (tcp) socket
463 int setup_outgoing_meta_socket(connection_t *cl)
466 struct sockaddr_in a;
470 if(debug_lvl >= DEBUG_CONNECTIONS)
471 syslog(LOG_INFO, _("Trying to connect to %s"), cl->hostname);
473 if((cfg = get_config_val(cl->config, config_port)) == NULL)
476 cl->port = cfg->data.val;
478 cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
479 if(cl->meta_socket == -1)
481 syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
482 cl->hostname, cl->port);
486 /* Bind first to get a fix on our source port */
488 a.sin_family = AF_INET;
489 a.sin_port = htons(0);
490 a.sin_addr.s_addr = htonl(INADDR_ANY);
492 if(bind(cl->meta_socket, (struct sockaddr *)&a, sizeof(struct sockaddr)))
494 close(cl->meta_socket);
495 syslog(LOG_ERR, _("System call `%s' failed: %m"), "bind");
499 /* Optimize TCP settings */
502 setsockopt(cl->meta_socket, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
503 setsockopt(cl->meta_socket, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
505 option = IPTOS_LOWDELAY;
506 setsockopt(cl->meta_socket, SOL_IP, IP_TOS, &option, sizeof(option));
510 a.sin_family = AF_INET;
511 a.sin_port = htons(cl->port);
512 a.sin_addr.s_addr = htonl(cl->address);
514 if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
516 close(cl->meta_socket);
517 syslog(LOG_ERR, _("%s port %hd: %m"), cl->hostname, cl->port);
521 flags = fcntl(cl->meta_socket, F_GETFL);
522 if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
524 close(cl->meta_socket);
525 syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
526 cl->hostname, cl->port);
530 if(debug_lvl >= DEBUG_CONNECTIONS)
531 syslog(LOG_INFO, _("Connected to %s port %hd"),
532 cl->hostname, cl->port);
540 Setup an outgoing meta connection.
542 int setup_outgoing_connection(char *name)
550 syslog(LOG_ERR, _("Invalid name for outgoing connection"));
554 ncn = new_connection();
555 asprintf(&ncn->name, "%s", name);
557 if(read_host_config(ncn))
559 syslog(LOG_ERR, _("Error reading host configuration file for %s"), ncn->name);
560 free_connection(ncn);
564 if(!(cfg = get_config_val(ncn->config, config_address)))
566 syslog(LOG_ERR, _("No address specified for %s"), ncn->name);
567 free_connection(ncn);
571 if(!(h = gethostbyname(cfg->data.ptr)))
573 syslog(LOG_ERR, _("Error looking up `%s': %m"), cfg->data.ptr);
574 free_connection(ncn);
578 ncn->address = ntohl(*((ipv4_t*)(h->h_addr_list[0])));
579 ncn->hostname = hostlookup(htonl(ncn->address));
581 if(setup_outgoing_meta_socket(ncn) < 0)
583 syslog(LOG_ERR, _("Could not set up a meta connection to %s"),
585 free_connection(ncn);
589 ncn->status.outgoing = 1;
590 ncn->buffer = xmalloc(MAXBUFSIZE);
592 ncn->last_ping_time = time(NULL);
601 int read_rsa_public_key(connection_t *cl)
609 cl->rsa_key = RSA_new();
611 /* First, check for simple PublicKey statement */
613 if((cfg = get_config_val(cl->config, config_publickey)))
615 BN_hex2bn(&cl->rsa_key->n, cfg->data.ptr);
616 BN_hex2bn(&cl->rsa_key->e, "FFFF");
620 /* Else, check for PublicKeyFile statement and read it */
622 if((cfg = get_config_val(cl->config, config_publickeyfile)))
624 if(is_safe_path(cfg->data.ptr))
626 if((fp = fopen(cfg->data.ptr, "r")) == NULL)
628 syslog(LOG_ERR, _("Error reading RSA public key file `%s': %m"),
632 result = PEM_read_RSAPublicKey(fp, &cl->rsa_key, NULL, NULL);
636 syslog(LOG_ERR, _("Reading RSA public key file `%s' failed: %m"),
646 /* Else, check if a harnessed public key is in the config file */
648 asprintf(&fname, "%s/hosts/%s", confbase, cl->name);
649 if((fp = fopen(fname, "r")))
651 result = PEM_read_RSAPublicKey(fp, &cl->rsa_key, NULL, NULL);
660 /* Nothing worked. */
662 syslog(LOG_ERR, _("No public key for %s specified!"), cl->name);
667 int read_rsa_private_key(void)
674 myself->rsa_key = RSA_new();
676 if((cfg = get_config_val(config, config_privatekey)))
678 BN_hex2bn(&myself->rsa_key->d, cfg->data.ptr);
679 BN_hex2bn(&myself->rsa_key->e, "FFFF");
681 else if((cfg = get_config_val(config, config_privatekeyfile)))
683 if((fp = fopen(cfg->data.ptr, "r")) == NULL)
685 syslog(LOG_ERR, _("Error reading RSA private key file `%s': %m"),
689 result = PEM_read_RSAPrivateKey(fp, &myself->rsa_key, NULL, NULL);
693 syslog(LOG_ERR, _("Reading RSA private key file `%s' failed: %m"),
700 syslog(LOG_ERR, _("No private key for tinc daemon specified!"));
708 Configure connection_t myself and set up the local sockets (listen only)
710 int setup_myself(void)
716 myself = new_connection();
718 asprintf(&myself->hostname, "MYSELF");
720 myself->protocol_version = PROT_CURRENT;
722 if(!(cfg = get_config_val(config, config_name))) /* Not acceptable */
724 syslog(LOG_ERR, _("Name for tinc daemon required!"));
728 asprintf(&myself->name, "%s", (char*)cfg->data.val);
730 if(check_id(myself->name))
732 syslog(LOG_ERR, _("Invalid name for myself!"));
736 if(read_rsa_private_key())
739 if(read_host_config(myself))
741 syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
745 if(read_rsa_public_key(myself))
750 if(RSA_check_key(myself->rsa_key) != 1)
752 syslog(LOG_ERR, _("Invalid public/private keypair!"));
756 if(!(cfg = get_config_val(myself->config, config_port)))
759 myself->port = cfg->data.val;
761 if((cfg = get_config_val(myself->config, config_indirectdata)))
762 if(cfg->data.val == stupid_true)
763 myself->options |= OPTION_INDIRECT;
765 if((cfg = get_config_val(myself->config, config_tcponly)))
766 if(cfg->data.val == stupid_true)
767 myself->options |= OPTION_TCPONLY;
769 /* Read in all the subnets specified in the host configuration file */
771 for(next = myself->config; (cfg = get_config_val(next, config_subnet)); next = cfg->next)
774 net->type = SUBNET_IPV4;
775 net->net.ipv4.address = cfg->data.ip->address;
776 net->net.ipv4.mask = cfg->data.ip->mask;
778 /* Teach newbies what subnets are... */
780 if((net->net.ipv4.address & net->net.ipv4.mask) != net->net.ipv4.address)
782 syslog(LOG_ERR, _("Network address and subnet mask do not match!"));
786 subnet_add(myself, net);
789 if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
791 syslog(LOG_ERR, _("Unable to set up a listening TCP socket!"));
795 if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
797 syslog(LOG_ERR, _("Unable to set up a listening UDP socket!"));
801 /* Generate packet encryption key */
803 myself->cipher_pkttype = EVP_bf_cbc();
805 myself->cipher_pktkeylength = myself->cipher_pkttype->key_len + myself->cipher_pkttype->iv_len;
807 myself->cipher_pktkey = (char *)xmalloc(myself->cipher_pktkeylength);
808 RAND_pseudo_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
810 if(!(cfg = get_config_val(config, config_keyexpire)))
813 keylifetime = cfg->data.val;
815 keyexpires = time(NULL) + keylifetime;
817 /* Check some options */
819 if((cfg = get_config_val(config, config_indirectdata)))
821 if(cfg->data.val == stupid_true)
822 myself->options |= OPTION_INDIRECT;
825 if((cfg = get_config_val(config, config_tcponly)))
827 if(cfg->data.val == stupid_true)
828 myself->options |= OPTION_TCPONLY;
831 if(myself->options & OPTION_TCPONLY)
832 myself->options |= OPTION_INDIRECT;
834 /* Activate ourselves */
836 myself->status.active = 1;
838 syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
844 sigalrm_handler(int a)
848 cfg = get_config_val(upstreamcfg, config_connectto);
851 if(upstreamcfg == config)
853 /* No upstream IP given, we're listen only. */
854 signal(SIGALRM, SIG_IGN);
859 /* We previously tried all the ConnectTo lines. Now wrap back to the first. */
860 cfg = get_config_val(config, config_connectto);
865 upstreamcfg = cfg->next;
866 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
868 signal(SIGALRM, SIG_IGN);
871 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
874 signal(SIGALRM, sigalrm_handler);
875 upstreamcfg = config;
876 seconds_till_retry += 5;
877 if(seconds_till_retry > MAXTIMEOUT) /* Don't wait more than MAXTIMEOUT seconds. */
878 seconds_till_retry = MAXTIMEOUT;
879 syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
881 alarm(seconds_till_retry);
886 setup all initial network connections
888 int setup_network_connections(void)
895 if((cfg = get_config_val(config, config_pingtimeout)) == NULL)
899 timeout = cfg->data.val;
906 if(setup_tap_fd() < 0)
909 /* Run tinc-up script to further initialize the tap interface */
910 execute_script("tinc-up");
912 if(setup_myself() < 0)
915 if(!(cfg = get_config_val(config, config_connectto)))
916 /* No upstream IP given, we're listen only. */
921 upstreamcfg = cfg->next;
922 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
924 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
929 signal(SIGALRM, sigalrm_handler);
930 upstreamcfg = config;
931 seconds_till_retry = MAXTIMEOUT;
932 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
933 alarm(seconds_till_retry);
943 close all open network connections
945 void close_network_connections(void)
950 for(node = connection_tree->head; node; node = node->next)
952 p = (connection_t *)node->data;
953 p->status.outgoing = 0;
954 p->status.active = 0;
955 terminate_connection(p);
959 if(myself->status.active)
961 close(myself->meta_socket);
962 free_connection(myself);
968 /* Execute tinc-down script right after shutting down the interface */
969 execute_script("tinc-down");
971 destroy_connection_tree();
977 handle an incoming tcp connect call and open
980 connection_t *create_new_connection(int sfd)
983 struct sockaddr_in ci;
984 int len = sizeof(ci);
986 p = new_connection();
988 if(getpeername(sfd, (struct sockaddr *) &ci, (socklen_t *) &len) < 0)
990 syslog(LOG_ERR, _("System call `%s' failed: %m"),
997 p->address = ntohl(ci.sin_addr.s_addr);
998 p->hostname = hostlookup(ci.sin_addr.s_addr);
999 p->port = htons(ci.sin_port); /* This one will be overwritten later */
1000 p->meta_socket = sfd;
1002 p->buffer = xmalloc(MAXBUFSIZE);
1004 p->last_ping_time = time(NULL);
1006 if(debug_lvl >= DEBUG_CONNECTIONS)
1007 syslog(LOG_NOTICE, _("Connection from %s port %d"),
1008 p->hostname, htons(ci.sin_port));
1010 p->allow_request = ID;
1016 put all file descriptors in an fd_set array
1018 void build_fdset(fd_set *fs)
1025 FD_SET(myself->socket, fs);
1027 for(node = connection_tree->head; node; node = node->next)
1029 p = (connection_t *)node->data;
1031 FD_SET(p->meta_socket, fs);
1034 FD_SET(myself->meta_socket, fs);
1040 receive incoming data from the listening
1041 udp socket and write it to the ethertap
1042 device after being decrypted
1044 void handle_incoming_vpn_data(void)
1047 int x, l = sizeof(x);
1048 struct sockaddr_in from;
1049 socklen_t fromlen = sizeof(from);
1052 if(getsockopt(myself->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1054 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1055 __FILE__, __LINE__, myself->socket);
1060 syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1064 if((pkt.len = recvfrom(myself->socket, (char *) pkt.salt, MTU, 0, (struct sockaddr *)&from, &fromlen)) <= 0)
1066 syslog(LOG_ERR, _("Receiving packet failed: %m"));
1070 cl = lookup_connection(ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
1074 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));
1078 receive_udppacket(cl, &pkt);
1083 terminate a connection and notify the other
1084 end before closing the sockets
1086 void terminate_connection(connection_t *cl)
1090 avl_node_t *node, *next;
1092 if(cl->status.remove)
1095 if(debug_lvl >= DEBUG_CONNECTIONS)
1096 syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1097 cl->name, cl->hostname);
1099 cl->status.remove = 1;
1104 close(cl->meta_socket);
1109 /* Find all connections that were lost because they were behind cl
1110 (the connection that was dropped). */
1112 for(node = connection_tree->head; node; node = node->next)
1114 p = (connection_t *)node->data;
1115 if(p->nexthop == cl && p != cl)
1116 terminate_connection(p);
1119 /* Inform others of termination if it was still active */
1121 if(cl->status.active)
1122 for(node = connection_tree->head; node; node = node->next)
1124 p = (connection_t *)node->data;
1125 if(p->status.meta && p->status.active && p != cl)
1126 send_del_host(p, cl); /* Sounds like recursion, but p does not have a meta connection :) */
1130 /* Remove the associated subnets */
1132 for(node = cl->subnet_tree->head; node; node = next)
1135 subnet = (subnet_t *)node->data;
1139 /* Check if this was our outgoing connection */
1141 if(cl->status.outgoing)
1143 cl->status.outgoing = 0;
1144 signal(SIGALRM, sigalrm_handler);
1145 seconds_till_retry = 5;
1146 alarm(seconds_till_retry);
1147 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
1152 cl->status.active = 0;
1157 Check if the other end is active.
1158 If we have sent packets, but didn't receive any,
1159 then possibly the other end is dead. We send a
1160 PING request over the meta connection. If the other
1161 end does not reply in time, we consider them dead
1162 and close the connection.
1164 void check_dead_connections(void)
1172 for(node = connection_tree->head; node; node = node->next)
1174 cl = (connection_t *)node->data;
1175 if(cl->status.active && cl->status.meta)
1177 if(cl->last_ping_time + timeout < now)
1179 if(cl->status.pinged)
1181 if(debug_lvl >= DEBUG_PROTOCOL)
1182 syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1183 cl->name, cl->hostname);
1184 cl->status.timeout = 1;
1185 terminate_connection(cl);
1198 accept a new tcp connect and create a
1201 int handle_new_meta_connection()
1204 struct sockaddr client;
1205 int nfd, len = sizeof(client);
1207 if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
1209 syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1213 if(!(ncn = create_new_connection(nfd)))
1217 syslog(LOG_NOTICE, _("Closed attempted connection"));
1221 connection_add(ncn);
1229 check all connections to see if anything
1230 happened on their sockets
1232 void check_network_activity(fd_set *f)
1237 if(FD_ISSET(myself->socket, f))
1238 handle_incoming_vpn_data();
1240 for(node = connection_tree->head; node; node = node->next)
1242 p = (connection_t *)node->data;
1244 if(p->status.remove)
1248 if(FD_ISSET(p->meta_socket, f))
1249 if(receive_meta(p) < 0)
1251 terminate_connection(p);
1256 if(FD_ISSET(myself->meta_socket, f))
1257 handle_new_meta_connection();
1262 read, encrypt and send data that is
1263 available through the ethertap device
1265 void handle_tap_input(void)
1270 if(taptype == TAP_TYPE_TUNTAP)
1272 if((lenin = read(tap_fd, vp.data, MTU)) <= 0)
1274 syslog(LOG_ERR, _("Error while reading from tun/tap device: %m"));
1281 if((lenin = read(tap_fd, vp.data - 2, MTU)) <= 0)
1283 syslog(LOG_ERR, _("Error while reading from ethertap device: %m"));
1289 total_tap_in += lenin;
1293 if(debug_lvl >= DEBUG_TRAFFIC)
1294 syslog(LOG_WARNING, _("Received short packet from tap device"));
1298 if(debug_lvl >= DEBUG_TRAFFIC)
1300 syslog(LOG_DEBUG, _("Read packet of length %d from tap device"), vp.len);
1303 route_outgoing(&vp);
1308 this is where it all happens...
1310 void main_loop(void)
1315 time_t last_ping_check;
1318 last_ping_check = time(NULL);
1322 tv.tv_sec = timeout;
1325 prune_connection_tree();
1328 if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1330 if(errno != EINTR) /* because of alarm */
1332 syslog(LOG_ERR, _("Error while waiting for input: %m"));
1339 syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1341 close_network_connections();
1342 clear_config(&config);
1344 if(read_server_config())
1346 syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1352 if(setup_network_connections())
1360 /* Let's check if everybody is still alive */
1362 if(last_ping_check + timeout < t)
1364 check_dead_connections();
1365 last_ping_check = time(NULL);
1367 /* Should we regenerate our key? */
1371 if(debug_lvl >= DEBUG_STATUS)
1372 syslog(LOG_INFO, _("Regenerating symmetric key"));
1374 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
1375 send_key_changed(myself, NULL);
1376 keyexpires = time(NULL) + keylifetime;
1382 check_network_activity(&fset);
1384 /* local tap data */
1385 if(FD_ISSET(tap_fd, &fset))