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