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