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