- doc
[oweals/gnunet.git] / src / cadet / gnunet-service-cadet_tunnel.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2013 GNUnet e.V.
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 #include "platform.h"
22 #include "gnunet_util_lib.h"
23
24 #include "gnunet_signatures.h"
25 #include "gnunet_statistics_service.h"
26
27 #include "cadet_protocol.h"
28 #include "cadet_path.h"
29
30 #include "gnunet-service-cadet_tunnel.h"
31 #include "gnunet-service-cadet_connection.h"
32 #include "gnunet-service-cadet_channel.h"
33 #include "gnunet-service-cadet_peer.h"
34
35 #define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__)
36 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
37
38 #define REKEY_WAIT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5)
39
40 #if !defined(GNUNET_CULL_LOGGING)
41 #define DUMP_KEYS_TO_STDERR GNUNET_YES
42 #else
43 #define DUMP_KEYS_TO_STDERR GNUNET_YES
44 #endif
45
46 #define MIN_TUNNEL_BUFFER       8
47 #define MAX_TUNNEL_BUFFER       64
48 #define MAX_SKIPPED_KEYS        64
49 #define MAX_KEY_GAP             256
50 #define AX_HEADER_SIZE (sizeof (uint32_t) * 2\
51                         + sizeof (struct GNUNET_CRYPTO_EcdhePublicKey))
52
53
54 /******************************************************************************/
55 /********************************   STRUCTS  **********************************/
56 /******************************************************************************/
57
58 struct CadetTChannel
59 {
60   struct CadetTChannel *next;
61   struct CadetTChannel *prev;
62   struct CadetChannel *ch;
63 };
64
65
66 /**
67  * Connection list and metadata.
68  */
69 struct CadetTConnection
70 {
71   /**
72    * Next in DLL.
73    */
74   struct CadetTConnection *next;
75
76   /**
77    * Prev in DLL.
78    */
79   struct CadetTConnection *prev;
80
81   /**
82    * Connection handle.
83    */
84   struct CadetConnection *c;
85
86   /**
87    * Creation time, to keep oldest connection alive.
88    */
89   struct GNUNET_TIME_Absolute created;
90
91   /**
92    * Connection throughput, to keep fastest connection alive.
93    */
94   uint32_t throughput;
95 };
96
97
98 /**
99  * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
100  */
101 struct CadetTunnelSkippedKey
102 {
103   /**
104    * DLL next.
105    */
106   struct CadetTunnelSkippedKey *next;
107
108   /**
109    * DLL prev.
110    */
111   struct CadetTunnelSkippedKey *prev;
112
113   /**
114    * When was this key stored (for timeout).
115    */
116   struct GNUNET_TIME_Absolute timestamp;
117
118   /**
119    * Header key.
120    */
121   struct GNUNET_CRYPTO_SymmetricSessionKey HK;
122
123   /**
124    * Message key.
125    */
126   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
127
128   /**
129    * Key number for a given HK.
130    */
131   unsigned int Kn;
132 };
133
134
135 /**
136  * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
137  */
138 struct CadetTunnelAxolotl
139 {
140   /**
141    * A (double linked) list of stored message keys and associated header keys
142    * for "skipped" messages, i.e. messages that have not been
143    * received despite the reception of more recent messages, (head).
144    */
145   struct CadetTunnelSkippedKey *skipped_head;
146
147   /**
148    * Skipped messages' keys DLL, tail.
149    */
150   struct CadetTunnelSkippedKey *skipped_tail;
151
152   /**
153    * Elements in @a skipped_head <-> @a skipped_tail.
154    */
155   unsigned int skipped;
156
157   /**
158    * 32-byte root key which gets updated by DH ratchet.
159    */
160   struct GNUNET_CRYPTO_SymmetricSessionKey RK;
161
162   /**
163    * 32-byte header key (send).
164    */
165   struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
166
167   /**
168    * 32-byte header key (recv)
169    */
170   struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
171
172   /**
173    * 32-byte next header key (send).
174    */
175   struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
176
177   /**
178    * 32-byte next header key (recv).
179    */
180   struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
181
182   /**
183    * 32-byte chain keys (used for forward-secrecy updating, send).
184    */
185   struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
186
187   /**
188    * 32-byte chain keys (used for forward-secrecy updating, recv).
189    */
190   struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
191
192   /**
193    * ECDH for key exchange (A0 / B0).
194    */
195   struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
196
197   /**
198    * ECDH Ratchet key (send).
199    */
200   struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
201
202   /**
203    * ECDH Ratchet key (recv).
204    */
205   struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
206
207   /**
208    * Message number (reset to 0 with each new ratchet, next message to send).
209    */
210   uint32_t Ns;
211
212   /**
213    * Message number (reset to 0 with each new ratchet, next message to recv).
214    */
215   uint32_t Nr;
216
217   /**
218    * Previous message numbers (# of msgs sent under prev ratchet)
219    */
220   uint32_t PNs;
221
222   /**
223    * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
224    */
225   int ratchet_flag;
226
227   /**
228    * Number of messages recieved since our last ratchet advance.
229    * - If this counter = 0, we cannot send a new ratchet key in next msg.
230    * - If this counter > 0, we can (but don't yet have to) send a new key.
231    */
232   unsigned int ratchet_allowed;
233
234   /**
235    * Number of messages recieved since our last ratchet advance.
236    * - If this counter = 0, we cannot send a new ratchet key in next msg.
237    * - If this counter > 0, we can (but don't yet have to) send a new key.
238    */
239   unsigned int ratchet_counter;
240
241   /**
242    * When does this ratchet expire and a new one is triggered.
243    */
244   struct GNUNET_TIME_Absolute ratchet_expiration;
245 };
246
247 /**
248  * Struct containing all information regarding a tunnel to a peer.
249  */
250 struct CadetTunnel
251 {
252   /**
253    * Endpoint of the tunnel.
254    */
255   struct CadetPeer *peer;
256
257   /**
258    * Axolotl info.
259    */
260   struct CadetTunnelAxolotl *ax;
261
262   /**
263    * State of the tunnel connectivity.
264    */
265   enum CadetTunnelCState cstate;
266
267   /**
268    * State of the tunnel encryption.
269    */
270   enum CadetTunnelEState estate;
271
272   /**
273    * Peer's ephemeral key, to recreate @c e_key and @c d_key when own ephemeral
274    * key changes.
275    */
276   struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
277
278   /**
279    * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
280    */
281   struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
282
283   /**
284    * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
285    */
286   struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
287
288   /**
289    * Task to start the rekey process.
290    */
291   struct GNUNET_SCHEDULER_Task *rekey_task;
292
293   /**
294    * Paths that are actively used to reach the destination peer.
295    */
296   struct CadetTConnection *connection_head;
297   struct CadetTConnection *connection_tail;
298
299   /**
300    * Next connection number.
301    */
302   uint32_t next_cid;
303
304   /**
305    * Channels inside this tunnel.
306    */
307   struct CadetTChannel *channel_head;
308   struct CadetTChannel *channel_tail;
309
310   /**
311    * Channel ID for the next created channel.
312    */
313   CADET_ChannelNumber next_chid;
314
315   /**
316    * Destroy flag: if true, destroy on last message.
317    */
318   struct GNUNET_SCHEDULER_Task * destroy_task;
319
320   /**
321    * Queued messages, to transmit once tunnel gets connected.
322    */
323   struct CadetTunnelDelayed *tq_head;
324   struct CadetTunnelDelayed *tq_tail;
325
326   /**
327    * Task to trim connections if too many are present.
328    */
329   struct GNUNET_SCHEDULER_Task * trim_connections_task;
330
331   /**
332    * Ephemeral message in the queue (to avoid queueing more than one).
333    */
334   struct CadetConnectionQueue *ephm_h;
335
336   /**
337    * Pong message in the queue.
338    */
339   struct CadetConnectionQueue *pong_h;
340 };
341
342
343 /**
344  * Struct used to save messages in a non-ready tunnel to send once connected.
345  */
346 struct CadetTunnelDelayed
347 {
348   /**
349    * DLL
350    */
351   struct CadetTunnelDelayed *next;
352   struct CadetTunnelDelayed *prev;
353
354   /**
355    * Tunnel.
356    */
357   struct CadetTunnel *t;
358
359   /**
360    * Tunnel queue given to the channel to cancel request. Update on send_queued.
361    */
362   struct CadetTunnelQueue *tq;
363
364   /**
365    * Message to send.
366    */
367   /* struct GNUNET_MessageHeader *msg; */
368 };
369
370
371 /**
372  * Handle for messages queued but not yet sent.
373  */
374 struct CadetTunnelQueue
375 {
376   /**
377    * Connection queue handle, to cancel if necessary.
378    */
379   struct CadetConnectionQueue *cq;
380
381   /**
382    * Handle in case message hasn't been given to a connection yet.
383    */
384   struct CadetTunnelDelayed *tqd;
385
386   /**
387    * Continuation to call once sent.
388    */
389   GCT_sent cont;
390
391   /**
392    * Closure for @c cont.
393    */
394   void *cont_cls;
395 };
396
397
398 /******************************************************************************/
399 /*******************************   GLOBALS  ***********************************/
400 /******************************************************************************/
401
402 /**
403  * Global handle to the statistics service.
404  */
405 extern struct GNUNET_STATISTICS_Handle *stats;
406
407 /**
408  * Local peer own ID (memory efficient handle).
409  */
410 extern GNUNET_PEER_Id myid;
411
412 /**
413  * Local peer own ID (full value).
414  */
415 extern struct GNUNET_PeerIdentity my_full_id;
416
417
418 /**
419  * Don't try to recover tunnels if shutting down.
420  */
421 extern int shutting_down;
422
423
424 /**
425  * Set of all tunnels, in order to trigger a new exchange on rekey.
426  * Indexed by peer's ID.
427  */
428 static struct GNUNET_CONTAINER_MultiPeerMap *tunnels;
429
430 /**
431  * Own Peer ID private key.
432  */
433 const static struct GNUNET_CRYPTO_EddsaPrivateKey *id_key;
434
435
436 /********************************  AXOLOTL ************************************/
437
438 /**
439  * How many messages are needed to trigger a ratchet advance.
440  */
441 static unsigned long long ratchet_messages;
442
443 /**
444  * How long until we trigger a ratched advance.
445  */
446 static struct GNUNET_TIME_Relative ratchet_time;
447
448
449 /******************************************************************************/
450 /********************************   STATIC  ***********************************/
451 /******************************************************************************/
452
453 /**
454  * Get string description for tunnel connectivity state.
455  *
456  * @param cs Tunnel state.
457  *
458  * @return String representation.
459  */
460 static const char *
461 cstate2s (enum CadetTunnelCState cs)
462 {
463   static char buf[32];
464
465   switch (cs)
466   {
467     case CADET_TUNNEL_NEW:
468       return "CADET_TUNNEL_NEW";
469     case CADET_TUNNEL_SEARCHING:
470       return "CADET_TUNNEL_SEARCHING";
471     case CADET_TUNNEL_WAITING:
472       return "CADET_TUNNEL_WAITING";
473     case CADET_TUNNEL_READY:
474       return "CADET_TUNNEL_READY";
475     case CADET_TUNNEL_SHUTDOWN:
476       return "CADET_TUNNEL_SHUTDOWN";
477     default:
478       SPRINTF (buf, "%u (UNKNOWN STATE)", cs);
479       return buf;
480   }
481   return "";
482 }
483
484
485 /**
486  * Get string description for tunnel encryption state.
487  *
488  * @param es Tunnel state.
489  *
490  * @return String representation.
491  */
492 static const char *
493 estate2s (enum CadetTunnelEState es)
494 {
495   static char buf[32];
496
497   switch (es)
498   {
499     case CADET_TUNNEL_KEY_UNINITIALIZED:
500       return "CADET_TUNNEL_KEY_UNINITIALIZED";
501     case CADET_TUNNEL_KEY_SENT:
502       return "CADET_TUNNEL_KEY_SENT";
503     case CADET_TUNNEL_KEY_PING:
504       return "CADET_TUNNEL_KEY_PING";
505     case CADET_TUNNEL_KEY_OK:
506       return "CADET_TUNNEL_KEY_OK";
507     case CADET_TUNNEL_KEY_REKEY:
508       return "CADET_TUNNEL_KEY_REKEY";
509     default:
510       SPRINTF (buf, "%u (UNKNOWN STATE)", es);
511       return buf;
512   }
513   return "";
514 }
515
516
517 /**
518  * @brief Check if tunnel is ready to send traffic.
519  *
520  * Tunnel must be connected and with encryption correctly set up.
521  *
522  * @param t Tunnel to check.
523  *
524  * @return #GNUNET_YES if ready, #GNUNET_NO otherwise
525  */
526 static int
527 is_ready (struct CadetTunnel *t)
528 {
529   int ready;
530   int conn_ok;
531   int enc_ok;
532
533   conn_ok = CADET_TUNNEL_READY == t->cstate;
534   enc_ok = CADET_TUNNEL_KEY_OK == t->estate
535            || CADET_TUNNEL_KEY_REKEY == t->estate
536            || CADET_TUNNEL_KEY_PING == t->estate;
537   ready = conn_ok && enc_ok;
538   ready = ready || GCT_is_loopback (t);
539   return ready;
540 }
541
542
543 /**
544  * Get the channel's buffer. ONLY FOR NON-LOOPBACK CHANNELS!!
545  *
546  * @param tch Tunnel's channel handle.
547  *
548  * @return Amount of messages the channel can still buffer towards the client.
549  */
550 static unsigned int
551 get_channel_buffer (const struct CadetTChannel *tch)
552 {
553   int fwd;
554
555   /* If channel is incoming, is terminal in the FWD direction and fwd is YES */
556   fwd = GCCH_is_terminal (tch->ch, GNUNET_YES);
557
558   return GCCH_get_buffer (tch->ch, fwd);
559 }
560
561
562 /**
563  * Get the channel's allowance status.
564  *
565  * @param tch Tunnel's channel handle.
566  *
567  * @return #GNUNET_YES if we allowed the client to send data to us.
568  */
569 static int
570 get_channel_allowed (const struct CadetTChannel *tch)
571 {
572   int fwd;
573
574   /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
575   fwd = GCCH_is_origin (tch->ch, GNUNET_YES);
576
577   return GCCH_get_allowed (tch->ch, fwd);
578 }
579
580
581 /**
582  * Get the connection's buffer.
583  *
584  * @param tc Tunnel's connection handle.
585  *
586  * @return Amount of messages the connection can still buffer.
587  */
588 static unsigned int
589 get_connection_buffer (const struct CadetTConnection *tc)
590 {
591   int fwd;
592
593   /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
594   fwd = GCC_is_origin (tc->c, GNUNET_YES);
595
596   return GCC_get_buffer (tc->c, fwd);
597 }
598
599
600 /**
601  * Get the connection's allowance.
602  *
603  * @param tc Tunnel's connection handle.
604  *
605  * @return Amount of messages we have allowed the next peer to send us.
606  */
607 static unsigned int
608 get_connection_allowed (const struct CadetTConnection *tc)
609 {
610   int fwd;
611
612   /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
613   fwd = GCC_is_origin (tc->c, GNUNET_YES);
614
615   return GCC_get_allowed (tc->c, fwd);
616 }
617
618
619 /**
620  * Create a new Axolotl ephemeral (ratchet) key.
621  *
622  * @param t Tunnel.
623  */
624 static void
625 new_ephemeral (struct CadetTunnel *t)
626 {
627   GNUNET_free_non_null (t->ax->DHRs);
628   t->ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create();
629   #if DUMP_KEYS_TO_STDERR
630   {
631     struct GNUNET_CRYPTO_EcdhePublicKey pub;
632     GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &pub);
633     LOG (GNUNET_ERROR_TYPE_DEBUG, "  new DHRs generated: pub  %s\n",
634         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &pub));
635   }
636   #endif
637 }
638
639
640 /**
641  * Calculate HMAC.
642  *
643  * @param plaintext Content to HMAC.
644  * @param size Size of @c plaintext.
645  * @param iv Initialization vector for the message.
646  * @param key Key to use.
647  * @param hmac[out] Destination to store the HMAC.
648  */
649 static void
650 t_hmac (const void *plaintext, size_t size,
651         uint32_t iv, const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
652         struct GNUNET_CADET_Hash *hmac)
653 {
654   static const char ctx[] = "cadet authentication key";
655   struct GNUNET_CRYPTO_AuthKey auth_key;
656   struct GNUNET_HashCode hash;
657
658 #if DUMP_KEYS_TO_STDERR
659   LOG (GNUNET_ERROR_TYPE_INFO, "  HMAC %u bytes with key %s\n", size,
660        GNUNET_i2s ((struct GNUNET_PeerIdentity *) key));
661 #endif
662   GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
663                                  &iv, sizeof (iv),
664                                  key, sizeof (*key),
665                                  ctx, sizeof (ctx),
666                                  NULL);
667   /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
668   GNUNET_CRYPTO_hmac (&auth_key, plaintext, size, &hash);
669   GNUNET_memcpy (hmac, &hash, sizeof (*hmac));
670 }
671
672
673 /**
674  * Perform a HMAC.
675  *
676  * @param key Key to use.
677  * @param hash[out] Resulting HMAC.
678  * @param source Source key material (data to HMAC).
679  * @param len Length of @a source.
680  */
681 static void
682 t_ax_hmac_hash (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
683                 struct GNUNET_HashCode *hash,
684                 void *source, unsigned int len)
685 {
686   static const char ctx[] = "axolotl HMAC-HASH";
687   struct GNUNET_CRYPTO_AuthKey auth_key;
688
689   GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
690                                  ctx, sizeof (ctx),
691                                  NULL);
692   GNUNET_CRYPTO_hmac (&auth_key, source, len, hash);
693 }
694
695
696 /**
697  * Derive a key from a HMAC-HASH.
698  *
699  * @param key Key to use for the HMAC.
700  * @param out Key to generate.
701  * @param source Source key material (data to HMAC).
702  * @param len Length of @a source.
703  */
704 static void
705 t_hmac_derive_key (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
706                    struct GNUNET_CRYPTO_SymmetricSessionKey *out,
707                    void *source, unsigned int len)
708 {
709   static const char ctx[] = "axolotl derive key";
710   struct GNUNET_HashCode h;
711
712   t_ax_hmac_hash (key, &h, source, len);
713   GNUNET_CRYPTO_kdf (out, sizeof (*out), ctx, sizeof (ctx),
714                      &h, sizeof (h), NULL);
715 }
716
717
718 /**
719  * Encrypt data with the axolotl tunnel key.
720  *
721  * @param t Tunnel whose key to use.
722  * @param dst Destination for the encrypted data.
723  * @param src Source of the plaintext. Can overlap with @c dst.
724  * @param size Size of the plaintext.
725  *
726  * @return Size of the encrypted data.
727  */
728 static int
729 t_ax_encrypt (struct CadetTunnel *t, void *dst, const void *src, size_t size)
730 {
731   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
732   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
733   struct CadetTunnelAxolotl *ax;
734   size_t out_size;
735   struct GNUNET_TIME_Absolute start_time;
736   struct GNUNET_TIME_Relative duration;
737
738   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_ax_encrypt start\n");
739   start_time = GNUNET_TIME_absolute_get ();
740
741   ax = t->ax;
742
743   ax->ratchet_counter++;
744   if (GNUNET_YES == ax->ratchet_allowed
745       && (ratchet_messages <= ax->ratchet_counter
746           || 0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us))
747   {
748     ax->ratchet_flag = GNUNET_YES;
749   }
750
751   if (GNUNET_YES == ax->ratchet_flag)
752   {
753     /* Advance ratchet */
754     struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
755     struct GNUNET_HashCode dh;
756     struct GNUNET_HashCode hmac;
757     static const char ctx[] = "axolotl ratchet";
758
759     new_ephemeral (t);
760     ax->HKs = ax->NHKs;
761
762     /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
763     GNUNET_CRYPTO_ecc_ecdh (ax->DHRs, &ax->DHRr, &dh);
764     t_ax_hmac_hash (&ax->RK, &hmac, &dh, sizeof (dh));
765     GNUNET_CRYPTO_kdf (keys, sizeof (keys), ctx, sizeof (ctx),
766                        &hmac, sizeof (hmac), NULL);
767     ax->RK = keys[0];
768     ax->NHKs = keys[1];
769     ax->CKs = keys[2];
770
771     ax->PNs = ax->Ns;
772     ax->Ns = 0;
773     ax->ratchet_flag = GNUNET_NO;
774     ax->ratchet_allowed = GNUNET_NO;
775     ax->ratchet_counter = 0;
776     ax->ratchet_expiration =
777       GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), ratchet_time);
778   }
779
780   t_hmac_derive_key (&ax->CKs, &MK, "0", 1);
781   GNUNET_CRYPTO_symmetric_derive_iv (&iv, &MK, NULL, 0, NULL);
782
783   #if DUMP_KEYS_TO_STDERR
784   LOG (GNUNET_ERROR_TYPE_DEBUG, "  CKs: %s\n",
785        GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->CKs));
786   LOG (GNUNET_ERROR_TYPE_INFO, "  AX_ENC with key %u: %s\n", ax->Ns,
787        GNUNET_i2s ((struct GNUNET_PeerIdentity *) &MK));
788   #endif
789
790   out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, &MK, &iv, dst);
791
792   t_hmac_derive_key (&ax->CKs, &ax->CKs, "1", 1);
793
794   duration = GNUNET_TIME_absolute_get_duration (start_time);
795   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_ax_encrypt duration %s\n",
796        GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
797   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_ax_encrypt end\n");
798
799   return out_size;
800 }
801
802
803 /**
804  * Decrypt data with the axolotl tunnel key.
805  *
806  * @param t Tunnel whose key to use.
807  * @param dst Destination for the decrypted data.
808  * @param src Source of the ciphertext. Can overlap with @c dst.
809  * @param size Size of the ciphertext.
810  *
811  * @return Size of the decrypted data.
812  */
813 static int
814 t_ax_decrypt (struct CadetTunnel *t, void *dst, const void *src, size_t size)
815 {
816   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
817   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
818   struct CadetTunnelAxolotl *ax;
819   size_t out_size;
820
821   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_ax_decrypt start\n");
822
823   ax = t->ax;
824
825   t_hmac_derive_key (&ax->CKr, &MK, "0", 1);
826   GNUNET_CRYPTO_symmetric_derive_iv (&iv, &MK, NULL, 0, NULL);
827
828   #if DUMP_KEYS_TO_STDERR
829   LOG (GNUNET_ERROR_TYPE_DEBUG, "  CKr: %s\n",
830        GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->CKr));
831   LOG (GNUNET_ERROR_TYPE_INFO, "  AX_DEC with key %u: %s\n", ax->Nr,
832        GNUNET_i2s ((struct GNUNET_PeerIdentity *) &MK));
833   #endif
834
835   GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
836   out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, &MK, &iv, dst);
837   GNUNET_assert (out_size == size);
838
839   t_hmac_derive_key (&ax->CKr, &ax->CKr, "1", 1);
840
841   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_ax_decrypt end\n");
842
843   return out_size;
844 }
845
846
847 /**
848  * Encrypt header with the axolotl header key.
849  *
850  * @param t Tunnel whose key to use.
851  * @param msg Message whose header to encrypt.
852  */
853 static void
854 t_h_encrypt (struct CadetTunnel *t, struct GNUNET_CADET_Encrypted *msg)
855 {
856   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
857   struct CadetTunnelAxolotl *ax;
858   size_t out_size;
859
860   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_h_encrypt start\n");
861
862   ax = t->ax;
863   GNUNET_CRYPTO_symmetric_derive_iv (&iv, &ax->HKs, NULL, 0, NULL);
864
865   #if DUMP_KEYS_TO_STDERR
866   LOG (GNUNET_ERROR_TYPE_INFO, "  AX_ENC_H with key %s\n",
867        GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->HKs));
868   #endif
869
870   out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->Ns, AX_HEADER_SIZE,
871                                               &ax->HKs, &iv, &msg->Ns);
872
873   GNUNET_assert (AX_HEADER_SIZE == out_size);
874
875   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_ax_encrypt end\n");
876 }
877
878
879 /**
880  * Decrypt header with the current axolotl header key.
881  *
882  * @param t Tunnel whose current ax HK to use.
883  * @param src Message whose header to decrypt.
884  * @param dst Where to decrypt header to.
885  */
886 static void
887 t_h_decrypt (struct CadetTunnel *t, const struct GNUNET_CADET_Encrypted *src,
888              struct GNUNET_CADET_Encrypted *dst)
889 {
890   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
891   struct CadetTunnelAxolotl *ax;
892   size_t out_size;
893
894   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_h_decrypt start\n");
895
896   ax = t->ax;
897   GNUNET_CRYPTO_symmetric_derive_iv (&iv, &ax->HKr, NULL, 0, NULL);
898
899   #if DUMP_KEYS_TO_STDERR
900   LOG (GNUNET_ERROR_TYPE_INFO, "  AX_DEC_H with key %s\n",
901        GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->HKr));
902   #endif
903
904   out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns, AX_HEADER_SIZE,
905                                               &ax->HKr, &iv, &dst->Ns);
906
907   GNUNET_assert (AX_HEADER_SIZE == out_size);
908
909   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_h_decrypt end\n");
910 }
911
912
913 /**
914  * Decrypt and verify data with the appropriate tunnel key and verify that the
915  * data has not been altered since it was sent by the remote peer.
916  *
917  * @param t Tunnel whose key to use.
918  * @param dst Destination for the plaintext.
919  * @param src Source of the message. Can overlap with @c dst.
920  * @param size Size of the message.
921  *
922  * @return Size of the decrypted data, -1 if an error was encountered.
923  */
924 static int
925 try_old_ax_keys (struct CadetTunnel *t, void *dst,
926                  const struct GNUNET_CADET_Encrypted *src, size_t size)
927 {
928   struct CadetTunnelSkippedKey *key;
929   struct GNUNET_CADET_Hash *hmac;
930   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
931   struct GNUNET_CADET_Encrypted plaintext_header;
932   struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
933   size_t esize;
934   size_t res;
935   size_t len;
936   unsigned int N;
937
938   LOG (GNUNET_ERROR_TYPE_DEBUG, "Trying old keys\n");
939   hmac = &plaintext_header.hmac;
940   esize = size - sizeof (struct GNUNET_CADET_Encrypted);
941
942   /* Find a correct Header Key */
943   for (key = t->ax->skipped_head; NULL != key; key = key->next)
944   {
945     #if DUMP_KEYS_TO_STDERR
946     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Trying hmac with key %s\n",
947          GNUNET_i2s ((struct GNUNET_PeerIdentity *) &key->HK));
948     #endif
949     t_hmac (&src->Ns, AX_HEADER_SIZE + esize, 0, &key->HK, hmac);
950     if (0 == memcmp (hmac, &src->hmac, sizeof (*hmac)))
951     {
952       LOG (GNUNET_ERROR_TYPE_DEBUG, "  hmac correct\n");
953       valid_HK = &key->HK;
954       break;
955     }
956   }
957   if (NULL == key)
958     return -1;
959
960   /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
961   GNUNET_assert (size > sizeof (struct GNUNET_CADET_Encrypted));
962   len = size - sizeof (struct GNUNET_CADET_Encrypted);
963   GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
964
965   /* Decrypt header */
966   GNUNET_CRYPTO_symmetric_derive_iv (&iv, &key->HK, NULL, 0, NULL);
967   res = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns, AX_HEADER_SIZE,
968                                          &key->HK, &iv, &plaintext_header.Ns);
969   GNUNET_assert (AX_HEADER_SIZE == res);
970   LOG (GNUNET_ERROR_TYPE_DEBUG, "  Message %u, previous: %u\n",
971        ntohl (plaintext_header.Ns), ntohl (plaintext_header.PNs));
972
973   /* Find the correct Message Key */
974   N = ntohl (plaintext_header.Ns);
975   while (NULL != key && N != key->Kn)
976     key = key->next;
977   if (NULL == key || 0 != memcmp (&key->HK, valid_HK, sizeof (*valid_HK)))
978     return -1;
979
980   #if DUMP_KEYS_TO_STDERR
981   LOG (GNUNET_ERROR_TYPE_INFO, "  AX_DEC_H with skipped key %s\n",
982        GNUNET_i2s ((struct GNUNET_PeerIdentity *) &key->HK));
983   LOG (GNUNET_ERROR_TYPE_INFO, "  AX_DEC with skipped key %u: %s\n",
984        key->Kn, GNUNET_i2s ((struct GNUNET_PeerIdentity *) &key->MK));
985   #endif
986
987   /* Decrypt payload */
988   GNUNET_CRYPTO_symmetric_derive_iv (&iv, &key->MK, NULL, 0, NULL);
989   res = GNUNET_CRYPTO_symmetric_decrypt (&src[1], len, &key->MK, &iv, dst);
990
991   /* Remove key */
992   GNUNET_CONTAINER_DLL_remove (t->ax->skipped_head, t->ax->skipped_tail, key);
993   t->ax->skipped--;
994   GNUNET_free (key); /* GNUNET_free overwrites memory with 0xbaadf00d */
995
996   return res;
997 }
998
999
1000 /**
1001  * Delete a key from the list of skipped keys.
1002  *
1003  * @param t Tunnel to delete from.
1004  * @param HKr Header Key to use.
1005  */
1006 static void
1007 store_skipped_key (struct CadetTunnel *t,
1008                    const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
1009 {
1010   struct CadetTunnelSkippedKey *key;
1011
1012   key = GNUNET_new (struct CadetTunnelSkippedKey);
1013   key->timestamp = GNUNET_TIME_absolute_get ();
1014   key->Kn = t->ax->Nr;
1015   key->HK = t->ax->HKr;
1016   t_hmac_derive_key (&t->ax->CKr, &key->MK, "0", 1);
1017   #if DUMP_KEYS_TO_STDERR
1018   LOG (GNUNET_ERROR_TYPE_DEBUG, "    storing MK for Nr %u: %s\n",
1019        key->Kn, GNUNET_i2s ((struct GNUNET_PeerIdentity *) &key->MK));
1020   LOG (GNUNET_ERROR_TYPE_DEBUG, "    for CKr: %s\n",
1021        GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->ax->CKr));
1022   #endif
1023   t_hmac_derive_key (&t->ax->CKr, &t->ax->CKr, "1", 1);
1024   GNUNET_CONTAINER_DLL_insert (t->ax->skipped_head, t->ax->skipped_tail, key);
1025   t->ax->Nr++;
1026   t->ax->skipped++;
1027 }
1028
1029
1030 /**
1031  * Delete a key from the list of skipped keys.
1032  *
1033  * @param t Tunnel to delete from.
1034  * @param key Key to delete.
1035  */
1036 static void
1037 delete_skipped_key (struct CadetTunnel *t, struct CadetTunnelSkippedKey *key)
1038 {
1039   GNUNET_CONTAINER_DLL_remove (t->ax->skipped_head, t->ax->skipped_tail, key);
1040   GNUNET_free (key);
1041   t->ax->skipped--;
1042 }
1043
1044
1045 /**
1046  * Stage skipped AX keys and calculate the message key.
1047  *
1048  * Stores each HK and MK for skipped messages.
1049  *
1050  * @param t Tunnel where to stage the keys.
1051  * @param HKr Header key.
1052  * @param Np Received meesage number.
1053  *
1054  * @return GNUNET_OK if keys were stored.
1055  *         GNUNET_SYSERR if an error ocurred (Np not expected).
1056  */
1057 static int
1058 store_ax_keys (struct CadetTunnel *t,
1059                const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1060                uint32_t Np)
1061 {
1062   int gap;
1063
1064
1065   gap = Np - t->ax->Nr;
1066   LOG (GNUNET_ERROR_TYPE_INFO, "Storing keys [%u, %u)\n", t->ax->Nr, Np);
1067   if (MAX_KEY_GAP < gap)
1068   {
1069     /* Avoid DoS (forcing peer to do 2*33 chain HMAC operations) */
1070     /* TODO: start new key exchange on return */
1071     GNUNET_break_op (0);
1072     LOG (GNUNET_ERROR_TYPE_WARNING, "Got message %u, expected %u+\n",
1073          Np, t->ax->Nr);
1074     return GNUNET_SYSERR;
1075   }
1076   if (0 > gap)
1077   {
1078     /* Delayed message: don't store keys, flag to try old keys. */
1079     return GNUNET_SYSERR;
1080   }
1081
1082   while (t->ax->Nr < Np)
1083     store_skipped_key (t, HKr);
1084
1085   while (t->ax->skipped > MAX_SKIPPED_KEYS)
1086     delete_skipped_key (t, t->ax->skipped_tail);
1087
1088   return GNUNET_OK;
1089 }
1090
1091
1092 /**
1093  * Decrypt and verify data with the appropriate tunnel key and verify that the
1094  * data has not been altered since it was sent by the remote peer.
1095  *
1096  * @param t Tunnel whose key to use.
1097  * @param dst Destination for the plaintext.
1098  * @param src Source of the message. Can overlap with @c dst.
1099  * @param size Size of the message.
1100  *
1101  * @return Size of the decrypted data, -1 if an error was encountered.
1102  */
1103 static int
1104 t_ax_decrypt_and_validate (struct CadetTunnel *t, void *dst,
1105                            const struct GNUNET_CADET_Encrypted *src,
1106                            size_t size)
1107 {
1108   struct CadetTunnelAxolotl *ax;
1109   struct GNUNET_CADET_Hash msg_hmac;
1110   struct GNUNET_HashCode hmac;
1111   struct GNUNET_CADET_Encrypted plaintext_header;
1112   uint32_t Np;
1113   uint32_t PNp;
1114   size_t esize; /* Size of encryped payload */
1115   size_t osize; /* Size of output (decrypted payload) */
1116
1117   esize = size - sizeof (struct GNUNET_CADET_Encrypted);
1118   ax = t->ax;
1119   if (NULL == ax)
1120     return -1;
1121
1122   /* Try current HK */
1123   t_hmac (&src->Ns, AX_HEADER_SIZE + esize, 0, &ax->HKr, &msg_hmac);
1124   if (0 != memcmp (&msg_hmac, &src->hmac, sizeof (msg_hmac)))
1125   {
1126     static const char ctx[] = "axolotl ratchet";
1127     struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1128     struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1129     struct GNUNET_HashCode dh;
1130     struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1131
1132     /* Try Next HK */
1133     LOG (GNUNET_ERROR_TYPE_DEBUG, "  trying next HK\n");
1134     t_hmac (&src->Ns, AX_HEADER_SIZE + esize, 0, &ax->NHKr, &msg_hmac);
1135     if (0 != memcmp (&msg_hmac, &src->hmac, sizeof (msg_hmac)))
1136     {
1137       /* Try the skipped keys, if that fails, we're out of luck. */
1138       return try_old_ax_keys (t, dst, src, size);
1139     }
1140     LOG (GNUNET_ERROR_TYPE_INFO, "next HK worked\n");
1141
1142     HK = ax->HKr;
1143     ax->HKr = ax->NHKr;
1144     t_h_decrypt (t, src, &plaintext_header);
1145     Np = ntohl (plaintext_header.Ns);
1146     PNp = ntohl (plaintext_header.PNs);
1147     DHRp = &plaintext_header.DHRs;
1148     store_ax_keys (t, &HK, PNp);
1149
1150     /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1151     GNUNET_CRYPTO_ecc_ecdh (ax->DHRs, DHRp, &dh);
1152     t_ax_hmac_hash (&ax->RK, &hmac, &dh, sizeof (dh));
1153     GNUNET_CRYPTO_kdf (keys, sizeof (keys), ctx, sizeof (ctx),
1154                        &hmac, sizeof (hmac), NULL);
1155
1156     /* Commit "purported" keys */
1157     ax->RK = keys[0];
1158     ax->NHKr = keys[1];
1159     ax->CKr = keys[2];
1160     ax->DHRr = *DHRp;
1161     ax->Nr = 0;
1162     ax->ratchet_allowed = GNUNET_YES;
1163   }
1164   else
1165   {
1166     LOG (GNUNET_ERROR_TYPE_DEBUG, "current HK\n");
1167     t_h_decrypt (t, src, &plaintext_header);
1168     Np = ntohl (plaintext_header.Ns);
1169     PNp = ntohl (plaintext_header.PNs);
1170   }
1171   LOG (GNUNET_ERROR_TYPE_INFO, "  got AX Nr %u\n", Np);
1172   if (Np != ax->Nr)
1173     if (GNUNET_OK != store_ax_keys (t, &ax->HKr, Np))
1174       /* Try the skipped keys, if that fails, we're out of luck. */
1175       return try_old_ax_keys (t, dst, src, size);
1176
1177   osize = t_ax_decrypt (t, dst, &src[1], esize);
1178   ax->Nr = Np + 1;
1179
1180   if (osize != esize)
1181   {
1182     GNUNET_break_op (0);
1183     return -1;
1184   }
1185
1186   return osize;
1187 }
1188
1189
1190 /**
1191  * Pick a connection on which send the next data message.
1192  *
1193  * @param t Tunnel on which to send the message.
1194  *
1195  * @return The connection on which to send the next message.
1196  */
1197 static struct CadetConnection *
1198 tunnel_get_connection (struct CadetTunnel *t)
1199 {
1200   struct CadetTConnection *iter;
1201   struct CadetConnection *best;
1202   unsigned int qn;
1203   unsigned int lowest_q;
1204
1205   LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GCT_2s (t));
1206   best = NULL;
1207   lowest_q = UINT_MAX;
1208   for (iter = t->connection_head; NULL != iter; iter = iter->next)
1209   {
1210     LOG (GNUNET_ERROR_TYPE_DEBUG, "  connection %s: %u\n",
1211          GCC_2s (iter->c), GCC_get_state (iter->c));
1212     if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
1213     {
1214       qn = GCC_get_qn (iter->c, GCC_is_origin (iter->c, GNUNET_YES));
1215       LOG (GNUNET_ERROR_TYPE_DEBUG, "    q_n %u, \n", qn);
1216       if (qn < lowest_q)
1217       {
1218         best = iter->c;
1219         lowest_q = qn;
1220       }
1221     }
1222   }
1223   LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GCC_2s (best));
1224   return best;
1225 }
1226
1227
1228 /**
1229  * Callback called when a queued message is sent.
1230  *
1231  * Calculates the average time and connection packet tracking.
1232  *
1233  * @param cls Closure (TunnelQueue handle).
1234  * @param c Connection this message was on.
1235  * @param q Connection queue handle (unused).
1236  * @param type Type of message sent.
1237  * @param fwd Was this a FWD going message?
1238  * @param size Size of the message.
1239  */
1240 static void
1241 tun_message_sent (void *cls,
1242               struct CadetConnection *c,
1243               struct CadetConnectionQueue *q,
1244               uint16_t type, int fwd, size_t size)
1245 {
1246   struct CadetTunnelQueue *qt = cls;
1247   struct CadetTunnel *t;
1248
1249   LOG (GNUNET_ERROR_TYPE_DEBUG, "tun_message_sent\n");
1250
1251   GNUNET_assert (NULL != qt->cont);
1252   t = NULL == c ? NULL : GCC_get_tunnel (c);
1253   qt->cont (qt->cont_cls, t, qt, type, size);
1254   GNUNET_free (qt);
1255 }
1256
1257
1258 static unsigned int
1259 count_queued_data (const struct CadetTunnel *t)
1260 {
1261   struct CadetTunnelDelayed *iter;
1262   unsigned int count;
1263
1264   for (count = 0, iter = t->tq_head; iter != NULL; iter = iter->next)
1265     count++;
1266
1267   return count;
1268 }
1269
1270 /**
1271  * Delete a queued message: either was sent or the channel was destroyed
1272  * before the tunnel's key exchange had a chance to finish.
1273  *
1274  * @param tqd Delayed queue handle.
1275  */
1276 static void
1277 unqueue_data (struct CadetTunnelDelayed *tqd)
1278 {
1279   GNUNET_CONTAINER_DLL_remove (tqd->t->tq_head, tqd->t->tq_tail, tqd);
1280   GNUNET_free (tqd);
1281 }
1282
1283
1284 /**
1285  * Cache a message to be sent once tunnel is online.
1286  *
1287  * @param t Tunnel to hold the message.
1288  * @param msg Message itself (copy will be made).
1289  */
1290 static struct CadetTunnelDelayed *
1291 queue_data (struct CadetTunnel *t, const struct GNUNET_MessageHeader *msg)
1292 {
1293   struct CadetTunnelDelayed *tqd;
1294   uint16_t size = ntohs (msg->size);
1295
1296   LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GCT_2s (t));
1297
1298   GNUNET_assert (GNUNET_NO == is_ready (t));
1299
1300   tqd = GNUNET_malloc (sizeof (struct CadetTunnelDelayed) + size);
1301
1302   tqd->t = t;
1303   GNUNET_memcpy (&tqd[1], msg, size);
1304   GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
1305   return tqd;
1306 }
1307
1308
1309 /**
1310  * Sends an already built message on a tunnel, encrypting it and
1311  * choosing the best connection.
1312  *
1313  * @param message Message to send. Function modifies it.
1314  * @param t Tunnel on which this message is transmitted.
1315  * @param c Connection to use (autoselect if NULL).
1316  * @param force Force the tunnel to take the message (buffer overfill).
1317  * @param cont Continuation to call once message is really sent.
1318  * @param cont_cls Closure for @c cont.
1319  * @param existing_q In case this a transmission of previously queued data,
1320  *                   this should be TunnelQueue given to the client.
1321  *                   Otherwise, NULL.
1322  * @return Handle to cancel message.
1323  *         NULL if @c cont is NULL or an error happens and message is dropped.
1324  */
1325 static struct CadetTunnelQueue *
1326 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1327                        struct CadetTunnel *t,
1328                        struct CadetConnection *c,
1329                        int force,
1330                        GCT_sent cont,
1331                        void *cont_cls,
1332                        struct CadetTunnelQueue *existing_q)
1333 {
1334   struct GNUNET_MessageHeader *msg;
1335   struct GNUNET_CADET_Encrypted *ax_msg;
1336   struct CadetTunnelQueue *tq;
1337   size_t size = ntohs (message->size);
1338   char cbuf[sizeof (struct GNUNET_CADET_Encrypted) + size] GNUNET_ALIGN;
1339   size_t esize;
1340   uint32_t mid;
1341   uint16_t type;
1342   int fwd;
1343
1344   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GCT_2s (t));
1345
1346   if (GNUNET_NO == is_ready (t))
1347   {
1348     struct CadetTunnelDelayed *tqd;
1349     /* A non null existing_q indicates sending of queued data.
1350      * Should only happen after tunnel becomes ready.
1351      */
1352     GNUNET_assert (NULL == existing_q);
1353     tqd = queue_data (t, message);
1354     if (NULL == cont)
1355       return NULL;
1356     tq = GNUNET_new (struct CadetTunnelQueue);
1357     tq->tqd = tqd;
1358     tqd->tq = tq;
1359     tq->cont = cont;
1360     tq->cont_cls = cont_cls;
1361     return tq;
1362   }
1363
1364   GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1365
1366   ax_msg = (struct GNUNET_CADET_Encrypted *) cbuf;
1367   msg = &ax_msg->header;
1368   msg->size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
1369   msg->type = htons (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
1370   esize = t_ax_encrypt (t, &ax_msg[1], message, size);
1371   ax_msg->Ns = htonl (t->ax->Ns++);
1372   ax_msg->PNs = htonl (t->ax->PNs);
1373   GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &ax_msg->DHRs);
1374   t_h_encrypt (t, ax_msg);
1375   t_hmac (&ax_msg->Ns, AX_HEADER_SIZE + esize, 0, &t->ax->HKs, &ax_msg->hmac);
1376   GNUNET_assert (esize == size);
1377
1378   if (NULL == c)
1379     c = tunnel_get_connection (t);
1380   if (NULL == c)
1381   {
1382     /* Why is tunnel 'ready'? Should have been queued! */
1383     if (NULL != t->destroy_task)
1384     {
1385       GNUNET_break (0);
1386       GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1387     }
1388     return NULL; /* Drop... */
1389   }
1390   fwd = GCC_is_origin (c, GNUNET_YES);
1391   ax_msg->cid = *GCC_get_id (c);
1392   ax_msg->pid = htonl (GCC_get_pid (c, fwd));
1393
1394   mid = 0;
1395   type = ntohs (message->type);
1396   switch (type)
1397   {
1398     case GNUNET_MESSAGE_TYPE_CADET_DATA:
1399     case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1400       if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
1401         mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
1402       else
1403         mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
1404       /* Fall thru */
1405     case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1406     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1407     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1408     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1409     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1410       break;
1411     default:
1412       GNUNET_break (0);
1413       LOG (GNUNET_ERROR_TYPE_ERROR, "type %s not valid\n", GC_m2s (type));
1414   }
1415   LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
1416
1417   if (NULL == cont)
1418   {
1419     GNUNET_break (NULL == GCC_send_prebuilt_message (msg, type, mid, c, fwd,
1420                                                      force, NULL, NULL));
1421     return NULL;
1422   }
1423   if (NULL == existing_q)
1424   {
1425     tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
1426   }
1427   else
1428   {
1429     tq = existing_q;
1430     tq->tqd = NULL;
1431   }
1432   tq->cq = GCC_send_prebuilt_message (msg, type, mid, c, fwd, force,
1433                                       &tun_message_sent, tq);
1434   GNUNET_assert (NULL != tq->cq);
1435   tq->cont = cont;
1436   tq->cont_cls = cont_cls;
1437
1438   return tq;
1439 }
1440
1441
1442 /**
1443  * Send all cached messages that we can, tunnel is online.
1444  *
1445  * @param t Tunnel that holds the messages. Cannot be loopback.
1446  */
1447 static void
1448 send_queued_data (struct CadetTunnel *t)
1449 {
1450   struct CadetTunnelDelayed *tqd;
1451   struct CadetTunnelDelayed *next;
1452   unsigned int room;
1453
1454   LOG (GNUNET_ERROR_TYPE_INFO, "Send queued data, tunnel %s\n", GCT_2s (t));
1455
1456   if (GCT_is_loopback (t))
1457   {
1458     GNUNET_break (0);
1459     return;
1460   }
1461
1462   if (GNUNET_NO == is_ready (t))
1463   {
1464     LOG (GNUNET_ERROR_TYPE_WARNING, "  not ready yet: %s/%s\n",
1465          estate2s (t->estate), cstate2s (t->cstate));
1466     return;
1467   }
1468
1469   room = GCT_get_connections_buffer (t);
1470   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer space: %u\n", room);
1471   LOG (GNUNET_ERROR_TYPE_DEBUG, "  tq head: %p\n", t->tq_head);
1472   for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
1473   {
1474     LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
1475     next = tqd->next;
1476     room--;
1477     send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
1478                            tqd->t, NULL, GNUNET_YES,
1479                            NULL != tqd->tq ? tqd->tq->cont : NULL,
1480                            NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
1481                            tqd->tq);
1482     unqueue_data (tqd);
1483   }
1484   LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
1485 }
1486
1487
1488 /**
1489  * @brief Resend the KX until we complete the handshake.
1490  *
1491  * @param cls Closure (tunnel).
1492  */
1493 static void
1494 kx_resend (void *cls)
1495 {
1496   struct CadetTunnel *t = cls;
1497
1498   t->rekey_task = NULL;
1499   if (CADET_TUNNEL_KEY_OK == t->estate)
1500   {
1501     /* Should have been canceled on estate change */
1502     GNUNET_break (0);
1503     return;
1504   }
1505
1506   GCT_send_kx (t, CADET_TUNNEL_KEY_SENT >= t->estate);
1507 }
1508
1509
1510 /**
1511  * Callback called when a queued message is sent.
1512  *
1513  * @param cls Closure.
1514  * @param c Connection this message was on.
1515  * @param type Type of message sent.
1516  * @param fwd Was this a FWD going message?
1517  * @param size Size of the message.
1518  */
1519 static void
1520 ephm_sent (void *cls,
1521            struct CadetConnection *c,
1522            struct CadetConnectionQueue *q,
1523            uint16_t type, int fwd, size_t size)
1524 {
1525   struct CadetTunnel *t = cls;
1526   LOG (GNUNET_ERROR_TYPE_DEBUG, "ephemeral sent %s\n", GC_m2s (type));
1527
1528   t->ephm_h = NULL;
1529
1530   if (CADET_TUNNEL_KEY_OK == t->estate)
1531     return;
1532
1533   if (NULL != t->rekey_task)
1534   {
1535     GNUNET_break (0);
1536     GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1537     GNUNET_SCHEDULER_cancel (t->rekey_task);
1538   }
1539   t->rekey_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
1540                                                 &kx_resend, t);
1541
1542 }
1543
1544
1545 /**
1546  * Called only on shutdown, destroy every tunnel.
1547  *
1548  * @param cls Closure (unused).
1549  * @param key Current public key.
1550  * @param value Value in the hash map (tunnel).
1551  *
1552  * @return #GNUNET_YES, so we should continue to iterate,
1553  */
1554 static int
1555 destroy_iterator (void *cls,
1556                 const struct GNUNET_PeerIdentity *key,
1557                 void *value)
1558 {
1559   struct CadetTunnel *t = value;
1560
1561   LOG (GNUNET_ERROR_TYPE_DEBUG,
1562        "GCT_shutdown destroying tunnel at %p\n", t);
1563   GCT_destroy (t);
1564   return GNUNET_YES;
1565 }
1566
1567
1568 /**
1569  * Notify remote peer that we don't know a channel he is talking about,
1570  * probably CHANNEL_DESTROY was missed.
1571  *
1572  * @param t Tunnel on which to notify.
1573  * @param gid ID of the channel.
1574  */
1575 static void
1576 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
1577 {
1578   struct GNUNET_CADET_ChannelManage msg;
1579
1580   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
1581   msg.header.size = htons (sizeof (msg));
1582   msg.chid = htonl (gid);
1583
1584   LOG (GNUNET_ERROR_TYPE_DEBUG,
1585        "WARNING destroying unknown channel %u on tunnel %s\n",
1586        gid, GCT_2s (t));
1587   send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
1588 }
1589
1590
1591 /**
1592  * Demultiplex data per channel and call appropriate channel handler.
1593  *
1594  * @param t Tunnel on which the data came.
1595  * @param msg Data message.
1596  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1597  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1598  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1599  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1600  */
1601 static void
1602 handle_data (struct CadetTunnel *t,
1603              const struct GNUNET_CADET_Data *msg,
1604              int fwd)
1605 {
1606   struct CadetChannel *ch;
1607   char buf[128];
1608   size_t size;
1609   uint16_t type;
1610
1611   /* Check size */
1612   size = ntohs (msg->header.size);
1613   if (size <
1614       sizeof (struct GNUNET_CADET_Data) +
1615       sizeof (struct GNUNET_MessageHeader))
1616   {
1617     GNUNET_break (0);
1618     return;
1619   }
1620   type = ntohs (msg[1].header.type);
1621   LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n", GC_m2s (type));
1622   SPRINTF (buf, "# received payload of type %hu", type);
1623   GNUNET_STATISTICS_update (stats, buf, 1, GNUNET_NO);
1624
1625
1626   /* Check channel */
1627   ch = GCT_get_channel (t, ntohl (msg->chid));
1628   if (NULL == ch)
1629   {
1630     GNUNET_STATISTICS_update (stats, "# data on unknown channel",
1631                               1, GNUNET_NO);
1632     LOG (GNUNET_ERROR_TYPE_DEBUG, "channel 0x%X unknown\n", ntohl (msg->chid));
1633     send_channel_destroy (t, ntohl (msg->chid));
1634     return;
1635   }
1636
1637   GCCH_handle_data (ch, msg, fwd);
1638 }
1639
1640
1641 /**
1642  * Demultiplex data ACKs per channel and update appropriate channel buffer info.
1643  *
1644  * @param t Tunnel on which the DATA ACK came.
1645  * @param msg DATA ACK message.
1646  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1647  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1648  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1649  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1650  */
1651 static void
1652 handle_data_ack (struct CadetTunnel *t,
1653                  const struct GNUNET_CADET_DataACK *msg,
1654                  int fwd)
1655 {
1656   struct CadetChannel *ch;
1657   size_t size;
1658
1659   /* Check size */
1660   size = ntohs (msg->header.size);
1661   if (size != sizeof (struct GNUNET_CADET_DataACK))
1662   {
1663     GNUNET_break (0);
1664     return;
1665   }
1666
1667   /* Check channel */
1668   ch = GCT_get_channel (t, ntohl (msg->chid));
1669   if (NULL == ch)
1670   {
1671     GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
1672                               1, GNUNET_NO);
1673     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1674          ntohl (msg->chid));
1675     return;
1676   }
1677
1678   GCCH_handle_data_ack (ch, msg, fwd);
1679 }
1680
1681
1682 /**
1683  * Handle channel create.
1684  *
1685  * @param t Tunnel on which the message came.
1686  * @param msg ChannelCreate message.
1687  */
1688 static void
1689 handle_ch_create (struct CadetTunnel *t,
1690                   const struct GNUNET_CADET_ChannelCreate *msg)
1691 {
1692   struct CadetChannel *ch;
1693   size_t size;
1694
1695   /* Check size */
1696   size = ntohs (msg->header.size);
1697   if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
1698   {
1699     GNUNET_break_op (0);
1700     return;
1701   }
1702
1703   /* Check channel */
1704   ch = GCT_get_channel (t, ntohl (msg->chid));
1705   if (NULL != ch && ! GCT_is_loopback (t))
1706   {
1707     /* Probably a retransmission, safe to ignore */
1708     LOG (GNUNET_ERROR_TYPE_DEBUG, "   already exists...\n");
1709   }
1710   ch = GCCH_handle_create (t, msg);
1711   if (NULL != ch)
1712     GCT_add_channel (t, ch);
1713 }
1714
1715
1716
1717 /**
1718  * Handle channel NACK: check correctness and call channel handler for NACKs.
1719  *
1720  * @param t Tunnel on which the NACK came.
1721  * @param msg NACK message.
1722  */
1723 static void
1724 handle_ch_nack (struct CadetTunnel *t,
1725                 const struct GNUNET_CADET_ChannelManage *msg)
1726 {
1727   struct CadetChannel *ch;
1728   size_t size;
1729
1730   /* Check size */
1731   size = ntohs (msg->header.size);
1732   if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1733   {
1734     GNUNET_break (0);
1735     return;
1736   }
1737
1738   /* Check channel */
1739   ch = GCT_get_channel (t, ntohl (msg->chid));
1740   if (NULL == ch)
1741   {
1742     GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
1743                               1, GNUNET_NO);
1744     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1745          ntohl (msg->chid));
1746     return;
1747   }
1748
1749   GCCH_handle_nack (ch);
1750 }
1751
1752
1753 /**
1754  * Handle a CHANNEL ACK (SYNACK/ACK).
1755  *
1756  * @param t Tunnel on which the CHANNEL ACK came.
1757  * @param msg CHANNEL ACK message.
1758  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1759  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1760  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1761  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1762  */
1763 static void
1764 handle_ch_ack (struct CadetTunnel *t,
1765                const struct GNUNET_CADET_ChannelManage *msg,
1766                int fwd)
1767 {
1768   struct CadetChannel *ch;
1769   size_t size;
1770
1771   /* Check size */
1772   size = ntohs (msg->header.size);
1773   if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1774   {
1775     GNUNET_break (0);
1776     return;
1777   }
1778
1779   /* Check channel */
1780   ch = GCT_get_channel (t, ntohl (msg->chid));
1781   if (NULL == ch)
1782   {
1783     GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
1784                               1, GNUNET_NO);
1785     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1786          ntohl (msg->chid));
1787     return;
1788   }
1789
1790   GCCH_handle_ack (ch, msg, fwd);
1791 }
1792
1793
1794 /**
1795  * Handle a channel destruction message.
1796  *
1797  * @param t Tunnel on which the message came.
1798  * @param msg Channel destroy message.
1799  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1800  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1801  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1802  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1803  */
1804 static void
1805 handle_ch_destroy (struct CadetTunnel *t,
1806                    const struct GNUNET_CADET_ChannelManage *msg,
1807                    int fwd)
1808 {
1809   struct CadetChannel *ch;
1810   size_t size;
1811
1812   /* Check size */
1813   size = ntohs (msg->header.size);
1814   if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1815   {
1816     GNUNET_break (0);
1817     return;
1818   }
1819
1820   /* Check channel */
1821   ch = GCT_get_channel (t, ntohl (msg->chid));
1822   if (NULL == ch)
1823   {
1824     /* Probably a retransmission, safe to ignore */
1825     return;
1826   }
1827
1828   GCCH_handle_destroy (ch, msg, fwd);
1829 }
1830
1831
1832 /**
1833  * Free Axolotl data.
1834  *
1835  * @param t Tunnel.
1836  */
1837 static void
1838 destroy_ax (struct CadetTunnel *t)
1839 {
1840   if (NULL == t->ax)
1841     return;
1842
1843   GNUNET_free_non_null (t->ax->DHRs);
1844   GNUNET_free_non_null (t->ax->kx_0);
1845   while (NULL != t->ax->skipped_head)
1846     delete_skipped_key (t, t->ax->skipped_head);
1847   GNUNET_assert (0 == t->ax->skipped);
1848
1849   GNUNET_free (t->ax);
1850   t->ax = NULL;
1851
1852   if (NULL != t->rekey_task)
1853   {
1854     GNUNET_SCHEDULER_cancel (t->rekey_task);
1855     t->rekey_task = NULL;
1856   }
1857   if (NULL != t->ephm_h)
1858   {
1859     GCC_cancel (t->ephm_h);
1860     t->ephm_h = NULL;
1861   }
1862 }
1863
1864
1865 /**
1866  * Demultiplex by message type and call appropriate handler for a message
1867  * towards a channel of a local tunnel.
1868  *
1869  * @param t Tunnel this message came on.
1870  * @param msgh Message header.
1871  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1872  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1873  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1874  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1875  */
1876 static void
1877 handle_decrypted (struct CadetTunnel *t,
1878                   const struct GNUNET_MessageHeader *msgh,
1879                   int fwd)
1880 {
1881   uint16_t type;
1882   char buf[256];
1883
1884   type = ntohs (msgh->type);
1885   LOG (GNUNET_ERROR_TYPE_DEBUG, "<-- %s on %s\n", GC_m2s (type), GCT_2s (t));
1886   SPRINTF (buf, "# received encrypted of type %hu (%s)", type, GC_m2s (type));
1887   GNUNET_STATISTICS_update (stats, buf, 1, GNUNET_NO);
1888
1889   switch (type)
1890   {
1891     case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1892       /* Do nothing, connection aleady got updated. */
1893       GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
1894       break;
1895
1896     case GNUNET_MESSAGE_TYPE_CADET_DATA:
1897       /* Don't send hop ACK, wait for client to ACK */
1898       handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
1899       break;
1900
1901     case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1902       handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
1903       break;
1904
1905     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1906       handle_ch_create (t, (struct GNUNET_CADET_ChannelCreate *) msgh);
1907       break;
1908
1909     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1910       handle_ch_nack (t, (struct GNUNET_CADET_ChannelManage *) msgh);
1911       break;
1912
1913     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1914       handle_ch_ack (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
1915       break;
1916
1917     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1918       handle_ch_destroy (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
1919       break;
1920
1921     default:
1922       GNUNET_break_op (0);
1923       LOG (GNUNET_ERROR_TYPE_WARNING,
1924            "end-to-end message not known (%u)\n",
1925            ntohs (msgh->type));
1926       GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1927   }
1928 }
1929
1930
1931 /******************************************************************************/
1932 /********************************    API    ***********************************/
1933 /******************************************************************************/
1934
1935 /**
1936  * Decrypt and process an encrypted message.
1937  *
1938  * Calls the appropriate handler for a message in a channel of a local tunnel.
1939  *
1940  * @param t Tunnel this message came on.
1941  * @param msg Message header.
1942  */
1943 void
1944 GCT_handle_encrypted (struct CadetTunnel *t,
1945                       const struct GNUNET_CADET_Encrypted *msg)
1946 {
1947   uint16_t size = ntohs (msg->header.size);
1948   char cbuf [size];
1949   int decrypted_size;
1950   const struct GNUNET_MessageHeader *msgh;
1951   unsigned int off;
1952
1953   GNUNET_STATISTICS_update (stats, "# received encrypted", 1, GNUNET_NO);
1954
1955   decrypted_size = t_ax_decrypt_and_validate (t, cbuf, msg, size);
1956
1957   if (-1 == decrypted_size)
1958   {
1959     GNUNET_STATISTICS_update (stats, "# unable to decrypt", 1, GNUNET_NO);
1960     if (CADET_TUNNEL_KEY_PING <= t->estate)
1961     {
1962       GNUNET_break_op (0);
1963       LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong crypto, tunnel %s\n", GCT_2s (t));
1964       GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1965     }
1966     return;
1967   }
1968   GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
1969
1970   /* FIXME: this is bad, as the structs returned from
1971      this loop may be unaligned, see util's MST for
1972      how to do this right. */
1973   off = 0;
1974   while (off + sizeof (struct GNUNET_MessageHeader) <= decrypted_size)
1975   {
1976     uint16_t msize;
1977
1978     msgh = (const struct GNUNET_MessageHeader *) &cbuf[off];
1979     msize = ntohs (msgh->size);
1980     if (msize < sizeof (struct GNUNET_MessageHeader))
1981     {
1982       GNUNET_break_op (0);
1983       return;
1984     }
1985     if (off + msize < decrypted_size)
1986     {
1987       GNUNET_break_op (0);
1988       return;
1989     }
1990     handle_decrypted (t, msgh, GNUNET_SYSERR);
1991     off += msize;
1992   }
1993 }
1994
1995
1996 /**
1997  * Handle a Key eXchange message.
1998  *
1999  * @param t Tunnel on which the message came.
2000  * @param msg KX message itself.
2001  */
2002 void
2003 GCT_handle_kx (struct CadetTunnel *t,
2004                const struct GNUNET_CADET_KX *msg)
2005 {
2006   struct CadetTunnelAxolotl *ax;
2007   struct GNUNET_HashCode key_material[3];
2008   struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
2009   const char salt[] = "CADET Axolotl salt";
2010   const struct GNUNET_PeerIdentity *pid;
2011   int am_I_alice;
2012
2013   LOG (GNUNET_ERROR_TYPE_INFO, "<== {        KX} on %s\n", GCT_2s (t));
2014
2015   if (NULL == t->ax)
2016   {
2017     /* Something is wrong if ax is NULL. Whose fault it is? */
2018     return;
2019   }
2020   ax = t->ax;
2021
2022   pid = GCT_get_destination (t);
2023   if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2024     am_I_alice = GNUNET_YES;
2025   else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2026     am_I_alice = GNUNET_NO;
2027   else
2028   {
2029     GNUNET_break_op (0);
2030     return;
2031   }
2032
2033   if (0 != (GNUNET_CADET_KX_FLAG_FORCE_REPLY & ntohl (msg->flags)))
2034   {
2035     if (NULL != t->rekey_task)
2036     {
2037       GNUNET_SCHEDULER_cancel (t->rekey_task);
2038       t->rekey_task = NULL;
2039     }
2040     GCT_send_kx (t, GNUNET_NO);
2041   }
2042
2043   if (0 == memcmp (&ax->DHRr, &msg->ratchet_key, sizeof(msg->ratchet_key)))
2044   {
2045     LOG (GNUNET_ERROR_TYPE_INFO, " known ratchet key, exit\n");
2046     return;
2047   }
2048
2049   LOG (GNUNET_ERROR_TYPE_INFO, " is Alice? %s\n", am_I_alice ? "YES" : "NO");
2050
2051   ax->DHRr = msg->ratchet_key;
2052
2053   /* ECDH A B0 */
2054   if (GNUNET_YES == am_I_alice)
2055   {
2056     GNUNET_CRYPTO_eddsa_ecdh (id_key,              /* A */
2057                               &msg->ephemeral_key, /* B0 */
2058                               &key_material[0]);
2059   }
2060   else
2061   {
2062     GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0,            /* B0 */
2063                               &pid->public_key,    /* A */
2064                               &key_material[0]);
2065   }
2066
2067   /* ECDH A0 B */
2068   if (GNUNET_YES == am_I_alice)
2069   {
2070     GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0,            /* A0 */
2071                               &pid->public_key,    /* B */
2072                               &key_material[1]);
2073   }
2074   else
2075   {
2076     GNUNET_CRYPTO_eddsa_ecdh (id_key,              /* A */
2077                               &msg->ephemeral_key, /* B0 */
2078                               &key_material[1]);
2079
2080
2081   }
2082
2083   /* ECDH A0 B0 */
2084   /* (This is the triple-DH, we could probably safely skip this,
2085      as A0/B0 are already in the key material.) */
2086   GNUNET_CRYPTO_ecc_ecdh (ax->kx_0,             /* A0 or B0 */
2087                           &msg->ephemeral_key,  /* B0 or A0 */
2088                           &key_material[2]);
2089
2090   #if DUMP_KEYS_TO_STDERR
2091   {
2092     unsigned int i;
2093     for (i = 0; i < 3; i++)
2094       LOG (GNUNET_ERROR_TYPE_INFO, "km[%u]: %s\n",
2095            i, GNUNET_h2s (&key_material[i]));
2096   }
2097   #endif
2098
2099   /* KDF */
2100   GNUNET_CRYPTO_kdf (keys, sizeof (keys),
2101                      salt, sizeof (salt),
2102                      &key_material, sizeof (key_material), NULL);
2103
2104   if (0 == memcmp (&ax->RK, &keys[0], sizeof(ax->RK)))
2105   {
2106     LOG (GNUNET_ERROR_TYPE_INFO, " known handshake key, exit\n");
2107     return;
2108   }
2109   ax->RK = keys[0];
2110   if (GNUNET_YES == am_I_alice)
2111   {
2112     ax->HKr = keys[1];
2113     ax->NHKs = keys[2];
2114     ax->NHKr = keys[3];
2115     ax->CKr = keys[4];
2116     ax->ratchet_flag = GNUNET_YES;
2117   }
2118   else
2119   {
2120     ax->HKs = keys[1];
2121     ax->NHKr = keys[2];
2122     ax->NHKs = keys[3];
2123     ax->CKs = keys[4];
2124     ax->ratchet_flag = GNUNET_NO;
2125     ax->ratchet_allowed = GNUNET_NO;
2126     ax->ratchet_counter = 0;
2127     ax->ratchet_expiration =
2128       GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), ratchet_time);
2129   }
2130   ax->PNs = 0;
2131   ax->Nr = 0;
2132   ax->Ns = 0;
2133   GCT_change_estate (t, CADET_TUNNEL_KEY_PING);
2134   send_queued_data (t);
2135 }
2136
2137 /**
2138  * Initialize the tunnel subsystem.
2139  *
2140  * @param c Configuration handle.
2141  * @param key ECC private key, to derive all other keys and do crypto.
2142  */
2143 void
2144 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
2145           const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
2146 {
2147   unsigned int expected_overhead;
2148
2149   LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
2150
2151   expected_overhead = 0;
2152   expected_overhead += sizeof (struct GNUNET_CADET_Encrypted);
2153   expected_overhead += sizeof (struct GNUNET_CADET_Data);
2154   expected_overhead += sizeof (struct GNUNET_CADET_ACK);
2155   GNUNET_assert (GNUNET_CONSTANTS_CADET_P2P_OVERHEAD == expected_overhead);
2156
2157   if (GNUNET_OK !=
2158       GNUNET_CONFIGURATION_get_value_number (c,
2159                                              "CADET",
2160                                              "RATCHET_MESSAGES",
2161                                              &ratchet_messages))
2162   {
2163     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
2164                                "CADET",
2165                                "RATCHET_MESSAGES",
2166                                "USING DEFAULT");
2167     ratchet_messages = 64;
2168   }
2169   if (GNUNET_OK !=
2170       GNUNET_CONFIGURATION_get_value_time (c,
2171                                            "CADET",
2172                                            "RATCHET_TIME",
2173                                            &ratchet_time))
2174   {
2175     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
2176                                "CADET", "RATCHET_TIME", "USING DEFAULT");
2177     ratchet_time = GNUNET_TIME_UNIT_HOURS;
2178   }
2179
2180
2181   id_key = key;
2182   tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
2183 }
2184
2185
2186 /**
2187  * Shut down the tunnel subsystem.
2188  */
2189 void
2190 GCT_shutdown (void)
2191 {
2192   LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down tunnels\n");
2193   GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
2194   GNUNET_CONTAINER_multipeermap_destroy (tunnels);
2195 }
2196
2197
2198 /**
2199  * Create a tunnel.
2200  *
2201  * @param destination Peer this tunnel is towards.
2202  */
2203 struct CadetTunnel *
2204 GCT_new (struct CadetPeer *destination)
2205 {
2206   struct CadetTunnel *t;
2207
2208   t = GNUNET_new (struct CadetTunnel);
2209   t->next_chid = 0;
2210   t->peer = destination;
2211
2212   if (GNUNET_OK !=
2213       GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
2214                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2215   {
2216     GNUNET_break (0);
2217     GNUNET_free (t);
2218     return NULL;
2219   }
2220   t->ax = GNUNET_new (struct CadetTunnelAxolotl);
2221   new_ephemeral (t);
2222   t->ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
2223   return t;
2224 }
2225
2226
2227 /**
2228  * Change the tunnel's connection state.
2229  *
2230  * @param t Tunnel whose connection state to change.
2231  * @param cstate New connection state.
2232  */
2233 void
2234 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
2235 {
2236   if (NULL == t)
2237     return;
2238   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
2239        GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
2240   if (myid != GCP_get_short_id (t->peer) &&
2241       CADET_TUNNEL_READY != t->cstate &&
2242       CADET_TUNNEL_READY == cstate)
2243   {
2244     t->cstate = cstate;
2245     if (CADET_TUNNEL_KEY_OK == t->estate)
2246     {
2247       LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered send queued data\n");
2248       send_queued_data (t);
2249     }
2250     else if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
2251     {
2252       LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered KX\n");
2253       GCT_send_kx (t, GNUNET_NO);
2254     }
2255     else
2256     {
2257       LOG (GNUNET_ERROR_TYPE_DEBUG, "estate %s\n", estate2s (t->estate));
2258     }
2259   }
2260   t->cstate = cstate;
2261
2262   if (CADET_TUNNEL_READY == cstate
2263       && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
2264   {
2265     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered stop dht\n");
2266     GCP_stop_search (t->peer);
2267   }
2268 }
2269
2270
2271 /**
2272  * Change the tunnel encryption state.
2273  *
2274  * If the encryption state changes to OK, stop the rekey task.
2275  *
2276  * @param t Tunnel whose encryption state to change, or NULL.
2277  * @param state New encryption state.
2278  */
2279 void
2280 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
2281 {
2282   enum CadetTunnelEState old;
2283
2284   if (NULL == t)
2285     return;
2286
2287   old = t->estate;
2288   t->estate = state;
2289   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate was %s\n",
2290        GCP_2s (t->peer), estate2s (old));
2291   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate is now %s\n",
2292        GCP_2s (t->peer), estate2s (t->estate));
2293
2294   if (CADET_TUNNEL_KEY_OK != old && CADET_TUNNEL_KEY_OK == t->estate)
2295   {
2296     if (NULL != t->rekey_task)
2297     {
2298       GNUNET_SCHEDULER_cancel (t->rekey_task);
2299       t->rekey_task = NULL;
2300     }
2301     /* Send queued data if tunnel is not loopback */
2302     if (myid != GCP_get_short_id (t->peer))
2303       send_queued_data (t);
2304   }
2305 }
2306
2307
2308 /**
2309  * @brief Check if tunnel has too many connections, and remove one if necessary.
2310  *
2311  * Currently this means the newest connection, unless it is a direct one.
2312  * Implemented as a task to avoid freeing a connection that is in the middle
2313  * of being created/processed.
2314  *
2315  * @param cls Closure (Tunnel to check).
2316  */
2317 static void
2318 trim_connections (void *cls)
2319 {
2320   struct CadetTunnel *t = cls;
2321
2322   t->trim_connections_task = NULL;
2323   if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
2324   {
2325     struct CadetTConnection *iter;
2326     struct CadetTConnection *c;
2327
2328     for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
2329     {
2330       if ((iter->created.abs_value_us > c->created.abs_value_us)
2331           && GNUNET_NO == GCC_is_direct (iter->c))
2332       {
2333         c = iter;
2334       }
2335     }
2336     if (NULL != c)
2337     {
2338       LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
2339            GCT_2s (t));
2340       LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
2341            GCC_2s (c->c));
2342       GCC_destroy (c->c);
2343     }
2344     else
2345     {
2346       GNUNET_break (0);
2347     }
2348   }
2349 }
2350
2351
2352 /**
2353  * Add a connection to a tunnel.
2354  *
2355  * @param t Tunnel.
2356  * @param c Connection.
2357  */
2358 void
2359 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
2360 {
2361   struct CadetTConnection *aux;
2362
2363   GNUNET_assert (NULL != c);
2364
2365   LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
2366   LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
2367   for (aux = t->connection_head; aux != NULL; aux = aux->next)
2368     if (aux->c == c)
2369       return;
2370
2371   aux = GNUNET_new (struct CadetTConnection);
2372   aux->c = c;
2373   aux->created = GNUNET_TIME_absolute_get ();
2374
2375   GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
2376
2377   if (CADET_TUNNEL_SEARCHING == t->cstate)
2378     GCT_change_cstate (t, CADET_TUNNEL_WAITING);
2379
2380   if (NULL != t->trim_connections_task)
2381     t->trim_connections_task = GNUNET_SCHEDULER_add_now (&trim_connections, t);
2382 }
2383
2384
2385 /**
2386  * Remove a connection from a tunnel.
2387  *
2388  * @param t Tunnel.
2389  * @param c Connection.
2390  */
2391 void
2392 GCT_remove_connection (struct CadetTunnel *t,
2393                        struct CadetConnection *c)
2394 {
2395   struct CadetTConnection *aux;
2396   struct CadetTConnection *next;
2397   unsigned int conns;
2398
2399   LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
2400        GCC_2s (c), GCT_2s (t));
2401   for (aux = t->connection_head; aux != NULL; aux = next)
2402   {
2403     next = aux->next;
2404     if (aux->c == c)
2405     {
2406       GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
2407       GNUNET_free (aux);
2408     }
2409   }
2410
2411   conns = GCT_count_connections (t);
2412   if (0 == conns
2413       && NULL == t->destroy_task
2414       && CADET_TUNNEL_SHUTDOWN != t->cstate
2415       && GNUNET_NO == shutting_down)
2416   {
2417     if (0 == GCT_count_any_connections (t))
2418       GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
2419     else
2420       GCT_change_cstate (t, CADET_TUNNEL_WAITING);
2421   }
2422
2423   /* Start new connections if needed */
2424   if (CONNECTIONS_PER_TUNNEL > conns
2425       && CADET_TUNNEL_SHUTDOWN != t->cstate
2426       && GNUNET_NO == shutting_down)
2427   {
2428     LOG (GNUNET_ERROR_TYPE_DEBUG, "  too few connections, getting new ones\n");
2429     GCP_connect (t->peer); /* Will change cstate to WAITING when possible */
2430     return;
2431   }
2432
2433   /* If not marked as ready, no change is needed */
2434   if (CADET_TUNNEL_READY != t->cstate)
2435     return;
2436
2437   /* Check if any connection is ready to maintain cstate */
2438   for (aux = t->connection_head; aux != NULL; aux = aux->next)
2439     if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
2440       return;
2441 }
2442
2443
2444 /**
2445  * Add a channel to a tunnel.
2446  *
2447  * @param t Tunnel.
2448  * @param ch Channel.
2449  */
2450 void
2451 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2452 {
2453   struct CadetTChannel *aux;
2454
2455   GNUNET_assert (NULL != ch);
2456
2457   LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
2458
2459   for (aux = t->channel_head; aux != NULL; aux = aux->next)
2460   {
2461     LOG (GNUNET_ERROR_TYPE_DEBUG, "  already there %p\n", aux->ch);
2462     if (aux->ch == ch)
2463       return;
2464   }
2465
2466   aux = GNUNET_new (struct CadetTChannel);
2467   aux->ch = ch;
2468   LOG (GNUNET_ERROR_TYPE_DEBUG,
2469        " adding %p to %p\n", aux, t->channel_head);
2470   GNUNET_CONTAINER_DLL_insert_tail (t->channel_head,
2471                                     t->channel_tail,
2472                                     aux);
2473
2474   if (NULL != t->destroy_task)
2475   {
2476     GNUNET_SCHEDULER_cancel (t->destroy_task);
2477     t->destroy_task = NULL;
2478     LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
2479   }
2480 }
2481
2482
2483 /**
2484  * Remove a channel from a tunnel.
2485  *
2486  * @param t Tunnel.
2487  * @param ch Channel.
2488  */
2489 void
2490 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2491 {
2492   struct CadetTChannel *aux;
2493
2494   LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
2495   for (aux = t->channel_head; aux != NULL; aux = aux->next)
2496   {
2497     if (aux->ch == ch)
2498     {
2499       LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
2500       GNUNET_CONTAINER_DLL_remove (t->channel_head,
2501                                    t->channel_tail,
2502                                    aux);
2503       GNUNET_free (aux);
2504       return;
2505     }
2506   }
2507 }
2508
2509
2510 /**
2511  * Search for a channel by global ID.
2512  *
2513  * @param t Tunnel containing the channel.
2514  * @param chid Public channel number.
2515  *
2516  * @return channel handler, NULL if doesn't exist
2517  */
2518 struct CadetChannel *
2519 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
2520 {
2521   struct CadetTChannel *iter;
2522
2523   if (NULL == t)
2524     return NULL;
2525
2526   for (iter = t->channel_head; NULL != iter; iter = iter->next)
2527   {
2528     if (GCCH_get_id (iter->ch) == chid)
2529       break;
2530   }
2531
2532   return NULL == iter ? NULL : iter->ch;
2533 }
2534
2535
2536 /**
2537  * @brief Destroy a tunnel and free all resources.
2538  *
2539  * Should only be called a while after the tunnel has been marked as destroyed,
2540  * in case there is a new channel added to the same peer shortly after marking
2541  * the tunnel. This way we avoid a new public key handshake.
2542  *
2543  * @param cls Closure (tunnel to destroy).
2544  */
2545 static void
2546 delayed_destroy (void *cls)
2547 {
2548   struct CadetTunnel *t = cls;
2549   struct CadetTConnection *iter;
2550
2551   t->destroy_task = NULL;
2552   LOG (GNUNET_ERROR_TYPE_DEBUG,
2553        "delayed destroying tunnel %p\n",
2554        t);
2555   t->cstate = CADET_TUNNEL_SHUTDOWN;
2556   for (iter = t->connection_head; NULL != iter; iter = iter->next)
2557   {
2558     GCC_send_destroy (iter->c);
2559   }
2560   GCT_destroy (t);
2561 }
2562
2563
2564 /**
2565  * Tunnel is empty: destroy it.
2566  *
2567  * Notifies all connections about the destruction.
2568  *
2569  * @param t Tunnel to destroy.
2570  */
2571 void
2572 GCT_destroy_empty (struct CadetTunnel *t)
2573 {
2574   if (GNUNET_YES == shutting_down)
2575     return; /* Will be destroyed immediately anyway */
2576
2577   if (NULL != t->destroy_task)
2578   {
2579     LOG (GNUNET_ERROR_TYPE_WARNING,
2580          "Tunnel %s is already scheduled for destruction. Tunnel debug dump:\n",
2581          GCT_2s (t));
2582     GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
2583     GNUNET_break (0);
2584     /* should never happen, tunnel can only become empty once, and the
2585      * task identifier should be NO_TASK (cleaned when the tunnel was created
2586      * or became un-empty)
2587      */
2588     return;
2589   }
2590
2591   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: scheduling destruction\n",
2592        GCT_2s (t));
2593
2594   // FIXME make delay a config option
2595   t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
2596                                                   &delayed_destroy, t);
2597   LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %p\n",
2598        t, t->destroy_task);
2599 }
2600
2601
2602 /**
2603  * Destroy tunnel if empty (no more channels).
2604  *
2605  * @param t Tunnel to destroy if empty.
2606  */
2607 void
2608 GCT_destroy_if_empty (struct CadetTunnel *t)
2609 {
2610   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
2611   if (0 < GCT_count_channels (t))
2612     return;
2613
2614   GCT_destroy_empty (t);
2615 }
2616
2617
2618 /**
2619  * Destroy the tunnel.
2620  *
2621  * This function does not generate any warning traffic to clients or peers.
2622  *
2623  * Tasks:
2624  * Cancel messages belonging to this tunnel queued to neighbors.
2625  * Free any allocated resources linked to the tunnel.
2626  *
2627  * @param t The tunnel to destroy.
2628  */
2629 void
2630 GCT_destroy (struct CadetTunnel *t)
2631 {
2632   struct CadetTConnection *iter_c;
2633   struct CadetTConnection *next_c;
2634   struct CadetTChannel *iter_ch;
2635   struct CadetTChannel *next_ch;
2636   unsigned int keepalives_queued;
2637
2638   if (NULL == t)
2639     return;
2640
2641   LOG (GNUNET_ERROR_TYPE_DEBUG,
2642        "destroying tunnel %s\n",
2643        GCP_2s (t->peer));
2644   GNUNET_break (GNUNET_YES ==
2645                 GNUNET_CONTAINER_multipeermap_remove (tunnels,
2646                                                       GCP_get_id (t->peer), t));
2647
2648   for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
2649   {
2650     next_c = iter_c->next;
2651     GCC_destroy (iter_c->c);
2652   }
2653   for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
2654   {
2655     next_ch = iter_ch->next;
2656     GCCH_destroy (iter_ch->ch);
2657     /* Should only happen on shutdown, but it's ok. */
2658   }
2659   keepalives_queued = 0;
2660   while (NULL != t->tq_head)
2661   {
2662     /* Should have been cleaned by destuction of channel. */
2663     struct GNUNET_MessageHeader *mh;
2664     uint16_t type;
2665
2666     mh = (struct GNUNET_MessageHeader *) &t->tq_head[1];
2667     type = ntohs (mh->type);
2668     if (0 == keepalives_queued && GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE == type)
2669     {
2670       keepalives_queued = 1;
2671       LOG (GNUNET_ERROR_TYPE_DEBUG,
2672            "one keepalive left behind on tunnel shutdown\n");
2673     }
2674     else if (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY == type)
2675     {
2676       LOG (GNUNET_ERROR_TYPE_WARNING,
2677            "tunnel destroyed before a CHANNEL_DESTROY was sent to peer\n");
2678     }
2679     else
2680     {
2681       GNUNET_break (0);
2682       LOG (GNUNET_ERROR_TYPE_ERROR,
2683            "message left behind on tunnel shutdown: %s\n",
2684            GC_m2s (type));
2685     }
2686     unqueue_data (t->tq_head);
2687   }
2688
2689
2690   if (NULL != t->destroy_task)
2691   {
2692     LOG (GNUNET_ERROR_TYPE_DEBUG,
2693          "cancelling dest: %p\n",
2694          t->destroy_task);
2695     GNUNET_SCHEDULER_cancel (t->destroy_task);
2696     t->destroy_task = NULL;
2697   }
2698
2699   if (NULL != t->trim_connections_task)
2700   {
2701     LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling trim: %p\n",
2702          t->trim_connections_task);
2703     GNUNET_SCHEDULER_cancel (t->trim_connections_task);
2704     t->trim_connections_task = NULL;
2705   }
2706
2707   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
2708   GCP_set_tunnel (t->peer, NULL);
2709
2710   if (NULL != t->rekey_task)
2711   {
2712     GNUNET_SCHEDULER_cancel (t->rekey_task);
2713     t->rekey_task = NULL;
2714   }
2715   if (NULL != t->ax)
2716     destroy_ax (t);
2717
2718   GNUNET_free (t);
2719 }
2720
2721
2722 /**
2723  * @brief Use the given path for the tunnel.
2724  * Update the next and prev hops (and RCs).
2725  * (Re)start the path refresh in case the tunnel is locally owned.
2726  *
2727  * @param t Tunnel to update.
2728  * @param p Path to use.
2729  *
2730  * @return Connection created.
2731  */
2732 struct CadetConnection *
2733 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *path)
2734 {
2735   struct CadetConnection *c;
2736   struct GNUNET_CADET_Hash cid;
2737   unsigned int own_pos;
2738
2739   if (NULL == t || NULL == path)
2740   {
2741     GNUNET_break (0);
2742     return NULL;
2743   }
2744
2745   if (CADET_TUNNEL_SHUTDOWN == t->cstate)
2746   {
2747     GNUNET_break (0);
2748     return NULL;
2749   }
2750
2751   for (own_pos = 0; own_pos < path->length; own_pos++)
2752   {
2753     if (path->peers[own_pos] == myid)
2754       break;
2755   }
2756   if (own_pos >= path->length)
2757   {
2758     GNUNET_break_op (0);
2759     return NULL;
2760   }
2761
2762   GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
2763   c = GCC_new (&cid, t, path, own_pos);
2764   if (NULL == c)
2765   {
2766     /* Path was flawed */
2767     return NULL;
2768   }
2769   GCT_add_connection (t, c);
2770   return c;
2771 }
2772
2773
2774 /**
2775  * Count all created connections of a tunnel. Not necessarily ready connections!
2776  *
2777  * @param t Tunnel on which to count.
2778  *
2779  * @return Number of connections created, either being established or ready.
2780  */
2781 unsigned int
2782 GCT_count_any_connections (struct CadetTunnel *t)
2783 {
2784   struct CadetTConnection *iter;
2785   unsigned int count;
2786
2787   if (NULL == t)
2788     return 0;
2789
2790   for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2791     count++;
2792
2793   return count;
2794 }
2795
2796
2797 /**
2798  * Count established (ready) connections of a tunnel.
2799  *
2800  * @param t Tunnel on which to count.
2801  *
2802  * @return Number of connections.
2803  */
2804 unsigned int
2805 GCT_count_connections (struct CadetTunnel *t)
2806 {
2807   struct CadetTConnection *iter;
2808   unsigned int count;
2809
2810   if (NULL == t)
2811     return 0;
2812
2813   for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2814     if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
2815       count++;
2816
2817   return count;
2818 }
2819
2820
2821 /**
2822  * Count channels of a tunnel.
2823  *
2824  * @param t Tunnel on which to count.
2825  *
2826  * @return Number of channels.
2827  */
2828 unsigned int
2829 GCT_count_channels (struct CadetTunnel *t)
2830 {
2831   struct CadetTChannel *iter;
2832   unsigned int count;
2833
2834   for (count = 0, iter = t->channel_head;
2835        NULL != iter;
2836        iter = iter->next, count++) /* skip */;
2837
2838   return count;
2839 }
2840
2841
2842 /**
2843  * Get the connectivity state of a tunnel.
2844  *
2845  * @param t Tunnel.
2846  *
2847  * @return Tunnel's connectivity state.
2848  */
2849 enum CadetTunnelCState
2850 GCT_get_cstate (struct CadetTunnel *t)
2851 {
2852   if (NULL == t)
2853   {
2854     GNUNET_assert (0);
2855     return (enum CadetTunnelCState) -1;
2856   }
2857   return t->cstate;
2858 }
2859
2860
2861 /**
2862  * Get the encryption state of a tunnel.
2863  *
2864  * @param t Tunnel.
2865  *
2866  * @return Tunnel's encryption state.
2867  */
2868 enum CadetTunnelEState
2869 GCT_get_estate (struct CadetTunnel *t)
2870 {
2871   if (NULL == t)
2872   {
2873     GNUNET_break (0);
2874     return (enum CadetTunnelEState) -1;
2875   }
2876   return t->estate;
2877 }
2878
2879 /**
2880  * Get the maximum buffer space for a tunnel towards a local client.
2881  *
2882  * @param t Tunnel.
2883  *
2884  * @return Biggest buffer space offered by any channel in the tunnel.
2885  */
2886 unsigned int
2887 GCT_get_channels_buffer (struct CadetTunnel *t)
2888 {
2889   struct CadetTChannel *iter;
2890   unsigned int buffer;
2891   unsigned int ch_buf;
2892
2893   if (NULL == t->channel_head)
2894   {
2895     /* Probably getting buffer for a channel create/handshake. */
2896     LOG (GNUNET_ERROR_TYPE_DEBUG, "  no channels, allow max\n");
2897     return MIN_TUNNEL_BUFFER;
2898   }
2899
2900   buffer = 0;
2901   for (iter = t->channel_head; NULL != iter; iter = iter->next)
2902   {
2903     ch_buf = get_channel_buffer (iter);
2904     if (ch_buf > buffer)
2905       buffer = ch_buf;
2906   }
2907   if (MIN_TUNNEL_BUFFER > buffer)
2908     return MIN_TUNNEL_BUFFER;
2909
2910   if (MAX_TUNNEL_BUFFER < buffer)
2911   {
2912     GNUNET_break (0);
2913     return MAX_TUNNEL_BUFFER;
2914   }
2915   return buffer;
2916 }
2917
2918
2919 /**
2920  * Get the total buffer space for a tunnel for P2P traffic.
2921  *
2922  * @param t Tunnel.
2923  *
2924  * @return Buffer space offered by all connections in the tunnel.
2925  */
2926 unsigned int
2927 GCT_get_connections_buffer (struct CadetTunnel *t)
2928 {
2929   struct CadetTConnection *iter;
2930   unsigned int buffer;
2931
2932   if (GNUNET_NO == is_ready (t))
2933   {
2934     if (count_queued_data (t) >= 3)
2935       return 0;
2936     else
2937       return 1;
2938   }
2939
2940   buffer = 0;
2941   for (iter = t->connection_head; NULL != iter; iter = iter->next)
2942   {
2943     if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
2944     {
2945       continue;
2946     }
2947     buffer += get_connection_buffer (iter);
2948   }
2949
2950   return buffer;
2951 }
2952
2953
2954 /**
2955  * Get the tunnel's destination.
2956  *
2957  * @param t Tunnel.
2958  *
2959  * @return ID of the destination peer.
2960  */
2961 const struct GNUNET_PeerIdentity *
2962 GCT_get_destination (struct CadetTunnel *t)
2963 {
2964   return GCP_get_id (t->peer);
2965 }
2966
2967
2968 /**
2969  * Get the tunnel's next free global channel ID.
2970  *
2971  * @param t Tunnel.
2972  *
2973  * @return GID of a channel free to use.
2974  */
2975 CADET_ChannelNumber
2976 GCT_get_next_chid (struct CadetTunnel *t)
2977 {
2978   CADET_ChannelNumber chid;
2979   CADET_ChannelNumber mask;
2980   int result;
2981
2982   /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
2983    * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
2984    * If peer's ID is bigger, start at 0x4... bit 30 = 1
2985    */
2986   result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
2987   if (0 > result)
2988     mask = 0x40000000;
2989   else
2990     mask = 0x0;
2991   t->next_chid |= mask;
2992
2993   while (NULL != GCT_get_channel (t, t->next_chid))
2994   {
2995     LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
2996     t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
2997     t->next_chid |= mask;
2998   }
2999   chid = t->next_chid;
3000   t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3001   t->next_chid |= mask;
3002
3003   return chid;
3004 }
3005
3006
3007 /**
3008  * Send ACK on one or more channels due to buffer in connections.
3009  *
3010  * @param t Channel which has some free buffer space.
3011  */
3012 void
3013 GCT_unchoke_channels (struct CadetTunnel *t)
3014 {
3015   struct CadetTChannel *iter;
3016   unsigned int buffer;
3017   unsigned int channels = GCT_count_channels (t);
3018   unsigned int choked_n;
3019   struct CadetChannel *choked[channels];
3020
3021   LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
3022   LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
3023   if (NULL != t->channel_head)
3024     LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
3025
3026   if (NULL != t->tq_head)
3027     send_queued_data (t);
3028
3029   /* Get buffer space */
3030   buffer = GCT_get_connections_buffer (t);
3031   if (0 == buffer)
3032   {
3033     return;
3034   }
3035
3036   /* Count and remember choked channels */
3037   choked_n = 0;
3038   for (iter = t->channel_head; NULL != iter; iter = iter->next)
3039   {
3040     if (GNUNET_NO == get_channel_allowed (iter))
3041     {
3042       choked[choked_n++] = iter->ch;
3043     }
3044   }
3045
3046   /* Unchoke random channels */
3047   while (0 < buffer && 0 < choked_n)
3048   {
3049     unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3050                                                choked_n);
3051     GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
3052     choked_n--;
3053     buffer--;
3054     choked[r] = choked[choked_n];
3055   }
3056 }
3057
3058
3059 /**
3060  * Send ACK on one or more connections due to buffer space to the client.
3061  *
3062  * Iterates all connections of the tunnel and sends ACKs appropriately.
3063  *
3064  * @param t Tunnel.
3065  */
3066 void
3067 GCT_send_connection_acks (struct CadetTunnel *t)
3068 {
3069   struct CadetTConnection *iter;
3070   uint32_t allowed;
3071   uint32_t to_allow;
3072   uint32_t allow_per_connection;
3073   unsigned int cs;
3074   unsigned int buffer;
3075
3076   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
3077        GCT_2s (t));
3078
3079   if (NULL == t)
3080   {
3081     GNUNET_break (0);
3082     return;
3083   }
3084
3085   if (CADET_TUNNEL_READY != t->cstate)
3086     return;
3087
3088   buffer = GCT_get_channels_buffer (t);
3089   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer %u\n", buffer);
3090
3091   /* Count connections, how many messages are already allowed */
3092   cs = GCT_count_connections (t);
3093   for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3094   {
3095     allowed += get_connection_allowed (iter);
3096   }
3097   LOG (GNUNET_ERROR_TYPE_DEBUG, "  allowed %u\n", allowed);
3098
3099   /* Make sure there is no overflow */
3100   if (allowed > buffer)
3101     return;
3102
3103   /* Authorize connections to send more data */
3104   to_allow = buffer - allowed;
3105
3106   for (iter = t->connection_head;
3107        NULL != iter && to_allow > 0;
3108        iter = iter->next)
3109   {
3110     if (CADET_CONNECTION_READY != GCC_get_state (iter->c)
3111         || get_connection_allowed (iter) > 64 / 3)
3112     {
3113       continue;
3114     }
3115     GNUNET_assert(cs != 0);
3116     allow_per_connection = to_allow/cs;
3117     to_allow -= allow_per_connection;
3118     cs--;
3119     GCC_allow (iter->c, allow_per_connection,
3120                GCC_is_origin (iter->c, GNUNET_NO));
3121   }
3122
3123   if (0 != to_allow)
3124   {
3125     /* Since we don't allow if it's allowed to send 64/3, this can happen. */
3126     LOG (GNUNET_ERROR_TYPE_DEBUG, "  reminding to_allow: %u\n", to_allow);
3127   }
3128 }
3129
3130
3131 /**
3132  * Cancel a previously sent message while it's in the queue.
3133  *
3134  * ONLY can be called before the continuation given to the send function
3135  * is called. Once the continuation is called, the message is no longer in the
3136  * queue.
3137  *
3138  * @param q Handle to the queue.
3139  */
3140 void
3141 GCT_cancel (struct CadetTunnelQueue *q)
3142 {
3143   if (NULL != q->cq)
3144   {
3145     GNUNET_assert (NULL == q->tqd);
3146     GCC_cancel (q->cq);
3147     /* tun_message_sent() will be called and free q */
3148   }
3149   else if (NULL != q->tqd)
3150   {
3151     unqueue_data (q->tqd);
3152     q->tqd = NULL;
3153     if (NULL != q->cont)
3154       q->cont (q->cont_cls, NULL, q, 0, 0);
3155     GNUNET_free (q);
3156   }
3157   else
3158   {
3159     GNUNET_break (0);
3160   }
3161 }
3162
3163
3164 /**
3165  * Check if the tunnel has queued traffic.
3166  *
3167  * @param t Tunnel to check.
3168  *
3169  * @return #GNUNET_YES if there is queued traffic
3170  *         #GNUNET_NO otherwise
3171  */
3172 int
3173 GCT_has_queued_traffic (struct CadetTunnel *t)
3174 {
3175   return (NULL != t->tq_head) ? GNUNET_YES : GNUNET_NO;
3176 }
3177
3178
3179 /**
3180  * Sends an already built message on a tunnel, encrypting it and
3181  * choosing the best connection if not provided.
3182  *
3183  * @param message Message to send. Function modifies it.
3184  * @param t Tunnel on which this message is transmitted.
3185  * @param c Connection to use (autoselect if NULL).
3186  * @param force Force the tunnel to take the message (buffer overfill).
3187  * @param cont Continuation to call once message is really sent.
3188  * @param cont_cls Closure for @c cont.
3189  *
3190  * @return Handle to cancel message. NULL if @c cont is NULL.
3191  */
3192 struct CadetTunnelQueue *
3193 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
3194                            struct CadetTunnel *t, struct CadetConnection *c,
3195                            int force, GCT_sent cont, void *cont_cls)
3196 {
3197   return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
3198 }
3199
3200
3201 /**
3202  * Send a KX message.
3203  *
3204  * @param t Tunnel on which to send it.
3205  * @param force_reply Force the other peer to reply with a KX message.
3206  */
3207 void
3208 GCT_send_kx (struct CadetTunnel *t, int force_reply)
3209 {
3210   struct CadetConnection *c;
3211   struct GNUNET_CADET_KX msg;
3212   enum GNUNET_CADET_KX_Flags flags;
3213
3214   LOG (GNUNET_ERROR_TYPE_INFO, "==> {        KX} on %s\n", GCT_2s (t));
3215   if (NULL != t->ephm_h)
3216   {
3217     LOG (GNUNET_ERROR_TYPE_INFO, "     already queued, nop\n");
3218     return;
3219   }
3220
3221   /* Avoid loopback. */
3222   if (GCT_is_loopback (t))
3223   {
3224     GNUNET_break (0);
3225     return;
3226   }
3227   c = tunnel_get_connection (t);
3228   if (NULL == c)
3229   {
3230     if (NULL == t->destroy_task && CADET_TUNNEL_READY == t->cstate)
3231     {
3232       GNUNET_break (0);
3233       GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
3234     }
3235     return;
3236   }
3237
3238   msg.header.size = htons (sizeof (msg));
3239   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
3240   flags = GNUNET_CADET_KX_FLAG_NONE;
3241   if (GNUNET_YES == force_reply)
3242     flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY;
3243   msg.flags = htonl (flags);
3244   msg.cid = *GCC_get_id (c);
3245   GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->kx_0, &msg.ephemeral_key);
3246   GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &msg.ratchet_key);
3247
3248   t->ephm_h = GCC_send_prebuilt_message (&msg.header, 0, 0,
3249                                          c, GCC_is_origin (c, GNUNET_YES),
3250                                          GNUNET_YES, &ephm_sent, t);
3251   if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
3252     GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
3253 }
3254
3255
3256 /**
3257  * Is the tunnel directed towards the local peer?
3258  *
3259  * @param t Tunnel.
3260  *
3261  * @return #GNUNET_YES if it is loopback.
3262  */
3263 int
3264 GCT_is_loopback (const struct CadetTunnel *t)
3265 {
3266   return (myid == GCP_get_short_id (t->peer));
3267 }
3268
3269
3270 /**
3271  * Is the tunnel this path already?
3272  *
3273  * @param t Tunnel.
3274  * @param p Path.
3275  *
3276  * @return #GNUNET_YES a connection uses this path.
3277  */
3278 int
3279 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
3280 {
3281   struct CadetTConnection *iter;
3282
3283   for (iter = t->connection_head; NULL != iter; iter = iter->next)
3284     if (path_equivalent (GCC_get_path (iter->c), p))
3285       return GNUNET_YES;
3286
3287   return GNUNET_NO;
3288 }
3289
3290
3291 /**
3292  * Get a cost of a path for a tunnel considering existing connections.
3293  *
3294  * @param t Tunnel.
3295  * @param path Candidate path.
3296  *
3297  * @return Cost of the path (path length + number of overlapping nodes)
3298  */
3299 unsigned int
3300 GCT_get_path_cost (const struct CadetTunnel *t,
3301                    const struct CadetPeerPath *path)
3302 {
3303   struct CadetTConnection *iter;
3304   const struct CadetPeerPath *aux;
3305   unsigned int overlap;
3306   unsigned int i;
3307   unsigned int j;
3308
3309   if (NULL == path)
3310     return 0;
3311
3312   overlap = 0;
3313   GNUNET_assert (NULL != t);
3314
3315   for (i = 0; i < path->length; i++)
3316   {
3317     for (iter = t->connection_head; NULL != iter; iter = iter->next)
3318     {
3319       aux = GCC_get_path (iter->c);
3320       if (NULL == aux)
3321         continue;
3322
3323       for (j = 0; j < aux->length; j++)
3324       {
3325         if (path->peers[i] == aux->peers[j])
3326         {
3327           overlap++;
3328           break;
3329         }
3330       }
3331     }
3332   }
3333   return path->length + overlap;
3334 }
3335
3336
3337 /**
3338  * Get the static string for the peer this tunnel is directed.
3339  *
3340  * @param t Tunnel.
3341  *
3342  * @return Static string the destination peer's ID.
3343  */
3344 const char *
3345 GCT_2s (const struct CadetTunnel *t)
3346 {
3347   if (NULL == t)
3348     return "(NULL)";
3349
3350   return GCP_2s (t->peer);
3351 }
3352
3353
3354 /******************************************************************************/
3355 /*****************************    INFO/DEBUG    *******************************/
3356 /******************************************************************************/
3357
3358 static void
3359 ax_debug (const struct CadetTunnelAxolotl *ax, enum GNUNET_ErrorType level)
3360 {
3361   struct GNUNET_CRYPTO_EcdhePublicKey pub;
3362   struct CadetTunnelSkippedKey *iter;
3363
3364   LOG2 (level, "TTT  RK  \t %s\n",
3365         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->RK));
3366
3367   LOG2 (level, "TTT  HKs \t %s\n",
3368         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->HKs));
3369   LOG2 (level, "TTT  HKr \t %s\n",
3370         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->HKr));
3371   LOG2 (level, "TTT  NHKs\t %s\n",
3372         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->NHKs));
3373   LOG2 (level, "TTT  NHKr\t %s\n",
3374         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->NHKr));
3375
3376   LOG2 (level, "TTT  CKs \t %s\n",
3377         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->CKs));
3378   LOG2 (level, "TTT  CKr \t %s\n",
3379         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->CKr));
3380
3381   GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs, &pub);
3382   LOG2 (level, "TTT  DHRs\t %s\n",
3383         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &pub));
3384   LOG2 (level, "TTT  DHRr\t %s\n",
3385         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->DHRr));
3386
3387   LOG2 (level, "TTT  Nr\t %u\tNs\t%u\n", ax->Nr, ax->Ns);
3388   LOG2 (level, "TTT  PNs\t %u\tSkipped\t%u\n", ax->PNs, ax->skipped);
3389   LOG2 (level, "TTT  Ratchet\t%u\n", ax->ratchet_flag);
3390
3391   for (iter = ax->skipped_head; NULL != iter; iter = iter->next)
3392   {
3393     LOG2 (level, "TTT    HK\t %s\n",
3394           GNUNET_i2s ((struct GNUNET_PeerIdentity *) &iter->HK));
3395     LOG2 (level, "TTT    MK\t %s\n",
3396           GNUNET_i2s ((struct GNUNET_PeerIdentity *) &iter->MK));
3397   }
3398 }
3399
3400 /**
3401  * Log all possible info about the tunnel state.
3402  *
3403  * @param t Tunnel to debug.
3404  * @param level Debug level to use.
3405  */
3406 void
3407 GCT_debug (const struct CadetTunnel *t, enum GNUNET_ErrorType level)
3408 {
3409   struct CadetTChannel *iter_ch;
3410   struct CadetTConnection *iter_c;
3411   int do_log;
3412
3413   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
3414                                        "cadet-tun",
3415                                        __FILE__, __FUNCTION__, __LINE__);
3416   if (0 == do_log)
3417     return;
3418
3419   LOG2 (level, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
3420   LOG2 (level, "TTT  cstate %s, estate %s\n",
3421        cstate2s (t->cstate), estate2s (t->estate));
3422 #if DUMP_KEYS_TO_STDERR
3423   ax_debug (t->ax, level);
3424 #endif
3425   LOG2 (level, "TTT  tq_head %p, tq_tail %p\n", t->tq_head, t->tq_tail);
3426   LOG2 (level, "TTT  destroy %p\n", t->destroy_task);
3427   LOG2 (level, "TTT  channels:\n");
3428   for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = iter_ch->next)
3429   {
3430     GCCH_debug (iter_ch->ch, level);
3431   }
3432
3433   LOG2 (level, "TTT  connections:\n");
3434   for (iter_c = t->connection_head; NULL != iter_c; iter_c = iter_c->next)
3435   {
3436     GCC_debug (iter_c->c, level);
3437   }
3438
3439   LOG2 (level, "TTT DEBUG TUNNEL END\n");
3440 }
3441
3442
3443 /**
3444  * Iterate all tunnels.
3445  *
3446  * @param iter Iterator.
3447  * @param cls Closure for @c iter.
3448  */
3449 void
3450 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
3451 {
3452   GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
3453 }
3454
3455
3456 /**
3457  * Count all tunnels.
3458  *
3459  * @return Number of tunnels to remote peers kept by this peer.
3460  */
3461 unsigned int
3462 GCT_count_all (void)
3463 {
3464   return GNUNET_CONTAINER_multipeermap_size (tunnels);
3465 }
3466
3467
3468 /**
3469  * Iterate all connections of a tunnel.
3470  *
3471  * @param t Tunnel whose connections to iterate.
3472  * @param iter Iterator.
3473  * @param cls Closure for @c iter.
3474  */
3475 void
3476 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
3477 {
3478   struct CadetTConnection *ct;
3479
3480   for (ct = t->connection_head; NULL != ct; ct = ct->next)
3481     iter (cls, ct->c);
3482 }
3483
3484
3485 /**
3486  * Iterate all channels of a tunnel.
3487  *
3488  * @param t Tunnel whose channels to iterate.
3489  * @param iter Iterator.
3490  * @param cls Closure for @c iter.
3491  */
3492 void
3493 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
3494 {
3495   struct CadetTChannel *cht;
3496
3497   for (cht = t->channel_head; NULL != cht; cht = cht->next)
3498     iter (cls, cht->ch);
3499 }
3500