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