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