- New protocol. Will break everything else for now.
[oweals/tinc.git] / src / protocol.c
1 /*
2     protocol.c -- handle the meta-protocol
3     Copyright (C) 1999,2000 Ivo Timmermans <itimmermans@bigfoot.com>,
4                        2000 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.25 2000/09/10 15:18:03 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
34 #include <utils.h>
35 #include <xalloc.h>
36
37 #include <netinet/in.h>
38
39 #include "conf.h"
40 #include "encr.h"
41 #include "net.h"
42 #include "netutl.h"
43 #include "protocol.h"
44
45 #include "system.h"
46
47 /* Generic outgoing request routine - takes care of logging and error detection as well */
48
49 int send_request(conn_list_t *cl, const char *format, int request, /*args*/ ...)
50 {
51   va_list args;
52   char *buffer = NULL;
53 cp
54   if(debug_lvl >= DEBUG_PROTOCOL)
55     syslog(LOG_DEBUG, _("Sending %s to %s (%s)"), requestname[request], cl->id, cl->hostname);
56
57   va_start(args, format);
58   len = vasprintf(&buffer, format, args);
59   va_end(args);
60
61   if(len < 0 || !buffer)
62     {
63       syslog(LOG_ERR, _("Error during vasprintf(): %m"));
64       return -1;
65     }
66
67   if(debug_lvl >= DEBUG_META)
68     syslog(LOG_DEBUG, _("Sending meta data to %s (%s): %s"), cl->id, cl->hostname, buffer);
69
70   if(cl->status.encryptout)
71     {
72       /* FIXME: Do encryption */
73     }
74
75   if((write(cl->meta_socket, buffer, buflen)) < 0)
76     {
77       syslog(LOG_ERR, _("Sending meta data failed:  %m"));
78       return -1;
79     }
80 cp  
81 }
82
83 /* Connection protocol:
84
85    Client               Server
86    send_id(*)
87                         send_challenge
88    send_chal_reply(*)                   
89                         send_id
90    send_challenge
91                         send_chal_reply
92    send_ack
93                         send_ack
94
95    (*) Unencrypted.
96 */      
97
98 int send_id(conn_list_t *cl)
99 {
100 cp
101   return send_request(cl, "%d %s %d-%d %s", ID, myself->id, myself->min_version, myself->max_version, opt2str(myself->options));
102 }
103
104 int id_h(conn_list_t *cl)
105 {
106   conn_list_t *old;
107   char *options;
108 cp
109   if(sscanf(cl->buffer, "%*d %as %d-%d %as", &cl->id, &cl->min_version, &cl->max_version, &options) != 4)
110     {
111        syslog(LOG_ERR, _("Got bad ID from %s"), cl->hostname);
112        return -1;
113     }
114     
115   /* Check if version ranges overlap */
116   
117   if((cl->min_version > myself->max_version) || (cl->max_version < myself_min_version) || (cl->min_version > cl->max_version))
118     {
119       syslog(LOG_ERR, _("Peer %s uses incompatible version (%d-%d)"), cl->hostname, cl->min_version, cl->max_version);
120       return -1;
121     }
122
123   /* Check if option string is valid */
124   
125   if(str2opt(options) == -1)
126     {
127       syslog(LOG_ERR, _("Peer %s uses invalid option string"), cl->hostname);
128       return -1;
129     }
130     
131   /* Check if identity is a valid name */
132   
133   if(!check_id(cl->id))
134     {
135       syslog(LOG_ERR, _("Peer %s uses invalid identity name"), cl->hostname);
136       return -1;
137     }
138     
139   /* Load information about peer */
140   
141   if(!read_id(cl))
142     {
143       syslog(LOG_ERR, _("Peer %s had unknown identity (%s)"), cl->hostname, cl->id);
144       return -1;
145     }
146
147
148   /* First check if the host we connected to is already in our
149      connection list. If so, we are probably making a loop, which
150      is not desirable.
151    */
152
153   if(cl->status.outgoing)
154     {
155       if((old=lookup_id(cl->id)))
156         {
157           if(debug_lvl > DEBUG_CONNECTIONS)
158             syslog(LOG_NOTICE, _("Uplink %s (%s) is already in our connection list"), cl->id, cl->hostname);
159           cl->status.outgoing = 0;
160           old->status.outgoing = 1;
161           terminate_connection(cl);
162           return 0;
163         }
164     }
165
166   /* Since we know the identity now, we can encrypt the meta channel */
167   
168   cl->status.encryptout = 1;
169
170   /* Send a challenge to verify the identity */
171
172   cl->allow_request = CHAL_REPLY;
173 cp
174   return send_challenge(cl);
175 }
176
177 int send_challenge(conn_list_t *cl)
178 {
179   char *buffer;
180   int keylength;
181   int x;
182 cp
183   if(cl->chal_hash)
184     free(cl->chal_hash);
185   
186   /* Allocate buffers for the challenge and the hash */
187   
188   cl->chal_hash = xmalloc(SHA_DIGEST_LEN);
189   keylength = BN_num_bytes(cl->metakey.n);
190   buffer = xmalloc(keylength*2);
191
192   /* Copy random data and the public key to the buffer */
193   
194   RAND_bytes(buffer, keylength);
195   BN_bn2bin(cl->metakey.n, buffer+keylength);
196
197   /* Calculate the hash from that */
198
199   SHA1(buffer, keylength*2, cl->chal_hash);
200
201   /* Convert the random data to a hexadecimal formatted string */
202
203   bin2hex(buffer,buffer,keylength);
204   buffer[keylength*2] = '\0';
205
206   /* Send the challenge */
207   
208   cl->allow_request = CHAL_REPLY;
209   x = send_request(cl, "%d %s", CHALLENGE, buffer);
210   free(buffer);
211 cp
212   return x;
213 }
214
215 int challenge_h(conn_list_t *cl)
216 {
217   char *challenge;
218 cp
219   if(sscanf(cl->buffer, "%*d %as", &cl->id, &challenge) != 1)
220     {
221        syslog(LOG_ERR, _("Got bad CHALLENGE from %s (%s)"), cl->id, cl->hostname);
222        return -1;
223     }
224
225   /* Rest is done by send_chal_reply() */
226   
227   x = send_chal_reply(cl, challenge);
228   free(challenge);
229 cp
230   return x;
231 }
232
233 int send_chal_reply(conn_list_t *cl, char *challenge)
234 {
235   char *buffer;
236   int keylength;
237   char *hash;
238   int x;
239 cp
240   keylength = BN_num_bytes(myself->meyakey.n);
241
242   /* Check if the length of the challenge is all right */
243
244   if(strlen(challenge) != keylength*2)
245     {
246       syslog(LOG_ERROR, _("Intruder: wrong challenge length from %s (%s)"), cl->id, cl->hostname);
247       return -1;
248     }
249
250   /* Allocate buffers for the challenge and the hash */
251   
252   buffer = xmalloc(keylength*2);
253   hash = xmalloc(SHA_DIGEST_LEN*2+1);
254
255   /* Copy the incoming random data and our public key to the buffer */
256
257   hex2bin(challenge, buffer, keylength); 
258   BN_bn2bin(myself->metakey.n, buffer+keylength);
259
260   /* Calculate the hash from that */
261   
262   SHA1(buffer, keylength*2, hash);
263   free(buffer);
264
265   /* Convert the hash to a hexadecimal formatted string */
266
267   bin2hex(hash,hash,SHA_DIGEST_LEN);
268   hash[SHA_DIGEST_LEN*2] = '\0';
269
270   /* Send the reply */
271
272   if(cl->status.outgoing)
273     cl->allow_resuest = ID;
274   else
275     cl->allow_request = ACK;
276
277   x = send_request(cl, "%d %s", CHAL_REPLY, hash);
278   free(hash);
279 cp
280   return x;
281
282
283 int chal_reply_h(conn_list_t *cl)
284 {
285   char *hash;
286 cp
287   if(sscanf(cl->buffer, "%*d %as", &cl->id, &hash) != 2)
288     {
289        syslog(LOG_ERR, _("Got bad CHAL_REPLY from %s (%s)"), cl->id, cl->hostname);
290        return -1;
291     }
292
293   /* Check if the length of the hash is all right */
294   
295   if(strlen(hash) != SHA_DIGEST_LEN*2)
296     {
297       syslog(LOG_ERROR, _("Intruder: wrong challenge reply length from %s (%s)"), cl->id, cl->hostname);
298       return -1;
299     }
300     
301   /* Convert the hash to binary format */
302   
303   hex2bin(hash, hash, SHA_DIGEST_LEN);
304   
305   /* Verify the incoming hash with the calculated hash */
306   
307   if{!memcmp(hash, cl->chal_hash, SHA_DIGEST_LEN)}
308     {
309       syslog(LOG_ERROR, _("Intruder: wrong challenge reply from %s (%s)"), cl->id, cl->hostname);
310       return -1;
311     }
312
313   /* Identity has now been positively verified.
314      If we are accepting this new connection, then send our identity,
315      if we are making this connecting, acknowledge.
316    */
317    
318   free(hash);
319   free(cl->chal_hash);
320
321 cp
322   if(cl->status.outgoing)
323     {
324       cl->allow_request = ACK;
325       return send_ack(cl);
326     }
327   else
328     {
329       cl->allow_request = CHALLENGE;
330       return send_id(cl);
331     }
332 }
333
334 int send_ack(conn_list_t *cl)
335 {
336 cp
337   return send_request(cl, "%d", ACK);
338 }
339
340 int ack_h(conn_list_t *cl)
341 {
342 cp
343   /* Okay, before we active the connection, we check if there is another entry
344      in the connection list with the same vpn_ip. If so, it presumably is an
345      old connection that has timed out but we don't know it yet.
346    */
347
348   while((old = lookup_conn(cl->vpn_ip))) 
349     {
350       if(debug_lvl > 1)
351         syslog(LOG_NOTICE, _("Removing old entry for %s at %s in favour of new connection from %s"),
352         cl->vpn_hostname, old->real_hostname, cl->real_hostname);
353       old->status.active = 0;
354       terminate_connection(old);
355     }
356
357   /* Activate this connection */
358
359   cl->allow_request = ALL;
360   cl->status.active = 1;
361
362   if(debug_lvl > DEBUG_CONNECTIONS)
363     syslog(LOG_NOTICE, _("Connection with %s (%s) activated"), cl->id, cl->hostname);
364
365   /* Exchange information about other tinc daemons */
366
367   notify_others(cl, NULL, send_add_host);
368   notify_one(cl);
369
370   upstreamindex = 0;
371
372 cp
373   if(cl->status.outgoing)
374     return 0;
375   else
376     return send_ack(cl);
377 }
378
379 /* Address and subnet information exchange */
380
381 /* New and closed connections notification */
382
383 /* Status and error notification routines */
384
385 int send_status(conn_list_t *cl, int statusno, char *statusstring)
386 {
387 cp
388   return send_request(cl, "%d %d %s", STATUS, statusno, statusstring);
389 }
390
391 int send_error(conn_list_t *cl, int errno, char *errstring)
392 {
393 cp
394   return send_request(cl, "%d %d %s", ERROR, errno, errstring);
395 }
396
397 /* Old routines */
398
399
400 int send_termreq(conn_list_t *cl)
401 {
402 cp
403   if(debug_lvl > 1)
404     syslog(LOG_DEBUG, _("Sending TERMREQ to %s (%s)"),
405            cl->vpn_hostname, cl->real_hostname);
406
407   buflen = snprintf(buffer, MAXBUFSIZE, "%d %lx\n", TERMREQ, myself->vpn_ip);
408
409   if(write(cl->meta_socket, buffer, buflen) < 0)
410     {
411       if(debug_lvl > 1)
412         syslog(LOG_ERR, _("Send failed: %s:%d: %m"), __FILE__, __LINE__);
413       return -1;
414     }
415 cp
416   return 0;
417 }
418
419 int send_timeout(conn_list_t *cl)
420 {
421 cp
422   if(debug_lvl > 1)
423     syslog(LOG_DEBUG, _("Sending TIMEOUT to %s (%s)"),
424            cl->vpn_hostname, cl->real_hostname);
425
426   buflen = snprintf(buffer, MAXBUFSIZE, "%d %lx\n", PINGTIMEOUT, myself->vpn_ip);
427
428   if((write(cl->meta_socket, buffer, buflen)) < 0)
429     {
430       syslog(LOG_ERR, _("Send failed: %s:%d: %m"), __FILE__, __LINE__);
431       return -1;
432     }
433 cp
434   return 0;
435 }
436
437 int send_del_host(conn_list_t *cl, conn_list_t *new_host)
438 {
439 cp
440   if(debug_lvl > 1)
441     syslog(LOG_DEBUG, _("Sending DEL_HOST for %s (%s) to %s (%s)"),
442            new_host->vpn_hostname, new_host->real_hostname, cl->vpn_hostname, cl->real_hostname);
443
444   buflen = snprintf(buffer, MAXBUFSIZE, "%d %lx\n", DEL_HOST, new_host->vpn_ip);
445
446   if((write(cl->meta_socket, buffer, buflen)) < 0)
447     {
448       syslog(LOG_ERR, _("Send failed: %s:%d: %m"), __FILE__, __LINE__);
449       return -1;
450     }
451 cp
452   return 0;
453 }
454
455 int send_tcppacket(conn_list_t *cl, void *data, int len)
456 {
457 cp
458   if(debug_lvl > 3)
459     syslog(LOG_DEBUG, _("Sending PACKET to %s (%s)"),
460            cl->vpn_hostname, cl->real_hostname);
461
462   buflen = snprintf(buffer, MAXBUFSIZE, "%d %d\n", PACKET, len);
463
464   if((write(cl->meta_socket, buffer, buflen)) < 0)
465     {
466       syslog(LOG_ERR, _("Send failed: %s:%d: %m"), __FILE__, __LINE__);
467       return -1;
468     }
469     
470   if((write(cl->meta_socket, data, len)) < 0)
471     {
472       syslog(LOG_ERR, _("Send failed: %s:%d: %m"), __FILE__, __LINE__);
473       return -1;
474     }
475 cp
476   return 0;
477 }
478
479 int send_ping(conn_list_t *cl)
480 {
481 cp
482   if(debug_lvl > 1)
483     syslog(LOG_DEBUG, _("Sending PING to %s (%s)"),
484            cl->vpn_hostname, cl->real_hostname);
485
486   buflen = snprintf(buffer, MAXBUFSIZE, "%d\n", PING);
487
488   if((write(cl->meta_socket, buffer, buflen)) < 0)
489     {
490       syslog(LOG_ERR, _("Send failed: %s:%d: %m"), __FILE__, __LINE__);
491       return -1;
492     }
493 cp
494   return 0;
495 }
496
497 int send_pong(conn_list_t *cl)
498 {
499 cp
500   if(debug_lvl > 1)
501     syslog(LOG_DEBUG, _("Sending PONG to %s (%s)"),
502            cl->vpn_hostname, cl->real_hostname);
503
504   buflen = snprintf(buffer, MAXBUFSIZE, "%d\n", PONG);
505
506   if((write(cl->meta_socket, buffer, buflen)) < 0)
507     {
508       syslog(LOG_ERR, _("Send failed: %s:%d: %m"), __FILE__, __LINE__);
509       return -1;
510     }
511 cp
512   return 0;
513 }
514
515 int send_add_host(conn_list_t *cl, conn_list_t *new_host)
516 {
517   ip_t real_ip;
518   int flags;
519   char *hostname;
520 cp
521   real_ip = new_host->real_ip;
522   hostname = new_host->real_hostname;
523   flags = new_host->flags;
524   
525   /* If we need to propagate information about a new host that wants us to export
526    * it's indirectdata flag, we set the INDIRECTDATA flag and unset the EXPORT...
527    * flag, and set it's real_ip to our vpn_ip, so that net.c send_packet() will
528    * work correctly.
529    */
530      
531   if(flags & EXPORTINDIRECTDATA)
532     {
533       flags &= ~EXPORTINDIRECTDATA;
534       flags |= INDIRECTDATA;
535       real_ip = myself->vpn_ip;
536       hostname = myself->real_hostname;
537     }
538
539   if(debug_lvl > 1)
540     syslog(LOG_DEBUG, _("Sending ADD_HOST for %s (%s) to %s (%s)"),
541            new_host->vpn_hostname, hostname, cl->vpn_hostname, cl->real_hostname);
542
543   buflen = snprintf(buffer, MAXBUFSIZE, "%d %lx %lx/%lx:%x %d\n", ADD_HOST, real_ip, new_host->vpn_ip, new_host->vpn_mask, new_host->port, flags);
544
545   if((write(cl->meta_socket, buffer, buflen)) < 0)
546     {
547       syslog(LOG_ERR, _("Send failed: %s:%d: %m"), __FILE__, __LINE__);
548       return -1;
549     }
550 cp
551   return 0;
552 }
553
554 int send_key_changed(conn_list_t *cl, conn_list_t *src)
555 {
556 cp
557   if(debug_lvl > 1)
558     syslog(LOG_DEBUG, _("Sending KEY_CHANGED origin %s to %s (%s)"),
559            src->vpn_hostname, cl->vpn_hostname, cl->real_hostname);
560
561   buflen = snprintf(buffer, MAXBUFSIZE, "%d %lx\n", KEY_CHANGED, src->vpn_ip);
562
563   if((write(cl->meta_socket, buffer, buflen)) < 0)
564     {
565       syslog(LOG_ERR, _("Send failed: %s:%d: %m"), __FILE__, __LINE__);
566       return -1;
567     }
568 cp
569   return 0;
570 }
571
572 void send_key_changed_all(void)
573 {
574   conn_list_t *p;
575 cp
576   for(p = conn_list; p != NULL; p = p->next)
577     if(p->status.meta && p->status.active)
578       send_key_changed(p, myself);
579 cp
580 }
581
582
583 int send_key_request(ip_t to)
584 {
585   conn_list_t *fw;
586 cp
587   fw = lookup_conn(to);
588   if(!fw)
589     {
590       syslog(LOG_ERR, _("Attempting to send REQ_KEY to %d.%d.%d.%d, which does not exist?"),
591              IP_ADDR_V(to));
592       return -1;
593     }
594
595   if(debug_lvl > 1)
596     syslog(LOG_DEBUG, _("Sending REQ_KEY to %s (%s)"),
597            fw->nexthop->vpn_hostname, fw->nexthop->real_hostname);
598
599   buflen = snprintf(buffer, MAXBUFSIZE, "%d %lx %lx\n", REQ_KEY, to, myself->vpn_ip);
600
601   if((write(fw->nexthop->meta_socket, buffer, buflen)) < 0)
602     {
603       syslog(LOG_ERR, _("Send failed: %s:%d: %m"), __FILE__, __LINE__);
604       return -1;
605     }
606   fw->status.waitingforkey = 1;
607 cp
608   return 0;
609 }
610
611 int send_key_answer(conn_list_t *cl, ip_t to)
612 {
613   conn_list_t *fw;
614 cp
615
616   fw = lookup_conn(to);
617   
618   if(!fw)
619     {
620       syslog(LOG_ERR, _("Attempting to send ANS_KEY to %d.%d.%d.%d, which does not exist?"),
621              IP_ADDR_V(to));
622       return -1;
623     }
624
625  if(debug_lvl > 1)
626     syslog(LOG_DEBUG, _("Sending ANS_KEY to %s (%s)"),
627            fw->nexthop->vpn_hostname, fw->nexthop->real_hostname);
628
629   buflen = snprintf(buffer, MAXBUFSIZE, "%d %lx %lx %d %s\n", ANS_KEY, to, myself->vpn_ip, my_key_expiry, my_public_key_base36);
630
631   if((write(fw->nexthop->meta_socket, buffer, buflen)) < 0)
632     {
633       syslog(LOG_ERR, _("Send failed: %s:%d: %m"), __FILE__, __LINE__);
634       return -1;
635     }
636 cp
637   return 0;
638 }
639
640 /*
641   notify all my direct connections of a new host
642   that was added to the vpn, with the exception
643   of the source of the announcement.
644 */
645 int notify_others(conn_list_t *new, conn_list_t *source,
646                   int (*function)(conn_list_t*, conn_list_t*))
647 {
648   conn_list_t *p;
649 cp
650   for(p = conn_list; p != NULL; p = p->next)
651     if(p != new && p != source && p->status.meta && p->status.active)
652       function(p, new);
653 cp
654   return 0;
655 }
656
657 /*
658   notify one connection of everything
659   i have connected
660 */
661 int notify_one(conn_list_t *new)
662 {
663   conn_list_t *p;
664 cp
665   for(p = conn_list; p != NULL; p = p->next)
666     if(p != new && p->status.active)
667       send_add_host(new, p);
668 cp
669   return 0;
670 }
671
672 /*
673   The incoming request handlers
674 */
675
676
677 int termreq_h(conn_list_t *cl)
678 {
679 cp
680   if(!cl->status.active)
681     {
682       syslog(LOG_ERR, _("Got unauthorized TERMREQ from %s (%s)"),
683               cl->vpn_hostname, cl->real_hostname);
684       return -1;
685     }
686     
687   if(debug_lvl > 1)
688    syslog(LOG_DEBUG, _("Got TERMREQ from %s (%s)"),
689              cl->vpn_hostname, cl->real_hostname);
690   
691   cl->status.termreq = 1;
692
693   terminate_connection(cl);
694 cp
695   return 0;
696 }
697
698 int timeout_h(conn_list_t *cl)
699 {
700 cp
701   if(!cl->status.active)
702     {
703       syslog(LOG_ERR, _("Got unauthorized TIMEOUT from %s (%s)"),
704               cl->vpn_hostname, cl->real_hostname);
705       return -1;
706     }
707
708   if(debug_lvl > 1)
709     syslog(LOG_DEBUG, _("Got TIMEOUT from %s (%s)"),
710               cl->vpn_hostname, cl->real_hostname);
711
712   cl->status.termreq = 1;
713   terminate_connection(cl);
714 cp
715   return 0;
716 }
717
718 int del_host_h(conn_list_t *cl)
719 {
720   ip_t vpn_ip;
721   conn_list_t *fw;
722 cp
723   if(!cl->status.active)
724     {
725       syslog(LOG_ERR, _("Got unauthorized DEL_HOST from %s (%s)"),
726               cl->vpn_hostname, cl->real_hostname);
727       return -1;
728     }
729
730   if(sscanf(cl->buffer, "%*d %lx", &vpn_ip) != 1)
731     {
732        syslog(LOG_ERR, _("Got bad DEL_HOST from %s (%s)"),
733               cl->vpn_hostname, cl->real_hostname);
734        return -1;
735     }  
736
737   if(!(fw = lookup_conn(vpn_ip)))
738     {
739       syslog(LOG_ERR, _("Got DEL_HOST for %d.%d.%d.%d from %s (%s) which does not exist?"),
740              IP_ADDR_V(vpn_ip), cl->vpn_hostname, cl->real_hostname);
741       return 0;
742     }
743
744   /* Connections lists are really messed up if this happens */
745   if(vpn_ip == myself->vpn_ip)
746     {
747       syslog(LOG_ERR, _("Warning: got DEL_HOST from %s (%s) for ourself, restarting"),
748                cl->vpn_hostname, cl->real_hostname);
749       sighup = 1;
750       return 0;
751     }
752
753   if(debug_lvl > 1)
754     syslog(LOG_DEBUG, _("Got DEL_HOST for %s (%s) from %s (%s)"),
755            fw->vpn_hostname, fw->real_hostname, cl->vpn_hostname, cl->real_hostname);
756
757   notify_others(fw, cl, send_del_host);
758
759   fw->status.termreq = 1;
760   fw->status.active = 0;
761
762   terminate_connection(fw);
763 cp
764   return 0;
765 }
766
767 int tcppacket_h(conn_list_t *cl)
768 {
769   int len;
770 cp
771   if(!cl->status.active)
772     {
773       syslog(LOG_ERR, _("Got unauthorized PACKET from %s (%s)"),
774               cl->vpn_hostname, cl->real_hostname);
775       return -1;
776     }
777
778   if(sscanf(cl->buffer, "%*d %d", &len) != 1)
779     {
780        syslog(LOG_ERR, _("Got bad PACKET from %s (%s)"),
781               cl->vpn_hostname, cl->real_hostname);
782        return -1;
783     }  
784
785   if(len > MTU)
786     {
787        syslog(LOG_ERR, _("Got too big PACKET from %s (%s)"),
788               cl->vpn_hostname, cl->real_hostname);
789        return -1;
790     }  
791
792   if(debug_lvl > 3)
793     syslog(LOG_DEBUG, _("Got PACKET length %d from %s (%s)"), len,
794               cl->vpn_hostname, cl->real_hostname);
795
796   cl->tcppacket=len;
797 cp
798   return 0;
799 }
800
801
802 int ping_h(conn_list_t *cl)
803 {
804 cp
805   if(!cl->status.active)
806     {
807       syslog(LOG_ERR, _("Got unauthorized PING from %s (%s)"),
808               cl->vpn_hostname, cl->real_hostname);
809       return -1;
810     }
811
812   if(debug_lvl > 1)
813     syslog(LOG_DEBUG, _("Got PING from %s (%s)"),
814               cl->vpn_hostname, cl->real_hostname);
815
816   cl->status.pinged = 0;
817   cl->status.got_pong = 1;
818
819   send_pong(cl);
820 cp
821   return 0;
822 }
823
824 int pong_h(conn_list_t *cl)
825 {
826 cp
827   if(!cl->status.active)
828     {
829       syslog(LOG_ERR, _("Got unauthorized PONG from %s (%s)"),
830               cl->vpn_hostname, cl->real_hostname);
831       return -1;
832     }
833
834   if(debug_lvl > 1)
835     syslog(LOG_DEBUG, _("Got PONG from %s (%s)"),
836               cl->vpn_hostname, cl->real_hostname);
837
838   cl->status.got_pong = 1;
839 cp
840   return 0;
841 }
842
843 int add_host_h(conn_list_t *cl)
844 {
845   ip_t real_ip;
846   ip_t vpn_ip;
847   ip_t vpn_mask;
848   unsigned short port;
849   int flags;
850   conn_list_t *ncn, *old;
851 cp
852   if(!cl->status.active)
853     {
854       syslog(LOG_ERR, _("Got unauthorized ADD_HOST from %s (%s)"),
855               cl->vpn_hostname, cl->real_hostname);
856       return -1;
857     }
858     
859   if(sscanf(cl->buffer, "%*d %lx %lx/%lx:%hx %d", &real_ip, &vpn_ip, &vpn_mask, &port, &flags) != 5)
860     {
861        syslog(LOG_ERR, _("Got bad ADD_HOST from %s (%s)"),
862               cl->vpn_hostname, cl->real_hostname);
863        return -1;
864     }  
865
866   if((old = lookup_conn(vpn_ip)))
867     {
868       if((real_ip==old->real_ip) && (vpn_mask==old->vpn_mask) && (port==old->port))
869         {
870           if(debug_lvl>1)
871             syslog(LOG_NOTICE, _("Got duplicate ADD_HOST for %s (%s) from %s (%s)"),
872                    old->vpn_hostname, old->real_hostname, cl->vpn_hostname, cl->real_hostname);
873           goto skip_add_host;  /* One goto a day keeps the deeply nested if constructions away. */
874         }
875       else
876         {
877           if(debug_lvl>1)
878             syslog(LOG_NOTICE, _("Removing old entry for %s (%s)"),
879                    old->vpn_hostname, old->real_hostname);
880           old->status.active = 0;
881           terminate_connection(old);
882         }
883     }
884   
885   /* Connections lists are really messed up if this happens */
886   if(vpn_ip == myself->vpn_ip)
887     {
888       syslog(LOG_ERR, _("Warning: got ADD_HOST from %s (%s) for ourself, restarting"),
889                cl->vpn_hostname, cl->real_hostname);
890       sighup = 1;
891       return 0;
892     }
893     
894   ncn = new_conn_list();
895   ncn->real_ip = real_ip;
896   ncn->real_hostname = hostlookup(htonl(real_ip));
897   ncn->vpn_ip = vpn_ip;
898   ncn->vpn_mask = vpn_mask;
899   ncn->vpn_hostname = hostlookup(htonl(vpn_ip));
900   ncn->port = port;
901   ncn->flags = flags;
902   ncn->nexthop = cl;
903   ncn->next = conn_list;
904   conn_list = ncn;
905   ncn->status.active = 1;
906
907   if(debug_lvl > 1)
908     syslog(LOG_DEBUG, _("Got ADD_HOST for %s (%s) from %s (%s)"),
909            ncn->vpn_hostname, ncn->real_hostname, cl->vpn_hostname, cl->real_hostname);
910
911   notify_others(ncn, cl, send_add_host);
912
913 skip_add_host:
914 cp
915   return 0;
916 }
917
918 int req_key_h(conn_list_t *cl)
919 {
920   ip_t to;
921   ip_t from;
922   conn_list_t *fw;
923 cp
924   if(!cl->status.active)
925     {
926       syslog(LOG_ERR, _("Got unauthorized REQ_KEY from %s (%s)"),
927               cl->vpn_hostname, cl->real_hostname);
928       return -1;
929     }
930
931   if(sscanf(cl->buffer, "%*d %lx %lx", &to, &from) != 2)
932     {
933        syslog(LOG_ERR, _("Got bad REQ_KEY from %s (%s)"),
934               cl->vpn_hostname, cl->real_hostname);
935        return -1;
936     }  
937
938   if(debug_lvl > 1)
939     syslog(LOG_DEBUG, _("Got REQ_KEY origin %d.%d.%d.%d destination %d.%d.%d.%d from %s (%s)"),
940            IP_ADDR_V(from), IP_ADDR_V(to), cl->vpn_hostname, cl->real_hostname);
941
942   if((to & myself->vpn_mask) == (myself->vpn_ip & myself->vpn_mask))
943     {  /* hey! they want something from ME! :) */
944       send_key_answer(cl, from);
945       return 0;
946     }
947
948   fw = lookup_conn(to);
949   
950   if(!fw)
951     {
952       syslog(LOG_ERR, _("Attempting to forward REQ_KEY to %d.%d.%d.%d, which does not exist?"),
953              IP_ADDR_V(to));
954       return -1;
955     }
956
957   if(debug_lvl > 1)
958     syslog(LOG_DEBUG, _("Forwarding REQ_KEY to %s (%s)"),
959            fw->nexthop->vpn_hostname, fw->nexthop->real_hostname);
960   
961   cl->buffer[cl->reqlen-1] = '\n';
962   
963   if(write(fw->nexthop->meta_socket, cl->buffer, cl->reqlen) < 0)
964     {
965       syslog(LOG_ERR, _("Send failed: %s:%d: %m"), __FILE__, __LINE__);
966       return -1;
967     }
968 cp
969   return 0;
970 }
971
972 void set_keys(conn_list_t *cl, int expiry, char *key)
973 {
974   char *ek;
975 cp
976   if(!cl->public_key)
977     {
978       cl->public_key = xmalloc(sizeof(*cl->key));
979       cl->public_key->key = NULL;
980     }
981     
982   if(cl->public_key->key)
983     free(cl->public_key->key);
984   cl->public_key->length = strlen(key);
985   cl->public_key->expiry = expiry;
986   cl->public_key->key = xmalloc(cl->public_key->length + 1);
987   strcpy(cl->public_key->key, key);
988
989   ek = make_shared_key(key);
990   
991   if(!cl->key)
992     {
993       cl->key = xmalloc(sizeof(*cl->key));
994       cl->key->key = NULL;
995     }
996
997   if(cl->key->key)
998     free(cl->key->key);
999
1000   cl->key->length = strlen(ek);
1001   cl->key->expiry = expiry;
1002   cl->key->key = xmalloc(cl->key->length + 1);
1003   strcpy(cl->key->key, ek);
1004 cp
1005 }
1006
1007 int ans_key_h(conn_list_t *cl)
1008 {
1009   ip_t to;
1010   ip_t from;
1011   int expiry;
1012   char *key;
1013   conn_list_t *fw, *gk;
1014 cp
1015   if(!cl->status.active)
1016     {
1017       syslog(LOG_ERR, _("Got unauthorized ANS_KEY from %s (%s)"),
1018               cl->vpn_hostname, cl->real_hostname);
1019       return -1;
1020     }
1021
1022   if(sscanf(cl->buffer, "%*d %lx %lx %d %as", &to, &from, &expiry, &key) != 4)
1023     {
1024        syslog(LOG_ERR, _("Got bad ANS_KEY from %s (%s)"),
1025               cl->vpn_hostname, cl->real_hostname);
1026        return -1;
1027     }  
1028
1029   if(debug_lvl > 1)
1030     syslog(LOG_DEBUG, _("Got ANS_KEY origin %d.%d.%d.%d destination %d.%d.%d.%d from %s (%s)"),
1031             IP_ADDR_V(from), IP_ADDR_V(to), cl->vpn_hostname, cl->real_hostname);
1032
1033   if(to == myself->vpn_ip)
1034     {  /* hey! that key's for ME! :) */
1035       gk = lookup_conn(from);
1036
1037       if(!gk)
1038         {
1039           syslog(LOG_ERR, _("Receiving ANS_KEY origin %d.%d.%d.%d from %s (%s), which does not exist?"),
1040                  IP_ADDR_V(from), cl->vpn_hostname, cl->real_hostname);
1041           return -1;
1042         }
1043
1044       set_keys(gk, expiry, key);
1045       gk->status.validkey = 1;
1046       gk->status.waitingforkey = 0;
1047       flush_queues(gk);
1048       return 0;
1049     }
1050
1051   fw = lookup_conn(to);
1052   
1053   if(!fw)
1054     {
1055       syslog(LOG_ERR, _("Attempting to forward ANS_KEY to %d.%d.%d.%d, which does not exist?"),
1056              IP_ADDR_V(to));
1057       return -1;
1058     }
1059
1060   if(debug_lvl > 1)
1061     syslog(LOG_DEBUG, _("Forwarding ANS_KEY to %s (%s)"),
1062            fw->nexthop->vpn_hostname, fw->nexthop->real_hostname);
1063
1064   cl->buffer[cl->reqlen-1] = '\n';
1065
1066   if((write(fw->nexthop->meta_socket, cl->buffer, cl->reqlen)) < 0)
1067     {
1068       syslog(LOG_ERR, _("Send failed: %s:%d: %m"), __FILE__, __LINE__);
1069       return -1;
1070     }
1071 cp
1072   return 0;
1073 }
1074
1075 int key_changed_h(conn_list_t *cl)
1076 {
1077   ip_t from;
1078   conn_list_t *ik;
1079 cp
1080   if(!cl->status.active)
1081     {
1082       syslog(LOG_ERR, _("Got unauthorized KEY_CHANGED from %s (%s)"),
1083               cl->vpn_hostname, cl->real_hostname);
1084       return -1;
1085     }
1086
1087   if(sscanf(cl->buffer, "%*d %lx", &from) != 1)
1088     {
1089        syslog(LOG_ERR, _("Got bad KEY_CHANGED from %s (%s)"),
1090               cl->vpn_hostname, cl->real_hostname);
1091        return -1;
1092     }  
1093
1094   ik = lookup_conn(from);
1095
1096   if(!ik)
1097     {
1098       syslog(LOG_ERR, _("Got KEY_CHANGED origin %d.%d.%d.%d from %s (%s), which does not exist?"),
1099              IP_ADDR_V(from), cl->vpn_hostname, cl->real_hostname);
1100       return -1;
1101     }
1102
1103   if(debug_lvl > 1)
1104     syslog(LOG_DEBUG, _("Got KEY_CHANGED origin %s from %s (%s)"),
1105             ik->vpn_hostname, cl->vpn_hostname, cl->real_hostname);
1106
1107   ik->status.validkey = 0;
1108   ik->status.waitingforkey = 0;
1109
1110   notify_others(ik, cl, send_key_changed);
1111 cp
1112   return 0;
1113 }
1114
1115 /* "Complete overhaul". */
1116
1117 int (*request_handlers[6])(conn_list_t*) = {
1118   id_h, challenge_h, chal_reply_h, ack_h,
1119   status_h, error_h,
1120 };
1121
1122 char (*request_name[6]) = {
1123   "ID", "CHALLENGE", "CHAL_REPLY", "ACK",
1124   "STATUS", "ERROR",
1125 };