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