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