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