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