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