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