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 t Tunnel whose 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.
628 * @param msg_hmac HMAC of the message, or NULL if message does not carry
629 * integrity verification (PING, PONG)
631 * @return Size of the decrypted data, -1 if an error was encountered.
634 t_decrypt (struct CadetTunnel *t, void *dst, const void *src,
635 size_t size, uint32_t iv, const struct GNUNET_CADET_Hash *msg_hmac)
637 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
638 struct GNUNET_CRYPTO_SymmetricSessionKey *key;
640 struct GNUNET_CADET_Hash hmac;
642 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_decrypt start\n");
643 if (t->estate == CADET_TUNNEL3_KEY_OK || t->estate == CADET_TUNNEL3_KEY_PING)
647 else if (NULL != t->kx_ctx)
649 key = &t->kx_ctx->d_key_old;
653 GNUNET_STATISTICS_update (stats, "# non decryptable data", 1, GNUNET_NO);
654 LOG (GNUNET_ERROR_TYPE_DEBUG,
655 "WARNING got data on %s without a valid key\n",
661 t_hmac (t, src, size, iv, GNUNET_NO, &hmac);
662 if (NULL != msg_hmac && 0 != memcmp (msg_hmac, &hmac, sizeof (hmac)))
664 /* checksum failed */
665 // FIXME try other key
666 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
667 "Failed checksum validation for a message on tunnel `%s'\n",
669 GNUNET_STATISTICS_update (stats, "# wrong HMAC", 1, GNUNET_NO);
673 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_decrypt iv\n");
674 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
675 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_decrypt iv done\n");
676 out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, key, &siv, dst);
677 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_decrypt end\n");
684 * Create key material by doing ECDH on the local and remote ephemeral keys.
686 * @param key_material Where to store the key material.
687 * @param ephemeral_key Peer's public ephemeral key.
690 derive_key_material (struct GNUNET_HashCode *key_material,
691 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key)
694 GNUNET_CRYPTO_ecc_ecdh (my_ephemeral_key,
704 * Create a symmetic key from the identities of both ends and the key material
707 * @param key Destination for the generated key.
708 * @param sender ID of the peer that will encrypt with @c key.
709 * @param receiver ID of the peer that will decrypt with @c key.
710 * @param key_material Hash created with ECDH with the ephemeral keys.
713 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
714 const struct GNUNET_PeerIdentity *sender,
715 const struct GNUNET_PeerIdentity *receiver,
716 const struct GNUNET_HashCode *key_material)
718 const char salt[] = "CADET kx salt";
720 GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
722 key_material, sizeof (struct GNUNET_HashCode),
723 sender, sizeof (struct GNUNET_PeerIdentity),
724 receiver, sizeof (struct GNUNET_PeerIdentity),
730 * Derive the tunnel's keys using our own and the peer's ephemeral keys.
732 * @param t Tunnel for which to create the keys.
735 create_keys (struct CadetTunnel *t)
737 struct GNUNET_HashCode km;
739 derive_key_material (&km, &t->peers_ephemeral_key);
740 derive_symmertic (&t->e_key, &my_full_id, GCP_get_id (t->peer), &km);
741 derive_symmertic (&t->d_key, GCP_get_id (t->peer), &my_full_id, &km);
746 * Pick a connection on which send the next data message.
748 * @param t Tunnel on which to send the message.
750 * @return The connection on which to send the next message.
752 static struct CadetConnection *
753 tunnel_get_connection (struct CadetTunnel *t)
755 struct CadetTConnection *iter;
756 struct CadetConnection *best;
758 unsigned int lowest_q;
760 LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GCT_2s (t));
763 for (iter = t->connection_head; NULL != iter; iter = iter->next)
765 LOG (GNUNET_ERROR_TYPE_DEBUG, " connection %s: %u\n",
766 GCC_2s (iter->c), GCC_get_state (iter->c));
767 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
769 qn = GCC_get_qn (iter->c, GCC_is_origin (iter->c, GNUNET_YES));
770 LOG (GNUNET_ERROR_TYPE_DEBUG, " q_n %u, \n", qn);
778 LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GCC_2s (best));
784 * Callback called when a queued message is sent.
786 * Calculates the average time and connection packet tracking.
788 * @param cls Closure (TunnelQueue handle).
789 * @param c Connection this message was on.
790 * @param q Connection queue handle (unused).
791 * @param type Type of message sent.
792 * @param fwd Was this a FWD going message?
793 * @param size Size of the message.
796 tun_message_sent (void *cls,
797 struct CadetConnection *c,
798 struct CadetConnectionQueue *q,
799 uint16_t type, int fwd, size_t size)
801 struct CadetTunnelQueue *qt = cls;
802 struct CadetTunnel *t;
804 LOG (GNUNET_ERROR_TYPE_DEBUG, "tun_message_sent\n");
806 GNUNET_assert (NULL != qt->cont);
807 t = NULL == c ? NULL : GCC_get_tunnel (c);
808 qt->cont (qt->cont_cls, t, qt, type, size);
814 * Delete a queued message: either was sent or the channel was destroyed
815 * before the tunnel's key exchange had a chance to finish.
817 * @param tqd Delayed queue handle.
820 unqueue_data (struct CadetTunnelDelayed *tqd)
822 GNUNET_CONTAINER_DLL_remove (tqd->t->tq_head, tqd->t->tq_tail, tqd);
828 * Cache a message to be sent once tunnel is online.
830 * @param t Tunnel to hold the message.
831 * @param msg Message itself (copy will be made).
833 static struct CadetTunnelDelayed *
834 queue_data (struct CadetTunnel *t, const struct GNUNET_MessageHeader *msg)
836 struct CadetTunnelDelayed *tqd;
837 uint16_t size = ntohs (msg->size);
839 LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GCT_2s (t));
841 if (GNUNET_YES == is_ready (t))
847 tqd = GNUNET_malloc (sizeof (struct CadetTunnelDelayed) + size);
850 memcpy (&tqd[1], msg, size);
851 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
857 * Sends an already built message on a tunnel, encrypting it and
858 * choosing the best connection.
860 * @param message Message to send. Function modifies it.
861 * @param t Tunnel on which this message is transmitted.
862 * @param c Connection to use (autoselect if NULL).
863 * @param force Force the tunnel to take the message (buffer overfill).
864 * @param cont Continuation to call once message is really sent.
865 * @param cont_cls Closure for @c cont.
866 * @param existing_q In case this a transmission of previously queued data,
867 * this should be TunnelQueue given to the client.
870 * @return Handle to cancel message. NULL if @c cont is NULL.
872 static struct CadetTunnelQueue *
873 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
874 struct CadetTunnel *t, struct CadetConnection *c,
875 int force, GCT_sent cont, void *cont_cls,
876 struct CadetTunnelQueue *existing_q)
878 struct CadetTunnelQueue *tq;
879 struct GNUNET_CADET_Encrypted *msg;
880 size_t size = ntohs (message->size);
881 char cbuf[sizeof (struct GNUNET_CADET_Encrypted) + size];
887 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GCT_2s (t));
889 if (GNUNET_NO == is_ready (t))
891 struct CadetTunnelDelayed *tqd;
892 /* A non null existing_q indicates sending of queued data.
893 * Should only happen after tunnel becomes ready.
895 GNUNET_assert (NULL == existing_q);
896 tqd = queue_data (t, message);
899 tq = GNUNET_new (struct CadetTunnelQueue);
903 tq->cont_cls = cont_cls;
907 GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
909 iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
910 msg = (struct GNUNET_CADET_Encrypted *) cbuf;
911 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
913 GNUNET_assert (t_encrypt (t, &msg[1], message, size, iv) == size);
914 t_hmac (t, &msg[1], size, iv, GNUNET_YES, &msg->hmac);
915 msg->header.size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
918 c = tunnel_get_connection (t);
921 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task
922 || CADET_TUNNEL3_SEARCHING != t->cstate)
931 type = ntohs (message->type);
934 case GNUNET_MESSAGE_TYPE_CADET_DATA:
935 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
936 if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
937 mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
939 mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
941 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
942 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
943 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
944 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
945 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
946 msg->cid = *GCC_get_id (c);
947 msg->ttl = htonl (default_ttl);
952 LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
954 fwd = GCC_is_origin (c, GNUNET_YES);
958 GNUNET_break (NULL ==
959 GCC_send_prebuilt_message (&msg->header, type, mid,
960 c, fwd, force, NULL, NULL));
963 if (NULL == existing_q)
965 tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
972 tq->cq = GCC_send_prebuilt_message (&msg->header, type, mid, c, fwd, force,
973 &tun_message_sent, tq);
975 tq->cont_cls = cont_cls;
982 * Send all cached messages that we can, tunnel is online.
984 * @param t Tunnel that holds the messages. Cannot be loopback.
987 send_queued_data (struct CadetTunnel *t)
989 struct CadetTunnelDelayed *tqd;
990 struct CadetTunnelDelayed *next;
993 LOG (GNUNET_ERROR_TYPE_DEBUG,
994 "GCT_send_queued_data on tunnel %s\n",
997 if (GCT_is_loopback (t))
1003 if (GNUNET_NO == is_ready (t))
1005 LOG (GNUNET_ERROR_TYPE_DEBUG, " not ready yet: %s/%s\n",
1006 estate2s (t->estate), cstate2s (t->cstate));
1010 room = GCT_get_connections_buffer (t);
1011 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
1012 LOG (GNUNET_ERROR_TYPE_DEBUG, " tq head: %p\n", t->tq_head);
1013 for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
1015 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
1018 send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
1019 tqd->t, NULL, GNUNET_YES,
1020 NULL != tqd->tq ? tqd->tq->cont : NULL,
1021 NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
1025 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
1030 * Sends key exchange message on a tunnel, choosing the best connection.
1031 * Should not be called on loopback tunnels.
1033 * @param t Tunnel on which this message is transmitted.
1034 * @param message Message to send. Function modifies it.
1037 send_kx (struct CadetTunnel *t,
1038 const struct GNUNET_MessageHeader *message)
1040 struct CadetConnection *c;
1041 struct GNUNET_CADET_KX *msg;
1042 size_t size = ntohs (message->size);
1043 char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
1047 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
1049 /* Avoid loopback. */
1050 if (GCT_is_loopback (t))
1052 LOG (GNUNET_ERROR_TYPE_DEBUG, " loopback!\n");
1057 /* Even if tunnel is being destroyed, send anyway.
1058 * Could be a response to a rekey initiated by remote peer,
1059 * who is trying to create a new channel!
1062 /* Must have a connection. */
1063 if (NULL == t->connection_head)
1065 GNUNET_break (CADET_TUNNEL3_SEARCHING == t->cstate);
1070 msg = (struct GNUNET_CADET_KX *) cbuf;
1071 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
1072 msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
1073 c = tunnel_get_connection (t);
1076 GNUNET_break (GNUNET_SCHEDULER_NO_TASK != t->destroy_task
1077 || CADET_TUNNEL3_READY != t->cstate);
1081 type = ntohs (message->type);
1084 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
1085 case GNUNET_MESSAGE_TYPE_CADET_KX_PING:
1086 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
1087 memcpy (&msg[1], message, size);
1090 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
1095 fwd = GCC_is_origin (t->connection_head->c, GNUNET_YES);
1096 /* TODO save handle and cancel in case of a unneeded retransmission */
1097 GCC_send_prebuilt_message (&msg->header, GNUNET_MESSAGE_TYPE_CADET_KX,
1098 message->type, c, fwd, GNUNET_YES, NULL, NULL);
1103 * Send the ephemeral key on a tunnel.
1105 * @param t Tunnel on which to send the key.
1108 send_ephemeral (struct CadetTunnel *t)
1110 LOG (GNUNET_ERROR_TYPE_INFO, "=> EPHM for %s\n", GCT_2s (t));
1112 kx_msg.sender_status = htonl (t->estate);
1113 send_kx (t, &kx_msg.header);
1117 * Send a ping message on a tunnel.
1119 * @param t Tunnel on which to send the ping.
1122 send_ping (struct CadetTunnel *t)
1124 struct GNUNET_CADET_KX_Ping msg;
1126 LOG (GNUNET_ERROR_TYPE_INFO, "=> PING for %s\n", GCT_2s (t));
1127 msg.header.size = htons (sizeof (msg));
1128 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PING);
1129 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1130 msg.target = *GCP_get_id (t->peer);
1131 msg.nonce = t->kx_ctx->challenge;
1133 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
1134 LOG (GNUNET_ERROR_TYPE_DEBUG, " towards %s\n", GNUNET_i2s (&msg.target));
1135 t_encrypt (t, &msg.target, &msg.target, ping_encryption_size(), msg.iv);
1136 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
1137 LOG (GNUNET_ERROR_TYPE_DEBUG, " e towards %s\n", GNUNET_i2s (&msg.target));
1139 send_kx (t, &msg.header);
1144 * Send a pong message on a tunnel.
1146 * @param t Tunnel on which to send the pong.
1147 * @param challenge Value sent in the ping that we have to send back.
1150 send_pong (struct CadetTunnel *t, uint32_t challenge)
1152 struct GNUNET_CADET_KX_Pong msg;
1154 LOG (GNUNET_ERROR_TYPE_INFO, "=> PONG for %s\n", GCT_2s (t));
1155 msg.header.size = htons (sizeof (msg));
1156 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
1157 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1158 msg.nonce = challenge;
1159 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
1160 t_encrypt (t, &msg.nonce, &msg.nonce, sizeof (msg.nonce), msg.iv);
1161 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
1163 send_kx (t, &msg.header);
1168 * Initiate a rekey with the remote peer.
1170 * @param cls Closure (tunnel).
1171 * @param tc TaskContext.
1174 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1176 struct CadetTunnel *t = cls;
1178 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1180 LOG (GNUNET_ERROR_TYPE_DEBUG, "Re-key Tunnel %s\n", GCT_2s (t));
1181 if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1184 if (NULL == t->kx_ctx)
1186 LOG (GNUNET_ERROR_TYPE_DEBUG, " new kx ctx\n");
1187 t->kx_ctx = GNUNET_new (struct CadetTunnelKXCtx);
1188 t->kx_ctx->challenge =
1189 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1190 t->kx_ctx->d_key_old = t->d_key;
1191 t->kx_ctx->e_key_old = t->e_key;
1193 t->kx_ctx->rekey_start_time = GNUNET_TIME_absolute_get ();
1194 LOG (GNUNET_ERROR_TYPE_DEBUG, " new challenge for %s: %u\n",
1195 GCT_2s (t), t->kx_ctx->challenge);
1202 case CADET_TUNNEL3_KEY_UNINITIALIZED:
1203 t->estate = CADET_TUNNEL3_KEY_SENT;
1205 case CADET_TUNNEL3_KEY_SENT:
1207 case CADET_TUNNEL3_KEY_PING:
1208 case CADET_TUNNEL3_KEY_OK:
1210 t->estate = CADET_TUNNEL3_KEY_PING;
1213 LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
1216 // FIXME exponential backoff
1217 LOG (GNUNET_ERROR_TYPE_DEBUG, " next call in %s\n",
1218 GNUNET_STRINGS_relative_time_to_string (REKEY_WAIT, GNUNET_YES));
1219 t->rekey_task = GNUNET_SCHEDULER_add_delayed (REKEY_WAIT, &rekey_tunnel, t);
1224 * Our ephemeral key has changed, create new session key on all tunnels.
1226 * Each tunnel will start the Key Exchange with a random delay between
1227 * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
1228 * per second, on average.
1230 * @param cls Closure (size of the hashmap).
1231 * @param key Current public key.
1232 * @param value Value in the hash map (tunnel).
1234 * @return #GNUNET_YES, so we should continue to iterate,
1237 rekey_iterator (void *cls,
1238 const struct GNUNET_PeerIdentity *key,
1241 struct CadetTunnel *t = value;
1242 struct GNUNET_TIME_Relative delay;
1243 long n = (long) cls;
1246 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
1249 if (GNUNET_YES == GCT_is_loopback (t))
1252 r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
1253 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
1254 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1261 * Create a new ephemeral key and key message, schedule next rekeying.
1263 * @param cls Closure (unused).
1264 * @param tc TaskContext.
1267 rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1269 struct GNUNET_TIME_Absolute time;
1272 rekey_task = GNUNET_SCHEDULER_NO_TASK;
1274 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1277 GNUNET_free_non_null (my_ephemeral_key);
1278 my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
1280 time = GNUNET_TIME_absolute_get ();
1281 kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
1282 time = GNUNET_TIME_absolute_add (time, rekey_period);
1283 time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
1284 kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
1285 GNUNET_CRYPTO_ecdhe_key_get_public (my_ephemeral_key, &kx_msg.ephemeral_key);
1287 GNUNET_assert (GNUNET_OK ==
1288 GNUNET_CRYPTO_eddsa_sign (my_private_key,
1290 &kx_msg.signature));
1292 n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
1293 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
1295 rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period, &rekey, NULL);
1300 * Called only on shutdown, destroy every tunnel.
1302 * @param cls Closure (unused).
1303 * @param key Current public key.
1304 * @param value Value in the hash map (tunnel).
1306 * @return #GNUNET_YES, so we should continue to iterate,
1309 destroy_iterator (void *cls,
1310 const struct GNUNET_PeerIdentity *key,
1313 struct CadetTunnel *t = value;
1315 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
1322 * Notify remote peer that we don't know a channel he is talking about,
1323 * probably CHANNEL_DESTROY was missed.
1325 * @param t Tunnel on which to notify.
1326 * @param gid ID of the channel.
1329 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
1331 struct GNUNET_CADET_ChannelManage msg;
1333 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
1334 msg.header.size = htons (sizeof (msg));
1335 msg.chid = htonl (gid);
1337 LOG (GNUNET_ERROR_TYPE_DEBUG,
1338 "WARNING destroying unknown channel %u on tunnel %s\n",
1340 send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
1345 * Demultiplex data per channel and call appropriate channel handler.
1347 * @param t Tunnel on which the data came.
1348 * @param msg Data message.
1349 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1350 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1351 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1352 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1355 handle_data (struct CadetTunnel *t,
1356 const struct GNUNET_CADET_Data *msg,
1359 struct CadetChannel *ch;
1363 size = ntohs (msg->header.size);
1365 sizeof (struct GNUNET_CADET_Data) +
1366 sizeof (struct GNUNET_MessageHeader))
1371 LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
1372 GC_m2s (ntohs (msg[1].header.type)));
1375 ch = GCT_get_channel (t, ntohl (msg->chid));
1378 GNUNET_STATISTICS_update (stats, "# data on unknown channel",
1380 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
1382 send_channel_destroy (t, ntohl (msg->chid));
1386 GCCH_handle_data (ch, msg, fwd);
1391 * Demultiplex data ACKs per channel and update appropriate channel buffer info.
1393 * @param t Tunnel on which the DATA ACK came.
1394 * @param msg DATA ACK message.
1395 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1396 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1397 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1398 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1401 handle_data_ack (struct CadetTunnel *t,
1402 const struct GNUNET_CADET_DataACK *msg,
1405 struct CadetChannel *ch;
1409 size = ntohs (msg->header.size);
1410 if (size != sizeof (struct GNUNET_CADET_DataACK))
1417 ch = GCT_get_channel (t, ntohl (msg->chid));
1420 GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
1422 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1427 GCCH_handle_data_ack (ch, msg, fwd);
1432 * Handle channel create.
1434 * @param t Tunnel on which the data came.
1435 * @param msg Data message.
1438 handle_ch_create (struct CadetTunnel *t,
1439 const struct GNUNET_CADET_ChannelCreate *msg)
1441 struct CadetChannel *ch;
1445 size = ntohs (msg->header.size);
1446 if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
1453 ch = GCT_get_channel (t, ntohl (msg->chid));
1454 if (NULL != ch && ! GCT_is_loopback (t))
1456 /* Probably a retransmission, safe to ignore */
1457 LOG (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
1459 ch = GCCH_handle_create (t, msg);
1461 GCT_add_channel (t, ch);
1467 * Handle channel NACK: check correctness and call channel handler for NACKs.
1469 * @param t Tunnel on which the NACK came.
1470 * @param msg NACK message.
1473 handle_ch_nack (struct CadetTunnel *t,
1474 const struct GNUNET_CADET_ChannelManage *msg)
1476 struct CadetChannel *ch;
1480 size = ntohs (msg->header.size);
1481 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1488 ch = GCT_get_channel (t, ntohl (msg->chid));
1491 GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
1493 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1498 GCCH_handle_nack (ch);
1503 * Handle a CHANNEL ACK (SYNACK/ACK).
1505 * @param t Tunnel on which the CHANNEL ACK came.
1506 * @param msg CHANNEL ACK message.
1507 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1508 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1509 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1510 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1513 handle_ch_ack (struct CadetTunnel *t,
1514 const struct GNUNET_CADET_ChannelManage *msg,
1517 struct CadetChannel *ch;
1521 size = ntohs (msg->header.size);
1522 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1529 ch = GCT_get_channel (t, ntohl (msg->chid));
1532 GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
1534 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1539 GCCH_handle_ack (ch, msg, fwd);
1545 * Handle a channel destruction message.
1547 * @param t Tunnel on which the message came.
1548 * @param msg Channel destroy message.
1549 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1550 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1551 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1552 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1555 handle_ch_destroy (struct CadetTunnel *t,
1556 const struct GNUNET_CADET_ChannelManage *msg,
1559 struct CadetChannel *ch;
1563 size = ntohs (msg->header.size);
1564 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1571 ch = GCT_get_channel (t, ntohl (msg->chid));
1574 /* Probably a retransmission, safe to ignore */
1578 GCCH_handle_destroy (ch, msg, fwd);
1583 * The peer's ephemeral key has changed: update the symmetrical keys.
1585 * @param t Tunnel this message came on.
1586 * @param msg Key eXchange message.
1589 handle_ephemeral (struct CadetTunnel *t,
1590 const struct GNUNET_CADET_KX_Ephemeral *msg)
1592 LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
1594 if (GNUNET_OK != check_ephemeral (t, msg))
1596 GNUNET_break_op (0);
1599 t->peers_ephemeral_key = msg->ephemeral_key;
1601 if (CADET_TUNNEL3_KEY_SENT == t->estate)
1603 LOG (GNUNET_ERROR_TYPE_DEBUG, " our key was sent, sending ping\n");
1605 t->estate = CADET_TUNNEL3_KEY_PING;
1611 * Peer wants to check our symmetrical keys by sending an encrypted challenge.
1612 * Answer with by retransmitting the challenge with the "opposite" key.
1614 * @param t Tunnel this message came on.
1615 * @param msg Key eXchange Ping message.
1618 handle_ping (struct CadetTunnel *t,
1619 const struct GNUNET_CADET_KX_Ping *msg)
1621 struct GNUNET_CADET_KX_Ping res;
1623 if (ntohs (msg->header.size) != sizeof (res))
1625 GNUNET_break_op (0);
1629 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PING for %s\n", GCT_2s (t));
1630 t_decrypt (t, &res.target, &msg->target,
1631 ping_encryption_size (), msg->iv, NULL);
1632 if (0 != memcmp (&my_full_id, &res.target, sizeof (my_full_id)))
1634 GNUNET_STATISTICS_update (stats, "# malformed PINGs", 1, GNUNET_NO);
1635 LOG (GNUNET_ERROR_TYPE_WARNING, " malformed PING on %s\n", GCT_2s (t));
1636 LOG (GNUNET_ERROR_TYPE_DEBUG, " e got %u\n", msg->nonce);
1637 LOG (GNUNET_ERROR_TYPE_DEBUG, " e towards %s\n", GNUNET_i2s (&msg->target));
1638 LOG (GNUNET_ERROR_TYPE_DEBUG, " got %u\n", res.nonce);
1639 LOG (GNUNET_ERROR_TYPE_DEBUG, " towards %s\n", GNUNET_i2s (&res.target));
1645 send_pong (t, res.nonce);
1650 * Peer has answer to our challenge.
1651 * If answer is successful, consider the key exchange finished and clean
1652 * up all related state.
1654 * @param t Tunnel this message came on.
1655 * @param msg Key eXchange Pong message.
1658 handle_pong (struct CadetTunnel *t,
1659 const struct GNUNET_CADET_KX_Pong *msg)
1663 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
1664 if (GNUNET_SCHEDULER_NO_TASK == t->rekey_task)
1666 GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
1669 t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv, NULL);
1671 if (challenge != t->kx_ctx->challenge)
1673 LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
1674 LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
1675 challenge, msg->nonce, t->kx_ctx->challenge);
1680 GNUNET_SCHEDULER_cancel (t->rekey_task);
1681 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1682 GNUNET_free (t->kx_ctx);
1684 GCT_change_estate (t, CADET_TUNNEL3_KEY_OK);
1689 * Demultiplex by message type and call appropriate handler for a message
1690 * towards a channel of a local tunnel.
1692 * @param t Tunnel this message came on.
1693 * @param msgh Message header.
1694 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1695 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1696 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1697 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1700 handle_decrypted (struct CadetTunnel *t,
1701 const struct GNUNET_MessageHeader *msgh,
1706 type = ntohs (msgh->type);
1707 LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
1711 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1712 /* Do nothing, connection aleady got updated. */
1713 GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
1716 case GNUNET_MESSAGE_TYPE_CADET_DATA:
1717 /* Don't send hop ACK, wait for client to ACK */
1718 handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
1721 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1722 handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
1725 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1726 handle_ch_create (t,
1727 (struct GNUNET_CADET_ChannelCreate *) msgh);
1730 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1732 (struct GNUNET_CADET_ChannelManage *) msgh);
1735 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1737 (struct GNUNET_CADET_ChannelManage *) msgh,
1741 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1742 handle_ch_destroy (t,
1743 (struct GNUNET_CADET_ChannelManage *) msgh,
1748 GNUNET_break_op (0);
1749 LOG (GNUNET_ERROR_TYPE_WARNING,
1750 "end-to-end message not known (%u)\n",
1751 ntohs (msgh->type));
1756 /******************************************************************************/
1757 /******************************** API ***********************************/
1758 /******************************************************************************/
1761 * Decrypt and demultiplex by message type. Call appropriate handler
1762 * for every message.
1764 * @param t Tunnel this message came on.
1765 * @param msg Encrypted message.
1768 GCT_handle_encrypted (struct CadetTunnel *t,
1769 const struct GNUNET_CADET_Encrypted *msg)
1771 size_t size = ntohs (msg->header.size);
1772 size_t payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
1773 size_t decrypted_size;
1774 char cbuf [payload_size];
1775 struct GNUNET_MessageHeader *msgh;
1778 decrypted_size = t_decrypt (t, cbuf, &msg[1], payload_size,
1779 msg->iv, &msg->hmac);
1782 while (off < decrypted_size)
1784 msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
1785 handle_decrypted (t, msgh, GNUNET_SYSERR);
1786 off += ntohs (msgh->size);
1792 * Demultiplex an encapsulated KX message by message type.
1794 * @param t Tunnel on which the message came.
1795 * @param message Payload of KX message.
1798 GCT_handle_kx (struct CadetTunnel *t,
1799 const struct GNUNET_MessageHeader *message)
1803 type = ntohs (message->type);
1804 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received\n", type);
1807 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
1808 handle_ephemeral (t, (struct GNUNET_CADET_KX_Ephemeral *) message);
1811 case GNUNET_MESSAGE_TYPE_CADET_KX_PING:
1812 handle_ping (t, (struct GNUNET_CADET_KX_Ping *) message);
1815 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
1816 handle_pong (t, (struct GNUNET_CADET_KX_Pong *) message);
1820 GNUNET_break_op (0);
1821 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message not known (%u)\n", type);
1827 * Initialize the tunnel subsystem.
1829 * @param c Configuration handle.
1830 * @param key ECC private key, to derive all other keys and do crypto.
1833 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
1834 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
1836 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
1838 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
1841 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1842 "CADET", "DEFAULT_TTL", "USING DEFAULT");
1846 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
1849 rekey_period = GNUNET_TIME_UNIT_DAYS;
1852 my_private_key = key;
1853 kx_msg.header.size = htons (sizeof (kx_msg));
1854 kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
1855 kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
1856 kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
1857 kx_msg.origin_identity = my_full_id;
1858 rekey_task = GNUNET_SCHEDULER_add_now (&rekey, NULL);
1860 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
1865 * Shut down the tunnel subsystem.
1870 if (GNUNET_SCHEDULER_NO_TASK != rekey_task)
1872 GNUNET_SCHEDULER_cancel (rekey_task);
1873 rekey_task = GNUNET_SCHEDULER_NO_TASK;
1875 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
1876 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
1883 * @param destination Peer this tunnel is towards.
1885 struct CadetTunnel *
1886 GCT_new (struct CadetPeer *destination)
1888 struct CadetTunnel *t;
1890 t = GNUNET_new (struct CadetTunnel);
1892 t->peer = destination;
1895 GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
1896 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
1907 * Change the tunnel's connection state.
1909 * @param t Tunnel whose connection state to change.
1910 * @param cstate New connection state.
1913 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
1917 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
1918 GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
1919 if (myid != GCP_get_short_id (t->peer) &&
1920 CADET_TUNNEL3_READY != t->cstate &&
1921 CADET_TUNNEL3_READY == cstate)
1924 if (CADET_TUNNEL3_KEY_OK == t->estate)
1926 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered send queued data\n");
1927 send_queued_data (t);
1929 else if (CADET_TUNNEL3_KEY_UNINITIALIZED == t->estate)
1931 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered rekey\n");
1932 rekey_tunnel (t, NULL);
1937 if (CADET_TUNNEL3_READY == cstate
1938 && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
1940 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered stop dht\n");
1941 GCP_stop_search (t->peer);
1946 * Change the tunnel encryption state.
1948 * @param t Tunnel whose encryption state to change.
1949 * @param state New encryption state.
1952 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
1956 LOG (GNUNET_ERROR_TYPE_DEBUG,
1957 "Tunnel %s estate was %s\n",
1958 GCP_2s (t->peer), estate2s (t->estate));
1959 LOG (GNUNET_ERROR_TYPE_DEBUG,
1960 "Tunnel %s estate is now %s\n",
1961 GCP_2s (t->peer), estate2s (state));
1962 if (myid != GCP_get_short_id (t->peer) &&
1963 CADET_TUNNEL3_KEY_OK != t->estate && CADET_TUNNEL3_KEY_OK == state)
1966 send_queued_data (t);
1974 * @brief Check if tunnel has too many connections, and remove one if necessary.
1976 * Currently this means the newest connection, unless it is a direct one.
1977 * Implemented as a task to avoid freeing a connection that is in the middle
1978 * of being created/processed.
1980 * @param cls Closure (Tunnel to check).
1981 * @param tc Task context.
1984 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1986 struct CadetTunnel *t = cls;
1988 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1991 if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
1993 struct CadetTConnection *iter;
1994 struct CadetTConnection *c;
1996 for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
1998 if ((NULL == c || iter->created.abs_value_us > c->created.abs_value_us)
1999 && GNUNET_NO == GCC_is_direct (iter->c))
2006 LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
2008 LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
2021 * Add a connection to a tunnel.
2024 * @param c Connection.
2027 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
2029 struct CadetTConnection *aux;
2031 GNUNET_assert (NULL != c);
2033 LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
2034 LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
2035 for (aux = t->connection_head; aux != NULL; aux = aux->next)
2039 aux = GNUNET_new (struct CadetTConnection);
2041 aux->created = GNUNET_TIME_absolute_get ();
2043 GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
2045 GNUNET_SCHEDULER_add_now (&trim_connections, t);
2050 * Mark a path as no longer valid for this tunnel: has been tried and failed.
2052 * @param t Tunnel to update.
2053 * @param path Invalid path to remove. Is destroyed after removal.
2056 GCT_remove_path (struct CadetTunnel *t, struct CadetPeerPath *path)
2058 GCP_remove_path (t->peer, path);
2063 * Remove a connection from a tunnel.
2066 * @param c Connection.
2069 GCT_remove_connection (struct CadetTunnel *t,
2070 struct CadetConnection *c)
2072 struct CadetTConnection *aux;
2073 struct CadetTConnection *next;
2075 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
2076 GCC_2s (c), GCT_2s (t));
2077 for (aux = t->connection_head; aux != NULL; aux = next)
2082 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
2087 /* Start new connections if needed */
2088 if (CONNECTIONS_PER_TUNNEL < GCT_count_connections (t)
2089 && GNUNET_SCHEDULER_NO_TASK == t->destroy_task
2090 && CADET_TUNNEL3_SHUTDOWN != t->cstate
2091 && GNUNET_NO == shutting_down)
2093 LOG (GNUNET_ERROR_TYPE_DEBUG, " no more connections, getting new ones\n");
2094 t->cstate = CADET_TUNNEL3_SEARCHING;
2095 GCP_connect (t->peer);
2099 /* If not marked as ready, no change is needed */
2100 if (CADET_TUNNEL3_READY != t->cstate)
2103 /* Check if any connection is ready to maintaing cstate */
2104 for (aux = t->connection_head; aux != NULL; aux = aux->next)
2105 if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
2108 t->cstate = CADET_TUNNEL3_WAITING;
2113 * Add a channel to a tunnel.
2116 * @param ch Channel.
2119 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2121 struct CadetTChannel *aux;
2123 GNUNET_assert (NULL != ch);
2125 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
2127 for (aux = t->channel_head; aux != NULL; aux = aux->next)
2129 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
2134 aux = GNUNET_new (struct CadetTChannel);
2136 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
2137 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
2139 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2141 GNUNET_SCHEDULER_cancel (t->destroy_task);
2142 t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2143 LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
2149 * Remove a channel from a tunnel.
2152 * @param ch Channel.
2155 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2157 struct CadetTChannel *aux;
2159 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
2160 for (aux = t->channel_head; aux != NULL; aux = aux->next)
2164 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
2165 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
2174 * Search for a channel by global ID.
2176 * @param t Tunnel containing the channel.
2177 * @param chid Public channel number.
2179 * @return channel handler, NULL if doesn't exist
2181 struct CadetChannel *
2182 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
2184 struct CadetTChannel *iter;
2189 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2191 if (GCCH_get_id (iter->ch) == chid)
2195 return NULL == iter ? NULL : iter->ch;
2200 * @brief Destroy a tunnel and free all resources.
2202 * Should only be called a while after the tunnel has been marked as destroyed,
2203 * in case there is a new channel added to the same peer shortly after marking
2204 * the tunnel. This way we avoid a new public key handshake.
2206 * @param cls Closure (tunnel to destroy).
2207 * @param tc Task context.
2210 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2212 struct CadetTunnel *t = cls;
2213 struct CadetTConnection *iter;
2215 LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
2216 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2218 LOG (GNUNET_ERROR_TYPE_WARNING,
2219 "Not destroying tunnel, due to shutdown. "
2220 "Tunnel at %p should have been freed by GCT_shutdown\n", t);
2223 t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2224 t->cstate = CADET_TUNNEL3_SHUTDOWN;
2226 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2228 GCC_send_destroy (iter->c);
2235 * Tunnel is empty: destroy it.
2237 * Notifies all connections about the destruction.
2239 * @param t Tunnel to destroy.
2242 GCT_destroy_empty (struct CadetTunnel *t)
2244 if (GNUNET_YES == shutting_down)
2245 return; /* Will be destroyed immediately anyway */
2247 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2249 LOG (GNUNET_ERROR_TYPE_DEBUG,
2250 "Tunnel %s is already scheduled for destruction\n",
2253 /* should never happen, tunnel can only become empty once, and the
2254 * task identifier should be NO_TASK (cleaned when the tunnel was created
2255 * or became un-empty)
2260 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: destroying scheduled\n",
2263 t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
2264 &delayed_destroy, t);
2265 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llX\n",
2266 t, t->destroy_task);
2271 * Destroy tunnel if empty (no more channels).
2273 * @param t Tunnel to destroy if empty.
2276 GCT_destroy_if_empty (struct CadetTunnel *t)
2278 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
2279 if (1 < GCT_count_channels (t))
2282 GCT_destroy_empty (t);
2287 * Destroy the tunnel.
2289 * This function does not generate any warning traffic to clients or peers.
2292 * Cancel messages belonging to this tunnel queued to neighbors.
2293 * Free any allocated resources linked to the tunnel.
2295 * @param t The tunnel to destroy.
2298 GCT_destroy (struct CadetTunnel *t)
2300 struct CadetTConnection *iter_c;
2301 struct CadetTConnection *next_c;
2302 struct CadetTChannel *iter_ch;
2303 struct CadetTChannel *next_ch;
2308 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
2310 GNUNET_break (GNUNET_YES ==
2311 GNUNET_CONTAINER_multipeermap_remove (tunnels,
2312 GCP_get_id (t->peer), t));
2314 for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
2316 next_c = iter_c->next;
2317 GCC_destroy (iter_c->c);
2319 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
2321 next_ch = iter_ch->next;
2322 GCCH_destroy (iter_ch->ch);
2323 /* Should only happen on shutdown, but it's ok. */
2326 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2328 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling %llX\n", t->destroy_task);
2329 GNUNET_SCHEDULER_cancel (t->destroy_task);
2330 t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2333 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
2334 GCP_set_tunnel (t->peer, NULL);
2336 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
2338 GNUNET_SCHEDULER_cancel (t->rekey_task);
2339 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
2340 if (NULL != t->kx_ctx)
2341 GNUNET_free (t->kx_ctx);
2351 * @brief Use the given path for the tunnel.
2352 * Update the next and prev hops (and RCs).
2353 * (Re)start the path refresh in case the tunnel is locally owned.
2355 * @param t Tunnel to update.
2356 * @param p Path to use.
2358 * @return Connection created.
2360 struct CadetConnection *
2361 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
2363 struct CadetConnection *c;
2364 struct GNUNET_CADET_Hash cid;
2365 unsigned int own_pos;
2367 if (NULL == t || NULL == p)
2373 if (CADET_TUNNEL3_SHUTDOWN == t->cstate)
2379 for (own_pos = 0; own_pos < p->length; own_pos++)
2381 if (p->peers[own_pos] == myid)
2384 if (own_pos >= p->length)
2386 GNUNET_break_op (0);
2390 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
2391 c = GCC_new (&cid, t, p, own_pos);
2394 /* Path was flawed */
2397 GCT_add_connection (t, c);
2403 * Count established (ready) connections of a tunnel.
2405 * @param t Tunnel on which to count.
2407 * @return Number of connections.
2410 GCT_count_connections (struct CadetTunnel *t)
2412 struct CadetTConnection *iter;
2418 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2419 if (CADET_CONNECTION_DESTROYED != GCC_get_state (iter->c))
2426 * Count channels of a tunnel.
2428 * @param t Tunnel on which to count.
2430 * @return Number of channels.
2433 GCT_count_channels (struct CadetTunnel *t)
2435 struct CadetTChannel *iter;
2438 for (count = 0, iter = t->channel_head;
2440 iter = iter->next, count++) /* skip */;
2447 * Get the connectivity state of a tunnel.
2451 * @return Tunnel's connectivity state.
2453 enum CadetTunnelCState
2454 GCT_get_cstate (struct CadetTunnel *t)
2459 return (enum CadetTunnelCState) -1;
2466 * Get the encryption state of a tunnel.
2470 * @return Tunnel's encryption state.
2472 enum CadetTunnelEState
2473 GCT_get_estate (struct CadetTunnel *t)
2478 return (enum CadetTunnelEState) -1;
2484 * Get the maximum buffer space for a tunnel towards a local client.
2488 * @return Biggest buffer space offered by any channel in the tunnel.
2491 GCT_get_channels_buffer (struct CadetTunnel *t)
2493 struct CadetTChannel *iter;
2494 unsigned int buffer;
2495 unsigned int ch_buf;
2497 if (NULL == t->channel_head)
2499 /* Probably getting buffer for a channel create/handshake. */
2504 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2506 ch_buf = get_channel_buffer (iter);
2507 if (ch_buf > buffer)
2515 * Get the total buffer space for a tunnel for P2P traffic.
2519 * @return Buffer space offered by all connections in the tunnel.
2522 GCT_get_connections_buffer (struct CadetTunnel *t)
2524 struct CadetTConnection *iter;
2525 unsigned int buffer;
2528 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2530 if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
2534 buffer += get_connection_buffer (iter);
2542 * Get the tunnel's destination.
2546 * @return ID of the destination peer.
2548 const struct GNUNET_PeerIdentity *
2549 GCT_get_destination (struct CadetTunnel *t)
2551 return GCP_get_id (t->peer);
2556 * Get the tunnel's next free global channel ID.
2560 * @return GID of a channel free to use.
2563 GCT_get_next_chid (struct CadetTunnel *t)
2565 CADET_ChannelNumber chid;
2566 CADET_ChannelNumber mask;
2569 /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
2570 * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
2571 * If peer's ID is bigger, start at 0x4... bit 30 = 1
2573 result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
2578 t->next_chid |= mask;
2580 while (NULL != GCT_get_channel (t, t->next_chid))
2582 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
2583 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
2584 t->next_chid |= mask;
2586 chid = t->next_chid;
2587 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
2588 t->next_chid |= mask;
2595 * Send ACK on one or more channels due to buffer in connections.
2597 * @param t Channel which has some free buffer space.
2600 GCT_unchoke_channels (struct CadetTunnel *t)
2602 struct CadetTChannel *iter;
2603 unsigned int buffer;
2604 unsigned int channels = GCT_count_channels (t);
2605 unsigned int choked_n;
2606 struct CadetChannel *choked[channels];
2608 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
2609 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
2610 if (NULL != t->channel_head)
2611 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
2613 /* Get buffer space */
2614 buffer = GCT_get_connections_buffer (t);
2620 /* Count and remember choked channels */
2622 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2624 if (GNUNET_NO == get_channel_allowed (iter))
2626 choked[choked_n++] = iter->ch;
2630 /* Unchoke random channels */
2631 while (0 < buffer && 0 < choked_n)
2633 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2635 GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
2638 choked[r] = choked[choked_n];
2644 * Send ACK on one or more connections due to buffer space to the client.
2646 * Iterates all connections of the tunnel and sends ACKs appropriately.
2651 GCT_send_connection_acks (struct CadetTunnel *t)
2653 struct CadetTConnection *iter;
2656 uint32_t allow_per_connection;
2658 unsigned int buffer;
2660 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
2669 buffer = GCT_get_channels_buffer (t);
2670 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer %u\n", buffer);
2672 /* Count connections, how many messages are already allowed */
2673 cs = GCT_count_connections (t);
2674 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2676 allowed += get_connection_allowed (iter);
2678 LOG (GNUNET_ERROR_TYPE_DEBUG, " allowed %u\n", allowed);
2680 /* Make sure there is no overflow */
2681 if (allowed > buffer)
2686 /* Authorize connections to send more data */
2687 to_allow = buffer; /* - allowed; */
2689 for (iter = t->connection_head;
2690 NULL != iter && to_allow > 0;
2693 allow_per_connection = to_allow/cs;
2694 to_allow -= allow_per_connection;
2696 if (get_connection_allowed (iter) > 64 / 3)
2700 GCC_allow (iter->c, allow_per_connection,
2701 GCC_is_origin (iter->c, GNUNET_NO));
2704 GNUNET_break (to_allow == 0);
2709 * Cancel a previously sent message while it's in the queue.
2711 * ONLY can be called before the continuation given to the send function
2712 * is called. Once the continuation is called, the message is no longer in the
2715 * @param q Handle to the queue.
2718 GCT_cancel (struct CadetTunnelQueue *q)
2723 /* tun_message_sent() will be called and free q */
2725 else if (NULL != q->tqd)
2727 unqueue_data (q->tqd);
2729 if (NULL != q->cont)
2730 q->cont (q->cont_cls, NULL, q, 0, 0);
2741 * Sends an already built message on a tunnel, encrypting it and
2742 * choosing the best connection if not provided.
2744 * @param message Message to send. Function modifies it.
2745 * @param t Tunnel on which this message is transmitted.
2746 * @param c Connection to use (autoselect if NULL).
2747 * @param force Force the tunnel to take the message (buffer overfill).
2748 * @param cont Continuation to call once message is really sent.
2749 * @param cont_cls Closure for @c cont.
2751 * @return Handle to cancel message. NULL if @c cont is NULL.
2753 struct CadetTunnelQueue *
2754 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
2755 struct CadetTunnel *t, struct CadetConnection *c,
2756 int force, GCT_sent cont, void *cont_cls)
2758 return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
2763 * Is the tunnel directed towards the local peer?
2767 * @return #GNUNET_YES if it is loopback.
2770 GCT_is_loopback (const struct CadetTunnel *t)
2772 return (myid == GCP_get_short_id (t->peer));
2777 * Is the tunnel this path already?
2782 * @return #GNUNET_YES a connection uses this path.
2785 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
2787 struct CadetTConnection *iter;
2789 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2790 if (GCC_get_path (iter->c) == p)
2798 * Get a cost of a path for a tunnel considering existing connections.
2801 * @param path Candidate path.
2803 * @return Cost of the path (path length + number of overlapping nodes)
2806 GCT_get_path_cost (const struct CadetTunnel *t,
2807 const struct CadetPeerPath *path)
2809 struct CadetTConnection *iter;
2810 const struct CadetPeerPath *aux;
2811 unsigned int overlap;
2819 GNUNET_assert (NULL != t);
2821 for (i = 0; i < path->length; i++)
2823 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2825 aux = GCC_get_path (iter->c);
2829 for (j = 0; j < aux->length; j++)
2831 if (path->peers[i] == aux->peers[j])
2839 return path->length + overlap;
2844 * Get the static string for the peer this tunnel is directed.
2848 * @return Static string the destination peer's ID.
2851 GCT_2s (const struct CadetTunnel *t)
2856 return GCP_2s (t->peer);
2860 /******************************************************************************/
2861 /***************************** INFO/DEBUG *******************************/
2862 /******************************************************************************/
2866 * Log all possible info about the tunnel state to stderr.
2868 * @param t Tunnel to debug.
2871 GCT_debug (const struct CadetTunnel *t)
2873 struct CadetTChannel *iterch;
2874 struct CadetTConnection *iterc;
2876 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
2877 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT cstate %s, estate %s\n",
2878 cstate2s (t->cstate), estate2s (t->estate));
2879 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT kx_ctx %p, rekey_task %u\n",
2880 t->kx_ctx, t->rekey_task);
2881 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT tq_head %p, tq_tail %p\n",
2882 t->tq_head, t->tq_tail);
2883 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT destroy %u\n", t->destroy_task);
2885 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT channels:\n");
2886 for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
2888 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT - %s\n", GCCH_2s (iterch->ch));
2891 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT connections:\n");
2892 for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
2894 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT - %s [%u] buf: %u/%u (qn %u/%u)\n",
2895 GCC_2s (iterc->c), GCC_get_state (iterc->c),
2896 GCC_get_buffer (iterc->c, GNUNET_YES),
2897 GCC_get_buffer (iterc->c, GNUNET_NO),
2898 GCC_get_qn (iterc->c, GNUNET_YES),
2899 GCC_get_qn (iterc->c, GNUNET_NO));
2902 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT DEBUG TUNNEL END\n");
2907 * Iterate all tunnels.
2909 * @param iter Iterator.
2910 * @param cls Closure for @c iter.
2913 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
2915 GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
2920 * Count all tunnels.
2922 * @return Number of tunnels to remote peers kept by this peer.
2925 GCT_count_all (void)
2927 return GNUNET_CONTAINER_multipeermap_size (tunnels);
2932 * Iterate all connections of a tunnel.
2934 * @param t Tunnel whose connections to iterate.
2935 * @param iter Iterator.
2936 * @param cls Closure for @c iter.
2939 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
2941 struct CadetTConnection *ct;
2943 for (ct = t->connection_head; NULL != ct; ct = ct->next)
2949 * Iterate all channels of a tunnel.
2951 * @param t Tunnel whose channels to iterate.
2952 * @param iter Iterator.
2953 * @param cls Closure for @c iter.
2956 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
2958 struct CadetTChannel *cht;
2960 for (cht = t->channel_head; NULL != cht; cht = cht->next)
2961 iter (cls, cht->ch);