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 MeshTunnel3 *t;
165 struct MeshTunnel3Queue *q;
172 /* struct GNUNET_MessageHeader *msg; */
177 * Handle for messages queued but not yet sent.
179 struct MeshTunnel3Queue
182 * Connection queue handle, to cancel if necessary.
184 struct MeshConnectionQueue *q;
187 * Handle in case message hasn't been given to a connection yet.
189 struct MeshTunnelDelayed *tq;
192 * Continuation to call once sent.
197 * Closure for @c cont.
203 /******************************************************************************/
204 /******************************* GLOBALS ***********************************/
205 /******************************************************************************/
208 * Global handle to the statistics service.
210 extern struct GNUNET_STATISTICS_Handle *stats;
213 * Local peer own ID (memory efficient handle).
215 extern GNUNET_PEER_Id myid;
218 * Local peer own ID (full value).
220 extern struct GNUNET_PeerIdentity my_full_id;
224 * Set of all tunnels, in order to trigger a new exchange on rekey.
225 * Indexed by peer's ID.
227 static struct GNUNET_CONTAINER_MultiPeerMap *tunnels;
230 * Default TTL for payload packets.
232 static unsigned long long default_ttl;
237 const static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
240 * Own ephemeral private key.
242 static struct GNUNET_CRYPTO_EcdhePrivateKey *my_ephemeral_key;
245 * Cached message used to perform a key exchange.
247 static struct GNUNET_MESH_KX_Ephemeral kx_msg;
250 * Task to generate a new ephemeral key.
252 static GNUNET_SCHEDULER_TaskIdentifier rekey_task;
257 static struct GNUNET_TIME_Relative rekey_period;
259 /******************************************************************************/
260 /******************************** STATIC ***********************************/
261 /******************************************************************************/
264 * Get string description for tunnel connectivity state.
266 * @param cs Tunnel state.
268 * @return String representation.
271 cstate2s (enum MeshTunnel3CState cs)
273 static char buf[128];
277 case MESH_TUNNEL3_NEW:
278 return "MESH_TUNNEL3_NEW";
279 case MESH_TUNNEL3_SEARCHING:
280 return "MESH_TUNNEL3_SEARCHING";
281 case MESH_TUNNEL3_WAITING:
282 return "MESH_TUNNEL3_WAITING";
283 case MESH_TUNNEL3_READY:
284 return "MESH_TUNNEL3_READY";
287 sprintf (buf, "%u (UNKNOWN STATE)", cs);
295 * Get string description for tunnel encryption state.
297 * @param es Tunnel state.
299 * @return String representation.
302 estate2s (enum MeshTunnel3EState es)
304 static char buf[128];
308 case MESH_TUNNEL3_KEY_UNINITIALIZED:
309 return "MESH_TUNNEL3_KEY_UNINITIALIZED";
310 case MESH_TUNNEL3_KEY_SENT:
311 return "MESH_TUNNEL3_KEY_SENT";
312 case MESH_TUNNEL3_KEY_PING:
313 return "MESH_TUNNEL3_KEY_PING";
314 case MESH_TUNNEL3_KEY_OK:
315 return "MESH_TUNNEL3_KEY_OK";
318 sprintf (buf, "%u (UNKNOWN STATE)", es);
326 * @brief Check if tunnel is ready to send traffic.
328 * Tunnel must be connected and with encryption correctly set up.
330 * @param t Tunnel to check.
332 * @return #GNUNET_YES if ready, #GNUNET_NO otherwise
335 is_ready (struct MeshTunnel3 *t)
337 return (MESH_TUNNEL3_READY == t->cstate
338 && MESH_TUNNEL3_KEY_OK == t->estate)
339 || GMT_is_loopback (t);
344 * Ephemeral key message purpose size.
346 * @return Size of the part of the ephemeral key message that must be signed.
349 ephemeral_purpose_size (void)
351 return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
352 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
353 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
354 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
355 sizeof (struct GNUNET_PeerIdentity);
360 * Size of the encrypted part of a ping message.
362 * @return Size of the encrypted part of a ping message.
365 ping_encryption_size (void)
367 return sizeof (struct GNUNET_PeerIdentity) + sizeof (uint32_t);
372 * Get the channel's buffer. ONLY FOR NON-LOOPBACK CHANNELS!!
374 * @param tch Tunnel's channel handle.
376 * @return Amount of messages the channel can still buffer towards the client.
379 get_channel_buffer (const struct MeshTChannel *tch)
383 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
384 fwd = GMCH_is_origin (tch->ch, GNUNET_YES);
386 return GMCH_get_buffer (tch->ch, fwd);
391 * Get the channel's allowance status.
393 * @param tch Tunnel's channel handle.
395 * @return #GNUNET_YES if we allowed the client to send data to us.
398 get_channel_allowed (const struct MeshTChannel *tch)
402 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
403 fwd = GMCH_is_origin (tch->ch, GNUNET_YES);
405 return GMCH_get_allowed (tch->ch, fwd);
410 * Get the connection's buffer.
412 * @param tc Tunnel's connection handle.
414 * @return Amount of messages the connection can still buffer.
417 get_connection_buffer (const struct MeshTConnection *tc)
421 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
422 fwd = GMC_is_origin (tc->c, GNUNET_YES);
424 return GMC_get_buffer (tc->c, fwd);
429 * Get the connection's allowance.
431 * @param tc Tunnel's connection handle.
433 * @return Amount of messages we have allowed the next peer to send us.
436 get_connection_allowed (const struct MeshTConnection *tc)
440 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
441 fwd = GMC_is_origin (tc->c, GNUNET_YES);
443 return GMC_get_allowed (tc->c, fwd);
448 * Check that a ephemeral key message s well formed and correctly signed.
450 * @param t Tunnel on which the message came.
451 * @param msg The ephemeral key message.
453 * @return GNUNET_OK if message is fine, GNUNET_SYSERR otherwise.
456 check_ephemeral (struct MeshTunnel3 *t,
457 const struct GNUNET_MESH_KX_Ephemeral *msg)
459 /* Check message size */
460 if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_KX_Ephemeral))
461 return GNUNET_SYSERR;
463 /* Check signature size */
464 if (ntohl (msg->purpose.size) != ephemeral_purpose_size ())
465 return GNUNET_SYSERR;
468 if (0 != memcmp (&msg->origin_identity,
469 GMP_get_id (t->peer),
470 sizeof (struct GNUNET_PeerIdentity)))
471 return GNUNET_SYSERR;
473 /* Check signature */
475 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_MESH_KX,
478 &msg->origin_identity.public_key))
479 return GNUNET_SYSERR;
486 * Encrypt data with the tunnel key.
488 * @param t Tunnel whose key to use.
489 * @param dst Destination for the encrypted data.
490 * @param src Source of the plaintext. Can overlap with @c dst.
491 * @param size Size of the plaintext.
492 * @param iv Initialization Vector to use.
495 t_encrypt (struct MeshTunnel3 *t,
496 void *dst, const void *src,
497 size_t size, uint32_t iv)
499 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
501 GNUNET_CRYPTO_symmetric_derive_iv (&siv, &t->e_key, &iv, sizeof (uint32_t), NULL);
502 return GNUNET_CRYPTO_symmetric_encrypt (src, size, &t->e_key, &siv, dst);
507 * Decrypt data with the tunnel key.
509 * @param t Tunnel whose key to use.
510 * @param dst Destination for the plaintext.
511 * @param src Source of the encrypted data. Can overlap with @c dst.
512 * @param size Size of the encrypted data.
513 * @param iv Initialization Vector to use.
516 t_decrypt (struct MeshTunnel3 *t,
517 void *dst, const void *src,
518 size_t size, uint32_t iv)
520 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
522 GNUNET_CRYPTO_symmetric_derive_iv (&siv, &t->d_key, &iv, sizeof (uint32_t), NULL);
523 return GNUNET_CRYPTO_symmetric_decrypt (src, size, &t->d_key, &siv, dst);
528 * Create key material by doing ECDH on the local and remote ephemeral keys.
530 * @param key_material Where to store the key material.
531 * @param ephemeral_key Peer's public ephemeral key.
534 derive_key_material (struct GNUNET_HashCode *key_material,
535 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key)
538 GNUNET_CRYPTO_ecc_ecdh (my_ephemeral_key,
547 * Create a symmetic key from the identities of both ends and the key material
550 * @param key Destination for the generated key.
551 * @param sender ID of the peer that will encrypt with @c key.
552 * @param receiver ID of the peer that will decrypt with @c key.
553 * @param key_material Hash created with ECDH with the ephemeral keys.
556 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
557 const struct GNUNET_PeerIdentity *sender,
558 const struct GNUNET_PeerIdentity *receiver,
559 const struct GNUNET_HashCode *key_material)
561 const char salt[] = "MESH kx salt";
563 GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
565 key_material, sizeof (struct GNUNET_HashCode),
566 sender, sizeof (struct GNUNET_PeerIdentity),
567 receiver, sizeof (struct GNUNET_PeerIdentity),
572 * Pick a connection on which send the next data message.
574 * @param t Tunnel on which to send the message.
576 * @return The connection on which to send the next message.
578 static struct MeshConnection *
579 tunnel_get_connection (struct MeshTunnel3 *t)
581 struct MeshTConnection *iter;
582 struct MeshConnection *best;
584 unsigned int lowest_q;
586 LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GMP_2s (t->peer));
589 for (iter = t->connection_head; NULL != iter; iter = iter->next)
591 LOG (GNUNET_ERROR_TYPE_DEBUG, " connection %s: %u\n",
592 GMC_2s (iter->c), GMC_get_state (iter->c));
593 if (MESH_CONNECTION_READY == GMC_get_state (iter->c))
595 qn = GMC_get_qn (iter->c, GMC_is_origin (iter->c, GNUNET_YES));
596 LOG (GNUNET_ERROR_TYPE_DEBUG, " q_n %u, \n", qn);
604 LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GMC_2s (best));
610 * Callback called when a queued message is sent.
612 * Calculates the average time and connection packet tracking.
614 * @param cls Closure (TunnelQueue handle).
615 * @param c Connection this message was on.
616 * @param q Connection queue handle (unused).
617 * @param type Type of message sent.
618 * @param fwd Was this a FWD going message?
619 * @param size Size of the message.
622 message_sent (void *cls,
623 struct MeshConnection *c,
624 struct MeshConnectionQueue *q,
625 uint16_t type, int fwd, size_t size)
627 struct MeshTunnel3Queue *qt = cls;
629 GNUNET_assert (NULL != qt->cont);
630 qt->cont (qt->cont_cls, GMC_get_tunnel (c), qt, type, size);
636 * Delete a queued message: either was sent or the channel was destroyed
637 * before the tunnel's key exchange had a chance to finish.
639 * @param tq Queue handle.
642 unqueue_data (struct MeshTunnelDelayed *tq)
644 GNUNET_CONTAINER_DLL_remove (tq->t->tq_head, tq->t->tq_tail, tq);
650 * Cache a message to be sent once tunnel is online.
652 * @param t Tunnel to hold the message.
653 * @param msg Message itself (copy will be made).
655 static struct MeshTunnelDelayed *
656 queue_data (struct MeshTunnel3 *t, const struct GNUNET_MessageHeader *msg,
657 GMT_sent cont, void *cont_cls)
659 struct MeshTunnelDelayed *tq;
660 uint16_t size = ntohs (msg->size);
662 LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GMT_2s (t));
664 if (GNUNET_YES == is_ready (t))
670 tq = GNUNET_malloc (sizeof (struct MeshTunnelDelayed) + size);
674 tq->cont_cls = cont_cls;
675 memcpy (&tq[1], msg, size);
676 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tq);
683 * Sends an already built message on a tunnel, encrypting it and
684 * choosing the best connection.
686 * @param message Message to send. Function modifies it.
687 * @param t Tunnel on which this message is transmitted.
688 * @param force Force the tunnel to take the message (buffer overfill).
689 * @param cont Continuation to call once message is really sent.
690 * @param cont_cls Closure for @c cont.
691 * @param existing_q In case this a transmission of previously queued data,
692 * this should be TunnelQueue given to the client.
695 * @return Handle to cancel message. NULL if @c cont is NULL.
697 static struct MeshTunnel3Queue *
698 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
699 struct MeshTunnel3 *t, int force,
700 GMT_sent cont, void *cont_cls,
701 struct MeshTunnel3Queue *existing_q)
703 struct MeshTunnel3Queue *q;
704 struct MeshConnection *c;
705 struct GNUNET_MESH_Encrypted *msg;
706 size_t size = ntohs (message->size);
707 size_t encrypted_size;
708 char cbuf[sizeof (struct GNUNET_MESH_Encrypted) + size];
713 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GMT_2s (t));
715 if (GNUNET_NO == is_ready (t))
717 GNUNET_assert (NULL == existing_q);
718 q = GNUNET_new (struct MeshTunnel3Queue);
719 q->tq = queue_data (t, message, cont, cont_cls);
724 GNUNET_assert (GNUNET_NO == GMT_is_loopback (t));
726 iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
727 msg = (struct GNUNET_MESH_Encrypted *) cbuf;
728 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED);
730 encrypted_size = t_encrypt (t, &msg[1], message, size, iv);
731 msg->header.size = htons (sizeof (struct GNUNET_MESH_Encrypted)
733 c = tunnel_get_connection (t);
736 GNUNET_break (GNUNET_YES == t->destroy);
739 type = ntohs (message->type);
742 case GNUNET_MESSAGE_TYPE_MESH_DATA:
743 case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
744 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
745 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
746 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
747 msg->cid = *GMC_get_id (c);
748 msg->ttl = htonl (default_ttl);
751 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
756 fwd = GMC_is_origin (c, GNUNET_YES);
760 (void) GMC_send_prebuilt_message (&msg->header, c, fwd, force, NULL, NULL);
763 if (NULL == existing_q)
765 q = GNUNET_new (struct MeshTunnel3Queue); /* FIXME valgrind: leak*/
772 q->q = GMC_send_prebuilt_message (&msg->header, c, fwd, force,
775 q->cont_cls = cont_cls;
782 * Send all cached messages that we can, tunnel is online.
784 * @param t Tunnel that holds the messages. Cannot be loopback.
787 send_queued_data (struct MeshTunnel3 *t)
789 struct MeshTunnelDelayed *tq;
790 struct MeshTunnelDelayed *next;
793 LOG (GNUNET_ERROR_TYPE_DEBUG,
794 "GMT_send_queued_data on tunnel %s\n",
797 if (GMT_is_loopback (t))
803 if (GNUNET_NO == is_ready (t))
805 LOG (GNUNET_ERROR_TYPE_DEBUG, " not ready yet: %s/%s\n",
806 estate2s (t->estate), cstate2s (t->cstate));
810 room = GMT_get_connections_buffer (t);
811 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
812 LOG (GNUNET_ERROR_TYPE_DEBUG, " tq head: %p\n", t->tq_head);
813 for (tq = t->tq_head; NULL != tq && room > 0; tq = next)
815 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
818 send_prebuilt_message ((struct GNUNET_MessageHeader *)&tq[1],
819 tq->t, GNUNET_YES, tq->cont, tq->cont_cls, tq->q);
822 LOG (GNUNET_ERROR_TYPE_DEBUG,
823 "GMT_send_queued_data end\n",
829 * Sends key exchange message on a tunnel, choosing the best connection.
830 * Should not be called on loopback tunnels.
832 * @param t Tunnel on which this message is transmitted.
833 * @param message Message to send. Function modifies it.
836 send_kx (struct MeshTunnel3 *t,
837 const struct GNUNET_MessageHeader *message)
839 struct MeshConnection *c;
840 struct GNUNET_MESH_KX *msg;
841 size_t size = ntohs (message->size);
842 char cbuf[sizeof (struct GNUNET_MESH_KX) + size];
846 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GMT_2s (t));
848 /* Avoid loopback. */
849 if (GMT_is_loopback (t))
851 LOG (GNUNET_ERROR_TYPE_DEBUG, " loopback!\n");
856 /* Must have a connection. */
857 if (NULL == t->connection_head)
863 msg = (struct GNUNET_MESH_KX *) cbuf;
864 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX);
865 msg->header.size = htons (sizeof (struct GNUNET_MESH_KX) + size);
866 c = tunnel_get_connection (t);
869 GNUNET_break (GNUNET_YES == t->destroy);
872 type = ntohs (message->type);
875 case GNUNET_MESSAGE_TYPE_MESH_KX_EPHEMERAL:
876 case GNUNET_MESSAGE_TYPE_MESH_KX_PING:
877 case GNUNET_MESSAGE_TYPE_MESH_KX_PONG:
878 msg->reserved = htonl (0);
879 memcpy (&msg[1], message, size);
882 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
887 fwd = GMC_is_origin (t->connection_head->c, GNUNET_YES);
888 /* TODO save handle and cancel in case of a unneeded retransmission */
889 GMC_send_prebuilt_message (&msg->header, c, fwd, GNUNET_YES, NULL, NULL);
894 * Send the ephemeral key on a tunnel.
896 * @param t Tunnel on which to send the key.
899 send_ephemeral (struct MeshTunnel3 *t)
901 LOG (GNUNET_ERROR_TYPE_DEBUG, "%s()\n", __FUNCTION__);
903 kx_msg.sender_status = htonl (t->estate);
904 send_kx (t, &kx_msg.header);
908 * Send a ping message on a tunnel.
910 * @param t Tunnel on which to send the ping.
913 send_ping (struct MeshTunnel3 *t)
915 struct GNUNET_MESH_KX_Ping msg;
917 LOG (GNUNET_ERROR_TYPE_DEBUG, "%s()\n", __FUNCTION__);
918 msg.header.size = htons (sizeof (msg));
919 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX_PING);
920 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
921 msg.target = *GMP_get_id (t->peer);
922 msg.nonce = t->kx_ctx->challenge;
924 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
925 LOG (GNUNET_ERROR_TYPE_DEBUG, " towards %s\n", GNUNET_i2s (&msg.target));
926 t_encrypt (t, &msg.target, &msg.target, ping_encryption_size(), msg.iv);
927 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
928 LOG (GNUNET_ERROR_TYPE_DEBUG, " e towards %s\n", GNUNET_i2s (&msg.target));
930 send_kx (t, &msg.header);
935 * Send a pong message on a tunnel.
937 * @param t Tunnel on which to send the pong.
938 * @param challenge Value sent in the ping that we have to send back.
941 send_pong (struct MeshTunnel3 *t, uint32_t challenge)
943 struct GNUNET_MESH_KX_Pong msg;
945 LOG (GNUNET_ERROR_TYPE_DEBUG, "%s()\n", __FUNCTION__);
946 msg.header.size = htons (sizeof (msg));
947 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX_PONG);
948 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
949 msg.nonce = challenge;
950 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
951 t_encrypt (t, &msg.nonce, &msg.nonce, sizeof (msg.nonce), msg.iv);
952 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
954 send_kx (t, &msg.header);
959 * Initiate a rekey with the remote peer.
961 * @param cls Closure (tunnel).
962 * @param tc TaskContext.
965 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
967 struct MeshTunnel3 *t = cls;
969 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
971 LOG (GNUNET_ERROR_TYPE_DEBUG, "Re-key Tunnel\n");
972 if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
975 if (NULL == t->kx_ctx)
977 LOG (GNUNET_ERROR_TYPE_DEBUG, " new kx ctx\n");
978 t->kx_ctx = GNUNET_new (struct MeshTunnelKXCtx);
979 t->kx_ctx->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
981 t->kx_ctx->d_key_old = t->d_key;
986 case MESH_TUNNEL3_KEY_UNINITIALIZED:
987 t->estate = MESH_TUNNEL3_KEY_SENT;
989 case MESH_TUNNEL3_KEY_SENT:
991 case MESH_TUNNEL3_KEY_PING:
992 case MESH_TUNNEL3_KEY_OK:
994 t->estate = MESH_TUNNEL3_KEY_PING;
997 LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
1000 LOG (GNUNET_ERROR_TYPE_DEBUG, " next call in %s\n",
1001 GNUNET_STRINGS_relative_time_to_string (REKEY_WAIT, GNUNET_YES));
1002 t->rekey_task = GNUNET_SCHEDULER_add_delayed (REKEY_WAIT, &rekey_tunnel, t);
1007 * Out ephemeral key has changed, create new session key on all tunnels.
1009 * @param cls Closure (size of the hashmap).
1010 * @param key Current public key.
1011 * @param value Value in the hash map (tunnel).
1013 * @return #GNUNET_YES, so we should continue to iterate,
1016 rekey_iterator (void *cls,
1017 const struct GNUNET_PeerIdentity *key,
1020 struct MeshTunnel3 *t = value;
1021 struct GNUNET_TIME_Relative delay;
1022 long n = (long) cls;
1025 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
1028 r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
1029 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
1030 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1037 * Create a new ephemeral key and key message, schedule next rekeying.
1039 * @param cls Closure (unused).
1040 * @param tc TaskContext.
1043 rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1045 struct GNUNET_TIME_Absolute time;
1048 rekey_task = GNUNET_SCHEDULER_NO_TASK;
1050 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1053 GNUNET_free_non_null (my_ephemeral_key);
1054 my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
1056 time = GNUNET_TIME_absolute_get ();
1057 kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
1058 time = GNUNET_TIME_absolute_add (time, rekey_period);
1059 time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
1060 kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
1061 GNUNET_CRYPTO_ecdhe_key_get_public (my_ephemeral_key, &kx_msg.ephemeral_key);
1063 GNUNET_assert (GNUNET_OK ==
1064 GNUNET_CRYPTO_eddsa_sign (my_private_key,
1066 &kx_msg.signature));
1068 n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
1069 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
1071 rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period, &rekey, NULL);
1076 * Called only on shutdown, destroy every tunnel.
1078 * @param cls Closure (unused).
1079 * @param key Current public key.
1080 * @param value Value in the hash map (tunnel).
1082 * @return #GNUNET_YES, so we should continue to iterate,
1085 destroy_iterator (void *cls,
1086 const struct GNUNET_PeerIdentity *key,
1089 struct MeshTunnel3 *t = value;
1097 * Demultiplex data per channel and call appropriate channel handler.
1099 * @param t Tunnel on which the data came.
1100 * @param msg Data message.
1101 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1102 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1103 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1104 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1107 handle_data (struct MeshTunnel3 *t,
1108 const struct GNUNET_MESH_Data *msg,
1111 struct MeshChannel *ch;
1115 size = ntohs (msg->header.size);
1117 sizeof (struct GNUNET_MESH_Data) +
1118 sizeof (struct GNUNET_MessageHeader))
1123 LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
1124 GM_m2s (ntohs (msg[1].header.type)));
1127 ch = GMT_get_channel (t, ntohl (msg->chid));
1130 GNUNET_STATISTICS_update (stats, "# data on unknown channel",
1132 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1137 GMCH_handle_data (ch, msg, fwd);
1142 * Demultiplex data ACKs per channel and update appropriate channel buffer info.
1144 * @param t Tunnel on which the DATA ACK came.
1145 * @param msg DATA ACK message.
1146 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1147 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1148 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1149 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1152 handle_data_ack (struct MeshTunnel3 *t,
1153 const struct GNUNET_MESH_DataACK *msg,
1156 struct MeshChannel *ch;
1160 size = ntohs (msg->header.size);
1161 if (size != sizeof (struct GNUNET_MESH_DataACK))
1168 ch = GMT_get_channel (t, ntohl (msg->chid));
1171 GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
1173 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1178 GMCH_handle_data_ack (ch, msg, fwd);
1183 * Handle channel create.
1185 * @param t Tunnel on which the data came.
1186 * @param msg Data message.
1189 handle_ch_create (struct MeshTunnel3 *t,
1190 const struct GNUNET_MESH_ChannelCreate *msg)
1192 struct MeshChannel *ch;
1196 size = ntohs (msg->header.size);
1197 if (size != sizeof (struct GNUNET_MESH_ChannelCreate))
1204 ch = GMT_get_channel (t, ntohl (msg->chid));
1205 if (NULL != ch && ! GMT_is_loopback (t))
1207 /* Probably a retransmission, safe to ignore */
1208 LOG (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
1212 ch = GMCH_handle_create (t, msg);
1215 GMT_add_channel (t, ch);
1221 * Handle channel NACK: check correctness and call channel handler for NACKs.
1223 * @param t Tunnel on which the NACK came.
1224 * @param msg NACK message.
1227 handle_ch_nack (struct MeshTunnel3 *t,
1228 const struct GNUNET_MESH_ChannelManage *msg)
1230 struct MeshChannel *ch;
1234 size = ntohs (msg->header.size);
1235 if (size != sizeof (struct GNUNET_MESH_ChannelManage))
1242 ch = GMT_get_channel (t, ntohl (msg->chid));
1245 GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
1247 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1252 GMCH_handle_nack (ch);
1257 * Handle a CHANNEL ACK (SYNACK/ACK).
1259 * @param t Tunnel on which the CHANNEL ACK came.
1260 * @param msg CHANNEL ACK message.
1261 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1262 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1263 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1264 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1267 handle_ch_ack (struct MeshTunnel3 *t,
1268 const struct GNUNET_MESH_ChannelManage *msg,
1271 struct MeshChannel *ch;
1275 size = ntohs (msg->header.size);
1276 if (size != sizeof (struct GNUNET_MESH_ChannelManage))
1283 ch = GMT_get_channel (t, ntohl (msg->chid));
1286 GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
1288 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1293 GMCH_handle_ack (ch, msg, fwd);
1299 * Handle a channel destruction message.
1301 * @param t Tunnel on which the message came.
1302 * @param msg Channel destroy message.
1303 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1304 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1305 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1306 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1309 handle_ch_destroy (struct MeshTunnel3 *t,
1310 const struct GNUNET_MESH_ChannelManage *msg,
1313 struct MeshChannel *ch;
1317 size = ntohs (msg->header.size);
1318 if (size != sizeof (struct GNUNET_MESH_ChannelManage))
1325 ch = GMT_get_channel (t, ntohl (msg->chid));
1328 /* Probably a retransmission, safe to ignore */
1332 GMCH_handle_destroy (ch, msg, fwd);
1337 * The peer's ephemeral key has changed: update the symmetrical keys.
1339 * @param t Tunnel this message came on.
1340 * @param msg Key eXchange message.
1343 handle_ephemeral (struct MeshTunnel3 *t,
1344 const struct GNUNET_MESH_KX_Ephemeral *msg)
1346 struct GNUNET_HashCode km;
1347 LOG (GNUNET_ERROR_TYPE_DEBUG, " ephemeral key message\n");
1349 if (GNUNET_OK != check_ephemeral (t, msg))
1351 GNUNET_break_op (0);
1354 derive_key_material (&km, &msg->ephemeral_key);
1355 LOG (GNUNET_ERROR_TYPE_DEBUG, " km is %s\n", GNUNET_h2s (&km));
1356 derive_symmertic (&t->e_key, &my_full_id, GMP_get_id (t->peer), &km);
1357 derive_symmertic (&t->d_key, GMP_get_id (t->peer), &my_full_id, &km);
1358 if (MESH_TUNNEL3_KEY_SENT == t->estate)
1360 LOG (GNUNET_ERROR_TYPE_DEBUG, " our key was sent, send ping\n");
1362 t->estate = MESH_TUNNEL3_KEY_PING;
1368 * Peer wants to check our symmetrical keys by sending an encrypted challenge.
1369 * Answer with by retransmitting the challenge with the "opposite" key.
1371 * @param t Tunnel this message came on.
1372 * @param msg Key eXchange Ping message.
1375 handle_ping (struct MeshTunnel3 *t,
1376 const struct GNUNET_MESH_KX_Ping *msg)
1378 struct GNUNET_MESH_KX_Ping res;
1380 if (ntohs (msg->header.size) != sizeof (res))
1382 GNUNET_break_op (0);
1386 LOG (GNUNET_ERROR_TYPE_DEBUG, " ping message\n");
1387 t_decrypt (t, &res.target, &msg->target, ping_encryption_size (), msg->iv);
1388 if (0 != memcmp (&my_full_id, &res.target, sizeof (my_full_id)))
1390 GNUNET_break_op (0);
1391 LOG (GNUNET_ERROR_TYPE_DEBUG, " e got %u\n", msg->nonce);
1392 LOG (GNUNET_ERROR_TYPE_DEBUG, " e towards %s\n", GNUNET_i2s (&msg->target));
1393 LOG (GNUNET_ERROR_TYPE_DEBUG, " got %u\n", res.nonce);
1394 LOG (GNUNET_ERROR_TYPE_DEBUG, " towards %s\n", GNUNET_i2s (&res.target));
1398 send_pong (t, res.nonce);
1403 * Peer has answer to our challenge.
1404 * If answer is successful, consider the key exchange finished and clean
1405 * up all related state.
1407 * @param t Tunnel this message came on.
1408 * @param msg Key eXchange Pong message.
1411 handle_pong (struct MeshTunnel3 *t,
1412 const struct GNUNET_MESH_KX_Pong *msg)
1416 LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG received\n");
1417 if (GNUNET_SCHEDULER_NO_TASK == t->rekey_task)
1419 GNUNET_break_op (0);
1422 t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
1424 if (challenge != t->kx_ctx->challenge)
1426 LOG (GNUNET_ERROR_TYPE_DEBUG,
1427 "Wrong PONG challenge: %u (e: %u). Expected: %u.\n",
1428 challenge, msg->nonce, t->kx_ctx->challenge);
1429 GNUNET_break_op (0);
1432 GNUNET_SCHEDULER_cancel (t->rekey_task);
1433 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1434 GNUNET_free (t->kx_ctx);
1436 GMT_change_estate (t, MESH_TUNNEL3_KEY_OK);
1441 * Demultiplex by message type and call appropriate handler for a message
1442 * towards a channel of a local tunnel.
1444 * @param t Tunnel this message came on.
1445 * @param msgh Message header.
1446 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1447 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1448 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1449 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1452 handle_decrypted (struct MeshTunnel3 *t,
1453 const struct GNUNET_MessageHeader *msgh,
1458 type = ntohs (msgh->type);
1459 LOG (GNUNET_ERROR_TYPE_DEBUG,
1460 "Got a %s message!\n",
1465 case GNUNET_MESSAGE_TYPE_MESH_DATA:
1466 /* Don't send hop ACK, wait for client to ACK */
1467 handle_data (t, (struct GNUNET_MESH_Data *) msgh, fwd);
1470 case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
1471 handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh, fwd);
1474 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
1475 handle_ch_create (t,
1476 (struct GNUNET_MESH_ChannelCreate *) msgh);
1479 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_NACK:
1481 (struct GNUNET_MESH_ChannelManage *) msgh);
1484 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
1486 (struct GNUNET_MESH_ChannelManage *) msgh,
1490 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
1491 handle_ch_destroy (t,
1492 (struct GNUNET_MESH_ChannelManage *) msgh,
1497 GNUNET_break_op (0);
1498 LOG (GNUNET_ERROR_TYPE_DEBUG,
1499 "end-to-end message not known (%u)\n",
1500 ntohs (msgh->type));
1504 /******************************************************************************/
1505 /******************************** API ***********************************/
1506 /******************************************************************************/
1509 * Decrypt and demultiplex by message type. Call appropriate handler
1510 * for every message.
1512 * @param t Tunnel this message came on.
1513 * @param msg Encrypted message.
1516 GMT_handle_encrypted (struct MeshTunnel3 *t,
1517 const struct GNUNET_MESH_Encrypted *msg)
1519 size_t size = ntohs (msg->header.size);
1520 size_t payload_size = size - sizeof (struct GNUNET_MESH_Encrypted);
1521 size_t decrypted_size;
1522 char cbuf [payload_size];
1523 struct GNUNET_MessageHeader *msgh;
1526 decrypted_size = t_decrypt (t, cbuf, &msg[1], payload_size, msg->iv);
1528 while (off < decrypted_size)
1530 msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
1531 handle_decrypted (t, msgh, GNUNET_SYSERR);
1532 off += ntohs (msgh->size);
1538 * Demultiplex an encapsulated KX message by message type.
1540 * @param t Tunnel on which the message came.
1541 * @param message Payload of KX message.
1544 GMT_handle_kx (struct MeshTunnel3 *t,
1545 const struct GNUNET_MessageHeader *message)
1549 type = ntohs (message->type);
1550 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received\n", type);
1553 case GNUNET_MESSAGE_TYPE_MESH_KX_EPHEMERAL:
1554 handle_ephemeral (t, (struct GNUNET_MESH_KX_Ephemeral *) message);
1557 case GNUNET_MESSAGE_TYPE_MESH_KX_PING:
1558 handle_ping (t, (struct GNUNET_MESH_KX_Ping *) message);
1561 case GNUNET_MESSAGE_TYPE_MESH_KX_PONG:
1562 handle_pong (t, (struct GNUNET_MESH_KX_Pong *) message);
1566 GNUNET_break_op (0);
1567 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message not known (%u)\n", type);
1573 * Initialize the tunnel subsystem.
1575 * @param c Configuration handle.
1576 * @param key ECC private key, to derive all other keys and do crypto.
1579 GMT_init (const struct GNUNET_CONFIGURATION_Handle *c,
1580 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
1582 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
1584 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
1587 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1588 "MESH", "DEFAULT_TTL", "USING DEFAULT");
1592 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REKEY_PERIOD",
1595 rekey_period = GNUNET_TIME_UNIT_DAYS;
1598 my_private_key = key;
1599 kx_msg.header.size = htons (sizeof (kx_msg));
1600 kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX_EPHEMERAL);
1601 kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_MESH_KX);
1602 kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
1603 kx_msg.origin_identity = my_full_id;
1604 rekey_task = GNUNET_SCHEDULER_add_now (&rekey, NULL);
1606 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
1611 * Shut down the tunnel subsystem.
1616 if (GNUNET_SCHEDULER_NO_TASK != rekey_task)
1618 GNUNET_SCHEDULER_cancel (rekey_task);
1619 rekey_task = GNUNET_SCHEDULER_NO_TASK;
1621 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
1622 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
1629 * @param destination Peer this tunnel is towards.
1631 struct MeshTunnel3 *
1632 GMT_new (struct MeshPeer *destination)
1634 struct MeshTunnel3 *t;
1636 t = GNUNET_new (struct MeshTunnel3);
1638 t->peer = destination;
1641 GNUNET_CONTAINER_multipeermap_put (tunnels, GMP_get_id (destination), t,
1642 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
1653 * Change the tunnel's connection state.
1655 * @param t Tunnel whose connection state to change.
1656 * @param cstate New connection state.
1659 GMT_change_cstate (struct MeshTunnel3* t, enum MeshTunnel3CState cstate)
1663 LOG (GNUNET_ERROR_TYPE_DEBUG,
1664 "Tunnel %s cstate was %s\n",
1665 GMP_2s (t->peer), cstate2s (t->cstate));
1666 LOG (GNUNET_ERROR_TYPE_DEBUG,
1667 "Tunnel %s cstate is now %s\n",
1668 GMP_2s (t->peer), cstate2s (cstate));
1669 if (myid != GMP_get_short_id (t->peer) &&
1670 MESH_TUNNEL3_READY != t->cstate &&
1671 MESH_TUNNEL3_READY == cstate)
1674 if (MESH_TUNNEL3_KEY_OK == t->estate)
1676 LOG (GNUNET_ERROR_TYPE_DEBUG, " triggered send queued data\n");
1677 send_queued_data (t);
1679 else if (MESH_TUNNEL3_KEY_UNINITIALIZED == t->estate)
1681 LOG (GNUNET_ERROR_TYPE_DEBUG, " triggered rekey\n");
1682 rekey_tunnel (t, NULL);
1687 if (MESH_TUNNEL3_READY == cstate && 3 <= GMT_count_connections (t))
1689 GMP_stop_search (t->peer);
1694 * Change the tunnel encryption state.
1696 * @param t Tunnel whose encryption state to change.
1697 * @param state New encryption state.
1700 GMT_change_estate (struct MeshTunnel3* t, enum MeshTunnel3EState state)
1704 LOG (GNUNET_ERROR_TYPE_DEBUG,
1705 "Tunnel %s estate was %s\n",
1706 GMP_2s (t->peer), estate2s (t->estate));
1707 LOG (GNUNET_ERROR_TYPE_DEBUG,
1708 "Tunnel %s estate is now %s\n",
1709 GMP_2s (t->peer), estate2s (state));
1710 if (myid != GMP_get_short_id (t->peer) &&
1711 MESH_TUNNEL3_KEY_OK != t->estate && MESH_TUNNEL3_KEY_OK == state)
1714 send_queued_data (t);
1722 * Add a connection to a tunnel.
1725 * @param c Connection.
1728 GMT_add_connection (struct MeshTunnel3 *t, struct MeshConnection *c)
1730 struct MeshTConnection *aux;
1732 GNUNET_assert (NULL != c);
1734 for (aux = t->connection_head; aux != NULL; aux = aux->next)
1738 aux = GNUNET_new (struct MeshTConnection);
1740 GNUNET_CONTAINER_DLL_insert_tail (t->connection_head, t->connection_tail, aux);
1745 * Remove a connection from a tunnel.
1748 * @param c Connection.
1751 GMT_remove_connection (struct MeshTunnel3 *t, struct MeshConnection *c)
1753 struct MeshTConnection *aux;
1755 for (aux = t->connection_head; aux != NULL; aux = aux->next)
1758 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
1766 * Add a channel to a tunnel.
1769 * @param ch Channel.
1772 GMT_add_channel (struct MeshTunnel3 *t, struct MeshChannel *ch)
1774 struct MeshTChannel *aux;
1776 GNUNET_assert (NULL != ch);
1778 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
1780 for (aux = t->channel_head; aux != NULL; aux = aux->next)
1782 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
1787 aux = GNUNET_new (struct MeshTChannel);
1789 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
1790 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
1792 if (GNUNET_YES == t->destroy)
1794 t->destroy = GNUNET_NO;
1795 LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
1801 * Remove a channel from a tunnel.
1804 * @param ch Channel.
1807 GMT_remove_channel (struct MeshTunnel3 *t, struct MeshChannel *ch)
1809 struct MeshTChannel *aux;
1811 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
1812 for (aux = t->channel_head; aux != NULL; aux = aux->next)
1816 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GMCH_2s (ch));
1817 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
1826 * Search for a channel by global ID.
1828 * @param t Tunnel containing the channel.
1829 * @param chid Public channel number.
1831 * @return channel handler, NULL if doesn't exist
1833 struct MeshChannel *
1834 GMT_get_channel (struct MeshTunnel3 *t, MESH_ChannelNumber chid)
1836 struct MeshTChannel *iter;
1841 for (iter = t->channel_head; NULL != iter; iter = iter->next)
1843 if (GMCH_get_id (iter->ch) == chid)
1847 return NULL == iter ? NULL : iter->ch;
1852 * Tunnel is empty: destroy it.
1854 * Notifies all connections about the destruction.
1856 * @param t Tunnel to destroy.
1859 GMT_destroy_empty (struct MeshTunnel3 *t)
1861 struct MeshTConnection *iter;
1863 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel empty: destroying scheduled\n");
1864 for (iter = t->connection_head; NULL != iter; iter = iter->next)
1866 GMC_send_destroy (iter->c);
1869 t->cstate = MESH_TUNNEL3_NEW;
1870 t->destroy = GNUNET_YES;
1875 * Destroy tunnel if empty (no more channels).
1877 * @param t Tunnel to destroy if empty.
1880 GMT_destroy_if_empty (struct MeshTunnel3 *t)
1882 if (1 < GMT_count_channels (t))
1885 GMT_destroy_empty (t);
1890 * Destroy the tunnel.
1892 * This function does not generate any warning traffic to clients or peers.
1895 * Cancel messages belonging to this tunnel queued to neighbors.
1896 * Free any allocated resources linked to the tunnel.
1898 * @param t The tunnel to destroy.
1901 GMT_destroy (struct MeshTunnel3 *t)
1903 struct MeshTConnection *iter_c;
1904 struct MeshTConnection *next_c;
1905 struct MeshTChannel *iter_ch;
1906 struct MeshTChannel *next_ch;
1911 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GMP_2s (t->peer));
1913 GNUNET_break (GNUNET_YES ==
1914 GNUNET_CONTAINER_multipeermap_remove (tunnels,
1915 GMP_get_id (t->peer), t));
1917 for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
1919 next_c = iter_c->next;
1920 GMC_destroy (iter_c->c);
1922 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
1924 next_ch = iter_ch->next;
1925 GMCH_destroy (iter_ch->ch);
1926 /* Should only happen on shutdown, but it's ok. */
1929 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
1930 GMP_set_tunnel (t->peer, NULL);
1932 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
1933 GNUNET_SCHEDULER_cancel (t->rekey_task);
1940 * @brief Use the given path for the tunnel.
1941 * Update the next and prev hops (and RCs).
1942 * (Re)start the path refresh in case the tunnel is locally owned.
1944 * @param t Tunnel to update.
1945 * @param p Path to use.
1947 * @return Connection created.
1949 struct MeshConnection *
1950 GMT_use_path (struct MeshTunnel3 *t, struct MeshPeerPath *p)
1952 struct MeshConnection *c;
1953 struct GNUNET_HashCode cid;
1954 unsigned int own_pos;
1956 if (NULL == t || NULL == p)
1962 for (own_pos = 0; own_pos < p->length; own_pos++)
1964 if (p->peers[own_pos] == myid)
1967 if (own_pos > p->length - 1)
1973 GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE, &cid);
1974 c = GMC_new (&cid, t, p, own_pos);
1977 /* Path was flawed */
1980 GMT_add_connection (t, c);
1986 * Count established (ready) connections of a tunnel.
1988 * @param t Tunnel on which to count.
1990 * @return Number of connections.
1993 GMT_count_connections (struct MeshTunnel3 *t)
1995 struct MeshTConnection *iter;
1998 for (count = 0, iter = t->connection_head;
2000 iter = iter->next, count++);
2006 * Count channels of a tunnel.
2008 * @param t Tunnel on which to count.
2010 * @return Number of channels.
2013 GMT_count_channels (struct MeshTunnel3 *t)
2015 struct MeshTChannel *iter;
2018 for (count = 0, iter = t->channel_head;
2020 iter = iter->next, count++) /* skip */;
2027 * Get the connectivity state of a tunnel.
2031 * @return Tunnel's connectivity state.
2033 enum MeshTunnel3CState
2034 GMT_get_cstate (struct MeshTunnel3 *t)
2039 return (enum MeshTunnel3CState) -1;
2046 * Get the maximum buffer space for a tunnel towards a local client.
2050 * @return Biggest buffer space offered by any channel in the tunnel.
2053 GMT_get_channels_buffer (struct MeshTunnel3 *t)
2055 struct MeshTChannel *iter;
2056 unsigned int buffer;
2057 unsigned int ch_buf;
2059 if (NULL == t->channel_head)
2061 /* Probably getting buffer for a channel create/handshake. */
2066 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2068 ch_buf = get_channel_buffer (iter);
2069 if (ch_buf > buffer)
2077 * Get the total buffer space for a tunnel for P2P traffic.
2081 * @return Buffer space offered by all connections in the tunnel.
2084 GMT_get_connections_buffer (struct MeshTunnel3 *t)
2086 struct MeshTConnection *iter;
2087 unsigned int buffer;
2090 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2092 if (GMC_get_state (iter->c) != MESH_CONNECTION_READY)
2096 buffer += get_connection_buffer (iter);
2104 * Get the tunnel's destination.
2108 * @return ID of the destination peer.
2110 const struct GNUNET_PeerIdentity *
2111 GMT_get_destination (struct MeshTunnel3 *t)
2113 return GMP_get_id (t->peer);
2118 * Get the tunnel's next free global channel ID.
2122 * @return GID of a channel free to use.
2125 GMT_get_next_chid (struct MeshTunnel3 *t)
2127 MESH_ChannelNumber chid;
2128 MESH_ChannelNumber mask;
2131 /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
2132 * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
2133 * If peer's ID is bigger, start at 0x4... bit 30 = 1
2135 result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GMP_get_id (t->peer));
2141 while (NULL != GMT_get_channel (t, t->next_chid))
2143 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
2144 t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
2145 t->next_chid |= mask;
2147 chid = t->next_chid;
2148 t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
2149 t->next_chid |= mask;
2156 * Send ACK on one or more channels due to buffer in connections.
2158 * @param t Channel which has some free buffer space.
2161 GMT_unchoke_channels (struct MeshTunnel3 *t)
2163 struct MeshTChannel *iter;
2164 unsigned int buffer;
2165 unsigned int channels = GMT_count_channels (t);
2166 unsigned int choked_n;
2167 struct MeshChannel *choked[channels];
2169 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT_unchoke_channels on %s\n", GMT_2s (t));
2170 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
2171 if (NULL != t->channel_head)
2172 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
2174 /* Get buffer space */
2175 buffer = GMT_get_connections_buffer (t);
2181 /* Count and remember choked channels */
2183 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2185 if (GNUNET_NO == get_channel_allowed (iter))
2187 choked[choked_n++] = iter->ch;
2191 /* Unchoke random channels */
2192 while (0 < buffer && 0 < choked_n)
2194 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2196 GMCH_allow_client (choked[r], GMCH_is_origin (choked[r], GNUNET_YES));
2199 choked[r] = choked[choked_n];
2205 * Send ACK on one or more connections due to buffer space to the client.
2207 * Iterates all connections of the tunnel and sends ACKs appropriately.
2212 GMT_send_connection_acks (struct MeshTunnel3 *t)
2214 struct MeshTConnection *iter;
2217 uint32_t allow_per_connection;
2219 unsigned int buffer;
2221 LOG (GNUNET_ERROR_TYPE_DEBUG,
2222 "Tunnel send connection ACKs on %s\n",
2231 buffer = GMT_get_channels_buffer (t);
2233 /* Count connections, how many messages are already allowed */
2234 cs = GMT_count_connections (t);
2235 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2237 allowed += get_connection_allowed (iter);
2240 /* Make sure there is no overflow */
2241 if (allowed > buffer)
2246 /* Authorize connections to send more data */
2247 to_allow = buffer; /* - allowed; */
2249 for (iter = t->connection_head; NULL != iter && to_allow > 0; iter = iter->next)
2251 allow_per_connection = to_allow/cs;
2252 to_allow -= allow_per_connection;
2254 if (get_connection_allowed (iter) > 64 / 3)
2258 GMC_allow (iter->c, buffer, GMC_is_origin (iter->c, GNUNET_YES));
2261 GNUNET_break (to_allow == 0);
2266 * Cancel a previously sent message while it's in the queue.
2268 * ONLY can be called before the continuation given to the send function
2269 * is called. Once the continuation is called, the message is no longer in the
2272 * @param q Handle to the queue.
2275 GMT_cancel (struct MeshTunnel3Queue *q)
2280 /* message_sent() will be called and free q */
2282 else if (NULL != q->tq)
2284 unqueue_data (q->tq);
2294 * Sends an already built message on a tunnel, encrypting it and
2295 * choosing the best connection.
2297 * @param message Message to send. Function modifies it.
2298 * @param t Tunnel on which this message is transmitted.
2299 * @param force Force the tunnel to take the message (buffer overfill).
2300 * @param cont Continuation to call once message is really sent.
2301 * @param cont_cls Closure for @c cont.
2303 * @return Handle to cancel message. NULL if @c cont is NULL.
2305 struct MeshTunnel3Queue *
2306 GMT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
2307 struct MeshTunnel3 *t, int force,
2308 GMT_sent cont, void *cont_cls)
2310 return send_prebuilt_message (message, t, force, cont, cont_cls, NULL);
2315 * Is the tunnel directed towards the local peer?
2319 * @return #GNUNET_YES if it is loopback.
2322 GMT_is_loopback (const struct MeshTunnel3 *t)
2324 return (myid == GMP_get_short_id (t->peer));
2329 * Is the tunnel this path already?
2334 * @return #GNUNET_YES a connection uses this path.
2337 GMT_is_path_used (const struct MeshTunnel3 *t, const struct MeshPeerPath *p)
2339 struct MeshTConnection *iter;
2341 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2342 if (GMC_get_path (iter->c) == p)
2350 * Get a cost of a path for a tunnel considering existing connections.
2353 * @param path Candidate path.
2355 * @return Cost of the path (path length + number of overlapping nodes)
2358 GMT_get_path_cost (const struct MeshTunnel3 *t,
2359 const struct MeshPeerPath *path)
2361 struct MeshTConnection *iter;
2362 const struct MeshPeerPath *aux;
2363 unsigned int overlap;
2371 GNUNET_assert (NULL != t);
2373 for (i = 0; i < path->length; i++)
2375 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2377 aux = GMC_get_path (iter->c);
2381 for (j = 0; j < aux->length; j++)
2383 if (path->peers[i] == aux->peers[j])
2391 return (path->length + overlap) * (path->score * -1);
2396 * Get the static string for the peer this tunnel is directed.
2400 * @return Static string the destination peer's ID.
2403 GMT_2s (const struct MeshTunnel3 *t)
2408 return GMP_2s (t->peer);