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.108 2001/05/25 11:54:28 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 receive_tcppacket(connection_t *cl, char *buffer, int len)
192 memcpy(outpkt.data, buffer, len);
194 receive_packet(cl, &outpkt);
198 void accept_packet(vpn_packet_t *packet)
201 if(debug_lvl >= DEBUG_TRAFFIC)
202 syslog(LOG_DEBUG, _("Writing packet of %d bytes to tap device"),
205 if(taptype == TAP_TYPE_TUNTAP)
207 if(write(tap_fd, packet->data, packet->len) < 0)
208 syslog(LOG_ERR, _("Can't write to tun/tap device: %m"));
210 total_tap_out += packet->len;
214 if(write(tap_fd, packet->data - 2, packet->len + 2) < 0)
215 syslog(LOG_ERR, _("Can't write to ethertap device: %m"));
217 total_tap_out += packet->len;
223 send a packet to the given vpn ip.
225 void send_packet(connection_t *cl, vpn_packet_t *packet)
228 if(debug_lvl >= DEBUG_TRAFFIC)
229 syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
230 packet->len, cl->name, cl->hostname);
234 if(debug_lvl >= DEBUG_TRAFFIC)
236 syslog(LOG_NOTICE, _("Packet is looping back to us!"));
242 if(!cl->status.active)
244 if(debug_lvl >= DEBUG_TRAFFIC)
245 syslog(LOG_INFO, _("%s (%s) is not active, dropping packet"),
246 cl->name, cl->hostname);
251 /* Check if it has to go via TCP or UDP... */
253 if((cl->options | myself->options) & OPTION_TCPONLY)
255 if(send_tcppacket(cl, packet))
256 terminate_connection(cl);
259 send_udppacket(cl, packet);
262 void flush_queue(connection_t *cl)
264 list_node_t *node, *next;
266 if(debug_lvl >= DEBUG_TRAFFIC)
267 syslog(LOG_INFO, _("Flushing queue for %s (%s)"), cl->name, cl->hostname);
269 for(node = cl->queue->head; node; node = next)
272 send_udppacket(cl, (vpn_packet_t *)node->data);
273 list_delete_node(cl->queue, node);
279 open the local ethertap device
281 int setup_tap_fd(void)
284 const char *tapfname;
293 if((cfg = get_config_val(config, config_tapdevice)))
294 tapfname = cfg->data.ptr;
299 tapfname = "/dev/net/tun";
301 tapfname = "/dev/tap0";
305 tapfname = "/dev/tap0";
308 tapfname = "/dev/tun";
312 if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
314 syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
320 taptype = TAP_TYPE_ETHERTAP;
322 /* Set default MAC address for ethertap devices */
324 mymac.type = SUBNET_MAC;
325 mymac.net.mac.address.x[0] = 0xfe;
326 mymac.net.mac.address.x[1] = 0xfd;
327 mymac.net.mac.address.x[2] = 0x00;
328 mymac.net.mac.address.x[3] = 0x00;
329 mymac.net.mac.address.x[4] = 0x00;
330 mymac.net.mac.address.x[5] = 0x00;
334 /* Ok now check if this is an old ethertap or a new tun/tap thingie */
335 memset(&ifr, 0, sizeof(ifr));
337 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
339 strncpy(ifr.ifr_name, netname, IFNAMSIZ);
341 if (!ioctl(tap_fd, TUNSETIFF, (void *) &ifr))
343 syslog(LOG_INFO, _("%s is a new style tun/tap device"), tapfname);
344 taptype = TAP_TYPE_TUNTAP;
349 taptype = TAP_TYPE_TUNTAP;
356 set up the socket that we listen on for incoming
359 int setup_listen_meta_socket(int port)
362 struct sockaddr_in a;
366 if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
368 syslog(LOG_ERR, _("Creating metasocket failed: %m"));
372 flags = fcntl(nfd, F_GETFL);
373 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
376 syslog(LOG_ERR, _("System call `%s' failed: %m"),
381 /* Optimize TCP settings */
384 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
385 setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
386 setsockopt(nfd, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
388 option = IPTOS_LOWDELAY;
389 setsockopt(nfd, SOL_IP, IP_TOS, &option, sizeof(option));
391 if((cfg = get_config_val(config, config_interface)))
393 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, cfg->data.ptr, strlen(cfg->data.ptr)))
396 syslog(LOG_ERR, _("Unable to bind listen socket to interface %s: %m"), cfg->data.ptr);
401 memset(&a, 0, sizeof(a));
402 a.sin_family = AF_INET;
403 a.sin_port = htons(port);
405 if((cfg = get_config_val(config, config_interfaceip)))
406 a.sin_addr.s_addr = htonl(cfg->data.ip->address);
408 a.sin_addr.s_addr = htonl(INADDR_ANY);
410 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
413 syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
420 syslog(LOG_ERR, _("System call `%s' failed: %m"),
429 setup the socket for incoming encrypted
432 int setup_vpn_in_socket(int port)
435 struct sockaddr_in a;
438 if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
441 syslog(LOG_ERR, _("Creating socket failed: %m"));
445 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
447 flags = fcntl(nfd, F_GETFL);
448 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
451 syslog(LOG_ERR, _("System call `%s' failed: %m"),
456 memset(&a, 0, sizeof(a));
457 a.sin_family = AF_INET;
458 a.sin_port = htons(port);
459 a.sin_addr.s_addr = htonl(INADDR_ANY);
461 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
464 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
472 setup an outgoing meta (tcp) socket
474 int setup_outgoing_meta_socket(connection_t *cl)
477 struct sockaddr_in a;
481 if(debug_lvl >= DEBUG_CONNECTIONS)
482 syslog(LOG_INFO, _("Trying to connect to %s"), cl->hostname);
484 if((cfg = get_config_val(cl->config, config_port)) == NULL)
487 cl->port = cfg->data.val;
489 cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
490 if(cl->meta_socket == -1)
492 syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
493 cl->hostname, cl->port);
497 /* Bind first to get a fix on our source port */
499 a.sin_family = AF_INET;
500 a.sin_port = htons(0);
501 a.sin_addr.s_addr = htonl(INADDR_ANY);
503 if(bind(cl->meta_socket, (struct sockaddr *)&a, sizeof(struct sockaddr)))
505 close(cl->meta_socket);
506 syslog(LOG_ERR, _("System call `%s' failed: %m"), "bind");
510 /* Optimize TCP settings */
513 setsockopt(cl->meta_socket, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
514 setsockopt(cl->meta_socket, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
516 option = IPTOS_LOWDELAY;
517 setsockopt(cl->meta_socket, SOL_IP, IP_TOS, &option, sizeof(option));
521 a.sin_family = AF_INET;
522 a.sin_port = htons(cl->port);
523 a.sin_addr.s_addr = htonl(cl->address);
525 if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
527 close(cl->meta_socket);
528 syslog(LOG_ERR, _("%s port %hd: %m"), cl->hostname, cl->port);
532 flags = fcntl(cl->meta_socket, F_GETFL);
533 if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
535 close(cl->meta_socket);
536 syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
537 cl->hostname, cl->port);
541 if(debug_lvl >= DEBUG_CONNECTIONS)
542 syslog(LOG_INFO, _("Connected to %s port %hd"),
543 cl->hostname, cl->port);
551 Setup an outgoing meta connection.
553 int setup_outgoing_connection(char *name)
561 syslog(LOG_ERR, _("Invalid name for outgoing connection"));
565 ncn = new_connection();
566 asprintf(&ncn->name, "%s", name);
568 if(read_host_config(ncn))
570 syslog(LOG_ERR, _("Error reading host configuration file for %s"), ncn->name);
571 free_connection(ncn);
575 if(!(cfg = get_config_val(ncn->config, config_address)))
577 syslog(LOG_ERR, _("No address specified for %s"), ncn->name);
578 free_connection(ncn);
582 if(!(h = gethostbyname(cfg->data.ptr)))
584 syslog(LOG_ERR, _("Error looking up `%s': %m"), cfg->data.ptr);
585 free_connection(ncn);
589 ncn->address = ntohl(*((ipv4_t*)(h->h_addr_list[0])));
590 ncn->hostname = hostlookup(htonl(ncn->address));
592 if(setup_outgoing_meta_socket(ncn) < 0)
594 syslog(LOG_ERR, _("Could not set up a meta connection to %s"),
596 free_connection(ncn);
600 ncn->status.outgoing = 1;
601 ncn->buffer = xmalloc(MAXBUFSIZE);
603 ncn->last_ping_time = time(NULL);
612 int read_rsa_public_key(connection_t *cl)
620 cl->rsa_key = RSA_new();
622 /* First, check for simple PublicKey statement */
624 if((cfg = get_config_val(cl->config, config_publickey)))
626 BN_hex2bn(&cl->rsa_key->n, cfg->data.ptr);
627 BN_hex2bn(&cl->rsa_key->e, "FFFF");
631 /* Else, check for PublicKeyFile statement and read it */
633 if((cfg = get_config_val(cl->config, config_publickeyfile)))
635 if(is_safe_path(cfg->data.ptr))
637 if((fp = fopen(cfg->data.ptr, "r")) == NULL)
639 syslog(LOG_ERR, _("Error reading RSA public key file `%s': %m"),
643 result = PEM_read_RSAPublicKey(fp, &cl->rsa_key, NULL, NULL);
647 syslog(LOG_ERR, _("Reading RSA public key file `%s' failed: %m"),
657 /* Else, check if a harnessed public key is in the config file */
659 asprintf(&fname, "%s/hosts/%s", confbase, cl->name);
660 if((fp = fopen(fname, "r")))
662 result = PEM_read_RSAPublicKey(fp, &cl->rsa_key, NULL, NULL);
671 /* Nothing worked. */
673 syslog(LOG_ERR, _("No public key for %s specified!"), cl->name);
678 int read_rsa_private_key(void)
685 myself->rsa_key = RSA_new();
687 if((cfg = get_config_val(config, config_privatekey)))
689 BN_hex2bn(&myself->rsa_key->d, cfg->data.ptr);
690 BN_hex2bn(&myself->rsa_key->e, "FFFF");
692 else if((cfg = get_config_val(config, config_privatekeyfile)))
694 if((fp = fopen(cfg->data.ptr, "r")) == NULL)
696 syslog(LOG_ERR, _("Error reading RSA private key file `%s': %m"),
700 result = PEM_read_RSAPrivateKey(fp, &myself->rsa_key, NULL, NULL);
704 syslog(LOG_ERR, _("Reading RSA private key file `%s' failed: %m"),
711 syslog(LOG_ERR, _("No private key for tinc daemon specified!"));
719 Configure connection_t myself and set up the local sockets (listen only)
721 int setup_myself(void)
727 myself = new_connection();
729 asprintf(&myself->hostname, "MYSELF");
731 myself->protocol_version = PROT_CURRENT;
733 if(!(cfg = get_config_val(config, config_name))) /* Not acceptable */
735 syslog(LOG_ERR, _("Name for tinc daemon required!"));
739 asprintf(&myself->name, "%s", (char*)cfg->data.val);
741 if(check_id(myself->name))
743 syslog(LOG_ERR, _("Invalid name for myself!"));
747 if(read_rsa_private_key())
750 if(read_host_config(myself))
752 syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
756 if(read_rsa_public_key(myself))
761 if(RSA_check_key(myself->rsa_key) != 1)
763 syslog(LOG_ERR, _("Invalid public/private keypair!"));
767 if(!(cfg = get_config_val(myself->config, config_port)))
770 myself->port = cfg->data.val;
772 if((cfg = get_config_val(myself->config, config_indirectdata)))
773 if(cfg->data.val == stupid_true)
774 myself->options |= OPTION_INDIRECT;
776 if((cfg = get_config_val(myself->config, config_tcponly)))
777 if(cfg->data.val == stupid_true)
778 myself->options |= OPTION_TCPONLY;
780 /* Read in all the subnets specified in the host configuration file */
782 for(next = myself->config; (cfg = get_config_val(next, config_subnet)); next = cfg->next)
785 net->type = SUBNET_IPV4;
786 net->net.ipv4.address = cfg->data.ip->address;
787 net->net.ipv4.mask = cfg->data.ip->mask;
789 /* Teach newbies what subnets are... */
791 if((net->net.ipv4.address & net->net.ipv4.mask) != net->net.ipv4.address)
793 syslog(LOG_ERR, _("Network address and subnet mask do not match!"));
797 subnet_add(myself, net);
800 if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
802 syslog(LOG_ERR, _("Unable to set up a listening TCP socket!"));
806 if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
808 syslog(LOG_ERR, _("Unable to set up a listening UDP socket!"));
812 /* Generate packet encryption key */
814 myself->cipher_pkttype = EVP_bf_cbc();
816 myself->cipher_pktkeylength = myself->cipher_pkttype->key_len + myself->cipher_pkttype->iv_len;
818 myself->cipher_pktkey = (char *)xmalloc(myself->cipher_pktkeylength);
819 RAND_pseudo_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
821 if(!(cfg = get_config_val(config, config_keyexpire)))
824 keylifetime = cfg->data.val;
826 keyexpires = time(NULL) + keylifetime;
828 /* Check some options */
830 if((cfg = get_config_val(config, config_indirectdata)))
832 if(cfg->data.val == stupid_true)
833 myself->options |= OPTION_INDIRECT;
836 if((cfg = get_config_val(config, config_tcponly)))
838 if(cfg->data.val == stupid_true)
839 myself->options |= OPTION_TCPONLY;
842 if(myself->options & OPTION_TCPONLY)
843 myself->options |= OPTION_INDIRECT;
845 /* Activate ourselves */
847 myself->status.active = 1;
849 syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
855 sigalrm_handler(int a)
859 cfg = get_config_val(upstreamcfg, config_connectto);
863 if(upstreamcfg == config)
865 /* No upstream IP given, we're listen only. */
866 signal(SIGALRM, SIG_IGN);
872 /* We previously tried all the ConnectTo lines. Now wrap back to the first. */
873 cfg = get_config_val(config, config_connectto);
878 upstreamcfg = cfg->next;
879 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
881 signal(SIGALRM, SIG_IGN);
884 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
887 signal(SIGALRM, sigalrm_handler);
888 upstreamcfg = config;
889 seconds_till_retry += 5;
890 if(seconds_till_retry > MAXTIMEOUT) /* Don't wait more than MAXTIMEOUT seconds. */
891 seconds_till_retry = MAXTIMEOUT;
892 syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
894 alarm(seconds_till_retry);
899 setup all initial network connections
901 int setup_network_connections(void)
908 if((cfg = get_config_val(config, config_pingtimeout)) == NULL)
912 timeout = cfg->data.val;
919 if(setup_tap_fd() < 0)
922 /* Run tinc-up script to further initialize the tap interface */
923 execute_script("tinc-up");
925 if(setup_myself() < 0)
928 if(!(cfg = get_config_val(config, config_connectto)))
929 /* No upstream IP given, we're listen only. */
934 upstreamcfg = cfg->next;
935 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
937 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
942 signal(SIGALRM, sigalrm_handler);
943 upstreamcfg = config;
944 seconds_till_retry = MAXTIMEOUT;
945 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
946 alarm(seconds_till_retry);
956 close all open network connections
958 void close_network_connections(void)
963 for(node = connection_tree->head; node; node = node->next)
965 p = (connection_t *)node->data;
966 p->status.outgoing = 0;
967 p->status.active = 0;
968 terminate_connection(p);
972 if(myself->status.active)
974 close(myself->meta_socket);
975 free_connection(myself);
981 /* Execute tinc-down script right after shutting down the interface */
982 execute_script("tinc-down");
984 destroy_connection_tree();
990 handle an incoming tcp connect call and open
993 connection_t *create_new_connection(int sfd)
996 struct sockaddr_in ci;
997 int len = sizeof(ci);
999 p = new_connection();
1001 if(getpeername(sfd, (struct sockaddr *) &ci, (socklen_t *) &len) < 0)
1003 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1010 p->address = ntohl(ci.sin_addr.s_addr);
1011 p->hostname = hostlookup(ci.sin_addr.s_addr);
1012 p->port = htons(ci.sin_port); /* This one will be overwritten later */
1013 p->meta_socket = sfd;
1015 p->buffer = xmalloc(MAXBUFSIZE);
1017 p->last_ping_time = time(NULL);
1019 if(debug_lvl >= DEBUG_CONNECTIONS)
1020 syslog(LOG_NOTICE, _("Connection from %s port %d"),
1021 p->hostname, htons(ci.sin_port));
1023 p->allow_request = ID;
1029 put all file descriptors in an fd_set array
1031 void build_fdset(fd_set *fs)
1038 FD_SET(myself->socket, fs);
1040 for(node = connection_tree->head; node; node = node->next)
1042 p = (connection_t *)node->data;
1044 FD_SET(p->meta_socket, fs);
1047 FD_SET(myself->meta_socket, fs);
1053 receive incoming data from the listening
1054 udp socket and write it to the ethertap
1055 device after being decrypted
1057 void handle_incoming_vpn_data(void)
1060 int x, l = sizeof(x);
1061 struct sockaddr_in from;
1062 socklen_t fromlen = sizeof(from);
1065 if(getsockopt(myself->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1067 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1068 __FILE__, __LINE__, myself->socket);
1073 syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1077 if((pkt.len = recvfrom(myself->socket, (char *) pkt.salt, MTU, 0, (struct sockaddr *)&from, &fromlen)) <= 0)
1079 syslog(LOG_ERR, _("Receiving packet failed: %m"));
1083 cl = lookup_connection(ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
1087 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));
1091 cl->last_ping_time = time(NULL);
1093 receive_udppacket(cl, &pkt);
1098 terminate a connection and notify the other
1099 end before closing the sockets
1101 void terminate_connection(connection_t *cl)
1105 avl_node_t *node, *next;
1107 if(cl->status.remove)
1110 if(debug_lvl >= DEBUG_CONNECTIONS)
1111 syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1112 cl->name, cl->hostname);
1114 cl->status.remove = 1;
1119 close(cl->meta_socket);
1124 /* Find all connections that were lost because they were behind cl
1125 (the connection that was dropped). */
1127 for(node = connection_tree->head; node; node = node->next)
1129 p = (connection_t *)node->data;
1130 if(p->nexthop == cl && p != cl)
1131 terminate_connection(p);
1134 /* Inform others of termination if it was still active */
1136 if(cl->status.active)
1137 for(node = connection_tree->head; node; node = node->next)
1139 p = (connection_t *)node->data;
1140 if(p->status.meta && p->status.active && p != cl)
1141 send_del_host(p, cl); /* Sounds like recursion, but p does not have a meta connection :) */
1145 /* Remove the associated subnets */
1147 for(node = cl->subnet_tree->head; node; node = next)
1150 subnet = (subnet_t *)node->data;
1154 /* Check if this was our outgoing connection */
1156 if(cl->status.outgoing)
1158 cl->status.outgoing = 0;
1159 signal(SIGALRM, sigalrm_handler);
1160 seconds_till_retry = 5;
1161 alarm(seconds_till_retry);
1162 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
1167 cl->status.active = 0;
1172 Check if the other end is active.
1173 If we have sent packets, but didn't receive any,
1174 then possibly the other end is dead. We send a
1175 PING request over the meta connection. If the other
1176 end does not reply in time, we consider them dead
1177 and close the connection.
1179 void check_dead_connections(void)
1187 for(node = connection_tree->head; node; node = node->next)
1189 cl = (connection_t *)node->data;
1190 if(cl->status.active && cl->status.meta)
1192 if(cl->last_ping_time + timeout < now)
1194 if(cl->status.pinged)
1196 if(debug_lvl >= DEBUG_PROTOCOL)
1197 syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1198 cl->name, cl->hostname);
1199 cl->status.timeout = 1;
1200 terminate_connection(cl);
1213 accept a new tcp connect and create a
1216 int handle_new_meta_connection()
1219 struct sockaddr client;
1220 int nfd, len = sizeof(client);
1222 if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
1224 syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1228 if(!(ncn = create_new_connection(nfd)))
1232 syslog(LOG_NOTICE, _("Closed attempted connection"));
1236 connection_add(ncn);
1244 check all connections to see if anything
1245 happened on their sockets
1247 void check_network_activity(fd_set *f)
1252 if(FD_ISSET(myself->socket, f))
1253 handle_incoming_vpn_data();
1255 for(node = connection_tree->head; node; node = node->next)
1257 p = (connection_t *)node->data;
1259 if(p->status.remove)
1263 if(FD_ISSET(p->meta_socket, f))
1264 if(receive_meta(p) < 0)
1266 terminate_connection(p);
1271 if(FD_ISSET(myself->meta_socket, f))
1272 handle_new_meta_connection();
1277 read, encrypt and send data that is
1278 available through the ethertap device
1280 void handle_tap_input(void)
1285 if(taptype == TAP_TYPE_TUNTAP)
1287 if((lenin = read(tap_fd, vp.data, MTU)) <= 0)
1289 syslog(LOG_ERR, _("Error while reading from tun/tap device: %m"));
1296 if((lenin = read(tap_fd, vp.data - 2, MTU)) <= 0)
1298 syslog(LOG_ERR, _("Error while reading from ethertap device: %m"));
1304 total_tap_in += vp.len;
1308 if(debug_lvl >= DEBUG_TRAFFIC)
1309 syslog(LOG_WARNING, _("Received short packet from tap device"));
1313 if(debug_lvl >= DEBUG_TRAFFIC)
1315 syslog(LOG_DEBUG, _("Read packet of length %d from tap device"), vp.len);
1318 route_outgoing(&vp);
1323 this is where it all happens...
1325 void main_loop(void)
1330 time_t last_ping_check;
1333 last_ping_check = time(NULL);
1337 tv.tv_sec = timeout;
1340 prune_connection_tree();
1343 if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1345 if(errno != EINTR) /* because of alarm */
1347 syslog(LOG_ERR, _("Error while waiting for input: %m"));
1354 syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1356 close_network_connections();
1357 clear_config(&config);
1359 if(read_server_config())
1361 syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1367 if(setup_network_connections())
1375 /* Let's check if everybody is still alive */
1377 if(last_ping_check + timeout < t)
1379 check_dead_connections();
1380 last_ping_check = time(NULL);
1382 /* Should we regenerate our key? */
1386 if(debug_lvl >= DEBUG_STATUS)
1387 syslog(LOG_INFO, _("Regenerating symmetric key"));
1389 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
1390 send_key_changed(myself, NULL);
1391 keyexpires = time(NULL) + keylifetime;
1397 check_network_activity(&fset);
1399 /* local tap data */
1400 if(FD_ISSET(tap_fd, &fset))