2 This file is part of GNUnet.
3 Copyright (C) 2013 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 #include "gnunet_util_lib.h"
24 #include "gnunet_signatures.h"
25 #include "gnunet_statistics_service.h"
27 #include "cadet_protocol.h"
28 #include "cadet_path.h"
30 #include "gnunet-service-cadet_tunnel.h"
31 #include "gnunet-service-cadet_connection.h"
32 #include "gnunet-service-cadet_channel.h"
33 #include "gnunet-service-cadet_peer.h"
35 #define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__)
36 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
38 #define REKEY_WAIT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5)
40 #if !defined(GNUNET_CULL_LOGGING)
41 #define DUMP_KEYS_TO_STDERR GNUNET_YES
43 #define DUMP_KEYS_TO_STDERR GNUNET_NO
46 /******************************************************************************/
47 /******************************** STRUCTS **********************************/
48 /******************************************************************************/
52 struct CadetTChannel *next;
53 struct CadetTChannel *prev;
54 struct CadetChannel *ch;
59 * Connection list and metadata.
61 struct CadetTConnection
66 struct CadetTConnection *next;
71 struct CadetTConnection *prev;
76 struct CadetConnection *c;
79 * Creation time, to keep oldest connection alive.
81 struct GNUNET_TIME_Absolute created;
84 * Connection throughput, to keep fastest connection alive.
90 * Structure used during a Key eXchange.
92 struct CadetTunnelKXCtx
95 * Encryption ("our") old "confirmed" key, for encrypting traffic sent by us
96 * end before the key exchange is finished or times out.
98 struct GNUNET_CRYPTO_SymmetricSessionKey e_key_old;
101 * Decryption ("their") old "confirmed" key, for decrypting traffic sent by
102 * the other end before the key exchange started.
104 struct GNUNET_CRYPTO_SymmetricSessionKey d_key_old;
107 * Same as @c e_key_old, for the case of two simultaneous KX.
108 * This can happen if cadet decides to start a re-key while the peer has also
109 * started its re-key (due to network delay this is impossible to avoid).
110 * In this case, the key material generated with the peer's old ephemeral
111 * *might* (but doesn't have to) be incorrect.
112 * Since no more than two re-keys can happen simultaneously, this is enough.
114 struct GNUNET_CRYPTO_SymmetricSessionKey e_key_old2;
117 * Same as @c d_key_old, for the case described in @c e_key_old2.
119 struct GNUNET_CRYPTO_SymmetricSessionKey d_key_old2;
122 * Challenge to send and expect in the PONG.
127 * When the rekey started. One minute after this the new key will be used.
129 struct GNUNET_TIME_Absolute rekey_start_time;
132 * Task for delayed destruction of the Key eXchange context, to allow delayed
133 * messages with the old key to be decrypted successfully.
135 struct GNUNET_SCHEDULER_Task * finish_task;
139 * Encryption systems possible.
141 enum CadetTunnelEncryption
144 * Default Axolotl system.
149 * Fallback OTR-style encryption.
154 struct CadetTunnelSkippedKey
156 struct CadetTunnelSkippedKey *next;
157 struct CadetTunnelSkippedKey *prev;
159 struct GNUNET_TIME_Absolute timestamp;
161 struct GNUNET_CRYPTO_SymmetricSessionKey HK;
162 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
166 * Axolotl data, according to https://github.com/trevp/axolotl/wiki
168 struct CadetTunnelAxolotl
171 * A (double linked) list of stored message keys and associated header keys
172 * for "skipped" messages, i.e. messages that have not bee*n
173 * received despite the reception of more recent messages, (head)/
175 struct CadetTunnelSkippedKey *skipped_head;
178 * Skipped messages' keys DLL, tail.
180 struct CadetTunnelSkippedKey *skipped_tail;
183 * Elements in @a skipped_head <-> @a skipped_tail.
188 * 32-byte root key which gets updated by DH ratchet
190 struct GNUNET_CRYPTO_SymmetricSessionKey RK;
193 * 32-byte header key (send)
195 struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
198 * 32-byte header key (recv)
200 struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
203 * 32-byte next header key (send)
205 struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
208 * 32-byte next header key (recv)
210 struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
213 * 32-byte chain keys (used for forward-secrecy updating, send)
215 struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
218 * 32-byte chain keys (used for forward-secrecy updating, recv)
220 struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
223 * ECDH Ratchet key (send)
225 struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
228 * ECDH Ratchet key (recv)
230 struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
233 * Message number (reset to 0 with each new ratchet, send)
238 * Message numbers (reset to 0 with each new ratchet, recv)
243 * Previous message numbers (# of msgs sent under prev ratchet)
248 * True (#GNUNET_YES) if the party will send a new ratchet key in next msg.
254 * Struct containing all information regarding a tunnel to a peer.
259 * Endpoint of the tunnel.
261 struct CadetPeer *peer;
264 * Type of encryption used in the tunnel.
266 enum CadetTunnelEncryption enc_type;
271 struct CadetTunnelAxolotl *ax;
274 * State of the tunnel connectivity.
276 enum CadetTunnelCState cstate;
279 * State of the tunnel encryption.
281 enum CadetTunnelEState estate;
284 * Key eXchange context.
286 struct CadetTunnelKXCtx *kx_ctx;
289 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own ephemeral
292 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
295 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
297 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
300 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
302 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
305 * Task to start the rekey process.
307 struct GNUNET_SCHEDULER_Task * rekey_task;
310 * Paths that are actively used to reach the destination peer.
312 struct CadetTConnection *connection_head;
313 struct CadetTConnection *connection_tail;
316 * Next connection number.
321 * Channels inside this tunnel.
323 struct CadetTChannel *channel_head;
324 struct CadetTChannel *channel_tail;
327 * Channel ID for the next created channel.
329 CADET_ChannelNumber next_chid;
332 * Destroy flag: if true, destroy on last message.
334 struct GNUNET_SCHEDULER_Task * destroy_task;
337 * Queued messages, to transmit once tunnel gets connected.
339 struct CadetTunnelDelayed *tq_head;
340 struct CadetTunnelDelayed *tq_tail;
343 * Task to trim connections if too many are present.
345 struct GNUNET_SCHEDULER_Task * trim_connections_task;
348 * Ephemeral message in the queue (to avoid queueing more than one).
350 struct CadetConnectionQueue *ephm_h;
353 * Pong message in the queue.
355 struct CadetConnectionQueue *pong_h;
360 * Struct used to save messages in a non-ready tunnel to send once connected.
362 struct CadetTunnelDelayed
367 struct CadetTunnelDelayed *next;
368 struct CadetTunnelDelayed *prev;
373 struct CadetTunnel *t;
376 * Tunnel queue given to the channel to cancel request. Update on send_queued.
378 struct CadetTunnelQueue *tq;
383 /* struct GNUNET_MessageHeader *msg; */
388 * Handle for messages queued but not yet sent.
390 struct CadetTunnelQueue
393 * Connection queue handle, to cancel if necessary.
395 struct CadetConnectionQueue *cq;
398 * Handle in case message hasn't been given to a connection yet.
400 struct CadetTunnelDelayed *tqd;
403 * Continuation to call once sent.
408 * Closure for @c cont.
414 /******************************************************************************/
415 /******************************* GLOBALS ***********************************/
416 /******************************************************************************/
419 * Global handle to the statistics service.
421 extern struct GNUNET_STATISTICS_Handle *stats;
424 * Local peer own ID (memory efficient handle).
426 extern GNUNET_PEER_Id myid;
429 * Local peer own ID (full value).
431 extern struct GNUNET_PeerIdentity my_full_id;
435 * Don't try to recover tunnels if shutting down.
437 extern int shutting_down;
441 * Set of all tunnels, in order to trigger a new exchange on rekey.
442 * Indexed by peer's ID.
444 static struct GNUNET_CONTAINER_MultiPeerMap *tunnels;
447 * Default TTL for payload packets.
449 static unsigned long long default_ttl;
454 const static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
457 * Own Axolotl private key (derived from @a my_private_key).
459 const struct GNUNET_CRYPTO_EcdhePrivateKey *ax_identity;
462 * Own OTR ephemeral private key.
464 static struct GNUNET_CRYPTO_EcdhePrivateKey *my_ephemeral_key;
467 * Cached message used to perform a key exchange.
469 static struct GNUNET_CADET_KX_Ephemeral kx_msg;
472 * Task to generate a new ephemeral key.
474 static struct GNUNET_SCHEDULER_Task * rekey_task;
479 static struct GNUNET_TIME_Relative rekey_period;
482 /******************************************************************************/
483 /******************************** STATIC ***********************************/
484 /******************************************************************************/
487 * Get string description for tunnel connectivity state.
489 * @param cs Tunnel state.
491 * @return String representation.
494 cstate2s (enum CadetTunnelCState cs)
500 case CADET_TUNNEL_NEW:
501 return "CADET_TUNNEL_NEW";
502 case CADET_TUNNEL_SEARCHING:
503 return "CADET_TUNNEL_SEARCHING";
504 case CADET_TUNNEL_WAITING:
505 return "CADET_TUNNEL_WAITING";
506 case CADET_TUNNEL_READY:
507 return "CADET_TUNNEL_READY";
508 case CADET_TUNNEL_SHUTDOWN:
509 return "CADET_TUNNEL_SHUTDOWN";
511 SPRINTF (buf, "%u (UNKNOWN STATE)", cs);
519 * Get string description for tunnel encryption state.
521 * @param es Tunnel state.
523 * @return String representation.
526 estate2s (enum CadetTunnelEState es)
532 case CADET_TUNNEL_KEY_UNINITIALIZED:
533 return "CADET_TUNNEL_KEY_UNINITIALIZED";
534 case CADET_TUNNEL_KEY_SENT:
535 return "CADET_TUNNEL_KEY_SENT";
536 case CADET_TUNNEL_KEY_PING:
537 return "CADET_TUNNEL_KEY_PING";
538 case CADET_TUNNEL_KEY_OK:
539 return "CADET_TUNNEL_KEY_OK";
540 case CADET_TUNNEL_KEY_REKEY:
541 return "CADET_TUNNEL_KEY_REKEY";
543 SPRINTF (buf, "%u (UNKNOWN STATE)", es);
551 * @brief Check if tunnel is ready to send traffic.
553 * Tunnel must be connected and with encryption correctly set up.
555 * @param t Tunnel to check.
557 * @return #GNUNET_YES if ready, #GNUNET_NO otherwise
560 is_ready (struct CadetTunnel *t)
564 GCT_debug (t, GNUNET_ERROR_TYPE_DEBUG);
565 ready = CADET_TUNNEL_READY == t->cstate
566 && (CADET_TUNNEL_KEY_OK == t->estate
567 || CADET_TUNNEL_KEY_REKEY == t->estate);
568 ready = ready || GCT_is_loopback (t);
574 * Check if a key is invalid (NULL pointer or all 0)
576 * @param key Key to check.
578 * @return #GNUNET_YES if key is null, #GNUNET_NO if exists and is not 0.
581 is_key_null (struct GNUNET_CRYPTO_SymmetricSessionKey *key)
583 struct GNUNET_CRYPTO_SymmetricSessionKey null_key;
588 memset (&null_key, 0, sizeof (null_key));
589 if (0 == memcmp (key, &null_key, sizeof (null_key)))
596 * Ephemeral key message purpose size.
598 * @return Size of the part of the ephemeral key message that must be signed.
601 ephemeral_purpose_size (void)
603 return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
604 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
605 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
606 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
607 sizeof (struct GNUNET_PeerIdentity);
612 * Size of the encrypted part of a ping message.
614 * @return Size of the encrypted part of a ping message.
617 ping_encryption_size (void)
619 return sizeof (uint32_t);
624 * Get the channel's buffer. ONLY FOR NON-LOOPBACK CHANNELS!!
626 * @param tch Tunnel's channel handle.
628 * @return Amount of messages the channel can still buffer towards the client.
631 get_channel_buffer (const struct CadetTChannel *tch)
635 /* If channel is incoming, is terminal in the FWD direction and fwd is YES */
636 fwd = GCCH_is_terminal (tch->ch, GNUNET_YES);
638 return GCCH_get_buffer (tch->ch, fwd);
643 * Get the channel's allowance status.
645 * @param tch Tunnel's channel handle.
647 * @return #GNUNET_YES if we allowed the client to send data to us.
650 get_channel_allowed (const struct CadetTChannel *tch)
654 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
655 fwd = GCCH_is_origin (tch->ch, GNUNET_YES);
657 return GCCH_get_allowed (tch->ch, fwd);
662 * Get the connection's buffer.
664 * @param tc Tunnel's connection handle.
666 * @return Amount of messages the connection can still buffer.
669 get_connection_buffer (const struct CadetTConnection *tc)
673 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
674 fwd = GCC_is_origin (tc->c, GNUNET_YES);
676 return GCC_get_buffer (tc->c, fwd);
681 * Get the connection's allowance.
683 * @param tc Tunnel's connection handle.
685 * @return Amount of messages we have allowed the next peer to send us.
688 get_connection_allowed (const struct CadetTConnection *tc)
692 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
693 fwd = GCC_is_origin (tc->c, GNUNET_YES);
695 return GCC_get_allowed (tc->c, fwd);
700 * Check that a ephemeral key message s well formed and correctly signed.
702 * @param t Tunnel on which the message came.
703 * @param msg The ephemeral key message.
705 * @return GNUNET_OK if message is fine, GNUNET_SYSERR otherwise.
708 check_ephemeral (struct CadetTunnel *t,
709 const struct GNUNET_CADET_KX_Ephemeral *msg)
711 /* Check message size */
712 if (ntohs (msg->header.size) != sizeof (struct GNUNET_CADET_KX_Ephemeral))
713 return GNUNET_SYSERR;
715 /* Check signature size */
716 if (ntohl (msg->purpose.size) != ephemeral_purpose_size ())
717 return GNUNET_SYSERR;
720 if (0 != memcmp (&msg->origin_identity,
721 GCP_get_id (t->peer),
722 sizeof (struct GNUNET_PeerIdentity)))
723 return GNUNET_SYSERR;
725 /* Check signature */
727 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_CADET_KX,
730 &msg->origin_identity.public_key))
731 return GNUNET_SYSERR;
738 * Select the best key to use for encryption (send), based on KX status.
740 * Normally, return the current key. If there is a KX in progress and the old
741 * key is fresh enough, return the old key.
743 * @param t Tunnel to choose the key from.
745 * @return The optimal key to encrypt/hmac outgoing traffic.
747 static const struct GNUNET_CRYPTO_SymmetricSessionKey *
748 select_key (const struct CadetTunnel *t)
750 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
752 if (NULL != t->kx_ctx
753 && NULL == t->kx_ctx->finish_task)
755 struct GNUNET_TIME_Relative age;
757 age = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
758 LOG (GNUNET_ERROR_TYPE_DEBUG,
759 " key exchange in progress, started %s ago\n",
760 GNUNET_STRINGS_relative_time_to_string (age, GNUNET_YES));
761 // FIXME make duration of old keys configurable
762 if (age.rel_value_us < GNUNET_TIME_UNIT_MINUTES.rel_value_us)
764 LOG (GNUNET_ERROR_TYPE_DEBUG, " using old key\n");
765 key = &t->kx_ctx->e_key_old;
769 LOG (GNUNET_ERROR_TYPE_DEBUG, " using new key (old key too old)\n");
775 LOG (GNUNET_ERROR_TYPE_DEBUG, " no KX: using current key\n");
785 * @param plaintext Content to HMAC.
786 * @param size Size of @c plaintext.
787 * @param iv Initialization vector for the message.
788 * @param key Key to use.
789 * @param hmac[out] Destination to store the HMAC.
792 t_hmac (const void *plaintext, size_t size,
793 uint32_t iv, const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
794 struct GNUNET_CADET_Hash *hmac)
796 static const char ctx[] = "cadet authentication key";
797 struct GNUNET_CRYPTO_AuthKey auth_key;
798 struct GNUNET_HashCode hash;
800 #if DUMP_KEYS_TO_STDERR
801 LOG (GNUNET_ERROR_TYPE_INFO, " HMAC with key %s\n",
802 GNUNET_h2s ((struct GNUNET_HashCode *) key));
804 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
809 /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
810 GNUNET_CRYPTO_hmac (&auth_key, plaintext, size, &hash);
811 memcpy (hmac, &hash, sizeof (*hmac));
816 * Encrypt daforce_newest_keyta with the tunnel key.
818 * @param t Tunnel whose key to use.
819 * @param dst Destination for the encrypted data.
820 * @param src Source of the plaintext. Can overlap with @c dst.
821 * @param size Size of the plaintext.
822 * @param iv Initialization Vector to use.
823 * @param force_newest_key Force the use of the newest key, otherwise
824 * CADET will use the old key when allowed.
825 * This can happen in the case when a KX is going on
826 * and the old one hasn't expired.
829 t_encrypt (struct CadetTunnel *t, void *dst, const void *src,
830 size_t size, uint32_t iv, int force_newest_key)
832 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
833 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
836 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt start\n");
838 key = GNUNET_YES == force_newest_key ? &t->e_key : select_key (t);
839 #if DUMP_KEYS_TO_STDERR
840 LOG (GNUNET_ERROR_TYPE_INFO, " ENC with key %s\n",
841 GNUNET_h2s ((struct GNUNET_HashCode *) key));
843 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
844 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt IV derived\n");
845 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, key, &siv, dst);
846 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt end\n");
853 t_ax_hmac_hash (struct CadetTunnelAxolotl *ax,
854 struct GNUNET_CRYPTO_SymmetricSessionKey *key,
855 void *source, unsigned int len)
857 static const char ctx[] = "axolotl key derivation";
858 struct GNUNET_CRYPTO_AuthKey auth_key;
859 struct GNUNET_HashCode hash;
861 GNUNET_CRYPTO_hmac_derive_key (&auth_key, &ax->CKs,
864 GNUNET_CRYPTO_hmac (&auth_key, source, len, &hash);
865 GNUNET_CRYPTO_kdf (key, sizeof (*key),
867 &hash, sizeof (hash));
871 * Encrypt daforce_newest_keyta with the tunnel key.
873 * @param t Tunnel whose key to use.
874 * @param dst Destination for the encrypted data.
875 * @param src Source of the plaintext. Can overlap with @c dst.
876 * @param size Size of the plaintext.
878 * @return Size of the encrypted data.
881 t_ax_encrypt (struct CadetTunnel *t, void *dst, const void *src, size_t size)
883 struct GNUNET_CRYPTO_SymmetricSessionKey MK;
884 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
885 struct CadetTunnelAxolotl *ax;
888 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_ax_encrypt start\n");
892 if (GNUNET_YES == ax->ratchet_flag)
894 /* Advance ratchet */
897 t_ax_hmac_hash (ax, &MK, "0", 1);
898 GNUNET_CRYPTO_symmetric_derive_iv (&iv, &MK, NULL, 0, NULL);
901 #if DUMP_KEYS_TO_STDERR
902 LOG (GNUNET_ERROR_TYPE_INFO, " ENC with key %s\n",
903 GNUNET_h2s ((struct GNUNET_HashCode *) &MK));
905 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt IV derived\n");
906 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, &MK, &iv, dst);
907 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt end\n");
909 t_ax_hmac_hash (ax, &ax->CKs, "1", 1);
916 * Decrypt and verify data with the appropriate tunnel key.
918 * @param key Key to use.
919 * @param dst Destination for the plaintext.
920 * @param src Source of the encrypted data. Can overlap with @c dst.
921 * @param size Size of the encrypted data.
922 * @param iv Initialization Vector to use.
924 * @return Size of the decrypted data, -1 if an error was encountered.
927 decrypt (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
928 void *dst, const void *src, size_t size, uint32_t iv)
930 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
933 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt start\n");
934 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv\n");
935 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
936 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv done\n");
937 out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, key, &siv, dst);
938 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt end\n");
945 * Decrypt and verify data with the most recent tunnel key.
947 * @param t Tunnel whose key to use.
948 * @param dst Destination for the plaintext.
949 * @param src Source of the encrypted data. Can overlap with @c dst.
950 * @param size Size of the encrypted data.
951 * @param iv Initialization Vector to use.
953 * @return Size of the decrypted data, -1 if an error was encountered.
956 t_decrypt (struct CadetTunnel *t, void *dst, const void *src,
957 size_t size, uint32_t iv)
961 #if DUMP_KEYS_TO_STDERR
962 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_decrypt with %s\n",
963 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
965 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
967 GNUNET_STATISTICS_update (stats, "# non decryptable data", 1, GNUNET_NO);
968 LOG (GNUNET_ERROR_TYPE_WARNING,
969 "got data on %s without a valid key\n",
971 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
975 out_size = decrypt (&t->d_key, dst, src, size, iv);
982 * Decrypt and verify data with the appropriate tunnel key and verify that the
983 * data has not been altered since it was sent by the remote peer.
985 * @param t Tunnel whose key to use.
986 * @param dst Destination for the plaintext.
987 * @param src Source of the encrypted data. Can overlap with @c dst.
988 * @param size Size of the encrypted data.
989 * @param iv Initialization Vector to use.
990 * @param msg_hmac HMAC of the message, cannot be NULL.
992 * @return Size of the decrypted data, -1 if an error was encountered.
995 t_decrypt_and_validate (struct CadetTunnel *t,
996 void *dst, const void *src,
997 size_t size, uint32_t iv,
998 const struct GNUNET_CADET_Hash *msg_hmac)
1000 struct GNUNET_CRYPTO_SymmetricSessionKey *key;
1001 struct GNUNET_CADET_Hash hmac;
1004 /* Try primary (newest) key */
1006 decrypted_size = decrypt (key, dst, src, size, iv);
1007 t_hmac (src, size, iv, key, &hmac);
1008 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1009 return decrypted_size;
1011 /* If no key exchange is going on, we just failed. */
1012 if (NULL == t->kx_ctx)
1014 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1015 "Failed checksum validation on tunnel %s with no KX\n",
1017 GNUNET_STATISTICS_update (stats, "# wrong HMAC no KX", 1, GNUNET_NO);
1021 /* Try secondary key, from previous KX period. */
1022 key = &t->kx_ctx->d_key_old;
1023 decrypted_size = decrypt (key, dst, src, size, iv);
1024 t_hmac (src, size, iv, key, &hmac);
1025 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1026 return decrypted_size;
1028 /* Hail Mary, try tertiary, key, in case of parallel re-keys. */
1029 key = &t->kx_ctx->d_key_old2;
1030 decrypted_size = decrypt (key, dst, src, size, iv);
1031 t_hmac (src, size, iv, key, &hmac);
1032 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1033 return decrypted_size;
1035 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1036 "Failed checksum validation on tunnel %s with KX\n",
1038 GNUNET_STATISTICS_update (stats, "# wrong HMAC with KX", 1, GNUNET_NO);
1043 * Decrypt and verify data with the appropriate tunnel key and verify that the
1044 * data has not been altered since it was sent by the remote peer.
1046 * @param t Tunnel whose key to use.
1047 * @param dst Destination for the plaintext.
1048 * @param src Source of the encrypted data. Can overlap with @c dst.
1049 * @param size Size of the encrypted data.
1050 * @param msg_hmac HMAC of the message, cannot be NULL.
1052 * @return Size of the decrypted data, -1 if an error was encountered.
1055 t_ax_decrypt_and_validate (struct CadetTunnel *t,
1056 void *dst, const void *src, size_t size,
1057 const struct GNUNET_CADET_Hash *msg_hmac)
1059 struct CadetTunnelAxolotl *ax;
1074 * Create key material by doing ECDH on the local and remote ephemeral keys.
1076 * @param key_material Where to store the key material.
1077 * @param ephemeral_key Peer's public ephemeral key.
1080 derive_key_material (struct GNUNET_HashCode *key_material,
1081 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key)
1084 GNUNET_CRYPTO_ecc_ecdh (my_ephemeral_key,
1094 * Create a symmetic key from the identities of both ends and the key material
1097 * @param key Destination for the generated key.
1098 * @param sender ID of the peer that will encrypt with @c key.
1099 * @param receiver ID of the peer that will decrypt with @c key.
1100 * @param key_material Hash created with ECDH with the ephemeral keys.
1103 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
1104 const struct GNUNET_PeerIdentity *sender,
1105 const struct GNUNET_PeerIdentity *receiver,
1106 const struct GNUNET_HashCode *key_material)
1108 const char salt[] = "CADET kx salt";
1110 GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
1111 salt, sizeof (salt),
1112 key_material, sizeof (struct GNUNET_HashCode),
1113 sender, sizeof (struct GNUNET_PeerIdentity),
1114 receiver, sizeof (struct GNUNET_PeerIdentity),
1120 * Derive the tunnel's keys using our own and the peer's ephemeral keys.
1122 * @param t Tunnel for which to create the keys.
1125 create_keys (struct CadetTunnel *t)
1127 struct GNUNET_HashCode km;
1129 derive_key_material (&km, &t->peers_ephemeral_key);
1130 derive_symmertic (&t->e_key, &my_full_id, GCP_get_id (t->peer), &km);
1131 derive_symmertic (&t->d_key, GCP_get_id (t->peer), &my_full_id, &km);
1132 #if DUMP_KEYS_TO_STDERR
1133 LOG (GNUNET_ERROR_TYPE_INFO, "ME: %s\n",
1134 GNUNET_h2s ((struct GNUNET_HashCode *) &kx_msg.ephemeral_key));
1135 LOG (GNUNET_ERROR_TYPE_INFO, "PE: %s\n",
1136 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
1137 LOG (GNUNET_ERROR_TYPE_INFO, "KM: %s\n", GNUNET_h2s (&km));
1138 LOG (GNUNET_ERROR_TYPE_INFO, "EK: %s\n",
1139 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
1140 LOG (GNUNET_ERROR_TYPE_INFO, "DK: %s\n",
1141 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
1147 * Create a new Key eXchange context for the tunnel.
1149 * If the old keys were verified, keep them for old traffic. Create a new KX
1150 * timestamp and a new nonce.
1152 * @param t Tunnel for which to create the KX ctx.
1155 create_kx_ctx (struct CadetTunnel *t)
1157 LOG (GNUNET_ERROR_TYPE_INFO, " new kx ctx for %s\n", GCT_2s (t));
1159 if (NULL != t->kx_ctx)
1161 if (NULL != t->kx_ctx->finish_task)
1163 LOG (GNUNET_ERROR_TYPE_INFO, " resetting exisiting finish task\n");
1164 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
1165 t->kx_ctx->finish_task = NULL;
1170 t->kx_ctx = GNUNET_new (struct CadetTunnelKXCtx);
1171 t->kx_ctx->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1175 if (CADET_TUNNEL_KEY_OK == t->estate)
1177 LOG (GNUNET_ERROR_TYPE_INFO, " backing up keys\n");
1178 t->kx_ctx->d_key_old = t->d_key;
1179 t->kx_ctx->e_key_old = t->e_key;
1182 LOG (GNUNET_ERROR_TYPE_INFO, " old keys not valid, not saving\n");
1183 t->kx_ctx->rekey_start_time = GNUNET_TIME_absolute_get ();
1189 * @brief Finish the Key eXchange and destroy the old keys.
1191 * @param cls Closure (Tunnel for which to finish the KX).
1192 * @param tc Task context.
1195 finish_kx (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1197 struct CadetTunnel *t = cls;
1199 LOG (GNUNET_ERROR_TYPE_INFO, "finish KX for %s\n", GCT_2s (t));
1201 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1203 LOG (GNUNET_ERROR_TYPE_INFO, " shutdown\n");
1207 GNUNET_free (t->kx_ctx);
1213 * Destroy a Key eXchange context for the tunnel. This function only schedules
1214 * the destruction, the freeing of the memory (and clearing of old key material)
1215 * happens after a delay!
1217 * @param t Tunnel whose KX ctx to destroy.
1220 destroy_kx_ctx (struct CadetTunnel *t)
1222 struct GNUNET_TIME_Relative delay;
1224 if (NULL == t->kx_ctx || NULL != t->kx_ctx->finish_task)
1227 if (is_key_null (&t->kx_ctx->e_key_old))
1229 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_now (finish_kx, t);
1233 delay = GNUNET_TIME_relative_divide (rekey_period, 4);
1234 delay = GNUNET_TIME_relative_min (delay, GNUNET_TIME_UNIT_MINUTES);
1236 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_delayed (delay, finish_kx, t);
1242 * Pick a connection on which send the next data message.
1244 * @param t Tunnel on which to send the message.
1246 * @return The connection on which to send the next message.
1248 static struct CadetConnection *
1249 tunnel_get_connection (struct CadetTunnel *t)
1251 struct CadetTConnection *iter;
1252 struct CadetConnection *best;
1254 unsigned int lowest_q;
1256 LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GCT_2s (t));
1258 lowest_q = UINT_MAX;
1259 for (iter = t->connection_head; NULL != iter; iter = iter->next)
1261 LOG (GNUNET_ERROR_TYPE_DEBUG, " connection %s: %u\n",
1262 GCC_2s (iter->c), GCC_get_state (iter->c));
1263 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
1265 qn = GCC_get_qn (iter->c, GCC_is_origin (iter->c, GNUNET_YES));
1266 LOG (GNUNET_ERROR_TYPE_DEBUG, " q_n %u, \n", qn);
1274 LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GCC_2s (best));
1280 * Callback called when a queued message is sent.
1282 * Calculates the average time and connection packet tracking.
1284 * @param cls Closure (TunnelQueue handle).
1285 * @param c Connection this message was on.
1286 * @param q Connection queue handle (unused).
1287 * @param type Type of message sent.
1288 * @param fwd Was this a FWD going message?
1289 * @param size Size of the message.
1292 tun_message_sent (void *cls,
1293 struct CadetConnection *c,
1294 struct CadetConnectionQueue *q,
1295 uint16_t type, int fwd, size_t size)
1297 struct CadetTunnelQueue *qt = cls;
1298 struct CadetTunnel *t;
1300 LOG (GNUNET_ERROR_TYPE_DEBUG, "tun_message_sent\n");
1302 GNUNET_assert (NULL != qt->cont);
1303 t = NULL == c ? NULL : GCC_get_tunnel (c);
1304 qt->cont (qt->cont_cls, t, qt, type, size);
1310 count_queued_data (const struct CadetTunnel *t)
1312 struct CadetTunnelDelayed *iter;
1315 for (count = 0, iter = t->tq_head; iter != NULL; iter = iter->next)
1322 * Delete a queued message: either was sent or the channel was destroyed
1323 * before the tunnel's key exchange had a chance to finish.
1325 * @param tqd Delayed queue handle.
1328 unqueue_data (struct CadetTunnelDelayed *tqd)
1330 GNUNET_CONTAINER_DLL_remove (tqd->t->tq_head, tqd->t->tq_tail, tqd);
1336 * Cache a message to be sent once tunnel is online.
1338 * @param t Tunnel to hold the message.
1339 * @param msg Message itself (copy will be made).
1341 static struct CadetTunnelDelayed *
1342 queue_data (struct CadetTunnel *t, const struct GNUNET_MessageHeader *msg)
1344 struct CadetTunnelDelayed *tqd;
1345 uint16_t size = ntohs (msg->size);
1347 LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GCT_2s (t));
1349 if (GNUNET_YES == is_ready (t))
1355 tqd = GNUNET_malloc (sizeof (struct CadetTunnelDelayed) + size);
1358 memcpy (&tqd[1], msg, size);
1359 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
1365 * Sends an already built message on a tunnel, encrypting it and
1366 * choosing the best connection.
1368 * @param message Message to send. Function modifies it.
1369 * @param t Tunnel on which this message is transmitted.
1370 * @param c Connection to use (autoselect if NULL).
1371 * @param force Force the tunnel to take the message (buffer overfill).
1372 * @param cont Continuation to call once message is really sent.
1373 * @param cont_cls Closure for @c cont.
1374 * @param existing_q In case this a transmission of previously queued data,
1375 * this should be TunnelQueue given to the client.
1378 * @return Handle to cancel message.
1379 * NULL if @c cont is NULL or an error happens and message is dropped.
1381 static struct CadetTunnelQueue *
1382 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1383 struct CadetTunnel *t, struct CadetConnection *c,
1384 int force, GCT_sent cont, void *cont_cls,
1385 struct CadetTunnelQueue *existing_q)
1387 struct CadetTunnelQueue *tq;
1388 struct GNUNET_CADET_Encrypted *msg;
1389 size_t size = ntohs (message->size);
1390 char cbuf[sizeof (struct GNUNET_CADET_Encrypted) + size];
1397 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GCT_2s (t));
1399 if (GNUNET_NO == is_ready (t))
1401 struct CadetTunnelDelayed *tqd;
1402 /* A non null existing_q indicates sending of queued data.
1403 * Should only happen after tunnel becomes ready.
1405 GNUNET_assert (NULL == existing_q);
1406 tqd = queue_data (t, message);
1409 tq = GNUNET_new (struct CadetTunnelQueue);
1413 tq->cont_cls = cont_cls;
1417 GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1419 iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1420 msg = (struct GNUNET_CADET_Encrypted *) cbuf;
1421 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
1424 if (CADET_Axolotl == t->enc_type)
1425 esize = t_ax_encrypt (t, &msg[1], message, size);
1427 esize = t_encrypt (t, &msg[1], message, size, iv, GNUNET_NO);
1428 GNUNET_assert (esize == size);
1429 t_hmac (&msg[1], size, iv, select_key (t), &msg->hmac);
1430 msg->header.size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
1433 c = tunnel_get_connection (t);
1436 /* Why is tunnel 'ready'? Should have been queued! */
1437 if (NULL != t->destroy_task)
1440 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1442 return NULL; /* Drop... */
1446 type = ntohs (message->type);
1449 case GNUNET_MESSAGE_TYPE_CADET_DATA:
1450 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1451 if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
1452 mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
1454 mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
1456 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1457 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1458 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1459 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1460 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1461 msg->cid = *GCC_get_id (c);
1462 msg->ttl = htonl (default_ttl);
1466 LOG (GNUNET_ERROR_TYPE_ERROR, "type %s not valid\n", GC_m2s (type));
1468 LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
1470 fwd = GCC_is_origin (c, GNUNET_YES);
1474 GNUNET_break (NULL == GCC_send_prebuilt_message (&msg->header, type, mid, c,
1475 fwd, force, NULL, NULL));
1478 if (NULL == existing_q)
1480 tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
1487 tq->cq = GCC_send_prebuilt_message (&msg->header, type, mid, c, fwd, force,
1488 &tun_message_sent, tq);
1489 GNUNET_assert (NULL != tq->cq);
1491 tq->cont_cls = cont_cls;
1498 * Send all cached messages that we can, tunnel is online.
1500 * @param t Tunnel that holds the messages. Cannot be loopback.
1503 send_queued_data (struct CadetTunnel *t)
1505 struct CadetTunnelDelayed *tqd;
1506 struct CadetTunnelDelayed *next;
1509 LOG (GNUNET_ERROR_TYPE_INFO, "Send queued data, tunnel %s\n", GCT_2s (t));
1511 if (GCT_is_loopback (t))
1517 if (GNUNET_NO == is_ready (t))
1519 LOG (GNUNET_ERROR_TYPE_DEBUG, " not ready yet: %s/%s\n",
1520 estate2s (t->estate), cstate2s (t->cstate));
1524 room = GCT_get_connections_buffer (t);
1525 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
1526 LOG (GNUNET_ERROR_TYPE_DEBUG, " tq head: %p\n", t->tq_head);
1527 for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
1529 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
1532 send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
1533 tqd->t, NULL, GNUNET_YES,
1534 NULL != tqd->tq ? tqd->tq->cont : NULL,
1535 NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
1539 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
1544 * Callback called when a queued message is sent.
1546 * @param cls Closure.
1547 * @param c Connection this message was on.
1548 * @param type Type of message sent.
1549 * @param fwd Was this a FWD going message?
1550 * @param size Size of the message.
1553 ephm_sent (void *cls,
1554 struct CadetConnection *c,
1555 struct CadetConnectionQueue *q,
1556 uint16_t type, int fwd, size_t size)
1558 struct CadetTunnel *t = cls;
1559 LOG (GNUNET_ERROR_TYPE_DEBUG, "ephm_sent %s\n", GC_m2s (type));
1564 * Callback called when a queued message is sent.
1566 * @param cls Closure.
1567 * @param c Connection this message was on.
1568 * @param type Type of message sent.
1569 * @param fwd Was this a FWD going message?
1570 * @param size Size of the message.
1573 pong_sent (void *cls,
1574 struct CadetConnection *c,
1575 struct CadetConnectionQueue *q,
1576 uint16_t type, int fwd, size_t size)
1578 struct CadetTunnel *t = cls;
1579 LOG (GNUNET_ERROR_TYPE_DEBUG, "pong_sent %s\n", GC_m2s (type));
1585 * Sends key exchange message on a tunnel, choosing the best connection.
1586 * Should not be called on loopback tunnels.
1588 * @param t Tunnel on which this message is transmitted.
1589 * @param message Message to send. Function modifies it.
1591 * @return Handle to the message in the connection queue.
1593 static struct CadetConnectionQueue *
1594 send_kx (struct CadetTunnel *t,
1595 const struct GNUNET_MessageHeader *message)
1597 struct CadetConnection *c;
1598 struct GNUNET_CADET_KX *msg;
1599 size_t size = ntohs (message->size);
1600 char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
1605 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
1607 /* Avoid loopback. */
1608 if (GCT_is_loopback (t))
1610 LOG (GNUNET_ERROR_TYPE_DEBUG, " loopback!\n");
1614 type = ntohs (message->type);
1616 /* Even if tunnel is "being destroyed", send anyway.
1617 * Could be a response to a rekey initiated by remote peer,
1618 * who is trying to create a new channel!
1621 /* Must have a connection, or be looking for one. */
1622 if (NULL == t->connection_head)
1624 LOG (GNUNET_ERROR_TYPE_DEBUG, "%s while no connection\n", GC_m2s (type));
1625 if (CADET_TUNNEL_SEARCHING != t->cstate)
1628 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
1629 GCP_debug (t->peer, GNUNET_ERROR_TYPE_ERROR);
1634 msg = (struct GNUNET_CADET_KX *) cbuf;
1635 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
1636 msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
1637 c = tunnel_get_connection (t);
1640 if (NULL == t->destroy_task
1641 && CADET_TUNNEL_READY == t->cstate)
1644 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
1650 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
1651 GNUNET_assert (NULL == t->ephm_h);
1653 memcpy (&msg[1], message, size);
1655 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
1656 GNUNET_assert (NULL == t->pong_h);
1658 memcpy (&msg[1], message, size);
1662 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n", GC_m2s (type));
1666 fwd = GCC_is_origin (t->connection_head->c, GNUNET_YES);
1668 return GCC_send_prebuilt_message (&msg->header, type, 0, c,
1675 * Send the ephemeral key on a tunnel.
1677 * @param t Tunnel on which to send the key.
1680 send_ephemeral (struct CadetTunnel *t)
1682 LOG (GNUNET_ERROR_TYPE_INFO, "===> EPHM for %s\n", GCT_2s (t));
1683 if (NULL != t->ephm_h)
1685 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
1689 kx_msg.sender_status = htonl (t->estate);
1690 kx_msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1691 kx_msg.nonce = t->kx_ctx->challenge;
1692 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce c %u\n", kx_msg.nonce);
1693 t_encrypt (t, &kx_msg.nonce, &kx_msg.nonce,
1694 ping_encryption_size(), kx_msg.iv, GNUNET_YES);
1695 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce e %u\n", kx_msg.nonce);
1696 t->ephm_h = send_kx (t, &kx_msg.header);
1701 * Send a pong message on a tunnel.
1703 * @param t Tunnel on which to send the pong.
1704 * @param challenge Value sent in the ping that we have to send back.
1707 send_pong (struct CadetTunnel *t, uint32_t challenge)
1709 struct GNUNET_CADET_KX_Pong msg;
1711 LOG (GNUNET_ERROR_TYPE_INFO, "===> PONG for %s\n", GCT_2s (t));
1712 if (NULL != t->pong_h)
1714 LOG (GNUNET_ERROR_TYPE_INFO, " already queued\n");
1717 msg.header.size = htons (sizeof (msg));
1718 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
1719 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1720 msg.nonce = challenge;
1721 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
1722 t_encrypt (t, &msg.nonce, &msg.nonce,
1723 sizeof (msg.nonce), msg.iv, GNUNET_YES);
1724 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
1726 t->pong_h = send_kx (t, &msg.header);
1731 * Initiate a rekey with the remote peer.
1733 * @param cls Closure (tunnel).
1734 * @param tc TaskContext.
1737 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1739 struct CadetTunnel *t = cls;
1741 t->rekey_task = NULL;
1743 LOG (GNUNET_ERROR_TYPE_INFO, "Re-key Tunnel %s\n", GCT_2s (t));
1744 if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1747 GNUNET_assert (NULL != t->kx_ctx);
1748 struct GNUNET_TIME_Relative duration;
1750 duration = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
1751 LOG (GNUNET_ERROR_TYPE_DEBUG, " kx started %s ago\n",
1752 GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
1754 // FIXME make duration of old keys configurable
1755 if (duration.rel_value_us >= GNUNET_TIME_UNIT_MINUTES.rel_value_us)
1757 LOG (GNUNET_ERROR_TYPE_DEBUG, " deleting old keys\n");
1758 memset (&t->kx_ctx->d_key_old, 0, sizeof (t->kx_ctx->d_key_old));
1759 memset (&t->kx_ctx->e_key_old, 0, sizeof (t->kx_ctx->e_key_old));
1766 case CADET_TUNNEL_KEY_UNINITIALIZED:
1767 GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
1770 case CADET_TUNNEL_KEY_SENT:
1773 case CADET_TUNNEL_KEY_OK:
1775 * - state should have changed during rekey_iterator
1776 * - task should have been canceled at pong_handle
1779 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
1782 case CADET_TUNNEL_KEY_PING:
1783 case CADET_TUNNEL_KEY_REKEY:
1787 LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
1790 // FIXME exponential backoff
1791 struct GNUNET_TIME_Relative delay;
1793 delay = GNUNET_TIME_relative_divide (rekey_period, 16);
1794 delay = GNUNET_TIME_relative_min (delay, REKEY_WAIT);
1795 LOG (GNUNET_ERROR_TYPE_DEBUG, " next call in %s\n",
1796 GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
1797 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1802 * Our ephemeral key has changed, create new session key on all tunnels.
1804 * Each tunnel will start the Key Exchange with a random delay between
1805 * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
1806 * per second, on average.
1808 * @param cls Closure (size of the hashmap).
1809 * @param key Current public key.
1810 * @param value Value in the hash map (tunnel).
1812 * @return #GNUNET_YES, so we should continue to iterate,
1815 rekey_iterator (void *cls,
1816 const struct GNUNET_PeerIdentity *key,
1819 struct CadetTunnel *t = value;
1820 struct GNUNET_TIME_Relative delay;
1821 long n = (long) cls;
1824 if (NULL != t->rekey_task)
1827 if (GNUNET_YES == GCT_is_loopback (t))
1830 r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
1831 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
1832 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1834 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
1841 * Create a new ephemeral key and key message, schedule next rekeying.
1843 * @param cls Closure (unused).
1844 * @param tc TaskContext.
1847 rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1849 struct GNUNET_TIME_Absolute time;
1854 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1857 GNUNET_free_non_null (my_ephemeral_key);
1858 my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
1860 time = GNUNET_TIME_absolute_get ();
1861 kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
1862 time = GNUNET_TIME_absolute_add (time, rekey_period);
1863 time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
1864 kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
1865 GNUNET_CRYPTO_ecdhe_key_get_public (my_ephemeral_key, &kx_msg.ephemeral_key);
1866 LOG (GNUNET_ERROR_TYPE_INFO, "GLOBAL RE-KEY, NEW EPHM: %s\n",
1867 GNUNET_h2s ((struct GNUNET_HashCode *) &kx_msg.ephemeral_key));
1869 GNUNET_assert (GNUNET_OK ==
1870 GNUNET_CRYPTO_eddsa_sign (my_private_key,
1872 &kx_msg.signature));
1874 n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
1875 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
1877 rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period, &rekey, NULL);
1882 * Called only on shutdown, destroy every tunnel.
1884 * @param cls Closure (unused).
1885 * @param key Current public key.
1886 * @param value Value in the hash map (tunnel).
1888 * @return #GNUNET_YES, so we should continue to iterate,
1891 destroy_iterator (void *cls,
1892 const struct GNUNET_PeerIdentity *key,
1895 struct CadetTunnel *t = value;
1897 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
1904 * Notify remote peer that we don't know a channel he is talking about,
1905 * probably CHANNEL_DESTROY was missed.
1907 * @param t Tunnel on which to notify.
1908 * @param gid ID of the channel.
1911 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
1913 struct GNUNET_CADET_ChannelManage msg;
1915 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
1916 msg.header.size = htons (sizeof (msg));
1917 msg.chid = htonl (gid);
1919 LOG (GNUNET_ERROR_TYPE_DEBUG,
1920 "WARNING destroying unknown channel %u on tunnel %s\n",
1922 send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
1927 * Demultiplex data per channel and call appropriate channel handler.
1929 * @param t Tunnel on which the data came.
1930 * @param msg Data message.
1931 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1932 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1933 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1934 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1937 handle_data (struct CadetTunnel *t,
1938 const struct GNUNET_CADET_Data *msg,
1941 struct CadetChannel *ch;
1945 size = ntohs (msg->header.size);
1947 sizeof (struct GNUNET_CADET_Data) +
1948 sizeof (struct GNUNET_MessageHeader))
1953 LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
1954 GC_m2s (ntohs (msg[1].header.type)));
1957 ch = GCT_get_channel (t, ntohl (msg->chid));
1960 GNUNET_STATISTICS_update (stats, "# data on unknown channel",
1962 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
1964 send_channel_destroy (t, ntohl (msg->chid));
1968 GCCH_handle_data (ch, msg, fwd);
1973 * Demultiplex data ACKs per channel and update appropriate channel buffer info.
1975 * @param t Tunnel on which the DATA ACK came.
1976 * @param msg DATA ACK message.
1977 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1978 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1979 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1980 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1983 handle_data_ack (struct CadetTunnel *t,
1984 const struct GNUNET_CADET_DataACK *msg,
1987 struct CadetChannel *ch;
1991 size = ntohs (msg->header.size);
1992 if (size != sizeof (struct GNUNET_CADET_DataACK))
1999 ch = GCT_get_channel (t, ntohl (msg->chid));
2002 GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
2004 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2009 GCCH_handle_data_ack (ch, msg, fwd);
2014 * Handle channel create.
2016 * @param t Tunnel on which the data came.
2017 * @param msg Data message.
2020 handle_ch_create (struct CadetTunnel *t,
2021 const struct GNUNET_CADET_ChannelCreate *msg)
2023 struct CadetChannel *ch;
2027 size = ntohs (msg->header.size);
2028 if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
2035 ch = GCT_get_channel (t, ntohl (msg->chid));
2036 if (NULL != ch && ! GCT_is_loopback (t))
2038 /* Probably a retransmission, safe to ignore */
2039 LOG (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
2041 ch = GCCH_handle_create (t, msg);
2043 GCT_add_channel (t, ch);
2049 * Handle channel NACK: check correctness and call channel handler for NACKs.
2051 * @param t Tunnel on which the NACK came.
2052 * @param msg NACK message.
2055 handle_ch_nack (struct CadetTunnel *t,
2056 const struct GNUNET_CADET_ChannelManage *msg)
2058 struct CadetChannel *ch;
2062 size = ntohs (msg->header.size);
2063 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2070 ch = GCT_get_channel (t, ntohl (msg->chid));
2073 GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
2075 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2080 GCCH_handle_nack (ch);
2085 * Handle a CHANNEL ACK (SYNACK/ACK).
2087 * @param t Tunnel on which the CHANNEL ACK came.
2088 * @param msg CHANNEL ACK message.
2089 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2090 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2091 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2092 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2095 handle_ch_ack (struct CadetTunnel *t,
2096 const struct GNUNET_CADET_ChannelManage *msg,
2099 struct CadetChannel *ch;
2103 size = ntohs (msg->header.size);
2104 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2111 ch = GCT_get_channel (t, ntohl (msg->chid));
2114 GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
2116 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2121 GCCH_handle_ack (ch, msg, fwd);
2126 * Handle a channel destruction message.
2128 * @param t Tunnel on which the message came.
2129 * @param msg Channel destroy message.
2130 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2131 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2132 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2133 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2136 handle_ch_destroy (struct CadetTunnel *t,
2137 const struct GNUNET_CADET_ChannelManage *msg,
2140 struct CadetChannel *ch;
2144 size = ntohs (msg->header.size);
2145 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2152 ch = GCT_get_channel (t, ntohl (msg->chid));
2155 /* Probably a retransmission, safe to ignore */
2159 GCCH_handle_destroy (ch, msg, fwd);
2164 * Create a new Axolotl ephemeral (ratchet) key.
2169 new_ephemeral (struct CadetTunnel *t)
2171 GNUNET_free_non_null (t->ax->DHRs);
2172 t->ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create();
2177 * Free Axolotl data.
2182 destroy_ax (struct CadetTunnel *t)
2187 if (NULL != t->ax->DHRs)
2188 GNUNET_free (t->ax->DHRs);
2189 GNUNET_free (t->ax);
2196 * The peer's ephemeral key has changed: update the symmetrical keys.
2198 * @param t Tunnel this message came on.
2199 * @param msg Key eXchange message.
2202 handle_ephemeral (struct CadetTunnel *t,
2203 const struct GNUNET_CADET_KX_Ephemeral *msg)
2205 LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
2207 if (GNUNET_OK != check_ephemeral (t, msg))
2209 GNUNET_break_op (0);
2213 /* If we get a proper OTR-style ephemeral, fallback to old crypto. */
2217 t->enc_type = CADET_Fallback;
2221 * If the key is different from what we know, derive the new E/D keys.
2222 * Else destroy the rekey ctx (duplicate EPHM after successful KX).
2224 if (0 != memcmp (&t->peers_ephemeral_key, &msg->ephemeral_key,
2225 sizeof (msg->ephemeral_key)))
2227 #if DUMP_KEYS_TO_STDERR
2228 LOG (GNUNET_ERROR_TYPE_INFO, "OLD: %s\n",
2229 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
2230 LOG (GNUNET_ERROR_TYPE_INFO, "NEW: %s\n",
2231 GNUNET_h2s ((struct GNUNET_HashCode *) &msg->ephemeral_key));
2233 t->peers_ephemeral_key = msg->ephemeral_key;
2237 if (CADET_TUNNEL_KEY_OK == t->estate)
2239 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2241 if (NULL != t->rekey_task)
2242 GNUNET_SCHEDULER_cancel (t->rekey_task);
2243 t->rekey_task = GNUNET_SCHEDULER_add_now (rekey_tunnel, t);
2245 if (CADET_TUNNEL_KEY_SENT == t->estate)
2247 LOG (GNUNET_ERROR_TYPE_DEBUG, " our key was sent, sending challenge\n");
2249 GCT_change_estate (t, CADET_TUNNEL_KEY_PING);
2252 if (CADET_TUNNEL_KEY_UNINITIALIZED != ntohl(msg->sender_status))
2256 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce e %u\n", msg->nonce);
2257 t_decrypt (t, &nonce, &msg->nonce, ping_encryption_size (), msg->iv);
2258 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce c %u\n", nonce);
2259 send_pong (t, nonce);
2265 * Peer has answer to our challenge.
2266 * If answer is successful, consider the key exchange finished and clean
2267 * up all related state.
2269 * @param t Tunnel this message came on.
2270 * @param msg Key eXchange Pong message.
2273 handle_pong (struct CadetTunnel *t, const struct GNUNET_CADET_KX_Pong *msg)
2277 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
2278 if (NULL == t->rekey_task)
2280 GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
2283 if (NULL == t->kx_ctx)
2285 GNUNET_STATISTICS_update (stats, "# stray PONG messages", 1, GNUNET_NO);
2289 t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
2290 if (challenge != t->kx_ctx->challenge)
2292 LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
2293 LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
2294 challenge, msg->nonce, t->kx_ctx->challenge);
2298 GNUNET_SCHEDULER_cancel (t->rekey_task);
2299 t->rekey_task = NULL;
2301 /* Don't free the old keys right away, but after a delay.
2302 * Rationale: the KX could have happened over a very fast connection,
2303 * with payload traffic still signed with the old key stuck in a slower
2305 * Don't keep the keys longer than 1/4 the rekey period, and no longer than
2309 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2321 * WARNING! DANGER! Do not use this if you don't know what you are doing!
2322 * Ask Christian Grothoff, Werner Koch, Dan Bernstein and $GOD!
2324 * Transform a private EdDSA key (peer's key) into a key usable by DH.
2326 * @param k Private EdDSA key to transform.
2328 * @return Private key for EC Diffie-Hellman.
2330 static const struct GNUNET_CRYPTO_EcdhePrivateKey *
2331 get_private_ecdhe_from_eddsa (const struct GNUNET_CRYPTO_EddsaPrivateKey *k)
2333 return (const struct GNUNET_CRYPTO_EcdhePrivateKey *) k;
2338 * WARNING! DANGER! Do not use this if you don't know what you are doing!
2339 * Ask Christian Grothoff, Werner Koch, Dan Bernstein and $GOD!
2341 * Transform a public EdDSA key (peer's key) into a key usable by DH.
2343 * @param k Public EdDSA key to transform (peer's ID).
2345 * @return Public key for EC Diffie-Hellman.
2347 static const struct GNUNET_CRYPTO_EcdhePublicKey *
2348 get_public_ecdhe_from_id (const struct GNUNET_PeerIdentity *id)
2350 return (const struct GNUNET_CRYPTO_EcdhePublicKey *) id;
2355 * Handle Axolotl handshake.
2357 * @param t Tunnel this message came on.
2358 * @param msg Key eXchange Pong message.
2361 handle_kx_ax (struct CadetTunnel *t, const struct GNUNET_CADET_AX_KX *msg)
2363 struct GNUNET_CRYPTO_EcdhePublicKey eph;
2364 struct CadetTunnelAxolotl *ax;
2365 struct GNUNET_HashCode key_material[3];
2366 struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
2367 const struct GNUNET_CRYPTO_EcdhePublicKey *pub;
2368 const struct GNUNET_CRYPTO_EcdhePrivateKey *priv;
2369 const char salt[] = "CADET Axolotl salt";
2370 const struct GNUNET_PeerIdentity *pid;
2375 /* Something is wrong if ax is NULL. Whose fault it is? */
2376 GNUNET_break_op (CADET_Fallback == t->enc_type);
2377 GNUNET_break (CADET_Axolotl == t->enc_type);
2381 pid = GCT_get_destination (t);
2382 if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2383 is_alice = GNUNET_YES;
2384 else if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2385 is_alice = GNUNET_NO;
2388 GNUNET_break_op (0);
2393 ax->DHRr = msg->ratchet_key;
2395 GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs, &eph);
2396 if (0 != memcmp (&eph, &msg->peers_key, sizeof (eph)))
2403 if (GNUNET_YES == is_alice)
2405 priv = get_private_ecdhe_from_eddsa (my_private_key); /* A */
2406 pub = &msg->ephemeral_key; /* B0 */
2410 priv = ax->DHRs; /* B0 */
2411 pub = get_public_ecdhe_from_id (pid); /* A */
2413 GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[0]);
2416 if (GNUNET_YES == is_alice)
2418 priv = ax->DHRs; /* A0 */
2419 pub = get_public_ecdhe_from_id (pid); /* B */
2423 priv = get_private_ecdhe_from_eddsa (my_private_key); /* B */
2424 pub = &msg->ephemeral_key; /* A0 */
2426 GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[1]);
2429 priv = ax->DHRs; /* A0 or B0 */
2430 pub = &msg->ephemeral_key; /* B0 or A0 */
2431 GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[2]);
2434 GNUNET_CRYPTO_kdf (keys, sizeof (keys),
2435 salt, sizeof (salt),
2436 key_material, sizeof (key_material), NULL);
2439 if (GNUNET_YES == is_alice)
2445 ax->ratchet_flag = GNUNET_YES;
2453 ax->ratchet_flag = GNUNET_NO;
2459 * Demultiplex by message type and call appropriate handler for a message
2460 * towards a channel of a local tunnel.
2462 * @param t Tunnel this message came on.
2463 * @param msgh Message header.
2464 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2465 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2466 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2467 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2470 handle_decrypted (struct CadetTunnel *t,
2471 const struct GNUNET_MessageHeader *msgh,
2476 type = ntohs (msgh->type);
2477 LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
2481 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
2482 /* Do nothing, connection aleady got updated. */
2483 GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
2486 case GNUNET_MESSAGE_TYPE_CADET_DATA:
2487 /* Don't send hop ACK, wait for client to ACK */
2488 handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
2491 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
2492 handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
2495 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
2496 handle_ch_create (t, (struct GNUNET_CADET_ChannelCreate *) msgh);
2499 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
2500 handle_ch_nack (t, (struct GNUNET_CADET_ChannelManage *) msgh);
2503 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
2504 handle_ch_ack (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
2507 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
2508 handle_ch_destroy (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
2512 GNUNET_break_op (0);
2513 LOG (GNUNET_ERROR_TYPE_WARNING,
2514 "end-to-end message not known (%u)\n",
2515 ntohs (msgh->type));
2516 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
2520 /******************************************************************************/
2521 /******************************** API ***********************************/
2522 /******************************************************************************/
2524 * Decrypt old format and demultiplex by message type. Call appropriate handler
2525 * for a message towards a channel of a local tunnel.
2527 * @param t Tunnel this message came on.
2528 * @param msg Message header.
2531 GCT_handle_encrypted (struct CadetTunnel *t,
2532 const struct GNUNET_MessageHeader *msg)
2534 size_t size = ntohs (msg->size);
2535 size_t payload_size;
2538 uint16_t type = ntohs (msg->type);
2539 struct GNUNET_MessageHeader *msgh;
2542 if (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED == type)
2544 const struct GNUNET_CADET_Encrypted *emsg;
2546 emsg = (struct GNUNET_CADET_Encrypted *) msg;
2547 payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
2548 decrypted_size = t_decrypt_and_validate (t, cbuf, &emsg[1], payload_size,
2549 emsg->iv, &emsg->hmac);
2551 else if (GNUNET_MESSAGE_TYPE_CADET_AX == type)
2553 const struct GNUNET_CADET_AX *emsg;
2555 emsg = (struct GNUNET_CADET_AX *) msg;
2556 payload_size = size - sizeof (struct GNUNET_CADET_AX);
2557 decrypted_size = t_ax_decrypt_and_validate (t, cbuf, &emsg[1],
2558 payload_size, &emsg->hmac);
2561 if (-1 == decrypted_size)
2563 GNUNET_break_op (0);
2568 while (off < decrypted_size)
2572 msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
2573 msize = ntohs (msgh->size);
2574 if (msize < sizeof (struct GNUNET_MessageHeader))
2576 GNUNET_break_op (0);
2579 handle_decrypted (t, msgh, GNUNET_SYSERR);
2586 * Demultiplex an encapsulated KX message by message type.
2588 * @param t Tunnel on which the message came.
2589 * @param message Payload of KX message.
2592 GCT_handle_kx (struct CadetTunnel *t,
2593 const struct GNUNET_MessageHeader *message)
2597 type = ntohs (message->type);
2598 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received: %s\n", GC_m2s (type));
2601 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
2602 handle_ephemeral (t, (const struct GNUNET_CADET_KX_Ephemeral *) message);
2605 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
2606 handle_pong (t, (const struct GNUNET_CADET_KX_Pong *) message);
2609 case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
2610 handle_kx_ax (t, (const struct GNUNET_CADET_AX_KX *) message);
2614 GNUNET_break_op (0);
2615 LOG (GNUNET_ERROR_TYPE_WARNING, "kx message %s unknown\n", GC_m2s (type));
2621 * Initialize the tunnel subsystem.
2623 * @param c Configuration handle.
2624 * @param key ECC private key, to derive all other keys and do crypto.
2627 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
2628 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
2630 int expected_overhead;
2632 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
2634 expected_overhead = 0;
2635 expected_overhead += sizeof (struct GNUNET_CADET_Encrypted);
2636 expected_overhead += sizeof (struct GNUNET_CADET_Data);
2637 expected_overhead += sizeof (struct GNUNET_CADET_ACK);
2638 GNUNET_assert (GNUNET_CONSTANTS_CADET_P2P_OVERHEAD == expected_overhead);
2641 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
2644 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
2645 "CADET", "DEFAULT_TTL", "USING DEFAULT");
2649 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
2652 rekey_period = GNUNET_TIME_UNIT_DAYS;
2655 my_private_key = key;
2657 kx_msg.header.size = htons (sizeof (kx_msg));
2658 kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
2659 kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
2660 kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
2661 kx_msg.origin_identity = my_full_id;
2662 rekey_task = GNUNET_SCHEDULER_add_now (&rekey, NULL);
2664 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
2669 * Shut down the tunnel subsystem.
2674 if (NULL != rekey_task)
2676 GNUNET_SCHEDULER_cancel (rekey_task);
2679 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
2680 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
2687 * @param destination Peer this tunnel is towards.
2689 struct CadetTunnel *
2690 GCT_new (struct CadetPeer *destination)
2692 struct CadetTunnel *t;
2694 t = GNUNET_new (struct CadetTunnel);
2696 t->peer = destination;
2699 GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
2700 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2706 t->ax = GNUNET_new (struct CadetTunnelAxolotl);
2713 * Change the tunnel's connection state.
2715 * @param t Tunnel whose connection state to change.
2716 * @param cstate New connection state.
2719 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
2723 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
2724 GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
2725 if (myid != GCP_get_short_id (t->peer) &&
2726 CADET_TUNNEL_READY != t->cstate &&
2727 CADET_TUNNEL_READY == cstate)
2730 if (CADET_TUNNEL_KEY_OK == t->estate)
2732 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered send queued data\n");
2733 send_queued_data (t);
2735 else if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
2737 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered rekey\n");
2738 if (NULL != t->rekey_task)
2739 GNUNET_SCHEDULER_cancel (t->rekey_task);
2741 rekey_tunnel (t, NULL);
2746 if (CADET_TUNNEL_READY == cstate
2747 && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
2749 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered stop dht\n");
2750 GCP_stop_search (t->peer);
2756 * Change the tunnel encryption state.
2758 * @param t Tunnel whose encryption state to change, or NULL.
2759 * @param state New encryption state.
2762 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
2764 enum CadetTunnelEState old;
2771 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate was %s\n",
2772 GCP_2s (t->peer), estate2s (old));
2773 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate is now %s\n",
2774 GCP_2s (t->peer), estate2s (t->estate));
2776 /* Send queued data if enc state changes to OK */
2777 if (myid != GCP_get_short_id (t->peer) &&
2778 CADET_TUNNEL_KEY_OK != old && CADET_TUNNEL_KEY_OK == t->estate)
2780 send_queued_data (t);
2786 * @brief Check if tunnel has too many connections, and remove one if necessary.
2788 * Currently this means the newest connection, unless it is a direct one.
2789 * Implemented as a task to avoid freeing a connection that is in the middle
2790 * of being created/processed.
2792 * @param cls Closure (Tunnel to check).
2793 * @param tc Task context.
2796 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2798 struct CadetTunnel *t = cls;
2800 t->trim_connections_task = NULL;
2802 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2805 if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
2807 struct CadetTConnection *iter;
2808 struct CadetTConnection *c;
2810 for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
2812 if ((iter->created.abs_value_us > c->created.abs_value_us)
2813 && GNUNET_NO == GCC_is_direct (iter->c))
2820 LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
2822 LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
2835 * Add a connection to a tunnel.
2838 * @param c Connection.
2841 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
2843 struct CadetTConnection *aux;
2845 GNUNET_assert (NULL != c);
2847 LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
2848 LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
2849 for (aux = t->connection_head; aux != NULL; aux = aux->next)
2853 aux = GNUNET_new (struct CadetTConnection);
2855 aux->created = GNUNET_TIME_absolute_get ();
2857 GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
2859 if (CADET_TUNNEL_SEARCHING == t->cstate)
2860 GCT_change_estate (t, CADET_TUNNEL_WAITING);
2862 if (NULL != t->trim_connections_task)
2863 t->trim_connections_task = GNUNET_SCHEDULER_add_now (&trim_connections, t);
2868 * Remove a connection from a tunnel.
2871 * @param c Connection.
2874 GCT_remove_connection (struct CadetTunnel *t,
2875 struct CadetConnection *c)
2877 struct CadetTConnection *aux;
2878 struct CadetTConnection *next;
2881 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
2882 GCC_2s (c), GCT_2s (t));
2883 for (aux = t->connection_head; aux != NULL; aux = next)
2888 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
2893 conns = GCT_count_connections (t);
2895 && NULL == t->destroy_task
2896 && CADET_TUNNEL_SHUTDOWN != t->cstate
2897 && GNUNET_NO == shutting_down)
2899 if (0 == GCT_count_any_connections (t))
2900 GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
2902 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
2905 /* Start new connections if needed */
2906 if (CONNECTIONS_PER_TUNNEL > conns
2907 && NULL == t->destroy_task
2908 && CADET_TUNNEL_SHUTDOWN != t->cstate
2909 && GNUNET_NO == shutting_down)
2911 LOG (GNUNET_ERROR_TYPE_DEBUG, " too few connections, getting new ones\n");
2912 GCP_connect (t->peer); /* Will change cstate to WAITING when possible */
2916 /* If not marked as ready, no change is needed */
2917 if (CADET_TUNNEL_READY != t->cstate)
2920 /* Check if any connection is ready to maintain cstate */
2921 for (aux = t->connection_head; aux != NULL; aux = aux->next)
2922 if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
2928 * Add a channel to a tunnel.
2931 * @param ch Channel.
2934 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2936 struct CadetTChannel *aux;
2938 GNUNET_assert (NULL != ch);
2940 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
2942 for (aux = t->channel_head; aux != NULL; aux = aux->next)
2944 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
2949 aux = GNUNET_new (struct CadetTChannel);
2951 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
2952 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
2954 if (NULL != t->destroy_task)
2956 GNUNET_SCHEDULER_cancel (t->destroy_task);
2957 t->destroy_task = NULL;
2958 LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
2964 * Remove a channel from a tunnel.
2967 * @param ch Channel.
2970 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2972 struct CadetTChannel *aux;
2974 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
2975 for (aux = t->channel_head; aux != NULL; aux = aux->next)
2979 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
2980 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
2989 * Search for a channel by global ID.
2991 * @param t Tunnel containing the channel.
2992 * @param chid Public channel number.
2994 * @return channel handler, NULL if doesn't exist
2996 struct CadetChannel *
2997 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
2999 struct CadetTChannel *iter;
3004 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3006 if (GCCH_get_id (iter->ch) == chid)
3010 return NULL == iter ? NULL : iter->ch;
3015 * @brief Destroy a tunnel and free all resources.
3017 * Should only be called a while after the tunnel has been marked as destroyed,
3018 * in case there is a new channel added to the same peer shortly after marking
3019 * the tunnel. This way we avoid a new public key handshake.
3021 * @param cls Closure (tunnel to destroy).
3022 * @param tc Task context.
3025 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3027 struct CadetTunnel *t = cls;
3028 struct CadetTConnection *iter;
3030 LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
3031 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
3033 LOG (GNUNET_ERROR_TYPE_WARNING,
3034 "Not destroying tunnel, due to shutdown. "
3035 "Tunnel at %p should have been freed by GCT_shutdown\n", t);
3038 t->destroy_task = NULL;
3039 t->cstate = CADET_TUNNEL_SHUTDOWN;
3041 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3043 GCC_send_destroy (iter->c);
3050 * Tunnel is empty: destroy it.
3052 * Notifies all connections about the destruction.
3054 * @param t Tunnel to destroy.
3057 GCT_destroy_empty (struct CadetTunnel *t)
3059 if (GNUNET_YES == shutting_down)
3060 return; /* Will be destroyed immediately anyway */
3062 if (NULL != t->destroy_task)
3064 LOG (GNUNET_ERROR_TYPE_WARNING,
3065 "Tunnel %s is already scheduled for destruction. Tunnel debug dump:\n",
3067 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3069 /* should never happen, tunnel can only become empty once, and the
3070 * task identifier should be NO_TASK (cleaned when the tunnel was created
3071 * or became un-empty)
3076 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: scheduling destruction\n",
3079 // FIXME make delay a config option
3080 t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
3081 &delayed_destroy, t);
3082 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llu\n",
3083 t, t->destroy_task);
3088 * Destroy tunnel if empty (no more channels).
3090 * @param t Tunnel to destroy if empty.
3093 GCT_destroy_if_empty (struct CadetTunnel *t)
3095 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
3096 if (0 < GCT_count_channels (t))
3099 GCT_destroy_empty (t);
3104 * Destroy the tunnel.
3106 * This function does not generate any warning traffic to clients or peers.
3109 * Cancel messages belonging to this tunnel queued to neighbors.
3110 * Free any allocated resources linked to the tunnel.
3112 * @param t The tunnel to destroy.
3115 GCT_destroy (struct CadetTunnel *t)
3117 struct CadetTConnection *iter_c;
3118 struct CadetTConnection *next_c;
3119 struct CadetTChannel *iter_ch;
3120 struct CadetTChannel *next_ch;
3125 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
3127 GNUNET_break (GNUNET_YES ==
3128 GNUNET_CONTAINER_multipeermap_remove (tunnels,
3129 GCP_get_id (t->peer), t));
3131 for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
3133 next_c = iter_c->next;
3134 GCC_destroy (iter_c->c);
3136 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
3138 next_ch = iter_ch->next;
3139 GCCH_destroy (iter_ch->ch);
3140 /* Should only happen on shutdown, but it's ok. */
3143 if (NULL != t->destroy_task)
3145 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling dest: %llX\n", t->destroy_task);
3146 GNUNET_SCHEDULER_cancel (t->destroy_task);
3147 t->destroy_task = NULL;
3150 if (NULL != t->trim_connections_task)
3152 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling trim: %llX\n",
3153 t->trim_connections_task);
3154 GNUNET_SCHEDULER_cancel (t->trim_connections_task);
3155 t->trim_connections_task = NULL;
3158 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
3159 GCP_set_tunnel (t->peer, NULL);
3161 if (NULL != t->rekey_task)
3163 GNUNET_SCHEDULER_cancel (t->rekey_task);
3164 t->rekey_task = NULL;
3166 if (NULL != t->kx_ctx)
3168 if (NULL != t->kx_ctx->finish_task)
3169 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
3170 GNUNET_free (t->kx_ctx);
3181 * @brief Use the given path for the tunnel.
3182 * Update the next and prev hops (and RCs).
3183 * (Re)start the path refresh in case the tunnel is locally owned.
3185 * @param t Tunnel to update.
3186 * @param p Path to use.
3188 * @return Connection created.
3190 struct CadetConnection *
3191 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
3193 struct CadetConnection *c;
3194 struct GNUNET_CADET_Hash cid;
3195 unsigned int own_pos;
3197 if (NULL == t || NULL == p)
3203 if (CADET_TUNNEL_SHUTDOWN == t->cstate)
3209 for (own_pos = 0; own_pos < p->length; own_pos++)
3211 if (p->peers[own_pos] == myid)
3214 if (own_pos >= p->length)
3216 GNUNET_break_op (0);
3220 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
3221 c = GCC_new (&cid, t, p, own_pos);
3224 /* Path was flawed */
3227 GCT_add_connection (t, c);
3233 * Count all created connections of a tunnel. Not necessarily ready connections!
3235 * @param t Tunnel on which to count.
3237 * @return Number of connections created, either being established or ready.
3240 GCT_count_any_connections (struct CadetTunnel *t)
3242 struct CadetTConnection *iter;
3248 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3256 * Count established (ready) connections of a tunnel.
3258 * @param t Tunnel on which to count.
3260 * @return Number of connections.
3263 GCT_count_connections (struct CadetTunnel *t)
3265 struct CadetTConnection *iter;
3271 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3272 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
3280 * Count channels of a tunnel.
3282 * @param t Tunnel on which to count.
3284 * @return Number of channels.
3287 GCT_count_channels (struct CadetTunnel *t)
3289 struct CadetTChannel *iter;
3292 for (count = 0, iter = t->channel_head;
3294 iter = iter->next, count++) /* skip */;
3301 * Get the connectivity state of a tunnel.
3305 * @return Tunnel's connectivity state.
3307 enum CadetTunnelCState
3308 GCT_get_cstate (struct CadetTunnel *t)
3313 return (enum CadetTunnelCState) -1;
3320 * Get the encryption state of a tunnel.
3324 * @return Tunnel's encryption state.
3326 enum CadetTunnelEState
3327 GCT_get_estate (struct CadetTunnel *t)
3332 return (enum CadetTunnelEState) -1;
3338 * Get the maximum buffer space for a tunnel towards a local client.
3342 * @return Biggest buffer space offered by any channel in the tunnel.
3345 GCT_get_channels_buffer (struct CadetTunnel *t)
3347 struct CadetTChannel *iter;
3348 unsigned int buffer;
3349 unsigned int ch_buf;
3351 if (NULL == t->channel_head)
3353 /* Probably getting buffer for a channel create/handshake. */
3354 LOG (GNUNET_ERROR_TYPE_DEBUG, " no channels, allow max\n");
3359 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3361 ch_buf = get_channel_buffer (iter);
3362 if (ch_buf > buffer)
3370 * Get the total buffer space for a tunnel for P2P traffic.
3374 * @return Buffer space offered by all connections in the tunnel.
3377 GCT_get_connections_buffer (struct CadetTunnel *t)
3379 struct CadetTConnection *iter;
3380 unsigned int buffer;
3382 if (GNUNET_NO == is_ready (t))
3384 if (count_queued_data (t) > 3)
3391 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3393 if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
3397 buffer += get_connection_buffer (iter);
3405 * Get the tunnel's destination.
3409 * @return ID of the destination peer.
3411 const struct GNUNET_PeerIdentity *
3412 GCT_get_destination (struct CadetTunnel *t)
3414 return GCP_get_id (t->peer);
3419 * Get the tunnel's next free global channel ID.
3423 * @return GID of a channel free to use.
3426 GCT_get_next_chid (struct CadetTunnel *t)
3428 CADET_ChannelNumber chid;
3429 CADET_ChannelNumber mask;
3432 /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
3433 * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
3434 * If peer's ID is bigger, start at 0x4... bit 30 = 1
3436 result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
3441 t->next_chid |= mask;
3443 while (NULL != GCT_get_channel (t, t->next_chid))
3445 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
3446 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3447 t->next_chid |= mask;
3449 chid = t->next_chid;
3450 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3451 t->next_chid |= mask;
3458 * Send ACK on one or more channels due to buffer in connections.
3460 * @param t Channel which has some free buffer space.
3463 GCT_unchoke_channels (struct CadetTunnel *t)
3465 struct CadetTChannel *iter;
3466 unsigned int buffer;
3467 unsigned int channels = GCT_count_channels (t);
3468 unsigned int choked_n;
3469 struct CadetChannel *choked[channels];
3471 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
3472 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
3473 if (NULL != t->channel_head)
3474 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
3476 /* Get buffer space */
3477 buffer = GCT_get_connections_buffer (t);
3483 /* Count and remember choked channels */
3485 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3487 if (GNUNET_NO == get_channel_allowed (iter))
3489 choked[choked_n++] = iter->ch;
3493 /* Unchoke random channels */
3494 while (0 < buffer && 0 < choked_n)
3496 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3498 GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
3501 choked[r] = choked[choked_n];
3507 * Send ACK on one or more connections due to buffer space to the client.
3509 * Iterates all connections of the tunnel and sends ACKs appropriately.
3514 GCT_send_connection_acks (struct CadetTunnel *t)
3516 struct CadetTConnection *iter;
3519 uint32_t allow_per_connection;
3521 unsigned int buffer;
3523 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
3532 if (CADET_TUNNEL_READY != t->cstate)
3535 buffer = GCT_get_channels_buffer (t);
3536 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer %u\n", buffer);
3538 /* Count connections, how many messages are already allowed */
3539 cs = GCT_count_connections (t);
3540 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3542 allowed += get_connection_allowed (iter);
3544 LOG (GNUNET_ERROR_TYPE_DEBUG, " allowed %u\n", allowed);
3546 /* Make sure there is no overflow */
3547 if (allowed > buffer)
3550 /* Authorize connections to send more data */
3551 to_allow = buffer - allowed;
3553 for (iter = t->connection_head;
3554 NULL != iter && to_allow > 0;
3557 if (CADET_CONNECTION_READY != GCC_get_state (iter->c)
3558 || get_connection_allowed (iter) > 64 / 3)
3562 allow_per_connection = to_allow/cs;
3563 to_allow -= allow_per_connection;
3565 GCC_allow (iter->c, allow_per_connection,
3566 GCC_is_origin (iter->c, GNUNET_NO));
3571 /* Since we don't allow if it's allowed to send 64/3, this can happen. */
3572 LOG (GNUNET_ERROR_TYPE_DEBUG, " reminding to_allow: %u\n", to_allow);
3578 * Cancel a previously sent message while it's in the queue.
3580 * ONLY can be called before the continuation given to the send function
3581 * is called. Once the continuation is called, the message is no longer in the
3584 * @param q Handle to the queue.
3587 GCT_cancel (struct CadetTunnelQueue *q)
3592 /* tun_message_sent() will be called and free q */
3594 else if (NULL != q->tqd)
3596 unqueue_data (q->tqd);
3598 if (NULL != q->cont)
3599 q->cont (q->cont_cls, NULL, q, 0, 0);
3610 * Sends an already built message on a tunnel, encrypting it and
3611 * choosing the best connection if not provided.
3613 * @param message Message to send. Function modifies it.
3614 * @param t Tunnel on which this message is transmitted.
3615 * @param c Connection to use (autoselect if NULL).
3616 * @param force Force the tunnel to take the message (buffer overfill).
3617 * @param cont Continuation to call once message is really sent.
3618 * @param cont_cls Closure for @c cont.
3620 * @return Handle to cancel message. NULL if @c cont is NULL.
3622 struct CadetTunnelQueue *
3623 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
3624 struct CadetTunnel *t, struct CadetConnection *c,
3625 int force, GCT_sent cont, void *cont_cls)
3627 return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
3631 * Sends an already built and encrypted message on a tunnel, choosing the best
3632 * connection. Useful for re-queueing messages queued on a destroyed connection.
3634 * @param message Message to send. Function modifies it.
3635 * @param t Tunnel on which this message is transmitted.
3638 GCT_resend_message (const struct GNUNET_MessageHeader *message,
3639 struct CadetTunnel *t)
3641 struct CadetConnection *c;
3644 c = tunnel_get_connection (t);
3647 /* TODO queue in tunnel, marked as encrypted */
3648 LOG (GNUNET_ERROR_TYPE_DEBUG, "No connection available, dropping.\n");
3651 fwd = GCC_is_origin (c, GNUNET_YES);
3652 GNUNET_break (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
3653 GNUNET_YES, NULL, NULL));
3658 * Is the tunnel directed towards the local peer?
3662 * @return #GNUNET_YES if it is loopback.
3665 GCT_is_loopback (const struct CadetTunnel *t)
3667 return (myid == GCP_get_short_id (t->peer));
3672 * Is the tunnel this path already?
3677 * @return #GNUNET_YES a connection uses this path.
3680 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
3682 struct CadetTConnection *iter;
3684 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3685 if (path_equivalent (GCC_get_path (iter->c), p))
3693 * Get a cost of a path for a tunnel considering existing connections.
3696 * @param path Candidate path.
3698 * @return Cost of the path (path length + number of overlapping nodes)
3701 GCT_get_path_cost (const struct CadetTunnel *t,
3702 const struct CadetPeerPath *path)
3704 struct CadetTConnection *iter;
3705 const struct CadetPeerPath *aux;
3706 unsigned int overlap;
3714 GNUNET_assert (NULL != t);
3716 for (i = 0; i < path->length; i++)
3718 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3720 aux = GCC_get_path (iter->c);
3724 for (j = 0; j < aux->length; j++)
3726 if (path->peers[i] == aux->peers[j])
3734 return path->length + overlap;
3739 * Get the static string for the peer this tunnel is directed.
3743 * @return Static string the destination peer's ID.
3746 GCT_2s (const struct CadetTunnel *t)
3751 return GCP_2s (t->peer);
3755 /******************************************************************************/
3756 /***************************** INFO/DEBUG *******************************/
3757 /******************************************************************************/
3760 * Log all possible info about the tunnel state.
3762 * @param t Tunnel to debug.
3763 * @param level Debug level to use.
3766 GCT_debug (const struct CadetTunnel *t, enum GNUNET_ErrorType level)
3768 struct CadetTChannel *iterch;
3769 struct CadetTConnection *iterc;
3772 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
3774 __FILE__, __FUNCTION__, __LINE__);
3778 LOG2 (level, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
3779 LOG2 (level, "TTT cstate %s, estate %s\n",
3780 cstate2s (t->cstate), estate2s (t->estate));
3781 LOG2 (level, "TTT kx_ctx %p, rekey_task %u, finish task %u\n",
3782 t->kx_ctx, t->rekey_task, t->kx_ctx ? t->kx_ctx->finish_task : 0);
3783 #if DUMP_KEYS_TO_STDERR
3784 LOG2 (level, "TTT my EPHM\t %s\n",
3785 GNUNET_h2s ((struct GNUNET_HashCode *) &kx_msg.ephemeral_key));
3786 LOG2 (level, "TTT peers EPHM:\t %s\n",
3787 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
3788 LOG2 (level, "TTT ENC key:\t %s\n",
3789 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
3790 LOG2 (level, "TTT DEC key:\t %s\n",
3791 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
3794 LOG2 (level, "TTT OLD ENC key:\t %s\n",
3795 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->e_key_old));
3796 LOG2 (level, "TTT OLD DEC key:\t %s\n",
3797 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->d_key_old));
3800 LOG2 (level, "TTT tq_head %p, tq_tail %p\n", t->tq_head, t->tq_tail);
3801 LOG2 (level, "TTT destroy %u\n", t->destroy_task);
3803 LOG2 (level, "TTT channels:\n");
3804 for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
3806 LOG2 (level, "TTT - %s\n", GCCH_2s (iterch->ch));
3809 LOG2 (level, "TTT connections:\n");
3810 for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
3812 GCC_debug (iterc->c, level);
3815 LOG2 (level, "TTT DEBUG TUNNEL END\n");
3820 * Iterate all tunnels.
3822 * @param iter Iterator.
3823 * @param cls Closure for @c iter.
3826 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
3828 GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
3833 * Count all tunnels.
3835 * @return Number of tunnels to remote peers kept by this peer.
3838 GCT_count_all (void)
3840 return GNUNET_CONTAINER_multipeermap_size (tunnels);
3845 * Iterate all connections of a tunnel.
3847 * @param t Tunnel whose connections to iterate.
3848 * @param iter Iterator.
3849 * @param cls Closure for @c iter.
3852 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
3854 struct CadetTConnection *ct;
3856 for (ct = t->connection_head; NULL != ct; ct = ct->next)
3862 * Iterate all channels of a tunnel.
3864 * @param t Tunnel whose channels to iterate.
3865 * @param iter Iterator.
3866 * @param cls Closure for @c iter.
3869 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
3871 struct CadetTChannel *cht;
3873 for (cht = t->channel_head; NULL != cht; cht = cht->next)
3874 iter (cls, cht->ch);