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