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__)
37 #define REKEY_WAIT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5)
39 #define CONNECTIONS_PER_TUNNEL 3
41 #if !defined(GNUNET_CULL_LOGGING)
42 #define DUMP_KEYS_TO_STDERR GNUNET_YES
44 #define DUMP_KEYS_TO_STDERR GNUNET_NO
47 /******************************************************************************/
48 /******************************** STRUCTS **********************************/
49 /******************************************************************************/
53 struct CadetTChannel *next;
54 struct CadetTChannel *prev;
55 struct CadetChannel *ch;
60 * Connection list and metadata.
62 struct CadetTConnection
67 struct CadetTConnection *next;
72 struct CadetTConnection *prev;
77 struct CadetConnection *c;
80 * Creation time, to keep oldest connection alive.
82 struct GNUNET_TIME_Absolute created;
85 * Connection throughput, to keep fastest connection alive.
91 * Structure used during a Key eXchange.
93 struct CadetTunnelKXCtx
96 * Encryption ("our") old "confirmed" key, for encrypting traffic sent by us
97 * end before the key exchange is finished or times out.
99 struct GNUNET_CRYPTO_SymmetricSessionKey e_key_old;
102 * Decryption ("their") old "confirmed" key, for decrypting traffic sent by
103 * the other end before the key exchange started.
105 struct GNUNET_CRYPTO_SymmetricSessionKey d_key_old;
108 * Challenge to send in a ping and expect in the pong.
113 * When the rekey started. One minute after this the new key will be used.
115 struct GNUNET_TIME_Absolute rekey_start_time;
118 * Task for delayed destruction of the Key eXchange context, to allow delayed
119 * messages with the old key to be decrypted successfully.
121 GNUNET_SCHEDULER_TaskIdentifier finish_task;
125 * Struct containing all information regarding a tunnel to a peer.
130 * Endpoint of the tunnel.
132 struct CadetPeer *peer;
135 * State of the tunnel connectivity.
137 enum CadetTunnelCState cstate;
140 * State of the tunnel encryption.
142 enum CadetTunnelEState estate;
145 * Key eXchange context.
147 struct CadetTunnelKXCtx *kx_ctx;
150 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own ephemeral
153 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
156 * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
158 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
161 * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
163 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
166 * Task to start the rekey process.
168 GNUNET_SCHEDULER_TaskIdentifier rekey_task;
171 * Paths that are actively used to reach the destination peer.
173 struct CadetTConnection *connection_head;
174 struct CadetTConnection *connection_tail;
177 * Next connection number.
182 * Channels inside this tunnel.
184 struct CadetTChannel *channel_head;
185 struct CadetTChannel *channel_tail;
188 * Channel ID for the next created channel.
190 CADET_ChannelNumber next_chid;
193 * Destroy flag: if true, destroy on last message.
195 GNUNET_SCHEDULER_TaskIdentifier destroy_task;
198 * Queued messages, to transmit once tunnel gets connected.
200 struct CadetTunnelDelayed *tq_head;
201 struct CadetTunnelDelayed *tq_tail;
206 * Struct used to save messages in a non-ready tunnel to send once connected.
208 struct CadetTunnelDelayed
213 struct CadetTunnelDelayed *next;
214 struct CadetTunnelDelayed *prev;
219 struct CadetTunnel *t;
222 * Tunnel queue given to the channel to cancel request. Update on send_queued.
224 struct CadetTunnelQueue *tq;
229 /* struct GNUNET_MessageHeader *msg; */
234 * Handle for messages queued but not yet sent.
236 struct CadetTunnelQueue
239 * Connection queue handle, to cancel if necessary.
241 struct CadetConnectionQueue *cq;
244 * Handle in case message hasn't been given to a connection yet.
246 struct CadetTunnelDelayed *tqd;
249 * Continuation to call once sent.
254 * Closure for @c cont.
260 /******************************************************************************/
261 /******************************* GLOBALS ***********************************/
262 /******************************************************************************/
265 * Global handle to the statistics service.
267 extern struct GNUNET_STATISTICS_Handle *stats;
270 * Local peer own ID (memory efficient handle).
272 extern GNUNET_PEER_Id myid;
275 * Local peer own ID (full value).
277 extern struct GNUNET_PeerIdentity my_full_id;
281 * Don't try to recover tunnels if shutting down.
283 extern int shutting_down;
287 * Set of all tunnels, in order to trigger a new exchange on rekey.
288 * Indexed by peer's ID.
290 static struct GNUNET_CONTAINER_MultiPeerMap *tunnels;
293 * Default TTL for payload packets.
295 static unsigned long long default_ttl;
300 const static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
303 * Own ephemeral private key.
305 static struct GNUNET_CRYPTO_EcdhePrivateKey *my_ephemeral_key;
308 * Cached message used to perform a key exchange.
310 static struct GNUNET_CADET_KX_Ephemeral kx_msg;
313 * Task to generate a new ephemeral key.
315 static GNUNET_SCHEDULER_TaskIdentifier rekey_task;
320 static struct GNUNET_TIME_Relative rekey_period;
322 /******************************************************************************/
323 /******************************** STATIC ***********************************/
324 /******************************************************************************/
327 * Get string description for tunnel connectivity state.
329 * @param cs Tunnel state.
331 * @return String representation.
334 cstate2s (enum CadetTunnelCState cs)
340 case CADET_TUNNEL_NEW:
341 return "CADET_TUNNEL_NEW";
342 case CADET_TUNNEL_SEARCHING:
343 return "CADET_TUNNEL_SEARCHING";
344 case CADET_TUNNEL_WAITING:
345 return "CADET_TUNNEL_WAITING";
346 case CADET_TUNNEL_READY:
347 return "CADET_TUNNEL_READY";
350 sprintf (buf, "%u (UNKNOWN STATE)", cs);
358 * Get string description for tunnel encryption state.
360 * @param es Tunnel state.
362 * @return String representation.
365 estate2s (enum CadetTunnelEState es)
371 case CADET_TUNNEL_KEY_UNINITIALIZED:
372 return "CADET_TUNNEL_KEY_UNINITIALIZED";
373 case CADET_TUNNEL_KEY_SENT:
374 return "CADET_TUNNEL_KEY_SENT";
375 case CADET_TUNNEL_KEY_PING:
376 return "CADET_TUNNEL_KEY_PING";
377 case CADET_TUNNEL_KEY_OK:
378 return "CADET_TUNNEL_KEY_OK";
379 case CADET_TUNNEL_KEY_REKEY:
380 return "CADET_TUNNEL_KEY_REKEY";
382 sprintf (buf, "%u (UNKNOWN STATE)", es);
390 * @brief Check if tunnel is ready to send traffic.
392 * Tunnel must be connected and with encryption correctly set up.
394 * @param t Tunnel to check.
396 * @return #GNUNET_YES if ready, #GNUNET_NO otherwise
399 is_ready (struct CadetTunnel *t)
403 GCT_debug (t, GNUNET_ERROR_TYPE_DEBUG);
404 ready = CADET_TUNNEL_READY == t->cstate
405 && (CADET_TUNNEL_KEY_OK == t->estate
406 || CADET_TUNNEL_KEY_REKEY == t->estate);
407 ready = ready || GCT_is_loopback (t);
413 * Ephemeral key message purpose size.
415 * @return Size of the part of the ephemeral key message that must be signed.
418 ephemeral_purpose_size (void)
420 return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
421 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
422 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
423 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
424 sizeof (struct GNUNET_PeerIdentity);
429 * Size of the encrypted part of a ping message.
431 * @return Size of the encrypted part of a ping message.
434 ping_encryption_size (void)
436 return sizeof (struct GNUNET_PeerIdentity) + sizeof (uint32_t);
441 * Get the channel's buffer. ONLY FOR NON-LOOPBACK CHANNELS!!
443 * @param tch Tunnel's channel handle.
445 * @return Amount of messages the channel can still buffer towards the client.
448 get_channel_buffer (const struct CadetTChannel *tch)
452 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
453 fwd = GCCH_is_origin (tch->ch, GNUNET_YES);
455 return GCCH_get_buffer (tch->ch, fwd);
460 * Get the channel's allowance status.
462 * @param tch Tunnel's channel handle.
464 * @return #GNUNET_YES if we allowed the client to send data to us.
467 get_channel_allowed (const struct CadetTChannel *tch)
471 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
472 fwd = GCCH_is_origin (tch->ch, GNUNET_YES);
474 return GCCH_get_allowed (tch->ch, fwd);
479 * Get the connection's buffer.
481 * @param tc Tunnel's connection handle.
483 * @return Amount of messages the connection can still buffer.
486 get_connection_buffer (const struct CadetTConnection *tc)
490 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
491 fwd = GCC_is_origin (tc->c, GNUNET_YES);
493 return GCC_get_buffer (tc->c, fwd);
498 * Get the connection's allowance.
500 * @param tc Tunnel's connection handle.
502 * @return Amount of messages we have allowed the next peer to send us.
505 get_connection_allowed (const struct CadetTConnection *tc)
509 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
510 fwd = GCC_is_origin (tc->c, GNUNET_YES);
512 return GCC_get_allowed (tc->c, fwd);
517 * Check that a ephemeral key message s well formed and correctly signed.
519 * @param t Tunnel on which the message came.
520 * @param msg The ephemeral key message.
522 * @return GNUNET_OK if message is fine, GNUNET_SYSERR otherwise.
525 check_ephemeral (struct CadetTunnel *t,
526 const struct GNUNET_CADET_KX_Ephemeral *msg)
528 /* Check message size */
529 if (ntohs (msg->header.size) != sizeof (struct GNUNET_CADET_KX_Ephemeral))
530 return GNUNET_SYSERR;
532 /* Check signature size */
533 if (ntohl (msg->purpose.size) != ephemeral_purpose_size ())
534 return GNUNET_SYSERR;
537 if (0 != memcmp (&msg->origin_identity,
538 GCP_get_id (t->peer),
539 sizeof (struct GNUNET_PeerIdentity)))
540 return GNUNET_SYSERR;
542 /* Check signature */
544 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_CADET_KX,
547 &msg->origin_identity.public_key))
548 return GNUNET_SYSERR;
555 * Select the best key to use for encryption (send), based on KX status.
557 * Normally, return the current key. If there is a KX in progress and the old
558 * key is fresh enough, return the old key.
560 * @param t Tunnel to choose the key from.
562 * @return The optimal key to encrypt/hmac outgoing traffic.
564 static const struct GNUNET_CRYPTO_SymmetricSessionKey *
565 select_key (const struct CadetTunnel *t)
567 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
569 if (NULL != t->kx_ctx
570 && GNUNET_SCHEDULER_NO_TASK == t->kx_ctx->finish_task)
572 struct GNUNET_TIME_Relative age;
574 age = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
575 LOG (GNUNET_ERROR_TYPE_DEBUG,
576 " key exchange in progress, started %s ago\n",
577 GNUNET_STRINGS_relative_time_to_string (age, GNUNET_YES));
578 // FIXME make duration of old keys configurable
579 if (age.rel_value_us < GNUNET_TIME_UNIT_MINUTES.rel_value_us)
581 LOG (GNUNET_ERROR_TYPE_DEBUG, " using old key\n");
582 key = &t->kx_ctx->e_key_old;
586 LOG (GNUNET_ERROR_TYPE_DEBUG, " using new key\n");
592 LOG (GNUNET_ERROR_TYPE_DEBUG, " no KX: using current key\n");
602 * @param plaintext Content to HMAC.
603 * @param size Size of @c plaintext.
604 * @param iv Initialization vector for the message.
605 * @param key Key to use.
606 * @param hmac[out] Destination to store the HMAC.
609 t_hmac (const void *plaintext, size_t size,
610 uint32_t iv, const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
611 struct GNUNET_CADET_Hash *hmac)
613 static const char ctx[] = "cadet authentication key";
614 struct GNUNET_CRYPTO_AuthKey auth_key;
615 struct GNUNET_HashCode hash;
617 #if DUMP_KEYS_TO_STDERR
618 LOG (GNUNET_ERROR_TYPE_INFO, " HMAC with key %s\n",
619 GNUNET_h2s ((struct GNUNET_HashCode *) key));
621 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
626 /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
627 GNUNET_CRYPTO_hmac (&auth_key, plaintext, size, &hash);
628 memcpy (hmac, &hash, sizeof (*hmac));
633 * Encrypt daforce_newest_keyta with the tunnel key.
635 * @param t Tunnel whose key to use.
636 * @param dst Destination for the encrypted data.
637 * @param src Source of the plaintext. Can overlap with @c dst.
638 * @param size Size of the plaintext.
639 * @param iv Initialization Vector to use.
640 * @param force_newest_key Force the use of the newest key, otherwise
641 * CADET will use the old key when allowed.
642 * This can happen in the case when a KX is going on
643 * and the old one hasn't expired.
646 t_encrypt (struct CadetTunnel *t, void *dst, const void *src,
647 size_t size, uint32_t iv, int force_newest_key)
649 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
650 const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
653 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt start\n");
655 key = GNUNET_YES == force_newest_key ? &t->e_key : select_key (t);
656 #if DUMP_KEYS_TO_STDERR
657 LOG (GNUNET_ERROR_TYPE_INFO, " ENC with key %s\n",
658 GNUNET_h2s ((struct GNUNET_HashCode *) key));
660 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
661 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt IV derived\n");
662 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, key, &siv, dst);
663 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt end\n");
670 * Decrypt and verify data with the appropriate tunnel key.
672 * @param key Key to use.
673 * @param dst Destination for the plaintext.
674 * @param src Source of the encrypted data. Can overlap with @c dst.
675 * @param size Size of the encrypted data.
676 * @param iv Initialization Vector to use.
678 * @return Size of the decrypted data, -1 if an error was encountered.
681 decrypt (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
682 void *dst, const void *src, size_t size, uint32_t iv)
684 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
687 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt start\n");
688 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv\n");
689 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
690 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv done\n");
691 out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, key, &siv, dst);
692 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt end\n");
699 * Decrypt and verify data with the most recent tunnel key.
701 * @param t Tunnel whose 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 t_decrypt (struct CadetTunnel *t, void *dst, const void *src,
711 size_t size, uint32_t iv)
715 #if DUMP_KEYS_TO_STDERR
716 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_decrypt with %s\n",
717 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
719 if (t->estate == CADET_TUNNEL_KEY_UNINITIALIZED)
721 GNUNET_STATISTICS_update (stats, "# non decryptable data", 1, GNUNET_NO);
722 LOG (GNUNET_ERROR_TYPE_WARNING,
723 "got data on %s without a valid key\n",
725 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
729 out_size = decrypt (&t->d_key, dst, src, size, iv);
736 * Decrypt and verify data with the appropriate tunnel key and verify that the
737 * data has not been altered since it was sent by the remote peer.
739 * @param t Tunnel whose key to use.
740 * @param dst Destination for the plaintext.
741 * @param src Source of the encrypted data. Can overlap with @c dst.
742 * @param size Size of the encrypted data.
743 * @param iv Initialization Vector to use.
744 * @param msg_hmac HMAC of the message, cannot be NULL.
746 * @return Size of the decrypted data, -1 if an error was encountered.
749 t_decrypt_and_validate (struct CadetTunnel *t,
750 void *dst, const void *src,
751 size_t size, uint32_t iv,
752 const struct GNUNET_CADET_Hash *msg_hmac)
754 struct GNUNET_CRYPTO_SymmetricSessionKey *key;
755 struct GNUNET_CADET_Hash hmac;
758 /* Try primary (newest) key */
760 decrypted_size = decrypt (key, dst, src, size, iv);
761 t_hmac (src, size, iv, key, &hmac);
762 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
763 return decrypted_size;
765 /* If no key exchange is going on, we just failed */
766 if (NULL == t->kx_ctx)
768 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
769 "Failed checksum validation on tunnel %s with no KX\n",
771 GNUNET_STATISTICS_update (stats, "# wrong HMAC", 1, GNUNET_NO);
775 /* Try secondary (from previous KX period) key */
776 key = &t->kx_ctx->d_key_old;
777 decrypted_size = decrypt (key, dst, src, size, iv);
778 t_hmac (src, size, iv, key, &hmac);
779 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
780 return decrypted_size;
782 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
783 "Failed checksum validation on tunnel %s with KX\n",
785 GNUNET_STATISTICS_update (stats, "# wrong HMAC", 1, GNUNET_NO);
791 * Create key material by doing ECDH on the local and remote ephemeral keys.
793 * @param key_material Where to store the key material.
794 * @param ephemeral_key Peer's public ephemeral key.
797 derive_key_material (struct GNUNET_HashCode *key_material,
798 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key)
801 GNUNET_CRYPTO_ecc_ecdh (my_ephemeral_key,
811 * Create a symmetic key from the identities of both ends and the key material
814 * @param key Destination for the generated key.
815 * @param sender ID of the peer that will encrypt with @c key.
816 * @param receiver ID of the peer that will decrypt with @c key.
817 * @param key_material Hash created with ECDH with the ephemeral keys.
820 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
821 const struct GNUNET_PeerIdentity *sender,
822 const struct GNUNET_PeerIdentity *receiver,
823 const struct GNUNET_HashCode *key_material)
825 const char salt[] = "CADET kx salt";
827 GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
829 key_material, sizeof (struct GNUNET_HashCode),
830 sender, sizeof (struct GNUNET_PeerIdentity),
831 receiver, sizeof (struct GNUNET_PeerIdentity),
837 * Create a new Key eXchange context for the tunnel.
839 * Initializes the key copies, KX start timestamp and creates a new nonce.
841 * @param t Tunnel for which to create the KX ctx.
844 create_kx_ctx (struct CadetTunnel *t)
846 if (NULL != t->kx_ctx)
848 if (GNUNET_SCHEDULER_NO_TASK != t->kx_ctx->finish_task)
850 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
851 t->kx_ctx->finish_task = GNUNET_SCHEDULER_NO_TASK;
856 LOG (GNUNET_ERROR_TYPE_INFO, " new kx ctx for %s\n", GCT_2s (t));
857 t->kx_ctx = GNUNET_new (struct CadetTunnelKXCtx);
858 t->kx_ctx->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
860 t->kx_ctx->d_key_old = t->d_key;
861 t->kx_ctx->e_key_old = t->e_key;
862 t->kx_ctx->rekey_start_time = GNUNET_TIME_absolute_get ();
867 * @brief Finish the Key eXchange and destroy the old keys.
869 * @param cls Closure (Tunnel for which to finish the KX).
870 * @param tc Task context.
873 finish_kx (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
875 struct CadetTunnel *t = cls;
877 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
880 LOG (GNUNET_ERROR_TYPE_INFO, "finish KX for %s\n", GCT_2s (t));
882 GNUNET_free (t->kx_ctx);
888 * Destroy a Key eXchane context for the tunnel. This function only schedules
889 * the destruction, the freeing of the memory (and clearing of old key material)
890 * happens after a delay!
892 * @param t Tunnel whose KX ctx to destroy.
895 destroy_kx_ctx (struct CadetTunnel *t)
897 struct GNUNET_TIME_Relative delay;
899 if (NULL == t->kx_ctx || GNUNET_SCHEDULER_NO_TASK != t->kx_ctx->finish_task)
902 delay = GNUNET_TIME_relative_divide (rekey_period, 4);
903 delay = GNUNET_TIME_relative_min (delay, GNUNET_TIME_UNIT_MINUTES);
905 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_delayed (delay, finish_kx, t);
910 * Derive the tunnel's keys using our own and the peer's ephemeral keys.
912 * @param t Tunnel for which to create the keys.
915 create_keys (struct CadetTunnel *t)
917 struct GNUNET_HashCode km;
919 derive_key_material (&km, &t->peers_ephemeral_key);
920 derive_symmertic (&t->e_key, &my_full_id, GCP_get_id (t->peer), &km);
921 derive_symmertic (&t->d_key, GCP_get_id (t->peer), &my_full_id, &km);
922 #if DUMP_KEYS_TO_STDERR
923 LOG (GNUNET_ERROR_TYPE_INFO, "ME: %s\n",
924 GNUNET_h2s ((struct GNUNET_HashCode *) &kx_msg.ephemeral_key));
925 LOG (GNUNET_ERROR_TYPE_INFO, "PE: %s\n",
926 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
927 LOG (GNUNET_ERROR_TYPE_INFO, "KM: %s\n", GNUNET_h2s (&km));
928 LOG (GNUNET_ERROR_TYPE_INFO, "EK: %s\n",
929 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
930 LOG (GNUNET_ERROR_TYPE_INFO, "DK: %s\n",
931 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
937 * Pick a connection on which send the next data message.
939 * @param t Tunnel on which to send the message.
941 * @return The connection on which to send the next message.
943 static struct CadetConnection *
944 tunnel_get_connection (struct CadetTunnel *t)
946 struct CadetTConnection *iter;
947 struct CadetConnection *best;
949 unsigned int lowest_q;
951 LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GCT_2s (t));
954 for (iter = t->connection_head; NULL != iter; iter = iter->next)
956 LOG (GNUNET_ERROR_TYPE_DEBUG, " connection %s: %u\n",
957 GCC_2s (iter->c), GCC_get_state (iter->c));
958 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
960 qn = GCC_get_qn (iter->c, GCC_is_origin (iter->c, GNUNET_YES));
961 LOG (GNUNET_ERROR_TYPE_DEBUG, " q_n %u, \n", qn);
969 LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GCC_2s (best));
975 * Callback called when a queued message is sent.
977 * Calculates the average time and connection packet tracking.
979 * @param cls Closure (TunnelQueue handle).
980 * @param c Connection this message was on.
981 * @param q Connection queue handle (unused).
982 * @param type Type of message sent.
983 * @param fwd Was this a FWD going message?
984 * @param size Size of the message.
987 tun_message_sent (void *cls,
988 struct CadetConnection *c,
989 struct CadetConnectionQueue *q,
990 uint16_t type, int fwd, size_t size)
992 struct CadetTunnelQueue *qt = cls;
993 struct CadetTunnel *t;
995 LOG (GNUNET_ERROR_TYPE_DEBUG, "tun_message_sent\n");
997 GNUNET_assert (NULL != qt->cont);
998 t = NULL == c ? NULL : GCC_get_tunnel (c);
999 qt->cont (qt->cont_cls, t, qt, type, size);
1005 count_queued_data (const struct CadetTunnel *t)
1007 struct CadetTunnelDelayed *iter;
1010 for (count = 0, iter = t->tq_head; iter != NULL; iter = iter->next)
1017 * Delete a queued message: either was sent or the channel was destroyed
1018 * before the tunnel's key exchange had a chance to finish.
1020 * @param tqd Delayed queue handle.
1023 unqueue_data (struct CadetTunnelDelayed *tqd)
1025 GNUNET_CONTAINER_DLL_remove (tqd->t->tq_head, tqd->t->tq_tail, tqd);
1031 * Cache a message to be sent once tunnel is online.
1033 * @param t Tunnel to hold the message.
1034 * @param msg Message itself (copy will be made).
1036 static struct CadetTunnelDelayed *
1037 queue_data (struct CadetTunnel *t, const struct GNUNET_MessageHeader *msg)
1039 struct CadetTunnelDelayed *tqd;
1040 uint16_t size = ntohs (msg->size);
1042 LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GCT_2s (t));
1044 if (GNUNET_YES == is_ready (t))
1050 tqd = GNUNET_malloc (sizeof (struct CadetTunnelDelayed) + size);
1053 memcpy (&tqd[1], msg, size);
1054 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
1060 * Sends an already built message on a tunnel, encrypting it and
1061 * choosing the best connection.
1063 * @param message Message to send. Function modifies it.
1064 * @param t Tunnel on which this message is transmitted.
1065 * @param c Connection to use (autoselect if NULL).
1066 * @param force Force the tunnel to take the message (buffer overfill).
1067 * @param cont Continuation to call once message is really sent.
1068 * @param cont_cls Closure for @c cont.
1069 * @param existing_q In case this a transmission of previously queued data,
1070 * this should be TunnelQueue given to the client.
1073 * @return Handle to cancel message.
1074 * NULL if @c cont is NULL or an error happens and message is dropped.
1076 static struct CadetTunnelQueue *
1077 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1078 struct CadetTunnel *t, struct CadetConnection *c,
1079 int force, GCT_sent cont, void *cont_cls,
1080 struct CadetTunnelQueue *existing_q)
1082 struct CadetTunnelQueue *tq;
1083 struct GNUNET_CADET_Encrypted *msg;
1084 size_t size = ntohs (message->size);
1085 char cbuf[sizeof (struct GNUNET_CADET_Encrypted) + size];
1091 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GCT_2s (t));
1093 if (GNUNET_NO == is_ready (t))
1095 struct CadetTunnelDelayed *tqd;
1096 /* A non null existing_q indicates sending of queued data.
1097 * Should only happen after tunnel becomes ready.
1099 GNUNET_assert (NULL == existing_q);
1100 tqd = queue_data (t, message);
1103 tq = GNUNET_new (struct CadetTunnelQueue);
1107 tq->cont_cls = cont_cls;
1111 GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1113 iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1114 msg = (struct GNUNET_CADET_Encrypted *) cbuf;
1115 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
1117 GNUNET_assert (t_encrypt (t, &msg[1], message, size, iv, GNUNET_NO) == size);
1118 t_hmac (&msg[1], size, iv, select_key (t), &msg->hmac);
1119 msg->header.size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
1122 c = tunnel_get_connection (t);
1125 /* Why is tunnel 'ready'? Should have been queued! */
1126 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
1129 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1131 return NULL; /* Drop... */
1135 type = ntohs (message->type);
1138 case GNUNET_MESSAGE_TYPE_CADET_DATA:
1139 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1140 if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
1141 mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
1143 mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
1145 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1146 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1147 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1148 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1149 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1150 msg->cid = *GCC_get_id (c);
1151 msg->ttl = htonl (default_ttl);
1156 LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
1158 fwd = GCC_is_origin (c, GNUNET_YES);
1162 GNUNET_break (NULL == GCC_send_prebuilt_message (&msg->header, type, mid, c,
1163 fwd, force, NULL, NULL));
1166 if (NULL == existing_q)
1168 tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
1175 tq->cq = GCC_send_prebuilt_message (&msg->header, type, mid, c, fwd, force,
1176 &tun_message_sent, tq);
1177 GNUNET_assert (NULL != tq->cq);
1179 tq->cont_cls = cont_cls;
1186 * Send all cached messages that we can, tunnel is online.
1188 * @param t Tunnel that holds the messages. Cannot be loopback.
1191 send_queued_data (struct CadetTunnel *t)
1193 struct CadetTunnelDelayed *tqd;
1194 struct CadetTunnelDelayed *next;
1197 LOG (GNUNET_ERROR_TYPE_DEBUG,
1198 "GCT_send_queued_data on tunnel %s\n",
1201 if (GCT_is_loopback (t))
1207 if (GNUNET_NO == is_ready (t))
1209 LOG (GNUNET_ERROR_TYPE_DEBUG, " not ready yet: %s/%s\n",
1210 estate2s (t->estate), cstate2s (t->cstate));
1214 room = GCT_get_connections_buffer (t);
1215 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
1216 LOG (GNUNET_ERROR_TYPE_DEBUG, " tq head: %p\n", t->tq_head);
1217 for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
1219 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
1222 send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
1223 tqd->t, NULL, GNUNET_YES,
1224 NULL != tqd->tq ? tqd->tq->cont : NULL,
1225 NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
1229 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
1234 * Sends key exchange message on a tunnel, choosing the best connection.
1235 * Should not be called on loopback tunnels.
1237 * @param t Tunnel on which this message is transmitted.
1238 * @param message Message to send. Function modifies it.
1241 send_kx (struct CadetTunnel *t,
1242 const struct GNUNET_MessageHeader *message)
1244 struct CadetConnection *c;
1245 struct GNUNET_CADET_KX *msg;
1246 size_t size = ntohs (message->size);
1247 char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
1251 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
1253 /* Avoid loopback. */
1254 if (GCT_is_loopback (t))
1256 LOG (GNUNET_ERROR_TYPE_DEBUG, " loopback!\n");
1260 type = ntohs (message->type);
1262 /* Even if tunnel is being destroyed, send anyway.
1263 * Could be a response to a rekey initiated by remote peer,
1264 * who is trying to create a new channel!
1267 /* Must have a connection. */
1268 if (NULL == t->connection_head && CADET_TUNNEL_SEARCHING != t->cstate)
1270 LOG (GNUNET_ERROR_TYPE_WARNING, "\n\n\n");
1272 LOG (GNUNET_ERROR_TYPE_WARNING, "sending %s\n", GC_m2s (type));
1273 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1274 GCP_debug (t->peer, GNUNET_ERROR_TYPE_WARNING);
1275 LOG (GNUNET_ERROR_TYPE_WARNING, "\n\n\n");
1279 msg = (struct GNUNET_CADET_KX *) cbuf;
1280 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
1281 msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
1282 c = tunnel_get_connection (t);
1285 GNUNET_break (GNUNET_SCHEDULER_NO_TASK != t->destroy_task
1286 || CADET_TUNNEL_READY != t->cstate);
1287 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1292 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
1293 case GNUNET_MESSAGE_TYPE_CADET_KX_PING:
1294 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
1295 memcpy (&msg[1], message, size);
1298 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
1303 fwd = GCC_is_origin (t->connection_head->c, GNUNET_YES);
1304 /* TODO save handle and cancel in case of a unneeded retransmission */
1305 GNUNET_assert (NULL == GCC_send_prebuilt_message (&msg->header, type, 0, c,
1312 * Send the ephemeral key on a tunnel.
1314 * @param t Tunnel on which to send the key.
1317 send_ephemeral (struct CadetTunnel *t)
1319 LOG (GNUNET_ERROR_TYPE_INFO, "===> EPHM for %s\n", GCT_2s (t));
1321 kx_msg.sender_status = htonl (t->estate);
1322 send_kx (t, &kx_msg.header);
1326 * Send a ping message on a tunnel.
1328 * @param t Tunnel on which to send the ping.
1331 send_ping (struct CadetTunnel *t)
1333 struct GNUNET_CADET_KX_Ping msg;
1335 LOG (GNUNET_ERROR_TYPE_INFO, "===> PING for %s\n", GCT_2s (t));
1336 msg.header.size = htons (sizeof (msg));
1337 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PING);
1338 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1339 msg.target = *GCP_get_id (t->peer);
1340 msg.nonce = t->kx_ctx->challenge;
1342 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
1343 LOG (GNUNET_ERROR_TYPE_DEBUG, " towards %s\n", GNUNET_i2s (&msg.target));
1344 t_encrypt (t, &msg.target, &msg.target,
1345 ping_encryption_size(), msg.iv, GNUNET_YES);
1346 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
1347 LOG (GNUNET_ERROR_TYPE_DEBUG, " e towards %s\n", GNUNET_i2s (&msg.target));
1349 send_kx (t, &msg.header);
1354 * Send a pong message on a tunnel.
1356 * @param t Tunnel on which to send the pong.
1357 * @param challenge Value sent in the ping that we have to send back.
1360 send_pong (struct CadetTunnel *t, uint32_t challenge)
1362 struct GNUNET_CADET_KX_Pong msg;
1364 LOG (GNUNET_ERROR_TYPE_INFO, "===> PONG for %s\n", GCT_2s (t));
1365 msg.header.size = htons (sizeof (msg));
1366 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
1367 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1368 msg.nonce = challenge;
1369 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
1370 t_encrypt (t, &msg.nonce, &msg.nonce,
1371 sizeof (msg.nonce), msg.iv, GNUNET_YES);
1372 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
1374 send_kx (t, &msg.header);
1379 * Initiate a rekey with the remote peer.
1381 * @param cls Closure (tunnel).
1382 * @param tc TaskContext.
1385 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1387 struct CadetTunnel *t = cls;
1389 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1391 LOG (GNUNET_ERROR_TYPE_INFO, "Re-key Tunnel %s\n", GCT_2s (t));
1392 if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1395 if (NULL == t->kx_ctx)
1402 struct GNUNET_TIME_Relative duration;
1404 if (GNUNET_SCHEDULER_NO_TASK != t->kx_ctx->finish_task)
1406 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
1407 t->kx_ctx->finish_task = GNUNET_SCHEDULER_NO_TASK;
1410 duration = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
1411 LOG (GNUNET_ERROR_TYPE_DEBUG, " kx started %s ago\n",
1412 GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
1414 // FIXME make duration of old keys configurable
1415 if (duration.rel_value_us >= GNUNET_TIME_UNIT_MINUTES.rel_value_us)
1417 memset (&t->kx_ctx->d_key_old, 0, sizeof (t->kx_ctx->d_key_old));
1418 memset (&t->kx_ctx->e_key_old, 0, sizeof (t->kx_ctx->e_key_old));
1426 case CADET_TUNNEL_KEY_UNINITIALIZED:
1427 t->estate = CADET_TUNNEL_KEY_SENT;
1429 case CADET_TUNNEL_KEY_SENT:
1431 case CADET_TUNNEL_KEY_OK:
1432 t->estate = CADET_TUNNEL_KEY_REKEY;
1434 case CADET_TUNNEL_KEY_PING:
1435 case CADET_TUNNEL_KEY_REKEY:
1439 LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
1442 // FIXME exponential backoff
1443 struct GNUNET_TIME_Relative delay;
1445 delay = GNUNET_TIME_relative_divide (rekey_period, 16);
1446 delay = GNUNET_TIME_relative_min (delay, REKEY_WAIT);
1447 LOG (GNUNET_ERROR_TYPE_DEBUG, " next call in %s\n",
1448 GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
1449 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1454 * Our ephemeral key has changed, create new session key on all tunnels.
1456 * Each tunnel will start the Key Exchange with a random delay between
1457 * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
1458 * per second, on average.
1460 * @param cls Closure (size of the hashmap).
1461 * @param key Current public key.
1462 * @param value Value in the hash map (tunnel).
1464 * @return #GNUNET_YES, so we should continue to iterate,
1467 rekey_iterator (void *cls,
1468 const struct GNUNET_PeerIdentity *key,
1471 struct CadetTunnel *t = value;
1472 struct GNUNET_TIME_Relative delay;
1473 long n = (long) cls;
1476 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
1479 if (GNUNET_YES == GCT_is_loopback (t))
1482 r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
1483 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
1484 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1491 * Create a new ephemeral key and key message, schedule next rekeying.
1493 * @param cls Closure (unused).
1494 * @param tc TaskContext.
1497 rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1499 struct GNUNET_TIME_Absolute time;
1502 rekey_task = GNUNET_SCHEDULER_NO_TASK;
1504 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1507 GNUNET_free_non_null (my_ephemeral_key);
1508 my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
1510 time = GNUNET_TIME_absolute_get ();
1511 kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
1512 time = GNUNET_TIME_absolute_add (time, rekey_period);
1513 time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
1514 kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
1515 GNUNET_CRYPTO_ecdhe_key_get_public (my_ephemeral_key, &kx_msg.ephemeral_key);
1517 GNUNET_assert (GNUNET_OK ==
1518 GNUNET_CRYPTO_eddsa_sign (my_private_key,
1520 &kx_msg.signature));
1522 n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
1523 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
1525 rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period, &rekey, NULL);
1530 * Called only on shutdown, destroy every tunnel.
1532 * @param cls Closure (unused).
1533 * @param key Current public key.
1534 * @param value Value in the hash map (tunnel).
1536 * @return #GNUNET_YES, so we should continue to iterate,
1539 destroy_iterator (void *cls,
1540 const struct GNUNET_PeerIdentity *key,
1543 struct CadetTunnel *t = value;
1545 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
1552 * Notify remote peer that we don't know a channel he is talking about,
1553 * probably CHANNEL_DESTROY was missed.
1555 * @param t Tunnel on which to notify.
1556 * @param gid ID of the channel.
1559 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
1561 struct GNUNET_CADET_ChannelManage msg;
1563 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
1564 msg.header.size = htons (sizeof (msg));
1565 msg.chid = htonl (gid);
1567 LOG (GNUNET_ERROR_TYPE_DEBUG,
1568 "WARNING destroying unknown channel %u on tunnel %s\n",
1570 send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
1575 * Demultiplex data per channel and call appropriate channel handler.
1577 * @param t Tunnel on which the data came.
1578 * @param msg Data message.
1579 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1580 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1581 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1582 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1585 handle_data (struct CadetTunnel *t,
1586 const struct GNUNET_CADET_Data *msg,
1589 struct CadetChannel *ch;
1593 size = ntohs (msg->header.size);
1595 sizeof (struct GNUNET_CADET_Data) +
1596 sizeof (struct GNUNET_MessageHeader))
1601 LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
1602 GC_m2s (ntohs (msg[1].header.type)));
1605 ch = GCT_get_channel (t, ntohl (msg->chid));
1608 GNUNET_STATISTICS_update (stats, "# data on unknown channel",
1610 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
1612 send_channel_destroy (t, ntohl (msg->chid));
1616 GCCH_handle_data (ch, msg, fwd);
1621 * Demultiplex data ACKs per channel and update appropriate channel buffer info.
1623 * @param t Tunnel on which the DATA ACK came.
1624 * @param msg DATA ACK message.
1625 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1626 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1627 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1628 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1631 handle_data_ack (struct CadetTunnel *t,
1632 const struct GNUNET_CADET_DataACK *msg,
1635 struct CadetChannel *ch;
1639 size = ntohs (msg->header.size);
1640 if (size != sizeof (struct GNUNET_CADET_DataACK))
1647 ch = GCT_get_channel (t, ntohl (msg->chid));
1650 GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
1652 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1657 GCCH_handle_data_ack (ch, msg, fwd);
1662 * Handle channel create.
1664 * @param t Tunnel on which the data came.
1665 * @param msg Data message.
1668 handle_ch_create (struct CadetTunnel *t,
1669 const struct GNUNET_CADET_ChannelCreate *msg)
1671 struct CadetChannel *ch;
1675 size = ntohs (msg->header.size);
1676 if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
1683 ch = GCT_get_channel (t, ntohl (msg->chid));
1684 if (NULL != ch && ! GCT_is_loopback (t))
1686 /* Probably a retransmission, safe to ignore */
1687 LOG (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
1689 ch = GCCH_handle_create (t, msg);
1691 GCT_add_channel (t, ch);
1697 * Handle channel NACK: check correctness and call channel handler for NACKs.
1699 * @param t Tunnel on which the NACK came.
1700 * @param msg NACK message.
1703 handle_ch_nack (struct CadetTunnel *t,
1704 const struct GNUNET_CADET_ChannelManage *msg)
1706 struct CadetChannel *ch;
1710 size = ntohs (msg->header.size);
1711 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1718 ch = GCT_get_channel (t, ntohl (msg->chid));
1721 GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
1723 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1728 GCCH_handle_nack (ch);
1733 * Handle a CHANNEL ACK (SYNACK/ACK).
1735 * @param t Tunnel on which the CHANNEL ACK came.
1736 * @param msg CHANNEL ACK message.
1737 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1738 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1739 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1740 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1743 handle_ch_ack (struct CadetTunnel *t,
1744 const struct GNUNET_CADET_ChannelManage *msg,
1747 struct CadetChannel *ch;
1751 size = ntohs (msg->header.size);
1752 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1759 ch = GCT_get_channel (t, ntohl (msg->chid));
1762 GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
1764 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1769 GCCH_handle_ack (ch, msg, fwd);
1774 * Handle a channel destruction message.
1776 * @param t Tunnel on which the message came.
1777 * @param msg Channel destroy message.
1778 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1779 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1780 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1781 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1784 handle_ch_destroy (struct CadetTunnel *t,
1785 const struct GNUNET_CADET_ChannelManage *msg,
1788 struct CadetChannel *ch;
1792 size = ntohs (msg->header.size);
1793 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1800 ch = GCT_get_channel (t, ntohl (msg->chid));
1803 /* Probably a retransmission, safe to ignore */
1807 GCCH_handle_destroy (ch, msg, fwd);
1812 * The peer's ephemeral key has changed: update the symmetrical keys.
1814 * @param t Tunnel this message came on.
1815 * @param msg Key eXchange message.
1818 handle_ephemeral (struct CadetTunnel *t,
1819 const struct GNUNET_CADET_KX_Ephemeral *msg)
1821 LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
1823 if (GNUNET_OK != check_ephemeral (t, msg))
1825 GNUNET_break_op (0);
1830 if (0 != memcmp (&t->peers_ephemeral_key, &msg->ephemeral_key,
1831 sizeof (msg->ephemeral_key)))
1833 t->peers_ephemeral_key = msg->ephemeral_key;
1835 if (CADET_TUNNEL_KEY_OK == t->estate)
1837 t->estate = CADET_TUNNEL_KEY_REKEY;
1840 else if (CADET_TUNNEL_KEY_OK == t->estate)
1844 if (CADET_TUNNEL_KEY_SENT == t->estate)
1846 LOG (GNUNET_ERROR_TYPE_DEBUG, " our key was sent, sending ping\n");
1848 t->estate = CADET_TUNNEL_KEY_PING;
1854 * Peer wants to check our symmetrical keys by sending an encrypted challenge.
1855 * Answer with by retransmitting the challenge with the "opposite" key.
1857 * @param t Tunnel this message came on.
1858 * @param msg Key eXchange Ping message.
1861 handle_ping (struct CadetTunnel *t,
1862 const struct GNUNET_CADET_KX_Ping *msg)
1864 struct GNUNET_CADET_KX_Ping res;
1866 if (ntohs (msg->header.size) != sizeof (res))
1868 GNUNET_break_op (0);
1872 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PING for %s\n", GCT_2s (t));
1873 t_decrypt (t, &res.target, &msg->target, ping_encryption_size (), msg->iv);
1874 if (0 != memcmp (&my_full_id, &res.target, sizeof (my_full_id)))
1876 GNUNET_STATISTICS_update (stats, "# malformed PINGs", 1, GNUNET_NO);
1877 LOG (GNUNET_ERROR_TYPE_WARNING, " malformed PING on %s\n", GCT_2s (t));
1878 LOG (GNUNET_ERROR_TYPE_DEBUG, " e got %u\n", msg->nonce);
1879 LOG (GNUNET_ERROR_TYPE_DEBUG, " e towards %s\n", GNUNET_i2s (&msg->target));
1880 LOG (GNUNET_ERROR_TYPE_DEBUG, " got %u\n", res.nonce);
1881 LOG (GNUNET_ERROR_TYPE_DEBUG, " towards %s\n", GNUNET_i2s (&res.target));
1888 send_pong (t, res.nonce);
1893 * Peer has answer to our challenge.
1894 * If answer is successful, consider the key exchange finished and clean
1895 * up all related state.
1897 * @param t Tunnel this message came on.
1898 * @param msg Key eXchange Pong message.
1901 handle_pong (struct CadetTunnel *t,
1902 const struct GNUNET_CADET_KX_Pong *msg)
1906 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
1907 if (GNUNET_SCHEDULER_NO_TASK == t->rekey_task)
1909 GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
1912 t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
1914 if (challenge != t->kx_ctx->challenge)
1916 LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
1917 LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
1918 challenge, msg->nonce, t->kx_ctx->challenge);
1923 GNUNET_SCHEDULER_cancel (t->rekey_task);
1924 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1926 /* Don't free the old keys right away, but after a delay.
1927 * Rationale: the KX could have happened over a very fast connection,
1928 * with payload traffic still signed with the old key stuck in a slower
1930 * Don't keep the keys longer than 1/4 the rekey period, and no longer than
1934 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
1939 * Demultiplex by message type and call appropriate handler for a message
1940 * towards a channel of a local tunnel.
1942 * @param t Tunnel this message came on.
1943 * @param msgh Message header.
1944 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1945 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1946 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1947 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1950 handle_decrypted (struct CadetTunnel *t,
1951 const struct GNUNET_MessageHeader *msgh,
1956 type = ntohs (msgh->type);
1957 LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
1961 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1962 /* Do nothing, connection aleady got updated. */
1963 GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
1966 case GNUNET_MESSAGE_TYPE_CADET_DATA:
1967 /* Don't send hop ACK, wait for client to ACK */
1968 handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
1971 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1972 handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
1975 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1976 handle_ch_create (t,
1977 (struct GNUNET_CADET_ChannelCreate *) msgh);
1980 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1982 (struct GNUNET_CADET_ChannelManage *) msgh);
1985 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1987 (struct GNUNET_CADET_ChannelManage *) msgh,
1991 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1992 handle_ch_destroy (t,
1993 (struct GNUNET_CADET_ChannelManage *) msgh,
1998 GNUNET_break_op (0);
1999 LOG (GNUNET_ERROR_TYPE_WARNING,
2000 "end-to-end message not known (%u)\n",
2001 ntohs (msgh->type));
2002 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
2006 /******************************************************************************/
2007 /******************************** API ***********************************/
2008 /******************************************************************************/
2011 * Decrypt and demultiplex by message type. Call appropriate handler
2012 * for every message.
2014 * @param t Tunnel this message came on.
2015 * @param msg Encrypted message.
2018 GCT_handle_encrypted (struct CadetTunnel *t,
2019 const struct GNUNET_CADET_Encrypted *msg)
2021 size_t size = ntohs (msg->header.size);
2022 size_t payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
2024 char cbuf [payload_size];
2025 struct GNUNET_MessageHeader *msgh;
2028 decrypted_size = t_decrypt_and_validate (t, cbuf, &msg[1], payload_size,
2029 msg->iv, &msg->hmac);
2031 if (-1 == decrypted_size)
2033 GNUNET_break_op (0);
2038 while (off < decrypted_size)
2042 msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
2043 msize = ntohs (msgh->size);
2044 if (msize < sizeof (struct GNUNET_MessageHeader))
2046 GNUNET_break_op (0);
2049 handle_decrypted (t, msgh, GNUNET_SYSERR);
2056 * Demultiplex an encapsulated KX message by message type.
2058 * @param t Tunnel on which the message came.
2059 * @param message Payload of KX message.
2062 GCT_handle_kx (struct CadetTunnel *t,
2063 const struct GNUNET_MessageHeader *message)
2067 type = ntohs (message->type);
2068 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received\n", type);
2071 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
2072 handle_ephemeral (t, (struct GNUNET_CADET_KX_Ephemeral *) message);
2075 case GNUNET_MESSAGE_TYPE_CADET_KX_PING:
2076 handle_ping (t, (struct GNUNET_CADET_KX_Ping *) message);
2079 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
2080 handle_pong (t, (struct GNUNET_CADET_KX_Pong *) message);
2084 GNUNET_break_op (0);
2085 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message not known (%u)\n", type);
2091 * Initialize the tunnel subsystem.
2093 * @param c Configuration handle.
2094 * @param key ECC private key, to derive all other keys and do crypto.
2097 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
2098 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
2100 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
2102 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
2105 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
2106 "CADET", "DEFAULT_TTL", "USING DEFAULT");
2110 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
2113 rekey_period = GNUNET_TIME_UNIT_DAYS;
2116 my_private_key = key;
2117 kx_msg.header.size = htons (sizeof (kx_msg));
2118 kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
2119 kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
2120 kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
2121 kx_msg.origin_identity = my_full_id;
2122 rekey_task = GNUNET_SCHEDULER_add_now (&rekey, NULL);
2124 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
2129 * Shut down the tunnel subsystem.
2134 if (GNUNET_SCHEDULER_NO_TASK != rekey_task)
2136 GNUNET_SCHEDULER_cancel (rekey_task);
2137 rekey_task = GNUNET_SCHEDULER_NO_TASK;
2139 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
2140 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
2147 * @param destination Peer this tunnel is towards.
2149 struct CadetTunnel *
2150 GCT_new (struct CadetPeer *destination)
2152 struct CadetTunnel *t;
2154 t = GNUNET_new (struct CadetTunnel);
2156 t->peer = destination;
2159 GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
2160 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2171 * Change the tunnel's connection state.
2173 * @param t Tunnel whose connection state to change.
2174 * @param cstate New connection state.
2177 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
2181 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
2182 GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
2183 if (myid != GCP_get_short_id (t->peer) &&
2184 CADET_TUNNEL_READY != t->cstate &&
2185 CADET_TUNNEL_READY == cstate)
2188 if (CADET_TUNNEL_KEY_OK == t->estate)
2190 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered send queued data\n");
2191 send_queued_data (t);
2193 else if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
2195 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered rekey\n");
2196 rekey_tunnel (t, NULL);
2201 if (CADET_TUNNEL_READY == cstate
2202 && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
2204 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered stop dht\n");
2205 GCP_stop_search (t->peer);
2210 * Change the tunnel encryption state.
2212 * @param t Tunnel whose encryption state to change.
2213 * @param state New encryption state.
2216 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
2220 LOG (GNUNET_ERROR_TYPE_DEBUG,
2221 "Tunnel %s estate was %s\n",
2222 GCP_2s (t->peer), estate2s (t->estate));
2223 LOG (GNUNET_ERROR_TYPE_DEBUG,
2224 "Tunnel %s estate is now %s\n",
2225 GCP_2s (t->peer), estate2s (state));
2226 if (myid != GCP_get_short_id (t->peer) &&
2227 CADET_TUNNEL_KEY_OK != t->estate && CADET_TUNNEL_KEY_OK == state)
2230 send_queued_data (t);
2238 * @brief Check if tunnel has too many connections, and remove one if necessary.
2240 * Currently this means the newest connection, unless it is a direct one.
2241 * Implemented as a task to avoid freeing a connection that is in the middle
2242 * of being created/processed.
2244 * @param cls Closure (Tunnel to check).
2245 * @param tc Task context.
2248 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2250 struct CadetTunnel *t = cls;
2252 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2255 if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
2257 struct CadetTConnection *iter;
2258 struct CadetTConnection *c;
2260 for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
2262 if ((NULL == c || iter->created.abs_value_us > c->created.abs_value_us)
2263 && GNUNET_NO == GCC_is_direct (iter->c))
2270 LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
2272 LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
2285 * Add a connection to a tunnel.
2288 * @param c Connection.
2291 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
2293 struct CadetTConnection *aux;
2295 GNUNET_assert (NULL != c);
2297 LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
2298 LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
2299 for (aux = t->connection_head; aux != NULL; aux = aux->next)
2303 aux = GNUNET_new (struct CadetTConnection);
2305 aux->created = GNUNET_TIME_absolute_get ();
2307 GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
2309 GNUNET_SCHEDULER_add_now (&trim_connections, t);
2314 * Mark a path as no longer valid for this tunnel: has been tried and failed.
2316 * @param t Tunnel to update.
2317 * @param path Invalid path to remove. Is destroyed after removal.
2320 GCT_remove_path (struct CadetTunnel *t, struct CadetPeerPath *path)
2322 GCP_remove_path (t->peer, path);
2327 * Remove a connection from a tunnel.
2330 * @param c Connection.
2333 GCT_remove_connection (struct CadetTunnel *t,
2334 struct CadetConnection *c)
2336 struct CadetTConnection *aux;
2337 struct CadetTConnection *next;
2339 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
2340 GCC_2s (c), GCT_2s (t));
2341 for (aux = t->connection_head; aux != NULL; aux = next)
2346 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
2351 /* Start new connections if needed */
2352 if (CONNECTIONS_PER_TUNNEL > GCT_count_connections (t)
2353 && GNUNET_SCHEDULER_NO_TASK == t->destroy_task
2354 && CADET_TUNNEL_SHUTDOWN != t->cstate
2355 && GNUNET_NO == shutting_down)
2357 LOG (GNUNET_ERROR_TYPE_DEBUG, " no more connections, getting new ones\n");
2358 GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
2359 GCP_connect (t->peer);
2363 /* If not marked as ready, no change is needed */
2364 if (CADET_TUNNEL_READY != t->cstate)
2367 /* Check if any connection is ready to maintain cstate */
2368 for (aux = t->connection_head; aux != NULL; aux = aux->next)
2369 if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
2372 GCT_change_cstate (t, CADET_TUNNEL_WAITING);
2377 * Add a channel to a tunnel.
2380 * @param ch Channel.
2383 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2385 struct CadetTChannel *aux;
2387 GNUNET_assert (NULL != ch);
2389 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
2391 for (aux = t->channel_head; aux != NULL; aux = aux->next)
2393 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
2398 aux = GNUNET_new (struct CadetTChannel);
2400 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
2401 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
2403 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2405 GNUNET_SCHEDULER_cancel (t->destroy_task);
2406 t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2407 LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
2413 * Remove a channel from a tunnel.
2416 * @param ch Channel.
2419 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2421 struct CadetTChannel *aux;
2423 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
2424 for (aux = t->channel_head; aux != NULL; aux = aux->next)
2428 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
2429 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
2438 * Search for a channel by global ID.
2440 * @param t Tunnel containing the channel.
2441 * @param chid Public channel number.
2443 * @return channel handler, NULL if doesn't exist
2445 struct CadetChannel *
2446 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
2448 struct CadetTChannel *iter;
2453 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2455 if (GCCH_get_id (iter->ch) == chid)
2459 return NULL == iter ? NULL : iter->ch;
2464 * @brief Destroy a tunnel and free all resources.
2466 * Should only be called a while after the tunnel has been marked as destroyed,
2467 * in case there is a new channel added to the same peer shortly after marking
2468 * the tunnel. This way we avoid a new public key handshake.
2470 * @param cls Closure (tunnel to destroy).
2471 * @param tc Task context.
2474 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2476 struct CadetTunnel *t = cls;
2477 struct CadetTConnection *iter;
2479 LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
2480 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2482 LOG (GNUNET_ERROR_TYPE_WARNING,
2483 "Not destroying tunnel, due to shutdown. "
2484 "Tunnel at %p should have been freed by GCT_shutdown\n", t);
2487 t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2488 t->cstate = CADET_TUNNEL_SHUTDOWN;
2490 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2492 GCC_send_destroy (iter->c);
2499 * Tunnel is empty: destroy it.
2501 * Notifies all connections about the destruction.
2503 * @param t Tunnel to destroy.
2506 GCT_destroy_empty (struct CadetTunnel *t)
2508 if (GNUNET_YES == shutting_down)
2509 return; /* Will be destroyed immediately anyway */
2511 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2513 LOG (GNUNET_ERROR_TYPE_WARNING,
2514 "Tunnel %s is already scheduled for destruction. Tunnel debug dump:\n",
2516 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
2518 /* should never happen, tunnel can only become empty once, and the
2519 * task identifier should be NO_TASK (cleaned when the tunnel was created
2520 * or became un-empty)
2525 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: destroying scheduled\n",
2528 // FIXME make delay a config option
2529 t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
2530 &delayed_destroy, t);
2531 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llX\n",
2532 t, t->destroy_task);
2537 * Destroy tunnel if empty (no more channels).
2539 * @param t Tunnel to destroy if empty.
2542 GCT_destroy_if_empty (struct CadetTunnel *t)
2544 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
2545 if (1 < GCT_count_channels (t))
2548 GCT_destroy_empty (t);
2553 * Destroy the tunnel.
2555 * This function does not generate any warning traffic to clients or peers.
2558 * Cancel messages belonging to this tunnel queued to neighbors.
2559 * Free any allocated resources linked to the tunnel.
2561 * @param t The tunnel to destroy.
2564 GCT_destroy (struct CadetTunnel *t)
2566 struct CadetTConnection *iter_c;
2567 struct CadetTConnection *next_c;
2568 struct CadetTChannel *iter_ch;
2569 struct CadetTChannel *next_ch;
2574 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
2576 GNUNET_break (GNUNET_YES ==
2577 GNUNET_CONTAINER_multipeermap_remove (tunnels,
2578 GCP_get_id (t->peer), t));
2580 for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
2582 next_c = iter_c->next;
2583 GCC_destroy (iter_c->c);
2585 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
2587 next_ch = iter_ch->next;
2588 GCCH_destroy (iter_ch->ch);
2589 /* Should only happen on shutdown, but it's ok. */
2592 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2594 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling %llX\n", t->destroy_task);
2595 GNUNET_SCHEDULER_cancel (t->destroy_task);
2596 t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2599 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
2600 GCP_set_tunnel (t->peer, NULL);
2602 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
2604 GNUNET_SCHEDULER_cancel (t->rekey_task);
2605 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
2607 if (NULL != t->kx_ctx)
2609 if (GNUNET_SCHEDULER_NO_TASK != t->kx_ctx->finish_task)
2610 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
2611 GNUNET_free (t->kx_ctx);
2618 * @brief Use the given path for the tunnel.
2619 * Update the next and prev hops (and RCs).
2620 * (Re)start the path refresh in case the tunnel is locally owned.
2622 * @param t Tunnel to update.
2623 * @param p Path to use.
2625 * @return Connection created.
2627 struct CadetConnection *
2628 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
2630 struct CadetConnection *c;
2631 struct GNUNET_CADET_Hash cid;
2632 unsigned int own_pos;
2634 if (NULL == t || NULL == p)
2640 if (CADET_TUNNEL_SHUTDOWN == t->cstate)
2646 for (own_pos = 0; own_pos < p->length; own_pos++)
2648 if (p->peers[own_pos] == myid)
2651 if (own_pos >= p->length)
2653 GNUNET_break_op (0);
2657 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
2658 c = GCC_new (&cid, t, p, own_pos);
2661 /* Path was flawed */
2664 GCT_add_connection (t, c);
2670 * Count created connections of a tunnel. Not necessarily ready connections!
2672 * @param t Tunnel on which to count.
2674 * @return Number of connections created, either being established or ready.
2677 GCT_count_connections (struct CadetTunnel *t)
2679 struct CadetTConnection *iter;
2685 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2686 if (CADET_CONNECTION_DESTROYED != GCC_get_state (iter->c))
2693 * Count channels of a tunnel.
2695 * @param t Tunnel on which to count.
2697 * @return Number of channels.
2700 GCT_count_channels (struct CadetTunnel *t)
2702 struct CadetTChannel *iter;
2705 for (count = 0, iter = t->channel_head;
2707 iter = iter->next, count++) /* skip */;
2714 * Get the connectivity state of a tunnel.
2718 * @return Tunnel's connectivity state.
2720 enum CadetTunnelCState
2721 GCT_get_cstate (struct CadetTunnel *t)
2726 return (enum CadetTunnelCState) -1;
2733 * Get the encryption state of a tunnel.
2737 * @return Tunnel's encryption state.
2739 enum CadetTunnelEState
2740 GCT_get_estate (struct CadetTunnel *t)
2745 return (enum CadetTunnelEState) -1;
2751 * Get the maximum buffer space for a tunnel towards a local client.
2755 * @return Biggest buffer space offered by any channel in the tunnel.
2758 GCT_get_channels_buffer (struct CadetTunnel *t)
2760 struct CadetTChannel *iter;
2761 unsigned int buffer;
2762 unsigned int ch_buf;
2764 if (NULL == t->channel_head)
2766 /* Probably getting buffer for a channel create/handshake. */
2771 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2773 ch_buf = get_channel_buffer (iter);
2774 if (ch_buf > buffer)
2782 * Get the total buffer space for a tunnel for P2P traffic.
2786 * @return Buffer space offered by all connections in the tunnel.
2789 GCT_get_connections_buffer (struct CadetTunnel *t)
2791 struct CadetTConnection *iter;
2792 unsigned int buffer;
2794 if (GNUNET_NO == is_ready (t))
2796 if (count_queued_data (t) > 3)
2803 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2805 if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
2809 buffer += get_connection_buffer (iter);
2817 * Get the tunnel's destination.
2821 * @return ID of the destination peer.
2823 const struct GNUNET_PeerIdentity *
2824 GCT_get_destination (struct CadetTunnel *t)
2826 return GCP_get_id (t->peer);
2831 * Get the tunnel's next free global channel ID.
2835 * @return GID of a channel free to use.
2838 GCT_get_next_chid (struct CadetTunnel *t)
2840 CADET_ChannelNumber chid;
2841 CADET_ChannelNumber mask;
2844 /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
2845 * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
2846 * If peer's ID is bigger, start at 0x4... bit 30 = 1
2848 result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
2853 t->next_chid |= mask;
2855 while (NULL != GCT_get_channel (t, t->next_chid))
2857 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
2858 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
2859 t->next_chid |= mask;
2861 chid = t->next_chid;
2862 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
2863 t->next_chid |= mask;
2870 * Send ACK on one or more channels due to buffer in connections.
2872 * @param t Channel which has some free buffer space.
2875 GCT_unchoke_channels (struct CadetTunnel *t)
2877 struct CadetTChannel *iter;
2878 unsigned int buffer;
2879 unsigned int channels = GCT_count_channels (t);
2880 unsigned int choked_n;
2881 struct CadetChannel *choked[channels];
2883 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
2884 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
2885 if (NULL != t->channel_head)
2886 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
2888 /* Get buffer space */
2889 buffer = GCT_get_connections_buffer (t);
2895 /* Count and remember choked channels */
2897 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2899 if (GNUNET_NO == get_channel_allowed (iter))
2901 choked[choked_n++] = iter->ch;
2905 /* Unchoke random channels */
2906 while (0 < buffer && 0 < choked_n)
2908 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2910 GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
2913 choked[r] = choked[choked_n];
2919 * Send ACK on one or more connections due to buffer space to the client.
2921 * Iterates all connections of the tunnel and sends ACKs appropriately.
2926 GCT_send_connection_acks (struct CadetTunnel *t)
2928 struct CadetTConnection *iter;
2931 uint32_t allow_per_connection;
2933 unsigned int buffer;
2935 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
2944 buffer = GCT_get_channels_buffer (t);
2945 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer %u\n", buffer);
2947 /* Count connections, how many messages are already allowed */
2948 cs = GCT_count_connections (t);
2949 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2951 allowed += get_connection_allowed (iter);
2953 LOG (GNUNET_ERROR_TYPE_DEBUG, " allowed %u\n", allowed);
2955 /* Make sure there is no overflow */
2956 if (allowed > buffer)
2961 /* Authorize connections to send more data */
2962 to_allow = buffer; /* - allowed; */
2964 for (iter = t->connection_head;
2965 NULL != iter && to_allow > 0;
2968 allow_per_connection = to_allow/cs;
2969 to_allow -= allow_per_connection;
2971 if (get_connection_allowed (iter) > 64 / 3)
2975 GCC_allow (iter->c, allow_per_connection,
2976 GCC_is_origin (iter->c, GNUNET_NO));
2979 GNUNET_break (to_allow == 0);
2984 * Cancel a previously sent message while it's in the queue.
2986 * ONLY can be called before the continuation given to the send function
2987 * is called. Once the continuation is called, the message is no longer in the
2990 * @param q Handle to the queue.
2993 GCT_cancel (struct CadetTunnelQueue *q)
2998 /* tun_message_sent() will be called and free q */
3000 else if (NULL != q->tqd)
3002 unqueue_data (q->tqd);
3004 if (NULL != q->cont)
3005 q->cont (q->cont_cls, NULL, q, 0, 0);
3016 * Sends an already built message on a tunnel, encrypting it and
3017 * choosing the best connection if not provided.
3019 * @param message Message to send. Function modifies it.
3020 * @param t Tunnel on which this message is transmitted.
3021 * @param c Connection to use (autoselect if NULL).
3022 * @param force Force the tunnel to take the message (buffer overfill).
3023 * @param cont Continuation to call once message is really sent.
3024 * @param cont_cls Closure for @c cont.
3026 * @return Handle to cancel message. NULL if @c cont is NULL.
3028 struct CadetTunnelQueue *
3029 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
3030 struct CadetTunnel *t, struct CadetConnection *c,
3031 int force, GCT_sent cont, void *cont_cls)
3033 return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
3038 * Is the tunnel directed towards the local peer?
3042 * @return #GNUNET_YES if it is loopback.
3045 GCT_is_loopback (const struct CadetTunnel *t)
3047 return (myid == GCP_get_short_id (t->peer));
3052 * Is the tunnel this path already?
3057 * @return #GNUNET_YES a connection uses this path.
3060 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
3062 struct CadetTConnection *iter;
3064 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3065 if (GCC_get_path (iter->c) == p)
3073 * Get a cost of a path for a tunnel considering existing connections.
3076 * @param path Candidate path.
3078 * @return Cost of the path (path length + number of overlapping nodes)
3081 GCT_get_path_cost (const struct CadetTunnel *t,
3082 const struct CadetPeerPath *path)
3084 struct CadetTConnection *iter;
3085 const struct CadetPeerPath *aux;
3086 unsigned int overlap;
3094 GNUNET_assert (NULL != t);
3096 for (i = 0; i < path->length; i++)
3098 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3100 aux = GCC_get_path (iter->c);
3104 for (j = 0; j < aux->length; j++)
3106 if (path->peers[i] == aux->peers[j])
3114 return path->length + overlap;
3119 * Get the static string for the peer this tunnel is directed.
3123 * @return Static string the destination peer's ID.
3126 GCT_2s (const struct CadetTunnel *t)
3131 return GCP_2s (t->peer);
3135 /******************************************************************************/
3136 /***************************** INFO/DEBUG *******************************/
3137 /******************************************************************************/
3140 * Log all possible info about the tunnel state.
3142 * @param t Tunnel to debug.
3143 * @param level Debug level to use.
3146 GCT_debug (const struct CadetTunnel *t, enum GNUNET_ErrorType level)
3148 struct CadetTChannel *iterch;
3149 struct CadetTConnection *iterc;
3151 LOG (level, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
3152 LOG (level, "TTT cstate %s, estate %s\n",
3153 cstate2s (t->cstate), estate2s (t->estate));
3154 LOG (level, "TTT kx_ctx %p, rekey_task %u\n", t->kx_ctx, t->rekey_task);
3155 LOG (level, "TTT tq_head %p, tq_tail %p\n", t->tq_head, t->tq_tail);
3156 LOG (level, "TTT destroy %u\n", t->destroy_task);
3158 LOG (level, "TTT channels:\n");
3159 for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
3161 LOG (level, "TTT - %s\n", GCCH_2s (iterch->ch));
3164 LOG (level, "TTT connections:\n");
3165 for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
3167 LOG (level, "TTT - %s [%u] buf: %u/%u (qn %u/%u)\n",
3168 GCC_2s (iterc->c), GCC_get_state (iterc->c),
3169 GCC_get_buffer (iterc->c, GNUNET_YES),
3170 GCC_get_buffer (iterc->c, GNUNET_NO),
3171 GCC_get_qn (iterc->c, GNUNET_YES),
3172 GCC_get_qn (iterc->c, GNUNET_NO));
3175 LOG (level, "TTT DEBUG TUNNEL END\n");
3180 * Iterate all tunnels.
3182 * @param iter Iterator.
3183 * @param cls Closure for @c iter.
3186 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
3188 GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
3193 * Count all tunnels.
3195 * @return Number of tunnels to remote peers kept by this peer.
3198 GCT_count_all (void)
3200 return GNUNET_CONTAINER_multipeermap_size (tunnels);
3205 * Iterate all connections of a tunnel.
3207 * @param t Tunnel whose connections to iterate.
3208 * @param iter Iterator.
3209 * @param cls Closure for @c iter.
3212 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
3214 struct CadetTConnection *ct;
3216 for (ct = t->connection_head; NULL != ct; ct = ct->next)
3222 * Iterate all channels of a tunnel.
3224 * @param t Tunnel whose channels to iterate.
3225 * @param iter Iterator.
3226 * @param cls Closure for @c iter.
3229 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
3231 struct CadetTChannel *cht;
3233 for (cht = t->channel_head; NULL != cht; cht = cht->next)
3234 iter (cls, cht->ch);