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