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