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