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;
540 * Encrypt data with the tunnel key.
542 * @param t Tunnel whose key to use.
543 * @param dst Destination for the encrypted data.
544 * @param src Source of the plaintext. Can overlap with @c dst.
545 * @param size Size of the plaintext.
546 * @param iv Initialization Vector to use.
549 t_encrypt (struct CadetTunnel *t,
550 void *dst, const void *src,
551 size_t size, uint32_t iv)
553 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
554 struct GNUNET_CRYPTO_SymmetricSessionKey *e_key;
557 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt start\n");
558 if (NULL != t->kx_ctx)
560 struct GNUNET_TIME_Relative age;
562 age = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
563 LOG (GNUNET_ERROR_TYPE_DEBUG,
564 " key exchange in progress, started %s ago\n",
565 GNUNET_STRINGS_relative_time_to_string (age, GNUNET_YES));
566 if (age.rel_value_us < GNUNET_TIME_UNIT_MINUTES.rel_value_us)
568 LOG (GNUNET_ERROR_TYPE_DEBUG, " using old key\n");
569 e_key = &t->kx_ctx->e_key_old;
573 LOG (GNUNET_ERROR_TYPE_DEBUG, " using new key\n");
581 GNUNET_CRYPTO_symmetric_derive_iv (&siv, e_key, &iv, sizeof (iv), NULL);
582 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt IV derived\n");
583 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, e_key, &siv, dst);
584 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt end\n");
591 * Decrypt data with the tunnel key.
593 * @param t Tunnel whose key to use.
594 * @param dst Destination for the plaintext.
595 * @param src Source of the encrypted data. Can overlap with @c dst.
596 * @param size Size of the encrypted data.
597 * @param iv Initialization Vector to use.
600 t_decrypt (struct CadetTunnel *t,
601 void *dst, const void *src,
602 size_t size, uint32_t iv)
604 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
605 struct GNUNET_CRYPTO_SymmetricSessionKey *key;
608 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_decrypt start\n");
609 if (t->estate == CADET_TUNNEL3_KEY_OK || t->estate == CADET_TUNNEL3_KEY_PING)
613 else if (NULL != t->kx_ctx)
615 key = &t->kx_ctx->d_key_old;
619 GNUNET_STATISTICS_update (stats, "# non decryptable data", 1, GNUNET_NO);
620 LOG (GNUNET_ERROR_TYPE_DEBUG,
621 "WARNING got data on %s without a valid key\n",
627 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_decrypt iv\n");
628 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
629 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_decrypt iv done\n");
630 out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, key, &siv, dst);
631 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_decrypt end\n");
638 * Create key material by doing ECDH on the local and remote ephemeral keys.
640 * @param key_material Where to store the key material.
641 * @param ephemeral_key Peer's public ephemeral key.
644 derive_key_material (struct GNUNET_HashCode *key_material,
645 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key)
648 GNUNET_CRYPTO_ecc_ecdh (my_ephemeral_key,
658 * Create a symmetic key from the identities of both ends and the key material
661 * @param key Destination for the generated key.
662 * @param sender ID of the peer that will encrypt with @c key.
663 * @param receiver ID of the peer that will decrypt with @c key.
664 * @param key_material Hash created with ECDH with the ephemeral keys.
667 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
668 const struct GNUNET_PeerIdentity *sender,
669 const struct GNUNET_PeerIdentity *receiver,
670 const struct GNUNET_HashCode *key_material)
672 const char salt[] = "CADET kx salt";
674 GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
676 key_material, sizeof (struct GNUNET_HashCode),
677 sender, sizeof (struct GNUNET_PeerIdentity),
678 receiver, sizeof (struct GNUNET_PeerIdentity),
684 * Derive the tunnel's keys using our own and the peer's ephemeral keys.
686 * @param t Tunnel for which to create the keys.
689 create_keys (struct CadetTunnel *t)
691 struct GNUNET_HashCode km;
693 derive_key_material (&km, &t->peers_ephemeral_key);
694 derive_symmertic (&t->e_key, &my_full_id, GCP_get_id (t->peer), &km);
695 derive_symmertic (&t->d_key, GCP_get_id (t->peer), &my_full_id, &km);
700 * Pick a connection on which send the next data message.
702 * @param t Tunnel on which to send the message.
704 * @return The connection on which to send the next message.
706 static struct CadetConnection *
707 tunnel_get_connection (struct CadetTunnel *t)
709 struct CadetTConnection *iter;
710 struct CadetConnection *best;
712 unsigned int lowest_q;
714 LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GCT_2s (t));
717 for (iter = t->connection_head; NULL != iter; iter = iter->next)
719 LOG (GNUNET_ERROR_TYPE_DEBUG, " connection %s: %u\n",
720 GCC_2s (iter->c), GCC_get_state (iter->c));
721 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
723 qn = GCC_get_qn (iter->c, GCC_is_origin (iter->c, GNUNET_YES));
724 LOG (GNUNET_ERROR_TYPE_DEBUG, " q_n %u, \n", qn);
732 LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GCC_2s (best));
738 * Callback called when a queued message is sent.
740 * Calculates the average time and connection packet tracking.
742 * @param cls Closure (TunnelQueue handle).
743 * @param c Connection this message was on.
744 * @param q Connection queue handle (unused).
745 * @param type Type of message sent.
746 * @param fwd Was this a FWD going message?
747 * @param size Size of the message.
750 tun_message_sent (void *cls,
751 struct CadetConnection *c,
752 struct CadetConnectionQueue *q,
753 uint16_t type, int fwd, size_t size)
755 struct CadetTunnelQueue *qt = cls;
756 struct CadetTunnel *t;
758 LOG (GNUNET_ERROR_TYPE_DEBUG, "tun_message_sent\n");
760 GNUNET_assert (NULL != qt->cont);
761 t = NULL == c ? NULL : GCC_get_tunnel (c);
762 qt->cont (qt->cont_cls, t, qt, type, size);
768 * Delete a queued message: either was sent or the channel was destroyed
769 * before the tunnel's key exchange had a chance to finish.
771 * @param tqd Delayed queue handle.
774 unqueue_data (struct CadetTunnelDelayed *tqd)
776 GNUNET_CONTAINER_DLL_remove (tqd->t->tq_head, tqd->t->tq_tail, tqd);
782 * Cache a message to be sent once tunnel is online.
784 * @param t Tunnel to hold the message.
785 * @param msg Message itself (copy will be made).
787 static struct CadetTunnelDelayed *
788 queue_data (struct CadetTunnel *t, const struct GNUNET_MessageHeader *msg)
790 struct CadetTunnelDelayed *tqd;
791 uint16_t size = ntohs (msg->size);
793 LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GCT_2s (t));
795 if (GNUNET_YES == is_ready (t))
801 tqd = GNUNET_malloc (sizeof (struct CadetTunnelDelayed) + size);
804 memcpy (&tqd[1], msg, size);
805 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
813 * @param t Tunnel to get keys from.
814 * @param plaintext Content to HMAC.
815 * @param size Size of @c plaintext.
816 * @param iv Initialization vector for the message.
817 * @param outgoing Is this an outgoing message that we encrypted?
818 * @param hmac Destination to store the HMAC.
821 t_hmac (struct CadetTunnel *t, const void *plaintext, size_t size, uint32_t iv,
822 int outgoing, struct GNUNET_CADET_Hash *hmac)
824 struct GNUNET_CRYPTO_AuthKey auth_key;
825 static const char ctx[] = "cadet authentication key";
826 struct GNUNET_CRYPTO_SymmetricSessionKey *key;
827 struct GNUNET_HashCode hash;
829 key = outgoing ? &t->e_key : &t->d_key;
830 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
835 GNUNET_CRYPTO_hmac (&auth_key, plaintext, size, &hash);
836 memcpy (hmac, &hash, sizeof (*hmac));
841 * Sends an already built message on a tunnel, encrypting it and
842 * choosing the best connection.
844 * @param message Message to send. Function modifies it.
845 * @param t Tunnel on which this message is transmitted.
846 * @param c Connection to use (autoselect if NULL).
847 * @param force Force the tunnel to take the message (buffer overfill).
848 * @param cont Continuation to call once message is really sent.
849 * @param cont_cls Closure for @c cont.
850 * @param existing_q In case this a transmission of previously queued data,
851 * this should be TunnelQueue given to the client.
854 * @return Handle to cancel message. NULL if @c cont is NULL.
856 static struct CadetTunnelQueue *
857 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
858 struct CadetTunnel *t, struct CadetConnection *c,
859 int force, GCT_sent cont, void *cont_cls,
860 struct CadetTunnelQueue *existing_q)
862 struct CadetTunnelQueue *tq;
863 struct GNUNET_CADET_Encrypted *msg;
864 size_t size = ntohs (message->size);
865 char cbuf[sizeof (struct GNUNET_CADET_Encrypted) + size];
871 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GCT_2s (t));
873 if (GNUNET_NO == is_ready (t))
875 struct CadetTunnelDelayed *tqd;
876 /* A non null existing_q indicates sending of queued data.
877 * Should only happen after tunnel becomes ready.
879 GNUNET_assert (NULL == existing_q);
880 tqd = queue_data (t, message);
883 tq = GNUNET_new (struct CadetTunnelQueue);
887 tq->cont_cls = cont_cls;
891 GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
893 iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
894 msg = (struct GNUNET_CADET_Encrypted *) cbuf;
895 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
897 GNUNET_assert (t_encrypt (t, &msg[1], message, size, iv) == size);
898 t_hmac (t, &msg[1], size, iv, GNUNET_YES, &msg->hmac);
899 msg->header.size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
902 c = tunnel_get_connection (t);
905 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task
906 || CADET_TUNNEL3_SEARCHING != t->cstate)
915 type = ntohs (message->type);
918 case GNUNET_MESSAGE_TYPE_CADET_DATA:
919 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
920 if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
921 mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
923 mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
925 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
926 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
927 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
928 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
929 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
930 msg->cid = *GCC_get_id (c);
931 msg->ttl = htonl (default_ttl);
936 LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
938 fwd = GCC_is_origin (c, GNUNET_YES);
942 GNUNET_break (NULL ==
943 GCC_send_prebuilt_message (&msg->header, type, mid,
944 c, fwd, force, NULL, NULL));
947 if (NULL == existing_q)
949 tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
956 tq->cq = GCC_send_prebuilt_message (&msg->header, type, mid, c, fwd, force,
957 &tun_message_sent, tq);
959 tq->cont_cls = cont_cls;
966 * Send all cached messages that we can, tunnel is online.
968 * @param t Tunnel that holds the messages. Cannot be loopback.
971 send_queued_data (struct CadetTunnel *t)
973 struct CadetTunnelDelayed *tqd;
974 struct CadetTunnelDelayed *next;
977 LOG (GNUNET_ERROR_TYPE_DEBUG,
978 "GCT_send_queued_data on tunnel %s\n",
981 if (GCT_is_loopback (t))
987 if (GNUNET_NO == is_ready (t))
989 LOG (GNUNET_ERROR_TYPE_DEBUG, " not ready yet: %s/%s\n",
990 estate2s (t->estate), cstate2s (t->cstate));
994 room = GCT_get_connections_buffer (t);
995 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
996 LOG (GNUNET_ERROR_TYPE_DEBUG, " tq head: %p\n", t->tq_head);
997 for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
999 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
1002 send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
1003 tqd->t, NULL, GNUNET_YES,
1004 NULL != tqd->tq ? tqd->tq->cont : NULL,
1005 NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
1009 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
1014 * Sends key exchange message on a tunnel, choosing the best connection.
1015 * Should not be called on loopback tunnels.
1017 * @param t Tunnel on which this message is transmitted.
1018 * @param message Message to send. Function modifies it.
1021 send_kx (struct CadetTunnel *t,
1022 const struct GNUNET_MessageHeader *message)
1024 struct CadetConnection *c;
1025 struct GNUNET_CADET_KX *msg;
1026 size_t size = ntohs (message->size);
1027 char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
1031 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
1033 /* Avoid loopback. */
1034 if (GCT_is_loopback (t))
1036 LOG (GNUNET_ERROR_TYPE_DEBUG, " loopback!\n");
1041 /* Even if tunnel is being destroyed, send anyway.
1042 * Could be a response to a rekey initiated by remote peer,
1043 * who is trying to create a new channel!
1046 /* Must have a connection. */
1047 if (NULL == t->connection_head)
1049 GNUNET_break (CADET_TUNNEL3_SEARCHING == t->cstate);
1054 msg = (struct GNUNET_CADET_KX *) cbuf;
1055 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
1056 msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
1057 c = tunnel_get_connection (t);
1060 GNUNET_break (GNUNET_SCHEDULER_NO_TASK != t->destroy_task
1061 || CADET_TUNNEL3_READY != t->cstate);
1065 type = ntohs (message->type);
1068 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
1069 case GNUNET_MESSAGE_TYPE_CADET_KX_PING:
1070 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
1071 memcpy (&msg[1], message, size);
1074 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
1079 fwd = GCC_is_origin (t->connection_head->c, GNUNET_YES);
1080 /* TODO save handle and cancel in case of a unneeded retransmission */
1081 GCC_send_prebuilt_message (&msg->header, GNUNET_MESSAGE_TYPE_CADET_KX,
1082 message->type, c, fwd, GNUNET_YES, NULL, NULL);
1087 * Send the ephemeral key on a tunnel.
1089 * @param t Tunnel on which to send the key.
1092 send_ephemeral (struct CadetTunnel *t)
1094 LOG (GNUNET_ERROR_TYPE_INFO, "=> EPHM for %s\n", GCT_2s (t));
1096 kx_msg.sender_status = htonl (t->estate);
1097 send_kx (t, &kx_msg.header);
1101 * Send a ping message on a tunnel.
1103 * @param t Tunnel on which to send the ping.
1106 send_ping (struct CadetTunnel *t)
1108 struct GNUNET_CADET_KX_Ping msg;
1110 LOG (GNUNET_ERROR_TYPE_INFO, "=> PING for %s\n", GCT_2s (t));
1111 msg.header.size = htons (sizeof (msg));
1112 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PING);
1113 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1114 msg.target = *GCP_get_id (t->peer);
1115 msg.nonce = t->kx_ctx->challenge;
1117 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
1118 LOG (GNUNET_ERROR_TYPE_DEBUG, " towards %s\n", GNUNET_i2s (&msg.target));
1119 t_encrypt (t, &msg.target, &msg.target, ping_encryption_size(), msg.iv);
1120 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
1121 LOG (GNUNET_ERROR_TYPE_DEBUG, " e towards %s\n", GNUNET_i2s (&msg.target));
1123 send_kx (t, &msg.header);
1128 * Send a pong message on a tunnel.
1130 * @param t Tunnel on which to send the pong.
1131 * @param challenge Value sent in the ping that we have to send back.
1134 send_pong (struct CadetTunnel *t, uint32_t challenge)
1136 struct GNUNET_CADET_KX_Pong msg;
1138 LOG (GNUNET_ERROR_TYPE_INFO, "=> PONG for %s\n", GCT_2s (t));
1139 msg.header.size = htons (sizeof (msg));
1140 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
1141 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1142 msg.nonce = challenge;
1143 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
1144 t_encrypt (t, &msg.nonce, &msg.nonce, sizeof (msg.nonce), msg.iv);
1145 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
1147 send_kx (t, &msg.header);
1152 * Initiate a rekey with the remote peer.
1154 * @param cls Closure (tunnel).
1155 * @param tc TaskContext.
1158 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1160 struct CadetTunnel *t = cls;
1162 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1164 LOG (GNUNET_ERROR_TYPE_DEBUG, "Re-key Tunnel %s\n", GCT_2s (t));
1165 if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1168 if (NULL == t->kx_ctx)
1170 LOG (GNUNET_ERROR_TYPE_DEBUG, " new kx ctx\n");
1171 t->kx_ctx = GNUNET_new (struct CadetTunnelKXCtx);
1172 t->kx_ctx->challenge =
1173 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1174 t->kx_ctx->d_key_old = t->d_key;
1175 t->kx_ctx->e_key_old = t->e_key;
1177 t->kx_ctx->rekey_start_time = GNUNET_TIME_absolute_get ();
1178 LOG (GNUNET_ERROR_TYPE_DEBUG, " new challenge for %s: %u\n",
1179 GCT_2s (t), t->kx_ctx->challenge);
1186 case CADET_TUNNEL3_KEY_UNINITIALIZED:
1187 t->estate = CADET_TUNNEL3_KEY_SENT;
1189 case CADET_TUNNEL3_KEY_SENT:
1191 case CADET_TUNNEL3_KEY_PING:
1192 case CADET_TUNNEL3_KEY_OK:
1194 t->estate = CADET_TUNNEL3_KEY_PING;
1197 LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
1200 // FIXME exponential backoff
1201 LOG (GNUNET_ERROR_TYPE_DEBUG, " next call in %s\n",
1202 GNUNET_STRINGS_relative_time_to_string (REKEY_WAIT, GNUNET_YES));
1203 t->rekey_task = GNUNET_SCHEDULER_add_delayed (REKEY_WAIT, &rekey_tunnel, t);
1208 * Our ephemeral key has changed, create new session key on all tunnels.
1210 * Each tunnel will start the Key Exchange with a random delay between
1211 * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
1212 * per second, on average.
1214 * @param cls Closure (size of the hashmap).
1215 * @param key Current public key.
1216 * @param value Value in the hash map (tunnel).
1218 * @return #GNUNET_YES, so we should continue to iterate,
1221 rekey_iterator (void *cls,
1222 const struct GNUNET_PeerIdentity *key,
1225 struct CadetTunnel *t = value;
1226 struct GNUNET_TIME_Relative delay;
1227 long n = (long) cls;
1230 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
1233 if (GNUNET_YES == GCT_is_loopback (t))
1236 r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
1237 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
1238 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1245 * Create a new ephemeral key and key message, schedule next rekeying.
1247 * @param cls Closure (unused).
1248 * @param tc TaskContext.
1251 rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1253 struct GNUNET_TIME_Absolute time;
1256 rekey_task = GNUNET_SCHEDULER_NO_TASK;
1258 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1261 GNUNET_free_non_null (my_ephemeral_key);
1262 my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
1264 time = GNUNET_TIME_absolute_get ();
1265 kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
1266 time = GNUNET_TIME_absolute_add (time, rekey_period);
1267 time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
1268 kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
1269 GNUNET_CRYPTO_ecdhe_key_get_public (my_ephemeral_key, &kx_msg.ephemeral_key);
1271 GNUNET_assert (GNUNET_OK ==
1272 GNUNET_CRYPTO_eddsa_sign (my_private_key,
1274 &kx_msg.signature));
1276 n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
1277 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
1279 rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period, &rekey, NULL);
1284 * Called only on shutdown, destroy every tunnel.
1286 * @param cls Closure (unused).
1287 * @param key Current public key.
1288 * @param value Value in the hash map (tunnel).
1290 * @return #GNUNET_YES, so we should continue to iterate,
1293 destroy_iterator (void *cls,
1294 const struct GNUNET_PeerIdentity *key,
1297 struct CadetTunnel *t = value;
1299 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
1306 * Notify remote peer that we don't know a channel he is talking about,
1307 * probably CHANNEL_DESTROY was missed.
1309 * @param t Tunnel on which to notify.
1310 * @param gid ID of the channel.
1313 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
1315 struct GNUNET_CADET_ChannelManage msg;
1317 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
1318 msg.header.size = htons (sizeof (msg));
1319 msg.chid = htonl (gid);
1321 LOG (GNUNET_ERROR_TYPE_DEBUG,
1322 "WARNING destroying unknown channel %u on tunnel %s\n",
1324 send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
1329 * Demultiplex data per channel and call appropriate channel handler.
1331 * @param t Tunnel on which the data came.
1332 * @param msg Data message.
1333 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1334 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1335 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1336 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1339 handle_data (struct CadetTunnel *t,
1340 const struct GNUNET_CADET_Data *msg,
1343 struct CadetChannel *ch;
1347 size = ntohs (msg->header.size);
1349 sizeof (struct GNUNET_CADET_Data) +
1350 sizeof (struct GNUNET_MessageHeader))
1355 LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
1356 GC_m2s (ntohs (msg[1].header.type)));
1359 ch = GCT_get_channel (t, ntohl (msg->chid));
1362 GNUNET_STATISTICS_update (stats, "# data on unknown channel",
1364 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
1366 send_channel_destroy (t, ntohl (msg->chid));
1370 GCCH_handle_data (ch, msg, fwd);
1375 * Demultiplex data ACKs per channel and update appropriate channel buffer info.
1377 * @param t Tunnel on which the DATA ACK came.
1378 * @param msg DATA ACK message.
1379 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1380 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1381 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1382 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1385 handle_data_ack (struct CadetTunnel *t,
1386 const struct GNUNET_CADET_DataACK *msg,
1389 struct CadetChannel *ch;
1393 size = ntohs (msg->header.size);
1394 if (size != sizeof (struct GNUNET_CADET_DataACK))
1401 ch = GCT_get_channel (t, ntohl (msg->chid));
1404 GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
1406 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1411 GCCH_handle_data_ack (ch, msg, fwd);
1416 * Handle channel create.
1418 * @param t Tunnel on which the data came.
1419 * @param msg Data message.
1422 handle_ch_create (struct CadetTunnel *t,
1423 const struct GNUNET_CADET_ChannelCreate *msg)
1425 struct CadetChannel *ch;
1429 size = ntohs (msg->header.size);
1430 if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
1437 ch = GCT_get_channel (t, ntohl (msg->chid));
1438 if (NULL != ch && ! GCT_is_loopback (t))
1440 /* Probably a retransmission, safe to ignore */
1441 LOG (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
1443 ch = GCCH_handle_create (t, msg);
1445 GCT_add_channel (t, ch);
1451 * Handle channel NACK: check correctness and call channel handler for NACKs.
1453 * @param t Tunnel on which the NACK came.
1454 * @param msg NACK message.
1457 handle_ch_nack (struct CadetTunnel *t,
1458 const struct GNUNET_CADET_ChannelManage *msg)
1460 struct CadetChannel *ch;
1464 size = ntohs (msg->header.size);
1465 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1472 ch = GCT_get_channel (t, ntohl (msg->chid));
1475 GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
1477 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1482 GCCH_handle_nack (ch);
1487 * Handle a CHANNEL ACK (SYNACK/ACK).
1489 * @param t Tunnel on which the CHANNEL ACK came.
1490 * @param msg CHANNEL ACK message.
1491 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1492 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1493 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1494 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1497 handle_ch_ack (struct CadetTunnel *t,
1498 const struct GNUNET_CADET_ChannelManage *msg,
1501 struct CadetChannel *ch;
1505 size = ntohs (msg->header.size);
1506 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1513 ch = GCT_get_channel (t, ntohl (msg->chid));
1516 GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
1518 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1523 GCCH_handle_ack (ch, msg, fwd);
1529 * Handle a channel destruction message.
1531 * @param t Tunnel on which the message came.
1532 * @param msg Channel destroy message.
1533 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1534 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1535 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1536 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1539 handle_ch_destroy (struct CadetTunnel *t,
1540 const struct GNUNET_CADET_ChannelManage *msg,
1543 struct CadetChannel *ch;
1547 size = ntohs (msg->header.size);
1548 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1555 ch = GCT_get_channel (t, ntohl (msg->chid));
1558 /* Probably a retransmission, safe to ignore */
1562 GCCH_handle_destroy (ch, msg, fwd);
1567 * The peer's ephemeral key has changed: update the symmetrical keys.
1569 * @param t Tunnel this message came on.
1570 * @param msg Key eXchange message.
1573 handle_ephemeral (struct CadetTunnel *t,
1574 const struct GNUNET_CADET_KX_Ephemeral *msg)
1576 LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
1578 if (GNUNET_OK != check_ephemeral (t, msg))
1580 GNUNET_break_op (0);
1583 t->peers_ephemeral_key = msg->ephemeral_key;
1585 if (CADET_TUNNEL3_KEY_SENT == t->estate)
1587 LOG (GNUNET_ERROR_TYPE_DEBUG, " our key was sent, sending ping\n");
1589 t->estate = CADET_TUNNEL3_KEY_PING;
1595 * Peer wants to check our symmetrical keys by sending an encrypted challenge.
1596 * Answer with by retransmitting the challenge with the "opposite" key.
1598 * @param t Tunnel this message came on.
1599 * @param msg Key eXchange Ping message.
1602 handle_ping (struct CadetTunnel *t,
1603 const struct GNUNET_CADET_KX_Ping *msg)
1605 struct GNUNET_CADET_KX_Ping res;
1607 if (ntohs (msg->header.size) != sizeof (res))
1609 GNUNET_break_op (0);
1613 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PING for %s\n", GCT_2s (t));
1614 t_decrypt (t, &res.target, &msg->target, ping_encryption_size (), msg->iv);
1615 if (0 != memcmp (&my_full_id, &res.target, sizeof (my_full_id)))
1617 GNUNET_STATISTICS_update (stats, "# malformed PINGs", 1, GNUNET_NO);
1618 LOG (GNUNET_ERROR_TYPE_WARNING, " malformed PING on %s\n", GCT_2s (t));
1619 LOG (GNUNET_ERROR_TYPE_DEBUG, " e got %u\n", msg->nonce);
1620 LOG (GNUNET_ERROR_TYPE_DEBUG, " e towards %s\n", GNUNET_i2s (&msg->target));
1621 LOG (GNUNET_ERROR_TYPE_DEBUG, " got %u\n", res.nonce);
1622 LOG (GNUNET_ERROR_TYPE_DEBUG, " towards %s\n", GNUNET_i2s (&res.target));
1628 send_pong (t, res.nonce);
1633 * Peer has answer to our challenge.
1634 * If answer is successful, consider the key exchange finished and clean
1635 * up all related state.
1637 * @param t Tunnel this message came on.
1638 * @param msg Key eXchange Pong message.
1641 handle_pong (struct CadetTunnel *t,
1642 const struct GNUNET_CADET_KX_Pong *msg)
1646 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
1647 if (GNUNET_SCHEDULER_NO_TASK == t->rekey_task)
1649 GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
1652 t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
1654 if (challenge != t->kx_ctx->challenge)
1656 LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
1657 LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
1658 challenge, msg->nonce, t->kx_ctx->challenge);
1663 GNUNET_SCHEDULER_cancel (t->rekey_task);
1664 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1665 GNUNET_free (t->kx_ctx);
1667 GCT_change_estate (t, CADET_TUNNEL3_KEY_OK);
1672 * Demultiplex by message type and call appropriate handler for a message
1673 * towards a channel of a local tunnel.
1675 * @param t Tunnel this message came on.
1676 * @param msgh Message header.
1677 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1678 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1679 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1680 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1683 handle_decrypted (struct CadetTunnel *t,
1684 const struct GNUNET_MessageHeader *msgh,
1689 type = ntohs (msgh->type);
1690 LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
1694 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1695 /* Do nothing, connection aleady got updated. */
1696 GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
1699 case GNUNET_MESSAGE_TYPE_CADET_DATA:
1700 /* Don't send hop ACK, wait for client to ACK */
1701 handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
1704 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1705 handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
1708 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1709 handle_ch_create (t,
1710 (struct GNUNET_CADET_ChannelCreate *) msgh);
1713 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1715 (struct GNUNET_CADET_ChannelManage *) msgh);
1718 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1720 (struct GNUNET_CADET_ChannelManage *) msgh,
1724 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1725 handle_ch_destroy (t,
1726 (struct GNUNET_CADET_ChannelManage *) msgh,
1731 GNUNET_break_op (0);
1732 LOG (GNUNET_ERROR_TYPE_WARNING,
1733 "end-to-end message not known (%u)\n",
1734 ntohs (msgh->type));
1739 /******************************************************************************/
1740 /******************************** API ***********************************/
1741 /******************************************************************************/
1744 * Decrypt and demultiplex by message type. Call appropriate handler
1745 * for every message.
1747 * @param t Tunnel this message came on.
1748 * @param msg Encrypted message.
1751 GCT_handle_encrypted (struct CadetTunnel *t,
1752 const struct GNUNET_CADET_Encrypted *msg)
1754 size_t size = ntohs (msg->header.size);
1755 size_t payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
1756 size_t decrypted_size;
1757 char cbuf [payload_size];
1758 struct GNUNET_MessageHeader *msgh;
1760 struct GNUNET_CADET_Hash hmac;
1762 decrypted_size = t_decrypt (t, cbuf, &msg[1], payload_size, msg->iv);
1763 t_hmac (t, &msg[1], payload_size, msg->iv, GNUNET_NO, &hmac);
1764 if (0 != memcmp (&hmac, &msg->hmac, sizeof (hmac)))
1766 /* checksum failed */
1767 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1768 "Failed checksum validation for a message on tunnel `%s'\n",
1770 GNUNET_STATISTICS_update (stats, "# wrong HMAC", 1, GNUNET_NO);
1774 while (off < decrypted_size)
1776 msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
1777 handle_decrypted (t, msgh, GNUNET_SYSERR);
1778 off += ntohs (msgh->size);
1784 * Demultiplex an encapsulated KX message by message type.
1786 * @param t Tunnel on which the message came.
1787 * @param message Payload of KX message.
1790 GCT_handle_kx (struct CadetTunnel *t,
1791 const struct GNUNET_MessageHeader *message)
1795 type = ntohs (message->type);
1796 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received\n", type);
1799 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
1800 handle_ephemeral (t, (struct GNUNET_CADET_KX_Ephemeral *) message);
1803 case GNUNET_MESSAGE_TYPE_CADET_KX_PING:
1804 handle_ping (t, (struct GNUNET_CADET_KX_Ping *) message);
1807 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
1808 handle_pong (t, (struct GNUNET_CADET_KX_Pong *) message);
1812 GNUNET_break_op (0);
1813 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message not known (%u)\n", type);
1819 * Initialize the tunnel subsystem.
1821 * @param c Configuration handle.
1822 * @param key ECC private key, to derive all other keys and do crypto.
1825 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
1826 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
1828 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
1830 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
1833 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1834 "CADET", "DEFAULT_TTL", "USING DEFAULT");
1838 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
1841 rekey_period = GNUNET_TIME_UNIT_DAYS;
1844 my_private_key = key;
1845 kx_msg.header.size = htons (sizeof (kx_msg));
1846 kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
1847 kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
1848 kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
1849 kx_msg.origin_identity = my_full_id;
1850 rekey_task = GNUNET_SCHEDULER_add_now (&rekey, NULL);
1852 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
1857 * Shut down the tunnel subsystem.
1862 if (GNUNET_SCHEDULER_NO_TASK != rekey_task)
1864 GNUNET_SCHEDULER_cancel (rekey_task);
1865 rekey_task = GNUNET_SCHEDULER_NO_TASK;
1867 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
1868 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
1875 * @param destination Peer this tunnel is towards.
1877 struct CadetTunnel *
1878 GCT_new (struct CadetPeer *destination)
1880 struct CadetTunnel *t;
1882 t = GNUNET_new (struct CadetTunnel);
1884 t->peer = destination;
1887 GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
1888 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
1899 * Change the tunnel's connection state.
1901 * @param t Tunnel whose connection state to change.
1902 * @param cstate New connection state.
1905 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
1909 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
1910 GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
1911 if (myid != GCP_get_short_id (t->peer) &&
1912 CADET_TUNNEL3_READY != t->cstate &&
1913 CADET_TUNNEL3_READY == cstate)
1916 if (CADET_TUNNEL3_KEY_OK == t->estate)
1918 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered send queued data\n");
1919 send_queued_data (t);
1921 else if (CADET_TUNNEL3_KEY_UNINITIALIZED == t->estate)
1923 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered rekey\n");
1924 rekey_tunnel (t, NULL);
1929 if (CADET_TUNNEL3_READY == cstate
1930 && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
1932 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered stop dht\n");
1933 GCP_stop_search (t->peer);
1938 * Change the tunnel encryption state.
1940 * @param t Tunnel whose encryption state to change.
1941 * @param state New encryption state.
1944 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
1948 LOG (GNUNET_ERROR_TYPE_DEBUG,
1949 "Tunnel %s estate was %s\n",
1950 GCP_2s (t->peer), estate2s (t->estate));
1951 LOG (GNUNET_ERROR_TYPE_DEBUG,
1952 "Tunnel %s estate is now %s\n",
1953 GCP_2s (t->peer), estate2s (state));
1954 if (myid != GCP_get_short_id (t->peer) &&
1955 CADET_TUNNEL3_KEY_OK != t->estate && CADET_TUNNEL3_KEY_OK == state)
1958 send_queued_data (t);
1966 * @brief Check if tunnel has too many connections, and remove one if necessary.
1968 * Currently this means the newest connection, unless it is a direct one.
1969 * Implemented as a task to avoid freeing a connection that is in the middle
1970 * of being created/processed.
1972 * @param cls Closure (Tunnel to check).
1973 * @param tc Task context.
1976 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1978 struct CadetTunnel *t = cls;
1980 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1983 if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
1985 struct CadetTConnection *iter;
1986 struct CadetTConnection *c;
1988 for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
1990 if ((NULL == c || iter->created.abs_value_us > c->created.abs_value_us)
1991 && GNUNET_NO == GCC_is_direct (iter->c))
1998 LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
2000 LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
2013 * Add a connection to a tunnel.
2016 * @param c Connection.
2019 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
2021 struct CadetTConnection *aux;
2023 GNUNET_assert (NULL != c);
2025 LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
2026 LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
2027 for (aux = t->connection_head; aux != NULL; aux = aux->next)
2031 aux = GNUNET_new (struct CadetTConnection);
2033 aux->created = GNUNET_TIME_absolute_get ();
2035 GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
2037 GNUNET_SCHEDULER_add_now (&trim_connections, t);
2042 * Mark a path as no longer valid for this tunnel: has been tried and failed.
2044 * @param t Tunnel to update.
2045 * @param path Invalid path to remove. Is destroyed after removal.
2048 GCT_remove_path (struct CadetTunnel *t, struct CadetPeerPath *path)
2050 GCP_remove_path (t->peer, path);
2055 * Remove a connection from a tunnel.
2058 * @param c Connection.
2061 GCT_remove_connection (struct CadetTunnel *t,
2062 struct CadetConnection *c)
2064 struct CadetTConnection *aux;
2065 struct CadetTConnection *next;
2067 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
2068 GCC_2s (c), GCT_2s (t));
2069 for (aux = t->connection_head; aux != NULL; aux = next)
2074 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
2079 /* Start new connections if needed */
2080 if (CONNECTIONS_PER_TUNNEL < GCT_count_connections (t)
2081 && GNUNET_SCHEDULER_NO_TASK == t->destroy_task
2082 && CADET_TUNNEL3_SHUTDOWN != t->cstate
2083 && GNUNET_NO == shutting_down)
2085 LOG (GNUNET_ERROR_TYPE_DEBUG, " no more connections, getting new ones\n");
2086 t->cstate = CADET_TUNNEL3_SEARCHING;
2087 GCP_connect (t->peer);
2091 /* If not marked as ready, no change is needed */
2092 if (CADET_TUNNEL3_READY != t->cstate)
2095 /* Check if any connection is ready to maintaing cstate */
2096 for (aux = t->connection_head; aux != NULL; aux = aux->next)
2097 if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
2100 t->cstate = CADET_TUNNEL3_WAITING;
2105 * Add a channel to a tunnel.
2108 * @param ch Channel.
2111 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2113 struct CadetTChannel *aux;
2115 GNUNET_assert (NULL != ch);
2117 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
2119 for (aux = t->channel_head; aux != NULL; aux = aux->next)
2121 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
2126 aux = GNUNET_new (struct CadetTChannel);
2128 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
2129 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
2131 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2133 GNUNET_SCHEDULER_cancel (t->destroy_task);
2134 t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2135 LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
2141 * Remove a channel from a tunnel.
2144 * @param ch Channel.
2147 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2149 struct CadetTChannel *aux;
2151 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
2152 for (aux = t->channel_head; aux != NULL; aux = aux->next)
2156 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
2157 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
2166 * Search for a channel by global ID.
2168 * @param t Tunnel containing the channel.
2169 * @param chid Public channel number.
2171 * @return channel handler, NULL if doesn't exist
2173 struct CadetChannel *
2174 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
2176 struct CadetTChannel *iter;
2181 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2183 if (GCCH_get_id (iter->ch) == chid)
2187 return NULL == iter ? NULL : iter->ch;
2192 * @brief Destroy a tunnel and free all resources.
2194 * Should only be called a while after the tunnel has been marked as destroyed,
2195 * in case there is a new channel added to the same peer shortly after marking
2196 * the tunnel. This way we avoid a new public key handshake.
2198 * @param cls Closure (tunnel to destroy).
2199 * @param tc Task context.
2202 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2204 struct CadetTunnel *t = cls;
2205 struct CadetTConnection *iter;
2207 LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
2208 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2210 LOG (GNUNET_ERROR_TYPE_WARNING,
2211 "Not destroying tunnel, due to shutdown. "
2212 "Tunnel at %p should have been freed by GCT_shutdown\n", t);
2215 t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2216 t->cstate = CADET_TUNNEL3_SHUTDOWN;
2218 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2220 GCC_send_destroy (iter->c);
2227 * Tunnel is empty: destroy it.
2229 * Notifies all connections about the destruction.
2231 * @param t Tunnel to destroy.
2234 GCT_destroy_empty (struct CadetTunnel *t)
2236 if (GNUNET_YES == shutting_down)
2237 return; /* Will be destroyed immediately anyway */
2239 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2241 LOG (GNUNET_ERROR_TYPE_DEBUG,
2242 "Tunnel %s is already scheduled for destruction\n",
2245 /* should never happen, tunnel can only become empty once, and the
2246 * task identifier should be NO_TASK (cleaned when the tunnel was created
2247 * or became un-empty)
2252 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: destroying scheduled\n",
2255 t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
2256 &delayed_destroy, t);
2257 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llX\n",
2258 t, t->destroy_task);
2263 * Destroy tunnel if empty (no more channels).
2265 * @param t Tunnel to destroy if empty.
2268 GCT_destroy_if_empty (struct CadetTunnel *t)
2270 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
2271 if (1 < GCT_count_channels (t))
2274 GCT_destroy_empty (t);
2279 * Destroy the tunnel.
2281 * This function does not generate any warning traffic to clients or peers.
2284 * Cancel messages belonging to this tunnel queued to neighbors.
2285 * Free any allocated resources linked to the tunnel.
2287 * @param t The tunnel to destroy.
2290 GCT_destroy (struct CadetTunnel *t)
2292 struct CadetTConnection *iter_c;
2293 struct CadetTConnection *next_c;
2294 struct CadetTChannel *iter_ch;
2295 struct CadetTChannel *next_ch;
2300 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
2302 GNUNET_break (GNUNET_YES ==
2303 GNUNET_CONTAINER_multipeermap_remove (tunnels,
2304 GCP_get_id (t->peer), t));
2306 for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
2308 next_c = iter_c->next;
2309 GCC_destroy (iter_c->c);
2311 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
2313 next_ch = iter_ch->next;
2314 GCCH_destroy (iter_ch->ch);
2315 /* Should only happen on shutdown, but it's ok. */
2318 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2320 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling %llX\n", t->destroy_task);
2321 GNUNET_SCHEDULER_cancel (t->destroy_task);
2322 t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2325 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
2326 GCP_set_tunnel (t->peer, NULL);
2328 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
2330 GNUNET_SCHEDULER_cancel (t->rekey_task);
2331 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
2332 if (NULL != t->kx_ctx)
2333 GNUNET_free (t->kx_ctx);
2343 * @brief Use the given path for the tunnel.
2344 * Update the next and prev hops (and RCs).
2345 * (Re)start the path refresh in case the tunnel is locally owned.
2347 * @param t Tunnel to update.
2348 * @param p Path to use.
2350 * @return Connection created.
2352 struct CadetConnection *
2353 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
2355 struct CadetConnection *c;
2356 struct GNUNET_CADET_Hash cid;
2357 unsigned int own_pos;
2359 if (NULL == t || NULL == p)
2365 if (CADET_TUNNEL3_SHUTDOWN == t->cstate)
2371 for (own_pos = 0; own_pos < p->length; own_pos++)
2373 if (p->peers[own_pos] == myid)
2376 if (own_pos >= p->length)
2378 GNUNET_break_op (0);
2382 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
2383 c = GCC_new (&cid, t, p, own_pos);
2386 /* Path was flawed */
2389 GCT_add_connection (t, c);
2395 * Count established (ready) connections of a tunnel.
2397 * @param t Tunnel on which to count.
2399 * @return Number of connections.
2402 GCT_count_connections (struct CadetTunnel *t)
2404 struct CadetTConnection *iter;
2410 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2411 if (CADET_CONNECTION_DESTROYED != GCC_get_state (iter->c))
2418 * Count channels of a tunnel.
2420 * @param t Tunnel on which to count.
2422 * @return Number of channels.
2425 GCT_count_channels (struct CadetTunnel *t)
2427 struct CadetTChannel *iter;
2430 for (count = 0, iter = t->channel_head;
2432 iter = iter->next, count++) /* skip */;
2439 * Get the connectivity state of a tunnel.
2443 * @return Tunnel's connectivity state.
2445 enum CadetTunnelCState
2446 GCT_get_cstate (struct CadetTunnel *t)
2451 return (enum CadetTunnelCState) -1;
2458 * Get the encryption state of a tunnel.
2462 * @return Tunnel's encryption state.
2464 enum CadetTunnelEState
2465 GCT_get_estate (struct CadetTunnel *t)
2470 return (enum CadetTunnelEState) -1;
2476 * Get the maximum buffer space for a tunnel towards a local client.
2480 * @return Biggest buffer space offered by any channel in the tunnel.
2483 GCT_get_channels_buffer (struct CadetTunnel *t)
2485 struct CadetTChannel *iter;
2486 unsigned int buffer;
2487 unsigned int ch_buf;
2489 if (NULL == t->channel_head)
2491 /* Probably getting buffer for a channel create/handshake. */
2496 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2498 ch_buf = get_channel_buffer (iter);
2499 if (ch_buf > buffer)
2507 * Get the total buffer space for a tunnel for P2P traffic.
2511 * @return Buffer space offered by all connections in the tunnel.
2514 GCT_get_connections_buffer (struct CadetTunnel *t)
2516 struct CadetTConnection *iter;
2517 unsigned int buffer;
2520 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2522 if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
2526 buffer += get_connection_buffer (iter);
2534 * Get the tunnel's destination.
2538 * @return ID of the destination peer.
2540 const struct GNUNET_PeerIdentity *
2541 GCT_get_destination (struct CadetTunnel *t)
2543 return GCP_get_id (t->peer);
2548 * Get the tunnel's next free global channel ID.
2552 * @return GID of a channel free to use.
2555 GCT_get_next_chid (struct CadetTunnel *t)
2557 CADET_ChannelNumber chid;
2558 CADET_ChannelNumber mask;
2561 /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
2562 * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
2563 * If peer's ID is bigger, start at 0x4... bit 30 = 1
2565 result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
2570 t->next_chid |= mask;
2572 while (NULL != GCT_get_channel (t, t->next_chid))
2574 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
2575 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
2576 t->next_chid |= mask;
2578 chid = t->next_chid;
2579 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
2580 t->next_chid |= mask;
2587 * Send ACK on one or more channels due to buffer in connections.
2589 * @param t Channel which has some free buffer space.
2592 GCT_unchoke_channels (struct CadetTunnel *t)
2594 struct CadetTChannel *iter;
2595 unsigned int buffer;
2596 unsigned int channels = GCT_count_channels (t);
2597 unsigned int choked_n;
2598 struct CadetChannel *choked[channels];
2600 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
2601 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
2602 if (NULL != t->channel_head)
2603 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
2605 /* Get buffer space */
2606 buffer = GCT_get_connections_buffer (t);
2612 /* Count and remember choked channels */
2614 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2616 if (GNUNET_NO == get_channel_allowed (iter))
2618 choked[choked_n++] = iter->ch;
2622 /* Unchoke random channels */
2623 while (0 < buffer && 0 < choked_n)
2625 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2627 GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
2630 choked[r] = choked[choked_n];
2636 * Send ACK on one or more connections due to buffer space to the client.
2638 * Iterates all connections of the tunnel and sends ACKs appropriately.
2643 GCT_send_connection_acks (struct CadetTunnel *t)
2645 struct CadetTConnection *iter;
2648 uint32_t allow_per_connection;
2650 unsigned int buffer;
2652 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
2661 buffer = GCT_get_channels_buffer (t);
2662 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer %u\n", buffer);
2664 /* Count connections, how many messages are already allowed */
2665 cs = GCT_count_connections (t);
2666 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2668 allowed += get_connection_allowed (iter);
2670 LOG (GNUNET_ERROR_TYPE_DEBUG, " allowed %u\n", allowed);
2672 /* Make sure there is no overflow */
2673 if (allowed > buffer)
2678 /* Authorize connections to send more data */
2679 to_allow = buffer; /* - allowed; */
2681 for (iter = t->connection_head;
2682 NULL != iter && to_allow > 0;
2685 allow_per_connection = to_allow/cs;
2686 to_allow -= allow_per_connection;
2688 if (get_connection_allowed (iter) > 64 / 3)
2692 GCC_allow (iter->c, allow_per_connection,
2693 GCC_is_origin (iter->c, GNUNET_NO));
2696 GNUNET_break (to_allow == 0);
2701 * Cancel a previously sent message while it's in the queue.
2703 * ONLY can be called before the continuation given to the send function
2704 * is called. Once the continuation is called, the message is no longer in the
2707 * @param q Handle to the queue.
2710 GCT_cancel (struct CadetTunnelQueue *q)
2715 /* tun_message_sent() will be called and free q */
2717 else if (NULL != q->tqd)
2719 unqueue_data (q->tqd);
2721 if (NULL != q->cont)
2722 q->cont (q->cont_cls, NULL, q, 0, 0);
2733 * Sends an already built message on a tunnel, encrypting it and
2734 * choosing the best connection if not provided.
2736 * @param message Message to send. Function modifies it.
2737 * @param t Tunnel on which this message is transmitted.
2738 * @param c Connection to use (autoselect if NULL).
2739 * @param force Force the tunnel to take the message (buffer overfill).
2740 * @param cont Continuation to call once message is really sent.
2741 * @param cont_cls Closure for @c cont.
2743 * @return Handle to cancel message. NULL if @c cont is NULL.
2745 struct CadetTunnelQueue *
2746 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
2747 struct CadetTunnel *t, struct CadetConnection *c,
2748 int force, GCT_sent cont, void *cont_cls)
2750 return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
2755 * Is the tunnel directed towards the local peer?
2759 * @return #GNUNET_YES if it is loopback.
2762 GCT_is_loopback (const struct CadetTunnel *t)
2764 return (myid == GCP_get_short_id (t->peer));
2769 * Is the tunnel this path already?
2774 * @return #GNUNET_YES a connection uses this path.
2777 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
2779 struct CadetTConnection *iter;
2781 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2782 if (GCC_get_path (iter->c) == p)
2790 * Get a cost of a path for a tunnel considering existing connections.
2793 * @param path Candidate path.
2795 * @return Cost of the path (path length + number of overlapping nodes)
2798 GCT_get_path_cost (const struct CadetTunnel *t,
2799 const struct CadetPeerPath *path)
2801 struct CadetTConnection *iter;
2802 const struct CadetPeerPath *aux;
2803 unsigned int overlap;
2811 GNUNET_assert (NULL != t);
2813 for (i = 0; i < path->length; i++)
2815 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2817 aux = GCC_get_path (iter->c);
2821 for (j = 0; j < aux->length; j++)
2823 if (path->peers[i] == aux->peers[j])
2831 return path->length + overlap;
2836 * Get the static string for the peer this tunnel is directed.
2840 * @return Static string the destination peer's ID.
2843 GCT_2s (const struct CadetTunnel *t)
2848 return GCP_2s (t->peer);
2852 /******************************************************************************/
2853 /***************************** INFO/DEBUG *******************************/
2854 /******************************************************************************/
2858 * Log all possible info about the tunnel state to stderr.
2860 * @param t Tunnel to debug.
2863 GCT_debug (const struct CadetTunnel *t)
2865 struct CadetTChannel *iterch;
2866 struct CadetTConnection *iterc;
2868 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
2869 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT cstate %s, estate %s\n",
2870 cstate2s (t->cstate), estate2s (t->estate));
2871 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT kx_ctx %p, rekey_task %u\n",
2872 t->kx_ctx, t->rekey_task);
2873 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT tq_head %p, tq_tail %p\n",
2874 t->tq_head, t->tq_tail);
2875 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT destroy %u\n", t->destroy_task);
2877 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT channels:\n");
2878 for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
2880 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT - %s\n", GCCH_2s (iterch->ch));
2883 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT connections:\n");
2884 for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
2886 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT - %s [%u] buf: %u/%u (qn %u/%u)\n",
2887 GCC_2s (iterc->c), GCC_get_state (iterc->c),
2888 GCC_get_buffer (iterc->c, GNUNET_YES),
2889 GCC_get_buffer (iterc->c, GNUNET_NO),
2890 GCC_get_qn (iterc->c, GNUNET_YES),
2891 GCC_get_qn (iterc->c, GNUNET_NO));
2894 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT DEBUG TUNNEL END\n");
2899 * Iterate all tunnels.
2901 * @param iter Iterator.
2902 * @param cls Closure for @c iter.
2905 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
2907 GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
2912 * Count all tunnels.
2914 * @return Number of tunnels to remote peers kept by this peer.
2917 GCT_count_all (void)
2919 return GNUNET_CONTAINER_multipeermap_size (tunnels);
2924 * Iterate all connections of a tunnel.
2926 * @param t Tunnel whose connections to iterate.
2927 * @param iter Iterator.
2928 * @param cls Closure for @c iter.
2931 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
2933 struct CadetTConnection *ct;
2935 for (ct = t->connection_head; NULL != ct; ct = ct->next)
2941 * Iterate all channels of a tunnel.
2943 * @param t Tunnel whose channels to iterate.
2944 * @param iter Iterator.
2945 * @param cls Closure for @c iter.
2948 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
2950 struct CadetTChannel *cht;
2952 for (cht = t->channel_head; NULL != cht; cht = cht->next)
2953 iter (cls, cht->ch);