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 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 key, for decrypting traffic sent by the
103 * 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.
158 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
161 * Decryption ("their") key.
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 GNUNET_assert (NULL == t->kx_ctx);
848 LOG (GNUNET_ERROR_TYPE_INFO, " new kx ctx for %s\n", GCT_2s (t));
849 t->kx_ctx = GNUNET_new (struct CadetTunnelKXCtx);
850 t->kx_ctx->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
852 t->kx_ctx->d_key_old = t->d_key;
853 t->kx_ctx->e_key_old = t->e_key;
854 t->kx_ctx->rekey_start_time = GNUNET_TIME_absolute_get ();
859 * Derive the tunnel's keys using our own and the peer's ephemeral keys.
861 * @param t Tunnel for which to create the keys.
864 create_keys (struct CadetTunnel *t)
866 struct GNUNET_HashCode km;
868 derive_key_material (&km, &t->peers_ephemeral_key);
869 derive_symmertic (&t->e_key, &my_full_id, GCP_get_id (t->peer), &km);
870 derive_symmertic (&t->d_key, GCP_get_id (t->peer), &my_full_id, &km);
871 #if DUMP_KEYS_TO_STDERR
872 LOG (GNUNET_ERROR_TYPE_INFO, "ME: %s\n",
873 GNUNET_h2s ((struct GNUNET_HashCode *) &kx_msg.ephemeral_key));
874 LOG (GNUNET_ERROR_TYPE_INFO, "PE: %s\n",
875 GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
876 LOG (GNUNET_ERROR_TYPE_INFO, "KM: %s\n", GNUNET_h2s (&km));
877 LOG (GNUNET_ERROR_TYPE_INFO, "EK: %s\n",
878 GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
879 LOG (GNUNET_ERROR_TYPE_INFO, "DK: %s\n",
880 GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
886 * Pick a connection on which send the next data message.
888 * @param t Tunnel on which to send the message.
890 * @return The connection on which to send the next message.
892 static struct CadetConnection *
893 tunnel_get_connection (struct CadetTunnel *t)
895 struct CadetTConnection *iter;
896 struct CadetConnection *best;
898 unsigned int lowest_q;
900 LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GCT_2s (t));
903 for (iter = t->connection_head; NULL != iter; iter = iter->next)
905 LOG (GNUNET_ERROR_TYPE_DEBUG, " connection %s: %u\n",
906 GCC_2s (iter->c), GCC_get_state (iter->c));
907 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
909 qn = GCC_get_qn (iter->c, GCC_is_origin (iter->c, GNUNET_YES));
910 LOG (GNUNET_ERROR_TYPE_DEBUG, " q_n %u, \n", qn);
918 LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GCC_2s (best));
924 * Callback called when a queued message is sent.
926 * Calculates the average time and connection packet tracking.
928 * @param cls Closure (TunnelQueue handle).
929 * @param c Connection this message was on.
930 * @param q Connection queue handle (unused).
931 * @param type Type of message sent.
932 * @param fwd Was this a FWD going message?
933 * @param size Size of the message.
936 tun_message_sent (void *cls,
937 struct CadetConnection *c,
938 struct CadetConnectionQueue *q,
939 uint16_t type, int fwd, size_t size)
941 struct CadetTunnelQueue *qt = cls;
942 struct CadetTunnel *t;
944 LOG (GNUNET_ERROR_TYPE_DEBUG, "tun_message_sent\n");
946 GNUNET_assert (NULL != qt->cont);
947 t = NULL == c ? NULL : GCC_get_tunnel (c);
948 qt->cont (qt->cont_cls, t, qt, type, size);
954 count_queued_data (const struct CadetTunnel *t)
956 struct CadetTunnelDelayed *iter;
959 for (count = 0, iter = t->tq_head; iter != NULL; iter = iter->next)
966 * Delete a queued message: either was sent or the channel was destroyed
967 * before the tunnel's key exchange had a chance to finish.
969 * @param tqd Delayed queue handle.
972 unqueue_data (struct CadetTunnelDelayed *tqd)
974 GNUNET_CONTAINER_DLL_remove (tqd->t->tq_head, tqd->t->tq_tail, tqd);
980 * Cache a message to be sent once tunnel is online.
982 * @param t Tunnel to hold the message.
983 * @param msg Message itself (copy will be made).
985 static struct CadetTunnelDelayed *
986 queue_data (struct CadetTunnel *t, const struct GNUNET_MessageHeader *msg)
988 struct CadetTunnelDelayed *tqd;
989 uint16_t size = ntohs (msg->size);
991 LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GCT_2s (t));
993 if (GNUNET_YES == is_ready (t))
999 tqd = GNUNET_malloc (sizeof (struct CadetTunnelDelayed) + size);
1002 memcpy (&tqd[1], msg, size);
1003 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
1009 * Sends an already built message on a tunnel, encrypting it and
1010 * choosing the best connection.
1012 * @param message Message to send. Function modifies it.
1013 * @param t Tunnel on which this message is transmitted.
1014 * @param c Connection to use (autoselect if NULL).
1015 * @param force Force the tunnel to take the message (buffer overfill).
1016 * @param cont Continuation to call once message is really sent.
1017 * @param cont_cls Closure for @c cont.
1018 * @param existing_q In case this a transmission of previously queued data,
1019 * this should be TunnelQueue given to the client.
1022 * @return Handle to cancel message. NULL if @c cont is NULL.
1024 static struct CadetTunnelQueue *
1025 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1026 struct CadetTunnel *t, struct CadetConnection *c,
1027 int force, GCT_sent cont, void *cont_cls,
1028 struct CadetTunnelQueue *existing_q)
1030 struct CadetTunnelQueue *tq;
1031 struct GNUNET_CADET_Encrypted *msg;
1032 size_t size = ntohs (message->size);
1033 char cbuf[sizeof (struct GNUNET_CADET_Encrypted) + size];
1039 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GCT_2s (t));
1041 if (GNUNET_NO == is_ready (t))
1043 struct CadetTunnelDelayed *tqd;
1044 /* A non null existing_q indicates sending of queued data.
1045 * Should only happen after tunnel becomes ready.
1047 GNUNET_assert (NULL == existing_q);
1048 tqd = queue_data (t, message);
1051 tq = GNUNET_new (struct CadetTunnelQueue);
1055 tq->cont_cls = cont_cls;
1059 GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1061 iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1062 msg = (struct GNUNET_CADET_Encrypted *) cbuf;
1063 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
1065 GNUNET_assert (t_encrypt (t, &msg[1], message, size, iv, GNUNET_NO) == size);
1066 t_hmac (&msg[1], size, iv, select_key (t), &msg->hmac);
1067 msg->header.size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
1070 c = tunnel_get_connection (t);
1073 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task
1074 || CADET_TUNNEL_SEARCHING != t->cstate)
1077 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1083 type = ntohs (message->type);
1086 case GNUNET_MESSAGE_TYPE_CADET_DATA:
1087 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1088 if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
1089 mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
1091 mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
1093 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1094 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1095 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1096 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1097 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1098 msg->cid = *GCC_get_id (c);
1099 msg->ttl = htonl (default_ttl);
1104 LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
1106 fwd = GCC_is_origin (c, GNUNET_YES);
1110 GNUNET_break (NULL ==
1111 GCC_send_prebuilt_message (&msg->header, type, mid,
1112 c, fwd, force, NULL, NULL));
1115 if (NULL == existing_q)
1117 tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
1124 tq->cq = GCC_send_prebuilt_message (&msg->header, type, mid, c, fwd, force,
1125 &tun_message_sent, tq);
1127 tq->cont_cls = cont_cls;
1134 * Send all cached messages that we can, tunnel is online.
1136 * @param t Tunnel that holds the messages. Cannot be loopback.
1139 send_queued_data (struct CadetTunnel *t)
1141 struct CadetTunnelDelayed *tqd;
1142 struct CadetTunnelDelayed *next;
1145 LOG (GNUNET_ERROR_TYPE_DEBUG,
1146 "GCT_send_queued_data on tunnel %s\n",
1149 if (GCT_is_loopback (t))
1155 if (GNUNET_NO == is_ready (t))
1157 LOG (GNUNET_ERROR_TYPE_DEBUG, " not ready yet: %s/%s\n",
1158 estate2s (t->estate), cstate2s (t->cstate));
1162 room = GCT_get_connections_buffer (t);
1163 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
1164 LOG (GNUNET_ERROR_TYPE_DEBUG, " tq head: %p\n", t->tq_head);
1165 for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
1167 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
1170 send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
1171 tqd->t, NULL, GNUNET_YES,
1172 NULL != tqd->tq ? tqd->tq->cont : NULL,
1173 NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
1177 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
1182 * Sends key exchange message on a tunnel, choosing the best connection.
1183 * Should not be called on loopback tunnels.
1185 * @param t Tunnel on which this message is transmitted.
1186 * @param message Message to send. Function modifies it.
1189 send_kx (struct CadetTunnel *t,
1190 const struct GNUNET_MessageHeader *message)
1192 struct CadetConnection *c;
1193 struct GNUNET_CADET_KX *msg;
1194 size_t size = ntohs (message->size);
1195 char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
1199 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
1201 /* Avoid loopback. */
1202 if (GCT_is_loopback (t))
1204 LOG (GNUNET_ERROR_TYPE_DEBUG, " loopback!\n");
1209 /* Even if tunnel is being destroyed, send anyway.
1210 * Could be a response to a rekey initiated by remote peer,
1211 * who is trying to create a new channel!
1214 /* Must have a connection. */
1215 if (NULL == t->connection_head)
1217 GNUNET_break (CADET_TUNNEL_SEARCHING == t->cstate);
1218 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1222 msg = (struct GNUNET_CADET_KX *) cbuf;
1223 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
1224 msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
1225 c = tunnel_get_connection (t);
1228 GNUNET_break (GNUNET_SCHEDULER_NO_TASK != t->destroy_task
1229 || CADET_TUNNEL_READY != t->cstate);
1230 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1233 type = ntohs (message->type);
1236 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
1237 case GNUNET_MESSAGE_TYPE_CADET_KX_PING:
1238 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
1239 memcpy (&msg[1], message, size);
1242 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
1247 fwd = GCC_is_origin (t->connection_head->c, GNUNET_YES);
1248 /* TODO save handle and cancel in case of a unneeded retransmission */
1249 GCC_send_prebuilt_message (&msg->header, GNUNET_MESSAGE_TYPE_CADET_KX,
1250 message->type, c, fwd, GNUNET_YES, NULL, NULL);
1255 * Send the ephemeral key on a tunnel.
1257 * @param t Tunnel on which to send the key.
1260 send_ephemeral (struct CadetTunnel *t)
1262 LOG (GNUNET_ERROR_TYPE_INFO, "===> EPHM for %s\n", GCT_2s (t));
1264 kx_msg.sender_status = htonl (t->estate);
1265 send_kx (t, &kx_msg.header);
1269 * Send a ping message on a tunnel.
1271 * @param t Tunnel on which to send the ping.
1274 send_ping (struct CadetTunnel *t)
1276 struct GNUNET_CADET_KX_Ping msg;
1278 LOG (GNUNET_ERROR_TYPE_INFO, "===> PING for %s\n", GCT_2s (t));
1279 msg.header.size = htons (sizeof (msg));
1280 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PING);
1281 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1282 msg.target = *GCP_get_id (t->peer);
1283 msg.nonce = t->kx_ctx->challenge;
1285 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
1286 LOG (GNUNET_ERROR_TYPE_DEBUG, " towards %s\n", GNUNET_i2s (&msg.target));
1287 t_encrypt (t, &msg.target, &msg.target,
1288 ping_encryption_size(), msg.iv, GNUNET_YES);
1289 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
1290 LOG (GNUNET_ERROR_TYPE_DEBUG, " e towards %s\n", GNUNET_i2s (&msg.target));
1292 send_kx (t, &msg.header);
1297 * Send a pong message on a tunnel.
1299 * @param t Tunnel on which to send the pong.
1300 * @param challenge Value sent in the ping that we have to send back.
1303 send_pong (struct CadetTunnel *t, uint32_t challenge)
1305 struct GNUNET_CADET_KX_Pong msg;
1307 LOG (GNUNET_ERROR_TYPE_INFO, "===> PONG for %s\n", GCT_2s (t));
1308 msg.header.size = htons (sizeof (msg));
1309 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
1310 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1311 msg.nonce = challenge;
1312 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
1313 t_encrypt (t, &msg.nonce, &msg.nonce,
1314 sizeof (msg.nonce), msg.iv, GNUNET_YES);
1315 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
1317 send_kx (t, &msg.header);
1322 * Initiate a rekey with the remote peer.
1324 * @param cls Closure (tunnel).
1325 * @param tc TaskContext.
1328 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1330 struct CadetTunnel *t = cls;
1332 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1334 LOG (GNUNET_ERROR_TYPE_INFO, "Re-key Tunnel %s\n", GCT_2s (t));
1335 if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1338 if (NULL == t->kx_ctx)
1345 struct GNUNET_TIME_Relative duration;
1347 duration = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
1348 LOG (GNUNET_ERROR_TYPE_DEBUG, " kx started %s ago\n",
1349 GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
1351 // FIXME make duration of old keys configurable
1352 if (duration.rel_value_us >= GNUNET_TIME_UNIT_MINUTES.rel_value_us)
1354 memset (&t->kx_ctx->d_key_old, 0, sizeof (t->kx_ctx->d_key_old));
1355 memset (&t->kx_ctx->e_key_old, 0, sizeof (t->kx_ctx->e_key_old));
1363 case CADET_TUNNEL_KEY_UNINITIALIZED:
1364 t->estate = CADET_TUNNEL_KEY_SENT;
1366 case CADET_TUNNEL_KEY_SENT:
1368 case CADET_TUNNEL_KEY_OK:
1369 t->estate = CADET_TUNNEL_KEY_REKEY;
1371 case CADET_TUNNEL_KEY_PING:
1372 case CADET_TUNNEL_KEY_REKEY:
1376 LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
1379 // FIXME exponential backoff
1380 struct GNUNET_TIME_Relative delay;
1382 delay = GNUNET_TIME_relative_divide (rekey_period, 16);
1383 delay = GNUNET_TIME_relative_min (delay, REKEY_WAIT);
1384 LOG (GNUNET_ERROR_TYPE_DEBUG, " next call in %s\n",
1385 GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
1386 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1391 * Our ephemeral key has changed, create new session key on all tunnels.
1393 * Each tunnel will start the Key Exchange with a random delay between
1394 * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
1395 * per second, on average.
1397 * @param cls Closure (size of the hashmap).
1398 * @param key Current public key.
1399 * @param value Value in the hash map (tunnel).
1401 * @return #GNUNET_YES, so we should continue to iterate,
1404 rekey_iterator (void *cls,
1405 const struct GNUNET_PeerIdentity *key,
1408 struct CadetTunnel *t = value;
1409 struct GNUNET_TIME_Relative delay;
1410 long n = (long) cls;
1413 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
1416 if (GNUNET_YES == GCT_is_loopback (t))
1419 r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
1420 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
1421 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1428 * Create a new ephemeral key and key message, schedule next rekeying.
1430 * @param cls Closure (unused).
1431 * @param tc TaskContext.
1434 rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1436 struct GNUNET_TIME_Absolute time;
1439 rekey_task = GNUNET_SCHEDULER_NO_TASK;
1441 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1444 GNUNET_free_non_null (my_ephemeral_key);
1445 my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
1447 time = GNUNET_TIME_absolute_get ();
1448 kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
1449 time = GNUNET_TIME_absolute_add (time, rekey_period);
1450 time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
1451 kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
1452 GNUNET_CRYPTO_ecdhe_key_get_public (my_ephemeral_key, &kx_msg.ephemeral_key);
1454 GNUNET_assert (GNUNET_OK ==
1455 GNUNET_CRYPTO_eddsa_sign (my_private_key,
1457 &kx_msg.signature));
1459 n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
1460 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
1462 rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period, &rekey, NULL);
1467 * Called only on shutdown, destroy every tunnel.
1469 * @param cls Closure (unused).
1470 * @param key Current public key.
1471 * @param value Value in the hash map (tunnel).
1473 * @return #GNUNET_YES, so we should continue to iterate,
1476 destroy_iterator (void *cls,
1477 const struct GNUNET_PeerIdentity *key,
1480 struct CadetTunnel *t = value;
1482 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
1489 * Notify remote peer that we don't know a channel he is talking about,
1490 * probably CHANNEL_DESTROY was missed.
1492 * @param t Tunnel on which to notify.
1493 * @param gid ID of the channel.
1496 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
1498 struct GNUNET_CADET_ChannelManage msg;
1500 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
1501 msg.header.size = htons (sizeof (msg));
1502 msg.chid = htonl (gid);
1504 LOG (GNUNET_ERROR_TYPE_DEBUG,
1505 "WARNING destroying unknown channel %u on tunnel %s\n",
1507 send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
1512 * Demultiplex data per channel and call appropriate channel handler.
1514 * @param t Tunnel on which the data came.
1515 * @param msg Data message.
1516 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1517 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1518 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1519 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1522 handle_data (struct CadetTunnel *t,
1523 const struct GNUNET_CADET_Data *msg,
1526 struct CadetChannel *ch;
1530 size = ntohs (msg->header.size);
1532 sizeof (struct GNUNET_CADET_Data) +
1533 sizeof (struct GNUNET_MessageHeader))
1538 LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
1539 GC_m2s (ntohs (msg[1].header.type)));
1542 ch = GCT_get_channel (t, ntohl (msg->chid));
1545 GNUNET_STATISTICS_update (stats, "# data on unknown channel",
1547 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
1549 send_channel_destroy (t, ntohl (msg->chid));
1553 GCCH_handle_data (ch, msg, fwd);
1558 * Demultiplex data ACKs per channel and update appropriate channel buffer info.
1560 * @param t Tunnel on which the DATA ACK came.
1561 * @param msg DATA ACK message.
1562 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1563 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1564 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1565 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1568 handle_data_ack (struct CadetTunnel *t,
1569 const struct GNUNET_CADET_DataACK *msg,
1572 struct CadetChannel *ch;
1576 size = ntohs (msg->header.size);
1577 if (size != sizeof (struct GNUNET_CADET_DataACK))
1584 ch = GCT_get_channel (t, ntohl (msg->chid));
1587 GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
1589 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1594 GCCH_handle_data_ack (ch, msg, fwd);
1599 * Handle channel create.
1601 * @param t Tunnel on which the data came.
1602 * @param msg Data message.
1605 handle_ch_create (struct CadetTunnel *t,
1606 const struct GNUNET_CADET_ChannelCreate *msg)
1608 struct CadetChannel *ch;
1612 size = ntohs (msg->header.size);
1613 if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
1620 ch = GCT_get_channel (t, ntohl (msg->chid));
1621 if (NULL != ch && ! GCT_is_loopback (t))
1623 /* Probably a retransmission, safe to ignore */
1624 LOG (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
1626 ch = GCCH_handle_create (t, msg);
1628 GCT_add_channel (t, ch);
1634 * Handle channel NACK: check correctness and call channel handler for NACKs.
1636 * @param t Tunnel on which the NACK came.
1637 * @param msg NACK message.
1640 handle_ch_nack (struct CadetTunnel *t,
1641 const struct GNUNET_CADET_ChannelManage *msg)
1643 struct CadetChannel *ch;
1647 size = ntohs (msg->header.size);
1648 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1655 ch = GCT_get_channel (t, ntohl (msg->chid));
1658 GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
1660 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1665 GCCH_handle_nack (ch);
1670 * Handle a CHANNEL ACK (SYNACK/ACK).
1672 * @param t Tunnel on which the CHANNEL ACK came.
1673 * @param msg CHANNEL ACK message.
1674 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1675 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1676 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1677 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1680 handle_ch_ack (struct CadetTunnel *t,
1681 const struct GNUNET_CADET_ChannelManage *msg,
1684 struct CadetChannel *ch;
1688 size = ntohs (msg->header.size);
1689 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1696 ch = GCT_get_channel (t, ntohl (msg->chid));
1699 GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
1701 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1706 GCCH_handle_ack (ch, msg, fwd);
1711 * Handle a channel destruction message.
1713 * @param t Tunnel on which the message came.
1714 * @param msg Channel destroy message.
1715 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1716 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1717 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1718 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1721 handle_ch_destroy (struct CadetTunnel *t,
1722 const struct GNUNET_CADET_ChannelManage *msg,
1725 struct CadetChannel *ch;
1729 size = ntohs (msg->header.size);
1730 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1737 ch = GCT_get_channel (t, ntohl (msg->chid));
1740 /* Probably a retransmission, safe to ignore */
1744 GCCH_handle_destroy (ch, msg, fwd);
1749 * The peer's ephemeral key has changed: update the symmetrical keys.
1751 * @param t Tunnel this message came on.
1752 * @param msg Key eXchange message.
1755 handle_ephemeral (struct CadetTunnel *t,
1756 const struct GNUNET_CADET_KX_Ephemeral *msg)
1758 LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
1760 if (GNUNET_OK != check_ephemeral (t, msg))
1762 GNUNET_break_op (0);
1765 if (NULL == t->kx_ctx)
1767 if (0 != memcmp (&t->peers_ephemeral_key, &msg->ephemeral_key,
1768 sizeof (msg->ephemeral_key)))
1770 t->peers_ephemeral_key = msg->ephemeral_key;
1772 if (CADET_TUNNEL_KEY_OK == t->estate)
1774 t->estate = CADET_TUNNEL_KEY_REKEY;
1777 if (CADET_TUNNEL_KEY_SENT == t->estate)
1779 LOG (GNUNET_ERROR_TYPE_DEBUG, " our key was sent, sending ping\n");
1781 t->estate = CADET_TUNNEL_KEY_PING;
1787 * Peer wants to check our symmetrical keys by sending an encrypted challenge.
1788 * Answer with by retransmitting the challenge with the "opposite" key.
1790 * @param t Tunnel this message came on.
1791 * @param msg Key eXchange Ping message.
1794 handle_ping (struct CadetTunnel *t,
1795 const struct GNUNET_CADET_KX_Ping *msg)
1797 struct GNUNET_CADET_KX_Ping res;
1799 if (ntohs (msg->header.size) != sizeof (res))
1801 GNUNET_break_op (0);
1805 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PING for %s\n", GCT_2s (t));
1806 t_decrypt (t, &res.target, &msg->target, ping_encryption_size (), msg->iv);
1807 if (0 != memcmp (&my_full_id, &res.target, sizeof (my_full_id)))
1809 GNUNET_STATISTICS_update (stats, "# malformed PINGs", 1, GNUNET_NO);
1810 LOG (GNUNET_ERROR_TYPE_WARNING, " malformed PING on %s\n", GCT_2s (t));
1811 LOG (GNUNET_ERROR_TYPE_DEBUG, " e got %u\n", msg->nonce);
1812 LOG (GNUNET_ERROR_TYPE_DEBUG, " e towards %s\n", GNUNET_i2s (&msg->target));
1813 LOG (GNUNET_ERROR_TYPE_DEBUG, " got %u\n", res.nonce);
1814 LOG (GNUNET_ERROR_TYPE_DEBUG, " towards %s\n", GNUNET_i2s (&res.target));
1820 send_pong (t, res.nonce);
1825 * @brief Finish the Key eXchange and destroy the old keys.
1827 * @param cls Closure (Tunnel for which to finish the KX).
1828 * @param tc Task context.
1831 finish_kx (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1833 struct CadetTunnel *t = cls;
1835 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1838 LOG (GNUNET_ERROR_TYPE_INFO, "finish KX for %s\n", GCT_2s (t));
1840 GNUNET_free (t->kx_ctx);
1846 * Peer has answer to our challenge.
1847 * If answer is successful, consider the key exchange finished and clean
1848 * up all related state.
1850 * @param t Tunnel this message came on.
1851 * @param msg Key eXchange Pong message.
1854 handle_pong (struct CadetTunnel *t,
1855 const struct GNUNET_CADET_KX_Pong *msg)
1859 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
1860 if (GNUNET_SCHEDULER_NO_TASK == t->rekey_task)
1862 GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
1865 t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
1867 if (challenge != t->kx_ctx->challenge)
1869 LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
1870 LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
1871 challenge, msg->nonce, t->kx_ctx->challenge);
1876 GNUNET_SCHEDULER_cancel (t->rekey_task);
1877 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1879 /* Don't free the old keys right away, but after a delay.
1880 * Rationale: the KX could have happened over a very fast connection,
1881 * with payload traffic still signed with the old key stuck in a slower
1883 * Don't keep the keys longer than 1/4 the rekey period, and no longer than
1886 if (GNUNET_SCHEDULER_NO_TASK == t->kx_ctx->finish_task)
1888 struct GNUNET_TIME_Relative delay;
1890 delay = GNUNET_TIME_relative_divide (rekey_period, 4);
1891 delay = GNUNET_TIME_relative_min (delay, GNUNET_TIME_UNIT_MINUTES);
1892 t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_delayed (delay, finish_kx, t);
1894 GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
1899 * Demultiplex by message type and call appropriate handler for a message
1900 * towards a channel of a local tunnel.
1902 * @param t Tunnel this message came on.
1903 * @param msgh Message header.
1904 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1905 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1906 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1907 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1910 handle_decrypted (struct CadetTunnel *t,
1911 const struct GNUNET_MessageHeader *msgh,
1916 type = ntohs (msgh->type);
1917 LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
1921 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1922 /* Do nothing, connection aleady got updated. */
1923 GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
1926 case GNUNET_MESSAGE_TYPE_CADET_DATA:
1927 /* Don't send hop ACK, wait for client to ACK */
1928 handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
1931 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1932 handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
1935 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1936 handle_ch_create (t,
1937 (struct GNUNET_CADET_ChannelCreate *) msgh);
1940 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1942 (struct GNUNET_CADET_ChannelManage *) msgh);
1945 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1947 (struct GNUNET_CADET_ChannelManage *) msgh,
1951 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1952 handle_ch_destroy (t,
1953 (struct GNUNET_CADET_ChannelManage *) msgh,
1958 GNUNET_break_op (0);
1959 LOG (GNUNET_ERROR_TYPE_WARNING,
1960 "end-to-end message not known (%u)\n",
1961 ntohs (msgh->type));
1962 GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1966 /******************************************************************************/
1967 /******************************** API ***********************************/
1968 /******************************************************************************/
1971 * Decrypt and demultiplex by message type. Call appropriate handler
1972 * for every message.
1974 * @param t Tunnel this message came on.
1975 * @param msg Encrypted message.
1978 GCT_handle_encrypted (struct CadetTunnel *t,
1979 const struct GNUNET_CADET_Encrypted *msg)
1981 size_t size = ntohs (msg->header.size);
1982 size_t payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
1984 char cbuf [payload_size];
1985 struct GNUNET_MessageHeader *msgh;
1988 decrypted_size = t_decrypt_and_validate (t, cbuf, &msg[1], payload_size,
1989 msg->iv, &msg->hmac);
1991 if (-1 == decrypted_size)
1993 GNUNET_break_op (0);
1998 while (off < decrypted_size)
2002 msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
2003 msize = ntohs (msgh->size);
2004 if (msize < sizeof (struct GNUNET_MessageHeader))
2006 GNUNET_break_op (0);
2009 handle_decrypted (t, msgh, GNUNET_SYSERR);
2016 * Demultiplex an encapsulated KX message by message type.
2018 * @param t Tunnel on which the message came.
2019 * @param message Payload of KX message.
2022 GCT_handle_kx (struct CadetTunnel *t,
2023 const struct GNUNET_MessageHeader *message)
2027 type = ntohs (message->type);
2028 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received\n", type);
2031 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
2032 handle_ephemeral (t, (struct GNUNET_CADET_KX_Ephemeral *) message);
2035 case GNUNET_MESSAGE_TYPE_CADET_KX_PING:
2036 handle_ping (t, (struct GNUNET_CADET_KX_Ping *) message);
2039 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
2040 handle_pong (t, (struct GNUNET_CADET_KX_Pong *) message);
2044 GNUNET_break_op (0);
2045 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message not known (%u)\n", type);
2051 * Initialize the tunnel subsystem.
2053 * @param c Configuration handle.
2054 * @param key ECC private key, to derive all other keys and do crypto.
2057 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
2058 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
2060 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
2062 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
2065 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
2066 "CADET", "DEFAULT_TTL", "USING DEFAULT");
2070 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
2073 rekey_period = GNUNET_TIME_UNIT_DAYS;
2076 my_private_key = key;
2077 kx_msg.header.size = htons (sizeof (kx_msg));
2078 kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
2079 kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
2080 kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
2081 kx_msg.origin_identity = my_full_id;
2082 rekey_task = GNUNET_SCHEDULER_add_now (&rekey, NULL);
2084 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
2089 * Shut down the tunnel subsystem.
2094 if (GNUNET_SCHEDULER_NO_TASK != rekey_task)
2096 GNUNET_SCHEDULER_cancel (rekey_task);
2097 rekey_task = GNUNET_SCHEDULER_NO_TASK;
2099 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
2100 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
2107 * @param destination Peer this tunnel is towards.
2109 struct CadetTunnel *
2110 GCT_new (struct CadetPeer *destination)
2112 struct CadetTunnel *t;
2114 t = GNUNET_new (struct CadetTunnel);
2116 t->peer = destination;
2119 GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
2120 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2131 * Change the tunnel's connection state.
2133 * @param t Tunnel whose connection state to change.
2134 * @param cstate New connection state.
2137 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
2141 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
2142 GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
2143 if (myid != GCP_get_short_id (t->peer) &&
2144 CADET_TUNNEL_READY != t->cstate &&
2145 CADET_TUNNEL_READY == cstate)
2148 if (CADET_TUNNEL_KEY_OK == t->estate)
2150 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered send queued data\n");
2151 send_queued_data (t);
2153 else if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
2155 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered rekey\n");
2156 rekey_tunnel (t, NULL);
2161 if (CADET_TUNNEL_READY == cstate
2162 && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
2164 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered stop dht\n");
2165 GCP_stop_search (t->peer);
2170 * Change the tunnel encryption state.
2172 * @param t Tunnel whose encryption state to change.
2173 * @param state New encryption state.
2176 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
2180 LOG (GNUNET_ERROR_TYPE_DEBUG,
2181 "Tunnel %s estate was %s\n",
2182 GCP_2s (t->peer), estate2s (t->estate));
2183 LOG (GNUNET_ERROR_TYPE_DEBUG,
2184 "Tunnel %s estate is now %s\n",
2185 GCP_2s (t->peer), estate2s (state));
2186 if (myid != GCP_get_short_id (t->peer) &&
2187 CADET_TUNNEL_KEY_OK != t->estate && CADET_TUNNEL_KEY_OK == state)
2190 send_queued_data (t);
2198 * @brief Check if tunnel has too many connections, and remove one if necessary.
2200 * Currently this means the newest connection, unless it is a direct one.
2201 * Implemented as a task to avoid freeing a connection that is in the middle
2202 * of being created/processed.
2204 * @param cls Closure (Tunnel to check).
2205 * @param tc Task context.
2208 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2210 struct CadetTunnel *t = cls;
2212 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2215 if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
2217 struct CadetTConnection *iter;
2218 struct CadetTConnection *c;
2220 for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
2222 if ((NULL == c || iter->created.abs_value_us > c->created.abs_value_us)
2223 && GNUNET_NO == GCC_is_direct (iter->c))
2230 LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
2232 LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
2245 * Add a connection to a tunnel.
2248 * @param c Connection.
2251 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
2253 struct CadetTConnection *aux;
2255 GNUNET_assert (NULL != c);
2257 LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
2258 LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
2259 for (aux = t->connection_head; aux != NULL; aux = aux->next)
2263 aux = GNUNET_new (struct CadetTConnection);
2265 aux->created = GNUNET_TIME_absolute_get ();
2267 GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
2269 GNUNET_SCHEDULER_add_now (&trim_connections, t);
2274 * Mark a path as no longer valid for this tunnel: has been tried and failed.
2276 * @param t Tunnel to update.
2277 * @param path Invalid path to remove. Is destroyed after removal.
2280 GCT_remove_path (struct CadetTunnel *t, struct CadetPeerPath *path)
2282 GCP_remove_path (t->peer, path);
2287 * Remove a connection from a tunnel.
2290 * @param c Connection.
2293 GCT_remove_connection (struct CadetTunnel *t,
2294 struct CadetConnection *c)
2296 struct CadetTConnection *aux;
2297 struct CadetTConnection *next;
2299 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
2300 GCC_2s (c), GCT_2s (t));
2301 for (aux = t->connection_head; aux != NULL; aux = next)
2306 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
2311 /* Start new connections if needed */
2312 if (CONNECTIONS_PER_TUNNEL < GCT_count_connections (t)
2313 && GNUNET_SCHEDULER_NO_TASK == t->destroy_task
2314 && CADET_TUNNEL_SHUTDOWN != t->cstate
2315 && GNUNET_NO == shutting_down)
2317 LOG (GNUNET_ERROR_TYPE_DEBUG, " no more connections, getting new ones\n");
2318 t->cstate = CADET_TUNNEL_SEARCHING;
2319 GCP_connect (t->peer);
2323 /* If not marked as ready, no change is needed */
2324 if (CADET_TUNNEL_READY != t->cstate)
2327 /* Check if any connection is ready to maintaing cstate */
2328 for (aux = t->connection_head; aux != NULL; aux = aux->next)
2329 if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
2332 t->cstate = CADET_TUNNEL_WAITING;
2337 * Add a channel to a tunnel.
2340 * @param ch Channel.
2343 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2345 struct CadetTChannel *aux;
2347 GNUNET_assert (NULL != ch);
2349 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
2351 for (aux = t->channel_head; aux != NULL; aux = aux->next)
2353 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
2358 aux = GNUNET_new (struct CadetTChannel);
2360 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
2361 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
2363 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2365 GNUNET_SCHEDULER_cancel (t->destroy_task);
2366 t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2367 LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
2373 * Remove a channel from a tunnel.
2376 * @param ch Channel.
2379 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2381 struct CadetTChannel *aux;
2383 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
2384 for (aux = t->channel_head; aux != NULL; aux = aux->next)
2388 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
2389 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
2398 * Search for a channel by global ID.
2400 * @param t Tunnel containing the channel.
2401 * @param chid Public channel number.
2403 * @return channel handler, NULL if doesn't exist
2405 struct CadetChannel *
2406 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
2408 struct CadetTChannel *iter;
2413 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2415 if (GCCH_get_id (iter->ch) == chid)
2419 return NULL == iter ? NULL : iter->ch;
2424 * @brief Destroy a tunnel and free all resources.
2426 * Should only be called a while after the tunnel has been marked as destroyed,
2427 * in case there is a new channel added to the same peer shortly after marking
2428 * the tunnel. This way we avoid a new public key handshake.
2430 * @param cls Closure (tunnel to destroy).
2431 * @param tc Task context.
2434 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2436 struct CadetTunnel *t = cls;
2437 struct CadetTConnection *iter;
2439 LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
2440 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2442 LOG (GNUNET_ERROR_TYPE_WARNING,
2443 "Not destroying tunnel, due to shutdown. "
2444 "Tunnel at %p should have been freed by GCT_shutdown\n", t);
2447 t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2448 t->cstate = CADET_TUNNEL_SHUTDOWN;
2450 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2452 GCC_send_destroy (iter->c);
2459 * Tunnel is empty: destroy it.
2461 * Notifies all connections about the destruction.
2463 * @param t Tunnel to destroy.
2466 GCT_destroy_empty (struct CadetTunnel *t)
2468 if (GNUNET_YES == shutting_down)
2469 return; /* Will be destroyed immediately anyway */
2471 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2473 LOG (GNUNET_ERROR_TYPE_DEBUG,
2474 "Tunnel %s is already scheduled for destruction\n",
2477 /* should never happen, tunnel can only become empty once, and the
2478 * task identifier should be NO_TASK (cleaned when the tunnel was created
2479 * or became un-empty)
2484 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: destroying scheduled\n",
2487 t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
2488 &delayed_destroy, t);
2489 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llX\n",
2490 t, t->destroy_task);
2495 * Destroy tunnel if empty (no more channels).
2497 * @param t Tunnel to destroy if empty.
2500 GCT_destroy_if_empty (struct CadetTunnel *t)
2502 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
2503 if (1 < GCT_count_channels (t))
2506 GCT_destroy_empty (t);
2511 * Destroy the tunnel.
2513 * This function does not generate any warning traffic to clients or peers.
2516 * Cancel messages belonging to this tunnel queued to neighbors.
2517 * Free any allocated resources linked to the tunnel.
2519 * @param t The tunnel to destroy.
2522 GCT_destroy (struct CadetTunnel *t)
2524 struct CadetTConnection *iter_c;
2525 struct CadetTConnection *next_c;
2526 struct CadetTChannel *iter_ch;
2527 struct CadetTChannel *next_ch;
2532 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
2534 GNUNET_break (GNUNET_YES ==
2535 GNUNET_CONTAINER_multipeermap_remove (tunnels,
2536 GCP_get_id (t->peer), t));
2538 for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
2540 next_c = iter_c->next;
2541 GCC_destroy (iter_c->c);
2543 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
2545 next_ch = iter_ch->next;
2546 GCCH_destroy (iter_ch->ch);
2547 /* Should only happen on shutdown, but it's ok. */
2550 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2552 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling %llX\n", t->destroy_task);
2553 GNUNET_SCHEDULER_cancel (t->destroy_task);
2554 t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2557 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
2558 GCP_set_tunnel (t->peer, NULL);
2560 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
2562 GNUNET_SCHEDULER_cancel (t->rekey_task);
2563 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
2565 if (NULL != t->kx_ctx)
2567 if (GNUNET_SCHEDULER_NO_TASK != t->kx_ctx->finish_task)
2568 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
2569 GNUNET_free (t->kx_ctx);
2576 * @brief Use the given path for the tunnel.
2577 * Update the next and prev hops (and RCs).
2578 * (Re)start the path refresh in case the tunnel is locally owned.
2580 * @param t Tunnel to update.
2581 * @param p Path to use.
2583 * @return Connection created.
2585 struct CadetConnection *
2586 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
2588 struct CadetConnection *c;
2589 struct GNUNET_CADET_Hash cid;
2590 unsigned int own_pos;
2592 if (NULL == t || NULL == p)
2598 if (CADET_TUNNEL_SHUTDOWN == t->cstate)
2604 for (own_pos = 0; own_pos < p->length; own_pos++)
2606 if (p->peers[own_pos] == myid)
2609 if (own_pos >= p->length)
2611 GNUNET_break_op (0);
2615 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
2616 c = GCC_new (&cid, t, p, own_pos);
2619 /* Path was flawed */
2622 GCT_add_connection (t, c);
2628 * Count established (ready) connections of a tunnel.
2630 * @param t Tunnel on which to count.
2632 * @return Number of connections.
2635 GCT_count_connections (struct CadetTunnel *t)
2637 struct CadetTConnection *iter;
2643 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2644 if (CADET_CONNECTION_DESTROYED != GCC_get_state (iter->c))
2651 * Count channels of a tunnel.
2653 * @param t Tunnel on which to count.
2655 * @return Number of channels.
2658 GCT_count_channels (struct CadetTunnel *t)
2660 struct CadetTChannel *iter;
2663 for (count = 0, iter = t->channel_head;
2665 iter = iter->next, count++) /* skip */;
2672 * Get the connectivity state of a tunnel.
2676 * @return Tunnel's connectivity state.
2678 enum CadetTunnelCState
2679 GCT_get_cstate (struct CadetTunnel *t)
2684 return (enum CadetTunnelCState) -1;
2691 * Get the encryption state of a tunnel.
2695 * @return Tunnel's encryption state.
2697 enum CadetTunnelEState
2698 GCT_get_estate (struct CadetTunnel *t)
2703 return (enum CadetTunnelEState) -1;
2709 * Get the maximum buffer space for a tunnel towards a local client.
2713 * @return Biggest buffer space offered by any channel in the tunnel.
2716 GCT_get_channels_buffer (struct CadetTunnel *t)
2718 struct CadetTChannel *iter;
2719 unsigned int buffer;
2720 unsigned int ch_buf;
2722 if (NULL == t->channel_head)
2724 /* Probably getting buffer for a channel create/handshake. */
2729 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2731 ch_buf = get_channel_buffer (iter);
2732 if (ch_buf > buffer)
2740 * Get the total buffer space for a tunnel for P2P traffic.
2744 * @return Buffer space offered by all connections in the tunnel.
2747 GCT_get_connections_buffer (struct CadetTunnel *t)
2749 struct CadetTConnection *iter;
2750 unsigned int buffer;
2752 if (GNUNET_NO == is_ready (t))
2754 if (count_queued_data (t) > 3)
2761 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2763 if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
2767 buffer += get_connection_buffer (iter);
2775 * Get the tunnel's destination.
2779 * @return ID of the destination peer.
2781 const struct GNUNET_PeerIdentity *
2782 GCT_get_destination (struct CadetTunnel *t)
2784 return GCP_get_id (t->peer);
2789 * Get the tunnel's next free global channel ID.
2793 * @return GID of a channel free to use.
2796 GCT_get_next_chid (struct CadetTunnel *t)
2798 CADET_ChannelNumber chid;
2799 CADET_ChannelNumber mask;
2802 /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
2803 * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
2804 * If peer's ID is bigger, start at 0x4... bit 30 = 1
2806 result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
2811 t->next_chid |= mask;
2813 while (NULL != GCT_get_channel (t, t->next_chid))
2815 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
2816 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
2817 t->next_chid |= mask;
2819 chid = t->next_chid;
2820 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
2821 t->next_chid |= mask;
2828 * Send ACK on one or more channels due to buffer in connections.
2830 * @param t Channel which has some free buffer space.
2833 GCT_unchoke_channels (struct CadetTunnel *t)
2835 struct CadetTChannel *iter;
2836 unsigned int buffer;
2837 unsigned int channels = GCT_count_channels (t);
2838 unsigned int choked_n;
2839 struct CadetChannel *choked[channels];
2841 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
2842 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
2843 if (NULL != t->channel_head)
2844 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
2846 /* Get buffer space */
2847 buffer = GCT_get_connections_buffer (t);
2853 /* Count and remember choked channels */
2855 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2857 if (GNUNET_NO == get_channel_allowed (iter))
2859 choked[choked_n++] = iter->ch;
2863 /* Unchoke random channels */
2864 while (0 < buffer && 0 < choked_n)
2866 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2868 GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
2871 choked[r] = choked[choked_n];
2877 * Send ACK on one or more connections due to buffer space to the client.
2879 * Iterates all connections of the tunnel and sends ACKs appropriately.
2884 GCT_send_connection_acks (struct CadetTunnel *t)
2886 struct CadetTConnection *iter;
2889 uint32_t allow_per_connection;
2891 unsigned int buffer;
2893 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
2902 buffer = GCT_get_channels_buffer (t);
2903 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer %u\n", buffer);
2905 /* Count connections, how many messages are already allowed */
2906 cs = GCT_count_connections (t);
2907 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2909 allowed += get_connection_allowed (iter);
2911 LOG (GNUNET_ERROR_TYPE_DEBUG, " allowed %u\n", allowed);
2913 /* Make sure there is no overflow */
2914 if (allowed > buffer)
2919 /* Authorize connections to send more data */
2920 to_allow = buffer; /* - allowed; */
2922 for (iter = t->connection_head;
2923 NULL != iter && to_allow > 0;
2926 allow_per_connection = to_allow/cs;
2927 to_allow -= allow_per_connection;
2929 if (get_connection_allowed (iter) > 64 / 3)
2933 GCC_allow (iter->c, allow_per_connection,
2934 GCC_is_origin (iter->c, GNUNET_NO));
2937 GNUNET_break (to_allow == 0);
2942 * Cancel a previously sent message while it's in the queue.
2944 * ONLY can be called before the continuation given to the send function
2945 * is called. Once the continuation is called, the message is no longer in the
2948 * @param q Handle to the queue.
2951 GCT_cancel (struct CadetTunnelQueue *q)
2956 /* tun_message_sent() will be called and free q */
2958 else if (NULL != q->tqd)
2960 unqueue_data (q->tqd);
2962 if (NULL != q->cont)
2963 q->cont (q->cont_cls, NULL, q, 0, 0);
2974 * Sends an already built message on a tunnel, encrypting it and
2975 * choosing the best connection if not provided.
2977 * @param message Message to send. Function modifies it.
2978 * @param t Tunnel on which this message is transmitted.
2979 * @param c Connection to use (autoselect if NULL).
2980 * @param force Force the tunnel to take the message (buffer overfill).
2981 * @param cont Continuation to call once message is really sent.
2982 * @param cont_cls Closure for @c cont.
2984 * @return Handle to cancel message. NULL if @c cont is NULL.
2986 struct CadetTunnelQueue *
2987 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
2988 struct CadetTunnel *t, struct CadetConnection *c,
2989 int force, GCT_sent cont, void *cont_cls)
2991 return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
2996 * Is the tunnel directed towards the local peer?
3000 * @return #GNUNET_YES if it is loopback.
3003 GCT_is_loopback (const struct CadetTunnel *t)
3005 return (myid == GCP_get_short_id (t->peer));
3010 * Is the tunnel this path already?
3015 * @return #GNUNET_YES a connection uses this path.
3018 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
3020 struct CadetTConnection *iter;
3022 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3023 if (GCC_get_path (iter->c) == p)
3031 * Get a cost of a path for a tunnel considering existing connections.
3034 * @param path Candidate path.
3036 * @return Cost of the path (path length + number of overlapping nodes)
3039 GCT_get_path_cost (const struct CadetTunnel *t,
3040 const struct CadetPeerPath *path)
3042 struct CadetTConnection *iter;
3043 const struct CadetPeerPath *aux;
3044 unsigned int overlap;
3052 GNUNET_assert (NULL != t);
3054 for (i = 0; i < path->length; i++)
3056 for (iter = t->connection_head; NULL != iter; iter = iter->next)
3058 aux = GCC_get_path (iter->c);
3062 for (j = 0; j < aux->length; j++)
3064 if (path->peers[i] == aux->peers[j])
3072 return path->length + overlap;
3077 * Get the static string for the peer this tunnel is directed.
3081 * @return Static string the destination peer's ID.
3084 GCT_2s (const struct CadetTunnel *t)
3089 return GCP_2s (t->peer);
3093 /******************************************************************************/
3094 /***************************** INFO/DEBUG *******************************/
3095 /******************************************************************************/
3098 * Log all possible info about the tunnel state.
3100 * @param t Tunnel to debug.
3101 * @param level Debug level to use.
3104 GCT_debug (const struct CadetTunnel *t, enum GNUNET_ErrorType level)
3106 struct CadetTChannel *iterch;
3107 struct CadetTConnection *iterc;
3109 LOG (level, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
3110 LOG (level, "TTT cstate %s, estate %s\n",
3111 cstate2s (t->cstate), estate2s (t->estate));
3112 LOG (level, "TTT kx_ctx %p, rekey_task %u\n", t->kx_ctx, t->rekey_task);
3113 LOG (level, "TTT tq_head %p, tq_tail %p\n", t->tq_head, t->tq_tail);
3114 LOG (level, "TTT destroy %u\n", t->destroy_task);
3116 LOG (level, "TTT channels:\n");
3117 for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
3119 LOG (level, "TTT - %s\n", GCCH_2s (iterch->ch));
3122 LOG (level, "TTT connections:\n");
3123 for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
3125 LOG (level, "TTT - %s [%u] buf: %u/%u (qn %u/%u)\n",
3126 GCC_2s (iterc->c), GCC_get_state (iterc->c),
3127 GCC_get_buffer (iterc->c, GNUNET_YES),
3128 GCC_get_buffer (iterc->c, GNUNET_NO),
3129 GCC_get_qn (iterc->c, GNUNET_YES),
3130 GCC_get_qn (iterc->c, GNUNET_NO));
3133 LOG (level, "TTT DEBUG TUNNEL END\n");
3138 * Iterate all tunnels.
3140 * @param iter Iterator.
3141 * @param cls Closure for @c iter.
3144 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
3146 GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
3151 * Count all tunnels.
3153 * @return Number of tunnels to remote peers kept by this peer.
3156 GCT_count_all (void)
3158 return GNUNET_CONTAINER_multipeermap_size (tunnels);
3163 * Iterate all connections of a tunnel.
3165 * @param t Tunnel whose connections to iterate.
3166 * @param iter Iterator.
3167 * @param cls Closure for @c iter.
3170 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
3172 struct CadetTConnection *ct;
3174 for (ct = t->connection_head; NULL != ct; ct = ct->next)
3180 * Iterate all channels of a tunnel.
3182 * @param t Tunnel whose channels to iterate.
3183 * @param iter Iterator.
3184 * @param cls Closure for @c iter.
3187 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
3189 struct CadetTChannel *cht;
3191 for (cht = t->channel_head; NULL != cht; cht = cht->next)
3192 iter (cls, cht->ch);