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