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.
419 /******************************************************************************/
420 /******************************* GLOBALS ***********************************/
421 /******************************************************************************/
424 * Global handle to the statistics service.
426 extern struct GNUNET_STATISTICS_Handle *stats;
429 * Local peer own ID (memory efficient handle).
431 extern GNUNET_PEER_Id myid;
434 * Local peer own ID (full value).
436 extern struct GNUNET_PeerIdentity my_full_id;
440 * Don't try to recover tunnels if shutting down.
442 extern int shutting_down;
446 * Set of all tunnels, in order to trigger a new exchange on rekey.
447 * Indexed by peer's ID.
449 static struct GNUNET_CONTAINER_MultiPeerMap *tunnels;
452 * Default TTL for payload packets.
454 static unsigned long long default_ttl;
459 const static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
462 * Own Axolotl private key (derived from @a my_private_key).
464 const struct GNUNET_CRYPTO_EcdhePrivateKey *ax_identity;
467 * Own OTR ephemeral private key.
469 static struct GNUNET_CRYPTO_EcdhePrivateKey *my_ephemeral_key;
472 * Cached message used to perform a key exchange.
474 static struct GNUNET_CADET_KX_Ephemeral kx_msg;
477 * Task to generate a new ephemeral key.
479 static struct GNUNET_SCHEDULER_Task * rekey_task;
484 static struct GNUNET_TIME_Relative rekey_period;
487 /******************************************************************************/
488 /******************************** STATIC ***********************************/
489 /******************************************************************************/
492 * Get string description for tunnel connectivity state.
494 * @param cs Tunnel state.
496 * @return String representation.
499 cstate2s (enum CadetTunnelCState cs)
505 case CADET_TUNNEL_NEW:
506 return "CADET_TUNNEL_NEW";
507 case CADET_TUNNEL_SEARCHING:
508 return "CADET_TUNNEL_SEARCHING";
509 case CADET_TUNNEL_WAITING:
510 return "CADET_TUNNEL_WAITING";
511 case CADET_TUNNEL_READY:
512 return "CADET_TUNNEL_READY";
513 case CADET_TUNNEL_SHUTDOWN:
514 return "CADET_TUNNEL_SHUTDOWN";
516 SPRINTF (buf, "%u (UNKNOWN STATE)", cs);
524 * Get string description for tunnel encryption state.
526 * @param es Tunnel state.
528 * @return String representation.
531 estate2s (enum CadetTunnelEState es)
537 case CADET_TUNNEL_KEY_UNINITIALIZED:
538 return "CADET_TUNNEL_KEY_UNINITIALIZED";
539 case CADET_TUNNEL_KEY_SENT:
540 return "CADET_TUNNEL_KEY_SENT";
541 case CADET_TUNNEL_KEY_PING:
542 return "CADET_TUNNEL_KEY_PING";
543 case CADET_TUNNEL_KEY_OK:
544 return "CADET_TUNNEL_KEY_OK";
545 case CADET_TUNNEL_KEY_REKEY:
546 return "CADET_TUNNEL_KEY_REKEY";
548 SPRINTF (buf, "%u (UNKNOWN STATE)", es);
556 * @brief Check if tunnel is ready to send traffic.
558 * Tunnel must be connected and with encryption correctly set up.
560 * @param t Tunnel to check.
562 * @return #GNUNET_YES if ready, #GNUNET_NO otherwise
565 is_ready (struct CadetTunnel *t)
569 GCT_debug (t, GNUNET_ERROR_TYPE_DEBUG);
570 ready = CADET_TUNNEL_READY == t->cstate
571 && (CADET_TUNNEL_KEY_OK == t->estate
572 || CADET_TUNNEL_KEY_REKEY == t->estate);
573 ready = ready || GCT_is_loopback (t);
579 * Check if a key is invalid (NULL pointer or all 0)
581 * @param key Key to check.
583 * @return #GNUNET_YES if key is null, #GNUNET_NO if exists and is not 0.
586 is_key_null (struct GNUNET_CRYPTO_SymmetricSessionKey *key)
588 struct GNUNET_CRYPTO_SymmetricSessionKey null_key;
593 memset (&null_key, 0, sizeof (null_key));
594 if (0 == memcmp (key, &null_key, sizeof (null_key)))
601 * Ephemeral key message purpose size.
603 * @return Size of the part of the ephemeral key message that must be signed.
606 ephemeral_purpose_size (void)
608 return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
609 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
610 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
611 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
612 sizeof (struct GNUNET_PeerIdentity);
617 * Size of the encrypted part of a ping message.
619 * @return Size of the encrypted part of a ping message.
622 ping_encryption_size (void)
624 return sizeof (uint32_t);
629 * Get the channel's buffer. ONLY FOR NON-LOOPBACK CHANNELS!!
631 * @param tch Tunnel's channel handle.
633 * @return Amount of messages the channel can still buffer towards the client.
636 get_channel_buffer (const struct CadetTChannel *tch)
640 /* If channel is incoming, is terminal in the FWD direction and fwd is YES */
641 fwd = GCCH_is_terminal (tch->ch, GNUNET_YES);
643 return GCCH_get_buffer (tch->ch, fwd);
648 * Get the channel's allowance status.
650 * @param tch Tunnel's channel handle.
652 * @return #GNUNET_YES if we allowed the client to send data to us.
655 get_channel_allowed (const struct CadetTChannel *tch)
659 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
660 fwd = GCCH_is_origin (tch->ch, GNUNET_YES);
662 return GCCH_get_allowed (tch->ch, fwd);
667 * Get the connection's buffer.
669 * @param tc Tunnel's connection handle.
671 * @return Amount of messages the connection can still buffer.
674 get_connection_buffer (const struct CadetTConnection *tc)
678 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
679 fwd = GCC_is_origin (tc->c, GNUNET_YES);
681 return GCC_get_buffer (tc->c, fwd);
686 * Get the connection's allowance.
688 * @param tc Tunnel's connection handle.
690 * @return Amount of messages we have allowed the next peer to send us.
693 get_connection_allowed (const struct CadetTConnection *tc)
697 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
698 fwd = GCC_is_origin (tc->c, GNUNET_YES);
700 return GCC_get_allowed (tc->c, fwd);
705 * Check that a ephemeral key message s well formed and correctly signed.
707 * @param t Tunnel on which the message came.
708 * @param msg The ephemeral key message.
710 * @return GNUNET_OK if message is fine, GNUNET_SYSERR otherwise.
713 check_ephemeral (struct CadetTunnel *t,
714 const struct GNUNET_CADET_KX_Ephemeral *msg)
716 /* Check message size */
717 if (ntohs (msg->header.size) != sizeof (struct GNUNET_CADET_KX_Ephemeral))
718 return GNUNET_SYSERR;
720 /* Check signature size */
721 if (ntohl (msg->purpose.size) != ephemeral_purpose_size ())
722 return GNUNET_SYSERR;
725 if (0 != memcmp (&msg->origin_identity,
726 GCP_get_id (t->peer),
727 sizeof (struct GNUNET_PeerIdentity)))
728 return GNUNET_SYSERR;
730 /* Check signature */
732 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_CADET_KX,
735 &msg->origin_identity.public_key))
736 return GNUNET_SYSERR;
743 * Select the best key to use for encryption (send), based on KX status.
745 * Normally, return the current key. If there is a KX in progress and the old
746 * key is fresh enough, return the old key.
748 * @param t Tunnel to choose the key from.
750 * @return The optimal key to encrypt/hmac outgoing traffic.
752 static const struct GNUNET_CRYPTO_SymmetricSessionKey *
753 select_key (const struct CadetTunnel *t)
755 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
757 if (NULL != t->kx_ctx
758 && NULL == t->kx_ctx->finish_task)
760 struct GNUNET_TIME_Relative age;
762 age = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
763 LOG (GNUNET_ERROR_TYPE_DEBUG,
764 " key exchange in progress, started %s ago\n",
765 GNUNET_STRINGS_relative_time_to_string (age, GNUNET_YES));
766 // FIXME make duration of old keys configurable
767 if (age.rel_value_us < GNUNET_TIME_UNIT_MINUTES.rel_value_us)
769 LOG (GNUNET_ERROR_TYPE_DEBUG, " using old key\n");
770 key = &t->kx_ctx->e_key_old;
774 LOG (GNUNET_ERROR_TYPE_DEBUG, " using new key (old key too old)\n");
780 LOG (GNUNET_ERROR_TYPE_DEBUG, " no KX: using current key\n");
790 * @param plaintext Content to HMAC.
791 * @param size Size of @c plaintext.
792 * @param iv Initialization vector for the message.
793 * @param key Key to use.
794 * @param hmac[out] Destination to store the HMAC.
797 t_hmac (const void *plaintext, size_t size,
798 uint32_t iv, const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
799 struct GNUNET_CADET_Hash *hmac)
801 static const char ctx[] = "cadet authentication key";
802 struct GNUNET_CRYPTO_AuthKey auth_key;
803 struct GNUNET_HashCode hash;
805 #if DUMP_KEYS_TO_STDERR
806 LOG (GNUNET_ERROR_TYPE_INFO, " HMAC with key %s\n",
807 GNUNET_h2s ((struct GNUNET_HashCode *) key));
809 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
814 /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
815 GNUNET_CRYPTO_hmac (&auth_key, plaintext, size, &hash);
816 memcpy (hmac, &hash, sizeof (*hmac));
821 * Encrypt daforce_newest_keyta with the tunnel key.
823 * @param t Tunnel whose key to use.
824 * @param dst Destination for the encrypted data.
825 * @param src Source of the plaintext. Can overlap with @c dst.
826 * @param size Size of the plaintext.
827 * @param iv Initialization Vector to use.
828 * @param force_newest_key Force the use of the newest key, otherwise
829 * CADET will use the old key when allowed.
830 * This can happen in the case when a KX is going on
831 * and the old one hasn't expired.
834 t_encrypt (struct CadetTunnel *t, void *dst, const void *src,
835 size_t size, uint32_t iv, int force_newest_key)
837 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
838 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
841 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt start\n");
843 key = GNUNET_YES == force_newest_key ? &t->e_key : select_key (t);
844 #if DUMP_KEYS_TO_STDERR
845 LOG (GNUNET_ERROR_TYPE_INFO, " ENC with key %s\n",
846 GNUNET_h2s ((struct GNUNET_HashCode *) key));
848 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
849 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt IV derived\n");
850 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, key, &siv, dst);
851 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt end\n");
858 * Generate a new key with a HMAC mechanism from the existing chain key.
860 * @param ax Axolotl context.
861 * @param key[out] Derived key.
862 * @param source Source key material (data to HMAC).
863 * @param len Length of @a source.
866 t_ax_hmac_hash (struct CadetTunnelAxolotl *ax,
867 struct GNUNET_CRYPTO_SymmetricSessionKey *key,
868 void *source, unsigned int len)
870 static const char ctx[] = "axolotl key derivation";
871 struct GNUNET_CRYPTO_AuthKey auth_key;
872 struct GNUNET_HashCode hash;
874 GNUNET_CRYPTO_hmac_derive_key (&auth_key, &ax->CKs,
877 GNUNET_CRYPTO_hmac (&auth_key, source, len, &hash);
878 GNUNET_CRYPTO_kdf (key, sizeof (*key),
880 &hash, sizeof (hash));
885 * Encrypt data with the tunnel key.
887 * @param t Tunnel whose key to use.
888 * @param dst Destination for the encrypted data.
889 * @param src Source of the plaintext. Can overlap with @c dst.
890 * @param size Size of the plaintext.
892 * @return Size of the encrypted data.
895 t_ax_encrypt (struct CadetTunnel *t, void *dst, const void *src, size_t size)
897 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
898 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
899 struct CadetTunnelAxolotl *ax;
902 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt start\n");
906 if (GNUNET_YES == ax->ratchet_flag)
908 /* Advance ratchet */
911 t_ax_hmac_hash (ax, &MK, "0", 1);
912 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &MK, NULL, 0, NULL);
914 #if DUMP_KEYS_TO_STDERR
915 LOG (GNUNET_ERROR_TYPE_INFO, " ENC with key %s\n",
916 GNUNET_h2s ((struct GNUNET_HashCode *) &MK));
919 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, &MK, &iv, dst);
921 t_ax_hmac_hash (ax, &ax->CKs, "1", 1);
923 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt end\n");
930 * Decrypt and verify data with the appropriate tunnel key.
932 * @param key Key to use.
933 * @param dst Destination for the plaintext.
934 * @param src Source of the encrypted data. Can overlap with @c dst.
935 * @param size Size of the encrypted data.
936 * @param iv Initialization Vector to use.
938 * @return Size of the decrypted data, -1 if an error was encountered.
941 decrypt (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
942 void *dst, const void *src, size_t size, uint32_t iv)
944 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
947 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt start\n");
948 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv\n");
949 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
950 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv done\n");
951 out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, key, &siv, dst);
952 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt end\n");
959 * Decrypt and verify data with the most recent tunnel key.
961 * @param t Tunnel whose key to use.
962 * @param dst Destination for the plaintext.
963 * @param src Source of the encrypted data. Can overlap with @c dst.
964 * @param size Size of the encrypted data.
965 * @param iv Initialization Vector to use.
967 * @return Size of the decrypted data, -1 if an error was encountered.
970 t_decrypt (struct CadetTunnel *t, void *dst, const void *src,
971 size_t size, uint32_t iv)
975 #if DUMP_KEYS_TO_STDERR
976 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_decrypt with %s\n",
977 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
979 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
981 GNUNET_STATISTICS_update (stats, "# non decryptable data", 1, GNUNET_NO);
982 LOG (GNUNET_ERROR_TYPE_WARNING,
983 "got data on %s without a valid key\n",
985 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
989 out_size = decrypt (&t->d_key, dst, src, size, iv);
996 * Decrypt and verify data with the appropriate tunnel key and verify that the
997 * data has not been altered since it was sent by the remote peer.
999 * @param t Tunnel whose key to use.
1000 * @param dst Destination for the plaintext.
1001 * @param src Source of the encrypted data. Can overlap with @c dst.
1002 * @param size Size of the encrypted data.
1003 * @param iv Initialization Vector to use.
1004 * @param msg_hmac HMAC of the message, cannot be NULL.
1006 * @return Size of the decrypted data, -1 if an error was encountered.
1009 t_decrypt_and_validate (struct CadetTunnel *t,
1010 void *dst, const void *src,
1011 size_t size, uint32_t iv,
1012 const struct GNUNET_CADET_Hash *msg_hmac)
1014 struct GNUNET_CRYPTO_SymmetricSessionKey *key;
1015 struct GNUNET_CADET_Hash hmac;
1018 /* Try primary (newest) key */
1020 decrypted_size = decrypt (key, dst, src, size, iv);
1021 t_hmac (src, size, iv, key, &hmac);
1022 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1023 return decrypted_size;
1025 /* If no key exchange is going on, we just failed. */
1026 if (NULL == t->kx_ctx)
1028 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1029 "Failed checksum validation on tunnel %s with no KX\n",
1031 GNUNET_STATISTICS_update (stats, "# wrong HMAC no KX", 1, GNUNET_NO);
1035 /* Try secondary key, from previous KX period. */
1036 key = &t->kx_ctx->d_key_old;
1037 decrypted_size = decrypt (key, dst, src, size, iv);
1038 t_hmac (src, size, iv, key, &hmac);
1039 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1040 return decrypted_size;
1042 /* Hail Mary, try tertiary, key, in case of parallel re-keys. */
1043 key = &t->kx_ctx->d_key_old2;
1044 decrypted_size = decrypt (key, dst, src, size, iv);
1045 t_hmac (src, size, iv, key, &hmac);
1046 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1047 return decrypted_size;
1049 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1050 "Failed checksum validation on tunnel %s with KX\n",
1052 GNUNET_STATISTICS_update (stats, "# wrong HMAC with KX", 1, GNUNET_NO);
1057 * Decrypt and verify data with the appropriate tunnel key and verify that the
1058 * data has not been altered since it was sent by the remote peer.
1060 * @param t Tunnel whose key to use.
1061 * @param dst Destination for the plaintext.
1062 * @param src Source of the encrypted data. Can overlap with @c dst.
1063 * @param size Size of the encrypted data.
1064 * @param msg_hmac HMAC of the message, cannot be NULL.
1066 * @return Size of the decrypted data, -1 if an error was encountered.
1069 t_ax_decrypt_and_validate (struct CadetTunnel *t,
1070 void *dst, const void *src, size_t size,
1071 const struct GNUNET_CADET_Hash *msg_hmac)
1073 struct CadetTunnelAxolotl *ax;
1088 * Create key material by doing ECDH on the local and remote ephemeral keys.
1090 * @param key_material Where to store the key material.
1091 * @param ephemeral_key Peer's public ephemeral key.
1094 derive_key_material (struct GNUNET_HashCode *key_material,
1095 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key)
1098 GNUNET_CRYPTO_ecc_ecdh (my_ephemeral_key,
1108 * Create a symmetic key from the identities of both ends and the key material
1111 * @param key Destination for the generated key.
1112 * @param sender ID of the peer that will encrypt with @c key.
1113 * @param receiver ID of the peer that will decrypt with @c key.
1114 * @param key_material Hash created with ECDH with the ephemeral keys.
1117 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
1118 const struct GNUNET_PeerIdentity *sender,
1119 const struct GNUNET_PeerIdentity *receiver,
1120 const struct GNUNET_HashCode *key_material)
1122 const char salt[] = "CADET kx salt";
1124 GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
1125 salt, sizeof (salt),
1126 key_material, sizeof (struct GNUNET_HashCode),
1127 sender, sizeof (struct GNUNET_PeerIdentity),
1128 receiver, sizeof (struct GNUNET_PeerIdentity),
1134 * Derive the tunnel's keys using our own and the peer's ephemeral keys.
1136 * @param t Tunnel for which to create the keys.
1139 create_keys (struct CadetTunnel *t)
1141 struct GNUNET_HashCode km;
1143 derive_key_material (&km, &t->peers_ephemeral_key);
1144 derive_symmertic (&t->e_key, &my_full_id, GCP_get_id (t->peer), &km);
1145 derive_symmertic (&t->d_key, GCP_get_id (t->peer), &my_full_id, &km);
1146 #if DUMP_KEYS_TO_STDERR
1147 LOG (GNUNET_ERROR_TYPE_INFO, "ME: %s\n",
1148 GNUNET_h2s ((struct GNUNET_HashCode *) &kx_msg.ephemeral_key));
1149 LOG (GNUNET_ERROR_TYPE_INFO, "PE: %s\n",
1150 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
1151 LOG (GNUNET_ERROR_TYPE_INFO, "KM: %s\n", GNUNET_h2s (&km));
1152 LOG (GNUNET_ERROR_TYPE_INFO, "EK: %s\n",
1153 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
1154 LOG (GNUNET_ERROR_TYPE_INFO, "DK: %s\n",
1155 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
1161 * Create a new Key eXchange context for the tunnel.
1163 * If the old keys were verified, keep them for old traffic. Create a new KX
1164 * timestamp and a new nonce.
1166 * @param t Tunnel for which to create the KX ctx.
1169 create_kx_ctx (struct CadetTunnel *t)
1171 LOG (GNUNET_ERROR_TYPE_INFO, " new kx ctx for %s\n", GCT_2s (t));
1173 if (NULL != t->kx_ctx)
1175 if (NULL != t->kx_ctx->finish_task)
1177 LOG (GNUNET_ERROR_TYPE_INFO, " resetting exisiting finish task\n");
1178 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
1179 t->kx_ctx->finish_task = NULL;
1184 t->kx_ctx = GNUNET_new (struct CadetTunnelKXCtx);
1185 t->kx_ctx->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1189 if (CADET_TUNNEL_KEY_OK == t->estate)
1191 LOG (GNUNET_ERROR_TYPE_INFO, " backing up keys\n");
1192 t->kx_ctx->d_key_old = t->d_key;
1193 t->kx_ctx->e_key_old = t->e_key;
1196 LOG (GNUNET_ERROR_TYPE_INFO, " old keys not valid, not saving\n");
1197 t->kx_ctx->rekey_start_time = GNUNET_TIME_absolute_get ();
1203 * @brief Finish the Key eXchange and destroy the old keys.
1205 * @param cls Closure (Tunnel for which to finish the KX).
1206 * @param tc Task context.
1209 finish_kx (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1211 struct CadetTunnel *t = cls;
1213 LOG (GNUNET_ERROR_TYPE_INFO, "finish KX for %s\n", GCT_2s (t));
1215 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1217 LOG (GNUNET_ERROR_TYPE_INFO, " shutdown\n");
1221 GNUNET_free (t->kx_ctx);
1227 * Destroy a Key eXchange context for the tunnel. This function only schedules
1228 * the destruction, the freeing of the memory (and clearing of old key material)
1229 * happens after a delay!
1231 * @param t Tunnel whose KX ctx to destroy.
1234 destroy_kx_ctx (struct CadetTunnel *t)
1236 struct GNUNET_TIME_Relative delay;
1238 if (NULL == t->kx_ctx || NULL != t->kx_ctx->finish_task)
1241 if (is_key_null (&t->kx_ctx->e_key_old))
1243 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_now (finish_kx, t);
1247 delay = GNUNET_TIME_relative_divide (rekey_period, 4);
1248 delay = GNUNET_TIME_relative_min (delay, GNUNET_TIME_UNIT_MINUTES);
1250 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_delayed (delay, finish_kx, t);
1256 * Pick a connection on which send the next data message.
1258 * @param t Tunnel on which to send the message.
1260 * @return The connection on which to send the next message.
1262 static struct CadetConnection *
1263 tunnel_get_connection (struct CadetTunnel *t)
1265 struct CadetTConnection *iter;
1266 struct CadetConnection *best;
1268 unsigned int lowest_q;
1270 LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GCT_2s (t));
1272 lowest_q = UINT_MAX;
1273 for (iter = t->connection_head; NULL != iter; iter = iter->next)
1275 LOG (GNUNET_ERROR_TYPE_DEBUG, " connection %s: %u\n",
1276 GCC_2s (iter->c), GCC_get_state (iter->c));
1277 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
1279 qn = GCC_get_qn (iter->c, GCC_is_origin (iter->c, GNUNET_YES));
1280 LOG (GNUNET_ERROR_TYPE_DEBUG, " q_n %u, \n", qn);
1288 LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GCC_2s (best));
1294 * Callback called when a queued message is sent.
1296 * Calculates the average time and connection packet tracking.
1298 * @param cls Closure (TunnelQueue handle).
1299 * @param c Connection this message was on.
1300 * @param q Connection queue handle (unused).
1301 * @param type Type of message sent.
1302 * @param fwd Was this a FWD going message?
1303 * @param size Size of the message.
1306 tun_message_sent (void *cls,
1307 struct CadetConnection *c,
1308 struct CadetConnectionQueue *q,
1309 uint16_t type, int fwd, size_t size)
1311 struct CadetTunnelQueue *qt = cls;
1312 struct CadetTunnel *t;
1314 LOG (GNUNET_ERROR_TYPE_DEBUG, "tun_message_sent\n");
1316 GNUNET_assert (NULL != qt->cont);
1317 t = NULL == c ? NULL : GCC_get_tunnel (c);
1318 qt->cont (qt->cont_cls, t, qt, type, size);
1324 count_queued_data (const struct CadetTunnel *t)
1326 struct CadetTunnelDelayed *iter;
1329 for (count = 0, iter = t->tq_head; iter != NULL; iter = iter->next)
1336 * Delete a queued message: either was sent or the channel was destroyed
1337 * before the tunnel's key exchange had a chance to finish.
1339 * @param tqd Delayed queue handle.
1342 unqueue_data (struct CadetTunnelDelayed *tqd)
1344 GNUNET_CONTAINER_DLL_remove (tqd->t->tq_head, tqd->t->tq_tail, tqd);
1350 * Cache a message to be sent once tunnel is online.
1352 * @param t Tunnel to hold the message.
1353 * @param msg Message itself (copy will be made).
1355 static struct CadetTunnelDelayed *
1356 queue_data (struct CadetTunnel *t, const struct GNUNET_MessageHeader *msg)
1358 struct CadetTunnelDelayed *tqd;
1359 uint16_t size = ntohs (msg->size);
1361 LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GCT_2s (t));
1363 if (GNUNET_YES == is_ready (t))
1369 tqd = GNUNET_malloc (sizeof (struct CadetTunnelDelayed) + size);
1372 memcpy (&tqd[1], msg, size);
1373 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
1379 * Sends an already built message on a tunnel, encrypting it and
1380 * choosing the best connection.
1382 * @param message Message to send. Function modifies it.
1383 * @param t Tunnel on which this message is transmitted.
1384 * @param c Connection to use (autoselect if NULL).
1385 * @param force Force the tunnel to take the message (buffer overfill).
1386 * @param cont Continuation to call once message is really sent.
1387 * @param cont_cls Closure for @c cont.
1388 * @param existing_q In case this a transmission of previously queued data,
1389 * this should be TunnelQueue given to the client.
1392 * @return Handle to cancel message.
1393 * NULL if @c cont is NULL or an error happens and message is dropped.
1395 static struct CadetTunnelQueue *
1396 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1397 struct CadetTunnel *t, struct CadetConnection *c,
1398 int force, GCT_sent cont, void *cont_cls,
1399 struct CadetTunnelQueue *existing_q)
1401 struct CadetTunnelQueue *tq;
1402 struct GNUNET_CADET_Encrypted *msg;
1403 size_t size = ntohs (message->size);
1404 char cbuf[sizeof (struct GNUNET_CADET_Encrypted) + size];
1411 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GCT_2s (t));
1413 if (GNUNET_NO == is_ready (t))
1415 struct CadetTunnelDelayed *tqd;
1416 /* A non null existing_q indicates sending of queued data.
1417 * Should only happen after tunnel becomes ready.
1419 GNUNET_assert (NULL == existing_q);
1420 tqd = queue_data (t, message);
1423 tq = GNUNET_new (struct CadetTunnelQueue);
1427 tq->cont_cls = cont_cls;
1431 GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1433 iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1434 msg = (struct GNUNET_CADET_Encrypted *) cbuf;
1435 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
1438 if (CADET_Axolotl == t->enc_type)
1439 esize = t_ax_encrypt (t, &msg[1], message, size);
1441 esize = t_encrypt (t, &msg[1], message, size, iv, GNUNET_NO);
1442 GNUNET_assert (esize == size);
1443 t_hmac (&msg[1], size, iv, select_key (t), &msg->hmac);
1444 msg->header.size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
1447 c = tunnel_get_connection (t);
1450 /* Why is tunnel 'ready'? Should have been queued! */
1451 if (NULL != t->destroy_task)
1454 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1456 return NULL; /* Drop... */
1460 type = ntohs (message->type);
1463 case GNUNET_MESSAGE_TYPE_CADET_DATA:
1464 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1465 if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
1466 mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
1468 mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
1470 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1471 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1472 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1473 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1474 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1475 msg->cid = *GCC_get_id (c);
1476 msg->ttl = htonl (default_ttl);
1480 LOG (GNUNET_ERROR_TYPE_ERROR, "type %s not valid\n", GC_m2s (type));
1482 LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
1484 fwd = GCC_is_origin (c, GNUNET_YES);
1488 GNUNET_break (NULL == GCC_send_prebuilt_message (&msg->header, type, mid, c,
1489 fwd, force, NULL, NULL));
1492 if (NULL == existing_q)
1494 tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
1501 tq->cq = GCC_send_prebuilt_message (&msg->header, type, mid, c, fwd, force,
1502 &tun_message_sent, tq);
1503 GNUNET_assert (NULL != tq->cq);
1505 tq->cont_cls = cont_cls;
1512 * Send all cached messages that we can, tunnel is online.
1514 * @param t Tunnel that holds the messages. Cannot be loopback.
1517 send_queued_data (struct CadetTunnel *t)
1519 struct CadetTunnelDelayed *tqd;
1520 struct CadetTunnelDelayed *next;
1523 LOG (GNUNET_ERROR_TYPE_INFO, "Send queued data, tunnel %s\n", GCT_2s (t));
1525 if (GCT_is_loopback (t))
1531 if (GNUNET_NO == is_ready (t))
1533 LOG (GNUNET_ERROR_TYPE_DEBUG, " not ready yet: %s/%s\n",
1534 estate2s (t->estate), cstate2s (t->cstate));
1538 room = GCT_get_connections_buffer (t);
1539 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
1540 LOG (GNUNET_ERROR_TYPE_DEBUG, " tq head: %p\n", t->tq_head);
1541 for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
1543 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
1546 send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
1547 tqd->t, NULL, GNUNET_YES,
1548 NULL != tqd->tq ? tqd->tq->cont : NULL,
1549 NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
1553 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
1558 * Callback called when a queued message is sent.
1560 * @param cls Closure.
1561 * @param c Connection this message was on.
1562 * @param type Type of message sent.
1563 * @param fwd Was this a FWD going message?
1564 * @param size Size of the message.
1567 ephm_sent (void *cls,
1568 struct CadetConnection *c,
1569 struct CadetConnectionQueue *q,
1570 uint16_t type, int fwd, size_t size)
1572 struct CadetTunnel *t = cls;
1573 LOG (GNUNET_ERROR_TYPE_DEBUG, "ephm_sent %s\n", GC_m2s (type));
1578 * Callback called when a queued message is sent.
1580 * @param cls Closure.
1581 * @param c Connection this message was on.
1582 * @param type Type of message sent.
1583 * @param fwd Was this a FWD going message?
1584 * @param size Size of the message.
1587 pong_sent (void *cls,
1588 struct CadetConnection *c,
1589 struct CadetConnectionQueue *q,
1590 uint16_t type, int fwd, size_t size)
1592 struct CadetTunnel *t = cls;
1593 LOG (GNUNET_ERROR_TYPE_DEBUG, "pong_sent %s\n", GC_m2s (type));
1599 * Sends key exchange message on a tunnel, choosing the best connection.
1600 * Should not be called on loopback tunnels.
1602 * @param t Tunnel on which this message is transmitted.
1603 * @param message Message to send. Function modifies it.
1605 * @return Handle to the message in the connection queue.
1607 static struct CadetConnectionQueue *
1608 send_kx (struct CadetTunnel *t,
1609 const struct GNUNET_MessageHeader *message)
1611 struct CadetConnection *c;
1612 struct GNUNET_CADET_KX *msg;
1613 size_t size = ntohs (message->size);
1614 char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
1619 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
1621 /* Avoid loopback. */
1622 if (GCT_is_loopback (t))
1624 LOG (GNUNET_ERROR_TYPE_DEBUG, " loopback!\n");
1628 type = ntohs (message->type);
1630 /* Even if tunnel is "being destroyed", send anyway.
1631 * Could be a response to a rekey initiated by remote peer,
1632 * who is trying to create a new channel!
1635 /* Must have a connection, or be looking for one. */
1636 if (NULL == t->connection_head)
1638 LOG (GNUNET_ERROR_TYPE_DEBUG, "%s while no connection\n", GC_m2s (type));
1639 if (CADET_TUNNEL_SEARCHING != t->cstate)
1642 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
1643 GCP_debug (t->peer, GNUNET_ERROR_TYPE_ERROR);
1648 msg = (struct GNUNET_CADET_KX *) cbuf;
1649 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
1650 msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
1651 c = tunnel_get_connection (t);
1654 if (NULL == t->destroy_task
1655 && CADET_TUNNEL_READY == t->cstate)
1658 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
1664 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
1665 GNUNET_assert (NULL == t->ephm_h);
1667 memcpy (&msg[1], message, size);
1669 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
1670 GNUNET_assert (NULL == t->pong_h);
1672 memcpy (&msg[1], message, size);
1676 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n", GC_m2s (type));
1680 fwd = GCC_is_origin (c, GNUNET_YES);
1682 return GCC_send_prebuilt_message (&msg->header, type, 0, c,
1689 * Send the ephemeral key on a tunnel.
1691 * @param t Tunnel on which to send the key.
1694 send_ephemeral (struct CadetTunnel *t)
1696 LOG (GNUNET_ERROR_TYPE_INFO, "===> EPHM for %s\n", GCT_2s (t));
1697 if (NULL != t->ephm_h)
1699 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
1703 kx_msg.sender_status = htonl (t->estate);
1704 kx_msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1705 kx_msg.nonce = t->kx_ctx->challenge;
1706 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce c %u\n", kx_msg.nonce);
1707 t_encrypt (t, &kx_msg.nonce, &kx_msg.nonce,
1708 ping_encryption_size(), kx_msg.iv, GNUNET_YES);
1709 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce e %u\n", kx_msg.nonce);
1710 t->ephm_h = send_kx (t, &kx_msg.header);
1715 * Send a pong message on a tunnel.
1717 * @param t Tunnel on which to send the pong.
1718 * @param challenge Value sent in the ping that we have to send back.
1721 send_pong (struct CadetTunnel *t, uint32_t challenge)
1723 struct GNUNET_CADET_KX_Pong msg;
1725 LOG (GNUNET_ERROR_TYPE_INFO, "===> PONG for %s\n", GCT_2s (t));
1726 if (NULL != t->pong_h)
1728 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
1731 msg.header.size = htons (sizeof (msg));
1732 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
1733 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1734 msg.nonce = challenge;
1735 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
1736 t_encrypt (t, &msg.nonce, &msg.nonce,
1737 sizeof (msg.nonce), msg.iv, GNUNET_YES);
1738 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
1740 t->pong_h = send_kx (t, &msg.header);
1745 * Initiate a rekey with the remote peer.
1747 * @param cls Closure (tunnel).
1748 * @param tc TaskContext.
1751 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1753 struct CadetTunnel *t = cls;
1755 t->rekey_task = NULL;
1757 LOG (GNUNET_ERROR_TYPE_INFO, "Re-key Tunnel %s\n", GCT_2s (t));
1758 if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1761 GNUNET_assert (NULL != t->kx_ctx);
1762 struct GNUNET_TIME_Relative duration;
1764 duration = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
1765 LOG (GNUNET_ERROR_TYPE_DEBUG, " kx started %s ago\n",
1766 GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
1768 // FIXME make duration of old keys configurable
1769 if (duration.rel_value_us >= GNUNET_TIME_UNIT_MINUTES.rel_value_us)
1771 LOG (GNUNET_ERROR_TYPE_DEBUG, " deleting old keys\n");
1772 memset (&t->kx_ctx->d_key_old, 0, sizeof (t->kx_ctx->d_key_old));
1773 memset (&t->kx_ctx->e_key_old, 0, sizeof (t->kx_ctx->e_key_old));
1780 case CADET_TUNNEL_KEY_UNINITIALIZED:
1781 GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
1784 case CADET_TUNNEL_KEY_SENT:
1787 case CADET_TUNNEL_KEY_OK:
1789 * - state should have changed during rekey_iterator
1790 * - task should have been canceled at pong_handle
1793 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
1796 case CADET_TUNNEL_KEY_PING:
1797 case CADET_TUNNEL_KEY_REKEY:
1801 LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
1804 // FIXME exponential backoff
1805 struct GNUNET_TIME_Relative delay;
1807 delay = GNUNET_TIME_relative_divide (rekey_period, 16);
1808 delay = GNUNET_TIME_relative_min (delay, REKEY_WAIT);
1809 LOG (GNUNET_ERROR_TYPE_DEBUG, " next call in %s\n",
1810 GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
1811 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1816 * Our ephemeral key has changed, create new session key on all tunnels.
1818 * Each tunnel will start the Key Exchange with a random delay between
1819 * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
1820 * per second, on average.
1822 * @param cls Closure (size of the hashmap).
1823 * @param key Current public key.
1824 * @param value Value in the hash map (tunnel).
1826 * @return #GNUNET_YES, so we should continue to iterate,
1829 rekey_iterator (void *cls,
1830 const struct GNUNET_PeerIdentity *key,
1833 struct CadetTunnel *t = value;
1834 struct GNUNET_TIME_Relative delay;
1835 long n = (long) cls;
1838 if (NULL != t->rekey_task)
1841 if (GNUNET_YES == GCT_is_loopback (t))
1844 r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
1845 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
1846 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1848 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
1855 * Create a new ephemeral key and key message, schedule next rekeying.
1857 * @param cls Closure (unused).
1858 * @param tc TaskContext.
1861 rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1863 struct GNUNET_TIME_Absolute time;
1868 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1871 GNUNET_free_non_null (my_ephemeral_key);
1872 my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
1874 time = GNUNET_TIME_absolute_get ();
1875 kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
1876 time = GNUNET_TIME_absolute_add (time, rekey_period);
1877 time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
1878 kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
1879 GNUNET_CRYPTO_ecdhe_key_get_public (my_ephemeral_key, &kx_msg.ephemeral_key);
1880 LOG (GNUNET_ERROR_TYPE_INFO, "GLOBAL RE-KEY, NEW EPHM: %s\n",
1881 GNUNET_h2s ((struct GNUNET_HashCode *) &kx_msg.ephemeral_key));
1883 GNUNET_assert (GNUNET_OK ==
1884 GNUNET_CRYPTO_eddsa_sign (my_private_key,
1886 &kx_msg.signature));
1888 n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
1889 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
1891 rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period, &rekey, NULL);
1896 * Called only on shutdown, destroy every tunnel.
1898 * @param cls Closure (unused).
1899 * @param key Current public key.
1900 * @param value Value in the hash map (tunnel).
1902 * @return #GNUNET_YES, so we should continue to iterate,
1905 destroy_iterator (void *cls,
1906 const struct GNUNET_PeerIdentity *key,
1909 struct CadetTunnel *t = value;
1911 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
1918 * Notify remote peer that we don't know a channel he is talking about,
1919 * probably CHANNEL_DESTROY was missed.
1921 * @param t Tunnel on which to notify.
1922 * @param gid ID of the channel.
1925 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
1927 struct GNUNET_CADET_ChannelManage msg;
1929 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
1930 msg.header.size = htons (sizeof (msg));
1931 msg.chid = htonl (gid);
1933 LOG (GNUNET_ERROR_TYPE_DEBUG,
1934 "WARNING destroying unknown channel %u on tunnel %s\n",
1936 send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
1941 * Demultiplex data per channel and call appropriate channel handler.
1943 * @param t Tunnel on which the data came.
1944 * @param msg Data message.
1945 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1946 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1947 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1948 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1951 handle_data (struct CadetTunnel *t,
1952 const struct GNUNET_CADET_Data *msg,
1955 struct CadetChannel *ch;
1959 size = ntohs (msg->header.size);
1961 sizeof (struct GNUNET_CADET_Data) +
1962 sizeof (struct GNUNET_MessageHeader))
1967 LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
1968 GC_m2s (ntohs (msg[1].header.type)));
1971 ch = GCT_get_channel (t, ntohl (msg->chid));
1974 GNUNET_STATISTICS_update (stats, "# data on unknown channel",
1976 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
1978 send_channel_destroy (t, ntohl (msg->chid));
1982 GCCH_handle_data (ch, msg, fwd);
1987 * Demultiplex data ACKs per channel and update appropriate channel buffer info.
1989 * @param t Tunnel on which the DATA ACK came.
1990 * @param msg DATA ACK message.
1991 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1992 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1993 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1994 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1997 handle_data_ack (struct CadetTunnel *t,
1998 const struct GNUNET_CADET_DataACK *msg,
2001 struct CadetChannel *ch;
2005 size = ntohs (msg->header.size);
2006 if (size != sizeof (struct GNUNET_CADET_DataACK))
2013 ch = GCT_get_channel (t, ntohl (msg->chid));
2016 GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
2018 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2023 GCCH_handle_data_ack (ch, msg, fwd);
2028 * Handle channel create.
2030 * @param t Tunnel on which the data came.
2031 * @param msg Data message.
2034 handle_ch_create (struct CadetTunnel *t,
2035 const struct GNUNET_CADET_ChannelCreate *msg)
2037 struct CadetChannel *ch;
2041 size = ntohs (msg->header.size);
2042 if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
2049 ch = GCT_get_channel (t, ntohl (msg->chid));
2050 if (NULL != ch && ! GCT_is_loopback (t))
2052 /* Probably a retransmission, safe to ignore */
2053 LOG (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
2055 ch = GCCH_handle_create (t, msg);
2057 GCT_add_channel (t, ch);
2063 * Handle channel NACK: check correctness and call channel handler for NACKs.
2065 * @param t Tunnel on which the NACK came.
2066 * @param msg NACK message.
2069 handle_ch_nack (struct CadetTunnel *t,
2070 const struct GNUNET_CADET_ChannelManage *msg)
2072 struct CadetChannel *ch;
2076 size = ntohs (msg->header.size);
2077 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2084 ch = GCT_get_channel (t, ntohl (msg->chid));
2087 GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
2089 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2094 GCCH_handle_nack (ch);
2099 * Handle a CHANNEL ACK (SYNACK/ACK).
2101 * @param t Tunnel on which the CHANNEL ACK came.
2102 * @param msg CHANNEL ACK message.
2103 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2104 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2105 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2106 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2109 handle_ch_ack (struct CadetTunnel *t,
2110 const struct GNUNET_CADET_ChannelManage *msg,
2113 struct CadetChannel *ch;
2117 size = ntohs (msg->header.size);
2118 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2125 ch = GCT_get_channel (t, ntohl (msg->chid));
2128 GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
2130 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2135 GCCH_handle_ack (ch, msg, fwd);
2140 * Handle a channel destruction message.
2142 * @param t Tunnel on which the message came.
2143 * @param msg Channel destroy message.
2144 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2145 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2146 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2147 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2150 handle_ch_destroy (struct CadetTunnel *t,
2151 const struct GNUNET_CADET_ChannelManage *msg,
2154 struct CadetChannel *ch;
2158 size = ntohs (msg->header.size);
2159 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2166 ch = GCT_get_channel (t, ntohl (msg->chid));
2169 /* Probably a retransmission, safe to ignore */
2173 GCCH_handle_destroy (ch, msg, fwd);
2178 * Create a new Axolotl ephemeral (ratchet) key.
2183 new_ephemeral (struct CadetTunnel *t)
2185 GNUNET_free_non_null (t->ax->DHRs);
2186 t->ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create();
2191 * Free Axolotl data.
2196 destroy_ax (struct CadetTunnel *t)
2201 GNUNET_free_non_null (t->ax->DHRs);
2202 GNUNET_free_non_null (t->ax->kx_0);
2204 GNUNET_free (t->ax);
2211 * The peer's ephemeral key has changed: update the symmetrical keys.
2213 * @param t Tunnel this message came on.
2214 * @param msg Key eXchange message.
2217 handle_ephemeral (struct CadetTunnel *t,
2218 const struct GNUNET_CADET_KX_Ephemeral *msg)
2220 LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
2222 if (GNUNET_OK != check_ephemeral (t, msg))
2224 GNUNET_break_op (0);
2228 /* If we get a proper OTR-style ephemeral, fallback to old crypto. */
2232 t->enc_type = CADET_Fallback;
2236 * If the key is different from what we know, derive the new E/D keys.
2237 * Else destroy the rekey ctx (duplicate EPHM after successful KX).
2239 if (0 != memcmp (&t->peers_ephemeral_key, &msg->ephemeral_key,
2240 sizeof (msg->ephemeral_key)))
2242 #if DUMP_KEYS_TO_STDERR
2243 LOG (GNUNET_ERROR_TYPE_INFO, "OLD: %s\n",
2244 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
2245 LOG (GNUNET_ERROR_TYPE_INFO, "NEW: %s\n",
2246 GNUNET_h2s ((struct GNUNET_HashCode *) &msg->ephemeral_key));
2248 t->peers_ephemeral_key = msg->ephemeral_key;
2252 if (CADET_TUNNEL_KEY_OK == t->estate)
2254 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2256 if (NULL != t->rekey_task)
2257 GNUNET_SCHEDULER_cancel (t->rekey_task);
2258 t->rekey_task = GNUNET_SCHEDULER_add_now (rekey_tunnel, t);
2260 if (CADET_TUNNEL_KEY_SENT == t->estate)
2262 LOG (GNUNET_ERROR_TYPE_DEBUG, " our key was sent, sending challenge\n");
2264 GCT_change_estate (t, CADET_TUNNEL_KEY_PING);
2267 if (CADET_TUNNEL_KEY_UNINITIALIZED != ntohl(msg->sender_status))
2271 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce e %u\n", msg->nonce);
2272 t_decrypt (t, &nonce, &msg->nonce, ping_encryption_size (), msg->iv);
2273 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce c %u\n", nonce);
2274 send_pong (t, nonce);
2280 * Peer has answer to our challenge.
2281 * If answer is successful, consider the key exchange finished and clean
2282 * up all related state.
2284 * @param t Tunnel this message came on.
2285 * @param msg Key eXchange Pong message.
2288 handle_pong (struct CadetTunnel *t, const struct GNUNET_CADET_KX_Pong *msg)
2292 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
2293 if (NULL == t->rekey_task)
2295 GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
2298 if (NULL == t->kx_ctx)
2300 GNUNET_STATISTICS_update (stats, "# stray PONG messages", 1, GNUNET_NO);
2304 t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
2305 if (challenge != t->kx_ctx->challenge)
2307 LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
2308 LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
2309 challenge, msg->nonce, t->kx_ctx->challenge);
2313 GNUNET_SCHEDULER_cancel (t->rekey_task);
2314 t->rekey_task = NULL;
2316 /* Don't free the old keys right away, but after a delay.
2317 * Rationale: the KX could have happened over a very fast connection,
2318 * with payload traffic still signed with the old key stuck in a slower
2320 * Don't keep the keys longer than 1/4 the rekey period, and no longer than
2324 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2336 * WARNING! DANGER! Do not use this if you don't know what you are doing!
2337 * Ask Christian Grothoff, Werner Koch, Dan Bernstein and $GOD!
2339 * Transform a private EdDSA key (peer's key) into a key usable by DH.
2341 * @param k Private EdDSA key to transform.
2343 * @return Private key for EC Diffie-Hellman.
2345 static const struct GNUNET_CRYPTO_EcdhePrivateKey *
2346 get_private_ecdhe_from_eddsa (const struct GNUNET_CRYPTO_EddsaPrivateKey *k)
2348 return (const struct GNUNET_CRYPTO_EcdhePrivateKey *) k;
2353 * WARNING! DANGER! Do not use this if you don't know what you are doing!
2354 * Ask Christian Grothoff, Werner Koch, Dan Bernstein and $GOD!
2356 * Transform a public EdDSA key (peer's key) into a key usable by DH.
2358 * @param k Public EdDSA key to transform (peer's ID).
2360 * @return Public key for EC Diffie-Hellman.
2362 static const struct GNUNET_CRYPTO_EcdhePublicKey *
2363 get_public_ecdhe_from_id (const struct GNUNET_PeerIdentity *id)
2365 return (const struct GNUNET_CRYPTO_EcdhePublicKey *) id;
2370 * Handle Axolotl handshake.
2372 * @param t Tunnel this message came on.
2373 * @param msg Key eXchange Pong message.
2376 handle_kx_ax (struct CadetTunnel *t, const struct GNUNET_CADET_AX_KX *msg)
2378 struct GNUNET_CRYPTO_EcdhePublicKey eph;
2379 struct CadetTunnelAxolotl *ax;
2380 struct GNUNET_HashCode key_material[3];
2381 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
2382 const struct GNUNET_CRYPTO_EcdhePublicKey *pub;
2383 const struct GNUNET_CRYPTO_EcdhePrivateKey *priv;
2384 const char salt[] = "CADET Axolotl salt";
2385 const struct GNUNET_PeerIdentity *pid;
2390 /* Something is wrong if ax is NULL. Whose fault it is? */
2391 GNUNET_break_op (CADET_Fallback == t->enc_type);
2392 GNUNET_break (CADET_Axolotl == t->enc_type);
2396 pid = GCT_get_destination (t);
2397 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2398 is_alice = GNUNET_YES;
2399 else if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2400 is_alice = GNUNET_NO;
2403 GNUNET_break_op (0);
2408 ax->DHRr = msg->ratchet_key;
2410 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs, &eph);
2411 if (0 != memcmp (&eph, &msg->peers_key, sizeof (eph)))
2418 if (GNUNET_YES == is_alice)
2420 priv = get_private_ecdhe_from_eddsa (my_private_key); /* A */
2421 pub = &msg->ephemeral_key; /* B0 */
2425 priv = ax->kx_0; /* B0 */
2426 pub = get_public_ecdhe_from_id (pid); /* A */
2428 GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[0]);
2431 if (GNUNET_YES == is_alice)
2433 priv = ax->kx_0; /* A0 */
2434 pub = get_public_ecdhe_from_id (pid); /* B */
2438 priv = get_private_ecdhe_from_eddsa (my_private_key); /* B */
2439 pub = &msg->ephemeral_key; /* A0 */
2441 GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[1]);
2444 priv = ax->kx_0; /* A0 or B0 */
2445 pub = &msg->ephemeral_key; /* B0 or A0 */
2446 GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[2]);
2449 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
2450 salt, sizeof (salt),
2451 key_material, sizeof (key_material), NULL);
2454 if (GNUNET_YES == is_alice)
2460 ax->ratchet_flag = GNUNET_YES;
2468 ax->ratchet_flag = GNUNET_NO;
2474 * Demultiplex by message type and call appropriate handler for a message
2475 * towards a channel of a local tunnel.
2477 * @param t Tunnel this message came on.
2478 * @param msgh Message header.
2479 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2480 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2481 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2482 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2485 handle_decrypted (struct CadetTunnel *t,
2486 const struct GNUNET_MessageHeader *msgh,
2491 type = ntohs (msgh->type);
2492 LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
2496 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
2497 /* Do nothing, connection aleady got updated. */
2498 GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
2501 case GNUNET_MESSAGE_TYPE_CADET_DATA:
2502 /* Don't send hop ACK, wait for client to ACK */
2503 handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
2506 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
2507 handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
2510 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
2511 handle_ch_create (t, (struct GNUNET_CADET_ChannelCreate *) msgh);
2514 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
2515 handle_ch_nack (t, (struct GNUNET_CADET_ChannelManage *) msgh);
2518 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
2519 handle_ch_ack (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
2522 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
2523 handle_ch_destroy (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
2527 GNUNET_break_op (0);
2528 LOG (GNUNET_ERROR_TYPE_WARNING,
2529 "end-to-end message not known (%u)\n",
2530 ntohs (msgh->type));
2531 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
2535 /******************************************************************************/
2536 /******************************** API ***********************************/
2537 /******************************************************************************/
2539 * Decrypt old format and demultiplex by message type. Call appropriate handler
2540 * for a message towards a channel of a local tunnel.
2542 * @param t Tunnel this message came on.
2543 * @param msg Message header.
2546 GCT_handle_encrypted (struct CadetTunnel *t,
2547 const struct GNUNET_MessageHeader *msg)
2549 size_t size = ntohs (msg->size);
2550 size_t payload_size;
2553 uint16_t type = ntohs (msg->type);
2554 struct GNUNET_MessageHeader *msgh;
2557 if (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED == type)
2559 const struct GNUNET_CADET_Encrypted *emsg;
2561 emsg = (struct GNUNET_CADET_Encrypted *) msg;
2562 payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
2563 decrypted_size = t_decrypt_and_validate (t, cbuf, &emsg[1], payload_size,
2564 emsg->iv, &emsg->hmac);
2566 else if (GNUNET_MESSAGE_TYPE_CADET_AX == type)
2568 const struct GNUNET_CADET_AX *emsg;
2570 emsg = (struct GNUNET_CADET_AX *) msg;
2571 payload_size = size - sizeof (struct GNUNET_CADET_AX);
2572 decrypted_size = t_ax_decrypt_and_validate (t, cbuf, &emsg[1],
2573 payload_size, &emsg->hmac);
2576 if (-1 == decrypted_size)
2578 GNUNET_break_op (0);
2583 while (off < decrypted_size)
2587 msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
2588 msize = ntohs (msgh->size);
2589 if (msize < sizeof (struct GNUNET_MessageHeader))
2591 GNUNET_break_op (0);
2594 handle_decrypted (t, msgh, GNUNET_SYSERR);
2601 * Demultiplex an encapsulated KX message by message type.
2603 * @param t Tunnel on which the message came.
2604 * @param message Payload of KX message.
2607 GCT_handle_kx (struct CadetTunnel *t,
2608 const struct GNUNET_MessageHeader *message)
2612 type = ntohs (message->type);
2613 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received: %s\n", GC_m2s (type));
2616 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
2617 handle_ephemeral (t, (const struct GNUNET_CADET_KX_Ephemeral *) message);
2620 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
2621 handle_pong (t, (const struct GNUNET_CADET_KX_Pong *) message);
2624 case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
2625 handle_kx_ax (t, (const struct GNUNET_CADET_AX_KX *) message);
2629 GNUNET_break_op (0);
2630 LOG (GNUNET_ERROR_TYPE_WARNING, "kx message %s unknown\n", GC_m2s (type));
2636 * Initialize the tunnel subsystem.
2638 * @param c Configuration handle.
2639 * @param key ECC private key, to derive all other keys and do crypto.
2642 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
2643 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
2645 int expected_overhead;
2647 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
2649 expected_overhead = 0;
2650 expected_overhead += sizeof (struct GNUNET_CADET_Encrypted);
2651 expected_overhead += sizeof (struct GNUNET_CADET_Data);
2652 expected_overhead += sizeof (struct GNUNET_CADET_ACK);
2653 GNUNET_assert (GNUNET_CONSTANTS_CADET_P2P_OVERHEAD == expected_overhead);
2656 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
2659 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
2660 "CADET", "DEFAULT_TTL", "USING DEFAULT");
2664 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
2667 rekey_period = GNUNET_TIME_UNIT_DAYS;
2670 my_private_key = key;
2672 kx_msg.header.size = htons (sizeof (kx_msg));
2673 kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
2674 kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
2675 kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
2676 kx_msg.origin_identity = my_full_id;
2677 rekey_task = GNUNET_SCHEDULER_add_now (&rekey, NULL);
2679 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
2684 * Shut down the tunnel subsystem.
2689 if (NULL != rekey_task)
2691 GNUNET_SCHEDULER_cancel (rekey_task);
2694 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
2695 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
2702 * @param destination Peer this tunnel is towards.
2704 struct CadetTunnel *
2705 GCT_new (struct CadetPeer *destination)
2707 struct CadetTunnel *t;
2709 t = GNUNET_new (struct CadetTunnel);
2711 t->peer = destination;
2714 GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
2715 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2721 t->ax = GNUNET_new (struct CadetTunnelAxolotl);
2723 t->ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
2729 * Change the tunnel's connection state.
2731 * @param t Tunnel whose connection state to change.
2732 * @param cstate New connection state.
2735 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
2739 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
2740 GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
2741 if (myid != GCP_get_short_id (t->peer) &&
2742 CADET_TUNNEL_READY != t->cstate &&
2743 CADET_TUNNEL_READY == cstate)
2746 if (CADET_TUNNEL_KEY_OK == t->estate)
2748 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered send queued data\n");
2749 send_queued_data (t);
2751 else if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
2753 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered rekey\n");
2754 if (NULL != t->rekey_task)
2755 GNUNET_SCHEDULER_cancel (t->rekey_task);
2757 rekey_tunnel (t, NULL);
2762 if (CADET_TUNNEL_READY == cstate
2763 && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
2765 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered stop dht\n");
2766 GCP_stop_search (t->peer);
2772 * Change the tunnel encryption state.
2774 * @param t Tunnel whose encryption state to change, or NULL.
2775 * @param state New encryption state.
2778 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
2780 enum CadetTunnelEState old;
2787 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate was %s\n",
2788 GCP_2s (t->peer), estate2s (old));
2789 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate is now %s\n",
2790 GCP_2s (t->peer), estate2s (t->estate));
2792 /* Send queued data if enc state changes to OK */
2793 if (myid != GCP_get_short_id (t->peer) &&
2794 CADET_TUNNEL_KEY_OK != old && CADET_TUNNEL_KEY_OK == t->estate)
2796 send_queued_data (t);
2802 * @brief Check if tunnel has too many connections, and remove one if necessary.
2804 * Currently this means the newest connection, unless it is a direct one.
2805 * Implemented as a task to avoid freeing a connection that is in the middle
2806 * of being created/processed.
2808 * @param cls Closure (Tunnel to check).
2809 * @param tc Task context.
2812 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2814 struct CadetTunnel *t = cls;
2816 t->trim_connections_task = NULL;
2818 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2821 if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
2823 struct CadetTConnection *iter;
2824 struct CadetTConnection *c;
2826 for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
2828 if ((iter->created.abs_value_us > c->created.abs_value_us)
2829 && GNUNET_NO == GCC_is_direct (iter->c))
2836 LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
2838 LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
2851 * Add a connection to a tunnel.
2854 * @param c Connection.
2857 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
2859 struct CadetTConnection *aux;
2861 GNUNET_assert (NULL != c);
2863 LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
2864 LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
2865 for (aux = t->connection_head; aux != NULL; aux = aux->next)
2869 aux = GNUNET_new (struct CadetTConnection);
2871 aux->created = GNUNET_TIME_absolute_get ();
2873 GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
2875 if (CADET_TUNNEL_SEARCHING == t->cstate)
2876 GCT_change_estate (t, CADET_TUNNEL_WAITING);
2878 if (NULL != t->trim_connections_task)
2879 t->trim_connections_task = GNUNET_SCHEDULER_add_now (&trim_connections, t);
2884 * Remove a connection from a tunnel.
2887 * @param c Connection.
2890 GCT_remove_connection (struct CadetTunnel *t,
2891 struct CadetConnection *c)
2893 struct CadetTConnection *aux;
2894 struct CadetTConnection *next;
2897 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
2898 GCC_2s (c), GCT_2s (t));
2899 for (aux = t->connection_head; aux != NULL; aux = next)
2904 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
2909 conns = GCT_count_connections (t);
2911 && NULL == t->destroy_task
2912 && CADET_TUNNEL_SHUTDOWN != t->cstate
2913 && GNUNET_NO == shutting_down)
2915 if (0 == GCT_count_any_connections (t))
2916 GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
2918 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
2921 /* Start new connections if needed */
2922 if (CONNECTIONS_PER_TUNNEL > conns
2923 && NULL == t->destroy_task
2924 && CADET_TUNNEL_SHUTDOWN != t->cstate
2925 && GNUNET_NO == shutting_down)
2927 LOG (GNUNET_ERROR_TYPE_DEBUG, " too few connections, getting new ones\n");
2928 GCP_connect (t->peer); /* Will change cstate to WAITING when possible */
2932 /* If not marked as ready, no change is needed */
2933 if (CADET_TUNNEL_READY != t->cstate)
2936 /* Check if any connection is ready to maintain cstate */
2937 for (aux = t->connection_head; aux != NULL; aux = aux->next)
2938 if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
2944 * Add a channel to a tunnel.
2947 * @param ch Channel.
2950 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2952 struct CadetTChannel *aux;
2954 GNUNET_assert (NULL != ch);
2956 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
2958 for (aux = t->channel_head; aux != NULL; aux = aux->next)
2960 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
2965 aux = GNUNET_new (struct CadetTChannel);
2967 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
2968 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
2970 if (NULL != t->destroy_task)
2972 GNUNET_SCHEDULER_cancel (t->destroy_task);
2973 t->destroy_task = NULL;
2974 LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
2980 * Remove a channel from a tunnel.
2983 * @param ch Channel.
2986 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2988 struct CadetTChannel *aux;
2990 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
2991 for (aux = t->channel_head; aux != NULL; aux = aux->next)
2995 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
2996 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
3005 * Search for a channel by global ID.
3007 * @param t Tunnel containing the channel.
3008 * @param chid Public channel number.
3010 * @return channel handler, NULL if doesn't exist
3012 struct CadetChannel *
3013 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
3015 struct CadetTChannel *iter;
3020 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3022 if (GCCH_get_id (iter->ch) == chid)
3026 return NULL == iter ? NULL : iter->ch;
3031 * @brief Destroy a tunnel and free all resources.
3033 * Should only be called a while after the tunnel has been marked as destroyed,
3034 * in case there is a new channel added to the same peer shortly after marking
3035 * the tunnel. This way we avoid a new public key handshake.
3037 * @param cls Closure (tunnel to destroy).
3038 * @param tc Task context.
3041 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3043 struct CadetTunnel *t = cls;
3044 struct CadetTConnection *iter;
3046 LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
3047 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
3049 LOG (GNUNET_ERROR_TYPE_WARNING,
3050 "Not destroying tunnel, due to shutdown. "
3051 "Tunnel at %p should have been freed by GCT_shutdown\n", t);
3054 t->destroy_task = NULL;
3055 t->cstate = CADET_TUNNEL_SHUTDOWN;
3057 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3059 GCC_send_destroy (iter->c);
3066 * Tunnel is empty: destroy it.
3068 * Notifies all connections about the destruction.
3070 * @param t Tunnel to destroy.
3073 GCT_destroy_empty (struct CadetTunnel *t)
3075 if (GNUNET_YES == shutting_down)
3076 return; /* Will be destroyed immediately anyway */
3078 if (NULL != t->destroy_task)
3080 LOG (GNUNET_ERROR_TYPE_WARNING,
3081 "Tunnel %s is already scheduled for destruction. Tunnel debug dump:\n",
3083 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3085 /* should never happen, tunnel can only become empty once, and the
3086 * task identifier should be NO_TASK (cleaned when the tunnel was created
3087 * or became un-empty)
3092 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: scheduling destruction\n",
3095 // FIXME make delay a config option
3096 t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
3097 &delayed_destroy, t);
3098 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llu\n",
3099 t, t->destroy_task);
3104 * Destroy tunnel if empty (no more channels).
3106 * @param t Tunnel to destroy if empty.
3109 GCT_destroy_if_empty (struct CadetTunnel *t)
3111 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
3112 if (0 < GCT_count_channels (t))
3115 GCT_destroy_empty (t);
3120 * Destroy the tunnel.
3122 * This function does not generate any warning traffic to clients or peers.
3125 * Cancel messages belonging to this tunnel queued to neighbors.
3126 * Free any allocated resources linked to the tunnel.
3128 * @param t The tunnel to destroy.
3131 GCT_destroy (struct CadetTunnel *t)
3133 struct CadetTConnection *iter_c;
3134 struct CadetTConnection *next_c;
3135 struct CadetTChannel *iter_ch;
3136 struct CadetTChannel *next_ch;
3141 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
3143 GNUNET_break (GNUNET_YES ==
3144 GNUNET_CONTAINER_multipeermap_remove (tunnels,
3145 GCP_get_id (t->peer), t));
3147 for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
3149 next_c = iter_c->next;
3150 GCC_destroy (iter_c->c);
3152 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
3154 next_ch = iter_ch->next;
3155 GCCH_destroy (iter_ch->ch);
3156 /* Should only happen on shutdown, but it's ok. */
3159 if (NULL != t->destroy_task)
3161 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling dest: %llX\n", t->destroy_task);
3162 GNUNET_SCHEDULER_cancel (t->destroy_task);
3163 t->destroy_task = NULL;
3166 if (NULL != t->trim_connections_task)
3168 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling trim: %llX\n",
3169 t->trim_connections_task);
3170 GNUNET_SCHEDULER_cancel (t->trim_connections_task);
3171 t->trim_connections_task = NULL;
3174 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
3175 GCP_set_tunnel (t->peer, NULL);
3177 if (NULL != t->rekey_task)
3179 GNUNET_SCHEDULER_cancel (t->rekey_task);
3180 t->rekey_task = NULL;
3182 if (NULL != t->kx_ctx)
3184 if (NULL != t->kx_ctx->finish_task)
3185 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
3186 GNUNET_free (t->kx_ctx);
3197 * @brief Use the given path for the tunnel.
3198 * Update the next and prev hops (and RCs).
3199 * (Re)start the path refresh in case the tunnel is locally owned.
3201 * @param t Tunnel to update.
3202 * @param p Path to use.
3204 * @return Connection created.
3206 struct CadetConnection *
3207 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
3209 struct CadetConnection *c;
3210 struct GNUNET_CADET_Hash cid;
3211 unsigned int own_pos;
3213 if (NULL == t || NULL == p)
3219 if (CADET_TUNNEL_SHUTDOWN == t->cstate)
3225 for (own_pos = 0; own_pos < p->length; own_pos++)
3227 if (p->peers[own_pos] == myid)
3230 if (own_pos >= p->length)
3232 GNUNET_break_op (0);
3236 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
3237 c = GCC_new (&cid, t, p, own_pos);
3240 /* Path was flawed */
3243 GCT_add_connection (t, c);
3249 * Count all created connections of a tunnel. Not necessarily ready connections!
3251 * @param t Tunnel on which to count.
3253 * @return Number of connections created, either being established or ready.
3256 GCT_count_any_connections (struct CadetTunnel *t)
3258 struct CadetTConnection *iter;
3264 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3272 * Count established (ready) connections of a tunnel.
3274 * @param t Tunnel on which to count.
3276 * @return Number of connections.
3279 GCT_count_connections (struct CadetTunnel *t)
3281 struct CadetTConnection *iter;
3287 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3288 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
3296 * Count channels of a tunnel.
3298 * @param t Tunnel on which to count.
3300 * @return Number of channels.
3303 GCT_count_channels (struct CadetTunnel *t)
3305 struct CadetTChannel *iter;
3308 for (count = 0, iter = t->channel_head;
3310 iter = iter->next, count++) /* skip */;
3317 * Get the connectivity state of a tunnel.
3321 * @return Tunnel's connectivity state.
3323 enum CadetTunnelCState
3324 GCT_get_cstate (struct CadetTunnel *t)
3329 return (enum CadetTunnelCState) -1;
3336 * Get the encryption state of a tunnel.
3340 * @return Tunnel's encryption state.
3342 enum CadetTunnelEState
3343 GCT_get_estate (struct CadetTunnel *t)
3348 return (enum CadetTunnelEState) -1;
3354 * Get the maximum buffer space for a tunnel towards a local client.
3358 * @return Biggest buffer space offered by any channel in the tunnel.
3361 GCT_get_channels_buffer (struct CadetTunnel *t)
3363 struct CadetTChannel *iter;
3364 unsigned int buffer;
3365 unsigned int ch_buf;
3367 if (NULL == t->channel_head)
3369 /* Probably getting buffer for a channel create/handshake. */
3370 LOG (GNUNET_ERROR_TYPE_DEBUG, " no channels, allow max\n");
3375 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3377 ch_buf = get_channel_buffer (iter);
3378 if (ch_buf > buffer)
3386 * Get the total buffer space for a tunnel for P2P traffic.
3390 * @return Buffer space offered by all connections in the tunnel.
3393 GCT_get_connections_buffer (struct CadetTunnel *t)
3395 struct CadetTConnection *iter;
3396 unsigned int buffer;
3398 if (GNUNET_NO == is_ready (t))
3400 if (count_queued_data (t) > 3)
3407 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3409 if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
3413 buffer += get_connection_buffer (iter);
3421 * Get the tunnel's destination.
3425 * @return ID of the destination peer.
3427 const struct GNUNET_PeerIdentity *
3428 GCT_get_destination (struct CadetTunnel *t)
3430 return GCP_get_id (t->peer);
3435 * Get the tunnel's next free global channel ID.
3439 * @return GID of a channel free to use.
3442 GCT_get_next_chid (struct CadetTunnel *t)
3444 CADET_ChannelNumber chid;
3445 CADET_ChannelNumber mask;
3448 /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
3449 * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
3450 * If peer's ID is bigger, start at 0x4... bit 30 = 1
3452 result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
3457 t->next_chid |= mask;
3459 while (NULL != GCT_get_channel (t, t->next_chid))
3461 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
3462 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3463 t->next_chid |= mask;
3465 chid = t->next_chid;
3466 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3467 t->next_chid |= mask;
3474 * Send ACK on one or more channels due to buffer in connections.
3476 * @param t Channel which has some free buffer space.
3479 GCT_unchoke_channels (struct CadetTunnel *t)
3481 struct CadetTChannel *iter;
3482 unsigned int buffer;
3483 unsigned int channels = GCT_count_channels (t);
3484 unsigned int choked_n;
3485 struct CadetChannel *choked[channels];
3487 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
3488 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
3489 if (NULL != t->channel_head)
3490 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
3492 /* Get buffer space */
3493 buffer = GCT_get_connections_buffer (t);
3499 /* Count and remember choked channels */
3501 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3503 if (GNUNET_NO == get_channel_allowed (iter))
3505 choked[choked_n++] = iter->ch;
3509 /* Unchoke random channels */
3510 while (0 < buffer && 0 < choked_n)
3512 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3514 GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
3517 choked[r] = choked[choked_n];
3523 * Send ACK on one or more connections due to buffer space to the client.
3525 * Iterates all connections of the tunnel and sends ACKs appropriately.
3530 GCT_send_connection_acks (struct CadetTunnel *t)
3532 struct CadetTConnection *iter;
3535 uint32_t allow_per_connection;
3537 unsigned int buffer;
3539 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
3548 if (CADET_TUNNEL_READY != t->cstate)
3551 buffer = GCT_get_channels_buffer (t);
3552 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer %u\n", buffer);
3554 /* Count connections, how many messages are already allowed */
3555 cs = GCT_count_connections (t);
3556 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3558 allowed += get_connection_allowed (iter);
3560 LOG (GNUNET_ERROR_TYPE_DEBUG, " allowed %u\n", allowed);
3562 /* Make sure there is no overflow */
3563 if (allowed > buffer)
3566 /* Authorize connections to send more data */
3567 to_allow = buffer - allowed;
3569 for (iter = t->connection_head;
3570 NULL != iter && to_allow > 0;
3573 if (CADET_CONNECTION_READY != GCC_get_state (iter->c)
3574 || get_connection_allowed (iter) > 64 / 3)
3578 allow_per_connection = to_allow/cs;
3579 to_allow -= allow_per_connection;
3581 GCC_allow (iter->c, allow_per_connection,
3582 GCC_is_origin (iter->c, GNUNET_NO));
3587 /* Since we don't allow if it's allowed to send 64/3, this can happen. */
3588 LOG (GNUNET_ERROR_TYPE_DEBUG, " reminding to_allow: %u\n", to_allow);
3594 * Cancel a previously sent message while it's in the queue.
3596 * ONLY can be called before the continuation given to the send function
3597 * is called. Once the continuation is called, the message is no longer in the
3600 * @param q Handle to the queue.
3603 GCT_cancel (struct CadetTunnelQueue *q)
3608 /* tun_message_sent() will be called and free q */
3610 else if (NULL != q->tqd)
3612 unqueue_data (q->tqd);
3614 if (NULL != q->cont)
3615 q->cont (q->cont_cls, NULL, q, 0, 0);
3626 * Sends an already built message on a tunnel, encrypting it and
3627 * choosing the best connection if not provided.
3629 * @param message Message to send. Function modifies it.
3630 * @param t Tunnel on which this message is transmitted.
3631 * @param c Connection to use (autoselect if NULL).
3632 * @param force Force the tunnel to take the message (buffer overfill).
3633 * @param cont Continuation to call once message is really sent.
3634 * @param cont_cls Closure for @c cont.
3636 * @return Handle to cancel message. NULL if @c cont is NULL.
3638 struct CadetTunnelQueue *
3639 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
3640 struct CadetTunnel *t, struct CadetConnection *c,
3641 int force, GCT_sent cont, void *cont_cls)
3643 return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
3647 * Sends an already built and encrypted message on a tunnel, choosing the best
3648 * connection. Useful for re-queueing messages queued on a destroyed connection.
3650 * @param message Message to send. Function modifies it.
3651 * @param t Tunnel on which this message is transmitted.
3654 GCT_resend_message (const struct GNUNET_MessageHeader *message,
3655 struct CadetTunnel *t)
3657 struct CadetConnection *c;
3660 c = tunnel_get_connection (t);
3663 /* TODO queue in tunnel, marked as encrypted */
3664 LOG (GNUNET_ERROR_TYPE_DEBUG, "No connection available, dropping.\n");
3667 fwd = GCC_is_origin (c, GNUNET_YES);
3668 GNUNET_break (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
3669 GNUNET_YES, NULL, NULL));
3674 * Is the tunnel directed towards the local peer?
3678 * @return #GNUNET_YES if it is loopback.
3681 GCT_is_loopback (const struct CadetTunnel *t)
3683 return (myid == GCP_get_short_id (t->peer));
3688 * Is the tunnel this path already?
3693 * @return #GNUNET_YES a connection uses this path.
3696 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
3698 struct CadetTConnection *iter;
3700 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3701 if (path_equivalent (GCC_get_path (iter->c), p))
3709 * Get a cost of a path for a tunnel considering existing connections.
3712 * @param path Candidate path.
3714 * @return Cost of the path (path length + number of overlapping nodes)
3717 GCT_get_path_cost (const struct CadetTunnel *t,
3718 const struct CadetPeerPath *path)
3720 struct CadetTConnection *iter;
3721 const struct CadetPeerPath *aux;
3722 unsigned int overlap;
3730 GNUNET_assert (NULL != t);
3732 for (i = 0; i < path->length; i++)
3734 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3736 aux = GCC_get_path (iter->c);
3740 for (j = 0; j < aux->length; j++)
3742 if (path->peers[i] == aux->peers[j])
3750 return path->length + overlap;
3755 * Get the static string for the peer this tunnel is directed.
3759 * @return Static string the destination peer's ID.
3762 GCT_2s (const struct CadetTunnel *t)
3767 return GCP_2s (t->peer);
3771 /******************************************************************************/
3772 /***************************** INFO/DEBUG *******************************/
3773 /******************************************************************************/
3776 * Log all possible info about the tunnel state.
3778 * @param t Tunnel to debug.
3779 * @param level Debug level to use.
3782 GCT_debug (const struct CadetTunnel *t, enum GNUNET_ErrorType level)
3784 struct CadetTChannel *iterch;
3785 struct CadetTConnection *iterc;
3788 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
3790 __FILE__, __FUNCTION__, __LINE__);
3794 LOG2 (level, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
3795 LOG2 (level, "TTT cstate %s, estate %s\n",
3796 cstate2s (t->cstate), estate2s (t->estate));
3797 LOG2 (level, "TTT kx_ctx %p, rekey_task %u, finish task %u\n",
3798 t->kx_ctx, t->rekey_task, t->kx_ctx ? t->kx_ctx->finish_task : 0);
3799 #if DUMP_KEYS_TO_STDERR
3800 LOG2 (level, "TTT my EPHM\t %s\n",
3801 GNUNET_h2s ((struct GNUNET_HashCode *) &kx_msg.ephemeral_key));
3802 LOG2 (level, "TTT peers EPHM:\t %s\n",
3803 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
3804 LOG2 (level, "TTT ENC key:\t %s\n",
3805 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
3806 LOG2 (level, "TTT DEC key:\t %s\n",
3807 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
3810 LOG2 (level, "TTT OLD ENC key:\t %s\n",
3811 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->e_key_old));
3812 LOG2 (level, "TTT OLD DEC key:\t %s\n",
3813 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->d_key_old));
3816 LOG2 (level, "TTT tq_head %p, tq_tail %p\n", t->tq_head, t->tq_tail);
3817 LOG2 (level, "TTT destroy %u\n", t->destroy_task);
3819 LOG2 (level, "TTT channels:\n");
3820 for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
3822 LOG2 (level, "TTT - %s\n", GCCH_2s (iterch->ch));
3825 LOG2 (level, "TTT connections:\n");
3826 for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
3828 GCC_debug (iterc->c, level);
3831 LOG2 (level, "TTT DEBUG TUNNEL END\n");
3836 * Iterate all tunnels.
3838 * @param iter Iterator.
3839 * @param cls Closure for @c iter.
3842 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
3844 GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
3849 * Count all tunnels.
3851 * @return Number of tunnels to remote peers kept by this peer.
3854 GCT_count_all (void)
3856 return GNUNET_CONTAINER_multipeermap_size (tunnels);
3861 * Iterate all connections of a tunnel.
3863 * @param t Tunnel whose connections to iterate.
3864 * @param iter Iterator.
3865 * @param cls Closure for @c iter.
3868 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
3870 struct CadetTConnection *ct;
3872 for (ct = t->connection_head; NULL != ct; ct = ct->next)
3878 * Iterate all channels of a tunnel.
3880 * @param t Tunnel whose channels to iterate.
3881 * @param iter Iterator.
3882 * @param cls Closure for @c iter.
3885 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
3887 struct CadetTChannel *cht;
3889 for (cht = t->channel_head; NULL != cht; cht = cht->next)
3890 iter (cls, cht->ch);