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);
261 * Encrypt data with the tunnel key.
263 * @param t Tunnel whose key to use.
264 * @param dst Destination for the encrypted data.
265 * @param src Source of the plaintext.
266 * @param size Size of the plaintext.
267 * @param iv Initialization Vector to use.
270 t_encrypt (struct MeshTunnel3 *t,
271 void *dst, const void *src,
272 size_t size, uint64_t iv)
274 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
276 GNUNET_CRYPTO_symmetric_derive_iv (&siv, &t->e_key, &iv, sizeof (uint64_t), NULL);
277 return GNUNET_CRYPTO_symmetric_encrypt (src, size, &t->e_key, &siv, dst);
282 * Decrypt data with the tunnel key.
284 * @param t Tunnel whose key to use.
285 * @param dst Destination for the plaintext.
286 * @param src Source of the encrypted data.
287 * @param size Size of the encrypted data.
288 * @param iv Initialization Vector to use.
291 t_decrypt (struct MeshTunnel3 *t,
292 void *dst, const void *src,
293 size_t size, uint64_t iv)
295 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
297 GNUNET_CRYPTO_symmetric_derive_iv (&siv, &t->e_key, &iv, sizeof (uint64_t), NULL);
298 return GNUNET_CRYPTO_symmetric_decrypt (src, size, &t->d_key, &siv, dst);
302 * Pick a connection on which send the next data message.
304 * @param t Tunnel on which to send the message.
305 * @param fwd Is this a fwd message?
307 * @return The connection on which to send the next message.
309 static struct MeshConnection *
310 tunnel_get_connection (struct MeshTunnel3 *t, int fwd)
312 struct MeshTConnection *iter;
313 struct MeshConnection *best;
315 unsigned int lowest_q;
317 LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GMP_2s (t->peer));
320 for (iter = t->connection_head; NULL != iter; iter = iter->next)
322 LOG (GNUNET_ERROR_TYPE_DEBUG, " connection %s: %u\n",
323 GNUNET_h2s (GMC_get_id (iter->c)), GMC_get_state (iter->c));
324 if (MESH_CONNECTION_READY == GMC_get_state (iter->c))
326 qn = GMC_get_qn (iter->c, fwd);
327 LOG (GNUNET_ERROR_TYPE_DEBUG, " q_n %u, \n", qn);
340 * Send the ephemeral key on a tunnel.
342 * @param t Tunnel on which to send the key.
345 send_ephemeral (struct MeshTunnel3 *t)
347 kx_msg.sender_status = htonl (t->state);
349 /* When channel is NULL, fwd is irrelevant. */
350 GMT_send_prebuilt_message (&kx_msg.header, t, NULL, GNUNET_YES);
354 * Send a ping message on a tunnel.
356 * @param t Tunnel on which to send the ping.
359 send_ping (struct MeshTunnel3 *t)
361 struct GNUNET_MESH_KX_Ping msg;
364 msg.header.size = htons (sizeof (msg));
365 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX_PING);
366 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT_MAX);
367 msg.target = *GMP_get_id (t->peer);
368 msg.nonce = t->kx_ctx->challenge;
369 size = sizeof (msg.target) + sizeof (msg.nonce);
370 t_encrypt (t, &msg.target, &msg.target, size, msg.iv);
372 /* When channel is NULL, fwd is irrelevant. */
373 GMT_send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES);
378 * Send a pong message on a tunnel.
380 * @param t Tunnel on which to send the pong.
381 * @param challenge Value sent in the ping that we have to send back.
384 send_pong (struct MeshTunnel3 *t, uint32_t challenge)
386 struct GNUNET_MESH_KX_Pong msg;
388 msg.header.size = htons (sizeof (msg));
389 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX_PONG);
390 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT_MAX);
391 msg.nonce = htonl (challenge);
393 /* When channel is NULL, fwd is irrelevant. */
394 GMT_send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES);
399 * Initiate a rekey with the remote peer.
401 * @param cls Closure (tunnel).
402 * @param tc TaskContext.
405 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
407 struct MeshTunnel3 *t = cls;
409 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
411 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
414 t->kx_ctx = GNUNET_new (struct MeshTunnelKXCtx);
415 t->kx_ctx->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
417 t->kx_ctx->d_key_old = t->d_key;
420 t->rekey_task = GNUNET_SCHEDULER_add_delayed (REKEY_WAIT, &rekey_tunnel, t);
425 * Out ephemeral key has changed, create new session key on all tunnels.
427 * @param cls Closure (size of the hashmap).
428 * @param key Current public key.
429 * @param value Value in the hash map (tunnel).
431 * @return #GNUNET_YES, so we should continue to iterate,
434 rekey_iterator (void *cls,
435 const struct GNUNET_PeerIdentity *key,
438 struct MeshTunnel3 *t = value;
439 struct GNUNET_TIME_Relative delay;
443 r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
444 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
445 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
452 * Create a new ephemeral key and key message, schedule next rekeying.
454 * @param cls Closure (unused).
455 * @param tc TaskContext.
458 rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
460 struct GNUNET_TIME_Absolute time;
463 rekey_task = GNUNET_SCHEDULER_NO_TASK;
465 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
468 GNUNET_free_non_null (my_ephemeral_key);
469 my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
471 time = GNUNET_TIME_absolute_get ();
472 kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
473 time = GNUNET_TIME_absolute_add (time, rekey_period);
474 time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
475 kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
476 GNUNET_CRYPTO_ecdhe_key_get_public (my_ephemeral_key, &kx_msg.ephemeral_key);
478 GNUNET_assert (GNUNET_OK ==
479 GNUNET_CRYPTO_eddsa_sign (my_private_key,
483 n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
484 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
486 rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period, &rekey, NULL);
491 * Demultiplex data per channel and call appropriate channel handler.
493 * @param t Tunnel on which the data came.
494 * @param msg Data message.
495 * @param fwd Is this FWD data? (root -> dest)
498 handle_data (struct MeshTunnel3 *t,
499 const struct GNUNET_MESH_Data *msg,
502 struct MeshChannel *ch;
507 size = ntohs (msg->header.size);
509 sizeof (struct GNUNET_MESH_Data) +
510 sizeof (struct GNUNET_MessageHeader))
515 type = ntohs (msg->header.type);
516 LOG (GNUNET_ERROR_TYPE_DEBUG, "got a %s message\n",
517 GNUNET_MESH_DEBUG_M2S (type));
518 LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
519 GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
522 ch = GMT_get_channel (t, ntohl (msg->chid));
525 GNUNET_STATISTICS_update (stats, "# data on unknown channel",
527 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
532 GMT_change_state (t, MESH_TUNNEL3_READY);
533 GMCH_handle_data (ch, msg, fwd);
537 handle_data_ack (struct MeshTunnel3 *t,
538 const struct GNUNET_MESH_DataACK *msg,
541 struct MeshChannel *ch;
545 size = ntohs (msg->header.size);
546 if (size != sizeof (struct GNUNET_MESH_DataACK))
553 ch = GMT_get_channel (t, ntohl (msg->chid));
556 GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
558 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
563 GMCH_handle_data_ack (ch, msg, fwd);
567 handle_ch_create (struct MeshTunnel3 *t,
568 const struct GNUNET_MESH_ChannelCreate *msg,
571 struct MeshChannel *ch;
575 size = ntohs (msg->header.size);
576 if (size != sizeof (struct GNUNET_MESH_ChannelCreate))
583 ch = GMT_get_channel (t, ntohl (msg->chid));
586 /* Probably a retransmission, safe to ignore */
587 LOG (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
591 ch = GMCH_handle_create (t, msg, fwd);
593 GMT_add_channel (t, ch);
597 handle_ch_ack (struct MeshTunnel3 *t,
598 const struct GNUNET_MESH_ChannelManage *msg,
601 struct MeshChannel *ch;
605 size = ntohs (msg->header.size);
606 if (size != sizeof (struct GNUNET_MESH_ChannelManage))
613 ch = GMT_get_channel (t, ntohl (msg->chid));
616 GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
618 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
623 GMCH_handle_ack (ch, msg, fwd);
627 handle_ch_destroy (struct MeshTunnel3 *t,
628 const struct GNUNET_MESH_ChannelManage *msg,
631 struct MeshChannel *ch;
635 size = ntohs (msg->header.size);
636 if (size != sizeof (struct GNUNET_MESH_ChannelManage))
643 ch = GMT_get_channel (t, ntohl (msg->chid));
646 /* Probably a retransmission, safe to ignore */
650 GMCH_handle_destroy (ch, msg, fwd);
655 * The peer's ephemeral key has changed: update the symmetrical keys.
657 * @param t Tunnel this message came on.
658 * @param msg Key eXchange message.
661 handle_kx (struct MeshTunnel3 *t,
662 const struct GNUNET_MESH_KX *msg)
669 * Peer wants to check our symmetrical keys by sending an encrypted challenge.
670 * Answer with by retransmitting the challenge with the "opposite" key.
672 * @param t Tunnel this message came on.
673 * @param msg Key eXchange Ping message.
676 handle_ping (struct MeshTunnel3 *t,
677 const struct GNUNET_MESH_KX_Ping *msg)
681 challenge = ntohl (msg->nonce);
682 send_pong (t, challenge);
687 * Peer has answer to our challenge.
688 * If answer is successful, consider the key exchange finished and clean
689 * up all related state.
691 * @param t Tunnel this message came on.
692 * @param msg Key eXchange Pong message.
695 handle_pong (struct MeshTunnel3 *t,
696 const struct GNUNET_MESH_KX_Pong *msg)
698 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
700 GNUNET_SCHEDULER_cancel (t->rekey_task);
701 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
713 * Demultiplex by message type and call appropriate handler for a message
714 * towards a channel of a local tunnel.
716 * @param t Tunnel this message came on.
717 * @param msgh Message header.
718 * @param fwd Is this message fwd?
721 handle_decrypted (struct MeshTunnel3 *t,
722 const struct GNUNET_MessageHeader *msgh,
727 type = ntohs (msgh->type);
728 LOG (GNUNET_ERROR_TYPE_DEBUG,
729 "Got a %s message!\n",
730 GNUNET_MESH_DEBUG_M2S (type));
734 case GNUNET_MESSAGE_TYPE_MESH_DATA:
735 /* Don't send hop ACK, wait for client to ACK */
736 handle_data (t, (struct GNUNET_MESH_Data *) msgh, fwd);
739 case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
740 handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh, fwd);
743 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
745 (struct GNUNET_MESH_ChannelCreate *) msgh,
749 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
751 (struct GNUNET_MESH_ChannelManage *) msgh,
755 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
756 handle_ch_destroy (t,
757 (struct GNUNET_MESH_ChannelManage *) msgh,
763 LOG (GNUNET_ERROR_TYPE_DEBUG,
764 "end-to-end message not known (%u)\n",
769 /******************************************************************************/
770 /******************************** API ***********************************/
771 /******************************************************************************/
774 * Decrypt and demultiplex by message type. Call appropriate handler
777 * @param t Tunnel this message came on.
778 * @param msg Encrypted message.
779 * @param fwd Is this message fwd?
782 GMT_handle_encrypted (struct MeshTunnel3 *t,
783 const struct GNUNET_MESH_Encrypted *msg,
786 size_t size = ntohs (msg->header.size);
787 size_t payload_size = size - sizeof (struct GNUNET_MESH_Encrypted);
788 size_t decrypted_size;
789 char cbuf [payload_size];
790 struct GNUNET_MessageHeader *msgh;
793 decrypted_size = t_decrypt (t, cbuf, &msg[1], payload_size, msg->iv);
795 while (off < decrypted_size)
797 msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
798 handle_decrypted (t, msgh, fwd);
799 off += ntohs (msgh->size);
805 * Demultiplex an encapsulated KX message by message type.
807 * @param t Tunnel on which the message came.
808 * @param message KX message itself.
811 GMT_handle_kx (struct MeshTunnel3 *t,
812 const struct GNUNET_MessageHeader *message)
816 type = ntohs (message->type);
819 case GNUNET_MESSAGE_TYPE_MESH_KX:
820 handle_kx (t, (struct GNUNET_MESH_KX *) message);
823 case GNUNET_MESSAGE_TYPE_MESH_KX_PING:
824 handle_ping (t, (struct GNUNET_MESH_KX_Ping *) message);
827 case GNUNET_MESSAGE_TYPE_MESH_KX_PONG:
828 handle_pong (t, (struct GNUNET_MESH_KX_Pong *) message);
833 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message not known (%u)\n", type);
840 * Cache a message to be sent once tunnel is online.
842 * @param t Tunnel to hold the message.
843 * @param ch Channel the message is about.
844 * @param msg Message itself (copy will be made).
845 * @param fwd Is this fwd?
848 GMT_queue_data (struct MeshTunnel3 *t,
849 struct MeshChannel *ch,
850 struct GNUNET_MessageHeader *msg,
853 struct MeshTunnelQueue *tq;
854 uint16_t size = ntohs (msg->size);
856 tq = GNUNET_malloc (sizeof (struct MeshTunnelQueue) + size);
859 memcpy (&tq[1], msg, size);
860 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tq);
862 if (MESH_TUNNEL3_READY == t->state)
863 GMT_send_queued_data (t, fwd);
868 * Send all cached messages that we can, tunnel is online.
870 * @param t Tunnel that holds the messages.
871 * @param fwd Is this fwd?
874 GMT_send_queued_data (struct MeshTunnel3 *t, int fwd)
876 struct MeshTunnelQueue *tq;
877 struct MeshTunnelQueue *next;
880 LOG (GNUNET_ERROR_TYPE_DEBUG,
881 "GMT_send_queued_data on tunnel %s\n",
883 room = GMT_get_buffer (t, fwd);
884 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
885 for (tq = t->tq_head; NULL != tq && room > 0; tq = next)
887 LOG (GNUNET_ERROR_TYPE_DEBUG, " data on channel %s\n", GMCH_2s (tq->ch));
890 GNUNET_CONTAINER_DLL_remove (t->tq_head, t->tq_tail, tq);
891 GMCH_send_prebuilt_message ((struct GNUNET_MessageHeader *) &tq[1],
896 LOG (GNUNET_ERROR_TYPE_DEBUG,
897 "GMT_send_queued_data end\n",
903 * Initialize the tunnel subsystem.
905 * @param c Configuration handle.
906 * @param key ECC private key, to derive all other keys and do crypto.
909 GMT_init (const struct GNUNET_CONFIGURATION_Handle *c,
910 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
912 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
914 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
917 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
918 "MESH", "DEFAULT_TTL", "USING DEFAULT");
922 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REKEY_PERIOD",
925 rekey_period = GNUNET_TIME_UNIT_DAYS;
928 my_private_key = key;
929 kx_msg.header.size = htons (sizeof (kx_msg));
930 kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX);
931 kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_MESH_KX);
932 kx_msg.purpose.size = htonl (sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
933 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
934 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
935 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
936 sizeof (struct GNUNET_PeerIdentity));
937 kx_msg.origin_identity = my_full_id;
938 rekey_task = GNUNET_SCHEDULER_add_now (&rekey, NULL);
940 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
945 * Shut down the tunnel subsystem.
950 if (GNUNET_SCHEDULER_NO_TASK != rekey_task)
952 GNUNET_SCHEDULER_cancel (rekey_task);
953 rekey_task = GNUNET_SCHEDULER_NO_TASK;
955 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
962 * @param destination Peer this tunnel is towards.
965 GMT_new (struct MeshPeer *destination)
967 struct MeshTunnel3 *t;
969 t = GNUNET_new (struct MeshTunnel3);
971 t->peer = destination;
973 // GNUNET_CONTAINER_multihashmap_put (tunnels, tid, t,
974 // GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
977 // tunnel_destroy (t);
981 // char salt[] = "salt";
982 // GNUNET_CRYPTO_kdf (&t->e_key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
983 // salt, sizeof (salt),
984 // &t->e_key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
985 // &my_full_id, sizeof (struct GNUNET_PeerIdentity),
986 // GNUNET_PEER_resolve2 (t->peer->id), sizeof (struct GNUNET_PeerIdentity),
988 // GNUNET_CRYPTO_kdf (&t->d_key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
989 // salt, sizeof (salt),
990 // &t->d_key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
991 // GNUNET_PEER_resolve2 (t->peer->id), sizeof (struct GNUNET_PeerIdentity),
992 // &my_full_id, sizeof (struct GNUNET_PeerIdentity),
995 GNUNET_CONTAINER_multipeermap_put (tunnels, GMP_get_id (destination), t,
996 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1002 * Change the tunnel state.
1004 * @param t Tunnel whose state to change.
1005 * @param state New state.
1008 GMT_change_state (struct MeshTunnel3* t, enum MeshTunnel3State state)
1012 LOG (GNUNET_ERROR_TYPE_DEBUG,
1013 "Tunnel %s state was %s\n",
1015 GMT_state2s (t->state));
1016 LOG (GNUNET_ERROR_TYPE_DEBUG,
1017 "Tunnel %s state is now %s\n",
1019 GMT_state2s (state));
1021 if (MESH_TUNNEL3_READY == state && 3 <= GMT_count_connections (t))
1023 GMP_stop_search (t->peer);
1029 * Add a connection to a tunnel.
1032 * @param c Connection.
1035 GMT_add_connection (struct MeshTunnel3 *t, struct MeshConnection *c)
1037 struct MeshTConnection *aux;
1039 for (aux = t->connection_head; aux != NULL; aux = aux->next)
1043 aux = GNUNET_new (struct MeshTConnection);
1045 GNUNET_CONTAINER_DLL_insert_tail (t->connection_head, t->connection_tail, aux);
1050 * Remove a connection from a tunnel.
1053 * @param c Connection.
1056 GMT_remove_connection (struct MeshTunnel3 *t, struct MeshConnection *c)
1058 struct MeshTConnection *aux;
1060 for (aux = t->connection_head; aux != NULL; aux = aux->next)
1063 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
1071 * Add a channel to a tunnel.
1074 * @param ch Channel.
1077 GMT_add_channel (struct MeshTunnel3 *t, struct MeshChannel *ch)
1079 struct MeshTChannel *aux;
1081 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
1083 for (aux = t->channel_head; aux != NULL; aux = aux->next)
1085 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
1090 aux = GNUNET_new (struct MeshTChannel);
1092 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
1093 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
1098 * Remove a channel from a tunnel.
1101 * @param ch Channel.
1104 GMT_remove_channel (struct MeshTunnel3 *t, struct MeshChannel *ch)
1106 struct MeshTChannel *aux;
1108 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
1109 for (aux = t->channel_head; aux != NULL; aux = aux->next)
1113 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GMCH_2s (ch));
1114 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
1123 * Search for a channel by global ID.
1125 * @param t Tunnel containing the channel.
1126 * @param chid Public channel number.
1128 * @return channel handler, NULL if doesn't exist
1130 struct MeshChannel *
1131 GMT_get_channel (struct MeshTunnel3 *t, MESH_ChannelNumber chid)
1133 struct MeshTChannel *iter;
1138 for (iter = t->channel_head; NULL != iter; iter = iter->next)
1140 if (GMCH_get_id (iter->ch) == chid)
1144 return NULL == iter ? NULL : iter->ch;
1149 * Tunnel is empty: destroy it.
1151 * Notifies all connections about the destruction.
1153 * @param t Tunnel to destroy.
1156 GMT_destroy_empty (struct MeshTunnel3 *t)
1158 struct MeshTConnection *iter;
1160 for (iter = t->connection_head; NULL != iter; iter = iter->next)
1162 GMC_send_destroy (iter->c);
1165 t->destroy = GNUNET_YES;
1170 * Destroy tunnel if empty (no more channels).
1172 * @param t Tunnel to destroy if empty.
1175 GMT_destroy_if_empty (struct MeshTunnel3 *t)
1177 if (1 < GMT_count_channels (t))
1180 GMT_destroy_empty (t);
1185 * Destroy the tunnel.
1187 * This function does not generate any warning traffic to clients or peers.
1190 * Cancel messages belonging to this tunnel queued to neighbors.
1191 * Free any allocated resources linked to the tunnel.
1193 * @param t The tunnel to destroy.
1196 GMT_destroy (struct MeshTunnel3 *t)
1198 struct MeshTConnection *iter;
1199 struct MeshTConnection *next;
1204 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GMP_2s (t->peer));
1206 // if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &t->id, t))
1207 // GNUNET_break (0);
1209 for (iter = t->connection_head; NULL != iter; iter = next)
1212 GMC_destroy (iter->c);
1215 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
1216 GMP_set_tunnel (t->peer, NULL);
1218 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
1219 GNUNET_SCHEDULER_cancel (t->rekey_task);
1226 * @brief Use the given path for the tunnel.
1227 * Update the next and prev hops (and RCs).
1228 * (Re)start the path refresh in case the tunnel is locally owned.
1230 * @param t Tunnel to update.
1231 * @param p Path to use.
1233 * @return Connection created.
1235 struct MeshConnection *
1236 GMT_use_path (struct MeshTunnel3 *t, struct MeshPeerPath *p)
1238 struct MeshConnection *c;
1239 struct GNUNET_HashCode cid;
1240 unsigned int own_pos;
1242 if (NULL == t || NULL == p)
1248 for (own_pos = 0; own_pos < p->length; own_pos++)
1250 if (p->peers[own_pos] == myid)
1253 if (own_pos > p->length - 1)
1259 GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE, &cid);
1260 c = GMC_new (&cid, t, p, own_pos);
1261 GMT_add_connection (t, c);
1267 * Count established (ready) connections of a tunnel.
1269 * @param t Tunnel on which to count.
1271 * @return Number of connections.
1274 GMT_count_connections (struct MeshTunnel3 *t)
1276 struct MeshTConnection *iter;
1279 for (count = 0, iter = t->connection_head;
1281 iter = iter->next, count++);
1287 * Count channels of a tunnel.
1289 * @param t Tunnel on which to count.
1291 * @return Number of channels.
1294 GMT_count_channels (struct MeshTunnel3 *t)
1296 struct MeshTChannel *iter;
1299 for (count = 0, iter = t->channel_head;
1301 iter = iter->next, count++) /* skip */;
1308 * Get the state of a tunnel.
1312 * @return Tunnel's state.
1314 enum MeshTunnel3State
1315 GMT_get_state (struct MeshTunnel3 *t)
1318 return (enum MeshTunnel3State) -1;
1323 * Get the total buffer space for a tunnel.
1325 * If terminal, use the biggest channel buffer (or 64) if no channel exists.
1326 * If not terminal, use the sum of all connection buffers.
1329 * @param fwd Is this for FWD traffic?
1331 * @return Buffer space offered by all entities (c/ch) in the tunnel.
1334 GMT_get_buffer (struct MeshTunnel3 *t, int fwd)
1336 struct MeshTConnection *iter;
1337 unsigned int buffer;
1339 iter = t->connection_head;
1342 /* If terminal, return biggest channel buffer */
1343 if (NULL == iter || GMC_is_terminal (iter->c, fwd))
1345 struct MeshTChannel *iter_ch;
1346 unsigned int ch_buf;
1348 if (NULL == t->channel_head)
1350 /* Probably getting buffer for a channel create/handshake. */
1354 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = iter_ch->next)
1356 ch_buf = GMCH_get_buffer (iter_ch->ch, fwd);
1357 if (ch_buf > buffer)
1363 /* If not terminal, return sum of connection buffers */
1364 while (NULL != iter)
1366 if (GMC_get_state (iter->c) != MESH_CONNECTION_READY)
1372 buffer += GMC_get_buffer (iter->c, fwd);
1381 * Get the tunnel's destination.
1385 * @return ID of the destination peer.
1387 const struct GNUNET_PeerIdentity *
1388 GMT_get_destination (struct MeshTunnel3 *t)
1390 return GMP_get_id (t->peer);
1395 * Get the tunnel's next free global channel ID.
1399 * @return GID of a channel free to use.
1402 GMT_get_next_chid (struct MeshTunnel3 *t)
1404 MESH_ChannelNumber chid;
1406 while (NULL != GMT_get_channel (t, t->next_chid))
1408 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
1409 t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
1411 chid = t->next_chid;
1412 t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
1419 * Send ACK on one or more channels due to buffer in connections.
1421 * @param t Channel which has some free buffer space.
1422 * @param fwd Is this for FWD traffic? (ACK goes to root)
1425 GMT_unchoke_channels (struct MeshTunnel3 *t, int fwd)
1427 struct MeshTChannel *iter;
1428 unsigned int buffer;
1429 unsigned int channels = GMT_count_channels (t);
1430 unsigned int choked_n;
1431 struct MeshChannel *choked[channels];
1433 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT_unchoke_channels on %s\n", GMT_2s (t));
1434 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
1435 if (NULL != t->channel_head)
1436 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
1444 /* Get buffer space */
1445 buffer = GMT_get_buffer (t, fwd);
1451 /* Count and remember choked channels */
1453 for (iter = t->channel_head; NULL != iter; iter = iter->next)
1455 if (GNUNET_NO == GMCH_get_allowed (iter->ch, fwd))
1457 choked[choked_n++] = iter->ch;
1461 /* Unchoke random channels */
1462 while (0 < buffer && 0 < choked_n)
1464 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1466 GMCH_allow_client (choked[r], fwd);
1469 choked[r] = choked[choked_n];
1475 * Send ACK on one or more connections due to buffer space to the client.
1477 * Iterates all connections of the tunnel and sends ACKs appropriately.
1480 * @param fwd Is this in for FWD traffic? (ACK goes dest->root)
1483 GMT_send_acks (struct MeshTunnel3 *t, int fwd)
1485 struct MeshTConnection *iter;
1488 uint32_t allow_per_connection;
1490 unsigned int buffer;
1492 LOG (GNUNET_ERROR_TYPE_DEBUG,
1493 "Tunnel send %s ACKs on %s\n",
1494 fwd ? "FWD" : "BCK", GMT_2s (t));
1501 if (NULL == t->channel_head ||
1502 GNUNET_NO == GMCH_is_origin (t->channel_head->ch, !fwd))
1508 buffer = GMT_get_buffer (t, fwd);
1510 /* Count connections, how many messages are already allowed */
1511 cs = GMT_count_connections (t);
1512 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
1514 allowed += GMC_get_allowed (iter->c, fwd);
1517 /* Make sure there is no overflow */
1518 if (allowed > buffer)
1524 /* Authorize connections to send more data */
1525 to_allow = buffer; /* - allowed; */
1527 for (iter = t->connection_head; NULL != iter && to_allow > 0; iter = iter->next)
1529 allow_per_connection = to_allow/cs;
1530 to_allow -= allow_per_connection;
1532 if (GMC_get_allowed (iter->c, fwd) > 64 / 3)
1536 GMC_allow (iter->c, buffer, fwd);
1539 GNUNET_break (to_allow == 0);
1544 * Sends an already built message on a tunnel, encrypting it and
1545 * choosing the best connection.
1547 * @param message Message to send. Function modifies it.
1548 * @param t Tunnel on which this message is transmitted.
1549 * @param ch Channel on which this message is transmitted.
1550 * @param fwd Is this a fwd message?
1553 GMT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1554 struct MeshTunnel3 *t,
1555 struct MeshChannel *ch,
1558 struct MeshConnection *c;
1559 struct GNUNET_MESH_Encrypted *msg;
1560 size_t size = ntohs (message->size);
1561 size_t encrypted_size;
1562 char *cbuf[sizeof (struct GNUNET_MESH_Encrypted) + size + 64];
1566 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GMT_2s (t));
1568 iv = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_NONCE, UINT64_MAX);
1569 msg = (struct GNUNET_MESH_Encrypted *) cbuf;
1570 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED);
1571 msg->iv = GNUNET_htonll (iv);
1572 encrypted_size = t_encrypt (t, &msg[1], message, size, iv);
1573 msg->header.size = htons (sizeof (struct GNUNET_MESH_Encrypted) + encrypted_size);
1574 c = tunnel_get_connection (t, fwd);
1577 GNUNET_break (GNUNET_YES == t->destroy);
1580 type = ntohs (message->type);
1583 case GNUNET_MESSAGE_TYPE_MESH_DATA:
1584 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
1585 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
1586 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
1587 msg->cid = *GMC_get_id (c);
1588 msg->ttl = htonl (default_ttl);
1591 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
1592 GNUNET_MESH_DEBUG_M2S (type));
1596 GMC_send_prebuilt_message (&msg->header, c, fwd);
1600 * Is the tunnel directed towards the local peer?
1604 * @return GNUNET_YES if it is loopback.
1607 GMT_is_loopback (const struct MeshTunnel3 *t)
1609 return (myid == GMP_get_short_id(t->peer));
1614 * Is the tunnel using this path already?
1619 * @return GNUNET_YES a connection uses this path.
1622 GMT_is_path_used (const struct MeshTunnel3 *t, const struct MeshPeerPath *p)
1624 struct MeshTConnection *iter;
1626 for (iter = t->connection_head; NULL != iter; iter = iter->next)
1627 if (GMC_get_path (iter->c) == p)
1635 * Get a cost of a path for a tunnel considering existing connections.
1638 * @param path Candidate path.
1640 * @return Cost of the path (path length + number of overlapping nodes)
1643 GMT_get_path_cost (const struct MeshTunnel3 *t,
1644 const struct MeshPeerPath *path)
1646 struct MeshTConnection *iter;
1647 unsigned int overlap;
1655 GNUNET_assert (NULL != t);
1657 for (i = 0; i < path->length; i++)
1659 for (iter = t->connection_head; NULL != iter; iter = iter->next)
1661 for (j = 0; j < GMC_get_path (iter->c)->length; j++)
1663 if (path->peers[i] == GMC_get_path (iter->c)->peers[j])
1671 return (path->length + overlap) * (path->score * -1);
1676 * Get the static string for the peer this tunnel is directed.
1680 * @return Static string the destination peer's ID.
1683 GMT_2s (const struct MeshTunnel3 *t)
1685 return GMP_2s (t->peer);