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 "mesh_protocol.h"
28 #include "mesh_path.h"
30 #include "gnunet-service-mesh_tunnel.h"
31 #include "gnunet-service-mesh_connection.h"
32 #include "gnunet-service-mesh_channel.h"
33 #include "gnunet-service-mesh_peer.h"
35 #define LOG(level, ...) GNUNET_log_from(level,"mesh-tun",__VA_ARGS__)
37 #define REKEY_WAIT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5)
39 /******************************************************************************/
40 /******************************** STRUCTS **********************************/
41 /******************************************************************************/
45 struct MeshTChannel *next;
46 struct MeshTChannel *prev;
47 struct MeshChannel *ch;
50 struct MeshTConnection
52 struct MeshTConnection *next;
53 struct MeshTConnection *prev;
54 struct MeshConnection *c;
58 * Structure used during a Key eXchange.
60 struct MeshTunnelKXCtx
63 * Decryption ("their") old key, for decrypting traffic sent by the
64 * other end before the key exchange started.
66 struct GNUNET_CRYPTO_SymmetricSessionKey d_key_old;
69 * Challenge to send in a ping and expect in the pong.
75 * Struct containing all information regarding a tunnel to a peer.
80 * Endpoint of the tunnel.
82 struct MeshPeer *peer;
85 * State of the tunnel connectivity.
87 enum MeshTunnel3CState cstate;
90 * State of the tunnel encryption.
92 enum MeshTunnel3EState estate;
95 * Key eXchange context.
97 struct MeshTunnelKXCtx *kx_ctx;
100 * Encryption ("our") key.
102 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
105 * Decryption ("their") key.
107 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
110 * Task to start the rekey process.
112 GNUNET_SCHEDULER_TaskIdentifier rekey_task;
115 * Paths that are actively used to reach the destination peer.
117 struct MeshTConnection *connection_head;
118 struct MeshTConnection *connection_tail;
121 * Next connection number.
126 * Channels inside this tunnel.
128 struct MeshTChannel *channel_head;
129 struct MeshTChannel *channel_tail;
132 * Channel ID for the next created channel.
134 MESH_ChannelNumber next_chid;
137 * Destroy flag: if true, destroy on last message.
142 * Queued messages, to transmit once tunnel gets connected.
144 struct MeshTunnelDelayed *tq_head;
145 struct MeshTunnelDelayed *tq_tail;
150 * Struct used to save messages in a non-ready tunnel to send once connected.
152 struct MeshTunnelDelayed
157 struct MeshTunnelDelayed *next;
158 struct MeshTunnelDelayed *prev;
163 struct MeshChannel *ch;
168 /* struct GNUNET_MessageHeader *msg; */
173 * Handle for messages queued but not yet sent.
175 struct MeshTunnel3Queue
178 * Connection queue handle, to cancel if necessary.
180 struct MeshConnectionQueue *q;
183 * Continuation to call once sent.
188 * Closure for @c cont.
194 /******************************************************************************/
195 /******************************* GLOBALS ***********************************/
196 /******************************************************************************/
199 * Global handle to the statistics service.
201 extern struct GNUNET_STATISTICS_Handle *stats;
204 * Local peer own ID (memory efficient handle).
206 extern GNUNET_PEER_Id myid;
209 * Local peer own ID (full value).
211 extern struct GNUNET_PeerIdentity my_full_id;
215 * Set of all tunnels, in order to trigger a new exchange on rekey.
216 * Indexed by peer's ID.
218 static struct GNUNET_CONTAINER_MultiPeerMap *tunnels;
221 * Default TTL for payload packets.
223 static unsigned long long default_ttl;
228 const static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
231 * Own ephemeral private key.
233 static struct GNUNET_CRYPTO_EcdhePrivateKey *my_ephemeral_key;
236 * Cached message used to perform a key exchange.
238 static struct GNUNET_MESH_KX_Ephemeral kx_msg;
241 * Task to generate a new ephemeral key.
243 static GNUNET_SCHEDULER_TaskIdentifier rekey_task;
248 static struct GNUNET_TIME_Relative rekey_period;
250 /******************************************************************************/
251 /******************************** STATIC ***********************************/
252 /******************************************************************************/
255 * Get string description for tunnel connectivity state.
257 * @param cs Tunnel state.
259 * @return String representation.
262 cstate2s (enum MeshTunnel3CState cs)
264 static char buf[128];
268 case MESH_TUNNEL3_NEW:
269 return "MESH_TUNNEL3_NEW";
270 case MESH_TUNNEL3_SEARCHING:
271 return "MESH_TUNNEL3_SEARCHING";
272 case MESH_TUNNEL3_WAITING:
273 return "MESH_TUNNEL3_WAITING";
274 case MESH_TUNNEL3_READY:
275 return "MESH_TUNNEL3_READY";
278 sprintf (buf, "%u (UNKNOWN STATE)", cs);
286 * Get string description for tunnel encryption state.
288 * @param es Tunnel state.
290 * @return String representation.
293 estate2s (enum MeshTunnel3EState es)
295 static char buf[128];
299 case MESH_TUNNEL3_KEY_UNINITIALIZED:
300 return "MESH_TUNNEL3_KEY_UNINITIALIZED";
301 case MESH_TUNNEL3_KEY_SENT:
302 return "MESH_TUNNEL3_KEY_SENT";
303 case MESH_TUNNEL3_KEY_PING:
304 return "MESH_TUNNEL3_KEY_PING";
305 case MESH_TUNNEL3_KEY_OK:
306 return "MESH_TUNNEL3_KEY_OK";
309 sprintf (buf, "%u (UNKNOWN STATE)", es);
317 * @brief Check if tunnel is ready to send traffic.
319 * Tunnel must be connected and with encryption correctly set up.
321 * @param t Tunnel to check.
323 * @return #GNUNET_YES if ready, #GNUNET_NO otherwise
326 is_ready (struct MeshTunnel3 *t)
328 return (MESH_TUNNEL3_READY == t->cstate
329 && MESH_TUNNEL3_KEY_OK == t->estate)
330 || GMT_is_loopback (t);
335 * Ephemeral key message purpose size.
337 * @return Size of the part of the ephemeral key message that must be signed.
340 ephemeral_purpose_size (void)
342 return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
343 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
344 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
345 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
346 sizeof (struct GNUNET_PeerIdentity);
351 * Size of the encrypted part of a ping message.
353 * @return Size of the encrypted part of a ping message.
356 ping_encryption_size (void)
358 return sizeof (struct GNUNET_PeerIdentity) + sizeof (uint32_t);
363 * Get the channel's buffer. ONLY FOR NON-LOOPBACK CHANNELS!!
365 * @param tch Tunnel's channel handle.
367 * @return Amount of messages the channel can still buffer towards the client.
370 get_channel_buffer (const struct MeshTChannel *tch)
374 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
375 fwd = GMCH_is_origin (tch->ch, GNUNET_YES);
377 return GMCH_get_buffer (tch->ch, fwd);
382 * Get the channel's allowance status.
384 * @param tch Tunnel's channel handle.
386 * @return #GNUNET_YES if we allowed the client to send data to us.
389 get_channel_allowed (const struct MeshTChannel *tch)
393 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
394 fwd = GMCH_is_origin (tch->ch, GNUNET_YES);
396 return GMCH_get_allowed (tch->ch, fwd);
401 * Get the connection's buffer.
403 * @param tc Tunnel's connection handle.
405 * @return Amount of messages the connection can still buffer.
408 get_connection_buffer (const struct MeshTConnection *tc)
412 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
413 fwd = GMC_is_origin (tc->c, GNUNET_YES);
415 return GMC_get_buffer (tc->c, fwd);
420 * Get the connection's allowance.
422 * @param tc Tunnel's connection handle.
424 * @return Amount of messages we have allowed the next peer to send us.
427 get_connection_allowed (const struct MeshTConnection *tc)
431 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
432 fwd = GMC_is_origin (tc->c, GNUNET_YES);
434 return GMC_get_allowed (tc->c, fwd);
439 * Check that a ephemeral key message s well formed and correctly signed.
441 * @param t Tunnel on which the message came.
442 * @param msg The ephemeral key message.
444 * @return GNUNET_OK if message is fine, GNUNET_SYSERR otherwise.
447 check_ephemeral (struct MeshTunnel3 *t,
448 const struct GNUNET_MESH_KX_Ephemeral *msg)
450 /* Check message size */
451 if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_KX_Ephemeral))
452 return GNUNET_SYSERR;
454 /* Check signature size */
455 if (ntohl (msg->purpose.size) != ephemeral_purpose_size ())
456 return GNUNET_SYSERR;
459 if (0 != memcmp (&msg->origin_identity,
460 GMP_get_id (t->peer),
461 sizeof (struct GNUNET_PeerIdentity)))
462 return GNUNET_SYSERR;
464 /* Check signature */
466 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_MESH_KX,
469 &msg->origin_identity.public_key))
470 return GNUNET_SYSERR;
477 * Encrypt data with the tunnel key.
479 * @param t Tunnel whose key to use.
480 * @param dst Destination for the encrypted data.
481 * @param src Source of the plaintext. Can overlap with @c dst.
482 * @param size Size of the plaintext.
483 * @param iv Initialization Vector to use.
486 t_encrypt (struct MeshTunnel3 *t,
487 void *dst, const void *src,
488 size_t size, uint32_t iv)
490 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
492 GNUNET_CRYPTO_symmetric_derive_iv (&siv, &t->e_key, &iv, sizeof (uint32_t), NULL);
493 return GNUNET_CRYPTO_symmetric_encrypt (src, size, &t->e_key, &siv, dst);
498 * Decrypt data with the tunnel key.
500 * @param t Tunnel whose key to use.
501 * @param dst Destination for the plaintext.
502 * @param src Source of the encrypted data. Can overlap with @c dst.
503 * @param size Size of the encrypted data.
504 * @param iv Initialization Vector to use.
507 t_decrypt (struct MeshTunnel3 *t,
508 void *dst, const void *src,
509 size_t size, uint32_t iv)
511 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
513 GNUNET_CRYPTO_symmetric_derive_iv (&siv, &t->d_key, &iv, sizeof (uint32_t), NULL);
514 return GNUNET_CRYPTO_symmetric_decrypt (src, size, &t->d_key, &siv, dst);
519 * Create key material by doing ECDH on the local and remote ephemeral keys.
521 * @param key_material Where to store the key material.
522 * @param ephemeral_key Peer's public ephemeral key.
525 derive_key_material (struct GNUNET_HashCode *key_material,
526 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key)
529 GNUNET_CRYPTO_ecc_ecdh (my_ephemeral_key,
538 * Create a symmetic key from the identities of both ends and the key material
541 * @param key Destination for the generated key.
542 * @param sender ID of the peer that will encrypt with @c key.
543 * @param receiver ID of the peer that will decrypt with @c key.
544 * @param key_material Hash created with ECDH with the ephemeral keys.
547 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
548 const struct GNUNET_PeerIdentity *sender,
549 const struct GNUNET_PeerIdentity *receiver,
550 const struct GNUNET_HashCode *key_material)
552 const char salt[] = "MESH kx salt";
554 GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
556 key_material, sizeof (struct GNUNET_HashCode),
557 sender, sizeof (struct GNUNET_PeerIdentity),
558 receiver, sizeof (struct GNUNET_PeerIdentity),
563 * Pick a connection on which send the next data message.
565 * @param t Tunnel on which to send the message.
567 * @return The connection on which to send the next message.
569 static struct MeshConnection *
570 tunnel_get_connection (struct MeshTunnel3 *t)
572 struct MeshTConnection *iter;
573 struct MeshConnection *best;
575 unsigned int lowest_q;
577 LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GMP_2s (t->peer));
580 for (iter = t->connection_head; NULL != iter; iter = iter->next)
582 LOG (GNUNET_ERROR_TYPE_DEBUG, " connection %s: %u\n",
583 GMC_2s (iter->c), GMC_get_state (iter->c));
584 if (MESH_CONNECTION_READY == GMC_get_state (iter->c))
586 qn = GMC_get_qn (iter->c, GMC_is_origin (iter->c, GNUNET_YES));
587 LOG (GNUNET_ERROR_TYPE_DEBUG, " q_n %u, \n", qn);
595 LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GMC_2s (best));
601 * Send all cached messages that we can, tunnel is online.
603 * @param t Tunnel that holds the messages. Cannot be loopback.
606 send_queued_data (struct MeshTunnel3 *t)
608 struct MeshTunnelDelayed *tq;
609 struct MeshTunnelDelayed *next;
612 LOG (GNUNET_ERROR_TYPE_DEBUG,
613 "GMT_send_queued_data on tunnel %s\n",
616 if (GMT_is_loopback (t))
622 if (GNUNET_NO == is_ready (t))
624 LOG (GNUNET_ERROR_TYPE_DEBUG, " not ready yet: %s/%s\n",
625 estate2s (t->estate), cstate2s (t->cstate));
629 room = GMT_get_connections_buffer (t);
630 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
631 for (tq = t->tq_head; NULL != tq && room > 0; tq = next)
633 LOG (GNUNET_ERROR_TYPE_DEBUG, " data on channel %s\n", GMCH_2s (tq->ch));
636 GNUNET_CONTAINER_DLL_remove (t->tq_head, t->tq_tail, tq);
637 GMCH_send_prebuilt_message ((struct GNUNET_MessageHeader *) &tq[1],
638 tq->ch, GMCH_is_origin (tq->ch, GNUNET_YES),
643 LOG (GNUNET_ERROR_TYPE_DEBUG,
644 "GMT_send_queued_data end\n",
652 * Cache a message to be sent once tunnel is online.
654 * @param t Tunnel to hold the message.
655 * @param ch Channel the message is about.
656 * @param msg Message itself (copy will be made).
659 queue_data (struct MeshTunnel3 *t,
660 struct MeshChannel *ch,
661 const struct GNUNET_MessageHeader *msg)
663 struct MeshTunnelDelayed *tq;
664 uint16_t size = ntohs (msg->size);
666 LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GMT_2s (t));
668 if (GNUNET_YES == is_ready (t))
674 tq = GNUNET_malloc (sizeof (struct MeshTunnelDelayed) + size);
677 memcpy (&tq[1], msg, size);
678 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tq);
684 * Sends key exchange message on a tunnel, choosing the best connection.
685 * Should not be called on loopback tunnels.
687 * @param t Tunnel on which this message is transmitted.
688 * @param message Message to send. Function modifies it.
691 send_kx (struct MeshTunnel3 *t,
692 const struct GNUNET_MessageHeader *message)
694 struct MeshConnection *c;
695 struct GNUNET_MESH_KX *msg;
696 size_t size = ntohs (message->size);
697 char cbuf[sizeof (struct GNUNET_MESH_KX) + size];
701 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GMT_2s (t));
703 /* Avoid loopback. */
704 if (GMT_is_loopback (t))
706 LOG (GNUNET_ERROR_TYPE_DEBUG, " loopback!\n");
711 /* Must have a connection. */
712 if (NULL == t->connection_head)
718 msg = (struct GNUNET_MESH_KX *) cbuf;
719 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX);
720 msg->header.size = htons (sizeof (struct GNUNET_MESH_KX) + size);
721 c = tunnel_get_connection (t);
724 GNUNET_break (GNUNET_YES == t->destroy);
727 type = ntohs (message->type);
730 case GNUNET_MESSAGE_TYPE_MESH_KX_EPHEMERAL:
731 case GNUNET_MESSAGE_TYPE_MESH_KX_PING:
732 case GNUNET_MESSAGE_TYPE_MESH_KX_PONG:
733 msg->reserved = htonl (0);
734 memcpy (&msg[1], message, size);
737 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
738 GNUNET_MESH_DEBUG_M2S (type));
742 fwd = GMC_is_origin (t->connection_head->c, GNUNET_YES);
743 /* TODO save handle and cancel in case of a unneeded retransmission */
744 GMC_send_prebuilt_message (&msg->header, c, fwd, NULL, NULL);
749 * Send the ephemeral key on a tunnel.
751 * @param t Tunnel on which to send the key.
754 send_ephemeral (struct MeshTunnel3 *t)
756 LOG (GNUNET_ERROR_TYPE_DEBUG, "%s()\n", __FUNCTION__);
758 kx_msg.sender_status = htonl (t->estate);
759 send_kx (t, &kx_msg.header);
763 * Send a ping message on a tunnel.
765 * @param t Tunnel on which to send the ping.
768 send_ping (struct MeshTunnel3 *t)
770 struct GNUNET_MESH_KX_Ping msg;
772 LOG (GNUNET_ERROR_TYPE_DEBUG, "%s()\n", __FUNCTION__);
773 msg.header.size = htons (sizeof (msg));
774 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX_PING);
775 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
776 msg.target = *GMP_get_id (t->peer);
777 msg.nonce = t->kx_ctx->challenge;
779 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
780 LOG (GNUNET_ERROR_TYPE_DEBUG, " towards %s\n", GNUNET_i2s (&msg.target));
781 t_encrypt (t, &msg.target, &msg.target, ping_encryption_size(), msg.iv);
782 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
783 LOG (GNUNET_ERROR_TYPE_DEBUG, " e towards %s\n", GNUNET_i2s (&msg.target));
785 send_kx (t, &msg.header);
790 * Send a pong message on a tunnel.
792 * @param t Tunnel on which to send the pong.
793 * @param challenge Value sent in the ping that we have to send back.
796 send_pong (struct MeshTunnel3 *t, uint32_t challenge)
798 struct GNUNET_MESH_KX_Pong msg;
800 LOG (GNUNET_ERROR_TYPE_DEBUG, "%s()\n", __FUNCTION__);
801 msg.header.size = htons (sizeof (msg));
802 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX_PONG);
803 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
804 msg.nonce = challenge;
805 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
806 t_encrypt (t, &msg.nonce, &msg.nonce, sizeof (msg.nonce), msg.iv);
807 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
809 send_kx (t, &msg.header);
814 * Initiate a rekey with the remote peer.
816 * @param cls Closure (tunnel).
817 * @param tc TaskContext.
820 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
822 struct MeshTunnel3 *t = cls;
824 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
826 LOG (GNUNET_ERROR_TYPE_DEBUG, "Re-key Tunnel\n");
827 if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
830 if (NULL == t->kx_ctx)
832 LOG (GNUNET_ERROR_TYPE_DEBUG, " new kx ctx\n");
833 t->kx_ctx = GNUNET_new (struct MeshTunnelKXCtx);
834 t->kx_ctx->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
836 t->kx_ctx->d_key_old = t->d_key;
841 case MESH_TUNNEL3_KEY_UNINITIALIZED:
842 t->estate = MESH_TUNNEL3_KEY_SENT;
844 case MESH_TUNNEL3_KEY_SENT:
846 case MESH_TUNNEL3_KEY_PING:
847 case MESH_TUNNEL3_KEY_OK:
849 t->estate = MESH_TUNNEL3_KEY_PING;
852 LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
855 LOG (GNUNET_ERROR_TYPE_DEBUG, " next call in %s\n",
856 GNUNET_STRINGS_relative_time_to_string (REKEY_WAIT, GNUNET_YES));
857 t->rekey_task = GNUNET_SCHEDULER_add_delayed (REKEY_WAIT, &rekey_tunnel, t);
862 * Out ephemeral key has changed, create new session key on all tunnels.
864 * @param cls Closure (size of the hashmap).
865 * @param key Current public key.
866 * @param value Value in the hash map (tunnel).
868 * @return #GNUNET_YES, so we should continue to iterate,
871 rekey_iterator (void *cls,
872 const struct GNUNET_PeerIdentity *key,
875 struct MeshTunnel3 *t = value;
876 struct GNUNET_TIME_Relative delay;
880 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
883 r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
884 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
885 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
892 * Create a new ephemeral key and key message, schedule next rekeying.
894 * @param cls Closure (unused).
895 * @param tc TaskContext.
898 rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
900 struct GNUNET_TIME_Absolute time;
903 rekey_task = GNUNET_SCHEDULER_NO_TASK;
905 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
908 GNUNET_free_non_null (my_ephemeral_key);
909 my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
911 time = GNUNET_TIME_absolute_get ();
912 kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
913 time = GNUNET_TIME_absolute_add (time, rekey_period);
914 time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
915 kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
916 GNUNET_CRYPTO_ecdhe_key_get_public (my_ephemeral_key, &kx_msg.ephemeral_key);
918 GNUNET_assert (GNUNET_OK ==
919 GNUNET_CRYPTO_eddsa_sign (my_private_key,
923 n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
924 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
926 rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period, &rekey, NULL);
931 * Called only on shutdown, destroy every tunnel.
933 * @param cls Closure (unused).
934 * @param key Current public key.
935 * @param value Value in the hash map (tunnel).
937 * @return #GNUNET_YES, so we should continue to iterate,
940 destroy_iterator (void *cls,
941 const struct GNUNET_PeerIdentity *key,
944 struct MeshTunnel3 *t = value;
952 * Demultiplex data per channel and call appropriate channel handler.
954 * @param t Tunnel on which the data came.
955 * @param msg Data message.
956 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
957 * #GNUNET_YES if message is FWD on the respective channel (loopback)
958 * #GNUNET_NO if message is BCK on the respective channel (loopback)
959 * #GNUNET_SYSERR if message on a one-ended channel (remote)
962 handle_data (struct MeshTunnel3 *t,
963 const struct GNUNET_MESH_Data *msg,
966 struct MeshChannel *ch;
971 size = ntohs (msg->header.size);
973 sizeof (struct GNUNET_MESH_Data) +
974 sizeof (struct GNUNET_MessageHeader))
979 type = ntohs (msg->header.type);
980 LOG (GNUNET_ERROR_TYPE_DEBUG, "got a %s message\n",
981 GNUNET_MESH_DEBUG_M2S (type));
982 LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
983 GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
986 ch = GMT_get_channel (t, ntohl (msg->chid));
989 GNUNET_STATISTICS_update (stats, "# data on unknown channel",
991 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
996 GMT_change_cstate (t, MESH_TUNNEL3_READY);
997 GMCH_handle_data (ch, msg, fwd);
1002 * Demultiplex data ACKs per channel and update appropriate channel buffer info.
1004 * @param t Tunnel on which the DATA ACK came.
1005 * @param msg DATA ACK message.
1006 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1007 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1008 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1009 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1012 handle_data_ack (struct MeshTunnel3 *t,
1013 const struct GNUNET_MESH_DataACK *msg,
1016 struct MeshChannel *ch;
1020 size = ntohs (msg->header.size);
1021 if (size != sizeof (struct GNUNET_MESH_DataACK))
1028 ch = GMT_get_channel (t, ntohl (msg->chid));
1031 GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
1033 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1038 GMCH_handle_data_ack (ch, msg, fwd);
1043 * Handle channel create.
1045 * @param t Tunnel on which the data came.
1046 * @param msg Data message.
1049 handle_ch_create (struct MeshTunnel3 *t,
1050 const struct GNUNET_MESH_ChannelCreate *msg)
1052 struct MeshChannel *ch;
1056 size = ntohs (msg->header.size);
1057 if (size != sizeof (struct GNUNET_MESH_ChannelCreate))
1064 ch = GMT_get_channel (t, ntohl (msg->chid));
1065 if (NULL != ch && ! GMT_is_loopback (t))
1067 /* Probably a retransmission, safe to ignore */
1068 LOG (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
1072 ch = GMCH_handle_create (t, msg);
1075 GMT_add_channel (t, ch);
1081 * Handle channel NACK: check correctness and call channel handler for NACKs.
1083 * @param t Tunnel on which the NACK came.
1084 * @param msg NACK message.
1087 handle_ch_nack (struct MeshTunnel3 *t,
1088 const struct GNUNET_MESH_ChannelManage *msg)
1090 struct MeshChannel *ch;
1094 size = ntohs (msg->header.size);
1095 if (size != sizeof (struct GNUNET_MESH_ChannelManage))
1102 ch = GMT_get_channel (t, ntohl (msg->chid));
1105 GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
1107 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1112 GMCH_handle_nack (ch);
1117 * Handle a CHANNEL ACK (SYNACK/ACK).
1119 * @param t Tunnel on which the CHANNEL ACK came.
1120 * @param msg CHANNEL ACK message.
1121 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1122 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1123 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1124 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1127 handle_ch_ack (struct MeshTunnel3 *t,
1128 const struct GNUNET_MESH_ChannelManage *msg,
1131 struct MeshChannel *ch;
1135 size = ntohs (msg->header.size);
1136 if (size != sizeof (struct GNUNET_MESH_ChannelManage))
1143 ch = GMT_get_channel (t, ntohl (msg->chid));
1146 GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
1148 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1153 GMCH_handle_ack (ch, msg, fwd);
1159 * Handle a channel destruction message.
1161 * @param t Tunnel on which the message came.
1162 * @param msg Channel destroy message.
1163 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1164 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1165 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1166 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1169 handle_ch_destroy (struct MeshTunnel3 *t,
1170 const struct GNUNET_MESH_ChannelManage *msg,
1173 struct MeshChannel *ch;
1177 size = ntohs (msg->header.size);
1178 if (size != sizeof (struct GNUNET_MESH_ChannelManage))
1185 ch = GMT_get_channel (t, ntohl (msg->chid));
1188 /* Probably a retransmission, safe to ignore */
1192 GMCH_handle_destroy (ch, msg, fwd);
1197 * The peer's ephemeral key has changed: update the symmetrical keys.
1199 * @param t Tunnel this message came on.
1200 * @param msg Key eXchange message.
1203 handle_ephemeral (struct MeshTunnel3 *t,
1204 const struct GNUNET_MESH_KX_Ephemeral *msg)
1206 struct GNUNET_HashCode km;
1207 LOG (GNUNET_ERROR_TYPE_DEBUG, " ephemeral key message\n");
1209 if (GNUNET_OK != check_ephemeral (t, msg))
1211 GNUNET_break_op (0);
1214 derive_key_material (&km, &msg->ephemeral_key);
1215 LOG (GNUNET_ERROR_TYPE_DEBUG, " km is %s\n", GNUNET_h2s (&km));
1216 derive_symmertic (&t->e_key, &my_full_id, GMP_get_id (t->peer), &km);
1217 derive_symmertic (&t->d_key, GMP_get_id (t->peer), &my_full_id, &km);
1218 if (MESH_TUNNEL3_KEY_SENT == t->estate)
1220 LOG (GNUNET_ERROR_TYPE_DEBUG, " our key was sent, send ping\n");
1222 t->estate = MESH_TUNNEL3_KEY_PING;
1228 * Peer wants to check our symmetrical keys by sending an encrypted challenge.
1229 * Answer with by retransmitting the challenge with the "opposite" key.
1231 * @param t Tunnel this message came on.
1232 * @param msg Key eXchange Ping message.
1235 handle_ping (struct MeshTunnel3 *t,
1236 const struct GNUNET_MESH_KX_Ping *msg)
1238 struct GNUNET_MESH_KX_Ping res;
1240 if (ntohs (msg->header.size) != sizeof (res))
1242 GNUNET_break_op (0);
1246 LOG (GNUNET_ERROR_TYPE_DEBUG, " ping message\n");
1247 t_decrypt (t, &res.target, &msg->target, ping_encryption_size (), msg->iv);
1248 if (0 != memcmp (&my_full_id, &res.target, sizeof (my_full_id)))
1250 GNUNET_break_op (0);
1251 LOG (GNUNET_ERROR_TYPE_DEBUG, " e got %u\n", msg->nonce);
1252 LOG (GNUNET_ERROR_TYPE_DEBUG, " e towards %s\n", GNUNET_i2s (&msg->target));
1253 LOG (GNUNET_ERROR_TYPE_DEBUG, " got %u\n", res.nonce);
1254 LOG (GNUNET_ERROR_TYPE_DEBUG, " towards %s\n", GNUNET_i2s (&res.target));
1258 send_pong (t, res.nonce);
1263 * Peer has answer to our challenge.
1264 * If answer is successful, consider the key exchange finished and clean
1265 * up all related state.
1267 * @param t Tunnel this message came on.
1268 * @param msg Key eXchange Pong message.
1271 handle_pong (struct MeshTunnel3 *t,
1272 const struct GNUNET_MESH_KX_Pong *msg)
1276 LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG received\n");
1277 if (GNUNET_SCHEDULER_NO_TASK == t->rekey_task)
1279 GNUNET_break_op (0);
1282 t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
1284 if (challenge != t->kx_ctx->challenge)
1286 LOG (GNUNET_ERROR_TYPE_DEBUG,
1287 "Wrong PONG challenge: %u (e: %u). Expected: %u.\n",
1288 challenge, msg->nonce, t->kx_ctx->challenge);
1289 GNUNET_break_op (0);
1292 GNUNET_SCHEDULER_cancel (t->rekey_task);
1293 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1294 GNUNET_free (t->kx_ctx);
1296 GMT_change_estate (t, MESH_TUNNEL3_KEY_OK);
1301 * Demultiplex by message type and call appropriate handler for a message
1302 * towards a channel of a local tunnel.
1304 * @param t Tunnel this message came on.
1305 * @param msgh Message header.
1306 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1307 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1308 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1309 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1312 handle_decrypted (struct MeshTunnel3 *t,
1313 const struct GNUNET_MessageHeader *msgh,
1318 type = ntohs (msgh->type);
1319 LOG (GNUNET_ERROR_TYPE_DEBUG,
1320 "Got a %s message!\n",
1321 GNUNET_MESH_DEBUG_M2S (type));
1325 case GNUNET_MESSAGE_TYPE_MESH_DATA:
1326 /* Don't send hop ACK, wait for client to ACK */
1327 handle_data (t, (struct GNUNET_MESH_Data *) msgh, fwd);
1330 case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
1331 handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh, fwd);
1334 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
1335 handle_ch_create (t,
1336 (struct GNUNET_MESH_ChannelCreate *) msgh);
1339 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_NACK:
1341 (struct GNUNET_MESH_ChannelManage *) msgh);
1344 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
1346 (struct GNUNET_MESH_ChannelManage *) msgh,
1350 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
1351 handle_ch_destroy (t,
1352 (struct GNUNET_MESH_ChannelManage *) msgh,
1357 GNUNET_break_op (0);
1358 LOG (GNUNET_ERROR_TYPE_DEBUG,
1359 "end-to-end message not known (%u)\n",
1360 ntohs (msgh->type));
1364 /******************************************************************************/
1365 /******************************** API ***********************************/
1366 /******************************************************************************/
1369 * Decrypt and demultiplex by message type. Call appropriate handler
1370 * for every message.
1372 * @param t Tunnel this message came on.
1373 * @param msg Encrypted message.
1376 GMT_handle_encrypted (struct MeshTunnel3 *t,
1377 const struct GNUNET_MESH_Encrypted *msg)
1379 size_t size = ntohs (msg->header.size);
1380 size_t payload_size = size - sizeof (struct GNUNET_MESH_Encrypted);
1381 size_t decrypted_size;
1382 char cbuf [payload_size];
1383 struct GNUNET_MessageHeader *msgh;
1386 decrypted_size = t_decrypt (t, cbuf, &msg[1], payload_size, msg->iv);
1388 while (off < decrypted_size)
1390 msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
1391 handle_decrypted (t, msgh, GNUNET_SYSERR);
1392 off += ntohs (msgh->size);
1398 * Demultiplex an encapsulated KX message by message type.
1400 * @param t Tunnel on which the message came.
1401 * @param message Payload of KX message.
1404 GMT_handle_kx (struct MeshTunnel3 *t,
1405 const struct GNUNET_MessageHeader *message)
1409 type = ntohs (message->type);
1410 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received\n", type);
1413 case GNUNET_MESSAGE_TYPE_MESH_KX_EPHEMERAL:
1414 handle_ephemeral (t, (struct GNUNET_MESH_KX_Ephemeral *) message);
1417 case GNUNET_MESSAGE_TYPE_MESH_KX_PING:
1418 handle_ping (t, (struct GNUNET_MESH_KX_Ping *) message);
1421 case GNUNET_MESSAGE_TYPE_MESH_KX_PONG:
1422 handle_pong (t, (struct GNUNET_MESH_KX_Pong *) message);
1426 GNUNET_break_op (0);
1427 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message not known (%u)\n", type);
1433 * Initialize the tunnel subsystem.
1435 * @param c Configuration handle.
1436 * @param key ECC private key, to derive all other keys and do crypto.
1439 GMT_init (const struct GNUNET_CONFIGURATION_Handle *c,
1440 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
1442 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
1444 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
1447 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1448 "MESH", "DEFAULT_TTL", "USING DEFAULT");
1452 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REKEY_PERIOD",
1455 rekey_period = GNUNET_TIME_UNIT_DAYS;
1458 my_private_key = key;
1459 kx_msg.header.size = htons (sizeof (kx_msg));
1460 kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX_EPHEMERAL);
1461 kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_MESH_KX);
1462 kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
1463 kx_msg.origin_identity = my_full_id;
1464 rekey_task = GNUNET_SCHEDULER_add_now (&rekey, NULL);
1466 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
1471 * Shut down the tunnel subsystem.
1476 if (GNUNET_SCHEDULER_NO_TASK != rekey_task)
1478 GNUNET_SCHEDULER_cancel (rekey_task);
1479 rekey_task = GNUNET_SCHEDULER_NO_TASK;
1481 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
1482 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
1489 * @param destination Peer this tunnel is towards.
1491 struct MeshTunnel3 *
1492 GMT_new (struct MeshPeer *destination)
1494 struct MeshTunnel3 *t;
1496 t = GNUNET_new (struct MeshTunnel3);
1498 t->peer = destination;
1501 GNUNET_CONTAINER_multipeermap_put (tunnels, GMP_get_id (destination), t,
1502 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
1513 * Change the tunnel's connection state.
1515 * @param t Tunnel whose connection state to change.
1516 * @param cstate New connection state.
1519 GMT_change_cstate (struct MeshTunnel3* t, enum MeshTunnel3CState state)
1523 LOG (GNUNET_ERROR_TYPE_DEBUG,
1524 "Tunnel %s cstate was %s\n",
1525 GMP_2s (t->peer), cstate2s (t->cstate));
1526 LOG (GNUNET_ERROR_TYPE_DEBUG,
1527 "Tunnel %s cstate is now %s\n",
1528 GMP_2s (t->peer), cstate2s (state));
1529 if (myid != GMP_get_short_id (t->peer) &&
1530 MESH_TUNNEL3_READY != t->cstate &&
1531 MESH_TUNNEL3_READY == state)
1534 if (MESH_TUNNEL3_KEY_OK == t->estate)
1536 LOG (GNUNET_ERROR_TYPE_DEBUG, " triggered send queued data\n");
1537 send_queued_data (t);
1539 else if (MESH_TUNNEL3_KEY_UNINITIALIZED == t->estate)
1541 LOG (GNUNET_ERROR_TYPE_DEBUG, " triggered rekey\n");
1542 rekey_tunnel (t, NULL);
1547 if (MESH_TUNNEL3_READY == state && 3 <= GMT_count_connections (t))
1549 GMP_stop_search (t->peer);
1554 * Change the tunnel encryption state.
1556 * @param t Tunnel whose encryption state to change.
1557 * @param state New encryption state.
1560 GMT_change_estate (struct MeshTunnel3* t, enum MeshTunnel3EState state)
1564 LOG (GNUNET_ERROR_TYPE_DEBUG,
1565 "Tunnel %s estate was %s\n",
1566 GMP_2s (t->peer), estate2s (t->estate));
1567 LOG (GNUNET_ERROR_TYPE_DEBUG,
1568 "Tunnel %s estate is now %s\n",
1569 GMP_2s (t->peer), estate2s (state));
1570 if (myid != GMP_get_short_id (t->peer) &&
1571 MESH_TUNNEL3_KEY_OK != t->estate && MESH_TUNNEL3_KEY_OK == state)
1574 send_queued_data (t);
1582 * Add a connection to a tunnel.
1585 * @param c Connection.
1588 GMT_add_connection (struct MeshTunnel3 *t, struct MeshConnection *c)
1590 struct MeshTConnection *aux;
1592 for (aux = t->connection_head; aux != NULL; aux = aux->next)
1596 aux = GNUNET_new (struct MeshTConnection);
1598 GNUNET_CONTAINER_DLL_insert_tail (t->connection_head, t->connection_tail, aux);
1603 * Remove a connection from a tunnel.
1606 * @param c Connection.
1609 GMT_remove_connection (struct MeshTunnel3 *t, struct MeshConnection *c)
1611 struct MeshTConnection *aux;
1613 for (aux = t->connection_head; aux != NULL; aux = aux->next)
1616 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
1624 * Add a channel to a tunnel.
1627 * @param ch Channel.
1630 GMT_add_channel (struct MeshTunnel3 *t, struct MeshChannel *ch)
1632 struct MeshTChannel *aux;
1634 GNUNET_assert (NULL != ch);
1636 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
1638 for (aux = t->channel_head; aux != NULL; aux = aux->next)
1640 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
1645 aux = GNUNET_new (struct MeshTChannel);
1647 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
1648 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
1653 * Remove a channel from a tunnel.
1656 * @param ch Channel.
1659 GMT_remove_channel (struct MeshTunnel3 *t, struct MeshChannel *ch)
1661 struct MeshTChannel *aux;
1663 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
1664 for (aux = t->channel_head; aux != NULL; aux = aux->next)
1668 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GMCH_2s (ch));
1669 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
1678 * Search for a channel by global ID.
1680 * @param t Tunnel containing the channel.
1681 * @param chid Public channel number.
1683 * @return channel handler, NULL if doesn't exist
1685 struct MeshChannel *
1686 GMT_get_channel (struct MeshTunnel3 *t, MESH_ChannelNumber chid)
1688 struct MeshTChannel *iter;
1693 for (iter = t->channel_head; NULL != iter; iter = iter->next)
1695 if (GMCH_get_id (iter->ch) == chid)
1699 return NULL == iter ? NULL : iter->ch;
1704 * Tunnel is empty: destroy it.
1706 * Notifies all connections about the destruction.
1708 * @param t Tunnel to destroy.
1711 GMT_destroy_empty (struct MeshTunnel3 *t)
1713 struct MeshTConnection *iter;
1715 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel empty: destroying scheduled\n");
1716 for (iter = t->connection_head; NULL != iter; iter = iter->next)
1718 GMC_send_destroy (iter->c);
1721 t->cstate = MESH_TUNNEL3_NEW;
1722 t->destroy = GNUNET_YES;
1727 * Destroy tunnel if empty (no more channels).
1729 * @param t Tunnel to destroy if empty.
1732 GMT_destroy_if_empty (struct MeshTunnel3 *t)
1734 if (1 < GMT_count_channels (t))
1737 GMT_destroy_empty (t);
1742 * Destroy the tunnel.
1744 * This function does not generate any warning traffic to clients or peers.
1747 * Cancel messages belonging to this tunnel queued to neighbors.
1748 * Free any allocated resources linked to the tunnel.
1750 * @param t The tunnel to destroy.
1753 GMT_destroy (struct MeshTunnel3 *t)
1755 struct MeshTConnection *iter_c;
1756 struct MeshTConnection *next_c;
1757 struct MeshTChannel *iter_ch;
1758 struct MeshTChannel *next_ch;
1763 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GMP_2s (t->peer));
1765 GNUNET_break (GNUNET_YES ==
1766 GNUNET_CONTAINER_multipeermap_remove (tunnels,
1767 GMP_get_id (t->peer), t));
1769 for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
1771 next_c = iter_c->next;
1772 GMC_destroy (iter_c->c);
1774 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
1776 next_ch = iter_ch->next;
1777 GMCH_destroy (iter_ch->ch);
1778 /* Should only happen on shutdown, but it's ok. */
1781 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
1782 GMP_set_tunnel (t->peer, NULL);
1784 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
1785 GNUNET_SCHEDULER_cancel (t->rekey_task);
1792 * @brief Use the given path for the tunnel.
1793 * Update the next and prev hops (and RCs).
1794 * (Re)start the path refresh in case the tunnel is locally owned.
1796 * @param t Tunnel to update.
1797 * @param p Path to use.
1799 * @return Connection created.
1801 struct MeshConnection *
1802 GMT_use_path (struct MeshTunnel3 *t, struct MeshPeerPath *p)
1804 struct MeshConnection *c;
1805 struct GNUNET_HashCode cid;
1806 unsigned int own_pos;
1808 if (NULL == t || NULL == p)
1814 for (own_pos = 0; own_pos < p->length; own_pos++)
1816 if (p->peers[own_pos] == myid)
1819 if (own_pos > p->length - 1)
1825 GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE, &cid);
1826 c = GMC_new (&cid, t, p, own_pos);
1827 GMT_add_connection (t, c);
1833 * Count established (ready) connections of a tunnel.
1835 * @param t Tunnel on which to count.
1837 * @return Number of connections.
1840 GMT_count_connections (struct MeshTunnel3 *t)
1842 struct MeshTConnection *iter;
1845 for (count = 0, iter = t->connection_head;
1847 iter = iter->next, count++);
1853 * Count channels of a tunnel.
1855 * @param t Tunnel on which to count.
1857 * @return Number of channels.
1860 GMT_count_channels (struct MeshTunnel3 *t)
1862 struct MeshTChannel *iter;
1865 for (count = 0, iter = t->channel_head;
1867 iter = iter->next, count++) /* skip */;
1874 * Get the connectivity state of a tunnel.
1878 * @return Tunnel's connectivity state.
1880 enum MeshTunnel3CState
1881 GMT_get_cstate (struct MeshTunnel3 *t)
1886 return (enum MeshTunnel3CState) -1;
1893 * Get the maximum buffer space for a tunnel towards a local client.
1897 * @return Biggest buffer space offered by any channel in the tunnel.
1900 GMT_get_channels_buffer (struct MeshTunnel3 *t)
1902 struct MeshTChannel *iter;
1903 unsigned int buffer;
1904 unsigned int ch_buf;
1906 if (NULL == t->channel_head)
1908 /* Probably getting buffer for a channel create/handshake. */
1913 for (iter = t->channel_head; NULL != iter; iter = iter->next)
1915 ch_buf = get_channel_buffer (iter);
1916 if (ch_buf > buffer)
1924 * Get the total buffer space for a tunnel for P2P traffic.
1928 * @return Buffer space offered by all connections in the tunnel.
1931 GMT_get_connections_buffer (struct MeshTunnel3 *t)
1933 struct MeshTConnection *iter;
1934 unsigned int buffer;
1936 iter = t->connection_head;
1938 while (NULL != iter)
1940 if (GMC_get_state (iter->c) != MESH_CONNECTION_READY)
1946 buffer += get_connection_buffer (iter);
1955 * Get the tunnel's destination.
1959 * @return ID of the destination peer.
1961 const struct GNUNET_PeerIdentity *
1962 GMT_get_destination (struct MeshTunnel3 *t)
1964 return GMP_get_id (t->peer);
1969 * Get the tunnel's next free global channel ID.
1973 * @return GID of a channel free to use.
1976 GMT_get_next_chid (struct MeshTunnel3 *t)
1978 MESH_ChannelNumber chid;
1980 while (NULL != GMT_get_channel (t, t->next_chid))
1982 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
1983 t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
1985 chid = t->next_chid;
1986 t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
1993 * Send ACK on one or more channels due to buffer in connections.
1995 * @param t Channel which has some free buffer space.
1998 GMT_unchoke_channels (struct MeshTunnel3 *t)
2000 struct MeshTChannel *iter;
2001 unsigned int buffer;
2002 unsigned int channels = GMT_count_channels (t);
2003 unsigned int choked_n;
2004 struct MeshChannel *choked[channels];
2006 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT_unchoke_channels on %s\n", GMT_2s (t));
2007 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
2008 if (NULL != t->channel_head)
2009 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
2011 /* Get buffer space */
2012 buffer = GMT_get_connections_buffer (t);
2018 /* Count and remember choked channels */
2020 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2022 if (GNUNET_NO == get_channel_allowed (iter))
2024 choked[choked_n++] = iter->ch;
2028 /* Unchoke random channels */
2029 while (0 < buffer && 0 < choked_n)
2031 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2033 GMCH_allow_client (choked[r], GMCH_is_origin (choked[r], GNUNET_YES));
2036 choked[r] = choked[choked_n];
2042 * Send ACK on one or more connections due to buffer space to the client.
2044 * Iterates all connections of the tunnel and sends ACKs appropriately.
2049 GMT_send_connection_acks (struct MeshTunnel3 *t)
2051 struct MeshTConnection *iter;
2054 uint32_t allow_per_connection;
2056 unsigned int buffer;
2058 LOG (GNUNET_ERROR_TYPE_DEBUG,
2059 "Tunnel send connection ACKs on %s\n",
2068 buffer = GMT_get_channels_buffer (t);
2070 /* Count connections, how many messages are already allowed */
2071 cs = GMT_count_connections (t);
2072 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2074 allowed += get_connection_allowed (iter);
2077 /* Make sure there is no overflow */
2078 if (allowed > buffer)
2083 /* Authorize connections to send more data */
2084 to_allow = buffer; /* - allowed; */
2086 for (iter = t->connection_head; NULL != iter && to_allow > 0; iter = iter->next)
2088 allow_per_connection = to_allow/cs;
2089 to_allow -= allow_per_connection;
2091 if (get_connection_allowed (iter) > 64 / 3)
2095 GMC_allow (iter->c, buffer, GMC_is_origin (iter->c, GNUNET_YES));
2098 GNUNET_break (to_allow == 0);
2103 * Callback called when a queued message is sent.
2105 * Calculates the average time and connection packet tracking.
2107 * @param cls Closure (TunnelQueue handle).
2108 * @param c Connection this message was on.
2109 * @param type Type of message sent.
2110 * @param fwd Was this a FWD going message?
2111 * @param size Size of the message.
2114 message_sent (void *cls,
2115 struct MeshConnection *c,
2116 struct MeshConnectionQueue *q,
2117 uint16_t type, int fwd, size_t size)
2119 struct MeshTunnel3Queue *qt = cls;
2121 GNUNET_assert (NULL != qt->cont);
2122 qt->cont (qt->cont_cls, GMC_get_tunnel (c), qt, type, size);
2128 * Cancel a previously sent message while it's in the queue.
2130 * ONLY can be called before the continuation given to the send function
2131 * is called. Once the continuation is called, the message is no longer in the
2134 * @param q Handle to the queue.
2137 GMT_cancel (struct MeshTunnel3Queue *q)
2140 /* message_sent() will be called and free q */
2145 * Sends an already built message on a tunnel, encrypting it and
2146 * choosing the best connection.
2148 * @param message Message to send. Function modifies it.
2149 * @param t Tunnel on which this message is transmitted.
2150 * @param ch Channel on which this message is transmitted.
2151 * @param fwd Is this a fwd message on @c ch?
2152 * @param cont Continuation to call once message is really sent.
2153 * @param cont_cls Closure for @c cont.
2155 * @return Handle to cancel message. NULL if @c cont is NULL.
2157 struct MeshTunnel3Queue *
2158 GMT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
2159 struct MeshTunnel3 *t,
2160 struct MeshChannel *ch, int fwd,
2161 GMT_sent cont, void *cont_cls)
2163 struct MeshTunnel3Queue *q;
2164 struct MeshConnection *c;
2165 struct GNUNET_MESH_Encrypted *msg;
2166 size_t size = ntohs (message->size);
2167 size_t encrypted_size;
2168 char cbuf[sizeof (struct GNUNET_MESH_Encrypted) + size];
2172 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GMT_2s (t));
2174 if (GNUNET_NO == is_ready (t))
2176 queue_data (t, ch, message);
2181 if (GMT_is_loopback (t))
2183 LOG (GNUNET_ERROR_TYPE_DEBUG, " loopback!\n");
2184 handle_decrypted (t, message, fwd);
2185 /* FIXME: call cont? */
2186 return NULL; /* Already delivered, cannot cancel */
2189 iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
2190 msg = (struct GNUNET_MESH_Encrypted *) cbuf;
2191 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED);
2193 encrypted_size = t_encrypt (t, &msg[1], message, size, iv);
2194 msg->header.size = htons (sizeof (struct GNUNET_MESH_Encrypted) + encrypted_size);
2195 c = tunnel_get_connection (t);
2198 GNUNET_break (GNUNET_YES == t->destroy);
2201 type = ntohs (message->type);
2204 case GNUNET_MESSAGE_TYPE_MESH_DATA:
2205 case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
2206 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
2207 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
2208 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
2209 msg->cid = *GMC_get_id (c);
2210 msg->ttl = htonl (default_ttl);
2213 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
2214 GNUNET_MESH_DEBUG_M2S (type));
2218 fwd = GMC_is_origin (c, GNUNET_YES);
2222 (void) GMC_send_prebuilt_message (&msg->header, c, fwd, NULL, NULL);
2225 q = GNUNET_new (struct MeshTunnel3Queue); /* FIXME valgrind: leak*/
2226 q->q = GMC_send_prebuilt_message (&msg->header, c, fwd, &message_sent, q);
2228 q->cont_cls = cont_cls;
2234 * Is the tunnel directed towards the local peer?
2238 * @return #GNUNET_YES if it is loopback.
2241 GMT_is_loopback (const struct MeshTunnel3 *t)
2243 return (myid == GMP_get_short_id (t->peer));
2248 * Is the tunnel this path already?
2253 * @return #GNUNET_YES a connection uses this path.
2256 GMT_is_path_used (const struct MeshTunnel3 *t, const struct MeshPeerPath *p)
2258 struct MeshTConnection *iter;
2260 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2261 if (GMC_get_path (iter->c) == p)
2269 * Get a cost of a path for a tunnel considering existing connections.
2272 * @param path Candidate path.
2274 * @return Cost of the path (path length + number of overlapping nodes)
2277 GMT_get_path_cost (const struct MeshTunnel3 *t,
2278 const struct MeshPeerPath *path)
2280 struct MeshTConnection *iter;
2281 unsigned int overlap;
2289 GNUNET_assert (NULL != t);
2291 for (i = 0; i < path->length; i++)
2293 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2295 for (j = 0; j < GMC_get_path (iter->c)->length; j++)
2297 if (path->peers[i] == GMC_get_path (iter->c)->peers[j])
2305 return (path->length + overlap) * (path->score * -1);
2310 * Get the static string for the peer this tunnel is directed.
2314 * @return Static string the destination peer's ID.
2317 GMT_2s (const struct MeshTunnel3 *t)
2322 return GMP_2s (t->peer);