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