2 net.c -- most of the network code
3 Copyright (C) 1998,1999,2000 Ivo Timmermans <itimmermans@bigfoot.com>,
4 2000 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.61 2000/11/04 13:25:15 zarq Exp $
25 #include <arpa/inet.h>
28 #include <linux/sockios.h>
31 #include <netinet/in.h>
35 #include <sys/signal.h>
36 #include <sys/socket.h>
38 #include <sys/types.h>
41 #include <sys/ioctl.h>
42 #include <openssl/rand.h>
43 #include <openssl/evp.h>
44 #include <openssl/err.h>
47 #include LINUX_IF_TUN_H
64 int taptype = TAP_TYPE_ETHERTAP;
66 int total_tap_out = 0;
67 int total_socket_in = 0;
68 int total_socket_out = 0;
70 config_t *upstreamcfg;
71 static int seconds_till_retry;
77 char *interface_name = NULL; /* Contains the name of the interface */
82 Execute the given script.
83 This function doesn't really belong here.
85 int execute_script(const char* name)
90 extern char **environment; /* From tincd.c; contains our env */
94 asprintf(&scriptname, "%s/%s", confbase, name);
96 if((pid = fork()) < 0)
98 syslog(LOG_ERR, _("System call `%s' failed: %m"),
111 env = xmalloc(sizeof(environment) + 1 * sizeof(char*));
112 while(p = environment, i = 0; *p != NULL; p++)
114 asprintf(&(env[0]), "IFNAME=%s", interface_name);
115 execle(scriptname, NULL, env);
116 /* No return on success */
118 if(errno != ENOENT) /* Ignore if the file does not exist */
119 syslog(LOG_WARNING, _("Error executing `%s': %m"), scriptname);
121 /* No need to free things */
125 int xsend(conn_list_t *cl, vpn_packet_t *inpkt)
131 outpkt.len = inpkt->len;
133 /* Encrypt the packet */
135 EVP_EncryptInit(&ctx, cl->cipher_pkttype, cl->cipher_pktkey, cl->cipher_pktkey + cl->cipher_pkttype->key_len);
136 EVP_EncryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len);
137 EVP_EncryptFinal(&ctx, outpkt.data + outlen, &outpad);
138 outlen += outpad + 2;
141 outlen = outpkt.len + 2;
142 memcpy(&outpkt, inpkt, outlen);
145 if(debug_lvl >= DEBUG_TRAFFIC)
146 syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
147 outlen, cl->name, cl->hostname);
149 total_socket_out += outlen;
153 if((send(cl->socket, (char *) &(outpkt.len), outlen, 0)) < 0)
155 syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
156 cl->name, cl->hostname);
163 int xrecv(vpn_packet_t *inpkt)
169 outpkt.len = inpkt->len;
171 /* Decrypt the packet */
173 EVP_DecryptInit(&ctx, myself->cipher_pkttype, myself->cipher_pktkey, myself->cipher_pktkey + myself->cipher_pkttype->key_len);
174 EVP_DecryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len + 8);
175 EVP_DecryptFinal(&ctx, outpkt.data + outlen, &outpad);
179 outlen = outpkt.len+2;
180 memcpy(&outpkt, inpkt, outlen);
183 if(debug_lvl >= DEBUG_TRAFFIC)
184 syslog(LOG_ERR, _("Writing packet of %d bytes to tap device"),
187 /* Fix mac address */
189 memcpy(outpkt.data, mymac.net.mac.address.x, 6);
191 if(taptype == TAP_TYPE_TUNTAP)
193 if(write(tap_fd, outpkt.data, outpkt.len) < 0)
194 syslog(LOG_ERR, _("Can't write to tun/tap device: %m"));
196 total_tap_out += outpkt.len;
200 if(write(tap_fd, outpkt.data - 2, outpkt.len + 2) < 0)
201 syslog(LOG_ERR, _("Can't write to ethertap device: %m"));
203 total_tap_out += outpkt.len + 2;
210 add the given packet of size s to the
211 queue q, be it the send or receive queue
213 void add_queue(packet_queue_t **q, void *packet, size_t s)
217 e = xmalloc(sizeof(*e));
218 e->packet = xmalloc(s);
219 memcpy(e->packet, packet, s);
223 *q = xmalloc(sizeof(**q));
224 (*q)->head = (*q)->tail = NULL;
227 e->next = NULL; /* We insert at the tail */
229 if((*q)->tail) /* Do we have a tail? */
231 (*q)->tail->next = e;
232 e->prev = (*q)->tail;
234 else /* No tail -> no head too */
244 /* Remove a queue element */
245 void del_queue(packet_queue_t **q, queue_element_t *e)
250 if(e->next) /* There is a successor, so we are not tail */
252 if(e->prev) /* There is a predecessor, so we are not head */
254 e->next->prev = e->prev;
255 e->prev->next = e->next;
257 else /* We are head */
259 e->next->prev = NULL;
260 (*q)->head = e->next;
263 else /* We are tail (or all alone!) */
265 if(e->prev) /* We are not alone :) */
267 e->prev->next = NULL;
268 (*q)->tail = e->prev;
282 flush a queue by calling function for
283 each packet, and removing it when that
284 returned a zero exit code
286 void flush_queue(conn_list_t *cl, packet_queue_t **pq,
287 int (*function)(conn_list_t*,void*))
289 queue_element_t *p, *next = NULL;
291 for(p = (*pq)->head; p != NULL; )
295 if(!function(cl, p->packet))
301 if(debug_lvl >= DEBUG_TRAFFIC)
302 syslog(LOG_DEBUG, _("Queue flushed"));
307 flush the send&recv queues
308 void because nothing goes wrong here, packets
309 remain in the queue if something goes wrong
311 void flush_queues(conn_list_t *cl)
316 if(debug_lvl >= DEBUG_TRAFFIC)
317 syslog(LOG_DEBUG, _("Flushing send queue for %s (%s)"),
318 cl->name, cl->hostname);
319 flush_queue(cl, &(cl->sq), xsend);
324 if(debug_lvl >= DEBUG_TRAFFIC)
325 syslog(LOG_DEBUG, _("Flushing receive queue for %s (%s)"),
326 cl->name, cl->hostname);
327 flush_queue(cl, &(cl->rq), xrecv);
333 send a packet to the given vpn ip.
335 int send_packet(ip_t to, vpn_packet_t *packet)
340 if((subnet = lookup_subnet_ipv4(to)) == NULL)
342 if(debug_lvl >= DEBUG_TRAFFIC)
344 syslog(LOG_NOTICE, _("Trying to look up %d.%d.%d.%d in connection list failed!"),
353 /* If we ourselves have indirectdata flag set, we should send only to our uplink! */
355 /* FIXME - check for indirection and reprogram it The Right Way(tm) this time. */
357 if(!cl->status.dataopen)
358 if(setup_vpn_connection(cl) < 0)
360 syslog(LOG_ERR, _("Could not open UDP connection to %s (%s)"),
361 cl->name, cl->hostname);
365 if(!cl->status.validkey)
367 /* FIXME: Don't queue until everything else is fixed.
368 if(debug_lvl >= DEBUG_TRAFFIC)
369 syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
370 cl->name, cl->hostname);
371 add_queue(&(cl->sq), packet, packet->len + 2);
373 if(!cl->status.waitingforkey)
374 send_req_key(myself, cl); /* Keys should be sent to the host running the tincd */
378 if(!cl->status.active)
380 /* FIXME: Don't queue until everything else is fixed.
381 if(debug_lvl >= DEBUG_TRAFFIC)
382 syslog(LOG_INFO, _("%s (%s) is not ready, queueing packet"),
383 cl->name, cl->hostname);
384 add_queue(&(cl->sq), packet, packet->len + 2);
386 return 0; /* We don't want to mess up, do we? */
389 /* can we send it? can we? can we? huh? */
391 return xsend(cl, packet);
395 open the local ethertap device
397 int setup_tap_fd(void)
400 const char *tapfname;
405 if((cfg = get_config_val(config, tapdevice)))
406 tapfname = cfg->data.ptr;
409 tapfname = "/dev/misc/net/tun";
411 tapfname = "/dev/tap0";
414 if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
416 syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
422 /* Set default MAC address for ethertap devices */
424 taptype = TAP_TYPE_ETHERTAP;
425 mymac.type = SUBNET_MAC;
426 mymac.net.mac.address.x[0] = 0xfe;
427 mymac.net.mac.address.x[1] = 0xfd;
428 mymac.net.mac.address.x[2] = 0x00;
429 mymac.net.mac.address.x[3] = 0x00;
430 mymac.net.mac.address.x[4] = 0x00;
431 mymac.net.mac.address.x[5] = 0x00;
434 /* Ok now check if this is an old ethertap or a new tun/tap thingie */
435 memset(&ifr, 0, sizeof(ifr));
437 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
439 strncpy(ifr.ifr_name, netname, IFNAMSIZ);
441 if (!ioctl(tap_fd, TUNSETIFF, (void *) &ifr))
443 syslog(LOG_INFO, _("%s is a new style tun/tap device"), tapfname);
444 taptype = TAP_TYPE_TUNTAP;
448 /* Add name of network interface to environment (for scripts) */
450 ioctl(tap_fd, SIOCGIFNAME, (void *) &ifr);
451 interface_name = xmalloc(strlen(ifr.ifr_name));
452 strcpy(interface_name, ifr.ifr_name);
459 set up the socket that we listen on for incoming
462 int setup_listen_meta_socket(int port)
465 struct sockaddr_in a;
469 if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
471 syslog(LOG_ERR, _("Creating metasocket failed: %m"));
475 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
477 syslog(LOG_ERR, _("System call `%s' failed: %m"),
482 if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one)))
484 syslog(LOG_ERR, _("System call `%s' failed: %m"),
489 flags = fcntl(nfd, F_GETFL);
490 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
492 syslog(LOG_ERR, _("System call `%s' failed: %m"),
497 if((cfg = get_config_val(config, interface)))
499 if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, cfg->data.ptr, strlen(cfg->data.ptr)))
501 syslog(LOG_ERR, _("Unable to bind listen socket to interface %s: %m"), cfg->data.ptr);
506 memset(&a, 0, sizeof(a));
507 a.sin_family = AF_INET;
508 a.sin_port = htons(port);
510 if((cfg = get_config_val(config, interfaceip)))
511 a.sin_addr.s_addr = htonl(cfg->data.ip->address);
513 a.sin_addr.s_addr = htonl(INADDR_ANY);
515 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
517 syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
523 syslog(LOG_ERR, _("System call `%s' failed: %m"),
532 setup the socket for incoming encrypted
535 int setup_vpn_in_socket(int port)
538 struct sockaddr_in a;
541 if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
543 syslog(LOG_ERR, _("Creating socket failed: %m"));
547 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
549 syslog(LOG_ERR, _("System call `%s' failed: %m"),
554 flags = fcntl(nfd, F_GETFL);
555 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
557 syslog(LOG_ERR, _("System call `%s' failed: %m"),
562 memset(&a, 0, sizeof(a));
563 a.sin_family = AF_INET;
564 a.sin_port = htons(port);
565 a.sin_addr.s_addr = htonl(INADDR_ANY);
567 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
569 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
577 setup an outgoing meta (tcp) socket
579 int setup_outgoing_meta_socket(conn_list_t *cl)
582 struct sockaddr_in a;
585 if(debug_lvl >= DEBUG_CONNECTIONS)
586 syslog(LOG_INFO, _("Trying to connect to %s"), cl->hostname);
588 if((cfg = get_config_val(cl->config, port)) == NULL)
591 cl->port = cfg->data.val;
593 cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
594 if(cl->meta_socket == -1)
596 syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
597 cl->hostname, cl->port);
601 a.sin_family = AF_INET;
602 a.sin_port = htons(cl->port);
603 a.sin_addr.s_addr = htonl(cl->address);
605 if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
607 syslog(LOG_ERR, _("%s port %hd: %m"), cl->hostname, cl->port);
611 flags = fcntl(cl->meta_socket, F_GETFL);
612 if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
614 syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
615 cl->hostname, cl->port);
619 if(debug_lvl >= DEBUG_CONNECTIONS)
620 syslog(LOG_INFO, _("Connected to %s port %hd"),
621 cl->hostname, cl->port);
629 setup an outgoing connection. It's not
630 necessary to also open an udp socket as
631 well, because the other host will initiate
632 an authentication sequence during which
633 we will do just that.
635 int setup_outgoing_connection(char *name)
643 syslog(LOG_ERR, _("Invalid name for outgoing connection"));
647 ncn = new_conn_list();
648 asprintf(&ncn->name, "%s", name);
650 if(read_host_config(ncn))
652 syslog(LOG_ERR, _("Error reading host configuration file for %s"));
657 if(!(cfg = get_config_val(ncn->config, address)))
659 syslog(LOG_ERR, _("No address specified for %s"));
664 if(!(h = gethostbyname(cfg->data.ptr)))
666 syslog(LOG_ERR, _("Error looking up `%s': %m"), cfg->data.ptr);
671 ncn->address = ntohl(*((ip_t*)(h->h_addr_list[0])));
672 ncn->hostname = hostlookup(htonl(ncn->address));
674 if(setup_outgoing_meta_socket(ncn) < 0)
676 syslog(LOG_ERR, _("Could not set up a meta connection to %s"),
682 ncn->status.outgoing = 1;
683 ncn->buffer = xmalloc(MAXBUFSIZE);
685 ncn->last_ping_time = time(NULL);
696 Configure conn_list_t myself and set up the local sockets (listen only)
698 int setup_myself(void)
703 myself = new_conn_list();
705 asprintf(&myself->hostname, "MYSELF"); /* FIXME? Do hostlookup on ourselves? */
707 myself->protocol_version = PROT_CURRENT;
709 if(!(cfg = get_config_val(config, tincname))) /* Not acceptable */
711 syslog(LOG_ERR, _("Name for tinc daemon required!"));
715 asprintf(&myself->name, "%s", (char*)cfg->data.val);
717 if(check_id(myself->name))
719 syslog(LOG_ERR, _("Invalid name for myself!"));
723 if(!(cfg = get_config_val(config, privatekey)))
725 syslog(LOG_ERR, _("Private key for tinc daemon required!"));
730 myself->rsa_key = RSA_new();
731 BN_hex2bn(&myself->rsa_key->d, cfg->data.ptr);
732 BN_hex2bn(&myself->rsa_key->e, "FFFF");
735 if(read_host_config(myself))
737 syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
741 if(!(cfg = get_config_val(myself->config, publickey)))
743 syslog(LOG_ERR, _("Public key for tinc daemon required!"));
748 BN_hex2bn(&myself->rsa_key->n, cfg->data.ptr);
751 if(RSA_check_key(myself->rsa_key) != 1)
753 syslog(LOG_ERR, _("Invalid public/private keypair!"));
757 if(!(cfg = get_config_val(myself->config, port)))
760 myself->port = cfg->data.val;
762 if((cfg = get_config_val(myself->config, indirectdata)))
763 if(cfg->data.val == stupid_true)
764 myself->flags |= EXPORTINDIRECTDATA;
766 if((cfg = get_config_val(myself->config, tcponly)))
767 if(cfg->data.val == stupid_true)
768 myself->flags |= TCPONLY;
770 /* Read in all the subnets specified in the host configuration file */
772 for(cfg = myself->config; (cfg = get_config_val(cfg, subnet)); cfg = cfg->next)
775 net->type = SUBNET_IPV4;
776 net->net.ipv4.address = cfg->data.ip->address;
777 net->net.ipv4.mask = cfg->data.ip->mask;
779 /* Teach newbies what subnets are... */
781 if((net->net.ipv4.address & net->net.ipv4.mask) != net->net.ipv4.address)
783 syslog(LOG_ERR, _("Network address and subnet mask do not match!"));
787 subnet_add(myself, net);
790 if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
792 syslog(LOG_ERR, _("Unable to set up a listening socket!"));
796 if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
798 syslog(LOG_ERR, _("Unable to set up an incoming vpn data socket!"));
799 close(myself->meta_socket);
803 /* Generate packet encryption key */
805 myself->cipher_pkttype = EVP_bf_cfb();
807 myself->cipher_pktkeylength = myself->cipher_pkttype->key_len + myself->cipher_pkttype->iv_len;
809 myself->cipher_pktkey = (char *)xmalloc(myself->cipher_pktkeylength);
810 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
812 if(!(cfg = get_config_val(config, keyexpire)))
815 keylifetime = cfg->data.val;
817 keyexpires = time(NULL) + keylifetime;
819 /* Activate ourselves */
821 myself->status.active = 1;
823 syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
829 sigalrm_handler(int a)
833 cfg = get_config_val(upstreamcfg, connectto);
835 if(!cfg && upstreamcfg == config)
836 /* No upstream IP given, we're listen only. */
841 upstreamcfg = cfg->next;
842 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
844 signal(SIGALRM, SIG_IGN);
847 cfg = get_config_val(upstreamcfg, connectto); /* Or else we try the next ConnectTo line */
850 signal(SIGALRM, sigalrm_handler);
851 upstreamcfg = config;
852 seconds_till_retry += 5;
853 if(seconds_till_retry > MAXTIMEOUT) /* Don't wait more than MAXTIMEOUT seconds. */
854 seconds_till_retry = MAXTIMEOUT;
855 syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
857 alarm(seconds_till_retry);
862 setup all initial network connections
864 int setup_network_connections(void)
868 if((cfg = get_config_val(config, pingtimeout)) == NULL)
871 timeout = cfg->data.val;
873 if(setup_tap_fd() < 0)
876 if(setup_myself() < 0)
879 /* Run tinc-up script to further initialize the tap interface */
880 execute_script("tinc-up");
882 if(!(cfg = get_config_val(config, connectto)))
883 /* No upstream IP given, we're listen only. */
888 upstreamcfg = cfg->next;
889 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
891 cfg = get_config_val(upstreamcfg, connectto); /* Or else we try the next ConnectTo line */
894 signal(SIGALRM, sigalrm_handler);
895 upstreamcfg = config;
896 seconds_till_retry = MAXTIMEOUT;
897 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
898 alarm(seconds_till_retry);
904 close all open network connections
906 void close_network_connections(void)
910 for(p = conn_list; p != NULL; p = p->next)
912 p->status.active = 0;
913 terminate_connection(p);
917 if(myself->status.active)
919 close(myself->meta_socket);
920 close(myself->socket);
921 free_conn_list(myself);
927 /* Execute tinc-down script right after shutting down the interface */
928 execute_script("tinc-down");
932 syslog(LOG_NOTICE, _("Terminating"));
938 create a data (udp) socket
940 int setup_vpn_connection(conn_list_t *cl)
943 struct sockaddr_in a;
945 if(debug_lvl >= DEBUG_TRAFFIC)
946 syslog(LOG_DEBUG, _("Opening UDP socket to %s"), cl->hostname);
948 nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
951 syslog(LOG_ERR, _("Creating UDP socket failed: %m"));
955 a.sin_family = AF_INET;
956 a.sin_port = htons(cl->port);
957 a.sin_addr.s_addr = htonl(cl->address);
959 if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
961 syslog(LOG_ERR, _("Connecting to %s port %d failed: %m"),
962 cl->hostname, cl->port);
966 flags = fcntl(nfd, F_GETFL);
967 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
969 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m %s (%s)"), __FILE__, __LINE__, nfd,
970 cl->name, cl->hostname);
975 cl->status.dataopen = 1;
981 handle an incoming tcp connect call and open
984 conn_list_t *create_new_connection(int sfd)
987 struct sockaddr_in ci;
988 int len = sizeof(ci);
992 if(getpeername(sfd, &ci, &len) < 0)
994 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1000 p->address = ntohl(ci.sin_addr.s_addr);
1001 p->hostname = hostlookup(ci.sin_addr.s_addr);
1002 p->meta_socket = sfd;
1004 p->buffer = xmalloc(MAXBUFSIZE);
1006 p->last_ping_time = time(NULL);
1009 if(debug_lvl >= DEBUG_CONNECTIONS)
1010 syslog(LOG_NOTICE, _("Connection from %s port %d"),
1011 p->hostname, htons(ci.sin_port));
1013 p->allow_request = ID;
1019 put all file descriptors in an fd_set array
1021 void build_fdset(fd_set *fs)
1027 for(p = conn_list; p != NULL; p = p->next)
1030 FD_SET(p->meta_socket, fs);
1031 if(p->status.dataopen)
1032 FD_SET(p->socket, fs);
1035 FD_SET(myself->meta_socket, fs);
1036 FD_SET(myself->socket, fs);
1042 receive incoming data from the listening
1043 udp socket and write it to the ethertap
1044 device after being decrypted
1046 int handle_incoming_vpn_data()
1049 int x, l = sizeof(x);
1050 struct sockaddr from;
1052 socklen_t fromlen = sizeof(from);
1054 if(getsockopt(myself->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1056 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1057 __FILE__, __LINE__, myself->socket);
1062 syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1066 if((lenin = recvfrom(myself->socket, (char *) &(pkt.len), MTU, 0, &from, &fromlen)) <= 0)
1068 syslog(LOG_ERR, _("Receiving packet failed: %m"));
1072 if(debug_lvl >= DEBUG_TRAFFIC)
1074 syslog(LOG_DEBUG, _("Received packet of %d bytes"), lenin);
1082 terminate a connection and notify the other
1083 end before closing the sockets
1085 void terminate_connection(conn_list_t *cl)
1090 if(cl->status.remove)
1093 cl->status.remove = 1;
1095 if(debug_lvl >= DEBUG_CONNECTIONS)
1096 syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1097 cl->name, cl->hostname);
1102 close(cl->meta_socket);
1105 /* Find all connections that were lost because they were behind cl
1106 (the connection that was dropped). */
1109 for(p = conn_list; p != NULL; p = p->next)
1110 if((p->nexthop == cl) && (p != cl))
1111 terminate_connection(p); /* Sounds like recursion, but p does not have a meta connection :) */
1113 /* Inform others of termination if it was still active */
1115 if(cl->status.active)
1116 for(p = conn_list; p != NULL; p = p->next)
1117 if(p->status.meta && p->status.active && p!=cl)
1118 send_del_host(p, cl);
1120 /* Remove the associated subnets */
1122 for(s = cl->subnets; s; s = s->next)
1125 /* Check if this was our outgoing connection */
1127 if(cl->status.outgoing && cl->status.active)
1129 signal(SIGALRM, sigalrm_handler);
1130 seconds_till_retry = 5;
1131 alarm(seconds_till_retry);
1132 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
1137 cl->status.active = 0;
1142 Check if the other end is active.
1143 If we have sent packets, but didn't receive any,
1144 then possibly the other end is dead. We send a
1145 PING request over the meta connection. If the other
1146 end does not reply in time, we consider them dead
1147 and close the connection.
1149 int check_dead_connections(void)
1155 for(p = conn_list; p != NULL; p = p->next)
1157 if(p->status.active && p->status.meta)
1159 if(p->last_ping_time + timeout < now)
1161 if(p->status.pinged && !p->status.got_pong)
1163 if(debug_lvl >= DEBUG_PROTOCOL)
1164 syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1165 p->name, p->hostname);
1166 p->status.timeout = 1;
1167 terminate_connection(p);
1169 else if(p->want_ping)
1172 p->last_ping_time = now;
1173 p->status.pinged = 1;
1174 p->status.got_pong = 0;
1184 accept a new tcp connect and create a
1187 int handle_new_meta_connection()
1190 struct sockaddr client;
1191 int nfd, len = sizeof(client);
1193 if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
1195 syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1199 if(!(ncn = create_new_connection(nfd)))
1203 syslog(LOG_NOTICE, _("Closed attempted connection"));
1213 check all connections to see if anything
1214 happened on their sockets
1216 void check_network_activity(fd_set *f)
1219 int x, l = sizeof(x);
1221 for(p = conn_list; p != NULL; p = p->next)
1223 if(p->status.remove)
1226 if(p->status.dataopen)
1227 if(FD_ISSET(p->socket, f))
1230 The only thing that can happen to get us here is apparently an
1231 error on this outgoing(!) UDP socket that isn't immediate (i.e.
1232 something that will not trigger an error directly on send()).
1233 I've once got here when it said `No route to host'.
1235 getsockopt(p->socket, SOL_SOCKET, SO_ERROR, &x, &l);
1236 syslog(LOG_ERR, _("Outgoing data socket error for %s (%s): %s"),
1237 p->name, p->hostname, strerror(x));
1238 terminate_connection(p);
1243 if(FD_ISSET(p->meta_socket, f))
1244 if(receive_meta(p) < 0)
1246 terminate_connection(p);
1251 if(FD_ISSET(myself->socket, f))
1252 handle_incoming_vpn_data();
1254 if(FD_ISSET(myself->meta_socket, f))
1255 handle_new_meta_connection();
1260 read, encrypt and send data that is
1261 available through the ethertap device
1263 void handle_tap_input(void)
1268 if(taptype == TAP_TYPE_TUNTAP)
1270 if((lenin = read(tap_fd, vp.data, MTU)) <= 0)
1272 syslog(LOG_ERR, _("Error while reading from tun/tap device: %m"));
1279 if((lenin = read(tap_fd, vp.data - 2, MTU)) <= 0)
1281 syslog(LOG_ERR, _("Error while reading from ethertap device: %m"));
1287 total_tap_in += lenin;
1291 if(debug_lvl >= DEBUG_TRAFFIC)
1292 syslog(LOG_WARNING, _("Received short packet from tap device"));
1296 if(debug_lvl >= DEBUG_TRAFFIC)
1298 syslog(LOG_DEBUG, _("Read packet of length %d from tap device"), vp.len);
1301 send_packet(ntohl(*((unsigned long*)(&vp.data[30]))), &vp);
1306 this is where it all happens...
1308 void main_loop(void)
1313 time_t last_ping_check;
1316 last_ping_check = time(NULL);
1320 tv.tv_sec = timeout;
1326 if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1328 if(errno != EINTR) /* because of alarm */
1330 syslog(LOG_ERR, _("Error while waiting for input: %m"));
1337 syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1339 close_network_connections();
1340 clear_config(&config);
1342 if(read_server_config())
1344 syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1350 if(setup_network_connections())
1358 /* Let's check if everybody is still alive */
1360 if(last_ping_check + timeout < t)
1362 check_dead_connections();
1363 last_ping_check = time(NULL);
1365 /* Should we regenerate our key? */
1369 if(debug_lvl >= DEBUG_STATUS)
1370 syslog(LOG_INFO, _("Regenerating symmetric key"));
1372 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
1373 send_key_changed(myself, NULL);
1374 keyexpires = time(NULL) + keylifetime;
1380 check_network_activity(&fset);
1382 /* local tap data */
1383 if(FD_ISSET(tap_fd, &fset))