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