Ignore file for src/
[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.94 2001/01/13 16:36:21 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   char *fname;
614   void *result;
615 cp
616   if(!cl->rsa_key)
617     cl->rsa_key = RSA_new();
618
619   /* First, check for simple PublicKey statement */
620
621   if((cfg = get_config_val(cl->config, config_publickey)))
622     {
623       BN_hex2bn(&cl->rsa_key->n, cfg->data.ptr);
624       BN_hex2bn(&cl->rsa_key->e, "FFFF");
625       return 0;
626     }
627
628   /* Else, check for PublicKeyFile statement and read it */
629
630   if((cfg = get_config_val(cl->config, config_publickeyfile)))
631     {
632       if(is_safe_path(cfg->data.ptr))
633         {
634           if((fp = fopen(cfg->data.ptr, "r")) == NULL)
635             {
636               syslog(LOG_ERR, _("Error reading RSA public key file `%s': %m"),
637                      cfg->data.ptr);
638               return -1;
639             }
640           result = PEM_read_RSAPublicKey(fp, &cl->rsa_key, NULL, NULL);
641           fclose(fp);
642           if(!result)
643             {
644               syslog(LOG_ERR, _("Reading RSA public key file `%s' failed: %m"),
645                      cfg->data.ptr);
646               return -1;
647             }
648           return 0;
649         }
650       else
651         return -1;
652     }    
653
654   /* Else, check if a harnessed public key is in the config file */
655   
656   asprintf(&fname, "%s/hosts/%s", confbase, cl->name);
657   if((fp = fopen(fname, "r")))
658     {
659       result = PEM_read_RSAPublicKey(fp, &cl->rsa_key, NULL, NULL);
660       fclose(fp);
661       free(fname);
662       if(result)
663         return 0;
664     }
665
666   free(fname);
667
668   /* Nothing worked. */
669
670   syslog(LOG_ERR, _("No public key for %s specified!"), cl->name);
671 cp
672   return -1;
673 }
674
675 int read_rsa_private_key(void)
676 {
677   config_t const *cfg;
678   FILE *fp;
679   void *result;
680 cp
681   if(!myself->rsa_key)
682     myself->rsa_key = RSA_new();
683
684   if((cfg = get_config_val(config, config_privatekey)))
685     {
686       BN_hex2bn(&myself->rsa_key->d, cfg->data.ptr);
687       BN_hex2bn(&myself->rsa_key->e, "FFFF");
688     }
689   else if((cfg = get_config_val(config, config_privatekeyfile)))
690     {
691       if((fp = fopen(cfg->data.ptr, "r")) == NULL)
692         {
693           syslog(LOG_ERR, _("Error reading RSA private key file `%s': %m"),
694                  cfg->data.ptr);
695           return -1;
696         }
697       result = PEM_read_RSAPrivateKey(fp, &myself->rsa_key, NULL, NULL);
698       fclose(fp);
699       if(!result)
700         {
701           syslog(LOG_ERR, _("Reading RSA private key file `%s' failed: %m"),
702                  cfg->data.ptr);
703           return -1;
704         }
705     }    
706   else
707     {
708       syslog(LOG_ERR, _("No private key for tinc daemon specified!"));
709       return -1;
710     }
711 cp
712   return 0;
713 }
714
715 /*
716   Configure connection_t myself and set up the local sockets (listen only)
717 */
718 int setup_myself(void)
719 {
720   config_t const *cfg;
721   config_t *next;
722   subnet_t *net;
723 cp
724   myself = new_connection();
725
726   asprintf(&myself->hostname, "MYSELF");
727   myself->flags = 0;
728   myself->protocol_version = PROT_CURRENT;
729
730   if(!(cfg = get_config_val(config, config_name))) /* Not acceptable */
731     {
732       syslog(LOG_ERR, _("Name for tinc daemon required!"));
733       return -1;
734     }
735   else
736     asprintf(&myself->name, "%s", (char*)cfg->data.val);
737
738   if(check_id(myself->name))
739     {
740       syslog(LOG_ERR, _("Invalid name for myself!"));
741       return -1;
742     }
743 cp
744   if(read_rsa_private_key())
745     return -1;
746
747   if(read_host_config(myself))
748     {
749       syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
750       return -1;
751     }
752
753   if(read_rsa_public_key(myself))
754     return -1;
755 cp  
756
757 /*
758   if(RSA_check_key(myself->rsa_key) != 1)
759     {
760       syslog(LOG_ERR, _("Invalid public/private keypair!"));
761       return -1;
762     }
763 */
764   if(!(cfg = get_config_val(myself->config, config_port)))
765     myself->port = 655;
766   else
767     myself->port = cfg->data.val;
768
769   if((cfg = get_config_val(myself->config, config_indirectdata)))
770     if(cfg->data.val == stupid_true)
771       myself->flags |= EXPORTINDIRECTDATA;
772
773   if((cfg = get_config_val(myself->config, config_tcponly)))
774     if(cfg->data.val == stupid_true)
775       myself->flags |= TCPONLY;
776
777 /* Read in all the subnets specified in the host configuration file */
778
779   for(next = myself->config; (cfg = get_config_val(next, config_subnet)); next = cfg->next)
780     {
781       net = new_subnet();
782       net->type = SUBNET_IPV4;
783       net->net.ipv4.address = cfg->data.ip->address;
784       net->net.ipv4.mask = cfg->data.ip->mask;
785       
786       /* Teach newbies what subnets are... */
787       
788       if((net->net.ipv4.address & net->net.ipv4.mask) != net->net.ipv4.address)
789         {
790           syslog(LOG_ERR, _("Network address and subnet mask do not match!"));
791           return -1;
792         }        
793       
794       subnet_add(myself, net);
795     }
796     
797   if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
798     {
799       syslog(LOG_ERR, _("Unable to set up a listening TCP socket!"));
800       return -1;
801     }
802
803   if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
804     {
805       syslog(LOG_ERR, _("Unable to set up a listening UDP socket!"));
806       return -1;
807     }
808 cp
809   /* Generate packet encryption key */
810
811   myself->cipher_pkttype = EVP_bf_cfb();
812
813   myself->cipher_pktkeylength = myself->cipher_pkttype->key_len + myself->cipher_pkttype->iv_len;
814
815   myself->cipher_pktkey = (char *)xmalloc(myself->cipher_pktkeylength);
816   RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
817
818   if(!(cfg = get_config_val(config, config_keyexpire)))
819     keylifetime = 3600;
820   else
821     keylifetime = cfg->data.val;
822     
823   keyexpires = time(NULL) + keylifetime;
824 cp
825   /* Check some options */
826   
827   if((cfg = get_config_val(config, config_indirectdata)))
828     {
829       if(cfg->data.val == stupid_true)
830         myself->options |= OPTION_INDIRECT;
831     }
832
833   if((cfg = get_config_val(config, config_tcponly)))
834     {
835       if(cfg->data.val == stupid_true)
836         myself->options |= OPTION_TCPONLY;
837     }
838   /* Activate ourselves */
839
840   myself->status.active = 1;
841
842   syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
843 cp
844   return 0;
845 }
846
847 RETSIGTYPE
848 sigalrm_handler(int a)
849 {
850   config_t const *cfg;
851 cp
852   cfg = get_config_val(upstreamcfg, config_connectto);
853
854   if(!cfg && upstreamcfg == config)
855     /* No upstream IP given, we're listen only. */
856     return;
857
858   while(cfg)
859     {
860       upstreamcfg = cfg->next;
861       if(!setup_outgoing_connection(cfg->data.ptr))   /* function returns 0 when there are no problems */
862         {
863           signal(SIGALRM, SIG_IGN);
864           return;
865         }
866       cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
867     }
868
869   signal(SIGALRM, sigalrm_handler);
870   upstreamcfg = config;
871   seconds_till_retry += 5;
872   if(seconds_till_retry > MAXTIMEOUT)    /* Don't wait more than MAXTIMEOUT seconds. */
873     seconds_till_retry = MAXTIMEOUT;
874   syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
875          seconds_till_retry);
876   alarm(seconds_till_retry);
877 cp
878 }
879
880 /*
881   setup all initial network connections
882 */
883 int setup_network_connections(void)
884 {
885   config_t const *cfg;
886 cp
887   init_connections();
888   init_subnets();
889
890   if((cfg = get_config_val(config, config_pingtimeout)) == NULL)
891     timeout = 60;
892   else
893     {
894       timeout = cfg->data.val;
895       if(timeout < 1)
896         {
897           timeout = 86400;
898         }
899      }
900
901   if(setup_tap_fd() < 0)
902     return -1;
903
904   /* Run tinc-up script to further initialize the tap interface */
905   execute_script("tinc-up");
906   
907   if(setup_myself() < 0)
908     return -1;
909
910   if(!(cfg = get_config_val(config, config_connectto)))
911     /* No upstream IP given, we're listen only. */
912     return 0;
913
914   while(cfg)
915     {
916       upstreamcfg = cfg->next;
917       if(!setup_outgoing_connection(cfg->data.ptr))   /* function returns 0 when there are no problems */
918         return 0;
919       cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
920     }
921     
922   signal(SIGALRM, sigalrm_handler);
923   upstreamcfg = config;
924   seconds_till_retry = MAXTIMEOUT;
925   syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
926   alarm(seconds_till_retry);
927 cp
928   return 0;
929 }
930
931 /*
932   close all open network connections
933 */
934 void close_network_connections(void)
935 {
936   avl_node_t *node;
937   connection_t *p;
938 cp
939   for(node = connection_tree->head; node; node = node->next)
940     {
941       p = (connection_t *)node->data;
942       p->status.active = 0;
943       terminate_connection(p);
944     }
945
946   if(myself)
947     if(myself->status.active)
948       {
949         close(myself->meta_socket);
950         free_connection(myself);
951         myself = NULL;
952       }
953
954   close(tap_fd);
955
956   /* Execute tinc-down script right after shutting down the interface */
957   execute_script("tinc-down");
958
959   destroy_connection_tree();
960 cp
961   return;
962 }
963
964 /*
965   create a data (udp) socket
966   OBSOLETED: use only one listening socket for compatibility with non-Linux operating systems
967 */
968 int setup_vpn_connection(connection_t *cl)
969 {
970   int nfd, flags;
971   struct sockaddr_in a;
972   const int one = 1;
973 cp
974   if(debug_lvl >= DEBUG_TRAFFIC)
975     syslog(LOG_DEBUG, _("Opening UDP socket to %s"), cl->hostname);
976
977   nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
978   if(nfd == -1)
979     {
980       syslog(LOG_ERR, _("Creating UDP socket failed: %m"));
981       return -1;
982     }
983
984   if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
985     {
986       close(nfd);
987       syslog(LOG_ERR, _("System call `%s' failed: %m"),
988              "setsockopt");
989       return -1;
990     }
991
992   flags = fcntl(nfd, F_GETFL);
993   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
994     {
995       close(nfd);
996       syslog(LOG_ERR, _("System call `%s' failed: %m"),
997              "fcntl");
998       return -1;
999     }
1000
1001   memset(&a, 0, sizeof(a));
1002   a.sin_family = AF_INET;
1003   a.sin_port = htons(myself->port);
1004   a.sin_addr.s_addr = htonl(INADDR_ANY);
1005
1006   if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
1007     {
1008       close(nfd);
1009       syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), myself->port);
1010       return -1;
1011     }
1012
1013   a.sin_family = AF_INET;
1014   a.sin_port = htons(cl->port);
1015   a.sin_addr.s_addr = htonl(cl->address);
1016
1017   if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
1018     {
1019       close(nfd);
1020       syslog(LOG_ERR, _("Connecting to %s port %d failed: %m"),
1021              cl->hostname, cl->port);
1022       return -1;
1023     }
1024
1025   flags = fcntl(nfd, F_GETFL);
1026   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
1027     {
1028       close(nfd);
1029       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m %s (%s)"), __FILE__, __LINE__, nfd,
1030              cl->name, cl->hostname);
1031       return -1;
1032     }
1033
1034   cl->socket = nfd;
1035   cl->status.dataopen = 1;
1036 cp
1037   return 0;
1038 }
1039
1040 /*
1041   handle an incoming tcp connect call and open
1042   a connection to it.
1043 */
1044 connection_t *create_new_connection(int sfd)
1045 {
1046   connection_t *p;
1047   struct sockaddr_in ci;
1048   int len = sizeof(ci);
1049 cp
1050   p = new_connection();
1051
1052   if(getpeername(sfd, (struct sockaddr *) &ci, (socklen_t *) &len) < 0)
1053     {
1054       syslog(LOG_ERR, _("System call `%s' failed: %m"),
1055              "getpeername");
1056       close(sfd);
1057       return NULL;
1058     }
1059
1060   p->name = unknown;
1061   p->address = ntohl(ci.sin_addr.s_addr);
1062   p->hostname = hostlookup(ci.sin_addr.s_addr);
1063   p->port = htons(ci.sin_port);                         /* This one will be overwritten later */
1064   p->meta_socket = sfd;
1065   p->status.meta = 1;
1066   p->buffer = xmalloc(MAXBUFSIZE);
1067   p->buflen = 0;
1068   p->last_ping_time = time(NULL);
1069   
1070   if(debug_lvl >= DEBUG_CONNECTIONS)
1071     syslog(LOG_NOTICE, _("Connection from %s port %d"),
1072          p->hostname, htons(ci.sin_port));
1073
1074   p->allow_request = ID;
1075 cp
1076   return p;
1077 }
1078
1079 /*
1080   put all file descriptors in an fd_set array
1081 */
1082 void build_fdset(fd_set *fs)
1083 {
1084   avl_node_t *node;
1085   connection_t *p;
1086 cp
1087   FD_ZERO(fs);
1088
1089   FD_SET(myself->socket, fs);
1090
1091   for(node = connection_tree->head; node; node = node->next)
1092     {
1093       p = (connection_t *)node->data;
1094       if(p->status.meta)
1095         FD_SET(p->meta_socket, fs);
1096     }
1097
1098   FD_SET(myself->meta_socket, fs);
1099   FD_SET(tap_fd, fs);
1100 cp
1101 }
1102
1103 /*
1104   receive incoming data from the listening
1105   udp socket and write it to the ethertap
1106   device after being decrypted
1107 */
1108 int handle_incoming_vpn_data(void)
1109 {
1110   vpn_packet_t pkt;
1111   int x, l = sizeof(x);
1112   int lenin;
1113   struct sockaddr_in from;
1114   socklen_t fromlen = sizeof(from);
1115   connection_t *cl;
1116 cp
1117   if(getsockopt(myself->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1118     {
1119       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1120              __FILE__, __LINE__, myself->socket);
1121       return -1;
1122     }
1123   if(x)
1124     {
1125       syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1126       return -1;
1127     }
1128
1129   if((lenin = recvfrom(myself->socket, (char *) &(pkt.len), MTU, 0, (struct sockaddr *)&from, &fromlen)) <= 0)
1130     {
1131       syslog(LOG_ERR, _("Receiving packet failed: %m"));
1132       return -1;
1133     }
1134
1135   cl = lookup_connection(ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
1136   
1137   if(!cl)
1138     {
1139       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));
1140       return 0;
1141     }
1142
1143   if(debug_lvl >= DEBUG_TRAFFIC)
1144     {
1145       syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"), lenin,
1146              cl->name, cl->hostname);
1147     }
1148
1149 cp
1150   return xrecv(cl, &pkt);
1151 }
1152
1153 /*
1154   terminate a connection and notify the other
1155   end before closing the sockets
1156 */
1157 void terminate_connection(connection_t *cl)
1158 {
1159   connection_t *p;
1160   subnet_t *subnet;
1161   avl_node_t *node, *next;
1162 cp
1163   if(cl->status.remove)
1164     return;
1165
1166   if(debug_lvl >= DEBUG_CONNECTIONS)
1167     syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1168            cl->name, cl->hostname);
1169  
1170   cl->status.remove = 1;
1171   
1172   if(cl->socket)
1173     close(cl->socket);
1174   if(cl->status.meta)
1175     close(cl->meta_socket);
1176
1177   if(cl->status.meta)
1178     {
1179     
1180       /* Find all connections that were lost because they were behind cl
1181          (the connection that was dropped). */
1182
1183         for(node = connection_tree->head; node; node = node->next)
1184           {
1185             p = (connection_t *)node->data;
1186             if(p->nexthop == cl && p != cl)
1187               terminate_connection(p);
1188           }
1189
1190       /* Inform others of termination if it was still active */
1191
1192       if(cl->status.active)
1193         for(node = connection_tree->head; node; node = node->next)
1194           {
1195             p = (connection_t *)node->data;
1196             if(p->status.meta && p->status.active && p != cl)
1197               send_del_host(p, cl);     /* Sounds like recursion, but p does not have a meta connection :) */
1198           }
1199     }
1200
1201   /* Remove the associated subnets */
1202
1203   for(node = cl->subnet_tree->head; node; node = next)
1204     {
1205       next = node->next;
1206       subnet = (subnet_t *)node->data;
1207       subnet_del(subnet);
1208     }
1209
1210   /* Check if this was our outgoing connection */
1211     
1212   if(cl->status.outgoing && cl->status.active)
1213     {
1214       signal(SIGALRM, sigalrm_handler);
1215       seconds_till_retry = 5;
1216       alarm(seconds_till_retry);
1217       syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
1218     }
1219
1220   /* Inactivate */
1221
1222   cl->status.active = 0;
1223 cp
1224 }
1225
1226 /*
1227   Check if the other end is active.
1228   If we have sent packets, but didn't receive any,
1229   then possibly the other end is dead. We send a
1230   PING request over the meta connection. If the other
1231   end does not reply in time, we consider them dead
1232   and close the connection.
1233 */
1234 void check_dead_connections(void)
1235 {
1236   time_t now;
1237   avl_node_t *node;
1238   connection_t *cl;
1239 cp
1240   now = time(NULL);
1241
1242   for(node = connection_tree->head; node; node = node->next)
1243     {
1244       cl = (connection_t *)node->data;
1245       if(cl->status.active && cl->status.meta)
1246         {
1247           if(cl->last_ping_time + timeout < now)
1248             {
1249               if(cl->status.pinged)
1250                 {
1251                   if(debug_lvl >= DEBUG_PROTOCOL)
1252                     syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1253                            cl->name, cl->hostname);
1254                   cl->status.timeout = 1;
1255                   terminate_connection(cl);
1256                 }
1257               else
1258                 {
1259                   send_ping(cl);
1260                 }
1261             }
1262         }
1263     }
1264 cp
1265 }
1266
1267 /*
1268   accept a new tcp connect and create a
1269   new connection
1270 */
1271 int handle_new_meta_connection()
1272 {
1273   connection_t *ncn;
1274   struct sockaddr client;
1275   int nfd, len = sizeof(client);
1276 cp
1277   if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
1278     {
1279       syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1280       return -1;
1281     }
1282
1283   if(!(ncn = create_new_connection(nfd)))
1284     {
1285       shutdown(nfd, 2);
1286       close(nfd);
1287       syslog(LOG_NOTICE, _("Closed attempted connection"));
1288       return 0;
1289     }
1290
1291   connection_add(ncn);
1292 cp
1293   return 0;
1294 }
1295
1296 /*
1297   check all connections to see if anything
1298   happened on their sockets
1299 */
1300 void check_network_activity(fd_set *f)
1301 {
1302   connection_t *p;
1303   avl_node_t *node;
1304 cp
1305   if(FD_ISSET(myself->socket, f))
1306     handle_incoming_vpn_data();
1307
1308   for(node = connection_tree->head; node; node = node->next)
1309     {
1310       p = (connection_t *)node->data;
1311
1312       if(p->status.remove)
1313         return;
1314
1315       if(p->status.meta)
1316         if(FD_ISSET(p->meta_socket, f))
1317           if(receive_meta(p) < 0)
1318             {
1319               terminate_connection(p);
1320               return;
1321             } 
1322     }
1323     
1324   if(FD_ISSET(myself->meta_socket, f))
1325     handle_new_meta_connection();
1326 cp
1327 }
1328
1329 /*
1330   read, encrypt and send data that is
1331   available through the ethertap device
1332 */
1333 void handle_tap_input(void)
1334 {
1335   vpn_packet_t vp;
1336   int lenin;
1337 cp  
1338   if(taptype == TAP_TYPE_TUNTAP)
1339     {
1340       if((lenin = read(tap_fd, vp.data, MTU)) <= 0)
1341         {
1342           syslog(LOG_ERR, _("Error while reading from tun/tap device: %m"));
1343           return;
1344         }
1345       vp.len = lenin;
1346     }
1347   else                  /* ethertap */
1348     {
1349       if((lenin = read(tap_fd, vp.data - 2, MTU)) <= 0)
1350         {
1351           syslog(LOG_ERR, _("Error while reading from ethertap device: %m"));
1352           return;
1353         }
1354       vp.len = lenin - 2;
1355     }
1356
1357   total_tap_in += lenin;
1358
1359   if(lenin < 32)
1360     {
1361       if(debug_lvl >= DEBUG_TRAFFIC)
1362         syslog(LOG_WARNING, _("Received short packet from tap device"));
1363       return;
1364     }
1365
1366   if(debug_lvl >= DEBUG_TRAFFIC)
1367     {
1368       syslog(LOG_DEBUG, _("Read packet of length %d from tap device"), vp.len);
1369     }
1370
1371   send_packet(ntohl(*((unsigned long*)(&vp.data[30]))), &vp);
1372 cp
1373 }
1374
1375 /*
1376   this is where it all happens...
1377 */
1378 void main_loop(void)
1379 {
1380   fd_set fset;
1381   struct timeval tv;
1382   int r;
1383   time_t last_ping_check;
1384   int t;
1385 cp
1386   last_ping_check = time(NULL);
1387
1388   for(;;)
1389     {
1390       tv.tv_sec = timeout;
1391       tv.tv_usec = 0;
1392
1393       prune_connection_tree();
1394       build_fdset(&fset);
1395
1396       if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1397         {
1398           if(errno != EINTR) /* because of alarm */
1399             {
1400               syslog(LOG_ERR, _("Error while waiting for input: %m"));
1401               return;
1402             }
1403         }
1404
1405       if(sighup)
1406         {
1407           syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1408           sighup = 0;
1409           close_network_connections();
1410           clear_config(&config);
1411
1412           if(read_server_config())
1413             {
1414               syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1415               exit(0);
1416             }
1417
1418           sleep(5);
1419           
1420           if(setup_network_connections())
1421             return;
1422             
1423           continue;
1424         }
1425
1426       t = time(NULL);
1427
1428       /* Let's check if everybody is still alive */
1429
1430       if(last_ping_check + timeout < t)
1431         {
1432           check_dead_connections();
1433           last_ping_check = time(NULL);
1434
1435           /* Should we regenerate our key? */
1436
1437           if(keyexpires < t)
1438             {
1439               if(debug_lvl >= DEBUG_STATUS)
1440                 syslog(LOG_INFO, _("Regenerating symmetric key"));
1441                 
1442               RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
1443               send_key_changed(myself, NULL);
1444               keyexpires = time(NULL) + keylifetime;
1445             }
1446         }
1447
1448       if(r > 0)
1449         {
1450           check_network_activity(&fset);
1451
1452           /* local tap data */
1453           if(FD_ISSET(tap_fd, &fset))
1454             handle_tap_input();
1455         }
1456     }
1457 cp
1458 }