2 This file is part of GNUnet.
3 (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 #define CONNECTIONS_PER_TUNNEL 3
42 #if !defined(GNUNET_CULL_LOGGING)
43 #define DUMP_KEYS_TO_STDERR GNUNET_YES
45 #define DUMP_KEYS_TO_STDERR GNUNET_NO
48 /******************************************************************************/
49 /******************************** STRUCTS **********************************/
50 /******************************************************************************/
54 struct CadetTChannel *next;
55 struct CadetTChannel *prev;
56 struct CadetChannel *ch;
61 * Connection list and metadata.
63 struct CadetTConnection
68 struct CadetTConnection *next;
73 struct CadetTConnection *prev;
78 struct CadetConnection *c;
81 * Creation time, to keep oldest connection alive.
83 struct GNUNET_TIME_Absolute created;
86 * Connection throughput, to keep fastest connection alive.
92 * Structure used during a Key eXchange.
94 struct CadetTunnelKXCtx
97 * Encryption ("our") old "confirmed" key, for encrypting traffic sent by us
98 * end before the key exchange is finished or times out.
100 struct GNUNET_CRYPTO_SymmetricSessionKey e_key_old;
103 * Decryption ("their") old "confirmed" key, for decrypting traffic sent by
104 * the other end before the key exchange started.
106 struct GNUNET_CRYPTO_SymmetricSessionKey d_key_old;
109 * Challenge to send in a ping and expect in the pong.
114 * When the rekey started. One minute after this the new key will be used.
116 struct GNUNET_TIME_Absolute rekey_start_time;
119 * Task for delayed destruction of the Key eXchange context, to allow delayed
120 * messages with the old key to be decrypted successfully.
122 GNUNET_SCHEDULER_TaskIdentifier finish_task;
126 * Struct containing all information regarding a tunnel to a peer.
131 * Endpoint of the tunnel.
133 struct CadetPeer *peer;
136 * State of the tunnel connectivity.
138 enum CadetTunnelCState cstate;
141 * State of the tunnel encryption.
143 enum CadetTunnelEState estate;
146 * Key eXchange context.
148 struct CadetTunnelKXCtx *kx_ctx;
151 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own ephemeral
154 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
157 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
159 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
162 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
164 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
167 * Task to start the rekey process.
169 GNUNET_SCHEDULER_TaskIdentifier rekey_task;
172 * Paths that are actively used to reach the destination peer.
174 struct CadetTConnection *connection_head;
175 struct CadetTConnection *connection_tail;
178 * Next connection number.
183 * Channels inside this tunnel.
185 struct CadetTChannel *channel_head;
186 struct CadetTChannel *channel_tail;
189 * Channel ID for the next created channel.
191 CADET_ChannelNumber next_chid;
194 * Destroy flag: if true, destroy on last message.
196 GNUNET_SCHEDULER_TaskIdentifier destroy_task;
199 * Queued messages, to transmit once tunnel gets connected.
201 struct CadetTunnelDelayed *tq_head;
202 struct CadetTunnelDelayed *tq_tail;
205 * Task to trim connections if too many are present.
207 GNUNET_SCHEDULER_TaskIdentifier trim_connections_task;
212 * Struct used to save messages in a non-ready tunnel to send once connected.
214 struct CadetTunnelDelayed
219 struct CadetTunnelDelayed *next;
220 struct CadetTunnelDelayed *prev;
225 struct CadetTunnel *t;
228 * Tunnel queue given to the channel to cancel request. Update on send_queued.
230 struct CadetTunnelQueue *tq;
235 /* struct GNUNET_MessageHeader *msg; */
240 * Handle for messages queued but not yet sent.
242 struct CadetTunnelQueue
245 * Connection queue handle, to cancel if necessary.
247 struct CadetConnectionQueue *cq;
250 * Handle in case message hasn't been given to a connection yet.
252 struct CadetTunnelDelayed *tqd;
255 * Continuation to call once sent.
260 * Closure for @c cont.
266 /******************************************************************************/
267 /******************************* GLOBALS ***********************************/
268 /******************************************************************************/
271 * Global handle to the statistics service.
273 extern struct GNUNET_STATISTICS_Handle *stats;
276 * Local peer own ID (memory efficient handle).
278 extern GNUNET_PEER_Id myid;
281 * Local peer own ID (full value).
283 extern struct GNUNET_PeerIdentity my_full_id;
287 * Don't try to recover tunnels if shutting down.
289 extern int shutting_down;
293 * Set of all tunnels, in order to trigger a new exchange on rekey.
294 * Indexed by peer's ID.
296 static struct GNUNET_CONTAINER_MultiPeerMap *tunnels;
299 * Default TTL for payload packets.
301 static unsigned long long default_ttl;
306 const static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
309 * Own ephemeral private key.
311 static struct GNUNET_CRYPTO_EcdhePrivateKey *my_ephemeral_key;
314 * Cached message used to perform a key exchange.
316 static struct GNUNET_CADET_KX_Ephemeral kx_msg;
319 * Task to generate a new ephemeral key.
321 static GNUNET_SCHEDULER_TaskIdentifier rekey_task;
326 static struct GNUNET_TIME_Relative rekey_period;
328 /******************************************************************************/
329 /******************************** STATIC ***********************************/
330 /******************************************************************************/
333 * Get string description for tunnel connectivity state.
335 * @param cs Tunnel state.
337 * @return String representation.
340 cstate2s (enum CadetTunnelCState cs)
346 case CADET_TUNNEL_NEW:
347 return "CADET_TUNNEL_NEW";
348 case CADET_TUNNEL_SEARCHING:
349 return "CADET_TUNNEL_SEARCHING";
350 case CADET_TUNNEL_WAITING:
351 return "CADET_TUNNEL_WAITING";
352 case CADET_TUNNEL_READY:
353 return "CADET_TUNNEL_READY";
354 case CADET_TUNNEL_SHUTDOWN:
355 return "CADET_TUNNEL_SHUTDOWN";
357 SPRINTF (buf, "%u (UNKNOWN STATE)", cs);
365 * Get string description for tunnel encryption state.
367 * @param es Tunnel state.
369 * @return String representation.
372 estate2s (enum CadetTunnelEState es)
378 case CADET_TUNNEL_KEY_UNINITIALIZED:
379 return "CADET_TUNNEL_KEY_UNINITIALIZED";
380 case CADET_TUNNEL_KEY_SENT:
381 return "CADET_TUNNEL_KEY_SENT";
382 case CADET_TUNNEL_KEY_PING:
383 return "CADET_TUNNEL_KEY_PING";
384 case CADET_TUNNEL_KEY_OK:
385 return "CADET_TUNNEL_KEY_OK";
386 case CADET_TUNNEL_KEY_REKEY:
387 return "CADET_TUNNEL_KEY_REKEY";
389 SPRINTF (buf, "%u (UNKNOWN STATE)", es);
397 * @brief Check if tunnel is ready to send traffic.
399 * Tunnel must be connected and with encryption correctly set up.
401 * @param t Tunnel to check.
403 * @return #GNUNET_YES if ready, #GNUNET_NO otherwise
406 is_ready (struct CadetTunnel *t)
410 GCT_debug (t, GNUNET_ERROR_TYPE_DEBUG);
411 ready = CADET_TUNNEL_READY == t->cstate
412 && (CADET_TUNNEL_KEY_OK == t->estate
413 || CADET_TUNNEL_KEY_REKEY == t->estate);
414 ready = ready || GCT_is_loopback (t);
420 * Check if a key is invalid (NULL pointer or all 0)
422 * @param key Key to check.
424 * @return #GNUNET_YES if key is null, #GNUNET_NO if exists and is not 0.
427 is_key_null (struct GNUNET_CRYPTO_SymmetricSessionKey *key)
429 struct GNUNET_CRYPTO_SymmetricSessionKey null_key;
434 memset (&null_key, 0, sizeof (null_key));
435 if (0 == memcmp (key, &null_key, sizeof (null_key)))
442 * Ephemeral key message purpose size.
444 * @return Size of the part of the ephemeral key message that must be signed.
447 ephemeral_purpose_size (void)
449 return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
450 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
451 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
452 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
453 sizeof (struct GNUNET_PeerIdentity);
458 * Size of the encrypted part of a ping message.
460 * @return Size of the encrypted part of a ping message.
463 ping_encryption_size (void)
465 return sizeof (struct GNUNET_PeerIdentity) + sizeof (uint32_t);
470 * Get the channel's buffer. ONLY FOR NON-LOOPBACK CHANNELS!!
472 * @param tch Tunnel's channel handle.
474 * @return Amount of messages the channel can still buffer towards the client.
477 get_channel_buffer (const struct CadetTChannel *tch)
481 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
482 fwd = GCCH_is_origin (tch->ch, GNUNET_YES);
484 return GCCH_get_buffer (tch->ch, fwd);
489 * Get the channel's allowance status.
491 * @param tch Tunnel's channel handle.
493 * @return #GNUNET_YES if we allowed the client to send data to us.
496 get_channel_allowed (const struct CadetTChannel *tch)
500 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
501 fwd = GCCH_is_origin (tch->ch, GNUNET_YES);
503 return GCCH_get_allowed (tch->ch, fwd);
508 * Get the connection's buffer.
510 * @param tc Tunnel's connection handle.
512 * @return Amount of messages the connection can still buffer.
515 get_connection_buffer (const struct CadetTConnection *tc)
519 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
520 fwd = GCC_is_origin (tc->c, GNUNET_YES);
522 return GCC_get_buffer (tc->c, fwd);
527 * Get the connection's allowance.
529 * @param tc Tunnel's connection handle.
531 * @return Amount of messages we have allowed the next peer to send us.
534 get_connection_allowed (const struct CadetTConnection *tc)
538 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
539 fwd = GCC_is_origin (tc->c, GNUNET_YES);
541 return GCC_get_allowed (tc->c, fwd);
546 * Check that a ephemeral key message s well formed and correctly signed.
548 * @param t Tunnel on which the message came.
549 * @param msg The ephemeral key message.
551 * @return GNUNET_OK if message is fine, GNUNET_SYSERR otherwise.
554 check_ephemeral (struct CadetTunnel *t,
555 const struct GNUNET_CADET_KX_Ephemeral *msg)
557 /* Check message size */
558 if (ntohs (msg->header.size) != sizeof (struct GNUNET_CADET_KX_Ephemeral))
559 return GNUNET_SYSERR;
561 /* Check signature size */
562 if (ntohl (msg->purpose.size) != ephemeral_purpose_size ())
563 return GNUNET_SYSERR;
566 if (0 != memcmp (&msg->origin_identity,
567 GCP_get_id (t->peer),
568 sizeof (struct GNUNET_PeerIdentity)))
569 return GNUNET_SYSERR;
571 /* Check signature */
573 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_CADET_KX,
576 &msg->origin_identity.public_key))
577 return GNUNET_SYSERR;
584 * Select the best key to use for encryption (send), based on KX status.
586 * Normally, return the current key. If there is a KX in progress and the old
587 * key is fresh enough, return the old key.
589 * @param t Tunnel to choose the key from.
591 * @return The optimal key to encrypt/hmac outgoing traffic.
593 static const struct GNUNET_CRYPTO_SymmetricSessionKey *
594 select_key (const struct CadetTunnel *t)
596 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
598 if (NULL != t->kx_ctx
599 && GNUNET_SCHEDULER_NO_TASK == t->kx_ctx->finish_task)
601 struct GNUNET_TIME_Relative age;
603 age = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
604 LOG (GNUNET_ERROR_TYPE_DEBUG,
605 " key exchange in progress, started %s ago\n",
606 GNUNET_STRINGS_relative_time_to_string (age, GNUNET_YES));
607 // FIXME make duration of old keys configurable
608 if (age.rel_value_us < GNUNET_TIME_UNIT_MINUTES.rel_value_us)
610 LOG (GNUNET_ERROR_TYPE_DEBUG, " using old key\n");
611 key = &t->kx_ctx->e_key_old;
615 LOG (GNUNET_ERROR_TYPE_DEBUG, " using new key (old key too old)\n");
621 LOG (GNUNET_ERROR_TYPE_DEBUG, " no KX: using current key\n");
631 * @param plaintext Content to HMAC.
632 * @param size Size of @c plaintext.
633 * @param iv Initialization vector for the message.
634 * @param key Key to use.
635 * @param hmac[out] Destination to store the HMAC.
638 t_hmac (const void *plaintext, size_t size,
639 uint32_t iv, const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
640 struct GNUNET_CADET_Hash *hmac)
642 static const char ctx[] = "cadet authentication key";
643 struct GNUNET_CRYPTO_AuthKey auth_key;
644 struct GNUNET_HashCode hash;
646 #if DUMP_KEYS_TO_STDERR
647 LOG (GNUNET_ERROR_TYPE_INFO, " HMAC with key %s\n",
648 GNUNET_h2s ((struct GNUNET_HashCode *) key));
650 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
655 /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
656 GNUNET_CRYPTO_hmac (&auth_key, plaintext, size, &hash);
657 memcpy (hmac, &hash, sizeof (*hmac));
662 * Encrypt daforce_newest_keyta with the tunnel key.
664 * @param t Tunnel whose key to use.
665 * @param dst Destination for the encrypted data.
666 * @param src Source of the plaintext. Can overlap with @c dst.
667 * @param size Size of the plaintext.
668 * @param iv Initialization Vector to use.
669 * @param force_newest_key Force the use of the newest key, otherwise
670 * CADET will use the old key when allowed.
671 * This can happen in the case when a KX is going on
672 * and the old one hasn't expired.
675 t_encrypt (struct CadetTunnel *t, void *dst, const void *src,
676 size_t size, uint32_t iv, int force_newest_key)
678 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
679 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
682 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt start\n");
684 key = GNUNET_YES == force_newest_key ? &t->e_key : select_key (t);
685 #if DUMP_KEYS_TO_STDERR
686 LOG (GNUNET_ERROR_TYPE_INFO, " ENC with key %s\n",
687 GNUNET_h2s ((struct GNUNET_HashCode *) key));
689 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
690 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt IV derived\n");
691 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, key, &siv, dst);
692 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt end\n");
699 * Decrypt and verify data with the appropriate tunnel key.
701 * @param key Key to use.
702 * @param dst Destination for the plaintext.
703 * @param src Source of the encrypted data. Can overlap with @c dst.
704 * @param size Size of the encrypted data.
705 * @param iv Initialization Vector to use.
707 * @return Size of the decrypted data, -1 if an error was encountered.
710 decrypt (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
711 void *dst, const void *src, size_t size, uint32_t iv)
713 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
716 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt start\n");
717 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv\n");
718 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
719 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv done\n");
720 out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, key, &siv, dst);
721 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt end\n");
728 * Decrypt and verify data with the most recent tunnel key.
730 * @param t Tunnel whose key to use.
731 * @param dst Destination for the plaintext.
732 * @param src Source of the encrypted data. Can overlap with @c dst.
733 * @param size Size of the encrypted data.
734 * @param iv Initialization Vector to use.
736 * @return Size of the decrypted data, -1 if an error was encountered.
739 t_decrypt (struct CadetTunnel *t, void *dst, const void *src,
740 size_t size, uint32_t iv)
744 #if DUMP_KEYS_TO_STDERR
745 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_decrypt with %s\n",
746 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
748 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
750 GNUNET_STATISTICS_update (stats, "# non decryptable data", 1, GNUNET_NO);
751 LOG (GNUNET_ERROR_TYPE_WARNING,
752 "got data on %s without a valid key\n",
754 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
758 out_size = decrypt (&t->d_key, dst, src, size, iv);
765 * Decrypt and verify data with the appropriate tunnel key and verify that the
766 * data has not been altered since it was sent by the remote peer.
768 * @param t Tunnel whose key to use.
769 * @param dst Destination for the plaintext.
770 * @param src Source of the encrypted data. Can overlap with @c dst.
771 * @param size Size of the encrypted data.
772 * @param iv Initialization Vector to use.
773 * @param msg_hmac HMAC of the message, cannot be NULL.
775 * @return Size of the decrypted data, -1 if an error was encountered.
778 t_decrypt_and_validate (struct CadetTunnel *t,
779 void *dst, const void *src,
780 size_t size, uint32_t iv,
781 const struct GNUNET_CADET_Hash *msg_hmac)
783 struct GNUNET_CRYPTO_SymmetricSessionKey *key;
784 struct GNUNET_CADET_Hash hmac;
787 /* Try primary (newest) key */
789 decrypted_size = decrypt (key, dst, src, size, iv);
790 t_hmac (src, size, iv, key, &hmac);
791 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
792 return decrypted_size;
794 /* If no key exchange is going on, we just failed */
795 if (NULL == t->kx_ctx)
797 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
798 "Failed checksum validation on tunnel %s with no KX\n",
800 GNUNET_STATISTICS_update (stats, "# wrong HMAC", 1, GNUNET_NO);
804 /* Try secondary (from previous KX period) key */
805 key = &t->kx_ctx->d_key_old;
806 decrypted_size = decrypt (key, dst, src, size, iv);
807 t_hmac (src, size, iv, key, &hmac);
808 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
809 return decrypted_size;
811 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
812 "Failed checksum validation on tunnel %s with KX\n",
814 GNUNET_STATISTICS_update (stats, "# wrong HMAC", 1, GNUNET_NO);
820 * Create key material by doing ECDH on the local and remote ephemeral keys.
822 * @param key_material Where to store the key material.
823 * @param ephemeral_key Peer's public ephemeral key.
826 derive_key_material (struct GNUNET_HashCode *key_material,
827 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key)
830 GNUNET_CRYPTO_ecc_ecdh (my_ephemeral_key,
840 * Create a symmetic key from the identities of both ends and the key material
843 * @param key Destination for the generated key.
844 * @param sender ID of the peer that will encrypt with @c key.
845 * @param receiver ID of the peer that will decrypt with @c key.
846 * @param key_material Hash created with ECDH with the ephemeral keys.
849 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
850 const struct GNUNET_PeerIdentity *sender,
851 const struct GNUNET_PeerIdentity *receiver,
852 const struct GNUNET_HashCode *key_material)
854 const char salt[] = "CADET kx salt";
856 GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
858 key_material, sizeof (struct GNUNET_HashCode),
859 sender, sizeof (struct GNUNET_PeerIdentity),
860 receiver, sizeof (struct GNUNET_PeerIdentity),
866 * Create a new Key eXchange context for the tunnel.
868 * If the old keys were verified, keep them for old traffic. Create a new KX
869 * timestamp and a new nonce.
871 * @param t Tunnel for which to create the KX ctx.
874 create_kx_ctx (struct CadetTunnel *t)
876 LOG (GNUNET_ERROR_TYPE_INFO, " new kx ctx for %s\n", GCT_2s (t));
878 if (NULL != t->kx_ctx)
880 if (GNUNET_SCHEDULER_NO_TASK != t->kx_ctx->finish_task)
882 LOG (GNUNET_ERROR_TYPE_INFO, " resetting exisiting finish task\n");
883 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
884 t->kx_ctx->finish_task = GNUNET_SCHEDULER_NO_TASK;
889 t->kx_ctx = GNUNET_new (struct CadetTunnelKXCtx);
892 t->kx_ctx->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
894 if (CADET_TUNNEL_KEY_OK == t->estate)
896 t->kx_ctx->d_key_old = t->d_key;
897 t->kx_ctx->e_key_old = t->e_key;
899 t->kx_ctx->rekey_start_time = GNUNET_TIME_absolute_get ();
904 * @brief Finish the Key eXchange and destroy the old keys.
906 * @param cls Closure (Tunnel for which to finish the KX).
907 * @param tc Task context.
910 finish_kx (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
912 struct CadetTunnel *t = cls;
914 LOG (GNUNET_ERROR_TYPE_INFO, "finish KX for %s\n", GCT_2s (t));
916 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
918 LOG (GNUNET_ERROR_TYPE_INFO, " shutdown\n");
922 GNUNET_free (t->kx_ctx);
928 * Destroy a Key eXchange context for the tunnel. This function only schedules
929 * the destruction, the freeing of the memory (and clearing of old key material)
930 * happens after a delay!
932 * @param t Tunnel whose KX ctx to destroy.
935 destroy_kx_ctx (struct CadetTunnel *t)
937 struct GNUNET_TIME_Relative delay;
939 if (NULL == t->kx_ctx || GNUNET_SCHEDULER_NO_TASK != t->kx_ctx->finish_task)
942 if (is_key_null (&t->kx_ctx->e_key_old))
944 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_now (finish_kx, t);
948 delay = GNUNET_TIME_relative_divide (rekey_period, 4);
949 delay = GNUNET_TIME_relative_min (delay, GNUNET_TIME_UNIT_MINUTES);
951 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_delayed (delay, finish_kx, t);
956 * Derive the tunnel's keys using our own and the peer's ephemeral keys.
958 * @param t Tunnel for which to create the keys.
961 create_keys (struct CadetTunnel *t)
963 struct GNUNET_HashCode km;
965 derive_key_material (&km, &t->peers_ephemeral_key);
966 derive_symmertic (&t->e_key, &my_full_id, GCP_get_id (t->peer), &km);
967 derive_symmertic (&t->d_key, GCP_get_id (t->peer), &my_full_id, &km);
968 #if DUMP_KEYS_TO_STDERR
969 LOG (GNUNET_ERROR_TYPE_INFO, "ME: %s\n",
970 GNUNET_h2s ((struct GNUNET_HashCode *) &kx_msg.ephemeral_key));
971 LOG (GNUNET_ERROR_TYPE_INFO, "PE: %s\n",
972 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
973 LOG (GNUNET_ERROR_TYPE_INFO, "KM: %s\n", GNUNET_h2s (&km));
974 LOG (GNUNET_ERROR_TYPE_INFO, "EK: %s\n",
975 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
976 LOG (GNUNET_ERROR_TYPE_INFO, "DK: %s\n",
977 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
983 * Pick a connection on which send the next data message.
985 * @param t Tunnel on which to send the message.
987 * @return The connection on which to send the next message.
989 static struct CadetConnection *
990 tunnel_get_connection (struct CadetTunnel *t)
992 struct CadetTConnection *iter;
993 struct CadetConnection *best;
995 unsigned int lowest_q;
997 LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GCT_2s (t));
1000 for (iter = t->connection_head; NULL != iter; iter = iter->next)
1002 LOG (GNUNET_ERROR_TYPE_DEBUG, " connection %s: %u\n",
1003 GCC_2s (iter->c), GCC_get_state (iter->c));
1004 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
1006 qn = GCC_get_qn (iter->c, GCC_is_origin (iter->c, GNUNET_YES));
1007 LOG (GNUNET_ERROR_TYPE_DEBUG, " q_n %u, \n", qn);
1015 LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GCC_2s (best));
1021 * Callback called when a queued message is sent.
1023 * Calculates the average time and connection packet tracking.
1025 * @param cls Closure (TunnelQueue handle).
1026 * @param c Connection this message was on.
1027 * @param q Connection queue handle (unused).
1028 * @param type Type of message sent.
1029 * @param fwd Was this a FWD going message?
1030 * @param size Size of the message.
1033 tun_message_sent (void *cls,
1034 struct CadetConnection *c,
1035 struct CadetConnectionQueue *q,
1036 uint16_t type, int fwd, size_t size)
1038 struct CadetTunnelQueue *qt = cls;
1039 struct CadetTunnel *t;
1041 LOG (GNUNET_ERROR_TYPE_DEBUG, "tun_message_sent\n");
1043 GNUNET_assert (NULL != qt->cont);
1044 t = NULL == c ? NULL : GCC_get_tunnel (c);
1045 qt->cont (qt->cont_cls, t, qt, type, size);
1051 count_queued_data (const struct CadetTunnel *t)
1053 struct CadetTunnelDelayed *iter;
1056 for (count = 0, iter = t->tq_head; iter != NULL; iter = iter->next)
1063 * Delete a queued message: either was sent or the channel was destroyed
1064 * before the tunnel's key exchange had a chance to finish.
1066 * @param tqd Delayed queue handle.
1069 unqueue_data (struct CadetTunnelDelayed *tqd)
1071 GNUNET_CONTAINER_DLL_remove (tqd->t->tq_head, tqd->t->tq_tail, tqd);
1077 * Cache a message to be sent once tunnel is online.
1079 * @param t Tunnel to hold the message.
1080 * @param msg Message itself (copy will be made).
1082 static struct CadetTunnelDelayed *
1083 queue_data (struct CadetTunnel *t, const struct GNUNET_MessageHeader *msg)
1085 struct CadetTunnelDelayed *tqd;
1086 uint16_t size = ntohs (msg->size);
1088 LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GCT_2s (t));
1090 if (GNUNET_YES == is_ready (t))
1096 tqd = GNUNET_malloc (sizeof (struct CadetTunnelDelayed) + size);
1099 memcpy (&tqd[1], msg, size);
1100 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
1106 * Sends an already built message on a tunnel, encrypting it and
1107 * choosing the best connection.
1109 * @param message Message to send. Function modifies it.
1110 * @param t Tunnel on which this message is transmitted.
1111 * @param c Connection to use (autoselect if NULL).
1112 * @param force Force the tunnel to take the message (buffer overfill).
1113 * @param cont Continuation to call once message is really sent.
1114 * @param cont_cls Closure for @c cont.
1115 * @param existing_q In case this a transmission of previously queued data,
1116 * this should be TunnelQueue given to the client.
1119 * @return Handle to cancel message.
1120 * NULL if @c cont is NULL or an error happens and message is dropped.
1122 static struct CadetTunnelQueue *
1123 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1124 struct CadetTunnel *t, struct CadetConnection *c,
1125 int force, GCT_sent cont, void *cont_cls,
1126 struct CadetTunnelQueue *existing_q)
1128 struct CadetTunnelQueue *tq;
1129 struct GNUNET_CADET_Encrypted *msg;
1130 size_t size = ntohs (message->size);
1131 char cbuf[sizeof (struct GNUNET_CADET_Encrypted) + size];
1137 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GCT_2s (t));
1139 if (GNUNET_NO == is_ready (t))
1141 struct CadetTunnelDelayed *tqd;
1142 /* A non null existing_q indicates sending of queued data.
1143 * Should only happen after tunnel becomes ready.
1145 GNUNET_assert (NULL == existing_q);
1146 tqd = queue_data (t, message);
1149 tq = GNUNET_new (struct CadetTunnelQueue);
1153 tq->cont_cls = cont_cls;
1157 GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1159 iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1160 msg = (struct GNUNET_CADET_Encrypted *) cbuf;
1161 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
1163 GNUNET_assert (t_encrypt (t, &msg[1], message, size, iv, GNUNET_NO) == size);
1164 t_hmac (&msg[1], size, iv, select_key (t), &msg->hmac);
1165 msg->header.size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
1168 c = tunnel_get_connection (t);
1171 /* Why is tunnel 'ready'? Should have been queued! */
1172 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
1175 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1177 return NULL; /* Drop... */
1181 type = ntohs (message->type);
1184 case GNUNET_MESSAGE_TYPE_CADET_DATA:
1185 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1186 if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
1187 mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
1189 mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
1191 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1192 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1193 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1194 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1195 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1196 msg->cid = *GCC_get_id (c);
1197 msg->ttl = htonl (default_ttl);
1201 LOG (GNUNET_ERROR_TYPE_ERROR, "type %s not valid\n", GC_m2s (type));
1203 LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
1205 fwd = GCC_is_origin (c, GNUNET_YES);
1209 GNUNET_break (NULL == GCC_send_prebuilt_message (&msg->header, type, mid, c,
1210 fwd, force, NULL, NULL));
1213 if (NULL == existing_q)
1215 tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
1222 tq->cq = GCC_send_prebuilt_message (&msg->header, type, mid, c, fwd, force,
1223 &tun_message_sent, tq);
1224 GNUNET_assert (NULL != tq->cq);
1226 tq->cont_cls = cont_cls;
1233 * Send all cached messages that we can, tunnel is online.
1235 * @param t Tunnel that holds the messages. Cannot be loopback.
1238 send_queued_data (struct CadetTunnel *t)
1240 struct CadetTunnelDelayed *tqd;
1241 struct CadetTunnelDelayed *next;
1244 LOG (GNUNET_ERROR_TYPE_DEBUG,
1245 "GCT_send_queued_data on tunnel %s\n",
1248 if (GCT_is_loopback (t))
1254 if (GNUNET_NO == is_ready (t))
1256 LOG (GNUNET_ERROR_TYPE_DEBUG, " not ready yet: %s/%s\n",
1257 estate2s (t->estate), cstate2s (t->cstate));
1261 room = GCT_get_connections_buffer (t);
1262 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
1263 LOG (GNUNET_ERROR_TYPE_DEBUG, " tq head: %p\n", t->tq_head);
1264 for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
1266 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
1269 send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
1270 tqd->t, NULL, GNUNET_YES,
1271 NULL != tqd->tq ? tqd->tq->cont : NULL,
1272 NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
1276 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
1281 * Sends key exchange message on a tunnel, choosing the best connection.
1282 * Should not be called on loopback tunnels.
1284 * @param t Tunnel on which this message is transmitted.
1285 * @param message Message to send. Function modifies it.
1288 send_kx (struct CadetTunnel *t,
1289 const struct GNUNET_MessageHeader *message)
1291 struct CadetConnection *c;
1292 struct GNUNET_CADET_KX *msg;
1293 size_t size = ntohs (message->size);
1294 char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
1298 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
1300 /* Avoid loopback. */
1301 if (GCT_is_loopback (t))
1303 LOG (GNUNET_ERROR_TYPE_DEBUG, " loopback!\n");
1307 type = ntohs (message->type);
1309 /* Even if tunnel is being destroyed, send anyway.
1310 * Could be a response to a rekey initiated by remote peer,
1311 * who is trying to create a new channel!
1314 /* Must have a connection, or be looking for one. */
1315 if (NULL == t->connection_head)
1317 if (CADET_TUNNEL_SEARCHING != t->cstate)
1319 LOG (GNUNET_ERROR_TYPE_ERROR, "\n\n\n");
1321 LOG (GNUNET_ERROR_TYPE_ERROR, "no connection, sending %s\n", GC_m2s (type));
1322 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
1323 GCP_debug (t->peer, GNUNET_ERROR_TYPE_ERROR);
1324 LOG (GNUNET_ERROR_TYPE_ERROR, "\n\n\n");
1329 msg = (struct GNUNET_CADET_KX *) cbuf;
1330 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
1331 msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
1332 c = tunnel_get_connection (t);
1335 if (GNUNET_SCHEDULER_NO_TASK == t->destroy_task
1336 && CADET_TUNNEL_READY == t->cstate)
1339 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
1345 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
1346 case GNUNET_MESSAGE_TYPE_CADET_KX_PING:
1347 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
1348 memcpy (&msg[1], message, size);
1351 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
1356 fwd = GCC_is_origin (t->connection_head->c, GNUNET_YES);
1357 /* TODO save handle and cancel in case of a unneeded retransmission */
1358 GNUNET_assert (NULL == GCC_send_prebuilt_message (&msg->header, type, 0, c,
1365 * Send the ephemeral key on a tunnel.
1367 * @param t Tunnel on which to send the key.
1370 send_ephemeral (struct CadetTunnel *t)
1372 LOG (GNUNET_ERROR_TYPE_INFO, "===> EPHM for %s\n", GCT_2s (t));
1374 kx_msg.sender_status = htonl (t->estate);
1375 send_kx (t, &kx_msg.header);
1379 * Send a ping message on a tunnel.
1381 * @param t Tunnel on which to send the ping.
1384 send_ping (struct CadetTunnel *t)
1386 struct GNUNET_CADET_KX_Ping msg;
1388 LOG (GNUNET_ERROR_TYPE_INFO, "===> PING for %s\n", GCT_2s (t));
1389 msg.header.size = htons (sizeof (msg));
1390 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PING);
1391 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1392 msg.target = *GCP_get_id (t->peer);
1393 msg.nonce = t->kx_ctx->challenge;
1395 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
1396 LOG (GNUNET_ERROR_TYPE_DEBUG, " towards %s\n", GNUNET_i2s (&msg.target));
1397 t_encrypt (t, &msg.target, &msg.target,
1398 ping_encryption_size(), msg.iv, GNUNET_YES);
1399 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
1400 LOG (GNUNET_ERROR_TYPE_DEBUG, " e towards %s\n", GNUNET_i2s (&msg.target));
1402 send_kx (t, &msg.header);
1407 * Send a pong message on a tunnel.
1409 * @param t Tunnel on which to send the pong.
1410 * @param challenge Value sent in the ping that we have to send back.
1413 send_pong (struct CadetTunnel *t, uint32_t challenge)
1415 struct GNUNET_CADET_KX_Pong msg;
1417 LOG (GNUNET_ERROR_TYPE_INFO, "===> PONG for %s\n", GCT_2s (t));
1418 msg.header.size = htons (sizeof (msg));
1419 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
1420 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1421 msg.nonce = challenge;
1422 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
1423 t_encrypt (t, &msg.nonce, &msg.nonce,
1424 sizeof (msg.nonce), msg.iv, GNUNET_YES);
1425 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
1427 send_kx (t, &msg.header);
1432 * Initiate a rekey with the remote peer.
1434 * @param cls Closure (tunnel).
1435 * @param tc TaskContext.
1438 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1440 struct CadetTunnel *t = cls;
1442 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1444 LOG (GNUNET_ERROR_TYPE_INFO, "Re-key Tunnel %s\n", GCT_2s (t));
1445 if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1450 if (NULL == t->kx_ctx)
1456 struct GNUNET_TIME_Relative duration;
1458 duration = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
1459 LOG (GNUNET_ERROR_TYPE_DEBUG, " kx started %s ago\n",
1460 GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
1462 // FIXME make duration of old keys configurable
1463 if (duration.rel_value_us >= GNUNET_TIME_UNIT_MINUTES.rel_value_us)
1465 LOG (GNUNET_ERROR_TYPE_DEBUG, " deleting old keys\n");
1466 memset (&t->kx_ctx->d_key_old, 0, sizeof (t->kx_ctx->d_key_old));
1467 memset (&t->kx_ctx->e_key_old, 0, sizeof (t->kx_ctx->e_key_old));
1475 case CADET_TUNNEL_KEY_UNINITIALIZED:
1476 GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
1478 case CADET_TUNNEL_KEY_SENT:
1480 case CADET_TUNNEL_KEY_OK:
1481 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
1483 case CADET_TUNNEL_KEY_PING:
1484 case CADET_TUNNEL_KEY_REKEY:
1488 LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
1491 // FIXME exponential backoff
1492 struct GNUNET_TIME_Relative delay;
1494 delay = GNUNET_TIME_relative_divide (rekey_period, 16);
1495 delay = GNUNET_TIME_relative_min (delay, REKEY_WAIT);
1496 LOG (GNUNET_ERROR_TYPE_DEBUG, " next call in %s\n",
1497 GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
1498 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1503 * Our ephemeral key has changed, create new session key on all tunnels.
1505 * Each tunnel will start the Key Exchange with a random delay between
1506 * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
1507 * per second, on average.
1509 * @param cls Closure (size of the hashmap).
1510 * @param key Current public key.
1511 * @param value Value in the hash map (tunnel).
1513 * @return #GNUNET_YES, so we should continue to iterate,
1516 rekey_iterator (void *cls,
1517 const struct GNUNET_PeerIdentity *key,
1520 struct CadetTunnel *t = value;
1521 struct GNUNET_TIME_Relative delay;
1522 long n = (long) cls;
1525 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
1528 if (GNUNET_YES == GCT_is_loopback (t))
1531 r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
1532 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
1533 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1540 * Create a new ephemeral key and key message, schedule next rekeying.
1542 * @param cls Closure (unused).
1543 * @param tc TaskContext.
1546 rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1548 struct GNUNET_TIME_Absolute time;
1551 rekey_task = GNUNET_SCHEDULER_NO_TASK;
1553 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1556 GNUNET_free_non_null (my_ephemeral_key);
1557 my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
1559 time = GNUNET_TIME_absolute_get ();
1560 kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
1561 time = GNUNET_TIME_absolute_add (time, rekey_period);
1562 time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
1563 kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
1564 GNUNET_CRYPTO_ecdhe_key_get_public (my_ephemeral_key, &kx_msg.ephemeral_key);
1565 LOG (GNUNET_ERROR_TYPE_INFO, "GLOBAL RE-KEY, NEW EPHM: %s\n",
1566 GNUNET_h2s ((struct GNUNET_HashCode *) &kx_msg.ephemeral_key));
1568 GNUNET_assert (GNUNET_OK ==
1569 GNUNET_CRYPTO_eddsa_sign (my_private_key,
1571 &kx_msg.signature));
1573 n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
1574 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
1576 rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period, &rekey, NULL);
1581 * Called only on shutdown, destroy every tunnel.
1583 * @param cls Closure (unused).
1584 * @param key Current public key.
1585 * @param value Value in the hash map (tunnel).
1587 * @return #GNUNET_YES, so we should continue to iterate,
1590 destroy_iterator (void *cls,
1591 const struct GNUNET_PeerIdentity *key,
1594 struct CadetTunnel *t = value;
1596 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
1603 * Notify remote peer that we don't know a channel he is talking about,
1604 * probably CHANNEL_DESTROY was missed.
1606 * @param t Tunnel on which to notify.
1607 * @param gid ID of the channel.
1610 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
1612 struct GNUNET_CADET_ChannelManage msg;
1614 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
1615 msg.header.size = htons (sizeof (msg));
1616 msg.chid = htonl (gid);
1618 LOG (GNUNET_ERROR_TYPE_DEBUG,
1619 "WARNING destroying unknown channel %u on tunnel %s\n",
1621 send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
1626 * Demultiplex data per channel and call appropriate channel handler.
1628 * @param t Tunnel on which the data came.
1629 * @param msg Data message.
1630 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1631 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1632 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1633 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1636 handle_data (struct CadetTunnel *t,
1637 const struct GNUNET_CADET_Data *msg,
1640 struct CadetChannel *ch;
1644 size = ntohs (msg->header.size);
1646 sizeof (struct GNUNET_CADET_Data) +
1647 sizeof (struct GNUNET_MessageHeader))
1652 LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
1653 GC_m2s (ntohs (msg[1].header.type)));
1656 ch = GCT_get_channel (t, ntohl (msg->chid));
1659 GNUNET_STATISTICS_update (stats, "# data on unknown channel",
1661 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
1663 send_channel_destroy (t, ntohl (msg->chid));
1667 GCCH_handle_data (ch, msg, fwd);
1672 * Demultiplex data ACKs per channel and update appropriate channel buffer info.
1674 * @param t Tunnel on which the DATA ACK came.
1675 * @param msg DATA ACK message.
1676 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1677 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1678 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1679 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1682 handle_data_ack (struct CadetTunnel *t,
1683 const struct GNUNET_CADET_DataACK *msg,
1686 struct CadetChannel *ch;
1690 size = ntohs (msg->header.size);
1691 if (size != sizeof (struct GNUNET_CADET_DataACK))
1698 ch = GCT_get_channel (t, ntohl (msg->chid));
1701 GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
1703 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1708 GCCH_handle_data_ack (ch, msg, fwd);
1713 * Handle channel create.
1715 * @param t Tunnel on which the data came.
1716 * @param msg Data message.
1719 handle_ch_create (struct CadetTunnel *t,
1720 const struct GNUNET_CADET_ChannelCreate *msg)
1722 struct CadetChannel *ch;
1726 size = ntohs (msg->header.size);
1727 if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
1734 ch = GCT_get_channel (t, ntohl (msg->chid));
1735 if (NULL != ch && ! GCT_is_loopback (t))
1737 /* Probably a retransmission, safe to ignore */
1738 LOG (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
1740 ch = GCCH_handle_create (t, msg);
1742 GCT_add_channel (t, ch);
1748 * Handle channel NACK: check correctness and call channel handler for NACKs.
1750 * @param t Tunnel on which the NACK came.
1751 * @param msg NACK message.
1754 handle_ch_nack (struct CadetTunnel *t,
1755 const struct GNUNET_CADET_ChannelManage *msg)
1757 struct CadetChannel *ch;
1761 size = ntohs (msg->header.size);
1762 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1769 ch = GCT_get_channel (t, ntohl (msg->chid));
1772 GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
1774 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1779 GCCH_handle_nack (ch);
1784 * Handle a CHANNEL ACK (SYNACK/ACK).
1786 * @param t Tunnel on which the CHANNEL ACK came.
1787 * @param msg CHANNEL ACK message.
1788 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1789 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1790 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1791 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1794 handle_ch_ack (struct CadetTunnel *t,
1795 const struct GNUNET_CADET_ChannelManage *msg,
1798 struct CadetChannel *ch;
1802 size = ntohs (msg->header.size);
1803 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1810 ch = GCT_get_channel (t, ntohl (msg->chid));
1813 GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
1815 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1820 GCCH_handle_ack (ch, msg, fwd);
1825 * Handle a channel destruction message.
1827 * @param t Tunnel on which the message came.
1828 * @param msg Channel destroy message.
1829 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1830 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1831 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1832 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1835 handle_ch_destroy (struct CadetTunnel *t,
1836 const struct GNUNET_CADET_ChannelManage *msg,
1839 struct CadetChannel *ch;
1843 size = ntohs (msg->header.size);
1844 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1851 ch = GCT_get_channel (t, ntohl (msg->chid));
1854 /* Probably a retransmission, safe to ignore */
1858 GCCH_handle_destroy (ch, msg, fwd);
1863 * The peer's ephemeral key has changed: update the symmetrical keys.
1865 * @param t Tunnel this message came on.
1866 * @param msg Key eXchange message.
1869 handle_ephemeral (struct CadetTunnel *t,
1870 const struct GNUNET_CADET_KX_Ephemeral *msg)
1872 LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
1874 if (GNUNET_OK != check_ephemeral (t, msg))
1876 GNUNET_break_op (0);
1881 * If the key is different from what we know, derive the new E/D keys.
1882 * Else destroy the rekey ctx (duplicate EPHM after successful KX).
1884 if (0 != memcmp (&t->peers_ephemeral_key, &msg->ephemeral_key,
1885 sizeof (msg->ephemeral_key)))
1887 #if DUMP_KEYS_TO_STDERR
1888 LOG (GNUNET_ERROR_TYPE_INFO, "OLD: %s\n",
1889 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
1890 LOG (GNUNET_ERROR_TYPE_INFO, "NEW: %s\n",
1891 GNUNET_h2s ((struct GNUNET_HashCode *) &msg->ephemeral_key));
1893 t->peers_ephemeral_key = msg->ephemeral_key;
1896 if (CADET_TUNNEL_KEY_OK == t->estate)
1898 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
1900 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
1901 GNUNET_SCHEDULER_cancel (t->rekey_task);
1902 t->rekey_task = GNUNET_SCHEDULER_add_now (rekey_tunnel, t);
1904 if (CADET_TUNNEL_KEY_SENT == t->estate)
1906 LOG (GNUNET_ERROR_TYPE_DEBUG, " our key was sent, sending ping\n");
1908 GCT_change_estate (t, CADET_TUNNEL_KEY_PING);
1914 * Peer wants to check our symmetrical keys by sending an encrypted challenge.
1915 * Answer with by retransmitting the challenge with the "opposite" key.
1917 * @param t Tunnel this message came on.
1918 * @param msg Key eXchange Ping message.
1921 handle_ping (struct CadetTunnel *t,
1922 const struct GNUNET_CADET_KX_Ping *msg)
1924 struct GNUNET_CADET_KX_Ping res;
1926 if (ntohs (msg->header.size) != sizeof (res))
1928 GNUNET_break_op (0);
1932 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PING for %s\n", GCT_2s (t));
1933 t_decrypt (t, &res.target, &msg->target, ping_encryption_size (), msg->iv);
1934 if (0 != memcmp (&my_full_id, &res.target, sizeof (my_full_id)))
1936 /* probably peer hasn't got our new EPHM yet and derived the wrong keys */
1937 GNUNET_STATISTICS_update (stats, "# malformed PINGs", 1, GNUNET_NO);
1938 LOG (GNUNET_ERROR_TYPE_INFO, " malformed PING on %s\n", GCT_2s (t));
1939 LOG (GNUNET_ERROR_TYPE_DEBUG, " e got %u\n", msg->nonce);
1940 LOG (GNUNET_ERROR_TYPE_DEBUG, " e towards %s\n", GNUNET_i2s (&msg->target));
1941 LOG (GNUNET_ERROR_TYPE_DEBUG, " got %u\n", res.nonce);
1942 LOG (GNUNET_ERROR_TYPE_DEBUG, " towards %s\n", GNUNET_i2s (&res.target));
1949 send_pong (t, res.nonce);
1954 * Peer has answer to our challenge.
1955 * If answer is successful, consider the key exchange finished and clean
1956 * up all related state.
1958 * @param t Tunnel this message came on.
1959 * @param msg Key eXchange Pong message.
1962 handle_pong (struct CadetTunnel *t,
1963 const struct GNUNET_CADET_KX_Pong *msg)
1967 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
1968 if (GNUNET_SCHEDULER_NO_TASK == t->rekey_task)
1970 GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
1973 t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
1975 if (challenge != t->kx_ctx->challenge)
1977 LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
1978 LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
1979 challenge, msg->nonce, t->kx_ctx->challenge);
1984 GNUNET_SCHEDULER_cancel (t->rekey_task);
1985 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1987 /* Don't free the old keys right away, but after a delay.
1988 * Rationale: the KX could have happened over a very fast connection,
1989 * with payload traffic still signed with the old key stuck in a slower
1991 * Don't keep the keys longer than 1/4 the rekey period, and no longer than
1995 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2000 * Demultiplex by message type and call appropriate handler for a message
2001 * towards a channel of a local tunnel.
2003 * @param t Tunnel this message came on.
2004 * @param msgh Message header.
2005 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2006 * #GNUNET_YES if message is FWD on the respective channel (loopback)
2007 * #GNUNET_NO if message is BCK on the respective channel (loopback)
2008 * #GNUNET_SYSERR if message on a one-ended channel (remote)
2011 handle_decrypted (struct CadetTunnel *t,
2012 const struct GNUNET_MessageHeader *msgh,
2017 type = ntohs (msgh->type);
2018 LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
2022 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
2023 /* Do nothing, connection aleady got updated. */
2024 GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
2027 case GNUNET_MESSAGE_TYPE_CADET_DATA:
2028 /* Don't send hop ACK, wait for client to ACK */
2029 handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
2032 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
2033 handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
2036 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
2037 handle_ch_create (t,
2038 (struct GNUNET_CADET_ChannelCreate *) msgh);
2041 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
2043 (struct GNUNET_CADET_ChannelManage *) msgh);
2046 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
2048 (struct GNUNET_CADET_ChannelManage *) msgh,
2052 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
2053 handle_ch_destroy (t,
2054 (struct GNUNET_CADET_ChannelManage *) msgh,
2059 GNUNET_break_op (0);
2060 LOG (GNUNET_ERROR_TYPE_WARNING,
2061 "end-to-end message not known (%u)\n",
2062 ntohs (msgh->type));
2063 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
2067 /******************************************************************************/
2068 /******************************** API ***********************************/
2069 /******************************************************************************/
2072 * Decrypt and demultiplex by message type. Call appropriate handler
2073 * for every message.
2075 * @param t Tunnel this message came on.
2076 * @param msg Encrypted message.
2079 GCT_handle_encrypted (struct CadetTunnel *t,
2080 const struct GNUNET_CADET_Encrypted *msg)
2082 size_t size = ntohs (msg->header.size);
2083 size_t payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
2085 char cbuf [payload_size];
2086 struct GNUNET_MessageHeader *msgh;
2089 decrypted_size = t_decrypt_and_validate (t, cbuf, &msg[1], payload_size,
2090 msg->iv, &msg->hmac);
2092 if (-1 == decrypted_size)
2094 GNUNET_break_op (0);
2099 while (off < decrypted_size)
2103 msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
2104 msize = ntohs (msgh->size);
2105 if (msize < sizeof (struct GNUNET_MessageHeader))
2107 GNUNET_break_op (0);
2110 handle_decrypted (t, msgh, GNUNET_SYSERR);
2117 * Demultiplex an encapsulated KX message by message type.
2119 * @param t Tunnel on which the message came.
2120 * @param message Payload of KX message.
2123 GCT_handle_kx (struct CadetTunnel *t,
2124 const struct GNUNET_MessageHeader *message)
2128 type = ntohs (message->type);
2129 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received\n", type);
2132 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
2133 handle_ephemeral (t, (struct GNUNET_CADET_KX_Ephemeral *) message);
2136 case GNUNET_MESSAGE_TYPE_CADET_KX_PING:
2137 handle_ping (t, (struct GNUNET_CADET_KX_Ping *) message);
2140 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
2141 handle_pong (t, (struct GNUNET_CADET_KX_Pong *) message);
2145 GNUNET_break_op (0);
2146 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message not known (%u)\n", type);
2152 * Initialize the tunnel subsystem.
2154 * @param c Configuration handle.
2155 * @param key ECC private key, to derive all other keys and do crypto.
2158 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
2159 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
2161 int expected_overhead;
2163 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
2166 sizeof (struct GNUNET_CADET_Encrypted) + sizeof (struct GNUNET_CADET_Data);
2167 GNUNET_assert (GNUNET_CONSTANTS_CADET_P2P_OVERHEAD == expected_overhead);
2170 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
2173 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
2174 "CADET", "DEFAULT_TTL", "USING DEFAULT");
2178 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
2181 rekey_period = GNUNET_TIME_UNIT_DAYS;
2184 my_private_key = key;
2185 kx_msg.header.size = htons (sizeof (kx_msg));
2186 kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
2187 kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
2188 kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
2189 kx_msg.origin_identity = my_full_id;
2190 rekey_task = GNUNET_SCHEDULER_add_now (&rekey, NULL);
2192 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
2197 * Shut down the tunnel subsystem.
2202 if (GNUNET_SCHEDULER_NO_TASK != rekey_task)
2204 GNUNET_SCHEDULER_cancel (rekey_task);
2205 rekey_task = GNUNET_SCHEDULER_NO_TASK;
2207 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
2208 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
2215 * @param destination Peer this tunnel is towards.
2217 struct CadetTunnel *
2218 GCT_new (struct CadetPeer *destination)
2220 struct CadetTunnel *t;
2222 t = GNUNET_new (struct CadetTunnel);
2224 t->peer = destination;
2227 GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
2228 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2239 * Change the tunnel's connection state.
2241 * @param t Tunnel whose connection state to change.
2242 * @param cstate New connection state.
2245 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
2249 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
2250 GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
2251 if (myid != GCP_get_short_id (t->peer) &&
2252 CADET_TUNNEL_READY != t->cstate &&
2253 CADET_TUNNEL_READY == cstate)
2256 if (CADET_TUNNEL_KEY_OK == t->estate)
2258 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered send queued data\n");
2259 send_queued_data (t);
2261 else if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
2263 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered rekey\n");
2264 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
2265 GNUNET_SCHEDULER_cancel (t->rekey_task);
2266 rekey_tunnel (t, NULL);
2271 if (CADET_TUNNEL_READY == cstate
2272 && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
2274 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered stop dht\n");
2275 GCP_stop_search (t->peer);
2281 * Change the tunnel encryption state.
2283 * @param t Tunnel whose encryption state to change, or NULL.
2284 * @param state New encryption state.
2287 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
2292 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate was %s\n",
2293 GCP_2s (t->peer), estate2s (t->estate));
2294 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate is now %s\n",
2295 GCP_2s (t->peer), estate2s (state));
2297 /* Send queued data if enc state changes to OK */
2298 if (myid != GCP_get_short_id (t->peer) &&
2299 CADET_TUNNEL_KEY_OK != t->estate && CADET_TUNNEL_KEY_OK == state)
2301 send_queued_data (t);
2309 * @brief Check if tunnel has too many connections, and remove one if necessary.
2311 * Currently this means the newest connection, unless it is a direct one.
2312 * Implemented as a task to avoid freeing a connection that is in the middle
2313 * of being created/processed.
2315 * @param cls Closure (Tunnel to check).
2316 * @param tc Task context.
2319 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2321 struct CadetTunnel *t = cls;
2323 t->trim_connections_task = GNUNET_SCHEDULER_NO_TASK;
2325 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2328 if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
2330 struct CadetTConnection *iter;
2331 struct CadetTConnection *c;
2333 for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
2335 if ((NULL == c || iter->created.abs_value_us > c->created.abs_value_us)
2336 && GNUNET_NO == GCC_is_direct (iter->c))
2343 LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
2345 LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
2358 * Add a connection to a tunnel.
2361 * @param c Connection.
2364 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
2366 struct CadetTConnection *aux;
2368 GNUNET_assert (NULL != c);
2370 LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
2371 LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
2372 for (aux = t->connection_head; aux != NULL; aux = aux->next)
2376 aux = GNUNET_new (struct CadetTConnection);
2378 aux->created = GNUNET_TIME_absolute_get ();
2380 GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
2382 if (CADET_TUNNEL_SEARCHING == t->cstate)
2383 GCT_change_estate (t, CADET_TUNNEL_WAITING);
2385 if (GNUNET_SCHEDULER_NO_TASK != t->trim_connections_task)
2386 t->trim_connections_task = GNUNET_SCHEDULER_add_now (&trim_connections, t);
2391 * Remove a connection from a tunnel.
2394 * @param c Connection.
2397 GCT_remove_connection (struct CadetTunnel *t,
2398 struct CadetConnection *c)
2400 struct CadetTConnection *aux;
2401 struct CadetTConnection *next;
2404 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
2405 GCC_2s (c), GCT_2s (t));
2406 for (aux = t->connection_head; aux != NULL; aux = next)
2411 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
2416 conns = GCT_count_connections (t);
2418 && GNUNET_SCHEDULER_NO_TASK == t->destroy_task
2419 && CADET_TUNNEL_SHUTDOWN != t->cstate
2420 && GNUNET_NO == shutting_down)
2422 if (0 == GCT_count_any_connections (t))
2423 GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
2425 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
2428 /* Start new connections if needed */
2429 if (CONNECTIONS_PER_TUNNEL > conns
2430 && GNUNET_SCHEDULER_NO_TASK == t->destroy_task
2431 && CADET_TUNNEL_SHUTDOWN != t->cstate
2432 && GNUNET_NO == shutting_down)
2434 LOG (GNUNET_ERROR_TYPE_DEBUG, " too few connections, getting new ones\n");
2435 GCP_connect (t->peer); /* Will change cstate to WAITING when possible */
2439 /* If not marked as ready, no change is needed */
2440 if (CADET_TUNNEL_READY != t->cstate)
2443 /* Check if any connection is ready to maintain cstate */
2444 for (aux = t->connection_head; aux != NULL; aux = aux->next)
2445 if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
2451 * Add a channel to a tunnel.
2454 * @param ch Channel.
2457 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2459 struct CadetTChannel *aux;
2461 GNUNET_assert (NULL != ch);
2463 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
2465 for (aux = t->channel_head; aux != NULL; aux = aux->next)
2467 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
2472 aux = GNUNET_new (struct CadetTChannel);
2474 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
2475 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
2477 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2479 GNUNET_SCHEDULER_cancel (t->destroy_task);
2480 t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2481 LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
2487 * Remove a channel from a tunnel.
2490 * @param ch Channel.
2493 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2495 struct CadetTChannel *aux;
2497 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
2498 for (aux = t->channel_head; aux != NULL; aux = aux->next)
2502 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
2503 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
2512 * Search for a channel by global ID.
2514 * @param t Tunnel containing the channel.
2515 * @param chid Public channel number.
2517 * @return channel handler, NULL if doesn't exist
2519 struct CadetChannel *
2520 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
2522 struct CadetTChannel *iter;
2527 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2529 if (GCCH_get_id (iter->ch) == chid)
2533 return NULL == iter ? NULL : iter->ch;
2538 * @brief Destroy a tunnel and free all resources.
2540 * Should only be called a while after the tunnel has been marked as destroyed,
2541 * in case there is a new channel added to the same peer shortly after marking
2542 * the tunnel. This way we avoid a new public key handshake.
2544 * @param cls Closure (tunnel to destroy).
2545 * @param tc Task context.
2548 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2550 struct CadetTunnel *t = cls;
2551 struct CadetTConnection *iter;
2553 LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
2554 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2556 LOG (GNUNET_ERROR_TYPE_WARNING,
2557 "Not destroying tunnel, due to shutdown. "
2558 "Tunnel at %p should have been freed by GCT_shutdown\n", t);
2561 t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2562 t->cstate = CADET_TUNNEL_SHUTDOWN;
2564 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2566 GCC_send_destroy (iter->c);
2573 * Tunnel is empty: destroy it.
2575 * Notifies all connections about the destruction.
2577 * @param t Tunnel to destroy.
2580 GCT_destroy_empty (struct CadetTunnel *t)
2582 if (GNUNET_YES == shutting_down)
2583 return; /* Will be destroyed immediately anyway */
2585 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2587 LOG (GNUNET_ERROR_TYPE_WARNING,
2588 "Tunnel %s is already scheduled for destruction. Tunnel debug dump:\n",
2590 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
2592 /* should never happen, tunnel can only become empty once, and the
2593 * task identifier should be NO_TASK (cleaned when the tunnel was created
2594 * or became un-empty)
2599 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: destroying scheduled\n",
2602 // FIXME make delay a config option
2603 t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
2604 &delayed_destroy, t);
2605 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llX\n",
2606 t, t->destroy_task);
2611 * Destroy tunnel if empty (no more channels).
2613 * @param t Tunnel to destroy if empty.
2616 GCT_destroy_if_empty (struct CadetTunnel *t)
2618 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
2619 if (1 < GCT_count_channels (t))
2622 GCT_destroy_empty (t);
2627 * Destroy the tunnel.
2629 * This function does not generate any warning traffic to clients or peers.
2632 * Cancel messages belonging to this tunnel queued to neighbors.
2633 * Free any allocated resources linked to the tunnel.
2635 * @param t The tunnel to destroy.
2638 GCT_destroy (struct CadetTunnel *t)
2640 struct CadetTConnection *iter_c;
2641 struct CadetTConnection *next_c;
2642 struct CadetTChannel *iter_ch;
2643 struct CadetTChannel *next_ch;
2648 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
2650 GNUNET_break (GNUNET_YES ==
2651 GNUNET_CONTAINER_multipeermap_remove (tunnels,
2652 GCP_get_id (t->peer), t));
2654 for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
2656 next_c = iter_c->next;
2657 GCC_destroy (iter_c->c);
2659 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
2661 next_ch = iter_ch->next;
2662 GCCH_destroy (iter_ch->ch);
2663 /* Should only happen on shutdown, but it's ok. */
2666 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2668 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling dest: %llX\n", t->destroy_task);
2669 GNUNET_SCHEDULER_cancel (t->destroy_task);
2670 t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2673 if (GNUNET_SCHEDULER_NO_TASK != t->trim_connections_task)
2675 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling trim: %llX\n",
2676 t->trim_connections_task);
2677 GNUNET_SCHEDULER_cancel (t->trim_connections_task);
2678 t->trim_connections_task = GNUNET_SCHEDULER_NO_TASK;
2681 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
2682 GCP_set_tunnel (t->peer, NULL);
2684 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
2686 GNUNET_SCHEDULER_cancel (t->rekey_task);
2687 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
2689 if (NULL != t->kx_ctx)
2691 if (GNUNET_SCHEDULER_NO_TASK != t->kx_ctx->finish_task)
2692 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
2693 GNUNET_free (t->kx_ctx);
2700 * @brief Use the given path for the tunnel.
2701 * Update the next and prev hops (and RCs).
2702 * (Re)start the path refresh in case the tunnel is locally owned.
2704 * @param t Tunnel to update.
2705 * @param p Path to use.
2707 * @return Connection created.
2709 struct CadetConnection *
2710 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
2712 struct CadetConnection *c;
2713 struct GNUNET_CADET_Hash cid;
2714 unsigned int own_pos;
2716 if (NULL == t || NULL == p)
2722 if (CADET_TUNNEL_SHUTDOWN == t->cstate)
2728 for (own_pos = 0; own_pos < p->length; own_pos++)
2730 if (p->peers[own_pos] == myid)
2733 if (own_pos >= p->length)
2735 GNUNET_break_op (0);
2739 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
2740 c = GCC_new (&cid, t, p, own_pos);
2743 /* Path was flawed */
2746 GCT_add_connection (t, c);
2752 * Count all created connections of a tunnel. Not necessarily ready connections!
2754 * @param t Tunnel on which to count.
2756 * @return Number of connections created, either being established or ready.
2759 GCT_count_any_connections (struct CadetTunnel *t)
2761 struct CadetTConnection *iter;
2767 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2775 * Count established (ready) connections of a tunnel.
2777 * @param t Tunnel on which to count.
2779 * @return Number of connections.
2782 GCT_count_connections (struct CadetTunnel *t)
2784 struct CadetTConnection *iter;
2790 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2791 if (CADET_CONNECTION_DESTROYED != GCC_get_state (iter->c))
2799 * Count channels of a tunnel.
2801 * @param t Tunnel on which to count.
2803 * @return Number of channels.
2806 GCT_count_channels (struct CadetTunnel *t)
2808 struct CadetTChannel *iter;
2811 for (count = 0, iter = t->channel_head;
2813 iter = iter->next, count++) /* skip */;
2820 * Get the connectivity state of a tunnel.
2824 * @return Tunnel's connectivity state.
2826 enum CadetTunnelCState
2827 GCT_get_cstate (struct CadetTunnel *t)
2832 return (enum CadetTunnelCState) -1;
2839 * Get the encryption state of a tunnel.
2843 * @return Tunnel's encryption state.
2845 enum CadetTunnelEState
2846 GCT_get_estate (struct CadetTunnel *t)
2851 return (enum CadetTunnelEState) -1;
2857 * Get the maximum buffer space for a tunnel towards a local client.
2861 * @return Biggest buffer space offered by any channel in the tunnel.
2864 GCT_get_channels_buffer (struct CadetTunnel *t)
2866 struct CadetTChannel *iter;
2867 unsigned int buffer;
2868 unsigned int ch_buf;
2870 if (NULL == t->channel_head)
2872 /* Probably getting buffer for a channel create/handshake. */
2877 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2879 ch_buf = get_channel_buffer (iter);
2880 if (ch_buf > buffer)
2888 * Get the total buffer space for a tunnel for P2P traffic.
2892 * @return Buffer space offered by all connections in the tunnel.
2895 GCT_get_connections_buffer (struct CadetTunnel *t)
2897 struct CadetTConnection *iter;
2898 unsigned int buffer;
2900 if (GNUNET_NO == is_ready (t))
2902 if (count_queued_data (t) > 3)
2909 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2911 if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
2915 buffer += get_connection_buffer (iter);
2923 * Get the tunnel's destination.
2927 * @return ID of the destination peer.
2929 const struct GNUNET_PeerIdentity *
2930 GCT_get_destination (struct CadetTunnel *t)
2932 return GCP_get_id (t->peer);
2937 * Get the tunnel's next free global channel ID.
2941 * @return GID of a channel free to use.
2944 GCT_get_next_chid (struct CadetTunnel *t)
2946 CADET_ChannelNumber chid;
2947 CADET_ChannelNumber mask;
2950 /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
2951 * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
2952 * If peer's ID is bigger, start at 0x4... bit 30 = 1
2954 result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
2959 t->next_chid |= mask;
2961 while (NULL != GCT_get_channel (t, t->next_chid))
2963 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
2964 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
2965 t->next_chid |= mask;
2967 chid = t->next_chid;
2968 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
2969 t->next_chid |= mask;
2976 * Send ACK on one or more channels due to buffer in connections.
2978 * @param t Channel which has some free buffer space.
2981 GCT_unchoke_channels (struct CadetTunnel *t)
2983 struct CadetTChannel *iter;
2984 unsigned int buffer;
2985 unsigned int channels = GCT_count_channels (t);
2986 unsigned int choked_n;
2987 struct CadetChannel *choked[channels];
2989 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
2990 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
2991 if (NULL != t->channel_head)
2992 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
2994 /* Get buffer space */
2995 buffer = GCT_get_connections_buffer (t);
3001 /* Count and remember choked channels */
3003 for (iter = t->channel_head; NULL != iter; iter = iter->next)
3005 if (GNUNET_NO == get_channel_allowed (iter))
3007 choked[choked_n++] = iter->ch;
3011 /* Unchoke random channels */
3012 while (0 < buffer && 0 < choked_n)
3014 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3016 GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
3019 choked[r] = choked[choked_n];
3025 * Send ACK on one or more connections due to buffer space to the client.
3027 * Iterates all connections of the tunnel and sends ACKs appropriately.
3032 GCT_send_connection_acks (struct CadetTunnel *t)
3034 struct CadetTConnection *iter;
3037 uint32_t allow_per_connection;
3039 unsigned int buffer;
3041 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
3050 buffer = GCT_get_channels_buffer (t);
3051 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer %u\n", buffer);
3053 /* Count connections, how many messages are already allowed */
3054 cs = GCT_count_connections (t);
3055 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3057 allowed += get_connection_allowed (iter);
3059 LOG (GNUNET_ERROR_TYPE_DEBUG, " allowed %u\n", allowed);
3061 /* Make sure there is no overflow */
3062 if (allowed > buffer)
3067 /* Authorize connections to send more data */
3068 to_allow = buffer; /* - allowed; */
3070 for (iter = t->connection_head;
3071 NULL != iter && to_allow > 0;
3074 allow_per_connection = to_allow/cs;
3075 to_allow -= allow_per_connection;
3077 if (get_connection_allowed (iter) > 64 / 3)
3081 GCC_allow (iter->c, allow_per_connection,
3082 GCC_is_origin (iter->c, GNUNET_NO));
3085 GNUNET_break (to_allow == 0); //FIXME tripped
3090 * Cancel a previously sent message while it's in the queue.
3092 * ONLY can be called before the continuation given to the send function
3093 * is called. Once the continuation is called, the message is no longer in the
3096 * @param q Handle to the queue.
3099 GCT_cancel (struct CadetTunnelQueue *q)
3104 /* tun_message_sent() will be called and free q */
3106 else if (NULL != q->tqd)
3108 unqueue_data (q->tqd);
3110 if (NULL != q->cont)
3111 q->cont (q->cont_cls, NULL, q, 0, 0);
3122 * Sends an already built message on a tunnel, encrypting it and
3123 * choosing the best connection if not provided.
3125 * @param message Message to send. Function modifies it.
3126 * @param t Tunnel on which this message is transmitted.
3127 * @param c Connection to use (autoselect if NULL).
3128 * @param force Force the tunnel to take the message (buffer overfill).
3129 * @param cont Continuation to call once message is really sent.
3130 * @param cont_cls Closure for @c cont.
3132 * @return Handle to cancel message. NULL if @c cont is NULL.
3134 struct CadetTunnelQueue *
3135 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
3136 struct CadetTunnel *t, struct CadetConnection *c,
3137 int force, GCT_sent cont, void *cont_cls)
3139 return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
3143 * Sends an already built and encrypted message on a tunnel, choosing the best
3144 * connection. Useful for re-queueing messages queued on a destroyed connection.
3146 * @param message Message to send. Function modifies it.
3147 * @param t Tunnel on which this message is transmitted.
3150 GCT_resend_message (const struct GNUNET_MessageHeader *message,
3151 struct CadetTunnel *t)
3153 struct CadetConnection *c;
3156 c = tunnel_get_connection (t);
3159 /* TODO queue in tunnel, marked as encrypted */
3160 LOG (GNUNET_ERROR_TYPE_DEBUG, "No connection available, dropping.\n");
3163 fwd = GCC_is_origin (c, GNUNET_YES);
3164 GNUNET_break (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
3165 GNUNET_YES, NULL, NULL));
3170 * Is the tunnel directed towards the local peer?
3174 * @return #GNUNET_YES if it is loopback.
3177 GCT_is_loopback (const struct CadetTunnel *t)
3179 return (myid == GCP_get_short_id (t->peer));
3184 * Is the tunnel this path already?
3189 * @return #GNUNET_YES a connection uses this path.
3192 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
3194 struct CadetTConnection *iter;
3196 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3197 if (GCC_get_path (iter->c) == p)
3205 * Get a cost of a path for a tunnel considering existing connections.
3208 * @param path Candidate path.
3210 * @return Cost of the path (path length + number of overlapping nodes)
3213 GCT_get_path_cost (const struct CadetTunnel *t,
3214 const struct CadetPeerPath *path)
3216 struct CadetTConnection *iter;
3217 const struct CadetPeerPath *aux;
3218 unsigned int overlap;
3226 GNUNET_assert (NULL != t);
3228 for (i = 0; i < path->length; i++)
3230 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3232 aux = GCC_get_path (iter->c);
3236 for (j = 0; j < aux->length; j++)
3238 if (path->peers[i] == aux->peers[j])
3246 return path->length + overlap;
3251 * Get the static string for the peer this tunnel is directed.
3255 * @return Static string the destination peer's ID.
3258 GCT_2s (const struct CadetTunnel *t)
3263 return GCP_2s (t->peer);
3267 /******************************************************************************/
3268 /***************************** INFO/DEBUG *******************************/
3269 /******************************************************************************/
3272 * Log all possible info about the tunnel state.
3274 * @param t Tunnel to debug.
3275 * @param level Debug level to use.
3278 GCT_debug (const struct CadetTunnel *t, enum GNUNET_ErrorType level)
3280 struct CadetTChannel *iterch;
3281 struct CadetTConnection *iterc;
3284 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
3286 __FILE__, __FUNCTION__, __LINE__);
3290 LOG2 (level, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
3291 LOG2 (level, "TTT cstate %s, estate %s\n",
3292 cstate2s (t->cstate), estate2s (t->estate));
3293 LOG2 (level, "TTT kx_ctx %p, rekey_task %u, finish task %u\n",
3294 t->kx_ctx, t->rekey_task, t->kx_ctx ? t->kx_ctx->finish_task : 0);
3295 #if DUMP_KEYS_TO_STDERR
3296 LOG2 (level, "TTT my EPHM\t %s\n",
3297 GNUNET_h2s ((struct GNUNET_HashCode *) &kx_msg.ephemeral_key));
3298 LOG2 (level, "TTT peers EPHM:\t %s\n",
3299 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
3300 LOG2 (level, "TTT ENC key:\t %s\n",
3301 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
3302 LOG2 (level, "TTT DEC key:\t %s\n",
3303 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
3306 LOG2 (level, "TTT OLD ENC key:\t %s\n",
3307 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->e_key_old));
3308 LOG2 (level, "TTT OLD DEC key:\t %s\n",
3309 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->d_key_old));
3312 LOG2 (level, "TTT tq_head %p, tq_tail %p\n", t->tq_head, t->tq_tail);
3313 LOG2 (level, "TTT destroy %u\n", t->destroy_task);
3315 LOG2 (level, "TTT channels:\n");
3316 for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
3318 LOG2 (level, "TTT - %s\n", GCCH_2s (iterch->ch));
3321 LOG2 (level, "TTT connections:\n");
3322 for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
3324 GCC_debug (iterc->c, level);
3327 LOG2 (level, "TTT DEBUG TUNNEL END\n");
3332 * Iterate all tunnels.
3334 * @param iter Iterator.
3335 * @param cls Closure for @c iter.
3338 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
3340 GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
3345 * Count all tunnels.
3347 * @return Number of tunnels to remote peers kept by this peer.
3350 GCT_count_all (void)
3352 return GNUNET_CONTAINER_multipeermap_size (tunnels);
3357 * Iterate all connections of a tunnel.
3359 * @param t Tunnel whose connections to iterate.
3360 * @param iter Iterator.
3361 * @param cls Closure for @c iter.
3364 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
3366 struct CadetTConnection *ct;
3368 for (ct = t->connection_head; NULL != ct; ct = ct->next)
3374 * Iterate all channels of a tunnel.
3376 * @param t Tunnel whose channels to iterate.
3377 * @param iter Iterator.
3378 * @param cls Closure for @c iter.
3381 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
3383 struct CadetTChannel *cht;
3385 for (cht = t->channel_head; NULL != cht; cht = cht->next)
3386 iter (cls, cht->ch);