0397ba58cc55ef703053f62b0780250790441c42
[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.149 2001/11/16 12:22:02 zarq 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 <signal.h>
37 #include <sys/signal.h>
38 #include <sys/time.h>
39 #include <sys/types.h>
40 #include <syslog.h>
41 #include <unistd.h>
42 #include <sys/ioctl.h>
43 /* SunOS really wants sys/socket.h BEFORE net/if.h,
44    and FreeBSD wants these lines below the rest. */
45 #include <arpa/inet.h>
46 #include <sys/socket.h>
47 #include <net/if.h>
48
49 #include <openssl/rand.h>
50 #include <openssl/evp.h>
51 #include <openssl/pem.h>
52
53 #ifndef HAVE_RAND_PSEUDO_BYTES
54 #define RAND_pseudo_bytes RAND_bytes
55 #endif
56
57 #include <utils.h>
58 #include <xalloc.h>
59 #include <avl_tree.h>
60 #include <list.h>
61
62 #include "conf.h"
63 #include "connection.h"
64 #include "meta.h"
65 #include "net.h"
66 #include "process.h"
67 #include "protocol.h"
68 #include "subnet.h"
69 #include "process.h"
70 #include "route.h"
71 #include "device.h"
72
73 #include "system.h"
74
75 int maxtimeout = 900;
76 int seconds_till_retry = 5;
77
78 int tcp_socket = -1;
79 int udp_socket = -1;
80
81 int keylifetime = 0;
82 int keyexpires = 0;
83
84 int do_prune = 0;
85
86 /* VPN packet I/O */
87
88 void receive_udppacket(node_t *n, vpn_packet_t *inpkt)
89 {
90   vpn_packet_t outpkt;
91   int outlen, outpad;
92   EVP_CIPHER_CTX ctx;
93 cp
94   /* Decrypt the packet */
95
96   EVP_DecryptInit(&ctx, myself->cipher, myself->key, myself->key + myself->cipher->key_len);
97   EVP_DecryptUpdate(&ctx, outpkt.salt, &outlen, inpkt->salt, inpkt->len);
98   EVP_DecryptFinal(&ctx, outpkt.salt + outlen, &outpad);
99   outlen += outpad;
100   outpkt.len = outlen - sizeof(outpkt.salt);
101
102   receive_packet(n, &outpkt);
103 cp
104 }
105
106 void receive_tcppacket(connection_t *c, char *buffer, int len)
107 {
108   vpn_packet_t outpkt;
109 cp
110   outpkt.len = len;
111   memcpy(outpkt.data, buffer, len);
112
113   receive_packet(c->node, &outpkt);
114 cp
115 }
116
117 void receive_packet(node_t *n, vpn_packet_t *packet)
118 {
119 cp
120   if(debug_lvl >= DEBUG_TRAFFIC)
121     syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"), packet->len, n->name, n->hostname);
122
123   route_incoming(n, packet);
124 cp
125 }
126
127 void send_udppacket(node_t *n, vpn_packet_t *inpkt)
128 {
129   vpn_packet_t outpkt;
130   int outlen, outpad;
131   EVP_CIPHER_CTX ctx;
132   struct sockaddr_in to;
133   socklen_t tolen = sizeof(to);
134   vpn_packet_t *copy;
135 cp
136   if(!n->status.validkey)
137     {
138       if(debug_lvl >= DEBUG_TRAFFIC)
139         syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
140                n->name, n->hostname);
141
142       /* Since packet is on the stack of handle_tap_input(),
143          we have to make a copy of it first. */
144
145       copy = xmalloc(sizeof(vpn_packet_t));
146       memcpy(copy, inpkt, sizeof(vpn_packet_t));
147
148       list_insert_tail(n->queue, copy);
149
150       if(!n->status.waitingforkey)
151         send_req_key(n->nexthop->connection, myself, n);
152       return;
153     }
154
155   /* Encrypt the packet. */
156
157   RAND_pseudo_bytes(inpkt->salt, sizeof(inpkt->salt));
158
159   EVP_EncryptInit(&ctx, n->cipher, n->key, n->key + n->cipher->key_len);
160   EVP_EncryptUpdate(&ctx, outpkt.salt, &outlen, inpkt->salt, inpkt->len + sizeof(inpkt->salt));
161   EVP_EncryptFinal(&ctx, outpkt.salt + outlen, &outpad);
162   outlen += outpad;
163
164   to.sin_family = AF_INET;
165   to.sin_addr.s_addr = htonl(n->address);
166   to.sin_port = htons(n->port);
167
168   if((sendto(udp_socket, (char *) outpkt.salt, outlen, 0, (const struct sockaddr *)&to, tolen)) < 0)
169     {
170       syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
171              n->name, n->hostname);
172       return;
173     }
174 cp
175 }
176
177 /*
178   send a packet to the given vpn ip.
179 */
180 void send_packet(node_t *n, vpn_packet_t *packet)
181 {
182 cp
183   if(debug_lvl >= DEBUG_TRAFFIC)
184     syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
185            packet->len, n->name, n->hostname);
186
187   if(n == myself)
188     {
189       if(debug_lvl >= DEBUG_TRAFFIC)
190         {
191           syslog(LOG_NOTICE, _("Packet is looping back to us!"));
192         }
193
194       return;
195     }
196
197   if(n->via != n && debug_lvl >= DEBUG_TRAFFIC)
198     syslog(LOG_ERR, _("Sending packet to %s via %s (%s)"),
199            n->name, n->via->name, n->via->hostname);
200
201   if((myself->options | n->via->options) & OPTION_TCPONLY)
202     {
203       if(send_tcppacket(n->via->connection, packet))
204         terminate_connection(n->via->connection, 1);
205     }
206   else
207     send_udppacket(n->via, packet);
208 }
209
210 /* Broadcast a packet to all active direct connections */
211
212 void broadcast_packet(node_t *from, vpn_packet_t *packet)
213 {
214   avl_node_t *node;
215   connection_t *c;
216 cp
217   if(debug_lvl >= DEBUG_TRAFFIC)
218     syslog(LOG_INFO, _("Broadcasting packet of %d bytes from %s (%s)"),
219            packet->len, from->name, from->hostname);
220
221   for(node = connection_tree->head; node; node = node->next)
222     {
223       c = (connection_t *)node->data;
224       if(c->status.active && c != from->nexthop->connection)
225         send_packet(c->node, packet);
226     }
227 cp
228 }
229
230 void flush_queue(node_t *n)
231 {
232   list_node_t *node, *next;
233 cp
234   if(debug_lvl >= DEBUG_TRAFFIC)
235     syslog(LOG_INFO, _("Flushing queue for %s (%s)"), n->name, n->hostname);
236
237   for(node = n->queue->head; node; node = next)
238     {
239       next = node->next;
240       send_udppacket(n, (vpn_packet_t *)node->data);
241       list_delete_node(n->queue, node);
242     }
243 cp
244 }
245
246 /* Setup sockets */
247
248 int setup_listen_socket(int port)
249 {
250   int nfd, flags;
251   struct sockaddr_in a;
252   int option;
253   char *address;
254   ip_mask_t *ipmask;
255 #ifdef HAVE_LINUX
256   char *interface;
257 #endif
258 cp
259   if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
260     {
261       syslog(LOG_ERR, _("Creating metasocket failed: %m"));
262       return -1;
263     }
264
265   flags = fcntl(nfd, F_GETFL);
266   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
267     {
268       close(nfd);
269       syslog(LOG_ERR, _("System call `%s' failed: %m"),
270              "fcntl");
271       return -1;
272     }
273
274   /* Optimize TCP settings */
275
276   option = 1;
277   setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
278   setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
279 #ifdef HAVE_LINUX
280   setsockopt(nfd, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
281
282   option = IPTOS_LOWDELAY;
283   setsockopt(nfd, SOL_IP, IP_TOS, &option, sizeof(option));
284
285   if(get_config_string(lookup_config(config_tree, "BindToInterface"), &interface))
286     if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, interface, strlen(interface)))
287       {
288         close(nfd);
289         syslog(LOG_ERR, _("Can't bind to interface %s: %m"), interface);
290         return -1;
291       }
292 #endif
293
294   memset(&a, 0, sizeof(a));
295   a.sin_family = AF_INET;
296   a.sin_addr.s_addr = htonl(INADDR_ANY);
297   a.sin_port = htons(port);
298
299   if(get_config_string(lookup_config(config_tree, "BindToAddress"), &address))
300     {
301       ipmask = strtoip(address);
302       if(ipmask)
303       {
304         a.sin_addr.s_addr = htonl(ipmask->address);
305         free(ipmask);
306       }
307     }
308
309   if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
310     {
311       close(nfd);
312       syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
313       return -1;
314     }
315
316   if(listen(nfd, 3))
317     {
318       close(nfd);
319       syslog(LOG_ERR, _("System call `%s' failed: %m"),
320              "listen");
321       return -1;
322     }
323 cp
324   return nfd;
325 }
326
327 int setup_vpn_in_socket(int port)
328 {
329   int nfd, flags;
330   struct sockaddr_in a;
331   const int one = 1;
332 cp
333   if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
334     {
335       close(nfd);
336       syslog(LOG_ERR, _("Creating socket failed: %m"));
337       return -1;
338     }
339
340   setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
341
342   flags = fcntl(nfd, F_GETFL);
343   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
344     {
345       close(nfd);
346       syslog(LOG_ERR, _("System call `%s' failed: %m"),
347              "fcntl");
348       return -1;
349     }
350
351   memset(&a, 0, sizeof(a));
352   a.sin_family = AF_INET;
353   a.sin_port = htons(port);
354   a.sin_addr.s_addr = htonl(INADDR_ANY);
355
356   if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
357     {
358       close(nfd);
359       syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
360       return -1;
361     }
362 cp
363   return nfd;
364 }
365
366 int setup_outgoing_socket(connection_t *c)
367 {
368   int flags;
369   struct sockaddr_in a;
370 cp
371   if(debug_lvl >= DEBUG_CONNECTIONS)
372     syslog(LOG_INFO, _("Trying to connect to %s (%s)"), c->name, c->hostname);
373
374   c->socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
375
376   if(c->socket == -1)
377     {
378       syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
379              c->hostname, c->port);
380       return -1;
381     }
382
383   /* Bind first to get a fix on our source port???
384
385   a.sin_family = AF_INET;
386   a.sin_port = htons(0);
387   a.sin_addr.s_addr = htonl(INADDR_ANY);
388
389   if(bind(c->socket, (struct sockaddr *)&a, sizeof(struct sockaddr)))
390     {
391       close(c->socket);
392       syslog(LOG_ERR, _("System call `%s' failed: %m"), "bind");
393       return -1;
394     }
395
396   */
397
398   /* Optimize TCP settings?
399
400   option = 1;
401   setsockopt(c->socket, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option));
402 #ifdef HAVE_LINUX
403   setsockopt(c->socket, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
404
405   option = IPTOS_LOWDELAY;
406   setsockopt(c->socket, SOL_IP, IP_TOS, &option, sizeof(option));
407 #endif
408
409   */
410
411   /* Connect */
412
413   if(connect(c->socket, c->address->ai_addr, c->address->ai_addrlen) == -1)
414     {
415       close(c->socket);
416       syslog(LOG_ERR, _("%s port %s: %m"), c->hostname, c->port);
417       return -1;
418     }
419
420   flags = fcntl(c->socket, F_GETFL);
421
422   if(fcntl(c->socket, F_SETFL, flags | O_NONBLOCK) < 0)
423     {
424       close(c->socket);
425       syslog(LOG_ERR, _("fcntl for %s port %s: %m"),
426              c->hostname, c->port);
427       return -1;
428     }
429
430   if(debug_lvl >= DEBUG_CONNECTIONS)
431     syslog(LOG_INFO, _("Connected to %s port %s"),
432          c->hostname, c->port);
433 cp
434   return 0;
435 }
436
437 int setup_outgoing_connection(char *name)
438 {
439   connection_t *c;
440   node_t *n;
441   struct addrinfo *ai, *aitop, hints;
442   int r, ipv6preferred;
443
444 cp
445   n = lookup_node(name);
446   
447   if(n)
448     if(n->connection)
449       {
450         if(debug_lvl >= DEBUG_CONNECTIONS)       
451           syslog(LOG_INFO, _("Already connected to %s"), name);
452         return 0;
453       }
454
455   c = new_connection();
456   c->name = xstrdup(name);
457
458   init_configuration(&c->config_tree);
459   read_connection_config(c);
460   
461   if(!get_config_string(lookup_config(c->config_tree, "Address"), &c->hostname))
462     {
463       syslog(LOG_ERR, _("No address specified for %s"), c->name);
464       free_connection(c);
465       return -1;
466     }
467
468   if(!get_config_string(lookup_config(c->config_tree, "Port"), &c->port))
469     {
470       syslog(LOG_ERR, _("No port specified for %s"), c->name);
471       free_connection(c);
472       return -1;
473     }
474
475   hints.ai_socktype = SOCK_STREAM;
476   hints.ai_family = AF_INET;
477   if(get_config_bool(lookup_config(c->config_tree, "IPv6Preferred"), &ipv6preferred))
478     {
479       if(ipv6preferred)
480         hints.ai_family = PF_UNSPEC;
481     }
482
483   if((r = getaddrinfo(c->hostname, c->port, &hints, &aitop)) != 0)
484     {
485       syslog(LOG_ERR, _("Looking up %s failed: %s\n"),
486              c->hostname, gai_strerror(r));
487       return -1;
488     }
489
490   for(ai = aitop; ai != NULL; ai = ai->ai_next)
491     {
492       if(setup_outgoing_socket(c) < 0)
493         continue;
494     }
495
496   if(ai == NULL)
497     {
498       /* No connection alternative succeeded */
499       free_connection(c);
500       return -1;
501     }
502
503   c->status.outgoing = 1;
504   c->last_ping_time = time(NULL);
505
506   connection_add(c);
507
508   send_id(c);
509 cp
510   return 0;
511 }
512
513 int read_rsa_public_key(connection_t *c)
514 {
515   FILE *fp;
516   char *fname;
517   char *key;
518 cp
519   if(!c->rsa_key)
520     c->rsa_key = RSA_new();
521
522   /* First, check for simple PublicKey statement */
523
524   if(get_config_string(lookup_config(c->config_tree, "PublicKey"), &key))
525     {
526       BN_hex2bn(&c->rsa_key->n, key);
527       BN_hex2bn(&c->rsa_key->e, "FFFF");
528       return 0;
529     }
530
531   /* Else, check for PublicKeyFile statement and read it */
532
533   if(get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &fname))
534     {
535       if(is_safe_path(fname))
536         {
537           if((fp = fopen(fname, "r")) == NULL)
538             {
539               syslog(LOG_ERR, _("Error reading RSA public key file `%s': %m"),
540                      fname);
541               return -1;
542             }
543           c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
544           fclose(fp);
545           if(!c->rsa_key)
546             {
547               syslog(LOG_ERR, _("Reading RSA public key file `%s' failed: %m"),
548                      fname);
549               return -1;
550             }
551           return 0;
552         }
553       else
554         return -1;
555     }
556
557   /* Else, check if a harnessed public key is in the config file */
558
559   asprintf(&fname, "%s/hosts/%s", confbase, c->name);
560   if((fp = fopen(fname, "r")))
561     {
562       c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
563       fclose(fp);
564     }
565
566   free(fname);
567
568   if(c->rsa_key)
569     return 0;
570   else
571     {
572       syslog(LOG_ERR, _("No public key for %s specified!"), c->name);
573       return -1;
574     }
575 }
576
577 int read_rsa_private_key(void)
578 {
579   FILE *fp;
580   char *fname, *key;
581 cp
582   if(get_config_string(lookup_config(config_tree, "PrivateKey"), &key))
583     {
584       myself->connection->rsa_key = RSA_new();
585       BN_hex2bn(&myself->connection->rsa_key->d, key);
586       BN_hex2bn(&myself->connection->rsa_key->e, "FFFF");
587     }
588   else if(get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname))
589     {
590       if((fp = fopen(fname, "r")) == NULL)
591         {
592           syslog(LOG_ERR, _("Error reading RSA private key file `%s': %m"),
593                  fname);
594           return -1;
595         }
596       myself->connection->rsa_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
597       fclose(fp);
598       if(!myself->connection->rsa_key)
599         {
600           syslog(LOG_ERR, _("Reading RSA private key file `%s' failed: %m"),
601                  fname);
602           return -1;
603         }
604     }
605   else
606     {
607       syslog(LOG_ERR, _("No private key for tinc daemon specified!"));
608       return -1;
609     }
610 cp
611   return 0;
612 }
613
614 /*
615   Configure node_t myself and set up the local sockets (listen only)
616 */
617 int setup_myself(void)
618 {
619   config_t *cfg;
620   subnet_t *subnet;
621   char *name, *mode;
622   int choice;
623 cp
624   myself = new_node();
625   myself->connection = new_connection();
626   init_configuration(&myself->connection->config_tree);
627
628   asprintf(&myself->hostname, _("MYSELF"));
629   asprintf(&myself->connection->hostname, _("MYSELF"));
630
631   myself->connection->options = 0;
632   myself->connection->protocol_version = PROT_CURRENT;
633
634   if(!get_config_string(lookup_config(config_tree, "Name"), &name)) /* Not acceptable */
635     {
636       syslog(LOG_ERR, _("Name for tinc daemon required!"));
637       return -1;
638     }
639
640   if(check_id(name))
641     {
642       syslog(LOG_ERR, _("Invalid name for myself!"));
643       free(name);
644       return -1;
645     }
646
647   myself->name = name;
648   myself->connection->name = xstrdup(name);
649
650 cp
651   if(read_rsa_private_key())
652     return -1;
653
654   if(read_connection_config(myself->connection))
655     {
656       syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
657       return -1;
658     }
659
660   if(read_rsa_public_key(myself->connection))
661     return -1;
662 cp
663
664 /*
665   if(RSA_check_key(rsa_key) != 1)
666     {
667       syslog(LOG_ERR, _("Invalid public/private keypair!"));
668       return -1;
669     }
670 */
671   if(!get_config_port(lookup_config(myself->connection->config_tree, "Port"), &myself->port))
672     myself->port = 655;
673
674   myself->connection->port = myself->port;
675
676 /* Read in all the subnets specified in the host configuration file */
677
678   cfg = lookup_config(myself->connection->config_tree, "Subnet");
679
680   while(cfg)
681     {
682       if(!get_config_subnet(cfg, &subnet))
683         return -1;
684
685       subnet_add(myself, subnet);
686
687       cfg = lookup_config_next(myself->connection->config_tree, cfg);
688     }
689
690 cp
691   /* Check some options */
692
693   if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice))
694     if(choice)
695       myself->options |= OPTION_INDIRECT;
696
697   if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice))
698     if(choice)
699       myself->options |= OPTION_TCPONLY;
700
701   if(get_config_bool(lookup_config(myself->connection->config_tree, "IndirectData"), &choice))
702     if(choice)
703       myself->options |= OPTION_INDIRECT;
704
705   if(get_config_bool(lookup_config(myself->connection->config_tree, "TCPOnly"), &choice))
706     if(choice)
707       myself->options |= OPTION_TCPONLY;
708
709   if(myself->options & OPTION_TCPONLY)
710     myself->options |= OPTION_INDIRECT;
711
712   if(get_config_string(lookup_config(config_tree, "Mode"), &mode))
713     {
714       if(!strcasecmp(mode, "router"))
715         routing_mode = RMODE_ROUTER;
716       else if (!strcasecmp(mode, "switch"))
717         routing_mode = RMODE_SWITCH;
718       else if (!strcasecmp(mode, "hub"))
719         routing_mode = RMODE_HUB;
720       else
721         {
722           syslog(LOG_ERR, _("Invalid routing mode!"));
723           return -1;
724         }
725     }
726   else
727     routing_mode = RMODE_ROUTER;
728
729 cp
730   /* Open sockets */
731   
732   if((tcp_socket = setup_listen_socket(myself->port)) < 0)
733     {
734       syslog(LOG_ERR, _("Unable to set up a listening TCP socket!"));
735       return -1;
736     }
737
738   if((udp_socket = setup_vpn_in_socket(myself->port)) < 0)
739     {
740       syslog(LOG_ERR, _("Unable to set up a listening UDP socket!"));
741       return -1;
742     }
743 cp
744   /* Generate packet encryption key */
745
746   myself->cipher = EVP_bf_cbc();
747
748   myself->keylength = myself->cipher->key_len + myself->cipher->iv_len;
749
750   myself->key = (char *)xmalloc(myself->keylength);
751   RAND_pseudo_bytes(myself->key, myself->keylength);
752
753   if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
754     keylifetime = 3600;
755
756   keyexpires = time(NULL) + keylifetime;
757 cp
758   /* Done */
759
760   myself->nexthop = myself;
761   myself->via = myself;
762   myself->status.active = 1;
763   node_add(myself);
764
765   syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
766 cp
767   return 0;
768 }
769
770 /*
771   setup all initial network connections
772 */
773 int setup_network_connections(void)
774 {
775 cp
776   init_connections();
777   init_subnets();
778   init_nodes();
779   init_edges();
780
781   if(get_config_int(lookup_config(config_tree, "PingTimeout"), &timeout))
782     {
783       if(timeout < 1)
784         {
785           timeout = 86400;
786         }
787     }
788   else
789     timeout = 60;
790
791   if(setup_device() < 0)
792     return -1;
793
794   /* Run tinc-up script to further initialize the tap interface */
795   execute_script("tinc-up");
796
797   if(setup_myself() < 0)
798     return -1;
799
800   signal(SIGALRM, try_outgoing_connections);
801   alarm(5);
802 cp
803   return 0;
804 }
805
806 /*
807   close all open network connections
808 */
809 void close_network_connections(void)
810 {
811   avl_node_t *node, *next;
812   connection_t *c;
813 cp
814   for(node = connection_tree->head; node; node = next)
815     {
816       next = node->next;
817       c = (connection_t *)node->data;
818       c->status.outgoing = 0;
819       terminate_connection(c, 0);
820     }
821
822   terminate_connection(myself->connection, 0);
823
824   close(udp_socket);
825   close(tcp_socket);
826
827   exit_edges();
828   exit_subnets();
829   exit_nodes();
830   exit_connections();
831
832   execute_script("tinc-down");
833
834   close_device();
835 cp
836   return;
837 }
838
839 /*
840   handle an incoming tcp connect call and open
841   a connection to it.
842 */
843 connection_t *create_new_connection(int sfd)
844 {
845   connection_t *c;
846   struct sockaddr_in ci;
847   int len = sizeof(ci);
848 cp
849   c = new_connection();
850
851   if(getpeername(sfd, (struct sockaddr *) &ci, (socklen_t *) &len) < 0)
852     {
853       syslog(LOG_ERR, _("System call `%s' failed: %m"),
854              "getpeername");
855       close(sfd);
856       return NULL;
857     }
858
859   c->address = ntohl(ci.sin_addr.s_addr);
860   c->hostname = hostlookup(ci.sin_addr.s_addr);
861   c->port = htons(ci.sin_port);
862   c->socket = sfd;
863   c->last_ping_time = time(NULL);
864
865   if(debug_lvl >= DEBUG_CONNECTIONS)
866     syslog(LOG_NOTICE, _("Connection from %s port %d"),
867          c->hostname, c->port);
868
869   c->allow_request = ID;
870 cp
871   return c;
872 }
873
874 /*
875   put all file descriptors in an fd_set array
876 */
877 void build_fdset(fd_set *fs)
878 {
879   avl_node_t *node;
880   connection_t *c;
881 cp
882   FD_ZERO(fs);
883
884   for(node = connection_tree->head; node; node = node->next)
885     {
886       c = (connection_t *)node->data;
887       FD_SET(c->socket, fs);
888     }
889
890   FD_SET(tcp_socket, fs);
891   FD_SET(udp_socket, fs);
892   FD_SET(device_fd, fs);
893 cp
894 }
895
896 /*
897   receive incoming data from the listening
898   udp socket and write it to the ethertap
899   device after being decrypted
900 */
901 void handle_incoming_vpn_data(void)
902 {
903   vpn_packet_t pkt;
904   int x, l = sizeof(x);
905   struct sockaddr_in from;
906   socklen_t fromlen = sizeof(from);
907   node_t *n;
908 cp
909   if(getsockopt(udp_socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
910     {
911       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
912              __FILE__, __LINE__, udp_socket);
913       return;
914     }
915   if(x)
916     {
917       syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
918       return;
919     }
920
921   if((pkt.len = recvfrom(udp_socket, (char *) pkt.salt, MTU, 0, (struct sockaddr *)&from, &fromlen)) <= 0)
922     {
923       syslog(LOG_ERR, _("Receiving packet failed: %m"));
924       return;
925     }
926
927   n = lookup_node_udp(ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
928
929   if(!n)
930     {
931       syslog(LOG_WARNING, _("Received UDP packet on port %hd from unknown source %x:%hd"), myself->port, ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
932       return;
933     }
934 /*
935   if(n->connection)
936     n->connection->last_ping_time = time(NULL);
937 */
938   receive_udppacket(n, &pkt);
939 cp
940 }
941
942 /*
943   Terminate a connection:
944   - Close the socket
945   - Remove associated edge and tell other connections about it if report = 1
946   - Check if we need to retry making an outgoing connection
947   - Deactivate the host
948 */
949 void terminate_connection(connection_t *c, int report)
950 {
951   avl_node_t *node;
952   connection_t *other;
953 cp
954   if(c->status.remove)
955     return;
956   
957   if(debug_lvl >= DEBUG_CONNECTIONS)
958     syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
959            c->name, c->hostname);
960
961   c->status.remove = 1;
962   
963   if(c->socket)
964     close(c->socket);
965
966   if(c->edge)
967     {
968       if(report)
969         {
970           for(node = connection_tree->head; node; node = node->next)
971             {
972               other = (connection_t *)node->data;
973               if(other->status.active && other != c)
974                 send_del_edge(other, c->edge);
975             }
976         }
977
978       edge_del(c->edge);
979     }
980
981   /* Check if this was our outgoing connection */
982
983   if(c->status.outgoing)
984     {
985       c->status.outgoing = 0;
986       signal(SIGALRM, try_outgoing_connections);
987       alarm(seconds_till_retry);
988       syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
989     }
990
991   /* Deactivate */
992
993   c->status.active = 0;
994   if(c->node)
995     c->node->connection = NULL;
996   do_prune = 1;
997 cp
998 }
999
1000 /*
1001   Check if the other end is active.
1002   If we have sent packets, but didn't receive any,
1003   then possibly the other end is dead. We send a
1004   PING request over the meta connection. If the other
1005   end does not reply in time, we consider them dead
1006   and close the connection.
1007 */
1008 void check_dead_connections(void)
1009 {
1010   time_t now;
1011   avl_node_t *node, *next;
1012   connection_t *c;
1013 cp
1014   now = time(NULL);
1015
1016   for(node = connection_tree->head; node; node = next)
1017     {
1018       next = node->next;
1019       c = (connection_t *)node->data;
1020       if(c->last_ping_time + timeout < now)
1021         {
1022           if(c->status.active)
1023             {
1024               if(c->status.pinged)
1025                 {
1026                   if(debug_lvl >= DEBUG_PROTOCOL)
1027                     syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1028                            c->name, c->hostname);
1029                   c->status.timeout = 1;
1030                   terminate_connection(c, 1);
1031                 }
1032               else
1033                 {
1034                   send_ping(c);
1035                 }
1036             }
1037           else
1038             {
1039               if(debug_lvl >= DEBUG_CONNECTIONS)
1040                 syslog(LOG_WARNING, _("Timeout from %s (%s) during authentication"),
1041                        c->name, c->hostname);
1042               terminate_connection(c, 0);
1043             }
1044         }
1045     }
1046 cp
1047 }
1048
1049 /*
1050   accept a new tcp connect and create a
1051   new connection
1052 */
1053 int handle_new_meta_connection()
1054 {
1055   connection_t *new;
1056   struct sockaddr client;
1057   int fd, len = sizeof(client);
1058 cp
1059   if((fd = accept(tcp_socket, &client, &len)) < 0)
1060     {
1061       syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1062       return -1;
1063     }
1064
1065   if(!(new = create_new_connection(fd)))
1066     {
1067       shutdown(fd, 2);
1068       close(fd);
1069       syslog(LOG_NOTICE, _("Closed attempted connection"));
1070       return 0;
1071     }
1072
1073   connection_add(new);
1074
1075   send_id(new);
1076 cp
1077   return 0;
1078 }
1079
1080 void randomized_alarm(int seconds)
1081 {
1082   unsigned char r;
1083   RAND_pseudo_bytes(&r, 1);
1084   alarm((seconds * (int)r) / 128 + 1);
1085 }
1086
1087 /* This function is severely fucked up.
1088    We want to redesign it so the following rules apply:
1089    
1090    - Try all ConnectTo's in a row:
1091      - if a connect() fails, try next one immediately,
1092      - if it works, wait 5 seconds or so.
1093    - If none of them were succesful, increase delay and retry.
1094    - If all were succesful, don't try anymore.
1095 */
1096
1097 RETSIGTYPE
1098 try_outgoing_connections(int a)
1099 {
1100   static config_t *cfg = NULL;
1101   static int retry = 0;
1102   char *name;
1103 cp
1104   if(!cfg)
1105     cfg = lookup_config(config_tree, "ConnectTo");
1106
1107   if(!cfg)
1108     return;
1109
1110   while(cfg)
1111     {
1112       get_config_string(cfg, &name);
1113
1114       if(check_id(name))
1115         {
1116           syslog(LOG_ERR, _("Invalid name for outgoing connection in %s line %d"), cfg->file, cfg->line);
1117           continue;
1118         }
1119
1120       if(setup_outgoing_connection(name))   /* function returns 0 when there are no problems */
1121         retry = 1;
1122
1123       cfg = lookup_config_next(config._tree, cfg); /* Next time skip to next ConnectTo line */
1124     }
1125
1126   get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout);
1127
1128   if(retry)
1129     {
1130       seconds_till_retry += 5;
1131       if(seconds_till_retry > maxtimeout)    /* Don't wait more than MAXTIMEOUT seconds. */
1132         seconds_till_retry = maxtimeout;
1133
1134       syslog(LOG_ERR, _("Failed to setup any outgoing connection, will retry in %d seconds"),
1135         seconds_till_retry);
1136   
1137       /* Randomize timeout to avoid global synchronisation effects */
1138       randomized_alarm(seconds_till_retry);
1139     }
1140   else
1141     {
1142       seconds_till_retry = 5;
1143     }
1144 cp
1145 }
1146
1147 /*
1148   check all connections to see if anything
1149   happened on their sockets
1150 */
1151 void check_network_activity(fd_set *f)
1152 {
1153   connection_t *c;
1154   avl_node_t *node;
1155 cp
1156   if(FD_ISSET(udp_socket, f))
1157     handle_incoming_vpn_data();
1158
1159   for(node = connection_tree->head; node; node = node->next)
1160     {
1161       c = (connection_t *)node->data;
1162
1163       if(c->status.remove)
1164         return;
1165
1166       if(FD_ISSET(c->socket, f))
1167         if(receive_meta(c) < 0)
1168           {
1169             terminate_connection(c, c->status.active);
1170             return;
1171           }
1172     }
1173
1174   if(FD_ISSET(tcp_socket, f))
1175     handle_new_meta_connection();
1176 cp
1177 }
1178
1179 void prune_connections(void)
1180 {
1181   connection_t *c;
1182   avl_node_t *node, *next;
1183 cp
1184   for(node = connection_tree->head; node; node = next)
1185     {
1186       next = node->next;
1187       c = (connection_t *)node->data;
1188
1189       if(c->status.remove)
1190         connection_del(c);
1191     }
1192 cp
1193 }
1194
1195 /*
1196   this is where it all happens...
1197 */
1198 void main_loop(void)
1199 {
1200   fd_set fset;
1201   struct timeval tv;
1202   int r;
1203   time_t last_ping_check;
1204   int t;
1205   vpn_packet_t packet;
1206 cp
1207   last_ping_check = time(NULL);
1208
1209   for(;;)
1210     {
1211       tv.tv_sec = timeout;
1212       tv.tv_usec = 0;
1213
1214       if(do_prune)
1215         {
1216           prune_connections();
1217           do_prune = 0;
1218         }
1219
1220       build_fdset(&fset);
1221
1222       if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1223         {
1224           if(errno != EINTR) /* because of alarm */
1225             {
1226               syslog(LOG_ERR, _("Error while waiting for input: %m"));
1227               return;
1228             }
1229         }
1230
1231       if(sighup)
1232         {
1233           syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1234           sighup = 0;
1235           close_network_connections();
1236           exit_configuration(&config_tree);
1237
1238           if(read_server_config())
1239             {
1240               syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1241               exit(1);
1242             }
1243
1244           sleep(5);
1245
1246           if(setup_network_connections())
1247             return;
1248
1249           continue;
1250         }
1251
1252       t = time(NULL);
1253
1254       /* Let's check if everybody is still alive */
1255
1256       if(last_ping_check + timeout < t)
1257         {
1258           check_dead_connections();
1259           last_ping_check = time(NULL);
1260
1261           /* Should we regenerate our key? */
1262
1263           if(keyexpires < t)
1264             {
1265               if(debug_lvl >= DEBUG_STATUS)
1266                 syslog(LOG_INFO, _("Regenerating symmetric key"));
1267
1268               RAND_pseudo_bytes(myself->key, myself->keylength);
1269               send_key_changed(myself->connection, myself);
1270               keyexpires = time(NULL) + keylifetime;
1271             }
1272         }
1273
1274       if(r > 0)
1275         {
1276           check_network_activity(&fset);
1277
1278           /* local tap data */
1279           if(FD_ISSET(device_fd, &fset))
1280             {
1281               if(read_packet(&packet))
1282                 return;
1283               else
1284                 route_outgoing(&packet);
1285             }
1286         }
1287     }
1288 cp
1289 }