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