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