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