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