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 /******************************************************************************/
42 /******************************** STRUCTS **********************************/
43 /******************************************************************************/
47 struct CadetTChannel *next;
48 struct CadetTChannel *prev;
49 struct CadetChannel *ch;
54 * Connection list and metadata.
56 struct CadetTConnection
61 struct CadetTConnection *next;
66 struct CadetTConnection *prev;
71 struct CadetConnection *c;
74 * Creation time, to keep oldest connection alive.
76 struct GNUNET_TIME_Absolute created;
79 * Connection throughput, to keep fastest connection alive.
85 * Structure used during a Key eXchange.
87 struct CadetTunnelKXCtx
90 * Encryption ("our") old key, for encrypting traffic sent by us
91 * end before the key exchange is finished or times out.
93 struct GNUNET_CRYPTO_SymmetricSessionKey e_key_old;
96 * Decryption ("their") old key, for decrypting traffic sent by the
97 * other end before the key exchange started.
99 struct GNUNET_CRYPTO_SymmetricSessionKey d_key_old;
102 * Challenge to send in a ping and expect in the pong.
107 * When the rekey started. One minute after this the new key will be used.
109 struct GNUNET_TIME_Absolute rekey_start_time;
113 * Struct containing all information regarding a tunnel to a peer.
118 * Endpoint of the tunnel.
120 struct CadetPeer *peer;
123 * State of the tunnel connectivity.
125 enum CadetTunnelCState cstate;
128 * State of the tunnel encryption.
130 enum CadetTunnelEState estate;
133 * Key eXchange context.
135 struct CadetTunnelKXCtx *kx_ctx;
138 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own ephemeral
141 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
144 * Encryption ("our") key.
146 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
149 * Decryption ("their") key.
151 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
154 * Task to start the rekey process.
156 GNUNET_SCHEDULER_TaskIdentifier rekey_task;
159 * Paths that are actively used to reach the destination peer.
161 struct CadetTConnection *connection_head;
162 struct CadetTConnection *connection_tail;
165 * Next connection number.
170 * Channels inside this tunnel.
172 struct CadetTChannel *channel_head;
173 struct CadetTChannel *channel_tail;
176 * Channel ID for the next created channel.
178 CADET_ChannelNumber next_chid;
181 * Destroy flag: if true, destroy on last message.
183 GNUNET_SCHEDULER_TaskIdentifier destroy_task;
186 * Queued messages, to transmit once tunnel gets connected.
188 struct CadetTunnelDelayed *tq_head;
189 struct CadetTunnelDelayed *tq_tail;
194 * Struct used to save messages in a non-ready tunnel to send once connected.
196 struct CadetTunnelDelayed
201 struct CadetTunnelDelayed *next;
202 struct CadetTunnelDelayed *prev;
207 struct CadetTunnel *t;
210 * Tunnel queue given to the channel to cancel request. Update on send_queued.
212 struct CadetTunnelQueue *tq;
217 /* struct GNUNET_MessageHeader *msg; */
222 * Handle for messages queued but not yet sent.
224 struct CadetTunnelQueue
227 * Connection queue handle, to cancel if necessary.
229 struct CadetConnectionQueue *cq;
232 * Handle in case message hasn't been given to a connection yet.
234 struct CadetTunnelDelayed *tqd;
237 * Continuation to call once sent.
242 * Closure for @c cont.
248 /******************************************************************************/
249 /******************************* GLOBALS ***********************************/
250 /******************************************************************************/
253 * Global handle to the statistics service.
255 extern struct GNUNET_STATISTICS_Handle *stats;
258 * Local peer own ID (memory efficient handle).
260 extern GNUNET_PEER_Id myid;
263 * Local peer own ID (full value).
265 extern struct GNUNET_PeerIdentity my_full_id;
269 * Don't try to recover tunnels if shutting down.
271 extern int shutting_down;
275 * Set of all tunnels, in order to trigger a new exchange on rekey.
276 * Indexed by peer's ID.
278 static struct GNUNET_CONTAINER_MultiPeerMap *tunnels;
281 * Default TTL for payload packets.
283 static unsigned long long default_ttl;
288 const static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
291 * Own ephemeral private key.
293 static struct GNUNET_CRYPTO_EcdhePrivateKey *my_ephemeral_key;
296 * Cached message used to perform a key exchange.
298 static struct GNUNET_CADET_KX_Ephemeral kx_msg;
301 * Task to generate a new ephemeral key.
303 static GNUNET_SCHEDULER_TaskIdentifier rekey_task;
308 static struct GNUNET_TIME_Relative rekey_period;
310 /******************************************************************************/
311 /******************************** STATIC ***********************************/
312 /******************************************************************************/
315 * Get string description for tunnel connectivity state.
317 * @param cs Tunnel state.
319 * @return String representation.
322 cstate2s (enum CadetTunnelCState cs)
324 static char buf[128];
328 case CADET_TUNNEL3_NEW:
329 return "CADET_TUNNEL3_NEW";
330 case CADET_TUNNEL3_SEARCHING:
331 return "CADET_TUNNEL3_SEARCHING";
332 case CADET_TUNNEL3_WAITING:
333 return "CADET_TUNNEL3_WAITING";
334 case CADET_TUNNEL3_READY:
335 return "CADET_TUNNEL3_READY";
338 sprintf (buf, "%u (UNKNOWN STATE)", cs);
346 * Get string description for tunnel encryption state.
348 * @param es Tunnel state.
350 * @return String representation.
353 estate2s (enum CadetTunnelEState es)
355 static char buf[128];
359 case CADET_TUNNEL3_KEY_UNINITIALIZED:
360 return "CADET_TUNNEL3_KEY_UNINITIALIZED";
361 case CADET_TUNNEL3_KEY_SENT:
362 return "CADET_TUNNEL3_KEY_SENT";
363 case CADET_TUNNEL3_KEY_PING:
364 return "CADET_TUNNEL3_KEY_PING";
365 case CADET_TUNNEL3_KEY_OK:
366 return "CADET_TUNNEL3_KEY_OK";
369 sprintf (buf, "%u (UNKNOWN STATE)", es);
377 * @brief Check if tunnel is ready to send traffic.
379 * Tunnel must be connected and with encryption correctly set up.
381 * @param t Tunnel to check.
383 * @return #GNUNET_YES if ready, #GNUNET_NO otherwise
386 is_ready (struct CadetTunnel *t)
391 ready = (CADET_TUNNEL3_READY == t->cstate && CADET_TUNNEL3_KEY_OK == t->estate);
392 ready = ready || GCT_is_loopback (t);
398 * Ephemeral key message purpose size.
400 * @return Size of the part of the ephemeral key message that must be signed.
403 ephemeral_purpose_size (void)
405 return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
406 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
407 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
408 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
409 sizeof (struct GNUNET_PeerIdentity);
414 * Size of the encrypted part of a ping message.
416 * @return Size of the encrypted part of a ping message.
419 ping_encryption_size (void)
421 return sizeof (struct GNUNET_PeerIdentity) + sizeof (uint32_t);
426 * Get the channel's buffer. ONLY FOR NON-LOOPBACK CHANNELS!!
428 * @param tch Tunnel's channel handle.
430 * @return Amount of messages the channel can still buffer towards the client.
433 get_channel_buffer (const struct CadetTChannel *tch)
437 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
438 fwd = GCCH_is_origin (tch->ch, GNUNET_YES);
440 return GCCH_get_buffer (tch->ch, fwd);
445 * Get the channel's allowance status.
447 * @param tch Tunnel's channel handle.
449 * @return #GNUNET_YES if we allowed the client to send data to us.
452 get_channel_allowed (const struct CadetTChannel *tch)
456 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
457 fwd = GCCH_is_origin (tch->ch, GNUNET_YES);
459 return GCCH_get_allowed (tch->ch, fwd);
464 * Get the connection's buffer.
466 * @param tc Tunnel's connection handle.
468 * @return Amount of messages the connection can still buffer.
471 get_connection_buffer (const struct CadetTConnection *tc)
475 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
476 fwd = GCC_is_origin (tc->c, GNUNET_YES);
478 return GCC_get_buffer (tc->c, fwd);
483 * Get the connection's allowance.
485 * @param tc Tunnel's connection handle.
487 * @return Amount of messages we have allowed the next peer to send us.
490 get_connection_allowed (const struct CadetTConnection *tc)
494 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
495 fwd = GCC_is_origin (tc->c, GNUNET_YES);
497 return GCC_get_allowed (tc->c, fwd);
502 * Check that a ephemeral key message s well formed and correctly signed.
504 * @param t Tunnel on which the message came.
505 * @param msg The ephemeral key message.
507 * @return GNUNET_OK if message is fine, GNUNET_SYSERR otherwise.
510 check_ephemeral (struct CadetTunnel *t,
511 const struct GNUNET_CADET_KX_Ephemeral *msg)
513 /* Check message size */
514 if (ntohs (msg->header.size) != sizeof (struct GNUNET_CADET_KX_Ephemeral))
515 return GNUNET_SYSERR;
517 /* Check signature size */
518 if (ntohl (msg->purpose.size) != ephemeral_purpose_size ())
519 return GNUNET_SYSERR;
522 if (0 != memcmp (&msg->origin_identity,
523 GCP_get_id (t->peer),
524 sizeof (struct GNUNET_PeerIdentity)))
525 return GNUNET_SYSERR;
527 /* Check signature */
529 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_CADET_KX,
532 &msg->origin_identity.public_key))
533 return GNUNET_SYSERR;
542 * @param t Tunnel to get keys from.
543 * @param plaintext Content to HMAC.
544 * @param size Size of @c plaintext.
545 * @param iv Initialization vector for the message.
546 * @param outgoing Is this an outgoing message that we encrypted?
547 * @param hmac Destination to store the HMAC.
550 t_hmac (struct CadetTunnel *t, const void *plaintext, size_t size, uint32_t iv,
551 int outgoing, struct GNUNET_CADET_Hash *hmac)
553 struct GNUNET_CRYPTO_AuthKey auth_key;
554 static const char ctx[] = "cadet authentication key";
555 struct GNUNET_CRYPTO_SymmetricSessionKey *key;
556 struct GNUNET_HashCode hash;
558 key = outgoing ? &t->e_key : &t->d_key;
559 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
564 GNUNET_CRYPTO_hmac (&auth_key, plaintext, size, &hash);
565 memcpy (hmac, &hash, sizeof (*hmac));
570 * Encrypt data with the tunnel key.
572 * @param t Tunnel whose key to use.
573 * @param dst Destination for the encrypted data.
574 * @param src Source of the plaintext. Can overlap with @c dst.
575 * @param size Size of the plaintext.
576 * @param iv Initialization Vector to use.
579 t_encrypt (struct CadetTunnel *t,
580 void *dst, const void *src,
581 size_t size, uint32_t iv)
583 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
584 struct GNUNET_CRYPTO_SymmetricSessionKey *e_key;
587 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt start\n");
588 if (NULL != t->kx_ctx)
590 struct GNUNET_TIME_Relative age;
592 age = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
593 LOG (GNUNET_ERROR_TYPE_DEBUG,
594 " key exchange in progress, started %s ago\n",
595 GNUNET_STRINGS_relative_time_to_string (age, GNUNET_YES));
596 if (age.rel_value_us < GNUNET_TIME_UNIT_MINUTES.rel_value_us)
598 LOG (GNUNET_ERROR_TYPE_DEBUG, " using old key\n");
599 e_key = &t->kx_ctx->e_key_old;
603 LOG (GNUNET_ERROR_TYPE_DEBUG, " using new key\n");
611 GNUNET_CRYPTO_symmetric_derive_iv (&siv, e_key, &iv, sizeof (iv), NULL);
612 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt IV derived\n");
613 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, e_key, &siv, dst);
614 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt end\n");
621 * Decrypt and verify data with the appropriate tunnel key.
623 * @param key Key to use.
624 * @param dst Destination for the plaintext.
625 * @param src Source of the encrypted data. Can overlap with @c dst.
626 * @param size Size of the encrypted data.
627 * @param iv Initialization Vector to use.
629 * @return Size of the decrypted data, -1 if an error was encountered.
632 decrypt (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
633 void *dst, const void *src, size_t size, uint32_t iv)
635 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
638 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt start\n");
639 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv\n");
640 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
641 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv done\n");
642 out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, key, &siv, dst);
643 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt end\n");
650 * Decrypt and verify data with the most recent tunnel key.
652 * @param t Tunnel whose key to use.
653 * @param dst Destination for the plaintext.
654 * @param src Source of the encrypted data. Can overlap with @c dst.
655 * @param size Size of the encrypted data.
656 * @param iv Initialization Vector to use.
658 * @return Size of the decrypted data, -1 if an error was encountered.
661 t_decrypt (struct CadetTunnel *t, void *dst, const void *src,
662 size_t size, uint32_t iv)
664 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
665 struct GNUNET_CRYPTO_SymmetricSessionKey *key;
668 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_decrypt start\n");
669 if (t->estate == CADET_TUNNEL3_KEY_OK || t->estate == CADET_TUNNEL3_KEY_PING)
675 GNUNET_STATISTICS_update (stats, "# non decryptable data", 1, GNUNET_NO);
676 LOG (GNUNET_ERROR_TYPE_WARNING,
677 "got data on %s without a valid key\n",
683 out_size = decrypt (key, dst, src, size, iv);
690 * Decrypt and verify data with the appropriate tunnel key and verify that the
691 * data has not been altered since it was sent by the remote peer.
693 * @param t Tunnel whose key to use.
694 * @param dst Destination for the plaintext.
695 * @param src Source of the encrypted data. Can overlap with @c dst.
696 * @param size Size of the encrypted data.
697 * @param iv Initialization Vector to use.
698 * @param msg_hmac HMAC of the message, cannot be NULL.
700 * @return Size of the decrypted data, -1 if an error was encountered.
703 t_decrypt_and_validate (struct CadetTunnel *t,
704 void *dst, const void *src,
705 size_t size, uint32_t iv,
706 const struct GNUNET_CADET_Hash *msg_hmac)
708 struct GNUNET_CRYPTO_SymmetricSessionKey *key;
709 struct GNUNET_CADET_Hash hmac;
712 /* Try primary (newest) key */
714 decrypted_size = decrypt (key, dst, src, size, iv);
715 t_hmac (t, src, size, iv, GNUNET_NO, &hmac);
716 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
717 return decrypted_size;
719 /* If no key exchange is going on, we just failed */
720 if (NULL == t->kx_ctx)
722 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
723 "Failed checksum validation on tunnel %s with no KX\n",
725 GNUNET_STATISTICS_update (stats, "# wrong HMAC", 1, GNUNET_NO);
729 /* Try secondary (from previous KX period) key */
730 key = &t->kx_ctx->d_key_old;
731 decrypted_size = decrypt (key, dst, src, size, iv);
732 t_hmac (t, src, size, iv, GNUNET_NO, &hmac);
733 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
734 return decrypted_size;
736 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
737 "Failed checksum validation on tunnel %s with KX\n" place,
739 GNUNET_STATISTICS_update (stats, "# wrong HMAC", 1, GNUNET_NO);
745 * Create key material by doing ECDH on the local and remote ephemeral keys.
747 * @param key_material Where to store the key material.
748 * @param ephemeral_key Peer's public ephemeral key.
751 derive_key_material (struct GNUNET_HashCode *key_material,
752 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key)
755 GNUNET_CRYPTO_ecc_ecdh (my_ephemeral_key,
765 * Create a symmetic key from the identities of both ends and the key material
768 * @param key Destination for the generated key.
769 * @param sender ID of the peer that will encrypt with @c key.
770 * @param receiver ID of the peer that will decrypt with @c key.
771 * @param key_material Hash created with ECDH with the ephemeral keys.
774 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
775 const struct GNUNET_PeerIdentity *sender,
776 const struct GNUNET_PeerIdentity *receiver,
777 const struct GNUNET_HashCode *key_material)
779 const char salt[] = "CADET kx salt";
781 GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
783 key_material, sizeof (struct GNUNET_HashCode),
784 sender, sizeof (struct GNUNET_PeerIdentity),
785 receiver, sizeof (struct GNUNET_PeerIdentity),
791 * Derive the tunnel's keys using our own and the peer's ephemeral keys.
793 * @param t Tunnel for which to create the keys.
796 create_keys (struct CadetTunnel *t)
798 struct GNUNET_HashCode km;
800 derive_key_material (&km, &t->peers_ephemeral_key);
801 derive_symmertic (&t->e_key, &my_full_id, GCP_get_id (t->peer), &km);
802 derive_symmertic (&t->d_key, GCP_get_id (t->peer), &my_full_id, &km);
807 * Pick a connection on which send the next data message.
809 * @param t Tunnel on which to send the message.
811 * @return The connection on which to send the next message.
813 static struct CadetConnection *
814 tunnel_get_connection (struct CadetTunnel *t)
816 struct CadetTConnection *iter;
817 struct CadetConnection *best;
819 unsigned int lowest_q;
821 LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GCT_2s (t));
824 for (iter = t->connection_head; NULL != iter; iter = iter->next)
826 LOG (GNUNET_ERROR_TYPE_DEBUG, " connection %s: %u\n",
827 GCC_2s (iter->c), GCC_get_state (iter->c));
828 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
830 qn = GCC_get_qn (iter->c, GCC_is_origin (iter->c, GNUNET_YES));
831 LOG (GNUNET_ERROR_TYPE_DEBUG, " q_n %u, \n", qn);
839 LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GCC_2s (best));
845 * Callback called when a queued message is sent.
847 * Calculates the average time and connection packet tracking.
849 * @param cls Closure (TunnelQueue handle).
850 * @param c Connection this message was on.
851 * @param q Connection queue handle (unused).
852 * @param type Type of message sent.
853 * @param fwd Was this a FWD going message?
854 * @param size Size of the message.
857 tun_message_sent (void *cls,
858 struct CadetConnection *c,
859 struct CadetConnectionQueue *q,
860 uint16_t type, int fwd, size_t size)
862 struct CadetTunnelQueue *qt = cls;
863 struct CadetTunnel *t;
865 LOG (GNUNET_ERROR_TYPE_DEBUG, "tun_message_sent\n");
867 GNUNET_assert (NULL != qt->cont);
868 t = NULL == c ? NULL : GCC_get_tunnel (c);
869 qt->cont (qt->cont_cls, t, qt, type, size);
875 * Delete a queued message: either was sent or the channel was destroyed
876 * before the tunnel's key exchange had a chance to finish.
878 * @param tqd Delayed queue handle.
881 unqueue_data (struct CadetTunnelDelayed *tqd)
883 GNUNET_CONTAINER_DLL_remove (tqd->t->tq_head, tqd->t->tq_tail, tqd);
889 * Cache a message to be sent once tunnel is online.
891 * @param t Tunnel to hold the message.
892 * @param msg Message itself (copy will be made).
894 static struct CadetTunnelDelayed *
895 queue_data (struct CadetTunnel *t, const struct GNUNET_MessageHeader *msg)
897 struct CadetTunnelDelayed *tqd;
898 uint16_t size = ntohs (msg->size);
900 LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GCT_2s (t));
902 if (GNUNET_YES == is_ready (t))
908 tqd = GNUNET_malloc (sizeof (struct CadetTunnelDelayed) + size);
911 memcpy (&tqd[1], msg, size);
912 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
918 * Sends an already built message on a tunnel, encrypting it and
919 * choosing the best connection.
921 * @param message Message to send. Function modifies it.
922 * @param t Tunnel on which this message is transmitted.
923 * @param c Connection to use (autoselect if NULL).
924 * @param force Force the tunnel to take the message (buffer overfill).
925 * @param cont Continuation to call once message is really sent.
926 * @param cont_cls Closure for @c cont.
927 * @param existing_q In case this a transmission of previously queued data,
928 * this should be TunnelQueue given to the client.
931 * @return Handle to cancel message. NULL if @c cont is NULL.
933 static struct CadetTunnelQueue *
934 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
935 struct CadetTunnel *t, struct CadetConnection *c,
936 int force, GCT_sent cont, void *cont_cls,
937 struct CadetTunnelQueue *existing_q)
939 struct CadetTunnelQueue *tq;
940 struct GNUNET_CADET_Encrypted *msg;
941 size_t size = ntohs (message->size);
942 char cbuf[sizeof (struct GNUNET_CADET_Encrypted) + size];
948 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GCT_2s (t));
950 if (GNUNET_NO == is_ready (t))
952 struct CadetTunnelDelayed *tqd;
953 /* A non null existing_q indicates sending of queued data.
954 * Should only happen after tunnel becomes ready.
956 GNUNET_assert (NULL == existing_q);
957 tqd = queue_data (t, message);
960 tq = GNUNET_new (struct CadetTunnelQueue);
964 tq->cont_cls = cont_cls;
968 GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
970 iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
971 msg = (struct GNUNET_CADET_Encrypted *) cbuf;
972 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
974 GNUNET_assert (t_encrypt (t, &msg[1], message, size, iv) == size);
975 t_hmac (t, &msg[1], size, iv, GNUNET_YES, &msg->hmac);
976 msg->header.size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
979 c = tunnel_get_connection (t);
982 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task
983 || CADET_TUNNEL3_SEARCHING != t->cstate)
992 type = ntohs (message->type);
995 case GNUNET_MESSAGE_TYPE_CADET_DATA:
996 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
997 if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
998 mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
1000 mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
1002 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1003 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1004 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1005 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1006 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1007 msg->cid = *GCC_get_id (c);
1008 msg->ttl = htonl (default_ttl);
1013 LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
1015 fwd = GCC_is_origin (c, GNUNET_YES);
1019 GNUNET_break (NULL ==
1020 GCC_send_prebuilt_message (&msg->header, type, mid,
1021 c, fwd, force, NULL, NULL));
1024 if (NULL == existing_q)
1026 tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
1033 tq->cq = GCC_send_prebuilt_message (&msg->header, type, mid, c, fwd, force,
1034 &tun_message_sent, tq);
1036 tq->cont_cls = cont_cls;
1043 * Send all cached messages that we can, tunnel is online.
1045 * @param t Tunnel that holds the messages. Cannot be loopback.
1048 send_queued_data (struct CadetTunnel *t)
1050 struct CadetTunnelDelayed *tqd;
1051 struct CadetTunnelDelayed *next;
1054 LOG (GNUNET_ERROR_TYPE_DEBUG,
1055 "GCT_send_queued_data on tunnel %s\n",
1058 if (GCT_is_loopback (t))
1064 if (GNUNET_NO == is_ready (t))
1066 LOG (GNUNET_ERROR_TYPE_DEBUG, " not ready yet: %s/%s\n",
1067 estate2s (t->estate), cstate2s (t->cstate));
1071 room = GCT_get_connections_buffer (t);
1072 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
1073 LOG (GNUNET_ERROR_TYPE_DEBUG, " tq head: %p\n", t->tq_head);
1074 for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
1076 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
1079 send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
1080 tqd->t, NULL, GNUNET_YES,
1081 NULL != tqd->tq ? tqd->tq->cont : NULL,
1082 NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
1086 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
1091 * Sends key exchange message on a tunnel, choosing the best connection.
1092 * Should not be called on loopback tunnels.
1094 * @param t Tunnel on which this message is transmitted.
1095 * @param message Message to send. Function modifies it.
1098 send_kx (struct CadetTunnel *t,
1099 const struct GNUNET_MessageHeader *message)
1101 struct CadetConnection *c;
1102 struct GNUNET_CADET_KX *msg;
1103 size_t size = ntohs (message->size);
1104 char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
1108 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
1110 /* Avoid loopback. */
1111 if (GCT_is_loopback (t))
1113 LOG (GNUNET_ERROR_TYPE_DEBUG, " loopback!\n");
1118 /* Even if tunnel is being destroyed, send anyway.
1119 * Could be a response to a rekey initiated by remote peer,
1120 * who is trying to create a new channel!
1123 /* Must have a connection. */
1124 if (NULL == t->connection_head)
1126 GNUNET_break (CADET_TUNNEL3_SEARCHING == t->cstate);
1131 msg = (struct GNUNET_CADET_KX *) cbuf;
1132 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
1133 msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
1134 c = tunnel_get_connection (t);
1137 GNUNET_break (GNUNET_SCHEDULER_NO_TASK != t->destroy_task
1138 || CADET_TUNNEL3_READY != t->cstate);
1142 type = ntohs (message->type);
1145 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
1146 case GNUNET_MESSAGE_TYPE_CADET_KX_PING:
1147 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
1148 memcpy (&msg[1], message, size);
1151 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
1156 fwd = GCC_is_origin (t->connection_head->c, GNUNET_YES);
1157 /* TODO save handle and cancel in case of a unneeded retransmission */
1158 GCC_send_prebuilt_message (&msg->header, GNUNET_MESSAGE_TYPE_CADET_KX,
1159 message->type, c, fwd, GNUNET_YES, NULL, NULL);
1164 * Send the ephemeral key on a tunnel.
1166 * @param t Tunnel on which to send the key.
1169 send_ephemeral (struct CadetTunnel *t)
1171 LOG (GNUNET_ERROR_TYPE_INFO, "=> EPHM for %s\n", GCT_2s (t));
1173 kx_msg.sender_status = htonl (t->estate);
1174 send_kx (t, &kx_msg.header);
1178 * Send a ping message on a tunnel.
1180 * @param t Tunnel on which to send the ping.
1183 send_ping (struct CadetTunnel *t)
1185 struct GNUNET_CADET_KX_Ping msg;
1187 LOG (GNUNET_ERROR_TYPE_INFO, "=> PING for %s\n", GCT_2s (t));
1188 msg.header.size = htons (sizeof (msg));
1189 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PING);
1190 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1191 msg.target = *GCP_get_id (t->peer);
1192 msg.nonce = t->kx_ctx->challenge;
1194 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
1195 LOG (GNUNET_ERROR_TYPE_DEBUG, " towards %s\n", GNUNET_i2s (&msg.target));
1196 t_encrypt (t, &msg.target, &msg.target, ping_encryption_size(), msg.iv);
1197 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
1198 LOG (GNUNET_ERROR_TYPE_DEBUG, " e towards %s\n", GNUNET_i2s (&msg.target));
1200 send_kx (t, &msg.header);
1205 * Send a pong message on a tunnel.
1207 * @param t Tunnel on which to send the pong.
1208 * @param challenge Value sent in the ping that we have to send back.
1211 send_pong (struct CadetTunnel *t, uint32_t challenge)
1213 struct GNUNET_CADET_KX_Pong msg;
1215 LOG (GNUNET_ERROR_TYPE_INFO, "=> PONG for %s\n", GCT_2s (t));
1216 msg.header.size = htons (sizeof (msg));
1217 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
1218 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1219 msg.nonce = challenge;
1220 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
1221 t_encrypt (t, &msg.nonce, &msg.nonce, sizeof (msg.nonce), msg.iv);
1222 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
1224 send_kx (t, &msg.header);
1229 * Initiate a rekey with the remote peer.
1231 * @param cls Closure (tunnel).
1232 * @param tc TaskContext.
1235 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1237 struct CadetTunnel *t = cls;
1239 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1241 LOG (GNUNET_ERROR_TYPE_DEBUG, "Re-key Tunnel %s\n", GCT_2s (t));
1242 if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1245 if (NULL == t->kx_ctx)
1247 LOG (GNUNET_ERROR_TYPE_DEBUG, " new kx ctx\n");
1248 t->kx_ctx = GNUNET_new (struct CadetTunnelKXCtx);
1249 t->kx_ctx->challenge =
1250 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1251 t->kx_ctx->d_key_old = t->d_key;
1252 t->kx_ctx->e_key_old = t->e_key;
1254 t->kx_ctx->rekey_start_time = GNUNET_TIME_absolute_get ();
1255 LOG (GNUNET_ERROR_TYPE_DEBUG, " new challenge for %s: %u\n",
1256 GCT_2s (t), t->kx_ctx->challenge);
1263 case CADET_TUNNEL3_KEY_UNINITIALIZED:
1264 t->estate = CADET_TUNNEL3_KEY_SENT;
1266 case CADET_TUNNEL3_KEY_SENT:
1268 case CADET_TUNNEL3_KEY_PING:
1269 case CADET_TUNNEL3_KEY_OK:
1271 t->estate = CADET_TUNNEL3_KEY_PING;
1274 LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
1277 // FIXME exponential backoff
1278 LOG (GNUNET_ERROR_TYPE_DEBUG, " next call in %s\n",
1279 GNUNET_STRINGS_relative_time_to_string (REKEY_WAIT, GNUNET_YES));
1280 t->rekey_task = GNUNET_SCHEDULER_add_delayed (REKEY_WAIT, &rekey_tunnel, t);
1285 * Our ephemeral key has changed, create new session key on all tunnels.
1287 * Each tunnel will start the Key Exchange with a random delay between
1288 * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
1289 * per second, on average.
1291 * @param cls Closure (size of the hashmap).
1292 * @param key Current public key.
1293 * @param value Value in the hash map (tunnel).
1295 * @return #GNUNET_YES, so we should continue to iterate,
1298 rekey_iterator (void *cls,
1299 const struct GNUNET_PeerIdentity *key,
1302 struct CadetTunnel *t = value;
1303 struct GNUNET_TIME_Relative delay;
1304 long n = (long) cls;
1307 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
1310 if (GNUNET_YES == GCT_is_loopback (t))
1313 r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
1314 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
1315 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1322 * Create a new ephemeral key and key message, schedule next rekeying.
1324 * @param cls Closure (unused).
1325 * @param tc TaskContext.
1328 rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1330 struct GNUNET_TIME_Absolute time;
1333 rekey_task = GNUNET_SCHEDULER_NO_TASK;
1335 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1338 GNUNET_free_non_null (my_ephemeral_key);
1339 my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
1341 time = GNUNET_TIME_absolute_get ();
1342 kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
1343 time = GNUNET_TIME_absolute_add (time, rekey_period);
1344 time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
1345 kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
1346 GNUNET_CRYPTO_ecdhe_key_get_public (my_ephemeral_key, &kx_msg.ephemeral_key);
1348 GNUNET_assert (GNUNET_OK ==
1349 GNUNET_CRYPTO_eddsa_sign (my_private_key,
1351 &kx_msg.signature));
1353 n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
1354 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
1356 rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period, &rekey, NULL);
1361 * Called only on shutdown, destroy every tunnel.
1363 * @param cls Closure (unused).
1364 * @param key Current public key.
1365 * @param value Value in the hash map (tunnel).
1367 * @return #GNUNET_YES, so we should continue to iterate,
1370 destroy_iterator (void *cls,
1371 const struct GNUNET_PeerIdentity *key,
1374 struct CadetTunnel *t = value;
1376 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
1383 * Notify remote peer that we don't know a channel he is talking about,
1384 * probably CHANNEL_DESTROY was missed.
1386 * @param t Tunnel on which to notify.
1387 * @param gid ID of the channel.
1390 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
1392 struct GNUNET_CADET_ChannelManage msg;
1394 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
1395 msg.header.size = htons (sizeof (msg));
1396 msg.chid = htonl (gid);
1398 LOG (GNUNET_ERROR_TYPE_DEBUG,
1399 "WARNING destroying unknown channel %u on tunnel %s\n",
1401 send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
1406 * Demultiplex data per channel and call appropriate channel handler.
1408 * @param t Tunnel on which the data came.
1409 * @param msg Data message.
1410 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1411 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1412 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1413 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1416 handle_data (struct CadetTunnel *t,
1417 const struct GNUNET_CADET_Data *msg,
1420 struct CadetChannel *ch;
1424 size = ntohs (msg->header.size);
1426 sizeof (struct GNUNET_CADET_Data) +
1427 sizeof (struct GNUNET_MessageHeader))
1432 LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
1433 GC_m2s (ntohs (msg[1].header.type)));
1436 ch = GCT_get_channel (t, ntohl (msg->chid));
1439 GNUNET_STATISTICS_update (stats, "# data on unknown channel",
1441 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
1443 send_channel_destroy (t, ntohl (msg->chid));
1447 GCCH_handle_data (ch, msg, fwd);
1452 * Demultiplex data ACKs per channel and update appropriate channel buffer info.
1454 * @param t Tunnel on which the DATA ACK came.
1455 * @param msg DATA ACK message.
1456 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1457 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1458 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1459 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1462 handle_data_ack (struct CadetTunnel *t,
1463 const struct GNUNET_CADET_DataACK *msg,
1466 struct CadetChannel *ch;
1470 size = ntohs (msg->header.size);
1471 if (size != sizeof (struct GNUNET_CADET_DataACK))
1478 ch = GCT_get_channel (t, ntohl (msg->chid));
1481 GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
1483 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1488 GCCH_handle_data_ack (ch, msg, fwd);
1493 * Handle channel create.
1495 * @param t Tunnel on which the data came.
1496 * @param msg Data message.
1499 handle_ch_create (struct CadetTunnel *t,
1500 const struct GNUNET_CADET_ChannelCreate *msg)
1502 struct CadetChannel *ch;
1506 size = ntohs (msg->header.size);
1507 if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
1514 ch = GCT_get_channel (t, ntohl (msg->chid));
1515 if (NULL != ch && ! GCT_is_loopback (t))
1517 /* Probably a retransmission, safe to ignore */
1518 LOG (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
1520 ch = GCCH_handle_create (t, msg);
1522 GCT_add_channel (t, ch);
1528 * Handle channel NACK: check correctness and call channel handler for NACKs.
1530 * @param t Tunnel on which the NACK came.
1531 * @param msg NACK message.
1534 handle_ch_nack (struct CadetTunnel *t,
1535 const struct GNUNET_CADET_ChannelManage *msg)
1537 struct CadetChannel *ch;
1541 size = ntohs (msg->header.size);
1542 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1549 ch = GCT_get_channel (t, ntohl (msg->chid));
1552 GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
1554 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1559 GCCH_handle_nack (ch);
1564 * Handle a CHANNEL ACK (SYNACK/ACK).
1566 * @param t Tunnel on which the CHANNEL ACK came.
1567 * @param msg CHANNEL ACK message.
1568 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1569 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1570 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1571 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1574 handle_ch_ack (struct CadetTunnel *t,
1575 const struct GNUNET_CADET_ChannelManage *msg,
1578 struct CadetChannel *ch;
1582 size = ntohs (msg->header.size);
1583 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1590 ch = GCT_get_channel (t, ntohl (msg->chid));
1593 GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
1595 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1600 GCCH_handle_ack (ch, msg, fwd);
1606 * Handle a channel destruction message.
1608 * @param t Tunnel on which the message came.
1609 * @param msg Channel destroy message.
1610 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1611 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1612 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1613 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1616 handle_ch_destroy (struct CadetTunnel *t,
1617 const struct GNUNET_CADET_ChannelManage *msg,
1620 struct CadetChannel *ch;
1624 size = ntohs (msg->header.size);
1625 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1632 ch = GCT_get_channel (t, ntohl (msg->chid));
1635 /* Probably a retransmission, safe to ignore */
1639 GCCH_handle_destroy (ch, msg, fwd);
1644 * The peer's ephemeral key has changed: update the symmetrical keys.
1646 * @param t Tunnel this message came on.
1647 * @param msg Key eXchange message.
1650 handle_ephemeral (struct CadetTunnel *t,
1651 const struct GNUNET_CADET_KX_Ephemeral *msg)
1653 LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
1655 if (GNUNET_OK != check_ephemeral (t, msg))
1657 GNUNET_break_op (0);
1660 t->peers_ephemeral_key = msg->ephemeral_key;
1662 if (CADET_TUNNEL3_KEY_SENT == t->estate)
1664 LOG (GNUNET_ERROR_TYPE_DEBUG, " our key was sent, sending ping\n");
1666 t->estate = CADET_TUNNEL3_KEY_PING;
1672 * Peer wants to check our symmetrical keys by sending an encrypted challenge.
1673 * Answer with by retransmitting the challenge with the "opposite" key.
1675 * @param t Tunnel this message came on.
1676 * @param msg Key eXchange Ping message.
1679 handle_ping (struct CadetTunnel *t,
1680 const struct GNUNET_CADET_KX_Ping *msg)
1682 struct GNUNET_CADET_KX_Ping res;
1684 if (ntohs (msg->header.size) != sizeof (res))
1686 GNUNET_break_op (0);
1690 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PING for %s\n", GCT_2s (t));
1691 t_decrypt (t, &res.target, &msg->target, ping_encryption_size (), msg->iv);
1692 if (0 != memcmp (&my_full_id, &res.target, sizeof (my_full_id)))
1694 GNUNET_STATISTICS_update (stats, "# malformed PINGs", 1, GNUNET_NO);
1695 LOG (GNUNET_ERROR_TYPE_WARNING, " malformed PING on %s\n", GCT_2s (t));
1696 LOG (GNUNET_ERROR_TYPE_DEBUG, " e got %u\n", msg->nonce);
1697 LOG (GNUNET_ERROR_TYPE_DEBUG, " e towards %s\n", GNUNET_i2s (&msg->target));
1698 LOG (GNUNET_ERROR_TYPE_DEBUG, " got %u\n", res.nonce);
1699 LOG (GNUNET_ERROR_TYPE_DEBUG, " towards %s\n", GNUNET_i2s (&res.target));
1705 send_pong (t, res.nonce);
1710 * Peer has answer to our challenge.
1711 * If answer is successful, consider the key exchange finished and clean
1712 * up all related state.
1714 * @param t Tunnel this message came on.
1715 * @param msg Key eXchange Pong message.
1718 handle_pong (struct CadetTunnel *t,
1719 const struct GNUNET_CADET_KX_Pong *msg)
1723 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
1724 if (GNUNET_SCHEDULER_NO_TASK == t->rekey_task)
1726 GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
1729 t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
1731 if (challenge != t->kx_ctx->challenge)
1733 LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
1734 LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
1735 challenge, msg->nonce, t->kx_ctx->challenge);
1740 GNUNET_SCHEDULER_cancel (t->rekey_task);
1741 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1742 GNUNET_free (t->kx_ctx);
1744 GCT_change_estate (t, CADET_TUNNEL3_KEY_OK);
1749 * Demultiplex by message type and call appropriate handler for a message
1750 * towards a channel of a local tunnel.
1752 * @param t Tunnel this message came on.
1753 * @param msgh Message header.
1754 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1755 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1756 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1757 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1760 handle_decrypted (struct CadetTunnel *t,
1761 const struct GNUNET_MessageHeader *msgh,
1766 type = ntohs (msgh->type);
1767 LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
1771 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1772 /* Do nothing, connection aleady got updated. */
1773 GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
1776 case GNUNET_MESSAGE_TYPE_CADET_DATA:
1777 /* Don't send hop ACK, wait for client to ACK */
1778 handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
1781 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1782 handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
1785 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1786 handle_ch_create (t,
1787 (struct GNUNET_CADET_ChannelCreate *) msgh);
1790 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1792 (struct GNUNET_CADET_ChannelManage *) msgh);
1795 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1797 (struct GNUNET_CADET_ChannelManage *) msgh,
1801 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1802 handle_ch_destroy (t,
1803 (struct GNUNET_CADET_ChannelManage *) msgh,
1808 GNUNET_break_op (0);
1809 LOG (GNUNET_ERROR_TYPE_WARNING,
1810 "end-to-end message not known (%u)\n",
1811 ntohs (msgh->type));
1816 /******************************************************************************/
1817 /******************************** API ***********************************/
1818 /******************************************************************************/
1821 * Decrypt and demultiplex by message type. Call appropriate handler
1822 * for every message.
1824 * @param t Tunnel this message came on.
1825 * @param msg Encrypted message.
1828 GCT_handle_encrypted (struct CadetTunnel *t,
1829 const struct GNUNET_CADET_Encrypted *msg)
1831 size_t size = ntohs (msg->header.size);
1832 size_t payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
1834 char cbuf [payload_size];
1835 struct GNUNET_MessageHeader *msgh;
1838 decrypted_size = t_decrypt_and_validate (t, cbuf, &msg[1], payload_size,
1839 msg->iv, &msg->hmac);
1842 while (off < decrypted_size)
1844 msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
1845 handle_decrypted (t, msgh, GNUNET_SYSERR);
1846 off += ntohs (msgh->size);
1852 * Demultiplex an encapsulated KX message by message type.
1854 * @param t Tunnel on which the message came.
1855 * @param message Payload of KX message.
1858 GCT_handle_kx (struct CadetTunnel *t,
1859 const struct GNUNET_MessageHeader *message)
1863 type = ntohs (message->type);
1864 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received\n", type);
1867 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
1868 handle_ephemeral (t, (struct GNUNET_CADET_KX_Ephemeral *) message);
1871 case GNUNET_MESSAGE_TYPE_CADET_KX_PING:
1872 handle_ping (t, (struct GNUNET_CADET_KX_Ping *) message);
1875 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
1876 handle_pong (t, (struct GNUNET_CADET_KX_Pong *) message);
1880 GNUNET_break_op (0);
1881 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message not known (%u)\n", type);
1887 * Initialize the tunnel subsystem.
1889 * @param c Configuration handle.
1890 * @param key ECC private key, to derive all other keys and do crypto.
1893 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
1894 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
1896 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
1898 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
1901 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1902 "CADET", "DEFAULT_TTL", "USING DEFAULT");
1906 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
1909 rekey_period = GNUNET_TIME_UNIT_DAYS;
1912 my_private_key = key;
1913 kx_msg.header.size = htons (sizeof (kx_msg));
1914 kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
1915 kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
1916 kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
1917 kx_msg.origin_identity = my_full_id;
1918 rekey_task = GNUNET_SCHEDULER_add_now (&rekey, NULL);
1920 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
1925 * Shut down the tunnel subsystem.
1930 if (GNUNET_SCHEDULER_NO_TASK != rekey_task)
1932 GNUNET_SCHEDULER_cancel (rekey_task);
1933 rekey_task = GNUNET_SCHEDULER_NO_TASK;
1935 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
1936 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
1943 * @param destination Peer this tunnel is towards.
1945 struct CadetTunnel *
1946 GCT_new (struct CadetPeer *destination)
1948 struct CadetTunnel *t;
1950 t = GNUNET_new (struct CadetTunnel);
1952 t->peer = destination;
1955 GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
1956 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
1967 * Change the tunnel's connection state.
1969 * @param t Tunnel whose connection state to change.
1970 * @param cstate New connection state.
1973 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
1977 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
1978 GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
1979 if (myid != GCP_get_short_id (t->peer) &&
1980 CADET_TUNNEL3_READY != t->cstate &&
1981 CADET_TUNNEL3_READY == cstate)
1984 if (CADET_TUNNEL3_KEY_OK == t->estate)
1986 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered send queued data\n");
1987 send_queued_data (t);
1989 else if (CADET_TUNNEL3_KEY_UNINITIALIZED == t->estate)
1991 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered rekey\n");
1992 rekey_tunnel (t, NULL);
1997 if (CADET_TUNNEL3_READY == cstate
1998 && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
2000 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered stop dht\n");
2001 GCP_stop_search (t->peer);
2006 * Change the tunnel encryption state.
2008 * @param t Tunnel whose encryption state to change.
2009 * @param state New encryption state.
2012 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
2016 LOG (GNUNET_ERROR_TYPE_DEBUG,
2017 "Tunnel %s estate was %s\n",
2018 GCP_2s (t->peer), estate2s (t->estate));
2019 LOG (GNUNET_ERROR_TYPE_DEBUG,
2020 "Tunnel %s estate is now %s\n",
2021 GCP_2s (t->peer), estate2s (state));
2022 if (myid != GCP_get_short_id (t->peer) &&
2023 CADET_TUNNEL3_KEY_OK != t->estate && CADET_TUNNEL3_KEY_OK == state)
2026 send_queued_data (t);
2034 * @brief Check if tunnel has too many connections, and remove one if necessary.
2036 * Currently this means the newest connection, unless it is a direct one.
2037 * Implemented as a task to avoid freeing a connection that is in the middle
2038 * of being created/processed.
2040 * @param cls Closure (Tunnel to check).
2041 * @param tc Task context.
2044 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2046 struct CadetTunnel *t = cls;
2048 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2051 if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
2053 struct CadetTConnection *iter;
2054 struct CadetTConnection *c;
2056 for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
2058 if ((NULL == c || iter->created.abs_value_us > c->created.abs_value_us)
2059 && GNUNET_NO == GCC_is_direct (iter->c))
2066 LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
2068 LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
2081 * Add a connection to a tunnel.
2084 * @param c Connection.
2087 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
2089 struct CadetTConnection *aux;
2091 GNUNET_assert (NULL != c);
2093 LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
2094 LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
2095 for (aux = t->connection_head; aux != NULL; aux = aux->next)
2099 aux = GNUNET_new (struct CadetTConnection);
2101 aux->created = GNUNET_TIME_absolute_get ();
2103 GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
2105 GNUNET_SCHEDULER_add_now (&trim_connections, t);
2110 * Mark a path as no longer valid for this tunnel: has been tried and failed.
2112 * @param t Tunnel to update.
2113 * @param path Invalid path to remove. Is destroyed after removal.
2116 GCT_remove_path (struct CadetTunnel *t, struct CadetPeerPath *path)
2118 GCP_remove_path (t->peer, path);
2123 * Remove a connection from a tunnel.
2126 * @param c Connection.
2129 GCT_remove_connection (struct CadetTunnel *t,
2130 struct CadetConnection *c)
2132 struct CadetTConnection *aux;
2133 struct CadetTConnection *next;
2135 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
2136 GCC_2s (c), GCT_2s (t));
2137 for (aux = t->connection_head; aux != NULL; aux = next)
2142 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
2147 /* Start new connections if needed */
2148 if (CONNECTIONS_PER_TUNNEL < GCT_count_connections (t)
2149 && GNUNET_SCHEDULER_NO_TASK == t->destroy_task
2150 && CADET_TUNNEL3_SHUTDOWN != t->cstate
2151 && GNUNET_NO == shutting_down)
2153 LOG (GNUNET_ERROR_TYPE_DEBUG, " no more connections, getting new ones\n");
2154 t->cstate = CADET_TUNNEL3_SEARCHING;
2155 GCP_connect (t->peer);
2159 /* If not marked as ready, no change is needed */
2160 if (CADET_TUNNEL3_READY != t->cstate)
2163 /* Check if any connection is ready to maintaing cstate */
2164 for (aux = t->connection_head; aux != NULL; aux = aux->next)
2165 if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
2168 t->cstate = CADET_TUNNEL3_WAITING;
2173 * Add a channel to a tunnel.
2176 * @param ch Channel.
2179 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2181 struct CadetTChannel *aux;
2183 GNUNET_assert (NULL != ch);
2185 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
2187 for (aux = t->channel_head; aux != NULL; aux = aux->next)
2189 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
2194 aux = GNUNET_new (struct CadetTChannel);
2196 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
2197 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
2199 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2201 GNUNET_SCHEDULER_cancel (t->destroy_task);
2202 t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2203 LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
2209 * Remove a channel from a tunnel.
2212 * @param ch Channel.
2215 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2217 struct CadetTChannel *aux;
2219 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
2220 for (aux = t->channel_head; aux != NULL; aux = aux->next)
2224 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
2225 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
2234 * Search for a channel by global ID.
2236 * @param t Tunnel containing the channel.
2237 * @param chid Public channel number.
2239 * @return channel handler, NULL if doesn't exist
2241 struct CadetChannel *
2242 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
2244 struct CadetTChannel *iter;
2249 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2251 if (GCCH_get_id (iter->ch) == chid)
2255 return NULL == iter ? NULL : iter->ch;
2260 * @brief Destroy a tunnel and free all resources.
2262 * Should only be called a while after the tunnel has been marked as destroyed,
2263 * in case there is a new channel added to the same peer shortly after marking
2264 * the tunnel. This way we avoid a new public key handshake.
2266 * @param cls Closure (tunnel to destroy).
2267 * @param tc Task context.
2270 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2272 struct CadetTunnel *t = cls;
2273 struct CadetTConnection *iter;
2275 LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
2276 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2278 LOG (GNUNET_ERROR_TYPE_WARNING,
2279 "Not destroying tunnel, due to shutdown. "
2280 "Tunnel at %p should have been freed by GCT_shutdown\n", t);
2283 t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2284 t->cstate = CADET_TUNNEL3_SHUTDOWN;
2286 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2288 GCC_send_destroy (iter->c);
2295 * Tunnel is empty: destroy it.
2297 * Notifies all connections about the destruction.
2299 * @param t Tunnel to destroy.
2302 GCT_destroy_empty (struct CadetTunnel *t)
2304 if (GNUNET_YES == shutting_down)
2305 return; /* Will be destroyed immediately anyway */
2307 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2309 LOG (GNUNET_ERROR_TYPE_DEBUG,
2310 "Tunnel %s is already scheduled for destruction\n",
2313 /* should never happen, tunnel can only become empty once, and the
2314 * task identifier should be NO_TASK (cleaned when the tunnel was created
2315 * or became un-empty)
2320 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: destroying scheduled\n",
2323 t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
2324 &delayed_destroy, t);
2325 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llX\n",
2326 t, t->destroy_task);
2331 * Destroy tunnel if empty (no more channels).
2333 * @param t Tunnel to destroy if empty.
2336 GCT_destroy_if_empty (struct CadetTunnel *t)
2338 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
2339 if (1 < GCT_count_channels (t))
2342 GCT_destroy_empty (t);
2347 * Destroy the tunnel.
2349 * This function does not generate any warning traffic to clients or peers.
2352 * Cancel messages belonging to this tunnel queued to neighbors.
2353 * Free any allocated resources linked to the tunnel.
2355 * @param t The tunnel to destroy.
2358 GCT_destroy (struct CadetTunnel *t)
2360 struct CadetTConnection *iter_c;
2361 struct CadetTConnection *next_c;
2362 struct CadetTChannel *iter_ch;
2363 struct CadetTChannel *next_ch;
2368 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
2370 GNUNET_break (GNUNET_YES ==
2371 GNUNET_CONTAINER_multipeermap_remove (tunnels,
2372 GCP_get_id (t->peer), t));
2374 for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
2376 next_c = iter_c->next;
2377 GCC_destroy (iter_c->c);
2379 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
2381 next_ch = iter_ch->next;
2382 GCCH_destroy (iter_ch->ch);
2383 /* Should only happen on shutdown, but it's ok. */
2386 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2388 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling %llX\n", t->destroy_task);
2389 GNUNET_SCHEDULER_cancel (t->destroy_task);
2390 t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2393 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
2394 GCP_set_tunnel (t->peer, NULL);
2396 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
2398 GNUNET_SCHEDULER_cancel (t->rekey_task);
2399 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
2400 if (NULL != t->kx_ctx)
2401 GNUNET_free (t->kx_ctx);
2411 * @brief Use the given path for the tunnel.
2412 * Update the next and prev hops (and RCs).
2413 * (Re)start the path refresh in case the tunnel is locally owned.
2415 * @param t Tunnel to update.
2416 * @param p Path to use.
2418 * @return Connection created.
2420 struct CadetConnection *
2421 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
2423 struct CadetConnection *c;
2424 struct GNUNET_CADET_Hash cid;
2425 unsigned int own_pos;
2427 if (NULL == t || NULL == p)
2433 if (CADET_TUNNEL3_SHUTDOWN == t->cstate)
2439 for (own_pos = 0; own_pos < p->length; own_pos++)
2441 if (p->peers[own_pos] == myid)
2444 if (own_pos >= p->length)
2446 GNUNET_break_op (0);
2450 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
2451 c = GCC_new (&cid, t, p, own_pos);
2454 /* Path was flawed */
2457 GCT_add_connection (t, c);
2463 * Count established (ready) connections of a tunnel.
2465 * @param t Tunnel on which to count.
2467 * @return Number of connections.
2470 GCT_count_connections (struct CadetTunnel *t)
2472 struct CadetTConnection *iter;
2478 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2479 if (CADET_CONNECTION_DESTROYED != GCC_get_state (iter->c))
2486 * Count channels of a tunnel.
2488 * @param t Tunnel on which to count.
2490 * @return Number of channels.
2493 GCT_count_channels (struct CadetTunnel *t)
2495 struct CadetTChannel *iter;
2498 for (count = 0, iter = t->channel_head;
2500 iter = iter->next, count++) /* skip */;
2507 * Get the connectivity state of a tunnel.
2511 * @return Tunnel's connectivity state.
2513 enum CadetTunnelCState
2514 GCT_get_cstate (struct CadetTunnel *t)
2519 return (enum CadetTunnelCState) -1;
2526 * Get the encryption state of a tunnel.
2530 * @return Tunnel's encryption state.
2532 enum CadetTunnelEState
2533 GCT_get_estate (struct CadetTunnel *t)
2538 return (enum CadetTunnelEState) -1;
2544 * Get the maximum buffer space for a tunnel towards a local client.
2548 * @return Biggest buffer space offered by any channel in the tunnel.
2551 GCT_get_channels_buffer (struct CadetTunnel *t)
2553 struct CadetTChannel *iter;
2554 unsigned int buffer;
2555 unsigned int ch_buf;
2557 if (NULL == t->channel_head)
2559 /* Probably getting buffer for a channel create/handshake. */
2564 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2566 ch_buf = get_channel_buffer (iter);
2567 if (ch_buf > buffer)
2575 * Get the total buffer space for a tunnel for P2P traffic.
2579 * @return Buffer space offered by all connections in the tunnel.
2582 GCT_get_connections_buffer (struct CadetTunnel *t)
2584 struct CadetTConnection *iter;
2585 unsigned int buffer;
2588 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2590 if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
2594 buffer += get_connection_buffer (iter);
2602 * Get the tunnel's destination.
2606 * @return ID of the destination peer.
2608 const struct GNUNET_PeerIdentity *
2609 GCT_get_destination (struct CadetTunnel *t)
2611 return GCP_get_id (t->peer);
2616 * Get the tunnel's next free global channel ID.
2620 * @return GID of a channel free to use.
2623 GCT_get_next_chid (struct CadetTunnel *t)
2625 CADET_ChannelNumber chid;
2626 CADET_ChannelNumber mask;
2629 /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
2630 * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
2631 * If peer's ID is bigger, start at 0x4... bit 30 = 1
2633 result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
2638 t->next_chid |= mask;
2640 while (NULL != GCT_get_channel (t, t->next_chid))
2642 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
2643 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
2644 t->next_chid |= mask;
2646 chid = t->next_chid;
2647 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
2648 t->next_chid |= mask;
2655 * Send ACK on one or more channels due to buffer in connections.
2657 * @param t Channel which has some free buffer space.
2660 GCT_unchoke_channels (struct CadetTunnel *t)
2662 struct CadetTChannel *iter;
2663 unsigned int buffer;
2664 unsigned int channels = GCT_count_channels (t);
2665 unsigned int choked_n;
2666 struct CadetChannel *choked[channels];
2668 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
2669 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
2670 if (NULL != t->channel_head)
2671 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
2673 /* Get buffer space */
2674 buffer = GCT_get_connections_buffer (t);
2680 /* Count and remember choked channels */
2682 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2684 if (GNUNET_NO == get_channel_allowed (iter))
2686 choked[choked_n++] = iter->ch;
2690 /* Unchoke random channels */
2691 while (0 < buffer && 0 < choked_n)
2693 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2695 GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
2698 choked[r] = choked[choked_n];
2704 * Send ACK on one or more connections due to buffer space to the client.
2706 * Iterates all connections of the tunnel and sends ACKs appropriately.
2711 GCT_send_connection_acks (struct CadetTunnel *t)
2713 struct CadetTConnection *iter;
2716 uint32_t allow_per_connection;
2718 unsigned int buffer;
2720 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
2729 buffer = GCT_get_channels_buffer (t);
2730 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer %u\n", buffer);
2732 /* Count connections, how many messages are already allowed */
2733 cs = GCT_count_connections (t);
2734 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2736 allowed += get_connection_allowed (iter);
2738 LOG (GNUNET_ERROR_TYPE_DEBUG, " allowed %u\n", allowed);
2740 /* Make sure there is no overflow */
2741 if (allowed > buffer)
2746 /* Authorize connections to send more data */
2747 to_allow = buffer; /* - allowed; */
2749 for (iter = t->connection_head;
2750 NULL != iter && to_allow > 0;
2753 allow_per_connection = to_allow/cs;
2754 to_allow -= allow_per_connection;
2756 if (get_connection_allowed (iter) > 64 / 3)
2760 GCC_allow (iter->c, allow_per_connection,
2761 GCC_is_origin (iter->c, GNUNET_NO));
2764 GNUNET_break (to_allow == 0);
2769 * Cancel a previously sent message while it's in the queue.
2771 * ONLY can be called before the continuation given to the send function
2772 * is called. Once the continuation is called, the message is no longer in the
2775 * @param q Handle to the queue.
2778 GCT_cancel (struct CadetTunnelQueue *q)
2783 /* tun_message_sent() will be called and free q */
2785 else if (NULL != q->tqd)
2787 unqueue_data (q->tqd);
2789 if (NULL != q->cont)
2790 q->cont (q->cont_cls, NULL, q, 0, 0);
2801 * Sends an already built message on a tunnel, encrypting it and
2802 * choosing the best connection if not provided.
2804 * @param message Message to send. Function modifies it.
2805 * @param t Tunnel on which this message is transmitted.
2806 * @param c Connection to use (autoselect if NULL).
2807 * @param force Force the tunnel to take the message (buffer overfill).
2808 * @param cont Continuation to call once message is really sent.
2809 * @param cont_cls Closure for @c cont.
2811 * @return Handle to cancel message. NULL if @c cont is NULL.
2813 struct CadetTunnelQueue *
2814 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
2815 struct CadetTunnel *t, struct CadetConnection *c,
2816 int force, GCT_sent cont, void *cont_cls)
2818 return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
2823 * Is the tunnel directed towards the local peer?
2827 * @return #GNUNET_YES if it is loopback.
2830 GCT_is_loopback (const struct CadetTunnel *t)
2832 return (myid == GCP_get_short_id (t->peer));
2837 * Is the tunnel this path already?
2842 * @return #GNUNET_YES a connection uses this path.
2845 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
2847 struct CadetTConnection *iter;
2849 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2850 if (GCC_get_path (iter->c) == p)
2858 * Get a cost of a path for a tunnel considering existing connections.
2861 * @param path Candidate path.
2863 * @return Cost of the path (path length + number of overlapping nodes)
2866 GCT_get_path_cost (const struct CadetTunnel *t,
2867 const struct CadetPeerPath *path)
2869 struct CadetTConnection *iter;
2870 const struct CadetPeerPath *aux;
2871 unsigned int overlap;
2879 GNUNET_assert (NULL != t);
2881 for (i = 0; i < path->length; i++)
2883 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2885 aux = GCC_get_path (iter->c);
2889 for (j = 0; j < aux->length; j++)
2891 if (path->peers[i] == aux->peers[j])
2899 return path->length + overlap;
2904 * Get the static string for the peer this tunnel is directed.
2908 * @return Static string the destination peer's ID.
2911 GCT_2s (const struct CadetTunnel *t)
2916 return GCP_2s (t->peer);
2920 /******************************************************************************/
2921 /***************************** INFO/DEBUG *******************************/
2922 /******************************************************************************/
2926 * Log all possible info about the tunnel state to stderr.
2928 * @param t Tunnel to debug.
2931 GCT_debug (const struct CadetTunnel *t)
2933 struct CadetTChannel *iterch;
2934 struct CadetTConnection *iterc;
2936 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
2937 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT cstate %s, estate %s\n",
2938 cstate2s (t->cstate), estate2s (t->estate));
2939 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT kx_ctx %p, rekey_task %u\n",
2940 t->kx_ctx, t->rekey_task);
2941 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT tq_head %p, tq_tail %p\n",
2942 t->tq_head, t->tq_tail);
2943 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT destroy %u\n", t->destroy_task);
2945 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT channels:\n");
2946 for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
2948 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT - %s\n", GCCH_2s (iterch->ch));
2951 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT connections:\n");
2952 for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
2954 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT - %s [%u] buf: %u/%u (qn %u/%u)\n",
2955 GCC_2s (iterc->c), GCC_get_state (iterc->c),
2956 GCC_get_buffer (iterc->c, GNUNET_YES),
2957 GCC_get_buffer (iterc->c, GNUNET_NO),
2958 GCC_get_qn (iterc->c, GNUNET_YES),
2959 GCC_get_qn (iterc->c, GNUNET_NO));
2962 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT DEBUG TUNNEL END\n");
2967 * Iterate all tunnels.
2969 * @param iter Iterator.
2970 * @param cls Closure for @c iter.
2973 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
2975 GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
2980 * Count all tunnels.
2982 * @return Number of tunnels to remote peers kept by this peer.
2985 GCT_count_all (void)
2987 return GNUNET_CONTAINER_multipeermap_size (tunnels);
2992 * Iterate all connections of a tunnel.
2994 * @param t Tunnel whose connections to iterate.
2995 * @param iter Iterator.
2996 * @param cls Closure for @c iter.
2999 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
3001 struct CadetTConnection *ct;
3003 for (ct = t->connection_head; NULL != ct; ct = ct->next)
3009 * Iterate all channels of a tunnel.
3011 * @param t Tunnel whose channels to iterate.
3012 * @param iter Iterator.
3013 * @param cls Closure for @c iter.
3016 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
3018 struct CadetTChannel *cht;
3020 for (cht = t->channel_head; NULL != cht; cht = cht->next)
3021 iter (cls, cht->ch);