Various small fixes to make tinc runnable again.
[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.139 2001/10/27 15:19:13 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->port))
670     myself->port = 655;
671
672   myself->connection->port = myself->port;
673
674 /* Read in all the subnets specified in the host configuration file */
675
676   cfg = lookup_config(myself->connection->config_tree, "Subnet");
677
678   while(cfg)
679     {
680       if(!get_config_subnet(cfg, &subnet))
681         return -1;
682
683       subnet_add(myself, subnet);
684
685       cfg = lookup_config_next(myself->connection->config_tree, cfg);
686     }
687
688 cp
689   /* Check some options */
690
691   if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice))
692     if(choice)
693       myself->options |= OPTION_INDIRECT;
694
695   if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice))
696     if(choice)
697       myself->options |= OPTION_TCPONLY;
698
699   if(get_config_bool(lookup_config(myself->connection->config_tree, "IndirectData"), &choice))
700     if(choice)
701       myself->options |= OPTION_INDIRECT;
702
703   if(get_config_bool(lookup_config(myself->connection->config_tree, "TCPOnly"), &choice))
704     if(choice)
705       myself->options |= OPTION_TCPONLY;
706
707   if(myself->options & OPTION_TCPONLY)
708     myself->options |= OPTION_INDIRECT;
709
710   if(get_config_string(lookup_config(config_tree, "Mode"), &mode))
711     {
712       if(!strcasecmp(mode, "router"))
713         routing_mode = RMODE_ROUTER;
714       else if (!strcasecmp(mode, "switch"))
715         routing_mode = RMODE_SWITCH;
716       else if (!strcasecmp(mode, "hub"))
717         routing_mode = RMODE_HUB;
718       else
719         {
720           syslog(LOG_ERR, _("Invalid routing mode!"));
721           return -1;
722         }
723     }
724   else
725     routing_mode = RMODE_ROUTER;
726
727 cp
728   /* Open sockets */
729   
730   if((tcp_socket = setup_listen_socket(myself->port)) < 0)
731     {
732       syslog(LOG_ERR, _("Unable to set up a listening TCP socket!"));
733       return -1;
734     }
735
736   if((udp_socket = setup_vpn_in_socket(myself->port)) < 0)
737     {
738       syslog(LOG_ERR, _("Unable to set up a listening UDP socket!"));
739       return -1;
740     }
741 cp
742   /* Generate packet encryption key */
743
744   myself->cipher = EVP_bf_cbc();
745
746   myself->keylength = myself->cipher->key_len + myself->cipher->iv_len;
747
748   myself->key = (char *)xmalloc(myself->keylength);
749   RAND_pseudo_bytes(myself->key, myself->keylength);
750
751   if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
752     keylifetime = 3600;
753
754   keyexpires = time(NULL) + keylifetime;
755 cp
756   /* Done */
757
758   myself->nexthop = myself;
759   myself->via = myself;
760   myself->status.active = 1;
761   node_add(myself);
762
763   syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
764 cp
765   return 0;
766 }
767
768 /*
769   setup all initial network connections
770 */
771 int setup_network_connections(void)
772 {
773 cp
774   init_connections();
775   init_subnets();
776   init_nodes();
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, 0);
820
821 //  destroy_trees();
822
823   execute_script("tinc-down");
824
825   close_device();
826 cp
827   return;
828 }
829
830 /*
831   handle an incoming tcp connect call and open
832   a connection to it.
833 */
834 connection_t *create_new_connection(int sfd)
835 {
836   connection_t *c;
837   struct sockaddr_in ci;
838   int len = sizeof(ci);
839 cp
840   c = new_connection();
841
842   if(getpeername(sfd, (struct sockaddr *) &ci, (socklen_t *) &len) < 0)
843     {
844       syslog(LOG_ERR, _("System call `%s' failed: %m"),
845              "getpeername");
846       close(sfd);
847       return NULL;
848     }
849
850   c->address = ntohl(ci.sin_addr.s_addr);
851   c->hostname = hostlookup(ci.sin_addr.s_addr);
852   c->port = htons(ci.sin_port);                         /* This one will be overwritten later */
853   c->socket = sfd;
854   c->last_ping_time = time(NULL);
855
856   if(debug_lvl >= DEBUG_CONNECTIONS)
857     syslog(LOG_NOTICE, _("Connection from %s port %d"),
858          c->hostname, htons(ci.sin_port));
859
860   c->allow_request = ID;
861 cp
862   return c;
863 }
864
865 /*
866   put all file descriptors in an fd_set array
867 */
868 void build_fdset(fd_set *fs)
869 {
870   avl_node_t *node;
871   connection_t *c;
872 cp
873   FD_ZERO(fs);
874
875   for(node = connection_tree->head; node; node = node->next)
876     {
877       c = (connection_t *)node->data;
878       FD_SET(c->socket, fs);
879     }
880
881   FD_SET(tcp_socket, fs);
882   FD_SET(udp_socket, fs);
883   FD_SET(device_fd, fs);
884 cp
885 }
886
887 /*
888   receive incoming data from the listening
889   udp socket and write it to the ethertap
890   device after being decrypted
891 */
892 void handle_incoming_vpn_data(void)
893 {
894   vpn_packet_t pkt;
895   int x, l = sizeof(x);
896   struct sockaddr_in from;
897   socklen_t fromlen = sizeof(from);
898   node_t *n;
899 cp
900   if(getsockopt(udp_socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
901     {
902       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
903              __FILE__, __LINE__, udp_socket);
904       return;
905     }
906   if(x)
907     {
908       syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
909       return;
910     }
911
912   if((pkt.len = recvfrom(udp_socket, (char *) pkt.salt, MTU, 0, (struct sockaddr *)&from, &fromlen)) <= 0)
913     {
914       syslog(LOG_ERR, _("Receiving packet failed: %m"));
915       return;
916     }
917
918   n = lookup_node_udp(ntohl(from.sin_addr.s_addr), ntohs(from.sin_port));
919
920   if(!n)
921     {
922       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));
923       return;
924     }
925 /*
926   if(n->connection)
927     n->connection->last_ping_time = time(NULL);
928 */
929   receive_udppacket(n, &pkt);
930 cp
931 }
932
933 /*
934   Terminate a connection:
935   - Close the sockets
936   - Remove associated hosts and subnets
937   - Deactivate the host
938   - Since it might still be referenced, put it on the prune list.
939   - If report == 1, then send DEL_HOST messages to the other tinc daemons.
940 */
941 void terminate_connection(connection_t *c, int report)
942 {
943   /* Needs a serious rewrite. */
944 }
945
946 /*
947   Check if the other end is active.
948   If we have sent packets, but didn't receive any,
949   then possibly the other end is dead. We send a
950   PING request over the meta connection. If the other
951   end does not reply in time, we consider them dead
952   and close the connection.
953 */
954 void check_dead_connections(void)
955 {
956   time_t now;
957   avl_node_t *node, *next;
958   connection_t *c;
959 cp
960   now = time(NULL);
961
962   for(node = connection_tree->head; node; node = next)
963     {
964       next = node->next;
965       c = (connection_t *)node->data;
966       if(c->last_ping_time + timeout < now)
967         {
968           if(c->status.active)
969             {
970               if(c->status.pinged)
971                 {
972                   if(debug_lvl >= DEBUG_PROTOCOL)
973                     syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
974                            c->name, c->hostname);
975                   c->status.timeout = 1;
976                   terminate_connection(c, 1);
977                 }
978               else
979                 {
980                   send_ping(c);
981                 }
982             }
983           else
984             {
985               if(debug_lvl >= DEBUG_CONNECTIONS)
986                 syslog(LOG_WARNING, _("Timeout from %s (%s) during authentication"),
987                        c->name, c->hostname);
988               terminate_connection(c, 0);
989             }
990         }
991     }
992 cp
993 }
994
995 /*
996   accept a new tcp connect and create a
997   new connection
998 */
999 int handle_new_meta_connection()
1000 {
1001   connection_t *new;
1002   struct sockaddr client;
1003   int fd, len = sizeof(client);
1004 cp
1005   if((fd = accept(tcp_socket, &client, &len)) < 0)
1006     {
1007       syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1008       return -1;
1009     }
1010
1011   if(!(new = create_new_connection(fd)))
1012     {
1013       shutdown(fd, 2);
1014       close(fd);
1015       syslog(LOG_NOTICE, _("Closed attempted connection"));
1016       return 0;
1017     }
1018
1019   connection_add(new);
1020
1021   send_id(new);
1022 cp
1023   return 0;
1024 }
1025
1026 void randomized_alarm(int seconds)
1027 {
1028   unsigned char r;
1029   RAND_pseudo_bytes(&r, 1);
1030   alarm((seconds * (int)r) / 128 + 1);
1031 }
1032
1033 /* This function is severely fucked up.
1034    We want to redesign it so the following rules apply:
1035    
1036    - Try all ConnectTo's in a row:
1037      - if a connect() fails, try next one immediately,
1038      - if it works, wait 5 seconds or so.
1039    - If none of them were succesful, increase delay and retry.
1040    - If all were succesful, don't try anymore.
1041 */
1042
1043 RETSIGTYPE
1044 try_outgoing_connections(int a)
1045 {
1046   static config_t *cfg = NULL;
1047   static int retry = 0;
1048   char *name;
1049 cp
1050   if(!cfg)
1051     cfg = lookup_config(config_tree, "ConnectTo");
1052
1053   if(!cfg)
1054     return;
1055
1056   while(cfg)
1057     {
1058       get_config_string(cfg, &name);
1059       cfg = lookup_config_next(config_tree, cfg);  /* Next time skip to next ConnectTo line */
1060
1061       if(!setup_outgoing_connection(name))   /* function returns 0 when there are no problems */
1062         retry = 1;
1063
1064     }
1065
1066   get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout);
1067
1068   if(retry)
1069     {
1070       seconds_till_retry += 5;
1071       if(seconds_till_retry > maxtimeout)    /* Don't wait more than MAXTIMEOUT seconds. */
1072         seconds_till_retry = maxtimeout;
1073
1074       syslog(LOG_ERR, _("Failed to setup all outgoing connections, will retry in %d seconds"),
1075         seconds_till_retry);
1076   
1077       /* Randomize timeout to avoid global synchronisation effects */
1078       randomized_alarm(seconds_till_retry);
1079     }
1080   else
1081     {
1082       seconds_till_retry = 5;
1083     }
1084 cp
1085 }
1086
1087 /*
1088   check all connections to see if anything
1089   happened on their sockets
1090 */
1091 void check_network_activity(fd_set *f)
1092 {
1093   connection_t *c;
1094   avl_node_t *node;
1095 cp
1096   if(FD_ISSET(udp_socket, f))
1097     handle_incoming_vpn_data();
1098
1099   for(node = connection_tree->head; node; node = node->next)
1100     {
1101       c = (connection_t *)node->data;
1102
1103       if(c->status.remove)
1104         return;
1105
1106       if(FD_ISSET(c->socket, f))
1107         if(receive_meta(c) < 0)
1108           {
1109             terminate_connection(c, c->status.active);
1110             return;
1111           }
1112     }
1113
1114   if(FD_ISSET(tcp_socket, f))
1115     handle_new_meta_connection();
1116 cp
1117 }
1118
1119 /*
1120   this is where it all happens...
1121 */
1122 void main_loop(void)
1123 {
1124   fd_set fset;
1125   struct timeval tv;
1126   int r;
1127   time_t last_ping_check;
1128   int t;
1129   vpn_packet_t packet;
1130 cp
1131   last_ping_check = time(NULL);
1132
1133   for(;;)
1134     {
1135       tv.tv_sec = timeout;
1136       tv.tv_usec = 0;
1137
1138       build_fdset(&fset);
1139
1140       if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1141         {
1142           if(errno != EINTR) /* because of alarm */
1143             {
1144               syslog(LOG_ERR, _("Error while waiting for input: %m"));
1145               return;
1146             }
1147         }
1148
1149       if(sighup)
1150         {
1151           syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1152           sighup = 0;
1153           close_network_connections();
1154           exit_configuration(&config_tree);
1155
1156           if(read_server_config())
1157             {
1158               syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1159               exit(1);
1160             }
1161
1162           sleep(5);
1163
1164           if(setup_network_connections())
1165             return;
1166
1167           continue;
1168         }
1169
1170       t = time(NULL);
1171
1172       /* Let's check if everybody is still alive */
1173
1174       if(last_ping_check + timeout < t)
1175         {
1176           check_dead_connections();
1177           last_ping_check = time(NULL);
1178
1179           /* Should we regenerate our key? */
1180
1181           if(keyexpires < t)
1182             {
1183               if(debug_lvl >= DEBUG_STATUS)
1184                 syslog(LOG_INFO, _("Regenerating symmetric key"));
1185
1186               RAND_pseudo_bytes(myself->key, myself->keylength);
1187               send_key_changed(myself->connection, myself);
1188               keyexpires = time(NULL) + keylifetime;
1189             }
1190         }
1191
1192       if(r > 0)
1193         {
1194           check_network_activity(&fset);
1195
1196           /* local tap data */
1197           if(FD_ISSET(device_fd, &fset))
1198             {
1199               if(read_packet(&packet))
1200                 route_outgoing(&packet);
1201               else
1202                 return;
1203             }
1204         }
1205     }
1206 cp
1207 }