eliminate KX short cut
[oweals/gnunet.git] / src / cadet / gnunet-service-cadet_tunnels.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2013, 2017 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  * @file cadet/gnunet-service-cadet_tunnels.c
22  * @brief Information we track per tunnel.
23  * @author Bartlomiej Polot
24  * @author Christian Grothoff
25  *
26  * FIXME:
27  * - proper connection evaluation during connection management:
28  *   + consider quality (or quality spread?) of current connection set
29  *     when deciding how often to do maintenance
30  *   + interact with PEER to drive DHT GET/PUT operations based
31  *     on how much we like our connections
32  */
33 #include "platform.h"
34 #include "gnunet_util_lib.h"
35 #include "gnunet_statistics_service.h"
36 #include "gnunet_signatures.h"
37 #include "cadet_protocol.h"
38 #include "gnunet-service-cadet_channel.h"
39 #include "gnunet-service-cadet_connection.h"
40 #include "gnunet-service-cadet_tunnels.h"
41 #include "gnunet-service-cadet_peer.h"
42 #include "gnunet-service-cadet_paths.h"
43
44
45 #define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__)
46
47 /**
48  * How often do we try to decrypt payload with unverified key
49  * material?  Used to limit CPU increase upon receiving bogus
50  * KX.
51  */
52 #define MAX_UNVERIFIED_ATTEMPTS 16
53
54 /**
55  * How long do we wait until tearing down an idle tunnel?
56  */
57 #define IDLE_DESTROY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90)
58
59 /**
60  * How long do we wait initially before retransmitting the KX?
61  * TODO: replace by 2 RTT if/once we have connection-level RTT data!
62  */
63 #define INITIAL_KX_RETRY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 250)
64
65 /**
66  * Maximum number of skipped keys we keep in memory per tunnel.
67  */
68 #define MAX_SKIPPED_KEYS 64
69
70 /**
71  * Maximum number of keys (and thus ratchet steps) we are willing to
72  * skip before we decide this is either a bogus packet or a DoS-attempt.
73  */
74 #define MAX_KEY_GAP 256
75
76
77 /**
78  * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
79  */
80 struct CadetTunnelSkippedKey
81 {
82   /**
83    * DLL next.
84    */
85   struct CadetTunnelSkippedKey *next;
86
87   /**
88    * DLL prev.
89    */
90   struct CadetTunnelSkippedKey *prev;
91
92   /**
93    * When was this key stored (for timeout).
94    */
95   struct GNUNET_TIME_Absolute timestamp;
96
97   /**
98    * Header key.
99    */
100   struct GNUNET_CRYPTO_SymmetricSessionKey HK;
101
102   /**
103    * Message key.
104    */
105   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
106
107   /**
108    * Key number for a given HK.
109    */
110   unsigned int Kn;
111 };
112
113
114 /**
115  * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
116  */
117 struct CadetTunnelAxolotl
118 {
119   /**
120    * A (double linked) list of stored message keys and associated header keys
121    * for "skipped" messages, i.e. messages that have not been
122    * received despite the reception of more recent messages, (head).
123    */
124   struct CadetTunnelSkippedKey *skipped_head;
125
126   /**
127    * Skipped messages' keys DLL, tail.
128    */
129   struct CadetTunnelSkippedKey *skipped_tail;
130
131   /**
132    * 32-byte root key which gets updated by DH ratchet.
133    */
134   struct GNUNET_CRYPTO_SymmetricSessionKey RK;
135
136   /**
137    * 32-byte header key (currently used for sending).
138    */
139   struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
140
141   /**
142    * 32-byte header key (currently used for receiving)
143    */
144   struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
145
146   /**
147    * 32-byte next header key (for sending), used once the
148    * ratchet advances.  We are sure that the sender has this
149    * key as well only after @e ratchet_allowed is #GNUNET_YES.
150    */
151   struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
152
153   /**
154    * 32-byte next header key (for receiving).  To be tried
155    * when decrypting with @e HKr fails and thus the sender
156    * may have advanced the ratchet.
157    */
158   struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
159
160   /**
161    * 32-byte chain keys (used for forward-secrecy) for
162    * sending messages. Updated for every message.
163    */
164   struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
165
166   /**
167    * 32-byte chain keys (used for forward-secrecy) for
168    * receiving messages. Updated for every message. If
169    * messages are skipped, the respective derived MKs
170    * (and the current @HKr) are kept in the @e skipped_head DLL.
171    */
172   struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
173
174   /**
175    * ECDH for key exchange (A0 / B0).
176    */
177   struct GNUNET_CRYPTO_EcdhePrivateKey kx_0;
178
179   /**
180    * ECDH Ratchet key (our private key in the current DH).
181    */
182   struct GNUNET_CRYPTO_EcdhePrivateKey DHRs;
183
184   /**
185    * ECDH Ratchet key (other peer's public key in the current DH).
186    */
187   struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
188
189   /**
190    * Last ephemeral public key received from the other peer,
191    * for duplicate detection.
192    */
193   struct GNUNET_CRYPTO_EcdhePublicKey last_ephemeral;
194
195   /**
196    * Time when the current ratchet expires and a new one is triggered
197    * (if @e ratchet_allowed is #GNUNET_YES).
198    */
199   struct GNUNET_TIME_Absolute ratchet_expiration;
200
201   /**
202    * Number of elements in @a skipped_head <-> @a skipped_tail.
203    */
204   unsigned int skipped;
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    * True (#GNUNET_YES) if we have received a message from the
228    * other peer that uses the keys from our last ratchet step.
229    * This implies that we are again allowed to advance the ratchet,
230    * otherwise we have to wait until the other peer sees our current
231    * ephemeral key and advances first.
232    *
233    * #GNUNET_NO if we have advanced the ratched but lack any evidence
234    * that the other peer has noticed this.
235    */
236   int ratchet_allowed;
237
238   /**
239    * Number of messages recieved since our last ratchet advance.
240    *
241    * If this counter = 0, we cannot send a new ratchet key in the next
242    * message.
243    *
244    * If this counter > 0, we could (but don't have to) send a new key.
245    *
246    * Once the @e ratchet_counter is larger than
247    * #ratchet_messages (or @e ratchet_expiration time has past), and
248    * @e ratchet_allowed is #GNUNET_YES, we advance the ratchet.
249    */
250   unsigned int ratchet_counter;
251
252 };
253
254
255 /**
256  * Struct used to save messages in a non-ready tunnel to send once connected.
257  */
258 struct CadetTunnelQueueEntry
259 {
260   /**
261    * We are entries in a DLL
262    */
263   struct CadetTunnelQueueEntry *next;
264
265   /**
266    * We are entries in a DLL
267    */
268   struct CadetTunnelQueueEntry *prev;
269
270   /**
271    * Tunnel these messages belong in.
272    */
273   struct CadetTunnel *t;
274
275   /**
276    * Continuation to call once sent (on the channel layer).
277    */
278   GCT_SendContinuation cont;
279
280   /**
281    * Closure for @c cont.
282    */
283   void *cont_cls;
284
285   /**
286    * Envelope of message to send follows.
287    */
288   struct GNUNET_MQ_Envelope *env;
289
290   /**
291    * Where to put the connection identifier into the payload
292    * of the message in @e env once we have it?
293    */
294   struct GNUNET_CADET_ConnectionTunnelIdentifier *cid;
295 };
296
297
298 /**
299  * Struct containing all information regarding a tunnel to a peer.
300  */
301 struct CadetTunnel
302 {
303   /**
304    * Destination of the tunnel.
305    */
306   struct CadetPeer *destination;
307
308   /**
309    * Peer's ephemeral key, to recreate @c e_key and @c d_key when own
310    * ephemeral key changes.
311    */
312   struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
313
314   /**
315    * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
316    */
317   struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
318
319   /**
320    * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
321    */
322   struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
323
324   /**
325    * Axolotl info.
326    */
327   struct CadetTunnelAxolotl ax;
328
329   /**
330    * Unverified Axolotl info, used only if we got a fresh KX (not a
331    * KX_AUTH) while our end of the tunnel was still up.  In this case,
332    * we keep the fresh KX around but do not put it into action until
333    * we got encrypted payload that assures us of the authenticity of
334    * the KX.
335    */
336   struct CadetTunnelAxolotl *unverified_ax;
337
338   /**
339    * Task scheduled if there are no more channels using the tunnel.
340    */
341   struct GNUNET_SCHEDULER_Task *destroy_task;
342
343   /**
344    * Task to trim connections if too many are present.
345    */
346   struct GNUNET_SCHEDULER_Task *maintain_connections_task;
347
348   /**
349    * Task to send messages from queue (if possible).
350    */
351   struct GNUNET_SCHEDULER_Task *send_task;
352
353   /**
354    * Task to trigger KX.
355    */
356   struct GNUNET_SCHEDULER_Task *kx_task;
357
358   /**
359    * Tokenizer for decrypted messages.
360    */
361   struct GNUNET_MessageStreamTokenizer *mst;
362
363   /**
364    * Dispatcher for decrypted messages only (do NOT use for sending!).
365    */
366   struct GNUNET_MQ_Handle *mq;
367
368   /**
369    * DLL of ready connections that are actively used to reach the destination peer.
370    */
371   struct CadetTConnection *connection_ready_head;
372
373   /**
374    * DLL of ready connections that are actively used to reach the destination peer.
375    */
376   struct CadetTConnection *connection_ready_tail;
377
378   /**
379    * DLL of connections that we maintain that might be used to reach the destination peer.
380    */
381   struct CadetTConnection *connection_busy_head;
382
383   /**
384    * DLL of connections that we maintain that might be used to reach the destination peer.
385    */
386   struct CadetTConnection *connection_busy_tail;
387
388   /**
389    * Channels inside this tunnel. Maps
390    * `struct GNUNET_CADET_ChannelTunnelNumber` to a `struct CadetChannel`.
391    */
392   struct GNUNET_CONTAINER_MultiHashMap32 *channels;
393
394   /**
395    * Channel ID for the next created channel in this tunnel.
396    */
397   struct GNUNET_CADET_ChannelTunnelNumber next_ctn;
398
399   /**
400    * Queued messages, to transmit once tunnel gets connected.
401    */
402   struct CadetTunnelQueueEntry *tq_head;
403
404   /**
405    * Queued messages, to transmit once tunnel gets connected.
406    */
407   struct CadetTunnelQueueEntry *tq_tail;
408
409   /**
410    * Identification of the connection from which we are currently processing
411    * a message. Only valid (non-NULL) during #handle_decrypted() and the
412    * handle-*()-functions called from our @e mq during that function.
413    */
414   struct CadetTConnection *current_ct;
415
416   /**
417    * How long do we wait until we retry the KX?
418    */
419   struct GNUNET_TIME_Relative kx_retry_delay;
420
421   /**
422    * When do we try the next KX?
423    */
424   struct GNUNET_TIME_Absolute next_kx_attempt;
425
426   /**
427    * Number of connections in the @e connection_ready_head DLL.
428    */
429   unsigned int num_ready_connections;
430
431   /**
432    * Number of connections in the @e connection_busy_head DLL.
433    */
434   unsigned int num_busy_connections;
435
436   /**
437    * How often have we tried and failed to decrypt a message using
438    * the unverified KX material from @e unverified_ax?  Used to
439    * stop trying after #MAX_UNVERIFIED_ATTEMPTS.
440    */
441   unsigned int unverified_attempts;
442
443   /**
444    * Number of entries in the @e tq_head DLL.
445    */
446   unsigned int tq_len;
447
448   /**
449    * State of the tunnel encryption.
450    */
451   enum CadetTunnelEState estate;
452
453   /**
454    * Force triggering KX_AUTH independent of @e estate.
455    */
456   int kx_auth_requested;
457
458 };
459
460
461 /**
462  * Connection @a ct is now unready, clear it's ready flag
463  * and move it from the ready DLL to the busy DLL.
464  *
465  * @param ct connection to move to unready status
466  */
467 static void
468 mark_connection_unready (struct CadetTConnection *ct)
469 {
470   struct CadetTunnel *t = ct->t;
471
472   GNUNET_assert (GNUNET_YES == ct->is_ready);
473   GNUNET_CONTAINER_DLL_remove (t->connection_ready_head,
474                                t->connection_ready_tail,
475                                ct);
476   GNUNET_assert (0 < t->num_ready_connections);
477   t->num_ready_connections--;
478   ct->is_ready = GNUNET_NO;
479   GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
480                                t->connection_busy_tail,
481                                ct);
482   t->num_busy_connections++;
483 }
484
485
486 /**
487  * Get the static string for the peer this tunnel is directed.
488  *
489  * @param t Tunnel.
490  *
491  * @return Static string the destination peer's ID.
492  */
493 const char *
494 GCT_2s (const struct CadetTunnel *t)
495 {
496   static char buf[64];
497
498   if (NULL == t)
499     return "Tunnel(NULL)";
500   GNUNET_snprintf (buf,
501                    sizeof (buf),
502                    "Tunnel %s",
503                    GNUNET_i2s (GCP_get_id (t->destination)));
504   return buf;
505 }
506
507
508 /**
509  * Get string description for tunnel encryption state.
510  *
511  * @param es Tunnel state.
512  *
513  * @return String representation.
514  */
515 static const char *
516 estate2s (enum CadetTunnelEState es)
517 {
518   static char buf[32];
519
520   switch (es)
521   {
522   case CADET_TUNNEL_KEY_UNINITIALIZED:
523     return "CADET_TUNNEL_KEY_UNINITIALIZED";
524   case CADET_TUNNEL_KEY_AX_RECV:
525     return "CADET_TUNNEL_KEY_AX_RECV";
526   case CADET_TUNNEL_KEY_AX_SENT:
527     return "CADET_TUNNEL_KEY_AX_SENT";
528   case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
529     return "CADET_TUNNEL_KEY_AX_SENT_AND_RECV";
530   case CADET_TUNNEL_KEY_AX_AUTH_SENT:
531     return "CADET_TUNNEL_KEY_AX_AUTH_SENT";
532   case CADET_TUNNEL_KEY_OK:
533     return "CADET_TUNNEL_KEY_OK";
534   default:
535     GNUNET_snprintf (buf,
536                      sizeof (buf),
537                      "%u (UNKNOWN STATE)",
538                      es);
539     return buf;
540   }
541 }
542
543
544 /**
545  * Return the peer to which this tunnel goes.
546  *
547  * @param t a tunnel
548  * @return the destination of the tunnel
549  */
550 struct CadetPeer *
551 GCT_get_destination (struct CadetTunnel *t)
552 {
553   return t->destination;
554 }
555
556
557 /**
558  * Count channels of a tunnel.
559  *
560  * @param t Tunnel on which to count.
561  *
562  * @return Number of channels.
563  */
564 unsigned int
565 GCT_count_channels (struct CadetTunnel *t)
566 {
567   return GNUNET_CONTAINER_multihashmap32_size (t->channels);
568 }
569
570
571 /**
572  * Lookup a channel by its @a ctn.
573  *
574  * @param t tunnel to look in
575  * @param ctn number of channel to find
576  * @return NULL if channel does not exist
577  */
578 struct CadetChannel *
579 lookup_channel (struct CadetTunnel *t,
580                 struct GNUNET_CADET_ChannelTunnelNumber ctn)
581 {
582   return GNUNET_CONTAINER_multihashmap32_get (t->channels,
583                                               ntohl (ctn.cn));
584 }
585
586
587 /**
588  * Count all created connections of a tunnel. Not necessarily ready connections!
589  *
590  * @param t Tunnel on which to count.
591  *
592  * @return Number of connections created, either being established or ready.
593  */
594 unsigned int
595 GCT_count_any_connections (const struct CadetTunnel *t)
596 {
597   return t->num_ready_connections + t->num_busy_connections;
598 }
599
600
601 /**
602  * Find first connection that is ready in the list of
603  * our connections.  Picks ready connections round-robin.
604  *
605  * @param t tunnel to search
606  * @return NULL if we have no connection that is ready
607  */
608 static struct CadetTConnection *
609 get_ready_connection (struct CadetTunnel *t)
610 {
611   struct CadetTConnection *hd = t->connection_ready_head;
612
613   GNUNET_assert ( (NULL == hd) ||
614                   (GNUNET_YES == hd->is_ready) );
615   return hd;
616 }
617
618
619 /**
620  * Get the encryption state of a tunnel.
621  *
622  * @param t Tunnel.
623  *
624  * @return Tunnel's encryption state.
625  */
626 enum CadetTunnelEState
627 GCT_get_estate (struct CadetTunnel *t)
628 {
629   return t->estate;
630 }
631
632
633 /**
634  * Called when either we have a new connection, or a new message in the
635  * queue, or some existing connection has transmission capacity.  Looks
636  * at our message queue and if there is a message, picks a connection
637  * to send it on.
638  *
639  * @param cls the `struct CadetTunnel` to process messages on
640  */
641 static void
642 trigger_transmissions (void *cls);
643
644
645 /* ************************************** start core crypto ***************************** */
646
647
648 /**
649  * Create a new Axolotl ephemeral (ratchet) key.
650  *
651  * @param ax key material to update
652  */
653 static void
654 new_ephemeral (struct CadetTunnelAxolotl *ax)
655 {
656   LOG (GNUNET_ERROR_TYPE_DEBUG,
657        "Creating new ephemeral ratchet key (DHRs)\n");
658   GNUNET_assert (GNUNET_OK ==
659                  GNUNET_CRYPTO_ecdhe_key_create2 (&ax->DHRs));
660 }
661
662
663 /**
664  * Calculate HMAC.
665  *
666  * @param plaintext Content to HMAC.
667  * @param size Size of @c plaintext.
668  * @param iv Initialization vector for the message.
669  * @param key Key to use.
670  * @param hmac[out] Destination to store the HMAC.
671  */
672 static void
673 t_hmac (const void *plaintext,
674         size_t size,
675         uint32_t iv,
676         const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
677         struct GNUNET_ShortHashCode *hmac)
678 {
679   static const char ctx[] = "cadet authentication key";
680   struct GNUNET_CRYPTO_AuthKey auth_key;
681   struct GNUNET_HashCode hash;
682
683   GNUNET_CRYPTO_hmac_derive_key (&auth_key,
684                                  key,
685                                  &iv, sizeof (iv),
686                                  key, sizeof (*key),
687                                  ctx, sizeof (ctx),
688                                  NULL);
689   /* Two step: GNUNET_ShortHash is only 256 bits,
690      GNUNET_HashCode is 512, so we truncate. */
691   GNUNET_CRYPTO_hmac (&auth_key,
692                       plaintext,
693                       size,
694                       &hash);
695   GNUNET_memcpy (hmac,
696                  &hash,
697                  sizeof (*hmac));
698 }
699
700
701 /**
702  * Perform a HMAC.
703  *
704  * @param key Key to use.
705  * @param[out] hash Resulting HMAC.
706  * @param source Source key material (data to HMAC).
707  * @param len Length of @a source.
708  */
709 static void
710 t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
711                 struct GNUNET_HashCode *hash,
712                 const void *source,
713                 unsigned int len)
714 {
715   static const char ctx[] = "axolotl HMAC-HASH";
716   struct GNUNET_CRYPTO_AuthKey auth_key;
717
718   GNUNET_CRYPTO_hmac_derive_key (&auth_key,
719                                  key,
720                                  ctx, sizeof (ctx),
721                                  NULL);
722   GNUNET_CRYPTO_hmac (&auth_key,
723                       source,
724                       len,
725                       hash);
726 }
727
728
729 /**
730  * Derive a symmetric encryption key from an HMAC-HASH.
731  *
732  * @param key Key to use for the HMAC.
733  * @param[out] out Key to generate.
734  * @param source Source key material (data to HMAC).
735  * @param len Length of @a source.
736  */
737 static void
738 t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
739                    struct GNUNET_CRYPTO_SymmetricSessionKey *out,
740                    const void *source,
741                    unsigned int len)
742 {
743   static const char ctx[] = "axolotl derive key";
744   struct GNUNET_HashCode h;
745
746   t_ax_hmac_hash (key,
747                   &h,
748                   source,
749                   len);
750   GNUNET_CRYPTO_kdf (out, sizeof (*out),
751                      ctx, sizeof (ctx),
752                      &h, sizeof (h),
753                      NULL);
754 }
755
756
757 /**
758  * Encrypt data with the axolotl tunnel key.
759  *
760  * @param ax key material to use.
761  * @param dst Destination with @a size bytes for the encrypted data.
762  * @param src Source of the plaintext. Can overlap with @c dst, must contain @a size bytes
763  * @param size Size of the buffers at @a src and @a dst
764  */
765 static void
766 t_ax_encrypt (struct CadetTunnelAxolotl *ax,
767               void *dst,
768               const void *src,
769               size_t size)
770 {
771   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
772   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
773   size_t out_size;
774
775   ax->ratchet_counter++;
776   if ( (GNUNET_YES == ax->ratchet_allowed) &&
777        ( (ratchet_messages <= ax->ratchet_counter) ||
778          (0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us)) )
779   {
780     ax->ratchet_flag = GNUNET_YES;
781   }
782   if (GNUNET_YES == ax->ratchet_flag)
783   {
784     /* Advance ratchet */
785     struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
786     struct GNUNET_HashCode dh;
787     struct GNUNET_HashCode hmac;
788     static const char ctx[] = "axolotl ratchet";
789
790     new_ephemeral (ax);
791     ax->HKs = ax->NHKs;
792
793     /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
794     GNUNET_CRYPTO_ecc_ecdh (&ax->DHRs,
795                             &ax->DHRr,
796                             &dh);
797     t_ax_hmac_hash (&ax->RK,
798                     &hmac,
799                     &dh,
800                     sizeof (dh));
801     GNUNET_CRYPTO_kdf (keys, sizeof (keys),
802                        ctx, sizeof (ctx),
803                        &hmac, sizeof (hmac),
804                        NULL);
805     ax->RK = keys[0];
806     ax->NHKs = keys[1];
807     ax->CKs = keys[2];
808
809     ax->PNs = ax->Ns;
810     ax->Ns = 0;
811     ax->ratchet_flag = GNUNET_NO;
812     ax->ratchet_allowed = GNUNET_NO;
813     ax->ratchet_counter = 0;
814     ax->ratchet_expiration
815       = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
816                                   ratchet_time);
817   }
818
819   t_hmac_derive_key (&ax->CKs,
820                      &MK,
821                      "0",
822                      1);
823   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
824                                      &MK,
825                                      NULL, 0,
826                                      NULL);
827
828   out_size = GNUNET_CRYPTO_symmetric_encrypt (src,
829                                               size,
830                                               &MK,
831                                               &iv,
832                                               dst);
833   GNUNET_assert (size == out_size);
834   t_hmac_derive_key (&ax->CKs,
835                      &ax->CKs,
836                      "1",
837                      1);
838 }
839
840
841 /**
842  * Decrypt data with the axolotl tunnel key.
843  *
844  * @param ax key material to use.
845  * @param dst Destination for the decrypted data, must contain @a size bytes.
846  * @param src Source of the ciphertext. Can overlap with @c dst, must contain @a size bytes.
847  * @param size Size of the @a src and @a dst buffers
848  */
849 static void
850 t_ax_decrypt (struct CadetTunnelAxolotl *ax,
851               void *dst,
852               const void *src,
853               size_t size)
854 {
855   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
856   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
857   size_t out_size;
858
859   t_hmac_derive_key (&ax->CKr,
860                      &MK,
861                      "0",
862                      1);
863   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
864                                      &MK,
865                                      NULL, 0,
866                                      NULL);
867   GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
868   out_size = GNUNET_CRYPTO_symmetric_decrypt (src,
869                                               size,
870                                               &MK,
871                                               &iv,
872                                               dst);
873   GNUNET_assert (out_size == size);
874   t_hmac_derive_key (&ax->CKr,
875                      &ax->CKr,
876                      "1",
877                      1);
878 }
879
880
881 /**
882  * Encrypt header with the axolotl header key.
883  *
884  * @param ax key material to use.
885  * @param[in|out] msg Message whose header to encrypt.
886  */
887 static void
888 t_h_encrypt (struct CadetTunnelAxolotl *ax,
889              struct GNUNET_CADET_TunnelEncryptedMessage *msg)
890 {
891   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
892   size_t out_size;
893
894   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
895                                      &ax->HKs,
896                                      NULL, 0,
897                                      NULL);
898   out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->ax_header,
899                                               sizeof (struct GNUNET_CADET_AxHeader),
900                                               &ax->HKs,
901                                               &iv,
902                                               &msg->ax_header);
903   GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
904 }
905
906
907 /**
908  * Decrypt header with the current axolotl header key.
909  *
910  * @param ax key material to use.
911  * @param src Message whose header to decrypt.
912  * @param dst Where to decrypt header to.
913  */
914 static void
915 t_h_decrypt (struct CadetTunnelAxolotl *ax,
916              const struct GNUNET_CADET_TunnelEncryptedMessage *src,
917              struct GNUNET_CADET_TunnelEncryptedMessage *dst)
918 {
919   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
920   size_t out_size;
921
922   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
923                                      &ax->HKr,
924                                      NULL, 0,
925                                      NULL);
926   out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
927                                               sizeof (struct GNUNET_CADET_AxHeader),
928                                               &ax->HKr,
929                                               &iv,
930                                               &dst->ax_header.Ns);
931   GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
932 }
933
934
935 /**
936  * Delete a key from the list of skipped keys.
937  *
938  * @param ax key material to delete @a key from.
939  * @param key Key to delete.
940  */
941 static void
942 delete_skipped_key (struct CadetTunnelAxolotl *ax,
943                     struct CadetTunnelSkippedKey *key)
944 {
945   GNUNET_CONTAINER_DLL_remove (ax->skipped_head,
946                                ax->skipped_tail,
947                                key);
948   GNUNET_free (key);
949   ax->skipped--;
950 }
951
952
953 /**
954  * Decrypt and verify data with the appropriate tunnel key and verify that the
955  * data has not been altered since it was sent by the remote peer.
956  *
957  * @param ax key material to use.
958  * @param dst Destination for the plaintext.
959  * @param src Source of the message. Can overlap with @c dst.
960  * @param size Size of the message.
961  * @return Size of the decrypted data, -1 if an error was encountered.
962  */
963 static ssize_t
964 try_old_ax_keys (struct CadetTunnelAxolotl *ax,
965                  void *dst,
966                  const struct GNUNET_CADET_TunnelEncryptedMessage *src,
967                  size_t size)
968 {
969   struct CadetTunnelSkippedKey *key;
970   struct GNUNET_ShortHashCode *hmac;
971   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
972   struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
973   struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
974   size_t esize;
975   size_t res;
976   size_t len;
977   unsigned int N;
978
979   LOG (GNUNET_ERROR_TYPE_DEBUG,
980        "Trying skipped keys\n");
981   hmac = &plaintext_header.hmac;
982   esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
983
984   /* Find a correct Header Key */
985   valid_HK = NULL;
986   for (key = ax->skipped_head; NULL != key; key = key->next)
987   {
988     t_hmac (&src->ax_header,
989             sizeof (struct GNUNET_CADET_AxHeader) + esize,
990             0,
991             &key->HK,
992             hmac);
993     if (0 == memcmp (hmac,
994                      &src->hmac,
995                      sizeof (*hmac)))
996     {
997       valid_HK = &key->HK;
998       break;
999     }
1000   }
1001   if (NULL == key)
1002     return -1;
1003
1004   /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
1005   GNUNET_assert (size > sizeof (struct GNUNET_CADET_TunnelEncryptedMessage));
1006   len = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1007   GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
1008
1009   /* Decrypt header */
1010   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
1011                                      &key->HK,
1012                                      NULL, 0,
1013                                      NULL);
1014   res = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
1015                                          sizeof (struct GNUNET_CADET_AxHeader),
1016                                          &key->HK,
1017                                          &iv,
1018                                          &plaintext_header.ax_header.Ns);
1019   GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == res);
1020
1021   /* Find the correct message key */
1022   N = ntohl (plaintext_header.ax_header.Ns);
1023   while ( (NULL != key) &&
1024           (N != key->Kn) )
1025     key = key->next;
1026   if ( (NULL == key) ||
1027        (0 != memcmp (&key->HK,
1028                      valid_HK,
1029                      sizeof (*valid_HK))) )
1030     return -1;
1031
1032   /* Decrypt payload */
1033   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
1034                                      &key->MK,
1035                                      NULL,
1036                                      0,
1037                                      NULL);
1038   res = GNUNET_CRYPTO_symmetric_decrypt (&src[1],
1039                                          len,
1040                                          &key->MK,
1041                                          &iv,
1042                                          dst);
1043   delete_skipped_key (ax,
1044                       key);
1045   return res;
1046 }
1047
1048
1049 /**
1050  * Delete a key from the list of skipped keys.
1051  *
1052  * @param ax key material to delete from.
1053  * @param HKr Header Key to use.
1054  */
1055 static void
1056 store_skipped_key (struct CadetTunnelAxolotl *ax,
1057                    const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
1058 {
1059   struct CadetTunnelSkippedKey *key;
1060
1061   key = GNUNET_new (struct CadetTunnelSkippedKey);
1062   key->timestamp = GNUNET_TIME_absolute_get ();
1063   key->Kn = ax->Nr;
1064   key->HK = ax->HKr;
1065   t_hmac_derive_key (&ax->CKr,
1066                      &key->MK,
1067                      "0",
1068                      1);
1069   t_hmac_derive_key (&ax->CKr,
1070                      &ax->CKr,
1071                      "1",
1072                      1);
1073   GNUNET_CONTAINER_DLL_insert (ax->skipped_head,
1074                                ax->skipped_tail,
1075                                key);
1076   ax->skipped++;
1077   ax->Nr++;
1078 }
1079
1080
1081 /**
1082  * Stage skipped AX keys and calculate the message key.
1083  * Stores each HK and MK for skipped messages.
1084  *
1085  * @param ax key material to use
1086  * @param HKr Header key.
1087  * @param Np Received meesage number.
1088  * @return #GNUNET_OK if keys were stored.
1089  *         #GNUNET_SYSERR if an error ocurred (@a Np not expected).
1090  */
1091 static int
1092 store_ax_keys (struct CadetTunnelAxolotl *ax,
1093                const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1094                uint32_t Np)
1095 {
1096   int gap;
1097
1098   gap = Np - ax->Nr;
1099   LOG (GNUNET_ERROR_TYPE_DEBUG,
1100        "Storing skipped keys [%u, %u)\n",
1101        ax->Nr,
1102        Np);
1103   if (MAX_KEY_GAP < gap)
1104   {
1105     /* Avoid DoS (forcing peer to do more than #MAX_KEY_GAP HMAC operations) */
1106     /* TODO: start new key exchange on return */
1107     GNUNET_break_op (0);
1108     LOG (GNUNET_ERROR_TYPE_WARNING,
1109          "Got message %u, expected %u+\n",
1110          Np,
1111          ax->Nr);
1112     return GNUNET_SYSERR;
1113   }
1114   if (0 > gap)
1115   {
1116     /* Delayed message: don't store keys, flag to try old keys. */
1117     return GNUNET_SYSERR;
1118   }
1119
1120   while (ax->Nr < Np)
1121     store_skipped_key (ax,
1122                        HKr);
1123
1124   while (ax->skipped > MAX_SKIPPED_KEYS)
1125     delete_skipped_key (ax,
1126                         ax->skipped_tail);
1127   return GNUNET_OK;
1128 }
1129
1130
1131 /**
1132  * Decrypt and verify data with the appropriate tunnel key and verify that the
1133  * data has not been altered since it was sent by the remote peer.
1134  *
1135  * @param ax key material to use
1136  * @param dst Destination for the plaintext.
1137  * @param src Source of the message. Can overlap with @c dst.
1138  * @param size Size of the message.
1139  * @return Size of the decrypted data, -1 if an error was encountered.
1140  */
1141 static ssize_t
1142 t_ax_decrypt_and_validate (struct CadetTunnelAxolotl *ax,
1143                            void *dst,
1144                            const struct GNUNET_CADET_TunnelEncryptedMessage *src,
1145                            size_t size)
1146 {
1147   struct GNUNET_ShortHashCode msg_hmac;
1148   struct GNUNET_HashCode hmac;
1149   struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
1150   uint32_t Np;
1151   uint32_t PNp;
1152   size_t esize; /* Size of encryped payload */
1153
1154   esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1155
1156   /* Try current HK */
1157   t_hmac (&src->ax_header,
1158           sizeof (struct GNUNET_CADET_AxHeader) + esize,
1159           0, &ax->HKr,
1160           &msg_hmac);
1161   if (0 != memcmp (&msg_hmac,
1162                    &src->hmac,
1163                    sizeof (msg_hmac)))
1164   {
1165     static const char ctx[] = "axolotl ratchet";
1166     struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1167     struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1168     struct GNUNET_HashCode dh;
1169     struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1170
1171     /* Try Next HK */
1172     t_hmac (&src->ax_header,
1173             sizeof (struct GNUNET_CADET_AxHeader) + esize,
1174             0,
1175             &ax->NHKr,
1176             &msg_hmac);
1177     if (0 != memcmp (&msg_hmac,
1178                      &src->hmac,
1179                      sizeof (msg_hmac)))
1180     {
1181       /* Try the skipped keys, if that fails, we're out of luck. */
1182       return try_old_ax_keys (ax,
1183                               dst,
1184                               src,
1185                               size);
1186     }
1187     HK = ax->HKr;
1188     ax->HKr = ax->NHKr;
1189     t_h_decrypt (ax,
1190                  src,
1191                  &plaintext_header);
1192     Np = ntohl (plaintext_header.ax_header.Ns);
1193     PNp = ntohl (plaintext_header.ax_header.PNs);
1194     DHRp = &plaintext_header.ax_header.DHRs;
1195     store_ax_keys (ax,
1196                    &HK,
1197                    PNp);
1198
1199     /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1200     GNUNET_CRYPTO_ecc_ecdh (&ax->DHRs,
1201                             DHRp,
1202                             &dh);
1203     t_ax_hmac_hash (&ax->RK,
1204                     &hmac,
1205                     &dh, sizeof (dh));
1206     GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1207                        ctx, sizeof (ctx),
1208                        &hmac, sizeof (hmac),
1209                        NULL);
1210
1211     /* Commit "purported" keys */
1212     ax->RK = keys[0];
1213     ax->NHKr = keys[1];
1214     ax->CKr = keys[2];
1215     ax->DHRr = *DHRp;
1216     ax->Nr = 0;
1217     ax->ratchet_allowed = GNUNET_YES;
1218   }
1219   else
1220   {
1221     t_h_decrypt (ax,
1222                  src,
1223                  &plaintext_header);
1224     Np = ntohl (plaintext_header.ax_header.Ns);
1225     PNp = ntohl (plaintext_header.ax_header.PNs);
1226   }
1227   if ( (Np != ax->Nr) &&
1228        (GNUNET_OK != store_ax_keys (ax,
1229                                     &ax->HKr,
1230                                     Np)) )
1231   {
1232     /* Try the skipped keys, if that fails, we're out of luck. */
1233     return try_old_ax_keys (ax,
1234                             dst,
1235                             src,
1236                             size);
1237   }
1238
1239   t_ax_decrypt (ax,
1240                 dst,
1241                 &src[1],
1242                 esize);
1243   ax->Nr = Np + 1;
1244   return esize;
1245 }
1246
1247
1248 /**
1249  * Our tunnel became ready for the first time, notify channels
1250  * that have been waiting.
1251  *
1252  * @param cls our tunnel, not used
1253  * @param key unique ID of the channel, not used
1254  * @param value the `struct CadetChannel` to notify
1255  * @return #GNUNET_OK (continue to iterate)
1256  */
1257 static int
1258 notify_tunnel_up_cb (void *cls,
1259                      uint32_t key,
1260                      void *value)
1261 {
1262   struct CadetChannel *ch = value;
1263
1264   GCCH_tunnel_up (ch);
1265   return GNUNET_OK;
1266 }
1267
1268
1269 /**
1270  * Change the tunnel encryption state.
1271  * If the encryption state changes to OK, stop the rekey task.
1272  *
1273  * @param t Tunnel whose encryption state to change, or NULL.
1274  * @param state New encryption state.
1275  */
1276 void
1277 GCT_change_estate (struct CadetTunnel *t,
1278                    enum CadetTunnelEState state)
1279 {
1280   enum CadetTunnelEState old = t->estate;
1281
1282   t->estate = state;
1283   LOG (GNUNET_ERROR_TYPE_DEBUG,
1284        "%s estate changed from %s to %s\n",
1285        GCT_2s (t),
1286        estate2s (old),
1287        estate2s (state));
1288
1289   if ( (CADET_TUNNEL_KEY_OK != old) &&
1290        (CADET_TUNNEL_KEY_OK == t->estate) )
1291   {
1292     if (NULL != t->kx_task)
1293     {
1294       GNUNET_SCHEDULER_cancel (t->kx_task);
1295       t->kx_task = NULL;
1296     }
1297     /* notify all channels that have been waiting */
1298     GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1299                                              &notify_tunnel_up_cb,
1300                                              t);
1301     if (NULL != t->send_task)
1302       GNUNET_SCHEDULER_cancel (t->send_task);
1303     t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
1304                                              t);
1305   }
1306 }
1307
1308
1309 /**
1310  * Send a KX message.
1311  *
1312  * @param t tunnel on which to send the KX_AUTH
1313  * @param ct Tunnel and connection on which to send the KX_AUTH, NULL if
1314  *           we are to find one that is ready.
1315  * @param ax axolotl key context to use
1316  */
1317 static void
1318 send_kx (struct CadetTunnel *t,
1319          struct CadetTConnection *ct,
1320          struct CadetTunnelAxolotl *ax)
1321 {
1322   struct CadetConnection *cc;
1323   struct GNUNET_MQ_Envelope *env;
1324   struct GNUNET_CADET_TunnelKeyExchangeMessage *msg;
1325   enum GNUNET_CADET_KX_Flags flags;
1326
1327   if ( (NULL == ct) ||
1328        (GNUNET_NO == ct->is_ready) )
1329     ct = get_ready_connection (t);
1330   if (NULL == ct)
1331   {
1332     LOG (GNUNET_ERROR_TYPE_DEBUG,
1333          "Wanted to send %s in state %s, but no connection is ready, deferring\n",
1334          GCT_2s (t),
1335          estate2s (t->estate));
1336     t->next_kx_attempt = GNUNET_TIME_absolute_get ();
1337     return;
1338   }
1339   cc = ct->cc;
1340   LOG (GNUNET_ERROR_TYPE_DEBUG,
1341        "Sending KX on %s via %s in state %s\n",
1342        GCT_2s (t),
1343        GCC_2s (cc),
1344        estate2s (t->estate));
1345   env = GNUNET_MQ_msg (msg,
1346                        GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX);
1347   flags = GNUNET_CADET_KX_FLAG_FORCE_REPLY; /* always for KX */
1348   msg->flags = htonl (flags);
1349   msg->cid = *GCC_get_id (cc);
1350   GNUNET_CRYPTO_ecdhe_key_get_public (&ax->kx_0,
1351                                       &msg->ephemeral_key);
1352   GNUNET_CRYPTO_ecdhe_key_get_public (&ax->DHRs,
1353                                       &msg->ratchet_key);
1354   mark_connection_unready (ct);
1355   t->kx_retry_delay = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1356   t->next_kx_attempt = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1357   if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1358     GCT_change_estate (t,
1359                        CADET_TUNNEL_KEY_AX_SENT);
1360   else if (CADET_TUNNEL_KEY_AX_RECV == t->estate)
1361     GCT_change_estate (t,
1362                        CADET_TUNNEL_KEY_AX_SENT_AND_RECV);
1363   GCC_transmit (cc,
1364                 env);
1365   GNUNET_STATISTICS_update (stats,
1366                             "# KX transmitted",
1367                             1,
1368                             GNUNET_NO);
1369 }
1370
1371
1372 /**
1373  * Send a KX_AUTH message.
1374  *
1375  * @param t tunnel on which to send the KX_AUTH
1376  * @param ct Tunnel and connection on which to send the KX_AUTH, NULL if
1377  *           we are to find one that is ready.
1378  * @param ax axolotl key context to use
1379  * @param force_reply Force the other peer to reply with a KX_AUTH message
1380  *         (set if we would like to transmit right now, but cannot)
1381  */
1382 static void
1383 send_kx_auth (struct CadetTunnel *t,
1384               struct CadetTConnection *ct,
1385               struct CadetTunnelAxolotl *ax,
1386               int force_reply)
1387 {
1388   struct CadetConnection *cc;
1389   struct GNUNET_MQ_Envelope *env;
1390   struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg;
1391   enum GNUNET_CADET_KX_Flags flags;
1392
1393   if ( (NULL == ct) ||
1394        (GNUNET_NO == ct->is_ready) )
1395     ct = get_ready_connection (t);
1396   if (NULL == ct)
1397   {
1398     LOG (GNUNET_ERROR_TYPE_DEBUG,
1399          "Wanted to send KX_AUTH on %s, but no connection is ready, deferring\n",
1400          GCT_2s (t));
1401     t->next_kx_attempt = GNUNET_TIME_absolute_get ();
1402     t->kx_auth_requested = GNUNET_YES; /* queue KX_AUTH independent of estate */
1403     return;
1404   }
1405   t->kx_auth_requested = GNUNET_NO; /* clear flag */
1406   cc = ct->cc;
1407   LOG (GNUNET_ERROR_TYPE_DEBUG,
1408        "Sending KX_AUTH on %s using %s\n",
1409        GCT_2s (t),
1410        GCC_2s (ct->cc));
1411
1412   env = GNUNET_MQ_msg (msg,
1413                        GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX_AUTH);
1414   flags = GNUNET_CADET_KX_FLAG_NONE;
1415   if (GNUNET_YES == force_reply)
1416     flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY;
1417   msg->kx.flags = htonl (flags);
1418   msg->kx.cid = *GCC_get_id (cc);
1419   GNUNET_CRYPTO_ecdhe_key_get_public (&ax->kx_0,
1420                                       &msg->kx.ephemeral_key);
1421   GNUNET_CRYPTO_ecdhe_key_get_public (&ax->DHRs,
1422                                       &msg->kx.ratchet_key);
1423   /* Compute authenticator (this is the main difference to #send_kx()) */
1424   GNUNET_CRYPTO_hash (&ax->RK,
1425                       sizeof (ax->RK),
1426                       &msg->auth);
1427
1428   /* Compute when to be triggered again; actual job will
1429      be scheduled via #connection_ready_cb() */
1430   t->kx_retry_delay
1431     = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1432   t->next_kx_attempt
1433     = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1434
1435   /* Send via cc, mark it as unready */
1436   mark_connection_unready (ct);
1437
1438   /* Update state machine, unless we are already OK */
1439   if (CADET_TUNNEL_KEY_OK != t->estate)
1440     GCT_change_estate (t,
1441                        CADET_TUNNEL_KEY_AX_AUTH_SENT);
1442   GCC_transmit (cc,
1443                 env);
1444   GNUNET_STATISTICS_update (stats,
1445                             "# KX_AUTH transmitted",
1446                             1,
1447                             GNUNET_NO);
1448 }
1449
1450
1451 /**
1452  * Cleanup state used by @a ax.
1453  *
1454  * @param ax state to free, but not memory of @a ax itself
1455  */
1456 static void
1457 cleanup_ax (struct CadetTunnelAxolotl *ax)
1458 {
1459   while (NULL != ax->skipped_head)
1460     delete_skipped_key (ax,
1461                         ax->skipped_head);
1462   GNUNET_assert (0 == ax->skipped);
1463   GNUNET_CRYPTO_ecdhe_key_clear (&ax->kx_0);
1464   GNUNET_CRYPTO_ecdhe_key_clear (&ax->DHRs);
1465 }
1466
1467
1468 /**
1469  * Update our Axolotl key state based on the KX data we received.
1470  * Computes the new chain keys, and root keys, etc, and also checks
1471  * wether this is a replay of the current chain.
1472  *
1473  * @param[in|out] axolotl chain key state to recompute
1474  * @param pid peer identity of the other peer
1475  * @param ephemeral_key ephemeral public key of the other peer
1476  * @param ratchet_key senders next ephemeral public key
1477  * @return #GNUNET_OK on success, #GNUNET_NO if the resulting
1478  *       root key is already in @a ax and thus the KX is useless;
1479  *       #GNUNET_SYSERR on hard errors (i.e. @a pid is #my_full_id)
1480  */
1481 static int
1482 update_ax_by_kx (struct CadetTunnelAxolotl *ax,
1483                  const struct GNUNET_PeerIdentity *pid,
1484                  const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key,
1485                  const struct GNUNET_CRYPTO_EcdhePublicKey *ratchet_key)
1486 {
1487   struct GNUNET_HashCode key_material[3];
1488   struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
1489   const char salt[] = "CADET Axolotl salt";
1490   int am_I_alice;
1491
1492   if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1493                                            pid))
1494     am_I_alice = GNUNET_YES;
1495   else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1496                                                 pid))
1497     am_I_alice = GNUNET_NO;
1498   else
1499   {
1500     GNUNET_break_op (0);
1501     return GNUNET_SYSERR;
1502   }
1503
1504   if (0 == memcmp (&ax->DHRr,
1505                    ratchet_key,
1506                    sizeof (*ratchet_key)))
1507   {
1508     GNUNET_STATISTICS_update (stats,
1509                               "# Ratchet key already known",
1510                               1,
1511                               GNUNET_NO);
1512     LOG (GNUNET_ERROR_TYPE_DEBUG,
1513          "Ratchet key already known. Ignoring KX.\n");
1514     return GNUNET_NO;
1515   }
1516
1517   ax->DHRr = *ratchet_key;
1518   ax->last_ephemeral = *ephemeral_key;
1519   /* ECDH A B0 */
1520   if (GNUNET_YES == am_I_alice)
1521   {
1522     GNUNET_CRYPTO_eddsa_ecdh (my_private_key,      /* A */
1523                               ephemeral_key,       /* B0 */
1524                               &key_material[0]);
1525   }
1526   else
1527   {
1528     GNUNET_CRYPTO_ecdh_eddsa (&ax->kx_0,            /* B0 */
1529                               &pid->public_key,     /* A */
1530                               &key_material[0]);
1531   }
1532
1533   /* ECDH A0 B */
1534   if (GNUNET_YES == am_I_alice)
1535   {
1536     GNUNET_CRYPTO_ecdh_eddsa (&ax->kx_0,            /* A0 */
1537                               &pid->public_key,     /* B */
1538                               &key_material[1]);
1539   }
1540   else
1541   {
1542     GNUNET_CRYPTO_eddsa_ecdh (my_private_key,      /* A */
1543                               ephemeral_key,       /* B0 */
1544                               &key_material[1]);
1545   }
1546
1547   /* ECDH A0 B0 */
1548   GNUNET_CRYPTO_ecc_ecdh (&ax->kx_0,             /* A0 or B0 */
1549                           ephemeral_key,         /* B0 or A0 */
1550                           &key_material[2]);
1551
1552   /* KDF */
1553   GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1554                      salt, sizeof (salt),
1555                      &key_material, sizeof (key_material),
1556                      NULL);
1557
1558   if (0 == memcmp (&ax->RK,
1559                    &keys[0],
1560                    sizeof (ax->RK)))
1561   {
1562     LOG (GNUNET_ERROR_TYPE_DEBUG,
1563          "Root key of handshake already known. Ignoring KX.\n");
1564     GNUNET_STATISTICS_update (stats,
1565                               "# Root key already known",
1566                               1,
1567                               GNUNET_NO);
1568     return GNUNET_NO;
1569   }
1570
1571   ax->RK = keys[0];
1572   if (GNUNET_YES == am_I_alice)
1573   {
1574     ax->HKr = keys[1];
1575     ax->NHKs = keys[2];
1576     ax->NHKr = keys[3];
1577     ax->CKr = keys[4];
1578     ax->ratchet_flag = GNUNET_YES;
1579   }
1580   else
1581   {
1582     ax->HKs = keys[1];
1583     ax->NHKr = keys[2];
1584     ax->NHKs = keys[3];
1585     ax->CKs = keys[4];
1586     ax->ratchet_flag = GNUNET_NO;
1587     ax->ratchet_expiration
1588       = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
1589                                   ratchet_time);
1590   }
1591   return GNUNET_OK;
1592 }
1593
1594
1595 /**
1596  * Try to redo the KX or KX_AUTH handshake, if we can.
1597  *
1598  * @param cls the `struct CadetTunnel` to do KX for.
1599  */
1600 static void
1601 retry_kx (void *cls)
1602 {
1603   struct CadetTunnel *t = cls;
1604   struct CadetTunnelAxolotl *ax;
1605
1606   t->kx_task = NULL;
1607   LOG (GNUNET_ERROR_TYPE_DEBUG,
1608        "Trying to make KX progress on %s in state %s\n",
1609        GCT_2s (t),
1610        estate2s (t->estate));
1611   switch (t->estate)
1612   {
1613   case CADET_TUNNEL_KEY_UNINITIALIZED: /* first attempt */
1614   case CADET_TUNNEL_KEY_AX_SENT:       /* trying again */
1615     send_kx (t,
1616              NULL,
1617              &t->ax);
1618     break;
1619   case CADET_TUNNEL_KEY_AX_RECV:
1620   case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
1621     /* We are responding, so only require reply
1622        if WE have a channel waiting. */
1623     if (NULL != t->unverified_ax)
1624     {
1625       /* Send AX_AUTH so we might get this one verified */
1626       ax = t->unverified_ax;
1627     }
1628     else
1629     {
1630       /* How can this be? */
1631       GNUNET_break (0);
1632       ax = &t->ax;
1633     }
1634     send_kx_auth (t,
1635                   NULL,
1636                   ax,
1637                   (0 == GCT_count_channels (t))
1638                   ? GNUNET_NO
1639                   : GNUNET_YES);
1640     break;
1641   case CADET_TUNNEL_KEY_AX_AUTH_SENT:
1642     /* We are responding, so only require reply
1643        if WE have a channel waiting. */
1644     if (NULL != t->unverified_ax)
1645     {
1646       /* Send AX_AUTH so we might get this one verified */
1647       ax = t->unverified_ax;
1648     }
1649     else
1650     {
1651       /* How can this be? */
1652       GNUNET_break (0);
1653       ax = &t->ax;
1654     }
1655     send_kx_auth (t,
1656                   NULL,
1657                   ax,
1658                   (0 == GCT_count_channels (t))
1659                   ? GNUNET_NO
1660                   : GNUNET_YES);
1661     break;
1662   case CADET_TUNNEL_KEY_OK:
1663     /* Must have been the *other* peer asking us to
1664        respond with a KX_AUTH. */
1665     if (NULL != t->unverified_ax)
1666     {
1667       /* Sending AX_AUTH in response to AX so we might get this one verified */
1668       ax = t->unverified_ax;
1669     }
1670     else
1671     {
1672       /* Sending AX_AUTH in response to AX_AUTH */
1673       ax = &t->ax;
1674     }
1675     send_kx_auth (t,
1676                   NULL,
1677                   ax,
1678                   GNUNET_NO);
1679     break;
1680   }
1681 }
1682
1683
1684 /**
1685  * Handle KX message that lacks authentication (and which will thus
1686  * only be considered authenticated after we respond with our own
1687  * KX_AUTH and finally successfully decrypt payload).
1688  *
1689  * @param ct connection/tunnel combo that received encrypted message
1690  * @param msg the key exchange message
1691  */
1692 void
1693 GCT_handle_kx (struct CadetTConnection *ct,
1694                const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
1695 {
1696   struct CadetTunnel *t = ct->t;
1697   struct CadetTunnelAxolotl *ax;
1698   int ret;
1699
1700   GNUNET_STATISTICS_update (stats,
1701                             "# KX received",
1702                             1,
1703                             GNUNET_NO);
1704   if ( (0 ==
1705         memcmp (&t->ax.DHRr,
1706                 &msg->ratchet_key,
1707                 sizeof (msg->ratchet_key))) &&
1708        (0 ==
1709         memcmp (&t->ax.last_ephemeral,
1710                 &msg->ephemeral_key,
1711                 sizeof (msg->ephemeral_key))) )
1712
1713   {
1714     LOG (GNUNET_ERROR_TYPE_DEBUG,
1715          "Got duplicate KX. Firing back KX_AUTH.\n");
1716     GNUNET_STATISTICS_update (stats,
1717                               "# Duplicate KX received",
1718                               1,
1719                               GNUNET_NO);
1720     send_kx_auth (t,
1721                   ct,
1722                   &t->ax,
1723                   GNUNET_NO);
1724     return;
1725   }
1726
1727   /* We only keep ONE unverified KX around, so if there is an existing one,
1728      clean it up. */
1729   if (NULL != t->unverified_ax)
1730   {
1731     if ( (0 ==
1732           memcmp (&t->unverified_ax->DHRr,
1733                   &msg->ratchet_key,
1734                   sizeof (msg->ratchet_key))) &&
1735          (0 ==
1736           memcmp (&t->unverified_ax->last_ephemeral,
1737                   &msg->ephemeral_key,
1738                   sizeof (msg->ephemeral_key))) )
1739     {
1740       LOG (GNUNET_ERROR_TYPE_DEBUG,
1741            "Got duplicate unverified KX on %s. Fire back KX_AUTH again.\n",
1742            GCT_2s (t));
1743       GNUNET_STATISTICS_update (stats,
1744                                 "# Duplicate unverified KX received",
1745                                 1,
1746                                 GNUNET_NO);
1747 #if 0
1748       send_kx_auth (t,
1749                     ct,
1750                     t->unverified_ax,
1751                     GNUNET_NO);
1752       return;
1753 #endif
1754     }
1755     LOG (GNUNET_ERROR_TYPE_DEBUG,
1756          "Dropping old unverified KX state. Got a fresh KX for %s.\n",
1757          GCT_2s (t));
1758     GNUNET_STATISTICS_update (stats,
1759                               "# Unverified KX dropped for fresh KX",
1760                               1,
1761                               GNUNET_NO);
1762     memset (t->unverified_ax,
1763             0,
1764             sizeof (struct CadetTunnelAxolotl));
1765     t->unverified_ax->DHRs = t->ax.DHRs;
1766     t->unverified_ax->kx_0 = t->ax.kx_0;
1767   }
1768   else
1769   {
1770     LOG (GNUNET_ERROR_TYPE_DEBUG,
1771          "Creating fresh unverified KX for %s.\n",
1772          GCT_2s (t));
1773     GNUNET_STATISTICS_update (stats,
1774                               "# Fresh KX setup",
1775                               1,
1776                               GNUNET_NO);
1777     t->unverified_ax = GNUNET_new (struct CadetTunnelAxolotl);
1778     t->unverified_ax->DHRs = t->ax.DHRs;
1779     t->unverified_ax->kx_0 = t->ax.kx_0;
1780   }
1781   /* Set as the 'current' RK/DHRr the one we are currently using,
1782      so that the duplicate-detection logic of
1783      #update_ax_by_kx can work. */
1784   t->unverified_ax->RK = t->ax.RK;
1785   t->unverified_ax->DHRr = t->ax.DHRr;
1786   t->unverified_attempts = 0;
1787   ax = t->unverified_ax;
1788
1789   /* Update 'ax' by the new key material */
1790   ret = update_ax_by_kx (ax,
1791                          GCP_get_id (t->destination),
1792                          &msg->ephemeral_key,
1793                          &msg->ratchet_key);
1794   GNUNET_break (GNUNET_SYSERR != ret);
1795   if (GNUNET_OK != ret)
1796   {
1797     GNUNET_STATISTICS_update (stats,
1798                               "# Useless KX",
1799                               1,
1800                               GNUNET_NO);
1801     return; /* duplicate KX, nothing to do */
1802   }
1803   /* move ahead in our state machine */
1804   if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1805     GCT_change_estate (t,
1806                        CADET_TUNNEL_KEY_AX_RECV);
1807   else if (CADET_TUNNEL_KEY_AX_SENT == t->estate)
1808     GCT_change_estate (t,
1809                        CADET_TUNNEL_KEY_AX_SENT_AND_RECV);
1810
1811   /* KX is still not done, try again our end. */
1812   if (CADET_TUNNEL_KEY_OK != t->estate)
1813   {
1814     if (NULL != t->kx_task)
1815       GNUNET_SCHEDULER_cancel (t->kx_task);
1816     t->kx_task
1817       = GNUNET_SCHEDULER_add_now (&retry_kx,
1818                                   t);
1819   }
1820 }
1821
1822
1823 /**
1824  * Handle KX_AUTH message.
1825  *
1826  * @param ct connection/tunnel combo that received encrypted message
1827  * @param msg the key exchange message
1828  */
1829 void
1830 GCT_handle_kx_auth (struct CadetTConnection *ct,
1831                     const struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg)
1832 {
1833   struct CadetTunnel *t = ct->t;
1834   struct CadetTunnelAxolotl ax_tmp;
1835   struct GNUNET_HashCode kx_auth;
1836   int ret;
1837
1838   GNUNET_STATISTICS_update (stats,
1839                             "# KX_AUTH received",
1840                             1,
1841                             GNUNET_NO);
1842   if ( (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) ||
1843        (CADET_TUNNEL_KEY_AX_RECV == t->estate) )
1844   {
1845     /* Confusing, we got a KX_AUTH before we even send our own
1846        KX. This should not happen. We'll send our own KX ASAP anyway,
1847        so let's ignore this here. */
1848     GNUNET_break_op (0);
1849     return;
1850   }
1851   LOG (GNUNET_ERROR_TYPE_DEBUG,
1852        "Handling KX_AUTH message for %s\n",
1853        GCT_2s (t));
1854
1855   /* We do everything in ax_tmp until we've checked the authentication
1856      so we don't clobber anything we care about by accident. */
1857   ax_tmp = t->ax;
1858
1859   /* Update 'ax' by the new key material */
1860   ret = update_ax_by_kx (&ax_tmp,
1861                          GCP_get_id (t->destination),
1862                          &msg->kx.ephemeral_key,
1863                          &msg->kx.ratchet_key);
1864   if (GNUNET_OK != ret)
1865   {
1866     if (GNUNET_NO == ret)
1867       GNUNET_STATISTICS_update (stats,
1868                                 "# redundant KX_AUTH received",
1869                                 1,
1870                                 GNUNET_NO);
1871     else
1872       GNUNET_break (0); /* connect to self!? */
1873     return;
1874   }
1875   GNUNET_CRYPTO_hash (&ax_tmp.RK,
1876                       sizeof (ax_tmp.RK),
1877                       &kx_auth);
1878   if (0 != memcmp (&kx_auth,
1879                    &msg->auth,
1880                    sizeof (kx_auth)))
1881   {
1882     /* This KX_AUTH is not using the latest KX/KX_AUTH data
1883        we transmitted to the sender, refuse it, try KX again. */
1884     GNUNET_STATISTICS_update (stats,
1885                               "# KX_AUTH not using our last KX received (auth failure)",
1886                               1,
1887                               GNUNET_NO);
1888     send_kx (t,
1889              ct,
1890              &t->ax);
1891     return;
1892   }
1893   /* Yep, we're good. */
1894   t->ax = ax_tmp;
1895   if (NULL != t->unverified_ax)
1896   {
1897     /* We got some "stale" KX before, drop that. */
1898     cleanup_ax (t->unverified_ax);
1899     GNUNET_free (t->unverified_ax);
1900     t->unverified_ax = NULL;
1901   }
1902
1903   /* move ahead in our state machine */
1904   switch (t->estate)
1905   {
1906   case CADET_TUNNEL_KEY_UNINITIALIZED:
1907   case CADET_TUNNEL_KEY_AX_RECV:
1908     /* Checked above, this is impossible. */
1909     GNUNET_assert (0);
1910     break;
1911   case CADET_TUNNEL_KEY_AX_SENT:      /* This is the normal case */
1912   case CADET_TUNNEL_KEY_AX_SENT_AND_RECV: /* both peers started KX */
1913   case CADET_TUNNEL_KEY_AX_AUTH_SENT: /* both peers now did KX_AUTH */
1914     GCT_change_estate (t,
1915                        CADET_TUNNEL_KEY_OK);
1916     break;
1917   case CADET_TUNNEL_KEY_OK:
1918     /* Did not expect another KX_AUTH, but so what, still acceptable.
1919        Nothing to do here. */
1920     break;
1921   }
1922 }
1923
1924
1925
1926 /* ************************************** end core crypto ***************************** */
1927
1928
1929 /**
1930  * Compute the next free channel tunnel number for this tunnel.
1931  *
1932  * @param t the tunnel
1933  * @return unused number that can uniquely identify a channel in the tunnel
1934  */
1935 static struct GNUNET_CADET_ChannelTunnelNumber
1936 get_next_free_ctn (struct CadetTunnel *t)
1937 {
1938 #define HIGH_BIT 0x8000000
1939   struct GNUNET_CADET_ChannelTunnelNumber ret;
1940   uint32_t ctn;
1941   int cmp;
1942   uint32_t highbit;
1943
1944   cmp = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1945                                          GCP_get_id (GCT_get_destination (t)));
1946   if (0 < cmp)
1947     highbit = HIGH_BIT;
1948   else if (0 > cmp)
1949     highbit = 0;
1950   else
1951     GNUNET_assert (0); // loopback must never go here!
1952   ctn = ntohl (t->next_ctn.cn);
1953   while (NULL !=
1954          GNUNET_CONTAINER_multihashmap32_get (t->channels,
1955                                               ctn | highbit))
1956   {
1957     ctn = ((ctn + 1) & (~ HIGH_BIT));
1958   }
1959   t->next_ctn.cn = htonl ((ctn + 1) & (~ HIGH_BIT));
1960   ret.cn = htonl (ctn | highbit);
1961   return ret;
1962 }
1963
1964
1965 /**
1966  * Add a channel to a tunnel, and notify channel that we are ready
1967  * for transmission if we are already up.  Otherwise that notification
1968  * will be done later in #notify_tunnel_up_cb().
1969  *
1970  * @param t Tunnel.
1971  * @param ch Channel
1972  * @return unique number identifying @a ch within @a t
1973  */
1974 struct GNUNET_CADET_ChannelTunnelNumber
1975 GCT_add_channel (struct CadetTunnel *t,
1976                  struct CadetChannel *ch)
1977 {
1978   struct GNUNET_CADET_ChannelTunnelNumber ctn;
1979
1980   ctn = get_next_free_ctn (t);
1981   if (NULL != t->destroy_task)
1982   {
1983     GNUNET_SCHEDULER_cancel (t->destroy_task);
1984     t->destroy_task = NULL;
1985   }
1986   GNUNET_assert (GNUNET_YES ==
1987                  GNUNET_CONTAINER_multihashmap32_put (t->channels,
1988                                                       ntohl (ctn.cn),
1989                                                       ch,
1990                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1991   LOG (GNUNET_ERROR_TYPE_DEBUG,
1992        "Adding %s to %s\n",
1993        GCCH_2s (ch),
1994        GCT_2s (t));
1995   switch (t->estate)
1996   {
1997   case CADET_TUNNEL_KEY_UNINITIALIZED:
1998     /* waiting for connection to start KX */
1999     break;
2000   case CADET_TUNNEL_KEY_AX_RECV:
2001   case CADET_TUNNEL_KEY_AX_SENT:
2002   case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
2003     /* we're currently waiting for KX to complete */
2004     break;
2005   case CADET_TUNNEL_KEY_AX_AUTH_SENT:
2006     /* waiting for OTHER peer to send us data,
2007        we might need to prompt more aggressively! */
2008     if (NULL == t->kx_task)
2009       t->kx_task
2010         = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
2011                                    &retry_kx,
2012                                    t);
2013     break;
2014   case CADET_TUNNEL_KEY_OK:
2015     /* We are ready. Tell the new channel that we are up. */
2016     GCCH_tunnel_up (ch);
2017     break;
2018   }
2019   return ctn;
2020 }
2021
2022
2023 /**
2024  * We lost a connection, remove it from our list and clean up
2025  * the connection object itself.
2026  *
2027  * @param ct binding of connection to tunnel of the connection that was lost.
2028  */
2029 void
2030 GCT_connection_lost (struct CadetTConnection *ct)
2031 {
2032   struct CadetTunnel *t = ct->t;
2033
2034   if (GNUNET_YES == ct->is_ready)
2035   {
2036     GNUNET_CONTAINER_DLL_remove (t->connection_ready_head,
2037                                  t->connection_ready_tail,
2038                                  ct);
2039     t->num_ready_connections--;
2040   }
2041   else
2042   {
2043     GNUNET_CONTAINER_DLL_remove (t->connection_busy_head,
2044                                  t->connection_busy_tail,
2045                                  ct);
2046     t->num_busy_connections--;
2047   }
2048   GNUNET_free (ct);
2049 }
2050
2051
2052 /**
2053  * Clean up connection @a ct of a tunnel.
2054  *
2055  * @param cls the `struct CadetTunnel`
2056  * @param ct connection to clean up
2057  */
2058 static void
2059 destroy_t_connection (void *cls,
2060                       struct CadetTConnection *ct)
2061 {
2062   struct CadetTunnel *t = cls;
2063   struct CadetConnection *cc = ct->cc;
2064
2065   GNUNET_assert (ct->t == t);
2066   GCT_connection_lost (ct);
2067   GCC_destroy_without_tunnel (cc);
2068 }
2069
2070
2071 /**
2072  * This tunnel is no longer used, destroy it.
2073  *
2074  * @param cls the idle tunnel
2075  */
2076 static void
2077 destroy_tunnel (void *cls)
2078 {
2079   struct CadetTunnel *t = cls;
2080   struct CadetTunnelQueueEntry *tq;
2081
2082   t->destroy_task = NULL;
2083   LOG (GNUNET_ERROR_TYPE_DEBUG,
2084        "Destroying idle %s\n",
2085        GCT_2s (t));
2086   GNUNET_assert (0 == GCT_count_channels (t));
2087   GCT_iterate_connections (t,
2088                            &destroy_t_connection,
2089                            t);
2090   GNUNET_assert (NULL == t->connection_ready_head);
2091   GNUNET_assert (NULL == t->connection_busy_head);
2092   while (NULL != (tq = t->tq_head))
2093   {
2094     if (NULL != tq->cont)
2095       tq->cont (tq->cont_cls,
2096                 NULL);
2097     GCT_send_cancel (tq);
2098   }
2099   GCP_drop_tunnel (t->destination,
2100                    t);
2101   GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
2102   if (NULL != t->maintain_connections_task)
2103   {
2104     GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
2105     t->maintain_connections_task = NULL;
2106   }
2107   if (NULL != t->send_task)
2108   {
2109     GNUNET_SCHEDULER_cancel (t->send_task);
2110     t->send_task = NULL;
2111   }
2112   if (NULL != t->kx_task)
2113   {
2114     GNUNET_SCHEDULER_cancel (t->kx_task);
2115     t->kx_task = NULL;
2116   }
2117   GNUNET_MST_destroy (t->mst);
2118   GNUNET_MQ_destroy (t->mq);
2119   if (NULL != t->unverified_ax)
2120   {
2121     cleanup_ax (t->unverified_ax);
2122     GNUNET_free (t->unverified_ax);
2123   }
2124   cleanup_ax (&t->ax);
2125   GNUNET_assert (NULL == t->destroy_task);
2126   GNUNET_free (t);
2127 }
2128
2129
2130 /**
2131  * Remove a channel from a tunnel.
2132  *
2133  * @param t Tunnel.
2134  * @param ch Channel
2135  * @param ctn unique number identifying @a ch within @a t
2136  */
2137 void
2138 GCT_remove_channel (struct CadetTunnel *t,
2139                     struct CadetChannel *ch,
2140                     struct GNUNET_CADET_ChannelTunnelNumber ctn)
2141 {
2142   LOG (GNUNET_ERROR_TYPE_DEBUG,
2143        "Removing %s from %s\n",
2144        GCCH_2s (ch),
2145        GCT_2s (t));
2146   GNUNET_assert (GNUNET_YES ==
2147                  GNUNET_CONTAINER_multihashmap32_remove (t->channels,
2148                                                          ntohl (ctn.cn),
2149                                                          ch));
2150   if ( (0 ==
2151         GCT_count_channels (t)) &&
2152        (NULL == t->destroy_task) )
2153   {
2154     t->destroy_task
2155       = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
2156                                       &destroy_tunnel,
2157                                       t);
2158   }
2159 }
2160
2161
2162 /**
2163  * Destroy remaining channels during shutdown.
2164  *
2165  * @param cls the `struct CadetTunnel` of the channel
2166  * @param key key of the channel
2167  * @param value the `struct CadetChannel`
2168  * @return #GNUNET_OK (continue to iterate)
2169  */
2170 static int
2171 destroy_remaining_channels (void *cls,
2172                             uint32_t key,
2173                             void *value)
2174 {
2175   struct CadetChannel *ch = value;
2176
2177   GCCH_handle_remote_destroy (ch,
2178                               NULL);
2179   return GNUNET_OK;
2180 }
2181
2182
2183 /**
2184  * Destroys the tunnel @a t now, without delay. Used during shutdown.
2185  *
2186  * @param t tunnel to destroy
2187  */
2188 void
2189 GCT_destroy_tunnel_now (struct CadetTunnel *t)
2190 {
2191   GNUNET_assert (GNUNET_YES == shutting_down);
2192   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2193                                            &destroy_remaining_channels,
2194                                            t);
2195   GNUNET_assert (0 ==
2196                  GCT_count_channels (t));
2197   if (NULL != t->destroy_task)
2198   {
2199     GNUNET_SCHEDULER_cancel (t->destroy_task);
2200     t->destroy_task = NULL;
2201   }
2202   destroy_tunnel (t);
2203 }
2204
2205
2206 /**
2207  * Send normal payload from queue in @a t via connection @a ct.
2208  * Does nothing if our payload queue is empty.
2209  *
2210  * @param t tunnel to send data from
2211  * @param ct connection to use for transmission (is ready)
2212  */
2213 static void
2214 try_send_normal_payload (struct CadetTunnel *t,
2215                          struct CadetTConnection *ct)
2216 {
2217   struct CadetTunnelQueueEntry *tq;
2218
2219   GNUNET_assert (GNUNET_YES == ct->is_ready);
2220   tq = t->tq_head;
2221   if (NULL == tq)
2222   {
2223     /* no messages pending right now */
2224     LOG (GNUNET_ERROR_TYPE_DEBUG,
2225          "Not sending payload of %s on ready %s (nothing pending)\n",
2226          GCT_2s (t),
2227          GCC_2s (ct->cc));
2228     return;
2229   }
2230   /* ready to send message 'tq' on tunnel 'ct' */
2231   GNUNET_assert (t == tq->t);
2232   GNUNET_CONTAINER_DLL_remove (t->tq_head,
2233                                t->tq_tail,
2234                                tq);
2235   if (NULL != tq->cid)
2236     *tq->cid = *GCC_get_id (ct->cc);
2237   mark_connection_unready (ct);
2238   LOG (GNUNET_ERROR_TYPE_DEBUG,
2239        "Sending payload of %s on %s\n",
2240        GCT_2s (t),
2241        GCC_2s (ct->cc));
2242   GCC_transmit (ct->cc,
2243                 tq->env);
2244   if (NULL != tq->cont)
2245     tq->cont (tq->cont_cls,
2246               GCC_get_id (ct->cc));
2247   GNUNET_free (tq);
2248 }
2249
2250
2251 /**
2252  * A connection is @a is_ready for transmission.  Looks at our message
2253  * queue and if there is a message, sends it out via the connection.
2254  *
2255  * @param cls the `struct CadetTConnection` that is @a is_ready
2256  * @param is_ready #GNUNET_YES if connection are now ready,
2257  *                 #GNUNET_NO if connection are no longer ready
2258  */
2259 static void
2260 connection_ready_cb (void *cls,
2261                      int is_ready)
2262 {
2263   struct CadetTConnection *ct = cls;
2264   struct CadetTunnel *t = ct->t;
2265
2266   if (GNUNET_NO == is_ready)
2267   {
2268     LOG (GNUNET_ERROR_TYPE_DEBUG,
2269          "%s no longer ready for %s\n",
2270          GCC_2s (ct->cc),
2271          GCT_2s (t));
2272     mark_connection_unready (ct);
2273     return;
2274   }
2275   GNUNET_assert (GNUNET_NO == ct->is_ready);
2276   GNUNET_CONTAINER_DLL_remove (t->connection_busy_head,
2277                                t->connection_busy_tail,
2278                                ct);
2279   GNUNET_assert (0 < t->num_busy_connections);
2280   t->num_busy_connections--;
2281   ct->is_ready = GNUNET_YES;
2282   GNUNET_CONTAINER_DLL_insert_tail (t->connection_ready_head,
2283                                     t->connection_ready_tail,
2284                                     ct);
2285   t->num_ready_connections++;
2286
2287   LOG (GNUNET_ERROR_TYPE_DEBUG,
2288        "%s now ready for %s in state %s\n",
2289        GCC_2s (ct->cc),
2290        GCT_2s (t),
2291        estate2s (t->estate));
2292   switch (t->estate)
2293   {
2294   case CADET_TUNNEL_KEY_UNINITIALIZED:
2295     /* Do not begin KX if WE have no channels waiting! */
2296     if (0 == GCT_count_channels (t))
2297       return;
2298     /* We are uninitialized, just transmit immediately,
2299        without undue delay. */
2300     if (NULL != t->kx_task)
2301     {
2302       GNUNET_SCHEDULER_cancel (t->kx_task);
2303       t->kx_task = NULL;
2304     }
2305     send_kx (t,
2306              ct,
2307              &t->ax);
2308     break;
2309   case CADET_TUNNEL_KEY_AX_RECV:
2310   case CADET_TUNNEL_KEY_AX_SENT:
2311   case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
2312   case CADET_TUNNEL_KEY_AX_AUTH_SENT:
2313     /* we're currently waiting for KX to complete, schedule job */
2314     if (NULL == t->kx_task)
2315       t->kx_task
2316         = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
2317                                    &retry_kx,
2318                                    t);
2319     break;
2320   case CADET_TUNNEL_KEY_OK:
2321     if (GNUNET_YES == t->kx_auth_requested)
2322     {
2323       if (NULL != t->kx_task)
2324       {
2325         GNUNET_SCHEDULER_cancel (t->kx_task);
2326         t->kx_task = NULL;
2327       }
2328       send_kx_auth (t,
2329                     ct,
2330                     &t->ax,
2331                     GNUNET_NO);
2332       return;
2333     }
2334     try_send_normal_payload (t,
2335                              ct);
2336     break;
2337   }
2338 }
2339
2340
2341 /**
2342  * Called when either we have a new connection, or a new message in the
2343  * queue, or some existing connection has transmission capacity.  Looks
2344  * at our message queue and if there is a message, picks a connection
2345  * to send it on.
2346  *
2347  * @param cls the `struct CadetTunnel` to process messages on
2348  */
2349 static void
2350 trigger_transmissions (void *cls)
2351 {
2352   struct CadetTunnel *t = cls;
2353   struct CadetTConnection *ct;
2354
2355   t->send_task = NULL;
2356   if (NULL == t->tq_head)
2357     return; /* no messages pending right now */
2358   ct = get_ready_connection (t);
2359   if (NULL == ct)
2360     return; /* no connections ready */
2361   try_send_normal_payload (t,
2362                            ct);
2363 }
2364
2365
2366 /**
2367  * Closure for #evaluate_connection. Used to assemble summary information
2368  * about the existing connections so we can evaluate a new path.
2369  */
2370 struct EvaluationSummary
2371 {
2372
2373   /**
2374    * Minimum length of any of our connections, `UINT_MAX` if we have none.
2375    */
2376   unsigned int min_length;
2377
2378   /**
2379    * Maximum length of any of our connections, 0 if we have none.
2380    */
2381   unsigned int max_length;
2382
2383   /**
2384    * Minimum desirability of any of our connections, UINT64_MAX if we have none.
2385    */
2386   GNUNET_CONTAINER_HeapCostType min_desire;
2387
2388   /**
2389    * Maximum desirability of any of our connections, 0 if we have none.
2390    */
2391   GNUNET_CONTAINER_HeapCostType max_desire;
2392
2393   /**
2394    * Path we are comparing against for #evaluate_connection, can be NULL.
2395    */
2396   struct CadetPeerPath *path;
2397
2398   /**
2399    * Connection deemed the "worst" so far encountered by #evaluate_connection,
2400    * NULL if we did not yet encounter any connections.
2401    */
2402   struct CadetTConnection *worst;
2403
2404   /**
2405    * Numeric score of @e worst, only set if @e worst is non-NULL.
2406    */
2407   double worst_score;
2408
2409   /**
2410    * Set to #GNUNET_YES if we have a connection over @e path already.
2411    */
2412   int duplicate;
2413
2414 };
2415
2416
2417 /**
2418  * Evaluate a connection, updating our summary information in @a cls about
2419  * what kinds of connections we have.
2420  *
2421  * @param cls the `struct EvaluationSummary *` to update
2422  * @param ct a connection to include in the summary
2423  */
2424 static void
2425 evaluate_connection (void *cls,
2426                      struct CadetTConnection *ct)
2427 {
2428   struct EvaluationSummary *es = cls;
2429   struct CadetConnection *cc = ct->cc;
2430   struct CadetPeerPath *ps = GCC_get_path (cc);
2431   const struct CadetConnectionMetrics *metrics;
2432   GNUNET_CONTAINER_HeapCostType ct_desirability;
2433   struct GNUNET_TIME_Relative uptime;
2434   struct GNUNET_TIME_Relative last_use;
2435   uint32_t ct_length;
2436   double score;
2437   double success_rate;
2438
2439   if (ps == es->path)
2440   {
2441     LOG (GNUNET_ERROR_TYPE_DEBUG,
2442          "Ignoring duplicate path %s.\n",
2443          GCPP_2s (es->path));
2444     es->duplicate = GNUNET_YES;
2445     return;
2446   }
2447   ct_desirability = GCPP_get_desirability (ps);
2448   ct_length = GCPP_get_length (ps);
2449   metrics = GCC_get_metrics (cc);
2450   uptime = GNUNET_TIME_absolute_get_duration (metrics->age);
2451   last_use = GNUNET_TIME_absolute_get_duration (metrics->last_use);
2452   /* We add 1.0 here to avoid division by zero. */
2453   success_rate = (metrics->num_acked_transmissions + 1.0) / (metrics->num_successes + 1.0);
2454   score
2455     = ct_desirability
2456     + 100.0 / (1.0 + ct_length) /* longer paths = better */
2457     + sqrt (uptime.rel_value_us / 60000000LL) /* larger uptime = better */
2458     - last_use.rel_value_us / 1000L;          /* longer idle = worse */
2459   score *= success_rate;        /* weigh overall by success rate */
2460
2461   if ( (NULL == es->worst) ||
2462        (score < es->worst_score) )
2463   {
2464     es->worst = ct;
2465     es->worst_score = score;
2466   }
2467   es->min_length = GNUNET_MIN (es->min_length,
2468                                ct_length);
2469   es->max_length = GNUNET_MAX (es->max_length,
2470                                ct_length);
2471   es->min_desire = GNUNET_MIN (es->min_desire,
2472                                ct_desirability);
2473   es->max_desire = GNUNET_MAX (es->max_desire,
2474                                ct_desirability);
2475 }
2476
2477
2478 /**
2479  * Consider using the path @a p for the tunnel @a t.
2480  * The tunnel destination is at offset @a off in path @a p.
2481  *
2482  * @param cls our tunnel
2483  * @param path a path to our destination
2484  * @param off offset of the destination on path @a path
2485  * @return #GNUNET_YES (should keep iterating)
2486  */
2487 static int
2488 consider_path_cb (void *cls,
2489                   struct CadetPeerPath *path,
2490                   unsigned int off)
2491 {
2492   struct CadetTunnel *t = cls;
2493   struct EvaluationSummary es;
2494   struct CadetTConnection *ct;
2495
2496   GNUNET_assert (off < GCPP_get_length (path));
2497   es.min_length = UINT_MAX;
2498   es.max_length = 0;
2499   es.max_desire = 0;
2500   es.min_desire = UINT64_MAX;
2501   es.path = path;
2502   es.duplicate = GNUNET_NO;
2503   es.worst = NULL;
2504
2505   /* Compute evaluation summary over existing connections. */
2506   GCT_iterate_connections (t,
2507                            &evaluate_connection,
2508                            &es);
2509   if (GNUNET_YES == es.duplicate)
2510     return GNUNET_YES;
2511
2512   /* FIXME: not sure we should really just count
2513      'num_connections' here, as they may all have
2514      consistently failed to connect. */
2515
2516   /* We iterate by increasing path length; if we have enough paths and
2517      this one is more than twice as long than what we are currently
2518      using, then ignore all of these super-long ones! */
2519   if ( (GCT_count_any_connections (t) > DESIRED_CONNECTIONS_PER_TUNNEL) &&
2520        (es.min_length * 2 < off) &&
2521        (es.max_length < off) )
2522   {
2523     LOG (GNUNET_ERROR_TYPE_DEBUG,
2524          "Ignoring paths of length %u, they are way too long.\n",
2525          es.min_length * 2);
2526     return GNUNET_NO;
2527   }
2528   /* If we have enough paths and this one looks no better, ignore it. */
2529   if ( (GCT_count_any_connections (t) >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
2530        (es.min_length < GCPP_get_length (path)) &&
2531        (es.min_desire > GCPP_get_desirability (path)) &&
2532        (es.max_length < off) )
2533   {
2534     LOG (GNUNET_ERROR_TYPE_DEBUG,
2535          "Ignoring path (%u/%llu) to %s, got something better already.\n",
2536          GCPP_get_length (path),
2537          (unsigned long long) GCPP_get_desirability (path),
2538          GCP_2s (t->destination));
2539     return GNUNET_YES;
2540   }
2541
2542   /* Path is interesting (better by some metric, or we don't have
2543      enough paths yet). */
2544   ct = GNUNET_new (struct CadetTConnection);
2545   ct->created = GNUNET_TIME_absolute_get ();
2546   ct->t = t;
2547   ct->cc = GCC_create (t->destination,
2548                        path,
2549                        off,
2550                        GNUNET_CADET_OPTION_DEFAULT, /* FIXME: set based on what channels want/need! */
2551                        ct,
2552                        &connection_ready_cb,
2553                        ct);
2554
2555   /* FIXME: schedule job to kill connection (and path?)  if it takes
2556      too long to get ready! (And track performance data on how long
2557      other connections took with the tunnel!)
2558      => Note: to be done within 'connection'-logic! */
2559   GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
2560                                t->connection_busy_tail,
2561                                ct);
2562   t->num_busy_connections++;
2563   LOG (GNUNET_ERROR_TYPE_DEBUG,
2564        "Found interesting path %s for %s, created %s\n",
2565        GCPP_2s (path),
2566        GCT_2s (t),
2567        GCC_2s (ct->cc));
2568   return GNUNET_YES;
2569 }
2570
2571
2572 /**
2573  * Function called to maintain the connections underlying our tunnel.
2574  * Tries to maintain (incl. tear down) connections for the tunnel, and
2575  * if there is a significant change, may trigger transmissions.
2576  *
2577  * Basically, needs to check if there are connections that perform
2578  * badly, and if so eventually kill them and trigger a replacement.
2579  * The strategy is to open one more connection than
2580  * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
2581  * least-performing one, and then inquire for new ones.
2582  *
2583  * @param cls the `struct CadetTunnel`
2584  */
2585 static void
2586 maintain_connections_cb (void *cls)
2587 {
2588   struct CadetTunnel *t = cls;
2589   struct GNUNET_TIME_Relative delay;
2590   struct EvaluationSummary es;
2591
2592   t->maintain_connections_task = NULL;
2593   LOG (GNUNET_ERROR_TYPE_DEBUG,
2594        "Performing connection maintenance for %s.\n",
2595        GCT_2s (t));
2596
2597   es.min_length = UINT_MAX;
2598   es.max_length = 0;
2599   es.max_desire = 0;
2600   es.min_desire = UINT64_MAX;
2601   es.path = NULL;
2602   es.worst = NULL;
2603   es.duplicate = GNUNET_NO;
2604   GCT_iterate_connections (t,
2605                            &evaluate_connection,
2606                            &es);
2607   if ( (NULL != es.worst) &&
2608        (GCT_count_any_connections (t) > DESIRED_CONNECTIONS_PER_TUNNEL) )
2609   {
2610     /* Clear out worst-performing connection 'es.worst'. */
2611     destroy_t_connection (t,
2612                           es.worst);
2613   }
2614
2615   /* Consider additional paths */
2616   (void) GCP_iterate_paths (t->destination,
2617                             &consider_path_cb,
2618                             t);
2619
2620   /* FIXME: calculate when to try again based on how well we are doing;
2621      in particular, if we have to few connections, we might be able
2622      to do without this (as PATHS should tell us whenever a new path
2623      is available instantly; however, need to make sure this job is
2624      restarted after that happens).
2625      Furthermore, if the paths we do know are in a reasonably narrow
2626      quality band and are plentyful, we might also consider us stabilized
2627      and then reduce the frequency accordingly.  */
2628   delay = GNUNET_TIME_UNIT_MINUTES;
2629   t->maintain_connections_task
2630     = GNUNET_SCHEDULER_add_delayed (delay,
2631                                     &maintain_connections_cb,
2632                                     t);
2633 }
2634
2635
2636 /**
2637  * Consider using the path @a p for the tunnel @a t.
2638  * The tunnel destination is at offset @a off in path @a p.
2639  *
2640  * @param cls our tunnel
2641  * @param path a path to our destination
2642  * @param off offset of the destination on path @a path
2643  */
2644 void
2645 GCT_consider_path (struct CadetTunnel *t,
2646                    struct CadetPeerPath *p,
2647                    unsigned int off)
2648 {
2649   LOG (GNUNET_ERROR_TYPE_DEBUG,
2650        "Considering %s for %s\n",
2651        GCPP_2s (p),
2652        GCT_2s (t));
2653   (void) consider_path_cb (t,
2654                            p,
2655                            off);
2656 }
2657
2658
2659 /**
2660  * We got a keepalive. Track in statistics.
2661  *
2662  * @param cls the `struct CadetTunnel` for which we decrypted the message
2663  * @param msg  the message we received on the tunnel
2664  */
2665 static void
2666 handle_plaintext_keepalive (void *cls,
2667                             const struct GNUNET_MessageHeader *msg)
2668 {
2669   struct CadetTunnel *t = cls;
2670
2671   LOG (GNUNET_ERROR_TYPE_DEBUG,
2672        "Received KEEPALIVE on %s\n",
2673        GCT_2s (t));
2674   GNUNET_STATISTICS_update (stats,
2675                             "# keepalives received",
2676                             1,
2677                             GNUNET_NO);
2678 }
2679
2680
2681 /**
2682  * Check that @a msg is well-formed.
2683  *
2684  * @param cls the `struct CadetTunnel` for which we decrypted the message
2685  * @param msg  the message we received on the tunnel
2686  * @return #GNUNET_OK (any variable-size payload goes)
2687  */
2688 static int
2689 check_plaintext_data (void *cls,
2690                       const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2691 {
2692   return GNUNET_OK;
2693 }
2694
2695
2696 /**
2697  * We received payload data for a channel.  Locate the channel
2698  * and process the data, or return an error if the channel is unknown.
2699  *
2700  * @param cls the `struct CadetTunnel` for which we decrypted the message
2701  * @param msg the message we received on the tunnel
2702  */
2703 static void
2704 handle_plaintext_data (void *cls,
2705                        const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2706 {
2707   struct CadetTunnel *t = cls;
2708   struct CadetChannel *ch;
2709
2710   ch = lookup_channel (t,
2711                        msg->ctn);
2712   if (NULL == ch)
2713   {
2714     /* We don't know about such a channel, might have been destroyed on our
2715        end in the meantime, or never existed. Send back a DESTROY. */
2716     LOG (GNUNET_ERROR_TYPE_DEBUG,
2717          "Received %u bytes of application data for unknown channel %u, sending DESTROY\n",
2718          (unsigned int) (ntohs (msg->header.size) - sizeof (*msg)),
2719          ntohl (msg->ctn.cn));
2720     GCT_send_channel_destroy (t,
2721                               msg->ctn);
2722     return;
2723   }
2724   GCCH_handle_channel_plaintext_data (ch,
2725                                       GCC_get_id (t->current_ct->cc),
2726                                       msg);
2727 }
2728
2729
2730 /**
2731  * We received an acknowledgement for data we sent on a channel.
2732  * Locate the channel and process it, or return an error if the
2733  * channel is unknown.
2734  *
2735  * @param cls the `struct CadetTunnel` for which we decrypted the message
2736  * @param ack the message we received on the tunnel
2737  */
2738 static void
2739 handle_plaintext_data_ack (void *cls,
2740                            const struct GNUNET_CADET_ChannelDataAckMessage *ack)
2741 {
2742   struct CadetTunnel *t = cls;
2743   struct CadetChannel *ch;
2744
2745   ch = lookup_channel (t,
2746                        ack->ctn);
2747   if (NULL == ch)
2748   {
2749     /* We don't know about such a channel, might have been destroyed on our
2750        end in the meantime, or never existed. Send back a DESTROY. */
2751     LOG (GNUNET_ERROR_TYPE_DEBUG,
2752          "Received DATA_ACK for unknown channel %u, sending DESTROY\n",
2753          ntohl (ack->ctn.cn));
2754     GCT_send_channel_destroy (t,
2755                               ack->ctn);
2756     return;
2757   }
2758   GCCH_handle_channel_plaintext_data_ack (ch,
2759                                           GCC_get_id (t->current_ct->cc),
2760                                           ack);
2761 }
2762
2763
2764 /**
2765  * We have received a request to open a channel to a port from
2766  * another peer.  Creates the incoming channel.
2767  *
2768  * @param cls the `struct CadetTunnel` for which we decrypted the message
2769  * @param copen the message we received on the tunnel
2770  */
2771 static void
2772 handle_plaintext_channel_open (void *cls,
2773                                const struct GNUNET_CADET_ChannelOpenMessage *copen)
2774 {
2775   struct CadetTunnel *t = cls;
2776   struct CadetChannel *ch;
2777
2778   ch = GNUNET_CONTAINER_multihashmap32_get (t->channels,
2779                                             ntohl (copen->ctn.cn));
2780   if (NULL != ch)
2781   {
2782     LOG (GNUNET_ERROR_TYPE_DEBUG,
2783          "Received duplicate channel CHANNEL_OPEN on h_port %s from %s (%s), resending ACK\n",
2784          GNUNET_h2s (&copen->h_port),
2785          GCT_2s (t),
2786          GCCH_2s (ch));
2787     GCCH_handle_duplicate_open (ch,
2788                                 GCC_get_id (t->current_ct->cc));
2789     return;
2790   }
2791   LOG (GNUNET_ERROR_TYPE_DEBUG,
2792        "Received CHANNEL_OPEN on h_port %s from %s\n",
2793        GNUNET_h2s (&copen->h_port),
2794        GCT_2s (t));
2795   ch = GCCH_channel_incoming_new (t,
2796                                   copen->ctn,
2797                                   &copen->h_port,
2798                                   ntohl (copen->opt));
2799   if (NULL != t->destroy_task)
2800   {
2801     GNUNET_SCHEDULER_cancel (t->destroy_task);
2802     t->destroy_task = NULL;
2803   }
2804   GNUNET_assert (GNUNET_OK ==
2805                  GNUNET_CONTAINER_multihashmap32_put (t->channels,
2806                                                       ntohl (copen->ctn.cn),
2807                                                       ch,
2808                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2809 }
2810
2811
2812 /**
2813  * Send a DESTROY message via the tunnel.
2814  *
2815  * @param t the tunnel to transmit over
2816  * @param ctn ID of the channel to destroy
2817  */
2818 void
2819 GCT_send_channel_destroy (struct CadetTunnel *t,
2820                           struct GNUNET_CADET_ChannelTunnelNumber ctn)
2821 {
2822   struct GNUNET_CADET_ChannelDestroyMessage msg;
2823
2824   LOG (GNUNET_ERROR_TYPE_DEBUG,
2825        "Sending DESTORY message for channel ID %u\n",
2826        ntohl (ctn.cn));
2827   msg.header.size = htons (sizeof (msg));
2828   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2829   msg.reserved = htonl (0);
2830   msg.ctn = ctn;
2831   GCT_send (t,
2832             &msg.header,
2833             NULL,
2834             NULL);
2835 }
2836
2837
2838 /**
2839  * We have received confirmation from the target peer that the
2840  * given channel could be established (the port is open).
2841  * Tell the client.
2842  *
2843  * @param cls the `struct CadetTunnel` for which we decrypted the message
2844  * @param cm the message we received on the tunnel
2845  */
2846 static void
2847 handle_plaintext_channel_open_ack (void *cls,
2848                                    const struct GNUNET_CADET_ChannelOpenAckMessage *cm)
2849 {
2850   struct CadetTunnel *t = cls;
2851   struct CadetChannel *ch;
2852
2853   ch = lookup_channel (t,
2854                        cm->ctn);
2855   if (NULL == ch)
2856   {
2857     /* We don't know about such a channel, might have been destroyed on our
2858        end in the meantime, or never existed. Send back a DESTROY. */
2859     LOG (GNUNET_ERROR_TYPE_DEBUG,
2860          "Received channel OPEN_ACK for unknown channel %u, sending DESTROY\n",
2861          ntohl (cm->ctn.cn));
2862     GCT_send_channel_destroy (t,
2863                               cm->ctn);
2864     return;
2865   }
2866   LOG (GNUNET_ERROR_TYPE_DEBUG,
2867        "Received channel OPEN_ACK on channel %s from %s\n",
2868        GCCH_2s (ch),
2869        GCT_2s (t));
2870   GCCH_handle_channel_open_ack (ch,
2871                                 GCC_get_id (t->current_ct->cc),
2872                                 &cm->port);
2873 }
2874
2875
2876 /**
2877  * We received a message saying that a channel should be destroyed.
2878  * Pass it on to the correct channel.
2879  *
2880  * @param cls the `struct CadetTunnel` for which we decrypted the message
2881  * @param cm the message we received on the tunnel
2882  */
2883 static void
2884 handle_plaintext_channel_destroy (void *cls,
2885                                   const struct GNUNET_CADET_ChannelDestroyMessage *cm)
2886 {
2887   struct CadetTunnel *t = cls;
2888   struct CadetChannel *ch;
2889
2890   ch = lookup_channel (t,
2891                        cm->ctn);
2892   if (NULL == ch)
2893   {
2894     /* We don't know about such a channel, might have been destroyed on our
2895        end in the meantime, or never existed. */
2896     LOG (GNUNET_ERROR_TYPE_DEBUG,
2897          "Received channel DESTORY for unknown channel %u. Ignoring.\n",
2898          ntohl (cm->ctn.cn));
2899     return;
2900   }
2901   LOG (GNUNET_ERROR_TYPE_DEBUG,
2902        "Received channel DESTROY on %s from %s\n",
2903        GCCH_2s (ch),
2904        GCT_2s (t));
2905   GCCH_handle_remote_destroy (ch,
2906                               GCC_get_id (t->current_ct->cc));
2907 }
2908
2909
2910 /**
2911  * Handles a message we decrypted, by injecting it into
2912  * our message queue (which will do the dispatching).
2913  *
2914  * @param cls the `struct CadetTunnel` that got the message
2915  * @param msg the message
2916  * @return #GNUNET_OK on success (always)
2917  *    #GNUNET_NO to stop further processing (no error)
2918  *    #GNUNET_SYSERR to stop further processing with error
2919  */
2920 static int
2921 handle_decrypted (void *cls,
2922                   const struct GNUNET_MessageHeader *msg)
2923 {
2924   struct CadetTunnel *t = cls;
2925
2926   GNUNET_assert (NULL != t->current_ct);
2927   GNUNET_MQ_inject_message (t->mq,
2928                             msg);
2929   return GNUNET_OK;
2930 }
2931
2932
2933 /**
2934  * Function called if we had an error processing
2935  * an incoming decrypted message.
2936  *
2937  * @param cls the `struct CadetTunnel`
2938  * @param error error code
2939  */
2940 static void
2941 decrypted_error_cb (void *cls,
2942                     enum GNUNET_MQ_Error error)
2943 {
2944   GNUNET_break_op (0);
2945 }
2946
2947
2948 /**
2949  * Create a tunnel to @a destionation.  Must only be called
2950  * from within #GCP_get_tunnel().
2951  *
2952  * @param destination where to create the tunnel to
2953  * @return new tunnel to @a destination
2954  */
2955 struct CadetTunnel *
2956 GCT_create_tunnel (struct CadetPeer *destination)
2957 {
2958   struct CadetTunnel *t = GNUNET_new (struct CadetTunnel);
2959   struct GNUNET_MQ_MessageHandler handlers[] = {
2960     GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
2961                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
2962                              struct GNUNET_MessageHeader,
2963                              t),
2964     GNUNET_MQ_hd_var_size (plaintext_data,
2965                            GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
2966                            struct GNUNET_CADET_ChannelAppDataMessage,
2967                            t),
2968     GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
2969                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
2970                              struct GNUNET_CADET_ChannelDataAckMessage,
2971                              t),
2972     GNUNET_MQ_hd_fixed_size (plaintext_channel_open,
2973                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
2974                              struct GNUNET_CADET_ChannelOpenMessage,
2975                              t),
2976     GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack,
2977                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
2978                              struct GNUNET_CADET_ChannelOpenAckMessage,
2979                              t),
2980     GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
2981                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
2982                              struct GNUNET_CADET_ChannelDestroyMessage,
2983                              t),
2984     GNUNET_MQ_handler_end ()
2985   };
2986
2987   t->kx_retry_delay = INITIAL_KX_RETRY_DELAY;
2988   new_ephemeral (&t->ax);
2989   GNUNET_assert (GNUNET_OK ==
2990                  GNUNET_CRYPTO_ecdhe_key_create2 (&t->ax.kx_0));
2991   t->destination = destination;
2992   t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
2993   t->maintain_connections_task
2994     = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
2995                                 t);
2996   t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
2997                                          NULL,
2998                                          NULL,
2999                                          NULL,
3000                                          handlers,
3001                                          &decrypted_error_cb,
3002                                          t);
3003   t->mst = GNUNET_MST_create (&handle_decrypted,
3004                               t);
3005   return t;
3006 }
3007
3008
3009 /**
3010  * Add a @a connection to the @a tunnel.
3011  *
3012  * @param t a tunnel
3013  * @param cid connection identifer to use for the connection
3014  * @param options options for the connection
3015  * @param path path to use for the connection
3016  * @return #GNUNET_OK on success,
3017  *         #GNUNET_SYSERR on failure (duplicate connection)
3018  */
3019 int
3020 GCT_add_inbound_connection (struct CadetTunnel *t,
3021                             const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
3022                             enum GNUNET_CADET_ChannelOption options,
3023                             struct CadetPeerPath *path)
3024 {
3025   struct CadetTConnection *ct;
3026
3027   ct = GNUNET_new (struct CadetTConnection);
3028   ct->created = GNUNET_TIME_absolute_get ();
3029   ct->t = t;
3030   ct->cc = GCC_create_inbound (t->destination,
3031                                path,
3032                                options,
3033                                ct,
3034                                cid,
3035                                &connection_ready_cb,
3036                                ct);
3037   if (NULL == ct->cc)
3038   {
3039     LOG (GNUNET_ERROR_TYPE_DEBUG,
3040          "%s refused inbound %s (duplicate)\n",
3041          GCT_2s (t),
3042          GCC_2s (ct->cc));
3043     GNUNET_free (ct);
3044     return GNUNET_SYSERR;
3045   }
3046   /* FIXME: schedule job to kill connection (and path?)  if it takes
3047      too long to get ready! (And track performance data on how long
3048      other connections took with the tunnel!)
3049      => Note: to be done within 'connection'-logic! */
3050   GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
3051                                t->connection_busy_tail,
3052                                ct);
3053   t->num_busy_connections++;
3054   LOG (GNUNET_ERROR_TYPE_DEBUG,
3055        "%s has new %s\n",
3056        GCT_2s (t),
3057        GCC_2s (ct->cc));
3058   return GNUNET_OK;
3059 }
3060
3061
3062 /**
3063  * Handle encrypted message.
3064  *
3065  * @param ct connection/tunnel combo that received encrypted message
3066  * @param msg the encrypted message to decrypt
3067  */
3068 void
3069 GCT_handle_encrypted (struct CadetTConnection *ct,
3070                       const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
3071 {
3072   struct CadetTunnel *t = ct->t;
3073   uint16_t size = ntohs (msg->header.size);
3074   char cbuf [size] GNUNET_ALIGN;
3075   ssize_t decrypted_size;
3076
3077   LOG (GNUNET_ERROR_TYPE_DEBUG,
3078        "%s received %u bytes of encrypted data in state %d\n",
3079        GCT_2s (t),
3080        (unsigned int) size,
3081        t->estate);
3082
3083   switch (t->estate)
3084   {
3085   case CADET_TUNNEL_KEY_UNINITIALIZED:
3086   case CADET_TUNNEL_KEY_AX_RECV:
3087     /* We did not even SEND our KX, how can the other peer
3088        send us encrypted data? Must have been that we went
3089        down and the other peer still things we are up.
3090        Let's send it KX back. */
3091     GNUNET_STATISTICS_update (stats,
3092                               "# received encrypted without any KX",
3093                               1,
3094                               GNUNET_NO);
3095     if (NULL != t->kx_task)
3096     {
3097       GNUNET_SCHEDULER_cancel (t->kx_task);
3098       t->kx_task = NULL;
3099     }
3100     send_kx (t,
3101              ct,
3102              &t->ax);
3103     return;
3104   case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
3105     /* We send KX, and other peer send KX to us at the same time.
3106        Neither KX is AUTH'ed, so let's try KX_AUTH this time. */
3107     GNUNET_STATISTICS_update (stats,
3108                               "# received encrypted without KX_AUTH",
3109                               1,
3110                               GNUNET_NO);
3111     if (NULL != t->kx_task)
3112     {
3113       GNUNET_SCHEDULER_cancel (t->kx_task);
3114       t->kx_task = NULL;
3115     }
3116     send_kx_auth (t,
3117                   ct,
3118                   &t->ax,
3119                   GNUNET_YES);
3120     return;
3121   case CADET_TUNNEL_KEY_AX_SENT:
3122     /* We did not get the KX of the other peer, but that
3123        might have been lost.  Send our KX again immediately. */
3124     GNUNET_STATISTICS_update (stats,
3125                               "# received encrypted without KX",
3126                               1,
3127                               GNUNET_NO);
3128     if (NULL != t->kx_task)
3129     {
3130       GNUNET_SCHEDULER_cancel (t->kx_task);
3131       t->kx_task = NULL;
3132     }
3133     send_kx (t,
3134              ct,
3135              &t->ax);
3136     return;
3137   case CADET_TUNNEL_KEY_AX_AUTH_SENT:
3138     /* Great, first payload, we might graduate to OK! */
3139   case CADET_TUNNEL_KEY_OK:
3140     /* We are up and running, all good. */
3141     break;
3142   }
3143
3144   decrypted_size = -1;
3145   if (CADET_TUNNEL_KEY_OK == t->estate)
3146   {
3147     /* We have well-established key material available,
3148        try that. (This is the common case.) */
3149     decrypted_size = t_ax_decrypt_and_validate (&t->ax,
3150                                                 cbuf,
3151                                                 msg,
3152                                                 size);
3153   }
3154
3155   if ( (-1 == decrypted_size) &&
3156        (NULL != t->unverified_ax) )
3157   {
3158     /* We have un-authenticated KX material available. We should try
3159        this as a back-up option, in case the sender crashed and
3160        switched keys. */
3161     decrypted_size = t_ax_decrypt_and_validate (t->unverified_ax,
3162                                                 cbuf,
3163                                                 msg,
3164                                                 size);
3165     if (-1 != decrypted_size)
3166     {
3167       /* It worked! Treat this as authentication of the AX data! */
3168       cleanup_ax (&t->ax);
3169       t->ax = *t->unverified_ax;
3170       GNUNET_free (t->unverified_ax);
3171       t->unverified_ax = NULL;
3172     }
3173     if (CADET_TUNNEL_KEY_AX_AUTH_SENT == t->estate)
3174     {
3175       /* First time it worked, move tunnel into production! */
3176       GCT_change_estate (t,
3177                          CADET_TUNNEL_KEY_OK);
3178       if (NULL != t->send_task)
3179         GNUNET_SCHEDULER_cancel (t->send_task);
3180       t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
3181                                                t);
3182     }
3183   }
3184   if (NULL != t->unverified_ax)
3185   {
3186     /* We had unverified KX material that was useless; so increment
3187        counter and eventually move to ignore it.  Note that we even do
3188        this increment if we successfully decrypted with the old KX
3189        material and thus didn't even both with the new one.  This is
3190        the ideal case, as a malicious injection of bogus KX data
3191        basically only causes us to increment a counter a few times. */
3192     t->unverified_attempts++;
3193     LOG (GNUNET_ERROR_TYPE_DEBUG,
3194          "Failed to decrypt message with unverified KX data %u times\n",
3195          t->unverified_attempts);
3196     if (t->unverified_attempts > MAX_UNVERIFIED_ATTEMPTS)
3197     {
3198       cleanup_ax (t->unverified_ax);
3199       GNUNET_free (t->unverified_ax);
3200       t->unverified_ax = NULL;
3201     }
3202   }
3203
3204   if (-1 == decrypted_size)
3205   {
3206     /* Decryption failed for good, complain. */
3207     LOG (GNUNET_ERROR_TYPE_WARNING,
3208          "%s failed to decrypt and validate encrypted data, retrying KX\n",
3209          GCT_2s (t));
3210     GNUNET_STATISTICS_update (stats,
3211                               "# unable to decrypt",
3212                               1,
3213                               GNUNET_NO);
3214     if (NULL != t->kx_task)
3215     {
3216       GNUNET_SCHEDULER_cancel (t->kx_task);
3217       t->kx_task = NULL;
3218     }
3219     send_kx (t,
3220              ct,
3221              &t->ax);
3222     return;
3223   }
3224   GNUNET_STATISTICS_update (stats,
3225                             "# decrypted bytes",
3226                             decrypted_size,
3227                             GNUNET_NO);
3228
3229   /* The MST will ultimately call #handle_decrypted() on each message. */
3230   t->current_ct = ct;
3231   GNUNET_break_op (GNUNET_OK ==
3232                    GNUNET_MST_from_buffer (t->mst,
3233                                            cbuf,
3234                                            decrypted_size,
3235                                            GNUNET_YES,
3236                                            GNUNET_NO));
3237   t->current_ct = NULL;
3238 }
3239
3240
3241 /**
3242  * Sends an already built message on a tunnel, encrypting it and
3243  * choosing the best connection if not provided.
3244  *
3245  * @param message Message to send. Function modifies it.
3246  * @param t Tunnel on which this message is transmitted.
3247  * @param cont Continuation to call once message is really sent.
3248  * @param cont_cls Closure for @c cont.
3249  * @return Handle to cancel message
3250  */
3251 struct CadetTunnelQueueEntry *
3252 GCT_send (struct CadetTunnel *t,
3253           const struct GNUNET_MessageHeader *message,
3254           GCT_SendContinuation cont,
3255           void *cont_cls)
3256 {
3257   struct CadetTunnelQueueEntry *tq;
3258   uint16_t payload_size;
3259   struct GNUNET_MQ_Envelope *env;
3260   struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
3261
3262   if (CADET_TUNNEL_KEY_OK != t->estate)
3263   {
3264     GNUNET_break (0);
3265     return NULL;
3266   }
3267   payload_size = ntohs (message->size);
3268   LOG (GNUNET_ERROR_TYPE_DEBUG,
3269        "Encrypting %u bytes for %s\n",
3270        (unsigned int) payload_size,
3271        GCT_2s (t));
3272   env = GNUNET_MQ_msg_extra (ax_msg,
3273                              payload_size,
3274                              GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
3275   t_ax_encrypt (&t->ax,
3276                 &ax_msg[1],
3277                 message,
3278                 payload_size);
3279   GNUNET_STATISTICS_update (stats,
3280                             "# encrypted bytes",
3281                             payload_size,
3282                             GNUNET_NO);
3283   ax_msg->ax_header.Ns = htonl (t->ax.Ns++);
3284   ax_msg->ax_header.PNs = htonl (t->ax.PNs);
3285   /* FIXME: we should do this once, not once per message;
3286      this is a point multiplication, and DHRs does not
3287      change all the time. */
3288   GNUNET_CRYPTO_ecdhe_key_get_public (&t->ax.DHRs,
3289                                       &ax_msg->ax_header.DHRs);
3290   t_h_encrypt (&t->ax,
3291                ax_msg);
3292   t_hmac (&ax_msg->ax_header,
3293           sizeof (struct GNUNET_CADET_AxHeader) + payload_size,
3294           0,
3295           &t->ax.HKs,
3296           &ax_msg->hmac);
3297
3298   tq = GNUNET_malloc (sizeof (*tq));
3299   tq->t = t;
3300   tq->env = env;
3301   tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
3302   tq->cont = cont;
3303   tq->cont_cls = cont_cls;
3304   GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
3305                                     t->tq_tail,
3306                                     tq);
3307   if (NULL != t->send_task)
3308     GNUNET_SCHEDULER_cancel (t->send_task);
3309   t->send_task
3310     = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
3311                                 t);
3312   return tq;
3313 }
3314
3315
3316 /**
3317  * Cancel a previously sent message while it's in the queue.
3318  *
3319  * ONLY can be called before the continuation given to the send
3320  * function is called. Once the continuation is called, the message is
3321  * no longer in the queue!
3322  *
3323  * @param tq Handle to the queue entry to cancel.
3324  */
3325 void
3326 GCT_send_cancel (struct CadetTunnelQueueEntry *tq)
3327 {
3328   struct CadetTunnel *t = tq->t;
3329
3330   GNUNET_CONTAINER_DLL_remove (t->tq_head,
3331                                t->tq_tail,
3332                                tq);
3333   GNUNET_MQ_discard (tq->env);
3334   GNUNET_free (tq);
3335 }
3336
3337
3338 /**
3339  * Iterate over all connections of a tunnel.
3340  *
3341  * @param t Tunnel whose connections to iterate.
3342  * @param iter Iterator.
3343  * @param iter_cls Closure for @c iter.
3344  */
3345 void
3346 GCT_iterate_connections (struct CadetTunnel *t,
3347                          GCT_ConnectionIterator iter,
3348                          void *iter_cls)
3349 {
3350   struct CadetTConnection *n;
3351   for (struct CadetTConnection *ct = t->connection_ready_head;
3352        NULL != ct;
3353        ct = n)
3354   {
3355     n = ct->next;
3356     iter (iter_cls,
3357           ct);
3358   }
3359   for (struct CadetTConnection *ct = t->connection_busy_head;
3360        NULL != ct;
3361        ct = n)
3362   {
3363     n = ct->next;
3364     iter (iter_cls,
3365           ct);
3366   }
3367 }
3368
3369
3370 /**
3371  * Closure for #iterate_channels_cb.
3372  */
3373 struct ChanIterCls
3374 {
3375   /**
3376    * Function to call.
3377    */
3378   GCT_ChannelIterator iter;
3379
3380   /**
3381    * Closure for @e iter.
3382    */
3383   void *iter_cls;
3384 };
3385
3386
3387 /**
3388  * Helper function for #GCT_iterate_channels.
3389  *
3390  * @param cls the `struct ChanIterCls`
3391  * @param key unused
3392  * @param value a `struct CadetChannel`
3393  * @return #GNUNET_OK
3394  */
3395 static int
3396 iterate_channels_cb (void *cls,
3397                      uint32_t key,
3398                      void *value)
3399 {
3400   struct ChanIterCls *ctx = cls;
3401   struct CadetChannel *ch = value;
3402
3403   ctx->iter (ctx->iter_cls,
3404              ch);
3405   return GNUNET_OK;
3406 }
3407
3408
3409 /**
3410  * Iterate over all channels of a tunnel.
3411  *
3412  * @param t Tunnel whose channels to iterate.
3413  * @param iter Iterator.
3414  * @param iter_cls Closure for @c iter.
3415  */
3416 void
3417 GCT_iterate_channels (struct CadetTunnel *t,
3418                       GCT_ChannelIterator iter,
3419                       void *iter_cls)
3420 {
3421   struct ChanIterCls ctx;
3422
3423   ctx.iter = iter;
3424   ctx.iter_cls = iter_cls;
3425   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
3426                                            &iterate_channels_cb,
3427                                            &ctx);
3428
3429 }
3430
3431
3432 /**
3433  * Call #GCCH_debug() on a channel.
3434  *
3435  * @param cls points to the log level to use
3436  * @param key unused
3437  * @param value the `struct CadetChannel` to dump
3438  * @return #GNUNET_OK (continue iteration)
3439  */
3440 static int
3441 debug_channel (void *cls,
3442                uint32_t key,
3443                void *value)
3444 {
3445   const enum GNUNET_ErrorType *level = cls;
3446   struct CadetChannel *ch = value;
3447
3448   GCCH_debug (ch, *level);
3449   return GNUNET_OK;
3450 }
3451
3452
3453 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
3454
3455
3456 /**
3457  * Log all possible info about the tunnel state.
3458  *
3459  * @param t Tunnel to debug.
3460  * @param level Debug level to use.
3461  */
3462 void
3463 GCT_debug (const struct CadetTunnel *t,
3464            enum GNUNET_ErrorType level)
3465 {
3466 #if !defined(GNUNET_CULL_LOGGING)
3467   struct CadetTConnection *iter_c;
3468   int do_log;
3469
3470   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
3471                                        "cadet-tun",
3472                                        __FILE__, __FUNCTION__, __LINE__);
3473   if (0 == do_log)
3474     return;
3475
3476   LOG2 (level,
3477         "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
3478         GCT_2s (t),
3479         estate2s (t->estate),
3480         t->tq_len,
3481         GCT_count_any_connections (t));
3482   LOG2 (level,
3483         "TTT channels:\n");
3484   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
3485                                            &debug_channel,
3486                                            &level);
3487   LOG2 (level,
3488         "TTT connections:\n");
3489   for (iter_c = t->connection_ready_head; NULL != iter_c; iter_c = iter_c->next)
3490     GCC_debug (iter_c->cc,
3491                level);
3492   for (iter_c = t->connection_busy_head; NULL != iter_c; iter_c = iter_c->next)
3493     GCC_debug (iter_c->cc,
3494                level);
3495
3496   LOG2 (level,
3497         "TTT TUNNEL END\n");
3498 #endif
3499 }
3500
3501
3502 /* end of gnunet-service-cadet_tunnels.c */