7540e4737983be915ea6f2ecf8abf3b358dc4c61
[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.115 2001/10/31 12:50:24 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 an 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(0);
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       if(n->address != address || n->port != port)
879         syslog(LOG_DEBUG, _("Got %s from %s (%s) for %s which does not match existing entry"), "ADD_NODE", c->name, c->hostname, n->name);
880
881       return 0;
882     }
883   else
884     {
885       n = new_node();
886       n->name = xstrdup(name);
887       n->address = address;
888       n->port = port;
889       node_add(n);
890     }
891
892   /* Tell the rest about the new node */
893
894   for(node = connection_tree->head; node; node = node->next)
895     {
896       other = (connection_t *)node->data;
897       if(other->status.active && other !=c)
898         send_add_node(other, n);
899     }
900
901 cp
902   return 0;
903 }
904
905 int send_del_node(connection_t *c, node_t *n)
906 {
907 cp
908   return send_request(c, "%d %s %lx:%d", DEL_NODE,
909                       n->name, n->address, n->port);
910 }
911
912 int del_node_h(connection_t *c)
913 {
914   node_t *n;
915   char name[MAX_STRING_SIZE];
916   ipv4_t address;
917   port_t port;
918   connection_t *other;
919   avl_node_t *node;
920 cp
921   if(sscanf(c->buffer, "%*d "MAX_STRING" %lx:%hd", name, &address, &port) != 3)
922     {
923       syslog(LOG_ERR, _("Got bad %s from %s (%s)"), "DEL_NODE",
924              c->name, c->hostname);
925       return -1;
926     }
927
928   /* Check if identity is a valid name */
929
930   if(check_id(name))
931     {
932       syslog(LOG_ERR, _("Got bad %s from %s (%s): %s"), "DEL_NODE", c->name, c->hostname, _("invalid name"));
933       return -1;
934     }
935
936   /* Check if somebody tries to delete ourself */
937
938   if(!strcmp(name, myself->name))
939     {
940       syslog(LOG_ERR, _("Got %s from %s (%s) for ourself!"), "DEL_NODE",
941              c->name, c->hostname);
942       return -1;
943     }
944
945   /* Check if the deleted host exists */
946
947   n = lookup_node(name);
948
949   if(!n)
950     {
951       syslog(LOG_WARNING, _("Got %s from %s (%s) for %s which does not exist"), "DEL_NODE", c->name, c->hostname, n->name);
952       return 0;
953     }
954   
955   /* Check if the rest matches */
956   
957   if(address != n->address || port != n->port)
958     {
959       syslog(LOG_WARNING, _("Got %s from %s (%s) for %s which does not match existing entry"), "DEL_NODE", c->name, c->hostname, n->name);
960     }
961
962   /* Tell the rest about the deleted node */
963
964   for(node = connection_tree->head; node; node = node->next)
965     {
966       other = (connection_t *)node->data;
967       if(other->status.active && other != c)
968         send_del_node(other, n);
969     }
970
971   /* Delete the node */
972   
973   node_del(n);
974
975   mst_kruskal();
976   sssp_bfs(0);
977 cp
978   return 0;
979 }
980
981 /* Edges */
982
983 int send_add_edge(connection_t *c, edge_t *e)
984 {
985 cp
986   return send_request(c, "%d %s %s %lx %d", ADD_NODE,
987                       e->from->name, e->to->name, e->options, e->weight);
988 }
989
990 int add_edge_h(connection_t *c)
991 {
992   connection_t *other;
993   edge_t *e;
994   node_t *from, *to;
995   char from_name[MAX_STRING_SIZE];
996   char to_name[MAX_STRING_SIZE];
997   long int options;
998   int weight;
999   avl_node_t *node;
1000 cp
1001   if(sscanf(c->buffer, "%*d "MAX_STRING" "MAX_STRING" %lx %d", from_name, to_name, &options, &weight) != 4)
1002     {
1003        syslog(LOG_ERR, _("Got bad %s from %s (%s)"), "ADD_EDGE", c->name, c->hostname);
1004        return -1;
1005     }
1006
1007   /* Check if names are valid */
1008
1009   if(check_id(from_name))
1010     {
1011       syslog(LOG_ERR, _("Got bad %s from %s (%s): %s"), "ADD_EDGE", c->name, c->hostname, _("invalid name"));
1012       return -1;
1013     }
1014
1015   if(check_id(to_name))
1016     {
1017       syslog(LOG_ERR, _("Got bad %s from %s (%s): %s"), "ADD_EDGE", c->name, c->hostname, _("invalid name"));
1018       return -1;
1019     }
1020
1021   /* Lookup nodes */
1022
1023   from = lookup_node(from_name);
1024   
1025   if(!from)
1026     {
1027       syslog(LOG_ERR, _("Got bad %s from %s (%s): %s"), "ADD_EDGE", c->name, c->hostname, _("unknown node"));
1028       return -1;
1029     }
1030
1031   to = lookup_node(to_name);
1032   
1033   if(!to)
1034     {
1035       syslog(LOG_ERR, _("Got bad %s from %s (%s): %s"), "ADD_EDGE", c->name, c->hostname, _("unknown node"));
1036       return -1;
1037     }
1038
1039   /* Check if edge already exists */
1040   
1041   e = lookup_edge(from, to);
1042   
1043   if(e)
1044     {
1045       if(e->weight != weight || e->options != options)
1046         {
1047           syslog(LOG_ERR, _("Got %s from %s (%s) which does not match existing entry"), "ADD_EDGE", c->name, c->hostname);
1048           return -1;
1049         }
1050       
1051       return 0;
1052     }
1053   else
1054     {
1055       e = new_edge();
1056       e->from = from;
1057       e->to = to;
1058       e->options = options;
1059       e->weight = weight;
1060       edge_add(e);
1061     }
1062
1063   /* Tell the rest about the new edge */
1064
1065   for(node = connection_tree->head; node; node = node->next)
1066     {
1067       other = (connection_t *)node->data;
1068       if(other->status.active && other != c)
1069         send_add_edge(other, e);
1070     }
1071
1072   /* Run MST before or after we tell the rest? */
1073
1074   mst_kruskal();
1075   sssp_bfs(0);
1076 cp
1077   return 0;
1078 }
1079
1080 int send_del_edge(connection_t *c, edge_t *e)
1081 {
1082 cp
1083   return send_request(c, "%d %s %s %lx %d", DEL_EDGE,
1084                       e->from->name, e->to->name, e->options, e->weight);
1085 }
1086
1087 int del_edge_h(connection_t *c)
1088 {
1089   edge_t *e;
1090   char from_name[MAX_STRING_SIZE];
1091   char to_name[MAX_STRING_SIZE];
1092   node_t *from, *to;
1093   long int options;
1094   int weight;
1095   connection_t *other;
1096   avl_node_t *node;
1097 cp
1098   if(sscanf(c->buffer, "%*d "MAX_STRING" "MAX_STRING" %lx %d", from_name, to_name, &options, &weight) != 4)
1099     {
1100       syslog(LOG_ERR, _("Got bad %s from %s (%s)"), "DEL_EDGE",
1101              c->name, c->hostname);
1102       return -1;
1103     }
1104
1105   /* Check if names are valid */
1106
1107   if(check_id(from_name))
1108     {
1109       syslog(LOG_ERR, _("Got bad %s from %s (%s): %s"), "DEL_EDGE", c->name, c->hostname, _("invalid name"));
1110       return -1;
1111     }
1112
1113   if(check_id(to_name))
1114     {
1115       syslog(LOG_ERR, _("Got bad %s from %s (%s): %s"), "DEL_EDGE", c->name, c->hostname, _("invalid name"));
1116       return -1;
1117     }
1118
1119   /* Lookup nodes */
1120
1121   from = lookup_node(from_name);
1122   
1123   if(!from)
1124     {
1125       syslog(LOG_ERR, _("Got bad %s from %s (%s): %s"), "DEL_EDGE", c->name, c->hostname, _("unknown node"));
1126       return -1;
1127     }
1128
1129   to = lookup_node(to_name);
1130   
1131   if(!to)
1132     {
1133       syslog(LOG_ERR, _("Got bad %s from %s (%s): %s"), "DEL_EDGE", c->name, c->hostname, _("unknown node"));
1134       return -1;
1135     }
1136
1137   /* Check if edge exists */
1138   
1139   e = lookup_edge(from, to);
1140   
1141   if(e)
1142     {
1143       if(e->weight != weight || e->options != options)
1144         {
1145           syslog(LOG_ERR, _("Got %s from %s (%s) which does not match existing entry"), "ADD_EDGE", c->name, c->hostname);
1146           return -1;
1147         }
1148     }
1149   else
1150     {
1151       syslog(LOG_ERR, _("Got bad %s from %s (%s): %s"), "DEL_EDGE", c->name, c->hostname, _("unknown edge"));
1152       return -1;
1153     }
1154
1155   /* Tell the rest about the deleted edge */
1156
1157   for(node = connection_tree->head; node; node = node->next)
1158     {
1159       other = (connection_t *)node->data;
1160       if(other->status.active && other != c)
1161         send_del_edge(other, e);
1162     }
1163
1164   /* Delete the edge */
1165   
1166   edge_del(e);
1167
1168   /* Run MST before or after we tell the rest? */
1169
1170   mst_kruskal();
1171   sssp_bfs(1);
1172 cp
1173   return 0;
1174 }
1175
1176
1177 /* Status and error notification routines */
1178
1179 int send_status(connection_t *c, int statusno, char *statusstring)
1180 {
1181 cp
1182   if(!statusstring)
1183     statusstring = status_text[statusno];
1184 cp
1185   return send_request(c, "%d %d %s", STATUS, statusno, statusstring);
1186 }
1187
1188 int status_h(connection_t *c)
1189 {
1190   int statusno;
1191   char statusstring[MAX_STRING_SIZE];
1192 cp
1193   if(sscanf(c->buffer, "%*d %d "MAX_STRING, &statusno, statusstring) != 2)
1194     {
1195        syslog(LOG_ERR, _("Got bad %s from %s (%s)"), "STATUS",
1196               c->name, c->hostname);
1197        return -1;
1198     }
1199
1200   if(debug_lvl >= DEBUG_STATUS)
1201     {
1202       syslog(LOG_NOTICE, _("Status message from %s (%s): %s: %s"),
1203              c->name, c->hostname, status_text[statusno], statusstring);
1204     }
1205
1206 cp
1207   return 0;
1208 }
1209
1210 int send_error(connection_t *c, int err, char *errstring)
1211 {
1212 cp
1213   if(!errstring)
1214     errstring = strerror(err);
1215   return send_request(c, "%d %d %s", ERROR, err, errstring);
1216 }
1217
1218 int error_h(connection_t *c)
1219 {
1220   int err;
1221   char errorstring[MAX_STRING_SIZE];
1222 cp
1223   if(sscanf(c->buffer, "%*d %d "MAX_STRING, &err, errorstring) != 2)
1224     {
1225        syslog(LOG_ERR, _("Got bad %s from %s (%s)"), "ERROR",
1226               c->name, c->hostname);
1227        return -1;
1228     }
1229
1230   if(debug_lvl >= DEBUG_ERROR)
1231     {
1232       syslog(LOG_NOTICE, _("Error message from %s (%s): %s: %s"),
1233              c->name, c->hostname, strerror(err), errorstring);
1234     }
1235
1236   terminate_connection(c, c->status.active);
1237 cp
1238   return 0;
1239 }
1240
1241 int send_termreq(connection_t *c)
1242 {
1243 cp
1244   return send_request(c, "%d", TERMREQ);
1245 }
1246
1247 int termreq_h(connection_t *c)
1248 {
1249 cp
1250   terminate_connection(c, c->status.active);
1251 cp
1252   return 0;
1253 }
1254
1255 int send_ping(connection_t *c)
1256 {
1257   char salt[SALTLEN*2+1];
1258 cp
1259   c->status.pinged = 1;
1260   c->last_ping_time = time(NULL);
1261   RAND_pseudo_bytes(salt, SALTLEN);
1262   bin2hex(salt, salt, SALTLEN);
1263   salt[SALTLEN*2] = '\0';
1264 cp
1265   return send_request(c, "%d %s", PING, salt);
1266 }
1267
1268 int ping_h(connection_t *c)
1269 {
1270 cp
1271   return send_pong(c);
1272 }
1273
1274 int send_pong(connection_t *c)
1275 {
1276   char salt[SALTLEN*2+1];
1277 cp
1278   RAND_pseudo_bytes(salt, SALTLEN);
1279   bin2hex(salt, salt, SALTLEN);
1280   salt[SALTLEN*2] = '\0';
1281 cp
1282   return send_request(c, "%d %s", PONG, salt);
1283 }
1284
1285 int pong_h(connection_t *c)
1286 {
1287 cp
1288   c->status.pinged = 0;
1289 cp
1290   return 0;
1291 }
1292
1293 /* Key exchange */
1294
1295 int send_key_changed(connection_t *c, node_t *n)
1296 {
1297   connection_t *other;
1298   avl_node_t *node;
1299 cp
1300   /* Only send this message if some other daemon requested our key previously.
1301      This reduces unnecessary key_changed broadcasts.
1302   */
1303
1304   if(n == myself && !mykeyused)
1305     return 0;
1306
1307   for(node = connection_tree->head; node; node = node->next)
1308     {
1309       other = (connection_t *)node->data;
1310       if(other != c && other->status.active)
1311         send_request(other, "%d %s", KEY_CHANGED, n->name);
1312     }
1313 cp
1314   return 0;
1315 }
1316
1317 int key_changed_h(connection_t *c)
1318 {
1319   char name[MAX_STRING_SIZE];
1320   node_t *n;
1321 cp
1322   if(sscanf(c->buffer, "%*d "MAX_STRING, name) != 1)
1323     {
1324       syslog(LOG_ERR, _("Got bad %s from %s (%s)"), "KEY_CHANGED",
1325              c->name, c->hostname);
1326       return -1;
1327     }
1328
1329   n = lookup_node(name);
1330
1331   if(!n)
1332     {
1333       syslog(LOG_ERR, _("Got %s from %s (%s) origin %s which does not exist"), "KEY_CHANGED",
1334              c->name, c->hostname, name);
1335       return -1;
1336     }
1337
1338   n->status.validkey = 0;
1339   n->status.waitingforkey = 0;
1340
1341   send_key_changed(c, n);
1342 cp
1343   return 0;
1344 }
1345
1346 int send_req_key(connection_t *c, node_t *from, node_t *to)
1347 {
1348 cp
1349   return send_request(c, "%d %s %s", REQ_KEY,
1350                       from->name, to->name);
1351 }
1352
1353 int req_key_h(connection_t *c)
1354 {
1355   char from_name[MAX_STRING_SIZE];
1356   char to_name[MAX_STRING_SIZE];
1357   node_t *from, *to;
1358   char key[MAX_STRING_SIZE];
1359 cp
1360   if(sscanf(c->buffer, "%*d "MAX_STRING" "MAX_STRING, from_name, to_name) != 2)
1361     {
1362        syslog(LOG_ERR, _("Got bad %s from %s (%s)"), "REQ_KEY",
1363               c->name, c->hostname);
1364        return -1;
1365     }
1366
1367   from = lookup_node(from_name);
1368
1369   if(!from)
1370     {
1371       syslog(LOG_ERR, _("Got %s from %s (%s) origin %s which does not exist in our connection list"), "REQ_KEY",
1372              c->name, c->hostname, from_name);
1373       return -1;
1374     }
1375
1376   to = lookup_node(to_name);
1377   
1378   if(!to)
1379     {
1380       syslog(LOG_ERR, _("Got %s from %s (%s) destination %s which does not exist in our connection list"), "REQ_KEY",
1381              c->name, c->hostname, to_name);
1382       return -1;
1383     }
1384
1385   /* Check if this key request is for us */
1386
1387   if(to == myself)      /* Yes, send our own key back */
1388     {
1389       bin2hex(myself->key, key, myself->keylength);
1390       key[myself->keylength * 2] = '\0';
1391       send_ans_key(c, myself, from, key);
1392       mykeyused = 1;
1393     }
1394   else
1395     {
1396       if(to->status.validkey)   /* Proxy keys */
1397         {
1398           bin2hex(to->key, key, to->keylength);
1399           key[to->keylength * 2] = '\0';
1400           send_ans_key(c, to, from, key);
1401         }
1402       else
1403         send_req_key(to->nexthop->connection, from, to);
1404     }
1405
1406 cp
1407   return 0;
1408 }
1409
1410 int send_ans_key(connection_t *c, node_t *from, node_t *to, char *key)
1411 {
1412 cp
1413   return send_request(c, "%d %s %s %s", ANS_KEY,
1414                       from->name, to->name, key);
1415 }
1416
1417 int ans_key_h(connection_t *c)
1418 {
1419   char from_name[MAX_STRING_SIZE];
1420   char to_name[MAX_STRING_SIZE];
1421   char key[MAX_STRING_SIZE];
1422   int keylength;
1423   node_t *from, *to;
1424 cp
1425   if(sscanf(c->buffer, "%*d "MAX_STRING" "MAX_STRING" "MAX_STRING, from_name, to_name, key) != 3)
1426     {
1427        syslog(LOG_ERR, _("Got bad %s from %s (%s)"), "ANS_KEY",
1428               c->name, c->hostname);
1429        return -1;
1430     }
1431
1432   from = lookup_node(from_name);
1433
1434   if(!from)
1435     {
1436       syslog(LOG_ERR, _("Got %s from %s (%s) origin %s which does not exist in our connection list"), "ANS_KEY",
1437              c->name, c->hostname, from_name);
1438       return -1;
1439     }
1440
1441   to = lookup_node(to_name);
1442
1443   if(!to)
1444     {
1445       syslog(LOG_ERR, _("Got %s from %s (%s) destination %s which does not exist in our connection list"), "ANS_KEY",
1446              c->name, c->hostname, to_name);
1447       return -1;
1448     }
1449
1450   /* Check correctness of packet key */
1451
1452   keylength = strlen(key);
1453
1454   if(keylength != from->keylength * 2)
1455     {
1456       syslog(LOG_ERR, _("Got bad %s from %s (%s) origin %s: %s"), "ANS_KEY",
1457              c->name, c->hostname, from->name, _("invalid key length"));
1458       return -1;
1459     }
1460
1461   /* Forward it if necessary */
1462
1463   if(to != myself)
1464     {
1465       send_ans_key(to->nexthop->connection, from, to, key);
1466     }
1467
1468   /* Update our copy of the origin's packet key */
1469
1470   if(from->key)
1471     free(from->key);
1472
1473   from->key = xstrdup(key);
1474   keylength /= 2;
1475   hex2bin(from->key, from->key, keylength);
1476   from->key[keylength] = '\0';
1477
1478   from->status.validkey = 1;
1479   from->status.waitingforkey = 0;
1480   
1481   flush_queue(from);
1482 cp
1483   return 0;
1484 }
1485
1486 int send_tcppacket(connection_t *c, vpn_packet_t *packet)
1487 {
1488   int x;
1489 cp  
1490   /* Evil hack. */
1491
1492   x = send_request(c, "%d %hd", PACKET, packet->len);
1493
1494   if(x)
1495     return x;
1496 cp
1497   return send_meta(c, packet->data, packet->len);
1498 }
1499
1500 int tcppacket_h(connection_t *c)
1501 {
1502   short int len;
1503 cp  
1504   if(sscanf(c->buffer, "%*d %hd", &len) != 1)
1505     {
1506       syslog(LOG_ERR, _("Got bad %s from %s (%s)"), "PACKET", c->name, c->hostname);
1507       return -1;
1508     }
1509
1510   /* Set reqlen to len, this will tell receive_meta() that a tcppacket is coming. */
1511
1512   c->tcplen = len;
1513 cp
1514   return 0;
1515 }
1516
1517 /* Jumptable for the request handlers */
1518
1519 int (*request_handlers[])(connection_t*) = {
1520   id_h, metakey_h, challenge_h, chal_reply_h, ack_h,
1521   status_h, error_h, termreq_h,
1522   ping_h, pong_h,
1523   add_node_h, del_node_h,
1524   add_subnet_h, del_subnet_h,
1525   add_edge_h, del_edge_h,
1526   key_changed_h, req_key_h, ans_key_h,
1527   tcppacket_h,
1528 };
1529
1530 /* Request names */
1531
1532 char (*request_name[]) = {
1533   "ID", "METAKEY", "CHALLENGE", "CHAL_REPLY", "ACK",
1534   "STATUS", "ERROR", "TERMREQ",
1535   "PING", "PONG",
1536   "ADD_NODE", "DEL_NODE",
1537   "ADD_SUBNET", "DEL_SUBNET",
1538   "ADD_EDGE", "DEL_EDGE",
1539   "KEY_CHANGED", "REQ_KEY", "ANS_KEY",
1540   "PACKET",
1541 };
1542
1543 /* Status strings */
1544
1545 char (*status_text[]) = {
1546   "Warning",
1547 };
1548
1549 /* Error strings */
1550
1551 char (*error_text[]) = {
1552   "Error",
1553 };