2 This file is part of GNUnet.
3 Copyright (C) 2013 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 #include "gnunet_util_lib.h"
24 #include "gnunet_signatures.h"
25 #include "gnunet_statistics_service.h"
27 #include "cadet_protocol.h"
28 #include "cadet_path.h"
30 #include "gnunet-service-cadet_tunnel.h"
31 #include "gnunet-service-cadet_connection.h"
32 #include "gnunet-service-cadet_channel.h"
33 #include "gnunet-service-cadet_peer.h"
35 #define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__)
36 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
38 #define REKEY_WAIT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5)
40 #if !defined(GNUNET_CULL_LOGGING)
41 #define DUMP_KEYS_TO_STDERR GNUNET_YES
43 #define DUMP_KEYS_TO_STDERR GNUNET_NO
46 /******************************************************************************/
47 /******************************** STRUCTS **********************************/
48 /******************************************************************************/
52 struct CadetTChannel *next;
53 struct CadetTChannel *prev;
54 struct CadetChannel *ch;
59 * Connection list and metadata.
61 struct CadetTConnection
66 struct CadetTConnection *next;
71 struct CadetTConnection *prev;
76 struct CadetConnection *c;
79 * Creation time, to keep oldest connection alive.
81 struct GNUNET_TIME_Absolute created;
84 * Connection throughput, to keep fastest connection alive.
90 * Structure used during a Key eXchange.
92 struct CadetTunnelKXCtx
95 * Encryption ("our") old "confirmed" key, for encrypting traffic sent by us
96 * end before the key exchange is finished or times out.
98 struct GNUNET_CRYPTO_SymmetricSessionKey e_key_old;
101 * Decryption ("their") old "confirmed" key, for decrypting traffic sent by
102 * the other end before the key exchange started.
104 struct GNUNET_CRYPTO_SymmetricSessionKey d_key_old;
107 * Same as @c e_key_old, for the case of two simultaneous KX.
108 * This can happen if cadet decides to start a re-key while the peer has also
109 * started its re-key (due to network delay this is impossible to avoid).
110 * In this case, the key material generated with the peer's old ephemeral
111 * *might* (but doesn't have to) be incorrect.
112 * Since no more than two re-keys can happen simultaneously, this is enough.
114 struct GNUNET_CRYPTO_SymmetricSessionKey e_key_old2;
117 * Same as @c d_key_old, for the case described in @c e_key_old2.
119 struct GNUNET_CRYPTO_SymmetricSessionKey d_key_old2;
122 * Challenge to send and expect in the PONG.
127 * When the rekey started. One minute after this the new key will be used.
129 struct GNUNET_TIME_Absolute rekey_start_time;
132 * Task for delayed destruction of the Key eXchange context, to allow delayed
133 * messages with the old key to be decrypted successfully.
135 struct GNUNET_SCHEDULER_Task *finish_task;
139 * Encryption systems possible.
141 enum CadetTunnelEncryption
144 * Default Axolotl system.
149 * Fallback OTR-style encryption.
154 struct CadetTunnelSkippedKey
156 struct CadetTunnelSkippedKey *next;
157 struct CadetTunnelSkippedKey *prev;
159 struct GNUNET_TIME_Absolute timestamp;
161 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
162 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
166 * Axolotl data, according to https://github.com/trevp/axolotl/wiki
168 struct CadetTunnelAxolotl
171 * A (double linked) list of stored message keys and associated header keys
172 * for "skipped" messages, i.e. messages that have not bee*n
173 * received despite the reception of more recent messages, (head)/
175 struct CadetTunnelSkippedKey *skipped_head;
178 * Skipped messages' keys DLL, tail.
180 struct CadetTunnelSkippedKey *skipped_tail;
183 * Elements in @a skipped_head <-> @a skipped_tail.
188 * 32-byte root key which gets updated by DH ratchet
190 struct GNUNET_CRYPTO_SymmetricSessionKey RK;
193 * 32-byte header key (send)
195 struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
198 * 32-byte header key (recv)
200 struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
203 * 32-byte next header key (send)
205 struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
208 * 32-byte next header key (recv)
210 struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
213 * 32-byte chain keys (used for forward-secrecy updating, send)
215 struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
218 * 32-byte chain keys (used for forward-secrecy updating, recv)
220 struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
223 * ECDH for key exchange (A0 / B0)
225 struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
228 * ECDH Ratchet key (send)
230 struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
233 * ECDH Ratchet key (recv)
235 struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
238 * Message number (reset to 0 with each new ratchet, send)
243 * Message numbers (reset to 0 with each new ratchet, recv)
248 * Previous message numbers (# of msgs sent under prev ratchet)
253 * True (#GNUNET_YES) if the party will send a new ratchet key in next msg.
259 * Struct containing all information regarding a tunnel to a peer.
264 * Endpoint of the tunnel.
266 struct CadetPeer *peer;
269 * Type of encryption used in the tunnel.
271 enum CadetTunnelEncryption enc_type;
276 struct CadetTunnelAxolotl *ax;
279 * State of the tunnel connectivity.
281 enum CadetTunnelCState cstate;
284 * State of the tunnel encryption.
286 enum CadetTunnelEState estate;
289 * Key eXchange context.
291 struct CadetTunnelKXCtx *kx_ctx;
294 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own ephemeral
297 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
300 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
302 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
305 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
307 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
310 * Task to start the rekey process.
312 struct GNUNET_SCHEDULER_Task * rekey_task;
315 * Paths that are actively used to reach the destination peer.
317 struct CadetTConnection *connection_head;
318 struct CadetTConnection *connection_tail;
321 * Next connection number.
326 * Channels inside this tunnel.
328 struct CadetTChannel *channel_head;
329 struct CadetTChannel *channel_tail;
332 * Channel ID for the next created channel.
334 CADET_ChannelNumber next_chid;
337 * Destroy flag: if true, destroy on last message.
339 struct GNUNET_SCHEDULER_Task * destroy_task;
342 * Queued messages, to transmit once tunnel gets connected.
344 struct CadetTunnelDelayed *tq_head;
345 struct CadetTunnelDelayed *tq_tail;
348 * Task to trim connections if too many are present.
350 struct GNUNET_SCHEDULER_Task * trim_connections_task;
353 * Ephemeral message in the queue (to avoid queueing more than one).
355 struct CadetConnectionQueue *ephm_h;
358 * Pong message in the queue.
360 struct CadetConnectionQueue *pong_h;
365 * Struct used to save messages in a non-ready tunnel to send once connected.
367 struct CadetTunnelDelayed
372 struct CadetTunnelDelayed *next;
373 struct CadetTunnelDelayed *prev;
378 struct CadetTunnel *t;
381 * Tunnel queue given to the channel to cancel request. Update on send_queued.
383 struct CadetTunnelQueue *tq;
388 /* struct GNUNET_MessageHeader *msg; */
393 * Handle for messages queued but not yet sent.
395 struct CadetTunnelQueue
398 * Connection queue handle, to cancel if necessary.
400 struct CadetConnectionQueue *cq;
403 * Handle in case message hasn't been given to a connection yet.
405 struct CadetTunnelDelayed *tqd;
408 * Continuation to call once sent.
413 * Closure for @c cont.
420 * Cached Axolotl key with signature.
422 struct CadetAxolotlSignedKey
425 * Information about what is being signed (@a permanent_key).
427 struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
430 * Permanent public ECDH key.
432 struct GNUNET_CRYPTO_EcdhePublicKey permanent_key;
435 * An EdDSA signature of the permanent ECDH key with the Peer's ID key.
437 struct GNUNET_CRYPTO_EddsaSignature signature;
441 /******************************************************************************/
442 /******************************* GLOBALS ***********************************/
443 /******************************************************************************/
446 * Global handle to the statistics service.
448 extern struct GNUNET_STATISTICS_Handle *stats;
451 * Local peer own ID (memory efficient handle).
453 extern GNUNET_PEER_Id myid;
456 * Local peer own ID (full value).
458 extern struct GNUNET_PeerIdentity my_full_id;
462 * Don't try to recover tunnels if shutting down.
464 extern int shutting_down;
468 * Set of all tunnels, in order to trigger a new exchange on rekey.
469 * Indexed by peer's ID.
471 static struct GNUNET_CONTAINER_MultiPeerMap *tunnels;
474 * Default TTL for payload packets.
476 static unsigned long long default_ttl;
480 * Own Peer ID private key.
482 const static struct GNUNET_CRYPTO_EddsaPrivateKey *id_key;
484 /******************************** AXOLOTL ************************************/
486 static struct GNUNET_CRYPTO_EcdhePrivateKey *ax_key;
489 * Own Axolotl permanent public key (cache).
491 static struct CadetAxolotlSignedKey ax_identity;
493 /******************************** OTR ***********************************/
497 * Own global OTR ephemeral private key.
499 static struct GNUNET_CRYPTO_EcdhePrivateKey *otr_ephemeral_key;
502 * Cached message used to perform a OTR key exchange.
504 static struct GNUNET_CADET_KX_Ephemeral otr_kx_msg;
507 * Task to generate a new OTR ephemeral key.
509 static struct GNUNET_SCHEDULER_Task *rekey_task;
514 static struct GNUNET_TIME_Relative rekey_period;
517 /******************************************************************************/
518 /******************************** STATIC ***********************************/
519 /******************************************************************************/
522 * Get string description for tunnel connectivity state.
524 * @param cs Tunnel state.
526 * @return String representation.
529 cstate2s (enum CadetTunnelCState cs)
535 case CADET_TUNNEL_NEW:
536 return "CADET_TUNNEL_NEW";
537 case CADET_TUNNEL_SEARCHING:
538 return "CADET_TUNNEL_SEARCHING";
539 case CADET_TUNNEL_WAITING:
540 return "CADET_TUNNEL_WAITING";
541 case CADET_TUNNEL_READY:
542 return "CADET_TUNNEL_READY";
543 case CADET_TUNNEL_SHUTDOWN:
544 return "CADET_TUNNEL_SHUTDOWN";
546 SPRINTF (buf, "%u (UNKNOWN STATE)", cs);
554 * Get string description for tunnel encryption state.
556 * @param es Tunnel state.
558 * @return String representation.
561 estate2s (enum CadetTunnelEState es)
567 case CADET_TUNNEL_KEY_UNINITIALIZED:
568 return "CADET_TUNNEL_KEY_UNINITIALIZED";
569 case CADET_TUNNEL_KEY_SENT:
570 return "CADET_TUNNEL_KEY_SENT";
571 case CADET_TUNNEL_KEY_PING:
572 return "CADET_TUNNEL_KEY_PING";
573 case CADET_TUNNEL_KEY_OK:
574 return "CADET_TUNNEL_KEY_OK";
575 case CADET_TUNNEL_KEY_REKEY:
576 return "CADET_TUNNEL_KEY_REKEY";
578 SPRINTF (buf, "%u (UNKNOWN STATE)", es);
586 * @brief Check if tunnel is ready to send traffic.
588 * Tunnel must be connected and with encryption correctly set up.
590 * @param t Tunnel to check.
592 * @return #GNUNET_YES if ready, #GNUNET_NO otherwise
595 is_ready (struct CadetTunnel *t)
599 GCT_debug (t, GNUNET_ERROR_TYPE_DEBUG);
600 ready = CADET_TUNNEL_READY == t->cstate
601 && (CADET_TUNNEL_KEY_OK == t->estate
602 || CADET_TUNNEL_KEY_REKEY == t->estate);
603 ready = ready || GCT_is_loopback (t);
609 * Check if a key is invalid (NULL pointer or all 0)
611 * @param key Key to check.
613 * @return #GNUNET_YES if key is null, #GNUNET_NO if exists and is not 0.
616 is_key_null (struct GNUNET_CRYPTO_SymmetricSessionKey *key)
618 struct GNUNET_CRYPTO_SymmetricSessionKey null_key;
623 memset (&null_key, 0, sizeof (null_key));
624 if (0 == memcmp (key, &null_key, sizeof (null_key)))
631 * Ephemeral key message purpose size.
633 * @return Size of the part of the ephemeral key message that must be signed.
636 ephemeral_purpose_size (void)
638 return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
639 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
640 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
641 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
642 sizeof (struct GNUNET_PeerIdentity);
647 * Ephemeral key message purpose size.
649 * @return Size of the part of the ephemeral key message that must be signed.
652 ax_purpose_size (void)
654 return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
655 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey);
660 * Size of the encrypted part of a ping message.
662 * @return Size of the encrypted part of a ping message.
665 ping_encryption_size (void)
667 return sizeof (uint32_t);
672 * Get the channel's buffer. ONLY FOR NON-LOOPBACK CHANNELS!!
674 * @param tch Tunnel's channel handle.
676 * @return Amount of messages the channel can still buffer towards the client.
679 get_channel_buffer (const struct CadetTChannel *tch)
683 /* If channel is incoming, is terminal in the FWD direction and fwd is YES */
684 fwd = GCCH_is_terminal (tch->ch, GNUNET_YES);
686 return GCCH_get_buffer (tch->ch, fwd);
691 * Get the channel's allowance status.
693 * @param tch Tunnel's channel handle.
695 * @return #GNUNET_YES if we allowed the client to send data to us.
698 get_channel_allowed (const struct CadetTChannel *tch)
702 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
703 fwd = GCCH_is_origin (tch->ch, GNUNET_YES);
705 return GCCH_get_allowed (tch->ch, fwd);
710 * Get the connection's buffer.
712 * @param tc Tunnel's connection handle.
714 * @return Amount of messages the connection can still buffer.
717 get_connection_buffer (const struct CadetTConnection *tc)
721 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
722 fwd = GCC_is_origin (tc->c, GNUNET_YES);
724 return GCC_get_buffer (tc->c, fwd);
729 * Get the connection's allowance.
731 * @param tc Tunnel's connection handle.
733 * @return Amount of messages we have allowed the next peer to send us.
736 get_connection_allowed (const struct CadetTConnection *tc)
740 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
741 fwd = GCC_is_origin (tc->c, GNUNET_YES);
743 return GCC_get_allowed (tc->c, fwd);
748 * Check that a ephemeral key message s well formed and correctly signed.
750 * @param t Tunnel on which the message came.
751 * @param msg The ephemeral key message.
753 * @return GNUNET_OK if message is fine, GNUNET_SYSERR otherwise.
756 check_ephemeral (struct CadetTunnel *t,
757 const struct GNUNET_CADET_KX_Ephemeral *msg)
759 /* Check message size */
760 if (ntohs (msg->header.size) != sizeof (struct GNUNET_CADET_KX_Ephemeral))
761 return GNUNET_SYSERR;
763 /* Check signature size */
764 if (ntohl (msg->purpose.size) != ephemeral_purpose_size ())
765 return GNUNET_SYSERR;
768 if (0 != memcmp (&msg->origin_identity,
769 GCP_get_id (t->peer),
770 sizeof (struct GNUNET_PeerIdentity)))
771 return GNUNET_SYSERR;
773 /* Check signature */
775 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_CADET_KX,
778 &msg->origin_identity.public_key))
779 return GNUNET_SYSERR;
786 * Select the best key to use for encryption (send), based on KX status.
788 * Normally, return the current key. If there is a KX in progress and the old
789 * key is fresh enough, return the old key.
791 * @param t Tunnel to choose the key from.
793 * @return The optimal key to encrypt/hmac outgoing traffic.
795 static const struct GNUNET_CRYPTO_SymmetricSessionKey *
796 select_key (const struct CadetTunnel *t)
798 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
800 if (NULL != t->kx_ctx
801 && NULL == t->kx_ctx->finish_task)
803 struct GNUNET_TIME_Relative age;
805 age = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
806 LOG (GNUNET_ERROR_TYPE_DEBUG,
807 " key exchange in progress, started %s ago\n",
808 GNUNET_STRINGS_relative_time_to_string (age, GNUNET_YES));
809 // FIXME make duration of old keys configurable
810 if (age.rel_value_us < GNUNET_TIME_UNIT_MINUTES.rel_value_us)
812 LOG (GNUNET_ERROR_TYPE_DEBUG, " using old key\n");
813 key = &t->kx_ctx->e_key_old;
817 LOG (GNUNET_ERROR_TYPE_DEBUG, " using new key (old key too old)\n");
823 LOG (GNUNET_ERROR_TYPE_DEBUG, " no KX: using current key\n");
833 * @param plaintext Content to HMAC.
834 * @param size Size of @c plaintext.
835 * @param iv Initialization vector for the message.
836 * @param key Key to use.
837 * @param hmac[out] Destination to store the HMAC.
840 t_hmac (const void *plaintext, size_t size,
841 uint32_t iv, const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
842 struct GNUNET_CADET_Hash *hmac)
844 static const char ctx[] = "cadet authentication key";
845 struct GNUNET_CRYPTO_AuthKey auth_key;
846 struct GNUNET_HashCode hash;
848 #if DUMP_KEYS_TO_STDERR
849 LOG (GNUNET_ERROR_TYPE_INFO, " HMAC with key %s\n",
850 GNUNET_h2s ((struct GNUNET_HashCode *) key));
852 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
857 /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
858 GNUNET_CRYPTO_hmac (&auth_key, plaintext, size, &hash);
859 memcpy (hmac, &hash, sizeof (*hmac));
864 * Encrypt daforce_newest_keyta with the tunnel key.
866 * @param t Tunnel whose key to use.
867 * @param dst Destination for the encrypted data.
868 * @param src Source of the plaintext. Can overlap with @c dst.
869 * @param size Size of the plaintext.
870 * @param iv Initialization Vector to use.
871 * @param force_newest_key Force the use of the newest key, otherwise
872 * CADET will use the old key when allowed.
873 * This can happen in the case when a KX is going on
874 * and the old one hasn't expired.
877 t_encrypt (struct CadetTunnel *t, void *dst, const void *src,
878 size_t size, uint32_t iv, int force_newest_key)
880 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
881 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
884 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt start\n");
886 key = GNUNET_YES == force_newest_key ? &t->e_key : select_key (t);
887 #if DUMP_KEYS_TO_STDERR
888 LOG (GNUNET_ERROR_TYPE_INFO, " ENC with key %s\n",
889 GNUNET_h2s ((struct GNUNET_HashCode *) key));
891 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
892 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt IV derived\n");
893 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, key, &siv, dst);
894 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt end\n");
901 * Generate a new key with a HMAC mechanism from the existing chain key.
903 * @param ax Axolotl context.
904 * @param key[out] Derived key.
905 * @param source Source key material (data to HMAC).
906 * @param len Length of @a source.
909 t_ax_hmac_hash (struct CadetTunnelAxolotl *ax,
910 struct GNUNET_CRYPTO_SymmetricSessionKey *key,
911 void *source, unsigned int len)
913 static const char ctx[] = "axolotl key derivation";
914 struct GNUNET_CRYPTO_AuthKey auth_key;
915 struct GNUNET_HashCode hash;
917 GNUNET_CRYPTO_hmac_derive_key (&auth_key, &ax->CKs,
920 GNUNET_CRYPTO_hmac (&auth_key, source, len, &hash);
921 GNUNET_CRYPTO_kdf (key, sizeof (*key),
923 &hash, sizeof (hash));
928 * Encrypt data with the tunnel key.
930 * @param t Tunnel whose key to use.
931 * @param dst Destination for the encrypted data.
932 * @param src Source of the plaintext. Can overlap with @c dst.
933 * @param size Size of the plaintext.
935 * @return Size of the encrypted data.
938 t_ax_encrypt (struct CadetTunnel *t, void *dst, const void *src, size_t size)
940 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
941 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
942 struct CadetTunnelAxolotl *ax;
945 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt start\n");
949 if (GNUNET_YES == ax->ratchet_flag)
951 /* Advance ratchet */
954 t_ax_hmac_hash (ax, &MK, "0", 1);
955 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &MK, NULL, 0, NULL);
957 #if DUMP_KEYS_TO_STDERR
958 LOG (GNUNET_ERROR_TYPE_INFO, " ENC with key %s\n",
959 GNUNET_h2s ((struct GNUNET_HashCode *) &MK));
962 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, &MK, &iv, dst);
964 t_ax_hmac_hash (ax, &ax->CKs, "1", 1);
966 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt end\n");
973 * Decrypt and verify data with the appropriate tunnel key.
975 * @param key Key to use.
976 * @param dst Destination for the plaintext.
977 * @param src Source of the encrypted data. Can overlap with @c dst.
978 * @param size Size of the encrypted data.
979 * @param iv Initialization Vector to use.
981 * @return Size of the decrypted data, -1 if an error was encountered.
984 decrypt (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
985 void *dst, const void *src, size_t size, uint32_t iv)
987 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
990 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt start\n");
991 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv\n");
992 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
993 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv done\n");
994 out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, key, &siv, dst);
995 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt end\n");
1002 * Decrypt and verify data with the most recent tunnel key.
1004 * @param t Tunnel whose key to use.
1005 * @param dst Destination for the plaintext.
1006 * @param src Source of the encrypted data. Can overlap with @c dst.
1007 * @param size Size of the encrypted data.
1008 * @param iv Initialization Vector to use.
1010 * @return Size of the decrypted data, -1 if an error was encountered.
1013 t_decrypt (struct CadetTunnel *t, void *dst, const void *src,
1014 size_t size, uint32_t iv)
1018 #if DUMP_KEYS_TO_STDERR
1019 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_decrypt with %s\n",
1020 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
1022 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1024 GNUNET_STATISTICS_update (stats, "# non decryptable data", 1, GNUNET_NO);
1025 LOG (GNUNET_ERROR_TYPE_WARNING,
1026 "got data on %s without a valid key\n",
1028 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1032 out_size = decrypt (&t->d_key, dst, src, size, iv);
1039 * Decrypt and verify data with the appropriate tunnel key and verify that the
1040 * data has not been altered since it was sent by the remote peer.
1042 * @param t Tunnel whose key to use.
1043 * @param dst Destination for the plaintext.
1044 * @param src Source of the encrypted data. Can overlap with @c dst.
1045 * @param size Size of the encrypted data.
1046 * @param iv Initialization Vector to use.
1047 * @param msg_hmac HMAC of the message, cannot be NULL.
1049 * @return Size of the decrypted data, -1 if an error was encountered.
1052 t_decrypt_and_validate (struct CadetTunnel *t,
1053 void *dst, const void *src,
1054 size_t size, uint32_t iv,
1055 const struct GNUNET_CADET_Hash *msg_hmac)
1057 struct GNUNET_CRYPTO_SymmetricSessionKey *key;
1058 struct GNUNET_CADET_Hash hmac;
1061 /* Try primary (newest) key */
1063 decrypted_size = decrypt (key, dst, src, size, iv);
1064 t_hmac (src, size, iv, key, &hmac);
1065 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1066 return decrypted_size;
1068 /* If no key exchange is going on, we just failed. */
1069 if (NULL == t->kx_ctx)
1071 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1072 "Failed checksum validation on tunnel %s with no KX\n",
1074 GNUNET_STATISTICS_update (stats, "# wrong HMAC no KX", 1, GNUNET_NO);
1078 /* Try secondary key, from previous KX period. */
1079 key = &t->kx_ctx->d_key_old;
1080 decrypted_size = decrypt (key, dst, src, size, iv);
1081 t_hmac (src, size, iv, key, &hmac);
1082 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1083 return decrypted_size;
1085 /* Hail Mary, try tertiary, key, in case of parallel re-keys. */
1086 key = &t->kx_ctx->d_key_old2;
1087 decrypted_size = decrypt (key, dst, src, size, iv);
1088 t_hmac (src, size, iv, key, &hmac);
1089 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1090 return decrypted_size;
1092 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1093 "Failed checksum validation on tunnel %s with KX\n",
1095 GNUNET_STATISTICS_update (stats, "# wrong HMAC with KX", 1, GNUNET_NO);
1100 * Decrypt and verify data with the appropriate tunnel key and verify that the
1101 * data has not been altered since it was sent by the remote peer.
1103 * @param t Tunnel whose key to use.
1104 * @param dst Destination for the plaintext.
1105 * @param src Source of the encrypted data. Can overlap with @c dst.
1106 * @param size Size of the encrypted data.
1107 * @param msg_hmac HMAC of the message, cannot be NULL.
1109 * @return Size of the decrypted data, -1 if an error was encountered.
1112 t_ax_decrypt_and_validate (struct CadetTunnel *t,
1113 void *dst, const void *src, size_t size,
1114 const struct GNUNET_CADET_Hash *msg_hmac)
1116 struct CadetTunnelAxolotl *ax;
1131 * Create key material by doing ECDH on the local and remote ephemeral keys.
1133 * @param key_material Where to store the key material.
1134 * @param ephemeral_key Peer's public ephemeral key.
1137 derive_key_material (struct GNUNET_HashCode *key_material,
1138 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key)
1141 GNUNET_CRYPTO_ecc_ecdh (otr_ephemeral_key,
1151 * Create a symmetic key from the identities of both ends and the key material
1154 * @param key Destination for the generated key.
1155 * @param sender ID of the peer that will encrypt with @c key.
1156 * @param receiver ID of the peer that will decrypt with @c key.
1157 * @param key_material Hash created with ECDH with the ephemeral keys.
1160 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
1161 const struct GNUNET_PeerIdentity *sender,
1162 const struct GNUNET_PeerIdentity *receiver,
1163 const struct GNUNET_HashCode *key_material)
1165 const char salt[] = "CADET kx salt";
1167 GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
1168 salt, sizeof (salt),
1169 key_material, sizeof (struct GNUNET_HashCode),
1170 sender, sizeof (struct GNUNET_PeerIdentity),
1171 receiver, sizeof (struct GNUNET_PeerIdentity),
1177 * Derive the tunnel's keys using our own and the peer's ephemeral keys.
1179 * @param t Tunnel for which to create the keys.
1182 create_keys (struct CadetTunnel *t)
1184 struct GNUNET_HashCode km;
1186 derive_key_material (&km, &t->peers_ephemeral_key);
1187 derive_symmertic (&t->e_key, &my_full_id, GCP_get_id (t->peer), &km);
1188 derive_symmertic (&t->d_key, GCP_get_id (t->peer), &my_full_id, &km);
1189 #if DUMP_KEYS_TO_STDERR
1190 LOG (GNUNET_ERROR_TYPE_INFO, "ME: %s\n",
1191 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
1192 LOG (GNUNET_ERROR_TYPE_INFO, "PE: %s\n",
1193 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
1194 LOG (GNUNET_ERROR_TYPE_INFO, "KM: %s\n", GNUNET_h2s (&km));
1195 LOG (GNUNET_ERROR_TYPE_INFO, "EK: %s\n",
1196 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
1197 LOG (GNUNET_ERROR_TYPE_INFO, "DK: %s\n",
1198 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
1204 * Create a new Key eXchange context for the tunnel.
1206 * If the old keys were verified, keep them for old traffic. Create a new KX
1207 * timestamp and a new nonce.
1209 * @param t Tunnel for which to create the KX ctx.
1212 create_kx_ctx (struct CadetTunnel *t)
1214 LOG (GNUNET_ERROR_TYPE_INFO, " new kx ctx for %s\n", GCT_2s (t));
1216 if (NULL != t->kx_ctx)
1218 if (NULL != t->kx_ctx->finish_task)
1220 LOG (GNUNET_ERROR_TYPE_INFO, " resetting exisiting finish task\n");
1221 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
1222 t->kx_ctx->finish_task = NULL;
1227 t->kx_ctx = GNUNET_new (struct CadetTunnelKXCtx);
1228 t->kx_ctx->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1232 if (CADET_TUNNEL_KEY_OK == t->estate)
1234 LOG (GNUNET_ERROR_TYPE_INFO, " backing up keys\n");
1235 t->kx_ctx->d_key_old = t->d_key;
1236 t->kx_ctx->e_key_old = t->e_key;
1239 LOG (GNUNET_ERROR_TYPE_INFO, " old keys not valid, not saving\n");
1240 t->kx_ctx->rekey_start_time = GNUNET_TIME_absolute_get ();
1246 * @brief Finish the Key eXchange and destroy the old keys.
1248 * @param cls Closure (Tunnel for which to finish the KX).
1249 * @param tc Task context.
1252 finish_kx (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1254 struct CadetTunnel *t = cls;
1256 LOG (GNUNET_ERROR_TYPE_INFO, "finish KX for %s\n", GCT_2s (t));
1258 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1260 LOG (GNUNET_ERROR_TYPE_INFO, " shutdown\n");
1264 GNUNET_free (t->kx_ctx);
1270 * Destroy a Key eXchange context for the tunnel. This function only schedules
1271 * the destruction, the freeing of the memory (and clearing of old key material)
1272 * happens after a delay!
1274 * @param t Tunnel whose KX ctx to destroy.
1277 destroy_kx_ctx (struct CadetTunnel *t)
1279 struct GNUNET_TIME_Relative delay;
1281 if (NULL == t->kx_ctx || NULL != t->kx_ctx->finish_task)
1284 if (is_key_null (&t->kx_ctx->e_key_old))
1286 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_now (finish_kx, t);
1290 delay = GNUNET_TIME_relative_divide (rekey_period, 4);
1291 delay = GNUNET_TIME_relative_min (delay, GNUNET_TIME_UNIT_MINUTES);
1293 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_delayed (delay, finish_kx, t);
1299 * Pick a connection on which send the next data message.
1301 * @param t Tunnel on which to send the message.
1303 * @return The connection on which to send the next message.
1305 static struct CadetConnection *
1306 tunnel_get_connection (struct CadetTunnel *t)
1308 struct CadetTConnection *iter;
1309 struct CadetConnection *best;
1311 unsigned int lowest_q;
1313 LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GCT_2s (t));
1315 lowest_q = UINT_MAX;
1316 for (iter = t->connection_head; NULL != iter; iter = iter->next)
1318 LOG (GNUNET_ERROR_TYPE_DEBUG, " connection %s: %u\n",
1319 GCC_2s (iter->c), GCC_get_state (iter->c));
1320 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
1322 qn = GCC_get_qn (iter->c, GCC_is_origin (iter->c, GNUNET_YES));
1323 LOG (GNUNET_ERROR_TYPE_DEBUG, " q_n %u, \n", qn);
1331 LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GCC_2s (best));
1337 * Callback called when a queued message is sent.
1339 * Calculates the average time and connection packet tracking.
1341 * @param cls Closure (TunnelQueue handle).
1342 * @param c Connection this message was on.
1343 * @param q Connection queue handle (unused).
1344 * @param type Type of message sent.
1345 * @param fwd Was this a FWD going message?
1346 * @param size Size of the message.
1349 tun_message_sent (void *cls,
1350 struct CadetConnection *c,
1351 struct CadetConnectionQueue *q,
1352 uint16_t type, int fwd, size_t size)
1354 struct CadetTunnelQueue *qt = cls;
1355 struct CadetTunnel *t;
1357 LOG (GNUNET_ERROR_TYPE_DEBUG, "tun_message_sent\n");
1359 GNUNET_assert (NULL != qt->cont);
1360 t = NULL == c ? NULL : GCC_get_tunnel (c);
1361 qt->cont (qt->cont_cls, t, qt, type, size);
1367 count_queued_data (const struct CadetTunnel *t)
1369 struct CadetTunnelDelayed *iter;
1372 for (count = 0, iter = t->tq_head; iter != NULL; iter = iter->next)
1379 * Delete a queued message: either was sent or the channel was destroyed
1380 * before the tunnel's key exchange had a chance to finish.
1382 * @param tqd Delayed queue handle.
1385 unqueue_data (struct CadetTunnelDelayed *tqd)
1387 GNUNET_CONTAINER_DLL_remove (tqd->t->tq_head, tqd->t->tq_tail, tqd);
1393 * Cache a message to be sent once tunnel is online.
1395 * @param t Tunnel to hold the message.
1396 * @param msg Message itself (copy will be made).
1398 static struct CadetTunnelDelayed *
1399 queue_data (struct CadetTunnel *t, const struct GNUNET_MessageHeader *msg)
1401 struct CadetTunnelDelayed *tqd;
1402 uint16_t size = ntohs (msg->size);
1404 LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GCT_2s (t));
1406 if (GNUNET_YES == is_ready (t))
1412 tqd = GNUNET_malloc (sizeof (struct CadetTunnelDelayed) + size);
1415 memcpy (&tqd[1], msg, size);
1416 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
1422 * Sends an already built message on a tunnel, encrypting it and
1423 * choosing the best connection.
1425 * @param message Message to send. Function modifies it.
1426 * @param t Tunnel on which this message is transmitted.
1427 * @param c Connection to use (autoselect if NULL).
1428 * @param force Force the tunnel to take the message (buffer overfill).
1429 * @param cont Continuation to call once message is really sent.
1430 * @param cont_cls Closure for @c cont.
1431 * @param existing_q In case this a transmission of previously queued data,
1432 * this should be TunnelQueue given to the client.
1435 * @return Handle to cancel message.
1436 * NULL if @c cont is NULL or an error happens and message is dropped.
1438 static struct CadetTunnelQueue *
1439 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1440 struct CadetTunnel *t, struct CadetConnection *c,
1441 int force, GCT_sent cont, void *cont_cls,
1442 struct CadetTunnelQueue *existing_q)
1444 struct CadetTunnelQueue *tq;
1445 struct GNUNET_CADET_Encrypted *msg;
1446 size_t size = ntohs (message->size);
1447 char cbuf[sizeof (struct GNUNET_CADET_Encrypted) + size];
1454 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GCT_2s (t));
1456 if (GNUNET_NO == is_ready (t))
1458 struct CadetTunnelDelayed *tqd;
1459 /* A non null existing_q indicates sending of queued data.
1460 * Should only happen after tunnel becomes ready.
1462 GNUNET_assert (NULL == existing_q);
1463 tqd = queue_data (t, message);
1466 tq = GNUNET_new (struct CadetTunnelQueue);
1470 tq->cont_cls = cont_cls;
1474 GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1476 iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1477 msg = (struct GNUNET_CADET_Encrypted *) cbuf;
1478 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
1481 if (CADET_Axolotl == t->enc_type)
1482 esize = t_ax_encrypt (t, &msg[1], message, size);
1484 esize = t_encrypt (t, &msg[1], message, size, iv, GNUNET_NO);
1485 GNUNET_assert (esize == size);
1486 t_hmac (&msg[1], size, iv, select_key (t), &msg->hmac);
1487 msg->header.size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
1490 c = tunnel_get_connection (t);
1493 /* Why is tunnel 'ready'? Should have been queued! */
1494 if (NULL != t->destroy_task)
1497 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1499 return NULL; /* Drop... */
1503 type = ntohs (message->type);
1506 case GNUNET_MESSAGE_TYPE_CADET_DATA:
1507 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1508 if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
1509 mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
1511 mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
1513 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1514 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1515 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1516 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1517 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1518 msg->cid = *GCC_get_id (c);
1519 msg->ttl = htonl (default_ttl);
1523 LOG (GNUNET_ERROR_TYPE_ERROR, "type %s not valid\n", GC_m2s (type));
1525 LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
1527 fwd = GCC_is_origin (c, GNUNET_YES);
1531 GNUNET_break (NULL == GCC_send_prebuilt_message (&msg->header, type, mid, c,
1532 fwd, force, NULL, NULL));
1535 if (NULL == existing_q)
1537 tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
1544 tq->cq = GCC_send_prebuilt_message (&msg->header, type, mid, c, fwd, force,
1545 &tun_message_sent, tq);
1546 GNUNET_assert (NULL != tq->cq);
1548 tq->cont_cls = cont_cls;
1555 * Send all cached messages that we can, tunnel is online.
1557 * @param t Tunnel that holds the messages. Cannot be loopback.
1560 send_queued_data (struct CadetTunnel *t)
1562 struct CadetTunnelDelayed *tqd;
1563 struct CadetTunnelDelayed *next;
1566 LOG (GNUNET_ERROR_TYPE_INFO, "Send queued data, tunnel %s\n", GCT_2s (t));
1568 if (GCT_is_loopback (t))
1574 if (GNUNET_NO == is_ready (t))
1576 LOG (GNUNET_ERROR_TYPE_DEBUG, " not ready yet: %s/%s\n",
1577 estate2s (t->estate), cstate2s (t->cstate));
1581 room = GCT_get_connections_buffer (t);
1582 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
1583 LOG (GNUNET_ERROR_TYPE_DEBUG, " tq head: %p\n", t->tq_head);
1584 for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
1586 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
1589 send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
1590 tqd->t, NULL, GNUNET_YES,
1591 NULL != tqd->tq ? tqd->tq->cont : NULL,
1592 NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
1596 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
1601 * Callback called when a queued message is sent.
1603 * @param cls Closure.
1604 * @param c Connection this message was on.
1605 * @param type Type of message sent.
1606 * @param fwd Was this a FWD going message?
1607 * @param size Size of the message.
1610 ephm_sent (void *cls,
1611 struct CadetConnection *c,
1612 struct CadetConnectionQueue *q,
1613 uint16_t type, int fwd, size_t size)
1615 struct CadetTunnel *t = cls;
1616 LOG (GNUNET_ERROR_TYPE_DEBUG, "ephemeral sent %s\n", GC_m2s (type));
1621 * Callback called when a queued message is sent.
1623 * @param cls Closure.
1624 * @param c Connection this message was on.
1625 * @param type Type of message sent.
1626 * @param fwd Was this a FWD going message?
1627 * @param size Size of the message.
1630 pong_sent (void *cls,
1631 struct CadetConnection *c,
1632 struct CadetConnectionQueue *q,
1633 uint16_t type, int fwd, size_t size)
1635 struct CadetTunnel *t = cls;
1636 LOG (GNUNET_ERROR_TYPE_DEBUG, "pong_sent %s\n", GC_m2s (type));
1642 * Sends key exchange message on a tunnel, choosing the best connection.
1643 * Should not be called on loopback tunnels.
1645 * @param t Tunnel on which this message is transmitted.
1646 * @param message Message to send. Function modifies it.
1648 * @return Handle to the message in the connection queue.
1650 static struct CadetConnectionQueue *
1651 send_kx (struct CadetTunnel *t,
1652 const struct GNUNET_MessageHeader *message)
1654 struct CadetConnection *c;
1655 struct GNUNET_CADET_KX *msg;
1656 size_t size = ntohs (message->size);
1657 char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
1662 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
1664 /* Avoid loopback. */
1665 if (GCT_is_loopback (t))
1670 type = ntohs (message->type);
1672 /* Even if tunnel is "being destroyed", send anyway.
1673 * Could be a response to a rekey initiated by remote peer,
1674 * who is trying to create a new channel!
1677 /* Must have a connection, or be looking for one. */
1678 if (NULL == t->connection_head)
1680 LOG (GNUNET_ERROR_TYPE_DEBUG, "%s with no connection\n", GC_m2s (type));
1681 if (CADET_TUNNEL_SEARCHING != t->cstate)
1684 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
1685 GCP_debug (t->peer, GNUNET_ERROR_TYPE_ERROR);
1690 msg = (struct GNUNET_CADET_KX *) cbuf;
1691 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
1692 msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
1693 c = tunnel_get_connection (t);
1696 if (NULL == t->destroy_task && CADET_TUNNEL_READY == t->cstate)
1699 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
1705 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
1706 case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
1707 GNUNET_assert (NULL == t->ephm_h);
1710 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
1711 GNUNET_assert (NULL == t->pong_h);
1716 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n", GC_m2s (type));
1719 memcpy (&msg[1], message, size);
1721 fwd = GCC_is_origin (c, GNUNET_YES);
1723 return GCC_send_prebuilt_message (&msg->header, type, 0, c,
1730 * Send the ephemeral key on a tunnel.
1732 * @param t Tunnel on which to send the key.
1735 send_ephemeral (struct CadetTunnel *t)
1737 LOG (GNUNET_ERROR_TYPE_INFO, "===> EPHM for %s\n", GCT_2s (t));
1738 if (NULL != t->ephm_h)
1740 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
1744 otr_kx_msg.sender_status = htonl (t->estate);
1745 otr_kx_msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1746 otr_kx_msg.nonce = t->kx_ctx->challenge;
1747 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce c %u\n", otr_kx_msg.nonce);
1748 t_encrypt (t, &otr_kx_msg.nonce, &otr_kx_msg.nonce,
1749 ping_encryption_size(), otr_kx_msg.iv, GNUNET_YES);
1750 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce e %u\n", otr_kx_msg.nonce);
1751 t->ephm_h = send_kx (t, &otr_kx_msg.header);
1756 * Send a pong message on a tunnel.
1758 * @param t Tunnel on which to send the pong.
1759 * @param challenge Value sent in the ping that we have to send back.
1762 send_pong (struct CadetTunnel *t, uint32_t challenge)
1764 struct GNUNET_CADET_KX_Pong msg;
1766 LOG (GNUNET_ERROR_TYPE_INFO, "===> PONG for %s\n", GCT_2s (t));
1767 if (NULL != t->pong_h)
1769 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
1772 msg.header.size = htons (sizeof (msg));
1773 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
1774 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1775 msg.nonce = challenge;
1776 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
1777 t_encrypt (t, &msg.nonce, &msg.nonce,
1778 sizeof (msg.nonce), msg.iv, GNUNET_YES);
1779 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
1781 t->pong_h = send_kx (t, &msg.header);
1786 * Initiate a rekey with the remote peer.
1788 * @param cls Closure (tunnel).
1789 * @param tc TaskContext.
1792 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1794 struct CadetTunnel *t = cls;
1796 t->rekey_task = NULL;
1798 LOG (GNUNET_ERROR_TYPE_INFO, "Re-key Tunnel %s\n", GCT_2s (t));
1799 if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1802 GNUNET_assert (NULL != t->kx_ctx);
1803 struct GNUNET_TIME_Relative duration;
1805 duration = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
1806 LOG (GNUNET_ERROR_TYPE_DEBUG, " kx started %s ago\n",
1807 GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
1809 // FIXME make duration of old keys configurable
1810 if (duration.rel_value_us >= GNUNET_TIME_UNIT_MINUTES.rel_value_us)
1812 LOG (GNUNET_ERROR_TYPE_DEBUG, " deleting old keys\n");
1813 memset (&t->kx_ctx->d_key_old, 0, sizeof (t->kx_ctx->d_key_old));
1814 memset (&t->kx_ctx->e_key_old, 0, sizeof (t->kx_ctx->e_key_old));
1821 case CADET_TUNNEL_KEY_UNINITIALIZED:
1822 GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
1825 case CADET_TUNNEL_KEY_SENT:
1828 case CADET_TUNNEL_KEY_OK:
1830 * - state should have changed during rekey_iterator
1831 * - task should have been canceled at pong_handle
1834 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
1837 case CADET_TUNNEL_KEY_PING:
1838 case CADET_TUNNEL_KEY_REKEY:
1842 LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
1845 // FIXME exponential backoff
1846 struct GNUNET_TIME_Relative delay;
1848 delay = GNUNET_TIME_relative_divide (rekey_period, 16);
1849 delay = GNUNET_TIME_relative_min (delay, REKEY_WAIT);
1850 LOG (GNUNET_ERROR_TYPE_DEBUG, " next call in %s\n",
1851 GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
1852 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1857 * Our ephemeral key has changed, create new session key on all tunnels.
1859 * Each tunnel will start the Key Exchange with a random delay between
1860 * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
1861 * per second, on average.
1863 * @param cls Closure (size of the hashmap).
1864 * @param key Current public key.
1865 * @param value Value in the hash map (tunnel).
1867 * @return #GNUNET_YES, so we should continue to iterate,
1870 rekey_iterator (void *cls,
1871 const struct GNUNET_PeerIdentity *key,
1874 struct CadetTunnel *t = value;
1875 struct GNUNET_TIME_Relative delay;
1876 long n = (long) cls;
1879 if (NULL != t->rekey_task)
1882 if (GNUNET_YES == GCT_is_loopback (t))
1885 r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
1886 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
1887 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1889 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
1896 * Create a new ephemeral key and key message, schedule next rekeying.
1898 * @param cls Closure (unused).
1899 * @param tc TaskContext.
1902 global_otr_rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1904 struct GNUNET_TIME_Absolute time;
1909 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1912 GNUNET_free_non_null (otr_ephemeral_key);
1913 otr_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
1915 time = GNUNET_TIME_absolute_get ();
1916 otr_kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
1917 time = GNUNET_TIME_absolute_add (time, rekey_period);
1918 time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
1919 otr_kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
1920 GNUNET_CRYPTO_ecdhe_key_get_public (otr_ephemeral_key, &otr_kx_msg.ephemeral_key);
1921 LOG (GNUNET_ERROR_TYPE_INFO, "GLOBAL OTR RE-KEY, NEW EPHM: %s\n",
1922 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
1924 GNUNET_assert (GNUNET_OK ==
1925 GNUNET_CRYPTO_eddsa_sign (id_key,
1926 &otr_kx_msg.purpose,
1927 &otr_kx_msg.signature));
1929 n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
1930 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
1932 rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period,
1933 &global_otr_rekey, NULL);
1938 * Called only on shutdown, destroy every tunnel.
1940 * @param cls Closure (unused).
1941 * @param key Current public key.
1942 * @param value Value in the hash map (tunnel).
1944 * @return #GNUNET_YES, so we should continue to iterate,
1947 destroy_iterator (void *cls,
1948 const struct GNUNET_PeerIdentity *key,
1951 struct CadetTunnel *t = value;
1953 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
1960 * Notify remote peer that we don't know a channel he is talking about,
1961 * probably CHANNEL_DESTROY was missed.
1963 * @param t Tunnel on which to notify.
1964 * @param gid ID of the channel.
1967 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
1969 struct GNUNET_CADET_ChannelManage msg;
1971 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
1972 msg.header.size = htons (sizeof (msg));
1973 msg.chid = htonl (gid);
1975 LOG (GNUNET_ERROR_TYPE_DEBUG,
1976 "WARNING destroying unknown channel %u on tunnel %s\n",
1978 send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
1983 * Demultiplex data per channel and call appropriate channel handler.
1985 * @param t Tunnel on which the data came.
1986 * @param msg Data message.
1987 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1988 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1989 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1990 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1993 handle_data (struct CadetTunnel *t,
1994 const struct GNUNET_CADET_Data *msg,
1997 struct CadetChannel *ch;
2001 size = ntohs (msg->header.size);
2003 sizeof (struct GNUNET_CADET_Data) +
2004 sizeof (struct GNUNET_MessageHeader))
2009 LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
2010 GC_m2s (ntohs (msg[1].header.type)));
2013 ch = GCT_get_channel (t, ntohl (msg->chid));
2016 GNUNET_STATISTICS_update (stats, "# data on unknown channel",
2018 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
2020 send_channel_destroy (t, ntohl (msg->chid));
2024 GCCH_handle_data (ch, msg, fwd);
2029 * Demultiplex data ACKs per channel and update appropriate channel buffer info.
2031 * @param t Tunnel on which the DATA ACK came.
2032 * @param msg DATA ACK message.
2033 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2034 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2035 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2036 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2039 handle_data_ack (struct CadetTunnel *t,
2040 const struct GNUNET_CADET_DataACK *msg,
2043 struct CadetChannel *ch;
2047 size = ntohs (msg->header.size);
2048 if (size != sizeof (struct GNUNET_CADET_DataACK))
2055 ch = GCT_get_channel (t, ntohl (msg->chid));
2058 GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
2060 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2065 GCCH_handle_data_ack (ch, msg, fwd);
2070 * Handle channel create.
2072 * @param t Tunnel on which the data came.
2073 * @param msg Data message.
2076 handle_ch_create (struct CadetTunnel *t,
2077 const struct GNUNET_CADET_ChannelCreate *msg)
2079 struct CadetChannel *ch;
2083 size = ntohs (msg->header.size);
2084 if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
2091 ch = GCT_get_channel (t, ntohl (msg->chid));
2092 if (NULL != ch && ! GCT_is_loopback (t))
2094 /* Probably a retransmission, safe to ignore */
2095 LOG (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
2097 ch = GCCH_handle_create (t, msg);
2099 GCT_add_channel (t, ch);
2105 * Handle channel NACK: check correctness and call channel handler for NACKs.
2107 * @param t Tunnel on which the NACK came.
2108 * @param msg NACK message.
2111 handle_ch_nack (struct CadetTunnel *t,
2112 const struct GNUNET_CADET_ChannelManage *msg)
2114 struct CadetChannel *ch;
2118 size = ntohs (msg->header.size);
2119 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2126 ch = GCT_get_channel (t, ntohl (msg->chid));
2129 GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
2131 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2136 GCCH_handle_nack (ch);
2141 * Handle a CHANNEL ACK (SYNACK/ACK).
2143 * @param t Tunnel on which the CHANNEL ACK came.
2144 * @param msg CHANNEL ACK message.
2145 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2146 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2147 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2148 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2151 handle_ch_ack (struct CadetTunnel *t,
2152 const struct GNUNET_CADET_ChannelManage *msg,
2155 struct CadetChannel *ch;
2159 size = ntohs (msg->header.size);
2160 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2167 ch = GCT_get_channel (t, ntohl (msg->chid));
2170 GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
2172 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2177 GCCH_handle_ack (ch, msg, fwd);
2182 * Handle a channel destruction message.
2184 * @param t Tunnel on which the message came.
2185 * @param msg Channel destroy message.
2186 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2187 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2188 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2189 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2192 handle_ch_destroy (struct CadetTunnel *t,
2193 const struct GNUNET_CADET_ChannelManage *msg,
2196 struct CadetChannel *ch;
2200 size = ntohs (msg->header.size);
2201 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2208 ch = GCT_get_channel (t, ntohl (msg->chid));
2211 /* Probably a retransmission, safe to ignore */
2215 GCCH_handle_destroy (ch, msg, fwd);
2220 * Create a new Axolotl ephemeral (ratchet) key.
2225 new_ephemeral (struct CadetTunnel *t)
2227 GNUNET_free_non_null (t->ax->DHRs);
2228 t->ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create();
2233 * Free Axolotl data.
2238 destroy_ax (struct CadetTunnel *t)
2243 GNUNET_free_non_null (t->ax->DHRs);
2244 GNUNET_free_non_null (t->ax->kx_0);
2246 GNUNET_free (t->ax);
2253 * The peer's ephemeral key has changed: update the symmetrical keys.
2255 * @param t Tunnel this message came on.
2256 * @param msg Key eXchange message.
2259 handle_ephemeral (struct CadetTunnel *t,
2260 const struct GNUNET_CADET_KX_Ephemeral *msg)
2262 LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
2264 if (GNUNET_OK != check_ephemeral (t, msg))
2266 GNUNET_break_op (0);
2270 /* If we get a proper OTR-style ephemeral, fallback to old crypto. */
2274 t->enc_type = CADET_Fallback;
2275 if (NULL != t->rekey_task)
2276 GNUNET_SCHEDULER_cancel (t->rekey_task);
2278 rekey_tunnel (t, NULL);
2282 * If the key is different from what we know, derive the new E/D keys.
2283 * Else destroy the rekey ctx (duplicate EPHM after successful KX).
2285 if (0 != memcmp (&t->peers_ephemeral_key, &msg->ephemeral_key,
2286 sizeof (msg->ephemeral_key)))
2288 #if DUMP_KEYS_TO_STDERR
2289 LOG (GNUNET_ERROR_TYPE_INFO, "OLD: %s\n",
2290 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
2291 LOG (GNUNET_ERROR_TYPE_INFO, "NEW: %s\n",
2292 GNUNET_h2s ((struct GNUNET_HashCode *) &msg->ephemeral_key));
2294 t->peers_ephemeral_key = msg->ephemeral_key;
2298 if (CADET_TUNNEL_KEY_OK == t->estate)
2300 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2302 if (NULL != t->rekey_task)
2303 GNUNET_SCHEDULER_cancel (t->rekey_task);
2304 t->rekey_task = GNUNET_SCHEDULER_add_now (rekey_tunnel, t);
2306 if (CADET_TUNNEL_KEY_SENT == t->estate)
2308 LOG (GNUNET_ERROR_TYPE_DEBUG, " our key was sent, sending challenge\n");
2310 GCT_change_estate (t, CADET_TUNNEL_KEY_PING);
2313 if (CADET_TUNNEL_KEY_UNINITIALIZED != ntohl(msg->sender_status))
2317 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce e %u\n", msg->nonce);
2318 t_decrypt (t, &nonce, &msg->nonce, ping_encryption_size (), msg->iv);
2319 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce c %u\n", nonce);
2320 send_pong (t, nonce);
2326 * Peer has answer to our challenge.
2327 * If answer is successful, consider the key exchange finished and clean
2328 * up all related state.
2330 * @param t Tunnel this message came on.
2331 * @param msg Key eXchange Pong message.
2334 handle_pong (struct CadetTunnel *t, const struct GNUNET_CADET_KX_Pong *msg)
2338 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
2339 if (NULL == t->rekey_task)
2341 GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
2344 if (NULL == t->kx_ctx)
2346 GNUNET_STATISTICS_update (stats, "# stray PONG messages", 1, GNUNET_NO);
2350 t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
2351 if (challenge != t->kx_ctx->challenge)
2353 LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
2354 LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
2355 challenge, msg->nonce, t->kx_ctx->challenge);
2359 GNUNET_SCHEDULER_cancel (t->rekey_task);
2360 t->rekey_task = NULL;
2362 /* Don't free the old keys right away, but after a delay.
2363 * Rationale: the KX could have happened over a very fast connection,
2364 * with payload traffic still signed with the old key stuck in a slower
2366 * Don't keep the keys longer than 1/4 the rekey period, and no longer than
2370 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2375 * Handle Axolotl handshake.
2377 * @param t Tunnel this message came on.
2378 * @param msg Key eXchange Pong message.
2381 handle_kx_ax (struct CadetTunnel *t, const struct GNUNET_CADET_AX_KX *msg)
2383 struct CadetTunnelAxolotl *ax;
2384 struct GNUNET_HashCode key_material[3];
2385 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
2386 const struct GNUNET_CRYPTO_EcdhePublicKey *pub;
2387 const struct GNUNET_CRYPTO_EcdhePrivateKey *priv;
2388 const char salt[] = "CADET Axolotl salt";
2389 const struct GNUNET_PeerIdentity *pid;
2392 LOG (GNUNET_ERROR_TYPE_INFO, "<=== AX_KX on %s\n", GCT_2s (t));
2396 /* Something is wrong if ax is NULL. Whose fault it is? */
2397 GNUNET_break_op (CADET_Fallback == t->enc_type);
2398 GNUNET_break (CADET_Axolotl == t->enc_type);
2402 if (GNUNET_OK != GCP_check_key (t->peer, &msg->permanent_key,
2403 &msg->purpose, &msg->signature))
2405 GNUNET_break_op (0);
2409 pid = GCT_get_destination (t);
2410 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2411 am_I_alice = GNUNET_YES;
2412 else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2413 am_I_alice = GNUNET_NO;
2416 GNUNET_break_op (0);
2420 LOG (GNUNET_ERROR_TYPE_INFO, " is Alice? %s\n", am_I_alice ? "YES" : "NO");
2423 ax->DHRr = msg->ratchet_key;
2426 if (GNUNET_YES == am_I_alice)
2428 priv = ax_key; /* A */
2429 pub = &msg->ephemeral_key; /* B0 */
2433 priv = ax->kx_0; /* B0 */
2434 pub = &msg->permanent_key; /* A */
2436 GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[0]);
2439 if (GNUNET_YES == am_I_alice)
2441 priv = ax->kx_0; /* A0 */
2442 pub = &msg->permanent_key; /* B */
2446 priv = ax_key; /* B */
2447 pub = &msg->ephemeral_key; /* A0 */
2449 GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[1]);
2452 priv = ax->kx_0; /* A0 or B0 */
2453 pub = &msg->ephemeral_key; /* B0 or A0 */
2454 GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[2]);
2456 #if DUMP_KEYS_TO_STDERR
2459 for (i = 0; i < 3; i++)
2460 LOG (GNUNET_ERROR_TYPE_INFO, "km[%u]: %s\n",
2461 i, GNUNET_h2s (&key_material[i]));
2466 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
2467 salt, sizeof (salt),
2468 &key_material, sizeof (key_material), NULL);
2471 if (GNUNET_YES == am_I_alice)
2477 ax->ratchet_flag = GNUNET_YES;
2485 ax->ratchet_flag = GNUNET_NO;
2491 * Demultiplex by message type and call appropriate handler for a message
2492 * towards a channel of a local tunnel.
2494 * @param t Tunnel this message came on.
2495 * @param msgh Message header.
2496 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2497 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2498 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2499 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2502 handle_decrypted (struct CadetTunnel *t,
2503 const struct GNUNET_MessageHeader *msgh,
2508 type = ntohs (msgh->type);
2509 LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
2513 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
2514 /* Do nothing, connection aleady got updated. */
2515 GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
2518 case GNUNET_MESSAGE_TYPE_CADET_DATA:
2519 /* Don't send hop ACK, wait for client to ACK */
2520 handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
2523 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
2524 handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
2527 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
2528 handle_ch_create (t, (struct GNUNET_CADET_ChannelCreate *) msgh);
2531 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
2532 handle_ch_nack (t, (struct GNUNET_CADET_ChannelManage *) msgh);
2535 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
2536 handle_ch_ack (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
2539 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
2540 handle_ch_destroy (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
2544 GNUNET_break_op (0);
2545 LOG (GNUNET_ERROR_TYPE_WARNING,
2546 "end-to-end message not known (%u)\n",
2547 ntohs (msgh->type));
2548 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
2552 /******************************************************************************/
2553 /******************************** API ***********************************/
2554 /******************************************************************************/
2556 * Decrypt old format and demultiplex by message type. Call appropriate handler
2557 * for a message towards a channel of a local tunnel.
2559 * @param t Tunnel this message came on.
2560 * @param msg Message header.
2563 GCT_handle_encrypted (struct CadetTunnel *t,
2564 const struct GNUNET_MessageHeader *msg)
2566 size_t size = ntohs (msg->size);
2567 size_t payload_size;
2570 uint16_t type = ntohs (msg->type);
2571 struct GNUNET_MessageHeader *msgh;
2574 if (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED == type)
2576 const struct GNUNET_CADET_Encrypted *emsg;
2578 emsg = (struct GNUNET_CADET_Encrypted *) msg;
2579 payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
2580 decrypted_size = t_decrypt_and_validate (t, cbuf, &emsg[1], payload_size,
2581 emsg->iv, &emsg->hmac);
2583 else if (GNUNET_MESSAGE_TYPE_CADET_AX == type)
2585 const struct GNUNET_CADET_AX *emsg;
2587 emsg = (struct GNUNET_CADET_AX *) msg;
2588 payload_size = size - sizeof (struct GNUNET_CADET_AX);
2589 decrypted_size = t_ax_decrypt_and_validate (t, cbuf, &emsg[1],
2590 payload_size, &emsg->hmac);
2593 if (-1 == decrypted_size)
2595 GNUNET_break_op (0);
2600 while (off < decrypted_size)
2604 msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
2605 msize = ntohs (msgh->size);
2606 if (msize < sizeof (struct GNUNET_MessageHeader))
2608 GNUNET_break_op (0);
2611 handle_decrypted (t, msgh, GNUNET_SYSERR);
2618 * Demultiplex an encapsulated KX message by message type.
2620 * @param t Tunnel on which the message came.
2621 * @param message Payload of KX message.
2624 GCT_handle_kx (struct CadetTunnel *t,
2625 const struct GNUNET_MessageHeader *message)
2629 type = ntohs (message->type);
2630 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received: %s\n", GC_m2s (type));
2633 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
2634 handle_ephemeral (t, (const struct GNUNET_CADET_KX_Ephemeral *) message);
2637 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
2638 handle_pong (t, (const struct GNUNET_CADET_KX_Pong *) message);
2641 case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
2642 handle_kx_ax (t, (const struct GNUNET_CADET_AX_KX *) message);
2646 GNUNET_break_op (0);
2647 LOG (GNUNET_ERROR_TYPE_WARNING, "kx message %s unknown\n", GC_m2s (type));
2652 * Initialize the tunnel subsystem.
2654 * @param c Configuration handle.
2655 * @param key ECC private key, to derive all other keys and do crypto.
2658 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
2659 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
2661 int expected_overhead;
2663 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
2665 expected_overhead = 0;
2666 expected_overhead += sizeof (struct GNUNET_CADET_Encrypted);
2667 expected_overhead += sizeof (struct GNUNET_CADET_Data);
2668 expected_overhead += sizeof (struct GNUNET_CADET_ACK);
2669 GNUNET_assert (GNUNET_CONSTANTS_CADET_P2P_OVERHEAD == expected_overhead);
2672 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
2675 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
2676 "CADET", "DEFAULT_TTL", "USING DEFAULT");
2680 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
2683 rekey_period = GNUNET_TIME_UNIT_DAYS;
2688 otr_kx_msg.header.size = htons (sizeof (otr_kx_msg));
2689 otr_kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
2690 otr_kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
2691 otr_kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
2692 otr_kx_msg.origin_identity = my_full_id;
2693 rekey_task = GNUNET_SCHEDULER_add_now (&global_otr_rekey, NULL);
2695 ax_key = GNUNET_CRYPTO_ecdhe_key_create ();
2696 GNUNET_CRYPTO_ecdhe_key_get_public (ax_key, &ax_identity.permanent_key);
2697 ax_identity.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_AXKX);
2698 ax_identity.purpose.size = htonl (ax_purpose_size ());
2699 GNUNET_assert (GNUNET_OK ==
2700 GNUNET_CRYPTO_eddsa_sign (id_key,
2701 &ax_identity.purpose,
2702 &ax_identity.signature));
2704 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
2709 * Shut down the tunnel subsystem.
2714 if (NULL != rekey_task)
2716 GNUNET_SCHEDULER_cancel (rekey_task);
2719 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
2720 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
2721 GNUNET_free (ax_key);
2728 * @param destination Peer this tunnel is towards.
2730 struct CadetTunnel *
2731 GCT_new (struct CadetPeer *destination)
2733 struct CadetTunnel *t;
2735 t = GNUNET_new (struct CadetTunnel);
2737 t->peer = destination;
2740 GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
2741 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2747 t->ax = GNUNET_new (struct CadetTunnelAxolotl);
2749 t->ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
2755 * Change the tunnel's connection state.
2757 * @param t Tunnel whose connection state to change.
2758 * @param cstate New connection state.
2761 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
2765 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
2766 GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
2767 if (myid != GCP_get_short_id (t->peer) &&
2768 CADET_TUNNEL_READY != t->cstate &&
2769 CADET_TUNNEL_READY == cstate)
2772 if (CADET_TUNNEL_KEY_OK == t->estate)
2774 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered send queued data\n");
2775 send_queued_data (t);
2777 else if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
2779 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered kx\n");
2784 LOG (GNUNET_ERROR_TYPE_DEBUG, "estate %s\n", estate2s (t->estate));
2789 if (CADET_TUNNEL_READY == cstate
2790 && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
2792 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered stop dht\n");
2793 GCP_stop_search (t->peer);
2799 * Change the tunnel encryption state.
2801 * @param t Tunnel whose encryption state to change, or NULL.
2802 * @param state New encryption state.
2805 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
2807 enum CadetTunnelEState old;
2814 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate was %s\n",
2815 GCP_2s (t->peer), estate2s (old));
2816 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate is now %s\n",
2817 GCP_2s (t->peer), estate2s (t->estate));
2819 /* Send queued data if enc state changes to OK */
2820 if (myid != GCP_get_short_id (t->peer) &&
2821 CADET_TUNNEL_KEY_OK != old && CADET_TUNNEL_KEY_OK == t->estate)
2823 send_queued_data (t);
2829 * @brief Check if tunnel has too many connections, and remove one if necessary.
2831 * Currently this means the newest connection, unless it is a direct one.
2832 * Implemented as a task to avoid freeing a connection that is in the middle
2833 * of being created/processed.
2835 * @param cls Closure (Tunnel to check).
2836 * @param tc Task context.
2839 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2841 struct CadetTunnel *t = cls;
2843 t->trim_connections_task = NULL;
2845 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2848 if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
2850 struct CadetTConnection *iter;
2851 struct CadetTConnection *c;
2853 for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
2855 if ((iter->created.abs_value_us > c->created.abs_value_us)
2856 && GNUNET_NO == GCC_is_direct (iter->c))
2863 LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
2865 LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
2878 * Add a connection to a tunnel.
2881 * @param c Connection.
2884 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
2886 struct CadetTConnection *aux;
2888 GNUNET_assert (NULL != c);
2890 LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
2891 LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
2892 for (aux = t->connection_head; aux != NULL; aux = aux->next)
2896 aux = GNUNET_new (struct CadetTConnection);
2898 aux->created = GNUNET_TIME_absolute_get ();
2900 GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
2902 if (CADET_TUNNEL_SEARCHING == t->cstate)
2903 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
2905 if (NULL != t->trim_connections_task)
2906 t->trim_connections_task = GNUNET_SCHEDULER_add_now (&trim_connections, t);
2911 * Remove a connection from a tunnel.
2914 * @param c Connection.
2917 GCT_remove_connection (struct CadetTunnel *t,
2918 struct CadetConnection *c)
2920 struct CadetTConnection *aux;
2921 struct CadetTConnection *next;
2924 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
2925 GCC_2s (c), GCT_2s (t));
2926 for (aux = t->connection_head; aux != NULL; aux = next)
2931 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
2936 conns = GCT_count_connections (t);
2938 && NULL == t->destroy_task
2939 && CADET_TUNNEL_SHUTDOWN != t->cstate
2940 && GNUNET_NO == shutting_down)
2942 if (0 == GCT_count_any_connections (t))
2943 GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
2945 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
2948 /* Start new connections if needed */
2949 if (CONNECTIONS_PER_TUNNEL > conns
2950 && NULL == t->destroy_task
2951 && CADET_TUNNEL_SHUTDOWN != t->cstate
2952 && GNUNET_NO == shutting_down)
2954 LOG (GNUNET_ERROR_TYPE_DEBUG, " too few connections, getting new ones\n");
2955 GCP_connect (t->peer); /* Will change cstate to WAITING when possible */
2959 /* If not marked as ready, no change is needed */
2960 if (CADET_TUNNEL_READY != t->cstate)
2963 /* Check if any connection is ready to maintain cstate */
2964 for (aux = t->connection_head; aux != NULL; aux = aux->next)
2965 if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
2971 * Add a channel to a tunnel.
2974 * @param ch Channel.
2977 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2979 struct CadetTChannel *aux;
2981 GNUNET_assert (NULL != ch);
2983 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
2985 for (aux = t->channel_head; aux != NULL; aux = aux->next)
2987 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
2992 aux = GNUNET_new (struct CadetTChannel);
2994 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
2995 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
2997 if (NULL != t->destroy_task)
2999 GNUNET_SCHEDULER_cancel (t->destroy_task);
3000 t->destroy_task = NULL;
3001 LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
3007 * Remove a channel from a tunnel.
3010 * @param ch Channel.
3013 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3015 struct CadetTChannel *aux;
3017 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
3018 for (aux = t->channel_head; aux != NULL; aux = aux->next)
3022 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
3023 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
3032 * Search for a channel by global ID.
3034 * @param t Tunnel containing the channel.
3035 * @param chid Public channel number.
3037 * @return channel handler, NULL if doesn't exist
3039 struct CadetChannel *
3040 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
3042 struct CadetTChannel *iter;
3047 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3049 if (GCCH_get_id (iter->ch) == chid)
3053 return NULL == iter ? NULL : iter->ch;
3058 * @brief Destroy a tunnel and free all resources.
3060 * Should only be called a while after the tunnel has been marked as destroyed,
3061 * in case there is a new channel added to the same peer shortly after marking
3062 * the tunnel. This way we avoid a new public key handshake.
3064 * @param cls Closure (tunnel to destroy).
3065 * @param tc Task context.
3068 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3070 struct CadetTunnel *t = cls;
3071 struct CadetTConnection *iter;
3073 LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
3074 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
3076 LOG (GNUNET_ERROR_TYPE_WARNING,
3077 "Not destroying tunnel, due to shutdown. "
3078 "Tunnel at %p should have been freed by GCT_shutdown\n", t);
3081 t->destroy_task = NULL;
3082 t->cstate = CADET_TUNNEL_SHUTDOWN;
3084 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3086 GCC_send_destroy (iter->c);
3093 * Tunnel is empty: destroy it.
3095 * Notifies all connections about the destruction.
3097 * @param t Tunnel to destroy.
3100 GCT_destroy_empty (struct CadetTunnel *t)
3102 if (GNUNET_YES == shutting_down)
3103 return; /* Will be destroyed immediately anyway */
3105 if (NULL != t->destroy_task)
3107 LOG (GNUNET_ERROR_TYPE_WARNING,
3108 "Tunnel %s is already scheduled for destruction. Tunnel debug dump:\n",
3110 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3112 /* should never happen, tunnel can only become empty once, and the
3113 * task identifier should be NO_TASK (cleaned when the tunnel was created
3114 * or became un-empty)
3119 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: scheduling destruction\n",
3122 // FIXME make delay a config option
3123 t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
3124 &delayed_destroy, t);
3125 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llu\n",
3126 t, t->destroy_task);
3131 * Destroy tunnel if empty (no more channels).
3133 * @param t Tunnel to destroy if empty.
3136 GCT_destroy_if_empty (struct CadetTunnel *t)
3138 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
3139 if (0 < GCT_count_channels (t))
3142 GCT_destroy_empty (t);
3147 * Destroy the tunnel.
3149 * This function does not generate any warning traffic to clients or peers.
3152 * Cancel messages belonging to this tunnel queued to neighbors.
3153 * Free any allocated resources linked to the tunnel.
3155 * @param t The tunnel to destroy.
3158 GCT_destroy (struct CadetTunnel *t)
3160 struct CadetTConnection *iter_c;
3161 struct CadetTConnection *next_c;
3162 struct CadetTChannel *iter_ch;
3163 struct CadetTChannel *next_ch;
3168 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
3170 GNUNET_break (GNUNET_YES ==
3171 GNUNET_CONTAINER_multipeermap_remove (tunnels,
3172 GCP_get_id (t->peer), t));
3174 for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
3176 next_c = iter_c->next;
3177 GCC_destroy (iter_c->c);
3179 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
3181 next_ch = iter_ch->next;
3182 GCCH_destroy (iter_ch->ch);
3183 /* Should only happen on shutdown, but it's ok. */
3186 if (NULL != t->destroy_task)
3188 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling dest: %llX\n", t->destroy_task);
3189 GNUNET_SCHEDULER_cancel (t->destroy_task);
3190 t->destroy_task = NULL;
3193 if (NULL != t->trim_connections_task)
3195 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling trim: %llX\n",
3196 t->trim_connections_task);
3197 GNUNET_SCHEDULER_cancel (t->trim_connections_task);
3198 t->trim_connections_task = NULL;
3201 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
3202 GCP_set_tunnel (t->peer, NULL);
3204 if (NULL != t->rekey_task)
3206 GNUNET_SCHEDULER_cancel (t->rekey_task);
3207 t->rekey_task = NULL;
3209 if (NULL != t->kx_ctx)
3211 if (NULL != t->kx_ctx->finish_task)
3212 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
3213 GNUNET_free (t->kx_ctx);
3224 * @brief Use the given path for the tunnel.
3225 * Update the next and prev hops (and RCs).
3226 * (Re)start the path refresh in case the tunnel is locally owned.
3228 * @param t Tunnel to update.
3229 * @param p Path to use.
3231 * @return Connection created.
3233 struct CadetConnection *
3234 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
3236 struct CadetConnection *c;
3237 struct GNUNET_CADET_Hash cid;
3238 unsigned int own_pos;
3240 if (NULL == t || NULL == p)
3246 if (CADET_TUNNEL_SHUTDOWN == t->cstate)
3252 for (own_pos = 0; own_pos < p->length; own_pos++)
3254 if (p->peers[own_pos] == myid)
3257 if (own_pos >= p->length)
3259 GNUNET_break_op (0);
3263 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
3264 c = GCC_new (&cid, t, p, own_pos);
3267 /* Path was flawed */
3270 GCT_add_connection (t, c);
3276 * Count all created connections of a tunnel. Not necessarily ready connections!
3278 * @param t Tunnel on which to count.
3280 * @return Number of connections created, either being established or ready.
3283 GCT_count_any_connections (struct CadetTunnel *t)
3285 struct CadetTConnection *iter;
3291 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3299 * Count established (ready) connections of a tunnel.
3301 * @param t Tunnel on which to count.
3303 * @return Number of connections.
3306 GCT_count_connections (struct CadetTunnel *t)
3308 struct CadetTConnection *iter;
3314 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3315 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
3323 * Count channels of a tunnel.
3325 * @param t Tunnel on which to count.
3327 * @return Number of channels.
3330 GCT_count_channels (struct CadetTunnel *t)
3332 struct CadetTChannel *iter;
3335 for (count = 0, iter = t->channel_head;
3337 iter = iter->next, count++) /* skip */;
3344 * Get the connectivity state of a tunnel.
3348 * @return Tunnel's connectivity state.
3350 enum CadetTunnelCState
3351 GCT_get_cstate (struct CadetTunnel *t)
3356 return (enum CadetTunnelCState) -1;
3363 * Get the encryption state of a tunnel.
3367 * @return Tunnel's encryption state.
3369 enum CadetTunnelEState
3370 GCT_get_estate (struct CadetTunnel *t)
3375 return (enum CadetTunnelEState) -1;
3381 * Get the maximum buffer space for a tunnel towards a local client.
3385 * @return Biggest buffer space offered by any channel in the tunnel.
3388 GCT_get_channels_buffer (struct CadetTunnel *t)
3390 struct CadetTChannel *iter;
3391 unsigned int buffer;
3392 unsigned int ch_buf;
3394 if (NULL == t->channel_head)
3396 /* Probably getting buffer for a channel create/handshake. */
3397 LOG (GNUNET_ERROR_TYPE_DEBUG, " no channels, allow max\n");
3402 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3404 ch_buf = get_channel_buffer (iter);
3405 if (ch_buf > buffer)
3413 * Get the total buffer space for a tunnel for P2P traffic.
3417 * @return Buffer space offered by all connections in the tunnel.
3420 GCT_get_connections_buffer (struct CadetTunnel *t)
3422 struct CadetTConnection *iter;
3423 unsigned int buffer;
3425 if (GNUNET_NO == is_ready (t))
3427 if (count_queued_data (t) > 3)
3434 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3436 if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
3440 buffer += get_connection_buffer (iter);
3448 * Get the tunnel's destination.
3452 * @return ID of the destination peer.
3454 const struct GNUNET_PeerIdentity *
3455 GCT_get_destination (struct CadetTunnel *t)
3457 return GCP_get_id (t->peer);
3462 * Get the tunnel's next free global channel ID.
3466 * @return GID of a channel free to use.
3469 GCT_get_next_chid (struct CadetTunnel *t)
3471 CADET_ChannelNumber chid;
3472 CADET_ChannelNumber mask;
3475 /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
3476 * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
3477 * If peer's ID is bigger, start at 0x4... bit 30 = 1
3479 result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
3484 t->next_chid |= mask;
3486 while (NULL != GCT_get_channel (t, t->next_chid))
3488 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
3489 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3490 t->next_chid |= mask;
3492 chid = t->next_chid;
3493 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3494 t->next_chid |= mask;
3501 * Send ACK on one or more channels due to buffer in connections.
3503 * @param t Channel which has some free buffer space.
3506 GCT_unchoke_channels (struct CadetTunnel *t)
3508 struct CadetTChannel *iter;
3509 unsigned int buffer;
3510 unsigned int channels = GCT_count_channels (t);
3511 unsigned int choked_n;
3512 struct CadetChannel *choked[channels];
3514 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
3515 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
3516 if (NULL != t->channel_head)
3517 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
3519 /* Get buffer space */
3520 buffer = GCT_get_connections_buffer (t);
3526 /* Count and remember choked channels */
3528 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3530 if (GNUNET_NO == get_channel_allowed (iter))
3532 choked[choked_n++] = iter->ch;
3536 /* Unchoke random channels */
3537 while (0 < buffer && 0 < choked_n)
3539 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3541 GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
3544 choked[r] = choked[choked_n];
3550 * Send ACK on one or more connections due to buffer space to the client.
3552 * Iterates all connections of the tunnel and sends ACKs appropriately.
3557 GCT_send_connection_acks (struct CadetTunnel *t)
3559 struct CadetTConnection *iter;
3562 uint32_t allow_per_connection;
3564 unsigned int buffer;
3566 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
3575 if (CADET_TUNNEL_READY != t->cstate)
3578 buffer = GCT_get_channels_buffer (t);
3579 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer %u\n", buffer);
3581 /* Count connections, how many messages are already allowed */
3582 cs = GCT_count_connections (t);
3583 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3585 allowed += get_connection_allowed (iter);
3587 LOG (GNUNET_ERROR_TYPE_DEBUG, " allowed %u\n", allowed);
3589 /* Make sure there is no overflow */
3590 if (allowed > buffer)
3593 /* Authorize connections to send more data */
3594 to_allow = buffer - allowed;
3596 for (iter = t->connection_head;
3597 NULL != iter && to_allow > 0;
3600 if (CADET_CONNECTION_READY != GCC_get_state (iter->c)
3601 || get_connection_allowed (iter) > 64 / 3)
3605 allow_per_connection = to_allow/cs;
3606 to_allow -= allow_per_connection;
3608 GCC_allow (iter->c, allow_per_connection,
3609 GCC_is_origin (iter->c, GNUNET_NO));
3614 /* Since we don't allow if it's allowed to send 64/3, this can happen. */
3615 LOG (GNUNET_ERROR_TYPE_DEBUG, " reminding to_allow: %u\n", to_allow);
3621 * Cancel a previously sent message while it's in the queue.
3623 * ONLY can be called before the continuation given to the send function
3624 * is called. Once the continuation is called, the message is no longer in the
3627 * @param q Handle to the queue.
3630 GCT_cancel (struct CadetTunnelQueue *q)
3635 /* tun_message_sent() will be called and free q */
3637 else if (NULL != q->tqd)
3639 unqueue_data (q->tqd);
3641 if (NULL != q->cont)
3642 q->cont (q->cont_cls, NULL, q, 0, 0);
3653 * Sends an already built message on a tunnel, encrypting it and
3654 * choosing the best connection if not provided.
3656 * @param message Message to send. Function modifies it.
3657 * @param t Tunnel on which this message is transmitted.
3658 * @param c Connection to use (autoselect if NULL).
3659 * @param force Force the tunnel to take the message (buffer overfill).
3660 * @param cont Continuation to call once message is really sent.
3661 * @param cont_cls Closure for @c cont.
3663 * @return Handle to cancel message. NULL if @c cont is NULL.
3665 struct CadetTunnelQueue *
3666 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
3667 struct CadetTunnel *t, struct CadetConnection *c,
3668 int force, GCT_sent cont, void *cont_cls)
3670 return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
3675 * Send an Axolotl KX message.
3677 * @param t Tunnel on which to send it.
3680 GCT_send_ax_kx (struct CadetTunnel *t)
3682 struct GNUNET_CADET_AX_KX msg;
3684 LOG (GNUNET_ERROR_TYPE_INFO, "===> AX_KX for %s\n", GCT_2s (t));
3686 msg.header.size = htons (sizeof (msg));
3687 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_AX_KX);
3688 msg.permanent_key = ax_identity.permanent_key;
3689 msg.purpose = ax_identity.purpose;
3690 msg.signature = ax_identity.signature;
3691 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->kx_0, &msg.ephemeral_key);
3692 GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &msg.ratchet_key);
3694 t->ephm_h = send_kx (t, &msg.header);
3699 * Sends an already built and encrypted message on a tunnel, choosing the best
3700 * connection. Useful for re-queueing messages queued on a destroyed connection.
3702 * @param message Message to send. Function modifies it.
3703 * @param t Tunnel on which this message is transmitted.
3706 GCT_resend_message (const struct GNUNET_MessageHeader *message,
3707 struct CadetTunnel *t)
3709 struct CadetConnection *c;
3712 c = tunnel_get_connection (t);
3715 /* TODO queue in tunnel, marked as encrypted */
3716 LOG (GNUNET_ERROR_TYPE_DEBUG, "No connection available, dropping.\n");
3719 fwd = GCC_is_origin (c, GNUNET_YES);
3720 GNUNET_break (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
3721 GNUNET_YES, NULL, NULL));
3726 * Is the tunnel directed towards the local peer?
3730 * @return #GNUNET_YES if it is loopback.
3733 GCT_is_loopback (const struct CadetTunnel *t)
3735 return (myid == GCP_get_short_id (t->peer));
3740 * Is the tunnel this path already?
3745 * @return #GNUNET_YES a connection uses this path.
3748 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
3750 struct CadetTConnection *iter;
3752 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3753 if (path_equivalent (GCC_get_path (iter->c), p))
3761 * Get a cost of a path for a tunnel considering existing connections.
3764 * @param path Candidate path.
3766 * @return Cost of the path (path length + number of overlapping nodes)
3769 GCT_get_path_cost (const struct CadetTunnel *t,
3770 const struct CadetPeerPath *path)
3772 struct CadetTConnection *iter;
3773 const struct CadetPeerPath *aux;
3774 unsigned int overlap;
3782 GNUNET_assert (NULL != t);
3784 for (i = 0; i < path->length; i++)
3786 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3788 aux = GCC_get_path (iter->c);
3792 for (j = 0; j < aux->length; j++)
3794 if (path->peers[i] == aux->peers[j])
3802 return path->length + overlap;
3807 * Get the static string for the peer this tunnel is directed.
3811 * @return Static string the destination peer's ID.
3814 GCT_2s (const struct CadetTunnel *t)
3819 return GCP_2s (t->peer);
3823 /******************************************************************************/
3824 /***************************** INFO/DEBUG *******************************/
3825 /******************************************************************************/
3828 * Log all possible info about the tunnel state.
3830 * @param t Tunnel to debug.
3831 * @param level Debug level to use.
3834 GCT_debug (const struct CadetTunnel *t, enum GNUNET_ErrorType level)
3836 struct CadetTChannel *iterch;
3837 struct CadetTConnection *iterc;
3840 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
3842 __FILE__, __FUNCTION__, __LINE__);
3846 LOG2 (level, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
3847 LOG2 (level, "TTT cstate %s, estate %s\n",
3848 cstate2s (t->cstate), estate2s (t->estate));
3849 LOG2 (level, "TTT kx_ctx %p, rekey_task %u, finish task %u\n",
3850 t->kx_ctx, t->rekey_task, t->kx_ctx ? t->kx_ctx->finish_task : 0);
3851 #if DUMP_KEYS_TO_STDERR
3852 LOG2 (level, "TTT my EPHM\t %s\n",
3853 GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
3854 LOG2 (level, "TTT peers EPHM:\t %s\n",
3855 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
3856 LOG2 (level, "TTT ENC key:\t %s\n",
3857 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
3858 LOG2 (level, "TTT DEC key:\t %s\n",
3859 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
3862 LOG2 (level, "TTT OLD ENC key:\t %s\n",
3863 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->e_key_old));
3864 LOG2 (level, "TTT OLD DEC key:\t %s\n",
3865 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->d_key_old));
3868 LOG2 (level, "TTT tq_head %p, tq_tail %p\n", t->tq_head, t->tq_tail);
3869 LOG2 (level, "TTT destroy %u\n", t->destroy_task);
3871 LOG2 (level, "TTT channels:\n");
3872 for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
3874 LOG2 (level, "TTT - %s\n", GCCH_2s (iterch->ch));
3877 LOG2 (level, "TTT connections:\n");
3878 for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
3880 GCC_debug (iterc->c, level);
3883 LOG2 (level, "TTT DEBUG TUNNEL END\n");
3888 * Iterate all tunnels.
3890 * @param iter Iterator.
3891 * @param cls Closure for @c iter.
3894 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
3896 GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
3901 * Count all tunnels.
3903 * @return Number of tunnels to remote peers kept by this peer.
3906 GCT_count_all (void)
3908 return GNUNET_CONTAINER_multipeermap_size (tunnels);
3913 * Iterate all connections of a tunnel.
3915 * @param t Tunnel whose connections to iterate.
3916 * @param iter Iterator.
3917 * @param cls Closure for @c iter.
3920 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
3922 struct CadetTConnection *ct;
3924 for (ct = t->connection_head; NULL != ct; ct = ct->next)
3930 * Iterate all channels of a tunnel.
3932 * @param t Tunnel whose channels to iterate.
3933 * @param iter Iterator.
3934 * @param cls Closure for @c iter.
3937 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
3939 struct CadetTChannel *cht;
3941 for (cht = t->channel_head; NULL != cht; cht = cht->next)
3942 iter (cls, cht->ch);