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;
112 * Task for delayed destruction of the Key eXchange context, to allow delayed
113 * messages with the old key to be decrypted successfully.
115 GNUNET_SCHEDULER_TaskIdentifier finish_task;
119 * Struct containing all information regarding a tunnel to a peer.
124 * Endpoint of the tunnel.
126 struct CadetPeer *peer;
129 * State of the tunnel connectivity.
131 enum CadetTunnelCState cstate;
134 * State of the tunnel encryption.
136 enum CadetTunnelEState estate;
139 * Key eXchange context.
141 struct CadetTunnelKXCtx *kx_ctx;
144 * Peer's ephemeral key, to recreate @c e_key and @c d_key when own ephemeral
147 struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
150 * Encryption ("our") key.
152 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
155 * Decryption ("their") key.
157 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
160 * Task to start the rekey process.
162 GNUNET_SCHEDULER_TaskIdentifier rekey_task;
165 * Paths that are actively used to reach the destination peer.
167 struct CadetTConnection *connection_head;
168 struct CadetTConnection *connection_tail;
171 * Next connection number.
176 * Channels inside this tunnel.
178 struct CadetTChannel *channel_head;
179 struct CadetTChannel *channel_tail;
182 * Channel ID for the next created channel.
184 CADET_ChannelNumber next_chid;
187 * Destroy flag: if true, destroy on last message.
189 GNUNET_SCHEDULER_TaskIdentifier destroy_task;
192 * Queued messages, to transmit once tunnel gets connected.
194 struct CadetTunnelDelayed *tq_head;
195 struct CadetTunnelDelayed *tq_tail;
200 * Struct used to save messages in a non-ready tunnel to send once connected.
202 struct CadetTunnelDelayed
207 struct CadetTunnelDelayed *next;
208 struct CadetTunnelDelayed *prev;
213 struct CadetTunnel *t;
216 * Tunnel queue given to the channel to cancel request. Update on send_queued.
218 struct CadetTunnelQueue *tq;
223 /* struct GNUNET_MessageHeader *msg; */
228 * Handle for messages queued but not yet sent.
230 struct CadetTunnelQueue
233 * Connection queue handle, to cancel if necessary.
235 struct CadetConnectionQueue *cq;
238 * Handle in case message hasn't been given to a connection yet.
240 struct CadetTunnelDelayed *tqd;
243 * Continuation to call once sent.
248 * Closure for @c cont.
254 /******************************************************************************/
255 /******************************* GLOBALS ***********************************/
256 /******************************************************************************/
259 * Global handle to the statistics service.
261 extern struct GNUNET_STATISTICS_Handle *stats;
264 * Local peer own ID (memory efficient handle).
266 extern GNUNET_PEER_Id myid;
269 * Local peer own ID (full value).
271 extern struct GNUNET_PeerIdentity my_full_id;
275 * Don't try to recover tunnels if shutting down.
277 extern int shutting_down;
281 * Set of all tunnels, in order to trigger a new exchange on rekey.
282 * Indexed by peer's ID.
284 static struct GNUNET_CONTAINER_MultiPeerMap *tunnels;
287 * Default TTL for payload packets.
289 static unsigned long long default_ttl;
294 const static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
297 * Own ephemeral private key.
299 static struct GNUNET_CRYPTO_EcdhePrivateKey *my_ephemeral_key;
302 * Cached message used to perform a key exchange.
304 static struct GNUNET_CADET_KX_Ephemeral kx_msg;
307 * Task to generate a new ephemeral key.
309 static GNUNET_SCHEDULER_TaskIdentifier rekey_task;
314 static struct GNUNET_TIME_Relative rekey_period;
316 /******************************************************************************/
317 /******************************** STATIC ***********************************/
318 /******************************************************************************/
321 * Get string description for tunnel connectivity state.
323 * @param cs Tunnel state.
325 * @return String representation.
328 cstate2s (enum CadetTunnelCState cs)
330 static char buf[128];
334 case CADET_TUNNEL3_NEW:
335 return "CADET_TUNNEL3_NEW";
336 case CADET_TUNNEL3_SEARCHING:
337 return "CADET_TUNNEL3_SEARCHING";
338 case CADET_TUNNEL3_WAITING:
339 return "CADET_TUNNEL3_WAITING";
340 case CADET_TUNNEL3_READY:
341 return "CADET_TUNNEL3_READY";
344 sprintf (buf, "%u (UNKNOWN STATE)", cs);
352 * Get string description for tunnel encryption state.
354 * @param es Tunnel state.
356 * @return String representation.
359 estate2s (enum CadetTunnelEState es)
361 static char buf[128];
365 case CADET_TUNNEL3_KEY_UNINITIALIZED:
366 return "CADET_TUNNEL3_KEY_UNINITIALIZED";
367 case CADET_TUNNEL3_KEY_SENT:
368 return "CADET_TUNNEL3_KEY_SENT";
369 case CADET_TUNNEL3_KEY_PING:
370 return "CADET_TUNNEL3_KEY_PING";
371 case CADET_TUNNEL3_KEY_OK:
372 return "CADET_TUNNEL3_KEY_OK";
375 sprintf (buf, "%u (UNKNOWN STATE)", es);
383 * @brief Check if tunnel is ready to send traffic.
385 * Tunnel must be connected and with encryption correctly set up.
387 * @param t Tunnel to check.
389 * @return #GNUNET_YES if ready, #GNUNET_NO otherwise
392 is_ready (struct CadetTunnel *t)
397 ready = (CADET_TUNNEL3_READY == t->cstate && CADET_TUNNEL3_KEY_OK == t->estate);
398 ready = ready || GCT_is_loopback (t);
404 * Ephemeral key message purpose size.
406 * @return Size of the part of the ephemeral key message that must be signed.
409 ephemeral_purpose_size (void)
411 return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
412 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
413 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
414 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
415 sizeof (struct GNUNET_PeerIdentity);
420 * Size of the encrypted part of a ping message.
422 * @return Size of the encrypted part of a ping message.
425 ping_encryption_size (void)
427 return sizeof (struct GNUNET_PeerIdentity) + sizeof (uint32_t);
432 * Get the channel's buffer. ONLY FOR NON-LOOPBACK CHANNELS!!
434 * @param tch Tunnel's channel handle.
436 * @return Amount of messages the channel can still buffer towards the client.
439 get_channel_buffer (const struct CadetTChannel *tch)
443 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
444 fwd = GCCH_is_origin (tch->ch, GNUNET_YES);
446 return GCCH_get_buffer (tch->ch, fwd);
451 * Get the channel's allowance status.
453 * @param tch Tunnel's channel handle.
455 * @return #GNUNET_YES if we allowed the client to send data to us.
458 get_channel_allowed (const struct CadetTChannel *tch)
462 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
463 fwd = GCCH_is_origin (tch->ch, GNUNET_YES);
465 return GCCH_get_allowed (tch->ch, fwd);
470 * Get the connection's buffer.
472 * @param tc Tunnel's connection handle.
474 * @return Amount of messages the connection can still buffer.
477 get_connection_buffer (const struct CadetTConnection *tc)
481 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
482 fwd = GCC_is_origin (tc->c, GNUNET_YES);
484 return GCC_get_buffer (tc->c, fwd);
489 * Get the connection's allowance.
491 * @param tc Tunnel's connection handle.
493 * @return Amount of messages we have allowed the next peer to send us.
496 get_connection_allowed (const struct CadetTConnection *tc)
500 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
501 fwd = GCC_is_origin (tc->c, GNUNET_YES);
503 return GCC_get_allowed (tc->c, fwd);
508 * Check that a ephemeral key message s well formed and correctly signed.
510 * @param t Tunnel on which the message came.
511 * @param msg The ephemeral key message.
513 * @return GNUNET_OK if message is fine, GNUNET_SYSERR otherwise.
516 check_ephemeral (struct CadetTunnel *t,
517 const struct GNUNET_CADET_KX_Ephemeral *msg)
519 /* Check message size */
520 if (ntohs (msg->header.size) != sizeof (struct GNUNET_CADET_KX_Ephemeral))
521 return GNUNET_SYSERR;
523 /* Check signature size */
524 if (ntohl (msg->purpose.size) != ephemeral_purpose_size ())
525 return GNUNET_SYSERR;
528 if (0 != memcmp (&msg->origin_identity,
529 GCP_get_id (t->peer),
530 sizeof (struct GNUNET_PeerIdentity)))
531 return GNUNET_SYSERR;
533 /* Check signature */
535 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_CADET_KX,
538 &msg->origin_identity.public_key))
539 return GNUNET_SYSERR;
548 * @param t Tunnel to get keys from.
549 * @param plaintext Content to HMAC.
550 * @param size Size of @c plaintext.
551 * @param iv Initialization vector for the message.
552 * @param outgoing Is this an outgoing message that we encrypted?
553 * @param hmac Destination to store the HMAC.
556 t_hmac (struct CadetTunnel *t, const void *plaintext, size_t size, uint32_t iv,
557 int outgoing, struct GNUNET_CADET_Hash *hmac)
559 struct GNUNET_CRYPTO_AuthKey auth_key;
560 static const char ctx[] = "cadet authentication key";
561 struct GNUNET_CRYPTO_SymmetricSessionKey *key;
562 struct GNUNET_HashCode hash;
564 key = outgoing ? &t->e_key : &t->d_key;
565 GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
570 GNUNET_CRYPTO_hmac (&auth_key, plaintext, size, &hash);
571 memcpy (hmac, &hash, sizeof (*hmac));
576 * Encrypt data with the tunnel key.
578 * @param t Tunnel whose key to use.
579 * @param dst Destination for the encrypted data.
580 * @param src Source of the plaintext. Can overlap with @c dst.
581 * @param size Size of the plaintext.
582 * @param iv Initialization Vector to use.
583 * @param force_newest_key Force the use of the newest key, otherwise
584 * CADET will use the old key when allowed.
585 * This can happen in the case when a KX is going on
586 * and the old one hasn't expired.
589 t_encrypt (struct CadetTunnel *t, void *dst, const void *src,
590 size_t size, uint32_t iv, int force_newest_key)
592 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
593 struct GNUNET_CRYPTO_SymmetricSessionKey *e_key;
596 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt start\n");
597 if (GNUNET_NO == force_newest_key
599 && GNUNET_SCHEDULER_NO_TASK == t->kx_ctx->finish_task)
601 struct GNUNET_TIME_Relative age;
603 age = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
604 LOG (GNUNET_ERROR_TYPE_DEBUG,
605 " key exchange in progress, started %s ago\n",
606 GNUNET_STRINGS_relative_time_to_string (age, GNUNET_YES));
607 if (age.rel_value_us < GNUNET_TIME_UNIT_MINUTES.rel_value_us)
609 LOG (GNUNET_ERROR_TYPE_DEBUG, " using old key\n");
610 e_key = &t->kx_ctx->e_key_old;
614 LOG (GNUNET_ERROR_TYPE_DEBUG, " using new key\n");
622 GNUNET_CRYPTO_symmetric_derive_iv (&siv, e_key, &iv, sizeof (iv), NULL);
623 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt IV derived\n");
624 out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, e_key, &siv, dst);
625 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_encrypt end\n");
632 * Decrypt and verify data with the appropriate tunnel key.
634 * @param key Key to use.
635 * @param dst Destination for the plaintext.
636 * @param src Source of the encrypted data. Can overlap with @c dst.
637 * @param size Size of the encrypted data.
638 * @param iv Initialization Vector to use.
640 * @return Size of the decrypted data, -1 if an error was encountered.
643 decrypt (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
644 void *dst, const void *src, size_t size, uint32_t iv)
646 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
649 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt start\n");
650 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv\n");
651 GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
652 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt iv done\n");
653 out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, key, &siv, dst);
654 LOG (GNUNET_ERROR_TYPE_DEBUG, " decrypt end\n");
661 * Decrypt and verify data with the most recent tunnel key.
663 * @param t Tunnel whose key to use.
664 * @param dst Destination for the plaintext.
665 * @param src Source of the encrypted data. Can overlap with @c dst.
666 * @param size Size of the encrypted data.
667 * @param iv Initialization Vector to use.
669 * @return Size of the decrypted data, -1 if an error was encountered.
672 t_decrypt (struct CadetTunnel *t, void *dst, const void *src,
673 size_t size, uint32_t iv)
675 struct GNUNET_CRYPTO_SymmetricSessionKey *key;
678 LOG (GNUNET_ERROR_TYPE_DEBUG, " t_decrypt start\n");
679 if (t->estate == CADET_TUNNEL3_KEY_OK || t->estate == CADET_TUNNEL3_KEY_PING)
685 GNUNET_STATISTICS_update (stats, "# non decryptable data", 1, GNUNET_NO);
686 LOG (GNUNET_ERROR_TYPE_WARNING,
687 "got data on %s without a valid key\n",
693 out_size = decrypt (key, dst, src, size, iv);
700 * Decrypt and verify data with the appropriate tunnel key and verify that the
701 * data has not been altered since it was sent by the remote peer.
703 * @param t Tunnel whose key to use.
704 * @param dst Destination for the plaintext.
705 * @param src Source of the encrypted data. Can overlap with @c dst.
706 * @param size Size of the encrypted data.
707 * @param iv Initialization Vector to use.
708 * @param msg_hmac HMAC of the message, cannot be NULL.
710 * @return Size of the decrypted data, -1 if an error was encountered.
713 t_decrypt_and_validate (struct CadetTunnel *t,
714 void *dst, const void *src,
715 size_t size, uint32_t iv,
716 const struct GNUNET_CADET_Hash *msg_hmac)
718 struct GNUNET_CRYPTO_SymmetricSessionKey *key;
719 struct GNUNET_CADET_Hash hmac;
722 /* Try primary (newest) key */
724 decrypted_size = decrypt (key, dst, src, size, iv);
725 t_hmac (t, src, size, iv, GNUNET_NO, &hmac);
726 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
727 return decrypted_size;
729 /* If no key exchange is going on, we just failed */
730 if (NULL == t->kx_ctx)
732 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
733 "Failed checksum validation on tunnel %s with no KX\n",
735 GNUNET_STATISTICS_update (stats, "# wrong HMAC", 1, GNUNET_NO);
739 /* Try secondary (from previous KX period) key */
740 key = &t->kx_ctx->d_key_old;
741 decrypted_size = decrypt (key, dst, src, size, iv);
742 t_hmac (t, src, size, iv, GNUNET_NO, &hmac);
743 if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
744 return decrypted_size;
746 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
747 "Failed checksum validation on tunnel %s with KX\n",
749 GNUNET_STATISTICS_update (stats, "# wrong HMAC", 1, GNUNET_NO);
755 * Create key material by doing ECDH on the local and remote ephemeral keys.
757 * @param key_material Where to store the key material.
758 * @param ephemeral_key Peer's public ephemeral key.
761 derive_key_material (struct GNUNET_HashCode *key_material,
762 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key)
765 GNUNET_CRYPTO_ecc_ecdh (my_ephemeral_key,
775 * Create a symmetic key from the identities of both ends and the key material
778 * @param key Destination for the generated key.
779 * @param sender ID of the peer that will encrypt with @c key.
780 * @param receiver ID of the peer that will decrypt with @c key.
781 * @param key_material Hash created with ECDH with the ephemeral keys.
784 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
785 const struct GNUNET_PeerIdentity *sender,
786 const struct GNUNET_PeerIdentity *receiver,
787 const struct GNUNET_HashCode *key_material)
789 const char salt[] = "CADET kx salt";
791 GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
793 key_material, sizeof (struct GNUNET_HashCode),
794 sender, sizeof (struct GNUNET_PeerIdentity),
795 receiver, sizeof (struct GNUNET_PeerIdentity),
801 * Derive the tunnel's keys using our own and the peer's ephemeral keys.
803 * @param t Tunnel for which to create the keys.
806 create_keys (struct CadetTunnel *t)
808 struct GNUNET_HashCode km;
810 derive_key_material (&km, &t->peers_ephemeral_key);
811 derive_symmertic (&t->e_key, &my_full_id, GCP_get_id (t->peer), &km);
812 derive_symmertic (&t->d_key, GCP_get_id (t->peer), &my_full_id, &km);
817 * Pick a connection on which send the next data message.
819 * @param t Tunnel on which to send the message.
821 * @return The connection on which to send the next message.
823 static struct CadetConnection *
824 tunnel_get_connection (struct CadetTunnel *t)
826 struct CadetTConnection *iter;
827 struct CadetConnection *best;
829 unsigned int lowest_q;
831 LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GCT_2s (t));
834 for (iter = t->connection_head; NULL != iter; iter = iter->next)
836 LOG (GNUNET_ERROR_TYPE_DEBUG, " connection %s: %u\n",
837 GCC_2s (iter->c), GCC_get_state (iter->c));
838 if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
840 qn = GCC_get_qn (iter->c, GCC_is_origin (iter->c, GNUNET_YES));
841 LOG (GNUNET_ERROR_TYPE_DEBUG, " q_n %u, \n", qn);
849 LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GCC_2s (best));
855 * Callback called when a queued message is sent.
857 * Calculates the average time and connection packet tracking.
859 * @param cls Closure (TunnelQueue handle).
860 * @param c Connection this message was on.
861 * @param q Connection queue handle (unused).
862 * @param type Type of message sent.
863 * @param fwd Was this a FWD going message?
864 * @param size Size of the message.
867 tun_message_sent (void *cls,
868 struct CadetConnection *c,
869 struct CadetConnectionQueue *q,
870 uint16_t type, int fwd, size_t size)
872 struct CadetTunnelQueue *qt = cls;
873 struct CadetTunnel *t;
875 LOG (GNUNET_ERROR_TYPE_DEBUG, "tun_message_sent\n");
877 GNUNET_assert (NULL != qt->cont);
878 t = NULL == c ? NULL : GCC_get_tunnel (c);
879 qt->cont (qt->cont_cls, t, qt, type, size);
885 * Delete a queued message: either was sent or the channel was destroyed
886 * before the tunnel's key exchange had a chance to finish.
888 * @param tqd Delayed queue handle.
891 unqueue_data (struct CadetTunnelDelayed *tqd)
893 GNUNET_CONTAINER_DLL_remove (tqd->t->tq_head, tqd->t->tq_tail, tqd);
899 * Cache a message to be sent once tunnel is online.
901 * @param t Tunnel to hold the message.
902 * @param msg Message itself (copy will be made).
904 static struct CadetTunnelDelayed *
905 queue_data (struct CadetTunnel *t, const struct GNUNET_MessageHeader *msg)
907 struct CadetTunnelDelayed *tqd;
908 uint16_t size = ntohs (msg->size);
910 LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GCT_2s (t));
912 if (GNUNET_YES == is_ready (t))
918 tqd = GNUNET_malloc (sizeof (struct CadetTunnelDelayed) + size);
921 memcpy (&tqd[1], msg, size);
922 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
928 * Sends an already built message on a tunnel, encrypting it and
929 * choosing the best connection.
931 * @param message Message to send. Function modifies it.
932 * @param t Tunnel on which this message is transmitted.
933 * @param c Connection to use (autoselect if NULL).
934 * @param force Force the tunnel to take the message (buffer overfill).
935 * @param cont Continuation to call once message is really sent.
936 * @param cont_cls Closure for @c cont.
937 * @param existing_q In case this a transmission of previously queued data,
938 * this should be TunnelQueue given to the client.
941 * @return Handle to cancel message. NULL if @c cont is NULL.
943 static struct CadetTunnelQueue *
944 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
945 struct CadetTunnel *t, struct CadetConnection *c,
946 int force, GCT_sent cont, void *cont_cls,
947 struct CadetTunnelQueue *existing_q)
949 struct CadetTunnelQueue *tq;
950 struct GNUNET_CADET_Encrypted *msg;
951 size_t size = ntohs (message->size);
952 char cbuf[sizeof (struct GNUNET_CADET_Encrypted) + size];
958 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GCT_2s (t));
960 if (GNUNET_NO == is_ready (t))
962 struct CadetTunnelDelayed *tqd;
963 /* A non null existing_q indicates sending of queued data.
964 * Should only happen after tunnel becomes ready.
966 GNUNET_assert (NULL == existing_q);
967 tqd = queue_data (t, message);
970 tq = GNUNET_new (struct CadetTunnelQueue);
974 tq->cont_cls = cont_cls;
978 GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
980 iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
981 msg = (struct GNUNET_CADET_Encrypted *) cbuf;
982 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
984 GNUNET_assert (t_encrypt (t, &msg[1], message, size, iv, GNUNET_NO) == size);
985 t_hmac (t, &msg[1], size, iv, GNUNET_YES, &msg->hmac);
986 msg->header.size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
989 c = tunnel_get_connection (t);
992 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task
993 || CADET_TUNNEL3_SEARCHING != t->cstate)
1002 type = ntohs (message->type);
1005 case GNUNET_MESSAGE_TYPE_CADET_DATA:
1006 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1007 if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
1008 mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
1010 mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
1012 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1013 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1014 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1015 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1016 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1017 msg->cid = *GCC_get_id (c);
1018 msg->ttl = htonl (default_ttl);
1023 LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
1025 fwd = GCC_is_origin (c, GNUNET_YES);
1029 GNUNET_break (NULL ==
1030 GCC_send_prebuilt_message (&msg->header, type, mid,
1031 c, fwd, force, NULL, NULL));
1034 if (NULL == existing_q)
1036 tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
1043 tq->cq = GCC_send_prebuilt_message (&msg->header, type, mid, c, fwd, force,
1044 &tun_message_sent, tq);
1046 tq->cont_cls = cont_cls;
1053 * Send all cached messages that we can, tunnel is online.
1055 * @param t Tunnel that holds the messages. Cannot be loopback.
1058 send_queued_data (struct CadetTunnel *t)
1060 struct CadetTunnelDelayed *tqd;
1061 struct CadetTunnelDelayed *next;
1064 LOG (GNUNET_ERROR_TYPE_DEBUG,
1065 "GCT_send_queued_data on tunnel %s\n",
1068 if (GCT_is_loopback (t))
1074 if (GNUNET_NO == is_ready (t))
1076 LOG (GNUNET_ERROR_TYPE_DEBUG, " not ready yet: %s/%s\n",
1077 estate2s (t->estate), cstate2s (t->cstate));
1081 room = GCT_get_connections_buffer (t);
1082 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
1083 LOG (GNUNET_ERROR_TYPE_DEBUG, " tq head: %p\n", t->tq_head);
1084 for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
1086 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
1089 send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
1090 tqd->t, NULL, GNUNET_YES,
1091 NULL != tqd->tq ? tqd->tq->cont : NULL,
1092 NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
1096 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
1101 * Sends key exchange message on a tunnel, choosing the best connection.
1102 * Should not be called on loopback tunnels.
1104 * @param t Tunnel on which this message is transmitted.
1105 * @param message Message to send. Function modifies it.
1108 send_kx (struct CadetTunnel *t,
1109 const struct GNUNET_MessageHeader *message)
1111 struct CadetConnection *c;
1112 struct GNUNET_CADET_KX *msg;
1113 size_t size = ntohs (message->size);
1114 char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
1118 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
1120 /* Avoid loopback. */
1121 if (GCT_is_loopback (t))
1123 LOG (GNUNET_ERROR_TYPE_DEBUG, " loopback!\n");
1128 /* Even if tunnel is being destroyed, send anyway.
1129 * Could be a response to a rekey initiated by remote peer,
1130 * who is trying to create a new channel!
1133 /* Must have a connection. */
1134 if (NULL == t->connection_head)
1136 GNUNET_break (CADET_TUNNEL3_SEARCHING == t->cstate);
1141 msg = (struct GNUNET_CADET_KX *) cbuf;
1142 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
1143 msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
1144 c = tunnel_get_connection (t);
1147 GNUNET_break (GNUNET_SCHEDULER_NO_TASK != t->destroy_task
1148 || CADET_TUNNEL3_READY != t->cstate);
1152 type = ntohs (message->type);
1155 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
1156 case GNUNET_MESSAGE_TYPE_CADET_KX_PING:
1157 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
1158 memcpy (&msg[1], message, size);
1161 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
1166 fwd = GCC_is_origin (t->connection_head->c, GNUNET_YES);
1167 /* TODO save handle and cancel in case of a unneeded retransmission */
1168 GCC_send_prebuilt_message (&msg->header, GNUNET_MESSAGE_TYPE_CADET_KX,
1169 message->type, c, fwd, GNUNET_YES, NULL, NULL);
1174 * Send the ephemeral key on a tunnel.
1176 * @param t Tunnel on which to send the key.
1179 send_ephemeral (struct CadetTunnel *t)
1181 LOG (GNUNET_ERROR_TYPE_INFO, "===> EPHM for %s\n", GCT_2s (t));
1183 kx_msg.sender_status = htonl (t->estate);
1184 send_kx (t, &kx_msg.header);
1188 * Send a ping message on a tunnel.
1190 * @param t Tunnel on which to send the ping.
1193 send_ping (struct CadetTunnel *t)
1195 struct GNUNET_CADET_KX_Ping msg;
1197 LOG (GNUNET_ERROR_TYPE_INFO, "===> PING for %s\n", GCT_2s (t));
1198 msg.header.size = htons (sizeof (msg));
1199 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PING);
1200 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1201 msg.target = *GCP_get_id (t->peer);
1202 msg.nonce = t->kx_ctx->challenge;
1204 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
1205 LOG (GNUNET_ERROR_TYPE_DEBUG, " towards %s\n", GNUNET_i2s (&msg.target));
1206 t_encrypt (t, &msg.target, &msg.target,
1207 ping_encryption_size(), msg.iv, GNUNET_YES);
1208 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
1209 LOG (GNUNET_ERROR_TYPE_DEBUG, " e towards %s\n", GNUNET_i2s (&msg.target));
1211 send_kx (t, &msg.header);
1216 * Send a pong message on a tunnel.
1218 * @param t Tunnel on which to send the pong.
1219 * @param challenge Value sent in the ping that we have to send back.
1222 send_pong (struct CadetTunnel *t, uint32_t challenge)
1224 struct GNUNET_CADET_KX_Pong msg;
1226 LOG (GNUNET_ERROR_TYPE_INFO, "===> PONG for %s\n", GCT_2s (t));
1227 msg.header.size = htons (sizeof (msg));
1228 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
1229 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1230 msg.nonce = challenge;
1231 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
1232 t_encrypt (t, &msg.nonce, &msg.nonce,
1233 sizeof (msg.nonce), msg.iv, GNUNET_YES);
1234 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
1236 send_kx (t, &msg.header);
1241 * Initiate a rekey with the remote peer.
1243 * @param cls Closure (tunnel).
1244 * @param tc TaskContext.
1247 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1249 struct CadetTunnel *t = cls;
1251 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1253 LOG (GNUNET_ERROR_TYPE_DEBUG, "Re-key Tunnel %s\n", GCT_2s (t));
1254 if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1257 if (NULL == t->kx_ctx)
1259 LOG (GNUNET_ERROR_TYPE_DEBUG, " new kx ctx\n");
1260 t->kx_ctx = GNUNET_new (struct CadetTunnelKXCtx);
1261 t->kx_ctx->challenge =
1262 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1263 t->kx_ctx->d_key_old = t->d_key;
1264 t->kx_ctx->e_key_old = t->e_key;
1266 t->kx_ctx->rekey_start_time = GNUNET_TIME_absolute_get ();
1267 LOG (GNUNET_ERROR_TYPE_DEBUG, " new challenge for %s: %u\n",
1268 GCT_2s (t), t->kx_ctx->challenge);
1275 case CADET_TUNNEL3_KEY_UNINITIALIZED:
1276 t->estate = CADET_TUNNEL3_KEY_SENT;
1278 case CADET_TUNNEL3_KEY_SENT:
1280 case CADET_TUNNEL3_KEY_PING:
1281 case CADET_TUNNEL3_KEY_OK:
1283 t->estate = CADET_TUNNEL3_KEY_PING;
1286 LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
1289 // FIXME exponential backoff
1290 LOG (GNUNET_ERROR_TYPE_DEBUG, " next call in %s\n",
1291 GNUNET_STRINGS_relative_time_to_string (REKEY_WAIT, GNUNET_YES));
1292 t->rekey_task = GNUNET_SCHEDULER_add_delayed (REKEY_WAIT, &rekey_tunnel, t);
1297 * Our ephemeral key has changed, create new session key on all tunnels.
1299 * Each tunnel will start the Key Exchange with a random delay between
1300 * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
1301 * per second, on average.
1303 * @param cls Closure (size of the hashmap).
1304 * @param key Current public key.
1305 * @param value Value in the hash map (tunnel).
1307 * @return #GNUNET_YES, so we should continue to iterate,
1310 rekey_iterator (void *cls,
1311 const struct GNUNET_PeerIdentity *key,
1314 struct CadetTunnel *t = value;
1315 struct GNUNET_TIME_Relative delay;
1316 long n = (long) cls;
1319 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
1322 if (GNUNET_YES == GCT_is_loopback (t))
1325 r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
1326 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
1327 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1334 * Create a new ephemeral key and key message, schedule next rekeying.
1336 * @param cls Closure (unused).
1337 * @param tc TaskContext.
1340 rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1342 struct GNUNET_TIME_Absolute time;
1345 rekey_task = GNUNET_SCHEDULER_NO_TASK;
1347 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1350 GNUNET_free_non_null (my_ephemeral_key);
1351 my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
1353 time = GNUNET_TIME_absolute_get ();
1354 kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
1355 time = GNUNET_TIME_absolute_add (time, rekey_period);
1356 time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
1357 kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
1358 GNUNET_CRYPTO_ecdhe_key_get_public (my_ephemeral_key, &kx_msg.ephemeral_key);
1360 GNUNET_assert (GNUNET_OK ==
1361 GNUNET_CRYPTO_eddsa_sign (my_private_key,
1363 &kx_msg.signature));
1365 n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
1366 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
1368 rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period, &rekey, NULL);
1373 * Called only on shutdown, destroy every tunnel.
1375 * @param cls Closure (unused).
1376 * @param key Current public key.
1377 * @param value Value in the hash map (tunnel).
1379 * @return #GNUNET_YES, so we should continue to iterate,
1382 destroy_iterator (void *cls,
1383 const struct GNUNET_PeerIdentity *key,
1386 struct CadetTunnel *t = value;
1388 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
1395 * Notify remote peer that we don't know a channel he is talking about,
1396 * probably CHANNEL_DESTROY was missed.
1398 * @param t Tunnel on which to notify.
1399 * @param gid ID of the channel.
1402 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
1404 struct GNUNET_CADET_ChannelManage msg;
1406 msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
1407 msg.header.size = htons (sizeof (msg));
1408 msg.chid = htonl (gid);
1410 LOG (GNUNET_ERROR_TYPE_DEBUG,
1411 "WARNING destroying unknown channel %u on tunnel %s\n",
1413 send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
1418 * Demultiplex data per channel and call appropriate channel handler.
1420 * @param t Tunnel on which the data came.
1421 * @param msg Data message.
1422 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1423 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1424 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1425 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1428 handle_data (struct CadetTunnel *t,
1429 const struct GNUNET_CADET_Data *msg,
1432 struct CadetChannel *ch;
1436 size = ntohs (msg->header.size);
1438 sizeof (struct GNUNET_CADET_Data) +
1439 sizeof (struct GNUNET_MessageHeader))
1444 LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
1445 GC_m2s (ntohs (msg[1].header.type)));
1448 ch = GCT_get_channel (t, ntohl (msg->chid));
1451 GNUNET_STATISTICS_update (stats, "# data on unknown channel",
1453 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
1455 send_channel_destroy (t, ntohl (msg->chid));
1459 GCCH_handle_data (ch, msg, fwd);
1464 * Demultiplex data ACKs per channel and update appropriate channel buffer info.
1466 * @param t Tunnel on which the DATA ACK came.
1467 * @param msg DATA ACK message.
1468 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1469 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1470 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1471 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1474 handle_data_ack (struct CadetTunnel *t,
1475 const struct GNUNET_CADET_DataACK *msg,
1478 struct CadetChannel *ch;
1482 size = ntohs (msg->header.size);
1483 if (size != sizeof (struct GNUNET_CADET_DataACK))
1490 ch = GCT_get_channel (t, ntohl (msg->chid));
1493 GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
1495 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1500 GCCH_handle_data_ack (ch, msg, fwd);
1505 * Handle channel create.
1507 * @param t Tunnel on which the data came.
1508 * @param msg Data message.
1511 handle_ch_create (struct CadetTunnel *t,
1512 const struct GNUNET_CADET_ChannelCreate *msg)
1514 struct CadetChannel *ch;
1518 size = ntohs (msg->header.size);
1519 if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
1526 ch = GCT_get_channel (t, ntohl (msg->chid));
1527 if (NULL != ch && ! GCT_is_loopback (t))
1529 /* Probably a retransmission, safe to ignore */
1530 LOG (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
1532 ch = GCCH_handle_create (t, msg);
1534 GCT_add_channel (t, ch);
1540 * Handle channel NACK: check correctness and call channel handler for NACKs.
1542 * @param t Tunnel on which the NACK came.
1543 * @param msg NACK message.
1546 handle_ch_nack (struct CadetTunnel *t,
1547 const struct GNUNET_CADET_ChannelManage *msg)
1549 struct CadetChannel *ch;
1553 size = ntohs (msg->header.size);
1554 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1561 ch = GCT_get_channel (t, ntohl (msg->chid));
1564 GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
1566 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1571 GCCH_handle_nack (ch);
1576 * Handle a CHANNEL ACK (SYNACK/ACK).
1578 * @param t Tunnel on which the CHANNEL ACK came.
1579 * @param msg CHANNEL ACK message.
1580 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1581 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1582 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1583 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1586 handle_ch_ack (struct CadetTunnel *t,
1587 const struct GNUNET_CADET_ChannelManage *msg,
1590 struct CadetChannel *ch;
1594 size = ntohs (msg->header.size);
1595 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1602 ch = GCT_get_channel (t, ntohl (msg->chid));
1605 GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
1607 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1612 GCCH_handle_ack (ch, msg, fwd);
1617 * Handle a channel destruction message.
1619 * @param t Tunnel on which the message came.
1620 * @param msg Channel destroy message.
1621 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1622 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1623 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1624 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1627 handle_ch_destroy (struct CadetTunnel *t,
1628 const struct GNUNET_CADET_ChannelManage *msg,
1631 struct CadetChannel *ch;
1635 size = ntohs (msg->header.size);
1636 if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1643 ch = GCT_get_channel (t, ntohl (msg->chid));
1646 /* Probably a retransmission, safe to ignore */
1650 GCCH_handle_destroy (ch, msg, fwd);
1655 * The peer's ephemeral key has changed: update the symmetrical keys.
1657 * @param t Tunnel this message came on.
1658 * @param msg Key eXchange message.
1661 handle_ephemeral (struct CadetTunnel *t,
1662 const struct GNUNET_CADET_KX_Ephemeral *msg)
1664 LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
1666 if (GNUNET_OK != check_ephemeral (t, msg))
1668 GNUNET_break_op (0);
1671 t->peers_ephemeral_key = msg->ephemeral_key;
1673 if (CADET_TUNNEL3_KEY_SENT == t->estate)
1675 LOG (GNUNET_ERROR_TYPE_DEBUG, " our key was sent, sending ping\n");
1677 t->estate = CADET_TUNNEL3_KEY_PING;
1683 * Peer wants to check our symmetrical keys by sending an encrypted challenge.
1684 * Answer with by retransmitting the challenge with the "opposite" key.
1686 * @param t Tunnel this message came on.
1687 * @param msg Key eXchange Ping message.
1690 handle_ping (struct CadetTunnel *t,
1691 const struct GNUNET_CADET_KX_Ping *msg)
1693 struct GNUNET_CADET_KX_Ping res;
1695 if (ntohs (msg->header.size) != sizeof (res))
1697 GNUNET_break_op (0);
1701 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PING for %s\n", GCT_2s (t));
1702 t_decrypt (t, &res.target, &msg->target, ping_encryption_size (), msg->iv);
1703 if (0 != memcmp (&my_full_id, &res.target, sizeof (my_full_id)))
1705 GNUNET_STATISTICS_update (stats, "# malformed PINGs", 1, GNUNET_NO);
1706 LOG (GNUNET_ERROR_TYPE_WARNING, " malformed PING on %s\n", GCT_2s (t));
1707 LOG (GNUNET_ERROR_TYPE_DEBUG, " e got %u\n", msg->nonce);
1708 LOG (GNUNET_ERROR_TYPE_DEBUG, " e towards %s\n", GNUNET_i2s (&msg->target));
1709 LOG (GNUNET_ERROR_TYPE_DEBUG, " got %u\n", res.nonce);
1710 LOG (GNUNET_ERROR_TYPE_DEBUG, " towards %s\n", GNUNET_i2s (&res.target));
1716 send_pong (t, res.nonce);
1719 * @brief Finish the Key eXchange and destory the old keys.
1721 * @param cls Closure (Tunnel for which to finish the KX).
1722 * @param tc Task context.
1725 finish_kx (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1727 struct CadetTunnel *t = cls;
1729 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1732 GNUNET_free (t->kx_ctx);
1738 * Peer has answer to our challenge.
1739 * If answer is successful, consider the key exchange finished and clean
1740 * up all related state.
1742 * @param t Tunnel this message came on.
1743 * @param msg Key eXchange Pong message.
1746 handle_pong (struct CadetTunnel *t,
1747 const struct GNUNET_CADET_KX_Pong *msg)
1751 LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
1752 if (GNUNET_SCHEDULER_NO_TASK == t->rekey_task)
1754 GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
1757 t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
1759 if (challenge != t->kx_ctx->challenge)
1761 LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
1762 LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
1763 challenge, msg->nonce, t->kx_ctx->challenge);
1768 GNUNET_SCHEDULER_cancel (t->rekey_task);
1769 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1771 /* Don't free the old keys right away, but after a delay.
1772 * Rationale: the KX could have happened over a very fast connection,
1773 * with payload traffic still signed with the old key stuck in a slower
1776 if (GNUNET_SCHEDULER_NO_TASK == t->kx_ctx->finish_task)
1778 t->kx_ctx->finish_task =
1779 GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_MINUTES, finish_kx, t);
1781 GCT_change_estate (t, CADET_TUNNEL3_KEY_OK);
1786 * Demultiplex by message type and call appropriate handler for a message
1787 * towards a channel of a local tunnel.
1789 * @param t Tunnel this message came on.
1790 * @param msgh Message header.
1791 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1792 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1793 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1794 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1797 handle_decrypted (struct CadetTunnel *t,
1798 const struct GNUNET_MessageHeader *msgh,
1803 type = ntohs (msgh->type);
1804 LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
1808 case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1809 /* Do nothing, connection aleady got updated. */
1810 GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
1813 case GNUNET_MESSAGE_TYPE_CADET_DATA:
1814 /* Don't send hop ACK, wait for client to ACK */
1815 handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
1818 case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1819 handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
1822 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1823 handle_ch_create (t,
1824 (struct GNUNET_CADET_ChannelCreate *) msgh);
1827 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1829 (struct GNUNET_CADET_ChannelManage *) msgh);
1832 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1834 (struct GNUNET_CADET_ChannelManage *) msgh,
1838 case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1839 handle_ch_destroy (t,
1840 (struct GNUNET_CADET_ChannelManage *) msgh,
1845 GNUNET_break_op (0);
1846 LOG (GNUNET_ERROR_TYPE_WARNING,
1847 "end-to-end message not known (%u)\n",
1848 ntohs (msgh->type));
1853 /******************************************************************************/
1854 /******************************** API ***********************************/
1855 /******************************************************************************/
1858 * Decrypt and demultiplex by message type. Call appropriate handler
1859 * for every message.
1861 * @param t Tunnel this message came on.
1862 * @param msg Encrypted message.
1865 GCT_handle_encrypted (struct CadetTunnel *t,
1866 const struct GNUNET_CADET_Encrypted *msg)
1868 size_t size = ntohs (msg->header.size);
1869 size_t payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
1871 char cbuf [payload_size];
1872 struct GNUNET_MessageHeader *msgh;
1875 decrypted_size = t_decrypt_and_validate (t, cbuf, &msg[1], payload_size,
1876 msg->iv, &msg->hmac);
1879 while (off < decrypted_size)
1881 msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
1882 handle_decrypted (t, msgh, GNUNET_SYSERR);
1883 off += ntohs (msgh->size);
1889 * Demultiplex an encapsulated KX message by message type.
1891 * @param t Tunnel on which the message came.
1892 * @param message Payload of KX message.
1895 GCT_handle_kx (struct CadetTunnel *t,
1896 const struct GNUNET_MessageHeader *message)
1900 type = ntohs (message->type);
1901 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received\n", type);
1904 case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
1905 handle_ephemeral (t, (struct GNUNET_CADET_KX_Ephemeral *) message);
1908 case GNUNET_MESSAGE_TYPE_CADET_KX_PING:
1909 handle_ping (t, (struct GNUNET_CADET_KX_Ping *) message);
1912 case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
1913 handle_pong (t, (struct GNUNET_CADET_KX_Pong *) message);
1917 GNUNET_break_op (0);
1918 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message not known (%u)\n", type);
1924 * Initialize the tunnel subsystem.
1926 * @param c Configuration handle.
1927 * @param key ECC private key, to derive all other keys and do crypto.
1930 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
1931 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
1933 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
1935 GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
1938 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1939 "CADET", "DEFAULT_TTL", "USING DEFAULT");
1943 GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
1946 rekey_period = GNUNET_TIME_UNIT_DAYS;
1949 my_private_key = key;
1950 kx_msg.header.size = htons (sizeof (kx_msg));
1951 kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
1952 kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
1953 kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
1954 kx_msg.origin_identity = my_full_id;
1955 rekey_task = GNUNET_SCHEDULER_add_now (&rekey, NULL);
1957 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
1962 * Shut down the tunnel subsystem.
1967 if (GNUNET_SCHEDULER_NO_TASK != rekey_task)
1969 GNUNET_SCHEDULER_cancel (rekey_task);
1970 rekey_task = GNUNET_SCHEDULER_NO_TASK;
1972 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
1973 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
1980 * @param destination Peer this tunnel is towards.
1982 struct CadetTunnel *
1983 GCT_new (struct CadetPeer *destination)
1985 struct CadetTunnel *t;
1987 t = GNUNET_new (struct CadetTunnel);
1989 t->peer = destination;
1992 GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
1993 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2004 * Change the tunnel's connection state.
2006 * @param t Tunnel whose connection state to change.
2007 * @param cstate New connection state.
2010 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
2014 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
2015 GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
2016 if (myid != GCP_get_short_id (t->peer) &&
2017 CADET_TUNNEL3_READY != t->cstate &&
2018 CADET_TUNNEL3_READY == cstate)
2021 if (CADET_TUNNEL3_KEY_OK == t->estate)
2023 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered send queued data\n");
2024 send_queued_data (t);
2026 else if (CADET_TUNNEL3_KEY_UNINITIALIZED == t->estate)
2028 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered rekey\n");
2029 rekey_tunnel (t, NULL);
2034 if (CADET_TUNNEL3_READY == cstate
2035 && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
2037 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate triggered stop dht\n");
2038 GCP_stop_search (t->peer);
2043 * Change the tunnel encryption state.
2045 * @param t Tunnel whose encryption state to change.
2046 * @param state New encryption state.
2049 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
2053 LOG (GNUNET_ERROR_TYPE_DEBUG,
2054 "Tunnel %s estate was %s\n",
2055 GCP_2s (t->peer), estate2s (t->estate));
2056 LOG (GNUNET_ERROR_TYPE_DEBUG,
2057 "Tunnel %s estate is now %s\n",
2058 GCP_2s (t->peer), estate2s (state));
2059 if (myid != GCP_get_short_id (t->peer) &&
2060 CADET_TUNNEL3_KEY_OK != t->estate && CADET_TUNNEL3_KEY_OK == state)
2063 send_queued_data (t);
2071 * @brief Check if tunnel has too many connections, and remove one if necessary.
2073 * Currently this means the newest connection, unless it is a direct one.
2074 * Implemented as a task to avoid freeing a connection that is in the middle
2075 * of being created/processed.
2077 * @param cls Closure (Tunnel to check).
2078 * @param tc Task context.
2081 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2083 struct CadetTunnel *t = cls;
2085 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2088 if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
2090 struct CadetTConnection *iter;
2091 struct CadetTConnection *c;
2093 for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
2095 if ((NULL == c || iter->created.abs_value_us > c->created.abs_value_us)
2096 && GNUNET_NO == GCC_is_direct (iter->c))
2103 LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
2105 LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
2118 * Add a connection to a tunnel.
2121 * @param c Connection.
2124 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
2126 struct CadetTConnection *aux;
2128 GNUNET_assert (NULL != c);
2130 LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
2131 LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
2132 for (aux = t->connection_head; aux != NULL; aux = aux->next)
2136 aux = GNUNET_new (struct CadetTConnection);
2138 aux->created = GNUNET_TIME_absolute_get ();
2140 GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
2142 GNUNET_SCHEDULER_add_now (&trim_connections, t);
2147 * Mark a path as no longer valid for this tunnel: has been tried and failed.
2149 * @param t Tunnel to update.
2150 * @param path Invalid path to remove. Is destroyed after removal.
2153 GCT_remove_path (struct CadetTunnel *t, struct CadetPeerPath *path)
2155 GCP_remove_path (t->peer, path);
2160 * Remove a connection from a tunnel.
2163 * @param c Connection.
2166 GCT_remove_connection (struct CadetTunnel *t,
2167 struct CadetConnection *c)
2169 struct CadetTConnection *aux;
2170 struct CadetTConnection *next;
2172 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
2173 GCC_2s (c), GCT_2s (t));
2174 for (aux = t->connection_head; aux != NULL; aux = next)
2179 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
2184 /* Start new connections if needed */
2185 if (CONNECTIONS_PER_TUNNEL < GCT_count_connections (t)
2186 && GNUNET_SCHEDULER_NO_TASK == t->destroy_task
2187 && CADET_TUNNEL3_SHUTDOWN != t->cstate
2188 && GNUNET_NO == shutting_down)
2190 LOG (GNUNET_ERROR_TYPE_DEBUG, " no more connections, getting new ones\n");
2191 t->cstate = CADET_TUNNEL3_SEARCHING;
2192 GCP_connect (t->peer);
2196 /* If not marked as ready, no change is needed */
2197 if (CADET_TUNNEL3_READY != t->cstate)
2200 /* Check if any connection is ready to maintaing cstate */
2201 for (aux = t->connection_head; aux != NULL; aux = aux->next)
2202 if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
2205 t->cstate = CADET_TUNNEL3_WAITING;
2210 * Add a channel to a tunnel.
2213 * @param ch Channel.
2216 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2218 struct CadetTChannel *aux;
2220 GNUNET_assert (NULL != ch);
2222 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
2224 for (aux = t->channel_head; aux != NULL; aux = aux->next)
2226 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
2231 aux = GNUNET_new (struct CadetTChannel);
2233 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
2234 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
2236 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2238 GNUNET_SCHEDULER_cancel (t->destroy_task);
2239 t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2240 LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
2246 * Remove a channel from a tunnel.
2249 * @param ch Channel.
2252 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2254 struct CadetTChannel *aux;
2256 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
2257 for (aux = t->channel_head; aux != NULL; aux = aux->next)
2261 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
2262 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
2271 * Search for a channel by global ID.
2273 * @param t Tunnel containing the channel.
2274 * @param chid Public channel number.
2276 * @return channel handler, NULL if doesn't exist
2278 struct CadetChannel *
2279 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
2281 struct CadetTChannel *iter;
2286 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2288 if (GCCH_get_id (iter->ch) == chid)
2292 return NULL == iter ? NULL : iter->ch;
2297 * @brief Destroy a tunnel and free all resources.
2299 * Should only be called a while after the tunnel has been marked as destroyed,
2300 * in case there is a new channel added to the same peer shortly after marking
2301 * the tunnel. This way we avoid a new public key handshake.
2303 * @param cls Closure (tunnel to destroy).
2304 * @param tc Task context.
2307 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2309 struct CadetTunnel *t = cls;
2310 struct CadetTConnection *iter;
2312 LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
2313 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2315 LOG (GNUNET_ERROR_TYPE_WARNING,
2316 "Not destroying tunnel, due to shutdown. "
2317 "Tunnel at %p should have been freed by GCT_shutdown\n", t);
2320 t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2321 t->cstate = CADET_TUNNEL3_SHUTDOWN;
2323 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2325 GCC_send_destroy (iter->c);
2332 * Tunnel is empty: destroy it.
2334 * Notifies all connections about the destruction.
2336 * @param t Tunnel to destroy.
2339 GCT_destroy_empty (struct CadetTunnel *t)
2341 if (GNUNET_YES == shutting_down)
2342 return; /* Will be destroyed immediately anyway */
2344 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2346 LOG (GNUNET_ERROR_TYPE_DEBUG,
2347 "Tunnel %s is already scheduled for destruction\n",
2350 /* should never happen, tunnel can only become empty once, and the
2351 * task identifier should be NO_TASK (cleaned when the tunnel was created
2352 * or became un-empty)
2357 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: destroying scheduled\n",
2360 t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
2361 &delayed_destroy, t);
2362 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llX\n",
2363 t, t->destroy_task);
2368 * Destroy tunnel if empty (no more channels).
2370 * @param t Tunnel to destroy if empty.
2373 GCT_destroy_if_empty (struct CadetTunnel *t)
2375 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
2376 if (1 < GCT_count_channels (t))
2379 GCT_destroy_empty (t);
2384 * Destroy the tunnel.
2386 * This function does not generate any warning traffic to clients or peers.
2389 * Cancel messages belonging to this tunnel queued to neighbors.
2390 * Free any allocated resources linked to the tunnel.
2392 * @param t The tunnel to destroy.
2395 GCT_destroy (struct CadetTunnel *t)
2397 struct CadetTConnection *iter_c;
2398 struct CadetTConnection *next_c;
2399 struct CadetTChannel *iter_ch;
2400 struct CadetTChannel *next_ch;
2405 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
2407 GNUNET_break (GNUNET_YES ==
2408 GNUNET_CONTAINER_multipeermap_remove (tunnels,
2409 GCP_get_id (t->peer), t));
2411 for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
2413 next_c = iter_c->next;
2414 GCC_destroy (iter_c->c);
2416 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
2418 next_ch = iter_ch->next;
2419 GCCH_destroy (iter_ch->ch);
2420 /* Should only happen on shutdown, but it's ok. */
2423 if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2425 LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling %llX\n", t->destroy_task);
2426 GNUNET_SCHEDULER_cancel (t->destroy_task);
2427 t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2430 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
2431 GCP_set_tunnel (t->peer, NULL);
2433 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
2435 GNUNET_SCHEDULER_cancel (t->rekey_task);
2436 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
2438 if (NULL != t->kx_ctx)
2440 if (GNUNET_SCHEDULER_NO_TASK != t->kx_ctx->finish_task)
2441 GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
2442 GNUNET_free (t->kx_ctx);
2449 * @brief Use the given path for the tunnel.
2450 * Update the next and prev hops (and RCs).
2451 * (Re)start the path refresh in case the tunnel is locally owned.
2453 * @param t Tunnel to update.
2454 * @param p Path to use.
2456 * @return Connection created.
2458 struct CadetConnection *
2459 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
2461 struct CadetConnection *c;
2462 struct GNUNET_CADET_Hash cid;
2463 unsigned int own_pos;
2465 if (NULL == t || NULL == p)
2471 if (CADET_TUNNEL3_SHUTDOWN == t->cstate)
2477 for (own_pos = 0; own_pos < p->length; own_pos++)
2479 if (p->peers[own_pos] == myid)
2482 if (own_pos >= p->length)
2484 GNUNET_break_op (0);
2488 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
2489 c = GCC_new (&cid, t, p, own_pos);
2492 /* Path was flawed */
2495 GCT_add_connection (t, c);
2501 * Count established (ready) connections of a tunnel.
2503 * @param t Tunnel on which to count.
2505 * @return Number of connections.
2508 GCT_count_connections (struct CadetTunnel *t)
2510 struct CadetTConnection *iter;
2516 for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2517 if (CADET_CONNECTION_DESTROYED != GCC_get_state (iter->c))
2524 * Count channels of a tunnel.
2526 * @param t Tunnel on which to count.
2528 * @return Number of channels.
2531 GCT_count_channels (struct CadetTunnel *t)
2533 struct CadetTChannel *iter;
2536 for (count = 0, iter = t->channel_head;
2538 iter = iter->next, count++) /* skip */;
2545 * Get the connectivity state of a tunnel.
2549 * @return Tunnel's connectivity state.
2551 enum CadetTunnelCState
2552 GCT_get_cstate (struct CadetTunnel *t)
2557 return (enum CadetTunnelCState) -1;
2564 * Get the encryption state of a tunnel.
2568 * @return Tunnel's encryption state.
2570 enum CadetTunnelEState
2571 GCT_get_estate (struct CadetTunnel *t)
2576 return (enum CadetTunnelEState) -1;
2582 * Get the maximum buffer space for a tunnel towards a local client.
2586 * @return Biggest buffer space offered by any channel in the tunnel.
2589 GCT_get_channels_buffer (struct CadetTunnel *t)
2591 struct CadetTChannel *iter;
2592 unsigned int buffer;
2593 unsigned int ch_buf;
2595 if (NULL == t->channel_head)
2597 /* Probably getting buffer for a channel create/handshake. */
2602 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2604 ch_buf = get_channel_buffer (iter);
2605 if (ch_buf > buffer)
2613 * Get the total buffer space for a tunnel for P2P traffic.
2617 * @return Buffer space offered by all connections in the tunnel.
2620 GCT_get_connections_buffer (struct CadetTunnel *t)
2622 struct CadetTConnection *iter;
2623 unsigned int buffer;
2626 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2628 if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
2632 buffer += get_connection_buffer (iter);
2640 * Get the tunnel's destination.
2644 * @return ID of the destination peer.
2646 const struct GNUNET_PeerIdentity *
2647 GCT_get_destination (struct CadetTunnel *t)
2649 return GCP_get_id (t->peer);
2654 * Get the tunnel's next free global channel ID.
2658 * @return GID of a channel free to use.
2661 GCT_get_next_chid (struct CadetTunnel *t)
2663 CADET_ChannelNumber chid;
2664 CADET_ChannelNumber mask;
2667 /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
2668 * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
2669 * If peer's ID is bigger, start at 0x4... bit 30 = 1
2671 result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
2676 t->next_chid |= mask;
2678 while (NULL != GCT_get_channel (t, t->next_chid))
2680 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
2681 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
2682 t->next_chid |= mask;
2684 chid = t->next_chid;
2685 t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
2686 t->next_chid |= mask;
2693 * Send ACK on one or more channels due to buffer in connections.
2695 * @param t Channel which has some free buffer space.
2698 GCT_unchoke_channels (struct CadetTunnel *t)
2700 struct CadetTChannel *iter;
2701 unsigned int buffer;
2702 unsigned int channels = GCT_count_channels (t);
2703 unsigned int choked_n;
2704 struct CadetChannel *choked[channels];
2706 LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
2707 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
2708 if (NULL != t->channel_head)
2709 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
2711 /* Get buffer space */
2712 buffer = GCT_get_connections_buffer (t);
2718 /* Count and remember choked channels */
2720 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2722 if (GNUNET_NO == get_channel_allowed (iter))
2724 choked[choked_n++] = iter->ch;
2728 /* Unchoke random channels */
2729 while (0 < buffer && 0 < choked_n)
2731 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2733 GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
2736 choked[r] = choked[choked_n];
2742 * Send ACK on one or more connections due to buffer space to the client.
2744 * Iterates all connections of the tunnel and sends ACKs appropriately.
2749 GCT_send_connection_acks (struct CadetTunnel *t)
2751 struct CadetTConnection *iter;
2754 uint32_t allow_per_connection;
2756 unsigned int buffer;
2758 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
2767 buffer = GCT_get_channels_buffer (t);
2768 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer %u\n", buffer);
2770 /* Count connections, how many messages are already allowed */
2771 cs = GCT_count_connections (t);
2772 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2774 allowed += get_connection_allowed (iter);
2776 LOG (GNUNET_ERROR_TYPE_DEBUG, " allowed %u\n", allowed);
2778 /* Make sure there is no overflow */
2779 if (allowed > buffer)
2784 /* Authorize connections to send more data */
2785 to_allow = buffer; /* - allowed; */
2787 for (iter = t->connection_head;
2788 NULL != iter && to_allow > 0;
2791 allow_per_connection = to_allow/cs;
2792 to_allow -= allow_per_connection;
2794 if (get_connection_allowed (iter) > 64 / 3)
2798 GCC_allow (iter->c, allow_per_connection,
2799 GCC_is_origin (iter->c, GNUNET_NO));
2802 GNUNET_break (to_allow == 0);
2807 * Cancel a previously sent message while it's in the queue.
2809 * ONLY can be called before the continuation given to the send function
2810 * is called. Once the continuation is called, the message is no longer in the
2813 * @param q Handle to the queue.
2816 GCT_cancel (struct CadetTunnelQueue *q)
2821 /* tun_message_sent() will be called and free q */
2823 else if (NULL != q->tqd)
2825 unqueue_data (q->tqd);
2827 if (NULL != q->cont)
2828 q->cont (q->cont_cls, NULL, q, 0, 0);
2839 * Sends an already built message on a tunnel, encrypting it and
2840 * choosing the best connection if not provided.
2842 * @param message Message to send. Function modifies it.
2843 * @param t Tunnel on which this message is transmitted.
2844 * @param c Connection to use (autoselect if NULL).
2845 * @param force Force the tunnel to take the message (buffer overfill).
2846 * @param cont Continuation to call once message is really sent.
2847 * @param cont_cls Closure for @c cont.
2849 * @return Handle to cancel message. NULL if @c cont is NULL.
2851 struct CadetTunnelQueue *
2852 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
2853 struct CadetTunnel *t, struct CadetConnection *c,
2854 int force, GCT_sent cont, void *cont_cls)
2856 return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
2861 * Is the tunnel directed towards the local peer?
2865 * @return #GNUNET_YES if it is loopback.
2868 GCT_is_loopback (const struct CadetTunnel *t)
2870 return (myid == GCP_get_short_id (t->peer));
2875 * Is the tunnel this path already?
2880 * @return #GNUNET_YES a connection uses this path.
2883 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
2885 struct CadetTConnection *iter;
2887 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2888 if (GCC_get_path (iter->c) == p)
2896 * Get a cost of a path for a tunnel considering existing connections.
2899 * @param path Candidate path.
2901 * @return Cost of the path (path length + number of overlapping nodes)
2904 GCT_get_path_cost (const struct CadetTunnel *t,
2905 const struct CadetPeerPath *path)
2907 struct CadetTConnection *iter;
2908 const struct CadetPeerPath *aux;
2909 unsigned int overlap;
2917 GNUNET_assert (NULL != t);
2919 for (i = 0; i < path->length; i++)
2921 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2923 aux = GCC_get_path (iter->c);
2927 for (j = 0; j < aux->length; j++)
2929 if (path->peers[i] == aux->peers[j])
2937 return path->length + overlap;
2942 * Get the static string for the peer this tunnel is directed.
2946 * @return Static string the destination peer's ID.
2949 GCT_2s (const struct CadetTunnel *t)
2954 return GCP_2s (t->peer);
2958 /******************************************************************************/
2959 /***************************** INFO/DEBUG *******************************/
2960 /******************************************************************************/
2964 * Log all possible info about the tunnel state to stderr.
2966 * @param t Tunnel to debug.
2969 GCT_debug (const struct CadetTunnel *t)
2971 struct CadetTChannel *iterch;
2972 struct CadetTConnection *iterc;
2974 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
2975 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT cstate %s, estate %s\n",
2976 cstate2s (t->cstate), estate2s (t->estate));
2977 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT kx_ctx %p, rekey_task %u\n",
2978 t->kx_ctx, t->rekey_task);
2979 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT tq_head %p, tq_tail %p\n",
2980 t->tq_head, t->tq_tail);
2981 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT destroy %u\n", t->destroy_task);
2983 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT channels:\n");
2984 for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
2986 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT - %s\n", GCCH_2s (iterch->ch));
2989 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT connections:\n");
2990 for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
2992 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT - %s [%u] buf: %u/%u (qn %u/%u)\n",
2993 GCC_2s (iterc->c), GCC_get_state (iterc->c),
2994 GCC_get_buffer (iterc->c, GNUNET_YES),
2995 GCC_get_buffer (iterc->c, GNUNET_NO),
2996 GCC_get_qn (iterc->c, GNUNET_YES),
2997 GCC_get_qn (iterc->c, GNUNET_NO));
3000 LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT DEBUG TUNNEL END\n");
3005 * Iterate all tunnels.
3007 * @param iter Iterator.
3008 * @param cls Closure for @c iter.
3011 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
3013 GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
3018 * Count all tunnels.
3020 * @return Number of tunnels to remote peers kept by this peer.
3023 GCT_count_all (void)
3025 return GNUNET_CONTAINER_multipeermap_size (tunnels);
3030 * Iterate all connections of a tunnel.
3032 * @param t Tunnel whose connections to iterate.
3033 * @param iter Iterator.
3034 * @param cls Closure for @c iter.
3037 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
3039 struct CadetTConnection *ct;
3041 for (ct = t->connection_head; NULL != ct; ct = ct->next)
3047 * Iterate all channels of a tunnel.
3049 * @param t Tunnel whose channels to iterate.
3050 * @param iter Iterator.
3051 * @param cls Closure for @c iter.
3054 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
3056 struct CadetTChannel *cht;
3058 for (cht = t->channel_head; NULL != cht; cht = cht->next)
3059 iter (cls, cht->ch);