Remove IndirectData support for now, new implementation will be added
[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.105 2001/09/01 12:02:39 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 at %s"),
242                old->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, 0);
249       return 0;
250     }
251     
252   /* Also check if no other tinc daemon uses the same IP and port for UDP traffic */
253   
254   old = avl_search(active_tree, cl);
255   if(old)
256   {
257     syslog(LOG_ERR, _("%s is listening on %s:%hd, which is already in use by %s!"),
258            cl->name, cl->hostname, cl->port, old->name);
259     return -1;
260   }
261     
262   /* Activate this connection */
263
264   cl->allow_request = ALL;
265   cl->nexthop = cl;
266   cl->cipher_pkttype = EVP_bf_cbc();
267   cl->cipher_pktkeylength = cl->cipher_pkttype->key_len + cl->cipher_pkttype->iv_len;
268
269   active_add(cl);
270
271   if(debug_lvl >= DEBUG_CONNECTIONS)
272     syslog(LOG_NOTICE, _("Connection with %s (%s) activated"), cl->name, cl->hostname);
273
274   if(cl->status.outgoing)
275     seconds_till_retry = 5;     /* Reset retry timeout */
276 cp
277   /* Check some options */
278   
279   if((cfg = get_config_val(cl->config, config_indirectdata)))
280     {
281       if(cfg->data.val == stupid_true)
282         cl->options |= OPTION_INDIRECT;
283     }
284
285   if((cfg = get_config_val(cl->config, config_tcponly)))
286     {
287       if(cfg->data.val == stupid_true)
288         cl->options |= OPTION_TCPONLY;
289     }
290
291   /* Send him our subnets */
292   
293   for(node = myself->subnet_tree->head; node; node = node->next)
294     {
295       subnet = (subnet_t *)node->data;
296       send_add_subnet(cl, subnet);
297     }
298
299   /* And send him all the hosts and their subnets we know... */
300   
301   for(node = active_tree->head; node; node = node->next)
302     {
303       p = (connection_t *)node->data;
304       
305       if(p != cl)
306         {
307           /* Notify others of this connection */
308
309           if(p->status.meta)
310             send_add_host(p, cl);
311
312           /* Notify new connection of everything we know */
313
314           send_add_host(cl, p);
315
316           for(node2 = p->subnet_tree->head; node2; node2 = node2->next)
317             {
318               subnet = (subnet_t *)node2->data;
319               send_add_subnet(cl, subnet);
320             }
321         }
322     }
323 cp
324   return 0;
325 }
326
327 int send_challenge(connection_t *cl)
328 {
329   char *buffer;
330   int len, x;
331 cp
332   /* CHECKME: what is most reasonable value for len? */
333
334   len = RSA_size(cl->rsa_key);
335
336   /* Allocate buffers for the challenge */
337
338   buffer = xmalloc(len*2+1);
339
340   if(cl->hischallenge)
341     free(cl->hischallenge);
342     
343   cl->hischallenge = xmalloc(len);
344 cp
345   /* Copy random data to the buffer */
346
347   RAND_bytes(cl->hischallenge, len);
348
349 cp
350   /* Convert to hex */
351
352   bin2hex(cl->hischallenge, buffer, len);
353   buffer[len*2] = '\0';
354
355 cp
356   /* Send the challenge */
357
358   x = send_request(cl, "%d %s", CHALLENGE, buffer);
359   free(buffer);
360 cp
361   return x;
362 }
363
364 int challenge_h(connection_t *cl)
365 {
366   char buffer[MAX_STRING_SIZE];
367   int len;
368 cp
369   if(sscanf(cl->buffer, "%*d "MAX_STRING, buffer) != 1)
370     {
371        syslog(LOG_ERR, _("Got bad CHALLENGE from %s (%s)"), cl->name, cl->hostname);
372        return -1;
373     }
374
375   len = RSA_size(myself->rsa_key);
376
377   /* Check if the length of the challenge is all right */
378
379   if(strlen(buffer) != len*2)
380     {
381       syslog(LOG_ERR, _("Intruder: wrong challenge length from %s (%s)"), cl->name, cl->hostname);
382       return -1;
383     }
384
385   /* Allocate buffers for the challenge */
386
387   if(!cl->mychallenge)
388     cl->mychallenge = xmalloc(len);
389
390   /* Convert the challenge from hexadecimal back to binary */
391
392   hex2bin(buffer,cl->mychallenge,len);
393
394   cl->allow_request = CHAL_REPLY;
395
396   /* Rest is done by send_chal_reply() */
397 cp
398   return send_chal_reply(cl);
399 }
400
401 int send_chal_reply(connection_t *cl)
402 {
403   char hash[SHA_DIGEST_LENGTH*2+1];
404 cp
405   if(!cl->mychallenge)
406     {
407       syslog(LOG_ERR, _("Trying to send CHAL_REPLY to %s (%s) without a valid CHALLENGE"), cl->name, cl->hostname);
408       return -1;
409     }
410      
411   /* Calculate the hash from the challenge we received */
412
413   SHA1(cl->mychallenge, RSA_size(myself->rsa_key), hash);
414
415   /* Convert the hash to a hexadecimal formatted string */
416
417   bin2hex(hash,hash,SHA_DIGEST_LENGTH);
418   hash[SHA_DIGEST_LENGTH*2] = '\0';
419
420   /* Send the reply */
421
422 cp
423   return send_request(cl, "%d %s", CHAL_REPLY, hash);
424 }
425
426 int chal_reply_h(connection_t *cl)
427 {
428   char hishash[MAX_STRING_SIZE];
429   char myhash[SHA_DIGEST_LENGTH];
430 cp
431   if(sscanf(cl->buffer, "%*d "MAX_STRING, hishash) != 1)
432     {
433        syslog(LOG_ERR, _("Got bad CHAL_REPLY from %s (%s)"), cl->name, cl->hostname);
434        return -1;
435     }
436
437   /* Check if the length of the hash is all right */
438
439   if(strlen(hishash) != SHA_DIGEST_LENGTH*2)
440     {
441       syslog(LOG_ERR, _("Intruder: wrong challenge reply length from %s (%s)"), cl->name, cl->hostname);
442       return -1;
443     }
444
445   /* Convert the hash to binary format */
446
447   hex2bin(hishash, hishash, SHA_DIGEST_LENGTH);
448
449   /* Calculate the hash from the challenge we sent */
450
451   SHA1(cl->hischallenge, RSA_size(cl->rsa_key), myhash);
452
453   /* Verify the incoming hash with the calculated hash */
454
455   if(memcmp(hishash, myhash, SHA_DIGEST_LENGTH))
456     {
457       syslog(LOG_ERR, _("Intruder: wrong challenge reply from %s (%s)"), cl->name, cl->hostname);
458       if(debug_lvl >= DEBUG_SCARY_THINGS)
459         {
460           bin2hex(myhash, hishash, SHA_DIGEST_LENGTH);
461           hishash[SHA_DIGEST_LENGTH*2] = '\0';
462           syslog(LOG_DEBUG, _("Expected challenge reply: %s"), hishash);
463         }
464       return -1;
465     }
466
467   /* Identity has now been positively verified.
468      ack_h() handles the rest from now on.
469    */
470 cp
471   return ack_h(cl);
472 }
473
474 int send_metakey(connection_t *cl)
475 {
476   char *buffer;
477   int len, x;
478 cp
479   len = RSA_size(cl->rsa_key);
480
481   /* Allocate buffers for the meta key */
482
483   buffer = xmalloc(len*2+1);
484
485   if(!cl->cipher_outkey)
486     cl->cipher_outkey = xmalloc(len);
487     
488   if(!cl->cipher_outctx)
489     cl->cipher_outctx = xmalloc(sizeof(*cl->cipher_outctx));
490 cp
491   /* Copy random data to the buffer */
492
493   RAND_bytes(cl->cipher_outkey, len);
494
495   /* The message we send must be smaller than the modulus of the RSA key.
496      By definition, for a key of k bits, the following formula holds:
497      
498        2^(k-1) <= modulus < 2^(k)
499      
500      Where ^ means "to the power of", not "xor".
501      This means that to be sure, we must choose our message < 2^(k-1).
502      This can be done by setting the most significant bit to zero.
503   */
504   
505   cl->cipher_outkey[0] &= 0x7F;
506   
507   if(debug_lvl >= DEBUG_SCARY_THINGS)
508     {
509       bin2hex(cl->cipher_outkey, buffer, len);
510       buffer[len*2] = '\0';
511       syslog(LOG_DEBUG, _("Generated random meta key (unencrypted): %s"), buffer);
512     }
513
514   /* Encrypt the random data
515   
516      We do not use one of the PKCS padding schemes here.
517      This is allowed, because we encrypt a totally random string
518      with a length equal to that of the modulus of the RSA key.
519   */
520   
521   if(RSA_public_encrypt(len, cl->cipher_outkey, buffer, cl->rsa_key, RSA_NO_PADDING) != len)
522     {
523       syslog(LOG_ERR, _("Error during encryption of meta key for %s (%s)"), cl->name, cl->hostname);
524       free(buffer);
525       return -1;
526     }
527 cp
528   /* Convert the encrypted random data to a hexadecimal formatted string */
529
530   bin2hex(buffer, buffer, len);
531   buffer[len*2] = '\0';
532
533   /* Send the meta key */
534
535   x = send_request(cl, "%d %s", METAKEY, buffer);
536   free(buffer);
537
538   /* Further outgoing requests are encrypted with the key we just generated */
539
540   EVP_EncryptInit(cl->cipher_outctx, EVP_bf_cfb(),
541                   cl->cipher_outkey + len - EVP_bf_cfb()->key_len,
542                   cl->cipher_outkey + len - EVP_bf_cfb()->key_len - EVP_bf_cfb()->iv_len);
543
544   cl->status.encryptout = 1;
545 cp
546   return x;
547 }
548
549 int metakey_h(connection_t *cl)
550 {
551   char buffer[MAX_STRING_SIZE];
552   int len;
553 cp
554   if(sscanf(cl->buffer, "%*d "MAX_STRING, buffer) != 1)
555     {
556        syslog(LOG_ERR, _("Got bad METAKEY from %s (%s)"), cl->name, cl->hostname);
557        return -1;
558     }
559
560   len = RSA_size(myself->rsa_key);
561
562   /* Check if the length of the meta key is all right */
563
564   if(strlen(buffer) != len*2)
565     {
566       syslog(LOG_ERR, _("Intruder: wrong meta key length from %s (%s)"), cl->name, cl->hostname);
567       return -1;
568     }
569
570   /* Allocate buffers for the meta key */
571
572   if(!cl->cipher_inkey)
573     cl->cipher_inkey = xmalloc(len);
574
575   if(!cl->cipher_inctx)
576     cl->cipher_inctx = xmalloc(sizeof(*cl->cipher_inctx));
577
578   /* Convert the challenge from hexadecimal back to binary */
579
580   hex2bin(buffer,buffer,len);
581
582   /* Decrypt the meta key */
583   
584   if(RSA_private_decrypt(len, buffer, cl->cipher_inkey, myself->rsa_key, RSA_NO_PADDING) != len)        /* See challenge() */
585     {
586       syslog(LOG_ERR, _("Error during encryption of meta key for %s (%s)"), cl->name, cl->hostname);
587       return -1;
588     }
589
590   if(debug_lvl >= DEBUG_SCARY_THINGS)
591     {
592       bin2hex(cl->cipher_inkey, buffer, len);
593       buffer[len*2] = '\0';
594       syslog(LOG_DEBUG, _("Received random meta key (unencrypted): %s"), buffer);
595     }
596
597   /* All incoming requests will now be encrypted. */
598
599   EVP_DecryptInit(cl->cipher_inctx, EVP_bf_cfb(),
600                   cl->cipher_inkey + len - EVP_bf_cfb()->key_len,
601                   cl->cipher_inkey + len - EVP_bf_cfb()->key_len - EVP_bf_cfb()->iv_len);
602   
603   cl->status.decryptin = 1;
604
605   cl->allow_request = CHALLENGE;
606 cp
607   return send_challenge(cl);
608 }
609
610 /* Address and subnet information exchange */
611
612 int send_add_subnet(connection_t *cl, subnet_t *subnet)
613 {
614   int x;
615   char *netstr;
616   char *owner;
617 cp
618   owner = subnet->owner->name;
619
620   x = send_request(cl, "%d %s %s", ADD_SUBNET,
621                       owner, netstr = net2str(subnet));
622   free(netstr);
623 cp
624   return x;
625 }
626
627 int add_subnet_h(connection_t *cl)
628 {
629   char subnetstr[MAX_STRING_SIZE];
630   char name[MAX_STRING_SIZE];
631   connection_t *owner, *p;
632   subnet_t *subnet;
633   avl_node_t *node;
634 cp
635   if(sscanf(cl->buffer, "%*d "MAX_STRING" "MAX_STRING, name, subnetstr) != 2)
636     {
637       syslog(LOG_ERR, _("Got bad ADD_SUBNET from %s (%s)"), cl->name, cl->hostname);
638       return -1;
639     }
640
641   /* Check if owner name is a valid */
642
643   if(check_id(name))
644     {
645       syslog(LOG_ERR, _("Got bad ADD_SUBNET from %s (%s): invalid identity name"), cl->name, cl->hostname);
646       return -1;
647     }
648
649   /* Check if subnet string is valid */
650
651   if(!(subnet = str2net(subnetstr)))
652     {
653       syslog(LOG_ERR, _("Got bad ADD_SUBNET from %s (%s): invalid subnet string"), cl->name, cl->hostname);
654       return -1;
655     }
656
657   /* Check if somebody tries to add a subnet of ourself */
658
659   if(!strcmp(name, myself->name))
660     {
661       syslog(LOG_ERR, _("Warning: got ADD_SUBNET from %s (%s) for ourself, restarting"),
662              cl->name, cl->hostname);
663       sighup = 1;
664       return 0;
665     }
666
667   /* Check if the owner of the new subnet is in the connection list */
668
669   if(!(owner = lookup_id(name)))
670     {
671       syslog(LOG_ERR, _("Got ADD_SUBNET for %s from %s (%s) which is not in our connection list"),
672              name, cl->name, cl->hostname);
673       return -1;
674     }
675
676   /* If everything is correct, add the subnet to the list of the owner */
677
678   subnet_add(owner, subnet);
679
680   /* Tell the rest */
681   
682   for(node = connection_tree->head; node; node = node->next)
683     {
684       p = (connection_t *)node->data;
685       if(p->status.active && p!= cl)
686         send_add_subnet(p, subnet);
687     }
688 cp
689   return 0;
690 }
691
692 int send_del_subnet(connection_t *cl, subnet_t *subnet)
693 {
694   int x;
695   char *netstr;
696   char *owner;
697 cp
698   owner = subnet->owner->name;
699
700   x = send_request(cl, "%d %s %s", DEL_SUBNET, owner, netstr = net2str(subnet));
701   free(netstr);
702 cp
703   return x;
704 }
705
706 int del_subnet_h(connection_t *cl)
707 {
708   char subnetstr[MAX_STRING_SIZE];
709   char name[MAX_STRING_SIZE];
710   connection_t *owner, *p;
711   subnet_t *subnet;
712   avl_node_t *node;
713 cp
714   if(sscanf(cl->buffer, "%*d "MAX_STRING" "MAX_STRING, name, subnetstr) != 3)
715     {
716       syslog(LOG_ERR, _("Got bad DEL_SUBNET from %s (%s)"), cl->name, cl->hostname);
717       return -1;
718     }
719
720   /* Check if owner name is a valid */
721
722   if(check_id(name))
723     {
724       syslog(LOG_ERR, _("Got bad DEL_SUBNET from %s (%s): invalid identity name"), cl->name, cl->hostname);
725       return -1;
726     }
727
728   /* Check if subnet string is valid */
729
730   if(!(subnet = str2net(subnetstr)))
731     {
732       syslog(LOG_ERR, _("Got bad DEL_SUBNET from %s (%s): invalid subnet string"), cl->name, cl->hostname);
733       return -1;
734     }
735
736   free(subnetstr);
737   
738   /* Check if somebody tries to add a subnet of ourself */
739
740   if(!strcmp(name, myself->name))
741     {
742       syslog(LOG_ERR, _("Warning: got DEL_SUBNET from %s (%s) for ourself, restarting"),
743              cl->name, cl->hostname);
744       sighup = 1;
745       return 0;
746     }
747
748   /* Check if the owner of the new subnet is in the connection list */
749
750   if(!(owner = lookup_id(name)))
751     {
752       syslog(LOG_ERR, _("Got DEL_SUBNET for %s from %s (%s) which is not in our connection list"),
753              name, cl->name, cl->hostname);
754       return -1;
755     }
756
757   /* If everything is correct, delete the subnet from the list of the owner */
758
759   subnet_del(subnet);
760
761   /* Tell the rest */
762   
763   for(node = connection_tree->head; node; node = node->next)
764     {
765       p = (connection_t *)node->data;
766       if(p->status.active && p!= cl)
767         send_del_subnet(p, subnet);
768     }
769 cp
770   return 0;
771 }
772
773 /* New and closed connections notification */
774
775 int send_add_host(connection_t *cl, connection_t *other)
776 {
777 cp
778   return send_request(cl, "%d %s %lx:%d %lx", ADD_HOST,
779                       other->name, other->address, other->port, other->options);
780 }
781
782 int add_host_h(connection_t *cl)
783 {
784   connection_t *old, *new, *p;
785   char name[MAX_STRING_SIZE];
786   avl_node_t *node;
787 cp
788   new = new_connection();
789
790   if(sscanf(cl->buffer, "%*d "MAX_STRING" %lx:%hd %lx", name, &new->address, &new->port, &new->options) != 4)
791     {
792        syslog(LOG_ERR, _("Got bad ADD_HOST from %s (%s)"), cl->name, cl->hostname);
793        return -1;
794     }
795
796   /* Check if identity is a valid name */
797
798   if(check_id(name))
799     {
800       syslog(LOG_ERR, _("Got bad ADD_HOST from %s (%s): invalid identity name"), cl->name, cl->hostname);
801       free_connection(new);
802       return -1;
803     }
804
805   /* Check if somebody tries to add ourself */
806
807   if(!strcmp(name, myself->name))
808     {
809       syslog(LOG_ERR, _("Warning: got ADD_HOST from %s (%s) for ourself, restarting"), cl->name, cl->hostname);
810       sighup = 1;
811       free_connection(new);
812       return 0;
813     }
814     
815   /* Fill in more of the new connection structure */
816
817   new->hostname = hostlookup(htonl(new->address));
818
819   /* Check if the new host already exists in the connnection list */
820
821   if((old = lookup_id(name)))
822     {
823       if((new->address == old->address) && (new->port == old->port) && (cl->nexthop == old->nexthop))
824         {
825           if(debug_lvl >= DEBUG_CONNECTIONS)
826             syslog(LOG_NOTICE, _("Got duplicate ADD_HOST for %s (%s) from %s (%s)"),
827                    old->name, old->hostname, cl->name, cl->hostname);
828           free_connection(new);
829           return 0;
830         }
831       else
832         {
833           if(debug_lvl >= DEBUG_CONNECTIONS)
834             syslog(LOG_NOTICE, _("Removing old entry for %s (%s) from %s in favour of new connection from %s"),
835                    old->name, old->hostname, old->nexthop->name, cl->nexthop->name);
836
837           terminate_connection(old, 0);
838         }
839     }
840
841   /* Hook it up into the active tree */
842
843   new->name = xstrdup(name);
844   active_add(new);
845
846   /* Tell the rest about the new host */
847
848   for(node = connection_tree->head; node; node = node->next)
849     {
850       p = (connection_t *)node->data;
851       if(p->status.active && p!=cl)
852         send_add_host(p, new);
853     }
854
855   /* Fill in rest of connection structure */
856
857   new->nexthop = cl;
858   new->cipher_pkttype = EVP_bf_cbc();
859   new->cipher_pktkeylength = cl->cipher_pkttype->key_len + cl->cipher_pkttype->iv_len;
860 cp
861   return 0;
862 }
863
864 int send_del_host(connection_t *cl, connection_t *other)
865 {
866 cp
867   return send_request(cl, "%d %s %lx:%d %lx", DEL_HOST,
868                       other->name, other->address, other->port, other->options);
869 }
870
871 int del_host_h(connection_t *cl)
872 {
873   char name[MAX_STRING_SIZE];
874   ipv4_t address;
875   port_t port;
876   long int options;
877   connection_t *old, *p;
878   avl_node_t *node;
879 cp
880   if(sscanf(cl->buffer, "%*d "MAX_STRING" %lx:%hd %lx", name, &address, &port, &options) != 4)
881     {
882       syslog(LOG_ERR, _("Got bad DEL_HOST from %s (%s)"),
883              cl->name, cl->hostname);
884       return -1;
885     }
886
887   /* Check if identity is a valid name */
888
889   if(check_id(name))
890     {
891       syslog(LOG_ERR, _("Got bad DEL_HOST from %s (%s): invalid identity name"), cl->name, cl->hostname);
892       return -1;
893     }
894
895   /* Check if somebody tries to delete ourself */
896
897   if(!strcmp(name, myself->name))
898     {
899       syslog(LOG_ERR, _("Warning: got DEL_HOST from %s (%s) for ourself, restarting"),
900              cl->name, cl->hostname);
901       sighup = 1;
902       return 0;
903     }
904
905   /* Check if the deleted host already exists in the connnection list */
906
907   if(!(old = lookup_id(name)))
908     {
909       syslog(LOG_ERR, _("Got DEL_HOST from %s (%s) for %s which is not in our connection list"),
910              cl->name, cl->hostname, name);
911       return -1;
912     }
913   
914   /* Check if the rest matches */
915   
916   if(address!=old->address || port!=old->port || options!=old->options || cl!=old->nexthop)
917     {
918       syslog(LOG_WARNING, _("Got DEL_HOST from %s (%s) for %s which doesn't match"), cl->name, cl->hostname, old->name);
919       return 0;
920     }
921
922   /* Ok, since EVERYTHING seems to check out all right, delete it */
923
924   terminate_connection(old, 0);
925
926   /* Tell the rest about the deleted host */
927
928   for(node = connection_tree->head; node; node = node->next)
929     {
930       p = (connection_t *)node->data;
931       if(p->status.active && p!=cl)
932         send_del_host(p, old);
933     }
934 cp
935   return 0;
936 }
937
938 /* Status and error notification routines */
939
940 int send_status(connection_t *cl, int statusno, char *statusstring)
941 {
942 cp
943   if(!statusstring)
944     statusstring = status_text[statusno];
945 cp
946   return send_request(cl, "%d %d %s", STATUS, statusno, statusstring);
947 }
948
949 int status_h(connection_t *cl)
950 {
951   int statusno;
952   char statusstring[MAX_STRING_SIZE];
953 cp
954   if(sscanf(cl->buffer, "%*d %d "MAX_STRING, &statusno, statusstring) != 2)
955     {
956        syslog(LOG_ERR, _("Got bad STATUS from %s (%s)"),
957               cl->name, cl->hostname);
958        return -1;
959     }
960
961   if(debug_lvl >= DEBUG_STATUS)
962     {
963       syslog(LOG_NOTICE, _("Status message from %s (%s): %s: %s"),
964              cl->name, cl->hostname, status_text[statusno], statusstring);
965     }
966
967 cp
968   return 0;
969 }
970
971 int send_error(connection_t *cl, int err, char *errstring)
972 {
973 cp
974   if(!errstring)
975     errstring = strerror(err);
976   return send_request(cl, "%d %d %s", ERROR, err, errstring);
977 }
978
979 int error_h(connection_t *cl)
980 {
981   int err;
982   char errorstring[MAX_STRING_SIZE];
983 cp
984   if(sscanf(cl->buffer, "%*d %d "MAX_STRING, &err, errorstring) != 2)
985     {
986        syslog(LOG_ERR, _("Got bad ERROR from %s (%s)"),
987               cl->name, cl->hostname);
988        return -1;
989     }
990
991   if(debug_lvl >= DEBUG_ERROR)
992     {
993       syslog(LOG_NOTICE, _("Error message from %s (%s): %s: %s"),
994              cl->name, cl->hostname, strerror(err), errorstring);
995     }
996
997   terminate_connection(cl, cl->status.meta);
998 cp
999   return 0;
1000 }
1001
1002 int send_termreq(connection_t *cl)
1003 {
1004 cp
1005   return send_request(cl, "%d", TERMREQ);
1006 }
1007
1008 int termreq_h(connection_t *cl)
1009 {
1010 cp
1011   terminate_connection(cl, cl->status.meta);
1012 cp
1013   return 0;
1014 }
1015
1016 int send_ping(connection_t *cl)
1017 {
1018   char salt[SALTLEN*2+1];
1019 cp
1020   cl->status.pinged = 1;
1021   cl->last_ping_time = time(NULL);
1022   RAND_pseudo_bytes(salt, SALTLEN);
1023   bin2hex(salt, salt, SALTLEN);
1024   salt[SALTLEN*2] = '\0';
1025 cp
1026   return send_request(cl, "%d %s", PING, salt);
1027 }
1028
1029 int ping_h(connection_t *cl)
1030 {
1031 cp
1032   return send_pong(cl);
1033 }
1034
1035 int send_pong(connection_t *cl)
1036 {
1037   char salt[SALTLEN*2+1];
1038 cp
1039   RAND_pseudo_bytes(salt, SALTLEN);
1040   bin2hex(salt, salt, SALTLEN);
1041   salt[SALTLEN*2] = '\0';
1042 cp
1043   return send_request(cl, "%d %s", PONG, salt);
1044 }
1045
1046 int pong_h(connection_t *cl)
1047 {
1048 cp
1049   cl->status.pinged = 0;
1050 cp
1051   return 0;
1052 }
1053
1054 /* Key exchange */
1055
1056 int send_key_changed(connection_t *from, connection_t *cl)
1057 {
1058   connection_t *p;
1059   avl_node_t *node;
1060 cp
1061   /* Only send this message if some other daemon requested our key previously.
1062      This reduces unnecessary key_changed broadcasts.
1063   */
1064
1065   if(from==myself && !mykeyused)
1066     return 0;
1067
1068   for(node = connection_tree->head; node; node = node->next)
1069     {
1070       p = (connection_t *)node->data;
1071       if(p != cl && p->status.active)
1072         send_request(p, "%d %s", KEY_CHANGED, from->name);
1073     }
1074 cp
1075   return 0;
1076 }
1077
1078 int key_changed_h(connection_t *cl)
1079 {
1080   char from_id[MAX_STRING_SIZE];
1081   connection_t *from;
1082 cp
1083   if(sscanf(cl->buffer, "%*d "MAX_STRING, from_id) != 1)
1084     {
1085       syslog(LOG_ERR, _("Got bad KEY_CHANGED from %s (%s)"),
1086              cl->name, cl->hostname);
1087       return -1;
1088     }
1089
1090   if(!(from = lookup_id(from_id)))
1091     {
1092       syslog(LOG_ERR, _("Got KEY_CHANGED from %s (%s) origin %s which does not exist in our connection list"),
1093              cl->name, cl->hostname, from_id);
1094       return -1;
1095     }
1096
1097   from->status.validkey = 0;
1098   from->status.waitingforkey = 0;
1099
1100   send_key_changed(from, cl);
1101 cp
1102   return 0;
1103 }
1104
1105 int send_req_key(connection_t *from, connection_t *to)
1106 {
1107 cp
1108   return send_request(to->nexthop, "%d %s %s", REQ_KEY,
1109                       from->name, to->name);
1110 }
1111
1112 int req_key_h(connection_t *cl)
1113 {
1114   char from_id[MAX_STRING_SIZE];
1115   char to_id[MAX_STRING_SIZE];
1116   connection_t *from, *to;
1117   char pktkey[129];
1118 cp
1119   if(sscanf(cl->buffer, "%*d "MAX_STRING" "MAX_STRING, from_id, to_id) != 2)
1120     {
1121        syslog(LOG_ERR, _("Got bad REQ_KEY from %s (%s)"),
1122               cl->name, cl->hostname);
1123        return -1;
1124     }
1125
1126   if(!(from = lookup_id(from_id)))
1127     {
1128       syslog(LOG_ERR, _("Got REQ_KEY from %s (%s) origin %s which does not exist in our connection list"),
1129              cl->name, cl->hostname, from_id);
1130       return -1;
1131     }
1132
1133   /* Check if this key request is for us */
1134
1135   if(!strcmp(to_id, myself->name))      /* Yes, send our own key back */
1136     {
1137       bin2hex(myself->cipher_pktkey, pktkey, myself->cipher_pktkeylength);
1138       pktkey[myself->cipher_pktkeylength*2] = '\0';
1139       send_ans_key(myself, from, pktkey);
1140       mykeyused = 1;
1141     }
1142   else
1143     {
1144       if(!(to = lookup_id(to_id)))
1145         {
1146           syslog(LOG_ERR, _("Got REQ_KEY from %s (%s) destination %s which does not exist in our connection list"),
1147                  cl->name, cl->hostname, to_id);
1148           return -1;
1149         }
1150         
1151       if(to->status.validkey)   /* Proxy keys */
1152         {
1153           bin2hex(to->cipher_pktkey, pktkey, to->cipher_pktkeylength);
1154           pktkey[to->cipher_pktkeylength*2] = '\0';
1155           send_ans_key(to, from, pktkey);
1156         }
1157       else
1158         send_req_key(from, to);
1159     }
1160
1161 cp
1162   return 0;
1163 }
1164
1165 int send_ans_key(connection_t *from, connection_t *to, char *pktkey)
1166 {
1167 cp
1168   return send_request(to->nexthop, "%d %s %s %s", ANS_KEY,
1169                       from->name, to->name, pktkey);
1170 }
1171
1172 int ans_key_h(connection_t *cl)
1173 {
1174   char from_id[MAX_STRING_SIZE];
1175   char to_id[MAX_STRING_SIZE];
1176   char pktkey[MAX_STRING_SIZE];
1177   int keylength;
1178   connection_t *from, *to;
1179 cp
1180   if(sscanf(cl->buffer, "%*d "MAX_STRING" "MAX_STRING" "MAX_STRING, from_id, to_id, pktkey) != 3)
1181     {
1182        syslog(LOG_ERR, _("Got bad ANS_KEY from %s (%s)"),
1183               cl->name, cl->hostname);
1184        return -1;
1185     }
1186
1187   if(!(from = lookup_id(from_id)))
1188     {
1189       syslog(LOG_ERR, _("Got ANS_KEY from %s (%s) origin %s which does not exist in our connection list"),
1190              cl->name, cl->hostname, from_id);
1191       return -1;
1192     }
1193
1194   /* Check correctness of packet key */
1195
1196   keylength = strlen(pktkey);
1197
1198   if(keylength != from->cipher_pktkeylength*2)
1199     {
1200       syslog(LOG_ERR, _("Got bad ANS_KEY from %s (%s) origin %s: invalid key length"),
1201              cl->name, cl->hostname, from->name);
1202       return -1;
1203     }
1204
1205   /* Forward it if necessary */
1206
1207   if(strcmp(to_id, myself->name))
1208     {
1209       if(!(to = lookup_id(to_id)))
1210         {
1211           syslog(LOG_ERR, _("Got ANS_KEY from %s (%s) destination %s which does not exist in our connection list"),
1212                  cl->name, cl->hostname, to_id);
1213           return -1;
1214         }
1215       send_ans_key(from, to, pktkey);
1216     }
1217
1218   /* Update our copy of the origin's packet key */
1219
1220   if(from->cipher_pktkey)
1221     free(from->cipher_pktkey);
1222
1223   from->cipher_pktkey = xstrdup(pktkey);
1224   keylength /= 2;
1225   hex2bin(from->cipher_pktkey, from->cipher_pktkey, keylength);
1226   from->cipher_pktkey[keylength] = '\0';
1227
1228   from->status.validkey = 1;
1229   from->status.waitingforkey = 0;
1230   
1231   flush_queue(from);
1232 cp
1233   return 0;
1234 }
1235
1236 int send_tcppacket(connection_t *cl, vpn_packet_t *packet)
1237 {
1238   int x;
1239 cp  
1240   /* Evil hack. */
1241
1242   x = send_request(cl->nexthop, "%d %hd", PACKET, packet->len);
1243
1244   if(x)
1245     return x;
1246 cp
1247   return send_meta(cl, packet->data, packet->len);
1248 }
1249
1250 int tcppacket_h(connection_t *cl)
1251 {
1252   short int len;
1253 cp  
1254   if(sscanf(cl->buffer, "%*d %hd", &len) != 1)
1255     {
1256       syslog(LOG_ERR, _("Got bad PACKET from %s (%s)"), cl->name, cl->hostname);
1257       return -1;
1258     }
1259
1260   /* Set reqlen to len, this will tell receive_meta() that a tcppacket is coming. */
1261
1262   cl->tcplen = len;
1263 cp
1264   return 0;
1265 }
1266
1267 /* Jumptable for the request handlers */
1268
1269 int (*request_handlers[])(connection_t*) = {
1270   id_h, metakey_h, challenge_h, chal_reply_h,
1271   status_h, error_h, termreq_h,
1272   ping_h, pong_h,
1273   add_host_h, del_host_h,
1274   add_subnet_h, del_subnet_h,
1275   key_changed_h, req_key_h, ans_key_h,
1276   tcppacket_h,
1277 };
1278
1279 /* Request names */
1280
1281 char (*request_name[]) = {
1282   "ID", "METAKEY", "CHALLENGE", "CHAL_REPLY",
1283   "STATUS", "ERROR", "TERMREQ",
1284   "PING", "PONG",
1285   "ADD_HOST", "DEL_HOST",
1286   "ADD_SUBNET", "DEL_SUBNET",
1287   "KEY_CHANGED", "REQ_KEY", "ANS_KEY",
1288   "PACKET",
1289 };
1290
1291 /* Status strings */
1292
1293 char (*status_text[]) = {
1294   "Warning",
1295 };
1296
1297 /* Error strings */
1298
1299 char (*error_text[]) = {
1300   "Error",
1301 };