2 This file is part of GNUnet.
3 Copyright (C) 2013 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 #include "gnunet_util_lib.h"
24 #include "gnunet_signatures.h"
25 #include "gnunet_statistics_service.h"
27 #include "cadet_protocol.h"
28 #include "cadet_path.h"
30 #include "gnunet-service-cadet_tunnel.h"
31 #include "gnunet-service-cadet_connection.h"
32 #include "gnunet-service-cadet_channel.h"
33 #include "gnunet-service-cadet_peer.h"
35 #define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__)
36 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
38 #define REKEY_WAIT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5)
40 #if !defined(GNUNET_CULL_LOGGING)
41 #define DUMP_KEYS_TO_STDERR GNUNET_YES
43 #define DUMP_KEYS_TO_STDERR GNUNET_NO
46 /******************************************************************************/
47 /******************************** STRUCTS **********************************/
48 /******************************************************************************/
52 struct CadetTChannel *next;
53 struct CadetTChannel *prev;
54 struct CadetChannel *ch;
59 * Connection list and metadata.
61 struct CadetTConnection
66 struct CadetTConnection *next;
71 struct CadetTConnection *prev;
76 struct CadetConnection *c;
79 * Creation time, to keep oldest connection alive.
81 struct GNUNET_TIME_Absolute created;
84 * Connection throughput, to keep fastest connection alive.
90 * Structure used during a Key eXchange.
92 struct CadetTunnelKXCtx
95 * Encryption ("our") old "confirmed" key, for encrypting traffic sent by us
96 * end before the key exchange is finished or times out.
98 struct GNUNET_CRYPTO_SymmetricSessionKey e_key_old;
101 * Decryption ("their") old "confirmed" key, for decrypting traffic sent by
102 * the other end before the key exchange started.
104 struct GNUNET_CRYPTO_SymmetricSessionKey d_key_old;
107 * Same as @c e_key_old, for the case of two simultaneous KX.
108 * This can happen if cadet decides to start a re-key while the peer has also
109 * started its re-key (due to network delay this is impossible to avoid).
110 * In this case, the key material generated with the peer's old ephemeral
111 * *might* (but doesn't have to) be incorrect.
112 * Since no more than two re-keys can happen simultaneously, this is enough.
114 struct GNUNET_CRYPTO_SymmetricSessionKey e_key_old2;
117 * Same as @c d_key_old, for the case described in @c e_key_old2.
119 struct GNUNET_CRYPTO_SymmetricSessionKey d_key_old2;
122 * Challenge to send and expect in the PONG.
127 * When the rekey started. One minute after this the new key will be used.
129 struct GNUNET_TIME_Absolute rekey_start_time;
132 * Task for delayed destruction of the Key eXchange context, to allow delayed
133 * messages with the old key to be decrypted successfully.
135 struct GNUNET_SCHEDULER_Task * finish_task;
139 * Encryption systems possible.
141 enum CadetTunnelEncryption
144 * Default Axolotl system.
149 * Fallback OTR-style encryption.
154 struct CadetTunnelSkippedKey
156 struct CadetTunnelSkippedKey *next;
157 struct CadetTunnelSkippedKey *prev;
159 struct GNUNET_TIME_Absolute timestamp;
161 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
162 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
166 * Axolotl data, according to https://github.com/trevp/axolotl/wiki
168 struct CadetTunnelAxolotl
171 * A (double linked) list of stored message keys and associated header keys
172 * for "skipped" messages, i.e. messages that have not bee*n
173 * received despite the reception of more recent messages, (head)/
175 struct CadetTunnelSkippedKey *skipped_head;
178 * Skipped messages' keys DLL, tail.
180 struct CadetTunnelSkippedKey *skipped_tail;
183 * Elements in @a skipped_head <-> @a skipped_tail.
188 * 32-byte root key which gets updated by DH ratchet
190 struct GNUNET_CRYPTO_SymmetricSessionKey RK;
193 * 32-byte header key (send)
195 struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
198 * 32-byte header key (recv)
200 struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
203 * 32-byte next header key (send)
205 struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
208 * 32-byte next header key (recv)
210 struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
213 * 32-byte chain keys (used for forward-secrecy updating, send)
215 struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
218 * 32-byte chain keys (used for forward-secrecy updating, recv)
220 struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
223 * ECDH Ratchet key (send)
225 struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
228 * ECDH Ratchet key (recv)
230 struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
233 * Message number (reset to 0 with each new ratchet, send)
238 * Message numbers (reset to 0 with each new ratchet, recv)
243 * Previous message numbers (# of msgs sent under prev ratchet)
248 * True (#GNUNET_YES) if the party will send a new ratchet key in next msg.
254 * Struct containing all information regarding a tunnel to a peer.
259 * Endpoint of the tunnel.
261 struct CadetPeer *peer;
264 * Type of encryption used in the tunnel.
266 enum CadetTunnelEncryption enc_type;
271 struct CadetTunnelAxolotl *ax;
274 * State of the tunnel connectivity.
276 enum CadetTunnelCState cstate;
279 * State of the tunnel encryption.
281 enum CadetTunnelEState estate;
284 * Key eXchange context.
286 struct CadetTunnelKXCtx *kx_ctx;
289 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own ephemeral
292 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
295 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
297 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
300 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
302 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
305 * Task to start the rekey process.
307 struct GNUNET_SCHEDULER_Task * rekey_task;
310 * Paths that are actively used to reach the destination peer.
312 struct CadetTConnection *connection_head;
313 struct CadetTConnection *connection_tail;
316 * Next connection number.
321 * Channels inside this tunnel.
323 struct CadetTChannel *channel_head;
324 struct CadetTChannel *channel_tail;
327 * Channel ID for the next created channel.
329 CADET_ChannelNumber next_chid;
332 * Destroy flag: if true, destroy on last message.
334 struct GNUNET_SCHEDULER_Task * destroy_task;
337 * Queued messages, to transmit once tunnel gets connected.
339 struct CadetTunnelDelayed *tq_head;
340 struct CadetTunnelDelayed *tq_tail;
343 * Task to trim connections if too many are present.
345 struct GNUNET_SCHEDULER_Task * trim_connections_task;
348 * Ephemeral message in the queue (to avoid queueing more than one).
350 struct CadetConnectionQueue *ephm_h;
353 * Pong message in the queue.
355 struct CadetConnectionQueue *pong_h;
360 * Struct used to save messages in a non-ready tunnel to send once connected.
362 struct CadetTunnelDelayed
367 struct CadetTunnelDelayed *next;
368 struct CadetTunnelDelayed *prev;
373 struct CadetTunnel *t;
376 * Tunnel queue given to the channel to cancel request. Update on send_queued.
378 struct CadetTunnelQueue *tq;
383 /* struct GNUNET_MessageHeader *msg; */
388 * Handle for messages queued but not yet sent.
390 struct CadetTunnelQueue
393 * Connection queue handle, to cancel if necessary.
395 struct CadetConnectionQueue *cq;
398 * Handle in case message hasn't been given to a connection yet.
400 struct CadetTunnelDelayed *tqd;
403 * Continuation to call once sent.
408 * Closure for @c cont.
414 /******************************************************************************/
415 /******************************* GLOBALS ***********************************/
416 /******************************************************************************/
419 * Global handle to the statistics service.
421 extern struct GNUNET_STATISTICS_Handle *stats;
424 * Local peer own ID (memory efficient handle).
426 extern GNUNET_PEER_Id myid;
429 * Local peer own ID (full value).
431 extern struct GNUNET_PeerIdentity my_full_id;
435 * Don't try to recover tunnels if shutting down.
437 extern int shutting_down;
441 * Set of all tunnels, in order to trigger a new exchange on rekey.
442 * Indexed by peer's ID.
444 static struct GNUNET_CONTAINER_MultiPeerMap *tunnels;
447 * Default TTL for payload packets.
449 static unsigned long long default_ttl;
454 const static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
457 * Own OTR ephemeral private key.
459 static struct GNUNET_CRYPTO_EcdhePrivateKey *my_ephemeral_key;
462 * Cached message used to perform a key exchange.
464 static struct GNUNET_CADET_KX_Ephemeral kx_msg;
467 * Task to generate a new ephemeral key.
469 static struct GNUNET_SCHEDULER_Task * rekey_task;
474 static struct GNUNET_TIME_Relative rekey_period;
476 /******************************************************************************/
477 /******************************** STATIC ***********************************/
478 /******************************************************************************/
481 * Get string description for tunnel connectivity state.
483 * @param cs Tunnel state.
485 * @return String representation.
488 cstate2s (enum CadetTunnelCState cs)
494 case CADET_TUNNEL_NEW:
495 return "CADET_TUNNEL_NEW";
496 case CADET_TUNNEL_SEARCHING:
497 return "CADET_TUNNEL_SEARCHING";
498 case CADET_TUNNEL_WAITING:
499 return "CADET_TUNNEL_WAITING";
500 case CADET_TUNNEL_READY:
501 return "CADET_TUNNEL_READY";
502 case CADET_TUNNEL_SHUTDOWN:
503 return "CADET_TUNNEL_SHUTDOWN";
505 SPRINTF (buf, "%u (UNKNOWN STATE)", cs);
513 * Get string description for tunnel encryption state.
515 * @param es Tunnel state.
517 * @return String representation.
520 estate2s (enum CadetTunnelEState es)
526 case CADET_TUNNEL_KEY_UNINITIALIZED:
527 return "CADET_TUNNEL_KEY_UNINITIALIZED";
528 case CADET_TUNNEL_KEY_SENT:
529 return "CADET_TUNNEL_KEY_SENT";
530 case CADET_TUNNEL_KEY_PING:
531 return "CADET_TUNNEL_KEY_PING";
532 case CADET_TUNNEL_KEY_OK:
533 return "CADET_TUNNEL_KEY_OK";
534 case CADET_TUNNEL_KEY_REKEY:
535 return "CADET_TUNNEL_KEY_REKEY";
537 SPRINTF (buf, "%u (UNKNOWN STATE)", es);
545 * @brief Check if tunnel is ready to send traffic.
547 * Tunnel must be connected and with encryption correctly set up.
549 * @param t Tunnel to check.
551 * @return #GNUNET_YES if ready, #GNUNET_NO otherwise
554 is_ready (struct CadetTunnel *t)
558 GCT_debug (t, GNUNET_ERROR_TYPE_DEBUG);
559 ready = CADET_TUNNEL_READY == t->cstate
560 && (CADET_TUNNEL_KEY_OK == t->estate
561 || CADET_TUNNEL_KEY_REKEY == t->estate);
562 ready = ready || GCT_is_loopback (t);
568 * Check if a key is invalid (NULL pointer or all 0)
570 * @param key Key to check.
572 * @return #GNUNET_YES if key is null, #GNUNET_NO if exists and is not 0.
575 is_key_null (struct GNUNET_CRYPTO_SymmetricSessionKey *key)
577 struct GNUNET_CRYPTO_SymmetricSessionKey null_key;
582 memset (&null_key, 0, sizeof (null_key));
583 if (0 == memcmp (key, &null_key, sizeof (null_key)))
590 * Ephemeral key message purpose size.
592 * @return Size of the part of the ephemeral key message that must be signed.
595 ephemeral_purpose_size (void)
597 return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
598 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
599 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
600 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
601 sizeof (struct GNUNET_PeerIdentity);
606 * Size of the encrypted part of a ping message.
608 * @return Size of the encrypted part of a ping message.
611 ping_encryption_size (void)
613 return sizeof (uint32_t);
618 * Get the channel's buffer. ONLY FOR NON-LOOPBACK CHANNELS!!
620 * @param tch Tunnel's channel handle.
622 * @return Amount of messages the channel can still buffer towards the client.
625 get_channel_buffer (const struct CadetTChannel *tch)
629 /* If channel is incoming, is terminal in the FWD direction and fwd is YES */
630 fwd = GCCH_is_terminal (tch->ch, GNUNET_YES);
632 return GCCH_get_buffer (tch->ch, fwd);
637 * Get the channel's allowance status.
639 * @param tch Tunnel's channel handle.
641 * @return #GNUNET_YES if we allowed the client to send data to us.
644 get_channel_allowed (const struct CadetTChannel *tch)
648 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
649 fwd = GCCH_is_origin (tch->ch, GNUNET_YES);
651 return GCCH_get_allowed (tch->ch, fwd);
656 * Get the connection's buffer.
658 * @param tc Tunnel's connection handle.
660 * @return Amount of messages the connection can still buffer.
663 get_connection_buffer (const struct CadetTConnection *tc)
667 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
668 fwd = GCC_is_origin (tc->c, GNUNET_YES);
670 return GCC_get_buffer (tc->c, fwd);
675 * Get the connection's allowance.
677 * @param tc Tunnel's connection handle.
679 * @return Amount of messages we have allowed the next peer to send us.
682 get_connection_allowed (const struct CadetTConnection *tc)
686 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
687 fwd = GCC_is_origin (tc->c, GNUNET_YES);
689 return GCC_get_allowed (tc->c, fwd);
694 * Check that a ephemeral key message s well formed and correctly signed.
696 * @param t Tunnel on which the message came.
697 * @param msg The ephemeral key message.
699 * @return GNUNET_OK if message is fine, GNUNET_SYSERR otherwise.
702 check_ephemeral (struct CadetTunnel *t,
703 const struct GNUNET_CADET_KX_Ephemeral *msg)
705 /* Check message size */
706 if (ntohs (msg->header.size) != sizeof (struct GNUNET_CADET_KX_Ephemeral))
707 return GNUNET_SYSERR;
709 /* Check signature size */
710 if (ntohl (msg->purpose.size) != ephemeral_purpose_size ())
711 return GNUNET_SYSERR;
714 if (0 != memcmp (&msg->origin_identity,
715 GCP_get_id (t->peer),
716 sizeof (struct GNUNET_PeerIdentity)))
717 return GNUNET_SYSERR;
719 /* Check signature */
721 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_CADET_KX,
724 &msg->origin_identity.public_key))
725 return GNUNET_SYSERR;
732 * Select the best key to use for encryption (send), based on KX status.
734 * Normally, return the current key. If there is a KX in progress and the old
735 * key is fresh enough, return the old key.
737 * @param t Tunnel to choose the key from.
739 * @return The optimal key to encrypt/hmac outgoing traffic.
741 static const struct GNUNET_CRYPTO_SymmetricSessionKey *
742 select_key (const struct CadetTunnel *t)
744 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
746 if (NULL != t->kx_ctx
747 && NULL == t->kx_ctx->finish_task)
749 struct GNUNET_TIME_Relative age;
751 age = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
752 LOG (GNUNET_ERROR_TYPE_DEBUG,
753 " key exchange in progress, started %s ago\n",
754 GNUNET_STRINGS_relative_time_to_string (age, GNUNET_YES));
755 // FIXME make duration of old keys configurable
756 if (age.rel_value_us < GNUNET_TIME_UNIT_MINUTES.rel_value_us)
758 LOG (GNUNET_ERROR_TYPE_DEBUG, " using old key\n");
759 key = &t->kx_ctx->e_key_old;
763 LOG (GNUNET_ERROR_TYPE_DEBUG, " using new key (old key too old)\n");
769 LOG (GNUNET_ERROR_TYPE_DEBUG, " no KX: using current key\n");
779 * @param plaintext Content to HMAC.
780 * @param size Size of @c plaintext.
781 * @param iv Initialization vector for the message.
782 * @param key Key to use.
783 * @param hmac[out] Destination to store the HMAC.
786 t_hmac (const void *plaintext, size_t size,
787 uint32_t iv, const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
788 struct GNUNET_CADET_Hash *hmac)
790 static const char ctx[] = "cadet authentication key";
791 struct GNUNET_CRYPTO_AuthKey auth_key;
792 struct GNUNET_HashCode hash;
794 #if DUMP_KEYS_TO_STDERR
795 LOG (GNUNET_ERROR_TYPE_INFO, " HMAC with key %s\n",
796 GNUNET_h2s ((struct GNUNET_HashCode *) key));
798 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
803 /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
804 GNUNET_CRYPTO_hmac (&auth_key, plaintext, size, &hash);
805 memcpy (hmac, &hash, sizeof (*hmac));
810 * Encrypt daforce_newest_keyta with the tunnel key.
812 * @param t Tunnel whose key to use.
813 * @param dst Destination for the encrypted data.
814 * @param src Source of the plaintext. Can overlap with @c dst.
815 * @param size Size of the plaintext.
816 * @param iv Initialization Vector to use.
817 * @param force_newest_key Force the use of the newest key, otherwise
818 * CADET will use the old key when allowed.
819 * This can happen in the case when a KX is going on
820 * and the old one hasn't expired.
823 t_encrypt (struct CadetTunnel *t, void *dst, const void *src,
824 size_t size, uint32_t iv, int force_newest_key)
826 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
827 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
830 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt start\n");
832 key = GNUNET_YES == force_newest_key ? &t->e_key : select_key (t);
833 #if DUMP_KEYS_TO_STDERR
834 LOG (GNUNET_ERROR_TYPE_INFO, " ENC with key %s\n",
835 GNUNET_h2s ((struct GNUNET_HashCode *) key));
837 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
838 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt IV derived\n");
839 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, key, &siv, dst);
840 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt end\n");
847 * Decrypt and verify data with the appropriate tunnel key.
849 * @param key Key to use.
850 * @param dst Destination for the plaintext.
851 * @param src Source of the encrypted data. Can overlap with @c dst.
852 * @param size Size of the encrypted data.
853 * @param iv Initialization Vector to use.
855 * @return Size of the decrypted data, -1 if an error was encountered.
858 decrypt (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
859 void *dst, const void *src, size_t size, uint32_t iv)
861 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
864 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt start\n");
865 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv\n");
866 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
867 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv done\n");
868 out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, key, &siv, dst);
869 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt end\n");
876 * Decrypt and verify data with the most recent tunnel key.
878 * @param t Tunnel whose key to use.
879 * @param dst Destination for the plaintext.
880 * @param src Source of the encrypted data. Can overlap with @c dst.
881 * @param size Size of the encrypted data.
882 * @param iv Initialization Vector to use.
884 * @return Size of the decrypted data, -1 if an error was encountered.
887 t_decrypt (struct CadetTunnel *t, void *dst, const void *src,
888 size_t size, uint32_t iv)
892 #if DUMP_KEYS_TO_STDERR
893 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_decrypt with %s\n",
894 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
896 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
898 GNUNET_STATISTICS_update (stats, "# non decryptable data", 1, GNUNET_NO);
899 LOG (GNUNET_ERROR_TYPE_WARNING,
900 "got data on %s without a valid key\n",
902 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
906 out_size = decrypt (&t->d_key, dst, src, size, iv);
913 * Decrypt and verify data with the appropriate tunnel key and verify that the
914 * data has not been altered since it was sent by the remote peer.
916 * @param t Tunnel whose key to use.
917 * @param dst Destination for the plaintext.
918 * @param src Source of the encrypted data. Can overlap with @c dst.
919 * @param size Size of the encrypted data.
920 * @param iv Initialization Vector to use.
921 * @param msg_hmac HMAC of the message, cannot be NULL.
923 * @return Size of the decrypted data, -1 if an error was encountered.
926 t_decrypt_and_validate (struct CadetTunnel *t,
927 void *dst, const void *src,
928 size_t size, uint32_t iv,
929 const struct GNUNET_CADET_Hash *msg_hmac)
931 struct GNUNET_CRYPTO_SymmetricSessionKey *key;
932 struct GNUNET_CADET_Hash hmac;
935 /* Try primary (newest) key */
937 decrypted_size = decrypt (key, dst, src, size, iv);
938 t_hmac (src, size, iv, key, &hmac);
939 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
940 return decrypted_size;
942 /* If no key exchange is going on, we just failed. */
943 if (NULL == t->kx_ctx)
945 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
946 "Failed checksum validation on tunnel %s with no KX\n",
948 GNUNET_STATISTICS_update (stats, "# wrong HMAC no KX", 1, GNUNET_NO);
952 /* Try secondary key, from previous KX period. */
953 key = &t->kx_ctx->d_key_old;
954 decrypted_size = decrypt (key, dst, src, size, iv);
955 t_hmac (src, size, iv, key, &hmac);
956 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
957 return decrypted_size;
959 /* Hail Mary, try tertiary, key, in case of parallel re-keys. */
960 key = &t->kx_ctx->d_key_old2;
961 decrypted_size = decrypt (key, dst, src, size, iv);
962 t_hmac (src, size, iv, key, &hmac);
963 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
964 return decrypted_size;
966 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
967 "Failed checksum validation on tunnel %s with KX\n",
969 GNUNET_STATISTICS_update (stats, "# wrong HMAC with KX", 1, GNUNET_NO);
974 * Decrypt and verify data with the appropriate tunnel key and verify that the
975 * data has not been altered since it was sent by the remote peer.
977 * @param t Tunnel whose key to use.
978 * @param dst Destination for the plaintext.
979 * @param src Source of the encrypted data. Can overlap with @c dst.
980 * @param size Size of the encrypted data.
981 * @param msg_hmac HMAC of the message, cannot be NULL.
983 * @return Size of the decrypted data, -1 if an error was encountered.
986 t_ax_decrypt_and_validate (struct CadetTunnel *t,
987 void *dst, const void *src, size_t size,
988 const struct GNUNET_CADET_Hash *msg_hmac)
990 struct CadetTunnelAxolotl *ax;
1002 * Create key material by doing ECDH on the local and remote ephemeral keys.
1004 * @param key_material Where to store the key material.
1005 * @param ephemeral_key Peer's public ephemeral key.
1008 derive_key_material (struct GNUNET_HashCode *key_material,
1009 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key)
1012 GNUNET_CRYPTO_ecc_ecdh (my_ephemeral_key,
1022 * Create a symmetic key from the identities of both ends and the key material
1025 * @param key Destination for the generated key.
1026 * @param sender ID of the peer that will encrypt with @c key.
1027 * @param receiver ID of the peer that will decrypt with @c key.
1028 * @param key_material Hash created with ECDH with the ephemeral keys.
1031 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
1032 const struct GNUNET_PeerIdentity *sender,
1033 const struct GNUNET_PeerIdentity *receiver,
1034 const struct GNUNET_HashCode *key_material)
1036 const char salt[] = "CADET kx salt";
1038 GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
1039 salt, sizeof (salt),
1040 key_material, sizeof (struct GNUNET_HashCode),
1041 sender, sizeof (struct GNUNET_PeerIdentity),
1042 receiver, sizeof (struct GNUNET_PeerIdentity),
1048 * Derive the tunnel's keys using our own and the peer's ephemeral keys.
1050 * @param t Tunnel for which to create the keys.
1053 create_keys (struct CadetTunnel *t)
1055 struct GNUNET_HashCode km;
1057 derive_key_material (&km, &t->peers_ephemeral_key);
1058 derive_symmertic (&t->e_key, &my_full_id, GCP_get_id (t->peer), &km);
1059 derive_symmertic (&t->d_key, GCP_get_id (t->peer), &my_full_id, &km);
1060 #if DUMP_KEYS_TO_STDERR
1061 LOG (GNUNET_ERROR_TYPE_INFO, "ME: %s\n",
1062 GNUNET_h2s ((struct GNUNET_HashCode *) &kx_msg.ephemeral_key));
1063 LOG (GNUNET_ERROR_TYPE_INFO, "PE: %s\n",
1064 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
1065 LOG (GNUNET_ERROR_TYPE_INFO, "KM: %s\n", GNUNET_h2s (&km));
1066 LOG (GNUNET_ERROR_TYPE_INFO, "EK: %s\n",
1067 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
1068 LOG (GNUNET_ERROR_TYPE_INFO, "DK: %s\n",
1069 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
1075 * Create a new Key eXchange context for the tunnel.
1077 * If the old keys were verified, keep them for old traffic. Create a new KX
1078 * timestamp and a new nonce.
1080 * @param t Tunnel for which to create the KX ctx.
1083 create_kx_ctx (struct CadetTunnel *t)
1085 LOG (GNUNET_ERROR_TYPE_INFO, " new kx ctx for %s\n", GCT_2s (t));
1087 if (NULL != t->kx_ctx)
1089 if (NULL != t->kx_ctx->finish_task)
1091 LOG (GNUNET_ERROR_TYPE_INFO, " resetting exisiting finish task\n");
1092 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
1093 t->kx_ctx->finish_task = NULL;
1098 t->kx_ctx = GNUNET_new (struct CadetTunnelKXCtx);
1099 t->kx_ctx->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1103 if (CADET_TUNNEL_KEY_OK == t->estate)
1105 LOG (GNUNET_ERROR_TYPE_INFO, " backing up keys\n");
1106 t->kx_ctx->d_key_old = t->d_key;
1107 t->kx_ctx->e_key_old = t->e_key;
1110 LOG (GNUNET_ERROR_TYPE_INFO, " old keys not valid, not saving\n");
1111 t->kx_ctx->rekey_start_time = GNUNET_TIME_absolute_get ();
1117 * @brief Finish the Key eXchange and destroy the old keys.
1119 * @param cls Closure (Tunnel for which to finish the KX).
1120 * @param tc Task context.
1123 finish_kx (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1125 struct CadetTunnel *t = cls;
1127 LOG (GNUNET_ERROR_TYPE_INFO, "finish KX for %s\n", GCT_2s (t));
1129 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1131 LOG (GNUNET_ERROR_TYPE_INFO, " shutdown\n");
1135 GNUNET_free (t->kx_ctx);
1141 * Destroy a Key eXchange context for the tunnel. This function only schedules
1142 * the destruction, the freeing of the memory (and clearing of old key material)
1143 * happens after a delay!
1145 * @param t Tunnel whose KX ctx to destroy.
1148 destroy_kx_ctx (struct CadetTunnel *t)
1150 struct GNUNET_TIME_Relative delay;
1152 if (NULL == t->kx_ctx || NULL != t->kx_ctx->finish_task)
1155 if (is_key_null (&t->kx_ctx->e_key_old))
1157 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_now (finish_kx, t);
1161 delay = GNUNET_TIME_relative_divide (rekey_period, 4);
1162 delay = GNUNET_TIME_relative_min (delay, GNUNET_TIME_UNIT_MINUTES);
1164 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_delayed (delay, finish_kx, t);
1170 * Pick a connection on which send the next data message.
1172 * @param t Tunnel on which to send the message.
1174 * @return The connection on which to send the next message.
1176 static struct CadetConnection *
1177 tunnel_get_connection (struct CadetTunnel *t)
1179 struct CadetTConnection *iter;
1180 struct CadetConnection *best;
1182 unsigned int lowest_q;
1184 LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GCT_2s (t));
1186 lowest_q = UINT_MAX;
1187 for (iter = t->connection_head; NULL != iter; iter = iter->next)
1189 LOG (GNUNET_ERROR_TYPE_DEBUG, " connection %s: %u\n",
1190 GCC_2s (iter->c), GCC_get_state (iter->c));
1191 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
1193 qn = GCC_get_qn (iter->c, GCC_is_origin (iter->c, GNUNET_YES));
1194 LOG (GNUNET_ERROR_TYPE_DEBUG, " q_n %u, \n", qn);
1202 LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GCC_2s (best));
1208 * Callback called when a queued message is sent.
1210 * Calculates the average time and connection packet tracking.
1212 * @param cls Closure (TunnelQueue handle).
1213 * @param c Connection this message was on.
1214 * @param q Connection queue handle (unused).
1215 * @param type Type of message sent.
1216 * @param fwd Was this a FWD going message?
1217 * @param size Size of the message.
1220 tun_message_sent (void *cls,
1221 struct CadetConnection *c,
1222 struct CadetConnectionQueue *q,
1223 uint16_t type, int fwd, size_t size)
1225 struct CadetTunnelQueue *qt = cls;
1226 struct CadetTunnel *t;
1228 LOG (GNUNET_ERROR_TYPE_DEBUG, "tun_message_sent\n");
1230 GNUNET_assert (NULL != qt->cont);
1231 t = NULL == c ? NULL : GCC_get_tunnel (c);
1232 qt->cont (qt->cont_cls, t, qt, type, size);
1238 count_queued_data (const struct CadetTunnel *t)
1240 struct CadetTunnelDelayed *iter;
1243 for (count = 0, iter = t->tq_head; iter != NULL; iter = iter->next)
1250 * Delete a queued message: either was sent or the channel was destroyed
1251 * before the tunnel's key exchange had a chance to finish.
1253 * @param tqd Delayed queue handle.
1256 unqueue_data (struct CadetTunnelDelayed *tqd)
1258 GNUNET_CONTAINER_DLL_remove (tqd->t->tq_head, tqd->t->tq_tail, tqd);
1264 * Cache a message to be sent once tunnel is online.
1266 * @param t Tunnel to hold the message.
1267 * @param msg Message itself (copy will be made).
1269 static struct CadetTunnelDelayed *
1270 queue_data (struct CadetTunnel *t, const struct GNUNET_MessageHeader *msg)
1272 struct CadetTunnelDelayed *tqd;
1273 uint16_t size = ntohs (msg->size);
1275 LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GCT_2s (t));
1277 if (GNUNET_YES == is_ready (t))
1283 tqd = GNUNET_malloc (sizeof (struct CadetTunnelDelayed) + size);
1286 memcpy (&tqd[1], msg, size);
1287 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
1293 * Sends an already built message on a tunnel, encrypting it and
1294 * choosing the best connection.
1296 * @param message Message to send. Function modifies it.
1297 * @param t Tunnel on which this message is transmitted.
1298 * @param c Connection to use (autoselect if NULL).
1299 * @param force Force the tunnel to take the message (buffer overfill).
1300 * @param cont Continuation to call once message is really sent.
1301 * @param cont_cls Closure for @c cont.
1302 * @param existing_q In case this a transmission of previously queued data,
1303 * this should be TunnelQueue given to the client.
1306 * @return Handle to cancel message.
1307 * NULL if @c cont is NULL or an error happens and message is dropped.
1309 static struct CadetTunnelQueue *
1310 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1311 struct CadetTunnel *t, struct CadetConnection *c,
1312 int force, GCT_sent cont, void *cont_cls,
1313 struct CadetTunnelQueue *existing_q)
1315 struct CadetTunnelQueue *tq;
1316 struct GNUNET_CADET_Encrypted *msg;
1317 size_t size = ntohs (message->size);
1318 char cbuf[sizeof (struct GNUNET_CADET_Encrypted) + size];
1324 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GCT_2s (t));
1326 if (GNUNET_NO == is_ready (t))
1328 struct CadetTunnelDelayed *tqd;
1329 /* A non null existing_q indicates sending of queued data.
1330 * Should only happen after tunnel becomes ready.
1332 GNUNET_assert (NULL == existing_q);
1333 tqd = queue_data (t, message);
1336 tq = GNUNET_new (struct CadetTunnelQueue);
1340 tq->cont_cls = cont_cls;
1344 GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1346 iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1347 msg = (struct GNUNET_CADET_Encrypted *) cbuf;
1348 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
1350 GNUNET_assert (t_encrypt (t, &msg[1], message, size, iv, GNUNET_NO) == size);
1351 t_hmac (&msg[1], size, iv, select_key (t), &msg->hmac);
1352 msg->header.size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
1355 c = tunnel_get_connection (t);
1358 /* Why is tunnel 'ready'? Should have been queued! */
1359 if (NULL != t->destroy_task)
1362 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1364 return NULL; /* Drop... */
1368 type = ntohs (message->type);
1371 case GNUNET_MESSAGE_TYPE_CADET_DATA:
1372 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1373 if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
1374 mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
1376 mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
1378 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1379 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1380 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1381 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1382 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1383 msg->cid = *GCC_get_id (c);
1384 msg->ttl = htonl (default_ttl);
1388 LOG (GNUNET_ERROR_TYPE_ERROR, "type %s not valid\n", GC_m2s (type));
1390 LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
1392 fwd = GCC_is_origin (c, GNUNET_YES);
1396 GNUNET_break (NULL == GCC_send_prebuilt_message (&msg->header, type, mid, c,
1397 fwd, force, NULL, NULL));
1400 if (NULL == existing_q)
1402 tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
1409 tq->cq = GCC_send_prebuilt_message (&msg->header, type, mid, c, fwd, force,
1410 &tun_message_sent, tq);
1411 GNUNET_assert (NULL != tq->cq);
1413 tq->cont_cls = cont_cls;
1420 * Send all cached messages that we can, tunnel is online.
1422 * @param t Tunnel that holds the messages. Cannot be loopback.
1425 send_queued_data (struct CadetTunnel *t)
1427 struct CadetTunnelDelayed *tqd;
1428 struct CadetTunnelDelayed *next;
1431 LOG (GNUNET_ERROR_TYPE_INFO, "Send queued data, tunnel %s\n", GCT_2s (t));
1433 if (GCT_is_loopback (t))
1439 if (GNUNET_NO == is_ready (t))
1441 LOG (GNUNET_ERROR_TYPE_DEBUG, " not ready yet: %s/%s\n",
1442 estate2s (t->estate), cstate2s (t->cstate));
1446 room = GCT_get_connections_buffer (t);
1447 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
1448 LOG (GNUNET_ERROR_TYPE_DEBUG, " tq head: %p\n", t->tq_head);
1449 for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
1451 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
1454 send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
1455 tqd->t, NULL, GNUNET_YES,
1456 NULL != tqd->tq ? tqd->tq->cont : NULL,
1457 NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
1461 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
1466 * Callback called when a queued message is sent.
1468 * @param cls Closure.
1469 * @param c Connection this message was on.
1470 * @param type Type of message sent.
1471 * @param fwd Was this a FWD going message?
1472 * @param size Size of the message.
1475 ephm_sent (void *cls,
1476 struct CadetConnection *c,
1477 struct CadetConnectionQueue *q,
1478 uint16_t type, int fwd, size_t size)
1480 struct CadetTunnel *t = cls;
1481 LOG (GNUNET_ERROR_TYPE_DEBUG, "ephm_sent %s\n", GC_m2s (type));
1486 * Callback called when a queued message is sent.
1488 * @param cls Closure.
1489 * @param c Connection this message was on.
1490 * @param type Type of message sent.
1491 * @param fwd Was this a FWD going message?
1492 * @param size Size of the message.
1495 pong_sent (void *cls,
1496 struct CadetConnection *c,
1497 struct CadetConnectionQueue *q,
1498 uint16_t type, int fwd, size_t size)
1500 struct CadetTunnel *t = cls;
1501 LOG (GNUNET_ERROR_TYPE_DEBUG, "pong_sent %s\n", GC_m2s (type));
1507 * Sends key exchange message on a tunnel, choosing the best connection.
1508 * Should not be called on loopback tunnels.
1510 * @param t Tunnel on which this message is transmitted.
1511 * @param message Message to send. Function modifies it.
1513 * @return Handle to the message in the connection queue.
1515 static struct CadetConnectionQueue *
1516 send_kx (struct CadetTunnel *t,
1517 const struct GNUNET_MessageHeader *message)
1519 struct CadetConnection *c;
1520 struct GNUNET_CADET_KX *msg;
1521 size_t size = ntohs (message->size);
1522 char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
1527 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
1529 /* Avoid loopback. */
1530 if (GCT_is_loopback (t))
1532 LOG (GNUNET_ERROR_TYPE_DEBUG, " loopback!\n");
1536 type = ntohs (message->type);
1538 /* Even if tunnel is "being destroyed", send anyway.
1539 * Could be a response to a rekey initiated by remote peer,
1540 * who is trying to create a new channel!
1543 /* Must have a connection, or be looking for one. */
1544 if (NULL == t->connection_head)
1546 LOG (GNUNET_ERROR_TYPE_DEBUG, "%s while no connection\n", GC_m2s (type));
1547 if (CADET_TUNNEL_SEARCHING != t->cstate)
1550 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
1551 GCP_debug (t->peer, GNUNET_ERROR_TYPE_ERROR);
1556 msg = (struct GNUNET_CADET_KX *) cbuf;
1557 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
1558 msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
1559 c = tunnel_get_connection (t);
1562 if (NULL == t->destroy_task
1563 && CADET_TUNNEL_READY == t->cstate)
1566 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
1572 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
1573 GNUNET_assert (NULL == t->ephm_h);
1575 memcpy (&msg[1], message, size);
1577 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
1578 GNUNET_assert (NULL == t->pong_h);
1580 memcpy (&msg[1], message, size);
1584 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n", GC_m2s (type));
1588 fwd = GCC_is_origin (t->connection_head->c, GNUNET_YES);
1590 return GCC_send_prebuilt_message (&msg->header, type, 0, c,
1597 * Send the ephemeral key on a tunnel.
1599 * @param t Tunnel on which to send the key.
1602 send_ephemeral (struct CadetTunnel *t)
1604 LOG (GNUNET_ERROR_TYPE_INFO, "===> EPHM for %s\n", GCT_2s (t));
1605 if (NULL != t->ephm_h)
1607 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
1611 kx_msg.sender_status = htonl (t->estate);
1612 kx_msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1613 kx_msg.nonce = t->kx_ctx->challenge;
1614 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce c %u\n", kx_msg.nonce);
1615 t_encrypt (t, &kx_msg.nonce, &kx_msg.nonce,
1616 ping_encryption_size(), kx_msg.iv, GNUNET_YES);
1617 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce e %u\n", kx_msg.nonce);
1618 t->ephm_h = send_kx (t, &kx_msg.header);
1623 * Send a pong message on a tunnel.
1625 * @param t Tunnel on which to send the pong.
1626 * @param challenge Value sent in the ping that we have to send back.
1629 send_pong (struct CadetTunnel *t, uint32_t challenge)
1631 struct GNUNET_CADET_KX_Pong msg;
1633 LOG (GNUNET_ERROR_TYPE_INFO, "===> PONG for %s\n", GCT_2s (t));
1634 if (NULL != t->pong_h)
1636 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
1639 msg.header.size = htons (sizeof (msg));
1640 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
1641 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1642 msg.nonce = challenge;
1643 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
1644 t_encrypt (t, &msg.nonce, &msg.nonce,
1645 sizeof (msg.nonce), msg.iv, GNUNET_YES);
1646 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
1648 t->pong_h = send_kx (t, &msg.header);
1653 * Initiate a rekey with the remote peer.
1655 * @param cls Closure (tunnel).
1656 * @param tc TaskContext.
1659 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1661 struct CadetTunnel *t = cls;
1663 t->rekey_task = NULL;
1665 LOG (GNUNET_ERROR_TYPE_INFO, "Re-key Tunnel %s\n", GCT_2s (t));
1666 if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1669 GNUNET_assert (NULL != t->kx_ctx);
1670 struct GNUNET_TIME_Relative duration;
1672 duration = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
1673 LOG (GNUNET_ERROR_TYPE_DEBUG, " kx started %s ago\n",
1674 GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
1676 // FIXME make duration of old keys configurable
1677 if (duration.rel_value_us >= GNUNET_TIME_UNIT_MINUTES.rel_value_us)
1679 LOG (GNUNET_ERROR_TYPE_DEBUG, " deleting old keys\n");
1680 memset (&t->kx_ctx->d_key_old, 0, sizeof (t->kx_ctx->d_key_old));
1681 memset (&t->kx_ctx->e_key_old, 0, sizeof (t->kx_ctx->e_key_old));
1688 case CADET_TUNNEL_KEY_UNINITIALIZED:
1689 GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
1692 case CADET_TUNNEL_KEY_SENT:
1695 case CADET_TUNNEL_KEY_OK:
1697 * - state should have changed during rekey_iterator
1698 * - task should have been canceled at pong_handle
1701 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
1704 case CADET_TUNNEL_KEY_PING:
1705 case CADET_TUNNEL_KEY_REKEY:
1709 LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
1712 // FIXME exponential backoff
1713 struct GNUNET_TIME_Relative delay;
1715 delay = GNUNET_TIME_relative_divide (rekey_period, 16);
1716 delay = GNUNET_TIME_relative_min (delay, REKEY_WAIT);
1717 LOG (GNUNET_ERROR_TYPE_DEBUG, " next call in %s\n",
1718 GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
1719 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1724 * Our ephemeral key has changed, create new session key on all tunnels.
1726 * Each tunnel will start the Key Exchange with a random delay between
1727 * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
1728 * per second, on average.
1730 * @param cls Closure (size of the hashmap).
1731 * @param key Current public key.
1732 * @param value Value in the hash map (tunnel).
1734 * @return #GNUNET_YES, so we should continue to iterate,
1737 rekey_iterator (void *cls,
1738 const struct GNUNET_PeerIdentity *key,
1741 struct CadetTunnel *t = value;
1742 struct GNUNET_TIME_Relative delay;
1743 long n = (long) cls;
1746 if (NULL != t->rekey_task)
1749 if (GNUNET_YES == GCT_is_loopback (t))
1752 r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
1753 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
1754 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1756 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
1763 * Create a new ephemeral key and key message, schedule next rekeying.
1765 * @param cls Closure (unused).
1766 * @param tc TaskContext.
1769 rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1771 struct GNUNET_TIME_Absolute time;
1776 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1779 GNUNET_free_non_null (my_ephemeral_key);
1780 my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
1782 time = GNUNET_TIME_absolute_get ();
1783 kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
1784 time = GNUNET_TIME_absolute_add (time, rekey_period);
1785 time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
1786 kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
1787 GNUNET_CRYPTO_ecdhe_key_get_public (my_ephemeral_key, &kx_msg.ephemeral_key);
1788 LOG (GNUNET_ERROR_TYPE_INFO, "GLOBAL RE-KEY, NEW EPHM: %s\n",
1789 GNUNET_h2s ((struct GNUNET_HashCode *) &kx_msg.ephemeral_key));
1791 GNUNET_assert (GNUNET_OK ==
1792 GNUNET_CRYPTO_eddsa_sign (my_private_key,
1794 &kx_msg.signature));
1796 n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
1797 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
1799 rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period, &rekey, NULL);
1804 * Called only on shutdown, destroy every tunnel.
1806 * @param cls Closure (unused).
1807 * @param key Current public key.
1808 * @param value Value in the hash map (tunnel).
1810 * @return #GNUNET_YES, so we should continue to iterate,
1813 destroy_iterator (void *cls,
1814 const struct GNUNET_PeerIdentity *key,
1817 struct CadetTunnel *t = value;
1819 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
1826 * Notify remote peer that we don't know a channel he is talking about,
1827 * probably CHANNEL_DESTROY was missed.
1829 * @param t Tunnel on which to notify.
1830 * @param gid ID of the channel.
1833 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
1835 struct GNUNET_CADET_ChannelManage msg;
1837 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
1838 msg.header.size = htons (sizeof (msg));
1839 msg.chid = htonl (gid);
1841 LOG (GNUNET_ERROR_TYPE_DEBUG,
1842 "WARNING destroying unknown channel %u on tunnel %s\n",
1844 send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
1849 * Demultiplex data per channel and call appropriate channel handler.
1851 * @param t Tunnel on which the data came.
1852 * @param msg Data message.
1853 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1854 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1855 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1856 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1859 handle_data (struct CadetTunnel *t,
1860 const struct GNUNET_CADET_Data *msg,
1863 struct CadetChannel *ch;
1867 size = ntohs (msg->header.size);
1869 sizeof (struct GNUNET_CADET_Data) +
1870 sizeof (struct GNUNET_MessageHeader))
1875 LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
1876 GC_m2s (ntohs (msg[1].header.type)));
1879 ch = GCT_get_channel (t, ntohl (msg->chid));
1882 GNUNET_STATISTICS_update (stats, "# data on unknown channel",
1884 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
1886 send_channel_destroy (t, ntohl (msg->chid));
1890 GCCH_handle_data (ch, msg, fwd);
1895 * Demultiplex data ACKs per channel and update appropriate channel buffer info.
1897 * @param t Tunnel on which the DATA ACK came.
1898 * @param msg DATA ACK message.
1899 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1900 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1901 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1902 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1905 handle_data_ack (struct CadetTunnel *t,
1906 const struct GNUNET_CADET_DataACK *msg,
1909 struct CadetChannel *ch;
1913 size = ntohs (msg->header.size);
1914 if (size != sizeof (struct GNUNET_CADET_DataACK))
1921 ch = GCT_get_channel (t, ntohl (msg->chid));
1924 GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
1926 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1931 GCCH_handle_data_ack (ch, msg, fwd);
1936 * Handle channel create.
1938 * @param t Tunnel on which the data came.
1939 * @param msg Data message.
1942 handle_ch_create (struct CadetTunnel *t,
1943 const struct GNUNET_CADET_ChannelCreate *msg)
1945 struct CadetChannel *ch;
1949 size = ntohs (msg->header.size);
1950 if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
1957 ch = GCT_get_channel (t, ntohl (msg->chid));
1958 if (NULL != ch && ! GCT_is_loopback (t))
1960 /* Probably a retransmission, safe to ignore */
1961 LOG (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
1963 ch = GCCH_handle_create (t, msg);
1965 GCT_add_channel (t, ch);
1971 * Handle channel NACK: check correctness and call channel handler for NACKs.
1973 * @param t Tunnel on which the NACK came.
1974 * @param msg NACK message.
1977 handle_ch_nack (struct CadetTunnel *t,
1978 const struct GNUNET_CADET_ChannelManage *msg)
1980 struct CadetChannel *ch;
1984 size = ntohs (msg->header.size);
1985 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1992 ch = GCT_get_channel (t, ntohl (msg->chid));
1995 GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
1997 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2002 GCCH_handle_nack (ch);
2007 * Handle a CHANNEL ACK (SYNACK/ACK).
2009 * @param t Tunnel on which the CHANNEL ACK came.
2010 * @param msg CHANNEL ACK message.
2011 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2012 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2013 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2014 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2017 handle_ch_ack (struct CadetTunnel *t,
2018 const struct GNUNET_CADET_ChannelManage *msg,
2021 struct CadetChannel *ch;
2025 size = ntohs (msg->header.size);
2026 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2033 ch = GCT_get_channel (t, ntohl (msg->chid));
2036 GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
2038 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2043 GCCH_handle_ack (ch, msg, fwd);
2048 * Handle a channel destruction message.
2050 * @param t Tunnel on which the message came.
2051 * @param msg Channel destroy message.
2052 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2053 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2054 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2055 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2058 handle_ch_destroy (struct CadetTunnel *t,
2059 const struct GNUNET_CADET_ChannelManage *msg,
2062 struct CadetChannel *ch;
2066 size = ntohs (msg->header.size);
2067 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2074 ch = GCT_get_channel (t, ntohl (msg->chid));
2077 /* Probably a retransmission, safe to ignore */
2081 GCCH_handle_destroy (ch, msg, fwd);
2086 * The peer's ephemeral key has changed: update the symmetrical keys.
2088 * @param t Tunnel this message came on.
2089 * @param msg Key eXchange message.
2092 handle_ephemeral (struct CadetTunnel *t,
2093 const struct GNUNET_CADET_KX_Ephemeral *msg)
2095 LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
2097 if (GNUNET_OK != check_ephemeral (t, msg))
2099 GNUNET_break_op (0);
2103 /* If we get a proper OTR-style ephemeral, fallback to old crypto. */
2106 GNUNET_free (t->ax);
2108 t->enc_type = CADET_Fallback;
2112 * If the key is different from what we know, derive the new E/D keys.
2113 * Else destroy the rekey ctx (duplicate EPHM after successful KX).
2115 if (0 != memcmp (&t->peers_ephemeral_key, &msg->ephemeral_key,
2116 sizeof (msg->ephemeral_key)))
2118 #if DUMP_KEYS_TO_STDERR
2119 LOG (GNUNET_ERROR_TYPE_INFO, "OLD: %s\n",
2120 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
2121 LOG (GNUNET_ERROR_TYPE_INFO, "NEW: %s\n",
2122 GNUNET_h2s ((struct GNUNET_HashCode *) &msg->ephemeral_key));
2124 t->peers_ephemeral_key = msg->ephemeral_key;
2128 if (CADET_TUNNEL_KEY_OK == t->estate)
2130 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2132 if (NULL != t->rekey_task)
2133 GNUNET_SCHEDULER_cancel (t->rekey_task);
2134 t->rekey_task = GNUNET_SCHEDULER_add_now (rekey_tunnel, t);
2136 if (CADET_TUNNEL_KEY_SENT == t->estate)
2138 LOG (GNUNET_ERROR_TYPE_DEBUG, " our key was sent, sending challenge\n");
2140 GCT_change_estate (t, CADET_TUNNEL_KEY_PING);
2143 if (CADET_TUNNEL_KEY_UNINITIALIZED != ntohl(msg->sender_status))
2147 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce e %u\n", msg->nonce);
2148 t_decrypt (t, &nonce, &msg->nonce, ping_encryption_size (), msg->iv);
2149 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce c %u\n", nonce);
2150 send_pong (t, nonce);
2156 * Peer has answer to our challenge.
2157 * If answer is successful, consider the key exchange finished and clean
2158 * up all related state.
2160 * @param t Tunnel this message came on.
2161 * @param msg Key eXchange Pong message.
2164 handle_pong (struct CadetTunnel *t, const struct GNUNET_CADET_KX_Pong *msg)
2168 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
2169 if (NULL == t->rekey_task)
2171 GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
2174 if (NULL == t->kx_ctx)
2176 GNUNET_STATISTICS_update (stats, "# stray PONG messages", 1, GNUNET_NO);
2180 t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
2181 if (challenge != t->kx_ctx->challenge)
2183 LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
2184 LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
2185 challenge, msg->nonce, t->kx_ctx->challenge);
2189 GNUNET_SCHEDULER_cancel (t->rekey_task);
2190 t->rekey_task = NULL;
2192 /* Don't free the old keys right away, but after a delay.
2193 * Rationale: the KX could have happened over a very fast connection,
2194 * with payload traffic still signed with the old key stuck in a slower
2196 * Don't keep the keys longer than 1/4 the rekey period, and no longer than
2200 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2207 * @param t Tunnel this message came on.
2208 * @param msg Key eXchange Pong message.
2211 handle_kx_ax (struct CadetTunnel *t, const struct GNUNET_CADET_AX_KX *msg)
2216 t->ax = GNUNET_new (struct CadetTunnelAxolotl);
2222 * Demultiplex by message type and call appropriate handler for a message
2223 * towards a channel of a local tunnel.
2225 * @param t Tunnel this message came on.
2226 * @param msgh Message header.
2227 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2228 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2229 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2230 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2233 handle_decrypted (struct CadetTunnel *t,
2234 const struct GNUNET_MessageHeader *msgh,
2239 type = ntohs (msgh->type);
2240 LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
2244 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
2245 /* Do nothing, connection aleady got updated. */
2246 GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
2249 case GNUNET_MESSAGE_TYPE_CADET_DATA:
2250 /* Don't send hop ACK, wait for client to ACK */
2251 handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
2254 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
2255 handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
2258 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
2259 handle_ch_create (t,
2260 (struct GNUNET_CADET_ChannelCreate *) msgh);
2263 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
2265 (struct GNUNET_CADET_ChannelManage *) msgh);
2268 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
2270 (struct GNUNET_CADET_ChannelManage *) msgh,
2274 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
2275 handle_ch_destroy (t,
2276 (struct GNUNET_CADET_ChannelManage *) msgh,
2281 GNUNET_break_op (0);
2282 LOG (GNUNET_ERROR_TYPE_WARNING,
2283 "end-to-end message not known (%u)\n",
2284 ntohs (msgh->type));
2285 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
2289 /******************************************************************************/
2290 /******************************** API ***********************************/
2291 /******************************************************************************/
2293 * Decrypt old format and demultiplex by message type. Call appropriate handler
2294 * for a message towards a channel of a local tunnel.
2296 * @param t Tunnel this message came on.
2297 * @param msg Message header.
2300 GCT_handle_encrypted (struct CadetTunnel *t,
2301 const struct GNUNET_MessageHeader *msg)
2303 size_t size = ntohs (msg->size);
2304 size_t payload_size;
2307 uint16_t type = ntohs (msg->type);
2308 struct GNUNET_MessageHeader *msgh;
2311 if (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED == type)
2313 const struct GNUNET_CADET_Encrypted *emsg;
2315 emsg = (struct GNUNET_CADET_Encrypted *) msg;
2316 payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
2317 decrypted_size = t_decrypt_and_validate (t, cbuf, &emsg[1], payload_size,
2318 emsg->iv, &emsg->hmac);
2320 else if (GNUNET_MESSAGE_TYPE_CADET_AX == type)
2322 const struct GNUNET_CADET_AX *emsg;
2324 emsg = (struct GNUNET_CADET_AX *) msg;
2325 payload_size = size - sizeof (struct GNUNET_CADET_AX);
2326 decrypted_size = t_ax_decrypt_and_validate (t, cbuf, &emsg[1],
2327 payload_size, &emsg->hmac);
2330 if (-1 == decrypted_size)
2332 GNUNET_break_op (0);
2337 while (off < decrypted_size)
2341 msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
2342 msize = ntohs (msgh->size);
2343 if (msize < sizeof (struct GNUNET_MessageHeader))
2345 GNUNET_break_op (0);
2348 handle_decrypted (t, msgh, GNUNET_SYSERR);
2355 * Demultiplex an encapsulated KX message by message type.
2357 * @param t Tunnel on which the message came.
2358 * @param message Payload of KX message.
2361 GCT_handle_kx (struct CadetTunnel *t,
2362 const struct GNUNET_MessageHeader *message)
2366 type = ntohs (message->type);
2367 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received: %s\n", GC_m2s (type));
2370 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
2371 handle_ephemeral (t, (const struct GNUNET_CADET_KX_Ephemeral *) message);
2374 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
2375 handle_pong (t, (const struct GNUNET_CADET_KX_Pong *) message);
2378 case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
2379 handle_kx_ax (t, (const struct GNUNET_CADET_AX_KX *) message);
2383 GNUNET_break_op (0);
2384 LOG (GNUNET_ERROR_TYPE_WARNING, "kx message %s unknown\n", GC_m2s (type));
2390 * Initialize the tunnel subsystem.
2392 * @param c Configuration handle.
2393 * @param key ECC private key, to derive all other keys and do crypto.
2396 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
2397 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
2399 int expected_overhead;
2401 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
2403 expected_overhead = 0;
2404 expected_overhead += sizeof (struct GNUNET_CADET_Encrypted);
2405 expected_overhead += sizeof (struct GNUNET_CADET_Data);
2406 expected_overhead += sizeof (struct GNUNET_CADET_ACK);
2407 GNUNET_assert (GNUNET_CONSTANTS_CADET_P2P_OVERHEAD == expected_overhead);
2410 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
2413 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
2414 "CADET", "DEFAULT_TTL", "USING DEFAULT");
2418 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
2421 rekey_period = GNUNET_TIME_UNIT_DAYS;
2424 my_private_key = key;
2425 kx_msg.header.size = htons (sizeof (kx_msg));
2426 kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
2427 kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
2428 kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
2429 kx_msg.origin_identity = my_full_id;
2430 rekey_task = GNUNET_SCHEDULER_add_now (&rekey, NULL);
2432 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
2437 * Shut down the tunnel subsystem.
2442 if (NULL != rekey_task)
2444 GNUNET_SCHEDULER_cancel (rekey_task);
2447 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
2448 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
2455 * @param destination Peer this tunnel is towards.
2457 struct CadetTunnel *
2458 GCT_new (struct CadetPeer *destination)
2460 struct CadetTunnel *t;
2462 t = GNUNET_new (struct CadetTunnel);
2464 t->peer = destination;
2467 GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
2468 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2479 * Change the tunnel's connection state.
2481 * @param t Tunnel whose connection state to change.
2482 * @param cstate New connection state.
2485 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
2489 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
2490 GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
2491 if (myid != GCP_get_short_id (t->peer) &&
2492 CADET_TUNNEL_READY != t->cstate &&
2493 CADET_TUNNEL_READY == cstate)
2496 if (CADET_TUNNEL_KEY_OK == t->estate)
2498 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered send queued data\n");
2499 send_queued_data (t);
2501 else if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
2503 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered rekey\n");
2504 if (NULL != t->rekey_task)
2505 GNUNET_SCHEDULER_cancel (t->rekey_task);
2507 rekey_tunnel (t, NULL);
2512 if (CADET_TUNNEL_READY == cstate
2513 && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
2515 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered stop dht\n");
2516 GCP_stop_search (t->peer);
2522 * Change the tunnel encryption state.
2524 * @param t Tunnel whose encryption state to change, or NULL.
2525 * @param state New encryption state.
2528 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
2530 enum CadetTunnelEState old;
2537 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate was %s\n",
2538 GCP_2s (t->peer), estate2s (old));
2539 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate is now %s\n",
2540 GCP_2s (t->peer), estate2s (t->estate));
2542 /* Send queued data if enc state changes to OK */
2543 if (myid != GCP_get_short_id (t->peer) &&
2544 CADET_TUNNEL_KEY_OK != old && CADET_TUNNEL_KEY_OK == t->estate)
2546 send_queued_data (t);
2552 * @brief Check if tunnel has too many connections, and remove one if necessary.
2554 * Currently this means the newest connection, unless it is a direct one.
2555 * Implemented as a task to avoid freeing a connection that is in the middle
2556 * of being created/processed.
2558 * @param cls Closure (Tunnel to check).
2559 * @param tc Task context.
2562 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2564 struct CadetTunnel *t = cls;
2566 t->trim_connections_task = NULL;
2568 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2571 if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
2573 struct CadetTConnection *iter;
2574 struct CadetTConnection *c;
2576 for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
2578 if ((iter->created.abs_value_us > c->created.abs_value_us)
2579 && GNUNET_NO == GCC_is_direct (iter->c))
2586 LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
2588 LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
2601 * Add a connection to a tunnel.
2604 * @param c Connection.
2607 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
2609 struct CadetTConnection *aux;
2611 GNUNET_assert (NULL != c);
2613 LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
2614 LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
2615 for (aux = t->connection_head; aux != NULL; aux = aux->next)
2619 aux = GNUNET_new (struct CadetTConnection);
2621 aux->created = GNUNET_TIME_absolute_get ();
2623 GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
2625 if (CADET_TUNNEL_SEARCHING == t->cstate)
2626 GCT_change_estate (t, CADET_TUNNEL_WAITING);
2628 if (NULL != t->trim_connections_task)
2629 t->trim_connections_task = GNUNET_SCHEDULER_add_now (&trim_connections, t);
2634 * Remove a connection from a tunnel.
2637 * @param c Connection.
2640 GCT_remove_connection (struct CadetTunnel *t,
2641 struct CadetConnection *c)
2643 struct CadetTConnection *aux;
2644 struct CadetTConnection *next;
2647 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
2648 GCC_2s (c), GCT_2s (t));
2649 for (aux = t->connection_head; aux != NULL; aux = next)
2654 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
2659 conns = GCT_count_connections (t);
2661 && NULL == t->destroy_task
2662 && CADET_TUNNEL_SHUTDOWN != t->cstate
2663 && GNUNET_NO == shutting_down)
2665 if (0 == GCT_count_any_connections (t))
2666 GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
2668 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
2671 /* Start new connections if needed */
2672 if (CONNECTIONS_PER_TUNNEL > conns
2673 && NULL == t->destroy_task
2674 && CADET_TUNNEL_SHUTDOWN != t->cstate
2675 && GNUNET_NO == shutting_down)
2677 LOG (GNUNET_ERROR_TYPE_DEBUG, " too few connections, getting new ones\n");
2678 GCP_connect (t->peer); /* Will change cstate to WAITING when possible */
2682 /* If not marked as ready, no change is needed */
2683 if (CADET_TUNNEL_READY != t->cstate)
2686 /* Check if any connection is ready to maintain cstate */
2687 for (aux = t->connection_head; aux != NULL; aux = aux->next)
2688 if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
2694 * Add a channel to a tunnel.
2697 * @param ch Channel.
2700 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2702 struct CadetTChannel *aux;
2704 GNUNET_assert (NULL != ch);
2706 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
2708 for (aux = t->channel_head; aux != NULL; aux = aux->next)
2710 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
2715 aux = GNUNET_new (struct CadetTChannel);
2717 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
2718 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
2720 if (NULL != t->destroy_task)
2722 GNUNET_SCHEDULER_cancel (t->destroy_task);
2723 t->destroy_task = NULL;
2724 LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
2730 * Remove a channel from a tunnel.
2733 * @param ch Channel.
2736 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2738 struct CadetTChannel *aux;
2740 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
2741 for (aux = t->channel_head; aux != NULL; aux = aux->next)
2745 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
2746 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
2755 * Search for a channel by global ID.
2757 * @param t Tunnel containing the channel.
2758 * @param chid Public channel number.
2760 * @return channel handler, NULL if doesn't exist
2762 struct CadetChannel *
2763 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
2765 struct CadetTChannel *iter;
2770 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2772 if (GCCH_get_id (iter->ch) == chid)
2776 return NULL == iter ? NULL : iter->ch;
2781 * @brief Destroy a tunnel and free all resources.
2783 * Should only be called a while after the tunnel has been marked as destroyed,
2784 * in case there is a new channel added to the same peer shortly after marking
2785 * the tunnel. This way we avoid a new public key handshake.
2787 * @param cls Closure (tunnel to destroy).
2788 * @param tc Task context.
2791 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2793 struct CadetTunnel *t = cls;
2794 struct CadetTConnection *iter;
2796 LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
2797 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2799 LOG (GNUNET_ERROR_TYPE_WARNING,
2800 "Not destroying tunnel, due to shutdown. "
2801 "Tunnel at %p should have been freed by GCT_shutdown\n", t);
2804 t->destroy_task = NULL;
2805 t->cstate = CADET_TUNNEL_SHUTDOWN;
2807 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2809 GCC_send_destroy (iter->c);
2816 * Tunnel is empty: destroy it.
2818 * Notifies all connections about the destruction.
2820 * @param t Tunnel to destroy.
2823 GCT_destroy_empty (struct CadetTunnel *t)
2825 if (GNUNET_YES == shutting_down)
2826 return; /* Will be destroyed immediately anyway */
2828 if (NULL != t->destroy_task)
2830 LOG (GNUNET_ERROR_TYPE_WARNING,
2831 "Tunnel %s is already scheduled for destruction. Tunnel debug dump:\n",
2833 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
2835 /* should never happen, tunnel can only become empty once, and the
2836 * task identifier should be NO_TASK (cleaned when the tunnel was created
2837 * or became un-empty)
2842 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: scheduling destruction\n",
2845 // FIXME make delay a config option
2846 t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
2847 &delayed_destroy, t);
2848 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llu\n",
2849 t, t->destroy_task);
2854 * Destroy tunnel if empty (no more channels).
2856 * @param t Tunnel to destroy if empty.
2859 GCT_destroy_if_empty (struct CadetTunnel *t)
2861 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
2862 if (0 < GCT_count_channels (t))
2865 GCT_destroy_empty (t);
2870 * Destroy the tunnel.
2872 * This function does not generate any warning traffic to clients or peers.
2875 * Cancel messages belonging to this tunnel queued to neighbors.
2876 * Free any allocated resources linked to the tunnel.
2878 * @param t The tunnel to destroy.
2881 GCT_destroy (struct CadetTunnel *t)
2883 struct CadetTConnection *iter_c;
2884 struct CadetTConnection *next_c;
2885 struct CadetTChannel *iter_ch;
2886 struct CadetTChannel *next_ch;
2891 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
2893 GNUNET_break (GNUNET_YES ==
2894 GNUNET_CONTAINER_multipeermap_remove (tunnels,
2895 GCP_get_id (t->peer), t));
2897 for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
2899 next_c = iter_c->next;
2900 GCC_destroy (iter_c->c);
2902 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
2904 next_ch = iter_ch->next;
2905 GCCH_destroy (iter_ch->ch);
2906 /* Should only happen on shutdown, but it's ok. */
2909 if (NULL != t->destroy_task)
2911 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling dest: %llX\n", t->destroy_task);
2912 GNUNET_SCHEDULER_cancel (t->destroy_task);
2913 t->destroy_task = NULL;
2916 if (NULL != t->trim_connections_task)
2918 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling trim: %llX\n",
2919 t->trim_connections_task);
2920 GNUNET_SCHEDULER_cancel (t->trim_connections_task);
2921 t->trim_connections_task = NULL;
2924 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
2925 GCP_set_tunnel (t->peer, NULL);
2927 if (NULL != t->rekey_task)
2929 GNUNET_SCHEDULER_cancel (t->rekey_task);
2930 t->rekey_task = NULL;
2932 if (NULL != t->kx_ctx)
2934 if (NULL != t->kx_ctx->finish_task)
2935 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
2936 GNUNET_free (t->kx_ctx);
2943 * @brief Use the given path for the tunnel.
2944 * Update the next and prev hops (and RCs).
2945 * (Re)start the path refresh in case the tunnel is locally owned.
2947 * @param t Tunnel to update.
2948 * @param p Path to use.
2950 * @return Connection created.
2952 struct CadetConnection *
2953 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
2955 struct CadetConnection *c;
2956 struct GNUNET_CADET_Hash cid;
2957 unsigned int own_pos;
2959 if (NULL == t || NULL == p)
2965 if (CADET_TUNNEL_SHUTDOWN == t->cstate)
2971 for (own_pos = 0; own_pos < p->length; own_pos++)
2973 if (p->peers[own_pos] == myid)
2976 if (own_pos >= p->length)
2978 GNUNET_break_op (0);
2982 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
2983 c = GCC_new (&cid, t, p, own_pos);
2986 /* Path was flawed */
2989 GCT_add_connection (t, c);
2995 * Count all created connections of a tunnel. Not necessarily ready connections!
2997 * @param t Tunnel on which to count.
2999 * @return Number of connections created, either being established or ready.
3002 GCT_count_any_connections (struct CadetTunnel *t)
3004 struct CadetTConnection *iter;
3010 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3018 * Count established (ready) connections of a tunnel.
3020 * @param t Tunnel on which to count.
3022 * @return Number of connections.
3025 GCT_count_connections (struct CadetTunnel *t)
3027 struct CadetTConnection *iter;
3033 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3034 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
3042 * Count channels of a tunnel.
3044 * @param t Tunnel on which to count.
3046 * @return Number of channels.
3049 GCT_count_channels (struct CadetTunnel *t)
3051 struct CadetTChannel *iter;
3054 for (count = 0, iter = t->channel_head;
3056 iter = iter->next, count++) /* skip */;
3063 * Get the connectivity state of a tunnel.
3067 * @return Tunnel's connectivity state.
3069 enum CadetTunnelCState
3070 GCT_get_cstate (struct CadetTunnel *t)
3075 return (enum CadetTunnelCState) -1;
3082 * Get the encryption state of a tunnel.
3086 * @return Tunnel's encryption state.
3088 enum CadetTunnelEState
3089 GCT_get_estate (struct CadetTunnel *t)
3094 return (enum CadetTunnelEState) -1;
3100 * Get the maximum buffer space for a tunnel towards a local client.
3104 * @return Biggest buffer space offered by any channel in the tunnel.
3107 GCT_get_channels_buffer (struct CadetTunnel *t)
3109 struct CadetTChannel *iter;
3110 unsigned int buffer;
3111 unsigned int ch_buf;
3113 if (NULL == t->channel_head)
3115 /* Probably getting buffer for a channel create/handshake. */
3116 LOG (GNUNET_ERROR_TYPE_DEBUG, " no channels, allow max\n");
3121 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3123 ch_buf = get_channel_buffer (iter);
3124 if (ch_buf > buffer)
3132 * Get the total buffer space for a tunnel for P2P traffic.
3136 * @return Buffer space offered by all connections in the tunnel.
3139 GCT_get_connections_buffer (struct CadetTunnel *t)
3141 struct CadetTConnection *iter;
3142 unsigned int buffer;
3144 if (GNUNET_NO == is_ready (t))
3146 if (count_queued_data (t) > 3)
3153 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3155 if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
3159 buffer += get_connection_buffer (iter);
3167 * Get the tunnel's destination.
3171 * @return ID of the destination peer.
3173 const struct GNUNET_PeerIdentity *
3174 GCT_get_destination (struct CadetTunnel *t)
3176 return GCP_get_id (t->peer);
3181 * Get the tunnel's next free global channel ID.
3185 * @return GID of a channel free to use.
3188 GCT_get_next_chid (struct CadetTunnel *t)
3190 CADET_ChannelNumber chid;
3191 CADET_ChannelNumber mask;
3194 /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
3195 * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
3196 * If peer's ID is bigger, start at 0x4... bit 30 = 1
3198 result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
3203 t->next_chid |= mask;
3205 while (NULL != GCT_get_channel (t, t->next_chid))
3207 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
3208 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3209 t->next_chid |= mask;
3211 chid = t->next_chid;
3212 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3213 t->next_chid |= mask;
3220 * Send ACK on one or more channels due to buffer in connections.
3222 * @param t Channel which has some free buffer space.
3225 GCT_unchoke_channels (struct CadetTunnel *t)
3227 struct CadetTChannel *iter;
3228 unsigned int buffer;
3229 unsigned int channels = GCT_count_channels (t);
3230 unsigned int choked_n;
3231 struct CadetChannel *choked[channels];
3233 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
3234 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
3235 if (NULL != t->channel_head)
3236 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
3238 /* Get buffer space */
3239 buffer = GCT_get_connections_buffer (t);
3245 /* Count and remember choked channels */
3247 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3249 if (GNUNET_NO == get_channel_allowed (iter))
3251 choked[choked_n++] = iter->ch;
3255 /* Unchoke random channels */
3256 while (0 < buffer && 0 < choked_n)
3258 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3260 GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
3263 choked[r] = choked[choked_n];
3269 * Send ACK on one or more connections due to buffer space to the client.
3271 * Iterates all connections of the tunnel and sends ACKs appropriately.
3276 GCT_send_connection_acks (struct CadetTunnel *t)
3278 struct CadetTConnection *iter;
3281 uint32_t allow_per_connection;
3283 unsigned int buffer;
3285 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
3294 if (CADET_TUNNEL_READY != t->cstate)
3297 buffer = GCT_get_channels_buffer (t);
3298 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer %u\n", buffer);
3300 /* Count connections, how many messages are already allowed */
3301 cs = GCT_count_connections (t);
3302 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3304 allowed += get_connection_allowed (iter);
3306 LOG (GNUNET_ERROR_TYPE_DEBUG, " allowed %u\n", allowed);
3308 /* Make sure there is no overflow */
3309 if (allowed > buffer)
3312 /* Authorize connections to send more data */
3313 to_allow = buffer - allowed;
3315 for (iter = t->connection_head;
3316 NULL != iter && to_allow > 0;
3319 if (CADET_CONNECTION_READY != GCC_get_state (iter->c)
3320 || get_connection_allowed (iter) > 64 / 3)
3324 allow_per_connection = to_allow/cs;
3325 to_allow -= allow_per_connection;
3327 GCC_allow (iter->c, allow_per_connection,
3328 GCC_is_origin (iter->c, GNUNET_NO));
3333 /* Since we don't allow if it's allowed to send 64/3, this can happen. */
3334 LOG (GNUNET_ERROR_TYPE_DEBUG, " reminding to_allow: %u\n", to_allow);
3340 * Cancel a previously sent message while it's in the queue.
3342 * ONLY can be called before the continuation given to the send function
3343 * is called. Once the continuation is called, the message is no longer in the
3346 * @param q Handle to the queue.
3349 GCT_cancel (struct CadetTunnelQueue *q)
3354 /* tun_message_sent() will be called and free q */
3356 else if (NULL != q->tqd)
3358 unqueue_data (q->tqd);
3360 if (NULL != q->cont)
3361 q->cont (q->cont_cls, NULL, q, 0, 0);
3372 * Sends an already built message on a tunnel, encrypting it and
3373 * choosing the best connection if not provided.
3375 * @param message Message to send. Function modifies it.
3376 * @param t Tunnel on which this message is transmitted.
3377 * @param c Connection to use (autoselect if NULL).
3378 * @param force Force the tunnel to take the message (buffer overfill).
3379 * @param cont Continuation to call once message is really sent.
3380 * @param cont_cls Closure for @c cont.
3382 * @return Handle to cancel message. NULL if @c cont is NULL.
3384 struct CadetTunnelQueue *
3385 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
3386 struct CadetTunnel *t, struct CadetConnection *c,
3387 int force, GCT_sent cont, void *cont_cls)
3389 return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
3393 * Sends an already built and encrypted message on a tunnel, choosing the best
3394 * connection. Useful for re-queueing messages queued on a destroyed connection.
3396 * @param message Message to send. Function modifies it.
3397 * @param t Tunnel on which this message is transmitted.
3400 GCT_resend_message (const struct GNUNET_MessageHeader *message,
3401 struct CadetTunnel *t)
3403 struct CadetConnection *c;
3406 c = tunnel_get_connection (t);
3409 /* TODO queue in tunnel, marked as encrypted */
3410 LOG (GNUNET_ERROR_TYPE_DEBUG, "No connection available, dropping.\n");
3413 fwd = GCC_is_origin (c, GNUNET_YES);
3414 GNUNET_break (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
3415 GNUNET_YES, NULL, NULL));
3420 * Is the tunnel directed towards the local peer?
3424 * @return #GNUNET_YES if it is loopback.
3427 GCT_is_loopback (const struct CadetTunnel *t)
3429 return (myid == GCP_get_short_id (t->peer));
3434 * Is the tunnel this path already?
3439 * @return #GNUNET_YES a connection uses this path.
3442 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
3444 struct CadetTConnection *iter;
3446 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3447 if (path_equivalent (GCC_get_path (iter->c), p))
3455 * Get a cost of a path for a tunnel considering existing connections.
3458 * @param path Candidate path.
3460 * @return Cost of the path (path length + number of overlapping nodes)
3463 GCT_get_path_cost (const struct CadetTunnel *t,
3464 const struct CadetPeerPath *path)
3466 struct CadetTConnection *iter;
3467 const struct CadetPeerPath *aux;
3468 unsigned int overlap;
3476 GNUNET_assert (NULL != t);
3478 for (i = 0; i < path->length; i++)
3480 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3482 aux = GCC_get_path (iter->c);
3486 for (j = 0; j < aux->length; j++)
3488 if (path->peers[i] == aux->peers[j])
3496 return path->length + overlap;
3501 * Get the static string for the peer this tunnel is directed.
3505 * @return Static string the destination peer's ID.
3508 GCT_2s (const struct CadetTunnel *t)
3513 return GCP_2s (t->peer);
3517 /******************************************************************************/
3518 /***************************** INFO/DEBUG *******************************/
3519 /******************************************************************************/
3522 * Log all possible info about the tunnel state.
3524 * @param t Tunnel to debug.
3525 * @param level Debug level to use.
3528 GCT_debug (const struct CadetTunnel *t, enum GNUNET_ErrorType level)
3530 struct CadetTChannel *iterch;
3531 struct CadetTConnection *iterc;
3534 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
3536 __FILE__, __FUNCTION__, __LINE__);
3540 LOG2 (level, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
3541 LOG2 (level, "TTT cstate %s, estate %s\n",
3542 cstate2s (t->cstate), estate2s (t->estate));
3543 LOG2 (level, "TTT kx_ctx %p, rekey_task %u, finish task %u\n",
3544 t->kx_ctx, t->rekey_task, t->kx_ctx ? t->kx_ctx->finish_task : 0);
3545 #if DUMP_KEYS_TO_STDERR
3546 LOG2 (level, "TTT my EPHM\t %s\n",
3547 GNUNET_h2s ((struct GNUNET_HashCode *) &kx_msg.ephemeral_key));
3548 LOG2 (level, "TTT peers EPHM:\t %s\n",
3549 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
3550 LOG2 (level, "TTT ENC key:\t %s\n",
3551 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
3552 LOG2 (level, "TTT DEC key:\t %s\n",
3553 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
3556 LOG2 (level, "TTT OLD ENC key:\t %s\n",
3557 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->e_key_old));
3558 LOG2 (level, "TTT OLD DEC key:\t %s\n",
3559 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->d_key_old));
3562 LOG2 (level, "TTT tq_head %p, tq_tail %p\n", t->tq_head, t->tq_tail);
3563 LOG2 (level, "TTT destroy %u\n", t->destroy_task);
3565 LOG2 (level, "TTT channels:\n");
3566 for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
3568 LOG2 (level, "TTT - %s\n", GCCH_2s (iterch->ch));
3571 LOG2 (level, "TTT connections:\n");
3572 for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
3574 GCC_debug (iterc->c, level);
3577 LOG2 (level, "TTT DEBUG TUNNEL END\n");
3582 * Iterate all tunnels.
3584 * @param iter Iterator.
3585 * @param cls Closure for @c iter.
3588 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
3590 GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
3595 * Count all tunnels.
3597 * @return Number of tunnels to remote peers kept by this peer.
3600 GCT_count_all (void)
3602 return GNUNET_CONTAINER_multipeermap_size (tunnels);
3607 * Iterate all connections of a tunnel.
3609 * @param t Tunnel whose connections to iterate.
3610 * @param iter Iterator.
3611 * @param cls Closure for @c iter.
3614 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
3616 struct CadetTConnection *ct;
3618 for (ct = t->connection_head; NULL != ct; ct = ct->next)
3624 * Iterate all channels of a tunnel.
3626 * @param t Tunnel whose channels to iterate.
3627 * @param iter Iterator.
3628 * @param cls Closure for @c iter.
3631 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
3633 struct CadetTChannel *cht;
3635 for (cht = t->channel_head; NULL != cht; cht = cht->next)
3636 iter (cls, cht->ch);