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