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