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.69 2000/11/08 00:10:49 guus Exp $
25 #include <arpa/inet.h>
28 /* SunOS really wants sys/socket.h BEFORE net/if.h */
29 #include <sys/socket.h>
32 #include <netinet/in.h>
36 #include <sys/signal.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 */
116 chdir(confbase); /* This cannot fail since we already read config files from this directory. */
118 asprintf(&scriptname, "%s/%s", confbase, name);
119 execl(scriptname, NULL);
121 /* No return on success */
123 if(errno != ENOENT) /* Ignore if the file does not exist */
124 syslog(LOG_WARNING, _("Error executing `%s': %m"), scriptname);
126 /* No need to free things */
131 int xsend(conn_list_t *cl, vpn_packet_t *inpkt)
137 outpkt.len = inpkt->len;
139 /* Encrypt the packet */
141 EVP_EncryptInit(&ctx, cl->cipher_pkttype, cl->cipher_pktkey, cl->cipher_pktkey + cl->cipher_pkttype->key_len);
142 EVP_EncryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len);
143 EVP_EncryptFinal(&ctx, outpkt.data + outlen, &outpad);
144 outlen += outpad + 2;
147 outlen = outpkt.len + 2;
148 memcpy(&outpkt, inpkt, outlen);
151 if(debug_lvl >= DEBUG_TRAFFIC)
152 syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
153 outlen, cl->name, cl->hostname);
155 total_socket_out += outlen;
157 if((send(cl->socket, (char *) &(outpkt.len), outlen, 0)) < 0)
159 syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
160 cl->name, cl->hostname);
167 int xrecv(conn_list_t *cl, vpn_packet_t *inpkt)
173 outpkt.len = inpkt->len;
175 /* Decrypt the packet */
177 EVP_DecryptInit(&ctx, myself->cipher_pkttype, myself->cipher_pktkey, myself->cipher_pktkey + myself->cipher_pkttype->key_len);
178 EVP_DecryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len + 8);
179 EVP_DecryptFinal(&ctx, outpkt.data + outlen, &outpad);
183 outlen = outpkt.len+2;
184 memcpy(&outpkt, inpkt, outlen);
187 if(debug_lvl >= DEBUG_TRAFFIC)
188 syslog(LOG_ERR, _("Writing packet of %d bytes to tap device"),
191 /* Fix mac address */
193 memcpy(outpkt.data, mymac.net.mac.address.x, 6);
195 if(taptype == TAP_TYPE_TUNTAP)
197 if(write(tap_fd, outpkt.data, outpkt.len) < 0)
198 syslog(LOG_ERR, _("Can't write to tun/tap device: %m"));
200 total_tap_out += outpkt.len;
204 if(write(tap_fd, outpkt.data - 2, outpkt.len + 2) < 0)
205 syslog(LOG_ERR, _("Can't write to ethertap device: %m"));
207 total_tap_out += outpkt.len + 2;
214 add the given packet of size s to the
215 queue q, be it the send or receive queue
217 void add_queue(packet_queue_t **q, void *packet, size_t s)
221 e = xmalloc(sizeof(*e));
222 e->packet = xmalloc(s);
223 memcpy(e->packet, packet, s);
227 *q = xmalloc(sizeof(**q));
228 (*q)->head = (*q)->tail = NULL;
231 e->next = NULL; /* We insert at the tail */
233 if((*q)->tail) /* Do we have a tail? */
235 (*q)->tail->next = e;
236 e->prev = (*q)->tail;
238 else /* No tail -> no head too */
248 /* Remove a queue element */
249 void del_queue(packet_queue_t **q, queue_element_t *e)
254 if(e->next) /* There is a successor, so we are not tail */
256 if(e->prev) /* There is a predecessor, so we are not head */
258 e->next->prev = e->prev;
259 e->prev->next = e->next;
261 else /* We are head */
263 e->next->prev = NULL;
264 (*q)->head = e->next;
267 else /* We are tail (or all alone!) */
269 if(e->prev) /* We are not alone :) */
271 e->prev->next = NULL;
272 (*q)->tail = e->prev;
286 flush a queue by calling function for
287 each packet, and removing it when that
288 returned a zero exit code
290 void flush_queue(conn_list_t *cl, packet_queue_t **pq,
291 int (*function)(conn_list_t*,vpn_packet_t*))
293 queue_element_t *p, *next = NULL;
295 for(p = (*pq)->head; p != NULL; )
299 if(!function(cl, p->packet))
305 if(debug_lvl >= DEBUG_TRAFFIC)
306 syslog(LOG_DEBUG, _("Queue flushed"));
311 flush the send&recv queues
312 void because nothing goes wrong here, packets
313 remain in the queue if something goes wrong
315 void flush_queues(conn_list_t *cl)
320 if(debug_lvl >= DEBUG_TRAFFIC)
321 syslog(LOG_DEBUG, _("Flushing send queue for %s (%s)"),
322 cl->name, cl->hostname);
323 flush_queue(cl, &(cl->sq), xsend);
328 if(debug_lvl >= DEBUG_TRAFFIC)
329 syslog(LOG_DEBUG, _("Flushing receive queue for %s (%s)"),
330 cl->name, cl->hostname);
331 flush_queue(cl, &(cl->rq), xrecv);
337 send a packet to the given vpn ip.
339 int send_packet(ip_t to, vpn_packet_t *packet)
344 if((subnet = lookup_subnet_ipv4(to)) == NULL)
346 if(debug_lvl >= DEBUG_TRAFFIC)
348 syslog(LOG_NOTICE, _("Trying to look up %d.%d.%d.%d in connection list failed!"),
359 if(debug_lvl >= DEBUG_TRAFFIC)
361 syslog(LOG_NOTICE, _("Packet with destination %d.%d.%d.%d is looping back to us!"),
368 /* If we ourselves have indirectdata flag set, we should send only to our uplink! */
370 /* FIXME - check for indirection and reprogram it The Right Way(tm) this time. */
372 /* Connections are now opened beforehand...
374 if(!cl->status.dataopen)
375 if(setup_vpn_connection(cl) < 0)
377 syslog(LOG_ERR, _("Could not open UDP connection to %s (%s)"),
378 cl->name, cl->hostname);
383 if(!cl->status.validkey)
385 /* FIXME: Don't queue until everything else is fixed.
386 if(debug_lvl >= DEBUG_TRAFFIC)
387 syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
388 cl->name, cl->hostname);
389 add_queue(&(cl->sq), packet, packet->len + 2);
391 if(!cl->status.waitingforkey)
392 send_req_key(myself, cl); /* Keys should be sent to the host running the tincd */
396 if(!cl->status.active)
398 /* FIXME: Don't queue until everything else is fixed.
399 if(debug_lvl >= DEBUG_TRAFFIC)
400 syslog(LOG_INFO, _("%s (%s) is not ready, queueing packet"),
401 cl->name, cl->hostname);
402 add_queue(&(cl->sq), packet, packet->len + 2);
404 return 0; /* We don't want to mess up, do we? */
407 /* can we send it? can we? can we? huh? */
409 return xsend(cl, packet);
413 open the local ethertap device
415 int setup_tap_fd(void)
418 const char *tapfname;
423 if((cfg = get_config_val(config, config_tapdevice)))
424 tapfname = cfg->data.ptr;
427 tapfname = "/dev/misc/net/tun";
429 tapfname = "/dev/tap0";
432 if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
434 syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
440 /* Set default MAC address for ethertap devices */
442 taptype = TAP_TYPE_ETHERTAP;
443 mymac.type = SUBNET_MAC;
444 mymac.net.mac.address.x[0] = 0xfe;
445 mymac.net.mac.address.x[1] = 0xfd;
446 mymac.net.mac.address.x[2] = 0x00;
447 mymac.net.mac.address.x[3] = 0x00;
448 mymac.net.mac.address.x[4] = 0x00;
449 mymac.net.mac.address.x[5] = 0x00;
452 /* Ok now check if this is an old ethertap or a new tun/tap thingie */
453 memset(&ifr, 0, sizeof(ifr));
455 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
457 strncpy(ifr.ifr_name, netname, IFNAMSIZ);
459 if (!ioctl(tap_fd, TUNSETIFF, (void *) &ifr))
461 syslog(LOG_INFO, _("%s is a new style tun/tap device"), tapfname);
462 taptype = TAP_TYPE_TUNTAP;
470 set up the socket that we listen on for incoming
473 int setup_listen_meta_socket(int port)
476 struct sockaddr_in a;
480 if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
482 syslog(LOG_ERR, _("Creating metasocket failed: %m"));
486 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
488 syslog(LOG_ERR, _("System call `%s' failed: %m"),
493 if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one)))
495 syslog(LOG_ERR, _("System call `%s' failed: %m"),
500 flags = fcntl(nfd, F_GETFL);
501 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
503 syslog(LOG_ERR, _("System call `%s' failed: %m"),
508 if((cfg = get_config_val(config, config_interface)))
510 if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, cfg->data.ptr, strlen(cfg->data.ptr)))
512 syslog(LOG_ERR, _("Unable to bind listen socket to interface %s: %m"), cfg->data.ptr);
517 memset(&a, 0, sizeof(a));
518 a.sin_family = AF_INET;
519 a.sin_port = htons(port);
521 if((cfg = get_config_val(config, config_interfaceip)))
522 a.sin_addr.s_addr = htonl(cfg->data.ip->address);
524 a.sin_addr.s_addr = htonl(INADDR_ANY);
526 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
528 syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
534 syslog(LOG_ERR, _("System call `%s' failed: %m"),
543 setup the socket for incoming encrypted
546 int setup_vpn_in_socket(int port)
549 struct sockaddr_in a;
552 if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
554 syslog(LOG_ERR, _("Creating socket failed: %m"));
558 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
560 syslog(LOG_ERR, _("System call `%s' failed: %m"),
565 flags = fcntl(nfd, F_GETFL);
566 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
568 syslog(LOG_ERR, _("System call `%s' failed: %m"),
573 memset(&a, 0, sizeof(a));
574 a.sin_family = AF_INET;
575 a.sin_port = htons(port);
576 a.sin_addr.s_addr = htonl(INADDR_ANY);
578 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
580 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
588 setup an outgoing meta (tcp) socket
590 int setup_outgoing_meta_socket(conn_list_t *cl)
593 struct sockaddr_in a;
596 if(debug_lvl >= DEBUG_CONNECTIONS)
597 syslog(LOG_INFO, _("Trying to connect to %s"), cl->hostname);
599 if((cfg = get_config_val(cl->config, config_port)) == NULL)
602 cl->port = cfg->data.val;
604 cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
605 if(cl->meta_socket == -1)
607 syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
608 cl->hostname, cl->port);
612 a.sin_family = AF_INET;
613 a.sin_port = htons(cl->port);
614 a.sin_addr.s_addr = htonl(cl->address);
616 if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
618 syslog(LOG_ERR, _("%s port %hd: %m"), cl->hostname, cl->port);
622 flags = fcntl(cl->meta_socket, F_GETFL);
623 if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
625 syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
626 cl->hostname, cl->port);
630 if(debug_lvl >= DEBUG_CONNECTIONS)
631 syslog(LOG_INFO, _("Connected to %s port %hd"),
632 cl->hostname, cl->port);
640 setup an outgoing connection. It's not
641 necessary to also open an udp socket as
642 well, because the other host will initiate
643 an authentication sequence during which
644 we will do just that.
646 int setup_outgoing_connection(char *name)
654 syslog(LOG_ERR, _("Invalid name for outgoing connection"));
658 ncn = new_conn_list();
659 asprintf(&ncn->name, "%s", name);
661 if(read_host_config(ncn))
663 syslog(LOG_ERR, _("Error reading host configuration file for %s"));
668 if(!(cfg = get_config_val(ncn->config, config_address)))
670 syslog(LOG_ERR, _("No address specified for %s"));
675 if(!(h = gethostbyname(cfg->data.ptr)))
677 syslog(LOG_ERR, _("Error looking up `%s': %m"), cfg->data.ptr);
682 ncn->address = ntohl(*((ip_t*)(h->h_addr_list[0])));
683 ncn->hostname = hostlookup(htonl(ncn->address));
685 if(setup_outgoing_meta_socket(ncn) < 0)
687 syslog(LOG_ERR, _("Could not set up a meta connection to %s"),
693 ncn->status.outgoing = 1;
694 ncn->buffer = xmalloc(MAXBUFSIZE);
696 ncn->last_ping_time = time(NULL);
706 Configure conn_list_t myself and set up the local sockets (listen only)
708 int setup_myself(void)
714 myself = new_conn_list();
716 asprintf(&myself->hostname, "MYSELF"); /* FIXME? Do hostlookup on ourselves? */
718 myself->protocol_version = PROT_CURRENT;
720 if(!(cfg = get_config_val(config, config_name))) /* Not acceptable */
722 syslog(LOG_ERR, _("Name for tinc daemon required!"));
726 asprintf(&myself->name, "%s", (char*)cfg->data.val);
728 if(check_id(myself->name))
730 syslog(LOG_ERR, _("Invalid name for myself!"));
734 if(!(cfg = get_config_val(config, config_privatekey)))
736 syslog(LOG_ERR, _("Private key for tinc daemon required!"));
741 myself->rsa_key = RSA_new();
742 BN_hex2bn(&myself->rsa_key->d, cfg->data.ptr);
743 BN_hex2bn(&myself->rsa_key->e, "FFFF");
746 if(read_host_config(myself))
748 syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
752 if(!(cfg = get_config_val(myself->config, config_publickey)))
754 syslog(LOG_ERR, _("Public key for tinc daemon required!"));
759 BN_hex2bn(&myself->rsa_key->n, cfg->data.ptr);
762 if(RSA_check_key(myself->rsa_key) != 1)
764 syslog(LOG_ERR, _("Invalid public/private keypair!"));
768 if(!(cfg = get_config_val(myself->config, config_port)))
771 myself->port = cfg->data.val;
773 if((cfg = get_config_val(myself->config, config_indirectdata)))
774 if(cfg->data.val == stupid_true)
775 myself->flags |= EXPORTINDIRECTDATA;
777 if((cfg = get_config_val(myself->config, config_tcponly)))
778 if(cfg->data.val == stupid_true)
779 myself->flags |= TCPONLY;
781 /* Read in all the subnets specified in the host configuration file */
783 for(next = myself->config; (cfg = get_config_val(next, config_subnet)); next = cfg->next)
786 net->type = SUBNET_IPV4;
787 net->net.ipv4.address = cfg->data.ip->address;
788 net->net.ipv4.mask = cfg->data.ip->mask;
790 /* Teach newbies what subnets are... */
792 if((net->net.ipv4.address & net->net.ipv4.mask) != net->net.ipv4.address)
794 syslog(LOG_ERR, _("Network address and subnet mask do not match!"));
798 subnet_add(myself, net);
801 if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
803 syslog(LOG_ERR, _("Unable to set up a listening socket!"));
807 /* Generate packet encryption key */
809 myself->cipher_pkttype = EVP_bf_cfb();
811 myself->cipher_pktkeylength = myself->cipher_pkttype->key_len + myself->cipher_pkttype->iv_len;
813 myself->cipher_pktkey = (char *)xmalloc(myself->cipher_pktkeylength);
814 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
816 if(!(cfg = get_config_val(config, config_keyexpire)))
819 keylifetime = cfg->data.val;
821 keyexpires = time(NULL) + keylifetime;
823 /* Activate ourselves */
825 myself->status.active = 1;
827 syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
833 sigalrm_handler(int a)
837 cfg = get_config_val(upstreamcfg, config_connectto);
839 if(!cfg && upstreamcfg == config)
840 /* No upstream IP given, we're listen only. */
845 upstreamcfg = cfg->next;
846 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
848 signal(SIGALRM, SIG_IGN);
851 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
854 signal(SIGALRM, sigalrm_handler);
855 upstreamcfg = config;
856 seconds_till_retry += 5;
857 if(seconds_till_retry > MAXTIMEOUT) /* Don't wait more than MAXTIMEOUT seconds. */
858 seconds_till_retry = MAXTIMEOUT;
859 syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
861 alarm(seconds_till_retry);
866 setup all initial network connections
868 int setup_network_connections(void)
872 if((cfg = get_config_val(config, config_pingtimeout)) == NULL)
876 timeout = cfg->data.val;
883 if(setup_tap_fd() < 0)
886 if(setup_myself() < 0)
889 /* Run tinc-up script to further initialize the tap interface */
890 execute_script("tinc-up");
892 if(!(cfg = get_config_val(config, config_connectto)))
893 /* No upstream IP given, we're listen only. */
898 upstreamcfg = cfg->next;
899 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
901 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
904 signal(SIGALRM, sigalrm_handler);
905 upstreamcfg = config;
906 seconds_till_retry = MAXTIMEOUT;
907 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
908 alarm(seconds_till_retry);
914 close all open network connections
916 void close_network_connections(void)
920 for(p = conn_list; p != NULL; p = p->next)
922 p->status.active = 0;
923 terminate_connection(p);
927 if(myself->status.active)
929 close(myself->meta_socket);
930 free_conn_list(myself);
936 /* Execute tinc-down script right after shutting down the interface */
937 execute_script("tinc-down");
941 syslog(LOG_NOTICE, _("Terminating"));
947 create a data (udp) socket
949 int setup_vpn_connection(conn_list_t *cl)
952 struct sockaddr_in a;
955 if(debug_lvl >= DEBUG_TRAFFIC)
956 syslog(LOG_DEBUG, _("Opening UDP socket to %s"), cl->hostname);
958 nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
961 syslog(LOG_ERR, _("Creating UDP socket failed: %m"));
965 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
967 syslog(LOG_ERR, _("System call `%s' failed: %m"),
972 flags = fcntl(nfd, F_GETFL);
973 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
975 syslog(LOG_ERR, _("System call `%s' failed: %m"),
980 memset(&a, 0, sizeof(a));
981 a.sin_family = AF_INET;
982 a.sin_port = htons(myself->port);
983 a.sin_addr.s_addr = htonl(INADDR_ANY);
985 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
987 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), myself->port);
991 a.sin_family = AF_INET;
992 a.sin_port = htons(cl->port);
993 a.sin_addr.s_addr = htonl(cl->address);
995 if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
997 syslog(LOG_ERR, _("Connecting to %s port %d failed: %m"),
998 cl->hostname, cl->port);
1002 flags = fcntl(nfd, F_GETFL);
1003 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
1005 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m %s (%s)"), __FILE__, __LINE__, nfd,
1006 cl->name, cl->hostname);
1011 cl->status.dataopen = 1;
1017 handle an incoming tcp connect call and open
1020 conn_list_t *create_new_connection(int sfd)
1023 struct sockaddr_in ci;
1024 int len = sizeof(ci);
1026 p = new_conn_list();
1028 if(getpeername(sfd, &ci, &len) < 0)
1030 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1036 p->address = ntohl(ci.sin_addr.s_addr);
1037 p->hostname = hostlookup(ci.sin_addr.s_addr);
1038 p->meta_socket = sfd;
1040 p->buffer = xmalloc(MAXBUFSIZE);
1042 p->last_ping_time = time(NULL);
1044 if(debug_lvl >= DEBUG_CONNECTIONS)
1045 syslog(LOG_NOTICE, _("Connection from %s port %d"),
1046 p->hostname, htons(ci.sin_port));
1048 p->allow_request = ID;
1054 put all file descriptors in an fd_set array
1056 void build_fdset(fd_set *fs)
1062 for(p = conn_list; p != NULL; p = p->next)
1065 FD_SET(p->meta_socket, fs);
1066 if(p->status.dataopen)
1067 FD_SET(p->socket, fs);
1070 FD_SET(myself->meta_socket, fs);
1076 receive incoming data from the listening
1077 udp socket and write it to the ethertap
1078 device after being decrypted
1080 int handle_incoming_vpn_data(conn_list_t *cl)
1083 int x, l = sizeof(x);
1086 if(getsockopt(cl->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1088 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1089 __FILE__, __LINE__, cl->socket);
1094 syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1098 if((lenin = recv(cl->socket, (char *) &(pkt.len), MTU, 0)) <= 0)
1100 syslog(LOG_ERR, _("Receiving packet failed: %m"));
1104 if(debug_lvl >= DEBUG_TRAFFIC)
1106 syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"), lenin,
1107 cl->name, cl->hostname);
1111 return xrecv(cl, &pkt);
1115 terminate a connection and notify the other
1116 end before closing the sockets
1118 void terminate_connection(conn_list_t *cl)
1123 if(cl->status.remove)
1126 cl->status.remove = 1;
1128 if(debug_lvl >= DEBUG_CONNECTIONS)
1129 syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1130 cl->name, cl->hostname);
1135 close(cl->meta_socket);
1138 /* Find all connections that were lost because they were behind cl
1139 (the connection that was dropped). */
1142 for(p = conn_list; p != NULL; p = p->next)
1143 if((p->nexthop == cl) && (p != cl))
1144 terminate_connection(p); /* Sounds like recursion, but p does not have a meta connection :) */
1146 /* Inform others of termination if it was still active */
1148 if(cl->status.active)
1149 for(p = conn_list; p != NULL; p = p->next)
1150 if(p->status.meta && p->status.active && p!=cl)
1151 send_del_host(p, cl);
1153 /* Remove the associated subnets */
1155 for(s = cl->subnets; s; s = s->next)
1158 /* Check if this was our outgoing connection */
1160 if(cl->status.outgoing && cl->status.active)
1162 signal(SIGALRM, sigalrm_handler);
1163 seconds_till_retry = 5;
1164 alarm(seconds_till_retry);
1165 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
1170 cl->status.active = 0;
1175 Check if the other end is active.
1176 If we have sent packets, but didn't receive any,
1177 then possibly the other end is dead. We send a
1178 PING request over the meta connection. If the other
1179 end does not reply in time, we consider them dead
1180 and close the connection.
1182 int check_dead_connections(void)
1188 for(p = conn_list; p != NULL; p = p->next)
1190 if(p->status.active && p->status.meta)
1192 if(p->last_ping_time + timeout < now)
1194 if(p->status.pinged)
1196 if(debug_lvl >= DEBUG_PROTOCOL)
1197 syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1198 p->name, p->hostname);
1199 p->status.timeout = 1;
1200 terminate_connection(p);
1214 accept a new tcp connect and create a
1217 int handle_new_meta_connection()
1220 struct sockaddr client;
1221 int nfd, len = sizeof(client);
1223 if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
1225 syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1229 if(!(ncn = create_new_connection(nfd)))
1233 syslog(LOG_NOTICE, _("Closed attempted connection"));
1243 check all connections to see if anything
1244 happened on their sockets
1246 void check_network_activity(fd_set *f)
1250 for(p = conn_list; p != NULL; p = p->next)
1252 if(p->status.remove)
1255 if(p->status.dataopen)
1256 if(FD_ISSET(p->socket, f))
1258 handle_incoming_vpn_data(p);
1260 /* Old error stuff (FIXME: copy this to handle_incoming_vpn_data()
1262 getsockopt(p->socket, SOL_SOCKET, SO_ERROR, &x, &l);
1263 syslog(LOG_ERR, _("Outgoing data socket error for %s (%s): %s"),
1264 p->name, p->hostname, strerror(x));
1265 terminate_connection(p);
1271 if(FD_ISSET(p->meta_socket, f))
1272 if(receive_meta(p) < 0)
1274 terminate_connection(p);
1279 if(FD_ISSET(myself->meta_socket, f))
1280 handle_new_meta_connection();
1285 read, encrypt and send data that is
1286 available through the ethertap device
1288 void handle_tap_input(void)
1293 if(taptype == TAP_TYPE_TUNTAP)
1295 if((lenin = read(tap_fd, vp.data, MTU)) <= 0)
1297 syslog(LOG_ERR, _("Error while reading from tun/tap device: %m"));
1304 if((lenin = read(tap_fd, vp.data - 2, MTU)) <= 0)
1306 syslog(LOG_ERR, _("Error while reading from ethertap device: %m"));
1312 total_tap_in += lenin;
1316 if(debug_lvl >= DEBUG_TRAFFIC)
1317 syslog(LOG_WARNING, _("Received short packet from tap device"));
1321 if(debug_lvl >= DEBUG_TRAFFIC)
1323 syslog(LOG_DEBUG, _("Read packet of length %d from tap device"), vp.len);
1326 send_packet(ntohl(*((unsigned long*)(&vp.data[30]))), &vp);
1331 this is where it all happens...
1333 void main_loop(void)
1338 time_t last_ping_check;
1341 last_ping_check = time(NULL);
1345 tv.tv_sec = timeout;
1351 if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1353 if(errno != EINTR) /* because of alarm */
1355 syslog(LOG_ERR, _("Error while waiting for input: %m"));
1362 syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1364 close_network_connections();
1365 clear_config(&config);
1367 if(read_server_config())
1369 syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1375 if(setup_network_connections())
1383 /* Let's check if everybody is still alive */
1385 if(last_ping_check + timeout < t)
1387 check_dead_connections();
1388 last_ping_check = time(NULL);
1390 /* Should we regenerate our key? */
1394 if(debug_lvl >= DEBUG_STATUS)
1395 syslog(LOG_INFO, _("Regenerating symmetric key"));
1397 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
1398 send_key_changed(myself, NULL);
1399 keyexpires = time(NULL) + keylifetime;
1405 check_network_activity(&fset);
1407 /* local tap data */
1408 if(FD_ISSET(tap_fd, &fset))