3 This file is part of GNUnet.
4 Copyright (C) 2013, 2017 GNUnet e.V.
6 GNUnet is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published
8 by the Free Software Foundation; either version 3, or (at your
9 option) any later version.
11 GNUnet is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNUnet; see the file COPYING. If not, write to the
18 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19 Boston, MA 02110-1301, USA.
23 * @file cadet/gnunet-service-cadet-new_tunnels.c
24 * @brief Information we track per tunnel.
25 * @author Bartlomiej Polot
26 * @author Christian Grothoff
29 * - when managing connections, distinguish those that
30 * have (recently) had traffic from those that were
31 * never ready (or not recently)
32 * - clean up KX logic!
35 #include "gnunet_util_lib.h"
36 #include "gnunet_signatures.h"
37 #include "cadet_protocol.h"
38 #include "cadet_path.h"
39 #include "gnunet-service-cadet-new.h"
40 #include "gnunet-service-cadet-new_channel.h"
41 #include "gnunet-service-cadet-new_connection.h"
42 #include "gnunet-service-cadet-new_tunnels.h"
43 #include "gnunet-service-cadet-new_peer.h"
44 #include "gnunet-service-cadet-new_paths.h"
47 #define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__)
51 * How long do we wait until tearing down an idle tunnel?
53 #define IDLE_DESTROY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90)
56 * Yuck, replace by 'offsetof' expression?
59 #define AX_HEADER_SIZE (sizeof (uint32_t) * 2\
60 + sizeof (struct GNUNET_CRYPTO_EcdhePublicKey))
64 * Maximum number of skipped keys we keep in memory per tunnel.
66 #define MAX_SKIPPED_KEYS 64
69 * Maximum number of keys (and thus ratchet steps) we are willing to
70 * skip before we decide this is either a bogus packet or a DoS-attempt.
72 #define MAX_KEY_GAP 256
76 * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
78 struct CadetTunnelSkippedKey
83 struct CadetTunnelSkippedKey *next;
88 struct CadetTunnelSkippedKey *prev;
91 * When was this key stored (for timeout).
93 struct GNUNET_TIME_Absolute timestamp;
98 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
103 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
106 * Key number for a given HK.
113 * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
115 struct CadetTunnelAxolotl
118 * A (double linked) list of stored message keys and associated header keys
119 * for "skipped" messages, i.e. messages that have not been
120 * received despite the reception of more recent messages, (head).
122 struct CadetTunnelSkippedKey *skipped_head;
125 * Skipped messages' keys DLL, tail.
127 struct CadetTunnelSkippedKey *skipped_tail;
130 * 32-byte root key which gets updated by DH ratchet.
132 struct GNUNET_CRYPTO_SymmetricSessionKey RK;
135 * 32-byte header key (send).
137 struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
140 * 32-byte header key (recv)
142 struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
145 * 32-byte next header key (send).
147 struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
150 * 32-byte next header key (recv).
152 struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
155 * 32-byte chain keys (used for forward-secrecy updating, send).
157 struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
160 * 32-byte chain keys (used for forward-secrecy updating, recv).
162 struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
165 * ECDH for key exchange (A0 / B0).
167 struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
170 * ECDH Ratchet key (send).
172 struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
175 * ECDH Ratchet key (recv).
177 struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
180 * When does this ratchet expire and a new one is triggered.
182 struct GNUNET_TIME_Absolute ratchet_expiration;
185 * Number of elements in @a skipped_head <-> @a skipped_tail.
187 unsigned int skipped;
190 * Message number (reset to 0 with each new ratchet, next message to send).
195 * Message number (reset to 0 with each new ratchet, next message to recv).
200 * Previous message numbers (# of msgs sent under prev ratchet)
205 * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
210 * Number of messages recieved since our last ratchet advance.
211 * - If this counter = 0, we cannot send a new ratchet key in next msg.
212 * - If this counter > 0, we can (but don't yet have to) send a new key.
214 unsigned int ratchet_allowed;
217 * Number of messages recieved since our last ratchet advance.
218 * - If this counter = 0, we cannot send a new ratchet key in next msg.
219 * - If this counter > 0, we can (but don't yet have to) send a new key.
221 unsigned int ratchet_counter;
227 * Entry in list of connections used by tunnel, with metadata.
229 struct CadetTConnection
234 struct CadetTConnection *next;
239 struct CadetTConnection *prev;
244 struct CadetConnection *cc;
247 * Tunnel this connection belongs to.
249 struct CadetTunnel *t;
252 * Creation time, to keep oldest connection alive.
254 struct GNUNET_TIME_Absolute created;
257 * Connection throughput, to keep fastest connection alive.
264 * Struct used to save messages in a non-ready tunnel to send once connected.
266 struct CadetTunnelQueueEntry
269 * We are entries in a DLL
271 struct CadetTunnelQueueEntry *next;
274 * We are entries in a DLL
276 struct CadetTunnelQueueEntry *prev;
279 * Tunnel these messages belong in.
281 struct CadetTunnel *t;
284 * Continuation to call once sent (on the channel layer).
286 GNUNET_SCHEDULER_TaskCallback cont;
289 * Closure for @c cont.
294 * Envelope of message to send follows.
296 struct GNUNET_MQ_Envelope *env;
299 * Where to put the connection identifier into the payload
300 * of the message in @e env once we have it?
302 struct GNUNET_CADET_ConnectionTunnelIdentifier *cid;
307 * Struct containing all information regarding a tunnel to a peer.
312 * Destination of the tunnel.
314 struct CadetPeer *destination;
317 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own
318 * ephemeral key changes.
320 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
323 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
325 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
328 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
330 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
335 struct CadetTunnelAxolotl ax;
338 * State of the tunnel connectivity.
340 enum CadetTunnelCState cstate;
343 * State of the tunnel encryption.
345 enum CadetTunnelEState estate;
348 * Task to start the rekey process.
350 struct GNUNET_SCHEDULER_Task *rekey_task;
353 * DLL of connections that are actively used to reach the destination peer.
355 struct CadetTConnection *connection_head;
358 * DLL of connections that are actively used to reach the destination peer.
360 struct CadetTConnection *connection_tail;
363 * Channels inside this tunnel. Maps
364 * `struct GCT_ChannelTunnelNumber` to a `struct CadetChannel`.
366 struct GNUNET_CONTAINER_MultiHashMap32 *channels;
369 * Channel ID for the next created channel in this tunnel.
371 struct GCT_ChannelTunnelNumber next_chid;
374 * Queued messages, to transmit once tunnel gets connected.
376 struct CadetTunnelQueueEntry *tq_head;
379 * Queued messages, to transmit once tunnel gets connected.
381 struct CadetTunnelQueueEntry *tq_tail;
384 * Task scheduled if there are no more channels using the tunnel.
386 struct GNUNET_SCHEDULER_Task *destroy_task;
389 * Task to trim connections if too many are present.
391 struct GNUNET_SCHEDULER_Task *maintain_connections_task;
394 * Ephemeral message in the queue (to avoid queueing more than one).
396 struct CadetConnectionQueue *ephm_hKILL;
399 * Pong message in the queue.
401 struct CadetConnectionQueue *pong_hKILL;
404 * Number of connections in the @e connection_head DLL.
406 unsigned int num_connections;
409 * Number of entries in the @e tq_head DLL.
416 * Get the static string for the peer this tunnel is directed.
420 * @return Static string the destination peer's ID.
423 GCT_2s (const struct CadetTunnel *t)
430 GNUNET_snprintf (buf,
433 GCP_2s (t->destination));
439 * Return the peer to which this tunnel goes.
442 * @return the destination of the tunnel
445 GCT_get_destination (struct CadetTunnel *t)
447 return t->destination;
452 * Count channels of a tunnel.
454 * @param t Tunnel on which to count.
456 * @return Number of channels.
459 GCT_count_channels (struct CadetTunnel *t)
461 return GNUNET_CONTAINER_multihashmap32_size (t->channels);
466 * Count all created connections of a tunnel. Not necessarily ready connections!
468 * @param t Tunnel on which to count.
470 * @return Number of connections created, either being established or ready.
473 GCT_count_any_connections (struct CadetTunnel *t)
475 return t->num_connections;
480 * Get the connectivity state of a tunnel.
484 * @return Tunnel's connectivity state.
486 enum CadetTunnelCState
487 GCT_get_cstate (struct CadetTunnel *t)
494 * Get the encryption state of a tunnel.
498 * @return Tunnel's encryption state.
500 enum CadetTunnelEState
501 GCT_get_estate (struct CadetTunnel *t)
508 * Create a new Axolotl ephemeral (ratchet) key.
513 new_ephemeral (struct CadetTunnel *t)
515 GNUNET_free_non_null (t->ax.DHRs);
516 t->ax.DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
520 /* ************************************** start core crypto ***************************** */
526 * @param plaintext Content to HMAC.
527 * @param size Size of @c plaintext.
528 * @param iv Initialization vector for the message.
529 * @param key Key to use.
530 * @param hmac[out] Destination to store the HMAC.
533 t_hmac (const void *plaintext,
536 const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
537 struct GNUNET_CADET_Hash *hmac)
539 static const char ctx[] = "cadet authentication key";
540 struct GNUNET_CRYPTO_AuthKey auth_key;
541 struct GNUNET_HashCode hash;
543 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
549 /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
550 GNUNET_CRYPTO_hmac (&auth_key,
563 * @param key Key to use.
564 * @param hash[out] Resulting HMAC.
565 * @param source Source key material (data to HMAC).
566 * @param len Length of @a source.
569 t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
570 struct GNUNET_HashCode *hash,
574 static const char ctx[] = "axolotl HMAC-HASH";
575 struct GNUNET_CRYPTO_AuthKey auth_key;
577 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
581 GNUNET_CRYPTO_hmac (&auth_key,
589 * Derive a symmetric encryption key from an HMAC-HASH.
591 * @param key Key to use for the HMAC.
592 * @param[out] out Key to generate.
593 * @param source Source key material (data to HMAC).
594 * @param len Length of @a source.
597 t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
598 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
602 static const char ctx[] = "axolotl derive key";
603 struct GNUNET_HashCode h;
609 GNUNET_CRYPTO_kdf (out, sizeof (*out),
617 * Encrypt data with the axolotl tunnel key.
619 * @param t Tunnel whose key to use.
620 * @param dst Destination with @a size bytes for the encrypted data.
621 * @param src Source of the plaintext. Can overlap with @c dst, must contain @a size bytes
622 * @param size Size of the buffers at @a src and @a dst
625 t_ax_encrypt (struct CadetTunnel *t,
630 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
631 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
632 struct CadetTunnelAxolotl *ax;
636 ax->ratchet_counter++;
637 if ( (GNUNET_YES == ax->ratchet_allowed) &&
638 ( (ratchet_messages <= ax->ratchet_counter) ||
639 (0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us)) )
641 ax->ratchet_flag = GNUNET_YES;
643 if (GNUNET_YES == ax->ratchet_flag)
645 /* Advance ratchet */
646 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
647 struct GNUNET_HashCode dh;
648 struct GNUNET_HashCode hmac;
649 static const char ctx[] = "axolotl ratchet";
654 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
655 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
658 t_ax_hmac_hash (&ax->RK,
662 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
664 &hmac, sizeof (hmac),
672 ax->ratchet_flag = GNUNET_NO;
673 ax->ratchet_allowed = GNUNET_NO;
674 ax->ratchet_counter = 0;
675 ax->ratchet_expiration
676 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
680 t_hmac_derive_key (&ax->CKs,
684 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
689 out_size = GNUNET_CRYPTO_symmetric_encrypt (src,
694 GNUNET_assert (size == out_size);
695 t_hmac_derive_key (&ax->CKs,
703 * Decrypt data with the axolotl tunnel key.
705 * @param t Tunnel whose key to use.
706 * @param dst Destination for the decrypted data, must contain @a size bytes.
707 * @param src Source of the ciphertext. Can overlap with @c dst, must contain @a size bytes.
708 * @param size Size of the @a src and @a dst buffers
711 t_ax_decrypt (struct CadetTunnel *t,
716 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
717 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
718 struct CadetTunnelAxolotl *ax;
722 t_hmac_derive_key (&ax->CKr,
726 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
730 GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
731 out_size = GNUNET_CRYPTO_symmetric_decrypt (src,
736 GNUNET_assert (out_size == size);
737 t_hmac_derive_key (&ax->CKr,
745 * Encrypt header with the axolotl header key.
747 * @param t Tunnel whose key to use.
748 * @param msg Message whose header to encrypt.
751 t_h_encrypt (struct CadetTunnel *t,
752 struct GNUNET_CADET_Encrypted *msg)
754 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
755 struct CadetTunnelAxolotl *ax;
759 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
763 out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->Ns,
768 GNUNET_assert (AX_HEADER_SIZE == out_size);
773 * Decrypt header with the current axolotl header key.
775 * @param t Tunnel whose current ax HK to use.
776 * @param src Message whose header to decrypt.
777 * @param dst Where to decrypt header to.
780 t_h_decrypt (struct CadetTunnel *t,
781 const struct GNUNET_CADET_Encrypted *src,
782 struct GNUNET_CADET_Encrypted *dst)
784 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
785 struct CadetTunnelAxolotl *ax;
789 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
793 out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns,
798 GNUNET_assert (AX_HEADER_SIZE == out_size);
803 * Delete a key from the list of skipped keys.
805 * @param t Tunnel to delete from.
806 * @param key Key to delete.
809 delete_skipped_key (struct CadetTunnel *t,
810 struct CadetTunnelSkippedKey *key)
812 GNUNET_CONTAINER_DLL_remove (t->ax.skipped_head,
821 * Decrypt and verify data with the appropriate tunnel key and verify that the
822 * data has not been altered since it was sent by the remote peer.
824 * @param t Tunnel whose key to use.
825 * @param dst Destination for the plaintext.
826 * @param src Source of the message. Can overlap with @c dst.
827 * @param size Size of the message.
828 * @return Size of the decrypted data, -1 if an error was encountered.
831 try_old_ax_keys (struct CadetTunnel *t,
833 const struct GNUNET_CADET_Encrypted *src,
836 struct CadetTunnelSkippedKey *key;
837 struct GNUNET_CADET_Hash *hmac;
838 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
839 struct GNUNET_CADET_Encrypted plaintext_header;
840 struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
846 LOG (GNUNET_ERROR_TYPE_DEBUG,
847 "Trying skipped keys\n");
848 hmac = &plaintext_header.hmac;
849 esize = size - sizeof (struct GNUNET_CADET_Encrypted);
851 /* Find a correct Header Key */
853 for (key = t->ax.skipped_head; NULL != key; key = key->next)
856 AX_HEADER_SIZE + esize,
860 if (0 == memcmp (hmac,
871 /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
872 GNUNET_assert (size > sizeof (struct GNUNET_CADET_Encrypted));
873 len = size - sizeof (struct GNUNET_CADET_Encrypted);
874 GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
877 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
881 res = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns,
885 &plaintext_header.Ns);
886 GNUNET_assert (AX_HEADER_SIZE == res);
888 /* Find the correct message key */
889 N = ntohl (plaintext_header.Ns);
890 while ( (NULL != key) &&
893 if ( (NULL == key) ||
894 (0 != memcmp (&key->HK,
896 sizeof (*valid_HK))) )
899 /* Decrypt payload */
900 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
905 res = GNUNET_CRYPTO_symmetric_decrypt (&src[1],
910 delete_skipped_key (t,
917 * Delete a key from the list of skipped keys.
919 * @param t Tunnel to delete from.
920 * @param HKr Header Key to use.
923 store_skipped_key (struct CadetTunnel *t,
924 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
926 struct CadetTunnelSkippedKey *key;
928 key = GNUNET_new (struct CadetTunnelSkippedKey);
929 key->timestamp = GNUNET_TIME_absolute_get ();
932 t_hmac_derive_key (&t->ax.CKr,
936 t_hmac_derive_key (&t->ax.CKr,
940 GNUNET_CONTAINER_DLL_insert (t->ax.skipped_head,
949 * Stage skipped AX keys and calculate the message key.
950 * Stores each HK and MK for skipped messages.
952 * @param t Tunnel where to stage the keys.
953 * @param HKr Header key.
954 * @param Np Received meesage number.
955 * @return #GNUNET_OK if keys were stored.
956 * #GNUNET_SYSERR if an error ocurred (Np not expected).
959 store_ax_keys (struct CadetTunnel *t,
960 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
966 LOG (GNUNET_ERROR_TYPE_DEBUG,
967 "Storing skipped keys [%u, %u)\n",
970 if (MAX_KEY_GAP < gap)
972 /* Avoid DoS (forcing peer to do 2^33 chain HMAC operations) */
973 /* TODO: start new key exchange on return */
975 LOG (GNUNET_ERROR_TYPE_WARNING,
976 "Got message %u, expected %u+\n",
979 return GNUNET_SYSERR;
983 /* Delayed message: don't store keys, flag to try old keys. */
984 return GNUNET_SYSERR;
987 while (t->ax.Nr < Np)
988 store_skipped_key (t,
991 while (t->ax.skipped > MAX_SKIPPED_KEYS)
992 delete_skipped_key (t,
999 * Decrypt and verify data with the appropriate tunnel key and verify that the
1000 * data has not been altered since it was sent by the remote peer.
1002 * @param t Tunnel whose key to use.
1003 * @param dst Destination for the plaintext.
1004 * @param src Source of the message. Can overlap with @c dst.
1005 * @param size Size of the message.
1006 * @return Size of the decrypted data, -1 if an error was encountered.
1009 t_ax_decrypt_and_validate (struct CadetTunnel *t,
1011 const struct GNUNET_CADET_Encrypted *src,
1014 struct CadetTunnelAxolotl *ax;
1015 struct GNUNET_CADET_Hash msg_hmac;
1016 struct GNUNET_HashCode hmac;
1017 struct GNUNET_CADET_Encrypted plaintext_header;
1020 size_t esize; /* Size of encryped payload */
1022 esize = size - sizeof (struct GNUNET_CADET_Encrypted);
1025 /* Try current HK */
1027 AX_HEADER_SIZE + esize,
1030 if (0 != memcmp (&msg_hmac,
1034 static const char ctx[] = "axolotl ratchet";
1035 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1036 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1037 struct GNUNET_HashCode dh;
1038 struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1042 AX_HEADER_SIZE + esize,
1046 if (0 != memcmp (&msg_hmac,
1050 /* Try the skipped keys, if that fails, we're out of luck. */
1051 return try_old_ax_keys (t,
1061 Np = ntohl (plaintext_header.Ns);
1062 PNp = ntohl (plaintext_header.PNs);
1063 DHRp = &plaintext_header.DHRs;
1068 /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1069 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
1072 t_ax_hmac_hash (&ax->RK,
1075 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1077 &hmac, sizeof (hmac),
1080 /* Commit "purported" keys */
1086 ax->ratchet_allowed = GNUNET_YES;
1093 Np = ntohl (plaintext_header.Ns);
1094 PNp = ntohl (plaintext_header.PNs);
1096 if ( (Np != ax->Nr) &&
1097 (GNUNET_OK != store_ax_keys (t,
1101 /* Try the skipped keys, if that fails, we're out of luck. */
1102 return try_old_ax_keys (t,
1117 /* ************************************** end core crypto ***************************** */
1121 * Add a channel to a tunnel.
1125 * @return unique number identifying @a ch within @a t
1127 struct GCT_ChannelTunnelNumber
1128 GCT_add_channel (struct CadetTunnel *t,
1129 struct CadetChannel *ch)
1131 struct GCT_ChannelTunnelNumber ret;
1134 chid = ntohl (t->next_chid.channel_in_tunnel);
1136 GNUNET_CONTAINER_multihashmap32_get (t->channels,
1139 GNUNET_assert (GNUNET_YES ==
1140 GNUNET_CONTAINER_multihashmap32_put (t->channels,
1143 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1144 t->next_chid.channel_in_tunnel = htonl (chid + 1);
1145 ret.channel_in_tunnel = htonl (chid);
1151 * This tunnel is no longer used, destroy it.
1153 * @param cls the idle tunnel
1156 destroy_tunnel (void *cls)
1158 struct CadetTunnel *t = cls;
1159 struct CadetTConnection *ct;
1160 struct CadetTunnelQueueEntry *tqe;
1162 t->destroy_task = NULL;
1163 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap32_size (t->channels));
1164 while (NULL != (ct = t->connection_head))
1166 GNUNET_assert (ct->t == t);
1167 GNUNET_CONTAINER_DLL_remove (t->connection_head,
1170 GCC_destroy (ct->cc);
1173 while (NULL != (tqe = t->tq_head))
1175 GNUNET_CONTAINER_DLL_remove (t->tq_head,
1178 GNUNET_MQ_discard (tqe->env);
1181 GCP_drop_tunnel (t->destination,
1183 GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
1184 if (NULL != t->maintain_connections_task)
1186 GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
1187 t->maintain_connections_task = NULL;
1194 * A connection is ready for transmission. Looks at our message queue
1195 * and if there is a message, sends it out via the connection.
1197 * @param cls the `struct CadetTConnection` that is ready
1200 connection_ready_cb (void *cls)
1202 struct CadetTConnection *ct = cls;
1203 struct CadetTunnel *t = ct->t;
1204 struct CadetTunnelQueueEntry *tq = t->tq_head;
1207 return; /* no messages pending right now */
1209 /* ready to send message 'tq' on tunnel 'ct' */
1210 GNUNET_assert (t == tq->t);
1211 GNUNET_CONTAINER_DLL_remove (t->tq_head,
1214 if (NULL != tq->cid)
1215 *tq->cid = *GCC_get_id (ct->cc);
1216 GCC_transmit (ct->cc,
1218 tq->cont (tq->cont_cls);
1224 * Called when either we have a new connection, or a new message in the
1225 * queue, or some existing connection has transmission capacity. Looks
1226 * at our message queue and if there is a message, picks a connection
1229 * @param t tunnel to process messages on
1232 trigger_transmissions (struct CadetTunnel *t)
1234 struct CadetTConnection *ct;
1236 if (NULL == t->tq_head)
1237 return; /* no messages pending right now */
1238 for (ct = t->connection_head;
1241 if (GNUNET_YES == GCC_is_ready (ct->cc))
1244 return; /* no connections ready */
1245 connection_ready_cb (ct);
1250 * Function called to maintain the connections underlying our tunnel.
1251 * Tries to maintain (incl. tear down) connections for the tunnel, and
1252 * if there is a significant change, may trigger transmissions.
1254 * Basically, needs to check if there are connections that perform
1255 * badly, and if so eventually kill them and trigger a replacement.
1256 * The strategy is to open one more connection than
1257 * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
1258 * least-performing one, and then inquire for new ones.
1260 * @param cls the `struct CadetTunnel`
1263 maintain_connections_cb (void *cls)
1265 struct CadetTunnel *t = cls;
1267 GNUNET_break (0); // FIXME: implement!
1272 * Consider using the path @a p for the tunnel @a t.
1273 * The tunnel destination is at offset @a off in path @a p.
1275 * @param cls our tunnel
1276 * @param path a path to our destination
1277 * @param off offset of the destination on path @a path
1278 * @return #GNUNET_YES (should keep iterating)
1281 consider_path_cb (void *cls,
1282 struct CadetPeerPath *path,
1285 struct CadetTunnel *t = cls;
1286 unsigned int min_length = UINT_MAX;
1287 GNUNET_CONTAINER_HeapCostType max_desire = 0;
1288 struct CadetTConnection *ct;
1290 /* Check if we care about the new path. */
1291 for (ct = t->connection_head;
1295 struct CadetPeerPath *ps;
1297 ps = GCC_get_path (ct->cc);
1299 return GNUNET_YES; /* duplicate */
1300 min_length = GNUNET_MIN (min_length,
1301 GCPP_get_length (ps));
1302 max_desire = GNUNET_MAX (max_desire,
1303 GCPP_get_desirability (ps));
1306 /* FIXME: not sure we should really just count
1307 'num_connections' here, as they may all have
1308 consistently failed to connect. */
1310 /* We iterate by increasing path length; if we have enough paths and
1311 this one is more than twice as long than what we are currently
1312 using, then ignore all of these super-long ones! */
1313 if ( (t->num_connections > DESIRED_CONNECTIONS_PER_TUNNEL) &&
1314 (min_length * 2 < off) )
1316 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1317 "Ignoring paths of length %u, they are way too long.\n",
1321 /* If we have enough paths and this one looks no better, ignore it. */
1322 if ( (t->num_connections >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
1323 (min_length < GCPP_get_length (path)) &&
1324 (max_desire > GCPP_get_desirability (path)) )
1326 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1327 "Ignoring path (%u/%llu) to %s, got something better already.\n",
1328 GCPP_get_length (path),
1329 (unsigned long long) GCPP_get_desirability (path),
1330 GCP_2s (t->destination));
1334 /* Path is interesting (better by some metric, or we don't have
1335 enough paths yet). */
1336 ct = GNUNET_new (struct CadetTConnection);
1337 ct->created = GNUNET_TIME_absolute_get ();
1339 ct->cc = GCC_create (t->destination,
1342 &connection_ready_cb,
1344 /* FIXME: schedule job to kill connection (and path?) if it takes
1345 too long to get ready! (And track performance data on how long
1346 other connections took with the tunnel!)
1347 => Note: to be done within 'connection'-logic! */
1348 GNUNET_CONTAINER_DLL_insert (t->connection_head,
1351 t->num_connections++;
1357 * Consider using the path @a p for the tunnel @a t.
1358 * The tunnel destination is at offset @a off in path @a p.
1360 * @param cls our tunnel
1361 * @param path a path to our destination
1362 * @param off offset of the destination on path @a path
1365 GCT_consider_path (struct CadetTunnel *t,
1366 struct CadetPeerPath *p,
1369 (void) consider_path_cb (t,
1376 * Create a tunnel to @a destionation. Must only be called
1377 * from within #GCP_get_tunnel().
1379 * @param destination where to create the tunnel to
1380 * @return new tunnel to @a destination
1382 struct CadetTunnel *
1383 GCT_create_tunnel (struct CadetPeer *destination)
1385 struct CadetTunnel *t;
1387 t = GNUNET_new (struct CadetTunnel);
1388 t->destination = destination;
1389 t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
1390 (void) GCP_iterate_paths (destination,
1393 t->maintain_connections_task
1394 = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
1401 * Remove a channel from a tunnel.
1405 * @param gid unique number identifying @a ch within @a t
1408 GCT_remove_channel (struct CadetTunnel *t,
1409 struct CadetChannel *ch,
1410 struct GCT_ChannelTunnelNumber gid)
1412 GNUNET_assert (GNUNET_YES ==
1413 GNUNET_CONTAINER_multihashmap32_remove (t->channels,
1414 ntohl (gid.channel_in_tunnel),
1417 GNUNET_CONTAINER_multihashmap32_size (t->channels))
1419 t->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
1427 * Sends an already built message on a tunnel, encrypting it and
1428 * choosing the best connection if not provided.
1430 * @param message Message to send. Function modifies it.
1431 * @param t Tunnel on which this message is transmitted.
1432 * @param cont Continuation to call once message is really sent.
1433 * @param cont_cls Closure for @c cont.
1434 * @return Handle to cancel message. NULL if @c cont is NULL.
1436 struct CadetTunnelQueueEntry *
1437 GCT_send (struct CadetTunnel *t,
1438 const struct GNUNET_MessageHeader *message,
1439 GNUNET_SCHEDULER_TaskCallback cont,
1442 struct CadetTunnelQueueEntry *tq;
1443 uint16_t payload_size;
1444 struct GNUNET_MQ_Envelope *env;
1445 struct GNUNET_CADET_Encrypted *ax_msg;
1447 /* FIXME: what about KX not yet being ready? (see "is_ready()" check in old code!) */
1449 payload_size = ntohs (message->size);
1450 env = GNUNET_MQ_msg_extra (ax_msg,
1452 GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
1457 ax_msg->Ns = htonl (t->ax.Ns++);
1458 ax_msg->PNs = htonl (t->ax.PNs);
1459 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax.DHRs,
1463 t_hmac (&ax_msg->Ns,
1464 AX_HEADER_SIZE + payload_size,
1468 // ax_msg->pid = htonl (GCC_get_pid (c, fwd)); // FIXME: connection flow-control not (re)implemented yet!
1470 tq = GNUNET_malloc (sizeof (*tq));
1473 tq->cid = &ax_msg->cid;
1475 tq->cont_cls = cont_cls;
1476 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
1479 trigger_transmissions (t);
1485 * Cancel a previously sent message while it's in the queue.
1487 * ONLY can be called before the continuation given to the send
1488 * function is called. Once the continuation is called, the message is
1489 * no longer in the queue!
1491 * @param q Handle to the queue entry to cancel.
1494 GCT_send_cancel (struct CadetTunnelQueueEntry *q)
1496 struct CadetTunnel *t = q->t;
1498 GNUNET_CONTAINER_DLL_remove (t->tq_head,
1506 * Iterate over all connections of a tunnel.
1508 * @param t Tunnel whose connections to iterate.
1509 * @param iter Iterator.
1510 * @param iter_cls Closure for @c iter.
1513 GCT_iterate_connections (struct CadetTunnel *t,
1514 GCT_ConnectionIterator iter,
1517 for (struct CadetTConnection *ct = t->connection_head;
1526 * Closure for #iterate_channels_cb.
1533 GCT_ChannelIterator iter;
1536 * Closure for @e iter.
1543 * Helper function for #GCT_iterate_channels.
1545 * @param cls the `struct ChanIterCls`
1547 * @param value a `struct CadetChannel`
1548 * @return #GNUNET_OK
1551 iterate_channels_cb (void *cls,
1555 struct ChanIterCls *ctx = cls;
1556 struct CadetChannel *ch = value;
1558 ctx->iter (ctx->iter_cls,
1565 * Iterate over all channels of a tunnel.
1567 * @param t Tunnel whose channels to iterate.
1568 * @param iter Iterator.
1569 * @param iter_cls Closure for @c iter.
1572 GCT_iterate_channels (struct CadetTunnel *t,
1573 GCT_ChannelIterator iter,
1576 struct ChanIterCls ctx;
1579 ctx.iter_cls = iter_cls;
1580 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1581 &iterate_channels_cb,
1588 * Call #GCCH_debug() on a channel.
1590 * @param cls points to the log level to use
1592 * @param value the `struct CadetChannel` to dump
1593 * @return #GNUNET_OK (continue iteration)
1596 debug_channel (void *cls,
1600 const enum GNUNET_ErrorType *level = cls;
1601 struct CadetChannel *ch = value;
1603 GCCH_debug (ch, *level);
1609 * Get string description for tunnel connectivity state.
1611 * @param cs Tunnel state.
1613 * @return String representation.
1616 cstate2s (enum CadetTunnelCState cs)
1618 static char buf[32];
1622 case CADET_TUNNEL_NEW:
1623 return "CADET_TUNNEL_NEW";
1624 case CADET_TUNNEL_SEARCHING:
1625 return "CADET_TUNNEL_SEARCHING";
1626 case CADET_TUNNEL_WAITING:
1627 return "CADET_TUNNEL_WAITING";
1628 case CADET_TUNNEL_READY:
1629 return "CADET_TUNNEL_READY";
1630 case CADET_TUNNEL_SHUTDOWN:
1631 return "CADET_TUNNEL_SHUTDOWN";
1633 SPRINTF (buf, "%u (UNKNOWN STATE)", cs);
1640 * Get string description for tunnel encryption state.
1642 * @param es Tunnel state.
1644 * @return String representation.
1647 estate2s (enum CadetTunnelEState es)
1649 static char buf[32];
1653 case CADET_TUNNEL_KEY_UNINITIALIZED:
1654 return "CADET_TUNNEL_KEY_UNINITIALIZED";
1655 case CADET_TUNNEL_KEY_SENT:
1656 return "CADET_TUNNEL_KEY_SENT";
1657 case CADET_TUNNEL_KEY_PING:
1658 return "CADET_TUNNEL_KEY_PING";
1659 case CADET_TUNNEL_KEY_OK:
1660 return "CADET_TUNNEL_KEY_OK";
1661 case CADET_TUNNEL_KEY_REKEY:
1662 return "CADET_TUNNEL_KEY_REKEY";
1664 SPRINTF (buf, "%u (UNKNOWN STATE)", es);
1670 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
1674 * Log all possible info about the tunnel state.
1676 * @param t Tunnel to debug.
1677 * @param level Debug level to use.
1680 GCT_debug (const struct CadetTunnel *t,
1681 enum GNUNET_ErrorType level)
1683 struct CadetTConnection *iter_c;
1686 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
1688 __FILE__, __FUNCTION__, __LINE__);
1693 "TTT TUNNEL TOWARDS %s in cstate %s, estate %s tq_len: %u #cons: %u\n",
1695 cstate2s (t->cstate),
1696 estate2s (t->estate),
1698 t->num_connections);
1699 #if DUMP_KEYS_TO_STDERR
1700 ax_debug (t->ax, level);
1704 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1708 "TTT connections:\n");
1709 for (iter_c = t->connection_head; NULL != iter_c; iter_c = iter_c->next)
1710 GCC_debug (iter_c->cc,
1714 "TTT TUNNEL END\n");
1718 /* end of gnunet-service-cadet-new_tunnels.c */