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 #define MAX_SKIPPED_KEYS 64
47 #define MAX_KEY_GAP 256
48 #define AX_HEADER_SIZE (sizeof (uint32_t) * 2\
49 + sizeof (struct GNUNET_CRYPTO_EcdhePublicKey))
52 /******************************************************************************/
53 /******************************** STRUCTS **********************************/
54 /******************************************************************************/
58 struct CadetTChannel *next;
59 struct CadetTChannel *prev;
60 struct CadetChannel *ch;
65 * Connection list and metadata.
67 struct CadetTConnection
72 struct CadetTConnection *next;
77 struct CadetTConnection *prev;
82 struct CadetConnection *c;
85 * Creation time, to keep oldest connection alive.
87 struct GNUNET_TIME_Absolute created;
90 * Connection throughput, to keep fastest connection alive.
96 * Structure used during a Key eXchange.
98 struct CadetTunnelKXCtx
101 * Encryption ("our") old "confirmed" key, for encrypting traffic sent by us
102 * end before the key exchange is finished or times out.
104 struct GNUNET_CRYPTO_SymmetricSessionKey e_key_old;
107 * Decryption ("their") old "confirmed" key, for decrypting traffic sent by
108 * the other end before the key exchange started.
110 struct GNUNET_CRYPTO_SymmetricSessionKey d_key_old;
113 * Same as @c e_key_old, for the case of two simultaneous KX.
114 * This can happen if cadet decides to start a re-key while the peer has also
115 * started its re-key (due to network delay this is impossible to avoid).
116 * In this case, the key material generated with the peer's old ephemeral
117 * *might* (but doesn't have to) be incorrect.
118 * Since no more than two re-keys can happen simultaneously, this is enough.
120 struct GNUNET_CRYPTO_SymmetricSessionKey e_key_old2;
123 * Same as @c d_key_old, for the case described in @c e_key_old2.
125 struct GNUNET_CRYPTO_SymmetricSessionKey d_key_old2;
128 * Challenge to send and expect in the PONG.
133 * When the rekey started. One minute after this the new key will be used.
135 struct GNUNET_TIME_Absolute rekey_start_time;
138 * Task for delayed destruction of the Key eXchange context, to allow delayed
139 * messages with the old key to be decrypted successfully.
141 struct GNUNET_SCHEDULER_Task *finish_task;
145 * Encryption systems possible.
147 enum CadetTunnelEncryption
150 * Default Axolotl system.
155 * Fallback OTR-style encryption.
161 * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
163 struct CadetTunnelSkippedKey
168 struct CadetTunnelSkippedKey *next;
173 struct CadetTunnelSkippedKey *prev;
176 * When was this key stored (for timeout).
178 struct GNUNET_TIME_Absolute timestamp;
183 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
188 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
192 * Axolotl data, according to @url https://github.com/trevp/axolotl/wiki .
194 struct CadetTunnelAxolotl
197 * A (double linked) list of stored message keys and associated header keys
198 * for "skipped" messages, i.e. messages that have not been
199 * received despite the reception of more recent messages, (head).
201 struct CadetTunnelSkippedKey *skipped_head;
204 * Skipped messages' keys DLL, tail.
206 struct CadetTunnelSkippedKey *skipped_tail;
209 * Elements in @a skipped_head <-> @a skipped_tail.
211 unsigned int skipped;
214 * 32-byte root key which gets updated by DH ratchet.
216 struct GNUNET_CRYPTO_SymmetricSessionKey RK;
219 * 32-byte header key (send).
221 struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
224 * 32-byte header key (recv)
226 struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
229 * 32-byte next header key (send).
231 struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
234 * 32-byte next header key (recv).
236 struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
239 * 32-byte chain keys (used for forward-secrecy updating, send).
241 struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
244 * 32-byte chain keys (used for forward-secrecy updating, recv).
246 struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
249 * ECDH for key exchange (A0 / B0).
251 struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
254 * ECDH Identity key (recv).
256 struct GNUNET_CRYPTO_EcdhePublicKey DHIr;
259 * ECDH Ratchet key (send).
261 struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
264 * ECDH Ratchet key (recv).
266 struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
269 * Message number (reset to 0 with each new ratchet, next message to send).
274 * Message number (reset to 0 with each new ratchet, next message to recv).
279 * Previous message numbers (# of msgs sent under prev ratchet)
284 * True (#GNUNET_YES) if the party will send a new ratchet key in next msg.
290 * Struct containing all information regarding a tunnel to a peer.
295 * Endpoint of the tunnel.
297 struct CadetPeer *peer;
300 * Type of encryption used in the tunnel.
302 enum CadetTunnelEncryption enc_type;
307 struct CadetTunnelAxolotl *ax;
310 * State of the tunnel connectivity.
312 enum CadetTunnelCState cstate;
315 * State of the tunnel encryption.
317 enum CadetTunnelEState estate;
320 * Key eXchange context.
322 struct CadetTunnelKXCtx *kx_ctx;
325 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own ephemeral
328 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
331 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
333 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
336 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
338 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
341 * Task to start the rekey process.
343 struct GNUNET_SCHEDULER_Task * rekey_task;
346 * Paths that are actively used to reach the destination peer.
348 struct CadetTConnection *connection_head;
349 struct CadetTConnection *connection_tail;
352 * Next connection number.
357 * Channels inside this tunnel.
359 struct CadetTChannel *channel_head;
360 struct CadetTChannel *channel_tail;
363 * Channel ID for the next created channel.
365 CADET_ChannelNumber next_chid;
368 * Destroy flag: if true, destroy on last message.
370 struct GNUNET_SCHEDULER_Task * destroy_task;
373 * Queued messages, to transmit once tunnel gets connected.
375 struct CadetTunnelDelayed *tq_head;
376 struct CadetTunnelDelayed *tq_tail;
379 * Task to trim connections if too many are present.
381 struct GNUNET_SCHEDULER_Task * trim_connections_task;
384 * Ephemeral message in the queue (to avoid queueing more than one).
386 struct CadetConnectionQueue *ephm_h;
389 * Pong message in the queue.
391 struct CadetConnectionQueue *pong_h;
396 * Struct used to save messages in a non-ready tunnel to send once connected.
398 struct CadetTunnelDelayed
403 struct CadetTunnelDelayed *next;
404 struct CadetTunnelDelayed *prev;
409 struct CadetTunnel *t;
412 * Tunnel queue given to the channel to cancel request. Update on send_queued.
414 struct CadetTunnelQueue *tq;
419 /* struct GNUNET_MessageHeader *msg; */
424 * Handle for messages queued but not yet sent.
426 struct CadetTunnelQueue
429 * Connection queue handle, to cancel if necessary.
431 struct CadetConnectionQueue *cq;
434 * Handle in case message hasn't been given to a connection yet.
436 struct CadetTunnelDelayed *tqd;
439 * Continuation to call once sent.
444 * Closure for @c cont.
451 * Cached Axolotl key with signature.
453 struct CadetAxolotlSignedKey
456 * Information about what is being signed (@a permanent_key).
458 struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
461 * Permanent public ECDH key.
463 struct GNUNET_CRYPTO_EcdhePublicKey permanent_key;
466 * An EdDSA signature of the permanent ECDH key with the Peer's ID key.
468 struct GNUNET_CRYPTO_EddsaSignature signature;
472 /******************************************************************************/
473 /******************************* GLOBALS ***********************************/
474 /******************************************************************************/
477 * Global handle to the statistics service.
479 extern struct GNUNET_STATISTICS_Handle *stats;
482 * Local peer own ID (memory efficient handle).
484 extern GNUNET_PEER_Id myid;
487 * Local peer own ID (full value).
489 extern struct GNUNET_PeerIdentity my_full_id;
493 * Don't try to recover tunnels if shutting down.
495 extern int shutting_down;
499 * Set of all tunnels, in order to trigger a new exchange on rekey.
500 * Indexed by peer's ID.
502 static struct GNUNET_CONTAINER_MultiPeerMap *tunnels;
505 * Default TTL for payload packets.
507 static unsigned long long default_ttl;
511 * Own Peer ID private key.
513 const static struct GNUNET_CRYPTO_EddsaPrivateKey *id_key;
515 /******************************** AXOLOTL ************************************/
517 static struct GNUNET_CRYPTO_EcdhePrivateKey *ax_key;
520 * Own Axolotl permanent public key (cache).
522 static struct CadetAxolotlSignedKey ax_identity;
524 /******************************** OTR ***********************************/
528 * Own global OTR ephemeral private key.
530 static struct GNUNET_CRYPTO_EcdhePrivateKey *otr_ephemeral_key;
533 * Cached message used to perform a OTR key exchange.
535 static struct GNUNET_CADET_KX_Ephemeral otr_kx_msg;
538 * Task to generate a new OTR ephemeral key.
540 static struct GNUNET_SCHEDULER_Task *rekey_task;
545 static struct GNUNET_TIME_Relative rekey_period;
548 /******************************************************************************/
549 /******************************** STATIC ***********************************/
550 /******************************************************************************/
553 * Get string description for tunnel connectivity state.
555 * @param cs Tunnel state.
557 * @return String representation.
560 cstate2s (enum CadetTunnelCState cs)
566 case CADET_TUNNEL_NEW:
567 return "CADET_TUNNEL_NEW";
568 case CADET_TUNNEL_SEARCHING:
569 return "CADET_TUNNEL_SEARCHING";
570 case CADET_TUNNEL_WAITING:
571 return "CADET_TUNNEL_WAITING";
572 case CADET_TUNNEL_READY:
573 return "CADET_TUNNEL_READY";
574 case CADET_TUNNEL_SHUTDOWN:
575 return "CADET_TUNNEL_SHUTDOWN";
577 SPRINTF (buf, "%u (UNKNOWN STATE)", cs);
585 * Get string description for tunnel encryption state.
587 * @param es Tunnel state.
589 * @return String representation.
592 estate2s (enum CadetTunnelEState es)
598 case CADET_TUNNEL_KEY_UNINITIALIZED:
599 return "CADET_TUNNEL_KEY_UNINITIALIZED";
600 case CADET_TUNNEL_KEY_SENT:
601 return "CADET_TUNNEL_KEY_SENT";
602 case CADET_TUNNEL_KEY_PING:
603 return "CADET_TUNNEL_KEY_PING";
604 case CADET_TUNNEL_KEY_OK:
605 return "CADET_TUNNEL_KEY_OK";
606 case CADET_TUNNEL_KEY_REKEY:
607 return "CADET_TUNNEL_KEY_REKEY";
609 SPRINTF (buf, "%u (UNKNOWN STATE)", es);
617 * @brief Check if tunnel is ready to send traffic.
619 * Tunnel must be connected and with encryption correctly set up.
621 * @param t Tunnel to check.
623 * @return #GNUNET_YES if ready, #GNUNET_NO otherwise
626 is_ready (struct CadetTunnel *t)
630 GCT_debug (t, GNUNET_ERROR_TYPE_DEBUG);
631 ready = CADET_TUNNEL_READY == t->cstate
632 && (CADET_TUNNEL_KEY_OK == t->estate
633 || CADET_TUNNEL_KEY_REKEY == t->estate);
634 ready = ready || GCT_is_loopback (t);
640 * Check if a key is invalid (NULL pointer or all 0)
642 * @param key Key to check.
644 * @return #GNUNET_YES if key is null, #GNUNET_NO if exists and is not 0.
647 is_key_null (struct GNUNET_CRYPTO_SymmetricSessionKey *key)
649 struct GNUNET_CRYPTO_SymmetricSessionKey null_key;
654 memset (&null_key, 0, sizeof (null_key));
655 if (0 == memcmp (key, &null_key, sizeof (null_key)))
662 * Ephemeral key message purpose size.
664 * @return Size of the part of the ephemeral key message that must be signed.
667 ephemeral_purpose_size (void)
669 return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
670 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
671 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
672 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
673 sizeof (struct GNUNET_PeerIdentity);
678 * Ephemeral key message purpose size.
680 * @return Size of the part of the ephemeral key message that must be signed.
683 ax_purpose_size (void)
685 return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
686 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey);
691 * Size of the encrypted part of a ping message.
693 * @return Size of the encrypted part of a ping message.
696 ping_encryption_size (void)
698 return sizeof (uint32_t);
703 * Get the channel's buffer. ONLY FOR NON-LOOPBACK CHANNELS!!
705 * @param tch Tunnel's channel handle.
707 * @return Amount of messages the channel can still buffer towards the client.
710 get_channel_buffer (const struct CadetTChannel *tch)
714 /* If channel is incoming, is terminal in the FWD direction and fwd is YES */
715 fwd = GCCH_is_terminal (tch->ch, GNUNET_YES);
717 return GCCH_get_buffer (tch->ch, fwd);
722 * Get the channel's allowance status.
724 * @param tch Tunnel's channel handle.
726 * @return #GNUNET_YES if we allowed the client to send data to us.
729 get_channel_allowed (const struct CadetTChannel *tch)
733 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
734 fwd = GCCH_is_origin (tch->ch, GNUNET_YES);
736 return GCCH_get_allowed (tch->ch, fwd);
741 * Get the connection's buffer.
743 * @param tc Tunnel's connection handle.
745 * @return Amount of messages the connection can still buffer.
748 get_connection_buffer (const struct CadetTConnection *tc)
752 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
753 fwd = GCC_is_origin (tc->c, GNUNET_YES);
755 return GCC_get_buffer (tc->c, fwd);
760 * Get the connection's allowance.
762 * @param tc Tunnel's connection handle.
764 * @return Amount of messages we have allowed the next peer to send us.
767 get_connection_allowed (const struct CadetTConnection *tc)
771 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
772 fwd = GCC_is_origin (tc->c, GNUNET_YES);
774 return GCC_get_allowed (tc->c, fwd);
779 * Check that a ephemeral key message s well formed and correctly signed.
781 * @param t Tunnel on which the message came.
782 * @param msg The ephemeral key message.
784 * @return GNUNET_OK if message is fine, GNUNET_SYSERR otherwise.
787 check_ephemeral (struct CadetTunnel *t,
788 const struct GNUNET_CADET_KX_Ephemeral *msg)
790 /* Check message size */
791 if (ntohs (msg->header.size) != sizeof (struct GNUNET_CADET_KX_Ephemeral))
792 return GNUNET_SYSERR;
794 /* Check signature size */
795 if (ntohl (msg->purpose.size) != ephemeral_purpose_size ())
796 return GNUNET_SYSERR;
799 if (0 != memcmp (&msg->origin_identity,
800 GCP_get_id (t->peer),
801 sizeof (struct GNUNET_PeerIdentity)))
802 return GNUNET_SYSERR;
804 /* Check signature */
806 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_CADET_KX,
809 &msg->origin_identity.public_key))
810 return GNUNET_SYSERR;
817 * Select the best key to use for encryption (send), based on KX status.
819 * Normally, return the current key. If there is a KX in progress and the old
820 * key is fresh enough, return the old key.
822 * @param t Tunnel to choose the key from.
824 * @return The optimal key to encrypt/hmac outgoing traffic.
826 static const struct GNUNET_CRYPTO_SymmetricSessionKey *
827 select_key (const struct CadetTunnel *t)
829 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
831 if (NULL != t->kx_ctx
832 && NULL == t->kx_ctx->finish_task)
834 struct GNUNET_TIME_Relative age;
836 age = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
837 LOG (GNUNET_ERROR_TYPE_DEBUG,
838 " key exchange in progress, started %s ago\n",
839 GNUNET_STRINGS_relative_time_to_string (age, GNUNET_YES));
840 // FIXME make duration of old keys configurable
841 if (age.rel_value_us < GNUNET_TIME_UNIT_MINUTES.rel_value_us)
843 LOG (GNUNET_ERROR_TYPE_DEBUG, " using old key\n");
844 key = &t->kx_ctx->e_key_old;
848 LOG (GNUNET_ERROR_TYPE_DEBUG, " using new key (old key too old)\n");
854 LOG (GNUNET_ERROR_TYPE_DEBUG, " no KX: using current key\n");
864 * @param plaintext Content to HMAC.
865 * @param size Size of @c plaintext.
866 * @param iv Initialization vector for the message.
867 * @param key Key to use.
868 * @param hmac[out] Destination to store the HMAC.
871 t_hmac (const void *plaintext, size_t size,
872 uint32_t iv, const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
873 struct GNUNET_CADET_Hash *hmac)
875 static const char ctx[] = "cadet authentication key";
876 struct GNUNET_CRYPTO_AuthKey auth_key;
877 struct GNUNET_HashCode hash;
879 #if DUMP_KEYS_TO_STDERR
880 LOG (GNUNET_ERROR_TYPE_INFO, " HMAC %u bytes with key %s\n", size,
881 GNUNET_h2s ((struct GNUNET_HashCode *) key));
883 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
888 /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
889 GNUNET_CRYPTO_hmac (&auth_key, plaintext, size, &hash);
890 memcpy (hmac, &hash, sizeof (*hmac));
895 * Encrypt daforce_newest_keyta with the tunnel key.
897 * @param t Tunnel whose key to use.
898 * @param dst Destination for the encrypted data.
899 * @param src Source of the plaintext. Can overlap with @c dst.
900 * @param size Size of the plaintext.
901 * @param iv Initialization Vector to use.
902 * @param force_newest_key Force the use of the newest key, otherwise
903 * CADET will use the old key when allowed.
904 * This can happen in the case when a KX is going on
905 * and the old one hasn't expired.
908 t_encrypt (struct CadetTunnel *t, void *dst, const void *src,
909 size_t size, uint32_t iv, int force_newest_key)
911 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
912 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
915 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt start\n");
917 key = GNUNET_YES == force_newest_key ? &t->e_key : select_key (t);
918 #if DUMP_KEYS_TO_STDERR
919 LOG (GNUNET_ERROR_TYPE_INFO, " ENC with key %s\n",
920 GNUNET_h2s ((struct GNUNET_HashCode *) key));
922 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
923 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt IV derived\n");
924 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, key, &siv, dst);
925 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt end\n");
934 * @param key Key to use.
935 * @param hash[out] Resulting HMAC.
936 * @param source Source key material (data to HMAC).
937 * @param len Length of @a source.
940 t_ax_hmac_hash (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
941 struct GNUNET_HashCode *hash,
942 void *source, unsigned int len)
944 static const char ctx[] = "axolotl HMAC-HASH";
945 struct GNUNET_CRYPTO_AuthKey auth_key;
947 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
950 GNUNET_CRYPTO_hmac (&auth_key, source, len, hash);
955 * Derive a key from a HMAC-HASH.
957 * @param key Key to use for the HMAC.
958 * @param out Key to generate.
959 * @param source Source key material (data to HMAC).
960 * @param len Length of @a source.
963 t_hmac_derive_key (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
964 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
965 void *source, unsigned int len)
967 static const char ctx[] = "axolotl derive key";
968 struct GNUNET_HashCode h;
970 t_ax_hmac_hash (key, &h, source, len);
971 GNUNET_CRYPTO_kdf (out, sizeof (*out), ctx, sizeof (ctx),
972 &h, sizeof (h), NULL);
977 * Encrypt data with the axolotl tunnel key.
979 * @param t Tunnel whose key to use.
980 * @param dst Destination for the encrypted data.
981 * @param src Source of the plaintext. Can overlap with @c dst.
982 * @param size Size of the plaintext.
984 * @return Size of the encrypted data.
987 t_ax_encrypt (struct CadetTunnel *t, void *dst, const void *src, size_t size)
989 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
990 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
991 struct CadetTunnelAxolotl *ax;
994 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt start\n");
998 if (GNUNET_YES == ax->ratchet_flag)
1000 /* Advance ratchet */
1001 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
1002 struct GNUNET_HashCode dh;
1003 struct GNUNET_HashCode hmac;
1004 static const char ctx[] = "axolotl ratchet";
1006 ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
1009 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
1010 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs, &ax->DHRr, &dh);
1011 t_ax_hmac_hash (&ax->RK, &hmac, &dh, sizeof (dh));
1012 GNUNET_CRYPTO_kdf (keys, sizeof (keys), ctx, sizeof (ctx),
1013 &hmac, sizeof (hmac), NULL);
1020 ax->ratchet_flag = GNUNET_NO;
1023 t_hmac_derive_key (&ax->CKs, &MK, "0", 1);
1024 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &MK, NULL, 0, NULL);
1026 #if DUMP_KEYS_TO_STDERR
1027 LOG (GNUNET_ERROR_TYPE_INFO, " CKs: %s\n",
1028 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKs));
1029 LOG (GNUNET_ERROR_TYPE_INFO, " AX_ENC with key %u: %s\n", ax->Ns,
1030 GNUNET_h2s ((struct GNUNET_HashCode *) &MK));
1033 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, &MK, &iv, dst);
1035 t_hmac_derive_key (&ax->CKs, &ax->CKs, "1", 1);
1037 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt end\n");
1044 * Decrypt data with the axolotl tunnel key.
1046 * @param t Tunnel whose key to use.
1047 * @param dst Destination for the decrypted data.
1048 * @param src Source of the ciphertext. Can overlap with @c dst.
1049 * @param size Size of the ciphertext.
1051 * @return Size of the decrypted data.
1054 t_ax_decrypt (struct CadetTunnel *t, void *dst, const void *src, size_t size)
1056 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
1057 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1058 struct CadetTunnelAxolotl *ax;
1061 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_decrypt start\n");
1065 t_hmac_derive_key (&ax->CKr, &MK, "0", 1);
1066 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &MK, NULL, 0, NULL);
1068 #if DUMP_KEYS_TO_STDERR
1069 LOG (GNUNET_ERROR_TYPE_INFO, " CKr: %s\n",
1070 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKr));
1071 LOG (GNUNET_ERROR_TYPE_INFO, " AX_DEC with key %u: %s\n", ax->Nr,
1072 GNUNET_h2s ((struct GNUNET_HashCode *) &MK));
1075 GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
1076 out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, &MK, &iv, dst);
1077 GNUNET_assert (out_size == size);
1079 t_hmac_derive_key (&ax->CKr, &ax->CKr, "1", 1);
1081 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_decrypt end\n");
1088 * Encrypt header with the axolotl header key.
1090 * @param t Tunnel whose key to use.
1091 * @param msg Message whose header to encrypt.
1094 t_h_encrypt (struct CadetTunnel *t, struct GNUNET_CADET_AX *msg)
1096 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1097 struct CadetTunnelAxolotl *ax;
1100 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_h_encrypt start\n");
1103 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &ax->HKs, NULL, 0, NULL);
1105 #if DUMP_KEYS_TO_STDERR
1106 LOG (GNUNET_ERROR_TYPE_INFO, " AX_ENC_H with key %s\n",
1107 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKs));
1110 out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->Ns, AX_HEADER_SIZE,
1111 &ax->HKs, &iv, &msg->Ns);
1113 GNUNET_assert (AX_HEADER_SIZE == out_size);
1115 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt end\n");
1120 * Decrypt header with the current axolotl header key.
1122 * @param t Tunnel whose current ax HK to use.
1123 * @param src Message whose header to decrypt.
1124 * @param dst Where to decrypt header to.
1127 t_h_decrypt (struct CadetTunnel *t, const struct GNUNET_CADET_AX *src,
1128 struct GNUNET_CADET_AX *dst)
1130 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1131 struct CadetTunnelAxolotl *ax;
1134 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_h_decrypt start\n");
1137 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &ax->HKr, NULL, 0, NULL);
1139 #if DUMP_KEYS_TO_STDERR
1140 LOG (GNUNET_ERROR_TYPE_INFO, " AX_DEC_H with key %s\n",
1141 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKr));
1144 out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns, AX_HEADER_SIZE,
1145 &ax->HKr, &iv, &dst->Ns);
1147 GNUNET_assert (AX_HEADER_SIZE == out_size);
1149 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_decrypt end\n");
1154 * Decrypt and verify data with the appropriate tunnel key.
1156 * @param key Key to use.
1157 * @param dst Destination for the plaintext.
1158 * @param src Source of the encrypted data. Can overlap with @c dst.
1159 * @param size Size of the encrypted data.
1160 * @param iv Initialization Vector to use.
1162 * @return Size of the decrypted data, -1 if an error was encountered.
1165 decrypt (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
1166 void *dst, const void *src, size_t size, uint32_t iv)
1168 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
1171 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt start\n");
1172 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv\n");
1173 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
1174 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv done\n");
1175 out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, key, &siv, dst);
1176 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt end\n");
1183 * Decrypt and verify data with the most recent tunnel key.
1185 * @param t Tunnel whose key to use.
1186 * @param dst Destination for the plaintext.
1187 * @param src Source of the encrypted data. Can overlap with @c dst.
1188 * @param size Size of the encrypted data.
1189 * @param iv Initialization Vector to use.
1191 * @return Size of the decrypted data, -1 if an error was encountered.
1194 t_decrypt (struct CadetTunnel *t, void *dst, const void *src,
1195 size_t size, uint32_t iv)
1199 #if DUMP_KEYS_TO_STDERR
1200 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_decrypt with %s\n",
1201 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
1203 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1205 GNUNET_STATISTICS_update (stats, "# non decryptable data", 1, GNUNET_NO);
1206 LOG (GNUNET_ERROR_TYPE_WARNING,
1207 "got data on %s without a valid key\n",
1209 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1213 out_size = decrypt (&t->d_key, dst, src, size, iv);
1220 * Decrypt and verify data with the appropriate tunnel key and verify that the
1221 * data has not been altered since it was sent by the remote peer.
1223 * @param t Tunnel whose key to use.
1224 * @param dst Destination for the plaintext.
1225 * @param src Source of the encrypted data. Can overlap with @c dst.
1226 * @param size Size of the encrypted data.
1227 * @param iv Initialization Vector to use.
1228 * @param msg_hmac HMAC of the message, cannot be NULL.
1230 * @return Size of the decrypted data, -1 if an error was encountered.
1233 t_decrypt_and_validate (struct CadetTunnel *t,
1234 void *dst, const void *src,
1235 size_t size, uint32_t iv,
1236 const struct GNUNET_CADET_Hash *msg_hmac)
1238 struct GNUNET_CRYPTO_SymmetricSessionKey *key;
1239 struct GNUNET_CADET_Hash hmac;
1242 /* Try primary (newest) key */
1244 decrypted_size = decrypt (key, dst, src, size, iv);
1245 t_hmac (src, size, iv, key, &hmac);
1246 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1247 return decrypted_size;
1249 /* If no key exchange is going on, we just failed. */
1250 if (NULL == t->kx_ctx)
1252 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1253 "Failed checksum validation on tunnel %s with no KX\n",
1255 GNUNET_STATISTICS_update (stats, "# wrong HMAC no KX", 1, GNUNET_NO);
1259 /* Try secondary key, from previous KX period. */
1260 key = &t->kx_ctx->d_key_old;
1261 decrypted_size = decrypt (key, dst, src, size, iv);
1262 t_hmac (src, size, iv, key, &hmac);
1263 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1264 return decrypted_size;
1266 /* Hail Mary, try tertiary, key, in case of parallel re-keys. */
1267 key = &t->kx_ctx->d_key_old2;
1268 decrypted_size = decrypt (key, dst, src, size, iv);
1269 t_hmac (src, size, iv, key, &hmac);
1270 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1271 return decrypted_size;
1273 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1274 "Failed checksum validation on tunnel %s with KX\n",
1276 GNUNET_STATISTICS_update (stats, "# wrong HMAC with KX", 1, GNUNET_NO);
1282 * Decrypt and verify data with the appropriate tunnel key and verify that the
1283 * data has not been altered since it was sent by the remote peer.
1285 * @param t Tunnel whose key to use.
1286 * @param dst Destination for the plaintext.
1287 * @param src Source of the message. Can overlap with @c dst.
1288 * @param size Size of the message.
1290 * @return Size of the decrypted data, -1 if an error was encountered.
1293 try_old_ax_keys (struct CadetTunnel *t, struct GNUNET_CADET_AX *dst,
1294 const struct GNUNET_CADET_AX *src, size_t size)
1296 struct CadetTunnelSkippedKey *key;
1297 struct GNUNET_CADET_Hash hmac;
1298 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1303 for (key = t->ax->skipped_head; NULL != key; key = key->next)
1305 t_hmac (&src->Ns, AX_HEADER_SIZE, 0, &key->HK, &hmac);
1306 if (0 != memcmp (&hmac, &src->hmac, sizeof (hmac)))
1312 #if DUMP_KEYS_TO_STDERR
1313 LOG (GNUNET_ERROR_TYPE_INFO, " AX_DEC with skipped key %s\n",
1314 GNUNET_h2s ((struct GNUNET_HashCode *) &key->MK));
1317 GNUNET_assert (size > sizeof (struct GNUNET_CADET_AX));
1318 len = size - sizeof (struct GNUNET_CADET_AX);
1319 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &key->MK, NULL, 0, NULL);
1320 res = GNUNET_CRYPTO_symmetric_decrypt (&src[1], len, &key->MK, &iv, &dst[1]);
1322 GNUNET_CONTAINER_DLL_remove (t->ax->skipped_head, t->ax->skipped_tail, key);
1331 * Stage skipped AX keys and calculate the message key.
1333 * Stores each HK and MK for skipped messages.
1335 * @param t Tunnel where to stage the keys.
1336 * @param HKr Header key.
1337 * @param Nr Current message number.
1338 * @param Np Received meesage number.
1339 * @param CKr[in/out] Chain key, gets ratcheted forward to the new state.
1342 store_ax_keys (struct CadetTunnel *t,
1343 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1344 uint32_t Nr, uint32_t Np,
1345 struct GNUNET_CRYPTO_SymmetricSessionKey *CKr)
1347 struct CadetTunnelSkippedKey *key;
1352 if (MAX_KEY_GAP < gap || 0 > gap)
1354 /* Avoid DoS (forcing peer to do 2*33 chain HMAC operations) */
1355 /* TODO: start new key exchange on return */
1356 GNUNET_break_op (0);
1360 for (i = Nr; i < Np; i++)
1362 key = GNUNET_new (struct CadetTunnelSkippedKey);
1363 key->timestamp = GNUNET_TIME_absolute_get ();
1364 t_hmac_derive_key (CKr, &key->MK, "0", 1);
1365 #if DUMP_KEYS_TO_STDERR
1366 LOG (GNUNET_ERROR_TYPE_INFO, " storing MK for Nr %u: %s\n",
1367 i, GNUNET_h2s ((struct GNUNET_HashCode *) &key->MK));
1368 LOG (GNUNET_ERROR_TYPE_INFO, " for CKr: %s\n",
1369 GNUNET_h2s ((struct GNUNET_HashCode *) &t->ax->CKr));
1371 t_hmac_derive_key (CKr, CKr, "1", 1);
1372 GNUNET_CONTAINER_DLL_insert (t->ax->skipped_head, t->ax->skipped_tail, key);
1379 * Decrypt and verify data with the appropriate tunnel key and verify that the
1380 * data has not been altered since it was sent by the remote peer.
1382 * @param t Tunnel whose key to use.
1383 * @param dst Destination for the plaintext.
1384 * @param src Source of the message. Can overlap with @c dst.
1385 * @param size Size of the message.
1387 * @return Size of the decrypted data, -1 if an error was encountered.
1390 t_ax_decrypt_and_validate (struct CadetTunnel *t, void *dst,
1391 const struct GNUNET_CADET_AX *src, size_t size)
1393 struct CadetTunnelAxolotl *ax;
1394 struct GNUNET_CADET_Hash msg_hmac;
1395 struct GNUNET_HashCode hmac;
1396 struct GNUNET_CADET_AX *dstmsg;
1404 esize = size - sizeof (struct GNUNET_CADET_AX);
1409 /* Try current HK */
1410 t_hmac (&src->Ns, AX_HEADER_SIZE + esize, 0, &ax->HKr, &msg_hmac);
1411 if (0 != memcmp (&msg_hmac, &src->hmac, sizeof (msg_hmac)))
1413 static const char ctx[] = "axolotl ratchet";
1414 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1415 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1416 struct GNUNET_HashCode dh;
1417 struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1420 t_hmac (&src->Ns, AX_HEADER_SIZE + esize, 0, &ax->NHKr, &msg_hmac);
1421 if (0 != memcmp (&msg_hmac, &src->hmac, sizeof (msg_hmac)))
1423 /* Try the skipped keys, if that fails, we're out of luck. */
1424 return try_old_ax_keys (t, dst, src, size);
1426 LOG (GNUNET_ERROR_TYPE_INFO, "next HK\n");
1430 t_h_decrypt (t, src, dstmsg);
1431 Np = ntohl (dstmsg->Ns);
1432 PNp = ntohl (dstmsg->PNs);
1433 DHRp = &dstmsg->DHRs;
1434 store_ax_keys (t, &HK, ax->Nr, PNp, &ax->CKr);
1436 /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1437 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs, DHRp, &dh);
1438 t_ax_hmac_hash (&ax->RK, &hmac, &dh, sizeof (dh));
1439 GNUNET_CRYPTO_kdf (keys, sizeof (keys), ctx, sizeof (ctx),
1440 &hmac, sizeof (hmac), NULL);
1442 /* Commit "purported" keys */
1451 LOG (GNUNET_ERROR_TYPE_DEBUG, "current HK\n");
1452 t_h_decrypt (t, src, dstmsg);
1453 Np = ntohl (dstmsg->Ns);
1454 PNp = ntohl (dstmsg->PNs);
1458 store_ax_keys (t, &ax->HKr, ax->Nr, Np, &ax->CKr);
1462 osize = t_ax_decrypt (t, dst, &src[1], esize);
1465 GNUNET_break_op (0);
1474 * Create key material by doing ECDH on the local and remote ephemeral keys.
1476 * @param key_material Where to store the key material.
1477 * @param ephemeral Peer's public ephemeral key.
1479 * @return GNUNET_OK if it went fine, GNUNET_SYSERR otherwise.
1482 derive_otr_key_material (struct GNUNET_HashCode *key_material,
1483 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral)
1486 GNUNET_CRYPTO_ecc_ecdh (otr_ephemeral_key, ephemeral, key_material))
1489 return GNUNET_SYSERR;
1496 * Create a symmetic key from the identities of both ends and the key material
1499 * @param key Destination for the generated key.
1500 * @param sender ID of the peer that will encrypt with @c key.
1501 * @param receiver ID of the peer that will decrypt with @c key.
1502 * @param key_material Hash created with ECDH with the ephemeral keys.
1505 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
1506 const struct GNUNET_PeerIdentity *sender,
1507 const struct GNUNET_PeerIdentity *receiver,
1508 const struct GNUNET_HashCode *key_material)
1510 const char salt[] = "CADET kx salt";
1512 GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
1513 salt, sizeof (salt),
1514 key_material, sizeof (struct GNUNET_HashCode),
1515 sender, sizeof (struct GNUNET_PeerIdentity),
1516 receiver, sizeof (struct GNUNET_PeerIdentity),
1522 * Derive the tunnel's keys using our own and the peer's ephemeral keys.
1524 * @param t Tunnel for which to create the keys.
1526 * @return GNUNET_OK if successful, GNUNET_SYSERR otherwise.
1529 create_otr_keys (struct CadetTunnel *t)
1531 struct GNUNET_HashCode km;
1533 if (GNUNET_OK != derive_otr_key_material (&km, &t->peers_ephemeral_key))
1534 return GNUNET_SYSERR;
1535 derive_symmertic (&t->e_key, &my_full_id, GCP_get_id (t->peer), &km);
1536 derive_symmertic (&t->d_key, GCP_get_id (t->peer), &my_full_id, &km);
1537 #if DUMP_KEYS_TO_STDERR
1538 LOG (GNUNET_ERROR_TYPE_INFO, "ME: %s\n",
1539 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
1540 LOG (GNUNET_ERROR_TYPE_INFO, "PE: %s\n",
1541 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
1542 LOG (GNUNET_ERROR_TYPE_INFO, "KM: %s\n", GNUNET_h2s (&km));
1543 LOG (GNUNET_ERROR_TYPE_INFO, "EK: %s\n",
1544 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
1545 LOG (GNUNET_ERROR_TYPE_INFO, "DK: %s\n",
1546 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
1553 * Create a new Key eXchange context for the tunnel.
1555 * If the old keys were verified, keep them for old traffic. Create a new KX
1556 * timestamp and a new nonce.
1558 * @param t Tunnel for which to create the KX ctx.
1560 * @return GNUNET_OK if successful, GNUNET_SYSERR otherwise.
1563 create_kx_ctx (struct CadetTunnel *t)
1565 LOG (GNUNET_ERROR_TYPE_INFO, " new kx ctx for %s\n", GCT_2s (t));
1567 if (NULL != t->kx_ctx)
1569 if (NULL != t->kx_ctx->finish_task)
1571 LOG (GNUNET_ERROR_TYPE_INFO, " resetting exisiting finish task\n");
1572 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
1573 t->kx_ctx->finish_task = NULL;
1578 t->kx_ctx = GNUNET_new (struct CadetTunnelKXCtx);
1579 t->kx_ctx->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1583 if (CADET_TUNNEL_KEY_OK == t->estate)
1585 LOG (GNUNET_ERROR_TYPE_INFO, " backing up keys\n");
1586 t->kx_ctx->d_key_old = t->d_key;
1587 t->kx_ctx->e_key_old = t->e_key;
1590 LOG (GNUNET_ERROR_TYPE_INFO, " old keys not valid, not saving\n");
1591 t->kx_ctx->rekey_start_time = GNUNET_TIME_absolute_get ();
1592 return create_otr_keys (t);
1597 * @brief Finish the Key eXchange and destroy the old keys.
1599 * @param cls Closure (Tunnel for which to finish the KX).
1600 * @param tc Task context.
1603 finish_kx (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1605 struct CadetTunnel *t = cls;
1607 LOG (GNUNET_ERROR_TYPE_INFO, "finish KX for %s\n", GCT_2s (t));
1609 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1611 LOG (GNUNET_ERROR_TYPE_INFO, " shutdown\n");
1615 GNUNET_free (t->kx_ctx);
1621 * Destroy a Key eXchange context for the tunnel. This function only schedules
1622 * the destruction, the freeing of the memory (and clearing of old key material)
1623 * happens after a delay!
1625 * @param t Tunnel whose KX ctx to destroy.
1628 destroy_kx_ctx (struct CadetTunnel *t)
1630 struct GNUNET_TIME_Relative delay;
1632 if (NULL == t->kx_ctx || NULL != t->kx_ctx->finish_task)
1635 if (is_key_null (&t->kx_ctx->e_key_old))
1637 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_now (finish_kx, t);
1641 delay = GNUNET_TIME_relative_divide (rekey_period, 4);
1642 delay = GNUNET_TIME_relative_min (delay, GNUNET_TIME_UNIT_MINUTES);
1644 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_delayed (delay, finish_kx, t);
1650 * Pick a connection on which send the next data message.
1652 * @param t Tunnel on which to send the message.
1654 * @return The connection on which to send the next message.
1656 static struct CadetConnection *
1657 tunnel_get_connection (struct CadetTunnel *t)
1659 struct CadetTConnection *iter;
1660 struct CadetConnection *best;
1662 unsigned int lowest_q;
1664 LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GCT_2s (t));
1666 lowest_q = UINT_MAX;
1667 for (iter = t->connection_head; NULL != iter; iter = iter->next)
1669 LOG (GNUNET_ERROR_TYPE_DEBUG, " connection %s: %u\n",
1670 GCC_2s (iter->c), GCC_get_state (iter->c));
1671 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
1673 qn = GCC_get_qn (iter->c, GCC_is_origin (iter->c, GNUNET_YES));
1674 LOG (GNUNET_ERROR_TYPE_DEBUG, " q_n %u, \n", qn);
1682 LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GCC_2s (best));
1688 * Callback called when a queued message is sent.
1690 * Calculates the average time and connection packet tracking.
1692 * @param cls Closure (TunnelQueue handle).
1693 * @param c Connection this message was on.
1694 * @param q Connection queue handle (unused).
1695 * @param type Type of message sent.
1696 * @param fwd Was this a FWD going message?
1697 * @param size Size of the message.
1700 tun_message_sent (void *cls,
1701 struct CadetConnection *c,
1702 struct CadetConnectionQueue *q,
1703 uint16_t type, int fwd, size_t size)
1705 struct CadetTunnelQueue *qt = cls;
1706 struct CadetTunnel *t;
1708 LOG (GNUNET_ERROR_TYPE_DEBUG, "tun_message_sent\n");
1710 GNUNET_assert (NULL != qt->cont);
1711 t = NULL == c ? NULL : GCC_get_tunnel (c);
1712 qt->cont (qt->cont_cls, t, qt, type, size);
1718 count_queued_data (const struct CadetTunnel *t)
1720 struct CadetTunnelDelayed *iter;
1723 for (count = 0, iter = t->tq_head; iter != NULL; iter = iter->next)
1730 * Delete a queued message: either was sent or the channel was destroyed
1731 * before the tunnel's key exchange had a chance to finish.
1733 * @param tqd Delayed queue handle.
1736 unqueue_data (struct CadetTunnelDelayed *tqd)
1738 GNUNET_CONTAINER_DLL_remove (tqd->t->tq_head, tqd->t->tq_tail, tqd);
1744 * Cache a message to be sent once tunnel is online.
1746 * @param t Tunnel to hold the message.
1747 * @param msg Message itself (copy will be made).
1749 static struct CadetTunnelDelayed *
1750 queue_data (struct CadetTunnel *t, const struct GNUNET_MessageHeader *msg)
1752 struct CadetTunnelDelayed *tqd;
1753 uint16_t size = ntohs (msg->size);
1755 LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GCT_2s (t));
1757 if (GNUNET_YES == is_ready (t))
1763 tqd = GNUNET_malloc (sizeof (struct CadetTunnelDelayed) + size);
1766 memcpy (&tqd[1], msg, size);
1767 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
1773 * Sends an already built message on a tunnel, encrypting it and
1774 * choosing the best connection.
1776 * @param message Message to send. Function modifies it.
1777 * @param t Tunnel on which this message is transmitted.
1778 * @param c Connection to use (autoselect if NULL).
1779 * @param force Force the tunnel to take the message (buffer overfill).
1780 * @param cont Continuation to call once message is really sent.
1781 * @param cont_cls Closure for @c cont.
1782 * @param existing_q In case this a transmission of previously queued data,
1783 * this should be TunnelQueue given to the client.
1786 * @return Handle to cancel message.
1787 * NULL if @c cont is NULL or an error happens and message is dropped.
1789 static struct CadetTunnelQueue *
1790 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1791 struct CadetTunnel *t, struct CadetConnection *c,
1792 int force, GCT_sent cont, void *cont_cls,
1793 struct CadetTunnelQueue *existing_q)
1795 struct GNUNET_MessageHeader *msg;
1796 struct GNUNET_CADET_Encrypted *otr_msg;
1797 struct GNUNET_CADET_AX *ax_msg;
1798 struct CadetTunnelQueue *tq;
1799 size_t size = ntohs (message->size);
1800 const uint16_t max_overhead = sizeof (struct GNUNET_CADET_Encrypted)
1801 + sizeof (struct GNUNET_CADET_AX);
1802 char cbuf[max_overhead + size];
1809 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GCT_2s (t));
1811 if (GNUNET_NO == is_ready (t))
1813 struct CadetTunnelDelayed *tqd;
1814 /* A non null existing_q indicates sending of queued data.
1815 * Should only happen after tunnel becomes ready.
1817 GNUNET_assert (NULL == existing_q);
1818 tqd = queue_data (t, message);
1821 tq = GNUNET_new (struct CadetTunnelQueue);
1825 tq->cont_cls = cont_cls;
1829 GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1831 if (CADET_Axolotl == t->enc_type)
1833 ax_msg = (struct GNUNET_CADET_AX *) cbuf;
1834 msg = &ax_msg->header;
1835 msg->size = htons (sizeof (struct GNUNET_CADET_AX) + size);
1836 msg->type = htons (GNUNET_MESSAGE_TYPE_CADET_AX);
1837 ax_msg->reserved = 0;
1838 esize = t_ax_encrypt (t, &ax_msg[1], message, size);
1839 ax_msg->Ns = htonl (t->ax->Ns++);
1840 ax_msg->PNs = htonl (t->ax->PNs);
1841 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &ax_msg->DHRs);
1842 t_h_encrypt (t, ax_msg);
1843 t_hmac (&ax_msg->Ns, AX_HEADER_SIZE + esize, 0, &t->ax->HKs, &ax_msg->hmac);
1847 otr_msg = (struct GNUNET_CADET_Encrypted *) cbuf;
1848 msg = &otr_msg->header;
1849 iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1851 esize = t_encrypt (t, &otr_msg[1], message, size, iv, GNUNET_NO);
1852 t_hmac (&otr_msg[1], size, iv, select_key (t), &otr_msg->hmac);
1853 msg->size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
1854 msg->type = htons (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
1856 GNUNET_assert (esize == size);
1859 c = tunnel_get_connection (t);
1862 /* Why is tunnel 'ready'? Should have been queued! */
1863 if (NULL != t->destroy_task)
1866 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1868 return NULL; /* Drop... */
1872 type = ntohs (message->type);
1875 case GNUNET_MESSAGE_TYPE_CADET_DATA:
1876 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1877 if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
1878 mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
1880 mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
1882 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1883 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1884 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1885 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1886 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1890 LOG (GNUNET_ERROR_TYPE_ERROR, "type %s not valid\n", GC_m2s (type));
1892 LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
1894 fwd = GCC_is_origin (c, GNUNET_YES);
1898 GNUNET_break (NULL == GCC_send_prebuilt_message (msg, type,
1899 mid, c, fwd, force, NULL, NULL));
1902 if (NULL == existing_q)
1904 tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
1911 tq->cq = GCC_send_prebuilt_message (msg, type, mid, c, fwd, force,
1912 &tun_message_sent, tq);
1913 GNUNET_assert (NULL != tq->cq);
1915 tq->cont_cls = cont_cls;
1922 * Send all cached messages that we can, tunnel is online.
1924 * @param t Tunnel that holds the messages. Cannot be loopback.
1927 send_queued_data (struct CadetTunnel *t)
1929 struct CadetTunnelDelayed *tqd;
1930 struct CadetTunnelDelayed *next;
1933 LOG (GNUNET_ERROR_TYPE_INFO, "Send queued data, tunnel %s\n", GCT_2s (t));
1935 if (GCT_is_loopback (t))
1941 if (GNUNET_NO == is_ready (t))
1943 LOG (GNUNET_ERROR_TYPE_DEBUG, " not ready yet: %s/%s\n",
1944 estate2s (t->estate), cstate2s (t->cstate));
1948 room = GCT_get_connections_buffer (t);
1949 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
1950 LOG (GNUNET_ERROR_TYPE_DEBUG, " tq head: %p\n", t->tq_head);
1951 for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
1953 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
1956 send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
1957 tqd->t, NULL, GNUNET_YES,
1958 NULL != tqd->tq ? tqd->tq->cont : NULL,
1959 NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
1963 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
1968 * Callback called when a queued message is sent.
1970 * @param cls Closure.
1971 * @param c Connection this message was on.
1972 * @param type Type of message sent.
1973 * @param fwd Was this a FWD going message?
1974 * @param size Size of the message.
1977 ephm_sent (void *cls,
1978 struct CadetConnection *c,
1979 struct CadetConnectionQueue *q,
1980 uint16_t type, int fwd, size_t size)
1982 struct CadetTunnel *t = cls;
1983 LOG (GNUNET_ERROR_TYPE_DEBUG, "ephemeral sent %s\n", GC_m2s (type));
1988 * Callback called when a queued message is sent.
1990 * @param cls Closure.
1991 * @param c Connection this message was on.
1992 * @param type Type of message sent.
1993 * @param fwd Was this a FWD going message?
1994 * @param size Size of the message.
1997 pong_sent (void *cls,
1998 struct CadetConnection *c,
1999 struct CadetConnectionQueue *q,
2000 uint16_t type, int fwd, size_t size)
2002 struct CadetTunnel *t = cls;
2003 LOG (GNUNET_ERROR_TYPE_DEBUG, "pong_sent %s\n", GC_m2s (type));
2009 * Sends key exchange message on a tunnel, choosing the best connection.
2010 * Should not be called on loopback tunnels.
2012 * @param t Tunnel on which this message is transmitted.
2013 * @param message Message to send. Function modifies it.
2015 * @return Handle to the message in the connection queue.
2017 static struct CadetConnectionQueue *
2018 send_kx (struct CadetTunnel *t,
2019 const struct GNUNET_MessageHeader *message)
2021 struct CadetConnection *c;
2022 struct GNUNET_CADET_KX *msg;
2023 size_t size = ntohs (message->size);
2024 char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
2029 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
2031 /* Avoid loopback. */
2032 if (GCT_is_loopback (t))
2037 type = ntohs (message->type);
2039 /* Even if tunnel is "being destroyed", send anyway.
2040 * Could be a response to a rekey initiated by remote peer,
2041 * who is trying to create a new channel!
2044 /* Must have a connection, or be looking for one. */
2045 if (NULL == t->connection_head)
2047 LOG (GNUNET_ERROR_TYPE_DEBUG, "%s with no connection\n", GC_m2s (type));
2048 if (CADET_TUNNEL_SEARCHING != t->cstate)
2051 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
2052 GCP_debug (t->peer, GNUNET_ERROR_TYPE_ERROR);
2057 msg = (struct GNUNET_CADET_KX *) cbuf;
2058 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
2059 msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
2060 c = tunnel_get_connection (t);
2063 if (NULL == t->destroy_task && CADET_TUNNEL_READY == t->cstate)
2066 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
2072 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
2073 case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
2074 GNUNET_assert (NULL == t->ephm_h);
2077 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
2078 GNUNET_assert (NULL == t->pong_h);
2083 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n", GC_m2s (type));
2086 memcpy (&msg[1], message, size);
2088 fwd = GCC_is_origin (c, GNUNET_YES);
2090 return GCC_send_prebuilt_message (&msg->header, type, 0, c,
2097 * Send the ephemeral key on a tunnel.
2099 * @param t Tunnel on which to send the key.
2102 send_ephemeral (struct CadetTunnel *t)
2104 LOG (GNUNET_ERROR_TYPE_INFO, "===> EPHM for %s\n", GCT_2s (t));
2105 if (NULL != t->ephm_h)
2107 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
2111 otr_kx_msg.sender_status = htonl (t->estate);
2112 otr_kx_msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
2113 otr_kx_msg.nonce = t->kx_ctx->challenge;
2114 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce c %u\n", otr_kx_msg.nonce);
2115 t_encrypt (t, &otr_kx_msg.nonce, &otr_kx_msg.nonce,
2116 ping_encryption_size(), otr_kx_msg.iv, GNUNET_YES);
2117 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce e %u\n", otr_kx_msg.nonce);
2118 t->ephm_h = send_kx (t, &otr_kx_msg.header);
2123 * Send a pong message on a tunnel.
2125 * @param t Tunnel on which to send the pong.
2126 * @param challenge Value sent in the ping that we have to send back.
2129 send_pong (struct CadetTunnel *t, uint32_t challenge)
2131 struct GNUNET_CADET_KX_Pong msg;
2133 LOG (GNUNET_ERROR_TYPE_INFO, "===> PONG for %s\n", GCT_2s (t));
2134 if (NULL != t->pong_h)
2136 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
2139 msg.header.size = htons (sizeof (msg));
2140 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
2141 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
2142 msg.nonce = challenge;
2143 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
2144 t_encrypt (t, &msg.nonce, &msg.nonce,
2145 sizeof (msg.nonce), msg.iv, GNUNET_YES);
2146 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
2148 t->pong_h = send_kx (t, &msg.header);
2153 * Initiate a rekey with the remote peer.
2155 * @param cls Closure (tunnel).
2156 * @param tc TaskContext.
2159 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2161 struct CadetTunnel *t = cls;
2163 t->rekey_task = NULL;
2165 LOG (GNUNET_ERROR_TYPE_INFO, "Re-key Tunnel %s\n", GCT_2s (t));
2166 if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2169 GNUNET_assert (NULL != t->kx_ctx);
2170 struct GNUNET_TIME_Relative duration;
2172 duration = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
2173 LOG (GNUNET_ERROR_TYPE_DEBUG, " kx started %s ago\n",
2174 GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
2176 // FIXME make duration of old keys configurable
2177 if (duration.rel_value_us >= GNUNET_TIME_UNIT_MINUTES.rel_value_us)
2179 LOG (GNUNET_ERROR_TYPE_DEBUG, " deleting old keys\n");
2180 memset (&t->kx_ctx->d_key_old, 0, sizeof (t->kx_ctx->d_key_old));
2181 memset (&t->kx_ctx->e_key_old, 0, sizeof (t->kx_ctx->e_key_old));
2188 case CADET_TUNNEL_KEY_UNINITIALIZED:
2189 GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
2192 case CADET_TUNNEL_KEY_SENT:
2195 case CADET_TUNNEL_KEY_OK:
2197 * - state should have changed during rekey_iterator
2198 * - task should have been canceled at pong_handle
2201 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2204 case CADET_TUNNEL_KEY_PING:
2205 case CADET_TUNNEL_KEY_REKEY:
2209 LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
2212 // FIXME exponential backoff
2213 struct GNUNET_TIME_Relative delay;
2215 delay = GNUNET_TIME_relative_divide (rekey_period, 16);
2216 delay = GNUNET_TIME_relative_min (delay, REKEY_WAIT);
2217 LOG (GNUNET_ERROR_TYPE_DEBUG, " next call in %s\n",
2218 GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
2219 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
2224 * Our ephemeral key has changed, create new session key on all tunnels.
2226 * Each tunnel will start the Key Exchange with a random delay between
2227 * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
2228 * per second, on average.
2230 * @param cls Closure (size of the hashmap).
2231 * @param key Current public key.
2232 * @param value Value in the hash map (tunnel).
2234 * @return #GNUNET_YES, so we should continue to iterate,
2237 rekey_iterator (void *cls,
2238 const struct GNUNET_PeerIdentity *key,
2241 struct CadetTunnel *t = value;
2242 struct GNUNET_TIME_Relative delay;
2243 long n = (long) cls;
2246 if (NULL != t->rekey_task)
2249 if (GNUNET_YES == GCT_is_loopback (t))
2252 if (CADET_OTR != t->enc_type)
2255 r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
2256 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
2257 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
2258 if (GNUNET_OK == create_kx_ctx (t))
2259 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2271 * Create a new ephemeral key and key message, schedule next rekeying.
2273 * @param cls Closure (unused).
2274 * @param tc TaskContext.
2277 global_otr_rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2279 struct GNUNET_TIME_Absolute time;
2284 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2287 GNUNET_free_non_null (otr_ephemeral_key);
2288 otr_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
2290 time = GNUNET_TIME_absolute_get ();
2291 otr_kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
2292 time = GNUNET_TIME_absolute_add (time, rekey_period);
2293 time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
2294 otr_kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
2295 GNUNET_CRYPTO_ecdhe_key_get_public (otr_ephemeral_key, &otr_kx_msg.ephemeral_key);
2296 LOG (GNUNET_ERROR_TYPE_INFO, "GLOBAL OTR RE-KEY, NEW EPHM: %s\n",
2297 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
2299 GNUNET_assert (GNUNET_OK ==
2300 GNUNET_CRYPTO_eddsa_sign (id_key,
2301 &otr_kx_msg.purpose,
2302 &otr_kx_msg.signature));
2304 n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
2305 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
2307 rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period,
2308 &global_otr_rekey, NULL);
2313 * Called only on shutdown, destroy every tunnel.
2315 * @param cls Closure (unused).
2316 * @param key Current public key.
2317 * @param value Value in the hash map (tunnel).
2319 * @return #GNUNET_YES, so we should continue to iterate,
2322 destroy_iterator (void *cls,
2323 const struct GNUNET_PeerIdentity *key,
2326 struct CadetTunnel *t = value;
2328 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
2335 * Notify remote peer that we don't know a channel he is talking about,
2336 * probably CHANNEL_DESTROY was missed.
2338 * @param t Tunnel on which to notify.
2339 * @param gid ID of the channel.
2342 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
2344 struct GNUNET_CADET_ChannelManage msg;
2346 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2347 msg.header.size = htons (sizeof (msg));
2348 msg.chid = htonl (gid);
2350 LOG (GNUNET_ERROR_TYPE_DEBUG,
2351 "WARNING destroying unknown channel %u on tunnel %s\n",
2353 send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
2358 * Demultiplex data per channel and call appropriate channel handler.
2360 * @param t Tunnel on which the data came.
2361 * @param msg Data message.
2362 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2363 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2364 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2365 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2368 handle_data (struct CadetTunnel *t,
2369 const struct GNUNET_CADET_Data *msg,
2372 struct CadetChannel *ch;
2376 size = ntohs (msg->header.size);
2378 sizeof (struct GNUNET_CADET_Data) +
2379 sizeof (struct GNUNET_MessageHeader))
2384 LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
2385 GC_m2s (ntohs (msg[1].header.type)));
2388 ch = GCT_get_channel (t, ntohl (msg->chid));
2391 GNUNET_STATISTICS_update (stats, "# data on unknown channel",
2393 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
2395 send_channel_destroy (t, ntohl (msg->chid));
2399 GCCH_handle_data (ch, msg, fwd);
2404 * Demultiplex data ACKs per channel and update appropriate channel buffer info.
2406 * @param t Tunnel on which the DATA ACK came.
2407 * @param msg DATA ACK message.
2408 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2409 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2410 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2411 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2414 handle_data_ack (struct CadetTunnel *t,
2415 const struct GNUNET_CADET_DataACK *msg,
2418 struct CadetChannel *ch;
2422 size = ntohs (msg->header.size);
2423 if (size != sizeof (struct GNUNET_CADET_DataACK))
2430 ch = GCT_get_channel (t, ntohl (msg->chid));
2433 GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
2435 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2440 GCCH_handle_data_ack (ch, msg, fwd);
2445 * Handle channel create.
2447 * @param t Tunnel on which the data came.
2448 * @param msg Data message.
2451 handle_ch_create (struct CadetTunnel *t,
2452 const struct GNUNET_CADET_ChannelCreate *msg)
2454 struct CadetChannel *ch;
2458 size = ntohs (msg->header.size);
2459 if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
2466 ch = GCT_get_channel (t, ntohl (msg->chid));
2467 if (NULL != ch && ! GCT_is_loopback (t))
2469 /* Probably a retransmission, safe to ignore */
2470 LOG (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
2472 ch = GCCH_handle_create (t, msg);
2474 GCT_add_channel (t, ch);
2480 * Handle channel NACK: check correctness and call channel handler for NACKs.
2482 * @param t Tunnel on which the NACK came.
2483 * @param msg NACK message.
2486 handle_ch_nack (struct CadetTunnel *t,
2487 const struct GNUNET_CADET_ChannelManage *msg)
2489 struct CadetChannel *ch;
2493 size = ntohs (msg->header.size);
2494 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2501 ch = GCT_get_channel (t, ntohl (msg->chid));
2504 GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
2506 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2511 GCCH_handle_nack (ch);
2516 * Handle a CHANNEL ACK (SYNACK/ACK).
2518 * @param t Tunnel on which the CHANNEL ACK came.
2519 * @param msg CHANNEL ACK message.
2520 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2521 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2522 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2523 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2526 handle_ch_ack (struct CadetTunnel *t,
2527 const struct GNUNET_CADET_ChannelManage *msg,
2530 struct CadetChannel *ch;
2534 size = ntohs (msg->header.size);
2535 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2542 ch = GCT_get_channel (t, ntohl (msg->chid));
2545 GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
2547 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2552 GCCH_handle_ack (ch, msg, fwd);
2557 * Handle a channel destruction message.
2559 * @param t Tunnel on which the message came.
2560 * @param msg Channel destroy message.
2561 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2562 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2563 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2564 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2567 handle_ch_destroy (struct CadetTunnel *t,
2568 const struct GNUNET_CADET_ChannelManage *msg,
2571 struct CadetChannel *ch;
2575 size = ntohs (msg->header.size);
2576 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2583 ch = GCT_get_channel (t, ntohl (msg->chid));
2586 /* Probably a retransmission, safe to ignore */
2590 GCCH_handle_destroy (ch, msg, fwd);
2595 * Create a new Axolotl ephemeral (ratchet) key.
2600 new_ephemeral (struct CadetTunnel *t)
2602 GNUNET_free_non_null (t->ax->DHRs);
2603 t->ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create();
2608 * Free Axolotl data.
2613 destroy_ax (struct CadetTunnel *t)
2618 GNUNET_free_non_null (t->ax->DHRs);
2619 GNUNET_free_non_null (t->ax->kx_0);
2621 GNUNET_free (t->ax);
2628 * The peer's ephemeral key has changed: update the symmetrical keys.
2630 * @param t Tunnel this message came on.
2631 * @param msg Key eXchange message.
2634 handle_ephemeral (struct CadetTunnel *t,
2635 const struct GNUNET_CADET_KX_Ephemeral *msg)
2637 LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
2639 if (GNUNET_OK != check_ephemeral (t, msg))
2641 GNUNET_break_op (0);
2645 /* If we get a proper OTR-style ephemeral, fallback to old crypto. */
2649 t->enc_type = CADET_OTR;
2650 if (NULL != t->rekey_task)
2651 GNUNET_SCHEDULER_cancel (t->rekey_task);
2652 if (GNUNET_OK != create_kx_ctx (t))
2658 rekey_tunnel (t, NULL);
2662 * If the key is different from what we know, derive the new E/D keys.
2663 * Else destroy the rekey ctx (duplicate EPHM after successful KX).
2665 if (0 != memcmp (&t->peers_ephemeral_key, &msg->ephemeral_key,
2666 sizeof (msg->ephemeral_key)))
2668 #if DUMP_KEYS_TO_STDERR
2669 LOG (GNUNET_ERROR_TYPE_INFO, "OLD: %s\n",
2670 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
2671 LOG (GNUNET_ERROR_TYPE_INFO, "NEW: %s\n",
2672 GNUNET_h2s ((struct GNUNET_HashCode *) &msg->ephemeral_key));
2674 t->peers_ephemeral_key = msg->ephemeral_key;
2676 if (GNUNET_OK != create_kx_ctx (t))
2683 if (CADET_TUNNEL_KEY_OK == t->estate)
2685 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2687 if (NULL != t->rekey_task)
2688 GNUNET_SCHEDULER_cancel (t->rekey_task);
2689 t->rekey_task = GNUNET_SCHEDULER_add_now (rekey_tunnel, t);
2691 if (CADET_TUNNEL_KEY_SENT == t->estate)
2693 LOG (GNUNET_ERROR_TYPE_DEBUG, " our key was sent, sending challenge\n");
2695 GCT_change_estate (t, CADET_TUNNEL_KEY_PING);
2698 if (CADET_TUNNEL_KEY_UNINITIALIZED != ntohl(msg->sender_status))
2702 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce e %u\n", msg->nonce);
2703 t_decrypt (t, &nonce, &msg->nonce, ping_encryption_size (), msg->iv);
2704 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce c %u\n", nonce);
2705 send_pong (t, nonce);
2711 * Peer has answer to our challenge.
2712 * If answer is successful, consider the key exchange finished and clean
2713 * up all related state.
2715 * @param t Tunnel this message came on.
2716 * @param msg Key eXchange Pong message.
2719 handle_pong (struct CadetTunnel *t, const struct GNUNET_CADET_KX_Pong *msg)
2723 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
2724 if (NULL == t->rekey_task)
2726 GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
2729 if (NULL == t->kx_ctx)
2731 GNUNET_STATISTICS_update (stats, "# stray PONG messages", 1, GNUNET_NO);
2735 t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
2736 if (challenge != t->kx_ctx->challenge)
2738 LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
2739 LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
2740 challenge, msg->nonce, t->kx_ctx->challenge);
2744 GNUNET_SCHEDULER_cancel (t->rekey_task);
2745 t->rekey_task = NULL;
2747 /* Don't free the old keys right away, but after a delay.
2748 * Rationale: the KX could have happened over a very fast connection,
2749 * with payload traffic still signed with the old key stuck in a slower
2751 * Don't keep the keys longer than 1/4 the rekey period, and no longer than
2755 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2760 * Handle Axolotl handshake.
2762 * @param t Tunnel this message came on.
2763 * @param msg Key eXchange Pong message.
2766 handle_kx_ax (struct CadetTunnel *t, const struct GNUNET_CADET_AX_KX *msg)
2768 struct CadetTunnelAxolotl *ax;
2769 struct GNUNET_HashCode key_material[3];
2770 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
2771 const struct GNUNET_CRYPTO_EcdhePublicKey *pub;
2772 const struct GNUNET_CRYPTO_EcdhePrivateKey *priv;
2773 const char salt[] = "CADET Axolotl salt";
2774 const struct GNUNET_PeerIdentity *pid;
2777 LOG (GNUNET_ERROR_TYPE_INFO, "<=== AX_KX on %s\n", GCT_2s (t));
2781 /* Something is wrong if ax is NULL. Whose fault it is? */
2782 GNUNET_break_op (CADET_OTR == t->enc_type);
2783 GNUNET_break (CADET_Axolotl == t->enc_type);
2787 if (GNUNET_OK != GCP_check_key (t->peer, &msg->permanent_key,
2788 &msg->purpose, &msg->signature))
2790 GNUNET_break_op (0);
2794 pid = GCT_get_destination (t);
2795 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2796 am_I_alice = GNUNET_YES;
2797 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2798 am_I_alice = GNUNET_NO;
2801 GNUNET_break_op (0);
2805 LOG (GNUNET_ERROR_TYPE_INFO, " is Alice? %s\n", am_I_alice ? "YES" : "NO");
2808 ax->DHRr = msg->ratchet_key;
2809 ax->DHIr = msg->permanent_key;
2812 if (GNUNET_YES == am_I_alice)
2814 priv = ax_key; /* A */
2815 pub = &msg->ephemeral_key; /* B0 */
2819 priv = ax->kx_0; /* B0 */
2820 pub = &ax->DHIr; /* A */
2822 GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[0]);
2825 if (GNUNET_YES == am_I_alice)
2827 priv = ax->kx_0; /* A0 */
2828 pub = &ax->DHIr; /* B */
2832 priv = ax_key; /* B */
2833 pub = &msg->ephemeral_key; /* A0 */
2835 GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[1]);
2838 priv = ax->kx_0; /* A0 or B0 */
2839 pub = &msg->ephemeral_key; /* B0 or A0 */
2840 GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[2]);
2842 #if DUMP_KEYS_TO_STDERR
2845 for (i = 0; i < 3; i++)
2846 LOG (GNUNET_ERROR_TYPE_INFO, "km[%u]: %s\n",
2847 i, GNUNET_h2s (&key_material[i]));
2852 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
2853 salt, sizeof (salt),
2854 &key_material, sizeof (key_material), NULL);
2857 if (GNUNET_YES == am_I_alice)
2863 ax->ratchet_flag = GNUNET_YES;
2871 ax->ratchet_flag = GNUNET_NO;
2873 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2878 * Demultiplex by message type and call appropriate handler for a message
2879 * towards a channel of a local tunnel.
2881 * @param t Tunnel this message came on.
2882 * @param msgh Message header.
2883 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2884 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2885 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2886 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2889 handle_decrypted (struct CadetTunnel *t,
2890 const struct GNUNET_MessageHeader *msgh,
2895 type = ntohs (msgh->type);
2896 LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
2900 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
2901 /* Do nothing, connection aleady got updated. */
2902 GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
2905 case GNUNET_MESSAGE_TYPE_CADET_DATA:
2906 /* Don't send hop ACK, wait for client to ACK */
2907 handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
2910 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
2911 handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
2914 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
2915 handle_ch_create (t, (struct GNUNET_CADET_ChannelCreate *) msgh);
2918 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
2919 handle_ch_nack (t, (struct GNUNET_CADET_ChannelManage *) msgh);
2922 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
2923 handle_ch_ack (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
2926 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
2927 handle_ch_destroy (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
2931 GNUNET_break_op (0);
2932 LOG (GNUNET_ERROR_TYPE_WARNING,
2933 "end-to-end message not known (%u)\n",
2934 ntohs (msgh->type));
2935 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
2939 /******************************************************************************/
2940 /******************************** API ***********************************/
2941 /******************************************************************************/
2943 * Decrypt old format and demultiplex by message type. Call appropriate handler
2944 * for a message towards a channel of a local tunnel.
2946 * @param t Tunnel this message came on.
2947 * @param msg Message header.
2950 GCT_handle_encrypted (struct CadetTunnel *t,
2951 const struct GNUNET_MessageHeader *msg)
2953 uint16_t size = ntohs (msg->size);
2955 size_t payload_size;
2958 struct GNUNET_MessageHeader *msgh;
2961 type = ntohs (msg->type);
2962 if (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED == type)
2964 const struct GNUNET_CADET_Encrypted *emsg;
2966 emsg = (struct GNUNET_CADET_Encrypted *) msg;
2967 payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
2968 decrypted_size = t_decrypt_and_validate (t, cbuf, &emsg[1], payload_size,
2969 emsg->iv, &emsg->hmac);
2971 else if (GNUNET_MESSAGE_TYPE_CADET_AX == type)
2973 const struct GNUNET_CADET_AX *emsg;
2975 emsg = (struct GNUNET_CADET_AX *) msg;
2976 decrypted_size = t_ax_decrypt_and_validate (t, cbuf, emsg, size);
2979 if (-1 == decrypted_size)
2981 GNUNET_break_op (0);
2986 while (off < decrypted_size)
2990 msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
2991 msize = ntohs (msgh->size);
2992 if (msize < sizeof (struct GNUNET_MessageHeader))
2994 GNUNET_break_op (0);
2997 handle_decrypted (t, msgh, GNUNET_SYSERR);
3004 * Demultiplex an encapsulated KX message by message type.
3006 * @param t Tunnel on which the message came.
3007 * @param message Payload of KX message.
3010 GCT_handle_kx (struct CadetTunnel *t,
3011 const struct GNUNET_MessageHeader *message)
3015 type = ntohs (message->type);
3016 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received: %s\n", GC_m2s (type));
3019 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
3020 handle_ephemeral (t, (const struct GNUNET_CADET_KX_Ephemeral *) message);
3023 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
3024 handle_pong (t, (const struct GNUNET_CADET_KX_Pong *) message);
3027 case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
3028 handle_kx_ax (t, (const struct GNUNET_CADET_AX_KX *) message);
3032 GNUNET_break_op (0);
3033 LOG (GNUNET_ERROR_TYPE_WARNING, "kx message %s unknown\n", GC_m2s (type));
3038 * Initialize the tunnel subsystem.
3040 * @param c Configuration handle.
3041 * @param key ECC private key, to derive all other keys and do crypto.
3044 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
3045 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
3047 int expected_overhead;
3049 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
3051 expected_overhead = 0;
3052 expected_overhead += sizeof (struct GNUNET_CADET_Encrypted);
3053 expected_overhead += sizeof (struct GNUNET_CADET_Data);
3054 expected_overhead += sizeof (struct GNUNET_CADET_ACK);
3055 GNUNET_assert (GNUNET_CONSTANTS_CADET_P2P_OVERHEAD == expected_overhead);
3058 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
3061 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
3062 "CADET", "DEFAULT_TTL", "USING DEFAULT");
3066 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
3069 rekey_period = GNUNET_TIME_UNIT_DAYS;
3074 otr_kx_msg.header.size = htons (sizeof (otr_kx_msg));
3075 otr_kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
3076 otr_kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
3077 otr_kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
3078 otr_kx_msg.origin_identity = my_full_id;
3079 rekey_task = GNUNET_SCHEDULER_add_now (&global_otr_rekey, NULL);
3081 ax_key = GNUNET_CRYPTO_ecdhe_key_create ();
3082 GNUNET_CRYPTO_ecdhe_key_get_public (ax_key, &ax_identity.permanent_key);
3083 ax_identity.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_AXKX);
3084 ax_identity.purpose.size = htonl (ax_purpose_size ());
3085 GNUNET_assert (GNUNET_OK ==
3086 GNUNET_CRYPTO_eddsa_sign (id_key,
3087 &ax_identity.purpose,
3088 &ax_identity.signature));
3090 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
3095 * Shut down the tunnel subsystem.
3100 if (NULL != rekey_task)
3102 GNUNET_SCHEDULER_cancel (rekey_task);
3105 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
3106 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
3107 GNUNET_free (ax_key);
3114 * @param destination Peer this tunnel is towards.
3116 struct CadetTunnel *
3117 GCT_new (struct CadetPeer *destination)
3119 struct CadetTunnel *t;
3121 t = GNUNET_new (struct CadetTunnel);
3123 t->peer = destination;
3126 GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
3127 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3133 t->ax = GNUNET_new (struct CadetTunnelAxolotl);
3135 t->ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
3141 * Change the tunnel's connection state.
3143 * @param t Tunnel whose connection state to change.
3144 * @param cstate New connection state.
3147 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
3151 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
3152 GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
3153 if (myid != GCP_get_short_id (t->peer) &&
3154 CADET_TUNNEL_READY != t->cstate &&
3155 CADET_TUNNEL_READY == cstate)
3158 if (CADET_TUNNEL_KEY_OK == t->estate)
3160 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered send queued data\n");
3161 send_queued_data (t);
3163 else if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
3165 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered kx\n");
3170 LOG (GNUNET_ERROR_TYPE_DEBUG, "estate %s\n", estate2s (t->estate));
3175 if (CADET_TUNNEL_READY == cstate
3176 && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
3178 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered stop dht\n");
3179 GCP_stop_search (t->peer);
3185 * Change the tunnel encryption state.
3187 * @param t Tunnel whose encryption state to change, or NULL.
3188 * @param state New encryption state.
3191 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
3193 enum CadetTunnelEState old;
3200 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate was %s\n",
3201 GCP_2s (t->peer), estate2s (old));
3202 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate is now %s\n",
3203 GCP_2s (t->peer), estate2s (t->estate));
3205 /* Send queued data if enc state changes to OK */
3206 if (myid != GCP_get_short_id (t->peer) &&
3207 CADET_TUNNEL_KEY_OK != old && CADET_TUNNEL_KEY_OK == t->estate)
3209 send_queued_data (t);
3215 * @brief Check if tunnel has too many connections, and remove one if necessary.
3217 * Currently this means the newest connection, unless it is a direct one.
3218 * Implemented as a task to avoid freeing a connection that is in the middle
3219 * of being created/processed.
3221 * @param cls Closure (Tunnel to check).
3222 * @param tc Task context.
3225 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3227 struct CadetTunnel *t = cls;
3229 t->trim_connections_task = NULL;
3231 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3234 if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
3236 struct CadetTConnection *iter;
3237 struct CadetTConnection *c;
3239 for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
3241 if ((iter->created.abs_value_us > c->created.abs_value_us)
3242 && GNUNET_NO == GCC_is_direct (iter->c))
3249 LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
3251 LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
3264 * Add a connection to a tunnel.
3267 * @param c Connection.
3270 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
3272 struct CadetTConnection *aux;
3274 GNUNET_assert (NULL != c);
3276 LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
3277 LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
3278 for (aux = t->connection_head; aux != NULL; aux = aux->next)
3282 aux = GNUNET_new (struct CadetTConnection);
3284 aux->created = GNUNET_TIME_absolute_get ();
3286 GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
3288 if (CADET_TUNNEL_SEARCHING == t->cstate)
3289 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3291 if (NULL != t->trim_connections_task)
3292 t->trim_connections_task = GNUNET_SCHEDULER_add_now (&trim_connections, t);
3297 * Remove a connection from a tunnel.
3300 * @param c Connection.
3303 GCT_remove_connection (struct CadetTunnel *t,
3304 struct CadetConnection *c)
3306 struct CadetTConnection *aux;
3307 struct CadetTConnection *next;
3310 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
3311 GCC_2s (c), GCT_2s (t));
3312 for (aux = t->connection_head; aux != NULL; aux = next)
3317 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
3322 conns = GCT_count_connections (t);
3324 && NULL == t->destroy_task
3325 && CADET_TUNNEL_SHUTDOWN != t->cstate
3326 && GNUNET_NO == shutting_down)
3328 if (0 == GCT_count_any_connections (t))
3329 GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
3331 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3334 /* Start new connections if needed */
3335 if (CONNECTIONS_PER_TUNNEL > conns
3336 && NULL == t->destroy_task
3337 && CADET_TUNNEL_SHUTDOWN != t->cstate
3338 && GNUNET_NO == shutting_down)
3340 LOG (GNUNET_ERROR_TYPE_DEBUG, " too few connections, getting new ones\n");
3341 GCP_connect (t->peer); /* Will change cstate to WAITING when possible */
3345 /* If not marked as ready, no change is needed */
3346 if (CADET_TUNNEL_READY != t->cstate)
3349 /* Check if any connection is ready to maintain cstate */
3350 for (aux = t->connection_head; aux != NULL; aux = aux->next)
3351 if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
3357 * Add a channel to a tunnel.
3360 * @param ch Channel.
3363 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3365 struct CadetTChannel *aux;
3367 GNUNET_assert (NULL != ch);
3369 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
3371 for (aux = t->channel_head; aux != NULL; aux = aux->next)
3373 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
3378 aux = GNUNET_new (struct CadetTChannel);
3380 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
3381 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
3383 if (NULL != t->destroy_task)
3385 GNUNET_SCHEDULER_cancel (t->destroy_task);
3386 t->destroy_task = NULL;
3387 LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
3393 * Remove a channel from a tunnel.
3396 * @param ch Channel.
3399 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3401 struct CadetTChannel *aux;
3403 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
3404 for (aux = t->channel_head; aux != NULL; aux = aux->next)
3408 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
3409 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
3418 * Search for a channel by global ID.
3420 * @param t Tunnel containing the channel.
3421 * @param chid Public channel number.
3423 * @return channel handler, NULL if doesn't exist
3425 struct CadetChannel *
3426 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
3428 struct CadetTChannel *iter;
3433 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3435 if (GCCH_get_id (iter->ch) == chid)
3439 return NULL == iter ? NULL : iter->ch;
3444 * @brief Destroy a tunnel and free all resources.
3446 * Should only be called a while after the tunnel has been marked as destroyed,
3447 * in case there is a new channel added to the same peer shortly after marking
3448 * the tunnel. This way we avoid a new public key handshake.
3450 * @param cls Closure (tunnel to destroy).
3451 * @param tc Task context.
3454 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3456 struct CadetTunnel *t = cls;
3457 struct CadetTConnection *iter;
3459 LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
3460 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
3462 LOG (GNUNET_ERROR_TYPE_WARNING,
3463 "Not destroying tunnel, due to shutdown. "
3464 "Tunnel at %p should have been freed by GCT_shutdown\n", t);
3467 t->destroy_task = NULL;
3468 t->cstate = CADET_TUNNEL_SHUTDOWN;
3470 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3472 GCC_send_destroy (iter->c);
3479 * Tunnel is empty: destroy it.
3481 * Notifies all connections about the destruction.
3483 * @param t Tunnel to destroy.
3486 GCT_destroy_empty (struct CadetTunnel *t)
3488 if (GNUNET_YES == shutting_down)
3489 return; /* Will be destroyed immediately anyway */
3491 if (NULL != t->destroy_task)
3493 LOG (GNUNET_ERROR_TYPE_WARNING,
3494 "Tunnel %s is already scheduled for destruction. Tunnel debug dump:\n",
3496 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3498 /* should never happen, tunnel can only become empty once, and the
3499 * task identifier should be NO_TASK (cleaned when the tunnel was created
3500 * or became un-empty)
3505 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: scheduling destruction\n",
3508 // FIXME make delay a config option
3509 t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
3510 &delayed_destroy, t);
3511 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llu\n",
3512 t, t->destroy_task);
3517 * Destroy tunnel if empty (no more channels).
3519 * @param t Tunnel to destroy if empty.
3522 GCT_destroy_if_empty (struct CadetTunnel *t)
3524 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
3525 if (0 < GCT_count_channels (t))
3528 GCT_destroy_empty (t);
3533 * Destroy the tunnel.
3535 * This function does not generate any warning traffic to clients or peers.
3538 * Cancel messages belonging to this tunnel queued to neighbors.
3539 * Free any allocated resources linked to the tunnel.
3541 * @param t The tunnel to destroy.
3544 GCT_destroy (struct CadetTunnel *t)
3546 struct CadetTConnection *iter_c;
3547 struct CadetTConnection *next_c;
3548 struct CadetTChannel *iter_ch;
3549 struct CadetTChannel *next_ch;
3554 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
3556 GNUNET_break (GNUNET_YES ==
3557 GNUNET_CONTAINER_multipeermap_remove (tunnels,
3558 GCP_get_id (t->peer), t));
3560 for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
3562 next_c = iter_c->next;
3563 GCC_destroy (iter_c->c);
3565 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
3567 next_ch = iter_ch->next;
3568 GCCH_destroy (iter_ch->ch);
3569 /* Should only happen on shutdown, but it's ok. */
3572 if (NULL != t->destroy_task)
3574 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling dest: %llX\n", t->destroy_task);
3575 GNUNET_SCHEDULER_cancel (t->destroy_task);
3576 t->destroy_task = NULL;
3579 if (NULL != t->trim_connections_task)
3581 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling trim: %llX\n",
3582 t->trim_connections_task);
3583 GNUNET_SCHEDULER_cancel (t->trim_connections_task);
3584 t->trim_connections_task = NULL;
3587 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
3588 GCP_set_tunnel (t->peer, NULL);
3590 if (NULL != t->rekey_task)
3592 GNUNET_SCHEDULER_cancel (t->rekey_task);
3593 t->rekey_task = NULL;
3595 if (NULL != t->kx_ctx)
3597 if (NULL != t->kx_ctx->finish_task)
3598 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
3599 GNUNET_free (t->kx_ctx);
3610 * @brief Use the given path for the tunnel.
3611 * Update the next and prev hops (and RCs).
3612 * (Re)start the path refresh in case the tunnel is locally owned.
3614 * @param t Tunnel to update.
3615 * @param p Path to use.
3617 * @return Connection created.
3619 struct CadetConnection *
3620 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
3622 struct CadetConnection *c;
3623 struct GNUNET_CADET_Hash cid;
3624 unsigned int own_pos;
3626 if (NULL == t || NULL == p)
3632 if (CADET_TUNNEL_SHUTDOWN == t->cstate)
3638 for (own_pos = 0; own_pos < p->length; own_pos++)
3640 if (p->peers[own_pos] == myid)
3643 if (own_pos >= p->length)
3645 GNUNET_break_op (0);
3649 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
3650 c = GCC_new (&cid, t, p, own_pos);
3653 /* Path was flawed */
3656 GCT_add_connection (t, c);
3662 * Count all created connections of a tunnel. Not necessarily ready connections!
3664 * @param t Tunnel on which to count.
3666 * @return Number of connections created, either being established or ready.
3669 GCT_count_any_connections (struct CadetTunnel *t)
3671 struct CadetTConnection *iter;
3677 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3685 * Count established (ready) connections of a tunnel.
3687 * @param t Tunnel on which to count.
3689 * @return Number of connections.
3692 GCT_count_connections (struct CadetTunnel *t)
3694 struct CadetTConnection *iter;
3700 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3701 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
3709 * Count channels of a tunnel.
3711 * @param t Tunnel on which to count.
3713 * @return Number of channels.
3716 GCT_count_channels (struct CadetTunnel *t)
3718 struct CadetTChannel *iter;
3721 for (count = 0, iter = t->channel_head;
3723 iter = iter->next, count++) /* skip */;
3730 * Get the connectivity state of a tunnel.
3734 * @return Tunnel's connectivity state.
3736 enum CadetTunnelCState
3737 GCT_get_cstate (struct CadetTunnel *t)
3742 return (enum CadetTunnelCState) -1;
3749 * Get the encryption state of a tunnel.
3753 * @return Tunnel's encryption state.
3755 enum CadetTunnelEState
3756 GCT_get_estate (struct CadetTunnel *t)
3761 return (enum CadetTunnelEState) -1;
3767 * Get the maximum buffer space for a tunnel towards a local client.
3771 * @return Biggest buffer space offered by any channel in the tunnel.
3774 GCT_get_channels_buffer (struct CadetTunnel *t)
3776 struct CadetTChannel *iter;
3777 unsigned int buffer;
3778 unsigned int ch_buf;
3780 if (NULL == t->channel_head)
3782 /* Probably getting buffer for a channel create/handshake. */
3783 LOG (GNUNET_ERROR_TYPE_DEBUG, " no channels, allow max\n");
3788 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3790 ch_buf = get_channel_buffer (iter);
3791 if (ch_buf > buffer)
3799 * Get the total buffer space for a tunnel for P2P traffic.
3803 * @return Buffer space offered by all connections in the tunnel.
3806 GCT_get_connections_buffer (struct CadetTunnel *t)
3808 struct CadetTConnection *iter;
3809 unsigned int buffer;
3811 if (GNUNET_NO == is_ready (t))
3813 if (count_queued_data (t) > 3)
3820 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3822 if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
3826 buffer += get_connection_buffer (iter);
3834 * Get the tunnel's destination.
3838 * @return ID of the destination peer.
3840 const struct GNUNET_PeerIdentity *
3841 GCT_get_destination (struct CadetTunnel *t)
3843 return GCP_get_id (t->peer);
3848 * Get the tunnel's next free global channel ID.
3852 * @return GID of a channel free to use.
3855 GCT_get_next_chid (struct CadetTunnel *t)
3857 CADET_ChannelNumber chid;
3858 CADET_ChannelNumber mask;
3861 /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
3862 * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
3863 * If peer's ID is bigger, start at 0x4... bit 30 = 1
3865 result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
3870 t->next_chid |= mask;
3872 while (NULL != GCT_get_channel (t, t->next_chid))
3874 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
3875 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3876 t->next_chid |= mask;
3878 chid = t->next_chid;
3879 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3880 t->next_chid |= mask;
3887 * Send ACK on one or more channels due to buffer in connections.
3889 * @param t Channel which has some free buffer space.
3892 GCT_unchoke_channels (struct CadetTunnel *t)
3894 struct CadetTChannel *iter;
3895 unsigned int buffer;
3896 unsigned int channels = GCT_count_channels (t);
3897 unsigned int choked_n;
3898 struct CadetChannel *choked[channels];
3900 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
3901 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
3902 if (NULL != t->channel_head)
3903 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
3905 /* Get buffer space */
3906 buffer = GCT_get_connections_buffer (t);
3912 /* Count and remember choked channels */
3914 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3916 if (GNUNET_NO == get_channel_allowed (iter))
3918 choked[choked_n++] = iter->ch;
3922 /* Unchoke random channels */
3923 while (0 < buffer && 0 < choked_n)
3925 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3927 GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
3930 choked[r] = choked[choked_n];
3936 * Send ACK on one or more connections due to buffer space to the client.
3938 * Iterates all connections of the tunnel and sends ACKs appropriately.
3943 GCT_send_connection_acks (struct CadetTunnel *t)
3945 struct CadetTConnection *iter;
3948 uint32_t allow_per_connection;
3950 unsigned int buffer;
3952 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
3961 if (CADET_TUNNEL_READY != t->cstate)
3964 buffer = GCT_get_channels_buffer (t);
3965 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer %u\n", buffer);
3967 /* Count connections, how many messages are already allowed */
3968 cs = GCT_count_connections (t);
3969 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3971 allowed += get_connection_allowed (iter);
3973 LOG (GNUNET_ERROR_TYPE_DEBUG, " allowed %u\n", allowed);
3975 /* Make sure there is no overflow */
3976 if (allowed > buffer)
3979 /* Authorize connections to send more data */
3980 to_allow = buffer - allowed;
3982 for (iter = t->connection_head;
3983 NULL != iter && to_allow > 0;
3986 if (CADET_CONNECTION_READY != GCC_get_state (iter->c)
3987 || get_connection_allowed (iter) > 64 / 3)
3991 allow_per_connection = to_allow/cs;
3992 to_allow -= allow_per_connection;
3994 GCC_allow (iter->c, allow_per_connection,
3995 GCC_is_origin (iter->c, GNUNET_NO));
4000 /* Since we don't allow if it's allowed to send 64/3, this can happen. */
4001 LOG (GNUNET_ERROR_TYPE_DEBUG, " reminding to_allow: %u\n", to_allow);
4007 * Cancel a previously sent message while it's in the queue.
4009 * ONLY can be called before the continuation given to the send function
4010 * is called. Once the continuation is called, the message is no longer in the
4013 * @param q Handle to the queue.
4016 GCT_cancel (struct CadetTunnelQueue *q)
4021 /* tun_message_sent() will be called and free q */
4023 else if (NULL != q->tqd)
4025 unqueue_data (q->tqd);
4027 if (NULL != q->cont)
4028 q->cont (q->cont_cls, NULL, q, 0, 0);
4039 * Sends an already built message on a tunnel, encrypting it and
4040 * choosing the best connection if not provided.
4042 * @param message Message to send. Function modifies it.
4043 * @param t Tunnel on which this message is transmitted.
4044 * @param c Connection to use (autoselect if NULL).
4045 * @param force Force the tunnel to take the message (buffer overfill).
4046 * @param cont Continuation to call once message is really sent.
4047 * @param cont_cls Closure for @c cont.
4049 * @return Handle to cancel message. NULL if @c cont is NULL.
4051 struct CadetTunnelQueue *
4052 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
4053 struct CadetTunnel *t, struct CadetConnection *c,
4054 int force, GCT_sent cont, void *cont_cls)
4056 return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
4061 * Send an Axolotl KX message.
4063 * @param t Tunnel on which to send it.
4066 GCT_send_ax_kx (struct CadetTunnel *t)
4068 struct GNUNET_CADET_AX_KX msg;
4070 LOG (GNUNET_ERROR_TYPE_INFO, "===> AX_KX for %s\n", GCT_2s (t));
4072 msg.header.size = htons (sizeof (msg));
4073 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_AX_KX);
4074 msg.permanent_key = ax_identity.permanent_key;
4075 msg.purpose = ax_identity.purpose;
4076 msg.signature = ax_identity.signature;
4077 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->kx_0, &msg.ephemeral_key);
4078 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &msg.ratchet_key);
4080 t->ephm_h = send_kx (t, &msg.header);
4081 GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
4086 * Sends an already built and encrypted message on a tunnel, choosing the best
4087 * connection. Useful for re-queueing messages queued on a destroyed connection.
4089 * @param message Message to send. Function modifies it.
4090 * @param t Tunnel on which this message is transmitted.
4093 GCT_resend_message (const struct GNUNET_MessageHeader *message,
4094 struct CadetTunnel *t)
4096 struct CadetConnection *c;
4099 c = tunnel_get_connection (t);
4102 /* TODO queue in tunnel, marked as encrypted */
4103 LOG (GNUNET_ERROR_TYPE_DEBUG, "No connection available, dropping.\n");
4106 fwd = GCC_is_origin (c, GNUNET_YES);
4107 GNUNET_break (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
4108 GNUNET_YES, NULL, NULL));
4113 * Is the tunnel directed towards the local peer?
4117 * @return #GNUNET_YES if it is loopback.
4120 GCT_is_loopback (const struct CadetTunnel *t)
4122 return (myid == GCP_get_short_id (t->peer));
4127 * Is the tunnel this path already?
4132 * @return #GNUNET_YES a connection uses this path.
4135 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
4137 struct CadetTConnection *iter;
4139 for (iter = t->connection_head; NULL != iter; iter = iter->next)
4140 if (path_equivalent (GCC_get_path (iter->c), p))
4148 * Get a cost of a path for a tunnel considering existing connections.
4151 * @param path Candidate path.
4153 * @return Cost of the path (path length + number of overlapping nodes)
4156 GCT_get_path_cost (const struct CadetTunnel *t,
4157 const struct CadetPeerPath *path)
4159 struct CadetTConnection *iter;
4160 const struct CadetPeerPath *aux;
4161 unsigned int overlap;
4169 GNUNET_assert (NULL != t);
4171 for (i = 0; i < path->length; i++)
4173 for (iter = t->connection_head; NULL != iter; iter = iter->next)
4175 aux = GCC_get_path (iter->c);
4179 for (j = 0; j < aux->length; j++)
4181 if (path->peers[i] == aux->peers[j])
4189 return path->length + overlap;
4194 * Get the static string for the peer this tunnel is directed.
4198 * @return Static string the destination peer's ID.
4201 GCT_2s (const struct CadetTunnel *t)
4206 return GCP_2s (t->peer);
4210 /******************************************************************************/
4211 /***************************** INFO/DEBUG *******************************/
4212 /******************************************************************************/
4215 ax_debug (const struct CadetTunnelAxolotl *ax, enum GNUNET_ErrorType level)
4217 struct GNUNET_CRYPTO_EcdhePublicKey pub;
4218 struct CadetTunnelSkippedKey *iter;
4221 LOG2 (level, "TTT RK\t %s\n",
4222 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->RK));
4224 LOG2 (level, "TTT HKs\t %s\n",
4225 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKs));
4226 LOG2 (level, "TTT HKr\t %s\n",
4227 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKr));
4228 LOG2 (level, "TTT NHKs\t %s\n",
4229 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->NHKs));
4230 LOG2 (level, "TTT NHKr\t %s\n",
4231 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->NHKr));
4233 LOG2 (level, "TTT CKs\t %s\n",
4234 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKs));
4235 LOG2 (level, "TTT CKr\t %s\n",
4236 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKr));
4238 GNUNET_CRYPTO_ecdhe_key_get_public (ax_key, &pub);
4239 LOG2 (level, "TTT DHIs\t %s\n",
4240 GNUNET_h2s ((struct GNUNET_HashCode *) &pub));
4241 LOG2 (level, "TTT DHIr\t %s\n",
4242 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->DHIr));
4243 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs, &pub);
4244 LOG2 (level, "TTT DHRs\t %s\n",
4245 GNUNET_h2s ((struct GNUNET_HashCode *) &pub));
4246 LOG2 (level, "TTT DHRr\t %s\n",
4247 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->DHRr));
4249 LOG2 (level, "TTT Nr\t %u\tNs\t%u\n", ax->Nr, ax->Ns);
4250 LOG2 (level, "TTT PNs\t %u\tSkipped\t%u\n", ax->PNs, ax->skipped);
4251 LOG2 (level, "TTT Ratchet\t%u\n", ax->ratchet_flag);
4253 for (iter = ax->skipped_head; NULL != iter; iter = iter->next)
4255 LOG2 (level, "TTT HK\t %s\n",
4256 GNUNET_h2s ((struct GNUNET_HashCode *) &iter->HK));
4257 LOG2 (level, "TTT MK\t %s\n",
4258 GNUNET_h2s ((struct GNUNET_HashCode *) &iter->MK));
4263 * Log all possible info about the tunnel state.
4265 * @param t Tunnel to debug.
4266 * @param level Debug level to use.
4269 GCT_debug (const struct CadetTunnel *t, enum GNUNET_ErrorType level)
4271 struct CadetTChannel *iterch;
4272 struct CadetTConnection *iterc;
4275 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
4277 __FILE__, __FUNCTION__, __LINE__);
4281 LOG2 (level, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
4282 LOG2 (level, "TTT cstate %s, estate %s\n",
4283 cstate2s (t->cstate), estate2s (t->estate));
4284 LOG2 (level, "TTT kx_ctx %p, rekey_task %u, finish task %u\n",
4285 t->kx_ctx, t->rekey_task, t->kx_ctx ? t->kx_ctx->finish_task : 0);
4286 #if DUMP_KEYS_TO_STDERR
4287 if (CADET_Axolotl == t->enc_type)
4289 ax_debug (t->ax, level);
4293 LOG2 (level, "TTT my EPHM\t %s\n",
4294 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
4295 LOG2 (level, "TTT peers EPHM:\t %s\n",
4296 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
4297 LOG2 (level, "TTT ENC key:\t %s\n",
4298 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
4299 LOG2 (level, "TTT DEC key:\t %s\n",
4300 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
4303 LOG2 (level, "TTT OLD ENC key:\t %s\n",
4304 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->e_key_old));
4305 LOG2 (level, "TTT OLD DEC key:\t %s\n",
4306 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->d_key_old));
4310 LOG2 (level, "TTT tq_head %p, tq_tail %p\n", t->tq_head, t->tq_tail);
4311 LOG2 (level, "TTT destroy %u\n", t->destroy_task);
4313 LOG2 (level, "TTT channels:\n");
4314 for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
4316 LOG2 (level, "TTT - %s\n", GCCH_2s (iterch->ch));
4319 LOG2 (level, "TTT connections:\n");
4320 for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
4322 GCC_debug (iterc->c, level);
4325 LOG2 (level, "TTT DEBUG TUNNEL END\n");
4330 * Iterate all tunnels.
4332 * @param iter Iterator.
4333 * @param cls Closure for @c iter.
4336 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
4338 GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
4343 * Count all tunnels.
4345 * @return Number of tunnels to remote peers kept by this peer.
4348 GCT_count_all (void)
4350 return GNUNET_CONTAINER_multipeermap_size (tunnels);
4355 * Iterate all connections of a tunnel.
4357 * @param t Tunnel whose connections to iterate.
4358 * @param iter Iterator.
4359 * @param cls Closure for @c iter.
4362 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
4364 struct CadetTConnection *ct;
4366 for (ct = t->connection_head; NULL != ct; ct = ct->next)
4372 * Iterate all channels of a tunnel.
4374 * @param t Tunnel whose channels to iterate.
4375 * @param iter Iterator.
4376 * @param cls Closure for @c iter.
4379 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
4381 struct CadetTChannel *cht;
4383 for (cht = t->channel_head; NULL != cht; cht = cht->next)
4384 iter (cls, cht->ch);