2 This file is part of GNUnet.
3 Copyright (C) 2013, 2017 GNUnet e.V.
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
21 * @file cadet/gnunet-service-cadet-new_tunnels.c
22 * @brief Information we track per tunnel.
23 * @author Bartlomiej Polot
24 * @author Christian Grothoff
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
34 #include "gnunet_util_lib.h"
35 #include "gnunet_statistics_service.h"
36 #include "gnunet_signatures.h"
37 #include "gnunet-service-cadet-new.h"
38 #include "cadet_protocol.h"
39 #include "gnunet-service-cadet-new_channel.h"
40 #include "gnunet-service-cadet-new_connection.h"
41 #include "gnunet-service-cadet-new_tunnels.h"
42 #include "gnunet-service-cadet-new_peer.h"
43 #include "gnunet-service-cadet-new_paths.h"
46 #define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__)
49 * How often do we try to decrypt payload with unverified key
50 * material? Used to limit CPU increase upon receiving bogus
53 #define MAX_UNVERIFIED_ATTEMPTS 16
56 * How long do we wait until tearing down an idle tunnel?
58 #define IDLE_DESTROY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90)
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!
64 #define INITIAL_KX_RETRY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 250)
67 * Maximum number of skipped keys we keep in memory per tunnel.
69 #define MAX_SKIPPED_KEYS 64
72 * Maximum number of keys (and thus ratchet steps) we are willing to
73 * skip before we decide this is either a bogus packet or a DoS-attempt.
75 #define MAX_KEY_GAP 256
79 * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
81 struct CadetTunnelSkippedKey
86 struct CadetTunnelSkippedKey *next;
91 struct CadetTunnelSkippedKey *prev;
94 * When was this key stored (for timeout).
96 struct GNUNET_TIME_Absolute timestamp;
101 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
106 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
109 * Key number for a given HK.
116 * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
118 struct CadetTunnelAxolotl
121 * A (double linked) list of stored message keys and associated header keys
122 * for "skipped" messages, i.e. messages that have not been
123 * received despite the reception of more recent messages, (head).
125 struct CadetTunnelSkippedKey *skipped_head;
128 * Skipped messages' keys DLL, tail.
130 struct CadetTunnelSkippedKey *skipped_tail;
133 * 32-byte root key which gets updated by DH ratchet.
135 struct GNUNET_CRYPTO_SymmetricSessionKey RK;
138 * 32-byte header key (currently used for sending).
140 struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
143 * 32-byte header key (currently used for receiving)
145 struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
148 * 32-byte next header key (for sending), used once the
149 * ratchet advances. We are sure that the sender has this
150 * key as well only after @e ratchet_allowed is #GNUNET_YES.
152 struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
155 * 32-byte next header key (for receiving). To be tried
156 * when decrypting with @e HKr fails and thus the sender
157 * may have advanced the ratchet.
159 struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
162 * 32-byte chain keys (used for forward-secrecy) for
163 * sending messages. Updated for every message.
165 struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
168 * 32-byte chain keys (used for forward-secrecy) for
169 * receiving messages. Updated for every message. If
170 * messages are skipped, the respective derived MKs
171 * (and the current @HKr) are kept in the @e skipped_head DLL.
173 struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
176 * ECDH for key exchange (A0 / B0). Note that for the
177 * 'unverified_ax', this member is an alias with the main
178 * 't->ax.kx_0' value, so do not free it!
180 struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
183 * ECDH Ratchet key (our private key in the current DH). Note that
184 * for the 'unverified_ax', this member is an alias with the main
185 * 't->ax.kx_0' value, so do not free it!
187 struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
190 * ECDH Ratchet key (other peer's public key in the current DH).
192 struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
195 * Time when the current ratchet expires and a new one is triggered
196 * (if @e ratchet_allowed is #GNUNET_YES).
198 struct GNUNET_TIME_Absolute ratchet_expiration;
201 * Number of elements in @a skipped_head <-> @a skipped_tail.
203 unsigned int skipped;
206 * Message number (reset to 0 with each new ratchet, next message to send).
211 * Message number (reset to 0 with each new ratchet, next message to recv).
216 * Previous message numbers (# of msgs sent under prev ratchet)
221 * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
226 * True (#GNUNET_YES) if we have received a message from the
227 * other peer that uses the keys from our last ratchet step.
228 * This implies that we are again allowed to advance the ratchet,
229 * otherwise we have to wait until the other peer sees our current
230 * ephemeral key and advances first.
232 * #GNUNET_NO if we have advanced the ratched but lack any evidence
233 * that the other peer has noticed this.
238 * Number of messages recieved since our last ratchet advance.
240 * If this counter = 0, we cannot send a new ratchet key in the next
243 * If this counter > 0, we could (but don't have to) send a new key.
245 * Once the @e ratchet_counter is larger than
246 * #ratchet_messages (or @e ratchet_expiration time has past), and
247 * @e ratchet_allowed is #GNUNET_YES, we advance the ratchet.
249 unsigned int ratchet_counter;
255 * Struct used to save messages in a non-ready tunnel to send once connected.
257 struct CadetTunnelQueueEntry
260 * We are entries in a DLL
262 struct CadetTunnelQueueEntry *next;
265 * We are entries in a DLL
267 struct CadetTunnelQueueEntry *prev;
270 * Tunnel these messages belong in.
272 struct CadetTunnel *t;
275 * Continuation to call once sent (on the channel layer).
277 GCT_SendContinuation cont;
280 * Closure for @c cont.
285 * Envelope of message to send follows.
287 struct GNUNET_MQ_Envelope *env;
290 * Where to put the connection identifier into the payload
291 * of the message in @e env once we have it?
293 struct GNUNET_CADET_ConnectionTunnelIdentifier *cid;
298 * Struct containing all information regarding a tunnel to a peer.
303 * Destination of the tunnel.
305 struct CadetPeer *destination;
308 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own
309 * ephemeral key changes.
311 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
314 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
316 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
319 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
321 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
326 struct CadetTunnelAxolotl ax;
329 * Unverified Axolotl info, used only if we got a fresh KX (not a
330 * KX_AUTH) while our end of the tunnel was still up. In this case,
331 * we keep the fresh KX around but do not put it into action until
332 * we got encrypted payload that assures us of the authenticity of
335 struct CadetTunnelAxolotl *unverified_ax;
338 * Task scheduled if there are no more channels using the tunnel.
340 struct GNUNET_SCHEDULER_Task *destroy_task;
343 * Task to trim connections if too many are present.
345 struct GNUNET_SCHEDULER_Task *maintain_connections_task;
348 * Task to send messages from queue (if possible).
350 struct GNUNET_SCHEDULER_Task *send_task;
353 * Task to trigger KX.
355 struct GNUNET_SCHEDULER_Task *kx_task;
358 * Tokenizer for decrypted messages.
360 struct GNUNET_MessageStreamTokenizer *mst;
363 * Dispatcher for decrypted messages only (do NOT use for sending!).
365 struct GNUNET_MQ_Handle *mq;
368 * DLL of ready connections that are actively used to reach the destination peer.
370 struct CadetTConnection *connection_ready_head;
373 * DLL of ready connections that are actively used to reach the destination peer.
375 struct CadetTConnection *connection_ready_tail;
378 * DLL of connections that we maintain that might be used to reach the destination peer.
380 struct CadetTConnection *connection_busy_head;
383 * DLL of connections that we maintain that might be used to reach the destination peer.
385 struct CadetTConnection *connection_busy_tail;
388 * Channels inside this tunnel. Maps
389 * `struct GNUNET_CADET_ChannelTunnelNumber` to a `struct CadetChannel`.
391 struct GNUNET_CONTAINER_MultiHashMap32 *channels;
394 * Channel ID for the next created channel in this tunnel.
396 struct GNUNET_CADET_ChannelTunnelNumber next_ctn;
399 * Queued messages, to transmit once tunnel gets connected.
401 struct CadetTunnelQueueEntry *tq_head;
404 * Queued messages, to transmit once tunnel gets connected.
406 struct CadetTunnelQueueEntry *tq_tail;
409 * Identification of the connection from which we are currently processing
410 * a message. Only valid (non-NULL) during #handle_decrypted() and the
411 * handle-*()-functions called from our @e mq during that function.
413 struct CadetTConnection *current_ct;
416 * How long do we wait until we retry the KX?
418 struct GNUNET_TIME_Relative kx_retry_delay;
421 * When do we try the next KX?
423 struct GNUNET_TIME_Absolute next_kx_attempt;
426 * Number of connections in the @e connection_ready_head DLL.
428 unsigned int num_ready_connections;
431 * Number of connections in the @e connection_busy_head DLL.
433 unsigned int num_busy_connections;
436 * How often have we tried and failed to decrypt a message using
437 * the unverified KX material from @e unverified_ax? Used to
438 * stop trying after #MAX_UNVERIFIED_ATTEMPTS.
440 unsigned int unverified_attempts;
443 * Number of entries in the @e tq_head DLL.
448 * State of the tunnel encryption.
450 enum CadetTunnelEState estate;
453 * Force triggering KX_AUTH independent of @e estate.
455 int kx_auth_requested;
461 * Connection @a ct is now unready, clear it's ready flag
462 * and move it from the ready DLL to the busy DLL.
464 * @param ct connection to move to unready status
467 mark_connection_unready (struct CadetTConnection *ct)
469 struct CadetTunnel *t = ct->t;
471 GNUNET_assert (GNUNET_YES == ct->is_ready);
472 GNUNET_CONTAINER_DLL_remove (t->connection_ready_head,
473 t->connection_ready_tail,
475 GNUNET_assert (0 < t->num_ready_connections);
476 t->num_ready_connections--;
477 ct->is_ready = GNUNET_NO;
478 GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
479 t->connection_busy_tail,
481 t->num_busy_connections++;
486 * Get the static string for the peer this tunnel is directed.
490 * @return Static string the destination peer's ID.
493 GCT_2s (const struct CadetTunnel *t)
498 return "Tunnel(NULL)";
499 GNUNET_snprintf (buf,
502 GNUNET_i2s (GCP_get_id (t->destination)));
508 * Get string description for tunnel encryption state.
510 * @param es Tunnel state.
512 * @return String representation.
515 estate2s (enum CadetTunnelEState es)
521 case CADET_TUNNEL_KEY_UNINITIALIZED:
522 return "CADET_TUNNEL_KEY_UNINITIALIZED";
523 case CADET_TUNNEL_KEY_AX_RECV:
524 return "CADET_TUNNEL_KEY_AX_RECV";
525 case CADET_TUNNEL_KEY_AX_SENT:
526 return "CADET_TUNNEL_KEY_AX_SENT";
527 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
528 return "CADET_TUNNEL_KEY_AX_SENT_AND_RECV";
529 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
530 return "CADET_TUNNEL_KEY_AX_AUTH_SENT";
531 case CADET_TUNNEL_KEY_OK:
532 return "CADET_TUNNEL_KEY_OK";
534 GNUNET_snprintf (buf,
536 "%u (UNKNOWN STATE)",
544 * Return the peer to which this tunnel goes.
547 * @return the destination of the tunnel
550 GCT_get_destination (struct CadetTunnel *t)
552 return t->destination;
557 * Count channels of a tunnel.
559 * @param t Tunnel on which to count.
561 * @return Number of channels.
564 GCT_count_channels (struct CadetTunnel *t)
566 return GNUNET_CONTAINER_multihashmap32_size (t->channels);
571 * Lookup a channel by its @a ctn.
573 * @param t tunnel to look in
574 * @param ctn number of channel to find
575 * @return NULL if channel does not exist
577 struct CadetChannel *
578 lookup_channel (struct CadetTunnel *t,
579 struct GNUNET_CADET_ChannelTunnelNumber ctn)
581 return GNUNET_CONTAINER_multihashmap32_get (t->channels,
587 * Count all created connections of a tunnel. Not necessarily ready connections!
589 * @param t Tunnel on which to count.
591 * @return Number of connections created, either being established or ready.
594 GCT_count_any_connections (const struct CadetTunnel *t)
596 return t->num_ready_connections + t->num_busy_connections;
601 * Find first connection that is ready in the list of
602 * our connections. Picks ready connections round-robin.
604 * @param t tunnel to search
605 * @return NULL if we have no connection that is ready
607 static struct CadetTConnection *
608 get_ready_connection (struct CadetTunnel *t)
610 return t->connection_ready_head;
615 * Get the encryption state of a tunnel.
619 * @return Tunnel's encryption state.
621 enum CadetTunnelEState
622 GCT_get_estate (struct CadetTunnel *t)
629 * Called when either we have a new connection, or a new message in the
630 * queue, or some existing connection has transmission capacity. Looks
631 * at our message queue and if there is a message, picks a connection
634 * @param cls the `struct CadetTunnel` to process messages on
637 trigger_transmissions (void *cls);
640 /* ************************************** start core crypto ***************************** */
644 * Create a new Axolotl ephemeral (ratchet) key.
646 * @param ax key material to update
649 new_ephemeral (struct CadetTunnelAxolotl *ax)
651 GNUNET_free_non_null (ax->DHRs);
652 LOG (GNUNET_ERROR_TYPE_DEBUG,
653 "Creating new ephemeral ratchet key (DHRs)\n");
654 ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
661 * @param plaintext Content to HMAC.
662 * @param size Size of @c plaintext.
663 * @param iv Initialization vector for the message.
664 * @param key Key to use.
665 * @param hmac[out] Destination to store the HMAC.
668 t_hmac (const void *plaintext,
671 const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
672 struct GNUNET_ShortHashCode *hmac)
674 static const char ctx[] = "cadet authentication key";
675 struct GNUNET_CRYPTO_AuthKey auth_key;
676 struct GNUNET_HashCode hash;
678 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
684 /* Two step: GNUNET_ShortHash is only 256 bits,
685 GNUNET_HashCode is 512, so we truncate. */
686 GNUNET_CRYPTO_hmac (&auth_key,
699 * @param key Key to use.
700 * @param[out] hash Resulting HMAC.
701 * @param source Source key material (data to HMAC).
702 * @param len Length of @a source.
705 t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
706 struct GNUNET_HashCode *hash,
710 static const char ctx[] = "axolotl HMAC-HASH";
711 struct GNUNET_CRYPTO_AuthKey auth_key;
713 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
717 GNUNET_CRYPTO_hmac (&auth_key,
725 * Derive a symmetric encryption key from an HMAC-HASH.
727 * @param key Key to use for the HMAC.
728 * @param[out] out Key to generate.
729 * @param source Source key material (data to HMAC).
730 * @param len Length of @a source.
733 t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
734 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
738 static const char ctx[] = "axolotl derive key";
739 struct GNUNET_HashCode h;
745 GNUNET_CRYPTO_kdf (out, sizeof (*out),
753 * Encrypt data with the axolotl tunnel key.
755 * @param ax key material to use.
756 * @param dst Destination with @a size bytes for the encrypted data.
757 * @param src Source of the plaintext. Can overlap with @c dst, must contain @a size bytes
758 * @param size Size of the buffers at @a src and @a dst
761 t_ax_encrypt (struct CadetTunnelAxolotl *ax,
766 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
767 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
770 ax->ratchet_counter++;
771 if ( (GNUNET_YES == ax->ratchet_allowed) &&
772 ( (ratchet_messages <= ax->ratchet_counter) ||
773 (0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us)) )
775 ax->ratchet_flag = GNUNET_YES;
777 if (GNUNET_YES == ax->ratchet_flag)
779 /* Advance ratchet */
780 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
781 struct GNUNET_HashCode dh;
782 struct GNUNET_HashCode hmac;
783 static const char ctx[] = "axolotl ratchet";
788 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
789 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
792 t_ax_hmac_hash (&ax->RK,
796 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
798 &hmac, sizeof (hmac),
806 ax->ratchet_flag = GNUNET_NO;
807 ax->ratchet_allowed = GNUNET_NO;
808 ax->ratchet_counter = 0;
809 ax->ratchet_expiration
810 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
814 t_hmac_derive_key (&ax->CKs,
818 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
823 out_size = GNUNET_CRYPTO_symmetric_encrypt (src,
828 GNUNET_assert (size == out_size);
829 t_hmac_derive_key (&ax->CKs,
837 * Decrypt data with the axolotl tunnel key.
839 * @param ax key material to use.
840 * @param dst Destination for the decrypted data, must contain @a size bytes.
841 * @param src Source of the ciphertext. Can overlap with @c dst, must contain @a size bytes.
842 * @param size Size of the @a src and @a dst buffers
845 t_ax_decrypt (struct CadetTunnelAxolotl *ax,
850 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
851 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
854 t_hmac_derive_key (&ax->CKr,
858 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
862 GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
863 out_size = GNUNET_CRYPTO_symmetric_decrypt (src,
868 GNUNET_assert (out_size == size);
869 t_hmac_derive_key (&ax->CKr,
877 * Encrypt header with the axolotl header key.
879 * @param ax key material to use.
880 * @param[in|out] msg Message whose header to encrypt.
883 t_h_encrypt (struct CadetTunnelAxolotl *ax,
884 struct GNUNET_CADET_TunnelEncryptedMessage *msg)
886 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
889 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
893 out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->ax_header,
894 sizeof (struct GNUNET_CADET_AxHeader),
898 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
903 * Decrypt header with the current axolotl header key.
905 * @param ax key material to use.
906 * @param src Message whose header to decrypt.
907 * @param dst Where to decrypt header to.
910 t_h_decrypt (struct CadetTunnelAxolotl *ax,
911 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
912 struct GNUNET_CADET_TunnelEncryptedMessage *dst)
914 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
917 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
921 out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
922 sizeof (struct GNUNET_CADET_AxHeader),
926 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
931 * Delete a key from the list of skipped keys.
933 * @param ax key material to delete @a key from.
934 * @param key Key to delete.
937 delete_skipped_key (struct CadetTunnelAxolotl *ax,
938 struct CadetTunnelSkippedKey *key)
940 GNUNET_CONTAINER_DLL_remove (ax->skipped_head,
949 * Decrypt and verify data with the appropriate tunnel key and verify that the
950 * data has not been altered since it was sent by the remote peer.
952 * @param ax key material to use.
953 * @param dst Destination for the plaintext.
954 * @param src Source of the message. Can overlap with @c dst.
955 * @param size Size of the message.
956 * @return Size of the decrypted data, -1 if an error was encountered.
959 try_old_ax_keys (struct CadetTunnelAxolotl *ax,
961 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
964 struct CadetTunnelSkippedKey *key;
965 struct GNUNET_ShortHashCode *hmac;
966 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
967 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
968 struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
974 LOG (GNUNET_ERROR_TYPE_DEBUG,
975 "Trying skipped keys\n");
976 hmac = &plaintext_header.hmac;
977 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
979 /* Find a correct Header Key */
981 for (key = ax->skipped_head; NULL != key; key = key->next)
983 t_hmac (&src->ax_header,
984 sizeof (struct GNUNET_CADET_AxHeader) + esize,
988 if (0 == memcmp (hmac,
999 /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
1000 GNUNET_assert (size > sizeof (struct GNUNET_CADET_TunnelEncryptedMessage));
1001 len = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1002 GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
1004 /* Decrypt header */
1005 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
1009 res = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
1010 sizeof (struct GNUNET_CADET_AxHeader),
1013 &plaintext_header.ax_header.Ns);
1014 GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == res);
1016 /* Find the correct message key */
1017 N = ntohl (plaintext_header.ax_header.Ns);
1018 while ( (NULL != key) &&
1021 if ( (NULL == key) ||
1022 (0 != memcmp (&key->HK,
1024 sizeof (*valid_HK))) )
1027 /* Decrypt payload */
1028 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
1033 res = GNUNET_CRYPTO_symmetric_decrypt (&src[1],
1038 delete_skipped_key (ax,
1045 * Delete a key from the list of skipped keys.
1047 * @param ax key material to delete from.
1048 * @param HKr Header Key to use.
1051 store_skipped_key (struct CadetTunnelAxolotl *ax,
1052 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
1054 struct CadetTunnelSkippedKey *key;
1056 key = GNUNET_new (struct CadetTunnelSkippedKey);
1057 key->timestamp = GNUNET_TIME_absolute_get ();
1060 t_hmac_derive_key (&ax->CKr,
1064 t_hmac_derive_key (&ax->CKr,
1068 GNUNET_CONTAINER_DLL_insert (ax->skipped_head,
1077 * Stage skipped AX keys and calculate the message key.
1078 * Stores each HK and MK for skipped messages.
1080 * @param ax key material to use
1081 * @param HKr Header key.
1082 * @param Np Received meesage number.
1083 * @return #GNUNET_OK if keys were stored.
1084 * #GNUNET_SYSERR if an error ocurred (@a Np not expected).
1087 store_ax_keys (struct CadetTunnelAxolotl *ax,
1088 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1094 LOG (GNUNET_ERROR_TYPE_DEBUG,
1095 "Storing skipped keys [%u, %u)\n",
1098 if (MAX_KEY_GAP < gap)
1100 /* Avoid DoS (forcing peer to do more than #MAX_KEY_GAP HMAC operations) */
1101 /* TODO: start new key exchange on return */
1102 GNUNET_break_op (0);
1103 LOG (GNUNET_ERROR_TYPE_WARNING,
1104 "Got message %u, expected %u+\n",
1107 return GNUNET_SYSERR;
1111 /* Delayed message: don't store keys, flag to try old keys. */
1112 return GNUNET_SYSERR;
1116 store_skipped_key (ax,
1119 while (ax->skipped > MAX_SKIPPED_KEYS)
1120 delete_skipped_key (ax,
1127 * Decrypt and verify data with the appropriate tunnel key and verify that the
1128 * data has not been altered since it was sent by the remote peer.
1130 * @param ax key material to use
1131 * @param dst Destination for the plaintext.
1132 * @param src Source of the message. Can overlap with @c dst.
1133 * @param size Size of the message.
1134 * @return Size of the decrypted data, -1 if an error was encountered.
1137 t_ax_decrypt_and_validate (struct CadetTunnelAxolotl *ax,
1139 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
1142 struct GNUNET_ShortHashCode msg_hmac;
1143 struct GNUNET_HashCode hmac;
1144 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
1147 size_t esize; /* Size of encryped payload */
1149 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1151 /* Try current HK */
1152 t_hmac (&src->ax_header,
1153 sizeof (struct GNUNET_CADET_AxHeader) + esize,
1156 if (0 != memcmp (&msg_hmac,
1160 static const char ctx[] = "axolotl ratchet";
1161 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1162 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1163 struct GNUNET_HashCode dh;
1164 struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1167 t_hmac (&src->ax_header,
1168 sizeof (struct GNUNET_CADET_AxHeader) + esize,
1172 if (0 != memcmp (&msg_hmac,
1176 /* Try the skipped keys, if that fails, we're out of luck. */
1177 return try_old_ax_keys (ax,
1187 Np = ntohl (plaintext_header.ax_header.Ns);
1188 PNp = ntohl (plaintext_header.ax_header.PNs);
1189 DHRp = &plaintext_header.ax_header.DHRs;
1194 /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1195 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
1198 t_ax_hmac_hash (&ax->RK,
1201 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1203 &hmac, sizeof (hmac),
1206 /* Commit "purported" keys */
1212 ax->ratchet_allowed = GNUNET_YES;
1219 Np = ntohl (plaintext_header.ax_header.Ns);
1220 PNp = ntohl (plaintext_header.ax_header.PNs);
1222 if ( (Np != ax->Nr) &&
1223 (GNUNET_OK != store_ax_keys (ax,
1227 /* Try the skipped keys, if that fails, we're out of luck. */
1228 return try_old_ax_keys (ax,
1244 * Our tunnel became ready for the first time, notify channels
1245 * that have been waiting.
1247 * @param cls our tunnel, not used
1248 * @param key unique ID of the channel, not used
1249 * @param value the `struct CadetChannel` to notify
1250 * @return #GNUNET_OK (continue to iterate)
1253 notify_tunnel_up_cb (void *cls,
1257 struct CadetChannel *ch = value;
1259 GCCH_tunnel_up (ch);
1265 * Change the tunnel encryption state.
1266 * If the encryption state changes to OK, stop the rekey task.
1268 * @param t Tunnel whose encryption state to change, or NULL.
1269 * @param state New encryption state.
1272 GCT_change_estate (struct CadetTunnel *t,
1273 enum CadetTunnelEState state)
1275 enum CadetTunnelEState old = t->estate;
1278 LOG (GNUNET_ERROR_TYPE_DEBUG,
1279 "%s estate changed from %s to %s\n",
1284 if ( (CADET_TUNNEL_KEY_OK != old) &&
1285 (CADET_TUNNEL_KEY_OK == t->estate) )
1287 if (NULL != t->kx_task)
1289 GNUNET_SCHEDULER_cancel (t->kx_task);
1292 /* notify all channels that have been waiting */
1293 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1294 ¬ify_tunnel_up_cb,
1296 if (NULL != t->send_task)
1297 GNUNET_SCHEDULER_cancel (t->send_task);
1298 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
1305 * Send a KX message.
1307 * @param t tunnel on which to send the KX_AUTH
1308 * @param ct Tunnel and connection on which to send the KX_AUTH, NULL if
1309 * we are to find one that is ready.
1310 * @param ax axolotl key context to use
1313 send_kx (struct CadetTunnel *t,
1314 struct CadetTConnection *ct,
1315 struct CadetTunnelAxolotl *ax)
1317 struct CadetConnection *cc;
1318 struct GNUNET_MQ_Envelope *env;
1319 struct GNUNET_CADET_TunnelKeyExchangeMessage *msg;
1320 enum GNUNET_CADET_KX_Flags flags;
1323 ct = get_ready_connection (t);
1326 LOG (GNUNET_ERROR_TYPE_DEBUG,
1327 "Wanted to send %s in state %s, but no connection is ready, deferring\n",
1329 estate2s (t->estate));
1330 t->next_kx_attempt = GNUNET_TIME_absolute_get ();
1334 LOG (GNUNET_ERROR_TYPE_DEBUG,
1335 "Sending KX on %s via %s using %s in state %s\n",
1338 estate2s (t->estate));
1339 env = GNUNET_MQ_msg (msg,
1340 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX);
1341 flags = GNUNET_CADET_KX_FLAG_FORCE_REPLY; /* always for KX */
1342 msg->flags = htonl (flags);
1343 msg->cid = *GCC_get_id (cc);
1344 GNUNET_CRYPTO_ecdhe_key_get_public (ax->kx_0,
1345 &msg->ephemeral_key);
1346 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs,
1348 mark_connection_unready (ct);
1349 t->kx_retry_delay = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1350 t->next_kx_attempt = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1351 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1352 GCT_change_estate (t,
1353 CADET_TUNNEL_KEY_AX_SENT);
1354 else if (CADET_TUNNEL_KEY_AX_RECV == t->estate)
1355 GCT_change_estate (t,
1356 CADET_TUNNEL_KEY_AX_SENT_AND_RECV);
1363 * Send a KX_AUTH message.
1365 * @param t tunnel on which to send the KX_AUTH
1366 * @param ct Tunnel and connection on which to send the KX_AUTH, NULL if
1367 * we are to find one that is ready.
1368 * @param ax axolotl key context to use
1369 * @param force_reply Force the other peer to reply with a KX_AUTH message
1370 * (set if we would like to transmit right now, but cannot)
1373 send_kx_auth (struct CadetTunnel *t,
1374 struct CadetTConnection *ct,
1375 struct CadetTunnelAxolotl *ax,
1378 struct CadetConnection *cc;
1379 struct GNUNET_MQ_Envelope *env;
1380 struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg;
1381 enum GNUNET_CADET_KX_Flags flags;
1383 if ( (NULL == ct) ||
1384 (GNUNET_NO == ct->is_ready) )
1385 ct = get_ready_connection (t);
1388 LOG (GNUNET_ERROR_TYPE_DEBUG,
1389 "Wanted to send KX_AUTH on %s, but no connection is ready, deferring\n",
1391 t->next_kx_attempt = GNUNET_TIME_absolute_get ();
1392 t->kx_auth_requested = GNUNET_YES; /* queue KX_AUTH independent of estate */
1395 t->kx_auth_requested = GNUNET_NO; /* clear flag */
1397 LOG (GNUNET_ERROR_TYPE_DEBUG,
1398 "Sending KX_AUTH on %s using %s\n",
1402 env = GNUNET_MQ_msg (msg,
1403 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX_AUTH);
1404 flags = GNUNET_CADET_KX_FLAG_NONE;
1405 if (GNUNET_YES == force_reply)
1406 flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY;
1407 msg->kx.flags = htonl (flags);
1408 msg->kx.cid = *GCC_get_id (cc);
1409 GNUNET_CRYPTO_ecdhe_key_get_public (ax->kx_0,
1410 &msg->kx.ephemeral_key);
1411 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs,
1412 &msg->kx.ratchet_key);
1413 /* Compute authenticator (this is the main difference to #send_kx()) */
1414 GNUNET_CRYPTO_hash (&ax->RK,
1418 /* Compute when to be triggered again; actual job will
1419 be scheduled via #connection_ready_cb() */
1421 = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1423 = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1425 /* Send via cc, mark it as unready */
1426 mark_connection_unready (ct);
1428 /* Update state machine, unless we are already OK */
1429 if (CADET_TUNNEL_KEY_OK != t->estate)
1430 GCT_change_estate (t,
1431 CADET_TUNNEL_KEY_AX_AUTH_SENT);
1439 * Cleanup state used by @a ax.
1441 * @param ax state to free, but not memory of @a ax itself
1444 cleanup_ax (struct CadetTunnelAxolotl *ax)
1446 while (NULL != ax->skipped_head)
1447 delete_skipped_key (ax,
1449 GNUNET_assert (0 == ax->skipped);
1450 GNUNET_free_non_null (ax->kx_0);
1451 GNUNET_free_non_null (ax->DHRs);
1456 * Update our Axolotl key state based on the KX data we received.
1457 * Computes the new chain keys, and root keys, etc, and also checks
1458 * wether this is a replay of the current chain.
1460 * @param[in|out] axolotl chain key state to recompute
1461 * @param pid peer identity of the other peer
1462 * @param ephemeral_key ephemeral public key of the other peer
1463 * @param ratchet_key senders next ephemeral public key
1464 * @return #GNUNET_OK on success, #GNUNET_NO if the resulting
1465 * root key is already in @a ax and thus the KX is useless;
1466 * #GNUNET_SYSERR on hard errors (i.e. @a pid is #my_full_id)
1469 update_ax_by_kx (struct CadetTunnelAxolotl *ax,
1470 const struct GNUNET_PeerIdentity *pid,
1471 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key,
1472 const struct GNUNET_CRYPTO_EcdhePublicKey *ratchet_key)
1474 struct GNUNET_HashCode key_material[3];
1475 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
1476 const char salt[] = "CADET Axolotl salt";
1479 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1481 am_I_alice = GNUNET_YES;
1482 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1484 am_I_alice = GNUNET_NO;
1487 GNUNET_break_op (0);
1488 return GNUNET_SYSERR;
1491 if (0 == memcmp (&ax->DHRr,
1493 sizeof (*ratchet_key)))
1495 LOG (GNUNET_ERROR_TYPE_DEBUG,
1496 "Ratchet key already known. Ignoring KX.\n");
1500 ax->DHRr = *ratchet_key;
1503 if (GNUNET_YES == am_I_alice)
1505 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1506 ephemeral_key, /* B0 */
1511 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* B0 */
1512 &pid->public_key, /* A */
1517 if (GNUNET_YES == am_I_alice)
1519 GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0, /* A0 */
1520 &pid->public_key, /* B */
1525 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* A */
1526 ephemeral_key, /* B0 */
1533 /* (This is the triple-DH, we could probably safely skip this,
1534 as A0/B0 are already in the key material.) */
1535 GNUNET_CRYPTO_ecc_ecdh (ax->kx_0, /* A0 or B0 */
1536 ephemeral_key, /* B0 or A0 */
1540 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1541 salt, sizeof (salt),
1542 &key_material, sizeof (key_material),
1545 if (0 == memcmp (&ax->RK,
1549 LOG (GNUNET_ERROR_TYPE_DEBUG,
1550 "Root key of handshake already known. Ignoring KX.\n");
1555 if (GNUNET_YES == am_I_alice)
1561 ax->ratchet_flag = GNUNET_YES;
1569 ax->ratchet_flag = GNUNET_NO;
1570 ax->ratchet_expiration
1571 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
1579 * Try to redo the KX or KX_AUTH handshake, if we can.
1581 * @param cls the `struct CadetTunnel` to do KX for.
1584 retry_kx (void *cls)
1586 struct CadetTunnel *t = cls;
1587 struct CadetTunnelAxolotl *ax;
1590 LOG (GNUNET_ERROR_TYPE_DEBUG,
1591 "Trying to make KX progress on %s in state %s\n",
1593 estate2s (t->estate));
1596 case CADET_TUNNEL_KEY_UNINITIALIZED: /* first attempt */
1597 case CADET_TUNNEL_KEY_AX_SENT: /* trying again */
1602 case CADET_TUNNEL_KEY_AX_RECV:
1603 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
1604 /* We are responding, so only require reply
1605 if WE have a channel waiting. */
1606 if (NULL != t->unverified_ax)
1608 /* Send AX_AUTH so we might get this one verified */
1609 ax = t->unverified_ax;
1613 /* How can this be? */
1620 (0 == GCT_count_channels (t))
1624 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
1625 /* We are responding, so only require reply
1626 if WE have a channel waiting. */
1627 if (NULL != t->unverified_ax)
1629 /* Send AX_AUTH so we might get this one verified */
1630 ax = t->unverified_ax;
1634 /* How can this be? */
1641 (0 == GCT_count_channels (t))
1645 case CADET_TUNNEL_KEY_OK:
1646 /* Must have been the *other* peer asking us to
1647 respond with a KX_AUTH. */
1648 if (NULL != t->unverified_ax)
1650 /* Sending AX_AUTH in response to AX so we might get this one verified */
1651 ax = t->unverified_ax;
1655 /* Sending AX_AUTH in response to AX_AUTH */
1668 * Handle KX message that lacks authentication (and which will thus
1669 * only be considered authenticated after we respond with our own
1670 * KX_AUTH and finally successfully decrypt payload).
1672 * @param ct connection/tunnel combo that received encrypted message
1673 * @param msg the key exchange message
1676 GCT_handle_kx (struct CadetTConnection *ct,
1677 const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
1679 struct CadetTunnel *t = ct->t;
1680 struct CadetTunnelAxolotl *ax;
1684 memcmp (&t->ax.DHRr,
1686 sizeof (msg->ratchet_key)))
1688 LOG (GNUNET_ERROR_TYPE_DEBUG,
1689 "Got duplicate KX. Firing back KX_AUTH.\n");
1697 /* We only keep ONE unverified KX around, so if there is an existing one,
1699 if (NULL != t->unverified_ax)
1702 memcmp (&t->unverified_ax->DHRr,
1704 sizeof (msg->ratchet_key)))
1706 LOG (GNUNET_ERROR_TYPE_DEBUG,
1707 "Got duplicate unverified KX on %s. Fire back KX_AUTH again.\n",
1715 LOG (GNUNET_ERROR_TYPE_DEBUG,
1716 "Dropping old unverified KX state. Got a fresh KX for %s.\n",
1718 memset (t->unverified_ax,
1720 sizeof (struct CadetTunnelAxolotl));
1721 t->unverified_ax->DHRs = t->ax.DHRs;
1722 t->unverified_ax->kx_0 = t->ax.kx_0;
1726 LOG (GNUNET_ERROR_TYPE_DEBUG,
1727 "Creating fresh unverified KX for %s.\n",
1729 t->unverified_ax = GNUNET_new (struct CadetTunnelAxolotl);
1730 t->unverified_ax->DHRs = t->ax.DHRs;
1731 t->unverified_ax->kx_0 = t->ax.kx_0;
1733 /* Set as the 'current' RK/DHRr the one we are currently using,
1734 so that the duplicate-detection logic of
1735 #update_ax_by_kx can work. */
1736 t->unverified_ax->RK = t->ax.RK;
1737 t->unverified_ax->DHRr = t->ax.DHRr;
1738 t->unverified_attempts = 0;
1739 ax = t->unverified_ax;
1741 /* Update 'ax' by the new key material */
1742 ret = update_ax_by_kx (ax,
1743 GCP_get_id (t->destination),
1744 &msg->ephemeral_key,
1746 GNUNET_break (GNUNET_SYSERR != ret);
1747 if (GNUNET_OK != ret)
1748 return; /* duplicate KX, nothing to do */
1750 /* move ahead in our state machine */
1751 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1752 GCT_change_estate (t,
1753 CADET_TUNNEL_KEY_AX_RECV);
1754 else if (CADET_TUNNEL_KEY_AX_SENT == t->estate)
1755 GCT_change_estate (t,
1756 CADET_TUNNEL_KEY_AX_SENT_AND_RECV);
1758 /* KX is still not done, try again our end. */
1759 if (CADET_TUNNEL_KEY_OK != t->estate)
1761 if (NULL != t->kx_task)
1762 GNUNET_SCHEDULER_cancel (t->kx_task);
1764 = GNUNET_SCHEDULER_add_now (&retry_kx,
1771 * Handle KX_AUTH message.
1773 * @param ct connection/tunnel combo that received encrypted message
1774 * @param msg the key exchange message
1777 GCT_handle_kx_auth (struct CadetTConnection *ct,
1778 const struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg)
1780 struct CadetTunnel *t = ct->t;
1781 struct CadetTunnelAxolotl ax_tmp;
1782 struct GNUNET_HashCode kx_auth;
1785 if ( (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) ||
1786 (CADET_TUNNEL_KEY_AX_RECV == t->estate) )
1788 /* Confusing, we got a KX_AUTH before we even send our own
1789 KX. This should not happen. We'll send our own KX ASAP anyway,
1790 so let's ignore this here. */
1791 GNUNET_break_op (0);
1794 LOG (GNUNET_ERROR_TYPE_DEBUG,
1795 "Handling KX_AUTH message for %s\n",
1798 /* We do everything in ax_tmp until we've checked the authentication
1799 so we don't clobber anything we care about by accident. */
1802 /* Update 'ax' by the new key material */
1803 ret = update_ax_by_kx (&ax_tmp,
1804 GCP_get_id (t->destination),
1805 &msg->kx.ephemeral_key,
1806 &msg->kx.ratchet_key);
1807 if (GNUNET_OK != ret)
1809 if (GNUNET_NO == ret)
1810 GNUNET_STATISTICS_update (stats,
1811 "# redundant KX_AUTH received",
1815 GNUNET_break (0); /* connect to self!? */
1818 GNUNET_CRYPTO_hash (&ax_tmp.RK,
1821 if (0 != memcmp (&kx_auth,
1825 /* This KX_AUTH is not using the latest KX/KX_AUTH data
1826 we transmitted to the sender, refuse it, try KX again. */
1827 GNUNET_break_op (0);
1833 /* Yep, we're good. */
1835 if (NULL != t->unverified_ax)
1837 /* We got some "stale" KX before, drop that. */
1838 t->unverified_ax->DHRs = NULL; /* aliased with ax.DHRs */
1839 t->unverified_ax->kx_0 = NULL; /* aliased with ax.DHRs */
1840 cleanup_ax (t->unverified_ax);
1841 GNUNET_free (t->unverified_ax);
1842 t->unverified_ax = NULL;
1845 /* move ahead in our state machine */
1848 case CADET_TUNNEL_KEY_UNINITIALIZED:
1849 case CADET_TUNNEL_KEY_AX_RECV:
1850 /* Checked above, this is impossible. */
1853 case CADET_TUNNEL_KEY_AX_SENT: /* This is the normal case */
1854 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV: /* both peers started KX */
1855 case CADET_TUNNEL_KEY_AX_AUTH_SENT: /* both peers now did KX_AUTH */
1856 GCT_change_estate (t,
1857 CADET_TUNNEL_KEY_OK);
1859 case CADET_TUNNEL_KEY_OK:
1860 /* Did not expect another KX_AUTH, but so what, still acceptable.
1861 Nothing to do here. */
1868 /* ************************************** end core crypto ***************************** */
1872 * Compute the next free channel tunnel number for this tunnel.
1874 * @param t the tunnel
1875 * @return unused number that can uniquely identify a channel in the tunnel
1877 static struct GNUNET_CADET_ChannelTunnelNumber
1878 get_next_free_ctn (struct CadetTunnel *t)
1880 #define HIGH_BIT 0x8000000
1881 struct GNUNET_CADET_ChannelTunnelNumber ret;
1886 cmp = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1887 GCP_get_id (GCT_get_destination (t)));
1893 GNUNET_assert (0); // loopback must never go here!
1894 ctn = ntohl (t->next_ctn.cn);
1896 GNUNET_CONTAINER_multihashmap32_get (t->channels,
1899 ctn = ((ctn + 1) & (~ HIGH_BIT)) | highbit;
1901 t->next_ctn.cn = htonl (((ctn + 1) & (~ HIGH_BIT)) | highbit);
1902 ret.cn = ntohl (ctn);
1908 * Add a channel to a tunnel, and notify channel that we are ready
1909 * for transmission if we are already up. Otherwise that notification
1910 * will be done later in #notify_tunnel_up_cb().
1914 * @return unique number identifying @a ch within @a t
1916 struct GNUNET_CADET_ChannelTunnelNumber
1917 GCT_add_channel (struct CadetTunnel *t,
1918 struct CadetChannel *ch)
1920 struct GNUNET_CADET_ChannelTunnelNumber ctn;
1922 ctn = get_next_free_ctn (t);
1923 if (NULL != t->destroy_task)
1925 GNUNET_SCHEDULER_cancel (t->destroy_task);
1926 t->destroy_task = NULL;
1928 GNUNET_assert (GNUNET_YES ==
1929 GNUNET_CONTAINER_multihashmap32_put (t->channels,
1932 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1933 LOG (GNUNET_ERROR_TYPE_DEBUG,
1934 "Adding %s to %s\n",
1939 case CADET_TUNNEL_KEY_UNINITIALIZED:
1940 /* waiting for connection to start KX */
1942 case CADET_TUNNEL_KEY_AX_RECV:
1943 case CADET_TUNNEL_KEY_AX_SENT:
1944 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
1945 /* we're currently waiting for KX to complete */
1947 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
1948 /* waiting for OTHER peer to send us data,
1949 we might need to prompt more aggressively! */
1950 if (NULL == t->kx_task)
1952 = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
1956 case CADET_TUNNEL_KEY_OK:
1957 /* We are ready. Tell the new channel that we are up. */
1958 GCCH_tunnel_up (ch);
1966 * We lost a connection, remove it from our list and clean up
1967 * the connection object itself.
1969 * @param ct binding of connection to tunnel of the connection that was lost.
1972 GCT_connection_lost (struct CadetTConnection *ct)
1974 struct CadetTunnel *t = ct->t;
1976 if (GNUNET_YES == ct->is_ready)
1977 GNUNET_CONTAINER_DLL_remove (t->connection_ready_head,
1978 t->connection_ready_tail,
1981 GNUNET_CONTAINER_DLL_remove (t->connection_busy_head,
1982 t->connection_busy_tail,
1989 * Clean up connection @a ct of a tunnel.
1991 * @param cls the `struct CadetTunnel`
1992 * @param ct connection to clean up
1995 destroy_t_connection (void *cls,
1996 struct CadetTConnection *ct)
1998 struct CadetTunnel *t = cls;
1999 struct CadetConnection *cc = ct->cc;
2001 GNUNET_assert (ct->t == t);
2002 GCT_connection_lost (ct);
2003 GCC_destroy_without_tunnel (cc);
2008 * This tunnel is no longer used, destroy it.
2010 * @param cls the idle tunnel
2013 destroy_tunnel (void *cls)
2015 struct CadetTunnel *t = cls;
2016 struct CadetTunnelQueueEntry *tq;
2018 t->destroy_task = NULL;
2019 LOG (GNUNET_ERROR_TYPE_DEBUG,
2020 "Destroying idle %s\n",
2022 GNUNET_assert (0 == GCT_count_channels (t));
2023 GCT_iterate_connections (t,
2024 &destroy_t_connection,
2026 GNUNET_assert (NULL == t->connection_ready_head);
2027 GNUNET_assert (NULL == t->connection_busy_head);
2028 while (NULL != (tq = t->tq_head))
2030 if (NULL != tq->cont)
2031 tq->cont (tq->cont_cls,
2033 GCT_send_cancel (tq);
2035 GCP_drop_tunnel (t->destination,
2037 GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
2038 if (NULL != t->maintain_connections_task)
2040 GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
2041 t->maintain_connections_task = NULL;
2043 if (NULL != t->send_task)
2045 GNUNET_SCHEDULER_cancel (t->send_task);
2046 t->send_task = NULL;
2048 if (NULL != t->kx_task)
2050 GNUNET_SCHEDULER_cancel (t->kx_task);
2053 GNUNET_MST_destroy (t->mst);
2054 GNUNET_MQ_destroy (t->mq);
2055 if (NULL != t->unverified_ax)
2057 t->unverified_ax->DHRs = NULL; /* aliased with ax.DHRs */
2058 t->unverified_ax->kx_0 = NULL; /* aliased with ax.DHRs */
2059 cleanup_ax (t->unverified_ax);
2060 GNUNET_free (t->unverified_ax);
2062 cleanup_ax (&t->ax);
2063 GNUNET_assert (NULL == t->destroy_task);
2069 * Remove a channel from a tunnel.
2073 * @param ctn unique number identifying @a ch within @a t
2076 GCT_remove_channel (struct CadetTunnel *t,
2077 struct CadetChannel *ch,
2078 struct GNUNET_CADET_ChannelTunnelNumber ctn)
2080 LOG (GNUNET_ERROR_TYPE_DEBUG,
2081 "Removing %s from %s\n",
2084 GNUNET_assert (GNUNET_YES ==
2085 GNUNET_CONTAINER_multihashmap32_remove (t->channels,
2089 GCT_count_channels (t)) &&
2090 (NULL == t->destroy_task) )
2093 = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
2101 * Destroy remaining channels during shutdown.
2103 * @param cls the `struct CadetTunnel` of the channel
2104 * @param key key of the channel
2105 * @param value the `struct CadetChannel`
2106 * @return #GNUNET_OK (continue to iterate)
2109 destroy_remaining_channels (void *cls,
2113 struct CadetChannel *ch = value;
2115 GCCH_handle_remote_destroy (ch,
2122 * Destroys the tunnel @a t now, without delay. Used during shutdown.
2124 * @param t tunnel to destroy
2127 GCT_destroy_tunnel_now (struct CadetTunnel *t)
2129 GNUNET_assert (GNUNET_YES == shutting_down);
2130 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2131 &destroy_remaining_channels,
2134 GCT_count_channels (t));
2135 if (NULL != t->destroy_task)
2137 GNUNET_SCHEDULER_cancel (t->destroy_task);
2138 t->destroy_task = NULL;
2145 * Send normal payload from queue in @a t via connection @a ct.
2146 * Does nothing if our payload queue is empty.
2148 * @param t tunnel to send data from
2149 * @param ct connection to use for transmission (is ready)
2152 try_send_normal_payload (struct CadetTunnel *t,
2153 struct CadetTConnection *ct)
2155 struct CadetTunnelQueueEntry *tq;
2157 GNUNET_assert (GNUNET_YES == ct->is_ready);
2161 /* no messages pending right now */
2162 LOG (GNUNET_ERROR_TYPE_DEBUG,
2163 "Not sending payload of %s on ready %s (nothing pending)\n",
2168 /* ready to send message 'tq' on tunnel 'ct' */
2169 GNUNET_assert (t == tq->t);
2170 GNUNET_CONTAINER_DLL_remove (t->tq_head,
2173 if (NULL != tq->cid)
2174 *tq->cid = *GCC_get_id (ct->cc);
2175 mark_connection_unready (ct);
2176 LOG (GNUNET_ERROR_TYPE_DEBUG,
2177 "Sending payload of %s on %s\n",
2180 GCC_transmit (ct->cc,
2182 if (NULL != tq->cont)
2183 tq->cont (tq->cont_cls,
2184 GCC_get_id (ct->cc));
2190 * A connection is @a is_ready for transmission. Looks at our message
2191 * queue and if there is a message, sends it out via the connection.
2193 * @param cls the `struct CadetTConnection` that is @a is_ready
2194 * @param is_ready #GNUNET_YES if connection are now ready,
2195 * #GNUNET_NO if connection are no longer ready
2198 connection_ready_cb (void *cls,
2201 struct CadetTConnection *ct = cls;
2202 struct CadetTunnel *t = ct->t;
2204 if (GNUNET_NO == is_ready)
2206 LOG (GNUNET_ERROR_TYPE_DEBUG,
2207 "%s no longer ready for %s\n",
2210 mark_connection_unready (ct);
2213 GNUNET_assert (GNUNET_NO == ct->is_ready);
2214 GNUNET_CONTAINER_DLL_remove (t->connection_busy_head,
2215 t->connection_busy_tail,
2217 GNUNET_assert (0 < t->num_busy_connections);
2218 t->num_busy_connections--;
2219 ct->is_ready = GNUNET_YES;
2220 GNUNET_CONTAINER_DLL_insert_tail (t->connection_ready_head,
2221 t->connection_ready_tail,
2223 t->num_ready_connections++;
2225 LOG (GNUNET_ERROR_TYPE_DEBUG,
2226 "%s now ready for %s in state %s\n",
2229 estate2s (t->estate));
2232 case CADET_TUNNEL_KEY_UNINITIALIZED:
2233 /* Do not begin KX if WE have no channels waiting! */
2234 if (0 == GCT_count_channels (t))
2236 /* We are uninitialized, just transmit immediately,
2237 without undue delay. */
2238 if (NULL != t->kx_task)
2240 GNUNET_SCHEDULER_cancel (t->kx_task);
2247 case CADET_TUNNEL_KEY_AX_RECV:
2248 case CADET_TUNNEL_KEY_AX_SENT:
2249 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
2250 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
2251 /* we're currently waiting for KX to complete, schedule job */
2252 if (NULL == t->kx_task)
2254 = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
2258 case CADET_TUNNEL_KEY_OK:
2259 if (GNUNET_YES == t->kx_auth_requested)
2261 if (NULL != t->kx_task)
2263 GNUNET_SCHEDULER_cancel (t->kx_task);
2272 try_send_normal_payload (t,
2280 * Called when either we have a new connection, or a new message in the
2281 * queue, or some existing connection has transmission capacity. Looks
2282 * at our message queue and if there is a message, picks a connection
2285 * @param cls the `struct CadetTunnel` to process messages on
2288 trigger_transmissions (void *cls)
2290 struct CadetTunnel *t = cls;
2291 struct CadetTConnection *ct;
2293 t->send_task = NULL;
2294 if (NULL == t->tq_head)
2295 return; /* no messages pending right now */
2296 ct = get_ready_connection (t);
2298 return; /* no connections ready */
2299 try_send_normal_payload (t,
2305 * Closure for #evaluate_connection. Used to assemble summary information
2306 * about the existing connections so we can evaluate a new path.
2308 struct EvaluationSummary
2312 * Minimum length of any of our connections, `UINT_MAX` if we have none.
2314 unsigned int min_length;
2317 * Maximum length of any of our connections, 0 if we have none.
2319 unsigned int max_length;
2322 * Minimum desirability of any of our connections, UINT64_MAX if we have none.
2324 GNUNET_CONTAINER_HeapCostType min_desire;
2327 * Maximum desirability of any of our connections, 0 if we have none.
2329 GNUNET_CONTAINER_HeapCostType max_desire;
2332 * Path we are comparing against for #evaluate_connection, can be NULL.
2334 struct CadetPeerPath *path;
2337 * Connection deemed the "worst" so far encountered by #evaluate_connection,
2338 * NULL if we did not yet encounter any connections.
2340 struct CadetTConnection *worst;
2343 * Numeric score of @e worst, only set if @e worst is non-NULL.
2348 * Set to #GNUNET_YES if we have a connection over @e path already.
2356 * Evaluate a connection, updating our summary information in @a cls about
2357 * what kinds of connections we have.
2359 * @param cls the `struct EvaluationSummary *` to update
2360 * @param ct a connection to include in the summary
2363 evaluate_connection (void *cls,
2364 struct CadetTConnection *ct)
2366 struct EvaluationSummary *es = cls;
2367 struct CadetConnection *cc = ct->cc;
2368 struct CadetPeerPath *ps = GCC_get_path (cc);
2369 const struct CadetConnectionMetrics *metrics;
2370 GNUNET_CONTAINER_HeapCostType ct_desirability;
2371 struct GNUNET_TIME_Relative uptime;
2372 struct GNUNET_TIME_Relative last_use;
2375 double success_rate;
2379 LOG (GNUNET_ERROR_TYPE_DEBUG,
2380 "Ignoring duplicate path %s.\n",
2381 GCPP_2s (es->path));
2382 es->duplicate = GNUNET_YES;
2385 ct_desirability = GCPP_get_desirability (ps);
2386 ct_length = GCPP_get_length (ps);
2387 metrics = GCC_get_metrics (cc);
2388 uptime = GNUNET_TIME_absolute_get_duration (metrics->age);
2389 last_use = GNUNET_TIME_absolute_get_duration (metrics->last_use);
2390 /* We add 1.0 here to avoid division by zero. */
2391 success_rate = (metrics->num_acked_transmissions + 1.0) / (metrics->num_successes + 1.0);
2394 + 100.0 / (1.0 + ct_length) /* longer paths = better */
2395 + sqrt (uptime.rel_value_us / 60000000LL) /* larger uptime = better */
2396 - last_use.rel_value_us / 1000L; /* longer idle = worse */
2397 score *= success_rate; /* weigh overall by success rate */
2399 if ( (NULL == es->worst) ||
2400 (score < es->worst_score) )
2403 es->worst_score = score;
2405 es->min_length = GNUNET_MIN (es->min_length,
2407 es->max_length = GNUNET_MAX (es->max_length,
2409 es->min_desire = GNUNET_MIN (es->min_desire,
2411 es->max_desire = GNUNET_MAX (es->max_desire,
2417 * Consider using the path @a p for the tunnel @a t.
2418 * The tunnel destination is at offset @a off in path @a p.
2420 * @param cls our tunnel
2421 * @param path a path to our destination
2422 * @param off offset of the destination on path @a path
2423 * @return #GNUNET_YES (should keep iterating)
2426 consider_path_cb (void *cls,
2427 struct CadetPeerPath *path,
2430 struct CadetTunnel *t = cls;
2431 struct EvaluationSummary es;
2432 struct CadetTConnection *ct;
2434 GNUNET_assert (off < GCPP_get_length (path));
2435 es.min_length = UINT_MAX;
2438 es.min_desire = UINT64_MAX;
2440 es.duplicate = GNUNET_NO;
2443 /* Compute evaluation summary over existing connections. */
2444 GCT_iterate_connections (t,
2445 &evaluate_connection,
2447 if (GNUNET_YES == es.duplicate)
2450 /* FIXME: not sure we should really just count
2451 'num_connections' here, as they may all have
2452 consistently failed to connect. */
2454 /* We iterate by increasing path length; if we have enough paths and
2455 this one is more than twice as long than what we are currently
2456 using, then ignore all of these super-long ones! */
2457 if ( (GCT_count_any_connections (t) > DESIRED_CONNECTIONS_PER_TUNNEL) &&
2458 (es.min_length * 2 < off) &&
2459 (es.max_length < off) )
2461 LOG (GNUNET_ERROR_TYPE_DEBUG,
2462 "Ignoring paths of length %u, they are way too long.\n",
2466 /* If we have enough paths and this one looks no better, ignore it. */
2467 if ( (GCT_count_any_connections (t) >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
2468 (es.min_length < GCPP_get_length (path)) &&
2469 (es.min_desire > GCPP_get_desirability (path)) &&
2470 (es.max_length < off) )
2472 LOG (GNUNET_ERROR_TYPE_DEBUG,
2473 "Ignoring path (%u/%llu) to %s, got something better already.\n",
2474 GCPP_get_length (path),
2475 (unsigned long long) GCPP_get_desirability (path),
2476 GCP_2s (t->destination));
2480 /* Path is interesting (better by some metric, or we don't have
2481 enough paths yet). */
2482 ct = GNUNET_new (struct CadetTConnection);
2483 ct->created = GNUNET_TIME_absolute_get ();
2485 ct->cc = GCC_create (t->destination,
2488 GNUNET_CADET_OPTION_DEFAULT, /* FIXME: set based on what channels want/need! */
2490 &connection_ready_cb,
2493 /* FIXME: schedule job to kill connection (and path?) if it takes
2494 too long to get ready! (And track performance data on how long
2495 other connections took with the tunnel!)
2496 => Note: to be done within 'connection'-logic! */
2497 GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
2498 t->connection_busy_tail,
2500 t->num_busy_connections++;
2501 LOG (GNUNET_ERROR_TYPE_DEBUG,
2502 "Found interesting path %s for %s, created %s\n",
2511 * Function called to maintain the connections underlying our tunnel.
2512 * Tries to maintain (incl. tear down) connections for the tunnel, and
2513 * if there is a significant change, may trigger transmissions.
2515 * Basically, needs to check if there are connections that perform
2516 * badly, and if so eventually kill them and trigger a replacement.
2517 * The strategy is to open one more connection than
2518 * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
2519 * least-performing one, and then inquire for new ones.
2521 * @param cls the `struct CadetTunnel`
2524 maintain_connections_cb (void *cls)
2526 struct CadetTunnel *t = cls;
2527 struct GNUNET_TIME_Relative delay;
2528 struct EvaluationSummary es;
2530 t->maintain_connections_task = NULL;
2531 LOG (GNUNET_ERROR_TYPE_DEBUG,
2532 "Performing connection maintenance for %s.\n",
2535 es.min_length = UINT_MAX;
2538 es.min_desire = UINT64_MAX;
2541 es.duplicate = GNUNET_NO;
2542 GCT_iterate_connections (t,
2543 &evaluate_connection,
2545 if ( (NULL != es.worst) &&
2546 (GCT_count_any_connections (t) > DESIRED_CONNECTIONS_PER_TUNNEL) )
2548 /* Clear out worst-performing connection 'es.worst'. */
2549 destroy_t_connection (t,
2553 /* Consider additional paths */
2554 (void) GCP_iterate_paths (t->destination,
2558 /* FIXME: calculate when to try again based on how well we are doing;
2559 in particular, if we have to few connections, we might be able
2560 to do without this (as PATHS should tell us whenever a new path
2561 is available instantly; however, need to make sure this job is
2562 restarted after that happens).
2563 Furthermore, if the paths we do know are in a reasonably narrow
2564 quality band and are plentyful, we might also consider us stabilized
2565 and then reduce the frequency accordingly. */
2566 delay = GNUNET_TIME_UNIT_MINUTES;
2567 t->maintain_connections_task
2568 = GNUNET_SCHEDULER_add_delayed (delay,
2569 &maintain_connections_cb,
2575 * Consider using the path @a p for the tunnel @a t.
2576 * The tunnel destination is at offset @a off in path @a p.
2578 * @param cls our tunnel
2579 * @param path a path to our destination
2580 * @param off offset of the destination on path @a path
2583 GCT_consider_path (struct CadetTunnel *t,
2584 struct CadetPeerPath *p,
2587 (void) consider_path_cb (t,
2594 * We got a keepalive. Track in statistics.
2596 * @param cls the `struct CadetTunnel` for which we decrypted the message
2597 * @param msg the message we received on the tunnel
2600 handle_plaintext_keepalive (void *cls,
2601 const struct GNUNET_MessageHeader *msg)
2603 struct CadetTunnel *t = cls;
2605 LOG (GNUNET_ERROR_TYPE_DEBUG,
2606 "Received KEEPALIVE on %s\n",
2608 GNUNET_STATISTICS_update (stats,
2609 "# keepalives received",
2616 * Check that @a msg is well-formed.
2618 * @param cls the `struct CadetTunnel` for which we decrypted the message
2619 * @param msg the message we received on the tunnel
2620 * @return #GNUNET_OK (any variable-size payload goes)
2623 check_plaintext_data (void *cls,
2624 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2631 * We received payload data for a channel. Locate the channel
2632 * and process the data, or return an error if the channel is unknown.
2634 * @param cls the `struct CadetTunnel` for which we decrypted the message
2635 * @param msg the message we received on the tunnel
2638 handle_plaintext_data (void *cls,
2639 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2641 struct CadetTunnel *t = cls;
2642 struct CadetChannel *ch;
2644 ch = lookup_channel (t,
2648 /* We don't know about such a channel, might have been destroyed on our
2649 end in the meantime, or never existed. Send back a DESTROY. */
2650 LOG (GNUNET_ERROR_TYPE_DEBUG,
2651 "Receicved %u bytes of application data for unknown channel %u, sending DESTROY\n",
2652 (unsigned int) (ntohs (msg->header.size) - sizeof (*msg)),
2653 ntohl (msg->ctn.cn));
2654 GCT_send_channel_destroy (t,
2658 GCCH_handle_channel_plaintext_data (ch,
2659 GCC_get_id (t->current_ct->cc),
2665 * We received an acknowledgement for data we sent on a channel.
2666 * Locate the channel and process it, or return an error if the
2667 * channel is unknown.
2669 * @param cls the `struct CadetTunnel` for which we decrypted the message
2670 * @param ack the message we received on the tunnel
2673 handle_plaintext_data_ack (void *cls,
2674 const struct GNUNET_CADET_ChannelDataAckMessage *ack)
2676 struct CadetTunnel *t = cls;
2677 struct CadetChannel *ch;
2679 ch = lookup_channel (t,
2683 /* We don't know about such a channel, might have been destroyed on our
2684 end in the meantime, or never existed. Send back a DESTROY. */
2685 LOG (GNUNET_ERROR_TYPE_DEBUG,
2686 "Receicved DATA_ACK for unknown channel %u, sending DESTROY\n",
2687 ntohl (ack->ctn.cn));
2688 GCT_send_channel_destroy (t,
2692 GCCH_handle_channel_plaintext_data_ack (ch,
2693 GCC_get_id (t->current_ct->cc),
2699 * We have received a request to open a channel to a port from
2700 * another peer. Creates the incoming channel.
2702 * @param cls the `struct CadetTunnel` for which we decrypted the message
2703 * @param copen the message we received on the tunnel
2706 handle_plaintext_channel_open (void *cls,
2707 const struct GNUNET_CADET_ChannelOpenMessage *copen)
2709 struct CadetTunnel *t = cls;
2710 struct CadetChannel *ch;
2712 ch = GNUNET_CONTAINER_multihashmap32_get (t->channels,
2713 ntohl (copen->ctn.cn));
2716 LOG (GNUNET_ERROR_TYPE_DEBUG,
2717 "Receicved duplicate channel OPEN on port %s from %s (%s), resending ACK\n",
2718 GNUNET_h2s (&copen->port),
2721 GCCH_handle_duplicate_open (ch,
2722 GCC_get_id (t->current_ct->cc));
2725 LOG (GNUNET_ERROR_TYPE_DEBUG,
2726 "Receicved channel OPEN on port %s from %s\n",
2727 GNUNET_h2s (&copen->port),
2729 ch = GCCH_channel_incoming_new (t,
2732 ntohl (copen->opt));
2733 if (NULL != t->destroy_task)
2735 GNUNET_SCHEDULER_cancel (t->destroy_task);
2736 t->destroy_task = NULL;
2738 GNUNET_assert (GNUNET_OK ==
2739 GNUNET_CONTAINER_multihashmap32_put (t->channels,
2740 ntohl (copen->ctn.cn),
2742 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2747 * Send a DESTROY message via the tunnel.
2749 * @param t the tunnel to transmit over
2750 * @param ctn ID of the channel to destroy
2753 GCT_send_channel_destroy (struct CadetTunnel *t,
2754 struct GNUNET_CADET_ChannelTunnelNumber ctn)
2756 struct GNUNET_CADET_ChannelManageMessage msg;
2758 LOG (GNUNET_ERROR_TYPE_DEBUG,
2759 "Sending DESTORY message for channel ID %u\n",
2761 msg.header.size = htons (sizeof (msg));
2762 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2763 msg.reserved = htonl (0);
2773 * We have received confirmation from the target peer that the
2774 * given channel could be established (the port is open).
2777 * @param cls the `struct CadetTunnel` for which we decrypted the message
2778 * @param cm the message we received on the tunnel
2781 handle_plaintext_channel_open_ack (void *cls,
2782 const struct GNUNET_CADET_ChannelManageMessage *cm)
2784 struct CadetTunnel *t = cls;
2785 struct CadetChannel *ch;
2787 ch = lookup_channel (t,
2791 /* We don't know about such a channel, might have been destroyed on our
2792 end in the meantime, or never existed. Send back a DESTROY. */
2793 LOG (GNUNET_ERROR_TYPE_DEBUG,
2794 "Received channel OPEN_ACK for unknown channel %u, sending DESTROY\n",
2795 ntohl (cm->ctn.cn));
2796 GCT_send_channel_destroy (t,
2800 LOG (GNUNET_ERROR_TYPE_DEBUG,
2801 "Received channel OPEN_ACK on channel %s from %s\n",
2804 GCCH_handle_channel_open_ack (ch,
2805 GCC_get_id (t->current_ct->cc));
2810 * We received a message saying that a channel should be destroyed.
2811 * Pass it on to the correct channel.
2813 * @param cls the `struct CadetTunnel` for which we decrypted the message
2814 * @param cm the message we received on the tunnel
2817 handle_plaintext_channel_destroy (void *cls,
2818 const struct GNUNET_CADET_ChannelManageMessage *cm)
2820 struct CadetTunnel *t = cls;
2821 struct CadetChannel *ch;
2823 ch = lookup_channel (t,
2827 /* We don't know about such a channel, might have been destroyed on our
2828 end in the meantime, or never existed. */
2829 LOG (GNUNET_ERROR_TYPE_DEBUG,
2830 "Received channel DESTORY for unknown channel %u. Ignoring.\n",
2831 ntohl (cm->ctn.cn));
2834 LOG (GNUNET_ERROR_TYPE_DEBUG,
2835 "Receicved channel DESTROY on %s from %s\n",
2838 GCCH_handle_remote_destroy (ch,
2839 GCC_get_id (t->current_ct->cc));
2844 * Handles a message we decrypted, by injecting it into
2845 * our message queue (which will do the dispatching).
2847 * @param cls the `struct CadetTunnel` that got the message
2848 * @param msg the message
2849 * @return #GNUNET_OK (continue to process)
2852 handle_decrypted (void *cls,
2853 const struct GNUNET_MessageHeader *msg)
2855 struct CadetTunnel *t = cls;
2857 GNUNET_assert (NULL != t->current_ct);
2858 GNUNET_MQ_inject_message (t->mq,
2865 * Function called if we had an error processing
2866 * an incoming decrypted message.
2868 * @param cls the `struct CadetTunnel`
2869 * @param error error code
2872 decrypted_error_cb (void *cls,
2873 enum GNUNET_MQ_Error error)
2875 GNUNET_break_op (0);
2880 * Create a tunnel to @a destionation. Must only be called
2881 * from within #GCP_get_tunnel().
2883 * @param destination where to create the tunnel to
2884 * @return new tunnel to @a destination
2886 struct CadetTunnel *
2887 GCT_create_tunnel (struct CadetPeer *destination)
2889 struct CadetTunnel *t = GNUNET_new (struct CadetTunnel);
2890 struct GNUNET_MQ_MessageHandler handlers[] = {
2891 GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
2892 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
2893 struct GNUNET_MessageHeader,
2895 GNUNET_MQ_hd_var_size (plaintext_data,
2896 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
2897 struct GNUNET_CADET_ChannelAppDataMessage,
2899 GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
2900 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
2901 struct GNUNET_CADET_ChannelDataAckMessage,
2903 GNUNET_MQ_hd_fixed_size (plaintext_channel_open,
2904 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
2905 struct GNUNET_CADET_ChannelOpenMessage,
2907 GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack,
2908 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
2909 struct GNUNET_CADET_ChannelManageMessage,
2911 GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
2912 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
2913 struct GNUNET_CADET_ChannelManageMessage,
2915 GNUNET_MQ_handler_end ()
2918 t->kx_retry_delay = INITIAL_KX_RETRY_DELAY;
2919 new_ephemeral (&t->ax);
2920 t->ax.kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
2921 t->destination = destination;
2922 t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
2923 t->maintain_connections_task
2924 = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
2926 t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
2931 &decrypted_error_cb,
2933 t->mst = GNUNET_MST_create (&handle_decrypted,
2940 * Add a @a connection to the @a tunnel.
2943 * @param cid connection identifer to use for the connection
2944 * @param options options for the connection
2945 * @param path path to use for the connection
2946 * @return #GNUNET_OK on success,
2947 * #GNUNET_SYSERR on failure (duplicate connection)
2950 GCT_add_inbound_connection (struct CadetTunnel *t,
2951 const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
2952 enum GNUNET_CADET_ChannelOption options,
2953 struct CadetPeerPath *path)
2955 struct CadetTConnection *ct;
2957 ct = GNUNET_new (struct CadetTConnection);
2958 ct->created = GNUNET_TIME_absolute_get ();
2960 ct->cc = GCC_create_inbound (t->destination,
2965 &connection_ready_cb,
2969 LOG (GNUNET_ERROR_TYPE_DEBUG,
2970 "%s refused inbound %s (duplicate)\n",
2974 return GNUNET_SYSERR;
2976 /* FIXME: schedule job to kill connection (and path?) if it takes
2977 too long to get ready! (And track performance data on how long
2978 other connections took with the tunnel!)
2979 => Note: to be done within 'connection'-logic! */
2980 GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
2981 t->connection_busy_tail,
2983 t->num_busy_connections++;
2984 LOG (GNUNET_ERROR_TYPE_DEBUG,
2993 * Handle encrypted message.
2995 * @param ct connection/tunnel combo that received encrypted message
2996 * @param msg the encrypted message to decrypt
2999 GCT_handle_encrypted (struct CadetTConnection *ct,
3000 const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
3002 struct CadetTunnel *t = ct->t;
3003 uint16_t size = ntohs (msg->header.size);
3004 char cbuf [size] GNUNET_ALIGN;
3005 ssize_t decrypted_size;
3007 LOG (GNUNET_ERROR_TYPE_DEBUG,
3008 "%s received %u bytes of encrypted data in state %d\n",
3010 (unsigned int) size,
3015 case CADET_TUNNEL_KEY_UNINITIALIZED:
3016 case CADET_TUNNEL_KEY_AX_RECV:
3017 /* We did not even SEND our KX, how can the other peer
3018 send us encrypted data? */
3019 GNUNET_break_op (0);
3021 case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
3022 /* We send KX, and other peer send KX to us at the same time.
3023 Neither KX is AUTH'ed, so let's try KX_AUTH this time. */
3024 GNUNET_STATISTICS_update (stats,
3025 "# received encrypted without KX_AUTH",
3028 if (NULL != t->kx_task)
3030 GNUNET_SCHEDULER_cancel (t->kx_task);
3038 case CADET_TUNNEL_KEY_AX_SENT:
3039 /* We did not get the KX of the other peer, but that
3040 might have been lost. Send our KX again immediately. */
3041 GNUNET_STATISTICS_update (stats,
3042 "# received encrypted without KX",
3045 if (NULL != t->kx_task)
3047 GNUNET_SCHEDULER_cancel (t->kx_task);
3054 case CADET_TUNNEL_KEY_AX_AUTH_SENT:
3055 /* Great, first payload, we might graduate to OK! */
3056 case CADET_TUNNEL_KEY_OK:
3057 /* We are up and running, all good. */
3061 GNUNET_STATISTICS_update (stats,
3062 "# received encrypted",
3065 decrypted_size = -1;
3066 if (CADET_TUNNEL_KEY_OK == t->estate)
3068 /* We have well-established key material available,
3069 try that. (This is the common case.) */
3070 decrypted_size = t_ax_decrypt_and_validate (&t->ax,
3076 if ( (-1 == decrypted_size) &&
3077 (NULL != t->unverified_ax) )
3079 /* We have un-authenticated KX material available. We should try
3080 this as a back-up option, in case the sender crashed and
3082 decrypted_size = t_ax_decrypt_and_validate (t->unverified_ax,
3086 if (-1 != decrypted_size)
3088 /* It worked! Treat this as authentication of the AX data! */
3089 t->ax.DHRs = NULL; /* aliased with ax.DHRs */
3090 t->ax.kx_0 = NULL; /* aliased with ax.DHRs */
3091 cleanup_ax (&t->ax);
3092 t->ax = *t->unverified_ax;
3093 GNUNET_free (t->unverified_ax);
3094 t->unverified_ax = NULL;
3096 if (CADET_TUNNEL_KEY_AX_AUTH_SENT == t->estate)
3098 /* First time it worked, move tunnel into production! */
3099 GCT_change_estate (t,
3100 CADET_TUNNEL_KEY_OK);
3101 if (NULL != t->send_task)
3102 GNUNET_SCHEDULER_cancel (t->send_task);
3103 t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
3107 if (NULL != t->unverified_ax)
3109 /* We had unverified KX material that was useless; so increment
3110 counter and eventually move to ignore it. Note that we even do
3111 this increment if we successfully decrypted with the old KX
3112 material and thus didn't even both with the new one. This is
3113 the ideal case, as a malicious injection of bogus KX data
3114 basically only causes us to increment a counter a few times. */
3115 t->unverified_attempts++;
3116 LOG (GNUNET_ERROR_TYPE_DEBUG,
3117 "Failed to decrypt message with unverified KX data %u times\n",
3118 t->unverified_attempts);
3119 if (t->unverified_attempts > MAX_UNVERIFIED_ATTEMPTS)
3121 t->unverified_ax->DHRs = NULL; /* aliased with ax.DHRs */
3122 t->unverified_ax->kx_0 = NULL; /* aliased with ax.DHRs */
3123 cleanup_ax (t->unverified_ax);
3124 GNUNET_free (t->unverified_ax);
3125 t->unverified_ax = NULL;
3129 if (-1 == decrypted_size)
3131 /* Decryption failed for good, complain. */
3132 GNUNET_break_op (0);
3133 LOG (GNUNET_ERROR_TYPE_WARNING,
3134 "%s failed to decrypt and validate encrypted data\n",
3136 GNUNET_STATISTICS_update (stats,
3137 "# unable to decrypt",
3143 /* The MST will ultimately call #handle_decrypted() on each message. */
3145 GNUNET_break_op (GNUNET_OK ==
3146 GNUNET_MST_from_buffer (t->mst,
3151 t->current_ct = NULL;
3156 * Sends an already built message on a tunnel, encrypting it and
3157 * choosing the best connection if not provided.
3159 * @param message Message to send. Function modifies it.
3160 * @param t Tunnel on which this message is transmitted.
3161 * @param cont Continuation to call once message is really sent.
3162 * @param cont_cls Closure for @c cont.
3163 * @return Handle to cancel message
3165 struct CadetTunnelQueueEntry *
3166 GCT_send (struct CadetTunnel *t,
3167 const struct GNUNET_MessageHeader *message,
3168 GCT_SendContinuation cont,
3171 struct CadetTunnelQueueEntry *tq;
3172 uint16_t payload_size;
3173 struct GNUNET_MQ_Envelope *env;
3174 struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
3176 if (CADET_TUNNEL_KEY_OK != t->estate)
3181 payload_size = ntohs (message->size);
3182 LOG (GNUNET_ERROR_TYPE_DEBUG,
3183 "Encrypting %u bytes for %s\n",
3184 (unsigned int) payload_size,
3186 env = GNUNET_MQ_msg_extra (ax_msg,
3188 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
3189 t_ax_encrypt (&t->ax,
3193 ax_msg->ax_header.Ns = htonl (t->ax.Ns++);
3194 ax_msg->ax_header.PNs = htonl (t->ax.PNs);
3195 /* FIXME: we should do this once, not once per message;
3196 this is a point multiplication, and DHRs does not
3197 change all the time. */
3198 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax.DHRs,
3199 &ax_msg->ax_header.DHRs);
3200 t_h_encrypt (&t->ax,
3202 t_hmac (&ax_msg->ax_header,
3203 sizeof (struct GNUNET_CADET_AxHeader) + payload_size,
3208 tq = GNUNET_malloc (sizeof (*tq));
3211 tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
3213 tq->cont_cls = cont_cls;
3214 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
3217 if (NULL != t->send_task)
3218 GNUNET_SCHEDULER_cancel (t->send_task);
3220 = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
3227 * Cancel a previously sent message while it's in the queue.
3229 * ONLY can be called before the continuation given to the send
3230 * function is called. Once the continuation is called, the message is
3231 * no longer in the queue!
3233 * @param tq Handle to the queue entry to cancel.
3236 GCT_send_cancel (struct CadetTunnelQueueEntry *tq)
3238 struct CadetTunnel *t = tq->t;
3240 GNUNET_CONTAINER_DLL_remove (t->tq_head,
3243 GNUNET_MQ_discard (tq->env);
3249 * Iterate over all connections of a tunnel.
3251 * @param t Tunnel whose connections to iterate.
3252 * @param iter Iterator.
3253 * @param iter_cls Closure for @c iter.
3256 GCT_iterate_connections (struct CadetTunnel *t,
3257 GCT_ConnectionIterator iter,
3260 struct CadetTConnection *n;
3261 for (struct CadetTConnection *ct = t->connection_ready_head;
3269 for (struct CadetTConnection *ct = t->connection_busy_head;
3281 * Closure for #iterate_channels_cb.
3288 GCT_ChannelIterator iter;
3291 * Closure for @e iter.
3298 * Helper function for #GCT_iterate_channels.
3300 * @param cls the `struct ChanIterCls`
3302 * @param value a `struct CadetChannel`
3303 * @return #GNUNET_OK
3306 iterate_channels_cb (void *cls,
3310 struct ChanIterCls *ctx = cls;
3311 struct CadetChannel *ch = value;
3313 ctx->iter (ctx->iter_cls,
3320 * Iterate over all channels of a tunnel.
3322 * @param t Tunnel whose channels to iterate.
3323 * @param iter Iterator.
3324 * @param iter_cls Closure for @c iter.
3327 GCT_iterate_channels (struct CadetTunnel *t,
3328 GCT_ChannelIterator iter,
3331 struct ChanIterCls ctx;
3334 ctx.iter_cls = iter_cls;
3335 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
3336 &iterate_channels_cb,
3343 * Call #GCCH_debug() on a channel.
3345 * @param cls points to the log level to use
3347 * @param value the `struct CadetChannel` to dump
3348 * @return #GNUNET_OK (continue iteration)
3351 debug_channel (void *cls,
3355 const enum GNUNET_ErrorType *level = cls;
3356 struct CadetChannel *ch = value;
3358 GCCH_debug (ch, *level);
3363 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
3367 * Log all possible info about the tunnel state.
3369 * @param t Tunnel to debug.
3370 * @param level Debug level to use.
3373 GCT_debug (const struct CadetTunnel *t,
3374 enum GNUNET_ErrorType level)
3376 struct CadetTConnection *iter_c;
3379 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
3381 __FILE__, __FUNCTION__, __LINE__);
3386 "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
3388 estate2s (t->estate),
3390 GCT_count_any_connections (t));
3393 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
3397 "TTT connections:\n");
3398 for (iter_c = t->connection_ready_head; NULL != iter_c; iter_c = iter_c->next)
3399 GCC_debug (iter_c->cc,
3401 for (iter_c = t->connection_busy_head; NULL != iter_c; iter_c = iter_c->next)
3402 GCC_debug (iter_c->cc,
3406 "TTT TUNNEL END\n");
3410 /* end of gnunet-service-cadet-new_tunnels.c */