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