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_enc.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, 30)
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.
87 enum MeshTunnel3State state;
90 * Key eXchange context.
92 struct MeshTunnelKXCtx *kx_ctx;
95 * Encryption ("our") key.
97 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
100 * Decryption ("their") key.
102 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
105 * Task to start the rekey process.
107 GNUNET_SCHEDULER_TaskIdentifier rekey_task;
110 * Paths that are actively used to reach the destination peer.
112 struct MeshTConnection *connection_head;
113 struct MeshTConnection *connection_tail;
116 * Next connection number.
121 * Channels inside this tunnel.
123 struct MeshTChannel *channel_head;
124 struct MeshTChannel *channel_tail;
127 * Channel ID for the next created channel.
129 MESH_ChannelNumber next_chid;
132 * Destroy flag: if true, destroy on last message.
137 * Queued messages, to transmit once tunnel gets connected.
139 struct MeshTunnelQueue *tq_head;
140 struct MeshTunnelQueue *tq_tail;
145 * Struct used to queue messages in a tunnel.
147 struct MeshTunnelQueue
152 struct MeshTunnelQueue *next;
153 struct MeshTunnelQueue *prev;
158 struct MeshChannel *ch;
163 /* struct GNUNET_MessageHeader *msg; */
167 /******************************************************************************/
168 /******************************* GLOBALS ***********************************/
169 /******************************************************************************/
172 * Global handle to the statistics service.
174 extern struct GNUNET_STATISTICS_Handle *stats;
177 * Local peer own ID (memory efficient handle).
179 extern GNUNET_PEER_Id myid;
182 * Local peer own ID (full value).
184 extern struct GNUNET_PeerIdentity my_full_id;
188 * Set of all tunnels, in order to trigger a new exchange on rekey.
189 * Indexed by peer's ID.
191 static struct GNUNET_CONTAINER_MultiPeerMap *tunnels;
194 * Default TTL for payload packets.
196 static unsigned long long default_ttl;
201 const static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
204 * Own ephemeral private key.
206 static struct GNUNET_CRYPTO_EcdhePrivateKey *my_ephemeral_key;
209 * Cached message used to perform a key exchange.
211 static struct GNUNET_MESH_KX_Ephemeral kx_msg;
214 * Task to generate a new ephemeral key.
216 static GNUNET_SCHEDULER_TaskIdentifier rekey_task;
221 static struct GNUNET_TIME_Relative rekey_period;
223 /******************************************************************************/
224 /******************************** STATIC ***********************************/
225 /******************************************************************************/
228 * Get string description for tunnel state.
230 * @param s Tunnel state.
232 * @return String representation.
235 GMT_state2s (enum MeshTunnel3State s)
237 static char buf[128];
241 case MESH_TUNNEL3_NEW:
242 return "MESH_TUNNEL3_NEW";
243 case MESH_TUNNEL3_SEARCHING:
244 return "MESH_TUNNEL3_SEARCHING";
245 case MESH_TUNNEL3_WAITING:
246 return "MESH_TUNNEL3_WAITING";
247 case MESH_TUNNEL3_READY:
248 return "MESH_TUNNEL3_READY";
249 case MESH_TUNNEL3_RECONNECTING:
250 return "MESH_TUNNEL3_RECONNECTING";
253 sprintf (buf, "%u (UNKNOWN STATE)", s);
260 * Fill ephemeral key message purpose size.
262 * @return Size of the part of the ephemeral key message that must be signed.
265 ephemeral_purpose_size (void)
267 return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
268 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
269 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
270 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
271 sizeof (struct GNUNET_PeerIdentity);
276 * Check that a ephemeral key message s well formed and correctly signed.
278 * @param t Tunnel on which the message came.
279 * @param msg The ephemeral key message.
281 * @return \GNUNET_OK if message is fine, \GNUNET_SYSERR otherwise.
284 check_ephemeral (struct MeshTunnel3 *t,
285 const struct GNUNET_MESH_KX_Ephemeral *msg)
287 /* Check message size */
288 if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_KX_Ephemeral))
289 return GNUNET_SYSERR;
291 /* Check signature size */
292 if (ntohl (msg->purpose.size) != ephemeral_purpose_size ())
293 return GNUNET_SYSERR;
296 if (0 != memcmp (&msg->origin_identity,
297 GMP_get_id (t->peer),
298 sizeof (struct GNUNET_PeerIdentity)))
299 return GNUNET_SYSERR;
301 /* Check signature */
303 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_MESH_KX,
306 &msg->origin_identity.public_key))
307 return GNUNET_SYSERR;
314 * Encrypt data with the tunnel key.
316 * @param t Tunnel whose key to use.
317 * @param dst Destination for the encrypted data.
318 * @param src Source of the plaintext.
319 * @param size Size of the plaintext.
320 * @param iv Initialization Vector to use.
323 t_encrypt (struct MeshTunnel3 *t,
324 void *dst, const void *src,
325 size_t size, uint64_t iv)
327 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
329 GNUNET_CRYPTO_symmetric_derive_iv (&siv, &t->e_key, &iv, sizeof (uint64_t), NULL);
330 return GNUNET_CRYPTO_symmetric_encrypt (src, size, &t->e_key, &siv, dst);
335 * Decrypt data with the tunnel key.
337 * @param t Tunnel whose key to use.
338 * @param dst Destination for the plaintext.
339 * @param src Source of the encrypted data.
340 * @param size Size of the encrypted data.
341 * @param iv Initialization Vector to use.
344 t_decrypt (struct MeshTunnel3 *t,
345 void *dst, const void *src,
346 size_t size, uint64_t iv)
348 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
350 GNUNET_CRYPTO_symmetric_derive_iv (&siv, &t->e_key, &iv, sizeof (uint64_t), NULL);
351 return GNUNET_CRYPTO_symmetric_decrypt (src, size, &t->d_key, &siv, dst);
356 * Create key material by doing ECDH on the local and remote ephemeral keys.
358 * @param key_material Where to store the key material.
359 * @param ephemeral_key Peer's public ephemeral key.
362 derive_key_material (struct GNUNET_HashCode *key_material,
363 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key)
366 GNUNET_CRYPTO_ecc_ecdh (my_ephemeral_key,
375 * Create a symmetic key from the identities of both ends and the key material
378 * @param key Destination for the generated key.
379 * @param sender ID of the peer that will encrypt with @c key.
380 * @param receiver ID of the peer that will decrypt with @c key.
381 * @param key_material Hash created with ECDH with the ephemeral keys.
384 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
385 const struct GNUNET_PeerIdentity *sender,
386 const struct GNUNET_PeerIdentity *receiver,
387 const struct GNUNET_HashCode *key_material)
389 const char salt[] = "MESH kx salt";
391 GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
393 key_material, sizeof (struct GNUNET_HashCode),
394 sender, sizeof (struct GNUNET_PeerIdentity),
395 receiver, sizeof (struct GNUNET_PeerIdentity),
400 * Pick a connection on which send the next data message.
402 * @param t Tunnel on which to send the message.
403 * @param fwd Is this a fwd message?
405 * @return The connection on which to send the next message.
407 static struct MeshConnection *
408 tunnel_get_connection (struct MeshTunnel3 *t, int fwd)
410 struct MeshTConnection *iter;
411 struct MeshConnection *best;
413 unsigned int lowest_q;
415 LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GMP_2s (t->peer));
418 for (iter = t->connection_head; NULL != iter; iter = iter->next)
420 LOG (GNUNET_ERROR_TYPE_DEBUG, " connection %s: %u\n",
421 GNUNET_h2s (GMC_get_id (iter->c)), GMC_get_state (iter->c));
422 if (MESH_CONNECTION_READY == GMC_get_state (iter->c))
424 qn = GMC_get_qn (iter->c, fwd);
425 LOG (GNUNET_ERROR_TYPE_DEBUG, " q_n %u, \n", qn);
438 * Send the ephemeral key on a tunnel.
440 * @param t Tunnel on which to send the key.
443 send_ephemeral (struct MeshTunnel3 *t)
445 kx_msg.sender_status = htonl (t->state);
447 /* When channel is NULL, fwd is irrelevant. */
448 GMT_send_prebuilt_message (&kx_msg.header, t, NULL, GNUNET_YES);
452 * Send a ping message on a tunnel.
454 * @param t Tunnel on which to send the ping.
457 send_ping (struct MeshTunnel3 *t)
459 struct GNUNET_MESH_KX_Ping msg;
462 msg.header.size = htons (sizeof (msg));
463 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX_PING);
464 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT_MAX);
465 msg.target = *GMP_get_id (t->peer);
466 msg.nonce = t->kx_ctx->challenge;
467 size = sizeof (msg.target) + sizeof (msg.nonce);
468 t_encrypt (t, &msg.target, &msg.target, size, msg.iv);
470 /* When channel is NULL, fwd is irrelevant. */
471 GMT_send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES);
476 * Send a pong message on a tunnel.
478 * @param t Tunnel on which to send the pong.
479 * @param challenge Value sent in the ping that we have to send back.
482 send_pong (struct MeshTunnel3 *t, uint32_t challenge)
484 struct GNUNET_MESH_KX_Pong msg;
486 msg.header.size = htons (sizeof (msg));
487 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX_PONG);
488 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT_MAX);
489 msg.nonce = htonl (challenge);
491 /* When channel is NULL, fwd is irrelevant. */
492 GMT_send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES);
497 * Initiate a rekey with the remote peer.
499 * @param cls Closure (tunnel).
500 * @param tc TaskContext.
503 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
505 struct MeshTunnel3 *t = cls;
507 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
509 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
512 t->kx_ctx = GNUNET_new (struct MeshTunnelKXCtx);
513 t->kx_ctx->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
515 t->kx_ctx->d_key_old = t->d_key;
518 t->rekey_task = GNUNET_SCHEDULER_add_delayed (REKEY_WAIT, &rekey_tunnel, t);
523 * Out ephemeral key has changed, create new session key on all tunnels.
525 * @param cls Closure (size of the hashmap).
526 * @param key Current public key.
527 * @param value Value in the hash map (tunnel).
529 * @return #GNUNET_YES, so we should continue to iterate,
532 rekey_iterator (void *cls,
533 const struct GNUNET_PeerIdentity *key,
536 struct MeshTunnel3 *t = value;
537 struct GNUNET_TIME_Relative delay;
541 r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
542 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
543 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
550 * Create a new ephemeral key and key message, schedule next rekeying.
552 * @param cls Closure (unused).
553 * @param tc TaskContext.
556 rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
558 struct GNUNET_TIME_Absolute time;
561 rekey_task = GNUNET_SCHEDULER_NO_TASK;
563 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
566 GNUNET_free_non_null (my_ephemeral_key);
567 my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
569 time = GNUNET_TIME_absolute_get ();
570 kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
571 time = GNUNET_TIME_absolute_add (time, rekey_period);
572 time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
573 kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
574 GNUNET_CRYPTO_ecdhe_key_get_public (my_ephemeral_key, &kx_msg.ephemeral_key);
576 GNUNET_assert (GNUNET_OK ==
577 GNUNET_CRYPTO_eddsa_sign (my_private_key,
581 n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
582 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
584 rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period, &rekey, NULL);
589 * Demultiplex data per channel and call appropriate channel handler.
591 * @param t Tunnel on which the data came.
592 * @param msg Data message.
593 * @param fwd Is this FWD data? (root -> dest)
596 handle_data (struct MeshTunnel3 *t,
597 const struct GNUNET_MESH_Data *msg,
600 struct MeshChannel *ch;
605 size = ntohs (msg->header.size);
607 sizeof (struct GNUNET_MESH_Data) +
608 sizeof (struct GNUNET_MessageHeader))
613 type = ntohs (msg->header.type);
614 LOG (GNUNET_ERROR_TYPE_DEBUG, "got a %s message\n",
615 GNUNET_MESH_DEBUG_M2S (type));
616 LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
617 GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
620 ch = GMT_get_channel (t, ntohl (msg->chid));
623 GNUNET_STATISTICS_update (stats, "# data on unknown channel",
625 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
630 GMT_change_state (t, MESH_TUNNEL3_READY);
631 GMCH_handle_data (ch, msg, fwd);
635 handle_data_ack (struct MeshTunnel3 *t,
636 const struct GNUNET_MESH_DataACK *msg,
639 struct MeshChannel *ch;
643 size = ntohs (msg->header.size);
644 if (size != sizeof (struct GNUNET_MESH_DataACK))
651 ch = GMT_get_channel (t, ntohl (msg->chid));
654 GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
656 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
661 GMCH_handle_data_ack (ch, msg, fwd);
665 handle_ch_create (struct MeshTunnel3 *t,
666 const struct GNUNET_MESH_ChannelCreate *msg,
669 struct MeshChannel *ch;
673 size = ntohs (msg->header.size);
674 if (size != sizeof (struct GNUNET_MESH_ChannelCreate))
681 ch = GMT_get_channel (t, ntohl (msg->chid));
684 /* Probably a retransmission, safe to ignore */
685 LOG (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
689 ch = GMCH_handle_create (t, msg, fwd);
691 GMT_add_channel (t, ch);
695 handle_ch_ack (struct MeshTunnel3 *t,
696 const struct GNUNET_MESH_ChannelManage *msg,
699 struct MeshChannel *ch;
703 size = ntohs (msg->header.size);
704 if (size != sizeof (struct GNUNET_MESH_ChannelManage))
711 ch = GMT_get_channel (t, ntohl (msg->chid));
714 GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
716 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
721 GMCH_handle_ack (ch, msg, fwd);
725 handle_ch_destroy (struct MeshTunnel3 *t,
726 const struct GNUNET_MESH_ChannelManage *msg,
729 struct MeshChannel *ch;
733 size = ntohs (msg->header.size);
734 if (size != sizeof (struct GNUNET_MESH_ChannelManage))
741 ch = GMT_get_channel (t, ntohl (msg->chid));
744 /* Probably a retransmission, safe to ignore */
748 GMCH_handle_destroy (ch, msg, fwd);
753 * The peer's ephemeral key has changed: update the symmetrical keys.
755 * @param t Tunnel this message came on.
756 * @param msg Key eXchange message.
759 handle_ephemeral (struct MeshTunnel3 *t,
760 const struct GNUNET_MESH_KX_Ephemeral *msg)
762 struct GNUNET_HashCode key_material;
763 LOG (GNUNET_ERROR_TYPE_DEBUG, " ephemeral key message\n");
765 if (GNUNET_OK != check_ephemeral (t, msg))
770 derive_key_material (&key_material, &msg->ephemeral_key);
771 derive_symmertic (&t->e_key, &my_full_id, GMP_get_id (t->peer), &key_material);
772 derive_symmertic (&t->d_key, GMP_get_id (t->peer), &my_full_id, &key_material);
777 * Peer wants to check our symmetrical keys by sending an encrypted challenge.
778 * Answer with by retransmitting the challenge with the "opposite" key.
780 * @param t Tunnel this message came on.
781 * @param msg Key eXchange Ping message.
784 handle_ping (struct MeshTunnel3 *t,
785 const struct GNUNET_MESH_KX_Ping *msg)
789 challenge = ntohl (msg->nonce);
790 send_pong (t, challenge);
795 * Peer has answer to our challenge.
796 * If answer is successful, consider the key exchange finished and clean
797 * up all related state.
799 * @param t Tunnel this message came on.
800 * @param msg Key eXchange Pong message.
803 handle_pong (struct MeshTunnel3 *t,
804 const struct GNUNET_MESH_KX_Pong *msg)
806 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
808 GNUNET_SCHEDULER_cancel (t->rekey_task);
809 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
821 * Demultiplex by message type and call appropriate handler for a message
822 * towards a channel of a local tunnel.
824 * @param t Tunnel this message came on.
825 * @param msgh Message header.
826 * @param fwd Is this message fwd?
829 handle_decrypted (struct MeshTunnel3 *t,
830 const struct GNUNET_MessageHeader *msgh,
835 type = ntohs (msgh->type);
836 LOG (GNUNET_ERROR_TYPE_DEBUG,
837 "Got a %s message!\n",
838 GNUNET_MESH_DEBUG_M2S (type));
842 case GNUNET_MESSAGE_TYPE_MESH_DATA:
843 /* Don't send hop ACK, wait for client to ACK */
844 handle_data (t, (struct GNUNET_MESH_Data *) msgh, fwd);
847 case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
848 handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh, fwd);
851 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
853 (struct GNUNET_MESH_ChannelCreate *) msgh,
857 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
859 (struct GNUNET_MESH_ChannelManage *) msgh,
863 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
864 handle_ch_destroy (t,
865 (struct GNUNET_MESH_ChannelManage *) msgh,
871 LOG (GNUNET_ERROR_TYPE_DEBUG,
872 "end-to-end message not known (%u)\n",
877 /******************************************************************************/
878 /******************************** API ***********************************/
879 /******************************************************************************/
882 * Decrypt and demultiplex by message type. Call appropriate handler
885 * @param t Tunnel this message came on.
886 * @param msg Encrypted message.
887 * @param fwd Is this message fwd?
890 GMT_handle_encrypted (struct MeshTunnel3 *t,
891 const struct GNUNET_MESH_Encrypted *msg,
894 size_t size = ntohs (msg->header.size);
895 size_t payload_size = size - sizeof (struct GNUNET_MESH_Encrypted);
896 size_t decrypted_size;
897 char cbuf [payload_size];
898 struct GNUNET_MessageHeader *msgh;
901 decrypted_size = t_decrypt (t, cbuf, &msg[1], payload_size, msg->iv);
903 while (off < decrypted_size)
905 msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
906 handle_decrypted (t, msgh, fwd);
907 off += ntohs (msgh->size);
913 * Demultiplex an encapsulated KX message by message type.
915 * @param t Tunnel on which the message came.
916 * @param message Payload of KX message.
919 GMT_handle_kx (struct MeshTunnel3 *t,
920 const struct GNUNET_MessageHeader *message)
924 type = ntohs (message->type);
925 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received\n", type);
928 case GNUNET_MESSAGE_TYPE_MESH_KX:
929 handle_ephemeral (t, (struct GNUNET_MESH_KX_Ephemeral *) message);
932 case GNUNET_MESSAGE_TYPE_MESH_KX_PING:
933 handle_ping (t, (struct GNUNET_MESH_KX_Ping *) message);
936 case GNUNET_MESSAGE_TYPE_MESH_KX_PONG:
937 handle_pong (t, (struct GNUNET_MESH_KX_Pong *) message);
942 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message not known (%u)\n", type);
949 * Cache a message to be sent once tunnel is online.
951 * @param t Tunnel to hold the message.
952 * @param ch Channel the message is about.
953 * @param msg Message itself (copy will be made).
954 * @param fwd Is this fwd?
957 GMT_queue_data (struct MeshTunnel3 *t,
958 struct MeshChannel *ch,
959 struct GNUNET_MessageHeader *msg,
962 struct MeshTunnelQueue *tq;
963 uint16_t size = ntohs (msg->size);
965 tq = GNUNET_malloc (sizeof (struct MeshTunnelQueue) + size);
968 memcpy (&tq[1], msg, size);
969 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tq);
971 if (MESH_TUNNEL3_READY == t->state)
972 GMT_send_queued_data (t, fwd);
977 * Send all cached messages that we can, tunnel is online.
979 * @param t Tunnel that holds the messages.
980 * @param fwd Is this fwd?
983 GMT_send_queued_data (struct MeshTunnel3 *t, int fwd)
985 struct MeshTunnelQueue *tq;
986 struct MeshTunnelQueue *next;
989 LOG (GNUNET_ERROR_TYPE_DEBUG,
990 "GMT_send_queued_data on tunnel %s\n",
992 room = GMT_get_buffer (t, fwd);
993 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
994 for (tq = t->tq_head; NULL != tq && room > 0; tq = next)
996 LOG (GNUNET_ERROR_TYPE_DEBUG, " data on channel %s\n", GMCH_2s (tq->ch));
999 GNUNET_CONTAINER_DLL_remove (t->tq_head, t->tq_tail, tq);
1000 GMCH_send_prebuilt_message ((struct GNUNET_MessageHeader *) &tq[1],
1005 LOG (GNUNET_ERROR_TYPE_DEBUG,
1006 "GMT_send_queued_data end\n",
1012 * Initialize the tunnel subsystem.
1014 * @param c Configuration handle.
1015 * @param key ECC private key, to derive all other keys and do crypto.
1018 GMT_init (const struct GNUNET_CONFIGURATION_Handle *c,
1019 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
1021 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
1023 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
1026 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1027 "MESH", "DEFAULT_TTL", "USING DEFAULT");
1031 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REKEY_PERIOD",
1034 rekey_period = GNUNET_TIME_UNIT_DAYS;
1037 my_private_key = key;
1038 kx_msg.header.size = htons (sizeof (kx_msg));
1039 kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX);
1040 kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_MESH_KX);
1041 kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
1042 kx_msg.origin_identity = my_full_id;
1043 rekey_task = GNUNET_SCHEDULER_add_now (&rekey, NULL);
1045 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
1050 * Shut down the tunnel subsystem.
1055 if (GNUNET_SCHEDULER_NO_TASK != rekey_task)
1057 GNUNET_SCHEDULER_cancel (rekey_task);
1058 rekey_task = GNUNET_SCHEDULER_NO_TASK;
1060 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
1067 * @param destination Peer this tunnel is towards.
1069 struct MeshTunnel3 *
1070 GMT_new (struct MeshPeer *destination)
1072 struct MeshTunnel3 *t;
1074 t = GNUNET_new (struct MeshTunnel3);
1076 t->peer = destination;
1079 GNUNET_CONTAINER_multipeermap_put (tunnels, GMP_get_id (destination), t,
1080 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
1091 * Change the tunnel state.
1093 * @param t Tunnel whose state to change.
1094 * @param state New state.
1097 GMT_change_state (struct MeshTunnel3* t, enum MeshTunnel3State state)
1101 LOG (GNUNET_ERROR_TYPE_DEBUG,
1102 "Tunnel %s state was %s\n",
1104 GMT_state2s (t->state));
1105 LOG (GNUNET_ERROR_TYPE_DEBUG,
1106 "Tunnel %s state is now %s\n",
1108 GMT_state2s (state));
1110 if (MESH_TUNNEL3_READY == state && 3 <= GMT_count_connections (t))
1112 GMP_stop_search (t->peer);
1118 * Add a connection to a tunnel.
1121 * @param c Connection.
1124 GMT_add_connection (struct MeshTunnel3 *t, struct MeshConnection *c)
1126 struct MeshTConnection *aux;
1128 for (aux = t->connection_head; aux != NULL; aux = aux->next)
1132 aux = GNUNET_new (struct MeshTConnection);
1134 GNUNET_CONTAINER_DLL_insert_tail (t->connection_head, t->connection_tail, aux);
1139 * Remove a connection from a tunnel.
1142 * @param c Connection.
1145 GMT_remove_connection (struct MeshTunnel3 *t, struct MeshConnection *c)
1147 struct MeshTConnection *aux;
1149 for (aux = t->connection_head; aux != NULL; aux = aux->next)
1152 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
1160 * Add a channel to a tunnel.
1163 * @param ch Channel.
1166 GMT_add_channel (struct MeshTunnel3 *t, struct MeshChannel *ch)
1168 struct MeshTChannel *aux;
1170 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
1172 for (aux = t->channel_head; aux != NULL; aux = aux->next)
1174 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
1179 aux = GNUNET_new (struct MeshTChannel);
1181 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
1182 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
1187 * Remove a channel from a tunnel.
1190 * @param ch Channel.
1193 GMT_remove_channel (struct MeshTunnel3 *t, struct MeshChannel *ch)
1195 struct MeshTChannel *aux;
1197 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
1198 for (aux = t->channel_head; aux != NULL; aux = aux->next)
1202 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GMCH_2s (ch));
1203 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
1212 * Search for a channel by global ID.
1214 * @param t Tunnel containing the channel.
1215 * @param chid Public channel number.
1217 * @return channel handler, NULL if doesn't exist
1219 struct MeshChannel *
1220 GMT_get_channel (struct MeshTunnel3 *t, MESH_ChannelNumber chid)
1222 struct MeshTChannel *iter;
1227 for (iter = t->channel_head; NULL != iter; iter = iter->next)
1229 if (GMCH_get_id (iter->ch) == chid)
1233 return NULL == iter ? NULL : iter->ch;
1238 * Tunnel is empty: destroy it.
1240 * Notifies all connections about the destruction.
1242 * @param t Tunnel to destroy.
1245 GMT_destroy_empty (struct MeshTunnel3 *t)
1247 struct MeshTConnection *iter;
1249 for (iter = t->connection_head; NULL != iter; iter = iter->next)
1251 GMC_send_destroy (iter->c);
1254 t->destroy = GNUNET_YES;
1259 * Destroy tunnel if empty (no more channels).
1261 * @param t Tunnel to destroy if empty.
1264 GMT_destroy_if_empty (struct MeshTunnel3 *t)
1266 if (1 < GMT_count_channels (t))
1269 GMT_destroy_empty (t);
1274 * Destroy the tunnel.
1276 * This function does not generate any warning traffic to clients or peers.
1279 * Cancel messages belonging to this tunnel queued to neighbors.
1280 * Free any allocated resources linked to the tunnel.
1282 * @param t The tunnel to destroy.
1285 GMT_destroy (struct MeshTunnel3 *t)
1287 struct MeshTConnection *iter;
1288 struct MeshTConnection *next;
1293 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GMP_2s (t->peer));
1295 // if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &t->id, t))
1296 // GNUNET_break (0);
1298 for (iter = t->connection_head; NULL != iter; iter = next)
1301 GMC_destroy (iter->c);
1304 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
1305 GMP_set_tunnel (t->peer, NULL);
1307 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
1308 GNUNET_SCHEDULER_cancel (t->rekey_task);
1315 * @brief Use the given path for the tunnel.
1316 * Update the next and prev hops (and RCs).
1317 * (Re)start the path refresh in case the tunnel is locally owned.
1319 * @param t Tunnel to update.
1320 * @param p Path to use.
1322 * @return Connection created.
1324 struct MeshConnection *
1325 GMT_use_path (struct MeshTunnel3 *t, struct MeshPeerPath *p)
1327 struct MeshConnection *c;
1328 struct GNUNET_HashCode cid;
1329 unsigned int own_pos;
1331 if (NULL == t || NULL == p)
1337 for (own_pos = 0; own_pos < p->length; own_pos++)
1339 if (p->peers[own_pos] == myid)
1342 if (own_pos > p->length - 1)
1348 GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE, &cid);
1349 c = GMC_new (&cid, t, p, own_pos);
1350 GMT_add_connection (t, c);
1356 * Count established (ready) connections of a tunnel.
1358 * @param t Tunnel on which to count.
1360 * @return Number of connections.
1363 GMT_count_connections (struct MeshTunnel3 *t)
1365 struct MeshTConnection *iter;
1368 for (count = 0, iter = t->connection_head;
1370 iter = iter->next, count++);
1376 * Count channels of a tunnel.
1378 * @param t Tunnel on which to count.
1380 * @return Number of channels.
1383 GMT_count_channels (struct MeshTunnel3 *t)
1385 struct MeshTChannel *iter;
1388 for (count = 0, iter = t->channel_head;
1390 iter = iter->next, count++) /* skip */;
1397 * Get the state of a tunnel.
1401 * @return Tunnel's state.
1403 enum MeshTunnel3State
1404 GMT_get_state (struct MeshTunnel3 *t)
1407 return (enum MeshTunnel3State) -1;
1412 * Get the total buffer space for a tunnel.
1414 * If terminal, use the biggest channel buffer (or 64) if no channel exists.
1415 * If not terminal, use the sum of all connection buffers.
1418 * @param fwd Is this for FWD traffic?
1420 * @return Buffer space offered by all entities (c/ch) in the tunnel.
1423 GMT_get_buffer (struct MeshTunnel3 *t, int fwd)
1425 struct MeshTConnection *iter;
1426 unsigned int buffer;
1428 iter = t->connection_head;
1431 /* If terminal, return biggest channel buffer */
1432 if (NULL == iter || GMC_is_terminal (iter->c, fwd))
1434 struct MeshTChannel *iter_ch;
1435 unsigned int ch_buf;
1437 if (NULL == t->channel_head)
1439 /* Probably getting buffer for a channel create/handshake. */
1443 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = iter_ch->next)
1445 ch_buf = GMCH_get_buffer (iter_ch->ch, fwd);
1446 if (ch_buf > buffer)
1452 /* If not terminal, return sum of connection buffers */
1453 while (NULL != iter)
1455 if (GMC_get_state (iter->c) != MESH_CONNECTION_READY)
1461 buffer += GMC_get_buffer (iter->c, fwd);
1470 * Get the tunnel's destination.
1474 * @return ID of the destination peer.
1476 const struct GNUNET_PeerIdentity *
1477 GMT_get_destination (struct MeshTunnel3 *t)
1479 return GMP_get_id (t->peer);
1484 * Get the tunnel's next free global channel ID.
1488 * @return GID of a channel free to use.
1491 GMT_get_next_chid (struct MeshTunnel3 *t)
1493 MESH_ChannelNumber chid;
1495 while (NULL != GMT_get_channel (t, t->next_chid))
1497 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
1498 t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
1500 chid = t->next_chid;
1501 t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
1508 * Send ACK on one or more channels due to buffer in connections.
1510 * @param t Channel which has some free buffer space.
1511 * @param fwd Is this for FWD traffic? (ACK goes to root)
1514 GMT_unchoke_channels (struct MeshTunnel3 *t, int fwd)
1516 struct MeshTChannel *iter;
1517 unsigned int buffer;
1518 unsigned int channels = GMT_count_channels (t);
1519 unsigned int choked_n;
1520 struct MeshChannel *choked[channels];
1522 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT_unchoke_channels on %s\n", GMT_2s (t));
1523 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
1524 if (NULL != t->channel_head)
1525 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
1533 /* Get buffer space */
1534 buffer = GMT_get_buffer (t, fwd);
1540 /* Count and remember choked channels */
1542 for (iter = t->channel_head; NULL != iter; iter = iter->next)
1544 if (GNUNET_NO == GMCH_get_allowed (iter->ch, fwd))
1546 choked[choked_n++] = iter->ch;
1550 /* Unchoke random channels */
1551 while (0 < buffer && 0 < choked_n)
1553 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1555 GMCH_allow_client (choked[r], fwd);
1558 choked[r] = choked[choked_n];
1564 * Send ACK on one or more connections due to buffer space to the client.
1566 * Iterates all connections of the tunnel and sends ACKs appropriately.
1569 * @param fwd Is this in for FWD traffic? (ACK goes dest->root)
1572 GMT_send_acks (struct MeshTunnel3 *t, int fwd)
1574 struct MeshTConnection *iter;
1577 uint32_t allow_per_connection;
1579 unsigned int buffer;
1581 LOG (GNUNET_ERROR_TYPE_DEBUG,
1582 "Tunnel send %s ACKs on %s\n",
1583 fwd ? "FWD" : "BCK", GMT_2s (t));
1590 if (NULL == t->channel_head ||
1591 GNUNET_NO == GMCH_is_origin (t->channel_head->ch, !fwd))
1597 buffer = GMT_get_buffer (t, fwd);
1599 /* Count connections, how many messages are already allowed */
1600 cs = GMT_count_connections (t);
1601 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
1603 allowed += GMC_get_allowed (iter->c, fwd);
1606 /* Make sure there is no overflow */
1607 if (allowed > buffer)
1613 /* Authorize connections to send more data */
1614 to_allow = buffer; /* - allowed; */
1616 for (iter = t->connection_head; NULL != iter && to_allow > 0; iter = iter->next)
1618 allow_per_connection = to_allow/cs;
1619 to_allow -= allow_per_connection;
1621 if (GMC_get_allowed (iter->c, fwd) > 64 / 3)
1625 GMC_allow (iter->c, buffer, fwd);
1628 GNUNET_break (to_allow == 0);
1633 * Sends an already built message on a tunnel, encrypting it and
1634 * choosing the best connection.
1636 * @param message Message to send. Function modifies it.
1637 * @param t Tunnel on which this message is transmitted.
1638 * @param ch Channel on which this message is transmitted.
1639 * @param fwd Is this a fwd message?
1642 GMT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1643 struct MeshTunnel3 *t,
1644 struct MeshChannel *ch,
1647 struct MeshConnection *c;
1648 struct GNUNET_MESH_Encrypted *msg;
1649 size_t size = ntohs (message->size);
1650 size_t encrypted_size;
1651 char *cbuf[sizeof (struct GNUNET_MESH_Encrypted) + size + 64];
1655 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GMT_2s (t));
1657 iv = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_NONCE, UINT64_MAX);
1658 msg = (struct GNUNET_MESH_Encrypted *) cbuf;
1659 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED);
1660 msg->iv = GNUNET_htonll (iv);
1661 encrypted_size = t_encrypt (t, &msg[1], message, size, iv);
1662 msg->header.size = htons (sizeof (struct GNUNET_MESH_Encrypted) + encrypted_size);
1663 c = tunnel_get_connection (t, fwd);
1666 GNUNET_break (GNUNET_YES == t->destroy);
1669 type = ntohs (message->type);
1672 case GNUNET_MESSAGE_TYPE_MESH_DATA:
1673 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
1674 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
1675 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
1676 msg->cid = *GMC_get_id (c);
1677 msg->ttl = htonl (default_ttl);
1680 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
1681 GNUNET_MESH_DEBUG_M2S (type));
1685 GMC_send_prebuilt_message (&msg->header, c, fwd);
1689 * Is the tunnel directed towards the local peer?
1693 * @return GNUNET_YES if it is loopback.
1696 GMT_is_loopback (const struct MeshTunnel3 *t)
1698 return (myid == GMP_get_short_id(t->peer));
1703 * Is the tunnel using this path already?
1708 * @return GNUNET_YES a connection uses this path.
1711 GMT_is_path_used (const struct MeshTunnel3 *t, const struct MeshPeerPath *p)
1713 struct MeshTConnection *iter;
1715 for (iter = t->connection_head; NULL != iter; iter = iter->next)
1716 if (GMC_get_path (iter->c) == p)
1724 * Get a cost of a path for a tunnel considering existing connections.
1727 * @param path Candidate path.
1729 * @return Cost of the path (path length + number of overlapping nodes)
1732 GMT_get_path_cost (const struct MeshTunnel3 *t,
1733 const struct MeshPeerPath *path)
1735 struct MeshTConnection *iter;
1736 unsigned int overlap;
1744 GNUNET_assert (NULL != t);
1746 for (i = 0; i < path->length; i++)
1748 for (iter = t->connection_head; NULL != iter; iter = iter->next)
1750 for (j = 0; j < GMC_get_path (iter->c)->length; j++)
1752 if (path->peers[i] == GMC_get_path (iter->c)->peers[j])
1760 return (path->length + overlap) * (path->score * -1);
1765 * Get the static string for the peer this tunnel is directed.
1769 * @return Static string the destination peer's ID.
1772 GMT_2s (const struct MeshTunnel3 *t)
1774 return GMP_2s (t->peer);