KEY_REKEY state was dead in old code, remove in new code; refactor KX logic in prepar...
[oweals/gnunet.git] / src / cadet / gnunet-service-cadet-new_tunnels.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2013, 2017 GNUnet e.V.
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20 /**
21  * @file cadet/gnunet-service-cadet-new_tunnels.c
22  * @brief Information we track per tunnel.
23  * @author Bartlomiej Polot
24  * @author Christian Grothoff
25  *
26  * FIXME:
27  * - KX:
28  *   + clean up KX logic, including adding sender authentication
29  *   + implement rekeying
30  *   + check KX estate machine -- make sure it is never stuck!
31  * - connection management
32  *   + properly (evaluate, kill old ones, search for new ones)
33  *   + when managing connections, distinguish those that
34  *     have (recently) had traffic from those that were
35  *     never ready (or not recently)
36  */
37 #include "platform.h"
38 #include "gnunet_util_lib.h"
39 #include "gnunet_statistics_service.h"
40 #include "gnunet_signatures.h"
41 #include "gnunet-service-cadet-new.h"
42 #include "cadet_protocol.h"
43 #include "gnunet-service-cadet-new_channel.h"
44 #include "gnunet-service-cadet-new_connection.h"
45 #include "gnunet-service-cadet-new_tunnels.h"
46 #include "gnunet-service-cadet-new_peer.h"
47 #include "gnunet-service-cadet-new_paths.h"
48
49
50 #define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__)
51
52 /**
53  * How often do we try to decrypt payload with unverified key
54  * material?  Used to limit CPU increase upon receiving bogus
55  * KX.
56  */
57 #define MAX_UNVERIFIED_ATTEMPTS 16
58
59 /**
60  * How long do we wait until tearing down an idle tunnel?
61  */
62 #define IDLE_DESTROY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90)
63
64 /**
65  * Maximum number of skipped keys we keep in memory per tunnel.
66  */
67 #define MAX_SKIPPED_KEYS 64
68
69 /**
70  * Maximum number of keys (and thus ratchet steps) we are willing to
71  * skip before we decide this is either a bogus packet or a DoS-attempt.
72  */
73 #define MAX_KEY_GAP 256
74
75
76 /**
77  * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
78  */
79 struct CadetTunnelSkippedKey
80 {
81   /**
82    * DLL next.
83    */
84   struct CadetTunnelSkippedKey *next;
85
86   /**
87    * DLL prev.
88    */
89   struct CadetTunnelSkippedKey *prev;
90
91   /**
92    * When was this key stored (for timeout).
93    */
94   struct GNUNET_TIME_Absolute timestamp;
95
96   /**
97    * Header key.
98    */
99   struct GNUNET_CRYPTO_SymmetricSessionKey HK;
100
101   /**
102    * Message key.
103    */
104   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
105
106   /**
107    * Key number for a given HK.
108    */
109   unsigned int Kn;
110 };
111
112
113 /**
114  * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
115  */
116 struct CadetTunnelAxolotl
117 {
118   /**
119    * A (double linked) list of stored message keys and associated header keys
120    * for "skipped" messages, i.e. messages that have not been
121    * received despite the reception of more recent messages, (head).
122    */
123   struct CadetTunnelSkippedKey *skipped_head;
124
125   /**
126    * Skipped messages' keys DLL, tail.
127    */
128   struct CadetTunnelSkippedKey *skipped_tail;
129
130   /**
131    * 32-byte root key which gets updated by DH ratchet.
132    */
133   struct GNUNET_CRYPTO_SymmetricSessionKey RK;
134
135   /**
136    * 32-byte header key (currently used for sending).
137    */
138   struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
139
140   /**
141    * 32-byte header key (currently used for receiving)
142    */
143   struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
144
145   /**
146    * 32-byte next header key (for sending), used once the
147    * ratchet advances.  We are sure that the sender has this
148    * key as well only after @e ratchet_allowed is #GNUNET_YES.
149    */
150   struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
151
152   /**
153    * 32-byte next header key (for receiving).  To be tried
154    * when decrypting with @e HKr fails and thus the sender
155    * may have advanced the ratchet.
156    */
157   struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
158
159   /**
160    * 32-byte chain keys (used for forward-secrecy) for
161    * sending messages. Updated for every message.
162    */
163   struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
164
165   /**
166    * 32-byte chain keys (used for forward-secrecy) for
167    * receiving messages. Updated for every message. If
168    * messages are skipped, the respective derived MKs
169    * (and the current @HKr) are kept in the @e skipped_head DLL.
170    */
171   struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
172
173   /**
174    * ECDH for key exchange (A0 / B0).
175    */
176   struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
177
178   /**
179    * ECDH Ratchet key (our private key in the current DH).
180    */
181   struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
182
183   /**
184    * ECDH Ratchet key (other peer's public key in the current DH).
185    */
186   struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
187
188   /**
189    * Time when the current ratchet expires and a new one is triggered
190    * (if @e ratchet_allowed is #GNUNET_YES).
191    */
192   struct GNUNET_TIME_Absolute ratchet_expiration;
193
194   /**
195    * Number of elements in @a skipped_head <-> @a skipped_tail.
196    */
197   unsigned int skipped;
198
199   /**
200    * Message number (reset to 0 with each new ratchet, next message to send).
201    */
202   uint32_t Ns;
203
204   /**
205    * Message number (reset to 0 with each new ratchet, next message to recv).
206    */
207   uint32_t Nr;
208
209   /**
210    * Previous message numbers (# of msgs sent under prev ratchet)
211    */
212   uint32_t PNs;
213
214   /**
215    * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
216    */
217   int ratchet_flag;
218
219   /**
220    * True (#GNUNET_YES) if we have received a message from the
221    * other peer that uses the keys from our last ratchet step.
222    * This implies that we are again allowed to advance the ratchet,
223    * otherwise we have to wait until the other peer sees our current
224    * ephemeral key and advances first.
225    *
226    * #GNUNET_NO if we have advanced the ratched but lack any evidence
227    * that the other peer has noticed this.
228    */
229   int ratchet_allowed;
230
231   /**
232    * Number of messages recieved since our last ratchet advance.
233    *
234    * If this counter = 0, we cannot send a new ratchet key in the next
235    * message.
236    *
237    * If this counter > 0, we could (but don't have to) send a new key.
238    *
239    * Once the @e ratchet_counter is larger than
240    * #ratchet_messages (or @e ratchet_expiration time has past), and
241    * @e ratchet_allowed is #GNUNET_YES, we advance the ratchet.
242    */
243   unsigned int ratchet_counter;
244
245 };
246
247
248 /**
249  * Struct used to save messages in a non-ready tunnel to send once connected.
250  */
251 struct CadetTunnelQueueEntry
252 {
253   /**
254    * We are entries in a DLL
255    */
256   struct CadetTunnelQueueEntry *next;
257
258   /**
259    * We are entries in a DLL
260    */
261   struct CadetTunnelQueueEntry *prev;
262
263   /**
264    * Tunnel these messages belong in.
265    */
266   struct CadetTunnel *t;
267
268   /**
269    * Continuation to call once sent (on the channel layer).
270    */
271   GNUNET_SCHEDULER_TaskCallback cont;
272
273   /**
274    * Closure for @c cont.
275    */
276   void *cont_cls;
277
278   /**
279    * Envelope of message to send follows.
280    */
281   struct GNUNET_MQ_Envelope *env;
282
283   /**
284    * Where to put the connection identifier into the payload
285    * of the message in @e env once we have it?
286    */
287   struct GNUNET_CADET_ConnectionTunnelIdentifier *cid;
288 };
289
290
291 /**
292  * Struct containing all information regarding a tunnel to a peer.
293  */
294 struct CadetTunnel
295 {
296   /**
297    * Destination of the tunnel.
298    */
299   struct CadetPeer *destination;
300
301   /**
302    * Peer's ephemeral key, to recreate @c e_key and @c d_key when own
303    * ephemeral key changes.
304    */
305   struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
306
307   /**
308    * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
309    */
310   struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
311
312   /**
313    * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
314    */
315   struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
316
317   /**
318    * Axolotl info.
319    */
320   struct CadetTunnelAxolotl ax;
321
322   /**
323    * Unverified Axolotl info, used only if we got a fresh KX (not a
324    * KX_AUTH) while our end of the tunnel was still up.  In this case,
325    * we keep the fresh KX around but do not put it into action until
326    * we got encrypted payload that assures us of the authenticity of
327    * the KX.
328    */
329   struct CadetTunnelAxolotl *unverified_ax;
330
331   /**
332    * Task scheduled if there are no more channels using the tunnel.
333    */
334   struct GNUNET_SCHEDULER_Task *destroy_task;
335
336   /**
337    * Task to trim connections if too many are present.
338    */
339   struct GNUNET_SCHEDULER_Task *maintain_connections_task;
340
341   /**
342    * Task to send messages from queue (if possible).
343    */
344   struct GNUNET_SCHEDULER_Task *send_task;
345
346   /**
347    * Task to trigger KX.
348    */
349   struct GNUNET_SCHEDULER_Task *kx_task;
350
351   /**
352    * Tokenizer for decrypted messages.
353    */
354   struct GNUNET_MessageStreamTokenizer *mst;
355
356   /**
357    * Dispatcher for decrypted messages only (do NOT use for sending!).
358    */
359   struct GNUNET_MQ_Handle *mq;
360
361   /**
362    * DLL of connections that are actively used to reach the destination peer.
363    */
364   struct CadetTConnection *connection_head;
365
366   /**
367    * DLL of connections that are actively used to reach the destination peer.
368    */
369   struct CadetTConnection *connection_tail;
370
371   /**
372    * Channels inside this tunnel. Maps
373    * `struct GNUNET_CADET_ChannelTunnelNumber` to a `struct CadetChannel`.
374    */
375   struct GNUNET_CONTAINER_MultiHashMap32 *channels;
376
377   /**
378    * Channel ID for the next created channel in this tunnel.
379    */
380   struct GNUNET_CADET_ChannelTunnelNumber next_ctn;
381
382   /**
383    * Queued messages, to transmit once tunnel gets connected.
384    */
385   struct CadetTunnelQueueEntry *tq_head;
386
387   /**
388    * Queued messages, to transmit once tunnel gets connected.
389    */
390   struct CadetTunnelQueueEntry *tq_tail;
391
392   /**
393    * How long do we wait until we retry the KX?
394    */
395   struct GNUNET_TIME_Relative kx_retry_delay;
396
397   /**
398    * When do we try the next KX?
399    */
400   struct GNUNET_TIME_Absolute next_kx_attempt;
401
402   /**
403    * Number of connections in the @e connection_head DLL.
404    */
405   unsigned int num_connections;
406
407   /**
408    * How often have we tried and failed to decrypt a message using
409    * the unverified KX material from @e unverified_ax?  Used to
410    * stop trying after #MAX_UNVERIFIED_ATTEMPTS.
411    */
412   unsigned int unverified_attempts;
413
414   /**
415    * Number of entries in the @e tq_head DLL.
416    */
417   unsigned int tq_len;
418
419   /**
420    * State of the tunnel encryption.
421    */
422   enum CadetTunnelEState estate;
423
424 };
425
426
427 /**
428  * Get the static string for the peer this tunnel is directed.
429  *
430  * @param t Tunnel.
431  *
432  * @return Static string the destination peer's ID.
433  */
434 const char *
435 GCT_2s (const struct CadetTunnel *t)
436 {
437   static char buf[64];
438
439   if (NULL == t)
440     return "Tunnel(NULL)";
441   GNUNET_snprintf (buf,
442                    sizeof (buf),
443                    "Tunnel %s",
444                    GNUNET_i2s (GCP_get_id (t->destination)));
445   return buf;
446 }
447
448
449 /**
450  * Get string description for tunnel encryption state.
451  *
452  * @param es Tunnel state.
453  *
454  * @return String representation.
455  */
456 static const char *
457 estate2s (enum CadetTunnelEState es)
458 {
459   static char buf[32];
460
461   switch (es)
462   {
463     case CADET_TUNNEL_KEY_UNINITIALIZED:
464       return "CADET_TUNNEL_KEY_UNINITIALIZED";
465     case CADET_TUNNEL_KEY_SENT:
466       return "CADET_TUNNEL_KEY_SENT";
467     case CADET_TUNNEL_KEY_PING:
468       return "CADET_TUNNEL_KEY_PING";
469     case CADET_TUNNEL_KEY_OK:
470       return "CADET_TUNNEL_KEY_OK";
471     default:
472       SPRINTF (buf, "%u (UNKNOWN STATE)", es);
473       return buf;
474   }
475 }
476
477
478 /**
479  * Return the peer to which this tunnel goes.
480  *
481  * @param t a tunnel
482  * @return the destination of the tunnel
483  */
484 struct CadetPeer *
485 GCT_get_destination (struct CadetTunnel *t)
486 {
487   return t->destination;
488 }
489
490
491 /**
492  * Count channels of a tunnel.
493  *
494  * @param t Tunnel on which to count.
495  *
496  * @return Number of channels.
497  */
498 unsigned int
499 GCT_count_channels (struct CadetTunnel *t)
500 {
501   return GNUNET_CONTAINER_multihashmap32_size (t->channels);
502 }
503
504
505 /**
506  * Lookup a channel by its @a ctn.
507  *
508  * @param t tunnel to look in
509  * @param ctn number of channel to find
510  * @return NULL if channel does not exist
511  */
512 struct CadetChannel *
513 lookup_channel (struct CadetTunnel *t,
514                 struct GNUNET_CADET_ChannelTunnelNumber ctn)
515 {
516   return GNUNET_CONTAINER_multihashmap32_get (t->channels,
517                                               ntohl (ctn.cn));
518 }
519
520
521 /**
522  * Count all created connections of a tunnel. Not necessarily ready connections!
523  *
524  * @param t Tunnel on which to count.
525  *
526  * @return Number of connections created, either being established or ready.
527  */
528 unsigned int
529 GCT_count_any_connections (struct CadetTunnel *t)
530 {
531   return t->num_connections;
532 }
533
534
535 /**
536  * Find first connection that is ready in the list of
537  * our connections.  Picks ready connections round-robin.
538  *
539  * @param t tunnel to search
540  * @return NULL if we have no connection that is ready
541  */
542 static struct CadetTConnection *
543 get_ready_connection (struct CadetTunnel *t)
544 {
545   for (struct CadetTConnection *pos = t->connection_head;
546        NULL != pos;
547        pos = pos->next)
548     if (GNUNET_YES == pos->is_ready)
549     {
550       if (pos != t->connection_tail)
551       {
552         /* move 'pos' to the end, so we try other ready connections
553            first next time (round-robin, modulo availability) */
554         GNUNET_CONTAINER_DLL_remove (t->connection_head,
555                                      t->connection_tail,
556                                      pos);
557         GNUNET_CONTAINER_DLL_insert_tail (t->connection_head,
558                                           t->connection_tail,
559                                           pos);
560       }
561       return pos;
562     }
563   return NULL;
564 }
565
566
567 /**
568  * Get the encryption state of a tunnel.
569  *
570  * @param t Tunnel.
571  *
572  * @return Tunnel's encryption state.
573  */
574 enum CadetTunnelEState
575 GCT_get_estate (struct CadetTunnel *t)
576 {
577   return t->estate;
578 }
579
580
581 /**
582  * Called when either we have a new connection, or a new message in the
583  * queue, or some existing connection has transmission capacity.  Looks
584  * at our message queue and if there is a message, picks a connection
585  * to send it on.
586  *
587  * @param cls the `struct CadetTunnel` to process messages on
588  */
589 static void
590 trigger_transmissions (void *cls);
591
592
593 /* ************************************** start core crypto ***************************** */
594
595
596 /**
597  * Create a new Axolotl ephemeral (ratchet) key.
598  *
599  * @param ax key material to update
600  */
601 static void
602 new_ephemeral (struct CadetTunnelAxolotl *ax)
603 {
604   GNUNET_free_non_null (ax->DHRs);
605   ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
606 }
607
608
609 /**
610  * Calculate HMAC.
611  *
612  * @param plaintext Content to HMAC.
613  * @param size Size of @c plaintext.
614  * @param iv Initialization vector for the message.
615  * @param key Key to use.
616  * @param hmac[out] Destination to store the HMAC.
617  */
618 static void
619 t_hmac (const void *plaintext,
620         size_t size,
621         uint32_t iv,
622         const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
623         struct GNUNET_ShortHashCode *hmac)
624 {
625   static const char ctx[] = "cadet authentication key";
626   struct GNUNET_CRYPTO_AuthKey auth_key;
627   struct GNUNET_HashCode hash;
628
629   GNUNET_CRYPTO_hmac_derive_key (&auth_key,
630                                  key,
631                                  &iv, sizeof (iv),
632                                  key, sizeof (*key),
633                                  ctx, sizeof (ctx),
634                                  NULL);
635   /* Two step: GNUNET_ShortHash is only 256 bits,
636      GNUNET_HashCode is 512, so we truncate. */
637   GNUNET_CRYPTO_hmac (&auth_key,
638                       plaintext,
639                       size,
640                       &hash);
641   GNUNET_memcpy (hmac,
642                  &hash,
643                  sizeof (*hmac));
644 }
645
646
647 /**
648  * Perform a HMAC.
649  *
650  * @param key Key to use.
651  * @param[out] hash Resulting HMAC.
652  * @param source Source key material (data to HMAC).
653  * @param len Length of @a source.
654  */
655 static void
656 t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
657                 struct GNUNET_HashCode *hash,
658                 const void *source,
659                 unsigned int len)
660 {
661   static const char ctx[] = "axolotl HMAC-HASH";
662   struct GNUNET_CRYPTO_AuthKey auth_key;
663
664   GNUNET_CRYPTO_hmac_derive_key (&auth_key,
665                                  key,
666                                  ctx, sizeof (ctx),
667                                  NULL);
668   GNUNET_CRYPTO_hmac (&auth_key,
669                       source,
670                       len,
671                       hash);
672 }
673
674
675 /**
676  * Derive a symmetric encryption key from an HMAC-HASH.
677  *
678  * @param key Key to use for the HMAC.
679  * @param[out] out Key to generate.
680  * @param source Source key material (data to HMAC).
681  * @param len Length of @a source.
682  */
683 static void
684 t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
685                    struct GNUNET_CRYPTO_SymmetricSessionKey *out,
686                    const void *source,
687                    unsigned int len)
688 {
689   static const char ctx[] = "axolotl derive key";
690   struct GNUNET_HashCode h;
691
692   t_ax_hmac_hash (key,
693                   &h,
694                   source,
695                   len);
696   GNUNET_CRYPTO_kdf (out, sizeof (*out),
697                      ctx, sizeof (ctx),
698                      &h, sizeof (h),
699                      NULL);
700 }
701
702
703 /**
704  * Encrypt data with the axolotl tunnel key.
705  *
706  * @param ax key material to use.
707  * @param dst Destination with @a size bytes for the encrypted data.
708  * @param src Source of the plaintext. Can overlap with @c dst, must contain @a size bytes
709  * @param size Size of the buffers at @a src and @a dst
710  */
711 static void
712 t_ax_encrypt (struct CadetTunnelAxolotl *ax,
713               void *dst,
714               const void *src,
715               size_t size)
716 {
717   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
718   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
719   size_t out_size;
720
721   ax->ratchet_counter++;
722   if ( (GNUNET_YES == ax->ratchet_allowed) &&
723        ( (ratchet_messages <= ax->ratchet_counter) ||
724          (0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us)) )
725   {
726     ax->ratchet_flag = GNUNET_YES;
727   }
728   if (GNUNET_YES == ax->ratchet_flag)
729   {
730     /* Advance ratchet */
731     struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
732     struct GNUNET_HashCode dh;
733     struct GNUNET_HashCode hmac;
734     static const char ctx[] = "axolotl ratchet";
735
736     new_ephemeral (ax);
737     ax->HKs = ax->NHKs;
738
739     /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
740     GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
741                             &ax->DHRr,
742                             &dh);
743     t_ax_hmac_hash (&ax->RK,
744                     &hmac,
745                     &dh,
746                     sizeof (dh));
747     GNUNET_CRYPTO_kdf (keys, sizeof (keys),
748                        ctx, sizeof (ctx),
749                        &hmac, sizeof (hmac),
750                        NULL);
751     ax->RK = keys[0];
752     ax->NHKs = keys[1];
753     ax->CKs = keys[2];
754
755     ax->PNs = ax->Ns;
756     ax->Ns = 0;
757     ax->ratchet_flag = GNUNET_NO;
758     ax->ratchet_allowed = GNUNET_NO;
759     ax->ratchet_counter = 0;
760     ax->ratchet_expiration
761       = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
762                                   ratchet_time);
763   }
764
765   t_hmac_derive_key (&ax->CKs,
766                      &MK,
767                      "0",
768                      1);
769   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
770                                      &MK,
771                                      NULL, 0,
772                                      NULL);
773
774   out_size = GNUNET_CRYPTO_symmetric_encrypt (src,
775                                               size,
776                                               &MK,
777                                               &iv,
778                                               dst);
779   GNUNET_assert (size == out_size);
780   t_hmac_derive_key (&ax->CKs,
781                      &ax->CKs,
782                      "1",
783                      1);
784 }
785
786
787 /**
788  * Decrypt data with the axolotl tunnel key.
789  *
790  * @param ax key material to use.
791  * @param dst Destination for the decrypted data, must contain @a size bytes.
792  * @param src Source of the ciphertext. Can overlap with @c dst, must contain @a size bytes.
793  * @param size Size of the @a src and @a dst buffers
794  */
795 static void
796 t_ax_decrypt (struct CadetTunnelAxolotl *ax,
797               void *dst,
798               const void *src,
799               size_t size)
800 {
801   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
802   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
803   size_t out_size;
804
805   t_hmac_derive_key (&ax->CKr,
806                      &MK,
807                      "0",
808                      1);
809   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
810                                      &MK,
811                                      NULL, 0,
812                                      NULL);
813   GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
814   out_size = GNUNET_CRYPTO_symmetric_decrypt (src,
815                                               size,
816                                               &MK,
817                                               &iv,
818                                               dst);
819   GNUNET_assert (out_size == size);
820   t_hmac_derive_key (&ax->CKr,
821                      &ax->CKr,
822                      "1",
823                      1);
824 }
825
826
827 /**
828  * Encrypt header with the axolotl header key.
829  *
830  * @param ax key material to use.
831  * @param[in|out] msg Message whose header to encrypt.
832  */
833 static void
834 t_h_encrypt (struct CadetTunnelAxolotl *ax,
835              struct GNUNET_CADET_TunnelEncryptedMessage *msg)
836 {
837   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
838   size_t out_size;
839
840   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
841                                      &ax->HKs,
842                                      NULL, 0,
843                                      NULL);
844   out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->ax_header,
845                                               sizeof (struct GNUNET_CADET_AxHeader),
846                                               &ax->HKs,
847                                               &iv,
848                                               &msg->ax_header);
849   GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
850 }
851
852
853 /**
854  * Decrypt header with the current axolotl header key.
855  *
856  * @param ax key material to use.
857  * @param src Message whose header to decrypt.
858  * @param dst Where to decrypt header to.
859  */
860 static void
861 t_h_decrypt (struct CadetTunnelAxolotl *ax,
862              const struct GNUNET_CADET_TunnelEncryptedMessage *src,
863              struct GNUNET_CADET_TunnelEncryptedMessage *dst)
864 {
865   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
866   size_t out_size;
867
868   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
869                                      &ax->HKr,
870                                      NULL, 0,
871                                      NULL);
872   out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
873                                               sizeof (struct GNUNET_CADET_AxHeader),
874                                               &ax->HKr,
875                                               &iv,
876                                               &dst->ax_header.Ns);
877   GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
878 }
879
880
881 /**
882  * Delete a key from the list of skipped keys.
883  *
884  * @param ax key material to delete @a key from.
885  * @param key Key to delete.
886  */
887 static void
888 delete_skipped_key (struct CadetTunnelAxolotl *ax,
889                     struct CadetTunnelSkippedKey *key)
890 {
891   GNUNET_CONTAINER_DLL_remove (ax->skipped_head,
892                                ax->skipped_tail,
893                                key);
894   GNUNET_free (key);
895   ax->skipped--;
896 }
897
898
899 /**
900  * Decrypt and verify data with the appropriate tunnel key and verify that the
901  * data has not been altered since it was sent by the remote peer.
902  *
903  * @param ax key material to use.
904  * @param dst Destination for the plaintext.
905  * @param src Source of the message. Can overlap with @c dst.
906  * @param size Size of the message.
907  * @return Size of the decrypted data, -1 if an error was encountered.
908  */
909 static ssize_t
910 try_old_ax_keys (struct CadetTunnelAxolotl *ax,
911                  void *dst,
912                  const struct GNUNET_CADET_TunnelEncryptedMessage *src,
913                  size_t size)
914 {
915   struct CadetTunnelSkippedKey *key;
916   struct GNUNET_ShortHashCode *hmac;
917   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
918   struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
919   struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
920   size_t esize;
921   size_t res;
922   size_t len;
923   unsigned int N;
924
925   LOG (GNUNET_ERROR_TYPE_DEBUG,
926        "Trying skipped keys\n");
927   hmac = &plaintext_header.hmac;
928   esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
929
930   /* Find a correct Header Key */
931   valid_HK = NULL;
932   for (key = ax->skipped_head; NULL != key; key = key->next)
933   {
934     t_hmac (&src->ax_header,
935             sizeof (struct GNUNET_CADET_AxHeader) + esize,
936             0,
937             &key->HK,
938             hmac);
939     if (0 == memcmp (hmac,
940                      &src->hmac,
941                      sizeof (*hmac)))
942     {
943       valid_HK = &key->HK;
944       break;
945     }
946   }
947   if (NULL == key)
948     return -1;
949
950   /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
951   GNUNET_assert (size > sizeof (struct GNUNET_CADET_TunnelEncryptedMessage));
952   len = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
953   GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
954
955   /* Decrypt header */
956   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
957                                      &key->HK,
958                                      NULL, 0,
959                                      NULL);
960   res = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
961                                          sizeof (struct GNUNET_CADET_AxHeader),
962                                          &key->HK,
963                                          &iv,
964                                          &plaintext_header.ax_header.Ns);
965   GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == res);
966
967   /* Find the correct message key */
968   N = ntohl (plaintext_header.ax_header.Ns);
969   while ( (NULL != key) &&
970           (N != key->Kn) )
971     key = key->next;
972   if ( (NULL == key) ||
973        (0 != memcmp (&key->HK,
974                      valid_HK,
975                      sizeof (*valid_HK))) )
976     return -1;
977
978   /* Decrypt payload */
979   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
980                                      &key->MK,
981                                      NULL,
982                                      0,
983                                      NULL);
984   res = GNUNET_CRYPTO_symmetric_decrypt (&src[1],
985                                          len,
986                                          &key->MK,
987                                          &iv,
988                                          dst);
989   delete_skipped_key (ax,
990                       key);
991   return res;
992 }
993
994
995 /**
996  * Delete a key from the list of skipped keys.
997  *
998  * @param ax key material to delete from.
999  * @param HKr Header Key to use.
1000  */
1001 static void
1002 store_skipped_key (struct CadetTunnelAxolotl *ax,
1003                    const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
1004 {
1005   struct CadetTunnelSkippedKey *key;
1006
1007   key = GNUNET_new (struct CadetTunnelSkippedKey);
1008   key->timestamp = GNUNET_TIME_absolute_get ();
1009   key->Kn = ax->Nr;
1010   key->HK = ax->HKr;
1011   t_hmac_derive_key (&ax->CKr,
1012                      &key->MK,
1013                      "0",
1014                      1);
1015   t_hmac_derive_key (&ax->CKr,
1016                      &ax->CKr,
1017                      "1",
1018                      1);
1019   GNUNET_CONTAINER_DLL_insert (ax->skipped_head,
1020                                ax->skipped_tail,
1021                                key);
1022   ax->skipped++;
1023   ax->Nr++;
1024 }
1025
1026
1027 /**
1028  * Stage skipped AX keys and calculate the message key.
1029  * Stores each HK and MK for skipped messages.
1030  *
1031  * @param ax key material to use
1032  * @param HKr Header key.
1033  * @param Np Received meesage number.
1034  * @return #GNUNET_OK if keys were stored.
1035  *         #GNUNET_SYSERR if an error ocurred (@a Np not expected).
1036  */
1037 static int
1038 store_ax_keys (struct CadetTunnelAxolotl *ax,
1039                const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1040                uint32_t Np)
1041 {
1042   int gap;
1043
1044   gap = Np - ax->Nr;
1045   LOG (GNUNET_ERROR_TYPE_DEBUG,
1046        "Storing skipped keys [%u, %u)\n",
1047        ax->Nr,
1048        Np);
1049   if (MAX_KEY_GAP < gap)
1050   {
1051     /* Avoid DoS (forcing peer to do more than #MAX_KEY_GAP HMAC operations) */
1052     /* TODO: start new key exchange on return */
1053     GNUNET_break_op (0);
1054     LOG (GNUNET_ERROR_TYPE_WARNING,
1055          "Got message %u, expected %u+\n",
1056          Np,
1057          ax->Nr);
1058     return GNUNET_SYSERR;
1059   }
1060   if (0 > gap)
1061   {
1062     /* Delayed message: don't store keys, flag to try old keys. */
1063     return GNUNET_SYSERR;
1064   }
1065
1066   while (ax->Nr < Np)
1067     store_skipped_key (ax,
1068                        HKr);
1069
1070   while (ax->skipped > MAX_SKIPPED_KEYS)
1071     delete_skipped_key (ax,
1072                         ax->skipped_tail);
1073   return GNUNET_OK;
1074 }
1075
1076
1077 /**
1078  * Decrypt and verify data with the appropriate tunnel key and verify that the
1079  * data has not been altered since it was sent by the remote peer.
1080  *
1081  * @param ax key material to use
1082  * @param dst Destination for the plaintext.
1083  * @param src Source of the message. Can overlap with @c dst.
1084  * @param size Size of the message.
1085  * @return Size of the decrypted data, -1 if an error was encountered.
1086  */
1087 static ssize_t
1088 t_ax_decrypt_and_validate (struct CadetTunnelAxolotl *ax,
1089                            void *dst,
1090                            const struct GNUNET_CADET_TunnelEncryptedMessage *src,
1091                            size_t size)
1092 {
1093   struct GNUNET_ShortHashCode msg_hmac;
1094   struct GNUNET_HashCode hmac;
1095   struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
1096   uint32_t Np;
1097   uint32_t PNp;
1098   size_t esize; /* Size of encryped payload */
1099
1100   esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1101
1102   /* Try current HK */
1103   t_hmac (&src->ax_header,
1104           sizeof (struct GNUNET_CADET_AxHeader) + esize,
1105           0, &ax->HKr,
1106           &msg_hmac);
1107   if (0 != memcmp (&msg_hmac,
1108                    &src->hmac,
1109                    sizeof (msg_hmac)))
1110   {
1111     static const char ctx[] = "axolotl ratchet";
1112     struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1113     struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1114     struct GNUNET_HashCode dh;
1115     struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1116
1117     /* Try Next HK */
1118     t_hmac (&src->ax_header,
1119             sizeof (struct GNUNET_CADET_AxHeader) + esize,
1120             0,
1121             &ax->NHKr,
1122             &msg_hmac);
1123     if (0 != memcmp (&msg_hmac,
1124                      &src->hmac,
1125                      sizeof (msg_hmac)))
1126     {
1127       /* Try the skipped keys, if that fails, we're out of luck. */
1128       return try_old_ax_keys (ax,
1129                               dst,
1130                               src,
1131                               size);
1132     }
1133     HK = ax->HKr;
1134     ax->HKr = ax->NHKr;
1135     t_h_decrypt (ax,
1136                  src,
1137                  &plaintext_header);
1138     Np = ntohl (plaintext_header.ax_header.Ns);
1139     PNp = ntohl (plaintext_header.ax_header.PNs);
1140     DHRp = &plaintext_header.ax_header.DHRs;
1141     store_ax_keys (ax,
1142                    &HK,
1143                    PNp);
1144
1145     /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1146     GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
1147                             DHRp,
1148                             &dh);
1149     t_ax_hmac_hash (&ax->RK,
1150                     &hmac,
1151                     &dh, sizeof (dh));
1152     GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1153                        ctx, sizeof (ctx),
1154                        &hmac, sizeof (hmac),
1155                        NULL);
1156
1157     /* Commit "purported" keys */
1158     ax->RK = keys[0];
1159     ax->NHKr = keys[1];
1160     ax->CKr = keys[2];
1161     ax->DHRr = *DHRp;
1162     ax->Nr = 0;
1163     ax->ratchet_allowed = GNUNET_YES;
1164   }
1165   else
1166   {
1167     t_h_decrypt (ax,
1168                  src,
1169                  &plaintext_header);
1170     Np = ntohl (plaintext_header.ax_header.Ns);
1171     PNp = ntohl (plaintext_header.ax_header.PNs);
1172   }
1173   if ( (Np != ax->Nr) &&
1174        (GNUNET_OK != store_ax_keys (ax,
1175                                     &ax->HKr,
1176                                     Np)) )
1177   {
1178     /* Try the skipped keys, if that fails, we're out of luck. */
1179     return try_old_ax_keys (ax,
1180                             dst,
1181                             src,
1182                             size);
1183   }
1184
1185   t_ax_decrypt (ax,
1186                 dst,
1187                 &src[1],
1188                 esize);
1189   ax->Nr = Np + 1;
1190   return esize;
1191 }
1192
1193
1194 /**
1195  * Our tunnel became ready for the first time, notify channels
1196  * that have been waiting.
1197  *
1198  * @param cls our tunnel, not used
1199  * @param key unique ID of the channel, not used
1200  * @param value the `struct CadetChannel` to notify
1201  * @return #GNUNET_OK (continue to iterate)
1202  */
1203 static int
1204 notify_tunnel_up_cb (void *cls,
1205                      uint32_t key,
1206                      void *value)
1207 {
1208   struct CadetChannel *ch = value;
1209
1210   GCCH_tunnel_up (ch);
1211   return GNUNET_OK;
1212 }
1213
1214
1215 /**
1216  * Change the tunnel encryption state.
1217  * If the encryption state changes to OK, stop the rekey task.
1218  *
1219  * @param t Tunnel whose encryption state to change, or NULL.
1220  * @param state New encryption state.
1221  */
1222 void
1223 GCT_change_estate (struct CadetTunnel *t,
1224                    enum CadetTunnelEState state)
1225 {
1226   enum CadetTunnelEState old = t->estate;
1227
1228   t->estate = state;
1229   LOG (GNUNET_ERROR_TYPE_DEBUG,
1230        "Tunnel %s estate changed from %d to %d\n",
1231        GCT_2s (t),
1232        old,
1233        state);
1234
1235   if ( (CADET_TUNNEL_KEY_OK != old) &&
1236        (CADET_TUNNEL_KEY_OK == t->estate) )
1237   {
1238     if (NULL != t->kx_task)
1239     {
1240       GNUNET_SCHEDULER_cancel (t->kx_task);
1241       t->kx_task = NULL;
1242     }
1243     /* notify all channels that have been waiting */
1244     GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1245                                              &notify_tunnel_up_cb,
1246                                              t);
1247   }
1248 }
1249
1250
1251 /**
1252  * Send a KX message.
1253  *
1254  * FIXME: does not take care of sender-authentication yet!
1255  *
1256  * @param t Tunnel on which to send it.
1257  * @param ax axolotl key context to use
1258  * @param force_reply Force the other peer to reply with a KX message.
1259  */
1260 static void
1261 send_kx (struct CadetTunnel *t,
1262          struct CadetTunnelAxolotl *ax,
1263          int force_reply)
1264 {
1265   struct CadetTConnection *ct;
1266   struct CadetConnection *cc;
1267   struct GNUNET_MQ_Envelope *env;
1268   struct GNUNET_CADET_TunnelKeyExchangeMessage *msg;
1269   enum GNUNET_CADET_KX_Flags flags;
1270
1271   ct = get_ready_connection (t);
1272   if (NULL == ct)
1273   {
1274     LOG (GNUNET_ERROR_TYPE_DEBUG,
1275          "Wanted to send KX on tunnel %s, but no connection is ready, deferring\n",
1276          GCT_2s (t));
1277     return;
1278   }
1279   cc = ct->cc;
1280   LOG (GNUNET_ERROR_TYPE_DEBUG,
1281        "Sending KX on tunnel %s using connection %s\n",
1282        GCT_2s (t),
1283        GCC_2s (ct->cc));
1284
1285   // GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1286   env = GNUNET_MQ_msg (msg,
1287                        GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX);
1288   flags = GNUNET_CADET_KX_FLAG_NONE;
1289   if (GNUNET_YES == force_reply)
1290     flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY;
1291   msg->flags = htonl (flags);
1292   msg->cid = *GCC_get_id (cc);
1293   GNUNET_CRYPTO_ecdhe_key_get_public (ax->kx_0,
1294                                       &msg->ephemeral_key);
1295   GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs,
1296                                       &msg->ratchet_key);
1297   ct->is_ready = GNUNET_NO;
1298   GCC_transmit (cc,
1299                 env);
1300   t->kx_retry_delay = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1301   t->next_kx_attempt = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1302   if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1303     GCT_change_estate (t,
1304                        CADET_TUNNEL_KEY_SENT);
1305 }
1306
1307
1308 /**
1309  * Cleanup state used by @a ax.
1310  *
1311  * @param ax state to free, but not memory of @a ax itself
1312  */
1313 static void
1314 cleanup_ax (struct CadetTunnelAxolotl *ax)
1315 {
1316   while (NULL != ax->skipped_head)
1317     delete_skipped_key (ax,
1318                         ax->skipped_head);
1319   GNUNET_assert (0 == ax->skipped);
1320   GNUNET_free_non_null (ax->kx_0);
1321   GNUNET_free_non_null (ax->DHRs);
1322 }
1323
1324
1325 /**
1326  * Update our Axolotl key state based on the KX data we received.
1327  * Computes the new chain keys, and root keys, etc, and also checks
1328  * wether this is a replay of the current chain.
1329  *
1330  * @param[in|out] axolotl chain key state to recompute
1331  * @param pid peer identity of the other peer
1332  * @param ephemeral_key ephemeral public key of the other peer
1333  * @param ratchet_key senders next ephemeral public key
1334  * @return #GNUNET_OK on success, #GNUNET_NO if the resulting
1335  *       root key is already in @a ax and thus the KX is useless;
1336  *       #GNUNET_SYSERR on hard errors (i.e. @a pid is #my_full_id)
1337  */
1338 static int
1339 update_ax_by_kx (struct CadetTunnelAxolotl *ax,
1340                  const struct GNUNET_PeerIdentity *pid,
1341                  const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key,
1342                  const struct GNUNET_CRYPTO_EcdhePublicKey *ratchet_key)
1343 {
1344   struct GNUNET_HashCode key_material[3];
1345   struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
1346   const char salt[] = "CADET Axolotl salt";
1347   int am_I_alice;
1348
1349   if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1350                                            pid))
1351     am_I_alice = GNUNET_YES;
1352   else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1353                                                 pid))
1354     am_I_alice = GNUNET_NO;
1355   else
1356   {
1357     GNUNET_break_op (0);
1358     return GNUNET_SYSERR;
1359   }
1360
1361   if (0 == memcmp (&ax->DHRr,
1362                    ratchet_key,
1363                    sizeof (*ratchet_key)))
1364   {
1365     LOG (GNUNET_ERROR_TYPE_DEBUG,
1366          "Ratchet key already known. Ignoring KX.\n");
1367     return GNUNET_NO;
1368   }
1369
1370   ax->DHRr = *ratchet_key;
1371
1372   /* ECDH A B0 */
1373   if (GNUNET_YES == am_I_alice)
1374   {
1375     GNUNET_CRYPTO_eddsa_ecdh (my_private_key,      /* A */
1376                               ephemeral_key, /* B0 */
1377                               &key_material[0]);
1378   }
1379   else
1380   {
1381     GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0,            /* B0 */
1382                               &pid->public_key,    /* A */
1383                               &key_material[0]);
1384   }
1385
1386   /* ECDH A0 B */
1387   if (GNUNET_YES == am_I_alice)
1388   {
1389     GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0,            /* A0 */
1390                               &pid->public_key,    /* B */
1391                               &key_material[1]);
1392   }
1393   else
1394   {
1395     GNUNET_CRYPTO_eddsa_ecdh (my_private_key,      /* A */
1396                               ephemeral_key, /* B0 */
1397                               &key_material[1]);
1398
1399
1400   }
1401
1402   /* ECDH A0 B0 */
1403   /* (This is the triple-DH, we could probably safely skip this,
1404      as A0/B0 are already in the key material.) */
1405   GNUNET_CRYPTO_ecc_ecdh (ax->kx_0,             /* A0 or B0 */
1406                           ephemeral_key,  /* B0 or A0 */
1407                           &key_material[2]);
1408
1409   /* KDF */
1410   GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1411                      salt, sizeof (salt),
1412                      &key_material, sizeof (key_material),
1413                      NULL);
1414
1415   if (0 == memcmp (&ax->RK,
1416                    &keys[0],
1417                    sizeof (ax->RK)))
1418   {
1419     LOG (GNUNET_ERROR_TYPE_DEBUG,
1420          "Root key of handshake already known. Ignoring KX.\n");
1421     return GNUNET_NO;
1422   }
1423
1424   ax->RK = keys[0];
1425   if (GNUNET_YES == am_I_alice)
1426   {
1427     ax->HKr = keys[1];
1428     ax->NHKs = keys[2];
1429     ax->NHKr = keys[3];
1430     ax->CKr = keys[4];
1431     ax->ratchet_flag = GNUNET_YES;
1432   }
1433   else
1434   {
1435     ax->HKs = keys[1];
1436     ax->NHKr = keys[2];
1437     ax->NHKs = keys[3];
1438     ax->CKs = keys[4];
1439     ax->ratchet_flag = GNUNET_NO;
1440     ax->ratchet_expiration
1441       = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
1442                                   ratchet_time);
1443   }
1444   return GNUNET_OK;
1445 }
1446
1447
1448 /**
1449  * Handle KX message that lacks authentication (and which will thus
1450  * only be considered authenticated after we respond with our own
1451  * KX_AUTH and finally successfully decrypt payload).
1452  *
1453  * @param ct connection/tunnel combo that received encrypted message
1454  * @param msg the key exchange message
1455  */
1456 void
1457 GCT_handle_kx (struct CadetTConnection *ct,
1458                const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
1459 {
1460   struct CadetTunnel *t = ct->t;
1461   struct CadetTunnelAxolotl *ax;
1462   int ret;
1463
1464   LOG (GNUNET_ERROR_TYPE_DEBUG,
1465        "Handling KX message for tunnel %s\n",
1466        GCT_2s (t));
1467
1468   /* We only keep ONE unverified KX around, so if there is an existing one,
1469      clean it up. */
1470   if (NULL != t->unverified_ax)
1471   {
1472     LOG (GNUNET_ERROR_TYPE_DEBUG,
1473          "Dropping old unverified KX state, got a fresh one.\n",
1474          t->unverified_attempts);
1475     cleanup_ax (t->unverified_ax);
1476     memset (t->unverified_ax,
1477             0,
1478             sizeof (struct CadetTunnelAxolotl));
1479     new_ephemeral (t->unverified_ax);
1480     t->unverified_ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
1481   }
1482   else
1483   {
1484     t->unverified_ax = GNUNET_new (struct CadetTunnelAxolotl);
1485     new_ephemeral (t->unverified_ax);
1486     t->unverified_ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
1487   }
1488   /* Set as the 'current' RK the one we are currently using,
1489      so that the duplicate-detection logic of
1490      #update_ax_by_kx can work. */
1491   t->unverified_ax->RK = t->ax.RK;
1492   t->unverified_attempts = 0;
1493   ax = t->unverified_ax;
1494
1495   /* FIXME: why this? Investigate use of kx_task! */
1496   if (0 != (GNUNET_CADET_KX_FLAG_FORCE_REPLY & ntohl (msg->flags)))
1497   {
1498     if (NULL != t->kx_task)
1499     {
1500       GNUNET_SCHEDULER_cancel (t->kx_task);
1501       t->kx_task = NULL;
1502     }
1503     send_kx (t,
1504              ax,
1505              GNUNET_NO);
1506   }
1507
1508   /* Update 'ax' by the new key material */
1509   ret = update_ax_by_kx (ax,
1510                          GCP_get_id (t->destination),
1511                          &msg->ephemeral_key,
1512                          &msg->ratchet_key);
1513   GNUNET_break (GNUNET_SYSERR != ret);
1514   if (GNUNET_OK != ret)
1515     return; /* duplicate KX, nothing to do */
1516
1517   /* move ahead in our state machine */
1518   switch (t->estate)
1519   {
1520   case CADET_TUNNEL_KEY_UNINITIALIZED:
1521     GCT_change_estate (t,
1522                        CADET_TUNNEL_KEY_PING);
1523     break;
1524   case CADET_TUNNEL_KEY_SENT:
1525     /* Got a response to us sending our key; now
1526        we can start transmitting! */
1527     GCT_change_estate (t,
1528                        CADET_TUNNEL_KEY_OK);
1529     if (NULL != t->send_task)
1530       GNUNET_SCHEDULER_cancel (t->send_task);
1531     t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
1532                                              t);
1533     break;
1534   case CADET_TUNNEL_KEY_PING:
1535     /* Got a key yet again; need encrypted payload or KX_AUTH
1536        to advance to #CADET_TUNNEL_KEY_OK! */
1537     break;
1538   case CADET_TUNNEL_KEY_OK:
1539     /* Did not expect a key, but so what. */
1540     break;
1541   }
1542 }
1543
1544
1545 /* ************************************** end core crypto ***************************** */
1546
1547
1548 /**
1549  * Compute the next free channel tunnel number for this tunnel.
1550  *
1551  * @param t the tunnel
1552  * @return unused number that can uniquely identify a channel in the tunnel
1553  */
1554 static struct GNUNET_CADET_ChannelTunnelNumber
1555 get_next_free_ctn (struct CadetTunnel *t)
1556 {
1557 #define HIGH_BIT 0x8000000
1558   struct GNUNET_CADET_ChannelTunnelNumber ret;
1559   uint32_t ctn;
1560   int cmp;
1561   uint32_t highbit;
1562
1563   cmp = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1564                                          GCP_get_id (GCT_get_destination (t)));
1565   if (0 < cmp)
1566     highbit = HIGH_BIT;
1567   else if (0 > cmp)
1568     highbit = 0;
1569   else
1570     GNUNET_assert (0); // loopback must never go here!
1571   ctn = ntohl (t->next_ctn.cn);
1572   while (NULL !=
1573          GNUNET_CONTAINER_multihashmap32_get (t->channels,
1574                                               ctn))
1575   {
1576     ctn = ((ctn + 1) & (~ HIGH_BIT)) | highbit;
1577   }
1578   t->next_ctn.cn = htonl (((ctn + 1) & (~ HIGH_BIT)) | highbit);
1579   ret.cn = ntohl (ctn);
1580   return ret;
1581 }
1582
1583
1584 /**
1585  * Add a channel to a tunnel, and notify channel that we are ready
1586  * for transmission if we are already up.  Otherwise that notification
1587  * will be done later in #notify_tunnel_up_cb().
1588  *
1589  * @param t Tunnel.
1590  * @param ch Channel
1591  * @return unique number identifying @a ch within @a t
1592  */
1593 struct GNUNET_CADET_ChannelTunnelNumber
1594 GCT_add_channel (struct CadetTunnel *t,
1595                  struct CadetChannel *ch)
1596 {
1597   struct GNUNET_CADET_ChannelTunnelNumber ctn;
1598
1599   ctn = get_next_free_ctn (t);
1600   GNUNET_assert (GNUNET_YES ==
1601                  GNUNET_CONTAINER_multihashmap32_put (t->channels,
1602                                                       ntohl (ctn.cn),
1603                                                       ch,
1604                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1605   LOG (GNUNET_ERROR_TYPE_DEBUG,
1606        "Adding channel %s to tunnel %s\n",
1607        GCCH_2s (ch),
1608        GCT_2s (t));
1609   if (CADET_TUNNEL_KEY_OK == t->estate)
1610     GCCH_tunnel_up (ch);
1611   return ctn;
1612 }
1613
1614
1615 /**
1616  * We lost a connection, remove it from our list and clean up
1617  * the connection object itself.
1618  *
1619  * @param ct binding of connection to tunnel of the connection that was lost.
1620  */
1621 void
1622 GCT_connection_lost (struct CadetTConnection *ct)
1623 {
1624   struct CadetTunnel *t = ct->t;
1625
1626   GNUNET_CONTAINER_DLL_remove (t->connection_head,
1627                                t->connection_tail,
1628                                ct);
1629   GNUNET_free (ct);
1630 }
1631
1632
1633 /**
1634  * This tunnel is no longer used, destroy it.
1635  *
1636  * @param cls the idle tunnel
1637  */
1638 static void
1639 destroy_tunnel (void *cls)
1640 {
1641   struct CadetTunnel *t = cls;
1642   struct CadetTConnection *ct;
1643   struct CadetTunnelQueueEntry *tq;
1644
1645   t->destroy_task = NULL;
1646   LOG (GNUNET_ERROR_TYPE_DEBUG,
1647        "Destroying idle tunnel %s\n",
1648        GCT_2s (t));
1649   GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap32_size (t->channels));
1650   while (NULL != (ct = t->connection_head))
1651   {
1652     struct CadetConnection *cc;
1653
1654     GNUNET_assert (ct->t == t);
1655     cc = ct->cc;
1656     GCT_connection_lost (ct);
1657     GCC_destroy_without_tunnel (cc);
1658   }
1659   while (NULL != (tq = t->tq_head))
1660   {
1661     if (NULL != tq->cont)
1662       tq->cont (tq->cont_cls);
1663     GCT_send_cancel (tq);
1664   }
1665   GCP_drop_tunnel (t->destination,
1666                    t);
1667   GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
1668   if (NULL != t->maintain_connections_task)
1669   {
1670     GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
1671     t->maintain_connections_task = NULL;
1672   }
1673   if (NULL != t->send_task)
1674   {
1675     GNUNET_SCHEDULER_cancel (t->send_task);
1676     t->send_task = NULL;
1677   }
1678   if (NULL != t->kx_task)
1679   {
1680     GNUNET_SCHEDULER_cancel (t->kx_task);
1681     t->kx_task = NULL;
1682   }
1683   GNUNET_MST_destroy (t->mst);
1684   GNUNET_MQ_destroy (t->mq);
1685   cleanup_ax (&t->ax);
1686   if (NULL != t->unverified_ax)
1687   {
1688     cleanup_ax (t->unverified_ax);
1689     GNUNET_free (t->unverified_ax);
1690   }
1691   GNUNET_free (t);
1692 }
1693
1694
1695 /**
1696  * Remove a channel from a tunnel.
1697  *
1698  * @param t Tunnel.
1699  * @param ch Channel
1700  * @param ctn unique number identifying @a ch within @a t
1701  */
1702 void
1703 GCT_remove_channel (struct CadetTunnel *t,
1704                     struct CadetChannel *ch,
1705                     struct GNUNET_CADET_ChannelTunnelNumber ctn)
1706 {
1707   LOG (GNUNET_ERROR_TYPE_DEBUG,
1708        "Removing channel %s from tunnel %s\n",
1709        GCCH_2s (ch),
1710        GCT_2s (t));
1711   GNUNET_assert (GNUNET_YES ==
1712                  GNUNET_CONTAINER_multihashmap32_remove (t->channels,
1713                                                          ntohl (ctn.cn),
1714                                                          ch));
1715   if (0 ==
1716       GNUNET_CONTAINER_multihashmap32_size (t->channels))
1717   {
1718     t->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
1719                                                     &destroy_tunnel,
1720                                                     t);
1721   }
1722 }
1723
1724
1725 /**
1726  * Destroy remaining channels during shutdown.
1727  *
1728  * @param cls the `struct CadetTunnel` of the channel
1729  * @param key key of the channel
1730  * @param value the `struct CadetChannel`
1731  * @return #GNUNET_OK (continue to iterate)
1732  */
1733 static int
1734 destroy_remaining_channels (void *cls,
1735                             uint32_t key,
1736                             void *value)
1737 {
1738   struct CadetChannel *ch = value;
1739
1740   GCCH_handle_remote_destroy (ch);
1741   return GNUNET_OK;
1742 }
1743
1744
1745 /**
1746  * Destroys the tunnel @a t now, without delay. Used during shutdown.
1747  *
1748  * @param t tunnel to destroy
1749  */
1750 void
1751 GCT_destroy_tunnel_now (struct CadetTunnel *t)
1752 {
1753   GNUNET_assert (GNUNET_YES == shutting_down);
1754   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1755                                            &destroy_remaining_channels,
1756                                            t);
1757   GNUNET_assert (0 ==
1758                  GNUNET_CONTAINER_multihashmap32_size (t->channels));
1759   if (NULL != t->destroy_task)
1760   {
1761     GNUNET_SCHEDULER_cancel (t->destroy_task);
1762     t->destroy_task = NULL;
1763   }
1764   destroy_tunnel (t);
1765 }
1766
1767
1768 /**
1769  * It's been a while, we should try to redo the KX, if we can.
1770  *
1771  * @param cls the `struct CadetTunnel` to do KX for.
1772  */
1773 static void
1774 retry_kx (void *cls)
1775 {
1776   struct CadetTunnel *t = cls;
1777
1778   t->kx_task = NULL;
1779   send_kx (t,
1780            &t->ax,
1781            ( (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) ||
1782              (CADET_TUNNEL_KEY_SENT == t->estate) )
1783            ? GNUNET_YES
1784            : GNUNET_NO);
1785 }
1786
1787
1788 /**
1789  * Send normal payload from queue in @a t via connection @a ct.
1790  * Does nothing if our payload queue is empty.
1791  *
1792  * @param t tunnel to send data from
1793  * @param ct connection to use for transmission (is ready)
1794  */
1795 static void
1796 try_send_normal_payload (struct CadetTunnel *t,
1797                          struct CadetTConnection *ct)
1798 {
1799   struct CadetTunnelQueueEntry *tq;
1800
1801   GNUNET_assert (GNUNET_YES == ct->is_ready);
1802   tq = t->tq_head;
1803   if (NULL == tq)
1804   {
1805     /* no messages pending right now */
1806     LOG (GNUNET_ERROR_TYPE_DEBUG,
1807          "Not sending payload of %s on ready %s (nothing pending)\n",
1808          GCT_2s (t),
1809          GCC_2s (ct->cc));
1810     return;
1811   }
1812   /* ready to send message 'tq' on tunnel 'ct' */
1813   GNUNET_assert (t == tq->t);
1814   GNUNET_CONTAINER_DLL_remove (t->tq_head,
1815                                t->tq_tail,
1816                                tq);
1817   if (NULL != tq->cid)
1818     *tq->cid = *GCC_get_id (ct->cc);
1819   ct->is_ready = GNUNET_NO;
1820   LOG (GNUNET_ERROR_TYPE_DEBUG,
1821        "Sending payload of %s on %s\n",
1822        GCT_2s (t),
1823        GCC_2s (ct->cc));
1824   GCC_transmit (ct->cc,
1825                 tq->env);
1826   if (NULL != tq->cont)
1827     tq->cont (tq->cont_cls);
1828   GNUNET_free (tq);
1829 }
1830
1831
1832 /**
1833  * A connection is @a is_ready for transmission.  Looks at our message
1834  * queue and if there is a message, sends it out via the connection.
1835  *
1836  * @param cls the `struct CadetTConnection` that is @a is_ready
1837  * @param is_ready #GNUNET_YES if connection are now ready,
1838  *                 #GNUNET_NO if connection are no longer ready
1839  */
1840 static void
1841 connection_ready_cb (void *cls,
1842                      int is_ready)
1843 {
1844   struct CadetTConnection *ct = cls;
1845   struct CadetTunnel *t = ct->t;
1846
1847   if (GNUNET_NO == is_ready)
1848   {
1849     LOG (GNUNET_ERROR_TYPE_DEBUG,
1850          "Connection %s no longer ready for tunnel %s\n",
1851          GCC_2s (ct->cc),
1852          GCT_2s (t));
1853     ct->is_ready = GNUNET_NO;
1854     return;
1855   }
1856   ct->is_ready = GNUNET_YES;
1857   LOG (GNUNET_ERROR_TYPE_DEBUG,
1858        "Connection %s now ready for tunnel %s in state %s\n",
1859        GCC_2s (ct->cc),
1860        GCT_2s (t),
1861        estate2s (t->estate));
1862   switch (t->estate)
1863   {
1864   case CADET_TUNNEL_KEY_UNINITIALIZED:
1865     send_kx (t,
1866              &t->ax,
1867              GNUNET_YES);
1868     break;
1869   case CADET_TUNNEL_KEY_SENT:
1870   case CADET_TUNNEL_KEY_PING:
1871     /* opportunity to #retry_kx() starts now, schedule job */
1872     if (NULL == t->kx_task)
1873     {
1874       t->kx_task
1875         = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
1876                                    &retry_kx,
1877                                    t);
1878     }
1879     break;
1880   case CADET_TUNNEL_KEY_OK:
1881     try_send_normal_payload (t,
1882                              ct);
1883     break;
1884   }
1885 }
1886
1887
1888 /**
1889  * Called when either we have a new connection, or a new message in the
1890  * queue, or some existing connection has transmission capacity.  Looks
1891  * at our message queue and if there is a message, picks a connection
1892  * to send it on.
1893  *
1894  * @param cls the `struct CadetTunnel` to process messages on
1895  */
1896 static void
1897 trigger_transmissions (void *cls)
1898 {
1899   struct CadetTunnel *t = cls;
1900   struct CadetTConnection *ct;
1901
1902   t->send_task = NULL;
1903   if (NULL == t->tq_head)
1904     return; /* no messages pending right now */
1905   ct = get_ready_connection (t);
1906   if (NULL == ct)
1907     return; /* no connections ready */
1908   try_send_normal_payload (t,
1909                            ct);
1910 }
1911
1912
1913 /**
1914  * Consider using the path @a p for the tunnel @a t.
1915  * The tunnel destination is at offset @a off in path @a p.
1916  *
1917  * @param cls our tunnel
1918  * @param path a path to our destination
1919  * @param off offset of the destination on path @a path
1920  * @return #GNUNET_YES (should keep iterating)
1921  */
1922 static int
1923 consider_path_cb (void *cls,
1924                   struct CadetPeerPath *path,
1925                   unsigned int off)
1926 {
1927   struct CadetTunnel *t = cls;
1928   unsigned int min_length = UINT_MAX;
1929   GNUNET_CONTAINER_HeapCostType max_desire = 0;
1930   struct CadetTConnection *ct;
1931
1932   /* Check if we care about the new path. */
1933   for (ct = t->connection_head;
1934        NULL != ct;
1935        ct = ct->next)
1936   {
1937     struct CadetPeerPath *ps;
1938
1939     ps = GCC_get_path (ct->cc);
1940     if (ps == path)
1941     {
1942       LOG (GNUNET_ERROR_TYPE_DEBUG,
1943            "Ignoring duplicate path %s for tunnel %s.\n",
1944            GCPP_2s (path),
1945            GCT_2s (t));
1946       return GNUNET_YES; /* duplicate */
1947     }
1948     min_length = GNUNET_MIN (min_length,
1949                              GCPP_get_length (ps));
1950     max_desire = GNUNET_MAX (max_desire,
1951                              GCPP_get_desirability (ps));
1952   }
1953
1954   /* FIXME: not sure we should really just count
1955      'num_connections' here, as they may all have
1956      consistently failed to connect. */
1957
1958   /* We iterate by increasing path length; if we have enough paths and
1959      this one is more than twice as long than what we are currently
1960      using, then ignore all of these super-long ones! */
1961   if ( (t->num_connections > DESIRED_CONNECTIONS_PER_TUNNEL) &&
1962        (min_length * 2 < off) )
1963   {
1964     LOG (GNUNET_ERROR_TYPE_DEBUG,
1965          "Ignoring paths of length %u, they are way too long.\n",
1966          min_length * 2);
1967     return GNUNET_NO;
1968   }
1969   /* If we have enough paths and this one looks no better, ignore it. */
1970   if ( (t->num_connections >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
1971        (min_length < GCPP_get_length (path)) &&
1972        (max_desire > GCPP_get_desirability (path)) )
1973   {
1974     LOG (GNUNET_ERROR_TYPE_DEBUG,
1975          "Ignoring path (%u/%llu) to %s, got something better already.\n",
1976          GCPP_get_length (path),
1977          (unsigned long long) GCPP_get_desirability (path),
1978          GCP_2s (t->destination));
1979     return GNUNET_YES;
1980   }
1981
1982   /* Path is interesting (better by some metric, or we don't have
1983      enough paths yet). */
1984   ct = GNUNET_new (struct CadetTConnection);
1985   ct->created = GNUNET_TIME_absolute_get ();
1986   ct->t = t;
1987   ct->cc = GCC_create (t->destination,
1988                        path,
1989                        ct,
1990                        &connection_ready_cb,
1991                        ct);
1992   /* FIXME: schedule job to kill connection (and path?)  if it takes
1993      too long to get ready! (And track performance data on how long
1994      other connections took with the tunnel!)
1995      => Note: to be done within 'connection'-logic! */
1996   GNUNET_CONTAINER_DLL_insert (t->connection_head,
1997                                t->connection_tail,
1998                                ct);
1999   t->num_connections++;
2000   LOG (GNUNET_ERROR_TYPE_DEBUG,
2001        "Found interesting path %s for tunnel %s, created connection %s\n",
2002        GCPP_2s (path),
2003        GCT_2s (t),
2004        GCC_2s (ct->cc));
2005   return GNUNET_YES;
2006 }
2007
2008
2009 /**
2010  * Function called to maintain the connections underlying our tunnel.
2011  * Tries to maintain (incl. tear down) connections for the tunnel, and
2012  * if there is a significant change, may trigger transmissions.
2013  *
2014  * Basically, needs to check if there are connections that perform
2015  * badly, and if so eventually kill them and trigger a replacement.
2016  * The strategy is to open one more connection than
2017  * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
2018  * least-performing one, and then inquire for new ones.
2019  *
2020  * @param cls the `struct CadetTunnel`
2021  */
2022 static void
2023 maintain_connections_cb (void *cls)
2024 {
2025   struct CadetTunnel *t = cls;
2026
2027   t->maintain_connections_task = NULL;
2028   LOG (GNUNET_ERROR_TYPE_DEBUG,
2029        "Performing connection maintenance for tunnel %s.\n",
2030        GCT_2s (t));
2031
2032   (void) GCP_iterate_paths (t->destination,
2033                             &consider_path_cb,
2034                             t);
2035
2036   GNUNET_break (0); // FIXME: implement!
2037 }
2038
2039
2040 /**
2041  * Consider using the path @a p for the tunnel @a t.
2042  * The tunnel destination is at offset @a off in path @a p.
2043  *
2044  * @param cls our tunnel
2045  * @param path a path to our destination
2046  * @param off offset of the destination on path @a path
2047  */
2048 void
2049 GCT_consider_path (struct CadetTunnel *t,
2050                    struct CadetPeerPath *p,
2051                    unsigned int off)
2052 {
2053   (void) consider_path_cb (t,
2054                            p,
2055                            off);
2056 }
2057
2058
2059 /**
2060  * We got a keepalive. Track in statistics.
2061  *
2062  * @param cls the `struct CadetTunnel` for which we decrypted the message
2063  * @param msg  the message we received on the tunnel
2064  */
2065 static void
2066 handle_plaintext_keepalive (void *cls,
2067                             const struct GNUNET_MessageHeader *msg)
2068 {
2069   struct CadetTunnel *t = cls;
2070
2071   LOG (GNUNET_ERROR_TYPE_DEBUG,
2072        "Received KEEPALIVE on tunnel %s\n",
2073        GCT_2s (t));
2074   GNUNET_STATISTICS_update (stats,
2075                             "# keepalives received",
2076                             1,
2077                             GNUNET_NO);
2078 }
2079
2080
2081 /**
2082  * Check that @a msg is well-formed.
2083  *
2084  * @param cls the `struct CadetTunnel` for which we decrypted the message
2085  * @param msg  the message we received on the tunnel
2086  * @return #GNUNET_OK (any variable-size payload goes)
2087  */
2088 static int
2089 check_plaintext_data (void *cls,
2090                       const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2091 {
2092   return GNUNET_OK;
2093 }
2094
2095
2096 /**
2097  * We received payload data for a channel.  Locate the channel
2098  * and process the data, or return an error if the channel is unknown.
2099  *
2100  * @param cls the `struct CadetTunnel` for which we decrypted the message
2101  * @param msg the message we received on the tunnel
2102  */
2103 static void
2104 handle_plaintext_data (void *cls,
2105                        const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2106 {
2107   struct CadetTunnel *t = cls;
2108   struct CadetChannel *ch;
2109
2110   ch = lookup_channel (t,
2111                        msg->ctn);
2112   if (NULL == ch)
2113   {
2114     /* We don't know about such a channel, might have been destroyed on our
2115        end in the meantime, or never existed. Send back a DESTROY. */
2116     LOG (GNUNET_ERROR_TYPE_DEBUG,
2117          "Receicved %u bytes of application data for unknown channel %u, sending DESTROY\n",
2118          (unsigned int) (ntohs (msg->header.size) - sizeof (*msg)),
2119          ntohl (msg->ctn.cn));
2120     GCT_send_channel_destroy (t,
2121                               msg->ctn);
2122     return;
2123   }
2124   GCCH_handle_channel_plaintext_data (ch,
2125                                       msg);
2126 }
2127
2128
2129 /**
2130  * We received an acknowledgement for data we sent on a channel.
2131  * Locate the channel and process it, or return an error if the
2132  * channel is unknown.
2133  *
2134  * @param cls the `struct CadetTunnel` for which we decrypted the message
2135  * @param ack the message we received on the tunnel
2136  */
2137 static void
2138 handle_plaintext_data_ack (void *cls,
2139                            const struct GNUNET_CADET_ChannelDataAckMessage *ack)
2140 {
2141   struct CadetTunnel *t = cls;
2142   struct CadetChannel *ch;
2143
2144   ch = lookup_channel (t,
2145                        ack->ctn);
2146   if (NULL == ch)
2147   {
2148     /* We don't know about such a channel, might have been destroyed on our
2149        end in the meantime, or never existed. Send back a DESTROY. */
2150     LOG (GNUNET_ERROR_TYPE_DEBUG,
2151          "Receicved DATA_ACK for unknown channel %u, sending DESTROY\n",
2152          ntohl (ack->ctn.cn));
2153     GCT_send_channel_destroy (t,
2154                               ack->ctn);
2155     return;
2156   }
2157   GCCH_handle_channel_plaintext_data_ack (ch,
2158                                           ack);
2159 }
2160
2161
2162 /**
2163  * We have received a request to open a channel to a port from
2164  * another peer.  Creates the incoming channel.
2165  *
2166  * @param cls the `struct CadetTunnel` for which we decrypted the message
2167  * @param copen the message we received on the tunnel
2168  */
2169 static void
2170 handle_plaintext_channel_open (void *cls,
2171                                const struct GNUNET_CADET_ChannelOpenMessage *copen)
2172 {
2173   struct CadetTunnel *t = cls;
2174   struct CadetChannel *ch;
2175
2176   ch = GNUNET_CONTAINER_multihashmap32_get (t->channels,
2177                                             ntohl (copen->ctn.cn));
2178   if (NULL != ch)
2179   {
2180     LOG (GNUNET_ERROR_TYPE_DEBUG,
2181          "Receicved duplicate channel OPEN on port %s from %s (%s), resending ACK\n",
2182          GNUNET_h2s (&copen->port),
2183          GCT_2s (t),
2184          GCCH_2s (ch));
2185     GCCH_handle_duplicate_open (ch);
2186     return;
2187   }
2188   LOG (GNUNET_ERROR_TYPE_DEBUG,
2189        "Receicved channel OPEN on port %s from %s\n",
2190        GNUNET_h2s (&copen->port),
2191        GCT_2s (t));
2192   ch = GCCH_channel_incoming_new (t,
2193                                   copen->ctn,
2194                                   &copen->port,
2195                                   ntohl (copen->opt));
2196   GNUNET_assert (GNUNET_OK ==
2197                  GNUNET_CONTAINER_multihashmap32_put (t->channels,
2198                                                       ntohl (copen->ctn.cn),
2199                                                       ch,
2200                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2201 }
2202
2203
2204 /**
2205  * Send a DESTROY message via the tunnel.
2206  *
2207  * @param t the tunnel to transmit over
2208  * @param ctn ID of the channel to destroy
2209  */
2210 void
2211 GCT_send_channel_destroy (struct CadetTunnel *t,
2212                           struct GNUNET_CADET_ChannelTunnelNumber ctn)
2213 {
2214   struct GNUNET_CADET_ChannelManageMessage msg;
2215
2216   LOG (GNUNET_ERROR_TYPE_DEBUG,
2217        "Sending DESTORY message for channel ID %u\n",
2218        ntohl (ctn.cn));
2219   msg.header.size = htons (sizeof (msg));
2220   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2221   msg.reserved = htonl (0);
2222   msg.ctn = ctn;
2223   GCT_send (t,
2224             &msg.header,
2225             NULL,
2226             NULL);
2227 }
2228
2229
2230 /**
2231  * We have received confirmation from the target peer that the
2232  * given channel could be established (the port is open).
2233  * Tell the client.
2234  *
2235  * @param cls the `struct CadetTunnel` for which we decrypted the message
2236  * @param cm the message we received on the tunnel
2237  */
2238 static void
2239 handle_plaintext_channel_open_ack (void *cls,
2240                                    const struct GNUNET_CADET_ChannelManageMessage *cm)
2241 {
2242   struct CadetTunnel *t = cls;
2243   struct CadetChannel *ch;
2244
2245   ch = lookup_channel (t,
2246                        cm->ctn);
2247   if (NULL == ch)
2248   {
2249     /* We don't know about such a channel, might have been destroyed on our
2250        end in the meantime, or never existed. Send back a DESTROY. */
2251     LOG (GNUNET_ERROR_TYPE_DEBUG,
2252          "Received channel OPEN_ACK for unknown channel %u, sending DESTROY\n",
2253          ntohl (cm->ctn.cn));
2254     GCT_send_channel_destroy (t,
2255                               cm->ctn);
2256     return;
2257   }
2258   LOG (GNUNET_ERROR_TYPE_DEBUG,
2259        "Received channel OPEN_ACK on channel %s from %s\n",
2260        GCCH_2s (ch),
2261        GCT_2s (t));
2262   GCCH_handle_channel_open_ack (ch);
2263 }
2264
2265
2266 /**
2267  * We received a message saying that a channel should be destroyed.
2268  * Pass it on to the correct channel.
2269  *
2270  * @param cls the `struct CadetTunnel` for which we decrypted the message
2271  * @param cm the message we received on the tunnel
2272  */
2273 static void
2274 handle_plaintext_channel_destroy (void *cls,
2275                                   const struct GNUNET_CADET_ChannelManageMessage *cm)
2276 {
2277   struct CadetTunnel *t = cls;
2278   struct CadetChannel *ch;
2279
2280   ch = lookup_channel (t,
2281                        cm->ctn);
2282   if (NULL == ch)
2283   {
2284     /* We don't know about such a channel, might have been destroyed on our
2285        end in the meantime, or never existed. */
2286     LOG (GNUNET_ERROR_TYPE_DEBUG,
2287          "Received channel DESTORY for unknown channel %u. Ignoring.\n",
2288          ntohl (cm->ctn.cn));
2289     return;
2290   }
2291   LOG (GNUNET_ERROR_TYPE_DEBUG,
2292        "Receicved channel DESTROY on %s from %s\n",
2293        GCCH_2s (ch),
2294        GCT_2s (t));
2295   GCCH_handle_remote_destroy (ch);
2296 }
2297
2298
2299 /**
2300  * Handles a message we decrypted, by injecting it into
2301  * our message queue (which will do the dispatching).
2302  *
2303  * @param cls the `struct CadetTunnel` that got the message
2304  * @param msg the message
2305  * @return #GNUNET_OK (continue to process)
2306  */
2307 static int
2308 handle_decrypted (void *cls,
2309                   const struct GNUNET_MessageHeader *msg)
2310 {
2311   struct CadetTunnel *t = cls;
2312
2313   GNUNET_MQ_inject_message (t->mq,
2314                             msg);
2315   return GNUNET_OK;
2316 }
2317
2318
2319 /**
2320  * Function called if we had an error processing
2321  * an incoming decrypted message.
2322  *
2323  * @param cls the `struct CadetTunnel`
2324  * @param error error code
2325  */
2326 static void
2327 decrypted_error_cb (void *cls,
2328                     enum GNUNET_MQ_Error error)
2329 {
2330   GNUNET_break_op (0);
2331 }
2332
2333
2334 /**
2335  * Create a tunnel to @a destionation.  Must only be called
2336  * from within #GCP_get_tunnel().
2337  *
2338  * @param destination where to create the tunnel to
2339  * @return new tunnel to @a destination
2340  */
2341 struct CadetTunnel *
2342 GCT_create_tunnel (struct CadetPeer *destination)
2343 {
2344   struct CadetTunnel *t = GNUNET_new (struct CadetTunnel);
2345   struct GNUNET_MQ_MessageHandler handlers[] = {
2346     GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
2347                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
2348                              struct GNUNET_MessageHeader,
2349                              t),
2350     GNUNET_MQ_hd_var_size (plaintext_data,
2351                            GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
2352                            struct GNUNET_CADET_ChannelAppDataMessage,
2353                            t),
2354     GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
2355                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
2356                              struct GNUNET_CADET_ChannelDataAckMessage,
2357                              t),
2358     GNUNET_MQ_hd_fixed_size (plaintext_channel_open,
2359                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
2360                              struct GNUNET_CADET_ChannelOpenMessage,
2361                              t),
2362     GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack,
2363                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
2364                              struct GNUNET_CADET_ChannelManageMessage,
2365                              t),
2366     GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
2367                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
2368                              struct GNUNET_CADET_ChannelManageMessage,
2369                              t),
2370     GNUNET_MQ_handler_end ()
2371   };
2372
2373   new_ephemeral (&t->ax);
2374   t->ax.kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
2375   t->destination = destination;
2376   t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
2377   t->maintain_connections_task
2378     = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
2379                                 t);
2380   t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
2381                                          NULL,
2382                                          NULL,
2383                                          NULL,
2384                                          handlers,
2385                                          &decrypted_error_cb,
2386                                          t);
2387   t->mst = GNUNET_MST_create (&handle_decrypted,
2388                               t);
2389   return t;
2390 }
2391
2392
2393 /**
2394  * Add a @a connection to the @a tunnel.
2395  *
2396  * @param t a tunnel
2397  * @param cid connection identifer to use for the connection
2398  * @param path path to use for the connection
2399  * @return #GNUNET_OK on success,
2400  *         #GNUNET_SYSERR on failure (duplicate connection)
2401  */
2402 int
2403 GCT_add_inbound_connection (struct CadetTunnel *t,
2404                             const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
2405                             struct CadetPeerPath *path)
2406 {
2407   struct CadetTConnection *ct;
2408
2409   ct = GNUNET_new (struct CadetTConnection);
2410   ct->created = GNUNET_TIME_absolute_get ();
2411   ct->t = t;
2412   ct->cc = GCC_create_inbound (t->destination,
2413                                path,
2414                                ct,
2415                                cid,
2416                                &connection_ready_cb,
2417                                ct);
2418   if (NULL == ct->cc)
2419   {
2420     LOG (GNUNET_ERROR_TYPE_DEBUG,
2421          "Tunnel %s refused inbound connection %s (duplicate)\n",
2422          GCT_2s (t),
2423          GCC_2s (ct->cc));
2424     GNUNET_free (ct);
2425     return GNUNET_SYSERR;
2426   }
2427   /* FIXME: schedule job to kill connection (and path?)  if it takes
2428      too long to get ready! (And track performance data on how long
2429      other connections took with the tunnel!)
2430      => Note: to be done within 'connection'-logic! */
2431   GNUNET_CONTAINER_DLL_insert (t->connection_head,
2432                                t->connection_tail,
2433                                ct);
2434   t->num_connections++;
2435   LOG (GNUNET_ERROR_TYPE_DEBUG,
2436        "Tunnel %s has new connection %s\n",
2437        GCT_2s (t),
2438        GCC_2s (ct->cc));
2439   return GNUNET_OK;
2440 }
2441
2442
2443 /**
2444  * Handle encrypted message.
2445  *
2446  * @param ct connection/tunnel combo that received encrypted message
2447  * @param msg the encrypted message to decrypt
2448  */
2449 void
2450 GCT_handle_encrypted (struct CadetTConnection *ct,
2451                       const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
2452 {
2453   struct CadetTunnel *t = ct->t;
2454   uint16_t size = ntohs (msg->header.size);
2455   char cbuf [size] GNUNET_ALIGN;
2456   ssize_t decrypted_size;
2457
2458   LOG (GNUNET_ERROR_TYPE_DEBUG,
2459        "Tunnel %s received %u bytes of encrypted data in state %d\n",
2460        GCT_2s (t),
2461        (unsigned int) size,
2462        t->estate);
2463
2464   switch (t->estate)
2465   {
2466   case CADET_TUNNEL_KEY_UNINITIALIZED:
2467     /* We did not even SEND our KX, how can the other peer
2468        send us encrypted data? */
2469     GNUNET_break_op (0);
2470     return;
2471   case CADET_TUNNEL_KEY_SENT:
2472     /* We did not get the KX of the other peer, but that
2473        might have been lost.  Ask for KX again. */
2474     GNUNET_STATISTICS_update (stats,
2475                               "# received encrypted without KX",
2476                               1,
2477                               GNUNET_NO);
2478     if (NULL != t->kx_task)
2479       GNUNET_SCHEDULER_cancel (t->kx_task);
2480     t->kx_task = GNUNET_SCHEDULER_add_now (&retry_kx,
2481                                            t);
2482     return;
2483   case CADET_TUNNEL_KEY_PING:
2484     /* Great, first payload, we might graduate to OK */
2485   case CADET_TUNNEL_KEY_OK:
2486     break;
2487   }
2488
2489   GNUNET_STATISTICS_update (stats,
2490                             "# received encrypted",
2491                             1,
2492                             GNUNET_NO);
2493   decrypted_size = -1;
2494   if (CADET_TUNNEL_KEY_OK == t->estate)
2495   {
2496     /* We have well-established key material available,
2497        try that. (This is the common case.) */
2498     decrypted_size = t_ax_decrypt_and_validate (&t->ax,
2499                                                 cbuf,
2500                                                 msg,
2501                                                 size);
2502   }
2503
2504   if ( (-1 == decrypted_size) &&
2505        (NULL != t->unverified_ax) )
2506   {
2507     /* We have un-authenticated KX material available. We should try
2508        this as a back-up option, in case the sender crashed and
2509        switched keys. */
2510     decrypted_size = t_ax_decrypt_and_validate (t->unverified_ax,
2511                                                 cbuf,
2512                                                 msg,
2513                                                 size);
2514     if (-1 != decrypted_size)
2515     {
2516       /* It worked! Treat this as authentication of the AX data! */
2517       cleanup_ax (&t->ax);
2518       t->ax = *t->unverified_ax;
2519       GNUNET_free (t->unverified_ax);
2520       t->unverified_ax = NULL;
2521     }
2522     if (CADET_TUNNEL_KEY_PING == t->estate)
2523     {
2524       /* First time it worked, move tunnel into production! */
2525       GCT_change_estate (t,
2526                          CADET_TUNNEL_KEY_OK);
2527       if (NULL != t->send_task)
2528         GNUNET_SCHEDULER_cancel (t->send_task);
2529       t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
2530                                                t);
2531     }
2532   }
2533   if (NULL != t->unverified_ax)
2534   {
2535     /* We had unverified KX material that was useless; so increment
2536        counter and eventually move to ignore it.  Note that we even do
2537        this increment if we successfully decrypted with the old KX
2538        material and thus didn't even both with the new one.  This is
2539        the ideal case, as a malicious injection of bogus KX data
2540        basically only causes us to increment a counter a few times. */
2541     t->unverified_attempts++;
2542     LOG (GNUNET_ERROR_TYPE_DEBUG,
2543          "Failed to decrypt message with unverified KX data %u times\n",
2544          t->unverified_attempts);
2545     if (t->unverified_attempts > MAX_UNVERIFIED_ATTEMPTS)
2546     {
2547       cleanup_ax (t->unverified_ax);
2548       GNUNET_free (t->unverified_ax);
2549       t->unverified_ax = NULL;
2550     }
2551   }
2552
2553   if (-1 == decrypted_size)
2554   {
2555     /* Decryption failed for good, complain. */
2556     GNUNET_break_op (0);
2557     LOG (GNUNET_ERROR_TYPE_WARNING,
2558          "Tunnel %s failed to decrypt and validate encrypted data\n",
2559          GCT_2s (t));
2560     GNUNET_STATISTICS_update (stats,
2561                               "# unable to decrypt",
2562                               1,
2563                               GNUNET_NO);
2564     return;
2565   }
2566
2567   /* The MST will ultimately call #handle_decrypted() on each message. */
2568   GNUNET_break_op (GNUNET_OK ==
2569                    GNUNET_MST_from_buffer (t->mst,
2570                                            cbuf,
2571                                            decrypted_size,
2572                                            GNUNET_YES,
2573                                            GNUNET_NO));
2574 }
2575
2576
2577 /**
2578  * Sends an already built message on a tunnel, encrypting it and
2579  * choosing the best connection if not provided.
2580  *
2581  * @param message Message to send. Function modifies it.
2582  * @param t Tunnel on which this message is transmitted.
2583  * @param cont Continuation to call once message is really sent.
2584  * @param cont_cls Closure for @c cont.
2585  * @return Handle to cancel message
2586  */
2587 struct CadetTunnelQueueEntry *
2588 GCT_send (struct CadetTunnel *t,
2589           const struct GNUNET_MessageHeader *message,
2590           GNUNET_SCHEDULER_TaskCallback cont,
2591           void *cont_cls)
2592 {
2593   struct CadetTunnelQueueEntry *tq;
2594   uint16_t payload_size;
2595   struct GNUNET_MQ_Envelope *env;
2596   struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
2597
2598   if (CADET_TUNNEL_KEY_OK != t->estate)
2599   {
2600     GNUNET_break (0);
2601     return NULL;
2602   }
2603   payload_size = ntohs (message->size);
2604   LOG (GNUNET_ERROR_TYPE_DEBUG,
2605        "Encrypting %u bytes for tunnel %s\n",
2606        (unsigned int) payload_size,
2607        GCT_2s (t));
2608   env = GNUNET_MQ_msg_extra (ax_msg,
2609                              payload_size,
2610                              GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
2611   t_ax_encrypt (&t->ax,
2612                 &ax_msg[1],
2613                 message,
2614                 payload_size);
2615   ax_msg->ax_header.Ns = htonl (t->ax.Ns++);
2616   ax_msg->ax_header.PNs = htonl (t->ax.PNs);
2617   /* FIXME: we should do this once, not once per message;
2618      this is a point multiplication, and DHRs does not
2619      change all the time. */
2620   GNUNET_CRYPTO_ecdhe_key_get_public (t->ax.DHRs,
2621                                       &ax_msg->ax_header.DHRs);
2622   t_h_encrypt (&t->ax,
2623                ax_msg);
2624   t_hmac (&ax_msg->ax_header,
2625           sizeof (struct GNUNET_CADET_AxHeader) + payload_size,
2626           0,
2627           &t->ax.HKs,
2628           &ax_msg->hmac);
2629
2630   tq = GNUNET_malloc (sizeof (*tq));
2631   tq->t = t;
2632   tq->env = env;
2633   tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
2634   tq->cont = cont;
2635   tq->cont_cls = cont_cls;
2636   GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
2637                                     t->tq_tail,
2638                                     tq);
2639   if (NULL != t->send_task)
2640     GNUNET_SCHEDULER_cancel (t->send_task);
2641   t->send_task
2642     = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
2643                                 t);
2644   return tq;
2645 }
2646
2647
2648 /**
2649  * Cancel a previously sent message while it's in the queue.
2650  *
2651  * ONLY can be called before the continuation given to the send
2652  * function is called. Once the continuation is called, the message is
2653  * no longer in the queue!
2654  *
2655  * @param tq Handle to the queue entry to cancel.
2656  */
2657 void
2658 GCT_send_cancel (struct CadetTunnelQueueEntry *tq)
2659 {
2660   struct CadetTunnel *t = tq->t;
2661
2662   GNUNET_CONTAINER_DLL_remove (t->tq_head,
2663                                t->tq_tail,
2664                                tq);
2665   GNUNET_MQ_discard (tq->env);
2666   GNUNET_free (tq);
2667 }
2668
2669
2670 /**
2671  * Iterate over all connections of a tunnel.
2672  *
2673  * @param t Tunnel whose connections to iterate.
2674  * @param iter Iterator.
2675  * @param iter_cls Closure for @c iter.
2676  */
2677 void
2678 GCT_iterate_connections (struct CadetTunnel *t,
2679                          GCT_ConnectionIterator iter,
2680                          void *iter_cls)
2681 {
2682   for (struct CadetTConnection *ct = t->connection_head;
2683        NULL != ct;
2684        ct = ct->next)
2685     iter (iter_cls,
2686           ct->cc);
2687 }
2688
2689
2690 /**
2691  * Closure for #iterate_channels_cb.
2692  */
2693 struct ChanIterCls
2694 {
2695   /**
2696    * Function to call.
2697    */
2698   GCT_ChannelIterator iter;
2699
2700   /**
2701    * Closure for @e iter.
2702    */
2703   void *iter_cls;
2704 };
2705
2706
2707 /**
2708  * Helper function for #GCT_iterate_channels.
2709  *
2710  * @param cls the `struct ChanIterCls`
2711  * @param key unused
2712  * @param value a `struct CadetChannel`
2713  * @return #GNUNET_OK
2714  */
2715 static int
2716 iterate_channels_cb (void *cls,
2717                      uint32_t key,
2718                      void *value)
2719 {
2720   struct ChanIterCls *ctx = cls;
2721   struct CadetChannel *ch = value;
2722
2723   ctx->iter (ctx->iter_cls,
2724              ch);
2725   return GNUNET_OK;
2726 }
2727
2728
2729 /**
2730  * Iterate over all channels of a tunnel.
2731  *
2732  * @param t Tunnel whose channels to iterate.
2733  * @param iter Iterator.
2734  * @param iter_cls Closure for @c iter.
2735  */
2736 void
2737 GCT_iterate_channels (struct CadetTunnel *t,
2738                       GCT_ChannelIterator iter,
2739                       void *iter_cls)
2740 {
2741   struct ChanIterCls ctx;
2742
2743   ctx.iter = iter;
2744   ctx.iter_cls = iter_cls;
2745   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2746                                            &iterate_channels_cb,
2747                                            &ctx);
2748
2749 }
2750
2751
2752 /**
2753  * Call #GCCH_debug() on a channel.
2754  *
2755  * @param cls points to the log level to use
2756  * @param key unused
2757  * @param value the `struct CadetChannel` to dump
2758  * @return #GNUNET_OK (continue iteration)
2759  */
2760 static int
2761 debug_channel (void *cls,
2762                uint32_t key,
2763                void *value)
2764 {
2765   const enum GNUNET_ErrorType *level = cls;
2766   struct CadetChannel *ch = value;
2767
2768   GCCH_debug (ch, *level);
2769   return GNUNET_OK;
2770 }
2771
2772
2773 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
2774
2775
2776 /**
2777  * Log all possible info about the tunnel state.
2778  *
2779  * @param t Tunnel to debug.
2780  * @param level Debug level to use.
2781  */
2782 void
2783 GCT_debug (const struct CadetTunnel *t,
2784            enum GNUNET_ErrorType level)
2785 {
2786   struct CadetTConnection *iter_c;
2787   int do_log;
2788
2789   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
2790                                        "cadet-tun",
2791                                        __FILE__, __FUNCTION__, __LINE__);
2792   if (0 == do_log)
2793     return;
2794
2795   LOG2 (level,
2796         "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
2797         GCT_2s (t),
2798         estate2s (t->estate),
2799         t->tq_len,
2800         t->num_connections);
2801   LOG2 (level,
2802         "TTT channels:\n");
2803   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2804                                            &debug_channel,
2805                                            &level);
2806   LOG2 (level,
2807         "TTT connections:\n");
2808   for (iter_c = t->connection_head; NULL != iter_c; iter_c = iter_c->next)
2809     GCC_debug (iter_c->cc,
2810                level);
2811
2812   LOG2 (level,
2813         "TTT TUNNEL END\n");
2814 }
2815
2816
2817 /* end of gnunet-service-cadet-new_tunnels.c */