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