- Added indirectdata and tcponly functionality.
[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.92 2001/01/07 20:19:29 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       return NULL;
1036     }
1037
1038   p->name = unknown;
1039   p->address = ntohl(ci.sin_addr.s_addr);
1040   p->hostname = hostlookup(ci.sin_addr.s_addr);
1041   p->port = htons(ci.sin_port);                         /* This one will be overwritten later */
1042   p->meta_socket = sfd;
1043   p->status.meta = 1;
1044   p->buffer = xmalloc(MAXBUFSIZE);
1045   p->buflen = 0;
1046   p->last_ping_time = time(NULL);
1047   
1048   if(debug_lvl >= DEBUG_CONNECTIONS)
1049     syslog(LOG_NOTICE, _("Connection from %s port %d"),
1050          p->hostname, htons(ci.sin_port));
1051
1052   p->allow_request = ID;
1053 cp
1054   return p;
1055 }
1056
1057 /*
1058   put all file descriptors in an fd_set array
1059 */
1060 void build_fdset(fd_set *fs)
1061 {
1062   avl_node_t *node;
1063   connection_t *p;
1064 cp
1065   FD_ZERO(fs);
1066
1067   FD_SET(myself->socket, fs);
1068
1069   for(node = connection_tree->head; node; node = node->next)
1070     {
1071       p = (connection_t *)node->data;
1072       if(p->status.meta)
1073         FD_SET(p->meta_socket, fs);
1074     }
1075
1076   FD_SET(myself->meta_socket, fs);
1077   FD_SET(tap_fd, fs);
1078 cp
1079 }
1080
1081 /*
1082   receive incoming data from the listening
1083   udp socket and write it to the ethertap
1084   device after being decrypted
1085 */
1086 int handle_incoming_vpn_data(void)
1087 {
1088   vpn_packet_t pkt;
1089   int x, l = sizeof(x);
1090   int lenin;
1091   struct sockaddr_in from;
1092   socklen_t fromlen = sizeof(from);
1093   connection_t *cl;
1094 cp
1095   if(getsockopt(myself->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1096     {
1097       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1098              __FILE__, __LINE__, myself->socket);
1099       return -1;
1100     }
1101   if(x)
1102     {
1103       syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1104       return -1;
1105     }
1106
1107   if((lenin = recvfrom(myself->socket, (char *) &(pkt.len), MTU, 0, (struct sockaddr *)&from, &fromlen)) <= 0)
1108     {
1109       syslog(LOG_ERR, _("Receiving packet failed: %m"));
1110       return -1;
1111     }
1112
1113   cl = lookup_connection(ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
1114   
1115   if(!cl)
1116     {
1117       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));
1118       return 0;
1119     }
1120
1121   if(debug_lvl >= DEBUG_TRAFFIC)
1122     {
1123       syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"), lenin,
1124              cl->name, cl->hostname);
1125     }
1126
1127 cp
1128   return xrecv(cl, &pkt);
1129 }
1130
1131 /*
1132   terminate a connection and notify the other
1133   end before closing the sockets
1134 */
1135 void terminate_connection(connection_t *cl)
1136 {
1137   connection_t *p;
1138   subnet_t *subnet;
1139   avl_node_t *node, *next;
1140 cp
1141   if(cl->status.remove)
1142     return;
1143
1144   cl->status.remove = 1;
1145
1146   if(debug_lvl >= DEBUG_CONNECTIONS)
1147     syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1148            cl->name, cl->hostname);
1149  
1150   if(cl->socket)
1151     close(cl->socket);
1152   if(cl->status.meta)
1153     close(cl->meta_socket);
1154
1155   /* Find all connections that were lost because they were behind cl
1156      (the connection that was dropped). */
1157
1158   if(cl->status.meta)
1159     for(node = connection_tree->head; node; node = node->next)
1160       {
1161         p = (connection_t *)node->data;
1162         if(p->nexthop == cl && p != cl)
1163           terminate_connection(p);
1164       }
1165
1166   /* Inform others of termination if it was still active */
1167
1168   if(cl->status.active)
1169     for(node = connection_tree->head; node; node = node->next)
1170       {
1171         p = (connection_t *)node->data;
1172         if(p->status.meta && p->status.active && p!=cl)
1173           send_del_host(p, cl); /* Sounds like recursion, but p does not have a meta connection :) */
1174       }
1175
1176   /* Remove the associated subnets */
1177
1178   for(node = cl->subnet_tree->head; node; node = next)
1179     {
1180       next = node->next;
1181       subnet = (subnet_t *)node->data;
1182       subnet_del(subnet);
1183     }
1184
1185   /* Check if this was our outgoing connection */
1186     
1187   if(cl->status.outgoing && cl->status.active)
1188     {
1189       signal(SIGALRM, sigalrm_handler);
1190       seconds_till_retry = 5;
1191       alarm(seconds_till_retry);
1192       syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
1193     }
1194
1195   /* Inactivate */
1196
1197   cl->status.active = 0;
1198 cp
1199 }
1200
1201 /*
1202   Check if the other end is active.
1203   If we have sent packets, but didn't receive any,
1204   then possibly the other end is dead. We send a
1205   PING request over the meta connection. If the other
1206   end does not reply in time, we consider them dead
1207   and close the connection.
1208 */
1209 void check_dead_connections(void)
1210 {
1211   time_t now;
1212   avl_node_t *node;
1213   connection_t *cl;
1214 cp
1215   now = time(NULL);
1216
1217   for(node = connection_tree->head; node; node = node->next)
1218     {
1219       cl = (connection_t *)node->data;
1220       if(cl->status.active && cl->status.meta)
1221         {
1222           if(cl->last_ping_time + timeout < now)
1223             {
1224               if(cl->status.pinged)
1225                 {
1226                   if(debug_lvl >= DEBUG_PROTOCOL)
1227                     syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1228                            cl->name, cl->hostname);
1229                   cl->status.timeout = 1;
1230                   terminate_connection(cl);
1231                 }
1232               else
1233                 {
1234                   send_ping(cl);
1235                 }
1236             }
1237         }
1238     }
1239 cp
1240 }
1241
1242 /*
1243   accept a new tcp connect and create a
1244   new connection
1245 */
1246 int handle_new_meta_connection()
1247 {
1248   connection_t *ncn;
1249   struct sockaddr client;
1250   int nfd, len = sizeof(client);
1251 cp
1252   if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
1253     {
1254       syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1255       return -1;
1256     }
1257
1258   if(!(ncn = create_new_connection(nfd)))
1259     {
1260       shutdown(nfd, 2);
1261       close(nfd);
1262       syslog(LOG_NOTICE, _("Closed attempted connection"));
1263       return 0;
1264     }
1265
1266   connection_add(ncn);
1267 cp
1268   return 0;
1269 }
1270
1271 /*
1272   check all connections to see if anything
1273   happened on their sockets
1274 */
1275 void check_network_activity(fd_set *f)
1276 {
1277   connection_t *p;
1278   avl_node_t *node;
1279 cp
1280   if(FD_ISSET(myself->socket, f))
1281     handle_incoming_vpn_data();
1282
1283   for(node = connection_tree->head; node; node = node->next)
1284     {
1285       p = (connection_t *)node->data;
1286
1287       if(p->status.remove)
1288         return;
1289
1290       if(p->status.meta)
1291         if(FD_ISSET(p->meta_socket, f))
1292           if(receive_meta(p) < 0)
1293             {
1294               terminate_connection(p);
1295               return;
1296             } 
1297     }
1298     
1299   if(FD_ISSET(myself->meta_socket, f))
1300     handle_new_meta_connection();
1301 cp
1302 }
1303
1304 /*
1305   read, encrypt and send data that is
1306   available through the ethertap device
1307 */
1308 void handle_tap_input(void)
1309 {
1310   vpn_packet_t vp;
1311   int lenin;
1312 cp  
1313   if(taptype == TAP_TYPE_TUNTAP)
1314     {
1315       if((lenin = read(tap_fd, vp.data, MTU)) <= 0)
1316         {
1317           syslog(LOG_ERR, _("Error while reading from tun/tap device: %m"));
1318           return;
1319         }
1320       vp.len = lenin;
1321     }
1322   else                  /* ethertap */
1323     {
1324       if((lenin = read(tap_fd, vp.data - 2, MTU)) <= 0)
1325         {
1326           syslog(LOG_ERR, _("Error while reading from ethertap device: %m"));
1327           return;
1328         }
1329       vp.len = lenin - 2;
1330     }
1331
1332   total_tap_in += lenin;
1333
1334   if(lenin < 32)
1335     {
1336       if(debug_lvl >= DEBUG_TRAFFIC)
1337         syslog(LOG_WARNING, _("Received short packet from tap device"));
1338       return;
1339     }
1340
1341   if(debug_lvl >= DEBUG_TRAFFIC)
1342     {
1343       syslog(LOG_DEBUG, _("Read packet of length %d from tap device"), vp.len);
1344     }
1345
1346   send_packet(ntohl(*((unsigned long*)(&vp.data[30]))), &vp);
1347 cp
1348 }
1349
1350 /*
1351   this is where it all happens...
1352 */
1353 void main_loop(void)
1354 {
1355   fd_set fset;
1356   struct timeval tv;
1357   int r;
1358   time_t last_ping_check;
1359   int t;
1360 cp
1361   last_ping_check = time(NULL);
1362
1363   for(;;)
1364     {
1365       tv.tv_sec = timeout;
1366       tv.tv_usec = 0;
1367
1368       prune_connection_tree();
1369       build_fdset(&fset);
1370
1371       if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1372         {
1373           if(errno != EINTR) /* because of alarm */
1374             {
1375               syslog(LOG_ERR, _("Error while waiting for input: %m"));
1376               return;
1377             }
1378         }
1379
1380       if(sighup)
1381         {
1382           syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1383           sighup = 0;
1384           close_network_connections();
1385           clear_config(&config);
1386
1387           if(read_server_config())
1388             {
1389               syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1390               exit(0);
1391             }
1392
1393           sleep(5);
1394           
1395           if(setup_network_connections())
1396             return;
1397             
1398           continue;
1399         }
1400
1401       t = time(NULL);
1402
1403       /* Let's check if everybody is still alive */
1404
1405       if(last_ping_check + timeout < t)
1406         {
1407           check_dead_connections();
1408           last_ping_check = time(NULL);
1409
1410           /* Should we regenerate our key? */
1411
1412           if(keyexpires < t)
1413             {
1414               if(debug_lvl >= DEBUG_STATUS)
1415                 syslog(LOG_INFO, _("Regenerating symmetric key"));
1416                 
1417               RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
1418               send_key_changed(myself, NULL);
1419               keyexpires = time(NULL) + keylifetime;
1420             }
1421         }
1422
1423       if(r > 0)
1424         {
1425           check_network_activity(&fset);
1426
1427           /* local tap data */
1428           if(FD_ISSET(tap_fd, &fset))
1429             handle_tap_input();
1430         }
1431     }
1432 cp
1433 }