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 * A (double linked) list of staged message keys and associated header keys
215 * for "skipped" messages, before they are commited to the real skipped list.
217 struct CadetTunnelSkippedKey *staged_head;
220 * Skipped messages' keys DLL, tail.
222 struct CadetTunnelSkippedKey *staged_tail;
225 * Elements in @a staged_head <-> @a staged_head.
230 * 32-byte root key which gets updated by DH ratchet.
232 struct GNUNET_CRYPTO_SymmetricSessionKey RK;
235 * 32-byte header key (send).
237 struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
240 * 32-byte header key (recv)
242 struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
245 * 32-byte next header key (send).
247 struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
250 * 32-byte next header key (recv).
252 struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
255 * 32-byte chain keys (used for forward-secrecy updating, send).
257 struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
260 * 32-byte chain keys (used for forward-secrecy updating, recv).
262 struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
265 * ECDH for key exchange (A0 / B0).
267 struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
270 * ECDH Identity key (recv).
272 struct GNUNET_CRYPTO_EcdhePublicKey DHIr;
275 * ECDH Ratchet key (send).
277 struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
280 * ECDH Ratchet key (recv).
282 struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
285 * Message number (reset to 0 with each new ratchet, next message to send).
290 * Message number (reset to 0 with each new ratchet, next message to recv).
295 * Previous message numbers (# of msgs sent under prev ratchet)
300 * True (#GNUNET_YES) if the party will send a new ratchet key in next msg.
306 * Struct containing all information regarding a tunnel to a peer.
311 * Endpoint of the tunnel.
313 struct CadetPeer *peer;
316 * Type of encryption used in the tunnel.
318 enum CadetTunnelEncryption enc_type;
323 struct CadetTunnelAxolotl *ax;
326 * State of the tunnel connectivity.
328 enum CadetTunnelCState cstate;
331 * State of the tunnel encryption.
333 enum CadetTunnelEState estate;
336 * Key eXchange context.
338 struct CadetTunnelKXCtx *kx_ctx;
341 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own ephemeral
344 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
347 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
349 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
352 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
354 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
357 * Task to start the rekey process.
359 struct GNUNET_SCHEDULER_Task * rekey_task;
362 * Paths that are actively used to reach the destination peer.
364 struct CadetTConnection *connection_head;
365 struct CadetTConnection *connection_tail;
368 * Next connection number.
373 * Channels inside this tunnel.
375 struct CadetTChannel *channel_head;
376 struct CadetTChannel *channel_tail;
379 * Channel ID for the next created channel.
381 CADET_ChannelNumber next_chid;
384 * Destroy flag: if true, destroy on last message.
386 struct GNUNET_SCHEDULER_Task * destroy_task;
389 * Queued messages, to transmit once tunnel gets connected.
391 struct CadetTunnelDelayed *tq_head;
392 struct CadetTunnelDelayed *tq_tail;
395 * Task to trim connections if too many are present.
397 struct GNUNET_SCHEDULER_Task * trim_connections_task;
400 * Ephemeral message in the queue (to avoid queueing more than one).
402 struct CadetConnectionQueue *ephm_h;
405 * Pong message in the queue.
407 struct CadetConnectionQueue *pong_h;
412 * Struct used to save messages in a non-ready tunnel to send once connected.
414 struct CadetTunnelDelayed
419 struct CadetTunnelDelayed *next;
420 struct CadetTunnelDelayed *prev;
425 struct CadetTunnel *t;
428 * Tunnel queue given to the channel to cancel request. Update on send_queued.
430 struct CadetTunnelQueue *tq;
435 /* struct GNUNET_MessageHeader *msg; */
440 * Handle for messages queued but not yet sent.
442 struct CadetTunnelQueue
445 * Connection queue handle, to cancel if necessary.
447 struct CadetConnectionQueue *cq;
450 * Handle in case message hasn't been given to a connection yet.
452 struct CadetTunnelDelayed *tqd;
455 * Continuation to call once sent.
460 * Closure for @c cont.
467 * Cached Axolotl key with signature.
469 struct CadetAxolotlSignedKey
472 * Information about what is being signed (@a permanent_key).
474 struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
477 * Permanent public ECDH key.
479 struct GNUNET_CRYPTO_EcdhePublicKey permanent_key;
482 * An EdDSA signature of the permanent ECDH key with the Peer's ID key.
484 struct GNUNET_CRYPTO_EddsaSignature signature;
488 /******************************************************************************/
489 /******************************* GLOBALS ***********************************/
490 /******************************************************************************/
493 * Global handle to the statistics service.
495 extern struct GNUNET_STATISTICS_Handle *stats;
498 * Local peer own ID (memory efficient handle).
500 extern GNUNET_PEER_Id myid;
503 * Local peer own ID (full value).
505 extern struct GNUNET_PeerIdentity my_full_id;
509 * Don't try to recover tunnels if shutting down.
511 extern int shutting_down;
515 * Set of all tunnels, in order to trigger a new exchange on rekey.
516 * Indexed by peer's ID.
518 static struct GNUNET_CONTAINER_MultiPeerMap *tunnels;
521 * Default TTL for payload packets.
523 static unsigned long long default_ttl;
527 * Own Peer ID private key.
529 const static struct GNUNET_CRYPTO_EddsaPrivateKey *id_key;
531 /******************************** AXOLOTL ************************************/
533 static struct GNUNET_CRYPTO_EcdhePrivateKey *ax_key;
536 * Own Axolotl permanent public key (cache).
538 static struct CadetAxolotlSignedKey ax_identity;
540 /******************************** OTR ***********************************/
544 * Own global OTR ephemeral private key.
546 static struct GNUNET_CRYPTO_EcdhePrivateKey *otr_ephemeral_key;
549 * Cached message used to perform a OTR key exchange.
551 static struct GNUNET_CADET_KX_Ephemeral otr_kx_msg;
554 * Task to generate a new OTR ephemeral key.
556 static struct GNUNET_SCHEDULER_Task *rekey_task;
561 static struct GNUNET_TIME_Relative rekey_period;
564 /******************************************************************************/
565 /******************************** STATIC ***********************************/
566 /******************************************************************************/
569 * Get string description for tunnel connectivity state.
571 * @param cs Tunnel state.
573 * @return String representation.
576 cstate2s (enum CadetTunnelCState cs)
582 case CADET_TUNNEL_NEW:
583 return "CADET_TUNNEL_NEW";
584 case CADET_TUNNEL_SEARCHING:
585 return "CADET_TUNNEL_SEARCHING";
586 case CADET_TUNNEL_WAITING:
587 return "CADET_TUNNEL_WAITING";
588 case CADET_TUNNEL_READY:
589 return "CADET_TUNNEL_READY";
590 case CADET_TUNNEL_SHUTDOWN:
591 return "CADET_TUNNEL_SHUTDOWN";
593 SPRINTF (buf, "%u (UNKNOWN STATE)", cs);
601 * Get string description for tunnel encryption state.
603 * @param es Tunnel state.
605 * @return String representation.
608 estate2s (enum CadetTunnelEState es)
614 case CADET_TUNNEL_KEY_UNINITIALIZED:
615 return "CADET_TUNNEL_KEY_UNINITIALIZED";
616 case CADET_TUNNEL_KEY_SENT:
617 return "CADET_TUNNEL_KEY_SENT";
618 case CADET_TUNNEL_KEY_PING:
619 return "CADET_TUNNEL_KEY_PING";
620 case CADET_TUNNEL_KEY_OK:
621 return "CADET_TUNNEL_KEY_OK";
622 case CADET_TUNNEL_KEY_REKEY:
623 return "CADET_TUNNEL_KEY_REKEY";
625 SPRINTF (buf, "%u (UNKNOWN STATE)", es);
633 * @brief Check if tunnel is ready to send traffic.
635 * Tunnel must be connected and with encryption correctly set up.
637 * @param t Tunnel to check.
639 * @return #GNUNET_YES if ready, #GNUNET_NO otherwise
642 is_ready (struct CadetTunnel *t)
646 GCT_debug (t, GNUNET_ERROR_TYPE_DEBUG);
647 ready = CADET_TUNNEL_READY == t->cstate
648 && (CADET_TUNNEL_KEY_OK == t->estate
649 || CADET_TUNNEL_KEY_REKEY == t->estate);
650 ready = ready || GCT_is_loopback (t);
656 * Check if a key is invalid (NULL pointer or all 0)
658 * @param key Key to check.
660 * @return #GNUNET_YES if key is null, #GNUNET_NO if exists and is not 0.
663 is_key_null (struct GNUNET_CRYPTO_SymmetricSessionKey *key)
665 struct GNUNET_CRYPTO_SymmetricSessionKey null_key;
670 memset (&null_key, 0, sizeof (null_key));
671 if (0 == memcmp (key, &null_key, sizeof (null_key)))
678 * Ephemeral key message purpose size.
680 * @return Size of the part of the ephemeral key message that must be signed.
683 ephemeral_purpose_size (void)
685 return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
686 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
687 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
688 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
689 sizeof (struct GNUNET_PeerIdentity);
694 * Ephemeral key message purpose size.
696 * @return Size of the part of the ephemeral key message that must be signed.
699 ax_purpose_size (void)
701 return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
702 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey);
707 * Size of the encrypted part of a ping message.
709 * @return Size of the encrypted part of a ping message.
712 ping_encryption_size (void)
714 return sizeof (uint32_t);
719 * Get the channel's buffer. ONLY FOR NON-LOOPBACK CHANNELS!!
721 * @param tch Tunnel's channel handle.
723 * @return Amount of messages the channel can still buffer towards the client.
726 get_channel_buffer (const struct CadetTChannel *tch)
730 /* If channel is incoming, is terminal in the FWD direction and fwd is YES */
731 fwd = GCCH_is_terminal (tch->ch, GNUNET_YES);
733 return GCCH_get_buffer (tch->ch, fwd);
738 * Get the channel's allowance status.
740 * @param tch Tunnel's channel handle.
742 * @return #GNUNET_YES if we allowed the client to send data to us.
745 get_channel_allowed (const struct CadetTChannel *tch)
749 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
750 fwd = GCCH_is_origin (tch->ch, GNUNET_YES);
752 return GCCH_get_allowed (tch->ch, fwd);
757 * Get the connection's buffer.
759 * @param tc Tunnel's connection handle.
761 * @return Amount of messages the connection can still buffer.
764 get_connection_buffer (const struct CadetTConnection *tc)
768 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
769 fwd = GCC_is_origin (tc->c, GNUNET_YES);
771 return GCC_get_buffer (tc->c, fwd);
776 * Get the connection's allowance.
778 * @param tc Tunnel's connection handle.
780 * @return Amount of messages we have allowed the next peer to send us.
783 get_connection_allowed (const struct CadetTConnection *tc)
787 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
788 fwd = GCC_is_origin (tc->c, GNUNET_YES);
790 return GCC_get_allowed (tc->c, fwd);
795 * Check that a ephemeral key message s well formed and correctly signed.
797 * @param t Tunnel on which the message came.
798 * @param msg The ephemeral key message.
800 * @return GNUNET_OK if message is fine, GNUNET_SYSERR otherwise.
803 check_ephemeral (struct CadetTunnel *t,
804 const struct GNUNET_CADET_KX_Ephemeral *msg)
806 /* Check message size */
807 if (ntohs (msg->header.size) != sizeof (struct GNUNET_CADET_KX_Ephemeral))
808 return GNUNET_SYSERR;
810 /* Check signature size */
811 if (ntohl (msg->purpose.size) != ephemeral_purpose_size ())
812 return GNUNET_SYSERR;
815 if (0 != memcmp (&msg->origin_identity,
816 GCP_get_id (t->peer),
817 sizeof (struct GNUNET_PeerIdentity)))
818 return GNUNET_SYSERR;
820 /* Check signature */
822 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_CADET_KX,
825 &msg->origin_identity.public_key))
826 return GNUNET_SYSERR;
833 * Select the best key to use for encryption (send), based on KX status.
835 * Normally, return the current key. If there is a KX in progress and the old
836 * key is fresh enough, return the old key.
838 * @param t Tunnel to choose the key from.
840 * @return The optimal key to encrypt/hmac outgoing traffic.
842 static const struct GNUNET_CRYPTO_SymmetricSessionKey *
843 select_key (const struct CadetTunnel *t)
845 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
847 if (NULL != t->kx_ctx
848 && NULL == t->kx_ctx->finish_task)
850 struct GNUNET_TIME_Relative age;
852 age = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
853 LOG (GNUNET_ERROR_TYPE_DEBUG,
854 " key exchange in progress, started %s ago\n",
855 GNUNET_STRINGS_relative_time_to_string (age, GNUNET_YES));
856 // FIXME make duration of old keys configurable
857 if (age.rel_value_us < GNUNET_TIME_UNIT_MINUTES.rel_value_us)
859 LOG (GNUNET_ERROR_TYPE_DEBUG, " using old key\n");
860 key = &t->kx_ctx->e_key_old;
864 LOG (GNUNET_ERROR_TYPE_DEBUG, " using new key (old key too old)\n");
870 LOG (GNUNET_ERROR_TYPE_DEBUG, " no KX: using current key\n");
880 * @param plaintext Content to HMAC.
881 * @param size Size of @c plaintext.
882 * @param iv Initialization vector for the message.
883 * @param key Key to use.
884 * @param hmac[out] Destination to store the HMAC.
887 t_hmac (const void *plaintext, size_t size,
888 uint32_t iv, const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
889 struct GNUNET_CADET_Hash *hmac)
891 static const char ctx[] = "cadet authentication key";
892 struct GNUNET_CRYPTO_AuthKey auth_key;
893 struct GNUNET_HashCode hash;
895 #if DUMP_KEYS_TO_STDERR
896 LOG (GNUNET_ERROR_TYPE_INFO, " HMAC %u bytes with key %s\n", size,
897 GNUNET_h2s ((struct GNUNET_HashCode *) key));
899 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
904 /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
905 GNUNET_CRYPTO_hmac (&auth_key, plaintext, size, &hash);
906 memcpy (hmac, &hash, sizeof (*hmac));
911 * Encrypt daforce_newest_keyta with the tunnel key.
913 * @param t Tunnel whose key to use.
914 * @param dst Destination for the encrypted data.
915 * @param src Source of the plaintext. Can overlap with @c dst.
916 * @param size Size of the plaintext.
917 * @param iv Initialization Vector to use.
918 * @param force_newest_key Force the use of the newest key, otherwise
919 * CADET will use the old key when allowed.
920 * This can happen in the case when a KX is going on
921 * and the old one hasn't expired.
924 t_encrypt (struct CadetTunnel *t, void *dst, const void *src,
925 size_t size, uint32_t iv, int force_newest_key)
927 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
928 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
931 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt start\n");
933 key = GNUNET_YES == force_newest_key ? &t->e_key : select_key (t);
934 #if DUMP_KEYS_TO_STDERR
935 LOG (GNUNET_ERROR_TYPE_INFO, " ENC with key %s\n",
936 GNUNET_h2s ((struct GNUNET_HashCode *) key));
938 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
939 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt IV derived\n");
940 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, key, &siv, dst);
941 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt end\n");
950 * @param key Key to use.
951 * @param hash[out] Resulting HMAC.
952 * @param source Source key material (data to HMAC).
953 * @param len Length of @a source.
956 t_ax_hmac_hash (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
957 struct GNUNET_HashCode *hash,
958 void *source, unsigned int len)
960 static const char ctx[] = "axolotl HMAC-HASH";
961 struct GNUNET_CRYPTO_AuthKey auth_key;
963 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
966 GNUNET_CRYPTO_hmac (&auth_key, source, len, hash);
971 * Derive a key from a HMAC-HASH.
973 * @param key Key to use for the HMAC.
974 * @param out Key to generate.
975 * @param source Source key material (data to HMAC).
976 * @param len Length of @a source.
979 t_hmac_derive_key (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
980 struct GNUNET_CRYPTO_SymmetricSessionKey *out,
981 void *source, unsigned int len)
983 static const char ctx[] = "axolotl derive key";
984 struct GNUNET_HashCode h;
986 t_ax_hmac_hash (key, &h, source, len);
987 GNUNET_CRYPTO_kdf (out, sizeof (*out), ctx, sizeof (ctx),
988 &h, sizeof (h), NULL);
993 * Encrypt data with the axolotl tunnel key.
995 * @param t Tunnel whose key to use.
996 * @param dst Destination for the encrypted data.
997 * @param src Source of the plaintext. Can overlap with @c dst.
998 * @param size Size of the plaintext.
1000 * @return Size of the encrypted data.
1003 t_ax_encrypt (struct CadetTunnel *t, void *dst, const void *src, size_t size)
1005 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
1006 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1007 struct CadetTunnelAxolotl *ax;
1010 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt start\n");
1014 if (GNUNET_YES == ax->ratchet_flag)
1016 /* Advance ratchet */
1017 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
1018 struct GNUNET_HashCode dh;
1019 struct GNUNET_HashCode hmac;
1020 static const char ctx[] = "axolotl ratchet";
1022 ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
1025 /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
1026 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs, &ax->DHRr, &dh);
1027 t_ax_hmac_hash (&ax->RK, &hmac, &dh, sizeof (dh));
1028 GNUNET_CRYPTO_kdf (keys, sizeof (keys), ctx, sizeof (ctx),
1029 &hmac, sizeof (hmac), NULL);
1036 ax->ratchet_flag = GNUNET_NO;
1039 t_hmac_derive_key (&ax->CKs, &MK, "0", 1);
1040 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &MK, NULL, 0, NULL);
1042 #if DUMP_KEYS_TO_STDERR
1043 LOG (GNUNET_ERROR_TYPE_INFO, " txt: %s\n",
1044 GNUNET_h2s ((struct GNUNET_HashCode *) src));
1045 LOG (GNUNET_ERROR_TYPE_INFO, " CKs: %s\n",
1046 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKs));
1047 LOG (GNUNET_ERROR_TYPE_INFO, " AX_ENC with key %s\n",
1048 GNUNET_h2s ((struct GNUNET_HashCode *) &MK));
1051 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, &MK, &iv, dst);
1053 t_hmac_derive_key (&ax->CKs, &ax->CKs, "1", 1);
1055 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt end\n");
1062 * Decrypt data with the axolotl tunnel key.
1064 * @param t Tunnel whose key to use.
1065 * @param dst Destination for the decrypted data.
1066 * @param src Source of the ciphertext. Can overlap with @c dst.
1067 * @param size Size of the ciphertext.
1069 * @return Size of the decrypted data.
1072 t_ax_decrypt (struct CadetTunnel *t, void *dst, const void *src, size_t size)
1074 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
1075 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1076 struct CadetTunnelAxolotl *ax;
1079 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_decrypt start\n");
1083 t_hmac_derive_key (&ax->CKr, &MK, "0", 1);
1084 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &MK, NULL, 0, NULL);
1086 #if DUMP_KEYS_TO_STDERR
1087 LOG (GNUNET_ERROR_TYPE_INFO, " CKr: %s\n",
1088 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKr));
1089 LOG (GNUNET_ERROR_TYPE_INFO, " AX_DEC with key %s\n",
1090 GNUNET_h2s ((struct GNUNET_HashCode *) &MK));
1093 GNUNET_assert (size > sizeof (struct GNUNET_MessageHeader));
1094 out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, &MK, &iv, dst);
1095 GNUNET_assert (out_size == size);
1097 t_hmac_derive_key (&ax->CKr, &ax->CKr, "1", 1);
1099 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_decrypt end\n");
1100 LOG (GNUNET_ERROR_TYPE_INFO, " txt: %s\n",
1101 GNUNET_h2s ((struct GNUNET_HashCode *) dst));
1109 * Encrypt header with the axolotl header key.
1111 * @param t Tunnel whose key to use.
1112 * @param msg Message whose header to encrypt.
1115 t_h_encrypt (struct CadetTunnel *t, struct GNUNET_CADET_AX *msg)
1117 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1118 struct CadetTunnelAxolotl *ax;
1121 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_h_encrypt start\n");
1124 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &ax->HKs, NULL, 0, NULL);
1126 #if DUMP_KEYS_TO_STDERR
1127 LOG (GNUNET_ERROR_TYPE_INFO, " AX_ENC_H with key %s\n",
1128 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKs));
1131 out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->Ns, AX_HEADER_SIZE,
1132 &ax->HKs, &iv, &msg->Ns);
1134 GNUNET_assert (AX_HEADER_SIZE == out_size);
1136 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt end\n");
1141 * Decrypt header with the current axolotl header key.
1143 * @param t Tunnel whose current ax HK to use.
1144 * @param src Message whose header to decrypt.
1145 * @param dst Where to decrypt header to.
1148 t_h_decrypt (struct CadetTunnel *t, const struct GNUNET_CADET_AX *src,
1149 struct GNUNET_CADET_AX *dst)
1151 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1152 struct CadetTunnelAxolotl *ax;
1155 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_h_decrypt start\n");
1158 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &ax->HKr, NULL, 0, NULL);
1160 #if DUMP_KEYS_TO_STDERR
1161 LOG (GNUNET_ERROR_TYPE_INFO, " AX_DEC_H with key %s\n",
1162 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKr));
1165 out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns, AX_HEADER_SIZE,
1166 &ax->HKr, &iv, &dst->Ns);
1168 GNUNET_assert (AX_HEADER_SIZE == out_size);
1170 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_decrypt end\n");
1175 * Decrypt and verify data with the appropriate tunnel key.
1177 * @param key Key to use.
1178 * @param dst Destination for the plaintext.
1179 * @param src Source of the encrypted data. Can overlap with @c dst.
1180 * @param size Size of the encrypted data.
1181 * @param iv Initialization Vector to use.
1183 * @return Size of the decrypted data, -1 if an error was encountered.
1186 decrypt (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
1187 void *dst, const void *src, size_t size, uint32_t iv)
1189 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
1192 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt start\n");
1193 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv\n");
1194 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
1195 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv done\n");
1196 out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, key, &siv, dst);
1197 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt end\n");
1204 * Decrypt and verify data with the most recent tunnel key.
1206 * @param t Tunnel whose key to use.
1207 * @param dst Destination for the plaintext.
1208 * @param src Source of the encrypted data. Can overlap with @c dst.
1209 * @param size Size of the encrypted data.
1210 * @param iv Initialization Vector to use.
1212 * @return Size of the decrypted data, -1 if an error was encountered.
1215 t_decrypt (struct CadetTunnel *t, void *dst, const void *src,
1216 size_t size, uint32_t iv)
1220 #if DUMP_KEYS_TO_STDERR
1221 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_decrypt with %s\n",
1222 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
1224 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1226 GNUNET_STATISTICS_update (stats, "# non decryptable data", 1, GNUNET_NO);
1227 LOG (GNUNET_ERROR_TYPE_WARNING,
1228 "got data on %s without a valid key\n",
1230 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1234 out_size = decrypt (&t->d_key, dst, src, size, iv);
1241 * Decrypt and verify data with the appropriate tunnel key and verify that the
1242 * data has not been altered since it was sent by the remote peer.
1244 * @param t Tunnel whose key to use.
1245 * @param dst Destination for the plaintext.
1246 * @param src Source of the encrypted data. Can overlap with @c dst.
1247 * @param size Size of the encrypted data.
1248 * @param iv Initialization Vector to use.
1249 * @param msg_hmac HMAC of the message, cannot be NULL.
1251 * @return Size of the decrypted data, -1 if an error was encountered.
1254 t_decrypt_and_validate (struct CadetTunnel *t,
1255 void *dst, const void *src,
1256 size_t size, uint32_t iv,
1257 const struct GNUNET_CADET_Hash *msg_hmac)
1259 struct GNUNET_CRYPTO_SymmetricSessionKey *key;
1260 struct GNUNET_CADET_Hash hmac;
1263 /* Try primary (newest) key */
1265 decrypted_size = decrypt (key, dst, src, size, iv);
1266 t_hmac (src, size, iv, key, &hmac);
1267 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1268 return decrypted_size;
1270 /* If no key exchange is going on, we just failed. */
1271 if (NULL == t->kx_ctx)
1273 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1274 "Failed checksum validation on tunnel %s with no KX\n",
1276 GNUNET_STATISTICS_update (stats, "# wrong HMAC no KX", 1, GNUNET_NO);
1280 /* Try secondary key, from previous KX period. */
1281 key = &t->kx_ctx->d_key_old;
1282 decrypted_size = decrypt (key, dst, src, size, iv);
1283 t_hmac (src, size, iv, key, &hmac);
1284 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1285 return decrypted_size;
1287 /* Hail Mary, try tertiary, key, in case of parallel re-keys. */
1288 key = &t->kx_ctx->d_key_old2;
1289 decrypted_size = decrypt (key, dst, src, size, iv);
1290 t_hmac (src, size, iv, key, &hmac);
1291 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1292 return decrypted_size;
1294 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1295 "Failed checksum validation on tunnel %s with KX\n",
1297 GNUNET_STATISTICS_update (stats, "# wrong HMAC with KX", 1, GNUNET_NO);
1303 * Decrypt and verify data with the appropriate tunnel key and verify that the
1304 * data has not been altered since it was sent by the remote peer.
1306 * @param t Tunnel whose key to use.
1307 * @param dst Destination for the plaintext.
1308 * @param src Source of the message. Can overlap with @c dst.
1309 * @param size Size of the message.
1311 * @return Size of the decrypted data, -1 if an error was encountered.
1314 try_old_ax_keys (struct CadetTunnel *t, struct GNUNET_CADET_AX *dst,
1315 const struct GNUNET_CADET_AX *src, size_t size)
1317 struct CadetTunnelSkippedKey *key;
1318 struct GNUNET_CADET_Hash hmac;
1319 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1324 for (key = t->ax->skipped_head; NULL != key; key = key->next)
1326 t_hmac (&src->Ns, AX_HEADER_SIZE, 0, &key->HK, &hmac);
1327 if (0 != memcmp (&hmac, &src->hmac, sizeof (hmac)))
1333 #if DUMP_KEYS_TO_STDERR
1334 LOG (GNUNET_ERROR_TYPE_INFO, " AX_DEC with skipped key %s\n",
1335 GNUNET_h2s ((struct GNUNET_HashCode *) &key->MK));
1338 GNUNET_assert (size > sizeof (struct GNUNET_CADET_AX));
1339 len = size - sizeof (struct GNUNET_CADET_AX);
1340 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &key->MK, NULL, 0, NULL);
1341 res = GNUNET_CRYPTO_symmetric_decrypt (&src[1], len, &key->MK, &iv, &dst[1]);
1343 GNUNET_CONTAINER_DLL_remove (t->ax->skipped_head, t->ax->skipped_tail, key);
1352 * Stage skipped AX keys and calculate the message key.
1354 * Stores each HK and MK for skipped messages.
1356 * @param t Tunnel where to stage the keys.
1357 * @param HKr Header key.
1358 * @param Nr Current message number.
1359 * @param Np Received meesage number.
1360 * @param CKr[in/out] Chain key, gets ratcheted forward to the new state.
1363 stage_ax_keys (struct CadetTunnel *t,
1364 const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1365 uint32_t Nr, uint32_t Np,
1366 struct GNUNET_CRYPTO_SymmetricSessionKey *CKr)
1368 struct CadetTunnelSkippedKey *key;
1371 if (Np - Nr > MAX_KEY_GAP)
1373 /* Avoid DoS (forcing peer to do 2*33 chain HMAC operations) */
1374 /* TODO: start new key exchange on return */
1375 GNUNET_break_op (0);
1379 for (i = Nr; i < Np; i++)
1381 key = GNUNET_new (struct CadetTunnelSkippedKey);
1382 key->timestamp = GNUNET_TIME_absolute_get ();
1383 t_hmac_derive_key (CKr, &key->MK, "0", 1);
1384 #if DUMP_KEYS_TO_STDERR
1385 LOG (GNUNET_ERROR_TYPE_INFO, " storing MK for Nr %u: %s\n",
1386 GNUNET_h2s ((struct GNUNET_HashCode *) &key->MK));
1387 LOG (GNUNET_ERROR_TYPE_INFO, " for CKr: %s\n",
1388 GNUNET_h2s ((struct GNUNET_HashCode *) &t->ax->CKr));
1390 t_hmac_derive_key (CKr, CKr, "1", 1);
1391 GNUNET_CONTAINER_DLL_insert (t->ax->skipped_head, t->ax->skipped_tail, key);
1395 for (;t->ax->skipped > MAX_SKIPPED_KEYS; t->ax->skipped--)
1397 key = t->ax->skipped_tail;
1398 GNUNET_CONTAINER_DLL_remove (t->ax->skipped_head, t->ax->skipped_tail, key);
1405 * Commit staged keys.
1407 * @param t Tunnel whose keys to commit.
1410 commit_ax_keys (struct CadetTunnel *t)
1417 * Decrypt and verify data with the appropriate tunnel key and verify that the
1418 * data has not been altered since it was sent by the remote peer.
1420 * @param t Tunnel whose key to use.
1421 * @param dst Destination for the plaintext.
1422 * @param src Source of the message. Can overlap with @c dst.
1423 * @param size Size of the message.
1425 * @return Size of the decrypted data, -1 if an error was encountered.
1428 t_ax_decrypt_and_validate (struct CadetTunnel *t, void *dst,
1429 const struct GNUNET_CADET_AX *src, size_t size)
1431 struct CadetTunnelAxolotl *ax;
1432 struct GNUNET_CADET_Hash msg_hmac;
1433 struct GNUNET_HashCode hmac;
1434 struct GNUNET_CADET_AX *dstmsg;
1442 esize = size - sizeof (struct GNUNET_CADET_AX);
1447 /* Try current HK */
1448 t_hmac (&src->Ns, AX_HEADER_SIZE + esize, 0, &ax->HKr, &msg_hmac);
1449 if (0 != memcmp (&msg_hmac, &src->hmac, sizeof (msg_hmac)))
1451 static const char ctx[] = "axolotl ratchet";
1452 struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1453 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1454 struct GNUNET_HashCode dh;
1455 struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1458 t_hmac (&src->Ns, AX_HEADER_SIZE + esize, 0, &ax->NHKr, &msg_hmac);
1459 if (0 != memcmp (&msg_hmac, &src->hmac, sizeof (msg_hmac)))
1461 /* Try the skipped keys, if that fails, we're out of luck. */
1462 return try_old_ax_keys (t, dst, src, size);
1464 LOG (GNUNET_ERROR_TYPE_INFO, "next HK\n");
1468 t_h_decrypt (t, src, dstmsg);
1469 Np = ntohl (dstmsg->Ns);
1470 PNp = ntohl (dstmsg->PNs);
1471 DHRp = &dstmsg->DHRs;
1472 stage_ax_keys (t, &HK, ax->Nr, PNp, &ax->CKr);
1474 /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1475 GNUNET_CRYPTO_ecc_ecdh (ax->DHRs, DHRp, &dh);
1476 t_ax_hmac_hash (&ax->RK, &hmac, &dh, sizeof (dh));
1477 GNUNET_CRYPTO_kdf (keys, sizeof (keys), ctx, sizeof (ctx),
1478 &hmac, sizeof (hmac), NULL);
1480 /* Commit "purported" keys */
1489 LOG (GNUNET_ERROR_TYPE_DEBUG, "current HK\n");
1490 t_h_decrypt (t, src, dstmsg);
1491 Np = ntohl (dstmsg->Ns);
1492 PNp = ntohl (dstmsg->PNs);
1495 if (Np > ax->Nr + 1)
1496 stage_ax_keys (t, &ax->HKr, ax->Nr, Np, &ax->CKr);
1501 osize = t_ax_decrypt (t, dst, &src[1], size);
1504 GNUNET_break_op (0);
1513 * Create key material by doing ECDH on the local and remote ephemeral keys.
1515 * @param key_material Where to store the key material.
1516 * @param ephemeral Peer's public ephemeral key.
1518 * @return GNUNET_OK if it went fine, GNUNET_SYSERR otherwise.
1521 derive_otr_key_material (struct GNUNET_HashCode *key_material,
1522 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral)
1525 GNUNET_CRYPTO_ecc_ecdh (otr_ephemeral_key, ephemeral, key_material))
1528 return GNUNET_SYSERR;
1535 * Create a symmetic key from the identities of both ends and the key material
1538 * @param key Destination for the generated key.
1539 * @param sender ID of the peer that will encrypt with @c key.
1540 * @param receiver ID of the peer that will decrypt with @c key.
1541 * @param key_material Hash created with ECDH with the ephemeral keys.
1544 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
1545 const struct GNUNET_PeerIdentity *sender,
1546 const struct GNUNET_PeerIdentity *receiver,
1547 const struct GNUNET_HashCode *key_material)
1549 const char salt[] = "CADET kx salt";
1551 GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
1552 salt, sizeof (salt),
1553 key_material, sizeof (struct GNUNET_HashCode),
1554 sender, sizeof (struct GNUNET_PeerIdentity),
1555 receiver, sizeof (struct GNUNET_PeerIdentity),
1561 * Derive the tunnel's keys using our own and the peer's ephemeral keys.
1563 * @param t Tunnel for which to create the keys.
1565 * @return GNUNET_OK if successful, GNUNET_SYSERR otherwise.
1568 create_otr_keys (struct CadetTunnel *t)
1570 struct GNUNET_HashCode km;
1572 if (GNUNET_OK != derive_otr_key_material (&km, &t->peers_ephemeral_key))
1573 return GNUNET_SYSERR;
1574 derive_symmertic (&t->e_key, &my_full_id, GCP_get_id (t->peer), &km);
1575 derive_symmertic (&t->d_key, GCP_get_id (t->peer), &my_full_id, &km);
1576 #if DUMP_KEYS_TO_STDERR
1577 LOG (GNUNET_ERROR_TYPE_INFO, "ME: %s\n",
1578 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
1579 LOG (GNUNET_ERROR_TYPE_INFO, "PE: %s\n",
1580 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
1581 LOG (GNUNET_ERROR_TYPE_INFO, "KM: %s\n", GNUNET_h2s (&km));
1582 LOG (GNUNET_ERROR_TYPE_INFO, "EK: %s\n",
1583 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
1584 LOG (GNUNET_ERROR_TYPE_INFO, "DK: %s\n",
1585 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
1592 * Create a new Key eXchange context for the tunnel.
1594 * If the old keys were verified, keep them for old traffic. Create a new KX
1595 * timestamp and a new nonce.
1597 * @param t Tunnel for which to create the KX ctx.
1599 * @return GNUNET_OK if successful, GNUNET_SYSERR otherwise.
1602 create_kx_ctx (struct CadetTunnel *t)
1604 LOG (GNUNET_ERROR_TYPE_INFO, " new kx ctx for %s\n", GCT_2s (t));
1606 if (NULL != t->kx_ctx)
1608 if (NULL != t->kx_ctx->finish_task)
1610 LOG (GNUNET_ERROR_TYPE_INFO, " resetting exisiting finish task\n");
1611 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
1612 t->kx_ctx->finish_task = NULL;
1617 t->kx_ctx = GNUNET_new (struct CadetTunnelKXCtx);
1618 t->kx_ctx->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1622 if (CADET_TUNNEL_KEY_OK == t->estate)
1624 LOG (GNUNET_ERROR_TYPE_INFO, " backing up keys\n");
1625 t->kx_ctx->d_key_old = t->d_key;
1626 t->kx_ctx->e_key_old = t->e_key;
1629 LOG (GNUNET_ERROR_TYPE_INFO, " old keys not valid, not saving\n");
1630 t->kx_ctx->rekey_start_time = GNUNET_TIME_absolute_get ();
1631 return create_otr_keys (t);
1636 * @brief Finish the Key eXchange and destroy the old keys.
1638 * @param cls Closure (Tunnel for which to finish the KX).
1639 * @param tc Task context.
1642 finish_kx (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1644 struct CadetTunnel *t = cls;
1646 LOG (GNUNET_ERROR_TYPE_INFO, "finish KX for %s\n", GCT_2s (t));
1648 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1650 LOG (GNUNET_ERROR_TYPE_INFO, " shutdown\n");
1654 GNUNET_free (t->kx_ctx);
1660 * Destroy a Key eXchange context for the tunnel. This function only schedules
1661 * the destruction, the freeing of the memory (and clearing of old key material)
1662 * happens after a delay!
1664 * @param t Tunnel whose KX ctx to destroy.
1667 destroy_kx_ctx (struct CadetTunnel *t)
1669 struct GNUNET_TIME_Relative delay;
1671 if (NULL == t->kx_ctx || NULL != t->kx_ctx->finish_task)
1674 if (is_key_null (&t->kx_ctx->e_key_old))
1676 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_now (finish_kx, t);
1680 delay = GNUNET_TIME_relative_divide (rekey_period, 4);
1681 delay = GNUNET_TIME_relative_min (delay, GNUNET_TIME_UNIT_MINUTES);
1683 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_delayed (delay, finish_kx, t);
1689 * Pick a connection on which send the next data message.
1691 * @param t Tunnel on which to send the message.
1693 * @return The connection on which to send the next message.
1695 static struct CadetConnection *
1696 tunnel_get_connection (struct CadetTunnel *t)
1698 struct CadetTConnection *iter;
1699 struct CadetConnection *best;
1701 unsigned int lowest_q;
1703 LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GCT_2s (t));
1705 lowest_q = UINT_MAX;
1706 for (iter = t->connection_head; NULL != iter; iter = iter->next)
1708 LOG (GNUNET_ERROR_TYPE_DEBUG, " connection %s: %u\n",
1709 GCC_2s (iter->c), GCC_get_state (iter->c));
1710 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
1712 qn = GCC_get_qn (iter->c, GCC_is_origin (iter->c, GNUNET_YES));
1713 LOG (GNUNET_ERROR_TYPE_DEBUG, " q_n %u, \n", qn);
1721 LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GCC_2s (best));
1727 * Callback called when a queued message is sent.
1729 * Calculates the average time and connection packet tracking.
1731 * @param cls Closure (TunnelQueue handle).
1732 * @param c Connection this message was on.
1733 * @param q Connection queue handle (unused).
1734 * @param type Type of message sent.
1735 * @param fwd Was this a FWD going message?
1736 * @param size Size of the message.
1739 tun_message_sent (void *cls,
1740 struct CadetConnection *c,
1741 struct CadetConnectionQueue *q,
1742 uint16_t type, int fwd, size_t size)
1744 struct CadetTunnelQueue *qt = cls;
1745 struct CadetTunnel *t;
1747 LOG (GNUNET_ERROR_TYPE_DEBUG, "tun_message_sent\n");
1749 GNUNET_assert (NULL != qt->cont);
1750 t = NULL == c ? NULL : GCC_get_tunnel (c);
1751 qt->cont (qt->cont_cls, t, qt, type, size);
1757 count_queued_data (const struct CadetTunnel *t)
1759 struct CadetTunnelDelayed *iter;
1762 for (count = 0, iter = t->tq_head; iter != NULL; iter = iter->next)
1769 * Delete a queued message: either was sent or the channel was destroyed
1770 * before the tunnel's key exchange had a chance to finish.
1772 * @param tqd Delayed queue handle.
1775 unqueue_data (struct CadetTunnelDelayed *tqd)
1777 GNUNET_CONTAINER_DLL_remove (tqd->t->tq_head, tqd->t->tq_tail, tqd);
1783 * Cache a message to be sent once tunnel is online.
1785 * @param t Tunnel to hold the message.
1786 * @param msg Message itself (copy will be made).
1788 static struct CadetTunnelDelayed *
1789 queue_data (struct CadetTunnel *t, const struct GNUNET_MessageHeader *msg)
1791 struct CadetTunnelDelayed *tqd;
1792 uint16_t size = ntohs (msg->size);
1794 LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GCT_2s (t));
1796 if (GNUNET_YES == is_ready (t))
1802 tqd = GNUNET_malloc (sizeof (struct CadetTunnelDelayed) + size);
1805 memcpy (&tqd[1], msg, size);
1806 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
1812 * Sends an already built message on a tunnel, encrypting it and
1813 * choosing the best connection.
1815 * @param message Message to send. Function modifies it.
1816 * @param t Tunnel on which this message is transmitted.
1817 * @param c Connection to use (autoselect if NULL).
1818 * @param force Force the tunnel to take the message (buffer overfill).
1819 * @param cont Continuation to call once message is really sent.
1820 * @param cont_cls Closure for @c cont.
1821 * @param existing_q In case this a transmission of previously queued data,
1822 * this should be TunnelQueue given to the client.
1825 * @return Handle to cancel message.
1826 * NULL if @c cont is NULL or an error happens and message is dropped.
1828 static struct CadetTunnelQueue *
1829 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1830 struct CadetTunnel *t, struct CadetConnection *c,
1831 int force, GCT_sent cont, void *cont_cls,
1832 struct CadetTunnelQueue *existing_q)
1834 struct GNUNET_MessageHeader *msg;
1835 struct GNUNET_CADET_Encrypted *otr_msg;
1836 struct GNUNET_CADET_AX *ax_msg;
1837 struct CadetTunnelQueue *tq;
1838 size_t size = ntohs (message->size);
1839 const uint16_t max_overhead = sizeof (struct GNUNET_CADET_Encrypted)
1840 + sizeof (struct GNUNET_CADET_AX);
1841 char cbuf[max_overhead + size];
1848 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GCT_2s (t));
1850 if (GNUNET_NO == is_ready (t))
1852 struct CadetTunnelDelayed *tqd;
1853 /* A non null existing_q indicates sending of queued data.
1854 * Should only happen after tunnel becomes ready.
1856 GNUNET_assert (NULL == existing_q);
1857 tqd = queue_data (t, message);
1860 tq = GNUNET_new (struct CadetTunnelQueue);
1864 tq->cont_cls = cont_cls;
1868 GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1870 if (CADET_Axolotl == t->enc_type)
1872 ax_msg = (struct GNUNET_CADET_AX *) cbuf;
1873 msg = &ax_msg->header;
1874 msg->size = htons (sizeof (struct GNUNET_CADET_AX) + size);
1875 msg->type = htons (GNUNET_MESSAGE_TYPE_CADET_AX);
1876 esize = t_ax_encrypt (t, &ax_msg[1], message, size);
1877 ax_msg->Ns = htonl (t->ax->Ns++);
1878 ax_msg->PNs = htonl (t->ax->PNs);
1879 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &ax_msg->DHRs);
1880 t_h_encrypt (t, ax_msg);
1881 t_hmac (&ax_msg->Ns, AX_HEADER_SIZE + esize, 0, &t->ax->HKs, &ax_msg->hmac);
1885 otr_msg = (struct GNUNET_CADET_Encrypted *) cbuf;
1886 msg = &otr_msg->header;
1887 iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1889 esize = t_encrypt (t, &otr_msg[1], message, size, iv, GNUNET_NO);
1890 t_hmac (&otr_msg[1], size, iv, select_key (t), &otr_msg->hmac);
1891 msg->size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
1892 msg->type = htons (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
1894 GNUNET_assert (esize == size);
1897 c = tunnel_get_connection (t);
1900 /* Why is tunnel 'ready'? Should have been queued! */
1901 if (NULL != t->destroy_task)
1904 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1906 return NULL; /* Drop... */
1910 type = ntohs (message->type);
1913 case GNUNET_MESSAGE_TYPE_CADET_DATA:
1914 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1915 if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
1916 mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
1918 mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
1920 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1921 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1922 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1923 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1924 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1928 LOG (GNUNET_ERROR_TYPE_ERROR, "type %s not valid\n", GC_m2s (type));
1930 LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
1932 fwd = GCC_is_origin (c, GNUNET_YES);
1936 GNUNET_break (NULL == GCC_send_prebuilt_message (msg, type,
1937 mid, c, fwd, force, NULL, NULL));
1940 if (NULL == existing_q)
1942 tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
1949 tq->cq = GCC_send_prebuilt_message (msg, type, mid, c, fwd, force,
1950 &tun_message_sent, tq);
1951 GNUNET_assert (NULL != tq->cq);
1953 tq->cont_cls = cont_cls;
1960 * Send all cached messages that we can, tunnel is online.
1962 * @param t Tunnel that holds the messages. Cannot be loopback.
1965 send_queued_data (struct CadetTunnel *t)
1967 struct CadetTunnelDelayed *tqd;
1968 struct CadetTunnelDelayed *next;
1971 LOG (GNUNET_ERROR_TYPE_INFO, "Send queued data, tunnel %s\n", GCT_2s (t));
1973 if (GCT_is_loopback (t))
1979 if (GNUNET_NO == is_ready (t))
1981 LOG (GNUNET_ERROR_TYPE_DEBUG, " not ready yet: %s/%s\n",
1982 estate2s (t->estate), cstate2s (t->cstate));
1986 room = GCT_get_connections_buffer (t);
1987 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
1988 LOG (GNUNET_ERROR_TYPE_DEBUG, " tq head: %p\n", t->tq_head);
1989 for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
1991 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
1994 send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
1995 tqd->t, NULL, GNUNET_YES,
1996 NULL != tqd->tq ? tqd->tq->cont : NULL,
1997 NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
2001 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
2006 * Callback called when a queued message is sent.
2008 * @param cls Closure.
2009 * @param c Connection this message was on.
2010 * @param type Type of message sent.
2011 * @param fwd Was this a FWD going message?
2012 * @param size Size of the message.
2015 ephm_sent (void *cls,
2016 struct CadetConnection *c,
2017 struct CadetConnectionQueue *q,
2018 uint16_t type, int fwd, size_t size)
2020 struct CadetTunnel *t = cls;
2021 LOG (GNUNET_ERROR_TYPE_DEBUG, "ephemeral sent %s\n", GC_m2s (type));
2026 * Callback called when a queued message is sent.
2028 * @param cls Closure.
2029 * @param c Connection this message was on.
2030 * @param type Type of message sent.
2031 * @param fwd Was this a FWD going message?
2032 * @param size Size of the message.
2035 pong_sent (void *cls,
2036 struct CadetConnection *c,
2037 struct CadetConnectionQueue *q,
2038 uint16_t type, int fwd, size_t size)
2040 struct CadetTunnel *t = cls;
2041 LOG (GNUNET_ERROR_TYPE_DEBUG, "pong_sent %s\n", GC_m2s (type));
2047 * Sends key exchange message on a tunnel, choosing the best connection.
2048 * Should not be called on loopback tunnels.
2050 * @param t Tunnel on which this message is transmitted.
2051 * @param message Message to send. Function modifies it.
2053 * @return Handle to the message in the connection queue.
2055 static struct CadetConnectionQueue *
2056 send_kx (struct CadetTunnel *t,
2057 const struct GNUNET_MessageHeader *message)
2059 struct CadetConnection *c;
2060 struct GNUNET_CADET_KX *msg;
2061 size_t size = ntohs (message->size);
2062 char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
2067 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
2069 /* Avoid loopback. */
2070 if (GCT_is_loopback (t))
2075 type = ntohs (message->type);
2077 /* Even if tunnel is "being destroyed", send anyway.
2078 * Could be a response to a rekey initiated by remote peer,
2079 * who is trying to create a new channel!
2082 /* Must have a connection, or be looking for one. */
2083 if (NULL == t->connection_head)
2085 LOG (GNUNET_ERROR_TYPE_DEBUG, "%s with no connection\n", GC_m2s (type));
2086 if (CADET_TUNNEL_SEARCHING != t->cstate)
2089 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
2090 GCP_debug (t->peer, GNUNET_ERROR_TYPE_ERROR);
2095 msg = (struct GNUNET_CADET_KX *) cbuf;
2096 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
2097 msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
2098 c = tunnel_get_connection (t);
2101 if (NULL == t->destroy_task && CADET_TUNNEL_READY == t->cstate)
2104 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
2110 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
2111 case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
2112 GNUNET_assert (NULL == t->ephm_h);
2115 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
2116 GNUNET_assert (NULL == t->pong_h);
2121 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n", GC_m2s (type));
2124 memcpy (&msg[1], message, size);
2126 fwd = GCC_is_origin (c, GNUNET_YES);
2128 return GCC_send_prebuilt_message (&msg->header, type, 0, c,
2135 * Send the ephemeral key on a tunnel.
2137 * @param t Tunnel on which to send the key.
2140 send_ephemeral (struct CadetTunnel *t)
2142 LOG (GNUNET_ERROR_TYPE_INFO, "===> EPHM for %s\n", GCT_2s (t));
2143 if (NULL != t->ephm_h)
2145 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
2149 otr_kx_msg.sender_status = htonl (t->estate);
2150 otr_kx_msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
2151 otr_kx_msg.nonce = t->kx_ctx->challenge;
2152 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce c %u\n", otr_kx_msg.nonce);
2153 t_encrypt (t, &otr_kx_msg.nonce, &otr_kx_msg.nonce,
2154 ping_encryption_size(), otr_kx_msg.iv, GNUNET_YES);
2155 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce e %u\n", otr_kx_msg.nonce);
2156 t->ephm_h = send_kx (t, &otr_kx_msg.header);
2161 * Send a pong message on a tunnel.
2163 * @param t Tunnel on which to send the pong.
2164 * @param challenge Value sent in the ping that we have to send back.
2167 send_pong (struct CadetTunnel *t, uint32_t challenge)
2169 struct GNUNET_CADET_KX_Pong msg;
2171 LOG (GNUNET_ERROR_TYPE_INFO, "===> PONG for %s\n", GCT_2s (t));
2172 if (NULL != t->pong_h)
2174 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
2177 msg.header.size = htons (sizeof (msg));
2178 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
2179 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
2180 msg.nonce = challenge;
2181 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
2182 t_encrypt (t, &msg.nonce, &msg.nonce,
2183 sizeof (msg.nonce), msg.iv, GNUNET_YES);
2184 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
2186 t->pong_h = send_kx (t, &msg.header);
2191 * Initiate a rekey with the remote peer.
2193 * @param cls Closure (tunnel).
2194 * @param tc TaskContext.
2197 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2199 struct CadetTunnel *t = cls;
2201 t->rekey_task = NULL;
2203 LOG (GNUNET_ERROR_TYPE_INFO, "Re-key Tunnel %s\n", GCT_2s (t));
2204 if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2207 GNUNET_assert (NULL != t->kx_ctx);
2208 struct GNUNET_TIME_Relative duration;
2210 duration = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
2211 LOG (GNUNET_ERROR_TYPE_DEBUG, " kx started %s ago\n",
2212 GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
2214 // FIXME make duration of old keys configurable
2215 if (duration.rel_value_us >= GNUNET_TIME_UNIT_MINUTES.rel_value_us)
2217 LOG (GNUNET_ERROR_TYPE_DEBUG, " deleting old keys\n");
2218 memset (&t->kx_ctx->d_key_old, 0, sizeof (t->kx_ctx->d_key_old));
2219 memset (&t->kx_ctx->e_key_old, 0, sizeof (t->kx_ctx->e_key_old));
2226 case CADET_TUNNEL_KEY_UNINITIALIZED:
2227 GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
2230 case CADET_TUNNEL_KEY_SENT:
2233 case CADET_TUNNEL_KEY_OK:
2235 * - state should have changed during rekey_iterator
2236 * - task should have been canceled at pong_handle
2239 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2242 case CADET_TUNNEL_KEY_PING:
2243 case CADET_TUNNEL_KEY_REKEY:
2247 LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
2250 // FIXME exponential backoff
2251 struct GNUNET_TIME_Relative delay;
2253 delay = GNUNET_TIME_relative_divide (rekey_period, 16);
2254 delay = GNUNET_TIME_relative_min (delay, REKEY_WAIT);
2255 LOG (GNUNET_ERROR_TYPE_DEBUG, " next call in %s\n",
2256 GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
2257 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
2262 * Our ephemeral key has changed, create new session key on all tunnels.
2264 * Each tunnel will start the Key Exchange with a random delay between
2265 * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
2266 * per second, on average.
2268 * @param cls Closure (size of the hashmap).
2269 * @param key Current public key.
2270 * @param value Value in the hash map (tunnel).
2272 * @return #GNUNET_YES, so we should continue to iterate,
2275 rekey_iterator (void *cls,
2276 const struct GNUNET_PeerIdentity *key,
2279 struct CadetTunnel *t = value;
2280 struct GNUNET_TIME_Relative delay;
2281 long n = (long) cls;
2284 if (NULL != t->rekey_task)
2287 if (GNUNET_YES == GCT_is_loopback (t))
2290 if (CADET_OTR != t->enc_type)
2293 r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
2294 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
2295 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
2296 if (GNUNET_OK == create_kx_ctx (t))
2297 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2309 * Create a new ephemeral key and key message, schedule next rekeying.
2311 * @param cls Closure (unused).
2312 * @param tc TaskContext.
2315 global_otr_rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2317 struct GNUNET_TIME_Absolute time;
2322 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2325 GNUNET_free_non_null (otr_ephemeral_key);
2326 otr_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
2328 time = GNUNET_TIME_absolute_get ();
2329 otr_kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
2330 time = GNUNET_TIME_absolute_add (time, rekey_period);
2331 time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
2332 otr_kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
2333 GNUNET_CRYPTO_ecdhe_key_get_public (otr_ephemeral_key, &otr_kx_msg.ephemeral_key);
2334 LOG (GNUNET_ERROR_TYPE_INFO, "GLOBAL OTR RE-KEY, NEW EPHM: %s\n",
2335 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
2337 GNUNET_assert (GNUNET_OK ==
2338 GNUNET_CRYPTO_eddsa_sign (id_key,
2339 &otr_kx_msg.purpose,
2340 &otr_kx_msg.signature));
2342 n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
2343 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
2345 rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period,
2346 &global_otr_rekey, NULL);
2351 * Called only on shutdown, destroy every tunnel.
2353 * @param cls Closure (unused).
2354 * @param key Current public key.
2355 * @param value Value in the hash map (tunnel).
2357 * @return #GNUNET_YES, so we should continue to iterate,
2360 destroy_iterator (void *cls,
2361 const struct GNUNET_PeerIdentity *key,
2364 struct CadetTunnel *t = value;
2366 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
2373 * Notify remote peer that we don't know a channel he is talking about,
2374 * probably CHANNEL_DESTROY was missed.
2376 * @param t Tunnel on which to notify.
2377 * @param gid ID of the channel.
2380 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
2382 struct GNUNET_CADET_ChannelManage msg;
2384 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2385 msg.header.size = htons (sizeof (msg));
2386 msg.chid = htonl (gid);
2388 LOG (GNUNET_ERROR_TYPE_DEBUG,
2389 "WARNING destroying unknown channel %u on tunnel %s\n",
2391 send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
2396 * Demultiplex data per channel and call appropriate channel handler.
2398 * @param t Tunnel on which the data came.
2399 * @param msg Data message.
2400 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2401 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2402 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2403 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2406 handle_data (struct CadetTunnel *t,
2407 const struct GNUNET_CADET_Data *msg,
2410 struct CadetChannel *ch;
2414 size = ntohs (msg->header.size);
2416 sizeof (struct GNUNET_CADET_Data) +
2417 sizeof (struct GNUNET_MessageHeader))
2422 LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
2423 GC_m2s (ntohs (msg[1].header.type)));
2426 ch = GCT_get_channel (t, ntohl (msg->chid));
2429 GNUNET_STATISTICS_update (stats, "# data on unknown channel",
2431 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
2433 send_channel_destroy (t, ntohl (msg->chid));
2437 GCCH_handle_data (ch, msg, fwd);
2442 * Demultiplex data ACKs per channel and update appropriate channel buffer info.
2444 * @param t Tunnel on which the DATA ACK came.
2445 * @param msg DATA ACK message.
2446 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2447 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2448 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2449 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2452 handle_data_ack (struct CadetTunnel *t,
2453 const struct GNUNET_CADET_DataACK *msg,
2456 struct CadetChannel *ch;
2460 size = ntohs (msg->header.size);
2461 if (size != sizeof (struct GNUNET_CADET_DataACK))
2468 ch = GCT_get_channel (t, ntohl (msg->chid));
2471 GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
2473 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2478 GCCH_handle_data_ack (ch, msg, fwd);
2483 * Handle channel create.
2485 * @param t Tunnel on which the data came.
2486 * @param msg Data message.
2489 handle_ch_create (struct CadetTunnel *t,
2490 const struct GNUNET_CADET_ChannelCreate *msg)
2492 struct CadetChannel *ch;
2496 size = ntohs (msg->header.size);
2497 if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
2504 ch = GCT_get_channel (t, ntohl (msg->chid));
2505 if (NULL != ch && ! GCT_is_loopback (t))
2507 /* Probably a retransmission, safe to ignore */
2508 LOG (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
2510 ch = GCCH_handle_create (t, msg);
2512 GCT_add_channel (t, ch);
2518 * Handle channel NACK: check correctness and call channel handler for NACKs.
2520 * @param t Tunnel on which the NACK came.
2521 * @param msg NACK message.
2524 handle_ch_nack (struct CadetTunnel *t,
2525 const struct GNUNET_CADET_ChannelManage *msg)
2527 struct CadetChannel *ch;
2531 size = ntohs (msg->header.size);
2532 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2539 ch = GCT_get_channel (t, ntohl (msg->chid));
2542 GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
2544 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2549 GCCH_handle_nack (ch);
2554 * Handle a CHANNEL ACK (SYNACK/ACK).
2556 * @param t Tunnel on which the CHANNEL ACK came.
2557 * @param msg CHANNEL ACK message.
2558 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2559 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2560 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2561 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2564 handle_ch_ack (struct CadetTunnel *t,
2565 const struct GNUNET_CADET_ChannelManage *msg,
2568 struct CadetChannel *ch;
2572 size = ntohs (msg->header.size);
2573 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2580 ch = GCT_get_channel (t, ntohl (msg->chid));
2583 GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
2585 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2590 GCCH_handle_ack (ch, msg, fwd);
2595 * Handle a channel destruction message.
2597 * @param t Tunnel on which the message came.
2598 * @param msg Channel destroy message.
2599 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2600 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2601 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2602 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2605 handle_ch_destroy (struct CadetTunnel *t,
2606 const struct GNUNET_CADET_ChannelManage *msg,
2609 struct CadetChannel *ch;
2613 size = ntohs (msg->header.size);
2614 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2621 ch = GCT_get_channel (t, ntohl (msg->chid));
2624 /* Probably a retransmission, safe to ignore */
2628 GCCH_handle_destroy (ch, msg, fwd);
2633 * Create a new Axolotl ephemeral (ratchet) key.
2638 new_ephemeral (struct CadetTunnel *t)
2640 GNUNET_free_non_null (t->ax->DHRs);
2641 t->ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create();
2646 * Free Axolotl data.
2651 destroy_ax (struct CadetTunnel *t)
2656 GNUNET_free_non_null (t->ax->DHRs);
2657 GNUNET_free_non_null (t->ax->kx_0);
2659 GNUNET_free (t->ax);
2666 * The peer's ephemeral key has changed: update the symmetrical keys.
2668 * @param t Tunnel this message came on.
2669 * @param msg Key eXchange message.
2672 handle_ephemeral (struct CadetTunnel *t,
2673 const struct GNUNET_CADET_KX_Ephemeral *msg)
2675 LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
2677 if (GNUNET_OK != check_ephemeral (t, msg))
2679 GNUNET_break_op (0);
2683 /* If we get a proper OTR-style ephemeral, fallback to old crypto. */
2687 t->enc_type = CADET_OTR;
2688 if (NULL != t->rekey_task)
2689 GNUNET_SCHEDULER_cancel (t->rekey_task);
2690 if (GNUNET_OK != create_kx_ctx (t))
2696 rekey_tunnel (t, NULL);
2700 * If the key is different from what we know, derive the new E/D keys.
2701 * Else destroy the rekey ctx (duplicate EPHM after successful KX).
2703 if (0 != memcmp (&t->peers_ephemeral_key, &msg->ephemeral_key,
2704 sizeof (msg->ephemeral_key)))
2706 #if DUMP_KEYS_TO_STDERR
2707 LOG (GNUNET_ERROR_TYPE_INFO, "OLD: %s\n",
2708 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
2709 LOG (GNUNET_ERROR_TYPE_INFO, "NEW: %s\n",
2710 GNUNET_h2s ((struct GNUNET_HashCode *) &msg->ephemeral_key));
2712 t->peers_ephemeral_key = msg->ephemeral_key;
2714 if (GNUNET_OK != create_kx_ctx (t))
2721 if (CADET_TUNNEL_KEY_OK == t->estate)
2723 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2725 if (NULL != t->rekey_task)
2726 GNUNET_SCHEDULER_cancel (t->rekey_task);
2727 t->rekey_task = GNUNET_SCHEDULER_add_now (rekey_tunnel, t);
2729 if (CADET_TUNNEL_KEY_SENT == t->estate)
2731 LOG (GNUNET_ERROR_TYPE_DEBUG, " our key was sent, sending challenge\n");
2733 GCT_change_estate (t, CADET_TUNNEL_KEY_PING);
2736 if (CADET_TUNNEL_KEY_UNINITIALIZED != ntohl(msg->sender_status))
2740 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce e %u\n", msg->nonce);
2741 t_decrypt (t, &nonce, &msg->nonce, ping_encryption_size (), msg->iv);
2742 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce c %u\n", nonce);
2743 send_pong (t, nonce);
2749 * Peer has answer to our challenge.
2750 * If answer is successful, consider the key exchange finished and clean
2751 * up all related state.
2753 * @param t Tunnel this message came on.
2754 * @param msg Key eXchange Pong message.
2757 handle_pong (struct CadetTunnel *t, const struct GNUNET_CADET_KX_Pong *msg)
2761 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
2762 if (NULL == t->rekey_task)
2764 GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
2767 if (NULL == t->kx_ctx)
2769 GNUNET_STATISTICS_update (stats, "# stray PONG messages", 1, GNUNET_NO);
2773 t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
2774 if (challenge != t->kx_ctx->challenge)
2776 LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
2777 LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
2778 challenge, msg->nonce, t->kx_ctx->challenge);
2782 GNUNET_SCHEDULER_cancel (t->rekey_task);
2783 t->rekey_task = NULL;
2785 /* Don't free the old keys right away, but after a delay.
2786 * Rationale: the KX could have happened over a very fast connection,
2787 * with payload traffic still signed with the old key stuck in a slower
2789 * Don't keep the keys longer than 1/4 the rekey period, and no longer than
2793 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2798 * Handle Axolotl handshake.
2800 * @param t Tunnel this message came on.
2801 * @param msg Key eXchange Pong message.
2804 handle_kx_ax (struct CadetTunnel *t, const struct GNUNET_CADET_AX_KX *msg)
2806 struct CadetTunnelAxolotl *ax;
2807 struct GNUNET_HashCode key_material[3];
2808 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
2809 const struct GNUNET_CRYPTO_EcdhePublicKey *pub;
2810 const struct GNUNET_CRYPTO_EcdhePrivateKey *priv;
2811 const char salt[] = "CADET Axolotl salt";
2812 const struct GNUNET_PeerIdentity *pid;
2815 LOG (GNUNET_ERROR_TYPE_INFO, "<=== AX_KX on %s\n", GCT_2s (t));
2819 /* Something is wrong if ax is NULL. Whose fault it is? */
2820 GNUNET_break_op (CADET_OTR == t->enc_type);
2821 GNUNET_break (CADET_Axolotl == t->enc_type);
2825 if (GNUNET_OK != GCP_check_key (t->peer, &msg->permanent_key,
2826 &msg->purpose, &msg->signature))
2828 GNUNET_break_op (0);
2832 pid = GCT_get_destination (t);
2833 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2834 am_I_alice = GNUNET_YES;
2835 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2836 am_I_alice = GNUNET_NO;
2839 GNUNET_break_op (0);
2843 LOG (GNUNET_ERROR_TYPE_INFO, " is Alice? %s\n", am_I_alice ? "YES" : "NO");
2846 ax->DHRr = msg->ratchet_key;
2847 ax->DHIr = msg->permanent_key;
2850 if (GNUNET_YES == am_I_alice)
2852 priv = ax_key; /* A */
2853 pub = &msg->ephemeral_key; /* B0 */
2857 priv = ax->kx_0; /* B0 */
2858 pub = &ax->DHIr; /* A */
2860 GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[0]);
2863 if (GNUNET_YES == am_I_alice)
2865 priv = ax->kx_0; /* A0 */
2866 pub = &ax->DHIr; /* B */
2870 priv = ax_key; /* B */
2871 pub = &msg->ephemeral_key; /* A0 */
2873 GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[1]);
2876 priv = ax->kx_0; /* A0 or B0 */
2877 pub = &msg->ephemeral_key; /* B0 or A0 */
2878 GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[2]);
2880 #if DUMP_KEYS_TO_STDERR
2883 for (i = 0; i < 3; i++)
2884 LOG (GNUNET_ERROR_TYPE_INFO, "km[%u]: %s\n",
2885 i, GNUNET_h2s (&key_material[i]));
2890 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
2891 salt, sizeof (salt),
2892 &key_material, sizeof (key_material), NULL);
2895 if (GNUNET_YES == am_I_alice)
2901 ax->ratchet_flag = GNUNET_YES;
2909 ax->ratchet_flag = GNUNET_NO;
2911 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2916 * Demultiplex by message type and call appropriate handler for a message
2917 * towards a channel of a local tunnel.
2919 * @param t Tunnel this message came on.
2920 * @param msgh Message header.
2921 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2922 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2923 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2924 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2927 handle_decrypted (struct CadetTunnel *t,
2928 const struct GNUNET_MessageHeader *msgh,
2933 type = ntohs (msgh->type);
2934 LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
2938 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
2939 /* Do nothing, connection aleady got updated. */
2940 GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
2943 case GNUNET_MESSAGE_TYPE_CADET_DATA:
2944 /* Don't send hop ACK, wait for client to ACK */
2945 handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
2948 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
2949 handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
2952 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
2953 handle_ch_create (t, (struct GNUNET_CADET_ChannelCreate *) msgh);
2956 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
2957 handle_ch_nack (t, (struct GNUNET_CADET_ChannelManage *) msgh);
2960 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
2961 handle_ch_ack (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
2964 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
2965 handle_ch_destroy (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
2969 GNUNET_break_op (0);
2970 LOG (GNUNET_ERROR_TYPE_WARNING,
2971 "end-to-end message not known (%u)\n",
2972 ntohs (msgh->type));
2973 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
2977 /******************************************************************************/
2978 /******************************** API ***********************************/
2979 /******************************************************************************/
2981 * Decrypt old format and demultiplex by message type. Call appropriate handler
2982 * for a message towards a channel of a local tunnel.
2984 * @param t Tunnel this message came on.
2985 * @param msg Message header.
2988 GCT_handle_encrypted (struct CadetTunnel *t,
2989 const struct GNUNET_MessageHeader *msg)
2991 uint16_t size = ntohs (msg->size);
2993 size_t payload_size;
2996 struct GNUNET_MessageHeader *msgh;
2999 type = ntohs (msg->type);
3000 if (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED == type)
3002 const struct GNUNET_CADET_Encrypted *emsg;
3004 emsg = (struct GNUNET_CADET_Encrypted *) msg;
3005 payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
3006 decrypted_size = t_decrypt_and_validate (t, cbuf, &emsg[1], payload_size,
3007 emsg->iv, &emsg->hmac);
3009 else if (GNUNET_MESSAGE_TYPE_CADET_AX == type)
3011 const struct GNUNET_CADET_AX *emsg;
3013 emsg = (struct GNUNET_CADET_AX *) msg;
3014 decrypted_size = t_ax_decrypt_and_validate (t, cbuf, emsg, size);
3017 if (-1 == decrypted_size)
3019 GNUNET_break_op (0);
3024 while (off < decrypted_size)
3028 msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
3029 msize = ntohs (msgh->size);
3030 if (msize < sizeof (struct GNUNET_MessageHeader))
3032 GNUNET_break_op (0);
3035 handle_decrypted (t, msgh, GNUNET_SYSERR);
3042 * Demultiplex an encapsulated KX message by message type.
3044 * @param t Tunnel on which the message came.
3045 * @param message Payload of KX message.
3048 GCT_handle_kx (struct CadetTunnel *t,
3049 const struct GNUNET_MessageHeader *message)
3053 type = ntohs (message->type);
3054 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received: %s\n", GC_m2s (type));
3057 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
3058 handle_ephemeral (t, (const struct GNUNET_CADET_KX_Ephemeral *) message);
3061 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
3062 handle_pong (t, (const struct GNUNET_CADET_KX_Pong *) message);
3065 case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
3066 handle_kx_ax (t, (const struct GNUNET_CADET_AX_KX *) message);
3070 GNUNET_break_op (0);
3071 LOG (GNUNET_ERROR_TYPE_WARNING, "kx message %s unknown\n", GC_m2s (type));
3076 * Initialize the tunnel subsystem.
3078 * @param c Configuration handle.
3079 * @param key ECC private key, to derive all other keys and do crypto.
3082 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
3083 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
3085 int expected_overhead;
3087 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
3089 expected_overhead = 0;
3090 expected_overhead += sizeof (struct GNUNET_CADET_Encrypted);
3091 expected_overhead += sizeof (struct GNUNET_CADET_Data);
3092 expected_overhead += sizeof (struct GNUNET_CADET_ACK);
3093 GNUNET_assert (GNUNET_CONSTANTS_CADET_P2P_OVERHEAD == expected_overhead);
3096 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
3099 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
3100 "CADET", "DEFAULT_TTL", "USING DEFAULT");
3104 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
3107 rekey_period = GNUNET_TIME_UNIT_DAYS;
3112 otr_kx_msg.header.size = htons (sizeof (otr_kx_msg));
3113 otr_kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
3114 otr_kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
3115 otr_kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
3116 otr_kx_msg.origin_identity = my_full_id;
3117 rekey_task = GNUNET_SCHEDULER_add_now (&global_otr_rekey, NULL);
3119 ax_key = GNUNET_CRYPTO_ecdhe_key_create ();
3120 GNUNET_CRYPTO_ecdhe_key_get_public (ax_key, &ax_identity.permanent_key);
3121 ax_identity.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_AXKX);
3122 ax_identity.purpose.size = htonl (ax_purpose_size ());
3123 GNUNET_assert (GNUNET_OK ==
3124 GNUNET_CRYPTO_eddsa_sign (id_key,
3125 &ax_identity.purpose,
3126 &ax_identity.signature));
3128 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
3133 * Shut down the tunnel subsystem.
3138 if (NULL != rekey_task)
3140 GNUNET_SCHEDULER_cancel (rekey_task);
3143 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
3144 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
3145 GNUNET_free (ax_key);
3152 * @param destination Peer this tunnel is towards.
3154 struct CadetTunnel *
3155 GCT_new (struct CadetPeer *destination)
3157 struct CadetTunnel *t;
3159 t = GNUNET_new (struct CadetTunnel);
3161 t->peer = destination;
3164 GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
3165 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3171 t->ax = GNUNET_new (struct CadetTunnelAxolotl);
3173 t->ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
3179 * Change the tunnel's connection state.
3181 * @param t Tunnel whose connection state to change.
3182 * @param cstate New connection state.
3185 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
3189 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
3190 GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
3191 if (myid != GCP_get_short_id (t->peer) &&
3192 CADET_TUNNEL_READY != t->cstate &&
3193 CADET_TUNNEL_READY == cstate)
3196 if (CADET_TUNNEL_KEY_OK == t->estate)
3198 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered send queued data\n");
3199 send_queued_data (t);
3201 else if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
3203 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered kx\n");
3208 LOG (GNUNET_ERROR_TYPE_DEBUG, "estate %s\n", estate2s (t->estate));
3213 if (CADET_TUNNEL_READY == cstate
3214 && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
3216 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered stop dht\n");
3217 GCP_stop_search (t->peer);
3223 * Change the tunnel encryption state.
3225 * @param t Tunnel whose encryption state to change, or NULL.
3226 * @param state New encryption state.
3229 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
3231 enum CadetTunnelEState old;
3238 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate was %s\n",
3239 GCP_2s (t->peer), estate2s (old));
3240 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate is now %s\n",
3241 GCP_2s (t->peer), estate2s (t->estate));
3243 /* Send queued data if enc state changes to OK */
3244 if (myid != GCP_get_short_id (t->peer) &&
3245 CADET_TUNNEL_KEY_OK != old && CADET_TUNNEL_KEY_OK == t->estate)
3247 send_queued_data (t);
3253 * @brief Check if tunnel has too many connections, and remove one if necessary.
3255 * Currently this means the newest connection, unless it is a direct one.
3256 * Implemented as a task to avoid freeing a connection that is in the middle
3257 * of being created/processed.
3259 * @param cls Closure (Tunnel to check).
3260 * @param tc Task context.
3263 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3265 struct CadetTunnel *t = cls;
3267 t->trim_connections_task = NULL;
3269 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3272 if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
3274 struct CadetTConnection *iter;
3275 struct CadetTConnection *c;
3277 for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
3279 if ((iter->created.abs_value_us > c->created.abs_value_us)
3280 && GNUNET_NO == GCC_is_direct (iter->c))
3287 LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
3289 LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
3302 * Add a connection to a tunnel.
3305 * @param c Connection.
3308 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
3310 struct CadetTConnection *aux;
3312 GNUNET_assert (NULL != c);
3314 LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
3315 LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
3316 for (aux = t->connection_head; aux != NULL; aux = aux->next)
3320 aux = GNUNET_new (struct CadetTConnection);
3322 aux->created = GNUNET_TIME_absolute_get ();
3324 GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
3326 if (CADET_TUNNEL_SEARCHING == t->cstate)
3327 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3329 if (NULL != t->trim_connections_task)
3330 t->trim_connections_task = GNUNET_SCHEDULER_add_now (&trim_connections, t);
3335 * Remove a connection from a tunnel.
3338 * @param c Connection.
3341 GCT_remove_connection (struct CadetTunnel *t,
3342 struct CadetConnection *c)
3344 struct CadetTConnection *aux;
3345 struct CadetTConnection *next;
3348 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
3349 GCC_2s (c), GCT_2s (t));
3350 for (aux = t->connection_head; aux != NULL; aux = next)
3355 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
3360 conns = GCT_count_connections (t);
3362 && NULL == t->destroy_task
3363 && CADET_TUNNEL_SHUTDOWN != t->cstate
3364 && GNUNET_NO == shutting_down)
3366 if (0 == GCT_count_any_connections (t))
3367 GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
3369 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3372 /* Start new connections if needed */
3373 if (CONNECTIONS_PER_TUNNEL > conns
3374 && NULL == t->destroy_task
3375 && CADET_TUNNEL_SHUTDOWN != t->cstate
3376 && GNUNET_NO == shutting_down)
3378 LOG (GNUNET_ERROR_TYPE_DEBUG, " too few connections, getting new ones\n");
3379 GCP_connect (t->peer); /* Will change cstate to WAITING when possible */
3383 /* If not marked as ready, no change is needed */
3384 if (CADET_TUNNEL_READY != t->cstate)
3387 /* Check if any connection is ready to maintain cstate */
3388 for (aux = t->connection_head; aux != NULL; aux = aux->next)
3389 if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
3395 * Add a channel to a tunnel.
3398 * @param ch Channel.
3401 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3403 struct CadetTChannel *aux;
3405 GNUNET_assert (NULL != ch);
3407 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
3409 for (aux = t->channel_head; aux != NULL; aux = aux->next)
3411 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
3416 aux = GNUNET_new (struct CadetTChannel);
3418 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
3419 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
3421 if (NULL != t->destroy_task)
3423 GNUNET_SCHEDULER_cancel (t->destroy_task);
3424 t->destroy_task = NULL;
3425 LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
3431 * Remove a channel from a tunnel.
3434 * @param ch Channel.
3437 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3439 struct CadetTChannel *aux;
3441 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
3442 for (aux = t->channel_head; aux != NULL; aux = aux->next)
3446 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
3447 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
3456 * Search for a channel by global ID.
3458 * @param t Tunnel containing the channel.
3459 * @param chid Public channel number.
3461 * @return channel handler, NULL if doesn't exist
3463 struct CadetChannel *
3464 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
3466 struct CadetTChannel *iter;
3471 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3473 if (GCCH_get_id (iter->ch) == chid)
3477 return NULL == iter ? NULL : iter->ch;
3482 * @brief Destroy a tunnel and free all resources.
3484 * Should only be called a while after the tunnel has been marked as destroyed,
3485 * in case there is a new channel added to the same peer shortly after marking
3486 * the tunnel. This way we avoid a new public key handshake.
3488 * @param cls Closure (tunnel to destroy).
3489 * @param tc Task context.
3492 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3494 struct CadetTunnel *t = cls;
3495 struct CadetTConnection *iter;
3497 LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
3498 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
3500 LOG (GNUNET_ERROR_TYPE_WARNING,
3501 "Not destroying tunnel, due to shutdown. "
3502 "Tunnel at %p should have been freed by GCT_shutdown\n", t);
3505 t->destroy_task = NULL;
3506 t->cstate = CADET_TUNNEL_SHUTDOWN;
3508 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3510 GCC_send_destroy (iter->c);
3517 * Tunnel is empty: destroy it.
3519 * Notifies all connections about the destruction.
3521 * @param t Tunnel to destroy.
3524 GCT_destroy_empty (struct CadetTunnel *t)
3526 if (GNUNET_YES == shutting_down)
3527 return; /* Will be destroyed immediately anyway */
3529 if (NULL != t->destroy_task)
3531 LOG (GNUNET_ERROR_TYPE_WARNING,
3532 "Tunnel %s is already scheduled for destruction. Tunnel debug dump:\n",
3534 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3536 /* should never happen, tunnel can only become empty once, and the
3537 * task identifier should be NO_TASK (cleaned when the tunnel was created
3538 * or became un-empty)
3543 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: scheduling destruction\n",
3546 // FIXME make delay a config option
3547 t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
3548 &delayed_destroy, t);
3549 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llu\n",
3550 t, t->destroy_task);
3555 * Destroy tunnel if empty (no more channels).
3557 * @param t Tunnel to destroy if empty.
3560 GCT_destroy_if_empty (struct CadetTunnel *t)
3562 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
3563 if (0 < GCT_count_channels (t))
3566 GCT_destroy_empty (t);
3571 * Destroy the tunnel.
3573 * This function does not generate any warning traffic to clients or peers.
3576 * Cancel messages belonging to this tunnel queued to neighbors.
3577 * Free any allocated resources linked to the tunnel.
3579 * @param t The tunnel to destroy.
3582 GCT_destroy (struct CadetTunnel *t)
3584 struct CadetTConnection *iter_c;
3585 struct CadetTConnection *next_c;
3586 struct CadetTChannel *iter_ch;
3587 struct CadetTChannel *next_ch;
3592 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
3594 GNUNET_break (GNUNET_YES ==
3595 GNUNET_CONTAINER_multipeermap_remove (tunnels,
3596 GCP_get_id (t->peer), t));
3598 for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
3600 next_c = iter_c->next;
3601 GCC_destroy (iter_c->c);
3603 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
3605 next_ch = iter_ch->next;
3606 GCCH_destroy (iter_ch->ch);
3607 /* Should only happen on shutdown, but it's ok. */
3610 if (NULL != t->destroy_task)
3612 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling dest: %llX\n", t->destroy_task);
3613 GNUNET_SCHEDULER_cancel (t->destroy_task);
3614 t->destroy_task = NULL;
3617 if (NULL != t->trim_connections_task)
3619 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling trim: %llX\n",
3620 t->trim_connections_task);
3621 GNUNET_SCHEDULER_cancel (t->trim_connections_task);
3622 t->trim_connections_task = NULL;
3625 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
3626 GCP_set_tunnel (t->peer, NULL);
3628 if (NULL != t->rekey_task)
3630 GNUNET_SCHEDULER_cancel (t->rekey_task);
3631 t->rekey_task = NULL;
3633 if (NULL != t->kx_ctx)
3635 if (NULL != t->kx_ctx->finish_task)
3636 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
3637 GNUNET_free (t->kx_ctx);
3648 * @brief Use the given path for the tunnel.
3649 * Update the next and prev hops (and RCs).
3650 * (Re)start the path refresh in case the tunnel is locally owned.
3652 * @param t Tunnel to update.
3653 * @param p Path to use.
3655 * @return Connection created.
3657 struct CadetConnection *
3658 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
3660 struct CadetConnection *c;
3661 struct GNUNET_CADET_Hash cid;
3662 unsigned int own_pos;
3664 if (NULL == t || NULL == p)
3670 if (CADET_TUNNEL_SHUTDOWN == t->cstate)
3676 for (own_pos = 0; own_pos < p->length; own_pos++)
3678 if (p->peers[own_pos] == myid)
3681 if (own_pos >= p->length)
3683 GNUNET_break_op (0);
3687 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
3688 c = GCC_new (&cid, t, p, own_pos);
3691 /* Path was flawed */
3694 GCT_add_connection (t, c);
3700 * Count all created connections of a tunnel. Not necessarily ready connections!
3702 * @param t Tunnel on which to count.
3704 * @return Number of connections created, either being established or ready.
3707 GCT_count_any_connections (struct CadetTunnel *t)
3709 struct CadetTConnection *iter;
3715 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3723 * Count established (ready) connections of a tunnel.
3725 * @param t Tunnel on which to count.
3727 * @return Number of connections.
3730 GCT_count_connections (struct CadetTunnel *t)
3732 struct CadetTConnection *iter;
3738 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3739 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
3747 * Count channels of a tunnel.
3749 * @param t Tunnel on which to count.
3751 * @return Number of channels.
3754 GCT_count_channels (struct CadetTunnel *t)
3756 struct CadetTChannel *iter;
3759 for (count = 0, iter = t->channel_head;
3761 iter = iter->next, count++) /* skip */;
3768 * Get the connectivity state of a tunnel.
3772 * @return Tunnel's connectivity state.
3774 enum CadetTunnelCState
3775 GCT_get_cstate (struct CadetTunnel *t)
3780 return (enum CadetTunnelCState) -1;
3787 * Get the encryption state of a tunnel.
3791 * @return Tunnel's encryption state.
3793 enum CadetTunnelEState
3794 GCT_get_estate (struct CadetTunnel *t)
3799 return (enum CadetTunnelEState) -1;
3805 * Get the maximum buffer space for a tunnel towards a local client.
3809 * @return Biggest buffer space offered by any channel in the tunnel.
3812 GCT_get_channels_buffer (struct CadetTunnel *t)
3814 struct CadetTChannel *iter;
3815 unsigned int buffer;
3816 unsigned int ch_buf;
3818 if (NULL == t->channel_head)
3820 /* Probably getting buffer for a channel create/handshake. */
3821 LOG (GNUNET_ERROR_TYPE_DEBUG, " no channels, allow max\n");
3826 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3828 ch_buf = get_channel_buffer (iter);
3829 if (ch_buf > buffer)
3837 * Get the total buffer space for a tunnel for P2P traffic.
3841 * @return Buffer space offered by all connections in the tunnel.
3844 GCT_get_connections_buffer (struct CadetTunnel *t)
3846 struct CadetTConnection *iter;
3847 unsigned int buffer;
3849 if (GNUNET_NO == is_ready (t))
3851 if (count_queued_data (t) > 3)
3858 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3860 if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
3864 buffer += get_connection_buffer (iter);
3872 * Get the tunnel's destination.
3876 * @return ID of the destination peer.
3878 const struct GNUNET_PeerIdentity *
3879 GCT_get_destination (struct CadetTunnel *t)
3881 return GCP_get_id (t->peer);
3886 * Get the tunnel's next free global channel ID.
3890 * @return GID of a channel free to use.
3893 GCT_get_next_chid (struct CadetTunnel *t)
3895 CADET_ChannelNumber chid;
3896 CADET_ChannelNumber mask;
3899 /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
3900 * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
3901 * If peer's ID is bigger, start at 0x4... bit 30 = 1
3903 result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
3908 t->next_chid |= mask;
3910 while (NULL != GCT_get_channel (t, t->next_chid))
3912 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
3913 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3914 t->next_chid |= mask;
3916 chid = t->next_chid;
3917 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3918 t->next_chid |= mask;
3925 * Send ACK on one or more channels due to buffer in connections.
3927 * @param t Channel which has some free buffer space.
3930 GCT_unchoke_channels (struct CadetTunnel *t)
3932 struct CadetTChannel *iter;
3933 unsigned int buffer;
3934 unsigned int channels = GCT_count_channels (t);
3935 unsigned int choked_n;
3936 struct CadetChannel *choked[channels];
3938 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
3939 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
3940 if (NULL != t->channel_head)
3941 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
3943 /* Get buffer space */
3944 buffer = GCT_get_connections_buffer (t);
3950 /* Count and remember choked channels */
3952 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3954 if (GNUNET_NO == get_channel_allowed (iter))
3956 choked[choked_n++] = iter->ch;
3960 /* Unchoke random channels */
3961 while (0 < buffer && 0 < choked_n)
3963 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3965 GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
3968 choked[r] = choked[choked_n];
3974 * Send ACK on one or more connections due to buffer space to the client.
3976 * Iterates all connections of the tunnel and sends ACKs appropriately.
3981 GCT_send_connection_acks (struct CadetTunnel *t)
3983 struct CadetTConnection *iter;
3986 uint32_t allow_per_connection;
3988 unsigned int buffer;
3990 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
3999 if (CADET_TUNNEL_READY != t->cstate)
4002 buffer = GCT_get_channels_buffer (t);
4003 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer %u\n", buffer);
4005 /* Count connections, how many messages are already allowed */
4006 cs = GCT_count_connections (t);
4007 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
4009 allowed += get_connection_allowed (iter);
4011 LOG (GNUNET_ERROR_TYPE_DEBUG, " allowed %u\n", allowed);
4013 /* Make sure there is no overflow */
4014 if (allowed > buffer)
4017 /* Authorize connections to send more data */
4018 to_allow = buffer - allowed;
4020 for (iter = t->connection_head;
4021 NULL != iter && to_allow > 0;
4024 if (CADET_CONNECTION_READY != GCC_get_state (iter->c)
4025 || get_connection_allowed (iter) > 64 / 3)
4029 allow_per_connection = to_allow/cs;
4030 to_allow -= allow_per_connection;
4032 GCC_allow (iter->c, allow_per_connection,
4033 GCC_is_origin (iter->c, GNUNET_NO));
4038 /* Since we don't allow if it's allowed to send 64/3, this can happen. */
4039 LOG (GNUNET_ERROR_TYPE_DEBUG, " reminding to_allow: %u\n", to_allow);
4045 * Cancel a previously sent message while it's in the queue.
4047 * ONLY can be called before the continuation given to the send function
4048 * is called. Once the continuation is called, the message is no longer in the
4051 * @param q Handle to the queue.
4054 GCT_cancel (struct CadetTunnelQueue *q)
4059 /* tun_message_sent() will be called and free q */
4061 else if (NULL != q->tqd)
4063 unqueue_data (q->tqd);
4065 if (NULL != q->cont)
4066 q->cont (q->cont_cls, NULL, q, 0, 0);
4077 * Sends an already built message on a tunnel, encrypting it and
4078 * choosing the best connection if not provided.
4080 * @param message Message to send. Function modifies it.
4081 * @param t Tunnel on which this message is transmitted.
4082 * @param c Connection to use (autoselect if NULL).
4083 * @param force Force the tunnel to take the message (buffer overfill).
4084 * @param cont Continuation to call once message is really sent.
4085 * @param cont_cls Closure for @c cont.
4087 * @return Handle to cancel message. NULL if @c cont is NULL.
4089 struct CadetTunnelQueue *
4090 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
4091 struct CadetTunnel *t, struct CadetConnection *c,
4092 int force, GCT_sent cont, void *cont_cls)
4094 return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
4099 * Send an Axolotl KX message.
4101 * @param t Tunnel on which to send it.
4104 GCT_send_ax_kx (struct CadetTunnel *t)
4106 struct GNUNET_CADET_AX_KX msg;
4108 LOG (GNUNET_ERROR_TYPE_INFO, "===> AX_KX for %s\n", GCT_2s (t));
4110 msg.header.size = htons (sizeof (msg));
4111 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_AX_KX);
4112 msg.permanent_key = ax_identity.permanent_key;
4113 msg.purpose = ax_identity.purpose;
4114 msg.signature = ax_identity.signature;
4115 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->kx_0, &msg.ephemeral_key);
4116 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &msg.ratchet_key);
4118 t->ephm_h = send_kx (t, &msg.header);
4119 GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
4124 * Sends an already built and encrypted message on a tunnel, choosing the best
4125 * connection. Useful for re-queueing messages queued on a destroyed connection.
4127 * @param message Message to send. Function modifies it.
4128 * @param t Tunnel on which this message is transmitted.
4131 GCT_resend_message (const struct GNUNET_MessageHeader *message,
4132 struct CadetTunnel *t)
4134 struct CadetConnection *c;
4137 c = tunnel_get_connection (t);
4140 /* TODO queue in tunnel, marked as encrypted */
4141 LOG (GNUNET_ERROR_TYPE_DEBUG, "No connection available, dropping.\n");
4144 fwd = GCC_is_origin (c, GNUNET_YES);
4145 GNUNET_break (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
4146 GNUNET_YES, NULL, NULL));
4151 * Is the tunnel directed towards the local peer?
4155 * @return #GNUNET_YES if it is loopback.
4158 GCT_is_loopback (const struct CadetTunnel *t)
4160 return (myid == GCP_get_short_id (t->peer));
4165 * Is the tunnel this path already?
4170 * @return #GNUNET_YES a connection uses this path.
4173 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
4175 struct CadetTConnection *iter;
4177 for (iter = t->connection_head; NULL != iter; iter = iter->next)
4178 if (path_equivalent (GCC_get_path (iter->c), p))
4186 * Get a cost of a path for a tunnel considering existing connections.
4189 * @param path Candidate path.
4191 * @return Cost of the path (path length + number of overlapping nodes)
4194 GCT_get_path_cost (const struct CadetTunnel *t,
4195 const struct CadetPeerPath *path)
4197 struct CadetTConnection *iter;
4198 const struct CadetPeerPath *aux;
4199 unsigned int overlap;
4207 GNUNET_assert (NULL != t);
4209 for (i = 0; i < path->length; i++)
4211 for (iter = t->connection_head; NULL != iter; iter = iter->next)
4213 aux = GCC_get_path (iter->c);
4217 for (j = 0; j < aux->length; j++)
4219 if (path->peers[i] == aux->peers[j])
4227 return path->length + overlap;
4232 * Get the static string for the peer this tunnel is directed.
4236 * @return Static string the destination peer's ID.
4239 GCT_2s (const struct CadetTunnel *t)
4244 return GCP_2s (t->peer);
4248 /******************************************************************************/
4249 /***************************** INFO/DEBUG *******************************/
4250 /******************************************************************************/
4253 ax_debug (const struct CadetTunnelAxolotl *ax, enum GNUNET_ErrorType level)
4255 struct GNUNET_CRYPTO_EcdhePublicKey pub;
4256 struct CadetTunnelSkippedKey *iter;
4259 LOG2 (level, "TTT RK\t %s\n",
4260 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->RK));
4262 LOG2 (level, "TTT HKs\t %s\n",
4263 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKs));
4264 LOG2 (level, "TTT HKr\t %s\n",
4265 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKr));
4266 LOG2 (level, "TTT NHKs\t %s\n",
4267 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->NHKs));
4268 LOG2 (level, "TTT NHKr\t %s\n",
4269 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->NHKr));
4271 LOG2 (level, "TTT CKs\t %s\n",
4272 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKs));
4273 LOG2 (level, "TTT CKr\t %s\n",
4274 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKr));
4276 GNUNET_CRYPTO_ecdhe_key_get_public (ax_key, &pub);
4277 LOG2 (level, "TTT DHIs\t %s\n",
4278 GNUNET_h2s ((struct GNUNET_HashCode *) &pub));
4279 LOG2 (level, "TTT DHIr\t %s\n",
4280 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->DHIr));
4281 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs, &pub);
4282 LOG2 (level, "TTT DHRs\t %s\n",
4283 GNUNET_h2s ((struct GNUNET_HashCode *) &pub));
4284 LOG2 (level, "TTT DHRr\t %s\n",
4285 GNUNET_h2s ((struct GNUNET_HashCode *) &ax->DHRr));
4287 LOG2 (level, "TTT Nr\t %u\tNs\t%u\n", ax->Nr, ax->Ns);
4288 LOG2 (level, "TTT PNs\t %u\tSkipped\t%u\n", ax->PNs, ax->skipped);
4289 LOG2 (level, "TTT Ratchet\t%u\n", ax->ratchet_flag);
4291 for (iter = ax->skipped_head; NULL != iter; iter = iter->next)
4293 LOG2 (level, "TTT HK\t %s\n",
4294 GNUNET_h2s ((struct GNUNET_HashCode *) &iter->HK));
4295 LOG2 (level, "TTT MK\t %s\n",
4296 GNUNET_h2s ((struct GNUNET_HashCode *) &iter->MK));
4301 * Log all possible info about the tunnel state.
4303 * @param t Tunnel to debug.
4304 * @param level Debug level to use.
4307 GCT_debug (const struct CadetTunnel *t, enum GNUNET_ErrorType level)
4309 struct CadetTChannel *iterch;
4310 struct CadetTConnection *iterc;
4313 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
4315 __FILE__, __FUNCTION__, __LINE__);
4319 LOG2 (level, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
4320 LOG2 (level, "TTT cstate %s, estate %s\n",
4321 cstate2s (t->cstate), estate2s (t->estate));
4322 LOG2 (level, "TTT kx_ctx %p, rekey_task %u, finish task %u\n",
4323 t->kx_ctx, t->rekey_task, t->kx_ctx ? t->kx_ctx->finish_task : 0);
4324 #if DUMP_KEYS_TO_STDERR
4325 if (CADET_Axolotl == t->enc_type)
4327 ax_debug (t->ax, level);
4331 LOG2 (level, "TTT my EPHM\t %s\n",
4332 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
4333 LOG2 (level, "TTT peers EPHM:\t %s\n",
4334 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
4335 LOG2 (level, "TTT ENC key:\t %s\n",
4336 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
4337 LOG2 (level, "TTT DEC key:\t %s\n",
4338 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
4341 LOG2 (level, "TTT OLD ENC key:\t %s\n",
4342 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->e_key_old));
4343 LOG2 (level, "TTT OLD DEC key:\t %s\n",
4344 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->d_key_old));
4348 LOG2 (level, "TTT tq_head %p, tq_tail %p\n", t->tq_head, t->tq_tail);
4349 LOG2 (level, "TTT destroy %u\n", t->destroy_task);
4351 LOG2 (level, "TTT channels:\n");
4352 for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
4354 LOG2 (level, "TTT - %s\n", GCCH_2s (iterch->ch));
4357 LOG2 (level, "TTT connections:\n");
4358 for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
4360 GCC_debug (iterc->c, level);
4363 LOG2 (level, "TTT DEBUG TUNNEL END\n");
4368 * Iterate all tunnels.
4370 * @param iter Iterator.
4371 * @param cls Closure for @c iter.
4374 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
4376 GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
4381 * Count all tunnels.
4383 * @return Number of tunnels to remote peers kept by this peer.
4386 GCT_count_all (void)
4388 return GNUNET_CONTAINER_multipeermap_size (tunnels);
4393 * Iterate all connections of a tunnel.
4395 * @param t Tunnel whose connections to iterate.
4396 * @param iter Iterator.
4397 * @param cls Closure for @c iter.
4400 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
4402 struct CadetTConnection *ct;
4404 for (ct = t->connection_head; NULL != ct; ct = ct->next)
4410 * Iterate all channels of a tunnel.
4412 * @param t Tunnel whose channels to iterate.
4413 * @param iter Iterator.
4414 * @param cls Closure for @c iter.
4417 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
4419 struct CadetTChannel *cht;
4421 for (cht = t->channel_head; NULL != cht; cht = cht->next)
4422 iter (cls, cht->ch);