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