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