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