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