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.74 2000/11/15 22:07:36 zarq Exp $
28 #include <netinet/in.h>
32 #include <sys/signal.h>
34 #include <sys/types.h>
37 #include <sys/ioctl.h>
38 /* SunOS really wants sys/socket.h BEFORE net/if.h,
39 and FreeBSD wants these lines below the rest. */
40 #include <arpa/inet.h>
41 #include <sys/socket.h>
44 #ifdef HAVE_OPENSSL_RAND_H
45 # include <openssl/rand.h>
50 #ifdef HAVE_OPENSSL_EVP_H
51 # include <openssl/evp.h>
56 #ifdef HAVE_OPENSSL_ERR_H
57 # include <openssl/err.h>
63 #include LINUX_IF_TUN_H
81 int taptype = TAP_TYPE_ETHERTAP;
83 int total_tap_out = 0;
84 int total_socket_in = 0;
85 int total_socket_out = 0;
87 config_t *upstreamcfg;
88 static int seconds_till_retry;
99 void _execute_script(const char *name)
108 asprintf(&s, "NETNAME=%s", netname);
109 putenv(s); /* Don't free s! see man 3 putenv */
118 if(chdir(confbase) < 0)
119 /* This cannot fail since we already read config files from this
121 /* Yes this can fail, somebody could have removed this directory
122 when we didn't pay attention. - Ivo */
125 /* Now if THIS fails, something wicked is going on. - Ivo */
126 syslog(LOG_ERR, _("Couldn't chdir to `/': %m"));
128 /* Continue anyway. */
131 asprintf(&scriptname, "%s/%s", confbase, name);
133 /* Close all file descriptors */
137 /* Open standard input */
138 if(open("/dev/null", O_RDONLY) < 0)
140 syslog(LOG_ERR, _("Opening `/dev/null' failed: %m"));
146 /* Standard output directly goes to syslog */
147 openlog(name, LOG_CONS | LOG_PID, LOG_DAEMON);
148 /* Standard error as well */
151 syslog(LOG_ERR, _("System call `%s' failed: %m"),
157 if(error && debug_lvl > 1)
158 syslog(LOG_INFO, _("This means that any output the script generates will not be shown in syslog."));
160 execl(scriptname, NULL);
161 /* No return on success */
163 if(errno != ENOENT) /* Ignore if the file does not exist */
164 syslog(LOG_WARNING, _("Error executing `%s': %m"), scriptname);
166 /* No need to free things */
171 Execute the given script.
172 This function doesn't really belong here.
174 int execute_script(const char *name)
178 if((pid = fork()) < 0)
180 syslog(LOG_ERR, _("System call `%s' failed: %m"),
187 list_append(child_pids, pid);
193 _execute_script(name);
196 int check_child(void *data)
202 pid = waitpid(pid, &status, WNOHANG);
203 if(WIFEXITED(status))
205 if(WIFSIGNALED(status)) /* Child was killed by a signal */
207 syslog(LOG_ERR, _("Child with PID %d was killed by signal %d (%s)"),
208 pid, WTERMSIG(status), strsignal(WTERMSIG(status)));
211 if(WEXITSTATUS(status) != 0)
213 syslog(LOG_INFO, _("Child with PID %d exited with code %d"),
214 WEXITSTATUS(status));
220 void check_children(void)
222 list_forall_nodes(child_pids, check_child);
225 int xsend(conn_list_t *cl, vpn_packet_t *inpkt)
231 outpkt.len = inpkt->len;
233 /* Encrypt the packet */
235 EVP_EncryptInit(&ctx, cl->cipher_pkttype, cl->cipher_pktkey, cl->cipher_pktkey + cl->cipher_pkttype->key_len);
236 EVP_EncryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len);
237 EVP_EncryptFinal(&ctx, outpkt.data + outlen, &outpad);
238 outlen += outpad + 2;
241 outlen = outpkt.len + 2;
242 memcpy(&outpkt, inpkt, outlen);
245 if(debug_lvl >= DEBUG_TRAFFIC)
246 syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
247 outlen, cl->name, cl->hostname);
249 total_socket_out += outlen;
251 if((send(cl->socket, (char *) &(outpkt.len), outlen, 0)) < 0)
253 syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
254 cl->name, cl->hostname);
261 int xrecv(conn_list_t *cl, vpn_packet_t *inpkt)
267 outpkt.len = inpkt->len;
269 /* Decrypt the packet */
271 EVP_DecryptInit(&ctx, myself->cipher_pkttype, myself->cipher_pktkey, myself->cipher_pktkey + myself->cipher_pkttype->key_len);
272 EVP_DecryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len + 8);
273 EVP_DecryptFinal(&ctx, outpkt.data + outlen, &outpad);
277 outlen = outpkt.len+2;
278 memcpy(&outpkt, inpkt, outlen);
281 if(debug_lvl >= DEBUG_TRAFFIC)
282 syslog(LOG_ERR, _("Writing packet of %d bytes to tap device"),
285 /* Fix mac address */
287 memcpy(outpkt.data, mymac.net.mac.address.x, 6);
289 if(taptype == TAP_TYPE_TUNTAP)
291 if(write(tap_fd, outpkt.data, outpkt.len) < 0)
292 syslog(LOG_ERR, _("Can't write to tun/tap device: %m"));
294 total_tap_out += outpkt.len;
298 if(write(tap_fd, outpkt.data - 2, outpkt.len + 2) < 0)
299 syslog(LOG_ERR, _("Can't write to ethertap device: %m"));
301 total_tap_out += outpkt.len + 2;
308 add the given packet of size s to the
309 queue q, be it the send or receive queue
311 void add_queue(packet_queue_t **q, void *packet, size_t s)
315 e = xmalloc(sizeof(*e));
316 e->packet = xmalloc(s);
317 memcpy(e->packet, packet, s);
321 *q = xmalloc(sizeof(**q));
322 (*q)->head = (*q)->tail = NULL;
325 e->next = NULL; /* We insert at the tail */
327 if((*q)->tail) /* Do we have a tail? */
329 (*q)->tail->next = e;
330 e->prev = (*q)->tail;
332 else /* No tail -> no head too */
342 /* Remove a queue element */
343 void del_queue(packet_queue_t **q, queue_element_t *e)
348 if(e->next) /* There is a successor, so we are not tail */
350 if(e->prev) /* There is a predecessor, so we are not head */
352 e->next->prev = e->prev;
353 e->prev->next = e->next;
355 else /* We are head */
357 e->next->prev = NULL;
358 (*q)->head = e->next;
361 else /* We are tail (or all alone!) */
363 if(e->prev) /* We are not alone :) */
365 e->prev->next = NULL;
366 (*q)->tail = e->prev;
380 flush a queue by calling function for
381 each packet, and removing it when that
382 returned a zero exit code
384 void flush_queue(conn_list_t *cl, packet_queue_t **pq,
385 int (*function)(conn_list_t*,vpn_packet_t*))
387 queue_element_t *p, *next = NULL;
389 for(p = (*pq)->head; p != NULL; )
393 if(!function(cl, p->packet))
399 if(debug_lvl >= DEBUG_TRAFFIC)
400 syslog(LOG_DEBUG, _("Queue flushed"));
405 flush the send&recv queues
406 void because nothing goes wrong here, packets
407 remain in the queue if something goes wrong
409 void flush_queues(conn_list_t *cl)
414 if(debug_lvl >= DEBUG_TRAFFIC)
415 syslog(LOG_DEBUG, _("Flushing send queue for %s (%s)"),
416 cl->name, cl->hostname);
417 flush_queue(cl, &(cl->sq), xsend);
422 if(debug_lvl >= DEBUG_TRAFFIC)
423 syslog(LOG_DEBUG, _("Flushing receive queue for %s (%s)"),
424 cl->name, cl->hostname);
425 flush_queue(cl, &(cl->rq), xrecv);
431 send a packet to the given vpn ip.
433 int send_packet(ip_t to, vpn_packet_t *packet)
438 if((subnet = lookup_subnet_ipv4(to)) == NULL)
440 if(debug_lvl >= DEBUG_TRAFFIC)
442 syslog(LOG_NOTICE, _("Trying to look up %d.%d.%d.%d in connection list failed!"),
453 if(debug_lvl >= DEBUG_TRAFFIC)
455 syslog(LOG_NOTICE, _("Packet with destination %d.%d.%d.%d is looping back to us!"),
462 /* If we ourselves have indirectdata flag set, we should send only to our uplink! */
464 /* FIXME - check for indirection and reprogram it The Right Way(tm) this time. */
466 /* Connections are now opened beforehand...
468 if(!cl->status.dataopen)
469 if(setup_vpn_connection(cl) < 0)
471 syslog(LOG_ERR, _("Could not open UDP connection to %s (%s)"),
472 cl->name, cl->hostname);
477 if(!cl->status.validkey)
479 /* FIXME: Don't queue until everything else is fixed.
480 if(debug_lvl >= DEBUG_TRAFFIC)
481 syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
482 cl->name, cl->hostname);
483 add_queue(&(cl->sq), packet, packet->len + 2);
485 if(!cl->status.waitingforkey)
486 send_req_key(myself, cl); /* Keys should be sent to the host running the tincd */
490 if(!cl->status.active)
492 /* FIXME: Don't queue until everything else is fixed.
493 if(debug_lvl >= DEBUG_TRAFFIC)
494 syslog(LOG_INFO, _("%s (%s) is not ready, queueing packet"),
495 cl->name, cl->hostname);
496 add_queue(&(cl->sq), packet, packet->len + 2);
498 return 0; /* We don't want to mess up, do we? */
501 /* can we send it? can we? can we? huh? */
503 return xsend(cl, packet);
507 open the local ethertap device
509 int setup_tap_fd(void)
512 const char *tapfname;
517 if((cfg = get_config_val(config, config_tapdevice)))
518 tapfname = cfg->data.ptr;
521 tapfname = "/dev/misc/net/tun";
523 tapfname = "/dev/tap0";
526 if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
528 syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
534 /* Set default MAC address for ethertap devices */
536 taptype = TAP_TYPE_ETHERTAP;
537 mymac.type = SUBNET_MAC;
538 mymac.net.mac.address.x[0] = 0xfe;
539 mymac.net.mac.address.x[1] = 0xfd;
540 mymac.net.mac.address.x[2] = 0x00;
541 mymac.net.mac.address.x[3] = 0x00;
542 mymac.net.mac.address.x[4] = 0x00;
543 mymac.net.mac.address.x[5] = 0x00;
546 /* Ok now check if this is an old ethertap or a new tun/tap thingie */
547 memset(&ifr, 0, sizeof(ifr));
549 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
551 strncpy(ifr.ifr_name, netname, IFNAMSIZ);
553 if (!ioctl(tap_fd, TUNSETIFF, (void *) &ifr))
555 syslog(LOG_INFO, _("%s is a new style tun/tap device"), tapfname);
556 taptype = TAP_TYPE_TUNTAP;
564 set up the socket that we listen on for incoming
567 int setup_listen_meta_socket(int port)
570 struct sockaddr_in a;
574 if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
576 syslog(LOG_ERR, _("Creating metasocket failed: %m"));
580 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
583 syslog(LOG_ERR, _("System call `%s' failed: %m"),
588 if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one)))
591 syslog(LOG_ERR, _("System call `%s' failed: %m"),
596 flags = fcntl(nfd, F_GETFL);
597 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
600 syslog(LOG_ERR, _("System call `%s' failed: %m"),
605 if((cfg = get_config_val(config, config_interface)))
607 if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, cfg->data.ptr, strlen(cfg->data.ptr)))
610 syslog(LOG_ERR, _("Unable to bind listen socket to interface %s: %m"), cfg->data.ptr);
615 memset(&a, 0, sizeof(a));
616 a.sin_family = AF_INET;
617 a.sin_port = htons(port);
619 if((cfg = get_config_val(config, config_interfaceip)))
620 a.sin_addr.s_addr = htonl(cfg->data.ip->address);
622 a.sin_addr.s_addr = htonl(INADDR_ANY);
624 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
627 syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
634 syslog(LOG_ERR, _("System call `%s' failed: %m"),
643 setup the socket for incoming encrypted
646 int setup_vpn_in_socket(int port)
649 struct sockaddr_in a;
652 if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
655 syslog(LOG_ERR, _("Creating socket failed: %m"));
659 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
662 syslog(LOG_ERR, _("System call `%s' failed: %m"),
667 flags = fcntl(nfd, F_GETFL);
668 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
671 syslog(LOG_ERR, _("System call `%s' failed: %m"),
676 memset(&a, 0, sizeof(a));
677 a.sin_family = AF_INET;
678 a.sin_port = htons(port);
679 a.sin_addr.s_addr = htonl(INADDR_ANY);
681 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
684 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
692 setup an outgoing meta (tcp) socket
694 int setup_outgoing_meta_socket(conn_list_t *cl)
697 struct sockaddr_in a;
700 if(debug_lvl >= DEBUG_CONNECTIONS)
701 syslog(LOG_INFO, _("Trying to connect to %s"), cl->hostname);
703 if((cfg = get_config_val(cl->config, config_port)) == NULL)
706 cl->port = cfg->data.val;
708 cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
709 if(cl->meta_socket == -1)
711 syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
712 cl->hostname, cl->port);
716 a.sin_family = AF_INET;
717 a.sin_port = htons(cl->port);
718 a.sin_addr.s_addr = htonl(cl->address);
720 if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
722 close(cl->meta_socket);
723 syslog(LOG_ERR, _("%s port %hd: %m"), cl->hostname, cl->port);
727 flags = fcntl(cl->meta_socket, F_GETFL);
728 if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
730 close(cl->meta_socket);
731 syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
732 cl->hostname, cl->port);
736 if(debug_lvl >= DEBUG_CONNECTIONS)
737 syslog(LOG_INFO, _("Connected to %s port %hd"),
738 cl->hostname, cl->port);
746 setup an outgoing connection. It's not
747 necessary to also open an udp socket as
748 well, because the other host will initiate
749 an authentication sequence during which
750 we will do just that.
752 int setup_outgoing_connection(char *name)
760 syslog(LOG_ERR, _("Invalid name for outgoing connection"));
764 ncn = new_conn_list();
765 asprintf(&ncn->name, "%s", name);
767 if(read_host_config(ncn))
769 syslog(LOG_ERR, _("Error reading host configuration file for %s"));
774 if(!(cfg = get_config_val(ncn->config, config_address)))
776 syslog(LOG_ERR, _("No address specified for %s"));
781 if(!(h = gethostbyname(cfg->data.ptr)))
783 syslog(LOG_ERR, _("Error looking up `%s': %m"), cfg->data.ptr);
788 ncn->address = ntohl(*((ip_t*)(h->h_addr_list[0])));
789 ncn->hostname = hostlookup(htonl(ncn->address));
791 if(setup_outgoing_meta_socket(ncn) < 0)
793 syslog(LOG_ERR, _("Could not set up a meta connection to %s"),
799 ncn->status.outgoing = 1;
800 ncn->buffer = xmalloc(MAXBUFSIZE);
802 ncn->last_ping_time = time(NULL);
812 Configure conn_list_t myself and set up the local sockets (listen only)
814 int setup_myself(void)
820 myself = new_conn_list();
822 asprintf(&myself->hostname, "MYSELF"); /* FIXME? Do hostlookup on ourselves? */
824 myself->protocol_version = PROT_CURRENT;
826 if(!(cfg = get_config_val(config, config_name))) /* Not acceptable */
828 syslog(LOG_ERR, _("Name for tinc daemon required!"));
832 asprintf(&myself->name, "%s", (char*)cfg->data.val);
834 if(check_id(myself->name))
836 syslog(LOG_ERR, _("Invalid name for myself!"));
840 if(!(cfg = get_config_val(config, config_privatekey)))
842 syslog(LOG_ERR, _("Private key for tinc daemon required!"));
847 myself->rsa_key = RSA_new();
848 BN_hex2bn(&myself->rsa_key->d, cfg->data.ptr);
849 BN_hex2bn(&myself->rsa_key->e, "FFFF");
852 if(read_host_config(myself))
854 syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
858 if(!(cfg = get_config_val(myself->config, config_publickey)))
860 syslog(LOG_ERR, _("Public key for tinc daemon required!"));
865 BN_hex2bn(&myself->rsa_key->n, cfg->data.ptr);
868 if(RSA_check_key(myself->rsa_key) != 1)
870 syslog(LOG_ERR, _("Invalid public/private keypair!"));
874 if(!(cfg = get_config_val(myself->config, config_port)))
877 myself->port = cfg->data.val;
879 if((cfg = get_config_val(myself->config, config_indirectdata)))
880 if(cfg->data.val == stupid_true)
881 myself->flags |= EXPORTINDIRECTDATA;
883 if((cfg = get_config_val(myself->config, config_tcponly)))
884 if(cfg->data.val == stupid_true)
885 myself->flags |= TCPONLY;
887 /* Read in all the subnets specified in the host configuration file */
889 for(next = myself->config; (cfg = get_config_val(next, config_subnet)); next = cfg->next)
892 net->type = SUBNET_IPV4;
893 net->net.ipv4.address = cfg->data.ip->address;
894 net->net.ipv4.mask = cfg->data.ip->mask;
896 /* Teach newbies what subnets are... */
898 if((net->net.ipv4.address & net->net.ipv4.mask) != net->net.ipv4.address)
900 syslog(LOG_ERR, _("Network address and subnet mask do not match!"));
904 subnet_add(myself, net);
907 if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
909 syslog(LOG_ERR, _("Unable to set up a listening socket!"));
913 /* Generate packet encryption key */
915 myself->cipher_pkttype = EVP_bf_cfb();
917 myself->cipher_pktkeylength = myself->cipher_pkttype->key_len + myself->cipher_pkttype->iv_len;
919 myself->cipher_pktkey = (char *)xmalloc(myself->cipher_pktkeylength);
920 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
922 if(!(cfg = get_config_val(config, config_keyexpire)))
925 keylifetime = cfg->data.val;
927 keyexpires = time(NULL) + keylifetime;
929 /* Activate ourselves */
931 myself->status.active = 1;
933 syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
935 child_pids = list_new();
941 sigalrm_handler(int a)
945 cfg = get_config_val(upstreamcfg, config_connectto);
947 if(!cfg && upstreamcfg == config)
948 /* No upstream IP given, we're listen only. */
953 upstreamcfg = cfg->next;
954 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
956 signal(SIGALRM, SIG_IGN);
959 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
962 signal(SIGALRM, sigalrm_handler);
963 upstreamcfg = config;
964 seconds_till_retry += 5;
965 if(seconds_till_retry > MAXTIMEOUT) /* Don't wait more than MAXTIMEOUT seconds. */
966 seconds_till_retry = MAXTIMEOUT;
967 syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
969 alarm(seconds_till_retry);
974 setup all initial network connections
976 int setup_network_connections(void)
980 if((cfg = get_config_val(config, config_pingtimeout)) == NULL)
984 timeout = cfg->data.val;
991 if(setup_tap_fd() < 0)
994 if(setup_myself() < 0)
997 /* Run tinc-up script to further initialize the tap interface */
998 execute_script("tinc-up");
1000 if(!(cfg = get_config_val(config, config_connectto)))
1001 /* No upstream IP given, we're listen only. */
1006 upstreamcfg = cfg->next;
1007 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
1009 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
1012 signal(SIGALRM, sigalrm_handler);
1013 upstreamcfg = config;
1014 seconds_till_retry = MAXTIMEOUT;
1015 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
1016 alarm(seconds_till_retry);
1022 close all open network connections
1024 void close_network_connections(void)
1028 for(p = conn_list; p != NULL; p = p->next)
1030 p->status.active = 0;
1031 terminate_connection(p);
1035 if(myself->status.active)
1037 close(myself->meta_socket);
1038 free_conn_list(myself);
1044 /* Execute tinc-down script right after shutting down the interface */
1045 execute_script("tinc-down");
1047 destroy_conn_list();
1049 syslog(LOG_NOTICE, _("Terminating"));
1055 create a data (udp) socket
1057 int setup_vpn_connection(conn_list_t *cl)
1060 struct sockaddr_in a;
1063 if(debug_lvl >= DEBUG_TRAFFIC)
1064 syslog(LOG_DEBUG, _("Opening UDP socket to %s"), cl->hostname);
1066 nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
1069 syslog(LOG_ERR, _("Creating UDP socket failed: %m"));
1073 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
1076 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1081 flags = fcntl(nfd, F_GETFL);
1082 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
1085 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1090 memset(&a, 0, sizeof(a));
1091 a.sin_family = AF_INET;
1092 a.sin_port = htons(myself->port);
1093 a.sin_addr.s_addr = htonl(INADDR_ANY);
1095 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
1098 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), myself->port);
1102 a.sin_family = AF_INET;
1103 a.sin_port = htons(cl->port);
1104 a.sin_addr.s_addr = htonl(cl->address);
1106 if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
1109 syslog(LOG_ERR, _("Connecting to %s port %d failed: %m"),
1110 cl->hostname, cl->port);
1114 flags = fcntl(nfd, F_GETFL);
1115 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
1118 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m %s (%s)"), __FILE__, __LINE__, nfd,
1119 cl->name, cl->hostname);
1124 cl->status.dataopen = 1;
1130 handle an incoming tcp connect call and open
1133 conn_list_t *create_new_connection(int sfd)
1136 struct sockaddr_in ci;
1137 int len = sizeof(ci);
1139 p = new_conn_list();
1141 if(getpeername(sfd, (struct sockaddr *) &ci, (socklen_t *) &len) < 0)
1143 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1149 p->address = ntohl(ci.sin_addr.s_addr);
1150 p->hostname = hostlookup(ci.sin_addr.s_addr);
1151 p->meta_socket = sfd;
1153 p->buffer = xmalloc(MAXBUFSIZE);
1155 p->last_ping_time = time(NULL);
1157 if(debug_lvl >= DEBUG_CONNECTIONS)
1158 syslog(LOG_NOTICE, _("Connection from %s port %d"),
1159 p->hostname, htons(ci.sin_port));
1161 p->allow_request = ID;
1167 put all file descriptors in an fd_set array
1169 void build_fdset(fd_set *fs)
1175 for(p = conn_list; p != NULL; p = p->next)
1178 FD_SET(p->meta_socket, fs);
1179 if(p->status.dataopen)
1180 FD_SET(p->socket, fs);
1183 FD_SET(myself->meta_socket, fs);
1189 receive incoming data from the listening
1190 udp socket and write it to the ethertap
1191 device after being decrypted
1193 int handle_incoming_vpn_data(conn_list_t *cl)
1196 int x, l = sizeof(x);
1199 if(getsockopt(cl->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1201 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1202 __FILE__, __LINE__, cl->socket);
1207 syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1211 if((lenin = recv(cl->socket, (char *) &(pkt.len), MTU, 0)) <= 0)
1213 syslog(LOG_ERR, _("Receiving packet failed: %m"));
1217 if(debug_lvl >= DEBUG_TRAFFIC)
1219 syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"), lenin,
1220 cl->name, cl->hostname);
1224 return xrecv(cl, &pkt);
1228 terminate a connection and notify the other
1229 end before closing the sockets
1231 void terminate_connection(conn_list_t *cl)
1236 if(cl->status.remove)
1239 cl->status.remove = 1;
1241 if(debug_lvl >= DEBUG_CONNECTIONS)
1242 syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1243 cl->name, cl->hostname);
1248 close(cl->meta_socket);
1251 /* Find all connections that were lost because they were behind cl
1252 (the connection that was dropped). */
1255 for(p = conn_list; p != NULL; p = p->next)
1256 if((p->nexthop == cl) && (p != cl))
1257 terminate_connection(p); /* Sounds like recursion, but p does not have a meta connection :) */
1259 /* Inform others of termination if it was still active */
1261 if(cl->status.active)
1262 for(p = conn_list; p != NULL; p = p->next)
1263 if(p->status.meta && p->status.active && p!=cl)
1264 send_del_host(p, cl);
1266 /* Remove the associated subnets */
1268 for(s = cl->subnets; s; s = s->next)
1271 /* Check if this was our outgoing connection */
1273 if(cl->status.outgoing && cl->status.active)
1275 signal(SIGALRM, sigalrm_handler);
1276 seconds_till_retry = 5;
1277 alarm(seconds_till_retry);
1278 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
1283 cl->status.active = 0;
1288 Check if the other end is active.
1289 If we have sent packets, but didn't receive any,
1290 then possibly the other end is dead. We send a
1291 PING request over the meta connection. If the other
1292 end does not reply in time, we consider them dead
1293 and close the connection.
1295 int check_dead_connections(void)
1301 for(p = conn_list; p != NULL; p = p->next)
1303 if(p->status.active && p->status.meta)
1305 if(p->last_ping_time + timeout < now)
1307 if(p->status.pinged)
1309 if(debug_lvl >= DEBUG_PROTOCOL)
1310 syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1311 p->name, p->hostname);
1312 p->status.timeout = 1;
1313 terminate_connection(p);
1327 accept a new tcp connect and create a
1330 int handle_new_meta_connection()
1333 struct sockaddr client;
1334 int nfd, len = sizeof(client);
1336 if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
1338 syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1342 if(!(ncn = create_new_connection(nfd)))
1346 syslog(LOG_NOTICE, _("Closed attempted connection"));
1356 check all connections to see if anything
1357 happened on their sockets
1359 void check_network_activity(fd_set *f)
1363 for(p = conn_list; p != NULL; p = p->next)
1365 if(p->status.remove)
1368 if(p->status.dataopen)
1369 if(FD_ISSET(p->socket, f))
1371 handle_incoming_vpn_data(p);
1373 /* Old error stuff (FIXME: copy this to handle_incoming_vpn_data()
1375 getsockopt(p->socket, SOL_SOCKET, SO_ERROR, &x, &l);
1376 syslog(LOG_ERR, _("Outgoing data socket error for %s (%s): %s"),
1377 p->name, p->hostname, strerror(x));
1378 terminate_connection(p);
1384 if(FD_ISSET(p->meta_socket, f))
1385 if(receive_meta(p) < 0)
1387 terminate_connection(p);
1392 if(FD_ISSET(myself->meta_socket, f))
1393 handle_new_meta_connection();
1398 read, encrypt and send data that is
1399 available through the ethertap device
1401 void handle_tap_input(void)
1406 if(taptype == TAP_TYPE_TUNTAP)
1408 if((lenin = read(tap_fd, vp.data, MTU)) <= 0)
1410 syslog(LOG_ERR, _("Error while reading from tun/tap device: %m"));
1417 if((lenin = read(tap_fd, vp.data - 2, MTU)) <= 0)
1419 syslog(LOG_ERR, _("Error while reading from ethertap device: %m"));
1425 total_tap_in += lenin;
1429 if(debug_lvl >= DEBUG_TRAFFIC)
1430 syslog(LOG_WARNING, _("Received short packet from tap device"));
1434 if(debug_lvl >= DEBUG_TRAFFIC)
1436 syslog(LOG_DEBUG, _("Read packet of length %d from tap device"), vp.len);
1439 send_packet(ntohl(*((unsigned long*)(&vp.data[30]))), &vp);
1444 this is where it all happens...
1446 void main_loop(void)
1451 time_t last_ping_check;
1454 last_ping_check = time(NULL);
1458 tv.tv_sec = timeout;
1464 if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1466 if(errno != EINTR) /* because of alarm */
1468 syslog(LOG_ERR, _("Error while waiting for input: %m"));
1475 syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1477 close_network_connections();
1478 clear_config(&config);
1480 if(read_server_config())
1482 syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1488 if(setup_network_connections())
1496 /* Let's check if everybody is still alive */
1498 if(last_ping_check + timeout < t)
1500 check_dead_connections();
1501 last_ping_check = time(NULL);
1503 /* Should we regenerate our key? */
1507 if(debug_lvl >= DEBUG_STATUS)
1508 syslog(LOG_INFO, _("Regenerating symmetric key"));
1510 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
1511 send_key_changed(myself, NULL);
1512 keyexpires = time(NULL) + keylifetime;
1518 check_network_activity(&fset);
1520 /* local tap data */
1521 if(FD_ISSET(tap_fd, &fset))