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.109 2001/05/28 08:21:43 guus Exp $
28 #include <netinet/in.h>
30 #include <netinet/ip.h>
31 #include <netinet/tcp.h>
36 #include <sys/signal.h>
38 #include <sys/types.h>
41 #include <sys/ioctl.h>
42 /* SunOS really wants sys/socket.h BEFORE net/if.h,
43 and FreeBSD wants these lines below the rest. */
44 #include <arpa/inet.h>
45 #include <sys/socket.h>
48 #ifdef HAVE_OPENSSL_RAND_H
49 # include <openssl/rand.h>
54 #ifdef HAVE_OPENSSL_EVP_H
55 # include <openssl/evp.h>
60 #ifdef HAVE_OPENSSL_ERR_H
61 # include <openssl/err.h>
66 #ifdef HAVE_OPENSSL_PEM_H
67 # include <openssl/pem.h>
73 #include LINUX_IF_TUN_H
82 #include "connection.h"
95 int taptype = TAP_TYPE_ETHERTAP;
97 int total_tap_out = 0;
98 int total_socket_in = 0;
99 int total_socket_out = 0;
101 config_t *upstreamcfg;
102 static int seconds_till_retry;
107 char *unknown = NULL;
109 void send_udppacket(connection_t *cl, vpn_packet_t *inpkt)
114 struct sockaddr_in to;
115 socklen_t tolen = sizeof(to);
118 if(!cl->status.validkey)
120 if(debug_lvl >= DEBUG_TRAFFIC)
121 syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
122 cl->name, cl->hostname);
124 /* Since packet is on the stack of handle_tap_input(),
125 we have to make a copy of it first. */
127 copy = xmalloc(sizeof(vpn_packet_t));
128 memcpy(copy, inpkt, sizeof(vpn_packet_t));
130 list_insert_tail(cl->queue, copy);
132 if(!cl->status.waitingforkey)
133 send_req_key(myself, cl);
137 /* Encrypt the packet. */
139 RAND_bytes(inpkt->salt, sizeof(inpkt->salt));
141 EVP_EncryptInit(&ctx, cl->cipher_pkttype, cl->cipher_pktkey, cl->cipher_pktkey + cl->cipher_pkttype->key_len);
142 EVP_EncryptUpdate(&ctx, outpkt.salt, &outlen, inpkt->salt, inpkt->len + sizeof(inpkt->salt));
143 EVP_EncryptFinal(&ctx, outpkt.salt + outlen, &outpad);
146 total_socket_out += outlen;
148 to.sin_family = AF_INET;
149 to.sin_addr.s_addr = htonl(cl->address);
150 to.sin_port = htons(cl->port);
152 if((sendto(myself->socket, (char *) outpkt.salt, outlen, 0, (const struct sockaddr *)&to, tolen)) < 0)
154 syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
155 cl->name, cl->hostname);
161 void receive_packet(connection_t *cl, vpn_packet_t *packet)
164 if(debug_lvl >= DEBUG_TRAFFIC)
165 syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"), packet->len, cl->name, cl->hostname);
167 route_incoming(cl, packet);
171 void receive_udppacket(connection_t *cl, vpn_packet_t *inpkt)
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.salt, &outlen, inpkt->salt, inpkt->len);
181 EVP_DecryptFinal(&ctx, outpkt.salt + outlen, &outpad);
183 outpkt.len = outlen - sizeof(outpkt.salt);
185 receive_packet(cl, &outpkt);
189 void receive_tcppacket(connection_t *cl, char *buffer, int len)
194 memcpy(outpkt.data, buffer, len);
196 receive_packet(cl, &outpkt);
200 void accept_packet(vpn_packet_t *packet)
203 if(debug_lvl >= DEBUG_TRAFFIC)
204 syslog(LOG_DEBUG, _("Writing packet of %d bytes to tap device"),
207 if(taptype == TAP_TYPE_TUNTAP)
209 if(write(tap_fd, packet->data, packet->len) < 0)
210 syslog(LOG_ERR, _("Can't write to tun/tap device: %m"));
212 total_tap_out += packet->len;
216 if(write(tap_fd, packet->data - 2, packet->len + 2) < 0)
217 syslog(LOG_ERR, _("Can't write to ethertap device: %m"));
219 total_tap_out += packet->len;
225 send a packet to the given vpn ip.
227 void send_packet(connection_t *cl, vpn_packet_t *packet)
230 if(debug_lvl >= DEBUG_TRAFFIC)
231 syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
232 packet->len, cl->name, cl->hostname);
236 if(debug_lvl >= DEBUG_TRAFFIC)
238 syslog(LOG_NOTICE, _("Packet is looping back to us!"));
244 if(!cl->status.active)
246 if(debug_lvl >= DEBUG_TRAFFIC)
247 syslog(LOG_INFO, _("%s (%s) is not active, dropping packet"),
248 cl->name, cl->hostname);
253 /* Check if it has to go via TCP or UDP... */
255 if((cl->options | myself->options) & OPTION_TCPONLY)
257 if(send_tcppacket(cl, packet))
258 terminate_connection(cl);
261 send_udppacket(cl, packet);
264 void flush_queue(connection_t *cl)
266 list_node_t *node, *next;
268 if(debug_lvl >= DEBUG_TRAFFIC)
269 syslog(LOG_INFO, _("Flushing queue for %s (%s)"), cl->name, cl->hostname);
271 for(node = cl->queue->head; node; node = next)
274 send_udppacket(cl, (vpn_packet_t *)node->data);
275 list_delete_node(cl->queue, node);
281 open the local ethertap device
283 int setup_tap_fd(void)
286 const char *tapfname;
295 if((cfg = get_config_val(config, config_tapdevice)))
296 tapfname = cfg->data.ptr;
301 tapfname = "/dev/net/tun";
303 tapfname = "/dev/tap0";
307 tapfname = "/dev/tap0";
310 tapfname = "/dev/tun";
314 if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
316 syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
322 taptype = TAP_TYPE_ETHERTAP;
324 /* Set default MAC address for ethertap devices */
326 mymac.type = SUBNET_MAC;
327 mymac.net.mac.address.x[0] = 0xfe;
328 mymac.net.mac.address.x[1] = 0xfd;
329 mymac.net.mac.address.x[2] = 0x00;
330 mymac.net.mac.address.x[3] = 0x00;
331 mymac.net.mac.address.x[4] = 0x00;
332 mymac.net.mac.address.x[5] = 0x00;
336 /* Ok now check if this is an old ethertap or a new tun/tap thingie */
337 memset(&ifr, 0, sizeof(ifr));
339 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
341 strncpy(ifr.ifr_name, netname, IFNAMSIZ);
343 if (!ioctl(tap_fd, TUNSETIFF, (void *) &ifr))
345 syslog(LOG_INFO, _("%s is a new style tun/tap device"), tapfname);
346 taptype = TAP_TYPE_TUNTAP;
351 taptype = TAP_TYPE_TUNTAP;
358 set up the socket that we listen on for incoming
361 int setup_listen_meta_socket(int port)
364 struct sockaddr_in a;
368 if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
370 syslog(LOG_ERR, _("Creating metasocket failed: %m"));
374 flags = fcntl(nfd, F_GETFL);
375 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
378 syslog(LOG_ERR, _("System call `%s' failed: %m"),
383 /* Optimize TCP settings */
386 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
387 setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
389 setsockopt(nfd, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
391 option = IPTOS_LOWDELAY;
392 setsockopt(nfd, SOL_IP, IP_TOS, &option, sizeof(option));
394 if((cfg = get_config_val(config, config_interface)))
396 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, cfg->data.ptr, strlen(cfg->data.ptr)))
399 syslog(LOG_ERR, _("Unable to bind listen socket to interface %s: %m"), cfg->data.ptr);
405 memset(&a, 0, sizeof(a));
406 a.sin_family = AF_INET;
407 a.sin_port = htons(port);
409 if((cfg = get_config_val(config, config_interfaceip)))
410 a.sin_addr.s_addr = htonl(cfg->data.ip->address);
412 a.sin_addr.s_addr = htonl(INADDR_ANY);
414 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
417 syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
424 syslog(LOG_ERR, _("System call `%s' failed: %m"),
433 setup the socket for incoming encrypted
436 int setup_vpn_in_socket(int port)
439 struct sockaddr_in a;
442 if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
445 syslog(LOG_ERR, _("Creating socket failed: %m"));
449 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
451 flags = fcntl(nfd, F_GETFL);
452 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
455 syslog(LOG_ERR, _("System call `%s' failed: %m"),
460 memset(&a, 0, sizeof(a));
461 a.sin_family = AF_INET;
462 a.sin_port = htons(port);
463 a.sin_addr.s_addr = htonl(INADDR_ANY);
465 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
468 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
476 setup an outgoing meta (tcp) socket
478 int setup_outgoing_meta_socket(connection_t *cl)
481 struct sockaddr_in a;
485 if(debug_lvl >= DEBUG_CONNECTIONS)
486 syslog(LOG_INFO, _("Trying to connect to %s"), cl->hostname);
488 if((cfg = get_config_val(cl->config, config_port)) == NULL)
491 cl->port = cfg->data.val;
493 cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
494 if(cl->meta_socket == -1)
496 syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
497 cl->hostname, cl->port);
501 /* Bind first to get a fix on our source port */
503 a.sin_family = AF_INET;
504 a.sin_port = htons(0);
505 a.sin_addr.s_addr = htonl(INADDR_ANY);
507 if(bind(cl->meta_socket, (struct sockaddr *)&a, sizeof(struct sockaddr)))
509 close(cl->meta_socket);
510 syslog(LOG_ERR, _("System call `%s' failed: %m"), "bind");
514 /* Optimize TCP settings */
517 setsockopt(cl->meta_socket, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
519 setsockopt(cl->meta_socket, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
521 option = IPTOS_LOWDELAY;
522 setsockopt(cl->meta_socket, SOL_IP, IP_TOS, &option, sizeof(option));
526 a.sin_family = AF_INET;
527 a.sin_port = htons(cl->port);
528 a.sin_addr.s_addr = htonl(cl->address);
530 if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
532 close(cl->meta_socket);
533 syslog(LOG_ERR, _("%s port %hd: %m"), cl->hostname, cl->port);
537 flags = fcntl(cl->meta_socket, F_GETFL);
538 if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
540 close(cl->meta_socket);
541 syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
542 cl->hostname, cl->port);
546 if(debug_lvl >= DEBUG_CONNECTIONS)
547 syslog(LOG_INFO, _("Connected to %s port %hd"),
548 cl->hostname, cl->port);
556 Setup an outgoing meta connection.
558 int setup_outgoing_connection(char *name)
566 syslog(LOG_ERR, _("Invalid name for outgoing connection"));
570 ncn = new_connection();
571 asprintf(&ncn->name, "%s", name);
573 if(read_host_config(ncn))
575 syslog(LOG_ERR, _("Error reading host configuration file for %s"), ncn->name);
576 free_connection(ncn);
580 if(!(cfg = get_config_val(ncn->config, config_address)))
582 syslog(LOG_ERR, _("No address specified for %s"), ncn->name);
583 free_connection(ncn);
587 if(!(h = gethostbyname(cfg->data.ptr)))
589 syslog(LOG_ERR, _("Error looking up `%s': %m"), cfg->data.ptr);
590 free_connection(ncn);
594 ncn->address = ntohl(*((ipv4_t*)(h->h_addr_list[0])));
595 ncn->hostname = hostlookup(htonl(ncn->address));
597 if(setup_outgoing_meta_socket(ncn) < 0)
599 syslog(LOG_ERR, _("Could not set up a meta connection to %s"),
601 free_connection(ncn);
605 ncn->status.outgoing = 1;
606 ncn->buffer = xmalloc(MAXBUFSIZE);
608 ncn->last_ping_time = time(NULL);
617 int read_rsa_public_key(connection_t *cl)
625 cl->rsa_key = RSA_new();
627 /* First, check for simple PublicKey statement */
629 if((cfg = get_config_val(cl->config, config_publickey)))
631 BN_hex2bn(&cl->rsa_key->n, cfg->data.ptr);
632 BN_hex2bn(&cl->rsa_key->e, "FFFF");
636 /* Else, check for PublicKeyFile statement and read it */
638 if((cfg = get_config_val(cl->config, config_publickeyfile)))
640 if(is_safe_path(cfg->data.ptr))
642 if((fp = fopen(cfg->data.ptr, "r")) == NULL)
644 syslog(LOG_ERR, _("Error reading RSA public key file `%s': %m"),
648 result = PEM_read_RSAPublicKey(fp, &cl->rsa_key, NULL, NULL);
652 syslog(LOG_ERR, _("Reading RSA public key file `%s' failed: %m"),
662 /* Else, check if a harnessed public key is in the config file */
664 asprintf(&fname, "%s/hosts/%s", confbase, cl->name);
665 if((fp = fopen(fname, "r")))
667 result = PEM_read_RSAPublicKey(fp, &cl->rsa_key, NULL, NULL);
676 /* Nothing worked. */
678 syslog(LOG_ERR, _("No public key for %s specified!"), cl->name);
683 int read_rsa_private_key(void)
690 myself->rsa_key = RSA_new();
692 if((cfg = get_config_val(config, config_privatekey)))
694 BN_hex2bn(&myself->rsa_key->d, cfg->data.ptr);
695 BN_hex2bn(&myself->rsa_key->e, "FFFF");
697 else if((cfg = get_config_val(config, config_privatekeyfile)))
699 if((fp = fopen(cfg->data.ptr, "r")) == NULL)
701 syslog(LOG_ERR, _("Error reading RSA private key file `%s': %m"),
705 result = PEM_read_RSAPrivateKey(fp, &myself->rsa_key, NULL, NULL);
709 syslog(LOG_ERR, _("Reading RSA private key file `%s' failed: %m"),
716 syslog(LOG_ERR, _("No private key for tinc daemon specified!"));
724 Configure connection_t myself and set up the local sockets (listen only)
726 int setup_myself(void)
732 myself = new_connection();
734 asprintf(&myself->hostname, "MYSELF");
736 myself->protocol_version = PROT_CURRENT;
738 if(!(cfg = get_config_val(config, config_name))) /* Not acceptable */
740 syslog(LOG_ERR, _("Name for tinc daemon required!"));
744 asprintf(&myself->name, "%s", (char*)cfg->data.val);
746 if(check_id(myself->name))
748 syslog(LOG_ERR, _("Invalid name for myself!"));
752 if(read_rsa_private_key())
755 if(read_host_config(myself))
757 syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
761 if(read_rsa_public_key(myself))
766 if(RSA_check_key(myself->rsa_key) != 1)
768 syslog(LOG_ERR, _("Invalid public/private keypair!"));
772 if(!(cfg = get_config_val(myself->config, config_port)))
775 myself->port = cfg->data.val;
777 if((cfg = get_config_val(myself->config, config_indirectdata)))
778 if(cfg->data.val == stupid_true)
779 myself->options |= OPTION_INDIRECT;
781 if((cfg = get_config_val(myself->config, config_tcponly)))
782 if(cfg->data.val == stupid_true)
783 myself->options |= OPTION_TCPONLY;
785 /* Read in all the subnets specified in the host configuration file */
787 for(next = myself->config; (cfg = get_config_val(next, config_subnet)); next = cfg->next)
790 net->type = SUBNET_IPV4;
791 net->net.ipv4.address = cfg->data.ip->address;
792 net->net.ipv4.mask = cfg->data.ip->mask;
794 /* Teach newbies what subnets are... */
796 if((net->net.ipv4.address & net->net.ipv4.mask) != net->net.ipv4.address)
798 syslog(LOG_ERR, _("Network address and subnet mask do not match!"));
802 subnet_add(myself, net);
805 if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
807 syslog(LOG_ERR, _("Unable to set up a listening TCP socket!"));
811 if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
813 syslog(LOG_ERR, _("Unable to set up a listening UDP socket!"));
817 /* Generate packet encryption key */
819 myself->cipher_pkttype = EVP_bf_cbc();
821 myself->cipher_pktkeylength = myself->cipher_pkttype->key_len + myself->cipher_pkttype->iv_len;
823 myself->cipher_pktkey = (char *)xmalloc(myself->cipher_pktkeylength);
824 RAND_pseudo_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
826 if(!(cfg = get_config_val(config, config_keyexpire)))
829 keylifetime = cfg->data.val;
831 keyexpires = time(NULL) + keylifetime;
833 /* Check some options */
835 if((cfg = get_config_val(config, config_indirectdata)))
837 if(cfg->data.val == stupid_true)
838 myself->options |= OPTION_INDIRECT;
841 if((cfg = get_config_val(config, config_tcponly)))
843 if(cfg->data.val == stupid_true)
844 myself->options |= OPTION_TCPONLY;
847 if(myself->options & OPTION_TCPONLY)
848 myself->options |= OPTION_INDIRECT;
850 /* Activate ourselves */
852 myself->status.active = 1;
854 syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
860 sigalrm_handler(int a)
864 cfg = get_config_val(upstreamcfg, config_connectto);
868 if(upstreamcfg == config)
870 /* No upstream IP given, we're listen only. */
871 signal(SIGALRM, SIG_IGN);
877 /* We previously tried all the ConnectTo lines. Now wrap back to the first. */
878 cfg = get_config_val(config, config_connectto);
883 upstreamcfg = cfg->next;
884 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
886 signal(SIGALRM, SIG_IGN);
889 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
892 signal(SIGALRM, sigalrm_handler);
893 upstreamcfg = config;
894 seconds_till_retry += 5;
895 if(seconds_till_retry > MAXTIMEOUT) /* Don't wait more than MAXTIMEOUT seconds. */
896 seconds_till_retry = MAXTIMEOUT;
897 syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
899 alarm(seconds_till_retry);
904 setup all initial network connections
906 int setup_network_connections(void)
913 if((cfg = get_config_val(config, config_pingtimeout)) == NULL)
917 timeout = cfg->data.val;
924 if(setup_tap_fd() < 0)
927 /* Run tinc-up script to further initialize the tap interface */
928 execute_script("tinc-up");
930 if(setup_myself() < 0)
933 if(!(cfg = get_config_val(config, config_connectto)))
934 /* No upstream IP given, we're listen only. */
939 upstreamcfg = cfg->next;
940 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
942 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
947 signal(SIGALRM, sigalrm_handler);
948 upstreamcfg = config;
949 seconds_till_retry = MAXTIMEOUT;
950 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
951 alarm(seconds_till_retry);
961 close all open network connections
963 void close_network_connections(void)
968 for(node = connection_tree->head; node; node = node->next)
970 p = (connection_t *)node->data;
971 p->status.outgoing = 0;
972 p->status.active = 0;
973 terminate_connection(p);
977 if(myself->status.active)
979 close(myself->meta_socket);
980 free_connection(myself);
986 /* Execute tinc-down script right after shutting down the interface */
987 execute_script("tinc-down");
989 destroy_connection_tree();
995 handle an incoming tcp connect call and open
998 connection_t *create_new_connection(int sfd)
1001 struct sockaddr_in ci;
1002 int len = sizeof(ci);
1004 p = new_connection();
1006 if(getpeername(sfd, (struct sockaddr *) &ci, (socklen_t *) &len) < 0)
1008 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1015 p->address = ntohl(ci.sin_addr.s_addr);
1016 p->hostname = hostlookup(ci.sin_addr.s_addr);
1017 p->port = htons(ci.sin_port); /* This one will be overwritten later */
1018 p->meta_socket = sfd;
1020 p->buffer = xmalloc(MAXBUFSIZE);
1022 p->last_ping_time = time(NULL);
1024 if(debug_lvl >= DEBUG_CONNECTIONS)
1025 syslog(LOG_NOTICE, _("Connection from %s port %d"),
1026 p->hostname, htons(ci.sin_port));
1028 p->allow_request = ID;
1034 put all file descriptors in an fd_set array
1036 void build_fdset(fd_set *fs)
1043 FD_SET(myself->socket, fs);
1045 for(node = connection_tree->head; node; node = node->next)
1047 p = (connection_t *)node->data;
1049 FD_SET(p->meta_socket, fs);
1052 FD_SET(myself->meta_socket, fs);
1058 receive incoming data from the listening
1059 udp socket and write it to the ethertap
1060 device after being decrypted
1062 void handle_incoming_vpn_data(void)
1065 int x, l = sizeof(x);
1066 struct sockaddr_in from;
1067 socklen_t fromlen = sizeof(from);
1070 if(getsockopt(myself->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1072 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1073 __FILE__, __LINE__, myself->socket);
1078 syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1082 if((pkt.len = recvfrom(myself->socket, (char *) pkt.salt, MTU, 0, (struct sockaddr *)&from, &fromlen)) <= 0)
1084 syslog(LOG_ERR, _("Receiving packet failed: %m"));
1088 cl = lookup_connection(ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
1092 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));
1096 cl->last_ping_time = time(NULL);
1098 receive_udppacket(cl, &pkt);
1103 terminate a connection and notify the other
1104 end before closing the sockets
1106 void terminate_connection(connection_t *cl)
1110 avl_node_t *node, *next;
1112 if(cl->status.remove)
1115 if(debug_lvl >= DEBUG_CONNECTIONS)
1116 syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1117 cl->name, cl->hostname);
1119 cl->status.remove = 1;
1124 close(cl->meta_socket);
1129 /* Find all connections that were lost because they were behind cl
1130 (the connection that was dropped). */
1132 for(node = connection_tree->head; node; node = node->next)
1134 p = (connection_t *)node->data;
1135 if(p->nexthop == cl && p != cl)
1136 terminate_connection(p);
1139 /* Inform others of termination if it was still active */
1141 if(cl->status.active)
1142 for(node = connection_tree->head; node; node = node->next)
1144 p = (connection_t *)node->data;
1145 if(p->status.meta && p->status.active && p != cl)
1146 send_del_host(p, cl); /* Sounds like recursion, but p does not have a meta connection :) */
1150 /* Remove the associated subnets */
1152 for(node = cl->subnet_tree->head; node; node = next)
1155 subnet = (subnet_t *)node->data;
1159 /* Check if this was our outgoing connection */
1161 if(cl->status.outgoing)
1163 cl->status.outgoing = 0;
1164 signal(SIGALRM, sigalrm_handler);
1165 seconds_till_retry = 5;
1166 alarm(seconds_till_retry);
1167 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
1172 cl->status.active = 0;
1177 Check if the other end is active.
1178 If we have sent packets, but didn't receive any,
1179 then possibly the other end is dead. We send a
1180 PING request over the meta connection. If the other
1181 end does not reply in time, we consider them dead
1182 and close the connection.
1184 void check_dead_connections(void)
1192 for(node = connection_tree->head; node; node = node->next)
1194 cl = (connection_t *)node->data;
1195 if(cl->status.active && cl->status.meta)
1197 if(cl->last_ping_time + timeout < now)
1199 if(cl->status.pinged)
1201 if(debug_lvl >= DEBUG_PROTOCOL)
1202 syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1203 cl->name, cl->hostname);
1204 cl->status.timeout = 1;
1205 terminate_connection(cl);
1218 accept a new tcp connect and create a
1221 int handle_new_meta_connection()
1224 struct sockaddr client;
1225 int nfd, len = sizeof(client);
1227 if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
1229 syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1233 if(!(ncn = create_new_connection(nfd)))
1237 syslog(LOG_NOTICE, _("Closed attempted connection"));
1241 connection_add(ncn);
1249 check all connections to see if anything
1250 happened on their sockets
1252 void check_network_activity(fd_set *f)
1257 if(FD_ISSET(myself->socket, f))
1258 handle_incoming_vpn_data();
1260 for(node = connection_tree->head; node; node = node->next)
1262 p = (connection_t *)node->data;
1264 if(p->status.remove)
1268 if(FD_ISSET(p->meta_socket, f))
1269 if(receive_meta(p) < 0)
1271 terminate_connection(p);
1276 if(FD_ISSET(myself->meta_socket, f))
1277 handle_new_meta_connection();
1282 read, encrypt and send data that is
1283 available through the ethertap device
1285 void handle_tap_input(void)
1290 if(taptype == TAP_TYPE_TUNTAP)
1292 if((lenin = read(tap_fd, vp.data, MTU)) <= 0)
1294 syslog(LOG_ERR, _("Error while reading from tun/tap device: %m"));
1301 if((lenin = read(tap_fd, vp.data - 2, MTU)) <= 0)
1303 syslog(LOG_ERR, _("Error while reading from ethertap device: %m"));
1309 total_tap_in += vp.len;
1313 if(debug_lvl >= DEBUG_TRAFFIC)
1314 syslog(LOG_WARNING, _("Received short packet from tap device"));
1318 if(debug_lvl >= DEBUG_TRAFFIC)
1320 syslog(LOG_DEBUG, _("Read packet of length %d from tap device"), vp.len);
1323 route_outgoing(&vp);
1328 this is where it all happens...
1330 void main_loop(void)
1335 time_t last_ping_check;
1338 last_ping_check = time(NULL);
1342 tv.tv_sec = timeout;
1345 prune_connection_tree();
1348 if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1350 if(errno != EINTR) /* because of alarm */
1352 syslog(LOG_ERR, _("Error while waiting for input: %m"));
1359 syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1361 close_network_connections();
1362 clear_config(&config);
1364 if(read_server_config())
1366 syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1372 if(setup_network_connections())
1380 /* Let's check if everybody is still alive */
1382 if(last_ping_check + timeout < t)
1384 check_dead_connections();
1385 last_ping_check = time(NULL);
1387 /* Should we regenerate our key? */
1391 if(debug_lvl >= DEBUG_STATUS)
1392 syslog(LOG_INFO, _("Regenerating symmetric key"));
1394 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
1395 send_key_changed(myself, NULL);
1396 keyexpires = time(NULL) + keylifetime;
1402 check_network_activity(&fset);
1404 /* local tap data */
1405 if(FD_ISSET(tap_fd, &fset))