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