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 * Encryption ("our") key.
140 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
143 * Decryption ("their") key.
145 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
148 * Task to start the rekey process.
150 GNUNET_SCHEDULER_TaskIdentifier rekey_task;
153 * Paths that are actively used to reach the destination peer.
155 struct CadetTConnection *connection_head;
156 struct CadetTConnection *connection_tail;
159 * Next connection number.
164 * Channels inside this tunnel.
166 struct CadetTChannel *channel_head;
167 struct CadetTChannel *channel_tail;
170 * Channel ID for the next created channel.
172 CADET_ChannelNumber next_chid;
175 * Destroy flag: if true, destroy on last message.
177 GNUNET_SCHEDULER_TaskIdentifier destroy_task;
180 * Queued messages, to transmit once tunnel gets connected.
182 struct CadetTunnelDelayed *tq_head;
183 struct CadetTunnelDelayed *tq_tail;
188 * Struct used to save messages in a non-ready tunnel to send once connected.
190 struct CadetTunnelDelayed
195 struct CadetTunnelDelayed *next;
196 struct CadetTunnelDelayed *prev;
201 struct CadetTunnel *t;
204 * Tunnel queue given to the channel to cancel request. Update on send_queued.
206 struct CadetTunnelQueue *tq;
211 /* struct GNUNET_MessageHeader *msg; */
216 * Handle for messages queued but not yet sent.
218 struct CadetTunnelQueue
221 * Connection queue handle, to cancel if necessary.
223 struct CadetConnectionQueue *cq;
226 * Handle in case message hasn't been given to a connection yet.
228 struct CadetTunnelDelayed *tqd;
231 * Continuation to call once sent.
236 * Closure for @c cont.
242 /******************************************************************************/
243 /******************************* GLOBALS ***********************************/
244 /******************************************************************************/
247 * Global handle to the statistics service.
249 extern struct GNUNET_STATISTICS_Handle *stats;
252 * Local peer own ID (memory efficient handle).
254 extern GNUNET_PEER_Id myid;
257 * Local peer own ID (full value).
259 extern struct GNUNET_PeerIdentity my_full_id;
263 * Don't try to recover tunnels if shutting down.
265 extern int shutting_down;
269 * Set of all tunnels, in order to trigger a new exchange on rekey.
270 * Indexed by peer's ID.
272 static struct GNUNET_CONTAINER_MultiPeerMap *tunnels;
275 * Default TTL for payload packets.
277 static unsigned long long default_ttl;
282 const static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
285 * Own ephemeral private key.
287 static struct GNUNET_CRYPTO_EcdhePrivateKey *my_ephemeral_key;
290 * Cached message used to perform a key exchange.
292 static struct GNUNET_CADET_KX_Ephemeral kx_msg;
295 * Task to generate a new ephemeral key.
297 static GNUNET_SCHEDULER_TaskIdentifier rekey_task;
302 static struct GNUNET_TIME_Relative rekey_period;
304 /******************************************************************************/
305 /******************************** STATIC ***********************************/
306 /******************************************************************************/
309 * Get string description for tunnel connectivity state.
311 * @param cs Tunnel state.
313 * @return String representation.
316 cstate2s (enum CadetTunnelCState cs)
318 static char buf[128];
322 case CADET_TUNNEL3_NEW:
323 return "CADET_TUNNEL3_NEW";
324 case CADET_TUNNEL3_SEARCHING:
325 return "CADET_TUNNEL3_SEARCHING";
326 case CADET_TUNNEL3_WAITING:
327 return "CADET_TUNNEL3_WAITING";
328 case CADET_TUNNEL3_READY:
329 return "CADET_TUNNEL3_READY";
332 sprintf (buf, "%u (UNKNOWN STATE)", cs);
340 * Get string description for tunnel encryption state.
342 * @param es Tunnel state.
344 * @return String representation.
347 estate2s (enum CadetTunnelEState es)
349 static char buf[128];
353 case CADET_TUNNEL3_KEY_UNINITIALIZED:
354 return "CADET_TUNNEL3_KEY_UNINITIALIZED";
355 case CADET_TUNNEL3_KEY_SENT:
356 return "CADET_TUNNEL3_KEY_SENT";
357 case CADET_TUNNEL3_KEY_PING:
358 return "CADET_TUNNEL3_KEY_PING";
359 case CADET_TUNNEL3_KEY_OK:
360 return "CADET_TUNNEL3_KEY_OK";
363 sprintf (buf, "%u (UNKNOWN STATE)", es);
371 * @brief Check if tunnel is ready to send traffic.
373 * Tunnel must be connected and with encryption correctly set up.
375 * @param t Tunnel to check.
377 * @return #GNUNET_YES if ready, #GNUNET_NO otherwise
380 is_ready (struct CadetTunnel *t)
385 ready = (CADET_TUNNEL3_READY == t->cstate && CADET_TUNNEL3_KEY_OK == t->estate);
386 ready = ready || GCT_is_loopback (t);
392 * Ephemeral key message purpose size.
394 * @return Size of the part of the ephemeral key message that must be signed.
397 ephemeral_purpose_size (void)
399 return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
400 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
401 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
402 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
403 sizeof (struct GNUNET_PeerIdentity);
408 * Size of the encrypted part of a ping message.
410 * @return Size of the encrypted part of a ping message.
413 ping_encryption_size (void)
415 return sizeof (struct GNUNET_PeerIdentity) + sizeof (uint32_t);
420 * Get the channel's buffer. ONLY FOR NON-LOOPBACK CHANNELS!!
422 * @param tch Tunnel's channel handle.
424 * @return Amount of messages the channel can still buffer towards the client.
427 get_channel_buffer (const struct CadetTChannel *tch)
431 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
432 fwd = GCCH_is_origin (tch->ch, GNUNET_YES);
434 return GCCH_get_buffer (tch->ch, fwd);
439 * Get the channel's allowance status.
441 * @param tch Tunnel's channel handle.
443 * @return #GNUNET_YES if we allowed the client to send data to us.
446 get_channel_allowed (const struct CadetTChannel *tch)
450 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
451 fwd = GCCH_is_origin (tch->ch, GNUNET_YES);
453 return GCCH_get_allowed (tch->ch, fwd);
458 * Get the connection's buffer.
460 * @param tc Tunnel's connection handle.
462 * @return Amount of messages the connection can still buffer.
465 get_connection_buffer (const struct CadetTConnection *tc)
469 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
470 fwd = GCC_is_origin (tc->c, GNUNET_YES);
472 return GCC_get_buffer (tc->c, fwd);
477 * Get the connection's allowance.
479 * @param tc Tunnel's connection handle.
481 * @return Amount of messages we have allowed the next peer to send us.
484 get_connection_allowed (const struct CadetTConnection *tc)
488 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
489 fwd = GCC_is_origin (tc->c, GNUNET_YES);
491 return GCC_get_allowed (tc->c, fwd);
496 * Check that a ephemeral key message s well formed and correctly signed.
498 * @param t Tunnel on which the message came.
499 * @param msg The ephemeral key message.
501 * @return GNUNET_OK if message is fine, GNUNET_SYSERR otherwise.
504 check_ephemeral (struct CadetTunnel *t,
505 const struct GNUNET_CADET_KX_Ephemeral *msg)
507 /* Check message size */
508 if (ntohs (msg->header.size) != sizeof (struct GNUNET_CADET_KX_Ephemeral))
509 return GNUNET_SYSERR;
511 /* Check signature size */
512 if (ntohl (msg->purpose.size) != ephemeral_purpose_size ())
513 return GNUNET_SYSERR;
516 if (0 != memcmp (&msg->origin_identity,
517 GCP_get_id (t->peer),
518 sizeof (struct GNUNET_PeerIdentity)))
519 return GNUNET_SYSERR;
521 /* Check signature */
523 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_CADET_KX,
526 &msg->origin_identity.public_key))
527 return GNUNET_SYSERR;
534 * Encrypt data with the tunnel key.
536 * @param t Tunnel whose key to use.
537 * @param dst Destination for the encrypted data.
538 * @param src Source of the plaintext. Can overlap with @c dst.
539 * @param size Size of the plaintext.
540 * @param iv Initialization Vector to use.
543 t_encrypt (struct CadetTunnel *t,
544 void *dst, const void *src,
545 size_t size, uint32_t iv)
547 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
550 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt start\n");
551 GNUNET_CRYPTO_symmetric_derive_iv (&siv, &t->e_key, &iv, sizeof (iv), NULL);
552 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt IV derived\n");
553 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, &t->e_key, &siv, dst);
554 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt end\n");
561 * Decrypt data with the tunnel key.
563 * @param t Tunnel whose key to use.
564 * @param dst Destination for the plaintext.
565 * @param src Source of the encrypted data. Can overlap with @c dst.
566 * @param size Size of the encrypted data.
567 * @param iv Initialization Vector to use.
570 t_decrypt (struct CadetTunnel *t,
571 void *dst, const void *src,
572 size_t size, uint32_t iv)
574 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
575 struct GNUNET_CRYPTO_SymmetricSessionKey *key;
578 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_decrypt start\n");
579 if (t->estate == CADET_TUNNEL3_KEY_OK || t->estate == CADET_TUNNEL3_KEY_PING)
583 else if (NULL != t->kx_ctx)
585 key = &t->kx_ctx->d_key_old;
589 GNUNET_STATISTICS_update (stats, "# non decryptable data", 1, GNUNET_NO);
590 LOG (GNUNET_ERROR_TYPE_DEBUG,
591 "WARNING got data on %s without a valid key\n",
597 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_decrypt iv\n");
598 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
599 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_decrypt iv done\n");
600 out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, key, &siv, dst);
601 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_decrypt end\n");
608 * Create key material by doing ECDH on the local and remote ephemeral keys.
610 * @param key_material Where to store the key material.
611 * @param ephemeral_key Peer's public ephemeral key.
614 derive_key_material (struct GNUNET_HashCode *key_material,
615 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key)
618 GNUNET_CRYPTO_ecc_ecdh (my_ephemeral_key,
627 * Create a symmetic key from the identities of both ends and the key material
630 * @param key Destination for the generated key.
631 * @param sender ID of the peer that will encrypt with @c key.
632 * @param receiver ID of the peer that will decrypt with @c key.
633 * @param key_material Hash created with ECDH with the ephemeral keys.
636 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
637 const struct GNUNET_PeerIdentity *sender,
638 const struct GNUNET_PeerIdentity *receiver,
639 const struct GNUNET_HashCode *key_material)
641 const char salt[] = "CADET kx salt";
643 GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
645 key_material, sizeof (struct GNUNET_HashCode),
646 sender, sizeof (struct GNUNET_PeerIdentity),
647 receiver, sizeof (struct GNUNET_PeerIdentity),
652 * Pick a connection on which send the next data message.
654 * @param t Tunnel on which to send the message.
656 * @return The connection on which to send the next message.
658 static struct CadetConnection *
659 tunnel_get_connection (struct CadetTunnel *t)
661 struct CadetTConnection *iter;
662 struct CadetConnection *best;
664 unsigned int lowest_q;
666 LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GCT_2s (t));
669 for (iter = t->connection_head; NULL != iter; iter = iter->next)
671 LOG (GNUNET_ERROR_TYPE_DEBUG, " connection %s: %u\n",
672 GCC_2s (iter->c), GCC_get_state (iter->c));
673 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
675 qn = GCC_get_qn (iter->c, GCC_is_origin (iter->c, GNUNET_YES));
676 LOG (GNUNET_ERROR_TYPE_DEBUG, " q_n %u, \n", qn);
684 LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GCC_2s (best));
690 * Callback called when a queued message is sent.
692 * Calculates the average time and connection packet tracking.
694 * @param cls Closure (TunnelQueue handle).
695 * @param c Connection this message was on.
696 * @param q Connection queue handle (unused).
697 * @param type Type of message sent.
698 * @param fwd Was this a FWD going message?
699 * @param size Size of the message.
702 tun_message_sent (void *cls,
703 struct CadetConnection *c,
704 struct CadetConnectionQueue *q,
705 uint16_t type, int fwd, size_t size)
707 struct CadetTunnelQueue *qt = cls;
708 struct CadetTunnel *t;
710 LOG (GNUNET_ERROR_TYPE_DEBUG, "tun_message_sent\n");
712 GNUNET_assert (NULL != qt->cont);
713 t = NULL == c ? NULL : GCC_get_tunnel (c);
714 qt->cont (qt->cont_cls, t, qt, type, size);
720 * Delete a queued message: either was sent or the channel was destroyed
721 * before the tunnel's key exchange had a chance to finish.
723 * @param tqd Delayed queue handle.
726 unqueue_data (struct CadetTunnelDelayed *tqd)
728 GNUNET_CONTAINER_DLL_remove (tqd->t->tq_head, tqd->t->tq_tail, tqd);
734 * Cache a message to be sent once tunnel is online.
736 * @param t Tunnel to hold the message.
737 * @param msg Message itself (copy will be made).
739 static struct CadetTunnelDelayed *
740 queue_data (struct CadetTunnel *t, const struct GNUNET_MessageHeader *msg)
742 struct CadetTunnelDelayed *tqd;
743 uint16_t size = ntohs (msg->size);
745 LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GCT_2s (t));
747 if (GNUNET_YES == is_ready (t))
753 tqd = GNUNET_malloc (sizeof (struct CadetTunnelDelayed) + size);
756 memcpy (&tqd[1], msg, size);
757 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
765 * @param t Tunnel to get keys from.
766 * @param plaintext Content to HMAC.
767 * @param size Size of @c plaintext.
768 * @param iv Initialization vector for the message.
769 * @param outgoing Is this an outgoing message that we encrypted?
770 * @param hmac Destination to store the HMAC.
773 t_hmac (struct CadetTunnel *t, const void *plaintext, size_t size, uint32_t iv,
774 int outgoing, struct GNUNET_CADET_Hash *hmac)
776 struct GNUNET_CRYPTO_AuthKey auth_key;
777 static const char ctx[] = "cadet authentication key";
778 struct GNUNET_CRYPTO_SymmetricSessionKey *key;
779 struct GNUNET_HashCode hash;
781 key = outgoing ? &t->e_key : &t->d_key;
782 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
787 GNUNET_CRYPTO_hmac (&auth_key, plaintext, size, &hash);
788 memcpy (hmac, &hash, sizeof (*hmac));
793 * Sends an already built message on a tunnel, encrypting it and
794 * choosing the best connection.
796 * @param message Message to send. Function modifies it.
797 * @param t Tunnel on which this message is transmitted.
798 * @param c Connection to use (autoselect if NULL).
799 * @param force Force the tunnel to take the message (buffer overfill).
800 * @param cont Continuation to call once message is really sent.
801 * @param cont_cls Closure for @c cont.
802 * @param existing_q In case this a transmission of previously queued data,
803 * this should be TunnelQueue given to the client.
806 * @return Handle to cancel message. NULL if @c cont is NULL.
808 static struct CadetTunnelQueue *
809 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
810 struct CadetTunnel *t, struct CadetConnection *c,
811 int force, GCT_sent cont, void *cont_cls,
812 struct CadetTunnelQueue *existing_q)
814 struct CadetTunnelQueue *tq;
815 struct GNUNET_CADET_Encrypted *msg;
816 size_t size = ntohs (message->size);
817 char cbuf[sizeof (struct GNUNET_CADET_Encrypted) + size];
823 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GCT_2s (t));
825 if (GNUNET_NO == is_ready (t))
827 struct CadetTunnelDelayed *tqd;
828 /* A non null existing_q indicates sending of queued data.
829 * Should only happen after tunnel becomes ready.
831 GNUNET_assert (NULL == existing_q);
832 tqd = queue_data (t, message);
835 tq = GNUNET_new (struct CadetTunnelQueue);
839 tq->cont_cls = cont_cls;
843 GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
845 iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
846 msg = (struct GNUNET_CADET_Encrypted *) cbuf;
847 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
849 GNUNET_assert (t_encrypt (t, &msg[1], message, size, iv) == size);
850 t_hmac (t, &msg[1], size, iv, GNUNET_YES, &msg->hmac);
851 msg->header.size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
854 c = tunnel_get_connection (t);
857 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task
858 || CADET_TUNNEL3_SEARCHING != t->cstate)
867 type = ntohs (message->type);
870 case GNUNET_MESSAGE_TYPE_CADET_DATA:
871 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
872 if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
873 mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
875 mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
877 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
878 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
879 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
880 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
881 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
882 msg->cid = *GCC_get_id (c);
883 msg->ttl = htonl (default_ttl);
888 LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
890 fwd = GCC_is_origin (c, GNUNET_YES);
894 GNUNET_break (NULL ==
895 GCC_send_prebuilt_message (&msg->header, type, mid,
896 c, fwd, force, NULL, NULL));
899 if (NULL == existing_q)
901 tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
908 tq->cq = GCC_send_prebuilt_message (&msg->header, type, mid, c, fwd, force,
909 &tun_message_sent, tq);
911 tq->cont_cls = cont_cls;
918 * Send all cached messages that we can, tunnel is online.
920 * @param t Tunnel that holds the messages. Cannot be loopback.
923 send_queued_data (struct CadetTunnel *t)
925 struct CadetTunnelDelayed *tqd;
926 struct CadetTunnelDelayed *next;
929 LOG (GNUNET_ERROR_TYPE_DEBUG,
930 "GCT_send_queued_data on tunnel %s\n",
933 if (GCT_is_loopback (t))
939 if (GNUNET_NO == is_ready (t))
941 LOG (GNUNET_ERROR_TYPE_DEBUG, " not ready yet: %s/%s\n",
942 estate2s (t->estate), cstate2s (t->cstate));
946 room = GCT_get_connections_buffer (t);
947 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
948 LOG (GNUNET_ERROR_TYPE_DEBUG, " tq head: %p\n", t->tq_head);
949 for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
951 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
954 send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
955 tqd->t, NULL, GNUNET_YES,
956 NULL != tqd->tq ? tqd->tq->cont : NULL,
957 NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
961 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
966 * Sends key exchange message on a tunnel, choosing the best connection.
967 * Should not be called on loopback tunnels.
969 * @param t Tunnel on which this message is transmitted.
970 * @param message Message to send. Function modifies it.
973 send_kx (struct CadetTunnel *t,
974 const struct GNUNET_MessageHeader *message)
976 struct CadetConnection *c;
977 struct GNUNET_CADET_KX *msg;
978 size_t size = ntohs (message->size);
979 char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
983 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
985 /* Avoid loopback. */
986 if (GCT_is_loopback (t))
988 LOG (GNUNET_ERROR_TYPE_DEBUG, " loopback!\n");
993 /* Even if tunnel is being destroyed, send anyway.
994 * Could be a response to a rekey initiated by remote peer,
995 * who is trying to create a new channel!
998 /* Must have a connection. */
999 if (NULL == t->connection_head)
1001 GNUNET_break (CADET_TUNNEL3_SEARCHING == t->cstate);
1006 msg = (struct GNUNET_CADET_KX *) cbuf;
1007 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
1008 msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
1009 c = tunnel_get_connection (t);
1012 GNUNET_break (GNUNET_SCHEDULER_NO_TASK != t->destroy_task
1013 || CADET_TUNNEL3_READY != t->cstate);
1017 type = ntohs (message->type);
1020 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
1021 case GNUNET_MESSAGE_TYPE_CADET_KX_PING:
1022 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
1023 memcpy (&msg[1], message, size);
1026 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
1031 fwd = GCC_is_origin (t->connection_head->c, GNUNET_YES);
1032 /* TODO save handle and cancel in case of a unneeded retransmission */
1033 GCC_send_prebuilt_message (&msg->header, GNUNET_MESSAGE_TYPE_CADET_KX,
1034 message->type, c, fwd, GNUNET_YES, NULL, NULL);
1039 * Send the ephemeral key on a tunnel.
1041 * @param t Tunnel on which to send the key.
1044 send_ephemeral (struct CadetTunnel *t)
1046 LOG (GNUNET_ERROR_TYPE_INFO, "=> EPHM for %s\n", GCT_2s (t));
1048 kx_msg.sender_status = htonl (t->estate);
1049 send_kx (t, &kx_msg.header);
1053 * Send a ping message on a tunnel.
1055 * @param t Tunnel on which to send the ping.
1058 send_ping (struct CadetTunnel *t)
1060 struct GNUNET_CADET_KX_Ping msg;
1062 LOG (GNUNET_ERROR_TYPE_INFO, "=> PING for %s\n", GCT_2s (t));
1063 msg.header.size = htons (sizeof (msg));
1064 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PING);
1065 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1066 msg.target = *GCP_get_id (t->peer);
1067 msg.nonce = t->kx_ctx->challenge;
1069 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
1070 LOG (GNUNET_ERROR_TYPE_DEBUG, " towards %s\n", GNUNET_i2s (&msg.target));
1071 t_encrypt (t, &msg.target, &msg.target, ping_encryption_size(), msg.iv);
1072 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
1073 LOG (GNUNET_ERROR_TYPE_DEBUG, " e towards %s\n", GNUNET_i2s (&msg.target));
1075 send_kx (t, &msg.header);
1080 * Send a pong message on a tunnel.
1082 * @param t Tunnel on which to send the pong.
1083 * @param challenge Value sent in the ping that we have to send back.
1086 send_pong (struct CadetTunnel *t, uint32_t challenge)
1088 struct GNUNET_CADET_KX_Pong msg;
1090 LOG (GNUNET_ERROR_TYPE_INFO, "=> PONG for %s\n", GCT_2s (t));
1091 msg.header.size = htons (sizeof (msg));
1092 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
1093 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1094 msg.nonce = challenge;
1095 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
1096 t_encrypt (t, &msg.nonce, &msg.nonce, sizeof (msg.nonce), msg.iv);
1097 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
1099 send_kx (t, &msg.header);
1104 * Initiate a rekey with the remote peer.
1106 * @param cls Closure (tunnel).
1107 * @param tc TaskContext.
1110 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1112 struct CadetTunnel *t = cls;
1114 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1116 LOG (GNUNET_ERROR_TYPE_DEBUG, "Re-key Tunnel %s\n", GCT_2s (t));
1117 if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1120 if (NULL == t->kx_ctx)
1122 LOG (GNUNET_ERROR_TYPE_DEBUG, " new kx ctx\n");
1123 t->kx_ctx = GNUNET_new (struct CadetTunnelKXCtx);
1124 t->kx_ctx->challenge =
1125 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1126 t->kx_ctx->d_key_old = t->d_key;
1127 LOG (GNUNET_ERROR_TYPE_DEBUG, " new challenge for %s: %u\n",
1128 GCT_2s (t), t->kx_ctx->challenge);
1133 case CADET_TUNNEL3_KEY_UNINITIALIZED:
1134 t->estate = CADET_TUNNEL3_KEY_SENT;
1136 case CADET_TUNNEL3_KEY_SENT:
1138 case CADET_TUNNEL3_KEY_PING:
1139 case CADET_TUNNEL3_KEY_OK:
1141 t->estate = CADET_TUNNEL3_KEY_PING;
1144 LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
1147 LOG (GNUNET_ERROR_TYPE_DEBUG, " next call in %s\n",
1148 GNUNET_STRINGS_relative_time_to_string (REKEY_WAIT, GNUNET_YES));
1149 t->rekey_task = GNUNET_SCHEDULER_add_delayed (REKEY_WAIT, &rekey_tunnel, t);
1154 * Our ephemeral key has changed, create new session key on all tunnels.
1156 * Each tunnel will start the Key Exchange with a random delay between
1157 * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
1158 * per second, on average.
1160 * @param cls Closure (size of the hashmap).
1161 * @param key Current public key.
1162 * @param value Value in the hash map (tunnel).
1164 * @return #GNUNET_YES, so we should continue to iterate,
1167 rekey_iterator (void *cls,
1168 const struct GNUNET_PeerIdentity *key,
1171 struct CadetTunnel *t = value;
1172 struct GNUNET_TIME_Relative delay;
1173 long n = (long) cls;
1176 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
1179 if (GNUNET_YES == GCT_is_loopback (t))
1182 r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
1183 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
1184 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1191 * Create a new ephemeral key and key message, schedule next rekeying.
1193 * @param cls Closure (unused).
1194 * @param tc TaskContext.
1197 rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1199 struct GNUNET_TIME_Absolute time;
1202 rekey_task = GNUNET_SCHEDULER_NO_TASK;
1204 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1207 GNUNET_free_non_null (my_ephemeral_key);
1208 my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
1210 time = GNUNET_TIME_absolute_get ();
1211 kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
1212 time = GNUNET_TIME_absolute_add (time, rekey_period);
1213 time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
1214 kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
1215 GNUNET_CRYPTO_ecdhe_key_get_public (my_ephemeral_key, &kx_msg.ephemeral_key);
1217 GNUNET_assert (GNUNET_OK ==
1218 GNUNET_CRYPTO_eddsa_sign (my_private_key,
1220 &kx_msg.signature));
1222 n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
1223 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
1225 rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period, &rekey, NULL);
1230 * Called only on shutdown, destroy every tunnel.
1232 * @param cls Closure (unused).
1233 * @param key Current public key.
1234 * @param value Value in the hash map (tunnel).
1236 * @return #GNUNET_YES, so we should continue to iterate,
1239 destroy_iterator (void *cls,
1240 const struct GNUNET_PeerIdentity *key,
1243 struct CadetTunnel *t = value;
1245 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
1252 * Notify remote peer that we don't know a channel he is talking about,
1253 * probably CHANNEL_DESTROY was missed.
1255 * @param t Tunnel on which to notify.
1256 * @param gid ID of the channel.
1259 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
1261 struct GNUNET_CADET_ChannelManage msg;
1263 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
1264 msg.header.size = htons (sizeof (msg));
1265 msg.chid = htonl (gid);
1267 LOG (GNUNET_ERROR_TYPE_DEBUG,
1268 "WARNING destroying unknown channel %u on tunnel %s\n",
1270 send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
1275 * Demultiplex data per channel and call appropriate channel handler.
1277 * @param t Tunnel on which the data came.
1278 * @param msg Data message.
1279 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1280 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1281 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1282 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1285 handle_data (struct CadetTunnel *t,
1286 const struct GNUNET_CADET_Data *msg,
1289 struct CadetChannel *ch;
1293 size = ntohs (msg->header.size);
1295 sizeof (struct GNUNET_CADET_Data) +
1296 sizeof (struct GNUNET_MessageHeader))
1301 LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
1302 GC_m2s (ntohs (msg[1].header.type)));
1305 ch = GCT_get_channel (t, ntohl (msg->chid));
1308 GNUNET_STATISTICS_update (stats, "# data on unknown channel",
1310 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
1312 send_channel_destroy (t, ntohl (msg->chid));
1316 GCCH_handle_data (ch, msg, fwd);
1321 * Demultiplex data ACKs per channel and update appropriate channel buffer info.
1323 * @param t Tunnel on which the DATA ACK came.
1324 * @param msg DATA ACK message.
1325 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1326 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1327 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1328 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1331 handle_data_ack (struct CadetTunnel *t,
1332 const struct GNUNET_CADET_DataACK *msg,
1335 struct CadetChannel *ch;
1339 size = ntohs (msg->header.size);
1340 if (size != sizeof (struct GNUNET_CADET_DataACK))
1347 ch = GCT_get_channel (t, ntohl (msg->chid));
1350 GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
1352 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1357 GCCH_handle_data_ack (ch, msg, fwd);
1362 * Handle channel create.
1364 * @param t Tunnel on which the data came.
1365 * @param msg Data message.
1368 handle_ch_create (struct CadetTunnel *t,
1369 const struct GNUNET_CADET_ChannelCreate *msg)
1371 struct CadetChannel *ch;
1375 size = ntohs (msg->header.size);
1376 if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
1383 ch = GCT_get_channel (t, ntohl (msg->chid));
1384 if (NULL != ch && ! GCT_is_loopback (t))
1386 /* Probably a retransmission, safe to ignore */
1387 LOG (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
1389 ch = GCCH_handle_create (t, msg);
1391 GCT_add_channel (t, ch);
1397 * Handle channel NACK: check correctness and call channel handler for NACKs.
1399 * @param t Tunnel on which the NACK came.
1400 * @param msg NACK message.
1403 handle_ch_nack (struct CadetTunnel *t,
1404 const struct GNUNET_CADET_ChannelManage *msg)
1406 struct CadetChannel *ch;
1410 size = ntohs (msg->header.size);
1411 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1418 ch = GCT_get_channel (t, ntohl (msg->chid));
1421 GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
1423 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1428 GCCH_handle_nack (ch);
1433 * Handle a CHANNEL ACK (SYNACK/ACK).
1435 * @param t Tunnel on which the CHANNEL ACK came.
1436 * @param msg CHANNEL ACK message.
1437 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1438 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1439 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1440 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1443 handle_ch_ack (struct CadetTunnel *t,
1444 const struct GNUNET_CADET_ChannelManage *msg,
1447 struct CadetChannel *ch;
1451 size = ntohs (msg->header.size);
1452 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1459 ch = GCT_get_channel (t, ntohl (msg->chid));
1462 GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
1464 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1469 GCCH_handle_ack (ch, msg, fwd);
1475 * Handle a channel destruction message.
1477 * @param t Tunnel on which the message came.
1478 * @param msg Channel destroy message.
1479 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1480 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1481 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1482 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1485 handle_ch_destroy (struct CadetTunnel *t,
1486 const struct GNUNET_CADET_ChannelManage *msg,
1489 struct CadetChannel *ch;
1493 size = ntohs (msg->header.size);
1494 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1501 ch = GCT_get_channel (t, ntohl (msg->chid));
1504 /* Probably a retransmission, safe to ignore */
1508 GCCH_handle_destroy (ch, msg, fwd);
1513 * The peer's ephemeral key has changed: update the symmetrical keys.
1515 * @param t Tunnel this message came on.
1516 * @param msg Key eXchange message.
1519 handle_ephemeral (struct CadetTunnel *t,
1520 const struct GNUNET_CADET_KX_Ephemeral *msg)
1522 struct GNUNET_HashCode km;
1523 LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
1525 if (GNUNET_OK != check_ephemeral (t, msg))
1527 GNUNET_break_op (0);
1530 derive_key_material (&km, &msg->ephemeral_key);
1531 LOG (GNUNET_ERROR_TYPE_DEBUG, " km is %s\n", GNUNET_h2s (&km));
1532 derive_symmertic (&t->e_key, &my_full_id, GCP_get_id (t->peer), &km);
1533 derive_symmertic (&t->d_key, GCP_get_id (t->peer), &my_full_id, &km);
1534 if (CADET_TUNNEL3_KEY_SENT == t->estate)
1536 LOG (GNUNET_ERROR_TYPE_DEBUG, " our key was sent, send ping\n");
1538 t->estate = CADET_TUNNEL3_KEY_PING;
1544 * Peer wants to check our symmetrical keys by sending an encrypted challenge.
1545 * Answer with by retransmitting the challenge with the "opposite" key.
1547 * @param t Tunnel this message came on.
1548 * @param msg Key eXchange Ping message.
1551 handle_ping (struct CadetTunnel *t,
1552 const struct GNUNET_CADET_KX_Ping *msg)
1554 struct GNUNET_CADET_KX_Ping res;
1556 if (ntohs (msg->header.size) != sizeof (res))
1558 GNUNET_break_op (0);
1562 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PING for %s\n", GCT_2s (t));
1563 t_decrypt (t, &res.target, &msg->target, ping_encryption_size (), msg->iv);
1564 if (0 != memcmp (&my_full_id, &res.target, sizeof (my_full_id)))
1566 GNUNET_STATISTICS_update (stats, "# malformed PINGs", 1, GNUNET_NO);
1567 LOG (GNUNET_ERROR_TYPE_WARNING, " malformed PING on %s\n", GCT_2s (t));
1568 LOG (GNUNET_ERROR_TYPE_DEBUG, " e got %u\n", msg->nonce);
1569 LOG (GNUNET_ERROR_TYPE_DEBUG, " e towards %s\n", GNUNET_i2s (&msg->target));
1570 LOG (GNUNET_ERROR_TYPE_DEBUG, " got %u\n", res.nonce);
1571 LOG (GNUNET_ERROR_TYPE_DEBUG, " towards %s\n", GNUNET_i2s (&res.target));
1577 send_pong (t, res.nonce);
1582 * Peer has answer to our challenge.
1583 * If answer is successful, consider the key exchange finished and clean
1584 * up all related state.
1586 * @param t Tunnel this message came on.
1587 * @param msg Key eXchange Pong message.
1590 handle_pong (struct CadetTunnel *t,
1591 const struct GNUNET_CADET_KX_Pong *msg)
1595 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
1596 if (GNUNET_SCHEDULER_NO_TASK == t->rekey_task)
1598 GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
1601 t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
1603 if (challenge != t->kx_ctx->challenge)
1605 LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
1606 LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
1607 challenge, msg->nonce, t->kx_ctx->challenge);
1612 GNUNET_SCHEDULER_cancel (t->rekey_task);
1613 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1614 GNUNET_free (t->kx_ctx);
1616 GCT_change_estate (t, CADET_TUNNEL3_KEY_OK);
1621 * Demultiplex by message type and call appropriate handler for a message
1622 * towards a channel of a local tunnel.
1624 * @param t Tunnel this message came on.
1625 * @param msgh Message header.
1626 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1627 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1628 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1629 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1632 handle_decrypted (struct CadetTunnel *t,
1633 const struct GNUNET_MessageHeader *msgh,
1638 type = ntohs (msgh->type);
1639 LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
1643 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1644 /* Do nothing, connection aleady got updated. */
1645 GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
1648 case GNUNET_MESSAGE_TYPE_CADET_DATA:
1649 /* Don't send hop ACK, wait for client to ACK */
1650 handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
1653 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1654 handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
1657 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1658 handle_ch_create (t,
1659 (struct GNUNET_CADET_ChannelCreate *) msgh);
1662 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1664 (struct GNUNET_CADET_ChannelManage *) msgh);
1667 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1669 (struct GNUNET_CADET_ChannelManage *) msgh,
1673 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1674 handle_ch_destroy (t,
1675 (struct GNUNET_CADET_ChannelManage *) msgh,
1680 GNUNET_break_op (0);
1681 LOG (GNUNET_ERROR_TYPE_WARNING,
1682 "end-to-end message not known (%u)\n",
1683 ntohs (msgh->type));
1688 /******************************************************************************/
1689 /******************************** API ***********************************/
1690 /******************************************************************************/
1693 * Decrypt and demultiplex by message type. Call appropriate handler
1694 * for every message.
1696 * @param t Tunnel this message came on.
1697 * @param msg Encrypted message.
1700 GCT_handle_encrypted (struct CadetTunnel *t,
1701 const struct GNUNET_CADET_Encrypted *msg)
1703 size_t size = ntohs (msg->header.size);
1704 size_t payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
1705 size_t decrypted_size;
1706 char cbuf [payload_size];
1707 struct GNUNET_MessageHeader *msgh;
1709 struct GNUNET_CADET_Hash hmac;
1711 decrypted_size = t_decrypt (t, cbuf, &msg[1], payload_size, msg->iv);
1712 t_hmac (t, &msg[1], payload_size, msg->iv, GNUNET_NO, &hmac);
1713 if (0 != memcmp (&hmac, &msg->hmac, sizeof (hmac)))
1715 /* checksum failed */
1716 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1717 "Failed checksum validation for a message on tunnel `%s'\n",
1719 GNUNET_STATISTICS_update (stats, "# wrong HMAC", 1, GNUNET_NO);
1723 while (off < decrypted_size)
1725 msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
1726 handle_decrypted (t, msgh, GNUNET_SYSERR);
1727 off += ntohs (msgh->size);
1733 * Demultiplex an encapsulated KX message by message type.
1735 * @param t Tunnel on which the message came.
1736 * @param message Payload of KX message.
1739 GCT_handle_kx (struct CadetTunnel *t,
1740 const struct GNUNET_MessageHeader *message)
1744 type = ntohs (message->type);
1745 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received\n", type);
1748 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
1749 handle_ephemeral (t, (struct GNUNET_CADET_KX_Ephemeral *) message);
1752 case GNUNET_MESSAGE_TYPE_CADET_KX_PING:
1753 handle_ping (t, (struct GNUNET_CADET_KX_Ping *) message);
1756 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
1757 handle_pong (t, (struct GNUNET_CADET_KX_Pong *) message);
1761 GNUNET_break_op (0);
1762 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message not known (%u)\n", type);
1768 * Initialize the tunnel subsystem.
1770 * @param c Configuration handle.
1771 * @param key ECC private key, to derive all other keys and do crypto.
1774 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
1775 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
1777 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
1779 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
1782 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1783 "CADET", "DEFAULT_TTL", "USING DEFAULT");
1787 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
1790 rekey_period = GNUNET_TIME_UNIT_DAYS;
1793 my_private_key = key;
1794 kx_msg.header.size = htons (sizeof (kx_msg));
1795 kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
1796 kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
1797 kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
1798 kx_msg.origin_identity = my_full_id;
1799 rekey_task = GNUNET_SCHEDULER_add_now (&rekey, NULL);
1801 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
1806 * Shut down the tunnel subsystem.
1811 if (GNUNET_SCHEDULER_NO_TASK != rekey_task)
1813 GNUNET_SCHEDULER_cancel (rekey_task);
1814 rekey_task = GNUNET_SCHEDULER_NO_TASK;
1816 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
1817 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
1824 * @param destination Peer this tunnel is towards.
1826 struct CadetTunnel *
1827 GCT_new (struct CadetPeer *destination)
1829 struct CadetTunnel *t;
1831 t = GNUNET_new (struct CadetTunnel);
1833 t->peer = destination;
1836 GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
1837 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
1848 * Change the tunnel's connection state.
1850 * @param t Tunnel whose connection state to change.
1851 * @param cstate New connection state.
1854 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
1858 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
1859 GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
1860 if (myid != GCP_get_short_id (t->peer) &&
1861 CADET_TUNNEL3_READY != t->cstate &&
1862 CADET_TUNNEL3_READY == cstate)
1865 if (CADET_TUNNEL3_KEY_OK == t->estate)
1867 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered send queued data\n");
1868 send_queued_data (t);
1870 else if (CADET_TUNNEL3_KEY_UNINITIALIZED == t->estate)
1872 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered rekey\n");
1873 rekey_tunnel (t, NULL);
1878 if (CADET_TUNNEL3_READY == cstate
1879 && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
1881 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered stop dht\n");
1882 GCP_stop_search (t->peer);
1887 * Change the tunnel encryption state.
1889 * @param t Tunnel whose encryption state to change.
1890 * @param state New encryption state.
1893 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
1897 LOG (GNUNET_ERROR_TYPE_DEBUG,
1898 "Tunnel %s estate was %s\n",
1899 GCP_2s (t->peer), estate2s (t->estate));
1900 LOG (GNUNET_ERROR_TYPE_DEBUG,
1901 "Tunnel %s estate is now %s\n",
1902 GCP_2s (t->peer), estate2s (state));
1903 if (myid != GCP_get_short_id (t->peer) &&
1904 CADET_TUNNEL3_KEY_OK != t->estate && CADET_TUNNEL3_KEY_OK == state)
1907 send_queued_data (t);
1915 * @brief Check if tunnel has too many connections, and remove one if necessary.
1917 * Currently this means the newest connection, unless it is a direct one.
1918 * Implemented as a task to avoid freeing a connection that is in the middle
1919 * of being created/processed.
1921 * @param cls Closure (Tunnel to check).
1922 * @param tc Task context.
1925 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1927 struct CadetTunnel *t = cls;
1929 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1932 if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
1934 struct CadetTConnection *iter;
1935 struct CadetTConnection *c;
1937 for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
1939 if ((NULL == c || iter->created.abs_value_us > c->created.abs_value_us)
1940 && GNUNET_NO == GCC_is_direct (iter->c))
1947 LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
1949 LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
1962 * Add a connection to a tunnel.
1965 * @param c Connection.
1968 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
1970 struct CadetTConnection *aux;
1972 GNUNET_assert (NULL != c);
1974 LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
1975 LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
1976 for (aux = t->connection_head; aux != NULL; aux = aux->next)
1980 aux = GNUNET_new (struct CadetTConnection);
1982 aux->created = GNUNET_TIME_absolute_get ();
1984 GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
1986 GNUNET_SCHEDULER_add_now (&trim_connections, t);
1991 * Mark a path as no longer valid for this tunnel: has been tried and failed.
1993 * @param t Tunnel to update.
1994 * @param path Invalid path to remove. Is destroyed after removal.
1997 GCT_remove_path (struct CadetTunnel *t, struct CadetPeerPath *path)
1999 GCP_remove_path (t->peer, path);
2004 * Remove a connection from a tunnel.
2007 * @param c Connection.
2010 GCT_remove_connection (struct CadetTunnel *t,
2011 struct CadetConnection *c)
2013 struct CadetTConnection *aux;
2014 struct CadetTConnection *next;
2016 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
2017 GCC_2s (c), GCT_2s (t));
2018 for (aux = t->connection_head; aux != NULL; aux = next)
2023 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
2028 /* Start new connections if needed */
2029 if (CONNECTIONS_PER_TUNNEL < GCT_count_connections (t)
2030 && GNUNET_SCHEDULER_NO_TASK == t->destroy_task
2031 && CADET_TUNNEL3_SHUTDOWN != t->cstate
2032 && GNUNET_NO == shutting_down)
2034 LOG (GNUNET_ERROR_TYPE_DEBUG, " no more connections, getting new ones\n");
2035 t->cstate = CADET_TUNNEL3_SEARCHING;
2036 GCP_connect (t->peer);
2040 /* If not marked as ready, no change is needed */
2041 if (CADET_TUNNEL3_READY != t->cstate)
2044 /* Check if any connection is ready to maintaing cstate */
2045 for (aux = t->connection_head; aux != NULL; aux = aux->next)
2046 if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
2049 t->cstate = CADET_TUNNEL3_WAITING;
2054 * Add a channel to a tunnel.
2057 * @param ch Channel.
2060 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2062 struct CadetTChannel *aux;
2064 GNUNET_assert (NULL != ch);
2066 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
2068 for (aux = t->channel_head; aux != NULL; aux = aux->next)
2070 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
2075 aux = GNUNET_new (struct CadetTChannel);
2077 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
2078 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
2080 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2082 GNUNET_SCHEDULER_cancel (t->destroy_task);
2083 t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2084 LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
2090 * Remove a channel from a tunnel.
2093 * @param ch Channel.
2096 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2098 struct CadetTChannel *aux;
2100 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
2101 for (aux = t->channel_head; aux != NULL; aux = aux->next)
2105 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
2106 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
2115 * Search for a channel by global ID.
2117 * @param t Tunnel containing the channel.
2118 * @param chid Public channel number.
2120 * @return channel handler, NULL if doesn't exist
2122 struct CadetChannel *
2123 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
2125 struct CadetTChannel *iter;
2130 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2132 if (GCCH_get_id (iter->ch) == chid)
2136 return NULL == iter ? NULL : iter->ch;
2141 * @brief Destroy a tunnel and free all resources.
2143 * Should only be called a while after the tunnel has been marked as destroyed,
2144 * in case there is a new channel added to the same peer shortly after marking
2145 * the tunnel. This way we avoid a new public key handshake.
2147 * @param cls Closure (tunnel to destroy).
2148 * @param tc Task context.
2151 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2153 struct CadetTunnel *t = cls;
2154 struct CadetTConnection *iter;
2156 LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
2157 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2159 LOG (GNUNET_ERROR_TYPE_WARNING,
2160 "Not destroying tunnel, due to shutdown. "
2161 "Tunnel at %p should have been freed by GCT_shutdown\n", t);
2164 t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2165 t->cstate = CADET_TUNNEL3_SHUTDOWN;
2167 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2169 GCC_send_destroy (iter->c);
2176 * Tunnel is empty: destroy it.
2178 * Notifies all connections about the destruction.
2180 * @param t Tunnel to destroy.
2183 GCT_destroy_empty (struct CadetTunnel *t)
2185 if (GNUNET_YES == shutting_down)
2186 return; /* Will be destroyed immediately anyway */
2188 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2190 LOG (GNUNET_ERROR_TYPE_DEBUG,
2191 "Tunnel %s is already scheduled for destruction\n",
2194 /* should never happen, tunnel can only become empty once, and the
2195 * task identifier should be NO_TASK (cleaned when the tunnel was created
2196 * or became un-empty)
2201 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: destroying scheduled\n",
2204 t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
2205 &delayed_destroy, t);
2206 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llX\n",
2207 t, t->destroy_task);
2212 * Destroy tunnel if empty (no more channels).
2214 * @param t Tunnel to destroy if empty.
2217 GCT_destroy_if_empty (struct CadetTunnel *t)
2219 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
2220 if (1 < GCT_count_channels (t))
2223 GCT_destroy_empty (t);
2228 * Destroy the tunnel.
2230 * This function does not generate any warning traffic to clients or peers.
2233 * Cancel messages belonging to this tunnel queued to neighbors.
2234 * Free any allocated resources linked to the tunnel.
2236 * @param t The tunnel to destroy.
2239 GCT_destroy (struct CadetTunnel *t)
2241 struct CadetTConnection *iter_c;
2242 struct CadetTConnection *next_c;
2243 struct CadetTChannel *iter_ch;
2244 struct CadetTChannel *next_ch;
2249 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
2251 GNUNET_break (GNUNET_YES ==
2252 GNUNET_CONTAINER_multipeermap_remove (tunnels,
2253 GCP_get_id (t->peer), t));
2255 for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
2257 next_c = iter_c->next;
2258 GCC_destroy (iter_c->c);
2260 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
2262 next_ch = iter_ch->next;
2263 GCCH_destroy (iter_ch->ch);
2264 /* Should only happen on shutdown, but it's ok. */
2267 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2269 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling %llX\n", t->destroy_task);
2270 GNUNET_SCHEDULER_cancel (t->destroy_task);
2271 t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2274 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
2275 GCP_set_tunnel (t->peer, NULL);
2277 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
2279 GNUNET_SCHEDULER_cancel (t->rekey_task);
2280 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
2281 if (NULL != t->kx_ctx)
2282 GNUNET_free (t->kx_ctx);
2292 * @brief Use the given path for the tunnel.
2293 * Update the next and prev hops (and RCs).
2294 * (Re)start the path refresh in case the tunnel is locally owned.
2296 * @param t Tunnel to update.
2297 * @param p Path to use.
2299 * @return Connection created.
2301 struct CadetConnection *
2302 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
2304 struct CadetConnection *c;
2305 struct GNUNET_CADET_Hash cid;
2306 unsigned int own_pos;
2308 if (NULL == t || NULL == p)
2314 if (CADET_TUNNEL3_SHUTDOWN == t->cstate)
2320 for (own_pos = 0; own_pos < p->length; own_pos++)
2322 if (p->peers[own_pos] == myid)
2325 if (own_pos >= p->length)
2327 GNUNET_break_op (0);
2331 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
2332 c = GCC_new (&cid, t, p, own_pos);
2335 /* Path was flawed */
2338 GCT_add_connection (t, c);
2344 * Count established (ready) connections of a tunnel.
2346 * @param t Tunnel on which to count.
2348 * @return Number of connections.
2351 GCT_count_connections (struct CadetTunnel *t)
2353 struct CadetTConnection *iter;
2359 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2360 if (CADET_CONNECTION_DESTROYED != GCC_get_state (iter->c))
2367 * Count channels of a tunnel.
2369 * @param t Tunnel on which to count.
2371 * @return Number of channels.
2374 GCT_count_channels (struct CadetTunnel *t)
2376 struct CadetTChannel *iter;
2379 for (count = 0, iter = t->channel_head;
2381 iter = iter->next, count++) /* skip */;
2388 * Get the connectivity state of a tunnel.
2392 * @return Tunnel's connectivity state.
2394 enum CadetTunnelCState
2395 GCT_get_cstate (struct CadetTunnel *t)
2400 return (enum CadetTunnelCState) -1;
2407 * Get the encryption state of a tunnel.
2411 * @return Tunnel's encryption state.
2413 enum CadetTunnelEState
2414 GCT_get_estate (struct CadetTunnel *t)
2419 return (enum CadetTunnelEState) -1;
2425 * Get the maximum buffer space for a tunnel towards a local client.
2429 * @return Biggest buffer space offered by any channel in the tunnel.
2432 GCT_get_channels_buffer (struct CadetTunnel *t)
2434 struct CadetTChannel *iter;
2435 unsigned int buffer;
2436 unsigned int ch_buf;
2438 if (NULL == t->channel_head)
2440 /* Probably getting buffer for a channel create/handshake. */
2445 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2447 ch_buf = get_channel_buffer (iter);
2448 if (ch_buf > buffer)
2456 * Get the total buffer space for a tunnel for P2P traffic.
2460 * @return Buffer space offered by all connections in the tunnel.
2463 GCT_get_connections_buffer (struct CadetTunnel *t)
2465 struct CadetTConnection *iter;
2466 unsigned int buffer;
2469 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2471 if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
2475 buffer += get_connection_buffer (iter);
2483 * Get the tunnel's destination.
2487 * @return ID of the destination peer.
2489 const struct GNUNET_PeerIdentity *
2490 GCT_get_destination (struct CadetTunnel *t)
2492 return GCP_get_id (t->peer);
2497 * Get the tunnel's next free global channel ID.
2501 * @return GID of a channel free to use.
2504 GCT_get_next_chid (struct CadetTunnel *t)
2506 CADET_ChannelNumber chid;
2507 CADET_ChannelNumber mask;
2510 /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
2511 * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
2512 * If peer's ID is bigger, start at 0x4... bit 30 = 1
2514 result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
2519 t->next_chid |= mask;
2521 while (NULL != GCT_get_channel (t, t->next_chid))
2523 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
2524 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
2525 t->next_chid |= mask;
2527 chid = t->next_chid;
2528 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
2529 t->next_chid |= mask;
2536 * Send ACK on one or more channels due to buffer in connections.
2538 * @param t Channel which has some free buffer space.
2541 GCT_unchoke_channels (struct CadetTunnel *t)
2543 struct CadetTChannel *iter;
2544 unsigned int buffer;
2545 unsigned int channels = GCT_count_channels (t);
2546 unsigned int choked_n;
2547 struct CadetChannel *choked[channels];
2549 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
2550 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
2551 if (NULL != t->channel_head)
2552 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
2554 /* Get buffer space */
2555 buffer = GCT_get_connections_buffer (t);
2561 /* Count and remember choked channels */
2563 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2565 if (GNUNET_NO == get_channel_allowed (iter))
2567 choked[choked_n++] = iter->ch;
2571 /* Unchoke random channels */
2572 while (0 < buffer && 0 < choked_n)
2574 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2576 GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
2579 choked[r] = choked[choked_n];
2585 * Send ACK on one or more connections due to buffer space to the client.
2587 * Iterates all connections of the tunnel and sends ACKs appropriately.
2592 GCT_send_connection_acks (struct CadetTunnel *t)
2594 struct CadetTConnection *iter;
2597 uint32_t allow_per_connection;
2599 unsigned int buffer;
2601 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
2610 buffer = GCT_get_channels_buffer (t);
2611 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer %u\n", buffer);
2613 /* Count connections, how many messages are already allowed */
2614 cs = GCT_count_connections (t);
2615 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2617 allowed += get_connection_allowed (iter);
2619 LOG (GNUNET_ERROR_TYPE_DEBUG, " allowed %u\n", allowed);
2621 /* Make sure there is no overflow */
2622 if (allowed > buffer)
2627 /* Authorize connections to send more data */
2628 to_allow = buffer; /* - allowed; */
2630 for (iter = t->connection_head;
2631 NULL != iter && to_allow > 0;
2634 allow_per_connection = to_allow/cs;
2635 to_allow -= allow_per_connection;
2637 if (get_connection_allowed (iter) > 64 / 3)
2641 GCC_allow (iter->c, allow_per_connection,
2642 GCC_is_origin (iter->c, GNUNET_NO));
2645 GNUNET_break (to_allow == 0);
2650 * Cancel a previously sent message while it's in the queue.
2652 * ONLY can be called before the continuation given to the send function
2653 * is called. Once the continuation is called, the message is no longer in the
2656 * @param q Handle to the queue.
2659 GCT_cancel (struct CadetTunnelQueue *q)
2664 /* tun_message_sent() will be called and free q */
2666 else if (NULL != q->tqd)
2668 unqueue_data (q->tqd);
2670 if (NULL != q->cont)
2671 q->cont (q->cont_cls, NULL, q, 0, 0);
2682 * Sends an already built message on a tunnel, encrypting it and
2683 * choosing the best connection if not provided.
2685 * @param message Message to send. Function modifies it.
2686 * @param t Tunnel on which this message is transmitted.
2687 * @param c Connection to use (autoselect if NULL).
2688 * @param force Force the tunnel to take the message (buffer overfill).
2689 * @param cont Continuation to call once message is really sent.
2690 * @param cont_cls Closure for @c cont.
2692 * @return Handle to cancel message. NULL if @c cont is NULL.
2694 struct CadetTunnelQueue *
2695 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
2696 struct CadetTunnel *t, struct CadetConnection *c,
2697 int force, GCT_sent cont, void *cont_cls)
2699 return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
2704 * Is the tunnel directed towards the local peer?
2708 * @return #GNUNET_YES if it is loopback.
2711 GCT_is_loopback (const struct CadetTunnel *t)
2713 return (myid == GCP_get_short_id (t->peer));
2718 * Is the tunnel this path already?
2723 * @return #GNUNET_YES a connection uses this path.
2726 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
2728 struct CadetTConnection *iter;
2730 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2731 if (GCC_get_path (iter->c) == p)
2739 * Get a cost of a path for a tunnel considering existing connections.
2742 * @param path Candidate path.
2744 * @return Cost of the path (path length + number of overlapping nodes)
2747 GCT_get_path_cost (const struct CadetTunnel *t,
2748 const struct CadetPeerPath *path)
2750 struct CadetTConnection *iter;
2751 const struct CadetPeerPath *aux;
2752 unsigned int overlap;
2760 GNUNET_assert (NULL != t);
2762 for (i = 0; i < path->length; i++)
2764 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2766 aux = GCC_get_path (iter->c);
2770 for (j = 0; j < aux->length; j++)
2772 if (path->peers[i] == aux->peers[j])
2780 return path->length + overlap;
2785 * Get the static string for the peer this tunnel is directed.
2789 * @return Static string the destination peer's ID.
2792 GCT_2s (const struct CadetTunnel *t)
2797 return GCP_2s (t->peer);
2801 /******************************************************************************/
2802 /***************************** INFO/DEBUG *******************************/
2803 /******************************************************************************/
2807 * Log all possible info about the tunnel state to stderr.
2809 * @param t Tunnel to debug.
2812 GCT_debug (const struct CadetTunnel *t)
2814 struct CadetTChannel *iterch;
2815 struct CadetTConnection *iterc;
2817 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
2818 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT cstate %s, estate %s\n",
2819 cstate2s (t->cstate), estate2s (t->estate));
2820 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT kx_ctx %p, rekey_task %u\n",
2821 t->kx_ctx, t->rekey_task);
2822 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT tq_head %p, tq_tail %p\n",
2823 t->tq_head, t->tq_tail);
2824 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT destroy %u\n", t->destroy_task);
2826 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT channels:\n");
2827 for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
2829 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT - %s\n", GCCH_2s (iterch->ch));
2832 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT connections:\n");
2833 for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
2835 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT - %s [%u] buf: %u/%u (qn %u/%u)\n",
2836 GCC_2s (iterc->c), GCC_get_state (iterc->c),
2837 GCC_get_buffer (iterc->c, GNUNET_YES),
2838 GCC_get_buffer (iterc->c, GNUNET_NO),
2839 GCC_get_qn (iterc->c, GNUNET_YES),
2840 GCC_get_qn (iterc->c, GNUNET_NO));
2843 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT DEBUG TUNNEL END\n");
2848 * Iterate all tunnels.
2850 * @param iter Iterator.
2851 * @param cls Closure for @c iter.
2854 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
2856 GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
2861 * Count all tunnels.
2863 * @return Number of tunnels to remote peers kept by this peer.
2866 GCT_count_all (void)
2868 return GNUNET_CONTAINER_multipeermap_size (tunnels);
2873 * Iterate all connections of a tunnel.
2875 * @param t Tunnel whose connections to iterate.
2876 * @param iter Iterator.
2877 * @param cls Closure for @c iter.
2880 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
2882 struct CadetTConnection *ct;
2884 for (ct = t->connection_head; NULL != ct; ct = ct->next)
2890 * Iterate all channels of a tunnel.
2892 * @param t Tunnel whose channels to iterate.
2893 * @param iter Iterator.
2894 * @param cls Closure for @c iter.
2897 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
2899 struct CadetTChannel *cht;
2901 for (cht = t->channel_head; NULL != cht; cht = cht->next)
2902 iter (cls, cht->ch);