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