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