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