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