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 #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 * Challenge to send in a ping and expect in the pong.
112 * When the rekey started. One minute after this the new key will be used.
114 struct GNUNET_TIME_Absolute rekey_start_time;
117 * Task for delayed destruction of the Key eXchange context, to allow delayed
118 * messages with the old key to be decrypted successfully.
120 GNUNET_SCHEDULER_TaskIdentifier finish_task;
124 * Struct containing all information regarding a tunnel to a peer.
129 * Endpoint of the tunnel.
131 struct CadetPeer *peer;
134 * State of the tunnel connectivity.
136 enum CadetTunnelCState cstate;
139 * State of the tunnel encryption.
141 enum CadetTunnelEState estate;
144 * Key eXchange context.
146 struct CadetTunnelKXCtx *kx_ctx;
149 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own ephemeral
152 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
155 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
157 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
160 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
162 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
165 * Task to start the rekey process.
167 GNUNET_SCHEDULER_TaskIdentifier rekey_task;
170 * Paths that are actively used to reach the destination peer.
172 struct CadetTConnection *connection_head;
173 struct CadetTConnection *connection_tail;
176 * Next connection number.
181 * Channels inside this tunnel.
183 struct CadetTChannel *channel_head;
184 struct CadetTChannel *channel_tail;
187 * Channel ID for the next created channel.
189 CADET_ChannelNumber next_chid;
192 * Destroy flag: if true, destroy on last message.
194 GNUNET_SCHEDULER_TaskIdentifier destroy_task;
197 * Queued messages, to transmit once tunnel gets connected.
199 struct CadetTunnelDelayed *tq_head;
200 struct CadetTunnelDelayed *tq_tail;
203 * Task to trim connections if too many are present.
205 GNUNET_SCHEDULER_TaskIdentifier trim_connections_task;
210 * Struct used to save messages in a non-ready tunnel to send once connected.
212 struct CadetTunnelDelayed
217 struct CadetTunnelDelayed *next;
218 struct CadetTunnelDelayed *prev;
223 struct CadetTunnel *t;
226 * Tunnel queue given to the channel to cancel request. Update on send_queued.
228 struct CadetTunnelQueue *tq;
233 /* struct GNUNET_MessageHeader *msg; */
238 * Handle for messages queued but not yet sent.
240 struct CadetTunnelQueue
243 * Connection queue handle, to cancel if necessary.
245 struct CadetConnectionQueue *cq;
248 * Handle in case message hasn't been given to a connection yet.
250 struct CadetTunnelDelayed *tqd;
253 * Continuation to call once sent.
258 * Closure for @c cont.
264 /******************************************************************************/
265 /******************************* GLOBALS ***********************************/
266 /******************************************************************************/
269 * Global handle to the statistics service.
271 extern struct GNUNET_STATISTICS_Handle *stats;
274 * Local peer own ID (memory efficient handle).
276 extern GNUNET_PEER_Id myid;
279 * Local peer own ID (full value).
281 extern struct GNUNET_PeerIdentity my_full_id;
285 * Don't try to recover tunnels if shutting down.
287 extern int shutting_down;
291 * Set of all tunnels, in order to trigger a new exchange on rekey.
292 * Indexed by peer's ID.
294 static struct GNUNET_CONTAINER_MultiPeerMap *tunnels;
297 * Default TTL for payload packets.
299 static unsigned long long default_ttl;
304 const static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
307 * Own ephemeral private key.
309 static struct GNUNET_CRYPTO_EcdhePrivateKey *my_ephemeral_key;
312 * Cached message used to perform a key exchange.
314 static struct GNUNET_CADET_KX_Ephemeral kx_msg;
317 * Task to generate a new ephemeral key.
319 static GNUNET_SCHEDULER_TaskIdentifier rekey_task;
324 static struct GNUNET_TIME_Relative rekey_period;
326 /******************************************************************************/
327 /******************************** STATIC ***********************************/
328 /******************************************************************************/
331 * Get string description for tunnel connectivity state.
333 * @param cs Tunnel state.
335 * @return String representation.
338 cstate2s (enum CadetTunnelCState cs)
344 case CADET_TUNNEL_NEW:
345 return "CADET_TUNNEL_NEW";
346 case CADET_TUNNEL_SEARCHING:
347 return "CADET_TUNNEL_SEARCHING";
348 case CADET_TUNNEL_WAITING:
349 return "CADET_TUNNEL_WAITING";
350 case CADET_TUNNEL_READY:
351 return "CADET_TUNNEL_READY";
352 case CADET_TUNNEL_SHUTDOWN:
353 return "CADET_TUNNEL_SHUTDOWN";
355 SPRINTF (buf, "%u (UNKNOWN STATE)", cs);
363 * Get string description for tunnel encryption state.
365 * @param es Tunnel state.
367 * @return String representation.
370 estate2s (enum CadetTunnelEState es)
376 case CADET_TUNNEL_KEY_UNINITIALIZED:
377 return "CADET_TUNNEL_KEY_UNINITIALIZED";
378 case CADET_TUNNEL_KEY_SENT:
379 return "CADET_TUNNEL_KEY_SENT";
380 case CADET_TUNNEL_KEY_PING:
381 return "CADET_TUNNEL_KEY_PING";
382 case CADET_TUNNEL_KEY_OK:
383 return "CADET_TUNNEL_KEY_OK";
384 case CADET_TUNNEL_KEY_REKEY:
385 return "CADET_TUNNEL_KEY_REKEY";
387 SPRINTF (buf, "%u (UNKNOWN STATE)", es);
395 * @brief Check if tunnel is ready to send traffic.
397 * Tunnel must be connected and with encryption correctly set up.
399 * @param t Tunnel to check.
401 * @return #GNUNET_YES if ready, #GNUNET_NO otherwise
404 is_ready (struct CadetTunnel *t)
408 GCT_debug (t, GNUNET_ERROR_TYPE_DEBUG);
409 ready = CADET_TUNNEL_READY == t->cstate
410 && (CADET_TUNNEL_KEY_OK == t->estate
411 || CADET_TUNNEL_KEY_REKEY == t->estate);
412 ready = ready || GCT_is_loopback (t);
418 * Check if a key is invalid (NULL pointer or all 0)
420 * @param key Key to check.
422 * @return #GNUNET_YES if key is null, #GNUNET_NO if exists and is not 0.
425 is_key_null (struct GNUNET_CRYPTO_SymmetricSessionKey *key)
427 struct GNUNET_CRYPTO_SymmetricSessionKey null_key;
432 memset (&null_key, 0, sizeof (null_key));
433 if (0 == memcmp (key, &null_key, sizeof (null_key)))
440 * Ephemeral key message purpose size.
442 * @return Size of the part of the ephemeral key message that must be signed.
445 ephemeral_purpose_size (void)
447 return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
448 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
449 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
450 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
451 sizeof (struct GNUNET_PeerIdentity);
456 * Size of the encrypted part of a ping message.
458 * @return Size of the encrypted part of a ping message.
461 ping_encryption_size (void)
463 return sizeof (uint32_t);
468 * Get the channel's buffer. ONLY FOR NON-LOOPBACK CHANNELS!!
470 * @param tch Tunnel's channel handle.
472 * @return Amount of messages the channel can still buffer towards the client.
475 get_channel_buffer (const struct CadetTChannel *tch)
479 /* If channel is incoming, is terminal in the FWD direction and fwd is YES */
480 fwd = GCCH_is_terminal (tch->ch, GNUNET_YES);
482 return GCCH_get_buffer (tch->ch, fwd);
487 * Get the channel's allowance status.
489 * @param tch Tunnel's channel handle.
491 * @return #GNUNET_YES if we allowed the client to send data to us.
494 get_channel_allowed (const struct CadetTChannel *tch)
498 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
499 fwd = GCCH_is_origin (tch->ch, GNUNET_YES);
501 return GCCH_get_allowed (tch->ch, fwd);
506 * Get the connection's buffer.
508 * @param tc Tunnel's connection handle.
510 * @return Amount of messages the connection can still buffer.
513 get_connection_buffer (const struct CadetTConnection *tc)
517 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
518 fwd = GCC_is_origin (tc->c, GNUNET_YES);
520 return GCC_get_buffer (tc->c, fwd);
525 * Get the connection's allowance.
527 * @param tc Tunnel's connection handle.
529 * @return Amount of messages we have allowed the next peer to send us.
532 get_connection_allowed (const struct CadetTConnection *tc)
536 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
537 fwd = GCC_is_origin (tc->c, GNUNET_YES);
539 return GCC_get_allowed (tc->c, fwd);
544 * Check that a ephemeral key message s well formed and correctly signed.
546 * @param t Tunnel on which the message came.
547 * @param msg The ephemeral key message.
549 * @return GNUNET_OK if message is fine, GNUNET_SYSERR otherwise.
552 check_ephemeral (struct CadetTunnel *t,
553 const struct GNUNET_CADET_KX_Ephemeral *msg)
555 /* Check message size */
556 if (ntohs (msg->header.size) != sizeof (struct GNUNET_CADET_KX_Ephemeral))
557 return GNUNET_SYSERR;
559 /* Check signature size */
560 if (ntohl (msg->purpose.size) != ephemeral_purpose_size ())
561 return GNUNET_SYSERR;
564 if (0 != memcmp (&msg->origin_identity,
565 GCP_get_id (t->peer),
566 sizeof (struct GNUNET_PeerIdentity)))
567 return GNUNET_SYSERR;
569 /* Check signature */
571 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_CADET_KX,
574 &msg->origin_identity.public_key))
575 return GNUNET_SYSERR;
582 * Select the best key to use for encryption (send), based on KX status.
584 * Normally, return the current key. If there is a KX in progress and the old
585 * key is fresh enough, return the old key.
587 * @param t Tunnel to choose the key from.
589 * @return The optimal key to encrypt/hmac outgoing traffic.
591 static const struct GNUNET_CRYPTO_SymmetricSessionKey *
592 select_key (const struct CadetTunnel *t)
594 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
596 if (NULL != t->kx_ctx
597 && GNUNET_SCHEDULER_NO_TASK == t->kx_ctx->finish_task)
599 struct GNUNET_TIME_Relative age;
601 age = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
602 LOG (GNUNET_ERROR_TYPE_DEBUG,
603 " key exchange in progress, started %s ago\n",
604 GNUNET_STRINGS_relative_time_to_string (age, GNUNET_YES));
605 // FIXME make duration of old keys configurable
606 if (age.rel_value_us < GNUNET_TIME_UNIT_MINUTES.rel_value_us)
608 LOG (GNUNET_ERROR_TYPE_DEBUG, " using old key\n");
609 key = &t->kx_ctx->e_key_old;
613 LOG (GNUNET_ERROR_TYPE_DEBUG, " using new key (old key too old)\n");
619 LOG (GNUNET_ERROR_TYPE_DEBUG, " no KX: using current key\n");
629 * @param plaintext Content to HMAC.
630 * @param size Size of @c plaintext.
631 * @param iv Initialization vector for the message.
632 * @param key Key to use.
633 * @param hmac[out] Destination to store the HMAC.
636 t_hmac (const void *plaintext, size_t size,
637 uint32_t iv, const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
638 struct GNUNET_CADET_Hash *hmac)
640 static const char ctx[] = "cadet authentication key";
641 struct GNUNET_CRYPTO_AuthKey auth_key;
642 struct GNUNET_HashCode hash;
644 #if DUMP_KEYS_TO_STDERR
645 LOG (GNUNET_ERROR_TYPE_INFO, " HMAC with key %s\n",
646 GNUNET_h2s ((struct GNUNET_HashCode *) key));
648 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
653 /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
654 GNUNET_CRYPTO_hmac (&auth_key, plaintext, size, &hash);
655 memcpy (hmac, &hash, sizeof (*hmac));
660 * Encrypt daforce_newest_keyta with the tunnel key.
662 * @param t Tunnel whose key to use.
663 * @param dst Destination for the encrypted data.
664 * @param src Source of the plaintext. Can overlap with @c dst.
665 * @param size Size of the plaintext.
666 * @param iv Initialization Vector to use.
667 * @param force_newest_key Force the use of the newest key, otherwise
668 * CADET will use the old key when allowed.
669 * This can happen in the case when a KX is going on
670 * and the old one hasn't expired.
673 t_encrypt (struct CadetTunnel *t, void *dst, const void *src,
674 size_t size, uint32_t iv, int force_newest_key)
676 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
677 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
680 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt start\n");
682 key = GNUNET_YES == force_newest_key ? &t->e_key : select_key (t);
683 #if DUMP_KEYS_TO_STDERR
684 LOG (GNUNET_ERROR_TYPE_INFO, " ENC with key %s\n",
685 GNUNET_h2s ((struct GNUNET_HashCode *) key));
687 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
688 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt IV derived\n");
689 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, key, &siv, dst);
690 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt end\n");
697 * Decrypt and verify data with the appropriate tunnel key.
699 * @param key Key to use.
700 * @param dst Destination for the plaintext.
701 * @param src Source of the encrypted data. Can overlap with @c dst.
702 * @param size Size of the encrypted data.
703 * @param iv Initialization Vector to use.
705 * @return Size of the decrypted data, -1 if an error was encountered.
708 decrypt (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
709 void *dst, const void *src, size_t size, uint32_t iv)
711 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
714 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt start\n");
715 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv\n");
716 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
717 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv done\n");
718 out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, key, &siv, dst);
719 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt end\n");
726 * Decrypt and verify data with the most recent tunnel key.
728 * @param t Tunnel whose key to use.
729 * @param dst Destination for the plaintext.
730 * @param src Source of the encrypted data. Can overlap with @c dst.
731 * @param size Size of the encrypted data.
732 * @param iv Initialization Vector to use.
734 * @return Size of the decrypted data, -1 if an error was encountered.
737 t_decrypt (struct CadetTunnel *t, void *dst, const void *src,
738 size_t size, uint32_t iv)
742 #if DUMP_KEYS_TO_STDERR
743 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_decrypt with %s\n",
744 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
746 if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
748 GNUNET_STATISTICS_update (stats, "# non decryptable data", 1, GNUNET_NO);
749 LOG (GNUNET_ERROR_TYPE_WARNING,
750 "got data on %s without a valid key\n",
752 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
756 out_size = decrypt (&t->d_key, dst, src, size, iv);
763 * Decrypt and verify data with the appropriate tunnel key and verify that the
764 * data has not been altered since it was sent by the remote peer.
766 * @param t Tunnel whose key to use.
767 * @param dst Destination for the plaintext.
768 * @param src Source of the encrypted data. Can overlap with @c dst.
769 * @param size Size of the encrypted data.
770 * @param iv Initialization Vector to use.
771 * @param msg_hmac HMAC of the message, cannot be NULL.
773 * @return Size of the decrypted data, -1 if an error was encountered.
776 t_decrypt_and_validate (struct CadetTunnel *t,
777 void *dst, const void *src,
778 size_t size, uint32_t iv,
779 const struct GNUNET_CADET_Hash *msg_hmac)
781 struct GNUNET_CRYPTO_SymmetricSessionKey *key;
782 struct GNUNET_CADET_Hash hmac;
785 /* Try primary (newest) key */
787 decrypted_size = decrypt (key, dst, src, size, iv);
788 t_hmac (src, size, iv, key, &hmac);
789 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
790 return decrypted_size;
792 /* If no key exchange is going on, we just failed */
793 if (NULL == t->kx_ctx)
795 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
796 "Failed checksum validation on tunnel %s with no KX\n",
798 GNUNET_STATISTICS_update (stats, "# wrong HMAC", 1, GNUNET_NO);
802 /* Try secondary (from previous KX period) key */
803 key = &t->kx_ctx->d_key_old;
804 decrypted_size = decrypt (key, dst, src, size, iv);
805 t_hmac (src, size, iv, key, &hmac);
806 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
807 return decrypted_size;
809 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
810 "Failed checksum validation on tunnel %s with KX\n",
812 GNUNET_STATISTICS_update (stats, "# wrong HMAC", 1, GNUNET_NO);
818 * Create key material by doing ECDH on the local and remote ephemeral keys.
820 * @param key_material Where to store the key material.
821 * @param ephemeral_key Peer's public ephemeral key.
824 derive_key_material (struct GNUNET_HashCode *key_material,
825 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key)
828 GNUNET_CRYPTO_ecc_ecdh (my_ephemeral_key,
838 * Create a symmetic key from the identities of both ends and the key material
841 * @param key Destination for the generated key.
842 * @param sender ID of the peer that will encrypt with @c key.
843 * @param receiver ID of the peer that will decrypt with @c key.
844 * @param key_material Hash created with ECDH with the ephemeral keys.
847 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
848 const struct GNUNET_PeerIdentity *sender,
849 const struct GNUNET_PeerIdentity *receiver,
850 const struct GNUNET_HashCode *key_material)
852 const char salt[] = "CADET kx salt";
854 GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
856 key_material, sizeof (struct GNUNET_HashCode),
857 sender, sizeof (struct GNUNET_PeerIdentity),
858 receiver, sizeof (struct GNUNET_PeerIdentity),
864 * Derive the tunnel's keys using our own and the peer's ephemeral keys.
866 * @param t Tunnel for which to create the keys.
869 create_keys (struct CadetTunnel *t)
871 struct GNUNET_HashCode km;
873 derive_key_material (&km, &t->peers_ephemeral_key);
874 derive_symmertic (&t->e_key, &my_full_id, GCP_get_id (t->peer), &km);
875 derive_symmertic (&t->d_key, GCP_get_id (t->peer), &my_full_id, &km);
876 #if DUMP_KEYS_TO_STDERR
877 LOG (GNUNET_ERROR_TYPE_INFO, "ME: %s\n",
878 GNUNET_h2s ((struct GNUNET_HashCode *) &kx_msg.ephemeral_key));
879 LOG (GNUNET_ERROR_TYPE_INFO, "PE: %s\n",
880 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
881 LOG (GNUNET_ERROR_TYPE_INFO, "KM: %s\n", GNUNET_h2s (&km));
882 LOG (GNUNET_ERROR_TYPE_INFO, "EK: %s\n",
883 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
884 LOG (GNUNET_ERROR_TYPE_INFO, "DK: %s\n",
885 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
891 * Create a new Key eXchange context for the tunnel.
893 * If the old keys were verified, keep them for old traffic. Create a new KX
894 * timestamp and a new nonce.
896 * @param t Tunnel for which to create the KX ctx.
899 create_kx_ctx (struct CadetTunnel *t)
901 LOG (GNUNET_ERROR_TYPE_INFO, " new kx ctx for %s\n", GCT_2s (t));
903 if (NULL != t->kx_ctx)
905 if (GNUNET_SCHEDULER_NO_TASK != t->kx_ctx->finish_task)
907 LOG (GNUNET_ERROR_TYPE_INFO, " resetting exisiting finish task\n");
908 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
909 t->kx_ctx->finish_task = GNUNET_SCHEDULER_NO_TASK;
914 t->kx_ctx = GNUNET_new (struct CadetTunnelKXCtx);
915 t->kx_ctx->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
919 if (CADET_TUNNEL_KEY_OK == t->estate)
921 LOG (GNUNET_ERROR_TYPE_INFO, " backing up keys\n");
922 t->kx_ctx->d_key_old = t->d_key;
923 t->kx_ctx->e_key_old = t->e_key;
925 t->kx_ctx->rekey_start_time = GNUNET_TIME_absolute_get ();
931 * @brief Finish the Key eXchange and destroy the old keys.
933 * @param cls Closure (Tunnel for which to finish the KX).
934 * @param tc Task context.
937 finish_kx (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
939 struct CadetTunnel *t = cls;
941 LOG (GNUNET_ERROR_TYPE_INFO, "finish KX for %s\n", GCT_2s (t));
943 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
945 LOG (GNUNET_ERROR_TYPE_INFO, " shutdown\n");
949 GNUNET_free (t->kx_ctx);
955 * Destroy a Key eXchange context for the tunnel. This function only schedules
956 * the destruction, the freeing of the memory (and clearing of old key material)
957 * happens after a delay!
959 * @param t Tunnel whose KX ctx to destroy.
962 destroy_kx_ctx (struct CadetTunnel *t)
964 struct GNUNET_TIME_Relative delay;
966 if (NULL == t->kx_ctx || GNUNET_SCHEDULER_NO_TASK != t->kx_ctx->finish_task)
969 if (is_key_null (&t->kx_ctx->e_key_old))
971 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_now (finish_kx, t);
975 delay = GNUNET_TIME_relative_divide (rekey_period, 4);
976 delay = GNUNET_TIME_relative_min (delay, GNUNET_TIME_UNIT_MINUTES);
978 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_delayed (delay, finish_kx, t);
984 * Pick a connection on which send the next data message.
986 * @param t Tunnel on which to send the message.
988 * @return The connection on which to send the next message.
990 static struct CadetConnection *
991 tunnel_get_connection (struct CadetTunnel *t)
993 struct CadetTConnection *iter;
994 struct CadetConnection *best;
996 unsigned int lowest_q;
998 LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GCT_2s (t));
1000 lowest_q = UINT_MAX;
1001 for (iter = t->connection_head; NULL != iter; iter = iter->next)
1003 LOG (GNUNET_ERROR_TYPE_DEBUG, " connection %s: %u\n",
1004 GCC_2s (iter->c), GCC_get_state (iter->c));
1005 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
1007 qn = GCC_get_qn (iter->c, GCC_is_origin (iter->c, GNUNET_YES));
1008 LOG (GNUNET_ERROR_TYPE_DEBUG, " q_n %u, \n", qn);
1016 LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GCC_2s (best));
1022 * Callback called when a queued message is sent.
1024 * Calculates the average time and connection packet tracking.
1026 * @param cls Closure (TunnelQueue handle).
1027 * @param c Connection this message was on.
1028 * @param q Connection queue handle (unused).
1029 * @param type Type of message sent.
1030 * @param fwd Was this a FWD going message?
1031 * @param size Size of the message.
1034 tun_message_sent (void *cls,
1035 struct CadetConnection *c,
1036 struct CadetConnectionQueue *q,
1037 uint16_t type, int fwd, size_t size)
1039 struct CadetTunnelQueue *qt = cls;
1040 struct CadetTunnel *t;
1042 LOG (GNUNET_ERROR_TYPE_DEBUG, "tun_message_sent\n");
1044 GNUNET_assert (NULL != qt->cont);
1045 t = NULL == c ? NULL : GCC_get_tunnel (c);
1046 qt->cont (qt->cont_cls, t, qt, type, size);
1052 count_queued_data (const struct CadetTunnel *t)
1054 struct CadetTunnelDelayed *iter;
1057 for (count = 0, iter = t->tq_head; iter != NULL; iter = iter->next)
1064 * Delete a queued message: either was sent or the channel was destroyed
1065 * before the tunnel's key exchange had a chance to finish.
1067 * @param tqd Delayed queue handle.
1070 unqueue_data (struct CadetTunnelDelayed *tqd)
1072 GNUNET_CONTAINER_DLL_remove (tqd->t->tq_head, tqd->t->tq_tail, tqd);
1078 * Cache a message to be sent once tunnel is online.
1080 * @param t Tunnel to hold the message.
1081 * @param msg Message itself (copy will be made).
1083 static struct CadetTunnelDelayed *
1084 queue_data (struct CadetTunnel *t, const struct GNUNET_MessageHeader *msg)
1086 struct CadetTunnelDelayed *tqd;
1087 uint16_t size = ntohs (msg->size);
1089 LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GCT_2s (t));
1091 if (GNUNET_YES == is_ready (t))
1097 tqd = GNUNET_malloc (sizeof (struct CadetTunnelDelayed) + size);
1100 memcpy (&tqd[1], msg, size);
1101 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
1107 * Sends an already built message on a tunnel, encrypting it and
1108 * choosing the best connection.
1110 * @param message Message to send. Function modifies it.
1111 * @param t Tunnel on which this message is transmitted.
1112 * @param c Connection to use (autoselect if NULL).
1113 * @param force Force the tunnel to take the message (buffer overfill).
1114 * @param cont Continuation to call once message is really sent.
1115 * @param cont_cls Closure for @c cont.
1116 * @param existing_q In case this a transmission of previously queued data,
1117 * this should be TunnelQueue given to the client.
1120 * @return Handle to cancel message.
1121 * NULL if @c cont is NULL or an error happens and message is dropped.
1123 static struct CadetTunnelQueue *
1124 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1125 struct CadetTunnel *t, struct CadetConnection *c,
1126 int force, GCT_sent cont, void *cont_cls,
1127 struct CadetTunnelQueue *existing_q)
1129 struct CadetTunnelQueue *tq;
1130 struct GNUNET_CADET_Encrypted *msg;
1131 size_t size = ntohs (message->size);
1132 char cbuf[sizeof (struct GNUNET_CADET_Encrypted) + size];
1138 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GCT_2s (t));
1140 if (GNUNET_NO == is_ready (t))
1142 struct CadetTunnelDelayed *tqd;
1143 /* A non null existing_q indicates sending of queued data.
1144 * Should only happen after tunnel becomes ready.
1146 GNUNET_assert (NULL == existing_q);
1147 tqd = queue_data (t, message);
1150 tq = GNUNET_new (struct CadetTunnelQueue);
1154 tq->cont_cls = cont_cls;
1158 GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1160 iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1161 msg = (struct GNUNET_CADET_Encrypted *) cbuf;
1162 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
1164 GNUNET_assert (t_encrypt (t, &msg[1], message, size, iv, GNUNET_NO) == size);
1165 t_hmac (&msg[1], size, iv, select_key (t), &msg->hmac);
1166 msg->header.size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
1169 c = tunnel_get_connection (t);
1172 /* Why is tunnel 'ready'? Should have been queued! */
1173 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
1176 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1178 return NULL; /* Drop... */
1182 type = ntohs (message->type);
1185 case GNUNET_MESSAGE_TYPE_CADET_DATA:
1186 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1187 if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
1188 mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
1190 mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
1192 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1193 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1194 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1195 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1196 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1197 msg->cid = *GCC_get_id (c);
1198 msg->ttl = htonl (default_ttl);
1202 LOG (GNUNET_ERROR_TYPE_ERROR, "type %s not valid\n", GC_m2s (type));
1204 LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
1206 fwd = GCC_is_origin (c, GNUNET_YES);
1210 GNUNET_break (NULL == GCC_send_prebuilt_message (&msg->header, type, mid, c,
1211 fwd, force, NULL, NULL));
1214 if (NULL == existing_q)
1216 tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
1223 tq->cq = GCC_send_prebuilt_message (&msg->header, type, mid, c, fwd, force,
1224 &tun_message_sent, tq);
1225 GNUNET_assert (NULL != tq->cq);
1227 tq->cont_cls = cont_cls;
1234 * Send all cached messages that we can, tunnel is online.
1236 * @param t Tunnel that holds the messages. Cannot be loopback.
1239 send_queued_data (struct CadetTunnel *t)
1241 struct CadetTunnelDelayed *tqd;
1242 struct CadetTunnelDelayed *next;
1245 LOG (GNUNET_ERROR_TYPE_INFO, "Send queued data, tunnel %s\n", GCT_2s (t));
1247 if (GCT_is_loopback (t))
1253 if (GNUNET_NO == is_ready (t))
1255 LOG (GNUNET_ERROR_TYPE_DEBUG, " not ready yet: %s/%s\n",
1256 estate2s (t->estate), cstate2s (t->cstate));
1260 room = GCT_get_connections_buffer (t);
1261 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
1262 LOG (GNUNET_ERROR_TYPE_DEBUG, " tq head: %p\n", t->tq_head);
1263 for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
1265 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
1268 send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
1269 tqd->t, NULL, GNUNET_YES,
1270 NULL != tqd->tq ? tqd->tq->cont : NULL,
1271 NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
1275 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
1280 * Sends key exchange message on a tunnel, choosing the best connection.
1281 * Should not be called on loopback tunnels.
1283 * @param t Tunnel on which this message is transmitted.
1284 * @param message Message to send. Function modifies it.
1287 send_kx (struct CadetTunnel *t,
1288 const struct GNUNET_MessageHeader *message)
1290 struct CadetConnection *c;
1291 struct GNUNET_CADET_KX *msg;
1292 size_t size = ntohs (message->size);
1293 char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
1297 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
1299 /* Avoid loopback. */
1300 if (GCT_is_loopback (t))
1302 LOG (GNUNET_ERROR_TYPE_DEBUG, " loopback!\n");
1306 type = ntohs (message->type);
1308 /* Even if tunnel is being destroyed, send anyway.
1309 * Could be a response to a rekey initiated by remote peer,
1310 * who is trying to create a new channel!
1313 /* Must have a connection, or be looking for one. */
1314 if (NULL == t->connection_head)
1316 if (CADET_TUNNEL_SEARCHING != t->cstate)
1318 LOG (GNUNET_ERROR_TYPE_ERROR, "\n\n\n");
1320 LOG (GNUNET_ERROR_TYPE_ERROR, "no connection, sending %s\n", GC_m2s (type));
1321 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
1322 GCP_debug (t->peer, GNUNET_ERROR_TYPE_ERROR);
1323 LOG (GNUNET_ERROR_TYPE_ERROR, "\n\n\n");
1328 msg = (struct GNUNET_CADET_KX *) cbuf;
1329 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
1330 msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
1331 c = tunnel_get_connection (t);
1334 if (GNUNET_SCHEDULER_NO_TASK == t->destroy_task
1335 && CADET_TUNNEL_READY == t->cstate)
1338 GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
1344 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
1345 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
1346 memcpy (&msg[1], message, size);
1350 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
1355 fwd = GCC_is_origin (t->connection_head->c, GNUNET_YES);
1356 /* TODO save handle and cancel in case of a unneeded retransmission */
1357 GNUNET_assert (NULL == GCC_send_prebuilt_message (&msg->header, type, 0, c,
1364 * Send the ephemeral key on a tunnel.
1366 * @param t Tunnel on which to send the key.
1369 send_ephemeral (struct CadetTunnel *t)
1371 LOG (GNUNET_ERROR_TYPE_INFO, "===> EPHM for %s\n", GCT_2s (t));
1373 kx_msg.sender_status = htonl (t->estate);
1374 kx_msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1375 kx_msg.nonce = t->kx_ctx->challenge;
1376 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce c %u\n", kx_msg.nonce);
1377 t_encrypt (t, &kx_msg.nonce, &kx_msg.nonce,
1378 ping_encryption_size(), kx_msg.iv, GNUNET_YES);
1379 LOG (GNUNET_ERROR_TYPE_DEBUG, " send nonce e %u\n", kx_msg.nonce);
1380 send_kx (t, &kx_msg.header);
1385 * Send a pong message on a tunnel.
1387 * @param t Tunnel on which to send the pong.
1388 * @param challenge Value sent in the ping that we have to send back.
1391 send_pong (struct CadetTunnel *t, uint32_t challenge)
1393 struct GNUNET_CADET_KX_Pong msg;
1395 LOG (GNUNET_ERROR_TYPE_INFO, "===> PONG for %s\n", GCT_2s (t));
1396 msg.header.size = htons (sizeof (msg));
1397 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
1398 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1399 msg.nonce = challenge;
1400 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
1401 t_encrypt (t, &msg.nonce, &msg.nonce,
1402 sizeof (msg.nonce), msg.iv, GNUNET_YES);
1403 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
1405 send_kx (t, &msg.header);
1410 * Initiate a rekey with the remote peer.
1412 * @param cls Closure (tunnel).
1413 * @param tc TaskContext.
1416 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1418 struct CadetTunnel *t = cls;
1420 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1422 LOG (GNUNET_ERROR_TYPE_INFO, "Re-key Tunnel %s\n", GCT_2s (t));
1423 if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1426 GNUNET_assert (NULL != t->kx_ctx);
1427 struct GNUNET_TIME_Relative duration;
1429 duration = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
1430 LOG (GNUNET_ERROR_TYPE_DEBUG, " kx started %s ago\n",
1431 GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
1433 // FIXME make duration of old keys configurable
1434 if (duration.rel_value_us >= GNUNET_TIME_UNIT_MINUTES.rel_value_us)
1436 LOG (GNUNET_ERROR_TYPE_DEBUG, " deleting old keys\n");
1437 memset (&t->kx_ctx->d_key_old, 0, sizeof (t->kx_ctx->d_key_old));
1438 memset (&t->kx_ctx->e_key_old, 0, sizeof (t->kx_ctx->e_key_old));
1445 case CADET_TUNNEL_KEY_UNINITIALIZED:
1446 GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
1449 case CADET_TUNNEL_KEY_SENT:
1452 case CADET_TUNNEL_KEY_OK:
1453 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
1456 case CADET_TUNNEL_KEY_PING:
1457 case CADET_TUNNEL_KEY_REKEY:
1461 LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
1464 // FIXME exponential backoff
1465 struct GNUNET_TIME_Relative delay;
1467 delay = GNUNET_TIME_relative_divide (rekey_period, 16);
1468 delay = GNUNET_TIME_relative_min (delay, REKEY_WAIT);
1469 LOG (GNUNET_ERROR_TYPE_DEBUG, " next call in %s\n",
1470 GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
1471 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1476 * Our ephemeral key has changed, create new session key on all tunnels.
1478 * Each tunnel will start the Key Exchange with a random delay between
1479 * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
1480 * per second, on average.
1482 * @param cls Closure (size of the hashmap).
1483 * @param key Current public key.
1484 * @param value Value in the hash map (tunnel).
1486 * @return #GNUNET_YES, so we should continue to iterate,
1489 rekey_iterator (void *cls,
1490 const struct GNUNET_PeerIdentity *key,
1493 struct CadetTunnel *t = value;
1494 struct GNUNET_TIME_Relative delay;
1495 long n = (long) cls;
1498 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
1501 if (GNUNET_YES == GCT_is_loopback (t))
1504 r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
1505 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
1506 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1508 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
1515 * Create a new ephemeral key and key message, schedule next rekeying.
1517 * @param cls Closure (unused).
1518 * @param tc TaskContext.
1521 rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1523 struct GNUNET_TIME_Absolute time;
1526 rekey_task = GNUNET_SCHEDULER_NO_TASK;
1528 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1531 GNUNET_free_non_null (my_ephemeral_key);
1532 my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
1534 time = GNUNET_TIME_absolute_get ();
1535 kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
1536 time = GNUNET_TIME_absolute_add (time, rekey_period);
1537 time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
1538 kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
1539 GNUNET_CRYPTO_ecdhe_key_get_public (my_ephemeral_key, &kx_msg.ephemeral_key);
1540 LOG (GNUNET_ERROR_TYPE_INFO, "GLOBAL RE-KEY, NEW EPHM: %s\n",
1541 GNUNET_h2s ((struct GNUNET_HashCode *) &kx_msg.ephemeral_key));
1543 GNUNET_assert (GNUNET_OK ==
1544 GNUNET_CRYPTO_eddsa_sign (my_private_key,
1546 &kx_msg.signature));
1548 n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
1549 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
1551 rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period, &rekey, NULL);
1556 * Called only on shutdown, destroy every tunnel.
1558 * @param cls Closure (unused).
1559 * @param key Current public key.
1560 * @param value Value in the hash map (tunnel).
1562 * @return #GNUNET_YES, so we should continue to iterate,
1565 destroy_iterator (void *cls,
1566 const struct GNUNET_PeerIdentity *key,
1569 struct CadetTunnel *t = value;
1571 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
1578 * Notify remote peer that we don't know a channel he is talking about,
1579 * probably CHANNEL_DESTROY was missed.
1581 * @param t Tunnel on which to notify.
1582 * @param gid ID of the channel.
1585 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
1587 struct GNUNET_CADET_ChannelManage msg;
1589 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
1590 msg.header.size = htons (sizeof (msg));
1591 msg.chid = htonl (gid);
1593 LOG (GNUNET_ERROR_TYPE_DEBUG,
1594 "WARNING destroying unknown channel %u on tunnel %s\n",
1596 send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
1601 * Demultiplex data per channel and call appropriate channel handler.
1603 * @param t Tunnel on which the data came.
1604 * @param msg Data message.
1605 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1606 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1607 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1608 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1611 handle_data (struct CadetTunnel *t,
1612 const struct GNUNET_CADET_Data *msg,
1615 struct CadetChannel *ch;
1619 size = ntohs (msg->header.size);
1621 sizeof (struct GNUNET_CADET_Data) +
1622 sizeof (struct GNUNET_MessageHeader))
1627 LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
1628 GC_m2s (ntohs (msg[1].header.type)));
1631 ch = GCT_get_channel (t, ntohl (msg->chid));
1634 GNUNET_STATISTICS_update (stats, "# data on unknown channel",
1636 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
1638 send_channel_destroy (t, ntohl (msg->chid));
1642 GCCH_handle_data (ch, msg, fwd);
1647 * Demultiplex data ACKs per channel and update appropriate channel buffer info.
1649 * @param t Tunnel on which the DATA ACK came.
1650 * @param msg DATA ACK message.
1651 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1652 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1653 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1654 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1657 handle_data_ack (struct CadetTunnel *t,
1658 const struct GNUNET_CADET_DataACK *msg,
1661 struct CadetChannel *ch;
1665 size = ntohs (msg->header.size);
1666 if (size != sizeof (struct GNUNET_CADET_DataACK))
1673 ch = GCT_get_channel (t, ntohl (msg->chid));
1676 GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
1678 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1683 GCCH_handle_data_ack (ch, msg, fwd);
1688 * Handle channel create.
1690 * @param t Tunnel on which the data came.
1691 * @param msg Data message.
1694 handle_ch_create (struct CadetTunnel *t,
1695 const struct GNUNET_CADET_ChannelCreate *msg)
1697 struct CadetChannel *ch;
1701 size = ntohs (msg->header.size);
1702 if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
1709 ch = GCT_get_channel (t, ntohl (msg->chid));
1710 if (NULL != ch && ! GCT_is_loopback (t))
1712 /* Probably a retransmission, safe to ignore */
1713 LOG (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
1715 ch = GCCH_handle_create (t, msg);
1717 GCT_add_channel (t, ch);
1723 * Handle channel NACK: check correctness and call channel handler for NACKs.
1725 * @param t Tunnel on which the NACK came.
1726 * @param msg NACK message.
1729 handle_ch_nack (struct CadetTunnel *t,
1730 const struct GNUNET_CADET_ChannelManage *msg)
1732 struct CadetChannel *ch;
1736 size = ntohs (msg->header.size);
1737 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1744 ch = GCT_get_channel (t, ntohl (msg->chid));
1747 GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
1749 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1754 GCCH_handle_nack (ch);
1759 * Handle a CHANNEL ACK (SYNACK/ACK).
1761 * @param t Tunnel on which the CHANNEL ACK came.
1762 * @param msg CHANNEL ACK message.
1763 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1764 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1765 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1766 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1769 handle_ch_ack (struct CadetTunnel *t,
1770 const struct GNUNET_CADET_ChannelManage *msg,
1773 struct CadetChannel *ch;
1777 size = ntohs (msg->header.size);
1778 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1785 ch = GCT_get_channel (t, ntohl (msg->chid));
1788 GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
1790 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1795 GCCH_handle_ack (ch, msg, fwd);
1800 * Handle a channel destruction message.
1802 * @param t Tunnel on which the message came.
1803 * @param msg Channel destroy message.
1804 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1805 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1806 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1807 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1810 handle_ch_destroy (struct CadetTunnel *t,
1811 const struct GNUNET_CADET_ChannelManage *msg,
1814 struct CadetChannel *ch;
1818 size = ntohs (msg->header.size);
1819 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1826 ch = GCT_get_channel (t, ntohl (msg->chid));
1829 /* Probably a retransmission, safe to ignore */
1833 GCCH_handle_destroy (ch, msg, fwd);
1838 * The peer's ephemeral key has changed: update the symmetrical keys.
1840 * @param t Tunnel this message came on.
1841 * @param msg Key eXchange message.
1844 handle_ephemeral (struct CadetTunnel *t,
1845 const struct GNUNET_CADET_KX_Ephemeral *msg)
1847 LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
1849 if (GNUNET_OK != check_ephemeral (t, msg))
1851 GNUNET_break_op (0);
1856 * If the key is different from what we know, derive the new E/D keys.
1857 * Else destroy the rekey ctx (duplicate EPHM after successful KX).
1859 if (0 != memcmp (&t->peers_ephemeral_key, &msg->ephemeral_key,
1860 sizeof (msg->ephemeral_key)))
1862 #if DUMP_KEYS_TO_STDERR
1863 LOG (GNUNET_ERROR_TYPE_INFO, "OLD: %s\n",
1864 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
1865 LOG (GNUNET_ERROR_TYPE_INFO, "NEW: %s\n",
1866 GNUNET_h2s ((struct GNUNET_HashCode *) &msg->ephemeral_key));
1868 t->peers_ephemeral_key = msg->ephemeral_key;
1872 if (CADET_TUNNEL_KEY_OK == t->estate)
1874 GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
1876 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
1877 GNUNET_SCHEDULER_cancel (t->rekey_task);
1878 t->rekey_task = GNUNET_SCHEDULER_add_now (rekey_tunnel, t);
1880 if (CADET_TUNNEL_KEY_SENT == t->estate)
1882 LOG (GNUNET_ERROR_TYPE_DEBUG, " our key was sent, sending challenge\n");
1884 GCT_change_estate (t, CADET_TUNNEL_KEY_PING);
1887 if (CADET_TUNNEL_KEY_UNINITIALIZED != ntohl(msg->sender_status))
1891 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce e %u\n", msg->nonce);
1892 t_decrypt (t, &nonce, &msg->nonce, ping_encryption_size (), msg->iv);
1893 LOG (GNUNET_ERROR_TYPE_DEBUG, " recv nonce c %u\n", nonce);
1894 send_pong (t, nonce);
1900 * Peer has answer to our challenge.
1901 * If answer is successful, consider the key exchange finished and clean
1902 * up all related state.
1904 * @param t Tunnel this message came on.
1905 * @param msg Key eXchange Pong message.
1908 handle_pong (struct CadetTunnel *t,
1909 const struct GNUNET_CADET_KX_Pong *msg)
1913 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
1914 if (GNUNET_SCHEDULER_NO_TASK == t->rekey_task)
1916 GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
1919 if (NULL == t->kx_ctx)
1921 GNUNET_STATISTICS_update (stats, "# stray PONG messages", 1, GNUNET_NO);
1925 t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
1926 if (challenge != t->kx_ctx->challenge)
1928 LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
1929 LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
1930 challenge, msg->nonce, t->kx_ctx->challenge);
1934 GNUNET_SCHEDULER_cancel (t->rekey_task);
1935 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1937 /* Don't free the old keys right away, but after a delay.
1938 * Rationale: the KX could have happened over a very fast connection,
1939 * with payload traffic still signed with the old key stuck in a slower
1941 * Don't keep the keys longer than 1/4 the rekey period, and no longer than
1945 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
1950 * Demultiplex by message type and call appropriate handler for a message
1951 * towards a channel of a local tunnel.
1953 * @param t Tunnel this message came on.
1954 * @param msgh Message header.
1955 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1956 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1957 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1958 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1961 handle_decrypted (struct CadetTunnel *t,
1962 const struct GNUNET_MessageHeader *msgh,
1967 type = ntohs (msgh->type);
1968 LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
1972 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1973 /* Do nothing, connection aleady got updated. */
1974 GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
1977 case GNUNET_MESSAGE_TYPE_CADET_DATA:
1978 /* Don't send hop ACK, wait for client to ACK */
1979 handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
1982 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1983 handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
1986 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1987 handle_ch_create (t,
1988 (struct GNUNET_CADET_ChannelCreate *) msgh);
1991 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1993 (struct GNUNET_CADET_ChannelManage *) msgh);
1996 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1998 (struct GNUNET_CADET_ChannelManage *) msgh,
2002 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
2003 handle_ch_destroy (t,
2004 (struct GNUNET_CADET_ChannelManage *) msgh,
2009 GNUNET_break_op (0);
2010 LOG (GNUNET_ERROR_TYPE_WARNING,
2011 "end-to-end message not known (%u)\n",
2012 ntohs (msgh->type));
2013 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
2017 /******************************************************************************/
2018 /******************************** API ***********************************/
2019 /******************************************************************************/
2022 * Decrypt and demultiplex by message type. Call appropriate handler
2023 * for every message.
2025 * @param t Tunnel this message came on.
2026 * @param msg Encrypted message.
2029 GCT_handle_encrypted (struct CadetTunnel *t,
2030 const struct GNUNET_CADET_Encrypted *msg)
2032 size_t size = ntohs (msg->header.size);
2033 size_t payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
2035 char cbuf [payload_size];
2036 struct GNUNET_MessageHeader *msgh;
2039 decrypted_size = t_decrypt_and_validate (t, cbuf, &msg[1], payload_size,
2040 msg->iv, &msg->hmac);
2042 if (-1 == decrypted_size)
2044 GNUNET_break_op (0);
2049 while (off < decrypted_size)
2053 msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
2054 msize = ntohs (msgh->size);
2055 if (msize < sizeof (struct GNUNET_MessageHeader))
2057 GNUNET_break_op (0);
2060 handle_decrypted (t, msgh, GNUNET_SYSERR);
2067 * Demultiplex an encapsulated KX message by message type.
2069 * @param t Tunnel on which the message came.
2070 * @param message Payload of KX message.
2073 GCT_handle_kx (struct CadetTunnel *t,
2074 const struct GNUNET_MessageHeader *message)
2078 type = ntohs (message->type);
2079 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received\n", type);
2082 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
2083 handle_ephemeral (t, (struct GNUNET_CADET_KX_Ephemeral *) message);
2086 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
2087 handle_pong (t, (struct GNUNET_CADET_KX_Pong *) message);
2091 GNUNET_break_op (0);
2092 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message not known (%u)\n", type);
2098 * Initialize the tunnel subsystem.
2100 * @param c Configuration handle.
2101 * @param key ECC private key, to derive all other keys and do crypto.
2104 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
2105 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
2107 int expected_overhead;
2109 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
2112 sizeof (struct GNUNET_CADET_Encrypted) + sizeof (struct GNUNET_CADET_Data);
2113 GNUNET_assert (GNUNET_CONSTANTS_CADET_P2P_OVERHEAD == expected_overhead);
2116 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
2119 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
2120 "CADET", "DEFAULT_TTL", "USING DEFAULT");
2124 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
2127 rekey_period = GNUNET_TIME_UNIT_DAYS;
2130 my_private_key = key;
2131 kx_msg.header.size = htons (sizeof (kx_msg));
2132 kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
2133 kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
2134 kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
2135 kx_msg.origin_identity = my_full_id;
2136 rekey_task = GNUNET_SCHEDULER_add_now (&rekey, NULL);
2138 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
2143 * Shut down the tunnel subsystem.
2148 if (GNUNET_SCHEDULER_NO_TASK != rekey_task)
2150 GNUNET_SCHEDULER_cancel (rekey_task);
2151 rekey_task = GNUNET_SCHEDULER_NO_TASK;
2153 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
2154 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
2161 * @param destination Peer this tunnel is towards.
2163 struct CadetTunnel *
2164 GCT_new (struct CadetPeer *destination)
2166 struct CadetTunnel *t;
2168 t = GNUNET_new (struct CadetTunnel);
2170 t->peer = destination;
2173 GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
2174 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2185 * Change the tunnel's connection state.
2187 * @param t Tunnel whose connection state to change.
2188 * @param cstate New connection state.
2191 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
2195 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
2196 GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
2197 if (myid != GCP_get_short_id (t->peer) &&
2198 CADET_TUNNEL_READY != t->cstate &&
2199 CADET_TUNNEL_READY == cstate)
2202 if (CADET_TUNNEL_KEY_OK == t->estate)
2204 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered send queued data\n");
2205 send_queued_data (t);
2207 else if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
2209 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered rekey\n");
2210 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
2211 GNUNET_SCHEDULER_cancel (t->rekey_task);
2213 rekey_tunnel (t, NULL);
2218 if (CADET_TUNNEL_READY == cstate
2219 && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
2221 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered stop dht\n");
2222 GCP_stop_search (t->peer);
2228 * Change the tunnel encryption state.
2230 * @param t Tunnel whose encryption state to change, or NULL.
2231 * @param state New encryption state.
2234 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
2236 enum CadetTunnelEState old;
2243 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate was %s\n",
2244 GCP_2s (t->peer), estate2s (old));
2245 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate is now %s\n",
2246 GCP_2s (t->peer), estate2s (t->estate));
2248 /* Send queued data if enc state changes to OK */
2249 if (myid != GCP_get_short_id (t->peer) &&
2250 CADET_TUNNEL_KEY_OK != old && CADET_TUNNEL_KEY_OK == t->estate)
2252 send_queued_data (t);
2258 * @brief Check if tunnel has too many connections, and remove one if necessary.
2260 * Currently this means the newest connection, unless it is a direct one.
2261 * Implemented as a task to avoid freeing a connection that is in the middle
2262 * of being created/processed.
2264 * @param cls Closure (Tunnel to check).
2265 * @param tc Task context.
2268 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2270 struct CadetTunnel *t = cls;
2272 t->trim_connections_task = GNUNET_SCHEDULER_NO_TASK;
2274 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2277 if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
2279 struct CadetTConnection *iter;
2280 struct CadetTConnection *c;
2282 for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
2284 if ((iter->created.abs_value_us > c->created.abs_value_us)
2285 && GNUNET_NO == GCC_is_direct (iter->c))
2292 LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
2294 LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
2307 * Add a connection to a tunnel.
2310 * @param c Connection.
2313 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
2315 struct CadetTConnection *aux;
2317 GNUNET_assert (NULL != c);
2319 LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
2320 LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
2321 for (aux = t->connection_head; aux != NULL; aux = aux->next)
2325 aux = GNUNET_new (struct CadetTConnection);
2327 aux->created = GNUNET_TIME_absolute_get ();
2329 GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
2331 if (CADET_TUNNEL_SEARCHING == t->cstate)
2332 GCT_change_estate (t, CADET_TUNNEL_WAITING);
2334 if (GNUNET_SCHEDULER_NO_TASK != t->trim_connections_task)
2335 t->trim_connections_task = GNUNET_SCHEDULER_add_now (&trim_connections, t);
2340 * Remove a connection from a tunnel.
2343 * @param c Connection.
2346 GCT_remove_connection (struct CadetTunnel *t,
2347 struct CadetConnection *c)
2349 struct CadetTConnection *aux;
2350 struct CadetTConnection *next;
2353 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
2354 GCC_2s (c), GCT_2s (t));
2355 for (aux = t->connection_head; aux != NULL; aux = next)
2360 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
2365 conns = GCT_count_connections (t);
2367 && GNUNET_SCHEDULER_NO_TASK == t->destroy_task
2368 && CADET_TUNNEL_SHUTDOWN != t->cstate
2369 && GNUNET_NO == shutting_down)
2371 if (0 == GCT_count_any_connections (t))
2372 GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
2374 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
2377 /* Start new connections if needed */
2378 if (CONNECTIONS_PER_TUNNEL > conns
2379 && GNUNET_SCHEDULER_NO_TASK == t->destroy_task
2380 && CADET_TUNNEL_SHUTDOWN != t->cstate
2381 && GNUNET_NO == shutting_down)
2383 LOG (GNUNET_ERROR_TYPE_DEBUG, " too few connections, getting new ones\n");
2384 GCP_connect (t->peer); /* Will change cstate to WAITING when possible */
2388 /* If not marked as ready, no change is needed */
2389 if (CADET_TUNNEL_READY != t->cstate)
2392 /* Check if any connection is ready to maintain cstate */
2393 for (aux = t->connection_head; aux != NULL; aux = aux->next)
2394 if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
2400 * Add a channel to a tunnel.
2403 * @param ch Channel.
2406 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2408 struct CadetTChannel *aux;
2410 GNUNET_assert (NULL != ch);
2412 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
2414 for (aux = t->channel_head; aux != NULL; aux = aux->next)
2416 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
2421 aux = GNUNET_new (struct CadetTChannel);
2423 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
2424 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
2426 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2428 GNUNET_SCHEDULER_cancel (t->destroy_task);
2429 t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2430 LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
2436 * Remove a channel from a tunnel.
2439 * @param ch Channel.
2442 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2444 struct CadetTChannel *aux;
2446 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
2447 for (aux = t->channel_head; aux != NULL; aux = aux->next)
2451 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
2452 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
2461 * Search for a channel by global ID.
2463 * @param t Tunnel containing the channel.
2464 * @param chid Public channel number.
2466 * @return channel handler, NULL if doesn't exist
2468 struct CadetChannel *
2469 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
2471 struct CadetTChannel *iter;
2476 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2478 if (GCCH_get_id (iter->ch) == chid)
2482 return NULL == iter ? NULL : iter->ch;
2487 * @brief Destroy a tunnel and free all resources.
2489 * Should only be called a while after the tunnel has been marked as destroyed,
2490 * in case there is a new channel added to the same peer shortly after marking
2491 * the tunnel. This way we avoid a new public key handshake.
2493 * @param cls Closure (tunnel to destroy).
2494 * @param tc Task context.
2497 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2499 struct CadetTunnel *t = cls;
2500 struct CadetTConnection *iter;
2502 LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
2503 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2505 LOG (GNUNET_ERROR_TYPE_WARNING,
2506 "Not destroying tunnel, due to shutdown. "
2507 "Tunnel at %p should have been freed by GCT_shutdown\n", t);
2510 t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2511 t->cstate = CADET_TUNNEL_SHUTDOWN;
2513 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2515 GCC_send_destroy (iter->c);
2522 * Tunnel is empty: destroy it.
2524 * Notifies all connections about the destruction.
2526 * @param t Tunnel to destroy.
2529 GCT_destroy_empty (struct CadetTunnel *t)
2531 if (GNUNET_YES == shutting_down)
2532 return; /* Will be destroyed immediately anyway */
2534 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2536 LOG (GNUNET_ERROR_TYPE_WARNING,
2537 "Tunnel %s is already scheduled for destruction. Tunnel debug dump:\n",
2539 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
2541 /* should never happen, tunnel can only become empty once, and the
2542 * task identifier should be NO_TASK (cleaned when the tunnel was created
2543 * or became un-empty)
2548 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: destroying scheduled\n",
2551 // FIXME make delay a config option
2552 t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
2553 &delayed_destroy, t);
2554 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llX\n",
2555 t, t->destroy_task);
2560 * Destroy tunnel if empty (no more channels).
2562 * @param t Tunnel to destroy if empty.
2565 GCT_destroy_if_empty (struct CadetTunnel *t)
2567 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
2568 if (1 < GCT_count_channels (t))
2571 GCT_destroy_empty (t);
2576 * Destroy the tunnel.
2578 * This function does not generate any warning traffic to clients or peers.
2581 * Cancel messages belonging to this tunnel queued to neighbors.
2582 * Free any allocated resources linked to the tunnel.
2584 * @param t The tunnel to destroy.
2587 GCT_destroy (struct CadetTunnel *t)
2589 struct CadetTConnection *iter_c;
2590 struct CadetTConnection *next_c;
2591 struct CadetTChannel *iter_ch;
2592 struct CadetTChannel *next_ch;
2597 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
2599 GNUNET_break (GNUNET_YES ==
2600 GNUNET_CONTAINER_multipeermap_remove (tunnels,
2601 GCP_get_id (t->peer), t));
2603 for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
2605 next_c = iter_c->next;
2606 GCC_destroy (iter_c->c);
2608 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
2610 next_ch = iter_ch->next;
2611 GCCH_destroy (iter_ch->ch);
2612 /* Should only happen on shutdown, but it's ok. */
2615 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2617 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling dest: %llX\n", t->destroy_task);
2618 GNUNET_SCHEDULER_cancel (t->destroy_task);
2619 t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2622 if (GNUNET_SCHEDULER_NO_TASK != t->trim_connections_task)
2624 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling trim: %llX\n",
2625 t->trim_connections_task);
2626 GNUNET_SCHEDULER_cancel (t->trim_connections_task);
2627 t->trim_connections_task = GNUNET_SCHEDULER_NO_TASK;
2630 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
2631 GCP_set_tunnel (t->peer, NULL);
2633 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
2635 GNUNET_SCHEDULER_cancel (t->rekey_task);
2636 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
2638 if (NULL != t->kx_ctx)
2640 if (GNUNET_SCHEDULER_NO_TASK != t->kx_ctx->finish_task)
2641 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
2642 GNUNET_free (t->kx_ctx);
2649 * @brief Use the given path for the tunnel.
2650 * Update the next and prev hops (and RCs).
2651 * (Re)start the path refresh in case the tunnel is locally owned.
2653 * @param t Tunnel to update.
2654 * @param p Path to use.
2656 * @return Connection created.
2658 struct CadetConnection *
2659 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
2661 struct CadetConnection *c;
2662 struct GNUNET_CADET_Hash cid;
2663 unsigned int own_pos;
2665 if (NULL == t || NULL == p)
2671 if (CADET_TUNNEL_SHUTDOWN == t->cstate)
2677 for (own_pos = 0; own_pos < p->length; own_pos++)
2679 if (p->peers[own_pos] == myid)
2682 if (own_pos >= p->length)
2684 GNUNET_break_op (0);
2688 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
2689 c = GCC_new (&cid, t, p, own_pos);
2692 /* Path was flawed */
2695 GCT_add_connection (t, c);
2701 * Count all created connections of a tunnel. Not necessarily ready connections!
2703 * @param t Tunnel on which to count.
2705 * @return Number of connections created, either being established or ready.
2708 GCT_count_any_connections (struct CadetTunnel *t)
2710 struct CadetTConnection *iter;
2716 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2724 * Count established (ready) connections of a tunnel.
2726 * @param t Tunnel on which to count.
2728 * @return Number of connections.
2731 GCT_count_connections (struct CadetTunnel *t)
2733 struct CadetTConnection *iter;
2739 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2740 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
2748 * Count channels of a tunnel.
2750 * @param t Tunnel on which to count.
2752 * @return Number of channels.
2755 GCT_count_channels (struct CadetTunnel *t)
2757 struct CadetTChannel *iter;
2760 for (count = 0, iter = t->channel_head;
2762 iter = iter->next, count++) /* skip */;
2769 * Get the connectivity state of a tunnel.
2773 * @return Tunnel's connectivity state.
2775 enum CadetTunnelCState
2776 GCT_get_cstate (struct CadetTunnel *t)
2781 return (enum CadetTunnelCState) -1;
2788 * Get the encryption state of a tunnel.
2792 * @return Tunnel's encryption state.
2794 enum CadetTunnelEState
2795 GCT_get_estate (struct CadetTunnel *t)
2800 return (enum CadetTunnelEState) -1;
2806 * Get the maximum buffer space for a tunnel towards a local client.
2810 * @return Biggest buffer space offered by any channel in the tunnel.
2813 GCT_get_channels_buffer (struct CadetTunnel *t)
2815 struct CadetTChannel *iter;
2816 unsigned int buffer;
2817 unsigned int ch_buf;
2819 if (NULL == t->channel_head)
2821 /* Probably getting buffer for a channel create/handshake. */
2822 LOG (GNUNET_ERROR_TYPE_DEBUG, " no channels, allow max\n");
2827 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2829 ch_buf = get_channel_buffer (iter);
2830 if (ch_buf > buffer)
2838 * Get the total buffer space for a tunnel for P2P traffic.
2842 * @return Buffer space offered by all connections in the tunnel.
2845 GCT_get_connections_buffer (struct CadetTunnel *t)
2847 struct CadetTConnection *iter;
2848 unsigned int buffer;
2850 if (GNUNET_NO == is_ready (t))
2852 if (count_queued_data (t) > 3)
2859 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2861 if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
2865 buffer += get_connection_buffer (iter);
2873 * Get the tunnel's destination.
2877 * @return ID of the destination peer.
2879 const struct GNUNET_PeerIdentity *
2880 GCT_get_destination (struct CadetTunnel *t)
2882 return GCP_get_id (t->peer);
2887 * Get the tunnel's next free global channel ID.
2891 * @return GID of a channel free to use.
2894 GCT_get_next_chid (struct CadetTunnel *t)
2896 CADET_ChannelNumber chid;
2897 CADET_ChannelNumber mask;
2900 /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
2901 * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
2902 * If peer's ID is bigger, start at 0x4... bit 30 = 1
2904 result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
2909 t->next_chid |= mask;
2911 while (NULL != GCT_get_channel (t, t->next_chid))
2913 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
2914 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
2915 t->next_chid |= mask;
2917 chid = t->next_chid;
2918 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
2919 t->next_chid |= mask;
2926 * Send ACK on one or more channels due to buffer in connections.
2928 * @param t Channel which has some free buffer space.
2931 GCT_unchoke_channels (struct CadetTunnel *t)
2933 struct CadetTChannel *iter;
2934 unsigned int buffer;
2935 unsigned int channels = GCT_count_channels (t);
2936 unsigned int choked_n;
2937 struct CadetChannel *choked[channels];
2939 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
2940 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
2941 if (NULL != t->channel_head)
2942 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
2944 /* Get buffer space */
2945 buffer = GCT_get_connections_buffer (t);
2951 /* Count and remember choked channels */
2953 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2955 if (GNUNET_NO == get_channel_allowed (iter))
2957 choked[choked_n++] = iter->ch;
2961 /* Unchoke random channels */
2962 while (0 < buffer && 0 < choked_n)
2964 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2966 GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
2969 choked[r] = choked[choked_n];
2975 * Send ACK on one or more connections due to buffer space to the client.
2977 * Iterates all connections of the tunnel and sends ACKs appropriately.
2982 GCT_send_connection_acks (struct CadetTunnel *t)
2984 struct CadetTConnection *iter;
2987 uint32_t allow_per_connection;
2989 unsigned int buffer;
2991 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
3000 if (CADET_TUNNEL_READY != t->cstate)
3003 buffer = GCT_get_channels_buffer (t);
3004 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer %u\n", buffer);
3006 /* Count connections, how many messages are already allowed */
3007 cs = GCT_count_connections (t);
3008 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3010 allowed += get_connection_allowed (iter);
3012 LOG (GNUNET_ERROR_TYPE_DEBUG, " allowed %u\n", allowed);
3014 /* Make sure there is no overflow */
3015 if (allowed > buffer)
3018 /* Authorize connections to send more data */
3019 to_allow = buffer - allowed;
3021 for (iter = t->connection_head;
3022 NULL != iter && to_allow > 0;
3025 if (CADET_CONNECTION_READY != GCC_get_state (iter->c)
3026 || get_connection_allowed (iter) > 64 / 3)
3030 allow_per_connection = to_allow/cs;
3031 to_allow -= allow_per_connection;
3033 GCC_allow (iter->c, allow_per_connection,
3034 GCC_is_origin (iter->c, GNUNET_NO));
3039 /* Since we don't allow if it's allowed to send 64/3, this can happen. */
3040 LOG (GNUNET_ERROR_TYPE_DEBUG, " reminding to_allow: %u\n", to_allow);
3046 * Cancel a previously sent message while it's in the queue.
3048 * ONLY can be called before the continuation given to the send function
3049 * is called. Once the continuation is called, the message is no longer in the
3052 * @param q Handle to the queue.
3055 GCT_cancel (struct CadetTunnelQueue *q)
3060 /* tun_message_sent() will be called and free q */
3062 else if (NULL != q->tqd)
3064 unqueue_data (q->tqd);
3066 if (NULL != q->cont)
3067 q->cont (q->cont_cls, NULL, q, 0, 0);
3078 * Sends an already built message on a tunnel, encrypting it and
3079 * choosing the best connection if not provided.
3081 * @param message Message to send. Function modifies it.
3082 * @param t Tunnel on which this message is transmitted.
3083 * @param c Connection to use (autoselect if NULL).
3084 * @param force Force the tunnel to take the message (buffer overfill).
3085 * @param cont Continuation to call once message is really sent.
3086 * @param cont_cls Closure for @c cont.
3088 * @return Handle to cancel message. NULL if @c cont is NULL.
3090 struct CadetTunnelQueue *
3091 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
3092 struct CadetTunnel *t, struct CadetConnection *c,
3093 int force, GCT_sent cont, void *cont_cls)
3095 return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
3099 * Sends an already built and encrypted message on a tunnel, choosing the best
3100 * connection. Useful for re-queueing messages queued on a destroyed connection.
3102 * @param message Message to send. Function modifies it.
3103 * @param t Tunnel on which this message is transmitted.
3106 GCT_resend_message (const struct GNUNET_MessageHeader *message,
3107 struct CadetTunnel *t)
3109 struct CadetConnection *c;
3112 c = tunnel_get_connection (t);
3115 /* TODO queue in tunnel, marked as encrypted */
3116 LOG (GNUNET_ERROR_TYPE_DEBUG, "No connection available, dropping.\n");
3119 fwd = GCC_is_origin (c, GNUNET_YES);
3120 GNUNET_break (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
3121 GNUNET_YES, NULL, NULL));
3126 * Is the tunnel directed towards the local peer?
3130 * @return #GNUNET_YES if it is loopback.
3133 GCT_is_loopback (const struct CadetTunnel *t)
3135 return (myid == GCP_get_short_id (t->peer));
3140 * Is the tunnel this path already?
3145 * @return #GNUNET_YES a connection uses this path.
3148 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
3150 struct CadetTConnection *iter;
3152 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3153 if (path_equivalent (GCC_get_path (iter->c), p))
3161 * Get a cost of a path for a tunnel considering existing connections.
3164 * @param path Candidate path.
3166 * @return Cost of the path (path length + number of overlapping nodes)
3169 GCT_get_path_cost (const struct CadetTunnel *t,
3170 const struct CadetPeerPath *path)
3172 struct CadetTConnection *iter;
3173 const struct CadetPeerPath *aux;
3174 unsigned int overlap;
3182 GNUNET_assert (NULL != t);
3184 for (i = 0; i < path->length; i++)
3186 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3188 aux = GCC_get_path (iter->c);
3192 for (j = 0; j < aux->length; j++)
3194 if (path->peers[i] == aux->peers[j])
3202 return path->length + overlap;
3207 * Get the static string for the peer this tunnel is directed.
3211 * @return Static string the destination peer's ID.
3214 GCT_2s (const struct CadetTunnel *t)
3219 return GCP_2s (t->peer);
3223 /******************************************************************************/
3224 /***************************** INFO/DEBUG *******************************/
3225 /******************************************************************************/
3228 * Log all possible info about the tunnel state.
3230 * @param t Tunnel to debug.
3231 * @param level Debug level to use.
3234 GCT_debug (const struct CadetTunnel *t, enum GNUNET_ErrorType level)
3236 struct CadetTChannel *iterch;
3237 struct CadetTConnection *iterc;
3240 do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
3242 __FILE__, __FUNCTION__, __LINE__);
3246 LOG2 (level, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
3247 LOG2 (level, "TTT cstate %s, estate %s\n",
3248 cstate2s (t->cstate), estate2s (t->estate));
3249 LOG2 (level, "TTT kx_ctx %p, rekey_task %u, finish task %u\n",
3250 t->kx_ctx, t->rekey_task, t->kx_ctx ? t->kx_ctx->finish_task : 0);
3251 #if DUMP_KEYS_TO_STDERR
3252 LOG2 (level, "TTT my EPHM\t %s\n",
3253 GNUNET_h2s ((struct GNUNET_HashCode *) &kx_msg.ephemeral_key));
3254 LOG2 (level, "TTT peers EPHM:\t %s\n",
3255 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
3256 LOG2 (level, "TTT ENC key:\t %s\n",
3257 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
3258 LOG2 (level, "TTT DEC key:\t %s\n",
3259 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
3262 LOG2 (level, "TTT OLD ENC key:\t %s\n",
3263 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->e_key_old));
3264 LOG2 (level, "TTT OLD DEC key:\t %s\n",
3265 GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->d_key_old));
3268 LOG2 (level, "TTT tq_head %p, tq_tail %p\n", t->tq_head, t->tq_tail);
3269 LOG2 (level, "TTT destroy %u\n", t->destroy_task);
3271 LOG2 (level, "TTT channels:\n");
3272 for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
3274 LOG2 (level, "TTT - %s\n", GCCH_2s (iterch->ch));
3277 LOG2 (level, "TTT connections:\n");
3278 for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
3280 GCC_debug (iterc->c, level);
3283 LOG2 (level, "TTT DEBUG TUNNEL END\n");
3288 * Iterate all tunnels.
3290 * @param iter Iterator.
3291 * @param cls Closure for @c iter.
3294 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
3296 GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
3301 * Count all tunnels.
3303 * @return Number of tunnels to remote peers kept by this peer.
3306 GCT_count_all (void)
3308 return GNUNET_CONTAINER_multipeermap_size (tunnels);
3313 * Iterate all connections of a tunnel.
3315 * @param t Tunnel whose connections to iterate.
3316 * @param iter Iterator.
3317 * @param cls Closure for @c iter.
3320 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
3322 struct CadetTConnection *ct;
3324 for (ct = t->connection_head; NULL != ct; ct = ct->next)
3330 * Iterate all channels of a tunnel.
3332 * @param t Tunnel whose channels to iterate.
3333 * @param iter Iterator.
3334 * @param cls Closure for @c iter.
3337 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
3339 struct CadetTChannel *cht;
3341 for (cht = t->channel_head; NULL != cht; cht = cht->next)
3342 iter (cls, cht->ch);