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