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