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