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