Correctly use the active_tree.
[tinc] / src / protocol.c
1 /*
2     protocol.c -- handle the meta-protocol
3     Copyright (C) 1999-2001 Ivo Timmermans <itimmermans@bigfoot.com>,
4                   2000,2001 Guus Sliepen <guus@sliepen.warande.net>
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20     $Id: protocol.c,v 1.28.4.100 2001/07/19 12:29:40 guus Exp $
21 */
22
23 #include "config.h"
24
25 #include <sys/types.h>
26
27 #include <stdlib.h>
28 #include <string.h>
29 #include <syslog.h>
30 #include <sys/socket.h>
31 #include <unistd.h>
32 #include <stdio.h>
33 #include <stdarg.h>
34 #include <errno.h>
35
36 #include <utils.h>
37 #include <xalloc.h>
38 #include <avl_tree.h>
39 #include <list.h>
40
41 #include <netinet/in.h>
42
43 #include <openssl/sha.h>
44 #include <openssl/rand.h>
45 #include <openssl/evp.h>
46
47 #ifndef HAVE_RAND_PSEUDO_BYTES
48 #define RAND_pseudo_bytes RAND_bytes
49 #endif
50
51 #include "conf.h"
52 #include "net.h"
53 #include "netutl.h"
54 #include "protocol.h"
55 #include "meta.h"
56 #include "connection.h"
57
58 #include "system.h"
59
60 int mykeyused = 0;
61
62 int check_id(char *id)
63 {
64   int i;
65
66   for (i = 0; i < strlen(id); i++)
67     if(!isalnum(id[i]) && id[i] != '_')
68       return -1;
69   
70   return 0;
71 }
72
73 /* Generic request routines - takes care of logging and error
74    detection as well */
75
76 int send_request(connection_t *cl, const char *format, ...)
77 {
78   va_list args;
79   char buffer[MAXBUFSIZE];
80   int len, request;
81
82 cp
83   /* Use vsnprintf instead of vasprintf: faster, no memory
84      fragmentation, cleanup is automatic, and there is a limit on the
85      input buffer anyway */
86
87   va_start(args, format);
88   len = vsnprintf(buffer, MAXBUFSIZE, format, args);
89   request = va_arg(args, int);
90   va_end(args);
91
92   if(len < 0 || len > MAXBUFSIZE-1)
93     {
94       syslog(LOG_ERR, _("Output buffer overflow while sending %s to %s (%s)"), request_name[request], cl->name, cl->hostname);
95       return -1;
96     }
97
98   if(debug_lvl >= DEBUG_PROTOCOL)
99     {
100       if(debug_lvl >= DEBUG_META)
101         syslog(LOG_DEBUG, _("Sending %s to %s (%s): %s"), request_name[request], cl->name, cl->hostname, buffer);
102       else
103         syslog(LOG_DEBUG, _("Sending %s to %s (%s)"), request_name[request], cl->name, cl->hostname);
104     }
105
106   buffer[len++] = '\n';
107 cp
108   return send_meta(cl, buffer, len);
109 }
110
111 int receive_request(connection_t *cl)
112 {
113   int request;
114 cp
115   if(sscanf(cl->buffer, "%d", &request) == 1)
116     {
117       if((request < 0) || (request >= LAST) || (request_handlers[request] == NULL))
118         {
119           if(debug_lvl >= DEBUG_META)
120             syslog(LOG_DEBUG, _("Unknown request from %s (%s): %s"),
121                    cl->name, cl->hostname, cl->buffer);
122           else
123             syslog(LOG_ERR, _("Unknown request from %s (%s)"),
124                    cl->name, cl->hostname);
125                    
126           return -1;
127         }
128       else
129         {
130           if(debug_lvl >= DEBUG_PROTOCOL)
131             {
132               if(debug_lvl >= DEBUG_META)
133                 syslog(LOG_DEBUG, _("Got %s from %s (%s): %s"),
134                        request_name[request], cl->name, cl->hostname, cl->buffer);
135               else
136                 syslog(LOG_DEBUG, _("Got %s from %s (%s)"),
137                        request_name[request], cl->name, cl->hostname);
138             }
139         }
140
141       if((cl->allow_request != ALL) && (cl->allow_request != request))
142         {
143           syslog(LOG_ERR, _("Unauthorized request from %s (%s)"), cl->name, cl->hostname);
144           return -1;
145         }
146
147       if(request_handlers[request](cl))
148         /* Something went wrong. Probably scriptkiddies. Terminate. */
149         {
150           syslog(LOG_ERR, _("Error while processing %s from %s (%s)"),
151                  request_name[request], cl->name, cl->hostname);
152           return -1;
153         }
154     }
155   else
156     {
157       syslog(LOG_ERR, _("Bogus data received from %s (%s)"),
158              cl->name, cl->hostname);
159       return -1;
160     }
161 cp
162   return 0;
163 }
164
165 /* The authentication protocol is described in detail in doc/SECURITY2,
166    the rest will be described in doc/PROTOCOL. */
167
168 int send_id(connection_t *cl)
169 {
170 cp
171   return send_request(cl, "%d %s %d %lx %hd", ID, myself->name, myself->protocol_version, myself->options, myself->port);
172 }
173
174 int id_h(connection_t *cl)
175 {
176   char name[MAX_STRING_SIZE];
177 cp
178   if(sscanf(cl->buffer, "%*d "MAX_STRING" %d %lx %hd", name, &cl->protocol_version, &cl->options, &cl->port) != 4)
179     {
180        syslog(LOG_ERR, _("Got bad ID from %s"), cl->hostname);
181        return -1;
182     }
183
184   /* Check if version matches */
185
186   if(cl->protocol_version != myself->protocol_version)
187     {
188       syslog(LOG_ERR, _("Peer %s (%s) uses incompatible version %d"),
189              cl->name, cl->hostname, cl->protocol_version);
190       return -1;
191     }
192
193   /* Check if identity is a valid name */
194
195   if(check_id(name))
196     {
197       syslog(LOG_ERR, _("Peer %s uses invalid identity name"), cl->hostname);
198       return -1;
199     }
200   
201   /* Copy string to cl */
202   
203   if(cl->name)
204     free(cl->name);
205     
206   cl->name = xstrdup(name);
207
208   /* Load information about peer */
209
210   if(read_host_config(cl))
211     {
212       syslog(LOG_ERR, _("Peer %s had unknown identity (%s)"), cl->hostname, cl->name);
213       return -1;
214     }
215
216   /* Read in the public key, so that we can send a metakey */
217
218   if(read_rsa_public_key(cl))
219     return -1;
220
221   cl->allow_request = METAKEY;
222 cp
223   return send_metakey(cl);
224 }
225
226 int ack_h(connection_t *cl)
227 {
228   config_t const *cfg;
229   connection_t *old, *p;
230   subnet_t *subnet;
231   avl_node_t *node, *node2;
232 cp
233   /* Okay, before we active the connection, we check if there is another entry
234      in the connection list with the same name. If so, it presumably is an
235      old connection that has timed out but we don't know it yet.
236    */
237
238   if((old = lookup_id(cl->name)))
239     {
240       if(debug_lvl >= DEBUG_CONNECTIONS)
241         syslog(LOG_NOTICE, _("Removing old connection for %s at %s in favour of new connection from %s"),
242                cl->name, old->hostname, cl->hostname);
243       if(old->status.outgoing)
244         {
245           cl->status.outgoing = 1;
246           old->status.outgoing = 0;
247         }
248       terminate_connection(old);
249       return 0;
250     }
251     
252   /* Now we can add the name to the id tree */
253   
254   id_add(cl);
255
256   /* Also check if no other tinc daemon uses the same IP and port for UDP traffic */
257   
258   old = avl_search(active_tree, cl);
259   if(old)
260   {
261     syslog(LOG_ERR, _("%s is listening on %s:%hd, which is already in use by %s!"),
262            cl->name, cl->hostname, cl->port, old->name);
263     return -1;
264   }
265     
266   /* Activate this connection */
267
268   cl->allow_request = ALL;
269   cl->status.active = 1;
270   cl->nexthop = cl;
271   cl->cipher_pkttype = EVP_bf_cbc();
272   cl->cipher_pktkeylength = cl->cipher_pkttype->key_len + cl->cipher_pkttype->iv_len;
273
274   active_add(cl);
275
276   if(debug_lvl >= DEBUG_CONNECTIONS)
277     syslog(LOG_NOTICE, _("Connection with %s (%s) activated"), cl->name, cl->hostname);
278
279   if(cl->status.outgoing)
280     seconds_till_retry = 5;     /* Reset retry timeout */
281 cp
282   /* Check some options */
283   
284   if((cfg = get_config_val(cl->config, config_indirectdata)))
285     {
286       if(cfg->data.val == stupid_true)
287         cl->options |= OPTION_INDIRECT;
288     }
289
290   if((cfg = get_config_val(cl->config, config_tcponly)))
291     {
292       if(cfg->data.val == stupid_true)
293         cl->options |= OPTION_TCPONLY;
294     }
295
296   /* Send him our subnets */
297   
298   for(node = myself->subnet_tree->head; node; node = node->next)
299     {
300       subnet = (subnet_t *)node->data;
301       send_add_subnet(cl, subnet);
302     }
303
304   /* And send him all the hosts and their subnets we know... */
305   
306   for(node = active_tree->head; node; node = node->next)
307     {
308       p = (connection_t *)node->data;
309       
310       if(p != cl && p->status.active)
311         {
312           /* Notify others of this connection */
313
314           if(p->status.meta)
315             send_add_host(p, cl);
316
317           /* Notify new connection of everything we know */
318
319           send_add_host(cl, p);
320
321           for(node2 = p->subnet_tree->head; node2; node2 = node2->next)
322             {
323               subnet = (subnet_t *)node2->data;
324               send_add_subnet(cl, subnet);
325             }
326         }
327     }
328 cp
329   return 0;
330 }
331
332 int send_challenge(connection_t *cl)
333 {
334   char *buffer;
335   int len, x;
336 cp
337   /* CHECKME: what is most reasonable value for len? */
338
339   len = RSA_size(cl->rsa_key);
340
341   /* Allocate buffers for the challenge */
342
343   buffer = xmalloc(len*2+1);
344
345   if(cl->hischallenge)
346     free(cl->hischallenge);
347     
348   cl->hischallenge = xmalloc(len);
349 cp
350   /* Copy random data to the buffer */
351
352   RAND_bytes(cl->hischallenge, len);
353
354 cp
355   /* Convert to hex */
356
357   bin2hex(cl->hischallenge, buffer, len);
358   buffer[len*2] = '\0';
359
360 cp
361   /* Send the challenge */
362
363   x = send_request(cl, "%d %s", CHALLENGE, buffer);
364   free(buffer);
365 cp
366   return x;
367 }
368
369 int challenge_h(connection_t *cl)
370 {
371   char buffer[MAX_STRING_SIZE];
372   int len;
373 cp
374   if(sscanf(cl->buffer, "%*d "MAX_STRING, buffer) != 1)
375     {
376        syslog(LOG_ERR, _("Got bad CHALLENGE from %s (%s)"), cl->name, cl->hostname);
377        return -1;
378     }
379
380   len = RSA_size(myself->rsa_key);
381
382   /* Check if the length of the challenge is all right */
383
384   if(strlen(buffer) != len*2)
385     {
386       syslog(LOG_ERR, _("Intruder: wrong challenge length from %s (%s)"), cl->name, cl->hostname);
387       return -1;
388     }
389
390   /* Allocate buffers for the challenge */
391
392   if(!cl->mychallenge)
393     cl->mychallenge = xmalloc(len);
394
395   /* Convert the challenge from hexadecimal back to binary */
396
397   hex2bin(buffer,cl->mychallenge,len);
398
399   cl->allow_request = CHAL_REPLY;
400
401   /* Rest is done by send_chal_reply() */
402 cp
403   return send_chal_reply(cl);
404 }
405
406 int send_chal_reply(connection_t *cl)
407 {
408   char hash[SHA_DIGEST_LENGTH*2+1];
409 cp
410   if(!cl->mychallenge)
411     {
412       syslog(LOG_ERR, _("Trying to send CHAL_REPLY to %s (%s) without a valid CHALLENGE"), cl->name, cl->hostname);
413       return -1;
414     }
415      
416   /* Calculate the hash from the challenge we received */
417
418   SHA1(cl->mychallenge, RSA_size(myself->rsa_key), hash);
419
420   /* Convert the hash to a hexadecimal formatted string */
421
422   bin2hex(hash,hash,SHA_DIGEST_LENGTH);
423   hash[SHA_DIGEST_LENGTH*2] = '\0';
424
425   /* Send the reply */
426
427 cp
428   return send_request(cl, "%d %s", CHAL_REPLY, hash);
429 }
430
431 int chal_reply_h(connection_t *cl)
432 {
433   char hishash[MAX_STRING_SIZE];
434   char myhash[SHA_DIGEST_LENGTH];
435 cp
436   if(sscanf(cl->buffer, "%*d "MAX_STRING, hishash) != 1)
437     {
438        syslog(LOG_ERR, _("Got bad CHAL_REPLY from %s (%s)"), cl->name, cl->hostname);
439        return -1;
440     }
441
442   /* Check if the length of the hash is all right */
443
444   if(strlen(hishash) != SHA_DIGEST_LENGTH*2)
445     {
446       syslog(LOG_ERR, _("Intruder: wrong challenge reply length from %s (%s)"), cl->name, cl->hostname);
447       return -1;
448     }
449
450   /* Convert the hash to binary format */
451
452   hex2bin(hishash, hishash, SHA_DIGEST_LENGTH);
453
454   /* Calculate the hash from the challenge we sent */
455
456   SHA1(cl->hischallenge, RSA_size(cl->rsa_key), myhash);
457
458   /* Verify the incoming hash with the calculated hash */
459
460   if(memcmp(hishash, myhash, SHA_DIGEST_LENGTH))
461     {
462       syslog(LOG_ERR, _("Intruder: wrong challenge reply from %s (%s)"), cl->name, cl->hostname);
463       if(debug_lvl >= DEBUG_SCARY_THINGS)
464         {
465           bin2hex(myhash, hishash, SHA_DIGEST_LENGTH);
466           hishash[SHA_DIGEST_LENGTH*2] = '\0';
467           syslog(LOG_DEBUG, _("Expected challenge reply: %s"), hishash);
468         }
469       return -1;
470     }
471
472   /* Identity has now been positively verified.
473      ack_h() handles the rest from now on.
474    */
475 cp
476   return ack_h(cl);
477 }
478
479 int send_metakey(connection_t *cl)
480 {
481   char *buffer;
482   int len, x;
483 cp
484   len = RSA_size(cl->rsa_key);
485
486   /* Allocate buffers for the meta key */
487
488   buffer = xmalloc(len*2+1);
489
490   if(!cl->cipher_outkey)
491     cl->cipher_outkey = xmalloc(len);
492     
493   if(!cl->cipher_outctx)
494     cl->cipher_outctx = xmalloc(sizeof(*cl->cipher_outctx));
495 cp
496   /* Copy random data to the buffer */
497
498   RAND_bytes(cl->cipher_outkey, len);
499
500   /* The message we send must be smaller than the modulus of the RSA key.
501      By definition, for a key of k bits, the following formula holds:
502      
503        2^(k-1) <= modulus < 2^(k)
504      
505      Where ^ means "to the power of", not "xor".
506      This means that to be sure, we must choose our message < 2^(k-1).
507      This can be done by setting the most significant bit to zero.
508   */
509   
510   cl->cipher_outkey[0] &= 0x7F;
511   
512   if(debug_lvl >= DEBUG_SCARY_THINGS)
513     {
514       bin2hex(cl->cipher_outkey, buffer, len);
515       buffer[len*2] = '\0';
516       syslog(LOG_DEBUG, _("Generated random meta key (unencrypted): %s"), buffer);
517     }
518
519   /* Encrypt the random data
520   
521      We do not use one of the PKCS padding schemes here.
522      This is allowed, because we encrypt a totally random string
523      with a length equal to that of the modulus of the RSA key.
524   */
525   
526   if(RSA_public_encrypt(len, cl->cipher_outkey, buffer, cl->rsa_key, RSA_NO_PADDING) != len)
527     {
528       syslog(LOG_ERR, _("Error during encryption of meta key for %s (%s)"), cl->name, cl->hostname);
529       free(buffer);
530       return -1;
531     }
532 cp
533   /* Convert the encrypted random data to a hexadecimal formatted string */
534
535   bin2hex(buffer, buffer, len);
536   buffer[len*2] = '\0';
537
538   /* Send the meta key */
539
540   x = send_request(cl, "%d %s", METAKEY, buffer);
541   free(buffer);
542
543   /* Further outgoing requests are encrypted with the key we just generated */
544
545   EVP_EncryptInit(cl->cipher_outctx, EVP_bf_cfb(),
546                   cl->cipher_outkey + len - EVP_bf_cfb()->key_len,
547                   cl->cipher_outkey + len - EVP_bf_cfb()->key_len - EVP_bf_cfb()->iv_len);
548
549   cl->status.encryptout = 1;
550 cp
551   return x;
552 }
553
554 int metakey_h(connection_t *cl)
555 {
556   char buffer[MAX_STRING_SIZE];
557   int len;
558 cp
559   if(sscanf(cl->buffer, "%*d "MAX_STRING, buffer) != 1)
560     {
561        syslog(LOG_ERR, _("Got bad METAKEY from %s (%s)"), cl->name, cl->hostname);
562        return -1;
563     }
564
565   len = RSA_size(myself->rsa_key);
566
567   /* Check if the length of the meta key is all right */
568
569   if(strlen(buffer) != len*2)
570     {
571       syslog(LOG_ERR, _("Intruder: wrong meta key length from %s (%s)"), cl->name, cl->hostname);
572       return -1;
573     }
574
575   /* Allocate buffers for the meta key */
576
577   if(!cl->cipher_inkey)
578     cl->cipher_inkey = xmalloc(len);
579
580   if(!cl->cipher_inctx)
581     cl->cipher_inctx = xmalloc(sizeof(*cl->cipher_inctx));
582
583   /* Convert the challenge from hexadecimal back to binary */
584
585   hex2bin(buffer,buffer,len);
586
587   /* Decrypt the meta key */
588   
589   if(RSA_private_decrypt(len, buffer, cl->cipher_inkey, myself->rsa_key, RSA_NO_PADDING) != len)        /* See challenge() */
590     {
591       syslog(LOG_ERR, _("Error during encryption of meta key for %s (%s)"), cl->name, cl->hostname);
592       return -1;
593     }
594
595   if(debug_lvl >= DEBUG_SCARY_THINGS)
596     {
597       bin2hex(cl->cipher_inkey, buffer, len);
598       buffer[len*2] = '\0';
599       syslog(LOG_DEBUG, _("Received random meta key (unencrypted): %s"), buffer);
600     }
601
602   /* All incoming requests will now be encrypted. */
603
604   EVP_DecryptInit(cl->cipher_inctx, EVP_bf_cfb(),
605                   cl->cipher_inkey + len - EVP_bf_cfb()->key_len,
606                   cl->cipher_inkey + len - EVP_bf_cfb()->key_len - EVP_bf_cfb()->iv_len);
607   
608   cl->status.decryptin = 1;
609
610   cl->allow_request = CHALLENGE;
611 cp
612   return send_challenge(cl);
613 }
614
615 /* Address and subnet information exchange */
616
617 int send_add_subnet(connection_t *cl, subnet_t *subnet)
618 {
619   int x;
620   char *netstr;
621   char *owner;
622 cp
623   if((cl->options | myself->options | subnet->owner->options) & OPTION_INDIRECT)
624     owner = myself->name;
625   else
626     owner = subnet->owner->name;
627
628   x = send_request(cl, "%d %s %s", ADD_SUBNET,
629                       owner, netstr = net2str(subnet));
630   free(netstr);
631 cp
632   return x;
633 }
634
635 int add_subnet_h(connection_t *cl)
636 {
637   char subnetstr[MAX_STRING_SIZE];
638   char name[MAX_STRING_SIZE];
639   connection_t *owner, *p;
640   subnet_t *subnet;
641   avl_node_t *node;
642 cp
643   if(sscanf(cl->buffer, "%*d "MAX_STRING" "MAX_STRING, name, subnetstr) != 2)
644     {
645       syslog(LOG_ERR, _("Got bad ADD_SUBNET from %s (%s)"), cl->name, cl->hostname);
646       return -1;
647     }
648
649   /* Check if owner name is a valid */
650
651   if(check_id(name))
652     {
653       syslog(LOG_ERR, _("Got bad ADD_SUBNET from %s (%s): invalid identity name"), cl->name, cl->hostname);
654       return -1;
655     }
656
657   /* Check if subnet string is valid */
658
659   if(!(subnet = str2net(subnetstr)))
660     {
661       syslog(LOG_ERR, _("Got bad ADD_SUBNET from %s (%s): invalid subnet string"), cl->name, cl->hostname);
662       return -1;
663     }
664
665   /* Check if somebody tries to add a subnet of ourself */
666
667   if(!strcmp(name, myself->name))
668     {
669       syslog(LOG_ERR, _("Warning: got ADD_SUBNET from %s (%s) for ourself, restarting"),
670              cl->name, cl->hostname);
671       sighup = 1;
672       return 0;
673     }
674
675   /* Check if the owner of the new subnet is in the connection list */
676
677   if(!(owner = lookup_id(name)))
678     {
679       syslog(LOG_ERR, _("Got ADD_SUBNET for %s from %s (%s) which is not in our connection list"),
680              name, cl->name, cl->hostname);
681       return -1;
682     }
683
684   /* If everything is correct, add the subnet to the list of the owner */
685
686   subnet_add(owner, subnet);
687
688   /* Tell the rest */
689   
690   for(node = connection_tree->head; node; node = node->next)
691     {
692       p = (connection_t *)node->data;
693       if(p->status.meta && p->status.active && p!= cl)
694         send_add_subnet(p, subnet);
695     }
696 cp
697   return 0;
698 }
699
700 int send_del_subnet(connection_t *cl, subnet_t *subnet)
701 {
702   int x;
703   char *netstr;
704   char *owner;
705 cp
706   if(cl->options & OPTION_INDIRECT)
707     owner = myself->name;
708   else
709     owner = subnet->owner->name;
710
711   x = send_request(cl, "%d %s %s", DEL_SUBNET, owner, netstr = net2str(subnet));
712   free(netstr);
713 cp
714   return x;
715 }
716
717 int del_subnet_h(connection_t *cl)
718 {
719   char subnetstr[MAX_STRING_SIZE];
720   char name[MAX_STRING_SIZE];
721   connection_t *owner, *p;
722   subnet_t *subnet;
723   avl_node_t *node;
724 cp
725   if(sscanf(cl->buffer, "%*d "MAX_STRING" "MAX_STRING, name, subnetstr) != 3)
726     {
727       syslog(LOG_ERR, _("Got bad DEL_SUBNET from %s (%s)"), cl->name, cl->hostname);
728       return -1;
729     }
730
731   /* Check if owner name is a valid */
732
733   if(check_id(name))
734     {
735       syslog(LOG_ERR, _("Got bad DEL_SUBNET from %s (%s): invalid identity name"), cl->name, cl->hostname);
736       return -1;
737     }
738
739   /* Check if subnet string is valid */
740
741   if(!(subnet = str2net(subnetstr)))
742     {
743       syslog(LOG_ERR, _("Got bad DEL_SUBNET from %s (%s): invalid subnet string"), cl->name, cl->hostname);
744       return -1;
745     }
746
747   free(subnetstr);
748   
749   /* Check if somebody tries to add a subnet of ourself */
750
751   if(!strcmp(name, myself->name))
752     {
753       syslog(LOG_ERR, _("Warning: got DEL_SUBNET from %s (%s) for ourself, restarting"),
754              cl->name, cl->hostname);
755       sighup = 1;
756       return 0;
757     }
758
759   /* Check if the owner of the new subnet is in the connection list */
760
761   if(!(owner = lookup_id(name)))
762     {
763       syslog(LOG_ERR, _("Got DEL_SUBNET for %s from %s (%s) which is not in our connection list"),
764              name, cl->name, cl->hostname);
765       return -1;
766     }
767
768   /* If everything is correct, delete the subnet from the list of the owner */
769
770   subnet_del(subnet);
771
772   /* Tell the rest */
773   
774   for(node = connection_tree->head; node; node = node->next)
775     {
776       p = (connection_t *)node->data;
777       if(p->status.meta && p->status.active && p!= cl)
778         send_del_subnet(p, subnet);
779     }
780 cp
781   return 0;
782 }
783
784 /* New and closed connections notification */
785
786 int send_add_host(connection_t *cl, connection_t *other)
787 {
788 cp
789   if(!((cl->options | myself->options | other->options) & OPTION_INDIRECT))
790     return send_request(cl, "%d %s %lx:%d %lx", ADD_HOST,
791                       other->name, other->address, other->port, other->options);
792   else
793     return 0;
794 }
795
796 int add_host_h(connection_t *cl)
797 {
798   connection_t *old, *new, *p;
799   char name[MAX_STRING_SIZE];
800   avl_node_t *node;
801 cp
802   new = new_connection();
803
804   if(sscanf(cl->buffer, "%*d "MAX_STRING" %lx:%hd %lx", name, &new->address, &new->port, &new->options) != 4)
805     {
806        syslog(LOG_ERR, _("Got bad ADD_HOST from %s (%s)"), cl->name, cl->hostname);
807        return -1;
808     }
809
810   /* Check if identity is a valid name */
811
812   if(check_id(name))
813     {
814       syslog(LOG_ERR, _("Got bad ADD_HOST from %s (%s): invalid identity name"), cl->name, cl->hostname);
815       free_connection(new);
816       return -1;
817     }
818
819   /* Check if somebody tries to add ourself */
820
821   if(!strcmp(name, myself->name))
822     {
823       syslog(LOG_ERR, _("Warning: got ADD_HOST from %s (%s) for ourself, restarting"), cl->name, cl->hostname);
824       sighup = 1;
825       free_connection(new);
826       return 0;
827     }
828     
829   /* Fill in more of the new connection structure */
830
831   new->hostname = hostlookup(htonl(new->address));
832
833   /* Check if the new host already exists in the connnection list */
834
835   if((old = lookup_id(name)))
836     {
837       if((new->address == old->address) && (new->port == old->port))
838         {
839           if(debug_lvl >= DEBUG_CONNECTIONS)
840             syslog(LOG_NOTICE, _("Got duplicate ADD_HOST for %s (%s) from %s (%s)"),
841                    old->name, old->hostname, cl->name, cl->hostname);
842           free_connection(new);
843           return 0;
844         }
845       else
846         {
847           if(debug_lvl >= DEBUG_CONNECTIONS)
848             syslog(LOG_NOTICE, _("Removing old entry for %s (%s) in favour of new connection"),
849                    old->name, old->hostname);
850
851           terminate_connection(old);
852         }
853     }
854
855   /* Hook it up into the active tree */
856
857   new->name = xstrdup(name);
858   active_add(new);
859   id_add(new);
860
861   /* Tell the rest about the new host */
862
863   for(node = connection_tree->head; node; node = node->next)
864     {
865       p = (connection_t *)node->data;
866       if(p->status.meta && p->status.active && p!=cl)
867         send_add_host(p, new);
868     }
869
870   /* Fill in rest of connection structure */
871
872   new->nexthop = cl;
873   new->status.active = 1;
874   new->cipher_pkttype = EVP_bf_cbc();
875   new->cipher_pktkeylength = cl->cipher_pkttype->key_len + cl->cipher_pkttype->iv_len;
876 cp
877   return 0;
878 }
879
880 int send_del_host(connection_t *cl, connection_t *other)
881 {
882 cp
883   if(!((cl->options | myself->options) & OPTION_INDIRECT))
884     return send_request(cl, "%d %s %lx:%d %lx", DEL_HOST,
885                       other->name, other->address, other->port, other->options);
886   else
887     return 0;
888 }
889
890 int del_host_h(connection_t *cl)
891 {
892   char name[MAX_STRING_SIZE];
893   ipv4_t address;
894   port_t port;
895   long int options;
896   connection_t *old, *p;
897   avl_node_t *node;
898 cp
899   if(sscanf(cl->buffer, "%*d "MAX_STRING" %lx:%hd %lx", name, &address, &port, &options) != 4)
900     {
901       syslog(LOG_ERR, _("Got bad DEL_HOST from %s (%s)"),
902              cl->name, cl->hostname);
903       return -1;
904     }
905
906   /* Check if identity is a valid name */
907
908   if(check_id(name))
909     {
910       syslog(LOG_ERR, _("Got bad DEL_HOST from %s (%s): invalid identity name"), cl->name, cl->hostname);
911       return -1;
912     }
913
914   /* Check if somebody tries to delete ourself */
915
916   if(!strcmp(name, myself->name))
917     {
918       syslog(LOG_ERR, _("Warning: got DEL_HOST from %s (%s) for ourself, restarting"),
919              cl->name, cl->hostname);
920       sighup = 1;
921       return 0;
922     }
923
924   /* Check if the new host already exists in the connnection list */
925
926   if(!(old = lookup_id(name)))
927     {
928       syslog(LOG_ERR, _("Got DEL_HOST from %s (%s) for %s which is not in our connection list"),
929              cl->name, cl->hostname, name);
930       return -1;
931     }
932   
933   /* Check if the rest matches */
934   
935   if(address!=old->address || port!=old->port || options!=old->options || cl!=old->nexthop)
936     {
937       syslog(LOG_WARNING, _("Got DEL_HOST from %s (%s) for %s which doesn't match"), cl->name, cl->hostname, old->name);
938       return 0;
939     }
940
941   /* Ok, since EVERYTHING seems to check out all right, delete it */
942
943   old->status.active = 0;
944   terminate_connection(old);
945
946   /* Tell the rest about the new host */
947
948   for(node = connection_tree->head; node; node = node->next)
949     {
950       p = (connection_t *)node->data;
951       if(p->status.meta && p->status.active && p!=cl)
952         send_del_host(p, old);
953     }
954 cp
955   return 0;
956 }
957
958 /* Status and error notification routines */
959
960 int send_status(connection_t *cl, int statusno, char *statusstring)
961 {
962 cp
963   if(!statusstring)
964     statusstring = status_text[statusno];
965 cp
966   return send_request(cl, "%d %d %s", STATUS, statusno, statusstring);
967 }
968
969 int status_h(connection_t *cl)
970 {
971   int statusno;
972   char statusstring[MAX_STRING_SIZE];
973 cp
974   if(sscanf(cl->buffer, "%*d %d "MAX_STRING, &statusno, statusstring) != 2)
975     {
976        syslog(LOG_ERR, _("Got bad STATUS from %s (%s)"),
977               cl->name, cl->hostname);
978        return -1;
979     }
980
981   if(debug_lvl >= DEBUG_STATUS)
982     {
983       syslog(LOG_NOTICE, _("Status message from %s (%s): %s: %s"),
984              cl->name, cl->hostname, status_text[statusno], statusstring);
985     }
986
987 cp
988   return 0;
989 }
990
991 int send_error(connection_t *cl, int err, char *errstring)
992 {
993 cp
994   if(!errstring)
995     errstring = strerror(err);
996   return send_request(cl, "%d %d %s", ERROR, err, errstring);
997 }
998
999 int error_h(connection_t *cl)
1000 {
1001   int err;
1002   char errorstring[MAX_STRING_SIZE];
1003 cp
1004   if(sscanf(cl->buffer, "%*d %d "MAX_STRING, &err, errorstring) != 2)
1005     {
1006        syslog(LOG_ERR, _("Got bad ERROR from %s (%s)"),
1007               cl->name, cl->hostname);
1008        return -1;
1009     }
1010
1011   if(debug_lvl >= DEBUG_ERROR)
1012     {
1013       syslog(LOG_NOTICE, _("Error message from %s (%s): %s: %s"),
1014              cl->name, cl->hostname, strerror(err), errorstring);
1015     }
1016
1017   terminate_connection(cl);
1018 cp
1019   return 0;
1020 }
1021
1022 int send_termreq(connection_t *cl)
1023 {
1024 cp
1025   return send_request(cl, "%d", TERMREQ);
1026 }
1027
1028 int termreq_h(connection_t *cl)
1029 {
1030 cp
1031   terminate_connection(cl);
1032 cp
1033   return 0;
1034 }
1035
1036 int send_ping(connection_t *cl)
1037 {
1038   char salt[SALTLEN*2+1];
1039 cp
1040   cl->status.pinged = 1;
1041   cl->last_ping_time = time(NULL);
1042   RAND_pseudo_bytes(salt, SALTLEN);
1043   bin2hex(salt, salt, SALTLEN);
1044   salt[SALTLEN*2] = '\0';
1045 cp
1046   return send_request(cl, "%d %s", PING, salt);
1047 }
1048
1049 int ping_h(connection_t *cl)
1050 {
1051 cp
1052   return send_pong(cl);
1053 }
1054
1055 int send_pong(connection_t *cl)
1056 {
1057   char salt[SALTLEN*2+1];
1058 cp
1059   RAND_pseudo_bytes(salt, SALTLEN);
1060   bin2hex(salt, salt, SALTLEN);
1061   salt[SALTLEN*2] = '\0';
1062 cp
1063   return send_request(cl, "%d %s", PONG, salt);
1064 }
1065
1066 int pong_h(connection_t *cl)
1067 {
1068 cp
1069   cl->status.pinged = 0;
1070 cp
1071   return 0;
1072 }
1073
1074 /* Key exchange */
1075
1076 int send_key_changed(connection_t *from, connection_t *cl)
1077 {
1078   connection_t *p;
1079   avl_node_t *node;
1080 cp
1081   /* Only send this message if some other daemon requested our key previously.
1082      This reduces unnecessary key_changed broadcasts.
1083   */
1084
1085   if(from==myself && !mykeyused)
1086     return 0;
1087
1088   for(node = connection_tree->head; node; node = node->next)
1089     {
1090       p = (connection_t *)node->data;
1091       if(p != cl && p->status.meta && p->status.active)
1092         if(!(p->options & OPTION_INDIRECT) || from == myself)
1093           send_request(p, "%d %s", KEY_CHANGED, from->name);
1094     }
1095 cp
1096   return 0;
1097 }
1098
1099 int key_changed_h(connection_t *cl)
1100 {
1101   char from_id[MAX_STRING_SIZE];
1102   connection_t *from;
1103 cp
1104   if(sscanf(cl->buffer, "%*d "MAX_STRING, from_id) != 1)
1105     {
1106       syslog(LOG_ERR, _("Got bad KEY_CHANGED from %s (%s)"),
1107              cl->name, cl->hostname);
1108       return -1;
1109     }
1110
1111   if(!(from = lookup_id(from_id)))
1112     {
1113       syslog(LOG_ERR, _("Got KEY_CHANGED from %s (%s) origin %s which does not exist in our connection list"),
1114              cl->name, cl->hostname, from_id);
1115       return -1;
1116     }
1117
1118   from->status.validkey = 0;
1119   from->status.waitingforkey = 0;
1120
1121   if(!(from->options | cl->options | myself->options) & OPTION_INDIRECT)
1122     send_key_changed(from, cl);
1123 cp
1124   return 0;
1125 }
1126
1127 int send_req_key(connection_t *from, connection_t *to)
1128 {
1129 cp
1130   return send_request(to->nexthop, "%d %s %s", REQ_KEY,
1131                       from->name, to->name);
1132 }
1133
1134 int req_key_h(connection_t *cl)
1135 {
1136   char from_id[MAX_STRING_SIZE];
1137   char to_id[MAX_STRING_SIZE];
1138   connection_t *from, *to;
1139   char pktkey[129];
1140 cp
1141   if(sscanf(cl->buffer, "%*d "MAX_STRING" "MAX_STRING, from_id, to_id) != 2)
1142     {
1143        syslog(LOG_ERR, _("Got bad REQ_KEY from %s (%s)"),
1144               cl->name, cl->hostname);
1145        return -1;
1146     }
1147
1148   if(!(from = lookup_id(from_id)))
1149     {
1150       syslog(LOG_ERR, _("Got REQ_KEY from %s (%s) origin %s which does not exist in our connection list"),
1151              cl->name, cl->hostname, from_id);
1152       return -1;
1153     }
1154
1155   /* Check if this key request is for us */
1156
1157   if(!strcmp(to_id, myself->name))      /* Yes, send our own key back */
1158     {
1159       bin2hex(myself->cipher_pktkey, pktkey, myself->cipher_pktkeylength);
1160       pktkey[myself->cipher_pktkeylength*2] = '\0';
1161       send_ans_key(myself, from, pktkey);
1162       mykeyused = 1;
1163     }
1164   else
1165     {
1166       if(!(to = lookup_id(to_id)))
1167         {
1168           syslog(LOG_ERR, _("Got REQ_KEY from %s (%s) destination %s which does not exist in our connection list"),
1169                  cl->name, cl->hostname, to_id);
1170           return -1;
1171         }
1172         
1173       if(to->status.validkey)   /* Proxy keys */
1174         {
1175           bin2hex(to->cipher_pktkey, pktkey, to->cipher_pktkeylength);
1176           pktkey[to->cipher_pktkeylength*2] = '\0';
1177           send_ans_key(to, from, pktkey);
1178         }
1179       else
1180         send_req_key(from, to);
1181     }
1182
1183 cp
1184   return 0;
1185 }
1186
1187 int send_ans_key(connection_t *from, connection_t *to, char *pktkey)
1188 {
1189 cp
1190   return send_request(to->nexthop, "%d %s %s %s", ANS_KEY,
1191                       from->name, to->name, pktkey);
1192 }
1193
1194 int ans_key_h(connection_t *cl)
1195 {
1196   char from_id[MAX_STRING_SIZE];
1197   char to_id[MAX_STRING_SIZE];
1198   char pktkey[MAX_STRING_SIZE];
1199   int keylength;
1200   connection_t *from, *to;
1201 cp
1202   if(sscanf(cl->buffer, "%*d "MAX_STRING" "MAX_STRING" "MAX_STRING, from_id, to_id, pktkey) != 3)
1203     {
1204        syslog(LOG_ERR, _("Got bad ANS_KEY from %s (%s)"),
1205               cl->name, cl->hostname);
1206        return -1;
1207     }
1208
1209   if(!(from = lookup_id(from_id)))
1210     {
1211       syslog(LOG_ERR, _("Got ANS_KEY from %s (%s) origin %s which does not exist in our connection list"),
1212              cl->name, cl->hostname, from_id);
1213       return -1;
1214     }
1215
1216   /* Check correctness of packet key */
1217
1218   keylength = strlen(pktkey);
1219
1220   if(keylength != from->cipher_pktkeylength*2)
1221     {
1222       syslog(LOG_ERR, _("Got bad ANS_KEY from %s (%s) origin %s: invalid key length"),
1223              cl->name, cl->hostname, from->name);
1224       return -1;
1225     }
1226
1227   /* Forward it if necessary */
1228
1229   if(strcmp(to_id, myself->name))
1230     {
1231       if(!(to = lookup_id(to_id)))
1232         {
1233           syslog(LOG_ERR, _("Got ANS_KEY from %s (%s) destination %s which does not exist in our connection list"),
1234                  cl->name, cl->hostname, to_id);
1235           return -1;
1236         }
1237       send_ans_key(from, to, pktkey);
1238     }
1239
1240   /* Update our copy of the origin's packet key */
1241
1242   if(from->cipher_pktkey)
1243     free(from->cipher_pktkey);
1244
1245   from->cipher_pktkey = xstrdup(pktkey);
1246   keylength /= 2;
1247   hex2bin(from->cipher_pktkey, from->cipher_pktkey, keylength);
1248   from->cipher_pktkey[keylength] = '\0';
1249
1250   from->status.validkey = 1;
1251   from->status.waitingforkey = 0;
1252   
1253   flush_queue(from);
1254 cp
1255   return 0;
1256 }
1257
1258 int send_tcppacket(connection_t *cl, vpn_packet_t *packet)
1259 {
1260   int x;
1261 cp  
1262   /* Evil hack. */
1263
1264   x = send_request(cl->nexthop, "%d %hd", PACKET, packet->len);
1265
1266   if(x)
1267     return x;
1268 cp
1269   return send_meta(cl, packet->data, packet->len);
1270 }
1271
1272 int tcppacket_h(connection_t *cl)
1273 {
1274   short int len;
1275 cp  
1276   if(sscanf(cl->buffer, "%*d %hd", &len) != 1)
1277     {
1278       syslog(LOG_ERR, _("Got bad PACKET from %s (%s)"), cl->name, cl->hostname);
1279       return -1;
1280     }
1281
1282   /* Set reqlen to len, this will tell receive_meta() that a tcppacket is coming. */
1283
1284   cl->tcplen = len;
1285 cp
1286   return 0;
1287 }
1288
1289 /* Jumptable for the request handlers */
1290
1291 int (*request_handlers[])(connection_t*) = {
1292   id_h, metakey_h, challenge_h, chal_reply_h,
1293   status_h, error_h, termreq_h,
1294   ping_h, pong_h,
1295   add_host_h, del_host_h,
1296   add_subnet_h, del_subnet_h,
1297   key_changed_h, req_key_h, ans_key_h,
1298   tcppacket_h,
1299 };
1300
1301 /* Request names */
1302
1303 char (*request_name[]) = {
1304   "ID", "METAKEY", "CHALLENGE", "CHAL_REPLY",
1305   "STATUS", "ERROR", "TERMREQ",
1306   "PING", "PONG",
1307   "ADD_HOST", "DEL_HOST",
1308   "ADD_SUBNET", "DEL_SUBNET",
1309   "KEY_CHANGED", "REQ_KEY", "ANS_KEY",
1310   "PACKET",
1311 };
1312
1313 /* Status strings */
1314
1315 char (*status_text[]) = {
1316   "Warning",
1317 };
1318
1319 /* Error strings */
1320
1321 char (*error_text[]) = {
1322   "Error",
1323 };