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.126 2001/07/21 20:21:25 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 #include <openssl/rand.h>
49 #include <openssl/evp.h>
50 #include <openssl/pem.h>
52 #ifndef HAVE_RAND_PSEUDO_BYTES
53 #define RAND_pseudo_bytes RAND_bytes
59 #include LINUX_IF_TUN_H
61 #include <linux/if_tun.h>
64 #include <net/if_tun.h>
69 #include <sys/sockio.h>
70 #include <sys/stropts.h>
71 #include <net/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 int seconds_till_retry = 5;
105 void send_udppacket(connection_t *cl, vpn_packet_t *inpkt)
110 struct sockaddr_in to;
111 socklen_t tolen = sizeof(to);
114 if(!cl->status.validkey)
116 if(debug_lvl >= DEBUG_TRAFFIC)
117 syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
118 cl->name, cl->hostname);
120 /* Since packet is on the stack of handle_tap_input(),
121 we have to make a copy of it first. */
123 copy = xmalloc(sizeof(vpn_packet_t));
124 memcpy(copy, inpkt, sizeof(vpn_packet_t));
126 list_insert_tail(cl->queue, copy);
128 if(!cl->status.waitingforkey)
129 send_req_key(myself, cl);
133 /* Encrypt the packet. */
135 RAND_pseudo_bytes(inpkt->salt, sizeof(inpkt->salt));
137 EVP_EncryptInit(&ctx, cl->cipher_pkttype, cl->cipher_pktkey, cl->cipher_pktkey + cl->cipher_pkttype->key_len);
138 EVP_EncryptUpdate(&ctx, outpkt.salt, &outlen, inpkt->salt, inpkt->len + sizeof(inpkt->salt));
139 EVP_EncryptFinal(&ctx, outpkt.salt + outlen, &outpad);
142 total_socket_out += outlen;
144 to.sin_family = AF_INET;
145 to.sin_addr.s_addr = htonl(cl->address);
146 to.sin_port = htons(cl->port);
148 if((sendto(myself->socket, (char *) outpkt.salt, outlen, 0, (const struct sockaddr *)&to, tolen)) < 0)
150 syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
151 cl->name, cl->hostname);
157 void receive_packet(connection_t *cl, vpn_packet_t *packet)
160 if(debug_lvl >= DEBUG_TRAFFIC)
161 syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"), packet->len, cl->name, cl->hostname);
163 route_incoming(cl, packet);
167 void receive_udppacket(connection_t *cl, vpn_packet_t *inpkt)
173 /* Decrypt the packet */
175 EVP_DecryptInit(&ctx, myself->cipher_pkttype, myself->cipher_pktkey, myself->cipher_pktkey + myself->cipher_pkttype->key_len);
176 EVP_DecryptUpdate(&ctx, outpkt.salt, &outlen, inpkt->salt, inpkt->len);
177 EVP_DecryptFinal(&ctx, outpkt.salt + outlen, &outpad);
179 outpkt.len = outlen - sizeof(outpkt.salt);
181 total_socket_in += outlen;
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"),
206 if(write(tap_fd, packet->data + 14, packet->len - 14) < 0)
207 syslog(LOG_ERR, _("Can't write to tun device: %m"));
209 total_tap_out += packet->len;
211 if(taptype == TAP_TYPE_TUNTAP)
213 if(write(tap_fd, packet->data, packet->len) < 0)
214 syslog(LOG_ERR, _("Can't write to tun/tap device: %m"));
216 total_tap_out += packet->len;
220 if(write(tap_fd, packet->data - 2, packet->len + 2) < 0)
221 syslog(LOG_ERR, _("Can't write to ethertap device: %m"));
223 total_tap_out += packet->len;
230 send a packet to the given vpn ip.
232 void send_packet(connection_t *cl, vpn_packet_t *packet)
235 if(debug_lvl >= DEBUG_TRAFFIC)
236 syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
237 packet->len, cl->name, cl->hostname);
241 if(debug_lvl >= DEBUG_TRAFFIC)
243 syslog(LOG_NOTICE, _("Packet is looping back to us!"));
249 if(!cl->status.active)
251 if(debug_lvl >= DEBUG_TRAFFIC)
252 syslog(LOG_INFO, _("%s (%s) is not active, dropping packet"),
253 cl->name, cl->hostname);
258 /* Check if it has to go via TCP or UDP... */
260 if((cl->options | myself->options) & OPTION_TCPONLY)
262 if(send_tcppacket(cl, packet))
263 terminate_connection(cl, 1);
266 send_udppacket(cl, packet);
269 /* Broadcast a packet to all active direct connections */
271 void broadcast_packet(connection_t *from, vpn_packet_t *packet)
276 if(debug_lvl >= DEBUG_TRAFFIC)
277 syslog(LOG_INFO, _("Broadcasting packet of %d bytes from %s (%s)"),
278 packet->len, from->name, from->hostname);
280 for(node = connection_tree->head; node; node = node->next)
282 cl = (connection_t *)node->data;
283 if(cl->status.active && cl != from)
284 send_packet(cl, packet);
289 void flush_queue(connection_t *cl)
291 list_node_t *node, *next;
293 if(debug_lvl >= DEBUG_TRAFFIC)
294 syslog(LOG_INFO, _("Flushing queue for %s (%s)"), cl->name, cl->hostname);
296 for(node = cl->queue->head; node; node = next)
299 send_udppacket(cl, (vpn_packet_t *)node->data);
300 list_delete_node(cl->queue, node);
306 open the local ethertap device
308 int setup_tap_fd(void)
311 const char *tapfname;
319 int ip_fd = -1, if_fd = -1;
325 if((cfg = get_config_val(config, config_tapdevice)))
326 tapfname = cfg->data.ptr;
331 tapfname = "/dev/net/tun";
333 tapfname = "/dev/tap0";
337 tapfname = "/dev/tap0";
340 tapfname = "/dev/tun";
344 if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
346 syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
352 /* Set default MAC address for ethertap devices */
354 mymac.type = SUBNET_MAC;
355 mymac.net.mac.address.x[0] = 0xfe;
356 mymac.net.mac.address.x[1] = 0xfd;
357 mymac.net.mac.address.x[2] = 0x00;
358 mymac.net.mac.address.x[3] = 0x00;
359 mymac.net.mac.address.x[4] = 0x00;
360 mymac.net.mac.address.x[5] = 0x00;
363 taptype = TAP_TYPE_ETHERTAP;
365 /* Ok now check if this is an old ethertap or a new tun/tap thingie */
366 memset(&ifr, 0, sizeof(ifr));
368 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
370 strncpy(ifr.ifr_name, netname, IFNAMSIZ);
372 if (!ioctl(tap_fd, TUNSETIFF, (void *) &ifr))
374 syslog(LOG_INFO, _("%s is a new style tun/tap device"), tapfname);
375 taptype = TAP_TYPE_TUNTAP;
380 taptype = TAP_TYPE_TUNTAP;
386 while(*ptr && !isdigit((int)*ptr)) ptr++;
389 if( (ip_fd = open("/dev/ip", O_RDWR, 0)) < 0){
390 syslog(LOG_ERR, _("Could not open /dev/ip: %m"));
394 /* Assign a new PPA and get its unit number. */
395 if( (ppa = ioctl(nfd, TUNNEWPPA, ppa)) < 0){
396 syslog(LOG_ERR, _("Can't assign new interface: %m"));
400 if( (if_fd = open(tapfname, O_RDWR, 0)) < 0){
401 syslog(LOG_ERR, _("Could not open %s twice: %m"), tapfname);
405 if(ioctl(if_fd, I_PUSH, "ip") < 0){
406 syslog(LOG_ERR, _("Can't push IP module: %m"));
410 /* Assign ppa according to the unit number returned by tun device */
411 if(ioctl(if_fd, IF_UNITSEL, (char *)&ppa) < 0){
412 syslog(LOG_ERR, _("Can't set PPA %d: %m"), ppa);
415 if(ioctl(ip_fd, I_LINK, if_fd) < 0){
416 syslog(LOG_ERR, _("Can't link TUN device to IP: %m"));
426 set up the socket that we listen on for incoming
429 int setup_listen_meta_socket(int port)
432 struct sockaddr_in a;
436 if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
438 syslog(LOG_ERR, _("Creating metasocket failed: %m"));
442 flags = fcntl(nfd, F_GETFL);
443 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
446 syslog(LOG_ERR, _("System call `%s' failed: %m"),
451 /* Optimize TCP settings */
454 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
455 setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
457 setsockopt(nfd, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
459 option = IPTOS_LOWDELAY;
460 setsockopt(nfd, SOL_IP, IP_TOS, &option, sizeof(option));
462 if((cfg = get_config_val(config, config_interface)))
464 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, cfg->data.ptr, strlen(cfg->data.ptr)))
467 syslog(LOG_ERR, _("Unable to bind listen socket to interface %s: %m"), cfg->data.ptr);
473 memset(&a, 0, sizeof(a));
474 a.sin_family = AF_INET;
475 a.sin_port = htons(port);
477 if((cfg = get_config_val(config, config_interfaceip)))
478 a.sin_addr.s_addr = htonl(cfg->data.ip->address);
480 a.sin_addr.s_addr = htonl(INADDR_ANY);
482 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
485 syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
492 syslog(LOG_ERR, _("System call `%s' failed: %m"),
501 setup the socket for incoming encrypted
504 int setup_vpn_in_socket(int port)
507 struct sockaddr_in a;
510 if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
513 syslog(LOG_ERR, _("Creating socket failed: %m"));
517 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
519 flags = fcntl(nfd, F_GETFL);
520 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
523 syslog(LOG_ERR, _("System call `%s' failed: %m"),
528 memset(&a, 0, sizeof(a));
529 a.sin_family = AF_INET;
530 a.sin_port = htons(port);
531 a.sin_addr.s_addr = htonl(INADDR_ANY);
533 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
536 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
544 setup an outgoing meta (tcp) socket
546 int setup_outgoing_meta_socket(connection_t *cl)
549 struct sockaddr_in a;
553 if(debug_lvl >= DEBUG_CONNECTIONS)
554 syslog(LOG_INFO, _("Trying to connect to %s"), cl->hostname);
556 if((cfg = get_config_val(cl->config, config_port)) == NULL)
559 cl->port = cfg->data.val;
561 cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
562 if(cl->meta_socket == -1)
564 syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
565 cl->hostname, cl->port);
569 /* Bind first to get a fix on our source port */
571 a.sin_family = AF_INET;
572 a.sin_port = htons(0);
573 a.sin_addr.s_addr = htonl(INADDR_ANY);
575 if(bind(cl->meta_socket, (struct sockaddr *)&a, sizeof(struct sockaddr)))
577 close(cl->meta_socket);
578 syslog(LOG_ERR, _("System call `%s' failed: %m"), "bind");
582 /* Optimize TCP settings */
585 setsockopt(cl->meta_socket, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
587 setsockopt(cl->meta_socket, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
589 option = IPTOS_LOWDELAY;
590 setsockopt(cl->meta_socket, SOL_IP, IP_TOS, &option, sizeof(option));
594 a.sin_family = AF_INET;
595 a.sin_port = htons(cl->port);
596 a.sin_addr.s_addr = htonl(cl->address);
598 if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
600 close(cl->meta_socket);
601 syslog(LOG_ERR, _("%s port %hd: %m"), cl->hostname, cl->port);
605 flags = fcntl(cl->meta_socket, F_GETFL);
606 if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
608 close(cl->meta_socket);
609 syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
610 cl->hostname, cl->port);
614 if(debug_lvl >= DEBUG_CONNECTIONS)
615 syslog(LOG_INFO, _("Connected to %s port %hd"),
616 cl->hostname, cl->port);
624 Setup an outgoing meta connection.
626 int setup_outgoing_connection(char *name)
628 connection_t *ncn, *old;
634 syslog(LOG_ERR, _("Invalid name for outgoing connection"));
638 /* Make sure we don't make an outgoing connection to a host that is already in our connection list */
640 if((old = lookup_id(name)))
642 if(debug_lvl >= DEBUG_CONNECTIONS)
643 syslog(LOG_NOTICE, _("We are already connected to %s."), name);
644 old->status.outgoing = 1;
648 ncn = new_connection();
649 asprintf(&ncn->name, "%s", name);
651 if(read_host_config(ncn))
653 syslog(LOG_ERR, _("Error reading host configuration file for %s"), ncn->name);
654 free_connection(ncn);
658 if(!(cfg = get_config_val(ncn->config, config_address)))
660 syslog(LOG_ERR, _("No address specified for %s"), ncn->name);
661 free_connection(ncn);
665 if(!(h = gethostbyname(cfg->data.ptr)))
667 syslog(LOG_ERR, _("Error looking up `%s': %m"), cfg->data.ptr);
668 free_connection(ncn);
672 ncn->address = ntohl(*((ipv4_t*)(h->h_addr_list[0])));
673 ncn->hostname = hostlookup(htonl(ncn->address));
675 if(setup_outgoing_meta_socket(ncn) < 0)
677 syslog(LOG_ERR, _("Could not set up a meta connection to %s"),
679 free_connection(ncn);
683 ncn->status.outgoing = 1;
684 ncn->buffer = xmalloc(MAXBUFSIZE);
686 ncn->last_ping_time = time(NULL);
695 int read_rsa_public_key(connection_t *cl)
703 cl->rsa_key = RSA_new();
705 /* First, check for simple PublicKey statement */
707 if((cfg = get_config_val(cl->config, config_publickey)))
709 BN_hex2bn(&cl->rsa_key->n, cfg->data.ptr);
710 BN_hex2bn(&cl->rsa_key->e, "FFFF");
714 /* Else, check for PublicKeyFile statement and read it */
716 if((cfg = get_config_val(cl->config, config_publickeyfile)))
718 if(is_safe_path(cfg->data.ptr))
720 if((fp = fopen(cfg->data.ptr, "r")) == NULL)
722 syslog(LOG_ERR, _("Error reading RSA public key file `%s': %m"),
726 result = PEM_read_RSAPublicKey(fp, &cl->rsa_key, NULL, NULL);
730 syslog(LOG_ERR, _("Reading RSA public key file `%s' failed: %m"),
740 /* Else, check if a harnessed public key is in the config file */
742 asprintf(&fname, "%s/hosts/%s", confbase, cl->name);
743 if((fp = fopen(fname, "r")))
745 result = PEM_read_RSAPublicKey(fp, &cl->rsa_key, NULL, NULL);
754 /* Nothing worked. */
756 syslog(LOG_ERR, _("No public key for %s specified!"), cl->name);
761 int read_rsa_private_key(void)
768 myself->rsa_key = RSA_new();
770 if((cfg = get_config_val(config, config_privatekey)))
772 BN_hex2bn(&myself->rsa_key->d, cfg->data.ptr);
773 BN_hex2bn(&myself->rsa_key->e, "FFFF");
775 else if((cfg = get_config_val(config, config_privatekeyfile)))
777 if((fp = fopen(cfg->data.ptr, "r")) == NULL)
779 syslog(LOG_ERR, _("Error reading RSA private key file `%s': %m"),
783 result = PEM_read_RSAPrivateKey(fp, &myself->rsa_key, NULL, NULL);
787 syslog(LOG_ERR, _("Reading RSA private key file `%s' failed: %m"),
794 syslog(LOG_ERR, _("No private key for tinc daemon specified!"));
802 Configure connection_t myself and set up the local sockets (listen only)
804 int setup_myself(void)
810 myself = new_connection();
812 asprintf(&myself->hostname, _("MYSELF"));
814 myself->protocol_version = PROT_CURRENT;
816 if(!(cfg = get_config_val(config, config_name))) /* Not acceptable */
818 syslog(LOG_ERR, _("Name for tinc daemon required!"));
822 asprintf(&myself->name, "%s", (char*)cfg->data.val);
824 if(check_id(myself->name))
826 syslog(LOG_ERR, _("Invalid name for myself!"));
830 if(read_rsa_private_key())
833 if(read_host_config(myself))
835 syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
839 if(read_rsa_public_key(myself))
844 if(RSA_check_key(myself->rsa_key) != 1)
846 syslog(LOG_ERR, _("Invalid public/private keypair!"));
850 if(!(cfg = get_config_val(myself->config, config_port)))
853 myself->port = cfg->data.val;
855 /* Read in all the subnets specified in the host configuration file */
857 for(next = myself->config; (cfg = get_config_val(next, config_subnet)); next = cfg->next)
860 net->type = SUBNET_IPV4;
861 net->net.ipv4.address = cfg->data.ip->address;
862 net->net.ipv4.mask = cfg->data.ip->mask;
864 /* Teach newbies what subnets are... */
866 if((net->net.ipv4.address & net->net.ipv4.mask) != net->net.ipv4.address)
868 syslog(LOG_ERR, _("Network address and subnet mask do not match!"));
872 subnet_add(myself, net);
876 /* Check some options */
878 if((cfg = get_config_val(config, config_indirectdata)))
879 if(cfg->data.val == stupid_true)
880 myself->options |= OPTION_INDIRECT;
882 if((cfg = get_config_val(config, config_tcponly)))
883 if(cfg->data.val == stupid_true)
884 myself->options |= OPTION_TCPONLY;
886 if((cfg = get_config_val(myself->config, config_indirectdata)))
887 if(cfg->data.val == stupid_true)
888 myself->options |= OPTION_INDIRECT;
890 if((cfg = get_config_val(myself->config, config_tcponly)))
891 if(cfg->data.val == stupid_true)
892 myself->options |= OPTION_TCPONLY;
894 if(myself->options & OPTION_TCPONLY)
895 myself->options |= OPTION_INDIRECT;
897 if((cfg = get_config_val(config, config_mode)))
899 if(!strcasecmp(cfg->data.ptr, "router"))
900 routing_mode = RMODE_ROUTER;
901 else if (!strcasecmp(cfg->data.ptr, "switch"))
902 routing_mode = RMODE_SWITCH;
903 else if (!strcasecmp(cfg->data.ptr, "hub"))
904 routing_mode = RMODE_HUB;
907 syslog(LOG_ERR, _("Invalid routing mode!"));
912 routing_mode = RMODE_ROUTER;
917 if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
919 syslog(LOG_ERR, _("Unable to set up a listening TCP socket!"));
923 if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
925 syslog(LOG_ERR, _("Unable to set up a listening UDP socket!"));
929 /* Generate packet encryption key */
931 myself->cipher_pkttype = EVP_bf_cbc();
933 myself->cipher_pktkeylength = myself->cipher_pkttype->key_len + myself->cipher_pkttype->iv_len;
935 myself->cipher_pktkey = (char *)xmalloc(myself->cipher_pktkeylength);
936 RAND_pseudo_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
938 if(!(cfg = get_config_val(config, config_keyexpire)))
941 keylifetime = cfg->data.val;
943 keyexpires = time(NULL) + keylifetime;
947 myself->status.active = 1;
950 syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
956 sigalrm_handler(int a)
960 cfg = get_config_val(upstreamcfg, config_connectto);
964 if(upstreamcfg == config)
966 /* No upstream IP given, we're listen only. */
967 signal(SIGALRM, SIG_IGN);
973 /* We previously tried all the ConnectTo lines. Now wrap back to the first. */
974 cfg = get_config_val(config, config_connectto);
979 upstreamcfg = cfg->next;
980 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
982 signal(SIGALRM, SIG_IGN);
985 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
988 signal(SIGALRM, sigalrm_handler);
989 upstreamcfg = config;
990 seconds_till_retry += 5;
991 if(seconds_till_retry > MAXTIMEOUT) /* Don't wait more than MAXTIMEOUT seconds. */
992 seconds_till_retry = MAXTIMEOUT;
993 syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
995 alarm(seconds_till_retry);
1000 setup all initial network connections
1002 int setup_network_connections(void)
1004 config_t const *cfg;
1009 if((cfg = get_config_val(config, config_pingtimeout)) == NULL)
1013 timeout = cfg->data.val;
1020 if(setup_tap_fd() < 0)
1023 /* Run tinc-up script to further initialize the tap interface */
1024 execute_script("tinc-up");
1026 if(setup_myself() < 0)
1029 if(!(cfg = get_config_val(config, config_connectto)))
1030 /* No upstream IP given, we're listen only. */
1035 upstreamcfg = cfg->next;
1036 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
1038 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
1043 signal(SIGALRM, sigalrm_handler);
1044 upstreamcfg = config;
1045 seconds_till_retry = MAXTIMEOUT;
1046 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
1047 alarm(seconds_till_retry);
1057 close all open network connections
1059 void close_network_connections(void)
1061 avl_node_t *node, *next;
1064 for(node = connection_tree->head; node; node = next)
1067 p = (connection_t *)node->data;
1068 p->status.outgoing = 0;
1069 terminate_connection(p, 0);
1072 terminate_connection(myself, 0);
1076 execute_script("tinc-down");
1084 handle an incoming tcp connect call and open
1087 connection_t *create_new_connection(int sfd)
1090 struct sockaddr_in ci;
1091 int len = sizeof(ci);
1093 p = new_connection();
1095 if(getpeername(sfd, (struct sockaddr *) &ci, (socklen_t *) &len) < 0)
1097 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1103 asprintf(&p->name, _("UNKNOWN"));
1104 p->address = ntohl(ci.sin_addr.s_addr);
1105 p->hostname = hostlookup(ci.sin_addr.s_addr);
1106 p->port = htons(ci.sin_port); /* This one will be overwritten later */
1107 p->meta_socket = sfd;
1109 p->buffer = xmalloc(MAXBUFSIZE);
1111 p->last_ping_time = time(NULL);
1113 if(debug_lvl >= DEBUG_CONNECTIONS)
1114 syslog(LOG_NOTICE, _("Connection from %s port %d"),
1115 p->hostname, htons(ci.sin_port));
1117 p->allow_request = ID;
1123 put all file descriptors in an fd_set array
1125 void build_fdset(fd_set *fs)
1132 FD_SET(myself->socket, fs);
1134 for(node = connection_tree->head; node; node = node->next)
1136 p = (connection_t *)node->data;
1137 FD_SET(p->meta_socket, fs);
1140 FD_SET(myself->meta_socket, fs);
1146 receive incoming data from the listening
1147 udp socket and write it to the ethertap
1148 device after being decrypted
1150 void handle_incoming_vpn_data(void)
1153 int x, l = sizeof(x);
1154 struct sockaddr_in from;
1155 socklen_t fromlen = sizeof(from);
1158 if(getsockopt(myself->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1160 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1161 __FILE__, __LINE__, myself->socket);
1166 syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1170 if((pkt.len = recvfrom(myself->socket, (char *) pkt.salt, MTU, 0, (struct sockaddr *)&from, &fromlen)) <= 0)
1172 syslog(LOG_ERR, _("Receiving packet failed: %m"));
1176 cl = lookup_active(ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
1180 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));
1184 cl->last_ping_time = time(NULL);
1186 receive_udppacket(cl, &pkt);
1191 Terminate a connection:
1193 - Remove associated hosts and subnets
1194 - Deactivate the host
1195 - Since it might still be referenced, put it on the prune list.
1196 - If report == 1, then send DEL_HOST messages to the other tinc daemons.
1198 void terminate_connection(connection_t *cl, int report)
1202 avl_node_t *node, *next;
1204 if(cl->status.remove)
1207 cl->status.remove = 1;
1212 close(cl->meta_socket);
1218 if(debug_lvl >= DEBUG_CONNECTIONS)
1219 syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1220 cl->name, cl->hostname);
1222 if(cl->status.active)
1224 /* Find all connections that were lost because they were behind cl
1225 (the connection that was dropped). */
1227 for(node = active_tree->head; node; node = next)
1230 p = (connection_t *)node->data;
1231 if(p->nexthop == cl)
1232 terminate_connection(p, report);
1237 /* Inform others of termination if needed */
1240 for(node = connection_tree->head; node; node = node->next)
1242 p = (connection_t *)node->data;
1243 if(p->status.active)
1244 send_del_host(p, cl); /* Sounds like recursion, but p does not have a meta connection :) */
1247 /* Remove the associated subnets */
1249 for(node = cl->subnet_tree->head; node; node = next)
1252 subnet = (subnet_t *)node->data;
1256 /* Check if this was our outgoing connection */
1258 if(cl->status.outgoing)
1260 cl->status.outgoing = 0;
1261 signal(SIGALRM, sigalrm_handler);
1262 alarm(seconds_till_retry);
1263 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
1266 /* Schedule it for pruning */
1272 Check if the other end is active.
1273 If we have sent packets, but didn't receive any,
1274 then possibly the other end is dead. We send a
1275 PING request over the meta connection. If the other
1276 end does not reply in time, we consider them dead
1277 and close the connection.
1279 void check_dead_connections(void)
1287 for(node = connection_tree->head; node; node = node->next)
1289 cl = (connection_t *)node->data;
1290 if(cl->status.active)
1292 if(cl->last_ping_time + timeout < now)
1294 if(cl->status.pinged)
1296 if(debug_lvl >= DEBUG_PROTOCOL)
1297 syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1298 cl->name, cl->hostname);
1299 cl->status.timeout = 1;
1300 terminate_connection(cl, 1);
1313 accept a new tcp connect and create a
1316 int handle_new_meta_connection()
1319 struct sockaddr client;
1320 int nfd, len = sizeof(client);
1322 if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
1324 syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1328 if(!(ncn = create_new_connection(nfd)))
1332 syslog(LOG_NOTICE, _("Closed attempted connection"));
1336 connection_add(ncn);
1344 check all connections to see if anything
1345 happened on their sockets
1347 void check_network_activity(fd_set *f)
1352 if(FD_ISSET(myself->socket, f))
1353 handle_incoming_vpn_data();
1355 for(node = connection_tree->head; node; node = node->next)
1357 p = (connection_t *)node->data;
1359 if(p->status.remove)
1362 if(FD_ISSET(p->meta_socket, f))
1363 if(receive_meta(p) < 0)
1365 terminate_connection(p, 1);
1370 if(FD_ISSET(myself->meta_socket, f))
1371 handle_new_meta_connection();
1376 read, encrypt and send data that is
1377 available through the ethertap device
1379 void handle_tap_input(void)
1385 if((lenin = read(tap_fd, vp.data + 14, MTU)) <= 0)
1387 syslog(LOG_ERR, _("Error while reading from tun device: %m"));
1390 memcpy(vp.data, mymac.net.mac.address.x, 6);
1391 memcpy(vp.data + 6, mymac.net.mac.address.x, 6);
1394 vp.len = lenin + 14;
1396 if(taptype == TAP_TYPE_TUNTAP)
1398 if((lenin = read(tap_fd, vp.data, MTU)) <= 0)
1400 syslog(LOG_ERR, _("Error while reading from tun/tap device: %m"));
1407 if((lenin = read(tap_fd, vp.data - 2, MTU)) <= 0)
1409 syslog(LOG_ERR, _("Error while reading from ethertap device: %m"));
1416 total_tap_in += vp.len;
1420 if(debug_lvl >= DEBUG_TRAFFIC)
1421 syslog(LOG_WARNING, _("Received short packet from tap device"));
1425 if(debug_lvl >= DEBUG_TRAFFIC)
1427 syslog(LOG_DEBUG, _("Read packet of length %d from tap device"), vp.len);
1430 route_outgoing(&vp);
1435 this is where it all happens...
1437 void main_loop(void)
1442 time_t last_ping_check;
1445 last_ping_check = time(NULL);
1449 tv.tv_sec = timeout;
1455 if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1457 if(errno != EINTR) /* because of alarm */
1459 syslog(LOG_ERR, _("Error while waiting for input: %m"));
1466 syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1468 close_network_connections();
1469 clear_config(&config);
1471 if(read_server_config())
1473 syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1479 if(setup_network_connections())
1487 /* Let's check if everybody is still alive */
1489 if(last_ping_check + timeout < t)
1491 check_dead_connections();
1492 last_ping_check = time(NULL);
1494 /* Should we regenerate our key? */
1498 if(debug_lvl >= DEBUG_STATUS)
1499 syslog(LOG_INFO, _("Regenerating symmetric key"));
1501 RAND_pseudo_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
1502 send_key_changed(myself, NULL);
1503 keyexpires = time(NULL) + keylifetime;
1509 check_network_activity(&fset);
1511 /* local tap data */
1512 if(FD_ISSET(tap_fd, &fset))