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