cleaning up some CADET logic, improving types used
[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_ChannelNumber next_chid;
314
315   /**
316    * Destroy flag: if true, destroy on last message.
317    */
318   struct GNUNET_SCHEDULER_Task * destroy_task;
319
320   /**
321    * Queued messages, to transmit once tunnel gets connected.
322    */
323   struct CadetTunnelDelayed *tq_head;
324   struct CadetTunnelDelayed *tq_tail;
325
326   /**
327    * Task to trim connections if too many are present.
328    */
329   struct GNUNET_SCHEDULER_Task * trim_connections_task;
330
331   /**
332    * Ephemeral message in the queue (to avoid queueing more than one).
333    */
334   struct CadetConnectionQueue *ephm_h;
335
336   /**
337    * Pong message in the queue.
338    */
339   struct CadetConnectionQueue *pong_h;
340 };
341
342
343 /**
344  * Struct used to save messages in a non-ready tunnel to send once connected.
345  */
346 struct CadetTunnelDelayed
347 {
348   /**
349    * DLL
350    */
351   struct CadetTunnelDelayed *next;
352   struct CadetTunnelDelayed *prev;
353
354   /**
355    * Tunnel.
356    */
357   struct CadetTunnel *t;
358
359   /**
360    * Tunnel queue given to the channel to cancel request. Update on send_queued.
361    */
362   struct CadetTunnelQueue *tq;
363
364   /**
365    * Message to send.
366    */
367   /* struct GNUNET_MessageHeader *msg; */
368 };
369
370
371 /**
372  * Handle for messages queued but not yet sent.
373  */
374 struct CadetTunnelQueue
375 {
376   /**
377    * Connection queue handle, to cancel if necessary.
378    */
379   struct CadetConnectionQueue *cq;
380
381   /**
382    * Handle in case message hasn't been given to a connection yet.
383    */
384   struct CadetTunnelDelayed *tqd;
385
386   /**
387    * Continuation to call once sent.
388    */
389   GCT_sent cont;
390
391   /**
392    * Closure for @c cont.
393    */
394   void *cont_cls;
395 };
396
397
398 /******************************************************************************/
399 /*******************************   GLOBALS  ***********************************/
400 /******************************************************************************/
401
402 /**
403  * Global handle to the statistics service.
404  */
405 extern struct GNUNET_STATISTICS_Handle *stats;
406
407 /**
408  * Local peer own ID (memory efficient handle).
409  */
410 extern GNUNET_PEER_Id myid;
411
412 /**
413  * Local peer own ID (full value).
414  */
415 extern struct GNUNET_PeerIdentity my_full_id;
416
417
418 /**
419  * Don't try to recover tunnels if shutting down.
420  */
421 extern int shutting_down;
422
423
424 /**
425  * Set of all tunnels, in order to trigger a new exchange on rekey.
426  * Indexed by peer's ID.
427  */
428 static struct GNUNET_CONTAINER_MultiPeerMap *tunnels;
429
430 /**
431  * Own Peer ID private key.
432  */
433 const static struct GNUNET_CRYPTO_EddsaPrivateKey *id_key;
434
435
436 /********************************  AXOLOTL ************************************/
437
438 /**
439  * How many messages are needed to trigger a ratchet advance.
440  */
441 static unsigned long long ratchet_messages;
442
443 /**
444  * How long until we trigger a ratched advance.
445  */
446 static struct GNUNET_TIME_Relative ratchet_time;
447
448
449 /******************************************************************************/
450 /********************************   STATIC  ***********************************/
451 /******************************************************************************/
452
453 /**
454  * Get string description for tunnel connectivity state.
455  *
456  * @param cs Tunnel state.
457  *
458  * @return String representation.
459  */
460 static const char *
461 cstate2s (enum CadetTunnelCState cs)
462 {
463   static char buf[32];
464
465   switch (cs)
466   {
467     case CADET_TUNNEL_NEW:
468       return "CADET_TUNNEL_NEW";
469     case CADET_TUNNEL_SEARCHING:
470       return "CADET_TUNNEL_SEARCHING";
471     case CADET_TUNNEL_WAITING:
472       return "CADET_TUNNEL_WAITING";
473     case CADET_TUNNEL_READY:
474       return "CADET_TUNNEL_READY";
475     case CADET_TUNNEL_SHUTDOWN:
476       return "CADET_TUNNEL_SHUTDOWN";
477     default:
478       SPRINTF (buf, "%u (UNKNOWN STATE)", cs);
479       return buf;
480   }
481   return "";
482 }
483
484
485 /**
486  * Get string description for tunnel encryption state.
487  *
488  * @param es Tunnel state.
489  *
490  * @return String representation.
491  */
492 static const char *
493 estate2s (enum CadetTunnelEState es)
494 {
495   static char buf[32];
496
497   switch (es)
498   {
499     case CADET_TUNNEL_KEY_UNINITIALIZED:
500       return "CADET_TUNNEL_KEY_UNINITIALIZED";
501     case CADET_TUNNEL_KEY_SENT:
502       return "CADET_TUNNEL_KEY_SENT";
503     case CADET_TUNNEL_KEY_PING:
504       return "CADET_TUNNEL_KEY_PING";
505     case CADET_TUNNEL_KEY_OK:
506       return "CADET_TUNNEL_KEY_OK";
507     case CADET_TUNNEL_KEY_REKEY:
508       return "CADET_TUNNEL_KEY_REKEY";
509     default:
510       SPRINTF (buf, "%u (UNKNOWN STATE)", es);
511       return buf;
512   }
513   return "";
514 }
515
516
517 /**
518  * @brief Check if tunnel is ready to send traffic.
519  *
520  * Tunnel must be connected and with encryption correctly set up.
521  *
522  * @param t Tunnel to check.
523  *
524  * @return #GNUNET_YES if ready, #GNUNET_NO otherwise
525  */
526 static int
527 is_ready (struct CadetTunnel *t)
528 {
529   int ready;
530   int conn_ok;
531   int enc_ok;
532
533   conn_ok = CADET_TUNNEL_READY == t->cstate;
534   enc_ok = CADET_TUNNEL_KEY_OK == t->estate
535            || CADET_TUNNEL_KEY_REKEY == t->estate
536            || CADET_TUNNEL_KEY_PING == t->estate;
537   ready = conn_ok && enc_ok;
538   ready = ready || GCT_is_loopback (t);
539   return ready;
540 }
541
542
543 /**
544  * Get the channel's buffer. ONLY FOR NON-LOOPBACK CHANNELS!!
545  *
546  * @param tch Tunnel's channel handle.
547  *
548  * @return Amount of messages the channel can still buffer towards the client.
549  */
550 static unsigned int
551 get_channel_buffer (const struct CadetTChannel *tch)
552 {
553   int fwd;
554
555   /* If channel is incoming, is terminal in the FWD direction and fwd is YES */
556   fwd = GCCH_is_terminal (tch->ch, GNUNET_YES);
557
558   return GCCH_get_buffer (tch->ch, fwd);
559 }
560
561
562 /**
563  * Get the channel's allowance status.
564  *
565  * @param tch Tunnel's channel handle.
566  *
567  * @return #GNUNET_YES if we allowed the client to send data to us.
568  */
569 static int
570 get_channel_allowed (const struct CadetTChannel *tch)
571 {
572   int fwd;
573
574   /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
575   fwd = GCCH_is_origin (tch->ch, GNUNET_YES);
576
577   return GCCH_get_allowed (tch->ch, fwd);
578 }
579
580
581 /**
582  * Get the connection's buffer.
583  *
584  * @param tc Tunnel's connection handle.
585  *
586  * @return Amount of messages the connection can still buffer.
587  */
588 static unsigned int
589 get_connection_buffer (const struct CadetTConnection *tc)
590 {
591   int fwd;
592
593   /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
594   fwd = GCC_is_origin (tc->c, GNUNET_YES);
595
596   return GCC_get_buffer (tc->c, fwd);
597 }
598
599
600 /**
601  * Get the connection's allowance.
602  *
603  * @param tc Tunnel's connection handle.
604  *
605  * @return Amount of messages we have allowed the next peer to send us.
606  */
607 static unsigned int
608 get_connection_allowed (const struct CadetTConnection *tc)
609 {
610   int fwd;
611
612   /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
613   fwd = GCC_is_origin (tc->c, GNUNET_YES);
614
615   return GCC_get_allowed (tc->c, fwd);
616 }
617
618
619 /**
620  * Create a new Axolotl ephemeral (ratchet) key.
621  *
622  * @param t Tunnel.
623  */
624 static void
625 new_ephemeral (struct CadetTunnel *t)
626 {
627   GNUNET_free_non_null (t->ax->DHRs);
628   t->ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create();
629   #if DUMP_KEYS_TO_STDERR
630   {
631     struct GNUNET_CRYPTO_EcdhePublicKey pub;
632     GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &pub);
633     LOG (GNUNET_ERROR_TYPE_DEBUG, "  new DHRs generated: pub  %s\n",
634         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &pub));
635   }
636   #endif
637 }
638
639
640 /**
641  * Calculate HMAC.
642  *
643  * @param plaintext Content to HMAC.
644  * @param size Size of @c plaintext.
645  * @param iv Initialization vector for the message.
646  * @param key Key to use.
647  * @param hmac[out] Destination to store the HMAC.
648  */
649 static void
650 t_hmac (const void *plaintext, size_t size,
651         uint32_t iv, const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
652         struct GNUNET_CADET_Hash *hmac)
653 {
654   static const char ctx[] = "cadet authentication key";
655   struct GNUNET_CRYPTO_AuthKey auth_key;
656   struct GNUNET_HashCode hash;
657
658 #if DUMP_KEYS_TO_STDERR
659   LOG (GNUNET_ERROR_TYPE_INFO, "  HMAC %u bytes with key %s\n", size,
660        GNUNET_i2s ((struct GNUNET_PeerIdentity *) key));
661 #endif
662   GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
663                                  &iv, sizeof (iv),
664                                  key, sizeof (*key),
665                                  ctx, sizeof (ctx),
666                                  NULL);
667   /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
668   GNUNET_CRYPTO_hmac (&auth_key, plaintext, size, &hash);
669   GNUNET_memcpy (hmac, &hash, sizeof (*hmac));
670 }
671
672
673 /**
674  * Perform a HMAC.
675  *
676  * @param key Key to use.
677  * @param hash[out] Resulting HMAC.
678  * @param source Source key material (data to HMAC).
679  * @param len Length of @a source.
680  */
681 static void
682 t_ax_hmac_hash (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
683                 struct GNUNET_HashCode *hash,
684                 void *source, unsigned int len)
685 {
686   static const char ctx[] = "axolotl HMAC-HASH";
687   struct GNUNET_CRYPTO_AuthKey auth_key;
688
689   GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
690                                  ctx, sizeof (ctx),
691                                  NULL);
692   GNUNET_CRYPTO_hmac (&auth_key, source, len, hash);
693 }
694
695
696 /**
697  * Derive a key from a HMAC-HASH.
698  *
699  * @param key Key to use for the HMAC.
700  * @param out Key to generate.
701  * @param source Source key material (data to HMAC).
702  * @param len Length of @a source.
703  */
704 static void
705 t_hmac_derive_key (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
706                    struct GNUNET_CRYPTO_SymmetricSessionKey *out,
707                    void *source, unsigned int len)
708 {
709   static const char ctx[] = "axolotl derive key";
710   struct GNUNET_HashCode h;
711
712   t_ax_hmac_hash (key, &h, source, len);
713   GNUNET_CRYPTO_kdf (out, sizeof (*out), ctx, sizeof (ctx),
714                      &h, sizeof (h), NULL);
715 }
716
717
718 /**
719  * Encrypt data with the axolotl tunnel key.
720  *
721  * @param t Tunnel whose key to use.
722  * @param dst Destination for the encrypted data.
723  * @param src Source of the plaintext. Can overlap with @c dst.
724  * @param size Size of the plaintext.
725  *
726  * @return Size of the encrypted data.
727  */
728 static int
729 t_ax_encrypt (struct CadetTunnel *t, void *dst, const void *src, size_t size)
730 {
731   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
732   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
733   struct CadetTunnelAxolotl *ax;
734   size_t out_size;
735
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_Encrypted *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_Encrypted *src,
878              struct GNUNET_CADET_Encrypted *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_Encrypted *src, size_t size)
917 {
918   struct CadetTunnelSkippedKey *key;
919   struct GNUNET_CADET_Hash *hmac;
920   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
921   struct GNUNET_CADET_Encrypted 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_Encrypted);
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_Encrypted));
952   len = size - sizeof (struct GNUNET_CADET_Encrypted);
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_Encrypted *src,
1096                            size_t size)
1097 {
1098   struct CadetTunnelAxolotl *ax;
1099   struct GNUNET_CADET_Hash msg_hmac;
1100   struct GNUNET_HashCode hmac;
1101   struct GNUNET_CADET_Encrypted 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_Encrypted);
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_Encrypted *ax_msg;
1326   struct CadetTunnelQueue *tq;
1327   size_t size = ntohs (message->size);
1328   char cbuf[sizeof (struct GNUNET_CADET_Encrypted) + size] GNUNET_ALIGN;
1329   size_t esize;
1330   uint32_t mid;
1331   uint16_t type;
1332   int fwd;
1333
1334   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GCT_2s (t));
1335
1336   if (GNUNET_NO == is_ready (t))
1337   {
1338     struct CadetTunnelDelayed *tqd;
1339     /* A non null existing_q indicates sending of queued data.
1340      * Should only happen after tunnel becomes ready.
1341      */
1342     GNUNET_assert (NULL == existing_q);
1343     tqd = queue_data (t, message);
1344     if (NULL == cont)
1345       return NULL;
1346     tq = GNUNET_new (struct CadetTunnelQueue);
1347     tq->tqd = tqd;
1348     tqd->tq = tq;
1349     tq->cont = cont;
1350     tq->cont_cls = cont_cls;
1351     return tq;
1352   }
1353
1354   GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1355
1356   ax_msg = (struct GNUNET_CADET_Encrypted *) cbuf;
1357   msg = &ax_msg->header;
1358   msg->size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
1359   msg->type = htons (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
1360   esize = t_ax_encrypt (t, &ax_msg[1], message, size);
1361   ax_msg->Ns = htonl (t->ax->Ns++);
1362   ax_msg->PNs = htonl (t->ax->PNs);
1363   GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &ax_msg->DHRs);
1364   t_h_encrypt (t, ax_msg);
1365   t_hmac (&ax_msg->Ns, AX_HEADER_SIZE + esize, 0, &t->ax->HKs, &ax_msg->hmac);
1366   GNUNET_assert (esize == size);
1367
1368   if (NULL == c)
1369     c = tunnel_get_connection (t);
1370   if (NULL == c)
1371   {
1372     /* Why is tunnel 'ready'? Should have been queued! */
1373     if (NULL != t->destroy_task)
1374     {
1375       GNUNET_break (0);
1376       GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1377     }
1378     return NULL; /* Drop... */
1379   }
1380   fwd = GCC_is_origin (c, GNUNET_YES);
1381   ax_msg->cid = *GCC_get_id (c);
1382   ax_msg->pid = htonl (GCC_get_pid (c, fwd));
1383
1384   mid = 0;
1385   type = ntohs (message->type);
1386   switch (type)
1387   {
1388     case GNUNET_MESSAGE_TYPE_CADET_DATA:
1389     case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1390       if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
1391         mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
1392       else
1393         mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
1394       /* Fall thru */
1395     case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1396     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1397     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1398     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1399     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1400       break;
1401     default:
1402       GNUNET_break (0);
1403       LOG (GNUNET_ERROR_TYPE_ERROR, "type %s not valid\n", GC_m2s (type));
1404   }
1405   LOG (GNUNET_ERROR_TYPE_DEBUG,
1406        "Sending message of type %s with PID %u and CID %s\n",
1407        GC_m2s (type),
1408        htonl (ax_msg->pid),
1409        GC_h2s (&ax_msg->cid));
1410
1411   if (NULL == cont)
1412   {
1413     (void) GCC_send_prebuilt_message (msg, type, mid, c, fwd,
1414                                       force, NULL, NULL);
1415     return NULL;
1416   }
1417   if (NULL == existing_q)
1418   {
1419     tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
1420   }
1421   else
1422   {
1423     tq = existing_q;
1424     tq->tqd = NULL;
1425   }
1426   tq->cont = cont;
1427   tq->cont_cls = cont_cls;
1428   tq->cq = GCC_send_prebuilt_message (msg, type, mid, c, fwd, force,
1429                                       &tun_message_sent, tq);
1430   GNUNET_assert (NULL != tq->cq);
1431
1432   return tq;
1433 }
1434
1435
1436 /**
1437  * Send all cached messages that we can, tunnel is online.
1438  *
1439  * @param t Tunnel that holds the messages. Cannot be loopback.
1440  */
1441 static void
1442 send_queued_data (struct CadetTunnel *t)
1443 {
1444   struct CadetTunnelDelayed *tqd;
1445   struct CadetTunnelDelayed *next;
1446   unsigned int room;
1447
1448   LOG (GNUNET_ERROR_TYPE_INFO, "Send queued data, tunnel %s\n", GCT_2s (t));
1449
1450   if (GCT_is_loopback (t))
1451   {
1452     GNUNET_break (0);
1453     return;
1454   }
1455
1456   if (GNUNET_NO == is_ready (t))
1457   {
1458     LOG (GNUNET_ERROR_TYPE_WARNING, "  not ready yet: %s/%s\n",
1459          estate2s (t->estate), cstate2s (t->cstate));
1460     return;
1461   }
1462
1463   room = GCT_get_connections_buffer (t);
1464   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer space: %u\n", room);
1465   LOG (GNUNET_ERROR_TYPE_DEBUG, "  tq head: %p\n", t->tq_head);
1466   for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
1467   {
1468     LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
1469     next = tqd->next;
1470     room--;
1471     send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
1472                            tqd->t, NULL, GNUNET_YES,
1473                            NULL != tqd->tq ? tqd->tq->cont : NULL,
1474                            NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
1475                            tqd->tq);
1476     unqueue_data (tqd);
1477   }
1478   LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
1479 }
1480
1481
1482 /**
1483  * @brief Resend the KX until we complete the handshake.
1484  *
1485  * @param cls Closure (tunnel).
1486  */
1487 static void
1488 kx_resend (void *cls)
1489 {
1490   struct CadetTunnel *t = cls;
1491
1492   t->rekey_task = NULL;
1493   if (CADET_TUNNEL_KEY_OK == t->estate)
1494   {
1495     /* Should have been canceled on estate change */
1496     GNUNET_break (0);
1497     return;
1498   }
1499
1500   GCT_send_kx (t, CADET_TUNNEL_KEY_SENT >= t->estate);
1501 }
1502
1503
1504 /**
1505  * Callback called when a queued message is sent.
1506  *
1507  * @param cls Closure.
1508  * @param c Connection this message was on.
1509  * @param type Type of message sent.
1510  * @param fwd Was this a FWD going message?
1511  * @param size Size of the message.
1512  */
1513 static void
1514 ephm_sent (void *cls,
1515            struct CadetConnection *c,
1516            struct CadetConnectionQueue *q,
1517            uint16_t type, int fwd, size_t size)
1518 {
1519   struct CadetTunnel *t = cls;
1520   LOG (GNUNET_ERROR_TYPE_DEBUG, "ephemeral sent %s\n", GC_m2s (type));
1521
1522   t->ephm_h = NULL;
1523
1524   if (CADET_TUNNEL_KEY_OK == t->estate)
1525     return;
1526
1527   if (NULL != t->rekey_task)
1528   {
1529     GNUNET_break (0);
1530     GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1531     GNUNET_SCHEDULER_cancel (t->rekey_task);
1532   }
1533   t->rekey_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
1534                                                 &kx_resend, t);
1535
1536 }
1537
1538
1539 /**
1540  * Called only on shutdown, destroy every tunnel.
1541  *
1542  * @param cls Closure (unused).
1543  * @param key Current public key.
1544  * @param value Value in the hash map (tunnel).
1545  *
1546  * @return #GNUNET_YES, so we should continue to iterate,
1547  */
1548 static int
1549 destroy_iterator (void *cls,
1550                 const struct GNUNET_PeerIdentity *key,
1551                 void *value)
1552 {
1553   struct CadetTunnel *t = value;
1554
1555   LOG (GNUNET_ERROR_TYPE_DEBUG,
1556        "GCT_shutdown destroying tunnel at %p\n", t);
1557   GCT_destroy (t);
1558   return GNUNET_YES;
1559 }
1560
1561
1562 /**
1563  * Notify remote peer that we don't know a channel he is talking about,
1564  * probably CHANNEL_DESTROY was missed.
1565  *
1566  * @param t Tunnel on which to notify.
1567  * @param gid ID of the channel.
1568  */
1569 static void
1570 send_channel_destroy (struct CadetTunnel *t,
1571                       struct GNUNET_CADET_ChannelNumber gid)
1572 {
1573   struct GNUNET_CADET_ChannelManage msg;
1574
1575   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
1576   msg.header.size = htons (sizeof (msg));
1577   msg.chid = gid;
1578
1579   LOG (GNUNET_ERROR_TYPE_DEBUG,
1580        "WARNING destroying unknown channel %u on tunnel %s\n",
1581        ntohl (gid.cn),
1582        GCT_2s (t));
1583   send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
1584 }
1585
1586
1587 /**
1588  * Demultiplex data per channel and call appropriate channel handler.
1589  *
1590  * @param t Tunnel on which the data came.
1591  * @param msg Data message.
1592  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1593  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1594  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1595  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1596  */
1597 static void
1598 handle_data (struct CadetTunnel *t,
1599              const struct GNUNET_CADET_Data *msg,
1600              int fwd)
1601 {
1602   struct CadetChannel *ch;
1603   char buf[128];
1604   size_t size;
1605   uint16_t type;
1606
1607   /* Check size */
1608   size = ntohs (msg->header.size);
1609   if (size <
1610       sizeof (struct GNUNET_CADET_Data) +
1611       sizeof (struct GNUNET_MessageHeader))
1612   {
1613     GNUNET_break (0);
1614     return;
1615   }
1616   type = ntohs (msg[1].header.type);
1617   LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n", GC_m2s (type));
1618   SPRINTF (buf, "# received payload of type %hu", type);
1619   GNUNET_STATISTICS_update (stats, buf, 1, GNUNET_NO);
1620
1621
1622   /* Check channel */
1623   ch = GCT_get_channel (t, msg->chid);
1624   if (NULL == ch)
1625   {
1626     GNUNET_STATISTICS_update (stats,
1627                               "# data on unknown channel",
1628                               1,
1629                               GNUNET_NO);
1630     LOG (GNUNET_ERROR_TYPE_DEBUG,
1631          "channel 0x%X unknown\n",
1632          ntohl (msg->chid.cn));
1633     send_channel_destroy (t, msg->chid);
1634     return;
1635   }
1636
1637   GCCH_handle_data (ch, msg, fwd);
1638 }
1639
1640
1641 /**
1642  * Demultiplex data ACKs per channel and update appropriate channel buffer info.
1643  *
1644  * @param t Tunnel on which the DATA ACK came.
1645  * @param msg DATA ACK message.
1646  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1647  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1648  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1649  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1650  */
1651 static void
1652 handle_data_ack (struct CadetTunnel *t,
1653                  const struct GNUNET_CADET_DataACK *msg,
1654                  int fwd)
1655 {
1656   struct CadetChannel *ch;
1657   size_t size;
1658
1659   /* Check size */
1660   size = ntohs (msg->header.size);
1661   if (size != sizeof (struct GNUNET_CADET_DataACK))
1662   {
1663     GNUNET_break (0);
1664     return;
1665   }
1666
1667   /* Check channel */
1668   ch = GCT_get_channel (t, msg->chid);
1669   if (NULL == ch)
1670   {
1671     GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
1672                               1, GNUNET_NO);
1673     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1674          ntohl (msg->chid.cn));
1675     return;
1676   }
1677
1678   GCCH_handle_data_ack (ch, msg, fwd);
1679 }
1680
1681
1682 /**
1683  * Handle channel create.
1684  *
1685  * @param t Tunnel on which the message came.
1686  * @param msg ChannelCreate message.
1687  */
1688 static void
1689 handle_ch_create (struct CadetTunnel *t,
1690                   const struct GNUNET_CADET_ChannelCreate *msg)
1691 {
1692   struct CadetChannel *ch;
1693   size_t size;
1694
1695   /* Check size */
1696   size = ntohs (msg->header.size);
1697   if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
1698   {
1699     GNUNET_break_op (0);
1700     return;
1701   }
1702
1703   /* Check channel */
1704   ch = GCT_get_channel (t, msg->chid);
1705   if (NULL != ch && ! GCT_is_loopback (t))
1706   {
1707     /* Probably a retransmission, safe to ignore */
1708     LOG (GNUNET_ERROR_TYPE_DEBUG, "   already exists...\n");
1709   }
1710   ch = GCCH_handle_create (t, msg);
1711   if (NULL != ch)
1712     GCT_add_channel (t, ch);
1713 }
1714
1715
1716
1717 /**
1718  * Handle channel NACK: check correctness and call channel handler for NACKs.
1719  *
1720  * @param t Tunnel on which the NACK came.
1721  * @param msg NACK message.
1722  */
1723 static void
1724 handle_ch_nack (struct CadetTunnel *t,
1725                 const struct GNUNET_CADET_ChannelManage *msg)
1726 {
1727   struct CadetChannel *ch;
1728   size_t size;
1729
1730   /* Check size */
1731   size = ntohs (msg->header.size);
1732   if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1733   {
1734     GNUNET_break (0);
1735     return;
1736   }
1737
1738   /* Check channel */
1739   ch = GCT_get_channel (t, msg->chid);
1740   if (NULL == ch)
1741   {
1742     GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
1743                               1, GNUNET_NO);
1744     LOG (GNUNET_ERROR_TYPE_DEBUG,
1745          "WARNING channel %u unknown\n",
1746          ntohl (msg->chid.cn));
1747     return;
1748   }
1749
1750   GCCH_handle_nack (ch);
1751 }
1752
1753
1754 /**
1755  * Handle a CHANNEL ACK (SYNACK/ACK).
1756  *
1757  * @param t Tunnel on which the CHANNEL ACK came.
1758  * @param msg CHANNEL ACK message.
1759  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1760  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1761  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1762  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1763  */
1764 static void
1765 handle_ch_ack (struct CadetTunnel *t,
1766                const struct GNUNET_CADET_ChannelManage *msg,
1767                int fwd)
1768 {
1769   struct CadetChannel *ch;
1770   size_t size;
1771
1772   /* Check size */
1773   size = ntohs (msg->header.size);
1774   if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1775   {
1776     GNUNET_break (0);
1777     return;
1778   }
1779
1780   /* Check channel */
1781   ch = GCT_get_channel (t, msg->chid);
1782   if (NULL == ch)
1783   {
1784     GNUNET_STATISTICS_update (stats,
1785                               "# channel ack on unknown channel",
1786                               1,
1787                               GNUNET_NO);
1788     LOG (GNUNET_ERROR_TYPE_DEBUG,
1789          "WARNING channel %u unknown\n",
1790          ntohl (msg->chid.cn));
1791     return;
1792   }
1793
1794   GCCH_handle_ack (ch, msg, fwd);
1795 }
1796
1797
1798 /**
1799  * Handle a channel destruction message.
1800  *
1801  * @param t Tunnel on which the message came.
1802  * @param msg Channel destroy message.
1803  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1804  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1805  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1806  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1807  */
1808 static void
1809 handle_ch_destroy (struct CadetTunnel *t,
1810                    const struct GNUNET_CADET_ChannelManage *msg,
1811                    int fwd)
1812 {
1813   struct CadetChannel *ch;
1814   size_t size;
1815
1816   /* Check size */
1817   size = ntohs (msg->header.size);
1818   if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1819   {
1820     GNUNET_break (0);
1821     return;
1822   }
1823
1824   /* Check channel */
1825   ch = GCT_get_channel (t, msg->chid);
1826   if (NULL == ch)
1827   {
1828     /* Probably a retransmission, safe to ignore */
1829     return;
1830   }
1831
1832   GCCH_handle_destroy (ch, msg, fwd);
1833 }
1834
1835
1836 /**
1837  * Free Axolotl data.
1838  *
1839  * @param t Tunnel.
1840  */
1841 static void
1842 destroy_ax (struct CadetTunnel *t)
1843 {
1844   if (NULL == t->ax)
1845     return;
1846
1847   GNUNET_free_non_null (t->ax->DHRs);
1848   GNUNET_free_non_null (t->ax->kx_0);
1849   while (NULL != t->ax->skipped_head)
1850     delete_skipped_key (t, t->ax->skipped_head);
1851   GNUNET_assert (0 == t->ax->skipped);
1852
1853   GNUNET_free (t->ax);
1854   t->ax = NULL;
1855
1856   if (NULL != t->rekey_task)
1857   {
1858     GNUNET_SCHEDULER_cancel (t->rekey_task);
1859     t->rekey_task = NULL;
1860   }
1861   if (NULL != t->ephm_h)
1862   {
1863     GCC_cancel (t->ephm_h);
1864     t->ephm_h = NULL;
1865   }
1866 }
1867
1868
1869 /**
1870  * Demultiplex by message type and call appropriate handler for a message
1871  * towards a channel of a local tunnel.
1872  *
1873  * @param t Tunnel this message came on.
1874  * @param msgh Message header.
1875  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1876  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1877  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1878  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1879  */
1880 static void
1881 handle_decrypted (struct CadetTunnel *t,
1882                   const struct GNUNET_MessageHeader *msgh,
1883                   int fwd)
1884 {
1885   uint16_t type;
1886   char buf[256];
1887
1888   type = ntohs (msgh->type);
1889   LOG (GNUNET_ERROR_TYPE_DEBUG, "<-- %s on %s\n", GC_m2s (type), GCT_2s (t));
1890   SPRINTF (buf, "# received encrypted of type %hu (%s)", type, GC_m2s (type));
1891   GNUNET_STATISTICS_update (stats, buf, 1, GNUNET_NO);
1892
1893   switch (type)
1894   {
1895     case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1896       /* Do nothing, connection aleady got updated. */
1897       GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
1898       break;
1899
1900     case GNUNET_MESSAGE_TYPE_CADET_DATA:
1901       /* Don't send hop ACK, wait for client to ACK */
1902       handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
1903       break;
1904
1905     case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1906       handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
1907       break;
1908
1909     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1910       handle_ch_create (t, (struct GNUNET_CADET_ChannelCreate *) msgh);
1911       break;
1912
1913     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1914       handle_ch_nack (t, (struct GNUNET_CADET_ChannelManage *) msgh);
1915       break;
1916
1917     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1918       handle_ch_ack (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
1919       break;
1920
1921     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1922       handle_ch_destroy (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
1923       break;
1924
1925     default:
1926       GNUNET_break_op (0);
1927       LOG (GNUNET_ERROR_TYPE_WARNING,
1928            "end-to-end message not known (%u)\n",
1929            ntohs (msgh->type));
1930       GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1931   }
1932 }
1933
1934
1935 /******************************************************************************/
1936 /********************************    API    ***********************************/
1937 /******************************************************************************/
1938
1939 /**
1940  * Decrypt and process an encrypted message.
1941  *
1942  * Calls the appropriate handler for a message in a channel of a local tunnel.
1943  *
1944  * @param t Tunnel this message came on.
1945  * @param msg Message header.
1946  */
1947 void
1948 GCT_handle_encrypted (struct CadetTunnel *t,
1949                       const struct GNUNET_CADET_Encrypted *msg)
1950 {
1951   uint16_t size = ntohs (msg->header.size);
1952   char cbuf [size];
1953   int decrypted_size;
1954   const struct GNUNET_MessageHeader *msgh;
1955   unsigned int off;
1956
1957   GNUNET_STATISTICS_update (stats, "# received encrypted", 1, GNUNET_NO);
1958
1959   decrypted_size = t_ax_decrypt_and_validate (t, cbuf, msg, size);
1960
1961   if (-1 == decrypted_size)
1962   {
1963     GNUNET_STATISTICS_update (stats, "# unable to decrypt", 1, GNUNET_NO);
1964     if (CADET_TUNNEL_KEY_PING <= t->estate)
1965     {
1966       GNUNET_break_op (0);
1967       LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong crypto, tunnel %s\n", GCT_2s (t));
1968       GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1969     }
1970     return;
1971   }
1972   GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
1973
1974   /* FIXME: this is bad, as the structs returned from
1975      this loop may be unaligned, see util's MST for
1976      how to do this right. */
1977   off = 0;
1978   while (off + sizeof (struct GNUNET_MessageHeader) <= decrypted_size)
1979   {
1980     uint16_t msize;
1981
1982     msgh = (const struct GNUNET_MessageHeader *) &cbuf[off];
1983     msize = ntohs (msgh->size);
1984     if (msize < sizeof (struct GNUNET_MessageHeader))
1985     {
1986       GNUNET_break_op (0);
1987       return;
1988     }
1989     if (off + msize < decrypted_size)
1990     {
1991       GNUNET_break_op (0);
1992       return;
1993     }
1994     handle_decrypted (t, msgh, GNUNET_SYSERR);
1995     off += msize;
1996   }
1997 }
1998
1999
2000 /**
2001  * Handle a Key eXchange message.
2002  *
2003  * @param t Tunnel on which the message came.
2004  * @param msg KX message itself.
2005  */
2006 void
2007 GCT_handle_kx (struct CadetTunnel *t,
2008                const struct GNUNET_CADET_KX *msg)
2009 {
2010   struct CadetTunnelAxolotl *ax;
2011   struct GNUNET_HashCode key_material[3];
2012   struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
2013   const char salt[] = "CADET Axolotl salt";
2014   const struct GNUNET_PeerIdentity *pid;
2015   int am_I_alice;
2016
2017   CADET_TIMING_START;
2018
2019   LOG (GNUNET_ERROR_TYPE_INFO, "<== {        KX} on %s\n", GCT_2s (t));
2020
2021   if (NULL == t->ax)
2022   {
2023     /* Something is wrong if ax is NULL. Whose fault it is? */
2024     return;
2025   }
2026   ax = t->ax;
2027
2028   pid = GCT_get_destination (t);
2029   if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2030     am_I_alice = GNUNET_YES;
2031   else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2032     am_I_alice = GNUNET_NO;
2033   else
2034   {
2035     GNUNET_break_op (0);
2036     return;
2037   }
2038
2039   if (0 != (GNUNET_CADET_KX_FLAG_FORCE_REPLY & ntohl (msg->flags)))
2040   {
2041     if (NULL != t->rekey_task)
2042     {
2043       GNUNET_SCHEDULER_cancel (t->rekey_task);
2044       t->rekey_task = NULL;
2045     }
2046     GCT_send_kx (t, GNUNET_NO);
2047   }
2048
2049   if (0 == memcmp (&ax->DHRr, &msg->ratchet_key, sizeof(msg->ratchet_key)))
2050   {
2051     LOG (GNUNET_ERROR_TYPE_INFO, " known ratchet key, exit\n");
2052     return;
2053   }
2054
2055   LOG (GNUNET_ERROR_TYPE_INFO, " is Alice? %s\n", am_I_alice ? "YES" : "NO");
2056
2057   ax->DHRr = msg->ratchet_key;
2058
2059   /* ECDH A B0 */
2060   if (GNUNET_YES == am_I_alice)
2061   {
2062     GNUNET_CRYPTO_eddsa_ecdh (id_key,              /* A */
2063                               &msg->ephemeral_key, /* B0 */
2064                               &key_material[0]);
2065   }
2066   else
2067   {
2068     GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0,            /* B0 */
2069                               &pid->public_key,    /* A */
2070                               &key_material[0]);
2071   }
2072
2073   /* ECDH A0 B */
2074   if (GNUNET_YES == am_I_alice)
2075   {
2076     GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0,            /* A0 */
2077                               &pid->public_key,    /* B */
2078                               &key_material[1]);
2079   }
2080   else
2081   {
2082     GNUNET_CRYPTO_eddsa_ecdh (id_key,              /* A */
2083                               &msg->ephemeral_key, /* B0 */
2084                               &key_material[1]);
2085
2086
2087   }
2088
2089   /* ECDH A0 B0 */
2090   /* (This is the triple-DH, we could probably safely skip this,
2091      as A0/B0 are already in the key material.) */
2092   GNUNET_CRYPTO_ecc_ecdh (ax->kx_0,             /* A0 or B0 */
2093                           &msg->ephemeral_key,  /* B0 or A0 */
2094                           &key_material[2]);
2095
2096   #if DUMP_KEYS_TO_STDERR
2097   {
2098     unsigned int i;
2099     for (i = 0; i < 3; i++)
2100       LOG (GNUNET_ERROR_TYPE_INFO, "km[%u]: %s\n",
2101            i, GNUNET_h2s (&key_material[i]));
2102   }
2103   #endif
2104
2105   /* KDF */
2106   GNUNET_CRYPTO_kdf (keys, sizeof (keys),
2107                      salt, sizeof (salt),
2108                      &key_material, sizeof (key_material), NULL);
2109
2110   if (0 == memcmp (&ax->RK, &keys[0], sizeof(ax->RK)))
2111   {
2112     LOG (GNUNET_ERROR_TYPE_INFO, " known handshake key, exit\n");
2113     return;
2114   }
2115   ax->RK = keys[0];
2116   if (GNUNET_YES == am_I_alice)
2117   {
2118     ax->HKr = keys[1];
2119     ax->NHKs = keys[2];
2120     ax->NHKr = keys[3];
2121     ax->CKr = keys[4];
2122     ax->ratchet_flag = GNUNET_YES;
2123   }
2124   else
2125   {
2126     ax->HKs = keys[1];
2127     ax->NHKr = keys[2];
2128     ax->NHKs = keys[3];
2129     ax->CKs = keys[4];
2130     ax->ratchet_flag = GNUNET_NO;
2131     ax->ratchet_allowed = GNUNET_NO;
2132     ax->ratchet_counter = 0;
2133     ax->ratchet_expiration =
2134       GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), ratchet_time);
2135   }
2136   ax->PNs = 0;
2137   ax->Nr = 0;
2138   ax->Ns = 0;
2139
2140   GCT_change_estate (t, CADET_TUNNEL_KEY_PING);
2141   send_queued_data (t);
2142
2143   CADET_TIMING_END;
2144 }
2145
2146 /**
2147  * Initialize the tunnel subsystem.
2148  *
2149  * @param c Configuration handle.
2150  * @param key ECC private key, to derive all other keys and do crypto.
2151  */
2152 void
2153 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
2154           const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
2155 {
2156   unsigned int expected_overhead;
2157
2158   LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
2159
2160   expected_overhead = 0;
2161   expected_overhead += sizeof (struct GNUNET_CADET_Encrypted);
2162   expected_overhead += sizeof (struct GNUNET_CADET_Data);
2163   expected_overhead += sizeof (struct GNUNET_CADET_ACK);
2164   GNUNET_assert (GNUNET_CONSTANTS_CADET_P2P_OVERHEAD == expected_overhead);
2165
2166   if (GNUNET_OK !=
2167       GNUNET_CONFIGURATION_get_value_number (c,
2168                                              "CADET",
2169                                              "RATCHET_MESSAGES",
2170                                              &ratchet_messages))
2171   {
2172     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
2173                                "CADET",
2174                                "RATCHET_MESSAGES",
2175                                "USING DEFAULT");
2176     ratchet_messages = 64;
2177   }
2178   if (GNUNET_OK !=
2179       GNUNET_CONFIGURATION_get_value_time (c,
2180                                            "CADET",
2181                                            "RATCHET_TIME",
2182                                            &ratchet_time))
2183   {
2184     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
2185                                "CADET", "RATCHET_TIME", "USING DEFAULT");
2186     ratchet_time = GNUNET_TIME_UNIT_HOURS;
2187   }
2188
2189
2190   id_key = key;
2191   tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
2192 }
2193
2194
2195 /**
2196  * Shut down the tunnel subsystem.
2197  */
2198 void
2199 GCT_shutdown (void)
2200 {
2201   LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down tunnels\n");
2202   GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
2203   GNUNET_CONTAINER_multipeermap_destroy (tunnels);
2204 }
2205
2206
2207 /**
2208  * Create a tunnel.
2209  *
2210  * @param destination Peer this tunnel is towards.
2211  */
2212 struct CadetTunnel *
2213 GCT_new (struct CadetPeer *destination)
2214 {
2215   struct CadetTunnel *t;
2216
2217   t = GNUNET_new (struct CadetTunnel);
2218   t->next_chid.cn = 0;
2219   t->peer = destination;
2220
2221   if (GNUNET_OK !=
2222       GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
2223                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2224   {
2225     GNUNET_break (0);
2226     GNUNET_free (t);
2227     return NULL;
2228   }
2229   t->ax = GNUNET_new (struct CadetTunnelAxolotl);
2230   new_ephemeral (t);
2231   t->ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
2232   return t;
2233 }
2234
2235
2236 /**
2237  * Change the tunnel's connection state.
2238  *
2239  * @param t Tunnel whose connection state to change.
2240  * @param cstate New connection state.
2241  */
2242 void
2243 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
2244 {
2245   if (NULL == t)
2246     return;
2247   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
2248        GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
2249   if (myid != GCP_get_short_id (t->peer) &&
2250       CADET_TUNNEL_READY != t->cstate &&
2251       CADET_TUNNEL_READY == cstate)
2252   {
2253     t->cstate = cstate;
2254     if (CADET_TUNNEL_KEY_OK == t->estate)
2255     {
2256       LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered send queued data\n");
2257       send_queued_data (t);
2258     }
2259     else if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
2260     {
2261       LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered KX\n");
2262       GCT_send_kx (t, GNUNET_NO);
2263     }
2264     else
2265     {
2266       LOG (GNUNET_ERROR_TYPE_DEBUG, "estate %s\n", estate2s (t->estate));
2267     }
2268   }
2269   t->cstate = cstate;
2270
2271   if (CADET_TUNNEL_READY == cstate
2272       && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
2273   {
2274     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered stop dht\n");
2275     GCP_stop_search (t->peer);
2276   }
2277 }
2278
2279
2280 /**
2281  * Change the tunnel encryption state.
2282  *
2283  * If the encryption state changes to OK, stop the rekey task.
2284  *
2285  * @param t Tunnel whose encryption state to change, or NULL.
2286  * @param state New encryption state.
2287  */
2288 void
2289 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
2290 {
2291   enum CadetTunnelEState old;
2292
2293   if (NULL == t)
2294     return;
2295
2296   old = t->estate;
2297   t->estate = state;
2298   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate was %s\n",
2299        GCP_2s (t->peer), estate2s (old));
2300   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate is now %s\n",
2301        GCP_2s (t->peer), estate2s (t->estate));
2302
2303   if (CADET_TUNNEL_KEY_OK != old && CADET_TUNNEL_KEY_OK == t->estate)
2304   {
2305     if (NULL != t->rekey_task)
2306     {
2307       GNUNET_SCHEDULER_cancel (t->rekey_task);
2308       t->rekey_task = NULL;
2309     }
2310     /* Send queued data if tunnel is not loopback */
2311     if (myid != GCP_get_short_id (t->peer))
2312       send_queued_data (t);
2313   }
2314 }
2315
2316
2317 /**
2318  * @brief Check if tunnel has too many connections, and remove one if necessary.
2319  *
2320  * Currently this means the newest connection, unless it is a direct one.
2321  * Implemented as a task to avoid freeing a connection that is in the middle
2322  * of being created/processed.
2323  *
2324  * @param cls Closure (Tunnel to check).
2325  */
2326 static void
2327 trim_connections (void *cls)
2328 {
2329   struct CadetTunnel *t = cls;
2330
2331   t->trim_connections_task = NULL;
2332   if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
2333   {
2334     struct CadetTConnection *iter;
2335     struct CadetTConnection *c;
2336
2337     for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
2338     {
2339       if ((iter->created.abs_value_us > c->created.abs_value_us)
2340           && GNUNET_NO == GCC_is_direct (iter->c))
2341       {
2342         c = iter;
2343       }
2344     }
2345     if (NULL != c)
2346     {
2347       LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
2348            GCT_2s (t));
2349       LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
2350            GCC_2s (c->c));
2351       GCC_destroy (c->c);
2352     }
2353     else
2354     {
2355       GNUNET_break (0);
2356     }
2357   }
2358 }
2359
2360
2361 /**
2362  * Add a connection to a tunnel.
2363  *
2364  * @param t Tunnel.
2365  * @param c Connection.
2366  */
2367 void
2368 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
2369 {
2370   struct CadetTConnection *aux;
2371
2372   GNUNET_assert (NULL != c);
2373
2374   LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
2375   LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
2376   for (aux = t->connection_head; aux != NULL; aux = aux->next)
2377     if (aux->c == c)
2378       return;
2379
2380   aux = GNUNET_new (struct CadetTConnection);
2381   aux->c = c;
2382   aux->created = GNUNET_TIME_absolute_get ();
2383
2384   GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
2385
2386   if (CADET_TUNNEL_SEARCHING == t->cstate)
2387     GCT_change_cstate (t, CADET_TUNNEL_WAITING);
2388
2389   if (NULL != t->trim_connections_task)
2390     t->trim_connections_task = GNUNET_SCHEDULER_add_now (&trim_connections, t);
2391 }
2392
2393
2394 /**
2395  * Remove a connection from a tunnel.
2396  *
2397  * @param t Tunnel.
2398  * @param c Connection.
2399  */
2400 void
2401 GCT_remove_connection (struct CadetTunnel *t,
2402                        struct CadetConnection *c)
2403 {
2404   struct CadetTConnection *aux;
2405   struct CadetTConnection *next;
2406   unsigned int conns;
2407
2408   LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
2409        GCC_2s (c), GCT_2s (t));
2410   for (aux = t->connection_head; aux != NULL; aux = next)
2411   {
2412     next = aux->next;
2413     if (aux->c == c)
2414     {
2415       GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
2416       GNUNET_free (aux);
2417     }
2418   }
2419
2420   conns = GCT_count_connections (t);
2421   if (0 == conns
2422       && NULL == t->destroy_task
2423       && CADET_TUNNEL_SHUTDOWN != t->cstate
2424       && GNUNET_NO == shutting_down)
2425   {
2426     if (0 == GCT_count_any_connections (t))
2427       GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
2428     else
2429       GCT_change_cstate (t, CADET_TUNNEL_WAITING);
2430   }
2431
2432   /* Start new connections if needed */
2433   if (CONNECTIONS_PER_TUNNEL > conns
2434       && CADET_TUNNEL_SHUTDOWN != t->cstate
2435       && GNUNET_NO == shutting_down)
2436   {
2437     LOG (GNUNET_ERROR_TYPE_DEBUG, "  too few connections, getting new ones\n");
2438     GCP_connect (t->peer); /* Will change cstate to WAITING when possible */
2439     return;
2440   }
2441
2442   /* If not marked as ready, no change is needed */
2443   if (CADET_TUNNEL_READY != t->cstate)
2444     return;
2445
2446   /* Check if any connection is ready to maintain cstate */
2447   for (aux = t->connection_head; aux != NULL; aux = aux->next)
2448     if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
2449       return;
2450 }
2451
2452
2453 /**
2454  * Add a channel to a tunnel.
2455  *
2456  * @param t Tunnel.
2457  * @param ch Channel.
2458  */
2459 void
2460 GCT_add_channel (struct CadetTunnel *t,
2461                  struct CadetChannel *ch)
2462 {
2463   struct CadetTChannel *aux;
2464
2465   GNUNET_assert (NULL != ch);
2466
2467   LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
2468
2469   for (aux = t->channel_head; aux != NULL; aux = aux->next)
2470   {
2471     LOG (GNUNET_ERROR_TYPE_DEBUG, "  already there %p\n", aux->ch);
2472     if (aux->ch == ch)
2473       return;
2474   }
2475
2476   aux = GNUNET_new (struct CadetTChannel);
2477   aux->ch = ch;
2478   LOG (GNUNET_ERROR_TYPE_DEBUG,
2479        " adding %p to %p\n", aux, t->channel_head);
2480   GNUNET_CONTAINER_DLL_insert_tail (t->channel_head,
2481                                     t->channel_tail,
2482                                     aux);
2483
2484   if (NULL != t->destroy_task)
2485   {
2486     GNUNET_SCHEDULER_cancel (t->destroy_task);
2487     t->destroy_task = NULL;
2488     LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
2489   }
2490 }
2491
2492
2493 /**
2494  * Remove a channel from a tunnel.
2495  *
2496  * @param t Tunnel.
2497  * @param ch Channel.
2498  */
2499 void
2500 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2501 {
2502   struct CadetTChannel *aux;
2503
2504   LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
2505   for (aux = t->channel_head; aux != NULL; aux = aux->next)
2506   {
2507     if (aux->ch == ch)
2508     {
2509       LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
2510       GNUNET_CONTAINER_DLL_remove (t->channel_head,
2511                                    t->channel_tail,
2512                                    aux);
2513       GNUNET_free (aux);
2514       return;
2515     }
2516   }
2517 }
2518
2519
2520 /**
2521  * Search for a channel by global ID.
2522  *
2523  * @param t Tunnel containing the channel.
2524  * @param chid Public channel number.
2525  *
2526  * @return channel handler, NULL if doesn't exist
2527  */
2528 struct CadetChannel *
2529 GCT_get_channel (struct CadetTunnel *t,
2530                  struct GNUNET_CADET_ChannelNumber chid)
2531 {
2532   struct CadetTChannel *iter;
2533
2534   if (NULL == t)
2535     return NULL;
2536
2537   for (iter = t->channel_head; NULL != iter; iter = iter->next)
2538   {
2539     if (GCCH_get_id (iter->ch).cn == chid.cn)
2540       break;
2541   }
2542
2543   return NULL == iter ? NULL : iter->ch;
2544 }
2545
2546
2547 /**
2548  * @brief Destroy a tunnel and free all resources.
2549  *
2550  * Should only be called a while after the tunnel has been marked as destroyed,
2551  * in case there is a new channel added to the same peer shortly after marking
2552  * the tunnel. This way we avoid a new public key handshake.
2553  *
2554  * @param cls Closure (tunnel to destroy).
2555  */
2556 static void
2557 delayed_destroy (void *cls)
2558 {
2559   struct CadetTunnel *t = cls;
2560   struct CadetTConnection *iter;
2561
2562   t->destroy_task = NULL;
2563   LOG (GNUNET_ERROR_TYPE_DEBUG,
2564        "delayed destroying tunnel %p\n",
2565        t);
2566   t->cstate = CADET_TUNNEL_SHUTDOWN;
2567   for (iter = t->connection_head; NULL != iter; iter = iter->next)
2568   {
2569     GCC_send_destroy (iter->c);
2570   }
2571   GCT_destroy (t);
2572 }
2573
2574
2575 /**
2576  * Tunnel is empty: destroy it.
2577  *
2578  * Notifies all connections about the destruction.
2579  *
2580  * @param t Tunnel to destroy.
2581  */
2582 void
2583 GCT_destroy_empty (struct CadetTunnel *t)
2584 {
2585   if (GNUNET_YES == shutting_down)
2586     return; /* Will be destroyed immediately anyway */
2587
2588   if (NULL != t->destroy_task)
2589   {
2590     LOG (GNUNET_ERROR_TYPE_WARNING,
2591          "Tunnel %s is already scheduled for destruction. Tunnel debug dump:\n",
2592          GCT_2s (t));
2593     GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
2594     GNUNET_break (0);
2595     /* should never happen, tunnel can only become empty once, and the
2596      * task identifier should be NO_TASK (cleaned when the tunnel was created
2597      * or became un-empty)
2598      */
2599     return;
2600   }
2601
2602   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: scheduling destruction\n",
2603        GCT_2s (t));
2604
2605   // FIXME make delay a config option
2606   t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
2607                                                   &delayed_destroy, t);
2608   LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %p\n",
2609        t, t->destroy_task);
2610 }
2611
2612
2613 /**
2614  * Destroy tunnel if empty (no more channels).
2615  *
2616  * @param t Tunnel to destroy if empty.
2617  */
2618 void
2619 GCT_destroy_if_empty (struct CadetTunnel *t)
2620 {
2621   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
2622   if (0 < GCT_count_channels (t))
2623     return;
2624
2625   GCT_destroy_empty (t);
2626 }
2627
2628
2629 /**
2630  * Destroy the tunnel.
2631  *
2632  * This function does not generate any warning traffic to clients or peers.
2633  *
2634  * Tasks:
2635  * Cancel messages belonging to this tunnel queued to neighbors.
2636  * Free any allocated resources linked to the tunnel.
2637  *
2638  * @param t The tunnel to destroy.
2639  */
2640 void
2641 GCT_destroy (struct CadetTunnel *t)
2642 {
2643   struct CadetTConnection *iter_c;
2644   struct CadetTConnection *next_c;
2645   struct CadetTChannel *iter_ch;
2646   struct CadetTChannel *next_ch;
2647   unsigned int keepalives_queued;
2648
2649   if (NULL == t)
2650     return;
2651
2652   LOG (GNUNET_ERROR_TYPE_DEBUG,
2653        "destroying tunnel %s\n",
2654        GCP_2s (t->peer));
2655   GNUNET_break (GNUNET_YES ==
2656                 GNUNET_CONTAINER_multipeermap_remove (tunnels,
2657                                                       GCP_get_id (t->peer), t));
2658
2659   for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
2660   {
2661     next_c = iter_c->next;
2662     GCC_destroy (iter_c->c);
2663   }
2664   for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
2665   {
2666     next_ch = iter_ch->next;
2667     GCCH_destroy (iter_ch->ch);
2668     /* Should only happen on shutdown, but it's ok. */
2669   }
2670   keepalives_queued = 0;
2671   while (NULL != t->tq_head)
2672   {
2673     /* Should have been cleaned by destuction of channel. */
2674     struct GNUNET_MessageHeader *mh;
2675     uint16_t type;
2676
2677     mh = (struct GNUNET_MessageHeader *) &t->tq_head[1];
2678     type = ntohs (mh->type);
2679     if (0 == keepalives_queued && GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE == type)
2680     {
2681       keepalives_queued = 1;
2682       LOG (GNUNET_ERROR_TYPE_DEBUG,
2683            "one keepalive left behind on tunnel shutdown\n");
2684     }
2685     else if (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY == type)
2686     {
2687       LOG (GNUNET_ERROR_TYPE_WARNING,
2688            "tunnel destroyed before a CHANNEL_DESTROY was sent to peer\n");
2689     }
2690     else
2691     {
2692       GNUNET_break (0);
2693       LOG (GNUNET_ERROR_TYPE_ERROR,
2694            "message left behind on tunnel shutdown: %s\n",
2695            GC_m2s (type));
2696     }
2697     unqueue_data (t->tq_head);
2698   }
2699
2700
2701   if (NULL != t->destroy_task)
2702   {
2703     LOG (GNUNET_ERROR_TYPE_DEBUG,
2704          "cancelling dest: %p\n",
2705          t->destroy_task);
2706     GNUNET_SCHEDULER_cancel (t->destroy_task);
2707     t->destroy_task = NULL;
2708   }
2709
2710   if (NULL != t->trim_connections_task)
2711   {
2712     LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling trim: %p\n",
2713          t->trim_connections_task);
2714     GNUNET_SCHEDULER_cancel (t->trim_connections_task);
2715     t->trim_connections_task = NULL;
2716   }
2717
2718   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
2719   GCP_set_tunnel (t->peer, NULL);
2720
2721   if (NULL != t->rekey_task)
2722   {
2723     GNUNET_SCHEDULER_cancel (t->rekey_task);
2724     t->rekey_task = NULL;
2725   }
2726   if (NULL != t->ax)
2727     destroy_ax (t);
2728
2729   GNUNET_free (t);
2730 }
2731
2732
2733 /**
2734  * @brief Use the given path for the tunnel.
2735  * Update the next and prev hops (and RCs).
2736  * (Re)start the path refresh in case the tunnel is locally owned.
2737  *
2738  * @param t Tunnel to update.
2739  * @param p Path to use.
2740  *
2741  * @return Connection created.
2742  */
2743 struct CadetConnection *
2744 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *path)
2745 {
2746   struct CadetConnection *c;
2747   struct GNUNET_CADET_Hash cid;
2748   unsigned int own_pos;
2749
2750   if (NULL == t || NULL == path)
2751   {
2752     GNUNET_break (0);
2753     return NULL;
2754   }
2755
2756   if (CADET_TUNNEL_SHUTDOWN == t->cstate)
2757   {
2758     GNUNET_break (0);
2759     return NULL;
2760   }
2761
2762   for (own_pos = 0; own_pos < path->length; own_pos++)
2763   {
2764     if (path->peers[own_pos] == myid)
2765       break;
2766   }
2767   if (own_pos >= path->length)
2768   {
2769     GNUNET_break_op (0);
2770     return NULL;
2771   }
2772
2773   GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
2774   c = GCC_new (&cid, t, path, own_pos);
2775   if (NULL == c)
2776   {
2777     /* Path was flawed */
2778     return NULL;
2779   }
2780   GCT_add_connection (t, c);
2781   return c;
2782 }
2783
2784
2785 /**
2786  * Count all created connections of a tunnel. Not necessarily ready connections!
2787  *
2788  * @param t Tunnel on which to count.
2789  *
2790  * @return Number of connections created, either being established or ready.
2791  */
2792 unsigned int
2793 GCT_count_any_connections (struct CadetTunnel *t)
2794 {
2795   struct CadetTConnection *iter;
2796   unsigned int count;
2797
2798   if (NULL == t)
2799     return 0;
2800
2801   for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2802     count++;
2803
2804   return count;
2805 }
2806
2807
2808 /**
2809  * Count established (ready) connections of a tunnel.
2810  *
2811  * @param t Tunnel on which to count.
2812  *
2813  * @return Number of connections.
2814  */
2815 unsigned int
2816 GCT_count_connections (struct CadetTunnel *t)
2817 {
2818   struct CadetTConnection *iter;
2819   unsigned int count;
2820
2821   if (NULL == t)
2822     return 0;
2823
2824   for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2825     if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
2826       count++;
2827
2828   return count;
2829 }
2830
2831
2832 /**
2833  * Count channels of a tunnel.
2834  *
2835  * @param t Tunnel on which to count.
2836  *
2837  * @return Number of channels.
2838  */
2839 unsigned int
2840 GCT_count_channels (struct CadetTunnel *t)
2841 {
2842   struct CadetTChannel *iter;
2843   unsigned int count;
2844
2845   for (count = 0, iter = t->channel_head;
2846        NULL != iter;
2847        iter = iter->next, count++) /* skip */;
2848
2849   return count;
2850 }
2851
2852
2853 /**
2854  * Get the connectivity state of a tunnel.
2855  *
2856  * @param t Tunnel.
2857  *
2858  * @return Tunnel's connectivity state.
2859  */
2860 enum CadetTunnelCState
2861 GCT_get_cstate (struct CadetTunnel *t)
2862 {
2863   if (NULL == t)
2864   {
2865     GNUNET_assert (0);
2866     return (enum CadetTunnelCState) -1;
2867   }
2868   return t->cstate;
2869 }
2870
2871
2872 /**
2873  * Get the encryption state of a tunnel.
2874  *
2875  * @param t Tunnel.
2876  *
2877  * @return Tunnel's encryption state.
2878  */
2879 enum CadetTunnelEState
2880 GCT_get_estate (struct CadetTunnel *t)
2881 {
2882   if (NULL == t)
2883   {
2884     GNUNET_break (0);
2885     return (enum CadetTunnelEState) -1;
2886   }
2887   return t->estate;
2888 }
2889
2890 /**
2891  * Get the maximum buffer space for a tunnel towards a local client.
2892  *
2893  * @param t Tunnel.
2894  *
2895  * @return Biggest buffer space offered by any channel in the tunnel.
2896  */
2897 unsigned int
2898 GCT_get_channels_buffer (struct CadetTunnel *t)
2899 {
2900   struct CadetTChannel *iter;
2901   unsigned int buffer;
2902   unsigned int ch_buf;
2903
2904   if (NULL == t->channel_head)
2905   {
2906     /* Probably getting buffer for a channel create/handshake. */
2907     LOG (GNUNET_ERROR_TYPE_DEBUG, "  no channels, allow max\n");
2908     return MIN_TUNNEL_BUFFER;
2909   }
2910
2911   buffer = 0;
2912   for (iter = t->channel_head; NULL != iter; iter = iter->next)
2913   {
2914     ch_buf = get_channel_buffer (iter);
2915     if (ch_buf > buffer)
2916       buffer = ch_buf;
2917   }
2918   if (MIN_TUNNEL_BUFFER > buffer)
2919     return MIN_TUNNEL_BUFFER;
2920
2921   if (MAX_TUNNEL_BUFFER < buffer)
2922   {
2923     GNUNET_break (0);
2924     return MAX_TUNNEL_BUFFER;
2925   }
2926   return buffer;
2927 }
2928
2929
2930 /**
2931  * Get the total buffer space for a tunnel for P2P traffic.
2932  *
2933  * @param t Tunnel.
2934  *
2935  * @return Buffer space offered by all connections in the tunnel.
2936  */
2937 unsigned int
2938 GCT_get_connections_buffer (struct CadetTunnel *t)
2939 {
2940   struct CadetTConnection *iter;
2941   unsigned int buffer;
2942
2943   if (GNUNET_NO == is_ready (t))
2944   {
2945     if (count_queued_data (t) >= 3)
2946       return 0;
2947     else
2948       return 1;
2949   }
2950
2951   buffer = 0;
2952   for (iter = t->connection_head; NULL != iter; iter = iter->next)
2953   {
2954     if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
2955     {
2956       continue;
2957     }
2958     buffer += get_connection_buffer (iter);
2959   }
2960
2961   return buffer;
2962 }
2963
2964
2965 /**
2966  * Get the tunnel's destination.
2967  *
2968  * @param t Tunnel.
2969  *
2970  * @return ID of the destination peer.
2971  */
2972 const struct GNUNET_PeerIdentity *
2973 GCT_get_destination (struct CadetTunnel *t)
2974 {
2975   return GCP_get_id (t->peer);
2976 }
2977
2978
2979 /**
2980  * Get the tunnel's next free global channel ID.
2981  *
2982  * @param t Tunnel.
2983  *
2984  * @return GID of a channel free to use.
2985  */
2986 struct GNUNET_CADET_ChannelNumber
2987 GCT_get_next_chid (struct CadetTunnel *t)
2988 {
2989   struct GNUNET_CADET_ChannelNumber chid;
2990   struct GNUNET_CADET_ChannelNumber mask;
2991   int result;
2992
2993   /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
2994    * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
2995    * If peer's ID is bigger, start at 0x4... bit 30 = 1
2996    */
2997   result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
2998   if (0 > result)
2999     mask.cn = htonl (0x40000000);
3000   else
3001     mask.cn = 0x0;
3002   t->next_chid.cn |= mask.cn;
3003
3004   while (NULL != GCT_get_channel (t, t->next_chid))
3005   {
3006     LOG (GNUNET_ERROR_TYPE_DEBUG,
3007          "Channel %u exists...\n",
3008          t->next_chid.cn);
3009     t->next_chid.cn = htonl ((ntohl (t->next_chid.cn) + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI);
3010     t->next_chid.cn |= mask.cn;
3011   }
3012   chid = t->next_chid;
3013   t->next_chid.cn = (t->next_chid.cn + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3014   t->next_chid.cn |= mask.cn;
3015
3016   return chid;
3017 }
3018
3019
3020 /**
3021  * Send ACK on one or more channels due to buffer in connections.
3022  *
3023  * @param t Channel which has some free buffer space.
3024  */
3025 void
3026 GCT_unchoke_channels (struct CadetTunnel *t)
3027 {
3028   struct CadetTChannel *iter;
3029   unsigned int buffer;
3030   unsigned int channels = GCT_count_channels (t);
3031   unsigned int choked_n;
3032   struct CadetChannel *choked[channels];
3033
3034   LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
3035   LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
3036   if (NULL != t->channel_head)
3037     LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
3038
3039   if (NULL != t->tq_head)
3040     send_queued_data (t);
3041
3042   /* Get buffer space */
3043   buffer = GCT_get_connections_buffer (t);
3044   if (0 == buffer)
3045   {
3046     return;
3047   }
3048
3049   /* Count and remember choked channels */
3050   choked_n = 0;
3051   for (iter = t->channel_head; NULL != iter; iter = iter->next)
3052   {
3053     if (GNUNET_NO == get_channel_allowed (iter))
3054     {
3055       choked[choked_n++] = iter->ch;
3056     }
3057   }
3058
3059   /* Unchoke random channels */
3060   while (0 < buffer && 0 < choked_n)
3061   {
3062     unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3063                                                choked_n);
3064     GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
3065     choked_n--;
3066     buffer--;
3067     choked[r] = choked[choked_n];
3068   }
3069 }
3070
3071
3072 /**
3073  * Send ACK on one or more connections due to buffer space to the client.
3074  *
3075  * Iterates all connections of the tunnel and sends ACKs appropriately.
3076  *
3077  * @param t Tunnel.
3078  */
3079 void
3080 GCT_send_connection_acks (struct CadetTunnel *t)
3081 {
3082   struct CadetTConnection *iter;
3083   uint32_t allowed;
3084   uint32_t to_allow;
3085   uint32_t allow_per_connection;
3086   unsigned int cs;
3087   unsigned int buffer;
3088
3089   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
3090        GCT_2s (t));
3091
3092   if (NULL == t)
3093   {
3094     GNUNET_break (0);
3095     return;
3096   }
3097
3098   if (CADET_TUNNEL_READY != t->cstate)
3099     return;
3100
3101   buffer = GCT_get_channels_buffer (t);
3102   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer %u\n", buffer);
3103
3104   /* Count connections, how many messages are already allowed */
3105   cs = GCT_count_connections (t);
3106   for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3107   {
3108     allowed += get_connection_allowed (iter);
3109   }
3110   LOG (GNUNET_ERROR_TYPE_DEBUG, "  allowed %u\n", allowed);
3111
3112   /* Make sure there is no overflow */
3113   if (allowed > buffer)
3114     return;
3115
3116   /* Authorize connections to send more data */
3117   to_allow = buffer - allowed;
3118
3119   for (iter = t->connection_head;
3120        NULL != iter && to_allow > 0;
3121        iter = iter->next)
3122   {
3123     if (CADET_CONNECTION_READY != GCC_get_state (iter->c)
3124         || get_connection_allowed (iter) > 64 / 3)
3125     {
3126       continue;
3127     }
3128     GNUNET_assert(cs != 0);
3129     allow_per_connection = to_allow/cs;
3130     to_allow -= allow_per_connection;
3131     cs--;
3132     GCC_allow (iter->c, allow_per_connection,
3133                GCC_is_origin (iter->c, GNUNET_NO));
3134   }
3135
3136   if (0 != to_allow)
3137   {
3138     /* Since we don't allow if it's allowed to send 64/3, this can happen. */
3139     LOG (GNUNET_ERROR_TYPE_DEBUG, "  reminding to_allow: %u\n", to_allow);
3140   }
3141 }
3142
3143
3144 /**
3145  * Cancel a previously sent message while it's in the queue.
3146  *
3147  * ONLY can be called before the continuation given to the send function
3148  * is called. Once the continuation is called, the message is no longer in the
3149  * queue.
3150  *
3151  * @param q Handle to the queue.
3152  */
3153 void
3154 GCT_cancel (struct CadetTunnelQueue *q)
3155 {
3156   if (NULL != q->cq)
3157   {
3158     GNUNET_assert (NULL == q->tqd);
3159     GCC_cancel (q->cq);
3160     /* tun_message_sent() will be called and free q */
3161   }
3162   else if (NULL != q->tqd)
3163   {
3164     unqueue_data (q->tqd);
3165     q->tqd = NULL;
3166     if (NULL != q->cont)
3167       q->cont (q->cont_cls, NULL, q, 0, 0);
3168     GNUNET_free (q);
3169   }
3170   else
3171   {
3172     GNUNET_break (0);
3173   }
3174 }
3175
3176
3177 /**
3178  * Check if the tunnel has queued traffic.
3179  *
3180  * @param t Tunnel to check.
3181  *
3182  * @return #GNUNET_YES if there is queued traffic
3183  *         #GNUNET_NO otherwise
3184  */
3185 int
3186 GCT_has_queued_traffic (struct CadetTunnel *t)
3187 {
3188   return (NULL != t->tq_head) ? GNUNET_YES : GNUNET_NO;
3189 }
3190
3191
3192 /**
3193  * Sends an already built message on a tunnel, encrypting it and
3194  * choosing the best connection if not provided.
3195  *
3196  * @param message Message to send. Function modifies it.
3197  * @param t Tunnel on which this message is transmitted.
3198  * @param c Connection to use (autoselect if NULL).
3199  * @param force Force the tunnel to take the message (buffer overfill).
3200  * @param cont Continuation to call once message is really sent.
3201  * @param cont_cls Closure for @c cont.
3202  *
3203  * @return Handle to cancel message. NULL if @c cont is NULL.
3204  */
3205 struct CadetTunnelQueue *
3206 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
3207                            struct CadetTunnel *t, struct CadetConnection *c,
3208                            int force, GCT_sent cont, void *cont_cls)
3209 {
3210   return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
3211 }
3212
3213
3214 /**
3215  * Send a KX message.
3216  *
3217  * @param t Tunnel on which to send it.
3218  * @param force_reply Force the other peer to reply with a KX message.
3219  */
3220 void
3221 GCT_send_kx (struct CadetTunnel *t, int force_reply)
3222 {
3223   struct CadetConnection *c;
3224   struct GNUNET_CADET_KX msg;
3225   enum GNUNET_CADET_KX_Flags flags;
3226
3227   LOG (GNUNET_ERROR_TYPE_INFO, "==> {        KX} on %s\n", GCT_2s (t));
3228   if (NULL != t->ephm_h)
3229   {
3230     LOG (GNUNET_ERROR_TYPE_INFO, "     already queued, nop\n");
3231     return;
3232   }
3233   GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
3234
3235   c = tunnel_get_connection (t);
3236   if (NULL == c)
3237   {
3238     if (NULL == t->destroy_task && CADET_TUNNEL_READY == t->cstate)
3239     {
3240       GNUNET_break (0);
3241       GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
3242     }
3243     return;
3244   }
3245
3246   msg.header.size = htons (sizeof (msg));
3247   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
3248   flags = GNUNET_CADET_KX_FLAG_NONE;
3249   if (GNUNET_YES == force_reply)
3250     flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY;
3251   msg.flags = htonl (flags);
3252   msg.cid = *GCC_get_id (c);
3253   GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->kx_0, &msg.ephemeral_key);
3254   GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &msg.ratchet_key);
3255
3256   t->ephm_h = GCC_send_prebuilt_message (&msg.header, UINT16_MAX, 0,
3257                                          c, GCC_is_origin (c, GNUNET_YES),
3258                                          GNUNET_YES, &ephm_sent, t);
3259   if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
3260     GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
3261 }
3262
3263
3264 /**
3265  * Is the tunnel directed towards the local peer?
3266  *
3267  * @param t Tunnel.
3268  *
3269  * @return #GNUNET_YES if it is loopback.
3270  */
3271 int
3272 GCT_is_loopback (const struct CadetTunnel *t)
3273 {
3274   return (myid == GCP_get_short_id (t->peer));
3275 }
3276
3277
3278 /**
3279  * Is the tunnel this path already?
3280  *
3281  * @param t Tunnel.
3282  * @param p Path.
3283  *
3284  * @return #GNUNET_YES a connection uses this path.
3285  */
3286 int
3287 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
3288 {
3289   struct CadetTConnection *iter;
3290
3291   for (iter = t->connection_head; NULL != iter; iter = iter->next)
3292     if (path_equivalent (GCC_get_path (iter->c), p))
3293       return GNUNET_YES;
3294
3295   return GNUNET_NO;
3296 }
3297
3298
3299 /**
3300  * Get a cost of a path for a tunnel considering existing connections.
3301  *
3302  * @param t Tunnel.
3303  * @param path Candidate path.
3304  *
3305  * @return Cost of the path (path length + number of overlapping nodes)
3306  */
3307 unsigned int
3308 GCT_get_path_cost (const struct CadetTunnel *t,
3309                    const struct CadetPeerPath *path)
3310 {
3311   struct CadetTConnection *iter;
3312   const struct CadetPeerPath *aux;
3313   unsigned int overlap;
3314   unsigned int i;
3315   unsigned int j;
3316
3317   if (NULL == path)
3318     return 0;
3319
3320   overlap = 0;
3321   GNUNET_assert (NULL != t);
3322
3323   for (i = 0; i < path->length; i++)
3324   {
3325     for (iter = t->connection_head; NULL != iter; iter = iter->next)
3326     {
3327       aux = GCC_get_path (iter->c);
3328       if (NULL == aux)
3329         continue;
3330
3331       for (j = 0; j < aux->length; j++)
3332       {
3333         if (path->peers[i] == aux->peers[j])
3334         {
3335           overlap++;
3336           break;
3337         }
3338       }
3339     }
3340   }
3341   return path->length + overlap;
3342 }
3343
3344
3345 /**
3346  * Get the static string for the peer this tunnel is directed.
3347  *
3348  * @param t Tunnel.
3349  *
3350  * @return Static string the destination peer's ID.
3351  */
3352 const char *
3353 GCT_2s (const struct CadetTunnel *t)
3354 {
3355   if (NULL == t)
3356     return "(NULL)";
3357
3358   return GCP_2s (t->peer);
3359 }
3360
3361
3362 /******************************************************************************/
3363 /*****************************    INFO/DEBUG    *******************************/
3364 /******************************************************************************/
3365
3366 static void
3367 ax_debug (const struct CadetTunnelAxolotl *ax, enum GNUNET_ErrorType level)
3368 {
3369   struct GNUNET_CRYPTO_EcdhePublicKey pub;
3370   struct CadetTunnelSkippedKey *iter;
3371
3372   LOG2 (level, "TTT  RK  \t %s\n",
3373         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->RK));
3374
3375   LOG2 (level, "TTT  HKs \t %s\n",
3376         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->HKs));
3377   LOG2 (level, "TTT  HKr \t %s\n",
3378         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->HKr));
3379   LOG2 (level, "TTT  NHKs\t %s\n",
3380         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->NHKs));
3381   LOG2 (level, "TTT  NHKr\t %s\n",
3382         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->NHKr));
3383
3384   LOG2 (level, "TTT  CKs \t %s\n",
3385         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->CKs));
3386   LOG2 (level, "TTT  CKr \t %s\n",
3387         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->CKr));
3388
3389   GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs, &pub);
3390   LOG2 (level, "TTT  DHRs\t %s\n",
3391         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &pub));
3392   LOG2 (level, "TTT  DHRr\t %s\n",
3393         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->DHRr));
3394
3395   LOG2 (level, "TTT  Nr\t %u\tNs\t%u\n", ax->Nr, ax->Ns);
3396   LOG2 (level, "TTT  PNs\t %u\tSkipped\t%u\n", ax->PNs, ax->skipped);
3397   LOG2 (level, "TTT  Ratchet\t%u\n", ax->ratchet_flag);
3398
3399   for (iter = ax->skipped_head; NULL != iter; iter = iter->next)
3400   {
3401     LOG2 (level, "TTT    HK\t %s\n",
3402           GNUNET_i2s ((struct GNUNET_PeerIdentity *) &iter->HK));
3403     LOG2 (level, "TTT    MK\t %s\n",
3404           GNUNET_i2s ((struct GNUNET_PeerIdentity *) &iter->MK));
3405   }
3406 }
3407
3408 /**
3409  * Log all possible info about the tunnel state.
3410  *
3411  * @param t Tunnel to debug.
3412  * @param level Debug level to use.
3413  */
3414 void
3415 GCT_debug (const struct CadetTunnel *t, enum GNUNET_ErrorType level)
3416 {
3417   struct CadetTChannel *iter_ch;
3418   struct CadetTConnection *iter_c;
3419   int do_log;
3420
3421   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
3422                                        "cadet-tun",
3423                                        __FILE__, __FUNCTION__, __LINE__);
3424   if (0 == do_log)
3425     return;
3426
3427   LOG2 (level, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
3428   LOG2 (level, "TTT  cstate %s, estate %s\n",
3429        cstate2s (t->cstate), estate2s (t->estate));
3430 #if DUMP_KEYS_TO_STDERR
3431   ax_debug (t->ax, level);
3432 #endif
3433   LOG2 (level, "TTT  tq_head %p, tq_tail %p\n", t->tq_head, t->tq_tail);
3434   LOG2 (level, "TTT  destroy %p\n", t->destroy_task);
3435   LOG2 (level, "TTT  channels:\n");
3436   for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = iter_ch->next)
3437   {
3438     GCCH_debug (iter_ch->ch, level);
3439   }
3440
3441   LOG2 (level, "TTT  connections:\n");
3442   for (iter_c = t->connection_head; NULL != iter_c; iter_c = iter_c->next)
3443   {
3444     GCC_debug (iter_c->c, level);
3445   }
3446
3447   LOG2 (level, "TTT DEBUG TUNNEL END\n");
3448 }
3449
3450
3451 /**
3452  * Iterate all tunnels.
3453  *
3454  * @param iter Iterator.
3455  * @param cls Closure for @c iter.
3456  */
3457 void
3458 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
3459 {
3460   GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
3461 }
3462
3463
3464 /**
3465  * Count all tunnels.
3466  *
3467  * @return Number of tunnels to remote peers kept by this peer.
3468  */
3469 unsigned int
3470 GCT_count_all (void)
3471 {
3472   return GNUNET_CONTAINER_multipeermap_size (tunnels);
3473 }
3474
3475
3476 /**
3477  * Iterate all connections of a tunnel.
3478  *
3479  * @param t Tunnel whose connections to iterate.
3480  * @param iter Iterator.
3481  * @param cls Closure for @c iter.
3482  */
3483 void
3484 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
3485 {
3486   struct CadetTConnection *ct;
3487
3488   for (ct = t->connection_head; NULL != ct; ct = ct->next)
3489     iter (cls, ct->c);
3490 }
3491
3492
3493 /**
3494  * Iterate all channels of a tunnel.
3495  *
3496  * @param t Tunnel whose channels to iterate.
3497  * @param iter Iterator.
3498  * @param cls Closure for @c iter.
3499  */
3500 void
3501 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
3502 {
3503   struct CadetTChannel *cht;
3504
3505   for (cht = t->channel_head; NULL != cht; cht = cht->next)
3506     iter (cls, cht->ch);
3507 }