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_statistics_service.h"
37 #include "gnunet_signatures.h"
38 #include "cadet_protocol.h"
39 #include "cadet_path.h"
40 #include "gnunet-service-cadet-new.h"
41 #include "gnunet-service-cadet-new_channel.h"
42 #include "gnunet-service-cadet-new_connection.h"
43 #include "gnunet-service-cadet-new_tunnels.h"
44 #include "gnunet-service-cadet-new_peer.h"
45 #include "gnunet-service-cadet-new_paths.h"
48 #define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__)
52 * How long do we wait until tearing down an idle tunnel?
54 #define IDLE_DESTROY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90)
57 * Yuck, replace by 'offsetof' expression?
60 #define AX_HEADER_SIZE (sizeof (uint32_t) * 2\
61 + sizeof (struct GNUNET_CRYPTO_EcdhePublicKey))
65 * Maximum number of skipped keys we keep in memory per tunnel.
67 #define MAX_SKIPPED_KEYS 64
70 * Maximum number of keys (and thus ratchet steps) we are willing to
71 * skip before we decide this is either a bogus packet or a DoS-attempt.
73 #define MAX_KEY_GAP 256
77 * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
79 struct CadetTunnelSkippedKey
84 struct CadetTunnelSkippedKey *next;
89 struct CadetTunnelSkippedKey *prev;
92 * When was this key stored (for timeout).
94 struct GNUNET_TIME_Absolute timestamp;
99 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
104 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
107 * Key number for a given HK.
114 * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
116 struct CadetTunnelAxolotl
119 * A (double linked) list of stored message keys and associated header keys
120 * for "skipped" messages, i.e. messages that have not been
121 * received despite the reception of more recent messages, (head).
123 struct CadetTunnelSkippedKey *skipped_head;
126 * Skipped messages' keys DLL, tail.
128 struct CadetTunnelSkippedKey *skipped_tail;
131 * 32-byte root key which gets updated by DH ratchet.
133 struct GNUNET_CRYPTO_SymmetricSessionKey RK;
136 * 32-byte header key (send).
138 struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
141 * 32-byte header key (recv)
143 struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
146 * 32-byte next header key (send).
148 struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
151 * 32-byte next header key (recv).
153 struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
156 * 32-byte chain keys (used for forward-secrecy updating, send).
158 struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
161 * 32-byte chain keys (used for forward-secrecy updating, recv).
163 struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
166 * ECDH for key exchange (A0 / B0).
168 struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
171 * ECDH Ratchet key (send).
173 struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
176 * ECDH Ratchet key (recv).
178 struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
181 * When does this ratchet expire and a new one is triggered.
183 struct GNUNET_TIME_Absolute ratchet_expiration;
186 * Number of elements in @a skipped_head <-> @a skipped_tail.
188 unsigned int skipped;
191 * Message number (reset to 0 with each new ratchet, next message to send).
196 * Message number (reset to 0 with each new ratchet, next message to recv).
201 * Previous message numbers (# of msgs sent under prev ratchet)
206 * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
211 * Number of messages recieved since our last ratchet advance.
212 * - If this counter = 0, we cannot send a new ratchet key in next msg.
213 * - If this counter > 0, we can (but don't yet have to) send a new key.
215 unsigned int ratchet_allowed;
218 * Number of messages recieved since our last ratchet advance.
219 * - If this counter = 0, we cannot send a new ratchet key in next msg.
220 * - If this counter > 0, we can (but don't yet have to) send a new key.
222 unsigned int ratchet_counter;
228 * Entry in list of connections used by tunnel, with metadata.
230 struct CadetTConnection
235 struct CadetTConnection *next;
240 struct CadetTConnection *prev;
245 struct CadetConnection *cc;
248 * Tunnel this connection belongs to.
250 struct CadetTunnel *t;
253 * Creation time, to keep oldest connection alive.
255 struct GNUNET_TIME_Absolute created;
258 * Connection throughput, to keep fastest connection alive.
265 * Struct used to save messages in a non-ready tunnel to send once connected.
267 struct CadetTunnelQueueEntry
270 * We are entries in a DLL
272 struct CadetTunnelQueueEntry *next;
275 * We are entries in a DLL
277 struct CadetTunnelQueueEntry *prev;
280 * Tunnel these messages belong in.
282 struct CadetTunnel *t;
285 * Continuation to call once sent (on the channel layer).
287 GNUNET_SCHEDULER_TaskCallback cont;
290 * Closure for @c cont.
295 * Envelope of message to send follows.
297 struct GNUNET_MQ_Envelope *env;
300 * Where to put the connection identifier into the payload
301 * of the message in @e env once we have it?
303 struct GNUNET_CADET_ConnectionTunnelIdentifier *cid;
308 * Struct containing all information regarding a tunnel to a peer.
313 * Destination of the tunnel.
315 struct CadetPeer *destination;
318 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own
319 * ephemeral key changes.
321 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
324 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
326 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
329 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
331 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
336 struct CadetTunnelAxolotl ax;
339 * State of the tunnel connectivity.
341 enum CadetTunnelCState cstate;
344 * State of the tunnel encryption.
346 enum CadetTunnelEState estate;
349 * Task to start the rekey process.
351 struct GNUNET_SCHEDULER_Task *rekey_task;
354 * DLL of connections that are actively used to reach the destination peer.
356 struct CadetTConnection *connection_head;
359 * DLL of connections that are actively used to reach the destination peer.
361 struct CadetTConnection *connection_tail;
364 * Channels inside this tunnel. Maps
365 * `struct GCT_ChannelTunnelNumber` to a `struct CadetChannel`.
367 struct GNUNET_CONTAINER_MultiHashMap32 *channels;
370 * Channel ID for the next created channel in this tunnel.
372 struct GCT_ChannelTunnelNumber next_chid;
375 * Queued messages, to transmit once tunnel gets connected.
377 struct CadetTunnelQueueEntry *tq_head;
380 * Queued messages, to transmit once tunnel gets connected.
382 struct CadetTunnelQueueEntry *tq_tail;
385 * Task scheduled if there are no more channels using the tunnel.
387 struct GNUNET_SCHEDULER_Task *destroy_task;
390 * Task to trim connections if too many are present.
392 struct GNUNET_SCHEDULER_Task *maintain_connections_task;
395 * Ephemeral message in the queue (to avoid queueing more than one).
397 struct CadetConnectionQueue *ephm_hKILL;
400 * Pong message in the queue.
402 struct CadetConnectionQueue *pong_hKILL;
405 * Number of connections in the @e connection_head DLL.
407 unsigned int num_connections;
410 * Number of entries in the @e tq_head DLL.
417 * Get the static string for the peer this tunnel is directed.
421 * @return Static string the destination peer's ID.
424 GCT_2s (const struct CadetTunnel *t)
431 GNUNET_snprintf (buf,
434 GCP_2s (t->destination));
440 * Return the peer to which this tunnel goes.
443 * @return the destination of the tunnel
446 GCT_get_destination (struct CadetTunnel *t)
448 return t->destination;
453 * Count channels of a tunnel.
455 * @param t Tunnel on which to count.
457 * @return Number of channels.
460 GCT_count_channels (struct CadetTunnel *t)
462 return GNUNET_CONTAINER_multihashmap32_size (t->channels);
467 * Count all created connections of a tunnel. Not necessarily ready connections!
469 * @param t Tunnel on which to count.
471 * @return Number of connections created, either being established or ready.
474 GCT_count_any_connections (struct CadetTunnel *t)
476 return t->num_connections;
481 * Get the connectivity state of a tunnel.
485 * @return Tunnel's connectivity state.
487 enum CadetTunnelCState
488 GCT_get_cstate (struct CadetTunnel *t)
495 * Get the encryption state of a tunnel.
499 * @return Tunnel's encryption state.
501 enum CadetTunnelEState
502 GCT_get_estate (struct CadetTunnel *t)
509 * Create a new Axolotl ephemeral (ratchet) key.
514 new_ephemeral (struct CadetTunnel *t)
516 GNUNET_free_non_null (t->ax.DHRs);
517 t->ax.DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
521 /* ************************************** start core crypto ***************************** */
527 * @param plaintext Content to HMAC.
528 * @param size Size of @c plaintext.
529 * @param iv Initialization vector for the message.
530 * @param key Key to use.
531 * @param hmac[out] Destination to store the HMAC.
534 t_hmac (const void *plaintext,
537 const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
538 struct GNUNET_ShortHashCode *hmac)
540 static const char ctx[] = "cadet authentication key";
541 struct GNUNET_CRYPTO_AuthKey auth_key;
542 struct GNUNET_HashCode hash;
544 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
550 /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
551 GNUNET_CRYPTO_hmac (&auth_key,
564 * @param key Key to use.
565 * @param hash[out] Resulting HMAC.
566 * @param source Source key material (data to HMAC).
567 * @param len Length of @a source.
570 t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
571 struct GNUNET_HashCode *hash,
575 static const char ctx[] = "axolotl HMAC-HASH";
576 struct GNUNET_CRYPTO_AuthKey auth_key;
578 GNUNET_CRYPTO_hmac_derive_key (&auth_key,
582 GNUNET_CRYPTO_hmac (&auth_key,
590 * Derive a symmetric encryption key from an HMAC-HASH.
592 * @param key Key to use for the HMAC.
593 * @param[out] out Key to generate.
594 * @param source Source key material (data to HMAC).
595 * @param len Length of @a source.
598 t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
599 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
603 static const char ctx[] = "axolotl derive key";
604 struct GNUNET_HashCode h;
610 GNUNET_CRYPTO_kdf (out, sizeof (*out),
618 * Encrypt data with the axolotl tunnel key.
620 * @param t Tunnel whose key to use.
621 * @param dst Destination with @a size bytes for the encrypted data.
622 * @param src Source of the plaintext. Can overlap with @c dst, must contain @a size bytes
623 * @param size Size of the buffers at @a src and @a dst
626 t_ax_encrypt (struct CadetTunnel *t,
631 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
632 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
633 struct CadetTunnelAxolotl *ax;
637 ax->ratchet_counter++;
638 if ( (GNUNET_YES == ax->ratchet_allowed) &&
639 ( (ratchet_messages <= ax->ratchet_counter) ||
640 (0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us)) )
642 ax->ratchet_flag = GNUNET_YES;
644 if (GNUNET_YES == ax->ratchet_flag)
646 /* Advance ratchet */
647 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
648 struct GNUNET_HashCode dh;
649 struct GNUNET_HashCode hmac;
650 static const char ctx[] = "axolotl ratchet";
655 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
656 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
659 t_ax_hmac_hash (&ax->RK,
663 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
665 &hmac, sizeof (hmac),
673 ax->ratchet_flag = GNUNET_NO;
674 ax->ratchet_allowed = GNUNET_NO;
675 ax->ratchet_counter = 0;
676 ax->ratchet_expiration
677 = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
681 t_hmac_derive_key (&ax->CKs,
685 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
690 out_size = GNUNET_CRYPTO_symmetric_encrypt (src,
695 GNUNET_assert (size == out_size);
696 t_hmac_derive_key (&ax->CKs,
704 * Decrypt data with the axolotl tunnel key.
706 * @param t Tunnel whose key to use.
707 * @param dst Destination for the decrypted data, must contain @a size bytes.
708 * @param src Source of the ciphertext. Can overlap with @c dst, must contain @a size bytes.
709 * @param size Size of the @a src and @a dst buffers
712 t_ax_decrypt (struct CadetTunnel *t,
717 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
718 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
719 struct CadetTunnelAxolotl *ax;
723 t_hmac_derive_key (&ax->CKr,
727 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
731 GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
732 out_size = GNUNET_CRYPTO_symmetric_decrypt (src,
737 GNUNET_assert (out_size == size);
738 t_hmac_derive_key (&ax->CKr,
746 * Encrypt header with the axolotl header key.
748 * @param t Tunnel whose key to use.
749 * @param msg Message whose header to encrypt.
752 t_h_encrypt (struct CadetTunnel *t,
753 struct GNUNET_CADET_Encrypted *msg)
755 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
756 struct CadetTunnelAxolotl *ax;
760 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
764 out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->Ns,
769 GNUNET_assert (AX_HEADER_SIZE == out_size);
774 * Decrypt header with the current axolotl header key.
776 * @param t Tunnel whose current ax HK to use.
777 * @param src Message whose header to decrypt.
778 * @param dst Where to decrypt header to.
781 t_h_decrypt (struct CadetTunnel *t,
782 const struct GNUNET_CADET_Encrypted *src,
783 struct GNUNET_CADET_Encrypted *dst)
785 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
786 struct CadetTunnelAxolotl *ax;
790 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
794 out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns,
799 GNUNET_assert (AX_HEADER_SIZE == out_size);
804 * Delete a key from the list of skipped keys.
806 * @param t Tunnel to delete from.
807 * @param key Key to delete.
810 delete_skipped_key (struct CadetTunnel *t,
811 struct CadetTunnelSkippedKey *key)
813 GNUNET_CONTAINER_DLL_remove (t->ax.skipped_head,
822 * Decrypt and verify data with the appropriate tunnel key and verify that the
823 * data has not been altered since it was sent by the remote peer.
825 * @param t Tunnel whose key to use.
826 * @param dst Destination for the plaintext.
827 * @param src Source of the message. Can overlap with @c dst.
828 * @param size Size of the message.
829 * @return Size of the decrypted data, -1 if an error was encountered.
832 try_old_ax_keys (struct CadetTunnel *t,
834 const struct GNUNET_CADET_Encrypted *src,
837 struct CadetTunnelSkippedKey *key;
838 struct GNUNET_ShortHashCode *hmac;
839 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
840 struct GNUNET_CADET_Encrypted plaintext_header;
841 struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
847 LOG (GNUNET_ERROR_TYPE_DEBUG,
848 "Trying skipped keys\n");
849 hmac = &plaintext_header.hmac;
850 esize = size - sizeof (struct GNUNET_CADET_Encrypted);
852 /* Find a correct Header Key */
854 for (key = t->ax.skipped_head; NULL != key; key = key->next)
857 AX_HEADER_SIZE + esize,
861 if (0 == memcmp (hmac,
872 /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
873 GNUNET_assert (size > sizeof (struct GNUNET_CADET_Encrypted));
874 len = size - sizeof (struct GNUNET_CADET_Encrypted);
875 GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
878 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
882 res = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns,
886 &plaintext_header.Ns);
887 GNUNET_assert (AX_HEADER_SIZE == res);
889 /* Find the correct message key */
890 N = ntohl (plaintext_header.Ns);
891 while ( (NULL != key) &&
894 if ( (NULL == key) ||
895 (0 != memcmp (&key->HK,
897 sizeof (*valid_HK))) )
900 /* Decrypt payload */
901 GNUNET_CRYPTO_symmetric_derive_iv (&iv,
906 res = GNUNET_CRYPTO_symmetric_decrypt (&src[1],
911 delete_skipped_key (t,
918 * Delete a key from the list of skipped keys.
920 * @param t Tunnel to delete from.
921 * @param HKr Header Key to use.
924 store_skipped_key (struct CadetTunnel *t,
925 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
927 struct CadetTunnelSkippedKey *key;
929 key = GNUNET_new (struct CadetTunnelSkippedKey);
930 key->timestamp = GNUNET_TIME_absolute_get ();
933 t_hmac_derive_key (&t->ax.CKr,
937 t_hmac_derive_key (&t->ax.CKr,
941 GNUNET_CONTAINER_DLL_insert (t->ax.skipped_head,
950 * Stage skipped AX keys and calculate the message key.
951 * Stores each HK and MK for skipped messages.
953 * @param t Tunnel where to stage the keys.
954 * @param HKr Header key.
955 * @param Np Received meesage number.
956 * @return #GNUNET_OK if keys were stored.
957 * #GNUNET_SYSERR if an error ocurred (Np not expected).
960 store_ax_keys (struct CadetTunnel *t,
961 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
967 LOG (GNUNET_ERROR_TYPE_DEBUG,
968 "Storing skipped keys [%u, %u)\n",
971 if (MAX_KEY_GAP < gap)
973 /* Avoid DoS (forcing peer to do 2^33 chain HMAC operations) */
974 /* TODO: start new key exchange on return */
976 LOG (GNUNET_ERROR_TYPE_WARNING,
977 "Got message %u, expected %u+\n",
980 return GNUNET_SYSERR;
984 /* Delayed message: don't store keys, flag to try old keys. */
985 return GNUNET_SYSERR;
988 while (t->ax.Nr < Np)
989 store_skipped_key (t,
992 while (t->ax.skipped > MAX_SKIPPED_KEYS)
993 delete_skipped_key (t,
1000 * Decrypt and verify data with the appropriate tunnel key and verify that the
1001 * data has not been altered since it was sent by the remote peer.
1003 * @param t Tunnel whose key to use.
1004 * @param dst Destination for the plaintext.
1005 * @param src Source of the message. Can overlap with @c dst.
1006 * @param size Size of the message.
1007 * @return Size of the decrypted data, -1 if an error was encountered.
1010 t_ax_decrypt_and_validate (struct CadetTunnel *t,
1012 const struct GNUNET_CADET_Encrypted *src,
1015 struct CadetTunnelAxolotl *ax;
1016 struct GNUNET_ShortHashCode msg_hmac;
1017 struct GNUNET_HashCode hmac;
1018 struct GNUNET_CADET_Encrypted plaintext_header;
1021 size_t esize; /* Size of encryped payload */
1023 esize = size - sizeof (struct GNUNET_CADET_Encrypted);
1026 /* Try current HK */
1028 AX_HEADER_SIZE + esize,
1031 if (0 != memcmp (&msg_hmac,
1035 static const char ctx[] = "axolotl ratchet";
1036 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1037 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1038 struct GNUNET_HashCode dh;
1039 struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1043 AX_HEADER_SIZE + esize,
1047 if (0 != memcmp (&msg_hmac,
1051 /* Try the skipped keys, if that fails, we're out of luck. */
1052 return try_old_ax_keys (t,
1062 Np = ntohl (plaintext_header.Ns);
1063 PNp = ntohl (plaintext_header.PNs);
1064 DHRp = &plaintext_header.DHRs;
1069 /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1070 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
1073 t_ax_hmac_hash (&ax->RK,
1076 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1078 &hmac, sizeof (hmac),
1081 /* Commit "purported" keys */
1087 ax->ratchet_allowed = GNUNET_YES;
1094 Np = ntohl (plaintext_header.Ns);
1095 PNp = ntohl (plaintext_header.PNs);
1097 if ( (Np != ax->Nr) &&
1098 (GNUNET_OK != store_ax_keys (t,
1102 /* Try the skipped keys, if that fails, we're out of luck. */
1103 return try_old_ax_keys (t,
1118 /* ************************************** end core crypto ***************************** */
1122 * Add a channel to a tunnel.
1126 * @return unique number identifying @a ch within @a t
1128 struct GCT_ChannelTunnelNumber
1129 GCT_add_channel (struct CadetTunnel *t,
1130 struct CadetChannel *ch)
1132 struct GCT_ChannelTunnelNumber ret;
1135 chid = ntohl (t->next_chid.channel_in_tunnel);
1137 GNUNET_CONTAINER_multihashmap32_get (t->channels,
1140 GNUNET_assert (GNUNET_YES ==
1141 GNUNET_CONTAINER_multihashmap32_put (t->channels,
1144 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1145 t->next_chid.channel_in_tunnel = htonl (chid + 1);
1146 ret.channel_in_tunnel = htonl (chid);
1152 * This tunnel is no longer used, destroy it.
1154 * @param cls the idle tunnel
1157 destroy_tunnel (void *cls)
1159 struct CadetTunnel *t = cls;
1160 struct CadetTConnection *ct;
1161 struct CadetTunnelQueueEntry *tqe;
1163 t->destroy_task = NULL;
1164 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap32_size (t->channels));
1165 while (NULL != (ct = t->connection_head))
1167 GNUNET_assert (ct->t == t);
1168 GNUNET_CONTAINER_DLL_remove (t->connection_head,
1171 GCC_destroy (ct->cc);
1174 while (NULL != (tqe = t->tq_head))
1176 GNUNET_CONTAINER_DLL_remove (t->tq_head,
1179 GNUNET_MQ_discard (tqe->env);
1182 GCP_drop_tunnel (t->destination,
1184 GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
1185 if (NULL != t->maintain_connections_task)
1187 GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
1188 t->maintain_connections_task = NULL;
1195 * A connection is ready for transmission. Looks at our message queue
1196 * and if there is a message, sends it out via the connection.
1198 * @param cls the `struct CadetTConnection` that is ready
1201 connection_ready_cb (void *cls)
1203 struct CadetTConnection *ct = cls;
1204 struct CadetTunnel *t = ct->t;
1205 struct CadetTunnelQueueEntry *tq = t->tq_head;
1208 return; /* no messages pending right now */
1210 /* ready to send message 'tq' on tunnel 'ct' */
1211 GNUNET_assert (t == tq->t);
1212 GNUNET_CONTAINER_DLL_remove (t->tq_head,
1215 if (NULL != tq->cid)
1216 *tq->cid = *GCC_get_id (ct->cc);
1217 GCC_transmit (ct->cc,
1219 tq->cont (tq->cont_cls);
1225 * Called when either we have a new connection, or a new message in the
1226 * queue, or some existing connection has transmission capacity. Looks
1227 * at our message queue and if there is a message, picks a connection
1230 * @param t tunnel to process messages on
1233 trigger_transmissions (struct CadetTunnel *t)
1235 struct CadetTConnection *ct;
1237 if (NULL == t->tq_head)
1238 return; /* no messages pending right now */
1239 for (ct = t->connection_head;
1242 if (GNUNET_YES == GCC_is_ready (ct->cc))
1245 return; /* no connections ready */
1246 connection_ready_cb (ct);
1251 * Function called to maintain the connections underlying our tunnel.
1252 * Tries to maintain (incl. tear down) connections for the tunnel, and
1253 * if there is a significant change, may trigger transmissions.
1255 * Basically, needs to check if there are connections that perform
1256 * badly, and if so eventually kill them and trigger a replacement.
1257 * The strategy is to open one more connection than
1258 * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
1259 * least-performing one, and then inquire for new ones.
1261 * @param cls the `struct CadetTunnel`
1264 maintain_connections_cb (void *cls)
1266 struct CadetTunnel *t = cls;
1268 GNUNET_break (0); // FIXME: implement!
1273 * Consider using the path @a p for the tunnel @a t.
1274 * The tunnel destination is at offset @a off in path @a p.
1276 * @param cls our tunnel
1277 * @param path a path to our destination
1278 * @param off offset of the destination on path @a path
1279 * @return #GNUNET_YES (should keep iterating)
1282 consider_path_cb (void *cls,
1283 struct CadetPeerPath *path,
1286 struct CadetTunnel *t = cls;
1287 unsigned int min_length = UINT_MAX;
1288 GNUNET_CONTAINER_HeapCostType max_desire = 0;
1289 struct CadetTConnection *ct;
1291 /* Check if we care about the new path. */
1292 for (ct = t->connection_head;
1296 struct CadetPeerPath *ps;
1298 ps = GCC_get_path (ct->cc);
1300 return GNUNET_YES; /* duplicate */
1301 min_length = GNUNET_MIN (min_length,
1302 GCPP_get_length (ps));
1303 max_desire = GNUNET_MAX (max_desire,
1304 GCPP_get_desirability (ps));
1307 /* FIXME: not sure we should really just count
1308 'num_connections' here, as they may all have
1309 consistently failed to connect. */
1311 /* We iterate by increasing path length; if we have enough paths and
1312 this one is more than twice as long than what we are currently
1313 using, then ignore all of these super-long ones! */
1314 if ( (t->num_connections > DESIRED_CONNECTIONS_PER_TUNNEL) &&
1315 (min_length * 2 < off) )
1317 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1318 "Ignoring paths of length %u, they are way too long.\n",
1322 /* If we have enough paths and this one looks no better, ignore it. */
1323 if ( (t->num_connections >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
1324 (min_length < GCPP_get_length (path)) &&
1325 (max_desire > GCPP_get_desirability (path)) )
1327 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1328 "Ignoring path (%u/%llu) to %s, got something better already.\n",
1329 GCPP_get_length (path),
1330 (unsigned long long) GCPP_get_desirability (path),
1331 GCP_2s (t->destination));
1335 /* Path is interesting (better by some metric, or we don't have
1336 enough paths yet). */
1337 ct = GNUNET_new (struct CadetTConnection);
1338 ct->created = GNUNET_TIME_absolute_get ();
1340 ct->cc = GCC_create (t->destination,
1343 &connection_ready_cb,
1345 /* FIXME: schedule job to kill connection (and path?) if it takes
1346 too long to get ready! (And track performance data on how long
1347 other connections took with the tunnel!)
1348 => Note: to be done within 'connection'-logic! */
1349 GNUNET_CONTAINER_DLL_insert (t->connection_head,
1352 t->num_connections++;
1358 * Consider using the path @a p for the tunnel @a t.
1359 * The tunnel destination is at offset @a off in path @a p.
1361 * @param cls our tunnel
1362 * @param path a path to our destination
1363 * @param off offset of the destination on path @a path
1366 GCT_consider_path (struct CadetTunnel *t,
1367 struct CadetPeerPath *p,
1370 (void) consider_path_cb (t,
1377 * Create a tunnel to @a destionation. Must only be called
1378 * from within #GCP_get_tunnel().
1380 * @param destination where to create the tunnel to
1381 * @return new tunnel to @a destination
1383 struct CadetTunnel *
1384 GCT_create_tunnel (struct CadetPeer *destination)
1386 struct CadetTunnel *t;
1388 t = GNUNET_new (struct CadetTunnel);
1389 t->destination = destination;
1390 t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
1391 (void) GCP_iterate_paths (destination,
1394 t->maintain_connections_task
1395 = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
1402 * Remove a channel from a tunnel.
1406 * @param gid unique number identifying @a ch within @a t
1409 GCT_remove_channel (struct CadetTunnel *t,
1410 struct CadetChannel *ch,
1411 struct GCT_ChannelTunnelNumber gid)
1413 GNUNET_assert (GNUNET_YES ==
1414 GNUNET_CONTAINER_multihashmap32_remove (t->channels,
1415 ntohl (gid.channel_in_tunnel),
1418 GNUNET_CONTAINER_multihashmap32_size (t->channels))
1420 t->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
1428 * Change the tunnel encryption state.
1429 * If the encryption state changes to OK, stop the rekey task.
1431 * @param t Tunnel whose encryption state to change, or NULL.
1432 * @param state New encryption state.
1435 GCT_change_estate (struct CadetTunnel *t,
1436 enum CadetTunnelEState state)
1438 enum CadetTunnelEState old = t->estate;
1441 LOG (GNUNET_ERROR_TYPE_DEBUG,
1442 "Tunnel %s estate changed from %d to %d\n",
1447 if ( (CADET_TUNNEL_KEY_OK != old) &&
1448 (CADET_TUNNEL_KEY_OK == t->estate) )
1450 if (NULL != t->rekey_task)
1452 GNUNET_SCHEDULER_cancel (t->rekey_task);
1453 t->rekey_task = NULL;
1456 /* Send queued data if tunnel is not loopback */
1457 if (myid != GCP_get_short_id (t->peer))
1458 send_queued_data (t);
1465 * Handle KX message.
1467 * @param ct connection/tunnel combo that received encrypted message
1468 * @param msg the key exchange message
1471 GCT_handle_kx (struct CadetTConnection *ct,
1472 const struct GNUNET_CADET_KX *msg)
1474 GNUNET_break (0); // not implemented
1479 * Handle encrypted message.
1481 * @param ct connection/tunnel combo that received encrypted message
1482 * @param msg the encrypted message to decrypt
1485 GCT_handle_encrypted (struct CadetTConnection *ct,
1486 const struct GNUNET_CADET_Encrypted *msg)
1488 struct CadetTunnel *t = ct->t;
1489 uint16_t size = ntohs (msg->header.size);
1490 char cbuf [size] GNUNET_ALIGN;
1491 ssize_t decrypted_size;
1492 const struct GNUNET_MessageHeader *msgh;
1495 GNUNET_STATISTICS_update (stats,
1496 "# received encrypted",
1500 decrypted_size = t_ax_decrypt_and_validate (t,
1505 if (-1 == decrypted_size)
1507 GNUNET_STATISTICS_update (stats,
1508 "# unable to decrypt",
1511 if (CADET_TUNNEL_KEY_PING <= t->estate)
1513 GNUNET_break_op (0);
1514 LOG (GNUNET_ERROR_TYPE_WARNING,
1515 "Wrong crypto, tunnel %s\n",
1518 GNUNET_ERROR_TYPE_WARNING);
1523 GCT_change_estate (t,
1524 CADET_TUNNEL_KEY_OK);
1527 /* FIXME: this is bad, as the structs returned from
1528 this loop may be unaligned, see util's MST for
1529 how to do this right.
1530 => Change MST API to use new MQ-style handlers! */
1532 while (off + sizeof (struct GNUNET_MessageHeader) <= decrypted_size)
1536 msgh = (const struct GNUNET_MessageHeader *) &cbuf[off];
1537 msize = ntohs (msgh->size);
1538 if (msize < sizeof (struct GNUNET_MessageHeader))
1540 GNUNET_break_op (0);
1543 if (off + msize < decrypted_size)
1545 GNUNET_break_op (0);
1548 handle_decrypted (t,
1557 * Sends an already built message on a tunnel, encrypting it and
1558 * choosing the best connection if not provided.
1560 * @param message Message to send. Function modifies it.
1561 * @param t Tunnel on which this message is transmitted.
1562 * @param cont Continuation to call once message is really sent.
1563 * @param cont_cls Closure for @c cont.
1564 * @return Handle to cancel message. NULL if @c cont is NULL.
1566 struct CadetTunnelQueueEntry *
1567 GCT_send (struct CadetTunnel *t,
1568 const struct GNUNET_MessageHeader *message,
1569 GNUNET_SCHEDULER_TaskCallback cont,
1572 struct CadetTunnelQueueEntry *tq;
1573 uint16_t payload_size;
1574 struct GNUNET_MQ_Envelope *env;
1575 struct GNUNET_CADET_Encrypted *ax_msg;
1577 /* FIXME: what about KX not yet being ready? (see "is_ready()" check in old code!) */
1579 payload_size = ntohs (message->size);
1580 env = GNUNET_MQ_msg_extra (ax_msg,
1582 GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
1587 ax_msg->Ns = htonl (t->ax.Ns++);
1588 ax_msg->PNs = htonl (t->ax.PNs);
1589 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax.DHRs,
1593 t_hmac (&ax_msg->Ns,
1594 AX_HEADER_SIZE + payload_size,
1598 // ax_msg->pid = htonl (GCC_get_pid (c, fwd)); // FIXME: connection flow-control not (re)implemented yet!
1600 tq = GNUNET_malloc (sizeof (*tq));
1603 tq->cid = &ax_msg->cid;
1605 tq->cont_cls = cont_cls;
1606 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
1609 trigger_transmissions (t);
1615 * Cancel a previously sent message while it's in the queue.
1617 * ONLY can be called before the continuation given to the send
1618 * function is called. Once the continuation is called, the message is
1619 * no longer in the queue!
1621 * @param q Handle to the queue entry to cancel.
1624 GCT_send_cancel (struct CadetTunnelQueueEntry *q)
1626 struct CadetTunnel *t = q->t;
1628 GNUNET_CONTAINER_DLL_remove (t->tq_head,
1636 * Iterate over all connections of a tunnel.
1638 * @param t Tunnel whose connections to iterate.
1639 * @param iter Iterator.
1640 * @param iter_cls Closure for @c iter.
1643 GCT_iterate_connections (struct CadetTunnel *t,
1644 GCT_ConnectionIterator iter,
1647 for (struct CadetTConnection *ct = t->connection_head;
1656 * Closure for #iterate_channels_cb.
1663 GCT_ChannelIterator iter;
1666 * Closure for @e iter.
1673 * Helper function for #GCT_iterate_channels.
1675 * @param cls the `struct ChanIterCls`
1677 * @param value a `struct CadetChannel`
1678 * @return #GNUNET_OK
1681 iterate_channels_cb (void *cls,
1685 struct ChanIterCls *ctx = cls;
1686 struct CadetChannel *ch = value;
1688 ctx->iter (ctx->iter_cls,
1695 * Iterate over all channels of a tunnel.
1697 * @param t Tunnel whose channels to iterate.
1698 * @param iter Iterator.
1699 * @param iter_cls Closure for @c iter.
1702 GCT_iterate_channels (struct CadetTunnel *t,
1703 GCT_ChannelIterator iter,
1706 struct ChanIterCls ctx;
1709 ctx.iter_cls = iter_cls;
1710 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1711 &iterate_channels_cb,
1718 * Call #GCCH_debug() on a channel.
1720 * @param cls points to the log level to use
1722 * @param value the `struct CadetChannel` to dump
1723 * @return #GNUNET_OK (continue iteration)
1726 debug_channel (void *cls,
1730 const enum GNUNET_ErrorType *level = cls;
1731 struct CadetChannel *ch = value;
1733 GCCH_debug (ch, *level);
1739 * Get string description for tunnel connectivity state.
1741 * @param cs Tunnel state.
1743 * @return String representation.
1746 cstate2s (enum CadetTunnelCState cs)
1748 static char buf[32];
1752 case CADET_TUNNEL_NEW:
1753 return "CADET_TUNNEL_NEW";
1754 case CADET_TUNNEL_SEARCHING:
1755 return "CADET_TUNNEL_SEARCHING";
1756 case CADET_TUNNEL_WAITING:
1757 return "CADET_TUNNEL_WAITING";
1758 case CADET_TUNNEL_READY:
1759 return "CADET_TUNNEL_READY";
1760 case CADET_TUNNEL_SHUTDOWN:
1761 return "CADET_TUNNEL_SHUTDOWN";
1763 SPRINTF (buf, "%u (UNKNOWN STATE)", cs);
1770 * Get string description for tunnel encryption state.
1772 * @param es Tunnel state.
1774 * @return String representation.
1777 estate2s (enum CadetTunnelEState es)
1779 static char buf[32];
1783 case CADET_TUNNEL_KEY_UNINITIALIZED:
1784 return "CADET_TUNNEL_KEY_UNINITIALIZED";
1785 case CADET_TUNNEL_KEY_SENT:
1786 return "CADET_TUNNEL_KEY_SENT";
1787 case CADET_TUNNEL_KEY_PING:
1788 return "CADET_TUNNEL_KEY_PING";
1789 case CADET_TUNNEL_KEY_OK:
1790 return "CADET_TUNNEL_KEY_OK";
1791 case CADET_TUNNEL_KEY_REKEY:
1792 return "CADET_TUNNEL_KEY_REKEY";
1794 SPRINTF (buf, "%u (UNKNOWN STATE)", es);
1800 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
1804 * Log all possible info about the tunnel state.
1806 * @param t Tunnel to debug.
1807 * @param level Debug level to use.
1810 GCT_debug (const struct CadetTunnel *t,
1811 enum GNUNET_ErrorType level)
1813 struct CadetTConnection *iter_c;
1816 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
1818 __FILE__, __FUNCTION__, __LINE__);
1823 "TTT TUNNEL TOWARDS %s in cstate %s, estate %s tq_len: %u #cons: %u\n",
1825 cstate2s (t->cstate),
1826 estate2s (t->estate),
1828 t->num_connections);
1829 #if DUMP_KEYS_TO_STDERR
1830 ax_debug (t->ax, level);
1834 GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1838 "TTT connections:\n");
1839 for (iter_c = t->connection_head; NULL != iter_c; iter_c = iter_c->next)
1840 GCC_debug (iter_c->cc,
1844 "TTT TUNNEL END\n");
1848 /* end of gnunet-service-cadet-new_tunnels.c */