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