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