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