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