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.68 2000/11/07 21:43:28 guus 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;
81 Execute the given script.
82 This function doesn't really belong here.
84 int execute_script(const char *name)
90 if((pid = fork()) < 0)
92 syslog(LOG_ERR, _("System call `%s' failed: %m"),
106 asprintf(&s, "NETNAME=%s", netname);
107 putenv(s); /* Don't free s! see man 3 putenv */
114 chdir(confbase); /* This cannot fail since we already read config files from this directory. */
116 asprintf(&scriptname, "%s/%s", confbase, name);
117 execl(scriptname, NULL);
119 /* No return on success */
121 if(errno != ENOENT) /* Ignore if the file does not exist */
122 syslog(LOG_WARNING, _("Error executing `%s': %m"), scriptname);
124 /* No need to free things */
129 int xsend(conn_list_t *cl, vpn_packet_t *inpkt)
135 outpkt.len = inpkt->len;
137 /* Encrypt the packet */
139 EVP_EncryptInit(&ctx, cl->cipher_pkttype, cl->cipher_pktkey, cl->cipher_pktkey + cl->cipher_pkttype->key_len);
140 EVP_EncryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len);
141 EVP_EncryptFinal(&ctx, outpkt.data + outlen, &outpad);
142 outlen += outpad + 2;
145 outlen = outpkt.len + 2;
146 memcpy(&outpkt, inpkt, outlen);
149 if(debug_lvl >= DEBUG_TRAFFIC)
150 syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
151 outlen, cl->name, cl->hostname);
153 total_socket_out += outlen;
155 if((send(cl->socket, (char *) &(outpkt.len), outlen, 0)) < 0)
157 syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
158 cl->name, cl->hostname);
165 int xrecv(conn_list_t *cl, vpn_packet_t *inpkt)
171 outpkt.len = inpkt->len;
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.data, &outlen, inpkt->data, inpkt->len + 8);
177 EVP_DecryptFinal(&ctx, outpkt.data + outlen, &outpad);
181 outlen = outpkt.len+2;
182 memcpy(&outpkt, inpkt, outlen);
185 if(debug_lvl >= DEBUG_TRAFFIC)
186 syslog(LOG_ERR, _("Writing packet of %d bytes to tap device"),
189 /* Fix mac address */
191 memcpy(outpkt.data, mymac.net.mac.address.x, 6);
193 if(taptype == TAP_TYPE_TUNTAP)
195 if(write(tap_fd, outpkt.data, outpkt.len) < 0)
196 syslog(LOG_ERR, _("Can't write to tun/tap device: %m"));
198 total_tap_out += outpkt.len;
202 if(write(tap_fd, outpkt.data - 2, outpkt.len + 2) < 0)
203 syslog(LOG_ERR, _("Can't write to ethertap device: %m"));
205 total_tap_out += outpkt.len + 2;
212 add the given packet of size s to the
213 queue q, be it the send or receive queue
215 void add_queue(packet_queue_t **q, void *packet, size_t s)
219 e = xmalloc(sizeof(*e));
220 e->packet = xmalloc(s);
221 memcpy(e->packet, packet, s);
225 *q = xmalloc(sizeof(**q));
226 (*q)->head = (*q)->tail = NULL;
229 e->next = NULL; /* We insert at the tail */
231 if((*q)->tail) /* Do we have a tail? */
233 (*q)->tail->next = e;
234 e->prev = (*q)->tail;
236 else /* No tail -> no head too */
246 /* Remove a queue element */
247 void del_queue(packet_queue_t **q, queue_element_t *e)
252 if(e->next) /* There is a successor, so we are not tail */
254 if(e->prev) /* There is a predecessor, so we are not head */
256 e->next->prev = e->prev;
257 e->prev->next = e->next;
259 else /* We are head */
261 e->next->prev = NULL;
262 (*q)->head = e->next;
265 else /* We are tail (or all alone!) */
267 if(e->prev) /* We are not alone :) */
269 e->prev->next = NULL;
270 (*q)->tail = e->prev;
284 flush a queue by calling function for
285 each packet, and removing it when that
286 returned a zero exit code
288 void flush_queue(conn_list_t *cl, packet_queue_t **pq,
289 int (*function)(conn_list_t*,vpn_packet_t*))
291 queue_element_t *p, *next = NULL;
293 for(p = (*pq)->head; p != NULL; )
297 if(!function(cl, p->packet))
303 if(debug_lvl >= DEBUG_TRAFFIC)
304 syslog(LOG_DEBUG, _("Queue flushed"));
309 flush the send&recv queues
310 void because nothing goes wrong here, packets
311 remain in the queue if something goes wrong
313 void flush_queues(conn_list_t *cl)
318 if(debug_lvl >= DEBUG_TRAFFIC)
319 syslog(LOG_DEBUG, _("Flushing send queue for %s (%s)"),
320 cl->name, cl->hostname);
321 flush_queue(cl, &(cl->sq), xsend);
326 if(debug_lvl >= DEBUG_TRAFFIC)
327 syslog(LOG_DEBUG, _("Flushing receive queue for %s (%s)"),
328 cl->name, cl->hostname);
329 flush_queue(cl, &(cl->rq), xrecv);
335 send a packet to the given vpn ip.
337 int send_packet(ip_t to, vpn_packet_t *packet)
342 if((subnet = lookup_subnet_ipv4(to)) == NULL)
344 if(debug_lvl >= DEBUG_TRAFFIC)
346 syslog(LOG_NOTICE, _("Trying to look up %d.%d.%d.%d in connection list failed!"),
357 if(debug_lvl >= DEBUG_TRAFFIC)
359 syslog(LOG_NOTICE, _("Packet with destination %d.%d.%d.%d is looping back to us!"),
366 /* If we ourselves have indirectdata flag set, we should send only to our uplink! */
368 /* FIXME - check for indirection and reprogram it The Right Way(tm) this time. */
370 /* Connections are now opened beforehand...
372 if(!cl->status.dataopen)
373 if(setup_vpn_connection(cl) < 0)
375 syslog(LOG_ERR, _("Could not open UDP connection to %s (%s)"),
376 cl->name, cl->hostname);
381 if(!cl->status.validkey)
383 /* FIXME: Don't queue until everything else is fixed.
384 if(debug_lvl >= DEBUG_TRAFFIC)
385 syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
386 cl->name, cl->hostname);
387 add_queue(&(cl->sq), packet, packet->len + 2);
389 if(!cl->status.waitingforkey)
390 send_req_key(myself, cl); /* Keys should be sent to the host running the tincd */
394 if(!cl->status.active)
396 /* FIXME: Don't queue until everything else is fixed.
397 if(debug_lvl >= DEBUG_TRAFFIC)
398 syslog(LOG_INFO, _("%s (%s) is not ready, queueing packet"),
399 cl->name, cl->hostname);
400 add_queue(&(cl->sq), packet, packet->len + 2);
402 return 0; /* We don't want to mess up, do we? */
405 /* can we send it? can we? can we? huh? */
407 return xsend(cl, packet);
411 open the local ethertap device
413 int setup_tap_fd(void)
416 const char *tapfname;
421 if((cfg = get_config_val(config, config_tapdevice)))
422 tapfname = cfg->data.ptr;
425 tapfname = "/dev/misc/net/tun";
427 tapfname = "/dev/tap0";
430 if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
432 syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
438 /* Set default MAC address for ethertap devices */
440 taptype = TAP_TYPE_ETHERTAP;
441 mymac.type = SUBNET_MAC;
442 mymac.net.mac.address.x[0] = 0xfe;
443 mymac.net.mac.address.x[1] = 0xfd;
444 mymac.net.mac.address.x[2] = 0x00;
445 mymac.net.mac.address.x[3] = 0x00;
446 mymac.net.mac.address.x[4] = 0x00;
447 mymac.net.mac.address.x[5] = 0x00;
450 /* Ok now check if this is an old ethertap or a new tun/tap thingie */
451 memset(&ifr, 0, sizeof(ifr));
453 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
455 strncpy(ifr.ifr_name, netname, IFNAMSIZ);
457 if (!ioctl(tap_fd, TUNSETIFF, (void *) &ifr))
459 syslog(LOG_INFO, _("%s is a new style tun/tap device"), tapfname);
460 taptype = TAP_TYPE_TUNTAP;
468 set up the socket that we listen on for incoming
471 int setup_listen_meta_socket(int port)
474 struct sockaddr_in a;
478 if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
480 syslog(LOG_ERR, _("Creating metasocket failed: %m"));
484 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
486 syslog(LOG_ERR, _("System call `%s' failed: %m"),
491 if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one)))
493 syslog(LOG_ERR, _("System call `%s' failed: %m"),
498 flags = fcntl(nfd, F_GETFL);
499 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
501 syslog(LOG_ERR, _("System call `%s' failed: %m"),
506 if((cfg = get_config_val(config, config_interface)))
508 if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, cfg->data.ptr, strlen(cfg->data.ptr)))
510 syslog(LOG_ERR, _("Unable to bind listen socket to interface %s: %m"), cfg->data.ptr);
515 memset(&a, 0, sizeof(a));
516 a.sin_family = AF_INET;
517 a.sin_port = htons(port);
519 if((cfg = get_config_val(config, config_interfaceip)))
520 a.sin_addr.s_addr = htonl(cfg->data.ip->address);
522 a.sin_addr.s_addr = htonl(INADDR_ANY);
524 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
526 syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
532 syslog(LOG_ERR, _("System call `%s' failed: %m"),
541 setup the socket for incoming encrypted
544 int setup_vpn_in_socket(int port)
547 struct sockaddr_in a;
550 if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
552 syslog(LOG_ERR, _("Creating socket failed: %m"));
556 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
558 syslog(LOG_ERR, _("System call `%s' failed: %m"),
563 flags = fcntl(nfd, F_GETFL);
564 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
566 syslog(LOG_ERR, _("System call `%s' failed: %m"),
571 memset(&a, 0, sizeof(a));
572 a.sin_family = AF_INET;
573 a.sin_port = htons(port);
574 a.sin_addr.s_addr = htonl(INADDR_ANY);
576 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
578 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
586 setup an outgoing meta (tcp) socket
588 int setup_outgoing_meta_socket(conn_list_t *cl)
591 struct sockaddr_in a;
594 if(debug_lvl >= DEBUG_CONNECTIONS)
595 syslog(LOG_INFO, _("Trying to connect to %s"), cl->hostname);
597 if((cfg = get_config_val(cl->config, config_port)) == NULL)
600 cl->port = cfg->data.val;
602 cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
603 if(cl->meta_socket == -1)
605 syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
606 cl->hostname, cl->port);
610 a.sin_family = AF_INET;
611 a.sin_port = htons(cl->port);
612 a.sin_addr.s_addr = htonl(cl->address);
614 if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
616 syslog(LOG_ERR, _("%s port %hd: %m"), cl->hostname, cl->port);
620 flags = fcntl(cl->meta_socket, F_GETFL);
621 if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
623 syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
624 cl->hostname, cl->port);
628 if(debug_lvl >= DEBUG_CONNECTIONS)
629 syslog(LOG_INFO, _("Connected to %s port %hd"),
630 cl->hostname, cl->port);
638 setup an outgoing connection. It's not
639 necessary to also open an udp socket as
640 well, because the other host will initiate
641 an authentication sequence during which
642 we will do just that.
644 int setup_outgoing_connection(char *name)
652 syslog(LOG_ERR, _("Invalid name for outgoing connection"));
656 ncn = new_conn_list();
657 asprintf(&ncn->name, "%s", name);
659 if(read_host_config(ncn))
661 syslog(LOG_ERR, _("Error reading host configuration file for %s"));
666 if(!(cfg = get_config_val(ncn->config, config_address)))
668 syslog(LOG_ERR, _("No address specified for %s"));
673 if(!(h = gethostbyname(cfg->data.ptr)))
675 syslog(LOG_ERR, _("Error looking up `%s': %m"), cfg->data.ptr);
680 ncn->address = ntohl(*((ip_t*)(h->h_addr_list[0])));
681 ncn->hostname = hostlookup(htonl(ncn->address));
683 if(setup_outgoing_meta_socket(ncn) < 0)
685 syslog(LOG_ERR, _("Could not set up a meta connection to %s"),
691 ncn->status.outgoing = 1;
692 ncn->buffer = xmalloc(MAXBUFSIZE);
694 ncn->last_ping_time = time(NULL);
704 Configure conn_list_t myself and set up the local sockets (listen only)
706 int setup_myself(void)
712 myself = new_conn_list();
714 asprintf(&myself->hostname, "MYSELF"); /* FIXME? Do hostlookup on ourselves? */
716 myself->protocol_version = PROT_CURRENT;
718 if(!(cfg = get_config_val(config, config_name))) /* Not acceptable */
720 syslog(LOG_ERR, _("Name for tinc daemon required!"));
724 asprintf(&myself->name, "%s", (char*)cfg->data.val);
726 if(check_id(myself->name))
728 syslog(LOG_ERR, _("Invalid name for myself!"));
732 if(!(cfg = get_config_val(config, config_privatekey)))
734 syslog(LOG_ERR, _("Private key for tinc daemon required!"));
739 myself->rsa_key = RSA_new();
740 BN_hex2bn(&myself->rsa_key->d, cfg->data.ptr);
741 BN_hex2bn(&myself->rsa_key->e, "FFFF");
744 if(read_host_config(myself))
746 syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
750 if(!(cfg = get_config_val(myself->config, config_publickey)))
752 syslog(LOG_ERR, _("Public key for tinc daemon required!"));
757 BN_hex2bn(&myself->rsa_key->n, cfg->data.ptr);
760 if(RSA_check_key(myself->rsa_key) != 1)
762 syslog(LOG_ERR, _("Invalid public/private keypair!"));
766 if(!(cfg = get_config_val(myself->config, config_port)))
769 myself->port = cfg->data.val;
771 if((cfg = get_config_val(myself->config, config_indirectdata)))
772 if(cfg->data.val == stupid_true)
773 myself->flags |= EXPORTINDIRECTDATA;
775 if((cfg = get_config_val(myself->config, config_tcponly)))
776 if(cfg->data.val == stupid_true)
777 myself->flags |= TCPONLY;
779 /* Read in all the subnets specified in the host configuration file */
781 for(next = myself->config; (cfg = get_config_val(next, config_subnet)); next = cfg->next)
784 net->type = SUBNET_IPV4;
785 net->net.ipv4.address = cfg->data.ip->address;
786 net->net.ipv4.mask = cfg->data.ip->mask;
788 /* Teach newbies what subnets are... */
790 if((net->net.ipv4.address & net->net.ipv4.mask) != net->net.ipv4.address)
792 syslog(LOG_ERR, _("Network address and subnet mask do not match!"));
796 subnet_add(myself, net);
799 if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
801 syslog(LOG_ERR, _("Unable to set up a listening socket!"));
805 /* Generate packet encryption key */
807 myself->cipher_pkttype = EVP_bf_cfb();
809 myself->cipher_pktkeylength = myself->cipher_pkttype->key_len + myself->cipher_pkttype->iv_len;
811 myself->cipher_pktkey = (char *)xmalloc(myself->cipher_pktkeylength);
812 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
814 if(!(cfg = get_config_val(config, config_keyexpire)))
817 keylifetime = cfg->data.val;
819 keyexpires = time(NULL) + keylifetime;
821 /* Activate ourselves */
823 myself->status.active = 1;
825 syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
831 sigalrm_handler(int a)
835 cfg = get_config_val(upstreamcfg, config_connectto);
837 if(!cfg && upstreamcfg == config)
838 /* No upstream IP given, we're listen only. */
843 upstreamcfg = cfg->next;
844 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
846 signal(SIGALRM, SIG_IGN);
849 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
852 signal(SIGALRM, sigalrm_handler);
853 upstreamcfg = config;
854 seconds_till_retry += 5;
855 if(seconds_till_retry > MAXTIMEOUT) /* Don't wait more than MAXTIMEOUT seconds. */
856 seconds_till_retry = MAXTIMEOUT;
857 syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
859 alarm(seconds_till_retry);
864 setup all initial network connections
866 int setup_network_connections(void)
870 if((cfg = get_config_val(config, config_pingtimeout)) == NULL)
874 timeout = cfg->data.val;
881 if(setup_tap_fd() < 0)
884 if(setup_myself() < 0)
887 /* Run tinc-up script to further initialize the tap interface */
888 execute_script("tinc-up");
890 if(!(cfg = get_config_val(config, config_connectto)))
891 /* No upstream IP given, we're listen only. */
896 upstreamcfg = cfg->next;
897 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
899 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
902 signal(SIGALRM, sigalrm_handler);
903 upstreamcfg = config;
904 seconds_till_retry = MAXTIMEOUT;
905 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
906 alarm(seconds_till_retry);
912 close all open network connections
914 void close_network_connections(void)
918 for(p = conn_list; p != NULL; p = p->next)
920 p->status.active = 0;
921 terminate_connection(p);
925 if(myself->status.active)
927 close(myself->meta_socket);
928 free_conn_list(myself);
934 /* Execute tinc-down script right after shutting down the interface */
935 execute_script("tinc-down");
939 syslog(LOG_NOTICE, _("Terminating"));
945 create a data (udp) socket
947 int setup_vpn_connection(conn_list_t *cl)
950 struct sockaddr_in a;
953 if(debug_lvl >= DEBUG_TRAFFIC)
954 syslog(LOG_DEBUG, _("Opening UDP socket to %s"), cl->hostname);
956 nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
959 syslog(LOG_ERR, _("Creating UDP socket failed: %m"));
963 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
965 syslog(LOG_ERR, _("System call `%s' failed: %m"),
970 flags = fcntl(nfd, F_GETFL);
971 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
973 syslog(LOG_ERR, _("System call `%s' failed: %m"),
978 memset(&a, 0, sizeof(a));
979 a.sin_family = AF_INET;
980 a.sin_port = htons(myself->port);
981 a.sin_addr.s_addr = htonl(INADDR_ANY);
983 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
985 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), myself->port);
989 a.sin_family = AF_INET;
990 a.sin_port = htons(cl->port);
991 a.sin_addr.s_addr = htonl(cl->address);
993 if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
995 syslog(LOG_ERR, _("Connecting to %s port %d failed: %m"),
996 cl->hostname, cl->port);
1000 flags = fcntl(nfd, F_GETFL);
1001 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
1003 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m %s (%s)"), __FILE__, __LINE__, nfd,
1004 cl->name, cl->hostname);
1009 cl->status.dataopen = 1;
1015 handle an incoming tcp connect call and open
1018 conn_list_t *create_new_connection(int sfd)
1021 struct sockaddr_in ci;
1022 int len = sizeof(ci);
1024 p = new_conn_list();
1026 if(getpeername(sfd, &ci, &len) < 0)
1028 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1034 p->address = ntohl(ci.sin_addr.s_addr);
1035 p->hostname = hostlookup(ci.sin_addr.s_addr);
1036 p->meta_socket = sfd;
1038 p->buffer = xmalloc(MAXBUFSIZE);
1040 p->last_ping_time = time(NULL);
1042 if(debug_lvl >= DEBUG_CONNECTIONS)
1043 syslog(LOG_NOTICE, _("Connection from %s port %d"),
1044 p->hostname, htons(ci.sin_port));
1046 p->allow_request = ID;
1052 put all file descriptors in an fd_set array
1054 void build_fdset(fd_set *fs)
1060 for(p = conn_list; p != NULL; p = p->next)
1063 FD_SET(p->meta_socket, fs);
1064 if(p->status.dataopen)
1065 FD_SET(p->socket, fs);
1068 FD_SET(myself->meta_socket, fs);
1074 receive incoming data from the listening
1075 udp socket and write it to the ethertap
1076 device after being decrypted
1078 int handle_incoming_vpn_data(conn_list_t *cl)
1081 int x, l = sizeof(x);
1084 if(getsockopt(cl->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1086 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1087 __FILE__, __LINE__, cl->socket);
1092 syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1096 if((lenin = recv(cl->socket, (char *) &(pkt.len), MTU, 0)) <= 0)
1098 syslog(LOG_ERR, _("Receiving packet failed: %m"));
1102 if(debug_lvl >= DEBUG_TRAFFIC)
1104 syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"), lenin,
1105 cl->name, cl->hostname);
1109 return xrecv(cl, &pkt);
1113 terminate a connection and notify the other
1114 end before closing the sockets
1116 void terminate_connection(conn_list_t *cl)
1121 if(cl->status.remove)
1124 cl->status.remove = 1;
1126 if(debug_lvl >= DEBUG_CONNECTIONS)
1127 syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1128 cl->name, cl->hostname);
1133 close(cl->meta_socket);
1136 /* Find all connections that were lost because they were behind cl
1137 (the connection that was dropped). */
1140 for(p = conn_list; p != NULL; p = p->next)
1141 if((p->nexthop == cl) && (p != cl))
1142 terminate_connection(p); /* Sounds like recursion, but p does not have a meta connection :) */
1144 /* Inform others of termination if it was still active */
1146 if(cl->status.active)
1147 for(p = conn_list; p != NULL; p = p->next)
1148 if(p->status.meta && p->status.active && p!=cl)
1149 send_del_host(p, cl);
1151 /* Remove the associated subnets */
1153 for(s = cl->subnets; s; s = s->next)
1156 /* Check if this was our outgoing connection */
1158 if(cl->status.outgoing && cl->status.active)
1160 signal(SIGALRM, sigalrm_handler);
1161 seconds_till_retry = 5;
1162 alarm(seconds_till_retry);
1163 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
1168 cl->status.active = 0;
1173 Check if the other end is active.
1174 If we have sent packets, but didn't receive any,
1175 then possibly the other end is dead. We send a
1176 PING request over the meta connection. If the other
1177 end does not reply in time, we consider them dead
1178 and close the connection.
1180 int check_dead_connections(void)
1186 for(p = conn_list; p != NULL; p = p->next)
1188 if(p->status.active && p->status.meta)
1190 if(p->last_ping_time + timeout < now)
1192 if(p->status.pinged)
1194 if(debug_lvl >= DEBUG_PROTOCOL)
1195 syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1196 p->name, p->hostname);
1197 p->status.timeout = 1;
1198 terminate_connection(p);
1212 accept a new tcp connect and create a
1215 int handle_new_meta_connection()
1218 struct sockaddr client;
1219 int nfd, len = sizeof(client);
1221 if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
1223 syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1227 if(!(ncn = create_new_connection(nfd)))
1231 syslog(LOG_NOTICE, _("Closed attempted connection"));
1241 check all connections to see if anything
1242 happened on their sockets
1244 void check_network_activity(fd_set *f)
1248 for(p = conn_list; p != NULL; p = p->next)
1250 if(p->status.remove)
1253 if(p->status.dataopen)
1254 if(FD_ISSET(p->socket, f))
1256 handle_incoming_vpn_data(p);
1258 /* Old error stuff (FIXME: copy this to handle_incoming_vpn_data()
1260 getsockopt(p->socket, SOL_SOCKET, SO_ERROR, &x, &l);
1261 syslog(LOG_ERR, _("Outgoing data socket error for %s (%s): %s"),
1262 p->name, p->hostname, strerror(x));
1263 terminate_connection(p);
1269 if(FD_ISSET(p->meta_socket, f))
1270 if(receive_meta(p) < 0)
1272 terminate_connection(p);
1277 if(FD_ISSET(myself->meta_socket, f))
1278 handle_new_meta_connection();
1283 read, encrypt and send data that is
1284 available through the ethertap device
1286 void handle_tap_input(void)
1291 if(taptype == TAP_TYPE_TUNTAP)
1293 if((lenin = read(tap_fd, vp.data, MTU)) <= 0)
1295 syslog(LOG_ERR, _("Error while reading from tun/tap device: %m"));
1302 if((lenin = read(tap_fd, vp.data - 2, MTU)) <= 0)
1304 syslog(LOG_ERR, _("Error while reading from ethertap device: %m"));
1310 total_tap_in += lenin;
1314 if(debug_lvl >= DEBUG_TRAFFIC)
1315 syslog(LOG_WARNING, _("Received short packet from tap device"));
1319 if(debug_lvl >= DEBUG_TRAFFIC)
1321 syslog(LOG_DEBUG, _("Read packet of length %d from tap device"), vp.len);
1324 send_packet(ntohl(*((unsigned long*)(&vp.data[30]))), &vp);
1329 this is where it all happens...
1331 void main_loop(void)
1336 time_t last_ping_check;
1339 last_ping_check = time(NULL);
1343 tv.tv_sec = timeout;
1349 if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1351 if(errno != EINTR) /* because of alarm */
1353 syslog(LOG_ERR, _("Error while waiting for input: %m"));
1360 syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1362 close_network_connections();
1363 clear_config(&config);
1365 if(read_server_config())
1367 syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1373 if(setup_network_connections())
1381 /* Let's check if everybody is still alive */
1383 if(last_ping_check + timeout < t)
1385 check_dead_connections();
1386 last_ping_check = time(NULL);
1388 /* Should we regenerate our key? */
1392 if(debug_lvl >= DEBUG_STATUS)
1393 syslog(LOG_INFO, _("Regenerating symmetric key"));
1395 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
1396 send_key_changed(myself, NULL);
1397 keyexpires = time(NULL) + keylifetime;
1403 check_network_activity(&fset);
1405 /* local tap data */
1406 if(FD_ISSET(tap_fd, &fset))