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;
166 * Tunnel queue given to the channel to cancel request. Update on send_queued.
168 struct MeshTunnel3Queue *tq;
173 /* struct GNUNET_MessageHeader *msg; */
178 * Handle for messages queued but not yet sent.
180 struct MeshTunnel3Queue
183 * Connection queue handle, to cancel if necessary.
185 struct MeshConnectionQueue *cq;
188 * Handle in case message hasn't been given to a connection yet.
190 struct MeshTunnelDelayed *tqd;
193 * Continuation to call once sent.
198 * Closure for @c cont.
204 /******************************************************************************/
205 /******************************* GLOBALS ***********************************/
206 /******************************************************************************/
209 * Global handle to the statistics service.
211 extern struct GNUNET_STATISTICS_Handle *stats;
214 * Local peer own ID (memory efficient handle).
216 extern GNUNET_PEER_Id myid;
219 * Local peer own ID (full value).
221 extern struct GNUNET_PeerIdentity my_full_id;
225 * Set of all tunnels, in order to trigger a new exchange on rekey.
226 * Indexed by peer's ID.
228 static struct GNUNET_CONTAINER_MultiPeerMap *tunnels;
231 * Default TTL for payload packets.
233 static unsigned long long default_ttl;
238 const static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
241 * Own ephemeral private key.
243 static struct GNUNET_CRYPTO_EcdhePrivateKey *my_ephemeral_key;
246 * Cached message used to perform a key exchange.
248 static struct GNUNET_MESH_KX_Ephemeral kx_msg;
251 * Task to generate a new ephemeral key.
253 static GNUNET_SCHEDULER_TaskIdentifier rekey_task;
258 static struct GNUNET_TIME_Relative rekey_period;
260 /******************************************************************************/
261 /******************************** STATIC ***********************************/
262 /******************************************************************************/
265 * Get string description for tunnel connectivity state.
267 * @param cs Tunnel state.
269 * @return String representation.
272 cstate2s (enum MeshTunnel3CState cs)
274 static char buf[128];
278 case MESH_TUNNEL3_NEW:
279 return "MESH_TUNNEL3_NEW";
280 case MESH_TUNNEL3_SEARCHING:
281 return "MESH_TUNNEL3_SEARCHING";
282 case MESH_TUNNEL3_WAITING:
283 return "MESH_TUNNEL3_WAITING";
284 case MESH_TUNNEL3_READY:
285 return "MESH_TUNNEL3_READY";
288 sprintf (buf, "%u (UNKNOWN STATE)", cs);
296 * Get string description for tunnel encryption state.
298 * @param es Tunnel state.
300 * @return String representation.
303 estate2s (enum MeshTunnel3EState es)
305 static char buf[128];
309 case MESH_TUNNEL3_KEY_UNINITIALIZED:
310 return "MESH_TUNNEL3_KEY_UNINITIALIZED";
311 case MESH_TUNNEL3_KEY_SENT:
312 return "MESH_TUNNEL3_KEY_SENT";
313 case MESH_TUNNEL3_KEY_PING:
314 return "MESH_TUNNEL3_KEY_PING";
315 case MESH_TUNNEL3_KEY_OK:
316 return "MESH_TUNNEL3_KEY_OK";
319 sprintf (buf, "%u (UNKNOWN STATE)", es);
327 * @brief Check if tunnel is ready to send traffic.
329 * Tunnel must be connected and with encryption correctly set up.
331 * @param t Tunnel to check.
333 * @return #GNUNET_YES if ready, #GNUNET_NO otherwise
336 is_ready (struct MeshTunnel3 *t)
338 return (MESH_TUNNEL3_READY == t->cstate
339 && MESH_TUNNEL3_KEY_OK == t->estate)
340 || GMT_is_loopback (t);
345 * Ephemeral key message purpose size.
347 * @return Size of the part of the ephemeral key message that must be signed.
350 ephemeral_purpose_size (void)
352 return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
353 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
354 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
355 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
356 sizeof (struct GNUNET_PeerIdentity);
361 * Size of the encrypted part of a ping message.
363 * @return Size of the encrypted part of a ping message.
366 ping_encryption_size (void)
368 return sizeof (struct GNUNET_PeerIdentity) + sizeof (uint32_t);
373 * Get the channel's buffer. ONLY FOR NON-LOOPBACK CHANNELS!!
375 * @param tch Tunnel's channel handle.
377 * @return Amount of messages the channel can still buffer towards the client.
380 get_channel_buffer (const struct MeshTChannel *tch)
384 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
385 fwd = GMCH_is_origin (tch->ch, GNUNET_YES);
387 return GMCH_get_buffer (tch->ch, fwd);
392 * Get the channel's allowance status.
394 * @param tch Tunnel's channel handle.
396 * @return #GNUNET_YES if we allowed the client to send data to us.
399 get_channel_allowed (const struct MeshTChannel *tch)
403 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
404 fwd = GMCH_is_origin (tch->ch, GNUNET_YES);
406 return GMCH_get_allowed (tch->ch, fwd);
411 * Get the connection's buffer.
413 * @param tc Tunnel's connection handle.
415 * @return Amount of messages the connection can still buffer.
418 get_connection_buffer (const struct MeshTConnection *tc)
422 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
423 fwd = GMC_is_origin (tc->c, GNUNET_YES);
425 return GMC_get_buffer (tc->c, fwd);
430 * Get the connection's allowance.
432 * @param tc Tunnel's connection handle.
434 * @return Amount of messages we have allowed the next peer to send us.
437 get_connection_allowed (const struct MeshTConnection *tc)
441 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
442 fwd = GMC_is_origin (tc->c, GNUNET_YES);
444 return GMC_get_allowed (tc->c, fwd);
449 * Check that a ephemeral key message s well formed and correctly signed.
451 * @param t Tunnel on which the message came.
452 * @param msg The ephemeral key message.
454 * @return GNUNET_OK if message is fine, GNUNET_SYSERR otherwise.
457 check_ephemeral (struct MeshTunnel3 *t,
458 const struct GNUNET_MESH_KX_Ephemeral *msg)
460 /* Check message size */
461 if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_KX_Ephemeral))
462 return GNUNET_SYSERR;
464 /* Check signature size */
465 if (ntohl (msg->purpose.size) != ephemeral_purpose_size ())
466 return GNUNET_SYSERR;
469 if (0 != memcmp (&msg->origin_identity,
470 GMP_get_id (t->peer),
471 sizeof (struct GNUNET_PeerIdentity)))
472 return GNUNET_SYSERR;
474 /* Check signature */
476 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_MESH_KX,
479 &msg->origin_identity.public_key))
480 return GNUNET_SYSERR;
487 * Encrypt data with the tunnel key.
489 * @param t Tunnel whose key to use.
490 * @param dst Destination for the encrypted data.
491 * @param src Source of the plaintext. Can overlap with @c dst.
492 * @param size Size of the plaintext.
493 * @param iv Initialization Vector to use.
496 t_encrypt (struct MeshTunnel3 *t,
497 void *dst, const void *src,
498 size_t size, uint32_t iv)
500 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
502 GNUNET_CRYPTO_symmetric_derive_iv (&siv, &t->e_key, &iv, sizeof (uint32_t), NULL);
503 return GNUNET_CRYPTO_symmetric_encrypt (src, size, &t->e_key, &siv, dst);
508 * Decrypt data with the tunnel key.
510 * @param t Tunnel whose key to use.
511 * @param dst Destination for the plaintext.
512 * @param src Source of the encrypted data. Can overlap with @c dst.
513 * @param size Size of the encrypted data.
514 * @param iv Initialization Vector to use.
517 t_decrypt (struct MeshTunnel3 *t,
518 void *dst, const void *src,
519 size_t size, uint32_t iv)
521 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
523 GNUNET_CRYPTO_symmetric_derive_iv (&siv, &t->d_key, &iv, sizeof (uint32_t), NULL);
524 return GNUNET_CRYPTO_symmetric_decrypt (src, size, &t->d_key, &siv, dst);
529 * Create key material by doing ECDH on the local and remote ephemeral keys.
531 * @param key_material Where to store the key material.
532 * @param ephemeral_key Peer's public ephemeral key.
535 derive_key_material (struct GNUNET_HashCode *key_material,
536 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key)
539 GNUNET_CRYPTO_ecc_ecdh (my_ephemeral_key,
548 * Create a symmetic key from the identities of both ends and the key material
551 * @param key Destination for the generated key.
552 * @param sender ID of the peer that will encrypt with @c key.
553 * @param receiver ID of the peer that will decrypt with @c key.
554 * @param key_material Hash created with ECDH with the ephemeral keys.
557 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
558 const struct GNUNET_PeerIdentity *sender,
559 const struct GNUNET_PeerIdentity *receiver,
560 const struct GNUNET_HashCode *key_material)
562 const char salt[] = "MESH kx salt";
564 GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
566 key_material, sizeof (struct GNUNET_HashCode),
567 sender, sizeof (struct GNUNET_PeerIdentity),
568 receiver, sizeof (struct GNUNET_PeerIdentity),
573 * Pick a connection on which send the next data message.
575 * @param t Tunnel on which to send the message.
577 * @return The connection on which to send the next message.
579 static struct MeshConnection *
580 tunnel_get_connection (struct MeshTunnel3 *t)
582 struct MeshTConnection *iter;
583 struct MeshConnection *best;
585 unsigned int lowest_q;
587 LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GMP_2s (t->peer));
590 for (iter = t->connection_head; NULL != iter; iter = iter->next)
592 LOG (GNUNET_ERROR_TYPE_DEBUG, " connection %s: %u\n",
593 GMC_2s (iter->c), GMC_get_state (iter->c));
594 if (MESH_CONNECTION_READY == GMC_get_state (iter->c))
596 qn = GMC_get_qn (iter->c, GMC_is_origin (iter->c, GNUNET_YES));
597 LOG (GNUNET_ERROR_TYPE_DEBUG, " q_n %u, \n", qn);
605 LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GMC_2s (best));
611 * Callback called when a queued message is sent.
613 * Calculates the average time and connection packet tracking.
615 * @param cls Closure (TunnelQueue handle).
616 * @param c Connection this message was on.
617 * @param q Connection queue handle (unused).
618 * @param type Type of message sent.
619 * @param fwd Was this a FWD going message?
620 * @param size Size of the message.
623 message_sent (void *cls,
624 struct MeshConnection *c,
625 struct MeshConnectionQueue *q,
626 uint16_t type, int fwd, size_t size)
628 struct MeshTunnel3Queue *qt = cls;
630 GNUNET_assert (NULL != qt->cont);
631 qt->cont (qt->cont_cls, GMC_get_tunnel (c), qt, type, size);
637 * Delete a queued message: either was sent or the channel was destroyed
638 * before the tunnel's key exchange had a chance to finish.
640 * @param tq Queue handle.
643 unqueue_data (struct MeshTunnelDelayed *tq)
645 GNUNET_CONTAINER_DLL_remove (tq->t->tq_head, tq->t->tq_tail, tq);
651 * Cache a message to be sent once tunnel is online.
653 * @param t Tunnel to hold the message.
654 * @param msg Message itself (copy will be made).
656 static struct MeshTunnelDelayed *
657 queue_data (struct MeshTunnel3 *t, const struct GNUNET_MessageHeader *msg)
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);
673 memcpy (&tq[1], msg, size);
674 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tq);
681 * Sends an already built message on a tunnel, encrypting it and
682 * choosing the best connection.
684 * @param message Message to send. Function modifies it.
685 * @param t Tunnel on which this message is transmitted.
686 * @param force Force the tunnel to take the message (buffer overfill).
687 * @param cont Continuation to call once message is really sent.
688 * @param cont_cls Closure for @c cont.
689 * @param existing_q In case this a transmission of previously queued data,
690 * this should be TunnelQueue given to the client.
693 * @return Handle to cancel message. NULL if @c cont is NULL.
695 static struct MeshTunnel3Queue *
696 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
697 struct MeshTunnel3 *t, int force,
698 GMT_sent cont, void *cont_cls,
699 struct MeshTunnel3Queue *existing_q)
701 struct MeshTunnel3Queue *tq;
702 struct MeshConnection *c;
703 struct GNUNET_MESH_Encrypted *msg;
704 size_t size = ntohs (message->size);
705 char cbuf[sizeof (struct GNUNET_MESH_Encrypted) + size];
710 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GMT_2s (t));
712 if (GNUNET_NO == is_ready (t))
714 GNUNET_assert (NULL == existing_q);
715 tq = GNUNET_new (struct MeshTunnel3Queue);
716 tq->tqd = queue_data (t, message);
719 tq->cont_cls = cont_cls;
723 GNUNET_assert (GNUNET_NO == GMT_is_loopback (t));
725 iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
726 msg = (struct GNUNET_MESH_Encrypted *) cbuf;
727 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED);
729 GNUNET_assert (t_encrypt (t, &msg[1], message, size, iv) == size);
730 msg->header.size = htons (sizeof (struct GNUNET_MESH_Encrypted) + size);
731 c = tunnel_get_connection (t);
734 GNUNET_break (GNUNET_YES == t->destroy);
737 type = ntohs (message->type);
740 case GNUNET_MESSAGE_TYPE_MESH_DATA:
741 case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
742 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
743 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
744 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
745 msg->cid = *GMC_get_id (c);
746 msg->ttl = htonl (default_ttl);
749 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
754 fwd = GMC_is_origin (c, GNUNET_YES);
758 (void) GMC_send_prebuilt_message (&msg->header, c, fwd, force, NULL, NULL);
761 if (NULL == existing_q)
763 tq = GNUNET_new (struct MeshTunnel3Queue); /* FIXME valgrind: leak*/
770 tq->cq = GMC_send_prebuilt_message (&msg->header, c, fwd, force,
773 tq->cont_cls = cont_cls;
780 * Send all cached messages that we can, tunnel is online.
782 * @param t Tunnel that holds the messages. Cannot be loopback.
785 send_queued_data (struct MeshTunnel3 *t)
787 struct MeshTunnelDelayed *tqd;
788 struct MeshTunnelDelayed *next;
791 LOG (GNUNET_ERROR_TYPE_DEBUG,
792 "GMT_send_queued_data on tunnel %s\n",
795 if (GMT_is_loopback (t))
801 if (GNUNET_NO == is_ready (t))
803 LOG (GNUNET_ERROR_TYPE_DEBUG, " not ready yet: %s/%s\n",
804 estate2s (t->estate), cstate2s (t->cstate));
808 room = GMT_get_connections_buffer (t);
809 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
810 LOG (GNUNET_ERROR_TYPE_DEBUG, " tq head: %p\n", t->tq_head);
811 for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
813 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
816 send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
818 tqd->tq->cont, tqd->tq->cont_cls, tqd->tq);
821 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT_send_queued_data end\n", GMP_2s (t->peer));
826 * Sends key exchange message on a tunnel, choosing the best connection.
827 * Should not be called on loopback tunnels.
829 * @param t Tunnel on which this message is transmitted.
830 * @param message Message to send. Function modifies it.
833 send_kx (struct MeshTunnel3 *t,
834 const struct GNUNET_MessageHeader *message)
836 struct MeshConnection *c;
837 struct GNUNET_MESH_KX *msg;
838 size_t size = ntohs (message->size);
839 char cbuf[sizeof (struct GNUNET_MESH_KX) + size];
843 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GMT_2s (t));
845 /* Avoid loopback. */
846 if (GMT_is_loopback (t))
848 LOG (GNUNET_ERROR_TYPE_DEBUG, " loopback!\n");
853 /* Must have a connection. */
854 if (NULL == t->connection_head)
860 msg = (struct GNUNET_MESH_KX *) cbuf;
861 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX);
862 msg->header.size = htons (sizeof (struct GNUNET_MESH_KX) + size);
863 c = tunnel_get_connection (t);
866 GNUNET_break (GNUNET_YES == t->destroy);
869 type = ntohs (message->type);
872 case GNUNET_MESSAGE_TYPE_MESH_KX_EPHEMERAL:
873 case GNUNET_MESSAGE_TYPE_MESH_KX_PING:
874 case GNUNET_MESSAGE_TYPE_MESH_KX_PONG:
875 msg->reserved = htonl (0);
876 memcpy (&msg[1], message, size);
879 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
884 fwd = GMC_is_origin (t->connection_head->c, GNUNET_YES);
885 /* TODO save handle and cancel in case of a unneeded retransmission */
886 GMC_send_prebuilt_message (&msg->header, c, fwd, GNUNET_YES, NULL, NULL);
891 * Send the ephemeral key on a tunnel.
893 * @param t Tunnel on which to send the key.
896 send_ephemeral (struct MeshTunnel3 *t)
898 LOG (GNUNET_ERROR_TYPE_DEBUG, "%s()\n", __FUNCTION__);
900 kx_msg.sender_status = htonl (t->estate);
901 send_kx (t, &kx_msg.header);
905 * Send a ping message on a tunnel.
907 * @param t Tunnel on which to send the ping.
910 send_ping (struct MeshTunnel3 *t)
912 struct GNUNET_MESH_KX_Ping msg;
914 LOG (GNUNET_ERROR_TYPE_DEBUG, "%s()\n", __FUNCTION__);
915 msg.header.size = htons (sizeof (msg));
916 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX_PING);
917 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
918 msg.target = *GMP_get_id (t->peer);
919 msg.nonce = t->kx_ctx->challenge;
921 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
922 LOG (GNUNET_ERROR_TYPE_DEBUG, " towards %s\n", GNUNET_i2s (&msg.target));
923 t_encrypt (t, &msg.target, &msg.target, ping_encryption_size(), msg.iv);
924 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
925 LOG (GNUNET_ERROR_TYPE_DEBUG, " e towards %s\n", GNUNET_i2s (&msg.target));
927 send_kx (t, &msg.header);
932 * Send a pong message on a tunnel.
934 * @param t Tunnel on which to send the pong.
935 * @param challenge Value sent in the ping that we have to send back.
938 send_pong (struct MeshTunnel3 *t, uint32_t challenge)
940 struct GNUNET_MESH_KX_Pong msg;
942 LOG (GNUNET_ERROR_TYPE_DEBUG, "%s()\n", __FUNCTION__);
943 msg.header.size = htons (sizeof (msg));
944 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX_PONG);
945 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
946 msg.nonce = challenge;
947 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
948 t_encrypt (t, &msg.nonce, &msg.nonce, sizeof (msg.nonce), msg.iv);
949 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
951 send_kx (t, &msg.header);
956 * Initiate a rekey with the remote peer.
958 * @param cls Closure (tunnel).
959 * @param tc TaskContext.
962 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
964 struct MeshTunnel3 *t = cls;
966 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
968 LOG (GNUNET_ERROR_TYPE_DEBUG, "Re-key Tunnel\n");
969 if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
972 if (NULL == t->kx_ctx)
974 LOG (GNUNET_ERROR_TYPE_DEBUG, " new kx ctx\n");
975 t->kx_ctx = GNUNET_new (struct MeshTunnelKXCtx);
976 t->kx_ctx->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
978 t->kx_ctx->d_key_old = t->d_key;
983 case MESH_TUNNEL3_KEY_UNINITIALIZED:
984 t->estate = MESH_TUNNEL3_KEY_SENT;
986 case MESH_TUNNEL3_KEY_SENT:
988 case MESH_TUNNEL3_KEY_PING:
989 case MESH_TUNNEL3_KEY_OK:
991 t->estate = MESH_TUNNEL3_KEY_PING;
994 LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
997 LOG (GNUNET_ERROR_TYPE_DEBUG, " next call in %s\n",
998 GNUNET_STRINGS_relative_time_to_string (REKEY_WAIT, GNUNET_YES));
999 t->rekey_task = GNUNET_SCHEDULER_add_delayed (REKEY_WAIT, &rekey_tunnel, t);
1004 * Out ephemeral key has changed, create new session key on all tunnels.
1006 * @param cls Closure (size of the hashmap).
1007 * @param key Current public key.
1008 * @param value Value in the hash map (tunnel).
1010 * @return #GNUNET_YES, so we should continue to iterate,
1013 rekey_iterator (void *cls,
1014 const struct GNUNET_PeerIdentity *key,
1017 struct MeshTunnel3 *t = value;
1018 struct GNUNET_TIME_Relative delay;
1019 long n = (long) cls;
1022 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
1025 r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
1026 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
1027 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1034 * Create a new ephemeral key and key message, schedule next rekeying.
1036 * @param cls Closure (unused).
1037 * @param tc TaskContext.
1040 rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1042 struct GNUNET_TIME_Absolute time;
1045 rekey_task = GNUNET_SCHEDULER_NO_TASK;
1047 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1050 GNUNET_free_non_null (my_ephemeral_key);
1051 my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
1053 time = GNUNET_TIME_absolute_get ();
1054 kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
1055 time = GNUNET_TIME_absolute_add (time, rekey_period);
1056 time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
1057 kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
1058 GNUNET_CRYPTO_ecdhe_key_get_public (my_ephemeral_key, &kx_msg.ephemeral_key);
1060 GNUNET_assert (GNUNET_OK ==
1061 GNUNET_CRYPTO_eddsa_sign (my_private_key,
1063 &kx_msg.signature));
1065 n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
1066 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
1068 rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period, &rekey, NULL);
1073 * Called only on shutdown, destroy every tunnel.
1075 * @param cls Closure (unused).
1076 * @param key Current public key.
1077 * @param value Value in the hash map (tunnel).
1079 * @return #GNUNET_YES, so we should continue to iterate,
1082 destroy_iterator (void *cls,
1083 const struct GNUNET_PeerIdentity *key,
1086 struct MeshTunnel3 *t = value;
1094 * Demultiplex data per channel and call appropriate channel handler.
1096 * @param t Tunnel on which the data came.
1097 * @param msg Data message.
1098 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1099 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1100 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1101 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1104 handle_data (struct MeshTunnel3 *t,
1105 const struct GNUNET_MESH_Data *msg,
1108 struct MeshChannel *ch;
1112 size = ntohs (msg->header.size);
1114 sizeof (struct GNUNET_MESH_Data) +
1115 sizeof (struct GNUNET_MessageHeader))
1120 LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
1121 GM_m2s (ntohs (msg[1].header.type)));
1124 ch = GMT_get_channel (t, ntohl (msg->chid));
1127 GNUNET_STATISTICS_update (stats, "# data on unknown channel",
1129 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1134 GMCH_handle_data (ch, msg, fwd);
1139 * Demultiplex data ACKs per channel and update appropriate channel buffer info.
1141 * @param t Tunnel on which the DATA ACK came.
1142 * @param msg DATA ACK message.
1143 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1144 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1145 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1146 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1149 handle_data_ack (struct MeshTunnel3 *t,
1150 const struct GNUNET_MESH_DataACK *msg,
1153 struct MeshChannel *ch;
1157 size = ntohs (msg->header.size);
1158 if (size != sizeof (struct GNUNET_MESH_DataACK))
1165 ch = GMT_get_channel (t, ntohl (msg->chid));
1168 GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
1170 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1175 GMCH_handle_data_ack (ch, msg, fwd);
1180 * Handle channel create.
1182 * @param t Tunnel on which the data came.
1183 * @param msg Data message.
1186 handle_ch_create (struct MeshTunnel3 *t,
1187 const struct GNUNET_MESH_ChannelCreate *msg)
1189 struct MeshChannel *ch;
1193 size = ntohs (msg->header.size);
1194 if (size != sizeof (struct GNUNET_MESH_ChannelCreate))
1201 ch = GMT_get_channel (t, ntohl (msg->chid));
1202 if (NULL != ch && ! GMT_is_loopback (t))
1204 /* Probably a retransmission, safe to ignore */
1205 LOG (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
1209 ch = GMCH_handle_create (t, msg);
1212 GMT_add_channel (t, ch);
1218 * Handle channel NACK: check correctness and call channel handler for NACKs.
1220 * @param t Tunnel on which the NACK came.
1221 * @param msg NACK message.
1224 handle_ch_nack (struct MeshTunnel3 *t,
1225 const struct GNUNET_MESH_ChannelManage *msg)
1227 struct MeshChannel *ch;
1231 size = ntohs (msg->header.size);
1232 if (size != sizeof (struct GNUNET_MESH_ChannelManage))
1239 ch = GMT_get_channel (t, ntohl (msg->chid));
1242 GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
1244 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1249 GMCH_handle_nack (ch);
1254 * Handle a CHANNEL ACK (SYNACK/ACK).
1256 * @param t Tunnel on which the CHANNEL ACK came.
1257 * @param msg CHANNEL ACK message.
1258 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1259 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1260 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1261 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1264 handle_ch_ack (struct MeshTunnel3 *t,
1265 const struct GNUNET_MESH_ChannelManage *msg,
1268 struct MeshChannel *ch;
1272 size = ntohs (msg->header.size);
1273 if (size != sizeof (struct GNUNET_MESH_ChannelManage))
1280 ch = GMT_get_channel (t, ntohl (msg->chid));
1283 GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
1285 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1290 GMCH_handle_ack (ch, msg, fwd);
1296 * Handle a channel destruction message.
1298 * @param t Tunnel on which the message came.
1299 * @param msg Channel destroy message.
1300 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1301 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1302 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1303 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1306 handle_ch_destroy (struct MeshTunnel3 *t,
1307 const struct GNUNET_MESH_ChannelManage *msg,
1310 struct MeshChannel *ch;
1314 size = ntohs (msg->header.size);
1315 if (size != sizeof (struct GNUNET_MESH_ChannelManage))
1322 ch = GMT_get_channel (t, ntohl (msg->chid));
1325 /* Probably a retransmission, safe to ignore */
1329 GMCH_handle_destroy (ch, msg, fwd);
1334 * The peer's ephemeral key has changed: update the symmetrical keys.
1336 * @param t Tunnel this message came on.
1337 * @param msg Key eXchange message.
1340 handle_ephemeral (struct MeshTunnel3 *t,
1341 const struct GNUNET_MESH_KX_Ephemeral *msg)
1343 struct GNUNET_HashCode km;
1344 LOG (GNUNET_ERROR_TYPE_DEBUG, " ephemeral key message\n");
1346 if (GNUNET_OK != check_ephemeral (t, msg))
1348 GNUNET_break_op (0);
1351 derive_key_material (&km, &msg->ephemeral_key);
1352 LOG (GNUNET_ERROR_TYPE_DEBUG, " km is %s\n", GNUNET_h2s (&km));
1353 derive_symmertic (&t->e_key, &my_full_id, GMP_get_id (t->peer), &km);
1354 derive_symmertic (&t->d_key, GMP_get_id (t->peer), &my_full_id, &km);
1355 if (MESH_TUNNEL3_KEY_SENT == t->estate)
1357 LOG (GNUNET_ERROR_TYPE_DEBUG, " our key was sent, send ping\n");
1359 t->estate = MESH_TUNNEL3_KEY_PING;
1365 * Peer wants to check our symmetrical keys by sending an encrypted challenge.
1366 * Answer with by retransmitting the challenge with the "opposite" key.
1368 * @param t Tunnel this message came on.
1369 * @param msg Key eXchange Ping message.
1372 handle_ping (struct MeshTunnel3 *t,
1373 const struct GNUNET_MESH_KX_Ping *msg)
1375 struct GNUNET_MESH_KX_Ping res;
1377 if (ntohs (msg->header.size) != sizeof (res))
1379 GNUNET_break_op (0);
1383 LOG (GNUNET_ERROR_TYPE_DEBUG, " ping message\n");
1384 t_decrypt (t, &res.target, &msg->target, ping_encryption_size (), msg->iv);
1385 if (0 != memcmp (&my_full_id, &res.target, sizeof (my_full_id)))
1387 GNUNET_break_op (0);
1388 LOG (GNUNET_ERROR_TYPE_DEBUG, " e got %u\n", msg->nonce);
1389 LOG (GNUNET_ERROR_TYPE_DEBUG, " e towards %s\n", GNUNET_i2s (&msg->target));
1390 LOG (GNUNET_ERROR_TYPE_DEBUG, " got %u\n", res.nonce);
1391 LOG (GNUNET_ERROR_TYPE_DEBUG, " towards %s\n", GNUNET_i2s (&res.target));
1395 send_pong (t, res.nonce);
1400 * Peer has answer to our challenge.
1401 * If answer is successful, consider the key exchange finished and clean
1402 * up all related state.
1404 * @param t Tunnel this message came on.
1405 * @param msg Key eXchange Pong message.
1408 handle_pong (struct MeshTunnel3 *t,
1409 const struct GNUNET_MESH_KX_Pong *msg)
1413 LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG received\n");
1414 if (GNUNET_SCHEDULER_NO_TASK == t->rekey_task)
1416 GNUNET_break_op (0);
1419 t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
1421 if (challenge != t->kx_ctx->challenge)
1423 LOG (GNUNET_ERROR_TYPE_DEBUG,
1424 "Wrong PONG challenge: %u (e: %u). Expected: %u.\n",
1425 challenge, msg->nonce, t->kx_ctx->challenge);
1426 GNUNET_break_op (0);
1429 GNUNET_SCHEDULER_cancel (t->rekey_task);
1430 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1431 GNUNET_free (t->kx_ctx);
1433 GMT_change_estate (t, MESH_TUNNEL3_KEY_OK);
1438 * Demultiplex by message type and call appropriate handler for a message
1439 * towards a channel of a local tunnel.
1441 * @param t Tunnel this message came on.
1442 * @param msgh Message header.
1443 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1444 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1445 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1446 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1449 handle_decrypted (struct MeshTunnel3 *t,
1450 const struct GNUNET_MessageHeader *msgh,
1455 type = ntohs (msgh->type);
1456 LOG (GNUNET_ERROR_TYPE_DEBUG,
1457 "Got a %s message!\n",
1462 case GNUNET_MESSAGE_TYPE_MESH_DATA:
1463 /* Don't send hop ACK, wait for client to ACK */
1464 handle_data (t, (struct GNUNET_MESH_Data *) msgh, fwd);
1467 case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
1468 handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh, fwd);
1471 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
1472 handle_ch_create (t,
1473 (struct GNUNET_MESH_ChannelCreate *) msgh);
1476 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_NACK:
1478 (struct GNUNET_MESH_ChannelManage *) msgh);
1481 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
1483 (struct GNUNET_MESH_ChannelManage *) msgh,
1487 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
1488 handle_ch_destroy (t,
1489 (struct GNUNET_MESH_ChannelManage *) msgh,
1494 GNUNET_break_op (0);
1495 LOG (GNUNET_ERROR_TYPE_DEBUG,
1496 "end-to-end message not known (%u)\n",
1497 ntohs (msgh->type));
1501 /******************************************************************************/
1502 /******************************** API ***********************************/
1503 /******************************************************************************/
1506 * Decrypt and demultiplex by message type. Call appropriate handler
1507 * for every message.
1509 * @param t Tunnel this message came on.
1510 * @param msg Encrypted message.
1513 GMT_handle_encrypted (struct MeshTunnel3 *t,
1514 const struct GNUNET_MESH_Encrypted *msg)
1516 size_t size = ntohs (msg->header.size);
1517 size_t payload_size = size - sizeof (struct GNUNET_MESH_Encrypted);
1518 size_t decrypted_size;
1519 char cbuf [payload_size];
1520 struct GNUNET_MessageHeader *msgh;
1523 decrypted_size = t_decrypt (t, cbuf, &msg[1], payload_size, msg->iv);
1525 while (off < decrypted_size)
1527 msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
1528 handle_decrypted (t, msgh, GNUNET_SYSERR);
1529 off += ntohs (msgh->size);
1535 * Demultiplex an encapsulated KX message by message type.
1537 * @param t Tunnel on which the message came.
1538 * @param message Payload of KX message.
1541 GMT_handle_kx (struct MeshTunnel3 *t,
1542 const struct GNUNET_MessageHeader *message)
1546 type = ntohs (message->type);
1547 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received\n", type);
1550 case GNUNET_MESSAGE_TYPE_MESH_KX_EPHEMERAL:
1551 handle_ephemeral (t, (struct GNUNET_MESH_KX_Ephemeral *) message);
1554 case GNUNET_MESSAGE_TYPE_MESH_KX_PING:
1555 handle_ping (t, (struct GNUNET_MESH_KX_Ping *) message);
1558 case GNUNET_MESSAGE_TYPE_MESH_KX_PONG:
1559 handle_pong (t, (struct GNUNET_MESH_KX_Pong *) message);
1563 GNUNET_break_op (0);
1564 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message not known (%u)\n", type);
1570 * Initialize the tunnel subsystem.
1572 * @param c Configuration handle.
1573 * @param key ECC private key, to derive all other keys and do crypto.
1576 GMT_init (const struct GNUNET_CONFIGURATION_Handle *c,
1577 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
1579 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
1581 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
1584 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1585 "MESH", "DEFAULT_TTL", "USING DEFAULT");
1589 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REKEY_PERIOD",
1592 rekey_period = GNUNET_TIME_UNIT_DAYS;
1595 my_private_key = key;
1596 kx_msg.header.size = htons (sizeof (kx_msg));
1597 kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX_EPHEMERAL);
1598 kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_MESH_KX);
1599 kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
1600 kx_msg.origin_identity = my_full_id;
1601 rekey_task = GNUNET_SCHEDULER_add_now (&rekey, NULL);
1603 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
1608 * Shut down the tunnel subsystem.
1613 if (GNUNET_SCHEDULER_NO_TASK != rekey_task)
1615 GNUNET_SCHEDULER_cancel (rekey_task);
1616 rekey_task = GNUNET_SCHEDULER_NO_TASK;
1618 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
1619 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
1626 * @param destination Peer this tunnel is towards.
1628 struct MeshTunnel3 *
1629 GMT_new (struct MeshPeer *destination)
1631 struct MeshTunnel3 *t;
1633 t = GNUNET_new (struct MeshTunnel3);
1635 t->peer = destination;
1638 GNUNET_CONTAINER_multipeermap_put (tunnels, GMP_get_id (destination), t,
1639 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
1650 * Change the tunnel's connection state.
1652 * @param t Tunnel whose connection state to change.
1653 * @param cstate New connection state.
1656 GMT_change_cstate (struct MeshTunnel3* t, enum MeshTunnel3CState cstate)
1660 LOG (GNUNET_ERROR_TYPE_DEBUG,
1661 "Tunnel %s cstate was %s\n",
1662 GMP_2s (t->peer), cstate2s (t->cstate));
1663 LOG (GNUNET_ERROR_TYPE_DEBUG,
1664 "Tunnel %s cstate is now %s\n",
1665 GMP_2s (t->peer), cstate2s (cstate));
1666 if (myid != GMP_get_short_id (t->peer) &&
1667 MESH_TUNNEL3_READY != t->cstate &&
1668 MESH_TUNNEL3_READY == cstate)
1671 if (MESH_TUNNEL3_KEY_OK == t->estate)
1673 LOG (GNUNET_ERROR_TYPE_DEBUG, " triggered send queued data\n");
1674 send_queued_data (t);
1676 else if (MESH_TUNNEL3_KEY_UNINITIALIZED == t->estate)
1678 LOG (GNUNET_ERROR_TYPE_DEBUG, " triggered rekey\n");
1679 rekey_tunnel (t, NULL);
1684 if (MESH_TUNNEL3_READY == cstate && 3 <= GMT_count_connections (t))
1686 GMP_stop_search (t->peer);
1691 * Change the tunnel encryption state.
1693 * @param t Tunnel whose encryption state to change.
1694 * @param state New encryption state.
1697 GMT_change_estate (struct MeshTunnel3* t, enum MeshTunnel3EState state)
1701 LOG (GNUNET_ERROR_TYPE_DEBUG,
1702 "Tunnel %s estate was %s\n",
1703 GMP_2s (t->peer), estate2s (t->estate));
1704 LOG (GNUNET_ERROR_TYPE_DEBUG,
1705 "Tunnel %s estate is now %s\n",
1706 GMP_2s (t->peer), estate2s (state));
1707 if (myid != GMP_get_short_id (t->peer) &&
1708 MESH_TUNNEL3_KEY_OK != t->estate && MESH_TUNNEL3_KEY_OK == state)
1711 send_queued_data (t);
1719 * Add a connection to a tunnel.
1722 * @param c Connection.
1725 GMT_add_connection (struct MeshTunnel3 *t, struct MeshConnection *c)
1727 struct MeshTConnection *aux;
1729 GNUNET_assert (NULL != c);
1731 for (aux = t->connection_head; aux != NULL; aux = aux->next)
1735 aux = GNUNET_new (struct MeshTConnection);
1737 GNUNET_CONTAINER_DLL_insert_tail (t->connection_head, t->connection_tail, aux);
1742 * Remove a connection from a tunnel.
1745 * @param c Connection.
1748 GMT_remove_connection (struct MeshTunnel3 *t, struct MeshConnection *c)
1750 struct MeshTConnection *aux;
1753 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
1754 GMC_2s (c), GMT_2s (t));
1755 for (aux = t->connection_head; aux != NULL; aux = aux->next)
1758 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
1763 /* Start new connections if needed */
1764 if (NULL == t->connection_head)
1766 LOG (GNUNET_ERROR_TYPE_DEBUG, " no more connections\n");
1767 GMP_connect (t->peer);
1768 t->cstate = MESH_TUNNEL3_SEARCHING;
1772 /* If not marked as ready, no change is needed */
1773 if (MESH_TUNNEL3_READY != t->cstate)
1776 /* Check if any connection is ready to maintaing cstate */
1777 for (aux = t->connection_head; aux != NULL; aux = aux->next)
1778 if (MESH_CONNECTION_READY == GMC_get_state (aux->c))
1781 t->cstate = MESH_TUNNEL3_WAITING;
1786 * Add a channel to a tunnel.
1789 * @param ch Channel.
1792 GMT_add_channel (struct MeshTunnel3 *t, struct MeshChannel *ch)
1794 struct MeshTChannel *aux;
1796 GNUNET_assert (NULL != ch);
1798 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
1800 for (aux = t->channel_head; aux != NULL; aux = aux->next)
1802 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
1807 aux = GNUNET_new (struct MeshTChannel);
1809 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
1810 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
1812 if (GNUNET_YES == t->destroy)
1814 t->destroy = GNUNET_NO;
1815 LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
1821 * Remove a channel from a tunnel.
1824 * @param ch Channel.
1827 GMT_remove_channel (struct MeshTunnel3 *t, struct MeshChannel *ch)
1829 struct MeshTChannel *aux;
1831 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
1832 for (aux = t->channel_head; aux != NULL; aux = aux->next)
1836 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GMCH_2s (ch));
1837 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
1846 * Search for a channel by global ID.
1848 * @param t Tunnel containing the channel.
1849 * @param chid Public channel number.
1851 * @return channel handler, NULL if doesn't exist
1853 struct MeshChannel *
1854 GMT_get_channel (struct MeshTunnel3 *t, MESH_ChannelNumber chid)
1856 struct MeshTChannel *iter;
1861 for (iter = t->channel_head; NULL != iter; iter = iter->next)
1863 if (GMCH_get_id (iter->ch) == chid)
1867 return NULL == iter ? NULL : iter->ch;
1872 * Tunnel is empty: destroy it.
1874 * Notifies all connections about the destruction.
1876 * @param t Tunnel to destroy.
1879 GMT_destroy_empty (struct MeshTunnel3 *t)
1881 struct MeshTConnection *iter;
1883 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel empty: destroying scheduled\n");
1884 for (iter = t->connection_head; NULL != iter; iter = iter->next)
1886 GMC_send_destroy (iter->c);
1889 t->cstate = MESH_TUNNEL3_NEW;
1890 t->destroy = GNUNET_YES;
1895 * Destroy tunnel if empty (no more channels).
1897 * @param t Tunnel to destroy if empty.
1900 GMT_destroy_if_empty (struct MeshTunnel3 *t)
1902 if (1 < GMT_count_channels (t))
1905 GMT_destroy_empty (t);
1910 * Destroy the tunnel.
1912 * This function does not generate any warning traffic to clients or peers.
1915 * Cancel messages belonging to this tunnel queued to neighbors.
1916 * Free any allocated resources linked to the tunnel.
1918 * @param t The tunnel to destroy.
1921 GMT_destroy (struct MeshTunnel3 *t)
1923 struct MeshTConnection *iter_c;
1924 struct MeshTConnection *next_c;
1925 struct MeshTChannel *iter_ch;
1926 struct MeshTChannel *next_ch;
1931 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GMP_2s (t->peer));
1933 GNUNET_break (GNUNET_YES ==
1934 GNUNET_CONTAINER_multipeermap_remove (tunnels,
1935 GMP_get_id (t->peer), t));
1937 for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
1939 next_c = iter_c->next;
1940 GMC_destroy (iter_c->c);
1942 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
1944 next_ch = iter_ch->next;
1945 GMCH_destroy (iter_ch->ch);
1946 /* Should only happen on shutdown, but it's ok. */
1949 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
1950 GMP_set_tunnel (t->peer, NULL);
1952 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
1953 GNUNET_SCHEDULER_cancel (t->rekey_task);
1960 * @brief Use the given path for the tunnel.
1961 * Update the next and prev hops (and RCs).
1962 * (Re)start the path refresh in case the tunnel is locally owned.
1964 * @param t Tunnel to update.
1965 * @param p Path to use.
1967 * @return Connection created.
1969 struct MeshConnection *
1970 GMT_use_path (struct MeshTunnel3 *t, struct MeshPeerPath *p)
1972 struct MeshConnection *c;
1973 struct GNUNET_HashCode cid;
1974 unsigned int own_pos;
1976 if (NULL == t || NULL == p)
1982 for (own_pos = 0; own_pos < p->length; own_pos++)
1984 if (p->peers[own_pos] == myid)
1987 if (own_pos > p->length - 1)
1993 GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE, &cid);
1994 c = GMC_new (&cid, t, p, own_pos);
1997 /* Path was flawed */
2000 GMT_add_connection (t, c);
2006 * Count established (ready) connections of a tunnel.
2008 * @param t Tunnel on which to count.
2010 * @return Number of connections.
2013 GMT_count_connections (struct MeshTunnel3 *t)
2015 struct MeshTConnection *iter;
2018 for (count = 0, iter = t->connection_head;
2020 iter = iter->next, count++);
2026 * Count channels of a tunnel.
2028 * @param t Tunnel on which to count.
2030 * @return Number of channels.
2033 GMT_count_channels (struct MeshTunnel3 *t)
2035 struct MeshTChannel *iter;
2038 for (count = 0, iter = t->channel_head;
2040 iter = iter->next, count++) /* skip */;
2047 * Get the connectivity state of a tunnel.
2051 * @return Tunnel's connectivity state.
2053 enum MeshTunnel3CState
2054 GMT_get_cstate (struct MeshTunnel3 *t)
2059 return (enum MeshTunnel3CState) -1;
2066 * Get the maximum buffer space for a tunnel towards a local client.
2070 * @return Biggest buffer space offered by any channel in the tunnel.
2073 GMT_get_channels_buffer (struct MeshTunnel3 *t)
2075 struct MeshTChannel *iter;
2076 unsigned int buffer;
2077 unsigned int ch_buf;
2079 if (NULL == t->channel_head)
2081 /* Probably getting buffer for a channel create/handshake. */
2086 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2088 ch_buf = get_channel_buffer (iter);
2089 if (ch_buf > buffer)
2097 * Get the total buffer space for a tunnel for P2P traffic.
2101 * @return Buffer space offered by all connections in the tunnel.
2104 GMT_get_connections_buffer (struct MeshTunnel3 *t)
2106 struct MeshTConnection *iter;
2107 unsigned int buffer;
2110 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2112 if (GMC_get_state (iter->c) != MESH_CONNECTION_READY)
2116 buffer += get_connection_buffer (iter);
2124 * Get the tunnel's destination.
2128 * @return ID of the destination peer.
2130 const struct GNUNET_PeerIdentity *
2131 GMT_get_destination (struct MeshTunnel3 *t)
2133 return GMP_get_id (t->peer);
2138 * Get the tunnel's next free global channel ID.
2142 * @return GID of a channel free to use.
2145 GMT_get_next_chid (struct MeshTunnel3 *t)
2147 MESH_ChannelNumber chid;
2148 MESH_ChannelNumber mask;
2151 /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
2152 * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
2153 * If peer's ID is bigger, start at 0x4... bit 30 = 1
2155 result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GMP_get_id (t->peer));
2161 while (NULL != GMT_get_channel (t, t->next_chid))
2163 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
2164 t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
2165 t->next_chid |= mask;
2167 chid = t->next_chid;
2168 t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
2169 t->next_chid |= mask;
2176 * Send ACK on one or more channels due to buffer in connections.
2178 * @param t Channel which has some free buffer space.
2181 GMT_unchoke_channels (struct MeshTunnel3 *t)
2183 struct MeshTChannel *iter;
2184 unsigned int buffer;
2185 unsigned int channels = GMT_count_channels (t);
2186 unsigned int choked_n;
2187 struct MeshChannel *choked[channels];
2189 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT_unchoke_channels on %s\n", GMT_2s (t));
2190 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
2191 if (NULL != t->channel_head)
2192 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
2194 /* Get buffer space */
2195 buffer = GMT_get_connections_buffer (t);
2201 /* Count and remember choked channels */
2203 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2205 if (GNUNET_NO == get_channel_allowed (iter))
2207 choked[choked_n++] = iter->ch;
2211 /* Unchoke random channels */
2212 while (0 < buffer && 0 < choked_n)
2214 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2216 GMCH_allow_client (choked[r], GMCH_is_origin (choked[r], GNUNET_YES));
2219 choked[r] = choked[choked_n];
2225 * Send ACK on one or more connections due to buffer space to the client.
2227 * Iterates all connections of the tunnel and sends ACKs appropriately.
2232 GMT_send_connection_acks (struct MeshTunnel3 *t)
2234 struct MeshTConnection *iter;
2237 uint32_t allow_per_connection;
2239 unsigned int buffer;
2241 LOG (GNUNET_ERROR_TYPE_DEBUG,
2242 "Tunnel send connection ACKs on %s\n",
2251 buffer = GMT_get_channels_buffer (t);
2253 /* Count connections, how many messages are already allowed */
2254 cs = GMT_count_connections (t);
2255 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2257 allowed += get_connection_allowed (iter);
2260 /* Make sure there is no overflow */
2261 if (allowed > buffer)
2266 /* Authorize connections to send more data */
2267 to_allow = buffer; /* - allowed; */
2269 for (iter = t->connection_head; NULL != iter && to_allow > 0; iter = iter->next)
2271 allow_per_connection = to_allow/cs;
2272 to_allow -= allow_per_connection;
2274 if (get_connection_allowed (iter) > 64 / 3)
2278 GMC_allow (iter->c, buffer, GMC_is_origin (iter->c, GNUNET_YES));
2281 GNUNET_break (to_allow == 0);
2286 * Cancel a previously sent message while it's in the queue.
2288 * ONLY can be called before the continuation given to the send function
2289 * is called. Once the continuation is called, the message is no longer in the
2292 * @param q Handle to the queue.
2295 GMT_cancel (struct MeshTunnel3Queue *q)
2300 /* message_sent() will be called and free q */
2302 else if (NULL != q->tqd)
2304 unqueue_data (q->tqd);
2314 * Sends an already built message on a tunnel, encrypting it and
2315 * choosing the best connection.
2317 * @param message Message to send. Function modifies it.
2318 * @param t Tunnel on which this message is transmitted.
2319 * @param force Force the tunnel to take the message (buffer overfill).
2320 * @param cont Continuation to call once message is really sent.
2321 * @param cont_cls Closure for @c cont.
2323 * @return Handle to cancel message. NULL if @c cont is NULL.
2325 struct MeshTunnel3Queue *
2326 GMT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
2327 struct MeshTunnel3 *t, int force,
2328 GMT_sent cont, void *cont_cls)
2330 return send_prebuilt_message (message, t, force, cont, cont_cls, NULL);
2335 * Is the tunnel directed towards the local peer?
2339 * @return #GNUNET_YES if it is loopback.
2342 GMT_is_loopback (const struct MeshTunnel3 *t)
2344 return (myid == GMP_get_short_id (t->peer));
2349 * Is the tunnel this path already?
2354 * @return #GNUNET_YES a connection uses this path.
2357 GMT_is_path_used (const struct MeshTunnel3 *t, const struct MeshPeerPath *p)
2359 struct MeshTConnection *iter;
2361 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2362 if (GMC_get_path (iter->c) == p)
2370 * Get a cost of a path for a tunnel considering existing connections.
2373 * @param path Candidate path.
2375 * @return Cost of the path (path length + number of overlapping nodes)
2378 GMT_get_path_cost (const struct MeshTunnel3 *t,
2379 const struct MeshPeerPath *path)
2381 struct MeshTConnection *iter;
2382 const struct MeshPeerPath *aux;
2383 unsigned int overlap;
2391 GNUNET_assert (NULL != t);
2393 for (i = 0; i < path->length; i++)
2395 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2397 aux = GMC_get_path (iter->c);
2401 for (j = 0; j < aux->length; j++)
2403 if (path->peers[i] == aux->peers[j])
2411 return (path->length + overlap) * (path->score * -1);
2416 * Get the static string for the peer this tunnel is directed.
2420 * @return Static string the destination peer's ID.
2423 GMT_2s (const struct MeshTunnel3 *t)
2428 return GMP_2s (t->peer);