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