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