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