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