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