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 * - implement sending and receiving KX messages
33 * - implement processing of incoming decrypted plaintext messages
34 * - clean up KX logic!
37 #include "gnunet_util_lib.h"
38 #include "gnunet_statistics_service.h"
39 #include "gnunet_signatures.h"
40 #include "cadet_protocol.h"
41 #include "cadet_path.h"
42 #include "gnunet-service-cadet-new.h"
43 #include "gnunet-service-cadet-new_channel.h"
44 #include "gnunet-service-cadet-new_connection.h"
45 #include "gnunet-service-cadet-new_tunnels.h"
46 #include "gnunet-service-cadet-new_peer.h"
47 #include "gnunet-service-cadet-new_paths.h"
50 #define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__)
54 * How long do we wait until tearing down an idle tunnel?
56 #define IDLE_DESTROY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90)
59 * Yuck, replace by 'offsetof' expression?
62 #define AX_HEADER_SIZE (sizeof (uint32_t) * 2\
63 + sizeof (struct GNUNET_CRYPTO_EcdhePublicKey))
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 (send).
140 struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
143 * 32-byte header key (recv)
145 struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
148 * 32-byte next header key (send).
150 struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
153 * 32-byte next header key (recv).
155 struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
158 * 32-byte chain keys (used for forward-secrecy updating, send).
160 struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
163 * 32-byte chain keys (used for forward-secrecy updating, recv).
165 struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
168 * ECDH for key exchange (A0 / B0).
170 struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
173 * ECDH Ratchet key (send).
175 struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
178 * ECDH Ratchet key (recv).
180 struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
183 * When does this ratchet expire and a new one is triggered.
185 struct GNUNET_TIME_Absolute ratchet_expiration;
188 * Number of elements in @a skipped_head <-> @a skipped_tail.
190 unsigned int skipped;
193 * Message number (reset to 0 with each new ratchet, next message to send).
198 * Message number (reset to 0 with each new ratchet, next message to recv).
203 * Previous message numbers (# of msgs sent under prev ratchet)
208 * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
213 * Number of messages recieved since our last ratchet advance.
214 * - If this counter = 0, we cannot send a new ratchet key in next msg.
215 * - If this counter > 0, we can (but don't yet have to) send a new key.
217 unsigned int ratchet_allowed;
220 * Number of messages recieved since our last ratchet advance.
221 * - If this counter = 0, we cannot send a new ratchet key in next msg.
222 * - If this counter > 0, we can (but don't yet have to) send a new key.
224 unsigned int ratchet_counter;
230 * Entry in list of connections used by tunnel, with metadata.
232 struct CadetTConnection
237 struct CadetTConnection *next;
242 struct CadetTConnection *prev;
247 struct CadetConnection *cc;
250 * Tunnel this connection belongs to.
252 struct CadetTunnel *t;
255 * Creation time, to keep oldest connection alive.
257 struct GNUNET_TIME_Absolute created;
260 * Connection throughput, to keep fastest connection alive.
267 * Struct used to save messages in a non-ready tunnel to send once connected.
269 struct CadetTunnelQueueEntry
272 * We are entries in a DLL
274 struct CadetTunnelQueueEntry *next;
277 * We are entries in a DLL
279 struct CadetTunnelQueueEntry *prev;
282 * Tunnel these messages belong in.
284 struct CadetTunnel *t;
287 * Continuation to call once sent (on the channel layer).
289 GNUNET_SCHEDULER_TaskCallback cont;
292 * Closure for @c cont.
297 * Envelope of message to send follows.
299 struct GNUNET_MQ_Envelope *env;
302 * Where to put the connection identifier into the payload
303 * of the message in @e env once we have it?
305 struct GNUNET_CADET_ConnectionTunnelIdentifier *cid;
310 * Struct containing all information regarding a tunnel to a peer.
315 * Destination of the tunnel.
317 struct CadetPeer *destination;
320 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own
321 * ephemeral key changes.
323 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
326 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
328 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
331 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
333 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
338 struct CadetTunnelAxolotl ax;
341 * State of the tunnel connectivity.
343 enum CadetTunnelCState cstate;
346 * State of the tunnel encryption.
348 enum CadetTunnelEState estate;
351 * Task to start the rekey process.
353 struct GNUNET_SCHEDULER_Task *rekey_task;
356 * Tokenizer for decrypted messages.
358 struct GNUNET_MessageStreamTokenizer *mst;
361 * Dispatcher for decrypted messages only (do NOT use for sending!).
363 struct GNUNET_MQ_Handle *mq;
366 * DLL of connections that are actively used to reach the destination peer.
368 struct CadetTConnection *connection_head;
371 * DLL of connections that are actively used to reach the destination peer.
373 struct CadetTConnection *connection_tail;
376 * Channels inside this tunnel. Maps
377 * `struct GCT_ChannelTunnelNumber` to a `struct CadetChannel`.
379 struct GNUNET_CONTAINER_MultiHashMap32 *channels;
382 * Channel ID for the next created channel in this tunnel.
384 struct GCT_ChannelTunnelNumber next_chid;
387 * Queued messages, to transmit once tunnel gets connected.
389 struct CadetTunnelQueueEntry *tq_head;
392 * Queued messages, to transmit once tunnel gets connected.
394 struct CadetTunnelQueueEntry *tq_tail;
397 * Task scheduled if there are no more channels using the tunnel.
399 struct GNUNET_SCHEDULER_Task *destroy_task;
402 * Task to trim connections if too many are present.
404 struct GNUNET_SCHEDULER_Task *maintain_connections_task;
407 * Ephemeral message in the queue (to avoid queueing more than one).
409 struct CadetConnectionQueue *ephm_hKILL;
412 * Pong message in the queue.
414 struct CadetConnectionQueue *pong_hKILL;
417 * Number of connections in the @e connection_head DLL.
419 unsigned int num_connections;
422 * Number of entries in the @e tq_head DLL.
429 * Get the static string for the peer this tunnel is directed.
433 * @return Static string the destination peer's ID.
436 GCT_2s (const struct CadetTunnel *t)
443 GNUNET_snprintf (buf,
446 GCP_2s (t->destination));
452 * Return the peer to which this tunnel goes.
455 * @return the destination of the tunnel
458 GCT_get_destination (struct CadetTunnel *t)
460 return t->destination;
465 * Count channels of a tunnel.
467 * @param t Tunnel on which to count.
469 * @return Number of channels.
472 GCT_count_channels (struct CadetTunnel *t)
474 return GNUNET_CONTAINER_multihashmap32_size (t->channels);
479 * Count all created connections of a tunnel. Not necessarily ready connections!
481 * @param t Tunnel on which to count.
483 * @return Number of connections created, either being established or ready.
486 GCT_count_any_connections (struct CadetTunnel *t)
488 return t->num_connections;
493 * Get the connectivity state of a tunnel.
497 * @return Tunnel's connectivity state.
499 enum CadetTunnelCState
500 GCT_get_cstate (struct CadetTunnel *t)
507 * Get the encryption state of a tunnel.
511 * @return Tunnel's encryption state.
513 enum CadetTunnelEState
514 GCT_get_estate (struct CadetTunnel *t)
521 * Create a new Axolotl ephemeral (ratchet) key.
526 new_ephemeral (struct CadetTunnel *t)
528 GNUNET_free_non_null (t->ax.DHRs);
529 t->ax.DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
533 /* ************************************** start core crypto ***************************** */
539 * @param plaintext Content to HMAC.
540 * @param size Size of @c plaintext.
541 * @param iv Initialization vector for the message.
542 * @param key Key to use.
543 * @param hmac[out] Destination to store the HMAC.
546 t_hmac (const void *plaintext,
549 const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
550 struct GNUNET_ShortHashCode *hmac)
552 static const char ctx[] = "cadet authentication key";
553 struct GNUNET_CRYPTO_AuthKey auth_key;
554 struct GNUNET_HashCode hash;
556 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
562 /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
563 GNUNET_CRYPTO_hmac (&auth_key,
576 * @param key Key to use.
577 * @param hash[out] Resulting HMAC.
578 * @param source Source key material (data to HMAC).
579 * @param len Length of @a source.
582 t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
583 struct GNUNET_HashCode *hash,
587 static const char ctx[] = "axolotl HMAC-HASH";
588 struct GNUNET_CRYPTO_AuthKey auth_key;
590 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
594 GNUNET_CRYPTO_hmac (&auth_key,
602 * Derive a symmetric encryption key from an HMAC-HASH.
604 * @param key Key to use for the HMAC.
605 * @param[out] out Key to generate.
606 * @param source Source key material (data to HMAC).
607 * @param len Length of @a source.
610 t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
611 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
615 static const char ctx[] = "axolotl derive key";
616 struct GNUNET_HashCode h;
622 GNUNET_CRYPTO_kdf (out, sizeof (*out),
630 * Encrypt data with the axolotl tunnel key.
632 * @param t Tunnel whose key to use.
633 * @param dst Destination with @a size bytes for the encrypted data.
634 * @param src Source of the plaintext. Can overlap with @c dst, must contain @a size bytes
635 * @param size Size of the buffers at @a src and @a dst
638 t_ax_encrypt (struct CadetTunnel *t,
643 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
644 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
645 struct CadetTunnelAxolotl *ax;
649 ax->ratchet_counter++;
650 if ( (GNUNET_YES == ax->ratchet_allowed) &&
651 ( (ratchet_messages <= ax->ratchet_counter) ||
652 (0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us)) )
654 ax->ratchet_flag = GNUNET_YES;
656 if (GNUNET_YES == ax->ratchet_flag)
658 /* Advance ratchet */
659 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
660 struct GNUNET_HashCode dh;
661 struct GNUNET_HashCode hmac;
662 static const char ctx[] = "axolotl ratchet";
667 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
668 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
671 t_ax_hmac_hash (&ax->RK,
675 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
677 &hmac, sizeof (hmac),
685 ax->ratchet_flag = GNUNET_NO;
686 ax->ratchet_allowed = GNUNET_NO;
687 ax->ratchet_counter = 0;
688 ax->ratchet_expiration
689 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
693 t_hmac_derive_key (&ax->CKs,
697 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
702 out_size = GNUNET_CRYPTO_symmetric_encrypt (src,
707 GNUNET_assert (size == out_size);
708 t_hmac_derive_key (&ax->CKs,
716 * Decrypt data with the axolotl tunnel key.
718 * @param t Tunnel whose key to use.
719 * @param dst Destination for the decrypted data, must contain @a size bytes.
720 * @param src Source of the ciphertext. Can overlap with @c dst, must contain @a size bytes.
721 * @param size Size of the @a src and @a dst buffers
724 t_ax_decrypt (struct CadetTunnel *t,
729 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
730 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
731 struct CadetTunnelAxolotl *ax;
735 t_hmac_derive_key (&ax->CKr,
739 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
743 GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
744 out_size = GNUNET_CRYPTO_symmetric_decrypt (src,
749 GNUNET_assert (out_size == size);
750 t_hmac_derive_key (&ax->CKr,
758 * Encrypt header with the axolotl header key.
760 * @param t Tunnel whose key to use.
761 * @param msg Message whose header to encrypt.
764 t_h_encrypt (struct CadetTunnel *t,
765 struct GNUNET_CADET_TunnelEncryptedMessage *msg)
767 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
768 struct CadetTunnelAxolotl *ax;
772 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
776 out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->Ns,
781 GNUNET_assert (AX_HEADER_SIZE == out_size);
786 * Decrypt header with the current axolotl header key.
788 * @param t Tunnel whose current ax HK to use.
789 * @param src Message whose header to decrypt.
790 * @param dst Where to decrypt header to.
793 t_h_decrypt (struct CadetTunnel *t,
794 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
795 struct GNUNET_CADET_TunnelEncryptedMessage *dst)
797 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
798 struct CadetTunnelAxolotl *ax;
802 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
806 out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns,
811 GNUNET_assert (AX_HEADER_SIZE == out_size);
816 * Delete a key from the list of skipped keys.
818 * @param t Tunnel to delete from.
819 * @param key Key to delete.
822 delete_skipped_key (struct CadetTunnel *t,
823 struct CadetTunnelSkippedKey *key)
825 GNUNET_CONTAINER_DLL_remove (t->ax.skipped_head,
834 * Decrypt and verify data with the appropriate tunnel key and verify that the
835 * data has not been altered since it was sent by the remote peer.
837 * @param t Tunnel whose key to use.
838 * @param dst Destination for the plaintext.
839 * @param src Source of the message. Can overlap with @c dst.
840 * @param size Size of the message.
841 * @return Size of the decrypted data, -1 if an error was encountered.
844 try_old_ax_keys (struct CadetTunnel *t,
846 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
849 struct CadetTunnelSkippedKey *key;
850 struct GNUNET_ShortHashCode *hmac;
851 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
852 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
853 struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
859 LOG (GNUNET_ERROR_TYPE_DEBUG,
860 "Trying skipped keys\n");
861 hmac = &plaintext_header.hmac;
862 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
864 /* Find a correct Header Key */
866 for (key = t->ax.skipped_head; NULL != key; key = key->next)
869 AX_HEADER_SIZE + esize,
873 if (0 == memcmp (hmac,
884 /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
885 GNUNET_assert (size > sizeof (struct GNUNET_CADET_TunnelEncryptedMessage));
886 len = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
887 GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
890 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
894 res = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns,
898 &plaintext_header.Ns);
899 GNUNET_assert (AX_HEADER_SIZE == res);
901 /* Find the correct message key */
902 N = ntohl (plaintext_header.Ns);
903 while ( (NULL != key) &&
906 if ( (NULL == key) ||
907 (0 != memcmp (&key->HK,
909 sizeof (*valid_HK))) )
912 /* Decrypt payload */
913 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
918 res = GNUNET_CRYPTO_symmetric_decrypt (&src[1],
923 delete_skipped_key (t,
930 * Delete a key from the list of skipped keys.
932 * @param t Tunnel to delete from.
933 * @param HKr Header Key to use.
936 store_skipped_key (struct CadetTunnel *t,
937 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
939 struct CadetTunnelSkippedKey *key;
941 key = GNUNET_new (struct CadetTunnelSkippedKey);
942 key->timestamp = GNUNET_TIME_absolute_get ();
945 t_hmac_derive_key (&t->ax.CKr,
949 t_hmac_derive_key (&t->ax.CKr,
953 GNUNET_CONTAINER_DLL_insert (t->ax.skipped_head,
962 * Stage skipped AX keys and calculate the message key.
963 * Stores each HK and MK for skipped messages.
965 * @param t Tunnel where to stage the keys.
966 * @param HKr Header key.
967 * @param Np Received meesage number.
968 * @return #GNUNET_OK if keys were stored.
969 * #GNUNET_SYSERR if an error ocurred (Np not expected).
972 store_ax_keys (struct CadetTunnel *t,
973 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
979 LOG (GNUNET_ERROR_TYPE_DEBUG,
980 "Storing skipped keys [%u, %u)\n",
983 if (MAX_KEY_GAP < gap)
985 /* Avoid DoS (forcing peer to do 2^33 chain HMAC operations) */
986 /* TODO: start new key exchange on return */
988 LOG (GNUNET_ERROR_TYPE_WARNING,
989 "Got message %u, expected %u+\n",
992 return GNUNET_SYSERR;
996 /* Delayed message: don't store keys, flag to try old keys. */
997 return GNUNET_SYSERR;
1000 while (t->ax.Nr < Np)
1001 store_skipped_key (t,
1004 while (t->ax.skipped > MAX_SKIPPED_KEYS)
1005 delete_skipped_key (t,
1006 t->ax.skipped_tail);
1012 * Decrypt and verify data with the appropriate tunnel key and verify that the
1013 * data has not been altered since it was sent by the remote peer.
1015 * @param t Tunnel whose key to use.
1016 * @param dst Destination for the plaintext.
1017 * @param src Source of the message. Can overlap with @c dst.
1018 * @param size Size of the message.
1019 * @return Size of the decrypted data, -1 if an error was encountered.
1022 t_ax_decrypt_and_validate (struct CadetTunnel *t,
1024 const struct GNUNET_CADET_TunnelEncryptedMessage *src,
1027 struct CadetTunnelAxolotl *ax;
1028 struct GNUNET_ShortHashCode msg_hmac;
1029 struct GNUNET_HashCode hmac;
1030 struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
1033 size_t esize; /* Size of encryped payload */
1035 esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1038 /* Try current HK */
1040 AX_HEADER_SIZE + esize,
1043 if (0 != memcmp (&msg_hmac,
1047 static const char ctx[] = "axolotl ratchet";
1048 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1049 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1050 struct GNUNET_HashCode dh;
1051 struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1055 AX_HEADER_SIZE + esize,
1059 if (0 != memcmp (&msg_hmac,
1063 /* Try the skipped keys, if that fails, we're out of luck. */
1064 return try_old_ax_keys (t,
1074 Np = ntohl (plaintext_header.Ns);
1075 PNp = ntohl (plaintext_header.PNs);
1076 DHRp = &plaintext_header.DHRs;
1081 /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1082 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
1085 t_ax_hmac_hash (&ax->RK,
1088 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1090 &hmac, sizeof (hmac),
1093 /* Commit "purported" keys */
1099 ax->ratchet_allowed = GNUNET_YES;
1106 Np = ntohl (plaintext_header.Ns);
1107 PNp = ntohl (plaintext_header.PNs);
1109 if ( (Np != ax->Nr) &&
1110 (GNUNET_OK != store_ax_keys (t,
1114 /* Try the skipped keys, if that fails, we're out of luck. */
1115 return try_old_ax_keys (t,
1130 /* ************************************** end core crypto ***************************** */
1134 * Add a channel to a tunnel.
1138 * @return unique number identifying @a ch within @a t
1140 struct GCT_ChannelTunnelNumber
1141 GCT_add_channel (struct CadetTunnel *t,
1142 struct CadetChannel *ch)
1144 struct GCT_ChannelTunnelNumber ret;
1147 chid = ntohl (t->next_chid.channel_in_tunnel);
1149 GNUNET_CONTAINER_multihashmap32_get (t->channels,
1152 GNUNET_assert (GNUNET_YES ==
1153 GNUNET_CONTAINER_multihashmap32_put (t->channels,
1156 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1157 t->next_chid.channel_in_tunnel = htonl (chid + 1);
1158 ret.channel_in_tunnel = htonl (chid);
1164 * This tunnel is no longer used, destroy it.
1166 * @param cls the idle tunnel
1169 destroy_tunnel (void *cls)
1171 struct CadetTunnel *t = cls;
1172 struct CadetTConnection *ct;
1173 struct CadetTunnelQueueEntry *tqe;
1175 t->destroy_task = NULL;
1176 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap32_size (t->channels));
1177 while (NULL != (ct = t->connection_head))
1179 GNUNET_assert (ct->t == t);
1180 GNUNET_CONTAINER_DLL_remove (t->connection_head,
1183 GCC_destroy (ct->cc);
1186 while (NULL != (tqe = t->tq_head))
1188 GNUNET_CONTAINER_DLL_remove (t->tq_head,
1191 GNUNET_MQ_discard (tqe->env);
1194 GCP_drop_tunnel (t->destination,
1196 GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
1197 if (NULL != t->maintain_connections_task)
1199 GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
1200 t->maintain_connections_task = NULL;
1202 GNUNET_MST_destroy (t->mst);
1203 GNUNET_MQ_destroy (t->mq);
1209 * A connection is ready for transmission. Looks at our message queue
1210 * and if there is a message, sends it out via the connection.
1212 * @param cls the `struct CadetTConnection` that is ready
1215 connection_ready_cb (void *cls)
1217 struct CadetTConnection *ct = cls;
1218 struct CadetTunnel *t = ct->t;
1219 struct CadetTunnelQueueEntry *tq = t->tq_head;
1222 return; /* no messages pending right now */
1224 /* ready to send message 'tq' on tunnel 'ct' */
1225 GNUNET_assert (t == tq->t);
1226 GNUNET_CONTAINER_DLL_remove (t->tq_head,
1229 if (NULL != tq->cid)
1230 *tq->cid = *GCC_get_id (ct->cc);
1231 GCC_transmit (ct->cc,
1233 tq->cont (tq->cont_cls);
1239 * Called when either we have a new connection, or a new message in the
1240 * queue, or some existing connection has transmission capacity. Looks
1241 * at our message queue and if there is a message, picks a connection
1244 * @param t tunnel to process messages on
1247 trigger_transmissions (struct CadetTunnel *t)
1249 struct CadetTConnection *ct;
1251 if (NULL == t->tq_head)
1252 return; /* no messages pending right now */
1253 for (ct = t->connection_head;
1256 if (GNUNET_YES == GCC_is_ready (ct->cc))
1259 return; /* no connections ready */
1260 connection_ready_cb (ct);
1265 * Function called to maintain the connections underlying our tunnel.
1266 * Tries to maintain (incl. tear down) connections for the tunnel, and
1267 * if there is a significant change, may trigger transmissions.
1269 * Basically, needs to check if there are connections that perform
1270 * badly, and if so eventually kill them and trigger a replacement.
1271 * The strategy is to open one more connection than
1272 * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
1273 * least-performing one, and then inquire for new ones.
1275 * @param cls the `struct CadetTunnel`
1278 maintain_connections_cb (void *cls)
1280 struct CadetTunnel *t = cls;
1282 GNUNET_break (0); // FIXME: implement!
1287 * Consider using the path @a p for the tunnel @a t.
1288 * The tunnel destination is at offset @a off in path @a p.
1290 * @param cls our tunnel
1291 * @param path a path to our destination
1292 * @param off offset of the destination on path @a path
1293 * @return #GNUNET_YES (should keep iterating)
1296 consider_path_cb (void *cls,
1297 struct CadetPeerPath *path,
1300 struct CadetTunnel *t = cls;
1301 unsigned int min_length = UINT_MAX;
1302 GNUNET_CONTAINER_HeapCostType max_desire = 0;
1303 struct CadetTConnection *ct;
1305 /* Check if we care about the new path. */
1306 for (ct = t->connection_head;
1310 struct CadetPeerPath *ps;
1312 ps = GCC_get_path (ct->cc);
1314 return GNUNET_YES; /* duplicate */
1315 min_length = GNUNET_MIN (min_length,
1316 GCPP_get_length (ps));
1317 max_desire = GNUNET_MAX (max_desire,
1318 GCPP_get_desirability (ps));
1321 /* FIXME: not sure we should really just count
1322 'num_connections' here, as they may all have
1323 consistently failed to connect. */
1325 /* We iterate by increasing path length; if we have enough paths and
1326 this one is more than twice as long than what we are currently
1327 using, then ignore all of these super-long ones! */
1328 if ( (t->num_connections > DESIRED_CONNECTIONS_PER_TUNNEL) &&
1329 (min_length * 2 < off) )
1331 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1332 "Ignoring paths of length %u, they are way too long.\n",
1336 /* If we have enough paths and this one looks no better, ignore it. */
1337 if ( (t->num_connections >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
1338 (min_length < GCPP_get_length (path)) &&
1339 (max_desire > GCPP_get_desirability (path)) )
1341 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1342 "Ignoring path (%u/%llu) to %s, got something better already.\n",
1343 GCPP_get_length (path),
1344 (unsigned long long) GCPP_get_desirability (path),
1345 GCP_2s (t->destination));
1349 /* Path is interesting (better by some metric, or we don't have
1350 enough paths yet). */
1351 ct = GNUNET_new (struct CadetTConnection);
1352 ct->created = GNUNET_TIME_absolute_get ();
1354 ct->cc = GCC_create (t->destination,
1357 &connection_ready_cb,
1359 /* FIXME: schedule job to kill connection (and path?) if it takes
1360 too long to get ready! (And track performance data on how long
1361 other connections took with the tunnel!)
1362 => Note: to be done within 'connection'-logic! */
1363 GNUNET_CONTAINER_DLL_insert (t->connection_head,
1366 t->num_connections++;
1372 * Consider using the path @a p for the tunnel @a t.
1373 * The tunnel destination is at offset @a off in path @a p.
1375 * @param cls our tunnel
1376 * @param path a path to our destination
1377 * @param off offset of the destination on path @a path
1380 GCT_consider_path (struct CadetTunnel *t,
1381 struct CadetPeerPath *p,
1384 (void) consider_path_cb (t,
1393 * @param cls the `struct CadetTunnel` for which we decrypted the message
1394 * @param msg the message we received on the tunnel
1397 handle_plaintext_keepalive (void *cls,
1398 const struct GNUNET_MessageHeader *msg)
1400 struct CadetTunnel *t = cls;
1401 GNUNET_break (0); // FIXME
1406 * Check that @a msg is well-formed.
1408 * @param cls the `struct CadetTunnel` for which we decrypted the message
1409 * @param msg the message we received on the tunnel
1410 * @return #GNUNET_OK (any variable-size payload goes)
1413 check_plaintext_data (void *cls,
1414 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
1423 * @param cls the `struct CadetTunnel` for which we decrypted the message
1424 * @param msg the message we received on the tunnel
1427 handle_plaintext_data (void *cls,
1428 const struct GNUNET_CADET_ChannelAppDataMessage *msg)
1430 struct CadetTunnel *t = cls;
1431 GNUNET_break (0); // FIXME!
1438 * @param cls the `struct CadetTunnel` for which we decrypted the message
1439 * @param ack the message we received on the tunnel
1442 handle_plaintext_data_ack (void *cls,
1443 const struct GNUNET_CADET_ChannelDataAckMessage *ack)
1445 struct CadetTunnel *t = cls;
1446 GNUNET_break (0); // FIXME!
1453 * @param cls the `struct CadetTunnel` for which we decrypted the message
1454 * @param cc the message we received on the tunnel
1457 handle_plaintext_channel_create (void *cls,
1458 const struct GNUNET_CADET_ChannelOpenMessage *cc)
1460 struct CadetTunnel *t = cls;
1461 GNUNET_break (0); // FIXME!
1468 * @param cls the `struct CadetTunnel` for which we decrypted the message
1469 * @param cm the message we received on the tunnel
1472 handle_plaintext_channel_nack (void *cls,
1473 const struct GNUNET_CADET_ChannelManageMessage *cm)
1475 struct CadetTunnel *t = cls;
1476 GNUNET_break (0); // FIXME!
1483 * @param cls the `struct CadetTunnel` for which we decrypted the message
1484 * @param cm the message we received on the tunnel
1487 handle_plaintext_channel_ack (void *cls,
1488 const struct GNUNET_CADET_ChannelManageMessage *cm)
1490 struct CadetTunnel *t = cls;
1491 GNUNET_break (0); // FIXME!
1498 * @param cls the `struct CadetTunnel` for which we decrypted the message
1499 * @param cm the message we received on the tunnel
1502 handle_plaintext_channel_destroy (void *cls,
1503 const struct GNUNET_CADET_ChannelManageMessage *cm)
1505 struct CadetTunnel *t = cls;
1506 GNUNET_break (0); // FIXME!
1511 * Handles a message we decrypted, by injecting it into
1512 * our message queue (which will do the dispatching).
1514 * @param cls the `struct CadetTunnel` that got the message
1515 * @param msg the message
1516 * @return #GNUNET_OK (continue to process)
1519 handle_decrypted (void *cls,
1520 const struct GNUNET_MessageHeader *msg)
1522 struct CadetTunnel *t = cls;
1524 GNUNET_MQ_inject_message (t->mq,
1531 * Function called if we had an error processing
1532 * an incoming decrypted message.
1534 * @param cls the `struct CadetTunnel`
1535 * @param error error code
1538 decrypted_error_cb (void *cls,
1539 enum GNUNET_MQ_Error error)
1541 GNUNET_break_op (0);
1546 * Create a tunnel to @a destionation. Must only be called
1547 * from within #GCP_get_tunnel().
1549 * @param destination where to create the tunnel to
1550 * @return new tunnel to @a destination
1552 struct CadetTunnel *
1553 GCT_create_tunnel (struct CadetPeer *destination)
1555 struct GNUNET_MQ_MessageHandler handlers[] = {
1556 GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
1557 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
1558 struct GNUNET_MessageHeader,
1560 GNUNET_MQ_hd_var_size (plaintext_data,
1561 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
1562 struct GNUNET_CADET_ChannelAppDataMessage,
1564 GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
1565 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
1566 struct GNUNET_CADET_ChannelDataAckMessage,
1568 GNUNET_MQ_hd_fixed_size (plaintext_channel_create,
1569 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
1570 struct GNUNET_CADET_ChannelOpenMessage,
1572 GNUNET_MQ_hd_fixed_size (plaintext_channel_nack,
1573 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_NACK_DEPRECATED,
1574 struct GNUNET_CADET_ChannelManageMessage,
1576 GNUNET_MQ_hd_fixed_size (plaintext_channel_ack,
1577 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
1578 struct GNUNET_CADET_ChannelManageMessage,
1580 GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
1581 GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
1582 struct GNUNET_CADET_ChannelManageMessage,
1584 GNUNET_MQ_handler_end ()
1586 struct CadetTunnel *t;
1588 t = GNUNET_new (struct CadetTunnel);
1589 t->destination = destination;
1590 t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
1591 (void) GCP_iterate_paths (destination,
1594 t->maintain_connections_task
1595 = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
1597 t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
1602 &decrypted_error_cb,
1604 t->mst = GNUNET_MST_create (&handle_decrypted,
1611 * Remove a channel from a tunnel.
1615 * @param gid unique number identifying @a ch within @a t
1618 GCT_remove_channel (struct CadetTunnel *t,
1619 struct CadetChannel *ch,
1620 struct GCT_ChannelTunnelNumber gid)
1622 GNUNET_assert (GNUNET_YES ==
1623 GNUNET_CONTAINER_multihashmap32_remove (t->channels,
1624 ntohl (gid.channel_in_tunnel),
1627 GNUNET_CONTAINER_multihashmap32_size (t->channels))
1629 t->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
1637 * Change the tunnel encryption state.
1638 * If the encryption state changes to OK, stop the rekey task.
1640 * @param t Tunnel whose encryption state to change, or NULL.
1641 * @param state New encryption state.
1644 GCT_change_estate (struct CadetTunnel *t,
1645 enum CadetTunnelEState state)
1647 enum CadetTunnelEState old = t->estate;
1650 LOG (GNUNET_ERROR_TYPE_DEBUG,
1651 "Tunnel %s estate changed from %d to %d\n",
1656 if ( (CADET_TUNNEL_KEY_OK != old) &&
1657 (CADET_TUNNEL_KEY_OK == t->estate) )
1659 if (NULL != t->rekey_task)
1661 GNUNET_SCHEDULER_cancel (t->rekey_task);
1662 t->rekey_task = NULL;
1665 /* Send queued data if tunnel is not loopback */
1666 if (myid != GCP_get_short_id (t->peer))
1667 send_queued_data (t);
1674 * Handle KX message.
1676 * @param ct connection/tunnel combo that received encrypted message
1677 * @param msg the key exchange message
1680 GCT_handle_kx (struct CadetTConnection *ct,
1681 const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
1683 GNUNET_break (0); // not implemented
1688 * Handle encrypted message.
1690 * @param ct connection/tunnel combo that received encrypted message
1691 * @param msg the encrypted message to decrypt
1694 GCT_handle_encrypted (struct CadetTConnection *ct,
1695 const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
1697 struct CadetTunnel *t = ct->t;
1698 uint16_t size = ntohs (msg->header.size);
1699 char cbuf [size] GNUNET_ALIGN;
1700 ssize_t decrypted_size;
1702 GNUNET_STATISTICS_update (stats,
1703 "# received encrypted",
1707 decrypted_size = t_ax_decrypt_and_validate (t,
1712 if (-1 == decrypted_size)
1714 GNUNET_STATISTICS_update (stats,
1715 "# unable to decrypt",
1718 if (CADET_TUNNEL_KEY_PING <= t->estate)
1720 GNUNET_break_op (0);
1721 LOG (GNUNET_ERROR_TYPE_WARNING,
1722 "Wrong crypto, tunnel %s\n",
1725 GNUNET_ERROR_TYPE_WARNING);
1730 GCT_change_estate (t,
1731 CADET_TUNNEL_KEY_OK);
1732 /* The MST will ultimately call #handle_decrypted() on each message. */
1733 GNUNET_break_op (GNUNET_OK ==
1734 GNUNET_MST_from_buffer (t->mst,
1743 * Sends an already built message on a tunnel, encrypting it and
1744 * choosing the best connection if not provided.
1746 * @param message Message to send. Function modifies it.
1747 * @param t Tunnel on which this message is transmitted.
1748 * @param cont Continuation to call once message is really sent.
1749 * @param cont_cls Closure for @c cont.
1750 * @return Handle to cancel message. NULL if @c cont is NULL.
1752 struct CadetTunnelQueueEntry *
1753 GCT_send (struct CadetTunnel *t,
1754 const struct GNUNET_MessageHeader *message,
1755 GNUNET_SCHEDULER_TaskCallback cont,
1758 struct CadetTunnelQueueEntry *tq;
1759 uint16_t payload_size;
1760 struct GNUNET_MQ_Envelope *env;
1761 struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
1763 /* FIXME: what about KX not yet being ready? (see "is_ready()" check in old code!) */
1765 payload_size = ntohs (message->size);
1766 env = GNUNET_MQ_msg_extra (ax_msg,
1768 GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
1773 ax_msg->Ns = htonl (t->ax.Ns++);
1774 ax_msg->PNs = htonl (t->ax.PNs);
1775 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax.DHRs,
1779 t_hmac (&ax_msg->Ns,
1780 AX_HEADER_SIZE + payload_size,
1784 // ax_msg->pid = htonl (GCC_get_pid (c, fwd)); // FIXME: connection flow-control not (re)implemented yet!
1786 tq = GNUNET_malloc (sizeof (*tq));
1789 tq->cid = &ax_msg->cid;
1791 tq->cont_cls = cont_cls;
1792 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
1795 trigger_transmissions (t);
1801 * Cancel a previously sent message while it's in the queue.
1803 * ONLY can be called before the continuation given to the send
1804 * function is called. Once the continuation is called, the message is
1805 * no longer in the queue!
1807 * @param q Handle to the queue entry to cancel.
1810 GCT_send_cancel (struct CadetTunnelQueueEntry *q)
1812 struct CadetTunnel *t = q->t;
1814 GNUNET_CONTAINER_DLL_remove (t->tq_head,
1822 * Iterate over all connections of a tunnel.
1824 * @param t Tunnel whose connections to iterate.
1825 * @param iter Iterator.
1826 * @param iter_cls Closure for @c iter.
1829 GCT_iterate_connections (struct CadetTunnel *t,
1830 GCT_ConnectionIterator iter,
1833 for (struct CadetTConnection *ct = t->connection_head;
1842 * Closure for #iterate_channels_cb.
1849 GCT_ChannelIterator iter;
1852 * Closure for @e iter.
1859 * Helper function for #GCT_iterate_channels.
1861 * @param cls the `struct ChanIterCls`
1863 * @param value a `struct CadetChannel`
1864 * @return #GNUNET_OK
1867 iterate_channels_cb (void *cls,
1871 struct ChanIterCls *ctx = cls;
1872 struct CadetChannel *ch = value;
1874 ctx->iter (ctx->iter_cls,
1881 * Iterate over all channels of a tunnel.
1883 * @param t Tunnel whose channels to iterate.
1884 * @param iter Iterator.
1885 * @param iter_cls Closure for @c iter.
1888 GCT_iterate_channels (struct CadetTunnel *t,
1889 GCT_ChannelIterator iter,
1892 struct ChanIterCls ctx;
1895 ctx.iter_cls = iter_cls;
1896 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1897 &iterate_channels_cb,
1904 * Call #GCCH_debug() on a channel.
1906 * @param cls points to the log level to use
1908 * @param value the `struct CadetChannel` to dump
1909 * @return #GNUNET_OK (continue iteration)
1912 debug_channel (void *cls,
1916 const enum GNUNET_ErrorType *level = cls;
1917 struct CadetChannel *ch = value;
1919 GCCH_debug (ch, *level);
1925 * Get string description for tunnel connectivity state.
1927 * @param cs Tunnel state.
1929 * @return String representation.
1932 cstate2s (enum CadetTunnelCState cs)
1934 static char buf[32];
1938 case CADET_TUNNEL_NEW:
1939 return "CADET_TUNNEL_NEW";
1940 case CADET_TUNNEL_SEARCHING:
1941 return "CADET_TUNNEL_SEARCHING";
1942 case CADET_TUNNEL_WAITING:
1943 return "CADET_TUNNEL_WAITING";
1944 case CADET_TUNNEL_READY:
1945 return "CADET_TUNNEL_READY";
1946 case CADET_TUNNEL_SHUTDOWN:
1947 return "CADET_TUNNEL_SHUTDOWN";
1949 SPRINTF (buf, "%u (UNKNOWN STATE)", cs);
1956 * Get string description for tunnel encryption state.
1958 * @param es Tunnel state.
1960 * @return String representation.
1963 estate2s (enum CadetTunnelEState es)
1965 static char buf[32];
1969 case CADET_TUNNEL_KEY_UNINITIALIZED:
1970 return "CADET_TUNNEL_KEY_UNINITIALIZED";
1971 case CADET_TUNNEL_KEY_SENT:
1972 return "CADET_TUNNEL_KEY_SENT";
1973 case CADET_TUNNEL_KEY_PING:
1974 return "CADET_TUNNEL_KEY_PING";
1975 case CADET_TUNNEL_KEY_OK:
1976 return "CADET_TUNNEL_KEY_OK";
1977 case CADET_TUNNEL_KEY_REKEY:
1978 return "CADET_TUNNEL_KEY_REKEY";
1980 SPRINTF (buf, "%u (UNKNOWN STATE)", es);
1986 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
1990 * Log all possible info about the tunnel state.
1992 * @param t Tunnel to debug.
1993 * @param level Debug level to use.
1996 GCT_debug (const struct CadetTunnel *t,
1997 enum GNUNET_ErrorType level)
1999 struct CadetTConnection *iter_c;
2002 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
2004 __FILE__, __FUNCTION__, __LINE__);
2009 "TTT TUNNEL TOWARDS %s in cstate %s, estate %s tq_len: %u #cons: %u\n",
2011 cstate2s (t->cstate),
2012 estate2s (t->estate),
2014 t->num_connections);
2015 #if DUMP_KEYS_TO_STDERR
2016 ax_debug (t->ax, level);
2020 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2024 "TTT connections:\n");
2025 for (iter_c = t->connection_head; NULL != iter_c; iter_c = iter_c->next)
2026 GCC_debug (iter_c->cc,
2030 "TTT TUNNEL END\n");
2034 /* end of gnunet-service-cadet-new_tunnels.c */