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.136 2001/10/08 13:37:30 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 int seconds_till_retry = 5;
104 void send_udppacket(connection_t *cl, vpn_packet_t *inpkt)
109 struct sockaddr_in to;
110 socklen_t tolen = sizeof(to);
113 if(!cl->status.validkey)
115 if(debug_lvl >= DEBUG_TRAFFIC)
116 syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
117 cl->name, cl->hostname);
119 /* Since packet is on the stack of handle_tap_input(),
120 we have to make a copy of it first. */
122 copy = xmalloc(sizeof(vpn_packet_t));
123 memcpy(copy, inpkt, sizeof(vpn_packet_t));
125 list_insert_tail(cl->queue, copy);
127 if(!cl->status.waitingforkey)
128 send_req_key(myself, cl);
132 /* Encrypt the packet. */
134 RAND_pseudo_bytes(inpkt->salt, sizeof(inpkt->salt));
136 EVP_EncryptInit(&ctx, cl->cipher_pkttype, cl->cipher_pktkey, cl->cipher_pktkey + cl->cipher_pkttype->key_len);
137 EVP_EncryptUpdate(&ctx, outpkt.salt, &outlen, inpkt->salt, inpkt->len + sizeof(inpkt->salt));
138 EVP_EncryptFinal(&ctx, outpkt.salt + outlen, &outpad);
141 total_socket_out += outlen;
143 to.sin_family = AF_INET;
144 to.sin_addr.s_addr = htonl(cl->address);
145 to.sin_port = htons(cl->port);
147 if((sendto(myself->socket, (char *) outpkt.salt, outlen, 0, (const struct sockaddr *)&to, tolen)) < 0)
149 syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
150 cl->name, cl->hostname);
156 void receive_packet(connection_t *cl, vpn_packet_t *packet)
159 if(debug_lvl >= DEBUG_TRAFFIC)
160 syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"), packet->len, cl->name, cl->hostname);
162 route_incoming(cl, packet);
166 void receive_udppacket(connection_t *cl, vpn_packet_t *inpkt)
172 /* Decrypt the packet */
174 EVP_DecryptInit(&ctx, myself->cipher_pkttype, myself->cipher_pktkey, myself->cipher_pktkey + myself->cipher_pkttype->key_len);
175 EVP_DecryptUpdate(&ctx, outpkt.salt, &outlen, inpkt->salt, inpkt->len);
176 EVP_DecryptFinal(&ctx, outpkt.salt + outlen, &outpad);
178 outpkt.len = outlen - sizeof(outpkt.salt);
180 total_socket_in += outlen;
182 receive_packet(cl, &outpkt);
186 void receive_tcppacket(connection_t *cl, char *buffer, int len)
191 memcpy(outpkt.data, buffer, len);
193 receive_packet(cl, &outpkt);
197 void accept_packet(vpn_packet_t *packet)
200 if(debug_lvl >= DEBUG_TRAFFIC)
201 syslog(LOG_DEBUG, _("Writing packet of %d bytes to tap device"),
205 if(write(tap_fd, packet->data + 14, packet->len - 14) < 0)
206 syslog(LOG_ERR, _("Can't write to tun/tap device: %m"));
208 total_tap_out += packet->len;
210 if(taptype == TAP_TYPE_TUNTAP)
212 if(write(tap_fd, packet->data, packet->len) < 0)
213 syslog(LOG_ERR, _("Can't write to tun/tap device: %m"));
215 total_tap_out += packet->len;
219 if(write(tap_fd, packet->data - 2, packet->len + 2) < 0)
220 syslog(LOG_ERR, _("Can't write to ethertap device: %m"));
222 total_tap_out += packet->len;
229 send a packet to the given vpn ip.
231 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 if(cl->via == myself)
263 if(via != cl && debug_lvl >= DEBUG_TRAFFIC)
264 syslog(LOG_ERR, _("Sending packet to %s via %s (%s)"),
265 cl->name, via->name, via->hostname);
267 if((myself->options | via->options) & OPTION_TCPONLY)
269 if(send_tcppacket(via, packet))
270 terminate_connection(via, 1);
273 send_udppacket(via, packet);
276 /* Broadcast a packet to all active direct connections */
278 void broadcast_packet(connection_t *from, vpn_packet_t *packet)
283 if(debug_lvl >= DEBUG_TRAFFIC)
284 syslog(LOG_INFO, _("Broadcasting packet of %d bytes from %s (%s)"),
285 packet->len, from->name, from->hostname);
287 for(node = connection_tree->head; node; node = node->next)
289 cl = (connection_t *)node->data;
290 if(cl->status.active && cl != from)
291 send_packet(cl, packet);
296 void flush_queue(connection_t *cl)
298 list_node_t *node, *next;
300 if(debug_lvl >= DEBUG_TRAFFIC)
301 syslog(LOG_INFO, _("Flushing queue for %s (%s)"), cl->name, cl->hostname);
303 for(node = cl->queue->head; node; node = next)
306 send_udppacket(cl, (vpn_packet_t *)node->data);
307 list_delete_node(cl->queue, node);
313 open the local ethertap device
315 int setup_tap_fd(void)
318 const char *tapfname;
326 int ip_fd = -1, if_fd = -1;
332 if((cfg = get_config_val(config, config_tapdevice)))
333 tapfname = cfg->data.ptr;
338 tapfname = "/dev/net/tun";
340 tapfname = "/dev/tap0";
344 tapfname = "/dev/tap0";
347 tapfname = "/dev/tun";
351 if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
353 syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
359 /* Set default MAC address for ethertap devices */
361 mymac.type = SUBNET_MAC;
362 mymac.net.mac.address.x[0] = 0xfe;
363 mymac.net.mac.address.x[1] = 0xfd;
364 mymac.net.mac.address.x[2] = 0x00;
365 mymac.net.mac.address.x[3] = 0x00;
366 mymac.net.mac.address.x[4] = 0x00;
367 mymac.net.mac.address.x[5] = 0x00;
371 /* Ok now check if this is an old ethertap or a new tun/tap thingie */
372 memset(&ifr, 0, sizeof(ifr));
374 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
376 strncpy(ifr.ifr_name, netname, IFNAMSIZ);
378 if (!ioctl(tap_fd, TUNSETIFF, (void *) &ifr))
380 syslog(LOG_INFO, _("%s is a Linux tun/tap device"), tapfname);
381 taptype = TAP_TYPE_TUNTAP;
384 if (!ioctl(tap_fd, (('T'<< 8) | 202), (void *) &ifr))
386 syslog(LOG_INFO, _("%s is a Linux tun/tap device"), tapfname);
387 syslog(LOG_WARNING, _("Old ioctl() request used"));
388 taptype = TAP_TYPE_TUNTAP;
393 syslog(LOG_INFO, _("%s is a Linux ethertap device"), tapfname);
394 taptype = TAP_TYPE_ETHERTAP;
398 syslog(LOG_INFO, _("%s is a FreeBSD tap device"), tapfname);
399 taptype = TAP_TYPE_TUNTAP;
405 while(*ptr && !isdigit((int)*ptr)) ptr++;
408 if( (ip_fd = open("/dev/ip", O_RDWR, 0)) < 0){
409 syslog(LOG_ERR, _("Could not open /dev/ip: %m"));
413 /* Assign a new PPA and get its unit number. */
414 if( (ppa = ioctl(nfd, TUNNEWPPA, ppa)) < 0){
415 syslog(LOG_ERR, _("Can't assign new interface: %m"));
419 if( (if_fd = open(tapfname, O_RDWR, 0)) < 0){
420 syslog(LOG_ERR, _("Could not open %s twice: %m"), tapfname);
424 if(ioctl(if_fd, I_PUSH, "ip") < 0){
425 syslog(LOG_ERR, _("Can't push IP module: %m"));
429 /* Assign ppa according to the unit number returned by tun device */
430 if(ioctl(if_fd, IF_UNITSEL, (char *)&ppa) < 0){
431 syslog(LOG_ERR, _("Can't set PPA %d: %m"), ppa);
435 if(ioctl(ip_fd, I_LINK, if_fd) < 0){
436 syslog(LOG_ERR, _("Can't link TUN device to IP: %m"));
440 syslog(LOG_INFO, _("%s is a Solaris tun device"), tapfname);
448 set up the socket that we listen on for incoming
451 int setup_listen_meta_socket(int port)
454 struct sockaddr_in a;
458 if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
460 syslog(LOG_ERR, _("Creating metasocket failed: %m"));
464 flags = fcntl(nfd, F_GETFL);
465 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
468 syslog(LOG_ERR, _("System call `%s' failed: %m"),
473 /* Optimize TCP settings */
476 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
477 setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
479 setsockopt(nfd, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
481 option = IPTOS_LOWDELAY;
482 setsockopt(nfd, SOL_IP, IP_TOS, &option, sizeof(option));
484 if((cfg = get_config_val(config, config_interface)))
486 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, cfg->data.ptr, strlen(cfg->data.ptr)))
489 syslog(LOG_ERR, _("Unable to bind listen socket to interface %s: %m"), cfg->data.ptr);
495 memset(&a, 0, sizeof(a));
496 a.sin_family = AF_INET;
497 a.sin_port = htons(port);
499 if((cfg = get_config_val(config, config_interfaceip)))
500 a.sin_addr.s_addr = htonl(cfg->data.ip->address);
502 a.sin_addr.s_addr = htonl(INADDR_ANY);
504 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
507 syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
514 syslog(LOG_ERR, _("System call `%s' failed: %m"),
523 setup the socket for incoming encrypted
526 int setup_vpn_in_socket(int port)
529 struct sockaddr_in a;
532 if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
535 syslog(LOG_ERR, _("Creating socket failed: %m"));
539 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
541 flags = fcntl(nfd, F_GETFL);
542 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
545 syslog(LOG_ERR, _("System call `%s' failed: %m"),
550 memset(&a, 0, sizeof(a));
551 a.sin_family = AF_INET;
552 a.sin_port = htons(port);
553 a.sin_addr.s_addr = htonl(INADDR_ANY);
555 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
558 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
566 setup an outgoing meta (tcp) socket
568 int setup_outgoing_meta_socket(connection_t *cl)
571 struct sockaddr_in a;
575 if(debug_lvl >= DEBUG_CONNECTIONS)
576 syslog(LOG_INFO, _("Trying to connect to %s"), cl->hostname);
578 if((cfg = get_config_val(cl->config, config_port)) == NULL)
581 cl->port = cfg->data.val;
583 cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
584 if(cl->meta_socket == -1)
586 syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
587 cl->hostname, cl->port);
591 /* Bind first to get a fix on our source port */
593 a.sin_family = AF_INET;
594 a.sin_port = htons(0);
595 a.sin_addr.s_addr = htonl(INADDR_ANY);
597 if(bind(cl->meta_socket, (struct sockaddr *)&a, sizeof(struct sockaddr)))
599 close(cl->meta_socket);
600 syslog(LOG_ERR, _("System call `%s' failed: %m"), "bind");
604 /* Optimize TCP settings */
607 setsockopt(cl->meta_socket, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
609 setsockopt(cl->meta_socket, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
611 option = IPTOS_LOWDELAY;
612 setsockopt(cl->meta_socket, SOL_IP, IP_TOS, &option, sizeof(option));
616 a.sin_family = AF_INET;
617 a.sin_port = htons(cl->port);
618 a.sin_addr.s_addr = htonl(cl->address);
620 if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
622 close(cl->meta_socket);
623 syslog(LOG_ERR, _("%s port %hd: %m"), cl->hostname, cl->port);
627 flags = fcntl(cl->meta_socket, F_GETFL);
628 if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
630 close(cl->meta_socket);
631 syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
632 cl->hostname, cl->port);
636 if(debug_lvl >= DEBUG_CONNECTIONS)
637 syslog(LOG_INFO, _("Connected to %s port %hd"),
638 cl->hostname, cl->port);
646 Setup an outgoing meta connection.
648 int setup_outgoing_connection(char *name)
650 connection_t *ncn, *old;
656 syslog(LOG_ERR, _("Invalid name for outgoing connection"));
660 /* Make sure we don't make an outgoing connection to a host that is already in our connection list */
662 if((old = lookup_id(name)))
664 if(!old->status.outgoing)
666 if(debug_lvl >= DEBUG_CONNECTIONS)
667 syslog(LOG_NOTICE, _("We are already connected to %s."), name);
669 old->status.outgoing = 1;
674 ncn = new_connection();
675 asprintf(&ncn->name, "%s", name);
677 if(read_host_config(ncn))
679 syslog(LOG_ERR, _("Error reading host configuration file for %s"), ncn->name);
680 free_connection(ncn);
684 if(!(cfg = get_config_val(ncn->config, config_address)))
686 syslog(LOG_ERR, _("No address specified for %s"), ncn->name);
687 free_connection(ncn);
691 if(!(h = gethostbyname(cfg->data.ptr)))
693 syslog(LOG_ERR, _("Error looking up `%s': %m"), cfg->data.ptr);
694 free_connection(ncn);
698 ncn->address = ntohl(*((ipv4_t*)(h->h_addr_list[0])));
699 ncn->hostname = hostlookup(htonl(ncn->address));
701 if(setup_outgoing_meta_socket(ncn) < 0)
703 syslog(LOG_ERR, _("Could not set up a meta connection to %s"),
705 free_connection(ncn);
709 ncn->status.outgoing = 1;
710 ncn->buffer = xmalloc(MAXBUFSIZE);
712 ncn->last_ping_time = time(NULL);
721 int read_rsa_public_key(connection_t *cl)
729 cl->rsa_key = RSA_new();
731 /* First, check for simple PublicKey statement */
733 if((cfg = get_config_val(cl->config, config_publickey)))
735 BN_hex2bn(&cl->rsa_key->n, cfg->data.ptr);
736 BN_hex2bn(&cl->rsa_key->e, "FFFF");
740 /* Else, check for PublicKeyFile statement and read it */
742 if((cfg = get_config_val(cl->config, config_publickeyfile)))
744 if(is_safe_path(cfg->data.ptr))
746 if((fp = fopen(cfg->data.ptr, "r")) == NULL)
748 syslog(LOG_ERR, _("Error reading RSA public key file `%s': %m"),
752 result = PEM_read_RSAPublicKey(fp, &cl->rsa_key, NULL, NULL);
756 syslog(LOG_ERR, _("Reading RSA public key file `%s' failed: %m"),
766 /* Else, check if a harnessed public key is in the config file */
768 asprintf(&fname, "%s/hosts/%s", confbase, cl->name);
769 if((fp = fopen(fname, "r")))
771 result = PEM_read_RSAPublicKey(fp, &cl->rsa_key, NULL, NULL);
780 /* Nothing worked. */
782 syslog(LOG_ERR, _("No public key for %s specified!"), cl->name);
787 int read_rsa_private_key(void)
794 myself->rsa_key = RSA_new();
796 if((cfg = get_config_val(config, config_privatekey)))
798 BN_hex2bn(&myself->rsa_key->d, cfg->data.ptr);
799 BN_hex2bn(&myself->rsa_key->e, "FFFF");
801 else if((cfg = get_config_val(config, config_privatekeyfile)))
803 if((fp = fopen(cfg->data.ptr, "r")) == NULL)
805 syslog(LOG_ERR, _("Error reading RSA private key file `%s': %m"),
809 result = PEM_read_RSAPrivateKey(fp, &myself->rsa_key, NULL, NULL);
813 syslog(LOG_ERR, _("Reading RSA private key file `%s' failed: %m"),
820 syslog(LOG_ERR, _("No private key for tinc daemon specified!"));
828 Configure connection_t myself and set up the local sockets (listen only)
830 int setup_myself(void)
836 myself = new_connection();
838 asprintf(&myself->hostname, _("MYSELF"));
840 myself->protocol_version = PROT_CURRENT;
842 if(!(cfg = get_config_val(config, config_name))) /* Not acceptable */
844 syslog(LOG_ERR, _("Name for tinc daemon required!"));
848 asprintf(&myself->name, "%s", (char*)cfg->data.val);
850 if(check_id(myself->name))
852 syslog(LOG_ERR, _("Invalid name for myself!"));
856 if(read_rsa_private_key())
859 if(read_host_config(myself))
861 syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
865 if(read_rsa_public_key(myself))
870 if(RSA_check_key(myself->rsa_key) != 1)
872 syslog(LOG_ERR, _("Invalid public/private keypair!"));
876 if(!(cfg = get_config_val(myself->config, config_port)))
879 myself->port = cfg->data.val;
881 /* Read in all the subnets specified in the host configuration file */
883 for(next = myself->config; (cfg = get_config_val(next, config_subnet)); next = cfg->next)
886 net->type = SUBNET_IPV4;
887 net->net.ipv4.address = cfg->data.ip->address;
888 net->net.ipv4.mask = cfg->data.ip->mask;
890 /* Teach newbies what subnets are... */
892 if((net->net.ipv4.address & net->net.ipv4.mask) != net->net.ipv4.address)
894 syslog(LOG_ERR, _("Network address and subnet mask do not match!"));
898 subnet_add(myself, net);
902 /* Check some options */
904 if((cfg = get_config_val(config, config_indirectdata)))
905 if(cfg->data.val == stupid_true)
906 myself->options |= OPTION_INDIRECT;
908 if((cfg = get_config_val(config, config_tcponly)))
909 if(cfg->data.val == stupid_true)
910 myself->options |= OPTION_TCPONLY;
912 if((cfg = get_config_val(myself->config, config_indirectdata)))
913 if(cfg->data.val == stupid_true)
914 myself->options |= OPTION_INDIRECT;
916 if((cfg = get_config_val(myself->config, config_tcponly)))
917 if(cfg->data.val == stupid_true)
918 myself->options |= OPTION_TCPONLY;
920 if(myself->options & OPTION_TCPONLY)
921 myself->options |= OPTION_INDIRECT;
923 if((cfg = get_config_val(config, config_mode)))
925 if(!strcasecmp(cfg->data.ptr, "router"))
926 routing_mode = RMODE_ROUTER;
927 else if (!strcasecmp(cfg->data.ptr, "switch"))
928 routing_mode = RMODE_SWITCH;
929 else if (!strcasecmp(cfg->data.ptr, "hub"))
930 routing_mode = RMODE_HUB;
933 syslog(LOG_ERR, _("Invalid routing mode!"));
938 routing_mode = RMODE_ROUTER;
943 if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
945 syslog(LOG_ERR, _("Unable to set up a listening TCP socket!"));
949 if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
951 syslog(LOG_ERR, _("Unable to set up a listening UDP socket!"));
955 /* Generate packet encryption key */
957 myself->cipher_pkttype = EVP_bf_cbc();
959 myself->cipher_pktkeylength = myself->cipher_pkttype->key_len + myself->cipher_pkttype->iv_len;
961 myself->cipher_pktkey = (char *)xmalloc(myself->cipher_pktkeylength);
962 RAND_pseudo_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
964 if(!(cfg = get_config_val(config, config_keyexpire)))
967 keylifetime = cfg->data.val;
969 keyexpires = time(NULL) + keylifetime;
973 myself->nexthop = myself;
974 myself->prevhop = myself;
975 myself->via = myself;
976 myself->status.active = 1;
979 syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
984 void randomized_alarm(int seconds)
987 RAND_pseudo_bytes(&r, 1);
988 alarm((seconds * (int)r) / 128 + 1);
992 try_outgoing_connections(int a)
997 cfg = get_config_val(config, config_connectto);
1001 if(setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
1003 cfg = get_config_val(cfg->next, config_connectto); /* Or else we try the next ConnectTo line */
1008 seconds_till_retry += 5;
1009 if(seconds_till_retry > MAXTIMEOUT) /* Don't wait more than MAXTIMEOUT seconds. */
1010 seconds_till_retry = MAXTIMEOUT;
1012 syslog(LOG_ERR, _("Failed to setup all outgoing connections, will retry in %d seconds"),
1013 seconds_till_retry);
1015 /* Randomize timeout to avoid global synchronisation effects */
1016 randomized_alarm(seconds_till_retry);
1020 seconds_till_retry = 5;
1026 setup all initial network connections
1028 int setup_network_connections(void)
1030 config_t const *cfg;
1035 if((cfg = get_config_val(config, config_pingtimeout)) == NULL)
1039 timeout = cfg->data.val;
1046 if(setup_tap_fd() < 0)
1049 /* Run tinc-up script to further initialize the tap interface */
1050 execute_script("tinc-up");
1052 if(setup_myself() < 0)
1055 signal(SIGALRM, try_outgoing_connections);
1062 close all open network connections
1064 void close_network_connections(void)
1066 avl_node_t *node, *next;
1069 for(node = connection_tree->head; node; node = next)
1072 p = (connection_t *)node->data;
1073 p->status.outgoing = 0;
1074 terminate_connection(p, 0);
1077 terminate_connection(myself, 0);
1081 execute_script("tinc-down");
1089 handle an incoming tcp connect call and open
1092 connection_t *create_new_connection(int sfd)
1095 struct sockaddr_in ci;
1096 int len = sizeof(ci);
1098 p = new_connection();
1100 if(getpeername(sfd, (struct sockaddr *) &ci, (socklen_t *) &len) < 0)
1102 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1108 asprintf(&p->name, _("UNKNOWN"));
1109 p->address = ntohl(ci.sin_addr.s_addr);
1110 p->hostname = hostlookup(ci.sin_addr.s_addr);
1111 p->port = htons(ci.sin_port); /* This one will be overwritten later */
1112 p->meta_socket = sfd;
1114 p->buffer = xmalloc(MAXBUFSIZE);
1116 p->last_ping_time = time(NULL);
1118 if(debug_lvl >= DEBUG_CONNECTIONS)
1119 syslog(LOG_NOTICE, _("Connection from %s port %d"),
1120 p->hostname, htons(ci.sin_port));
1122 p->allow_request = ID;
1128 put all file descriptors in an fd_set array
1130 void build_fdset(fd_set *fs)
1137 FD_SET(myself->socket, fs);
1139 for(node = connection_tree->head; node; node = node->next)
1141 p = (connection_t *)node->data;
1142 FD_SET(p->meta_socket, fs);
1145 FD_SET(myself->meta_socket, fs);
1151 receive incoming data from the listening
1152 udp socket and write it to the ethertap
1153 device after being decrypted
1155 void handle_incoming_vpn_data(void)
1158 int x, l = sizeof(x);
1159 struct sockaddr_in from;
1160 socklen_t fromlen = sizeof(from);
1163 if(getsockopt(myself->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1165 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1166 __FILE__, __LINE__, myself->socket);
1171 syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1175 if((pkt.len = recvfrom(myself->socket, (char *) pkt.salt, MTU, 0, (struct sockaddr *)&from, &fromlen)) <= 0)
1177 syslog(LOG_ERR, _("Receiving packet failed: %m"));
1181 cl = lookup_active(ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
1185 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));
1189 cl->last_ping_time = time(NULL);
1191 receive_udppacket(cl, &pkt);
1196 Terminate a connection:
1198 - Remove associated hosts and subnets
1199 - Deactivate the host
1200 - Since it might still be referenced, put it on the prune list.
1201 - If report == 1, then send DEL_HOST messages to the other tinc daemons.
1203 void terminate_connection(connection_t *cl, int report)
1207 avl_node_t *node, *next;
1209 if(cl->status.remove)
1212 cl->status.remove = 1;
1217 close(cl->meta_socket);
1223 if(debug_lvl >= DEBUG_CONNECTIONS)
1224 syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1225 cl->name, cl->hostname);
1227 if(cl->status.active)
1229 /* Find all connections that were lost because they were behind cl
1230 (the connection that was dropped). */
1232 for(node = active_tree->head; node; node = next)
1235 p = (connection_t *)node->data;
1236 if(p->nexthop == cl)
1237 terminate_connection(p, report);
1242 /* Inform others of termination if needed */
1245 for(node = connection_tree->head; node; node = node->next)
1247 p = (connection_t *)node->data;
1248 if(p->status.active)
1249 send_del_host(p, cl); /* Sounds like recursion, but p does not have a meta connection :) */
1252 /* Remove the associated subnets */
1254 for(node = cl->subnet_tree->head; node; node = next)
1257 subnet = (subnet_t *)node->data;
1261 /* Check if this was our outgoing connection */
1263 if(cl->status.outgoing)
1265 cl->status.outgoing = 0;
1266 signal(SIGALRM, try_outgoing_connections);
1267 alarm(seconds_till_retry);
1268 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
1271 /* Schedule it for pruning */
1277 Check if the other end is active.
1278 If we have sent packets, but didn't receive any,
1279 then possibly the other end is dead. We send a
1280 PING request over the meta connection. If the other
1281 end does not reply in time, we consider them dead
1282 and close the connection.
1284 void check_dead_connections(void)
1287 avl_node_t *node, *next;
1292 for(node = connection_tree->head; node; node = next)
1295 cl = (connection_t *)node->data;
1296 if(cl->last_ping_time + timeout < now)
1298 if(cl->status.active)
1300 if(cl->status.pinged)
1302 if(debug_lvl >= DEBUG_PROTOCOL)
1303 syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1304 cl->name, cl->hostname);
1305 cl->status.timeout = 1;
1306 terminate_connection(cl, 1);
1315 if(debug_lvl >= DEBUG_CONNECTIONS)
1316 syslog(LOG_WARNING, _("Timeout from %s (%s) during authentication"),
1317 cl->name, cl->hostname);
1318 terminate_connection(cl, 0);
1326 accept a new tcp connect and create a
1329 int handle_new_meta_connection()
1332 struct sockaddr client;
1333 int nfd, len = sizeof(client);
1335 if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
1337 syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1341 if(!(ncn = create_new_connection(nfd)))
1345 syslog(LOG_NOTICE, _("Closed attempted connection"));
1349 connection_add(ncn);
1357 check all connections to see if anything
1358 happened on their sockets
1360 void check_network_activity(fd_set *f)
1365 if(FD_ISSET(myself->socket, f))
1366 handle_incoming_vpn_data();
1368 for(node = connection_tree->head; node; node = node->next)
1370 p = (connection_t *)node->data;
1372 if(p->status.remove)
1375 if(FD_ISSET(p->meta_socket, f))
1376 if(receive_meta(p) < 0)
1378 terminate_connection(p, p->status.active);
1383 if(FD_ISSET(myself->meta_socket, f))
1384 handle_new_meta_connection();
1389 read, encrypt and send data that is
1390 available through the ethertap device
1392 void handle_tap_input(void)
1398 if((lenin = read(tap_fd, vp.data + 14, MTU)) <= 0)
1400 syslog(LOG_ERR, _("Error while reading from tun device: %m"));
1403 memcpy(vp.data, mymac.net.mac.address.x, 6);
1404 memcpy(vp.data + 6, mymac.net.mac.address.x, 6);
1407 vp.len = lenin + 14;
1409 if(taptype == TAP_TYPE_TUNTAP)
1411 if((lenin = read(tap_fd, vp.data, MTU)) <= 0)
1413 syslog(LOG_ERR, _("Error while reading from tun/tap device: %m"));
1420 if((lenin = read(tap_fd, vp.data - 2, MTU)) <= 0)
1422 syslog(LOG_ERR, _("Error while reading from ethertap device: %m"));
1429 total_tap_in += vp.len;
1433 if(debug_lvl >= DEBUG_TRAFFIC)
1434 syslog(LOG_WARNING, _("Received short packet from tap device"));
1438 if(debug_lvl >= DEBUG_TRAFFIC)
1440 syslog(LOG_DEBUG, _("Read packet of length %d from tap device"), vp.len);
1443 route_outgoing(&vp);
1448 this is where it all happens...
1450 void main_loop(void)
1455 time_t last_ping_check;
1458 last_ping_check = time(NULL);
1462 tv.tv_sec = timeout;
1468 if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1470 if(errno != EINTR) /* because of alarm */
1472 syslog(LOG_ERR, _("Error while waiting for input: %m"));
1479 syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1481 close_network_connections();
1482 clear_config(&config);
1484 if(read_server_config())
1486 syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1492 if(setup_network_connections())
1500 /* Let's check if everybody is still alive */
1502 if(last_ping_check + timeout < t)
1504 check_dead_connections();
1505 last_ping_check = time(NULL);
1507 /* Should we regenerate our key? */
1511 if(debug_lvl >= DEBUG_STATUS)
1512 syslog(LOG_INFO, _("Regenerating symmetric key"));
1514 RAND_pseudo_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
1515 send_key_changed(myself, NULL);
1516 keyexpires = time(NULL) + keylifetime;
1522 check_network_activity(&fset);
1524 /* local tap data */
1525 if(FD_ISSET(tap_fd, &fset))