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 * Out ephemeral key has changed, create new session key on all tunnels.
1156 * @param cls Closure (size of the hashmap).
1157 * @param key Current public key.
1158 * @param value Value in the hash map (tunnel).
1160 * @return #GNUNET_YES, so we should continue to iterate,
1163 rekey_iterator (void *cls,
1164 const struct GNUNET_PeerIdentity *key,
1167 struct CadetTunnel *t = value;
1168 struct GNUNET_TIME_Relative delay;
1169 long n = (long) cls;
1172 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
1175 if (GNUNET_YES == GCT_is_loopback (t))
1178 r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
1179 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
1180 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1187 * Create a new ephemeral key and key message, schedule next rekeying.
1189 * @param cls Closure (unused).
1190 * @param tc TaskContext.
1193 rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1195 struct GNUNET_TIME_Absolute time;
1198 rekey_task = GNUNET_SCHEDULER_NO_TASK;
1200 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1203 GNUNET_free_non_null (my_ephemeral_key);
1204 my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
1206 time = GNUNET_TIME_absolute_get ();
1207 kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
1208 time = GNUNET_TIME_absolute_add (time, rekey_period);
1209 time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
1210 kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
1211 GNUNET_CRYPTO_ecdhe_key_get_public (my_ephemeral_key, &kx_msg.ephemeral_key);
1213 GNUNET_assert (GNUNET_OK ==
1214 GNUNET_CRYPTO_eddsa_sign (my_private_key,
1216 &kx_msg.signature));
1218 n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
1219 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
1221 rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period, &rekey, NULL);
1226 * Called only on shutdown, destroy every tunnel.
1228 * @param cls Closure (unused).
1229 * @param key Current public key.
1230 * @param value Value in the hash map (tunnel).
1232 * @return #GNUNET_YES, so we should continue to iterate,
1235 destroy_iterator (void *cls,
1236 const struct GNUNET_PeerIdentity *key,
1239 struct CadetTunnel *t = value;
1241 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
1248 * Notify remote peer that we don't know a channel he is talking about,
1249 * probably CHANNEL_DESTROY was missed.
1251 * @param t Tunnel on which to notify.
1252 * @param gid ID of the channel.
1255 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
1257 struct GNUNET_CADET_ChannelManage msg;
1259 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
1260 msg.header.size = htons (sizeof (msg));
1261 msg.chid = htonl (gid);
1263 LOG (GNUNET_ERROR_TYPE_DEBUG,
1264 "WARNING destroying unknown channel %u on tunnel %s\n",
1266 send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
1271 * Demultiplex data per channel and call appropriate channel handler.
1273 * @param t Tunnel on which the data came.
1274 * @param msg Data message.
1275 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1276 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1277 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1278 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1281 handle_data (struct CadetTunnel *t,
1282 const struct GNUNET_CADET_Data *msg,
1285 struct CadetChannel *ch;
1289 size = ntohs (msg->header.size);
1291 sizeof (struct GNUNET_CADET_Data) +
1292 sizeof (struct GNUNET_MessageHeader))
1297 LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
1298 GC_m2s (ntohs (msg[1].header.type)));
1301 ch = GCT_get_channel (t, ntohl (msg->chid));
1304 GNUNET_STATISTICS_update (stats, "# data on unknown channel",
1306 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
1308 send_channel_destroy (t, ntohl (msg->chid));
1312 GCCH_handle_data (ch, msg, fwd);
1317 * Demultiplex data ACKs per channel and update appropriate channel buffer info.
1319 * @param t Tunnel on which the DATA ACK came.
1320 * @param msg DATA ACK message.
1321 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1322 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1323 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1324 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1327 handle_data_ack (struct CadetTunnel *t,
1328 const struct GNUNET_CADET_DataACK *msg,
1331 struct CadetChannel *ch;
1335 size = ntohs (msg->header.size);
1336 if (size != sizeof (struct GNUNET_CADET_DataACK))
1343 ch = GCT_get_channel (t, ntohl (msg->chid));
1346 GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
1348 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1353 GCCH_handle_data_ack (ch, msg, fwd);
1358 * Handle channel create.
1360 * @param t Tunnel on which the data came.
1361 * @param msg Data message.
1364 handle_ch_create (struct CadetTunnel *t,
1365 const struct GNUNET_CADET_ChannelCreate *msg)
1367 struct CadetChannel *ch;
1371 size = ntohs (msg->header.size);
1372 if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
1379 ch = GCT_get_channel (t, ntohl (msg->chid));
1380 if (NULL != ch && ! GCT_is_loopback (t))
1382 /* Probably a retransmission, safe to ignore */
1383 LOG (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
1385 ch = GCCH_handle_create (t, msg);
1387 GCT_add_channel (t, ch);
1393 * Handle channel NACK: check correctness and call channel handler for NACKs.
1395 * @param t Tunnel on which the NACK came.
1396 * @param msg NACK message.
1399 handle_ch_nack (struct CadetTunnel *t,
1400 const struct GNUNET_CADET_ChannelManage *msg)
1402 struct CadetChannel *ch;
1406 size = ntohs (msg->header.size);
1407 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1414 ch = GCT_get_channel (t, ntohl (msg->chid));
1417 GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
1419 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1424 GCCH_handle_nack (ch);
1429 * Handle a CHANNEL ACK (SYNACK/ACK).
1431 * @param t Tunnel on which the CHANNEL ACK came.
1432 * @param msg CHANNEL ACK message.
1433 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1434 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1435 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1436 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1439 handle_ch_ack (struct CadetTunnel *t,
1440 const struct GNUNET_CADET_ChannelManage *msg,
1443 struct CadetChannel *ch;
1447 size = ntohs (msg->header.size);
1448 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1455 ch = GCT_get_channel (t, ntohl (msg->chid));
1458 GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
1460 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1465 GCCH_handle_ack (ch, msg, fwd);
1471 * Handle a channel destruction message.
1473 * @param t Tunnel on which the message came.
1474 * @param msg Channel destroy message.
1475 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1476 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1477 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1478 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1481 handle_ch_destroy (struct CadetTunnel *t,
1482 const struct GNUNET_CADET_ChannelManage *msg,
1485 struct CadetChannel *ch;
1489 size = ntohs (msg->header.size);
1490 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1497 ch = GCT_get_channel (t, ntohl (msg->chid));
1500 /* Probably a retransmission, safe to ignore */
1504 GCCH_handle_destroy (ch, msg, fwd);
1509 * The peer's ephemeral key has changed: update the symmetrical keys.
1511 * @param t Tunnel this message came on.
1512 * @param msg Key eXchange message.
1515 handle_ephemeral (struct CadetTunnel *t,
1516 const struct GNUNET_CADET_KX_Ephemeral *msg)
1518 struct GNUNET_HashCode km;
1519 LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
1521 if (GNUNET_OK != check_ephemeral (t, msg))
1523 GNUNET_break_op (0);
1526 derive_key_material (&km, &msg->ephemeral_key);
1527 LOG (GNUNET_ERROR_TYPE_DEBUG, " km is %s\n", GNUNET_h2s (&km));
1528 derive_symmertic (&t->e_key, &my_full_id, GCP_get_id (t->peer), &km);
1529 derive_symmertic (&t->d_key, GCP_get_id (t->peer), &my_full_id, &km);
1530 if (CADET_TUNNEL3_KEY_SENT == t->estate)
1532 LOG (GNUNET_ERROR_TYPE_DEBUG, " our key was sent, send ping\n");
1534 t->estate = CADET_TUNNEL3_KEY_PING;
1540 * Peer wants to check our symmetrical keys by sending an encrypted challenge.
1541 * Answer with by retransmitting the challenge with the "opposite" key.
1543 * @param t Tunnel this message came on.
1544 * @param msg Key eXchange Ping message.
1547 handle_ping (struct CadetTunnel *t,
1548 const struct GNUNET_CADET_KX_Ping *msg)
1550 struct GNUNET_CADET_KX_Ping res;
1552 if (ntohs (msg->header.size) != sizeof (res))
1554 GNUNET_break_op (0);
1558 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PING for %s\n", GCT_2s (t));
1559 t_decrypt (t, &res.target, &msg->target, ping_encryption_size (), msg->iv);
1560 if (0 != memcmp (&my_full_id, &res.target, sizeof (my_full_id)))
1562 GNUNET_STATISTICS_update (stats, "# malformed PINGs", 1, GNUNET_NO);
1563 LOG (GNUNET_ERROR_TYPE_WARNING, " malformed PING on %s\n", GCT_2s (t));
1564 LOG (GNUNET_ERROR_TYPE_DEBUG, " e got %u\n", msg->nonce);
1565 LOG (GNUNET_ERROR_TYPE_DEBUG, " e towards %s\n", GNUNET_i2s (&msg->target));
1566 LOG (GNUNET_ERROR_TYPE_DEBUG, " got %u\n", res.nonce);
1567 LOG (GNUNET_ERROR_TYPE_DEBUG, " towards %s\n", GNUNET_i2s (&res.target));
1573 send_pong (t, res.nonce);
1578 * Peer has answer to our challenge.
1579 * If answer is successful, consider the key exchange finished and clean
1580 * up all related state.
1582 * @param t Tunnel this message came on.
1583 * @param msg Key eXchange Pong message.
1586 handle_pong (struct CadetTunnel *t,
1587 const struct GNUNET_CADET_KX_Pong *msg)
1591 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
1592 if (GNUNET_SCHEDULER_NO_TASK == t->rekey_task)
1594 GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
1597 t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
1599 if (challenge != t->kx_ctx->challenge)
1601 LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
1602 LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
1603 challenge, msg->nonce, t->kx_ctx->challenge);
1608 GNUNET_SCHEDULER_cancel (t->rekey_task);
1609 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1610 GNUNET_free (t->kx_ctx);
1612 GCT_change_estate (t, CADET_TUNNEL3_KEY_OK);
1617 * Demultiplex by message type and call appropriate handler for a message
1618 * towards a channel of a local tunnel.
1620 * @param t Tunnel this message came on.
1621 * @param msgh Message header.
1622 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1623 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1624 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1625 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1628 handle_decrypted (struct CadetTunnel *t,
1629 const struct GNUNET_MessageHeader *msgh,
1634 type = ntohs (msgh->type);
1635 LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
1639 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1640 /* Do nothing, connection aleady got updated. */
1641 GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
1644 case GNUNET_MESSAGE_TYPE_CADET_DATA:
1645 /* Don't send hop ACK, wait for client to ACK */
1646 handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
1649 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1650 handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
1653 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1654 handle_ch_create (t,
1655 (struct GNUNET_CADET_ChannelCreate *) msgh);
1658 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1660 (struct GNUNET_CADET_ChannelManage *) msgh);
1663 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1665 (struct GNUNET_CADET_ChannelManage *) msgh,
1669 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1670 handle_ch_destroy (t,
1671 (struct GNUNET_CADET_ChannelManage *) msgh,
1676 GNUNET_break_op (0);
1677 LOG (GNUNET_ERROR_TYPE_WARNING,
1678 "end-to-end message not known (%u)\n",
1679 ntohs (msgh->type));
1684 /******************************************************************************/
1685 /******************************** API ***********************************/
1686 /******************************************************************************/
1689 * Decrypt and demultiplex by message type. Call appropriate handler
1690 * for every message.
1692 * @param t Tunnel this message came on.
1693 * @param msg Encrypted message.
1696 GCT_handle_encrypted (struct CadetTunnel *t,
1697 const struct GNUNET_CADET_Encrypted *msg)
1699 size_t size = ntohs (msg->header.size);
1700 size_t payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
1701 size_t decrypted_size;
1702 char cbuf [payload_size];
1703 struct GNUNET_MessageHeader *msgh;
1705 struct GNUNET_CADET_Hash hmac;
1707 decrypted_size = t_decrypt (t, cbuf, &msg[1], payload_size, msg->iv);
1708 t_hmac (t, &msg[1], payload_size, msg->iv, GNUNET_NO, &hmac);
1709 if (0 != memcmp (&hmac, &msg->hmac, sizeof (hmac)))
1711 /* checksum failed */
1712 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1713 "Failed checksum validation for a message on tunnel `%s'\n",
1715 GNUNET_STATISTICS_update (stats, "# wrong HMAC", 1, GNUNET_NO);
1719 while (off < decrypted_size)
1721 msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
1722 handle_decrypted (t, msgh, GNUNET_SYSERR);
1723 off += ntohs (msgh->size);
1729 * Demultiplex an encapsulated KX message by message type.
1731 * @param t Tunnel on which the message came.
1732 * @param message Payload of KX message.
1735 GCT_handle_kx (struct CadetTunnel *t,
1736 const struct GNUNET_MessageHeader *message)
1740 type = ntohs (message->type);
1741 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received\n", type);
1744 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
1745 handle_ephemeral (t, (struct GNUNET_CADET_KX_Ephemeral *) message);
1748 case GNUNET_MESSAGE_TYPE_CADET_KX_PING:
1749 handle_ping (t, (struct GNUNET_CADET_KX_Ping *) message);
1752 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
1753 handle_pong (t, (struct GNUNET_CADET_KX_Pong *) message);
1757 GNUNET_break_op (0);
1758 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message not known (%u)\n", type);
1764 * Initialize the tunnel subsystem.
1766 * @param c Configuration handle.
1767 * @param key ECC private key, to derive all other keys and do crypto.
1770 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
1771 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
1773 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
1775 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
1778 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1779 "CADET", "DEFAULT_TTL", "USING DEFAULT");
1783 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
1786 rekey_period = GNUNET_TIME_UNIT_DAYS;
1789 my_private_key = key;
1790 kx_msg.header.size = htons (sizeof (kx_msg));
1791 kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
1792 kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
1793 kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
1794 kx_msg.origin_identity = my_full_id;
1795 rekey_task = GNUNET_SCHEDULER_add_now (&rekey, NULL);
1797 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
1802 * Shut down the tunnel subsystem.
1807 if (GNUNET_SCHEDULER_NO_TASK != rekey_task)
1809 GNUNET_SCHEDULER_cancel (rekey_task);
1810 rekey_task = GNUNET_SCHEDULER_NO_TASK;
1812 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
1813 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
1820 * @param destination Peer this tunnel is towards.
1822 struct CadetTunnel *
1823 GCT_new (struct CadetPeer *destination)
1825 struct CadetTunnel *t;
1827 t = GNUNET_new (struct CadetTunnel);
1829 t->peer = destination;
1832 GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
1833 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
1844 * Change the tunnel's connection state.
1846 * @param t Tunnel whose connection state to change.
1847 * @param cstate New connection state.
1850 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
1854 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
1855 GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
1856 if (myid != GCP_get_short_id (t->peer) &&
1857 CADET_TUNNEL3_READY != t->cstate &&
1858 CADET_TUNNEL3_READY == cstate)
1861 if (CADET_TUNNEL3_KEY_OK == t->estate)
1863 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered send queued data\n");
1864 send_queued_data (t);
1866 else if (CADET_TUNNEL3_KEY_UNINITIALIZED == t->estate)
1868 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered rekey\n");
1869 rekey_tunnel (t, NULL);
1874 if (CADET_TUNNEL3_READY == cstate
1875 && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
1877 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered stop dht\n");
1878 GCP_stop_search (t->peer);
1883 * Change the tunnel encryption state.
1885 * @param t Tunnel whose encryption state to change.
1886 * @param state New encryption state.
1889 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
1893 LOG (GNUNET_ERROR_TYPE_DEBUG,
1894 "Tunnel %s estate was %s\n",
1895 GCP_2s (t->peer), estate2s (t->estate));
1896 LOG (GNUNET_ERROR_TYPE_DEBUG,
1897 "Tunnel %s estate is now %s\n",
1898 GCP_2s (t->peer), estate2s (state));
1899 if (myid != GCP_get_short_id (t->peer) &&
1900 CADET_TUNNEL3_KEY_OK != t->estate && CADET_TUNNEL3_KEY_OK == state)
1903 send_queued_data (t);
1911 * @brief Check if tunnel has too many connections, and remove one if necessary.
1913 * Currently this means the newest connection, unless it is a direct one.
1914 * Implemented as a task to avoid freeing a connection that is in the middle
1915 * of being created/processed.
1917 * @param cls Closure (Tunnel to check).
1918 * @param tc Task context.
1921 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1923 struct CadetTunnel *t = cls;
1925 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1928 if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
1930 struct CadetTConnection *iter;
1931 struct CadetTConnection *c;
1933 for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
1935 if ((NULL == c || iter->created.abs_value_us > c->created.abs_value_us)
1936 && GNUNET_NO == GCC_is_direct (iter->c))
1943 LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
1945 LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
1958 * Add a connection to a tunnel.
1961 * @param c Connection.
1964 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
1966 struct CadetTConnection *aux;
1968 GNUNET_assert (NULL != c);
1970 LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
1971 LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
1972 for (aux = t->connection_head; aux != NULL; aux = aux->next)
1976 aux = GNUNET_new (struct CadetTConnection);
1978 aux->created = GNUNET_TIME_absolute_get ();
1980 GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
1982 GNUNET_SCHEDULER_add_now (&trim_connections, t);
1987 * Mark a path as no longer valid for this tunnel: has been tried and failed.
1989 * @param t Tunnel to update.
1990 * @param path Invalid path to remove. Is destroyed after removal.
1993 GCT_remove_path (struct CadetTunnel *t, struct CadetPeerPath *path)
1995 GCP_remove_path (t->peer, path);
2000 * Remove a connection from a tunnel.
2003 * @param c Connection.
2006 GCT_remove_connection (struct CadetTunnel *t,
2007 struct CadetConnection *c)
2009 struct CadetTConnection *aux;
2010 struct CadetTConnection *next;
2012 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
2013 GCC_2s (c), GCT_2s (t));
2014 for (aux = t->connection_head; aux != NULL; aux = next)
2019 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
2024 /* Start new connections if needed */
2025 if (CONNECTIONS_PER_TUNNEL < GCT_count_connections (t)
2026 && GNUNET_SCHEDULER_NO_TASK == t->destroy_task
2027 && CADET_TUNNEL3_SHUTDOWN != t->cstate
2028 && GNUNET_NO == shutting_down)
2030 LOG (GNUNET_ERROR_TYPE_DEBUG, " no more connections, getting new ones\n");
2031 t->cstate = CADET_TUNNEL3_SEARCHING;
2032 GCP_connect (t->peer);
2036 /* If not marked as ready, no change is needed */
2037 if (CADET_TUNNEL3_READY != t->cstate)
2040 /* Check if any connection is ready to maintaing cstate */
2041 for (aux = t->connection_head; aux != NULL; aux = aux->next)
2042 if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
2045 t->cstate = CADET_TUNNEL3_WAITING;
2050 * Add a channel to a tunnel.
2053 * @param ch Channel.
2056 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2058 struct CadetTChannel *aux;
2060 GNUNET_assert (NULL != ch);
2062 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
2064 for (aux = t->channel_head; aux != NULL; aux = aux->next)
2066 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
2071 aux = GNUNET_new (struct CadetTChannel);
2073 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
2074 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
2076 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2078 GNUNET_SCHEDULER_cancel (t->destroy_task);
2079 t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2080 LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
2086 * Remove a channel from a tunnel.
2089 * @param ch Channel.
2092 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2094 struct CadetTChannel *aux;
2096 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
2097 for (aux = t->channel_head; aux != NULL; aux = aux->next)
2101 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
2102 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
2111 * Search for a channel by global ID.
2113 * @param t Tunnel containing the channel.
2114 * @param chid Public channel number.
2116 * @return channel handler, NULL if doesn't exist
2118 struct CadetChannel *
2119 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
2121 struct CadetTChannel *iter;
2126 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2128 if (GCCH_get_id (iter->ch) == chid)
2132 return NULL == iter ? NULL : iter->ch;
2137 * @brief Destroy a tunnel and free all resources.
2139 * Should only be called a while after the tunnel has been marked as destroyed,
2140 * in case there is a new channel added to the same peer shortly after marking
2141 * the tunnel. This way we avoid a new public key handshake.
2143 * @param cls Closure (tunnel to destroy).
2144 * @param tc Task context.
2147 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2149 struct CadetTunnel *t = cls;
2150 struct CadetTConnection *iter;
2152 LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
2153 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2155 LOG (GNUNET_ERROR_TYPE_WARNING,
2156 "Not destroying tunnel, due to shutdown. "
2157 "Tunnel at %p should have been freed by GCT_shutdown\n", t);
2160 t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2161 t->cstate = CADET_TUNNEL3_SHUTDOWN;
2163 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2165 GCC_send_destroy (iter->c);
2172 * Tunnel is empty: destroy it.
2174 * Notifies all connections about the destruction.
2176 * @param t Tunnel to destroy.
2179 GCT_destroy_empty (struct CadetTunnel *t)
2181 if (GNUNET_YES == shutting_down)
2182 return; /* Will be destroyed immediately anyway */
2184 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2186 LOG (GNUNET_ERROR_TYPE_DEBUG,
2187 "Tunnel %s is already scheduled for destruction\n",
2190 /* should never happen, tunnel can only become empty once, and the
2191 * task identifier should be NO_TASK (cleaned when the tunnel was created
2192 * or became un-empty)
2197 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: destroying scheduled\n",
2200 t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
2201 &delayed_destroy, t);
2202 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llX\n",
2203 t, t->destroy_task);
2208 * Destroy tunnel if empty (no more channels).
2210 * @param t Tunnel to destroy if empty.
2213 GCT_destroy_if_empty (struct CadetTunnel *t)
2215 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
2216 if (1 < GCT_count_channels (t))
2219 GCT_destroy_empty (t);
2224 * Destroy the tunnel.
2226 * This function does not generate any warning traffic to clients or peers.
2229 * Cancel messages belonging to this tunnel queued to neighbors.
2230 * Free any allocated resources linked to the tunnel.
2232 * @param t The tunnel to destroy.
2235 GCT_destroy (struct CadetTunnel *t)
2237 struct CadetTConnection *iter_c;
2238 struct CadetTConnection *next_c;
2239 struct CadetTChannel *iter_ch;
2240 struct CadetTChannel *next_ch;
2245 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
2247 GNUNET_break (GNUNET_YES ==
2248 GNUNET_CONTAINER_multipeermap_remove (tunnels,
2249 GCP_get_id (t->peer), t));
2251 for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
2253 next_c = iter_c->next;
2254 GCC_destroy (iter_c->c);
2256 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
2258 next_ch = iter_ch->next;
2259 GCCH_destroy (iter_ch->ch);
2260 /* Should only happen on shutdown, but it's ok. */
2263 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2265 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling %llX\n", t->destroy_task);
2266 GNUNET_SCHEDULER_cancel (t->destroy_task);
2267 t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2270 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
2271 GCP_set_tunnel (t->peer, NULL);
2273 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
2275 GNUNET_SCHEDULER_cancel (t->rekey_task);
2276 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
2277 if (NULL != t->kx_ctx)
2278 GNUNET_free (t->kx_ctx);
2288 * @brief Use the given path for the tunnel.
2289 * Update the next and prev hops (and RCs).
2290 * (Re)start the path refresh in case the tunnel is locally owned.
2292 * @param t Tunnel to update.
2293 * @param p Path to use.
2295 * @return Connection created.
2297 struct CadetConnection *
2298 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
2300 struct CadetConnection *c;
2301 struct GNUNET_CADET_Hash cid;
2302 unsigned int own_pos;
2304 if (NULL == t || NULL == p)
2310 if (CADET_TUNNEL3_SHUTDOWN == t->cstate)
2316 for (own_pos = 0; own_pos < p->length; own_pos++)
2318 if (p->peers[own_pos] == myid)
2321 if (own_pos >= p->length)
2323 GNUNET_break_op (0);
2327 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
2328 c = GCC_new (&cid, t, p, own_pos);
2331 /* Path was flawed */
2334 GCT_add_connection (t, c);
2340 * Count established (ready) connections of a tunnel.
2342 * @param t Tunnel on which to count.
2344 * @return Number of connections.
2347 GCT_count_connections (struct CadetTunnel *t)
2349 struct CadetTConnection *iter;
2355 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2356 if (CADET_CONNECTION_DESTROYED != GCC_get_state (iter->c))
2363 * Count channels of a tunnel.
2365 * @param t Tunnel on which to count.
2367 * @return Number of channels.
2370 GCT_count_channels (struct CadetTunnel *t)
2372 struct CadetTChannel *iter;
2375 for (count = 0, iter = t->channel_head;
2377 iter = iter->next, count++) /* skip */;
2384 * Get the connectivity state of a tunnel.
2388 * @return Tunnel's connectivity state.
2390 enum CadetTunnelCState
2391 GCT_get_cstate (struct CadetTunnel *t)
2396 return (enum CadetTunnelCState) -1;
2403 * Get the encryption state of a tunnel.
2407 * @return Tunnel's encryption state.
2409 enum CadetTunnelEState
2410 GCT_get_estate (struct CadetTunnel *t)
2415 return (enum CadetTunnelEState) -1;
2421 * Get the maximum buffer space for a tunnel towards a local client.
2425 * @return Biggest buffer space offered by any channel in the tunnel.
2428 GCT_get_channels_buffer (struct CadetTunnel *t)
2430 struct CadetTChannel *iter;
2431 unsigned int buffer;
2432 unsigned int ch_buf;
2434 if (NULL == t->channel_head)
2436 /* Probably getting buffer for a channel create/handshake. */
2441 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2443 ch_buf = get_channel_buffer (iter);
2444 if (ch_buf > buffer)
2452 * Get the total buffer space for a tunnel for P2P traffic.
2456 * @return Buffer space offered by all connections in the tunnel.
2459 GCT_get_connections_buffer (struct CadetTunnel *t)
2461 struct CadetTConnection *iter;
2462 unsigned int buffer;
2465 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2467 if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
2471 buffer += get_connection_buffer (iter);
2479 * Get the tunnel's destination.
2483 * @return ID of the destination peer.
2485 const struct GNUNET_PeerIdentity *
2486 GCT_get_destination (struct CadetTunnel *t)
2488 return GCP_get_id (t->peer);
2493 * Get the tunnel's next free global channel ID.
2497 * @return GID of a channel free to use.
2500 GCT_get_next_chid (struct CadetTunnel *t)
2502 CADET_ChannelNumber chid;
2503 CADET_ChannelNumber mask;
2506 /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
2507 * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
2508 * If peer's ID is bigger, start at 0x4... bit 30 = 1
2510 result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
2515 t->next_chid |= mask;
2517 while (NULL != GCT_get_channel (t, t->next_chid))
2519 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
2520 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
2521 t->next_chid |= mask;
2523 chid = t->next_chid;
2524 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
2525 t->next_chid |= mask;
2532 * Send ACK on one or more channels due to buffer in connections.
2534 * @param t Channel which has some free buffer space.
2537 GCT_unchoke_channels (struct CadetTunnel *t)
2539 struct CadetTChannel *iter;
2540 unsigned int buffer;
2541 unsigned int channels = GCT_count_channels (t);
2542 unsigned int choked_n;
2543 struct CadetChannel *choked[channels];
2545 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
2546 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
2547 if (NULL != t->channel_head)
2548 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
2550 /* Get buffer space */
2551 buffer = GCT_get_connections_buffer (t);
2557 /* Count and remember choked channels */
2559 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2561 if (GNUNET_NO == get_channel_allowed (iter))
2563 choked[choked_n++] = iter->ch;
2567 /* Unchoke random channels */
2568 while (0 < buffer && 0 < choked_n)
2570 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2572 GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
2575 choked[r] = choked[choked_n];
2581 * Send ACK on one or more connections due to buffer space to the client.
2583 * Iterates all connections of the tunnel and sends ACKs appropriately.
2588 GCT_send_connection_acks (struct CadetTunnel *t)
2590 struct CadetTConnection *iter;
2593 uint32_t allow_per_connection;
2595 unsigned int buffer;
2597 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
2606 buffer = GCT_get_channels_buffer (t);
2607 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer %u\n", buffer);
2609 /* Count connections, how many messages are already allowed */
2610 cs = GCT_count_connections (t);
2611 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2613 allowed += get_connection_allowed (iter);
2615 LOG (GNUNET_ERROR_TYPE_DEBUG, " allowed %u\n", allowed);
2617 /* Make sure there is no overflow */
2618 if (allowed > buffer)
2623 /* Authorize connections to send more data */
2624 to_allow = buffer; /* - allowed; */
2626 for (iter = t->connection_head;
2627 NULL != iter && to_allow > 0;
2630 allow_per_connection = to_allow/cs;
2631 to_allow -= allow_per_connection;
2633 if (get_connection_allowed (iter) > 64 / 3)
2637 GCC_allow (iter->c, allow_per_connection,
2638 GCC_is_origin (iter->c, GNUNET_NO));
2641 GNUNET_break (to_allow == 0);
2646 * Cancel a previously sent message while it's in the queue.
2648 * ONLY can be called before the continuation given to the send function
2649 * is called. Once the continuation is called, the message is no longer in the
2652 * @param q Handle to the queue.
2655 GCT_cancel (struct CadetTunnelQueue *q)
2660 /* tun_message_sent() will be called and free q */
2662 else if (NULL != q->tqd)
2664 unqueue_data (q->tqd);
2666 if (NULL != q->cont)
2667 q->cont (q->cont_cls, NULL, q, 0, 0);
2678 * Sends an already built message on a tunnel, encrypting it and
2679 * choosing the best connection if not provided.
2681 * @param message Message to send. Function modifies it.
2682 * @param t Tunnel on which this message is transmitted.
2683 * @param c Connection to use (autoselect if NULL).
2684 * @param force Force the tunnel to take the message (buffer overfill).
2685 * @param cont Continuation to call once message is really sent.
2686 * @param cont_cls Closure for @c cont.
2688 * @return Handle to cancel message. NULL if @c cont is NULL.
2690 struct CadetTunnelQueue *
2691 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
2692 struct CadetTunnel *t, struct CadetConnection *c,
2693 int force, GCT_sent cont, void *cont_cls)
2695 return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
2700 * Is the tunnel directed towards the local peer?
2704 * @return #GNUNET_YES if it is loopback.
2707 GCT_is_loopback (const struct CadetTunnel *t)
2709 return (myid == GCP_get_short_id (t->peer));
2714 * Is the tunnel this path already?
2719 * @return #GNUNET_YES a connection uses this path.
2722 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
2724 struct CadetTConnection *iter;
2726 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2727 if (GCC_get_path (iter->c) == p)
2735 * Get a cost of a path for a tunnel considering existing connections.
2738 * @param path Candidate path.
2740 * @return Cost of the path (path length + number of overlapping nodes)
2743 GCT_get_path_cost (const struct CadetTunnel *t,
2744 const struct CadetPeerPath *path)
2746 struct CadetTConnection *iter;
2747 const struct CadetPeerPath *aux;
2748 unsigned int overlap;
2756 GNUNET_assert (NULL != t);
2758 for (i = 0; i < path->length; i++)
2760 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2762 aux = GCC_get_path (iter->c);
2766 for (j = 0; j < aux->length; j++)
2768 if (path->peers[i] == aux->peers[j])
2776 return path->length + overlap;
2781 * Get the static string for the peer this tunnel is directed.
2785 * @return Static string the destination peer's ID.
2788 GCT_2s (const struct CadetTunnel *t)
2793 return GCP_2s (t->peer);
2797 /******************************************************************************/
2798 /***************************** INFO/DEBUG *******************************/
2799 /******************************************************************************/
2803 * Log all possible info about the tunnel state to stderr.
2805 * @param t Tunnel to debug.
2808 GCT_debug (const struct CadetTunnel *t)
2810 struct CadetTChannel *iterch;
2811 struct CadetTConnection *iterc;
2813 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
2814 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT cstate %s, estate %s\n",
2815 cstate2s (t->cstate), estate2s (t->estate));
2816 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT kx_ctx %p, rekey_task %u\n",
2817 t->kx_ctx, t->rekey_task);
2818 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT tq_head %p, tq_tail %p\n",
2819 t->tq_head, t->tq_tail);
2820 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT destroy %u\n", t->destroy_task);
2822 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT channels:\n");
2823 for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
2825 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT - %s\n", GCCH_2s (iterch->ch));
2828 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT connections:\n");
2829 for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
2831 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT - %s [%u] buf: %u/%u (qn %u/%u)\n",
2832 GCC_2s (iterc->c), GCC_get_state (iterc->c),
2833 GCC_get_buffer (iterc->c, GNUNET_YES),
2834 GCC_get_buffer (iterc->c, GNUNET_NO),
2835 GCC_get_qn (iterc->c, GNUNET_YES),
2836 GCC_get_qn (iterc->c, GNUNET_NO));
2839 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT DEBUG TUNNEL END\n");
2844 * Iterate all tunnels.
2846 * @param iter Iterator.
2847 * @param cls Closure for @c iter.
2850 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
2852 GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
2857 * Count all tunnels.
2859 * @return Number of tunnels to remote peers kept by this peer.
2862 GCT_count_all (void)
2864 return GNUNET_CONTAINER_multipeermap_size (tunnels);
2869 * Iterate all connections of a tunnel.
2871 * @param t Tunnel whose connections to iterate.
2872 * @param iter Iterator.
2873 * @param cls Closure for @c iter.
2876 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
2878 struct CadetTConnection *ct;
2880 for (ct = t->connection_head; NULL != ct; ct = ct->next)
2886 * Iterate all channels of a tunnel.
2888 * @param t Tunnel whose channels to iterate.
2889 * @param iter Iterator.
2890 * @param cls Closure for @c iter.
2893 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
2895 struct CadetTChannel *cht;
2897 for (cht = t->channel_head; NULL != cht; cht = cht->next)
2898 iter (cls, cht->ch);