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