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