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.72 2000/11/15 01:28:21 zarq 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>
43 #ifdef HAVE_OPENSSL_RAND_H
44 # include <openssl/rand.h>
49 #ifdef HAVE_OPENSSL_EVP_H
50 # include <openssl/evp.h>
55 #ifdef HAVE_OPENSSL_ERR_H
56 # include <openssl/err.h>
62 #include LINUX_IF_TUN_H
79 int taptype = TAP_TYPE_ETHERTAP;
81 int total_tap_out = 0;
82 int total_socket_in = 0;
83 int total_socket_out = 0;
85 config_t *upstreamcfg;
86 static int seconds_till_retry;
96 Execute the given script.
97 This function doesn't really belong here.
99 int execute_script(const char *name)
106 if((pid = fork()) < 0)
108 syslog(LOG_ERR, _("System call `%s' failed: %m"),
124 asprintf(&s, "NETNAME=%s", netname);
125 putenv(s); /* Don't free s! see man 3 putenv */
134 if(chdir(confbase) < 0)
135 /* This cannot fail since we already read config files from this
137 /* Yes this can fail, somebody could have removed this directory
138 when we didn't pay attention. - Ivo */
141 /* Now if THIS fails, something wicked is going on. - Ivo */
142 syslog(LOG_ERR, _("Couldn't chdir to `/': %m"));
144 /* Continue anyway. */
147 asprintf(&scriptname, "%s/%s", confbase, name);
149 /* Close all file descriptors */
153 /* Open standard input */
154 if(open("/dev/null", O_RDONLY) < 0)
156 syslog(LOG_ERR, _("Opening `/dev/null' failed: %m"));
162 /* Standard output directly goes to syslog */
163 openlog(name, LOG_CONS | LOG_PID, LOG_DAEMON);
164 /* Standard error as well */
167 syslog(LOG_ERR, _("System call `%s' failed: %m"),
173 if(error && debug_lvl > 1)
174 syslog(LOG_INFO, _("This means that any output the script generates will not be shown in syslog."));
176 execl(scriptname, NULL);
177 /* No return on success */
179 if(errno != ENOENT) /* Ignore if the file does not exist */
180 syslog(LOG_WARNING, _("Error executing `%s': %m"), scriptname);
182 /* No need to free things */
186 int xsend(conn_list_t *cl, vpn_packet_t *inpkt)
192 outpkt.len = inpkt->len;
194 /* Encrypt the packet */
196 EVP_EncryptInit(&ctx, cl->cipher_pkttype, cl->cipher_pktkey, cl->cipher_pktkey + cl->cipher_pkttype->key_len);
197 EVP_EncryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len);
198 EVP_EncryptFinal(&ctx, outpkt.data + outlen, &outpad);
199 outlen += outpad + 2;
202 outlen = outpkt.len + 2;
203 memcpy(&outpkt, inpkt, outlen);
206 if(debug_lvl >= DEBUG_TRAFFIC)
207 syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
208 outlen, cl->name, cl->hostname);
210 total_socket_out += outlen;
212 if((send(cl->socket, (char *) &(outpkt.len), outlen, 0)) < 0)
214 syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
215 cl->name, cl->hostname);
222 int xrecv(conn_list_t *cl, vpn_packet_t *inpkt)
228 outpkt.len = inpkt->len;
230 /* Decrypt the packet */
232 EVP_DecryptInit(&ctx, myself->cipher_pkttype, myself->cipher_pktkey, myself->cipher_pktkey + myself->cipher_pkttype->key_len);
233 EVP_DecryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len + 8);
234 EVP_DecryptFinal(&ctx, outpkt.data + outlen, &outpad);
238 outlen = outpkt.len+2;
239 memcpy(&outpkt, inpkt, outlen);
242 if(debug_lvl >= DEBUG_TRAFFIC)
243 syslog(LOG_ERR, _("Writing packet of %d bytes to tap device"),
246 /* Fix mac address */
248 memcpy(outpkt.data, mymac.net.mac.address.x, 6);
250 if(taptype == TAP_TYPE_TUNTAP)
252 if(write(tap_fd, outpkt.data, outpkt.len) < 0)
253 syslog(LOG_ERR, _("Can't write to tun/tap device: %m"));
255 total_tap_out += outpkt.len;
259 if(write(tap_fd, outpkt.data - 2, outpkt.len + 2) < 0)
260 syslog(LOG_ERR, _("Can't write to ethertap device: %m"));
262 total_tap_out += outpkt.len + 2;
269 add the given packet of size s to the
270 queue q, be it the send or receive queue
272 void add_queue(packet_queue_t **q, void *packet, size_t s)
276 e = xmalloc(sizeof(*e));
277 e->packet = xmalloc(s);
278 memcpy(e->packet, packet, s);
282 *q = xmalloc(sizeof(**q));
283 (*q)->head = (*q)->tail = NULL;
286 e->next = NULL; /* We insert at the tail */
288 if((*q)->tail) /* Do we have a tail? */
290 (*q)->tail->next = e;
291 e->prev = (*q)->tail;
293 else /* No tail -> no head too */
303 /* Remove a queue element */
304 void del_queue(packet_queue_t **q, queue_element_t *e)
309 if(e->next) /* There is a successor, so we are not tail */
311 if(e->prev) /* There is a predecessor, so we are not head */
313 e->next->prev = e->prev;
314 e->prev->next = e->next;
316 else /* We are head */
318 e->next->prev = NULL;
319 (*q)->head = e->next;
322 else /* We are tail (or all alone!) */
324 if(e->prev) /* We are not alone :) */
326 e->prev->next = NULL;
327 (*q)->tail = e->prev;
341 flush a queue by calling function for
342 each packet, and removing it when that
343 returned a zero exit code
345 void flush_queue(conn_list_t *cl, packet_queue_t **pq,
346 int (*function)(conn_list_t*,vpn_packet_t*))
348 queue_element_t *p, *next = NULL;
350 for(p = (*pq)->head; p != NULL; )
354 if(!function(cl, p->packet))
360 if(debug_lvl >= DEBUG_TRAFFIC)
361 syslog(LOG_DEBUG, _("Queue flushed"));
366 flush the send&recv queues
367 void because nothing goes wrong here, packets
368 remain in the queue if something goes wrong
370 void flush_queues(conn_list_t *cl)
375 if(debug_lvl >= DEBUG_TRAFFIC)
376 syslog(LOG_DEBUG, _("Flushing send queue for %s (%s)"),
377 cl->name, cl->hostname);
378 flush_queue(cl, &(cl->sq), xsend);
383 if(debug_lvl >= DEBUG_TRAFFIC)
384 syslog(LOG_DEBUG, _("Flushing receive queue for %s (%s)"),
385 cl->name, cl->hostname);
386 flush_queue(cl, &(cl->rq), xrecv);
392 send a packet to the given vpn ip.
394 int send_packet(ip_t to, vpn_packet_t *packet)
399 if((subnet = lookup_subnet_ipv4(to)) == NULL)
401 if(debug_lvl >= DEBUG_TRAFFIC)
403 syslog(LOG_NOTICE, _("Trying to look up %d.%d.%d.%d in connection list failed!"),
414 if(debug_lvl >= DEBUG_TRAFFIC)
416 syslog(LOG_NOTICE, _("Packet with destination %d.%d.%d.%d is looping back to us!"),
423 /* If we ourselves have indirectdata flag set, we should send only to our uplink! */
425 /* FIXME - check for indirection and reprogram it The Right Way(tm) this time. */
427 /* Connections are now opened beforehand...
429 if(!cl->status.dataopen)
430 if(setup_vpn_connection(cl) < 0)
432 syslog(LOG_ERR, _("Could not open UDP connection to %s (%s)"),
433 cl->name, cl->hostname);
438 if(!cl->status.validkey)
440 /* FIXME: Don't queue until everything else is fixed.
441 if(debug_lvl >= DEBUG_TRAFFIC)
442 syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
443 cl->name, cl->hostname);
444 add_queue(&(cl->sq), packet, packet->len + 2);
446 if(!cl->status.waitingforkey)
447 send_req_key(myself, cl); /* Keys should be sent to the host running the tincd */
451 if(!cl->status.active)
453 /* FIXME: Don't queue until everything else is fixed.
454 if(debug_lvl >= DEBUG_TRAFFIC)
455 syslog(LOG_INFO, _("%s (%s) is not ready, queueing packet"),
456 cl->name, cl->hostname);
457 add_queue(&(cl->sq), packet, packet->len + 2);
459 return 0; /* We don't want to mess up, do we? */
462 /* can we send it? can we? can we? huh? */
464 return xsend(cl, packet);
468 open the local ethertap device
470 int setup_tap_fd(void)
473 const char *tapfname;
478 if((cfg = get_config_val(config, config_tapdevice)))
479 tapfname = cfg->data.ptr;
482 tapfname = "/dev/misc/net/tun";
484 tapfname = "/dev/tap0";
487 if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
489 syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
495 /* Set default MAC address for ethertap devices */
497 taptype = TAP_TYPE_ETHERTAP;
498 mymac.type = SUBNET_MAC;
499 mymac.net.mac.address.x[0] = 0xfe;
500 mymac.net.mac.address.x[1] = 0xfd;
501 mymac.net.mac.address.x[2] = 0x00;
502 mymac.net.mac.address.x[3] = 0x00;
503 mymac.net.mac.address.x[4] = 0x00;
504 mymac.net.mac.address.x[5] = 0x00;
507 /* Ok now check if this is an old ethertap or a new tun/tap thingie */
508 memset(&ifr, 0, sizeof(ifr));
510 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
512 strncpy(ifr.ifr_name, netname, IFNAMSIZ);
514 if (!ioctl(tap_fd, TUNSETIFF, (void *) &ifr))
516 syslog(LOG_INFO, _("%s is a new style tun/tap device"), tapfname);
517 taptype = TAP_TYPE_TUNTAP;
525 set up the socket that we listen on for incoming
528 int setup_listen_meta_socket(int port)
531 struct sockaddr_in a;
535 if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
537 syslog(LOG_ERR, _("Creating metasocket failed: %m"));
541 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
544 syslog(LOG_ERR, _("System call `%s' failed: %m"),
549 if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one)))
552 syslog(LOG_ERR, _("System call `%s' failed: %m"),
557 flags = fcntl(nfd, F_GETFL);
558 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
561 syslog(LOG_ERR, _("System call `%s' failed: %m"),
566 if((cfg = get_config_val(config, config_interface)))
568 if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, cfg->data.ptr, strlen(cfg->data.ptr)))
571 syslog(LOG_ERR, _("Unable to bind listen socket to interface %s: %m"), cfg->data.ptr);
576 memset(&a, 0, sizeof(a));
577 a.sin_family = AF_INET;
578 a.sin_port = htons(port);
580 if((cfg = get_config_val(config, config_interfaceip)))
581 a.sin_addr.s_addr = htonl(cfg->data.ip->address);
583 a.sin_addr.s_addr = htonl(INADDR_ANY);
585 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
588 syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
595 syslog(LOG_ERR, _("System call `%s' failed: %m"),
604 setup the socket for incoming encrypted
607 int setup_vpn_in_socket(int port)
610 struct sockaddr_in a;
613 if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
616 syslog(LOG_ERR, _("Creating socket failed: %m"));
620 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
623 syslog(LOG_ERR, _("System call `%s' failed: %m"),
628 flags = fcntl(nfd, F_GETFL);
629 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
632 syslog(LOG_ERR, _("System call `%s' failed: %m"),
637 memset(&a, 0, sizeof(a));
638 a.sin_family = AF_INET;
639 a.sin_port = htons(port);
640 a.sin_addr.s_addr = htonl(INADDR_ANY);
642 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
645 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
653 setup an outgoing meta (tcp) socket
655 int setup_outgoing_meta_socket(conn_list_t *cl)
658 struct sockaddr_in a;
661 if(debug_lvl >= DEBUG_CONNECTIONS)
662 syslog(LOG_INFO, _("Trying to connect to %s"), cl->hostname);
664 if((cfg = get_config_val(cl->config, config_port)) == NULL)
667 cl->port = cfg->data.val;
669 cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
670 if(cl->meta_socket == -1)
672 syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
673 cl->hostname, cl->port);
677 a.sin_family = AF_INET;
678 a.sin_port = htons(cl->port);
679 a.sin_addr.s_addr = htonl(cl->address);
681 if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
683 close(cl->meta_socket);
684 syslog(LOG_ERR, _("%s port %hd: %m"), cl->hostname, cl->port);
688 flags = fcntl(cl->meta_socket, F_GETFL);
689 if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
691 close(cl->meta_socket);
692 syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
693 cl->hostname, cl->port);
697 if(debug_lvl >= DEBUG_CONNECTIONS)
698 syslog(LOG_INFO, _("Connected to %s port %hd"),
699 cl->hostname, cl->port);
707 setup an outgoing connection. It's not
708 necessary to also open an udp socket as
709 well, because the other host will initiate
710 an authentication sequence during which
711 we will do just that.
713 int setup_outgoing_connection(char *name)
721 syslog(LOG_ERR, _("Invalid name for outgoing connection"));
725 ncn = new_conn_list();
726 asprintf(&ncn->name, "%s", name);
728 if(read_host_config(ncn))
730 syslog(LOG_ERR, _("Error reading host configuration file for %s"));
735 if(!(cfg = get_config_val(ncn->config, config_address)))
737 syslog(LOG_ERR, _("No address specified for %s"));
742 if(!(h = gethostbyname(cfg->data.ptr)))
744 syslog(LOG_ERR, _("Error looking up `%s': %m"), cfg->data.ptr);
749 ncn->address = ntohl(*((ip_t*)(h->h_addr_list[0])));
750 ncn->hostname = hostlookup(htonl(ncn->address));
752 if(setup_outgoing_meta_socket(ncn) < 0)
754 syslog(LOG_ERR, _("Could not set up a meta connection to %s"),
760 ncn->status.outgoing = 1;
761 ncn->buffer = xmalloc(MAXBUFSIZE);
763 ncn->last_ping_time = time(NULL);
773 Configure conn_list_t myself and set up the local sockets (listen only)
775 int setup_myself(void)
781 myself = new_conn_list();
783 asprintf(&myself->hostname, "MYSELF"); /* FIXME? Do hostlookup on ourselves? */
785 myself->protocol_version = PROT_CURRENT;
787 if(!(cfg = get_config_val(config, config_name))) /* Not acceptable */
789 syslog(LOG_ERR, _("Name for tinc daemon required!"));
793 asprintf(&myself->name, "%s", (char*)cfg->data.val);
795 if(check_id(myself->name))
797 syslog(LOG_ERR, _("Invalid name for myself!"));
801 if(!(cfg = get_config_val(config, config_privatekey)))
803 syslog(LOG_ERR, _("Private key for tinc daemon required!"));
808 myself->rsa_key = RSA_new();
809 BN_hex2bn(&myself->rsa_key->d, cfg->data.ptr);
810 BN_hex2bn(&myself->rsa_key->e, "FFFF");
813 if(read_host_config(myself))
815 syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
819 if(!(cfg = get_config_val(myself->config, config_publickey)))
821 syslog(LOG_ERR, _("Public key for tinc daemon required!"));
826 BN_hex2bn(&myself->rsa_key->n, cfg->data.ptr);
829 if(RSA_check_key(myself->rsa_key) != 1)
831 syslog(LOG_ERR, _("Invalid public/private keypair!"));
835 if(!(cfg = get_config_val(myself->config, config_port)))
838 myself->port = cfg->data.val;
840 if((cfg = get_config_val(myself->config, config_indirectdata)))
841 if(cfg->data.val == stupid_true)
842 myself->flags |= EXPORTINDIRECTDATA;
844 if((cfg = get_config_val(myself->config, config_tcponly)))
845 if(cfg->data.val == stupid_true)
846 myself->flags |= TCPONLY;
848 /* Read in all the subnets specified in the host configuration file */
850 for(next = myself->config; (cfg = get_config_val(next, config_subnet)); next = cfg->next)
853 net->type = SUBNET_IPV4;
854 net->net.ipv4.address = cfg->data.ip->address;
855 net->net.ipv4.mask = cfg->data.ip->mask;
857 /* Teach newbies what subnets are... */
859 if((net->net.ipv4.address & net->net.ipv4.mask) != net->net.ipv4.address)
861 syslog(LOG_ERR, _("Network address and subnet mask do not match!"));
865 subnet_add(myself, net);
868 if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
870 syslog(LOG_ERR, _("Unable to set up a listening socket!"));
874 /* Generate packet encryption key */
876 myself->cipher_pkttype = EVP_bf_cfb();
878 myself->cipher_pktkeylength = myself->cipher_pkttype->key_len + myself->cipher_pkttype->iv_len;
880 myself->cipher_pktkey = (char *)xmalloc(myself->cipher_pktkeylength);
881 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
883 if(!(cfg = get_config_val(config, config_keyexpire)))
886 keylifetime = cfg->data.val;
888 keyexpires = time(NULL) + keylifetime;
890 /* Activate ourselves */
892 myself->status.active = 1;
894 syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
900 sigalrm_handler(int a)
904 cfg = get_config_val(upstreamcfg, config_connectto);
906 if(!cfg && upstreamcfg == config)
907 /* No upstream IP given, we're listen only. */
912 upstreamcfg = cfg->next;
913 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
915 signal(SIGALRM, SIG_IGN);
918 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
921 signal(SIGALRM, sigalrm_handler);
922 upstreamcfg = config;
923 seconds_till_retry += 5;
924 if(seconds_till_retry > MAXTIMEOUT) /* Don't wait more than MAXTIMEOUT seconds. */
925 seconds_till_retry = MAXTIMEOUT;
926 syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
928 alarm(seconds_till_retry);
933 setup all initial network connections
935 int setup_network_connections(void)
939 if((cfg = get_config_val(config, config_pingtimeout)) == NULL)
943 timeout = cfg->data.val;
950 if(setup_tap_fd() < 0)
953 if(setup_myself() < 0)
956 /* Run tinc-up script to further initialize the tap interface */
957 execute_script("tinc-up");
959 if(!(cfg = get_config_val(config, config_connectto)))
960 /* No upstream IP given, we're listen only. */
965 upstreamcfg = cfg->next;
966 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
968 cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
971 signal(SIGALRM, sigalrm_handler);
972 upstreamcfg = config;
973 seconds_till_retry = MAXTIMEOUT;
974 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
975 alarm(seconds_till_retry);
981 close all open network connections
983 void close_network_connections(void)
987 for(p = conn_list; p != NULL; p = p->next)
989 p->status.active = 0;
990 terminate_connection(p);
994 if(myself->status.active)
996 close(myself->meta_socket);
997 free_conn_list(myself);
1003 /* Execute tinc-down script right after shutting down the interface */
1004 execute_script("tinc-down");
1006 destroy_conn_list();
1008 syslog(LOG_NOTICE, _("Terminating"));
1014 create a data (udp) socket
1016 int setup_vpn_connection(conn_list_t *cl)
1019 struct sockaddr_in a;
1022 if(debug_lvl >= DEBUG_TRAFFIC)
1023 syslog(LOG_DEBUG, _("Opening UDP socket to %s"), cl->hostname);
1025 nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
1028 syslog(LOG_ERR, _("Creating UDP socket failed: %m"));
1032 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
1035 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1040 flags = fcntl(nfd, F_GETFL);
1041 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
1044 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1049 memset(&a, 0, sizeof(a));
1050 a.sin_family = AF_INET;
1051 a.sin_port = htons(myself->port);
1052 a.sin_addr.s_addr = htonl(INADDR_ANY);
1054 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
1057 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), myself->port);
1061 a.sin_family = AF_INET;
1062 a.sin_port = htons(cl->port);
1063 a.sin_addr.s_addr = htonl(cl->address);
1065 if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
1068 syslog(LOG_ERR, _("Connecting to %s port %d failed: %m"),
1069 cl->hostname, cl->port);
1073 flags = fcntl(nfd, F_GETFL);
1074 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
1077 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m %s (%s)"), __FILE__, __LINE__, nfd,
1078 cl->name, cl->hostname);
1083 cl->status.dataopen = 1;
1089 handle an incoming tcp connect call and open
1092 conn_list_t *create_new_connection(int sfd)
1095 struct sockaddr_in ci;
1096 int len = sizeof(ci);
1098 p = new_conn_list();
1100 if(getpeername(sfd, &ci, &len) < 0)
1102 syslog(LOG_ERR, _("System call `%s' failed: %m"),
1108 p->address = ntohl(ci.sin_addr.s_addr);
1109 p->hostname = hostlookup(ci.sin_addr.s_addr);
1110 p->meta_socket = sfd;
1112 p->buffer = xmalloc(MAXBUFSIZE);
1114 p->last_ping_time = time(NULL);
1116 if(debug_lvl >= DEBUG_CONNECTIONS)
1117 syslog(LOG_NOTICE, _("Connection from %s port %d"),
1118 p->hostname, htons(ci.sin_port));
1120 p->allow_request = ID;
1126 put all file descriptors in an fd_set array
1128 void build_fdset(fd_set *fs)
1134 for(p = conn_list; p != NULL; p = p->next)
1137 FD_SET(p->meta_socket, fs);
1138 if(p->status.dataopen)
1139 FD_SET(p->socket, fs);
1142 FD_SET(myself->meta_socket, fs);
1148 receive incoming data from the listening
1149 udp socket and write it to the ethertap
1150 device after being decrypted
1152 int handle_incoming_vpn_data(conn_list_t *cl)
1155 int x, l = sizeof(x);
1158 if(getsockopt(cl->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1160 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1161 __FILE__, __LINE__, cl->socket);
1166 syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1170 if((lenin = recv(cl->socket, (char *) &(pkt.len), MTU, 0)) <= 0)
1172 syslog(LOG_ERR, _("Receiving packet failed: %m"));
1176 if(debug_lvl >= DEBUG_TRAFFIC)
1178 syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"), lenin,
1179 cl->name, cl->hostname);
1183 return xrecv(cl, &pkt);
1187 terminate a connection and notify the other
1188 end before closing the sockets
1190 void terminate_connection(conn_list_t *cl)
1195 if(cl->status.remove)
1198 cl->status.remove = 1;
1200 if(debug_lvl >= DEBUG_CONNECTIONS)
1201 syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1202 cl->name, cl->hostname);
1207 close(cl->meta_socket);
1210 /* Find all connections that were lost because they were behind cl
1211 (the connection that was dropped). */
1214 for(p = conn_list; p != NULL; p = p->next)
1215 if((p->nexthop == cl) && (p != cl))
1216 terminate_connection(p); /* Sounds like recursion, but p does not have a meta connection :) */
1218 /* Inform others of termination if it was still active */
1220 if(cl->status.active)
1221 for(p = conn_list; p != NULL; p = p->next)
1222 if(p->status.meta && p->status.active && p!=cl)
1223 send_del_host(p, cl);
1225 /* Remove the associated subnets */
1227 for(s = cl->subnets; s; s = s->next)
1230 /* Check if this was our outgoing connection */
1232 if(cl->status.outgoing && cl->status.active)
1234 signal(SIGALRM, sigalrm_handler);
1235 seconds_till_retry = 5;
1236 alarm(seconds_till_retry);
1237 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
1242 cl->status.active = 0;
1247 Check if the other end is active.
1248 If we have sent packets, but didn't receive any,
1249 then possibly the other end is dead. We send a
1250 PING request over the meta connection. If the other
1251 end does not reply in time, we consider them dead
1252 and close the connection.
1254 int check_dead_connections(void)
1260 for(p = conn_list; p != NULL; p = p->next)
1262 if(p->status.active && p->status.meta)
1264 if(p->last_ping_time + timeout < now)
1266 if(p->status.pinged)
1268 if(debug_lvl >= DEBUG_PROTOCOL)
1269 syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1270 p->name, p->hostname);
1271 p->status.timeout = 1;
1272 terminate_connection(p);
1286 accept a new tcp connect and create a
1289 int handle_new_meta_connection()
1292 struct sockaddr client;
1293 int nfd, len = sizeof(client);
1295 if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
1297 syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1301 if(!(ncn = create_new_connection(nfd)))
1305 syslog(LOG_NOTICE, _("Closed attempted connection"));
1315 check all connections to see if anything
1316 happened on their sockets
1318 void check_network_activity(fd_set *f)
1322 for(p = conn_list; p != NULL; p = p->next)
1324 if(p->status.remove)
1327 if(p->status.dataopen)
1328 if(FD_ISSET(p->socket, f))
1330 handle_incoming_vpn_data(p);
1332 /* Old error stuff (FIXME: copy this to handle_incoming_vpn_data()
1334 getsockopt(p->socket, SOL_SOCKET, SO_ERROR, &x, &l);
1335 syslog(LOG_ERR, _("Outgoing data socket error for %s (%s): %s"),
1336 p->name, p->hostname, strerror(x));
1337 terminate_connection(p);
1343 if(FD_ISSET(p->meta_socket, f))
1344 if(receive_meta(p) < 0)
1346 terminate_connection(p);
1351 if(FD_ISSET(myself->meta_socket, f))
1352 handle_new_meta_connection();
1357 read, encrypt and send data that is
1358 available through the ethertap device
1360 void handle_tap_input(void)
1365 if(taptype == TAP_TYPE_TUNTAP)
1367 if((lenin = read(tap_fd, vp.data, MTU)) <= 0)
1369 syslog(LOG_ERR, _("Error while reading from tun/tap device: %m"));
1376 if((lenin = read(tap_fd, vp.data - 2, MTU)) <= 0)
1378 syslog(LOG_ERR, _("Error while reading from ethertap device: %m"));
1384 total_tap_in += lenin;
1388 if(debug_lvl >= DEBUG_TRAFFIC)
1389 syslog(LOG_WARNING, _("Received short packet from tap device"));
1393 if(debug_lvl >= DEBUG_TRAFFIC)
1395 syslog(LOG_DEBUG, _("Read packet of length %d from tap device"), vp.len);
1398 send_packet(ntohl(*((unsigned long*)(&vp.data[30]))), &vp);
1403 this is where it all happens...
1405 void main_loop(void)
1410 time_t last_ping_check;
1413 last_ping_check = time(NULL);
1417 tv.tv_sec = timeout;
1423 if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1425 if(errno != EINTR) /* because of alarm */
1427 syslog(LOG_ERR, _("Error while waiting for input: %m"));
1434 syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1436 close_network_connections();
1437 clear_config(&config);
1439 if(read_server_config())
1441 syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1447 if(setup_network_connections())
1455 /* Let's check if everybody is still alive */
1457 if(last_ping_check + timeout < t)
1459 check_dead_connections();
1460 last_ping_check = time(NULL);
1462 /* Should we regenerate our key? */
1466 if(debug_lvl >= DEBUG_STATUS)
1467 syslog(LOG_INFO, _("Regenerating symmetric key"));
1469 RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
1470 send_key_changed(myself, NULL);
1471 keyexpires = time(NULL) + keylifetime;
1477 check_network_activity(&fset);
1479 /* local tap data */
1480 if(FD_ISSET(tap_fd, &fset))