- Prepended config_ to all configuration option names, because it confused
[tinc] / src / net.c
1 /*
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>
5
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.
10
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.
15
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.
19
20     $Id: net.c,v 1.35.4.67 2000/11/04 22:57:30 guus Exp $
21 */
22
23 #include "config.h"
24
25 #include <arpa/inet.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <linux/sockios.h>
29 #include <net/if.h>
30 #include <netdb.h>
31 #include <netinet/in.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <sys/signal.h>
36 #include <sys/socket.h>
37 #include <sys/time.h>
38 #include <sys/types.h>
39 #include <syslog.h>
40 #include <unistd.h>
41 #include <sys/ioctl.h>
42 #include <openssl/rand.h>
43 #include <openssl/evp.h>
44 #include <openssl/err.h>
45
46 #ifdef HAVE_TUNTAP
47 #include LINUX_IF_TUN_H
48 #endif
49
50 #include <utils.h>
51 #include <xalloc.h>
52
53 #include "conf.h"
54 #include "connlist.h"
55 #include "meta.h"
56 #include "net.h"
57 #include "netutl.h"
58 #include "protocol.h"
59 #include "subnet.h"
60
61 #include "system.h"
62
63 int tap_fd = -1;
64 int taptype = TAP_TYPE_ETHERTAP;
65 int total_tap_in = 0;
66 int total_tap_out = 0;
67 int total_socket_in = 0;
68 int total_socket_out = 0;
69
70 config_t *upstreamcfg;
71 static int seconds_till_retry;
72
73 int keylifetime = 0;
74 int keyexpires = 0;
75
76 char *unknown = NULL;
77 char *interface_name = NULL;  /* Contains the name of the interface */
78
79 subnet_t mymac;
80
81 /*
82   Execute the given script.
83   This function doesn't really belong here.
84 */
85 int execute_script(const char* name)
86 {
87   char *scriptname;
88   pid_t pid;
89   char *s;
90
91   if((pid = fork()) < 0)
92     {
93       syslog(LOG_ERR, _("System call `%s' failed: %m"),
94              "fork");
95       return -1;
96     }
97
98   if(pid)
99     {
100       return 0;
101     }
102
103   /* Child here */
104
105   asprintf(&scriptname, "%s/%s", confbase, name);
106   asprintf(&s, "IFNAME=%s", interface_name);
107   putenv(s);
108   free(s);
109
110   if(netname)
111     {
112       asprintf(&s, "NETNAME=%s", netname);
113       putenv(s);
114       free(s);
115     }
116   else
117     {
118       unsetenv("NETNAME");
119     }
120
121   if(chdir(confbase) < 0)
122     {
123       syslog(LOG_ERR, _("Couldn't chdir to `%s': %m"),
124              confbase);
125     }
126   
127   execl(scriptname, NULL);
128   /* No return on success */
129   
130   if(errno != ENOENT)  /* Ignore if the file does not exist */
131     syslog(LOG_WARNING, _("Error executing `%s': %m"), scriptname);
132
133   /* No need to free things */
134   exit(0);
135 }
136
137 int xsend(conn_list_t *cl, vpn_packet_t *inpkt)
138 {
139   vpn_packet_t outpkt;
140   int outlen, outpad;
141   EVP_CIPHER_CTX ctx;
142 cp
143   outpkt.len = inpkt->len;
144   
145   /* Encrypt the packet */
146   
147   EVP_EncryptInit(&ctx, cl->cipher_pkttype, cl->cipher_pktkey, cl->cipher_pktkey + cl->cipher_pkttype->key_len);
148   EVP_EncryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len);
149   EVP_EncryptFinal(&ctx, outpkt.data + outlen, &outpad);
150   outlen += outpad + 2;
151
152 /* Bypass
153   outlen = outpkt.len + 2;
154   memcpy(&outpkt, inpkt, outlen);
155 */  
156
157   if(debug_lvl >= DEBUG_TRAFFIC)
158     syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
159            outlen, cl->name, cl->hostname);
160
161   total_socket_out += outlen;
162
163   if((send(cl->socket, (char *) &(outpkt.len), outlen, 0)) < 0)
164     {
165       syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
166              cl->name, cl->hostname);
167       return -1;
168     }
169 cp
170   return 0;
171 }
172
173 int xrecv(conn_list_t *cl, vpn_packet_t *inpkt)
174 {
175   vpn_packet_t outpkt;
176   int outlen, outpad;
177   EVP_CIPHER_CTX ctx;
178 cp
179   outpkt.len = inpkt->len;
180
181   /* Decrypt the packet */
182
183   EVP_DecryptInit(&ctx, myself->cipher_pkttype, myself->cipher_pktkey, myself->cipher_pktkey + myself->cipher_pkttype->key_len);
184   EVP_DecryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len + 8);
185   EVP_DecryptFinal(&ctx, outpkt.data + outlen, &outpad);
186   outlen += outpad;
187
188 /* Bypass
189   outlen = outpkt.len+2;
190   memcpy(&outpkt, inpkt, outlen);
191 */
192      
193   if(debug_lvl >= DEBUG_TRAFFIC)
194     syslog(LOG_ERR, _("Writing packet of %d bytes to tap device"),
195            outpkt.len, outlen);
196
197   /* Fix mac address */
198
199   memcpy(outpkt.data, mymac.net.mac.address.x, 6);
200
201   if(taptype == TAP_TYPE_TUNTAP)
202     {
203       if(write(tap_fd, outpkt.data, outpkt.len) < 0)
204         syslog(LOG_ERR, _("Can't write to tun/tap device: %m"));
205       else
206         total_tap_out += outpkt.len;
207     }
208   else  /* ethertap */
209     {
210       if(write(tap_fd, outpkt.data - 2, outpkt.len + 2) < 0)
211         syslog(LOG_ERR, _("Can't write to ethertap device: %m"));
212       else
213         total_tap_out += outpkt.len + 2;
214     }
215 cp
216   return 0;
217 }
218
219 /*
220   add the given packet of size s to the
221   queue q, be it the send or receive queue
222 */
223 void add_queue(packet_queue_t **q, void *packet, size_t s)
224 {
225   queue_element_t *e;
226 cp
227   e = xmalloc(sizeof(*e));
228   e->packet = xmalloc(s);
229   memcpy(e->packet, packet, s);
230
231   if(!*q)
232     {
233       *q = xmalloc(sizeof(**q));
234       (*q)->head = (*q)->tail = NULL;
235     }
236
237   e->next = NULL;                       /* We insert at the tail */
238
239   if((*q)->tail)                        /* Do we have a tail? */
240     {
241       (*q)->tail->next = e;
242       e->prev = (*q)->tail;
243     }
244   else                                  /* No tail -> no head too */
245     {
246       (*q)->head = e;
247       e->prev = NULL;
248     }
249
250   (*q)->tail = e;
251 cp
252 }
253
254 /* Remove a queue element */
255 void del_queue(packet_queue_t **q, queue_element_t *e)
256 {
257 cp
258   free(e->packet);
259
260   if(e->next)                           /* There is a successor, so we are not tail */
261     {
262       if(e->prev)                       /* There is a predecessor, so we are not head */
263         {
264           e->next->prev = e->prev;
265           e->prev->next = e->next;
266         }
267       else                              /* We are head */
268         {
269           e->next->prev = NULL;
270           (*q)->head = e->next;
271         }
272     }
273   else                                  /* We are tail (or all alone!) */
274     {          
275       if(e->prev)                       /* We are not alone :) */
276         {
277           e->prev->next = NULL;
278           (*q)->tail = e->prev;
279         }
280       else                              /* Adieu */
281         {
282           free(*q);
283           *q = NULL;
284         }
285     }
286     
287   free(e);
288 cp
289 }
290
291 /*
292   flush a queue by calling function for
293   each packet, and removing it when that
294   returned a zero exit code
295 */
296 void flush_queue(conn_list_t *cl, packet_queue_t **pq,
297                  int (*function)(conn_list_t*,vpn_packet_t*))
298 {
299   queue_element_t *p, *next = NULL;
300 cp
301   for(p = (*pq)->head; p != NULL; )
302     {
303       next = p->next;
304
305       if(!function(cl, p->packet))
306         del_queue(pq, p);
307         
308       p = next;
309     }
310
311   if(debug_lvl >= DEBUG_TRAFFIC)
312     syslog(LOG_DEBUG, _("Queue flushed"));
313 cp
314 }
315
316 /*
317   flush the send&recv queues
318   void because nothing goes wrong here, packets
319   remain in the queue if something goes wrong
320 */
321 void flush_queues(conn_list_t *cl)
322 {
323 cp
324   if(cl->sq)
325     {
326       if(debug_lvl >= DEBUG_TRAFFIC)
327         syslog(LOG_DEBUG, _("Flushing send queue for %s (%s)"),
328                cl->name, cl->hostname);
329       flush_queue(cl, &(cl->sq), xsend);
330     }
331
332   if(cl->rq)
333     {
334       if(debug_lvl >=  DEBUG_TRAFFIC)
335         syslog(LOG_DEBUG, _("Flushing receive queue for %s (%s)"),
336                cl->name, cl->hostname);
337       flush_queue(cl, &(cl->rq), xrecv);
338     }
339 cp
340 }
341
342 /*
343   send a packet to the given vpn ip.
344 */
345 int send_packet(ip_t to, vpn_packet_t *packet)
346 {
347   conn_list_t *cl;
348   subnet_t *subnet;
349 cp
350   if((subnet = lookup_subnet_ipv4(to)) == NULL)
351     {
352       if(debug_lvl >= DEBUG_TRAFFIC)
353         {
354           syslog(LOG_NOTICE, _("Trying to look up %d.%d.%d.%d in connection list failed!"),
355                  IP_ADDR_V(to));
356         }
357
358       return -1;
359     }
360
361   cl = subnet->owner;
362     
363   if(cl == myself)
364     {
365       if(debug_lvl >= DEBUG_TRAFFIC)
366         {
367           syslog(LOG_NOTICE, _("Packet with destination %d.%d.%d.%d is looping back to us!"),
368                  IP_ADDR_V(to));
369         }
370
371       return -1;
372     }
373
374   /* If we ourselves have indirectdata flag set, we should send only to our uplink! */
375
376   /* FIXME - check for indirection and reprogram it The Right Way(tm) this time. */
377   
378   /* Connections are now opened beforehand...
379
380   if(!cl->status.dataopen)
381     if(setup_vpn_connection(cl) < 0)
382       {
383         syslog(LOG_ERR, _("Could not open UDP connection to %s (%s)"),
384                cl->name, cl->hostname);
385         return -1;
386       }
387   */
388       
389   if(!cl->status.validkey)
390     {
391 /* FIXME: Don't queue until everything else is fixed.
392       if(debug_lvl >= DEBUG_TRAFFIC)
393         syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
394                cl->name, cl->hostname);
395       add_queue(&(cl->sq), packet, packet->len + 2);
396 */
397       if(!cl->status.waitingforkey)
398         send_req_key(myself, cl);                       /* Keys should be sent to the host running the tincd */
399       return 0;
400     }
401
402   if(!cl->status.active)
403     {
404 /* FIXME: Don't queue until everything else is fixed.
405       if(debug_lvl >= DEBUG_TRAFFIC)
406         syslog(LOG_INFO, _("%s (%s) is not ready, queueing packet"),
407                cl->name, cl->hostname);
408       add_queue(&(cl->sq), packet, packet->len + 2);
409 */
410       return 0; /* We don't want to mess up, do we? */
411     }
412
413   /* can we send it? can we? can we? huh? */
414 cp
415   return xsend(cl, packet);
416 }
417
418 /*
419   open the local ethertap device
420 */
421 int setup_tap_fd(void)
422 {
423   int nfd;
424   const char *tapfname;
425   config_t const *cfg;
426   struct ifreq ifr;
427
428 cp  
429   if((cfg = get_config_val(config, config_tapdevice)))
430     tapfname = cfg->data.ptr;
431   else
432 #ifdef HAVE_TUNTAP
433     tapfname = "/dev/misc/net/tun";
434 #else
435     tapfname = "/dev/tap0";
436 #endif
437 cp
438   if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
439     {
440       syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
441       return -1;
442     }
443 cp
444   tap_fd = nfd;
445
446   /* Set default MAC address for ethertap devices */
447   
448   taptype = TAP_TYPE_ETHERTAP;
449   mymac.type = SUBNET_MAC;
450   mymac.net.mac.address.x[0] = 0xfe;
451   mymac.net.mac.address.x[1] = 0xfd;
452   mymac.net.mac.address.x[2] = 0x00;
453   mymac.net.mac.address.x[3] = 0x00;
454   mymac.net.mac.address.x[4] = 0x00;
455   mymac.net.mac.address.x[5] = 0x00;
456
457 #ifdef HAVE_TUNTAP
458   /* Ok now check if this is an old ethertap or a new tun/tap thingie */
459   memset(&ifr, 0, sizeof(ifr));
460 cp
461   ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
462   if (netname)
463     strncpy(ifr.ifr_name, netname, IFNAMSIZ);
464 cp
465   if (!ioctl(tap_fd, TUNSETIFF, (void *) &ifr))
466   { 
467     syslog(LOG_INFO, _("%s is a new style tun/tap device"), tapfname);
468     taptype = TAP_TYPE_TUNTAP;
469   }
470 #endif
471
472   /* Add name of network interface to environment (for scripts) */
473
474   ioctl(tap_fd, SIOCGIFNAME, (void *) &ifr);
475   interface_name = xmalloc(strlen(ifr.ifr_name));
476   strcpy(interface_name, ifr.ifr_name);
477   
478 cp
479   return 0;
480 }
481
482 /*
483   set up the socket that we listen on for incoming
484   (tcp) connections
485 */
486 int setup_listen_meta_socket(int port)
487 {
488   int nfd, flags;
489   struct sockaddr_in a;
490   const int one = 1;
491   config_t const *cfg;
492 cp
493   if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
494     {
495       syslog(LOG_ERR, _("Creating metasocket failed: %m"));
496       return -1;
497     }
498
499   if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
500     {
501       syslog(LOG_ERR, _("System call `%s' failed: %m"),
502              "setsockopt");
503       return -1;
504     }
505
506   if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one)))
507     {
508       syslog(LOG_ERR, _("System call `%s' failed: %m"),
509              "setsockopt");
510       return -1;
511     }
512
513   flags = fcntl(nfd, F_GETFL);
514   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
515     {
516       syslog(LOG_ERR, _("System call `%s' failed: %m"),
517              "fcntl");
518       return -1;
519     }
520
521   if((cfg = get_config_val(config, config_interface)))
522     {
523       if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, cfg->data.ptr, strlen(cfg->data.ptr)))
524         {
525           syslog(LOG_ERR, _("Unable to bind listen socket to interface %s: %m"), cfg->data.ptr);
526           return -1;
527         }
528     }
529
530   memset(&a, 0, sizeof(a));
531   a.sin_family = AF_INET;
532   a.sin_port = htons(port);
533   
534   if((cfg = get_config_val(config, config_interfaceip)))
535     a.sin_addr.s_addr = htonl(cfg->data.ip->address);
536   else
537     a.sin_addr.s_addr = htonl(INADDR_ANY);
538
539   if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
540     {
541       syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
542       return -1;
543     }
544
545   if(listen(nfd, 3))
546     {
547       syslog(LOG_ERR, _("System call `%s' failed: %m"),
548              "listen");
549       return -1;
550     }
551 cp
552   return nfd;
553 }
554
555 /*
556   setup the socket for incoming encrypted
557   data (the udp part)
558 */
559 int setup_vpn_in_socket(int port)
560 {
561   int nfd, flags;
562   struct sockaddr_in a;
563   const int one = 1;
564 cp
565   if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
566     {
567       syslog(LOG_ERR, _("Creating socket failed: %m"));
568       return -1;
569     }
570
571   if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
572     {
573       syslog(LOG_ERR, _("System call `%s' failed: %m"),
574              "setsockopt");
575       return -1;
576     }
577
578   flags = fcntl(nfd, F_GETFL);
579   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
580     {
581       syslog(LOG_ERR, _("System call `%s' failed: %m"),
582              "fcntl");
583       return -1;
584     }
585
586   memset(&a, 0, sizeof(a));
587   a.sin_family = AF_INET;
588   a.sin_port = htons(port);
589   a.sin_addr.s_addr = htonl(INADDR_ANY);
590
591   if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
592     {
593       syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
594       return -1;
595     }
596 cp
597   return nfd;
598 }
599
600 /*
601   setup an outgoing meta (tcp) socket
602 */
603 int setup_outgoing_meta_socket(conn_list_t *cl)
604 {
605   int flags;
606   struct sockaddr_in a;
607   config_t const *cfg;
608 cp
609   if(debug_lvl >= DEBUG_CONNECTIONS)
610     syslog(LOG_INFO, _("Trying to connect to %s"), cl->hostname);
611
612   if((cfg = get_config_val(cl->config, config_port)) == NULL)
613     cl->port = 655;
614   else
615     cl->port = cfg->data.val;
616
617   cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
618   if(cl->meta_socket == -1)
619     {
620       syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
621              cl->hostname, cl->port);
622       return -1;
623     }
624
625   a.sin_family = AF_INET;
626   a.sin_port = htons(cl->port);
627   a.sin_addr.s_addr = htonl(cl->address);
628
629   if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
630     {
631       syslog(LOG_ERR, _("%s port %hd: %m"), cl->hostname, cl->port);
632       return -1;
633     }
634
635   flags = fcntl(cl->meta_socket, F_GETFL);
636   if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
637     {
638       syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
639              cl->hostname, cl->port);
640       return -1;
641     }
642
643   if(debug_lvl >= DEBUG_CONNECTIONS)
644     syslog(LOG_INFO, _("Connected to %s port %hd"),
645          cl->hostname, cl->port);
646
647   cl->status.meta = 1;
648 cp
649   return 0;
650 }
651
652 /*
653   setup an outgoing connection. It's not
654   necessary to also open an udp socket as
655   well, because the other host will initiate
656   an authentication sequence during which
657   we will do just that.
658 */
659 int setup_outgoing_connection(char *name)
660 {
661   conn_list_t *ncn;
662   struct hostent *h;
663   config_t const *cfg;
664 cp
665   if(check_id(name))
666     {
667       syslog(LOG_ERR, _("Invalid name for outgoing connection"));
668       return -1;
669     }
670
671   ncn = new_conn_list();
672   asprintf(&ncn->name, "%s", name);
673     
674   if(read_host_config(ncn))
675     {
676       syslog(LOG_ERR, _("Error reading host configuration file for %s"));
677       free_conn_list(ncn);
678       return -1;
679     }
680     
681   if(!(cfg = get_config_val(ncn->config, config_address)))
682     {
683       syslog(LOG_ERR, _("No address specified for %s"));
684       free_conn_list(ncn);
685       return -1;
686     }
687     
688   if(!(h = gethostbyname(cfg->data.ptr)))
689     {
690       syslog(LOG_ERR, _("Error looking up `%s': %m"), cfg->data.ptr);
691       free_conn_list(ncn);
692       return -1;
693     }
694
695   ncn->address = ntohl(*((ip_t*)(h->h_addr_list[0])));
696   ncn->hostname = hostlookup(htonl(ncn->address));
697   
698   if(setup_outgoing_meta_socket(ncn) < 0)
699     {
700       syslog(LOG_ERR, _("Could not set up a meta connection to %s"),
701              ncn->hostname);
702       free_conn_list(ncn);
703       return -1;
704     }
705
706   ncn->status.outgoing = 1;
707   ncn->buffer = xmalloc(MAXBUFSIZE);
708   ncn->buflen = 0;
709   ncn->last_ping_time = time(NULL);
710
711   conn_list_add(ncn);
712
713   send_id(ncn);
714 cp
715   return 0;
716 }
717
718 /*
719   Configure conn_list_t myself and set up the local sockets (listen only)
720 */
721 int setup_myself(void)
722 {
723   config_t const *cfg;
724   config_t *next;
725   subnet_t *net;
726 cp
727   myself = new_conn_list();
728
729   asprintf(&myself->hostname, "MYSELF"); /* FIXME? Do hostlookup on ourselves? */
730   myself->flags = 0;
731   myself->protocol_version = PROT_CURRENT;
732
733   if(!(cfg = get_config_val(config, config_name))) /* Not acceptable */
734     {
735       syslog(LOG_ERR, _("Name for tinc daemon required!"));
736       return -1;
737     }
738   else
739     asprintf(&myself->name, "%s", (char*)cfg->data.val);
740
741   if(check_id(myself->name))
742     {
743       syslog(LOG_ERR, _("Invalid name for myself!"));
744       return -1;
745     }
746 cp
747   if(!(cfg = get_config_val(config, config_privatekey)))
748     {
749       syslog(LOG_ERR, _("Private key for tinc daemon required!"));
750       return -1;
751     }
752   else
753     {
754       myself->rsa_key = RSA_new();
755       BN_hex2bn(&myself->rsa_key->d, cfg->data.ptr);
756       BN_hex2bn(&myself->rsa_key->e, "FFFF");
757     }
758
759   if(read_host_config(myself))
760     {
761       syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
762       return -1;
763     }
764 cp  
765   if(!(cfg = get_config_val(myself->config, config_publickey)))
766     {
767       syslog(LOG_ERR, _("Public key for tinc daemon required!"));
768       return -1;
769     }
770   else
771     {
772       BN_hex2bn(&myself->rsa_key->n, cfg->data.ptr);
773     }
774 /*
775   if(RSA_check_key(myself->rsa_key) != 1)
776     {
777       syslog(LOG_ERR, _("Invalid public/private keypair!"));
778       return -1;
779     }
780 */
781   if(!(cfg = get_config_val(myself->config, config_port)))
782     myself->port = 655;
783   else
784     myself->port = cfg->data.val;
785
786   if((cfg = get_config_val(myself->config, config_indirectdata)))
787     if(cfg->data.val == stupid_true)
788       myself->flags |= EXPORTINDIRECTDATA;
789
790   if((cfg = get_config_val(myself->config, config_tcponly)))
791     if(cfg->data.val == stupid_true)
792       myself->flags |= TCPONLY;
793
794 /* Read in all the subnets specified in the host configuration file */
795
796   for(next = myself->config; (cfg = get_config_val(next, config_subnet)); next = cfg->next)
797     {
798       net = new_subnet();
799       net->type = SUBNET_IPV4;
800       net->net.ipv4.address = cfg->data.ip->address;
801       net->net.ipv4.mask = cfg->data.ip->mask;
802       
803       /* Teach newbies what subnets are... */
804       
805       if((net->net.ipv4.address & net->net.ipv4.mask) != net->net.ipv4.address)
806         {
807           syslog(LOG_ERR, _("Network address and subnet mask do not match!"));
808           return -1;
809         }        
810       
811       subnet_add(myself, net);
812     }
813     
814   if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
815     {
816       syslog(LOG_ERR, _("Unable to set up a listening socket!"));
817       return -1;
818     }
819
820   /* Generate packet encryption key */
821
822   myself->cipher_pkttype = EVP_bf_cfb();
823
824   myself->cipher_pktkeylength = myself->cipher_pkttype->key_len + myself->cipher_pkttype->iv_len;
825
826   myself->cipher_pktkey = (char *)xmalloc(myself->cipher_pktkeylength);
827   RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
828
829   if(!(cfg = get_config_val(config, config_keyexpire)))
830     keylifetime = 3600;
831   else
832     keylifetime = cfg->data.val;
833     
834   keyexpires = time(NULL) + keylifetime;
835
836   /* Activate ourselves */
837   
838   myself->status.active = 1;
839
840   syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
841 cp
842   return 0;
843 }
844
845 RETSIGTYPE
846 sigalrm_handler(int a)
847 {
848   config_t const *cfg;
849 cp
850   cfg = get_config_val(upstreamcfg, config_connectto);
851
852   if(!cfg && upstreamcfg == config)
853     /* No upstream IP given, we're listen only. */
854     return;
855
856   while(cfg)
857     {
858       upstreamcfg = cfg->next;
859       if(!setup_outgoing_connection(cfg->data.ptr))   /* function returns 0 when there are no problems */
860         {
861           signal(SIGALRM, SIG_IGN);
862           return;
863         }
864       cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
865     }
866
867   signal(SIGALRM, sigalrm_handler);
868   upstreamcfg = config;
869   seconds_till_retry += 5;
870   if(seconds_till_retry > MAXTIMEOUT)    /* Don't wait more than MAXTIMEOUT seconds. */
871     seconds_till_retry = MAXTIMEOUT;
872   syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
873          seconds_till_retry);
874   alarm(seconds_till_retry);
875 cp
876 }
877
878 /*
879   setup all initial network connections
880 */
881 int setup_network_connections(void)
882 {
883   config_t const *cfg;
884 cp
885   if((cfg = get_config_val(config, config_pingtimeout)) == NULL)
886     timeout = 60;
887   else
888     {
889       timeout = cfg->data.val;
890       if(timeout < 1)
891         {
892           timeout = 86400;
893         }
894      }
895
896   if(setup_tap_fd() < 0)
897     return -1;
898
899   if(setup_myself() < 0)
900     return -1;
901
902   /* Run tinc-up script to further initialize the tap interface */
903   execute_script("tinc-up");
904   
905   if(!(cfg = get_config_val(config, config_connectto)))
906     /* No upstream IP given, we're listen only. */
907     return 0;
908
909   while(cfg)
910     {
911       upstreamcfg = cfg->next;
912       if(!setup_outgoing_connection(cfg->data.ptr))   /* function returns 0 when there are no problems */
913         return 0;
914       cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
915     }
916     
917   signal(SIGALRM, sigalrm_handler);
918   upstreamcfg = config;
919   seconds_till_retry = MAXTIMEOUT;
920   syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
921   alarm(seconds_till_retry);
922 cp
923   return 0;
924 }
925
926 /*
927   close all open network connections
928 */
929 void close_network_connections(void)
930 {
931   conn_list_t *p;
932 cp
933   for(p = conn_list; p != NULL; p = p->next)
934     {
935       p->status.active = 0;
936       terminate_connection(p);
937     }
938
939   if(myself)
940     if(myself->status.active)
941       {
942         close(myself->meta_socket);
943         free_conn_list(myself);
944         myself = NULL;
945       }
946
947   close(tap_fd);
948
949   /* Execute tinc-down script right after shutting down the interface */
950   execute_script("tinc-down");
951
952   destroy_conn_list();
953
954   syslog(LOG_NOTICE, _("Terminating"));
955 cp
956   return;
957 }
958
959 /*
960   create a data (udp) socket
961 */
962 int setup_vpn_connection(conn_list_t *cl)
963 {
964   int nfd, flags;
965   struct sockaddr_in a;
966   const int one = 1;
967 cp
968   if(debug_lvl >= DEBUG_TRAFFIC)
969     syslog(LOG_DEBUG, _("Opening UDP socket to %s"), cl->hostname);
970
971   nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
972   if(nfd == -1)
973     {
974       syslog(LOG_ERR, _("Creating UDP socket failed: %m"));
975       return -1;
976     }
977
978   if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
979     {
980       syslog(LOG_ERR, _("System call `%s' failed: %m"),
981              "setsockopt");
982       return -1;
983     }
984
985   flags = fcntl(nfd, F_GETFL);
986   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
987     {
988       syslog(LOG_ERR, _("System call `%s' failed: %m"),
989              "fcntl");
990       return -1;
991     }
992
993   memset(&a, 0, sizeof(a));
994   a.sin_family = AF_INET;
995   a.sin_port = htons(myself->port);
996   a.sin_addr.s_addr = htonl(INADDR_ANY);
997
998   if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
999     {
1000       syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), myself->port);
1001       return -1;
1002     }
1003
1004   a.sin_family = AF_INET;
1005   a.sin_port = htons(cl->port);
1006   a.sin_addr.s_addr = htonl(cl->address);
1007
1008   if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
1009     {
1010       syslog(LOG_ERR, _("Connecting to %s port %d failed: %m"),
1011              cl->hostname, cl->port);
1012       return -1;
1013     }
1014
1015   flags = fcntl(nfd, F_GETFL);
1016   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
1017     {
1018       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m %s (%s)"), __FILE__, __LINE__, nfd,
1019              cl->name, cl->hostname);
1020       return -1;
1021     }
1022
1023   cl->socket = nfd;
1024   cl->status.dataopen = 1;
1025 cp
1026   return 0;
1027 }
1028
1029 /*
1030   handle an incoming tcp connect call and open
1031   a connection to it.
1032 */
1033 conn_list_t *create_new_connection(int sfd)
1034 {
1035   conn_list_t *p;
1036   struct sockaddr_in ci;
1037   int len = sizeof(ci);
1038 cp
1039   p = new_conn_list();
1040
1041   if(getpeername(sfd, &ci, &len) < 0)
1042     {
1043       syslog(LOG_ERR, _("System call `%s' failed: %m"),
1044              "getpeername");
1045       return NULL;
1046     }
1047
1048   p->name = unknown;
1049   p->address = ntohl(ci.sin_addr.s_addr);
1050   p->hostname = hostlookup(ci.sin_addr.s_addr);
1051   p->meta_socket = sfd;
1052   p->status.meta = 1;
1053   p->buffer = xmalloc(MAXBUFSIZE);
1054   p->buflen = 0;
1055   p->last_ping_time = time(NULL);
1056   
1057   if(debug_lvl >= DEBUG_CONNECTIONS)
1058     syslog(LOG_NOTICE, _("Connection from %s port %d"),
1059          p->hostname, htons(ci.sin_port));
1060
1061   p->allow_request = ID;
1062 cp
1063   return p;
1064 }
1065
1066 /*
1067   put all file descriptors in an fd_set array
1068 */
1069 void build_fdset(fd_set *fs)
1070 {
1071   conn_list_t *p;
1072 cp
1073   FD_ZERO(fs);
1074
1075   for(p = conn_list; p != NULL; p = p->next)
1076     {
1077       if(p->status.meta)
1078         FD_SET(p->meta_socket, fs);
1079       if(p->status.dataopen)
1080         FD_SET(p->socket, fs);
1081     }
1082
1083   FD_SET(myself->meta_socket, fs);
1084   FD_SET(tap_fd, fs);
1085 cp
1086 }
1087
1088 /*
1089   receive incoming data from the listening
1090   udp socket and write it to the ethertap
1091   device after being decrypted
1092 */
1093 int handle_incoming_vpn_data(conn_list_t *cl)
1094 {
1095   vpn_packet_t pkt;
1096   int x, l = sizeof(x);
1097   int lenin;
1098 cp
1099   if(getsockopt(cl->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1100     {
1101       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1102              __FILE__, __LINE__, cl->socket);
1103       return -1;
1104     }
1105   if(x)
1106     {
1107       syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1108       return -1;
1109     }
1110
1111   if((lenin = recv(cl->socket, (char *) &(pkt.len), MTU, 0)) <= 0)
1112     {
1113       syslog(LOG_ERR, _("Receiving packet failed: %m"));
1114       return -1;
1115     }
1116
1117   if(debug_lvl >= DEBUG_TRAFFIC)
1118     {
1119       syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"), lenin,
1120              cl->name, cl->hostname);
1121     }
1122
1123 cp
1124   return xrecv(cl, &pkt);
1125 }
1126
1127 /*
1128   terminate a connection and notify the other
1129   end before closing the sockets
1130 */
1131 void terminate_connection(conn_list_t *cl)
1132 {
1133   conn_list_t *p;
1134   subnet_t *s;
1135 cp
1136   if(cl->status.remove)
1137     return;
1138
1139   cl->status.remove = 1;
1140
1141   if(debug_lvl >= DEBUG_CONNECTIONS)
1142     syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1143            cl->name, cl->hostname);
1144  
1145   if(cl->socket)
1146     close(cl->socket);
1147   if(cl->status.meta)
1148     close(cl->meta_socket);
1149
1150 cp
1151   /* Find all connections that were lost because they were behind cl
1152      (the connection that was dropped). */
1153
1154   if(cl->status.meta)
1155     for(p = conn_list; p != NULL; p = p->next)
1156       if((p->nexthop == cl) && (p != cl))
1157         terminate_connection(p);        /* Sounds like recursion, but p does not have a meta connection :) */
1158
1159   /* Inform others of termination if it was still active */
1160
1161   if(cl->status.active)
1162     for(p = conn_list; p != NULL; p = p->next)
1163       if(p->status.meta && p->status.active && p!=cl)
1164         send_del_host(p, cl);
1165
1166   /* Remove the associated subnets */
1167
1168   for(s = cl->subnets; s; s = s->next)
1169     subnet_del(s);
1170
1171   /* Check if this was our outgoing connection */
1172     
1173   if(cl->status.outgoing && cl->status.active)
1174     {
1175       signal(SIGALRM, sigalrm_handler);
1176       seconds_till_retry = 5;
1177       alarm(seconds_till_retry);
1178       syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
1179     }
1180
1181   /* Inactivate */
1182
1183   cl->status.active = 0;
1184 cp
1185 }
1186
1187 /*
1188   Check if the other end is active.
1189   If we have sent packets, but didn't receive any,
1190   then possibly the other end is dead. We send a
1191   PING request over the meta connection. If the other
1192   end does not reply in time, we consider them dead
1193   and close the connection.
1194 */
1195 int check_dead_connections(void)
1196 {
1197   conn_list_t *p;
1198   time_t now;
1199 cp
1200   now = time(NULL);
1201   for(p = conn_list; p != NULL; p = p->next)
1202     {
1203       if(p->status.active && p->status.meta)
1204         {
1205           if(p->last_ping_time + timeout < now)
1206             {
1207               if(p->status.pinged)
1208                 {
1209                   if(debug_lvl >= DEBUG_PROTOCOL)
1210                     syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1211                            p->name, p->hostname);
1212                   p->status.timeout = 1;
1213                   terminate_connection(p);
1214                 }
1215               else
1216                 {
1217                   send_ping(p);
1218                 }
1219             }
1220         }
1221     }
1222 cp
1223   return 0;
1224 }
1225
1226 /*
1227   accept a new tcp connect and create a
1228   new connection
1229 */
1230 int handle_new_meta_connection()
1231 {
1232   conn_list_t *ncn;
1233   struct sockaddr client;
1234   int nfd, len = sizeof(client);
1235 cp
1236   if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
1237     {
1238       syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1239       return -1;
1240     }
1241
1242   if(!(ncn = create_new_connection(nfd)))
1243     {
1244       shutdown(nfd, 2);
1245       close(nfd);
1246       syslog(LOG_NOTICE, _("Closed attempted connection"));
1247       return 0;
1248     }
1249
1250   conn_list_add(ncn);
1251 cp
1252   return 0;
1253 }
1254
1255 /*
1256   check all connections to see if anything
1257   happened on their sockets
1258 */
1259 void check_network_activity(fd_set *f)
1260 {
1261   conn_list_t *p;
1262 cp
1263   for(p = conn_list; p != NULL; p = p->next)
1264     {
1265       if(p->status.remove)
1266         continue;
1267
1268       if(p->status.dataopen)
1269         if(FD_ISSET(p->socket, f))
1270           {
1271             handle_incoming_vpn_data(p);
1272
1273             /* Old error stuff (FIXME: copy this to handle_incoming_vpn_data()
1274             
1275             getsockopt(p->socket, SOL_SOCKET, SO_ERROR, &x, &l);
1276             syslog(LOG_ERR, _("Outgoing data socket error for %s (%s): %s"),
1277                    p->name, p->hostname, strerror(x));
1278             terminate_connection(p);
1279             */
1280             return;
1281           }  
1282
1283       if(p->status.meta)
1284         if(FD_ISSET(p->meta_socket, f))
1285           if(receive_meta(p) < 0)
1286             {
1287               terminate_connection(p);
1288               return;
1289             } 
1290     }
1291   
1292   if(FD_ISSET(myself->meta_socket, f))
1293     handle_new_meta_connection();
1294 cp
1295 }
1296
1297 /*
1298   read, encrypt and send data that is
1299   available through the ethertap device
1300 */
1301 void handle_tap_input(void)
1302 {
1303   vpn_packet_t vp;
1304   int lenin;
1305 cp  
1306   if(taptype == TAP_TYPE_TUNTAP)
1307     {
1308       if((lenin = read(tap_fd, vp.data, MTU)) <= 0)
1309         {
1310           syslog(LOG_ERR, _("Error while reading from tun/tap device: %m"));
1311           return;
1312         }
1313       vp.len = lenin;
1314     }
1315   else                  /* ethertap */
1316     {
1317       if((lenin = read(tap_fd, vp.data - 2, MTU)) <= 0)
1318         {
1319           syslog(LOG_ERR, _("Error while reading from ethertap device: %m"));
1320           return;
1321         }
1322       vp.len = lenin - 2;
1323     }
1324
1325   total_tap_in += lenin;
1326
1327   if(lenin < 32)
1328     {
1329       if(debug_lvl >= DEBUG_TRAFFIC)
1330         syslog(LOG_WARNING, _("Received short packet from tap device"));
1331       return;
1332     }
1333
1334   if(debug_lvl >= DEBUG_TRAFFIC)
1335     {
1336       syslog(LOG_DEBUG, _("Read packet of length %d from tap device"), vp.len);
1337     }
1338
1339   send_packet(ntohl(*((unsigned long*)(&vp.data[30]))), &vp);
1340 cp
1341 }
1342
1343 /*
1344   this is where it all happens...
1345 */
1346 void main_loop(void)
1347 {
1348   fd_set fset;
1349   struct timeval tv;
1350   int r;
1351   time_t last_ping_check;
1352   int t;
1353 cp
1354   last_ping_check = time(NULL);
1355
1356   for(;;)
1357     {
1358       tv.tv_sec = timeout;
1359       tv.tv_usec = 0;
1360
1361       prune_conn_list();
1362       build_fdset(&fset);
1363
1364       if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1365         {
1366           if(errno != EINTR) /* because of alarm */
1367             {
1368               syslog(LOG_ERR, _("Error while waiting for input: %m"));
1369               return;
1370             }
1371         }
1372
1373       if(sighup)
1374         {
1375           syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1376           sighup = 0;
1377           close_network_connections();
1378           clear_config(&config);
1379
1380           if(read_server_config())
1381             {
1382               syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1383               exit(0);
1384             }
1385
1386           sleep(5);
1387           
1388           if(setup_network_connections())
1389             return;
1390             
1391           continue;
1392         }
1393
1394       t = time(NULL);
1395
1396       /* Let's check if everybody is still alive */
1397
1398       if(last_ping_check + timeout < t)
1399         {
1400           check_dead_connections();
1401           last_ping_check = time(NULL);
1402
1403           /* Should we regenerate our key? */
1404
1405           if(keyexpires < t)
1406             {
1407               if(debug_lvl >= DEBUG_STATUS)
1408                 syslog(LOG_INFO, _("Regenerating symmetric key"));
1409                 
1410               RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
1411               send_key_changed(myself, NULL);
1412               keyexpires = time(NULL) + keylifetime;
1413             }
1414         }
1415
1416       if(r > 0)
1417         {
1418           check_network_activity(&fset);
1419
1420           /* local tap data */
1421           if(FD_ISSET(tap_fd, &fset))
1422             handle_tap_input();
1423         }
1424     }
1425 cp
1426 }