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