Correctly cycle through ConnectTo variables.
[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.104 2001/05/04 18:45:02 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)
852     if(upstreamcfg == config)
853     {
854       /* No upstream IP given, we're listen only. */
855       signal(SIGALRM, SIG_IGN);
856       return;
857     }
858   else
859     {
860       /* We previously tried all the ConnectTo lines. Now wrap back to the first. */
861       cfg = get_config_val(config, config_connectto);
862     }
863     
864   while(cfg)
865     {
866       upstreamcfg = cfg->next;
867       if(!setup_outgoing_connection(cfg->data.ptr))   /* function returns 0 when there are no problems */
868         {
869           signal(SIGALRM, SIG_IGN);
870           return;
871         }
872       cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
873     }
874
875   signal(SIGALRM, sigalrm_handler);
876   upstreamcfg = config;
877   seconds_till_retry += 5;
878   if(seconds_till_retry > MAXTIMEOUT)    /* Don't wait more than MAXTIMEOUT seconds. */
879     seconds_till_retry = MAXTIMEOUT;
880   syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
881          seconds_till_retry);
882   alarm(seconds_till_retry);
883 cp
884 }
885
886 /*
887   setup all initial network connections
888 */
889 int setup_network_connections(void)
890 {
891   config_t const *cfg;
892 cp
893   init_connections();
894   init_subnets();
895
896   if((cfg = get_config_val(config, config_pingtimeout)) == NULL)
897     timeout = 60;
898   else
899     {
900       timeout = cfg->data.val;
901       if(timeout < 1)
902         {
903           timeout = 86400;
904         }
905      }
906
907   if(setup_tap_fd() < 0)
908     return -1;
909
910   /* Run tinc-up script to further initialize the tap interface */
911   execute_script("tinc-up");
912
913   if(setup_myself() < 0)
914     return -1;
915
916   if(!(cfg = get_config_val(config, config_connectto)))
917     /* No upstream IP given, we're listen only. */
918     return 0;
919
920   while(cfg)
921     {
922       upstreamcfg = cfg->next;
923       if(!setup_outgoing_connection(cfg->data.ptr))   /* function returns 0 when there are no problems */
924         return 0;
925       cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
926     }
927
928   if(do_detach)
929     {
930       signal(SIGALRM, sigalrm_handler);
931       upstreamcfg = config;
932       seconds_till_retry = MAXTIMEOUT;
933       syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
934       alarm(seconds_till_retry);
935     }
936   else
937     return -1;
938
939 cp
940   return 0;
941 }
942
943 /*
944   close all open network connections
945 */
946 void close_network_connections(void)
947 {
948   avl_node_t *node;
949   connection_t *p;
950 cp
951   for(node = connection_tree->head; node; node = node->next)
952     {
953       p = (connection_t *)node->data;
954       p->status.outgoing = 0;
955       p->status.active = 0;
956       terminate_connection(p);
957     }
958
959   if(myself)
960     if(myself->status.active)
961       {
962         close(myself->meta_socket);
963         free_connection(myself);
964         myself = NULL;
965       }
966
967   close(tap_fd);
968
969   /* Execute tinc-down script right after shutting down the interface */
970   execute_script("tinc-down");
971
972   destroy_connection_tree();
973 cp
974   return;
975 }
976
977 /*
978   handle an incoming tcp connect call and open
979   a connection to it.
980 */
981 connection_t *create_new_connection(int sfd)
982 {
983   connection_t *p;
984   struct sockaddr_in ci;
985   int len = sizeof(ci);
986 cp
987   p = new_connection();
988
989   if(getpeername(sfd, (struct sockaddr *) &ci, (socklen_t *) &len) < 0)
990     {
991       syslog(LOG_ERR, _("System call `%s' failed: %m"),
992              "getpeername");
993       close(sfd);
994       return NULL;
995     }
996
997   p->name = unknown;
998   p->address = ntohl(ci.sin_addr.s_addr);
999   p->hostname = hostlookup(ci.sin_addr.s_addr);
1000   p->port = htons(ci.sin_port);                         /* This one will be overwritten later */
1001   p->meta_socket = sfd;
1002   p->status.meta = 1;
1003   p->buffer = xmalloc(MAXBUFSIZE);
1004   p->buflen = 0;
1005   p->last_ping_time = time(NULL);
1006
1007   if(debug_lvl >= DEBUG_CONNECTIONS)
1008     syslog(LOG_NOTICE, _("Connection from %s port %d"),
1009          p->hostname, htons(ci.sin_port));
1010
1011   p->allow_request = ID;
1012 cp
1013   return p;
1014 }
1015
1016 /*
1017   put all file descriptors in an fd_set array
1018 */
1019 void build_fdset(fd_set *fs)
1020 {
1021   avl_node_t *node;
1022   connection_t *p;
1023 cp
1024   FD_ZERO(fs);
1025
1026   FD_SET(myself->socket, fs);
1027
1028   for(node = connection_tree->head; node; node = node->next)
1029     {
1030       p = (connection_t *)node->data;
1031       if(p->status.meta)
1032         FD_SET(p->meta_socket, fs);
1033     }
1034
1035   FD_SET(myself->meta_socket, fs);
1036   FD_SET(tap_fd, fs);
1037 cp
1038 }
1039
1040 /*
1041   receive incoming data from the listening
1042   udp socket and write it to the ethertap
1043   device after being decrypted
1044 */
1045 void handle_incoming_vpn_data(void)
1046 {
1047   vpn_packet_t pkt;
1048   int x, l = sizeof(x);
1049   int lenin;
1050   struct sockaddr_in from;
1051   socklen_t fromlen = sizeof(from);
1052   connection_t *cl;
1053 cp
1054   if(getsockopt(myself->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1055     {
1056       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1057              __FILE__, __LINE__, myself->socket);
1058       return;
1059     }
1060   if(x)
1061     {
1062       syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1063       return;
1064     }
1065
1066   if((lenin = recvfrom(myself->socket, (char *) &(pkt.len), MTU, 0, (struct sockaddr *)&from, &fromlen)) <= 0)
1067     {
1068       syslog(LOG_ERR, _("Receiving packet failed: %m"));
1069       return;
1070     }
1071
1072   cl = lookup_connection(ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
1073
1074   if(!cl)
1075     {
1076       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));
1077       return;
1078     }
1079
1080   receive_udppacket(cl, &pkt);
1081 cp
1082 }
1083
1084 /*
1085   terminate a connection and notify the other
1086   end before closing the sockets
1087 */
1088 void terminate_connection(connection_t *cl)
1089 {
1090   connection_t *p;
1091   subnet_t *subnet;
1092   avl_node_t *node, *next;
1093 cp
1094   if(cl->status.remove)
1095     return;
1096
1097   if(debug_lvl >= DEBUG_CONNECTIONS)
1098     syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1099            cl->name, cl->hostname);
1100
1101   cl->status.remove = 1;
1102
1103   if(cl->socket)
1104     close(cl->socket);
1105   if(cl->status.meta)
1106     close(cl->meta_socket);
1107
1108   if(cl->status.meta)
1109     {
1110
1111       /* Find all connections that were lost because they were behind cl
1112          (the connection that was dropped). */
1113
1114         for(node = connection_tree->head; node; node = node->next)
1115           {
1116             p = (connection_t *)node->data;
1117             if(p->nexthop == cl && p != cl)
1118               terminate_connection(p);
1119           }
1120
1121       /* Inform others of termination if it was still active */
1122
1123       if(cl->status.active)
1124         for(node = connection_tree->head; node; node = node->next)
1125           {
1126             p = (connection_t *)node->data;
1127             if(p->status.meta && p->status.active && p != cl)
1128               send_del_host(p, cl);     /* Sounds like recursion, but p does not have a meta connection :) */
1129           }
1130     }
1131
1132   /* Remove the associated subnets */
1133
1134   for(node = cl->subnet_tree->head; node; node = next)
1135     {
1136       next = node->next;
1137       subnet = (subnet_t *)node->data;
1138       subnet_del(subnet);
1139     }
1140
1141   /* Check if this was our outgoing connection */
1142
1143   if(cl->status.outgoing)
1144     {
1145       cl->status.outgoing = 0;
1146       signal(SIGALRM, sigalrm_handler);
1147       seconds_till_retry = 5;
1148       alarm(seconds_till_retry);
1149       syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
1150     }
1151
1152   /* Inactivate */
1153
1154   cl->status.active = 0;
1155 cp
1156 }
1157
1158 /*
1159   Check if the other end is active.
1160   If we have sent packets, but didn't receive any,
1161   then possibly the other end is dead. We send a
1162   PING request over the meta connection. If the other
1163   end does not reply in time, we consider them dead
1164   and close the connection.
1165 */
1166 void check_dead_connections(void)
1167 {
1168   time_t now;
1169   avl_node_t *node;
1170   connection_t *cl;
1171 cp
1172   now = time(NULL);
1173
1174   for(node = connection_tree->head; node; node = node->next)
1175     {
1176       cl = (connection_t *)node->data;
1177       if(cl->status.active && cl->status.meta)
1178         {
1179           if(cl->last_ping_time + timeout < now)
1180             {
1181               if(cl->status.pinged)
1182                 {
1183                   if(debug_lvl >= DEBUG_PROTOCOL)
1184                     syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1185                            cl->name, cl->hostname);
1186                   cl->status.timeout = 1;
1187                   terminate_connection(cl);
1188                 }
1189               else
1190                 {
1191                   send_ping(cl);
1192                 }
1193             }
1194         }
1195     }
1196 cp
1197 }
1198
1199 /*
1200   accept a new tcp connect and create a
1201   new connection
1202 */
1203 int handle_new_meta_connection()
1204 {
1205   connection_t *ncn;
1206   struct sockaddr client;
1207   int nfd, len = sizeof(client);
1208 cp
1209   if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
1210     {
1211       syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1212       return -1;
1213     }
1214
1215   if(!(ncn = create_new_connection(nfd)))
1216     {
1217       shutdown(nfd, 2);
1218       close(nfd);
1219       syslog(LOG_NOTICE, _("Closed attempted connection"));
1220       return 0;
1221     }
1222
1223   connection_add(ncn);
1224
1225   send_id(ncn);
1226 cp
1227   return 0;
1228 }
1229
1230 /*
1231   check all connections to see if anything
1232   happened on their sockets
1233 */
1234 void check_network_activity(fd_set *f)
1235 {
1236   connection_t *p;
1237   avl_node_t *node;
1238 cp
1239   if(FD_ISSET(myself->socket, f))
1240     handle_incoming_vpn_data();
1241
1242   for(node = connection_tree->head; node; node = node->next)
1243     {
1244       p = (connection_t *)node->data;
1245
1246       if(p->status.remove)
1247         return;
1248
1249       if(p->status.meta)
1250         if(FD_ISSET(p->meta_socket, f))
1251           if(receive_meta(p) < 0)
1252             {
1253               terminate_connection(p);
1254               return;
1255             }
1256     }
1257
1258   if(FD_ISSET(myself->meta_socket, f))
1259     handle_new_meta_connection();
1260 cp
1261 }
1262
1263 /*
1264   read, encrypt and send data that is
1265   available through the ethertap device
1266 */
1267 void handle_tap_input(void)
1268 {
1269   vpn_packet_t vp;
1270   int lenin;
1271 cp
1272   if(taptype == TAP_TYPE_TUNTAP)
1273     {
1274       if((lenin = read(tap_fd, vp.data, MTU)) <= 0)
1275         {
1276           syslog(LOG_ERR, _("Error while reading from tun/tap device: %m"));
1277           return;
1278         }
1279       vp.len = lenin;
1280     }
1281   else                  /* ethertap */
1282     {
1283       if((lenin = read(tap_fd, vp.data - 2, MTU)) <= 0)
1284         {
1285           syslog(LOG_ERR, _("Error while reading from ethertap device: %m"));
1286           return;
1287         }
1288       vp.len = lenin - 2;
1289     }
1290
1291   total_tap_in += lenin;
1292
1293   if(lenin < 32)
1294     {
1295       if(debug_lvl >= DEBUG_TRAFFIC)
1296         syslog(LOG_WARNING, _("Received short packet from tap device"));
1297       return;
1298     }
1299
1300   if(debug_lvl >= DEBUG_TRAFFIC)
1301     {
1302       syslog(LOG_DEBUG, _("Read packet of length %d from tap device"), vp.len);
1303     }
1304
1305   route_outgoing(&vp);
1306 cp
1307 }
1308
1309 /*
1310   this is where it all happens...
1311 */
1312 void main_loop(void)
1313 {
1314   fd_set fset;
1315   struct timeval tv;
1316   int r;
1317   time_t last_ping_check;
1318   int t;
1319 cp
1320   last_ping_check = time(NULL);
1321
1322   for(;;)
1323     {
1324       tv.tv_sec = timeout;
1325       tv.tv_usec = 0;
1326
1327       prune_connection_tree();
1328       build_fdset(&fset);
1329
1330       if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1331         {
1332           if(errno != EINTR) /* because of alarm */
1333             {
1334               syslog(LOG_ERR, _("Error while waiting for input: %m"));
1335               return;
1336             }
1337         }
1338
1339       if(sighup)
1340         {
1341           syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1342           sighup = 0;
1343           close_network_connections();
1344           clear_config(&config);
1345
1346           if(read_server_config())
1347             {
1348               syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1349               exit(1);
1350             }
1351
1352           sleep(5);
1353
1354           if(setup_network_connections())
1355             return;
1356
1357           continue;
1358         }
1359
1360       t = time(NULL);
1361
1362       /* Let's check if everybody is still alive */
1363
1364       if(last_ping_check + timeout < t)
1365         {
1366           check_dead_connections();
1367           last_ping_check = time(NULL);
1368
1369           /* Should we regenerate our key? */
1370
1371           if(keyexpires < t)
1372             {
1373               if(debug_lvl >= DEBUG_STATUS)
1374                 syslog(LOG_INFO, _("Regenerating symmetric key"));
1375
1376               RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
1377               send_key_changed(myself, NULL);
1378               keyexpires = time(NULL) + keylifetime;
1379             }
1380         }
1381
1382       if(r > 0)
1383         {
1384           check_network_activity(&fset);
1385
1386           /* local tap data */
1387           if(FD_ISSET(tap_fd, &fset))
1388             handle_tap_input();
1389         }
1390     }
1391 cp
1392 }