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 * Don't try to recover tunnels if shutting down.
227 extern int shutting_down;
231 * Set of all tunnels, in order to trigger a new exchange on rekey.
232 * Indexed by peer's ID.
234 static struct GNUNET_CONTAINER_MultiPeerMap *tunnels;
237 * Default TTL for payload packets.
239 static unsigned long long default_ttl;
244 const static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
247 * Own ephemeral private key.
249 static struct GNUNET_CRYPTO_EcdhePrivateKey *my_ephemeral_key;
252 * Cached message used to perform a key exchange.
254 static struct GNUNET_MESH_KX_Ephemeral kx_msg;
257 * Task to generate a new ephemeral key.
259 static GNUNET_SCHEDULER_TaskIdentifier rekey_task;
264 static struct GNUNET_TIME_Relative rekey_period;
266 /******************************************************************************/
267 /******************************** STATIC ***********************************/
268 /******************************************************************************/
271 * Get string description for tunnel connectivity state.
273 * @param cs Tunnel state.
275 * @return String representation.
278 cstate2s (enum MeshTunnel3CState cs)
280 static char buf[128];
284 case MESH_TUNNEL3_NEW:
285 return "MESH_TUNNEL3_NEW";
286 case MESH_TUNNEL3_SEARCHING:
287 return "MESH_TUNNEL3_SEARCHING";
288 case MESH_TUNNEL3_WAITING:
289 return "MESH_TUNNEL3_WAITING";
290 case MESH_TUNNEL3_READY:
291 return "MESH_TUNNEL3_READY";
294 sprintf (buf, "%u (UNKNOWN STATE)", cs);
302 * Get string description for tunnel encryption state.
304 * @param es Tunnel state.
306 * @return String representation.
309 estate2s (enum MeshTunnel3EState es)
311 static char buf[128];
315 case MESH_TUNNEL3_KEY_UNINITIALIZED:
316 return "MESH_TUNNEL3_KEY_UNINITIALIZED";
317 case MESH_TUNNEL3_KEY_SENT:
318 return "MESH_TUNNEL3_KEY_SENT";
319 case MESH_TUNNEL3_KEY_PING:
320 return "MESH_TUNNEL3_KEY_PING";
321 case MESH_TUNNEL3_KEY_OK:
322 return "MESH_TUNNEL3_KEY_OK";
325 sprintf (buf, "%u (UNKNOWN STATE)", es);
333 * @brief Check if tunnel is ready to send traffic.
335 * Tunnel must be connected and with encryption correctly set up.
337 * @param t Tunnel to check.
339 * @return #GNUNET_YES if ready, #GNUNET_NO otherwise
342 is_ready (struct MeshTunnel3 *t)
344 return (MESH_TUNNEL3_READY == t->cstate
345 && MESH_TUNNEL3_KEY_OK == t->estate)
346 || GMT_is_loopback (t);
351 * Ephemeral key message purpose size.
353 * @return Size of the part of the ephemeral key message that must be signed.
356 ephemeral_purpose_size (void)
358 return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
359 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
360 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
361 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
362 sizeof (struct GNUNET_PeerIdentity);
367 * Size of the encrypted part of a ping message.
369 * @return Size of the encrypted part of a ping message.
372 ping_encryption_size (void)
374 return sizeof (struct GNUNET_PeerIdentity) + sizeof (uint32_t);
379 * Get the channel's buffer. ONLY FOR NON-LOOPBACK CHANNELS!!
381 * @param tch Tunnel's channel handle.
383 * @return Amount of messages the channel can still buffer towards the client.
386 get_channel_buffer (const struct MeshTChannel *tch)
390 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
391 fwd = GMCH_is_origin (tch->ch, GNUNET_YES);
393 return GMCH_get_buffer (tch->ch, fwd);
398 * Get the channel's allowance status.
400 * @param tch Tunnel's channel handle.
402 * @return #GNUNET_YES if we allowed the client to send data to us.
405 get_channel_allowed (const struct MeshTChannel *tch)
409 /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
410 fwd = GMCH_is_origin (tch->ch, GNUNET_YES);
412 return GMCH_get_allowed (tch->ch, fwd);
417 * Get the connection's buffer.
419 * @param tc Tunnel's connection handle.
421 * @return Amount of messages the connection can still buffer.
424 get_connection_buffer (const struct MeshTConnection *tc)
428 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
429 fwd = GMC_is_origin (tc->c, GNUNET_YES);
431 return GMC_get_buffer (tc->c, fwd);
436 * Get the connection's allowance.
438 * @param tc Tunnel's connection handle.
440 * @return Amount of messages we have allowed the next peer to send us.
443 get_connection_allowed (const struct MeshTConnection *tc)
447 /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
448 fwd = GMC_is_origin (tc->c, GNUNET_YES);
450 return GMC_get_allowed (tc->c, fwd);
455 * Check that a ephemeral key message s well formed and correctly signed.
457 * @param t Tunnel on which the message came.
458 * @param msg The ephemeral key message.
460 * @return GNUNET_OK if message is fine, GNUNET_SYSERR otherwise.
463 check_ephemeral (struct MeshTunnel3 *t,
464 const struct GNUNET_MESH_KX_Ephemeral *msg)
466 /* Check message size */
467 if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_KX_Ephemeral))
468 return GNUNET_SYSERR;
470 /* Check signature size */
471 if (ntohl (msg->purpose.size) != ephemeral_purpose_size ())
472 return GNUNET_SYSERR;
475 if (0 != memcmp (&msg->origin_identity,
476 GMP_get_id (t->peer),
477 sizeof (struct GNUNET_PeerIdentity)))
478 return GNUNET_SYSERR;
480 /* Check signature */
482 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_MESH_KX,
485 &msg->origin_identity.public_key))
486 return GNUNET_SYSERR;
493 * Encrypt data with the tunnel key.
495 * @param t Tunnel whose key to use.
496 * @param dst Destination for the encrypted data.
497 * @param src Source of the plaintext. Can overlap with @c dst.
498 * @param size Size of the plaintext.
499 * @param iv Initialization Vector to use.
502 t_encrypt (struct MeshTunnel3 *t,
503 void *dst, const void *src,
504 size_t size, uint32_t iv)
506 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
508 GNUNET_CRYPTO_symmetric_derive_iv (&siv, &t->e_key, &iv, sizeof (uint32_t), NULL);
509 return GNUNET_CRYPTO_symmetric_encrypt (src, size, &t->e_key, &siv, dst);
514 * Decrypt data with the tunnel key.
516 * @param t Tunnel whose key to use.
517 * @param dst Destination for the plaintext.
518 * @param src Source of the encrypted data. Can overlap with @c dst.
519 * @param size Size of the encrypted data.
520 * @param iv Initialization Vector to use.
523 t_decrypt (struct MeshTunnel3 *t,
524 void *dst, const void *src,
525 size_t size, uint32_t iv)
527 struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
529 GNUNET_CRYPTO_symmetric_derive_iv (&siv, &t->d_key, &iv, sizeof (uint32_t), NULL);
530 return GNUNET_CRYPTO_symmetric_decrypt (src, size, &t->d_key, &siv, dst);
535 * Create key material by doing ECDH on the local and remote ephemeral keys.
537 * @param key_material Where to store the key material.
538 * @param ephemeral_key Peer's public ephemeral key.
541 derive_key_material (struct GNUNET_HashCode *key_material,
542 const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key)
545 GNUNET_CRYPTO_ecc_ecdh (my_ephemeral_key,
554 * Create a symmetic key from the identities of both ends and the key material
557 * @param key Destination for the generated key.
558 * @param sender ID of the peer that will encrypt with @c key.
559 * @param receiver ID of the peer that will decrypt with @c key.
560 * @param key_material Hash created with ECDH with the ephemeral keys.
563 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
564 const struct GNUNET_PeerIdentity *sender,
565 const struct GNUNET_PeerIdentity *receiver,
566 const struct GNUNET_HashCode *key_material)
568 const char salt[] = "MESH kx salt";
570 GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
572 key_material, sizeof (struct GNUNET_HashCode),
573 sender, sizeof (struct GNUNET_PeerIdentity),
574 receiver, sizeof (struct GNUNET_PeerIdentity),
579 * Pick a connection on which send the next data message.
581 * @param t Tunnel on which to send the message.
583 * @return The connection on which to send the next message.
585 static struct MeshConnection *
586 tunnel_get_connection (struct MeshTunnel3 *t)
588 struct MeshTConnection *iter;
589 struct MeshConnection *best;
591 unsigned int lowest_q;
593 LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GMP_2s (t->peer));
596 for (iter = t->connection_head; NULL != iter; iter = iter->next)
598 LOG (GNUNET_ERROR_TYPE_DEBUG, " connection %s: %u\n",
599 GMC_2s (iter->c), GMC_get_state (iter->c));
600 if (MESH_CONNECTION_READY == GMC_get_state (iter->c))
602 qn = GMC_get_qn (iter->c, GMC_is_origin (iter->c, GNUNET_YES));
603 LOG (GNUNET_ERROR_TYPE_DEBUG, " q_n %u, \n", qn);
611 LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GMC_2s (best));
617 * Callback called when a queued message is sent.
619 * Calculates the average time and connection packet tracking.
621 * @param cls Closure (TunnelQueue handle).
622 * @param c Connection this message was on.
623 * @param q Connection queue handle (unused).
624 * @param type Type of message sent.
625 * @param fwd Was this a FWD going message?
626 * @param size Size of the message.
629 message_sent (void *cls,
630 struct MeshConnection *c,
631 struct MeshConnectionQueue *q,
632 uint16_t type, int fwd, size_t size)
634 struct MeshTunnel3Queue *qt = cls;
636 GNUNET_assert (NULL != qt->cont);
637 qt->cont (qt->cont_cls, GMC_get_tunnel (c), qt, type, size);
643 * Delete a queued message: either was sent or the channel was destroyed
644 * before the tunnel's key exchange had a chance to finish.
646 * @param tq Queue handle.
649 unqueue_data (struct MeshTunnelDelayed *tq)
651 GNUNET_CONTAINER_DLL_remove (tq->t->tq_head, tq->t->tq_tail, tq);
657 * Cache a message to be sent once tunnel is online.
659 * @param t Tunnel to hold the message.
660 * @param msg Message itself (copy will be made).
662 static struct MeshTunnelDelayed *
663 queue_data (struct MeshTunnel3 *t, const struct GNUNET_MessageHeader *msg)
665 struct MeshTunnelDelayed *tqd;
666 uint16_t size = ntohs (msg->size);
668 LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GMT_2s (t));
670 if (GNUNET_YES == is_ready (t))
676 tqd = GNUNET_malloc (sizeof (struct MeshTunnelDelayed) + size);
679 memcpy (&tqd[1], msg, size);
680 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
687 * Sends an already built message on a tunnel, encrypting it and
688 * choosing the best connection.
690 * @param message Message to send. Function modifies it.
691 * @param t Tunnel on which this message is transmitted.
692 * @param force Force the tunnel to take the message (buffer overfill).
693 * @param cont Continuation to call once message is really sent.
694 * @param cont_cls Closure for @c cont.
695 * @param existing_q In case this a transmission of previously queued data,
696 * this should be TunnelQueue given to the client.
699 * @return Handle to cancel message. NULL if @c cont is NULL.
701 static struct MeshTunnel3Queue *
702 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
703 struct MeshTunnel3 *t, int force,
704 GMT_sent cont, void *cont_cls,
705 struct MeshTunnel3Queue *existing_q)
707 struct MeshTunnel3Queue *tq;
708 struct MeshConnection *c;
709 struct GNUNET_MESH_Encrypted *msg;
710 size_t size = ntohs (message->size);
711 char cbuf[sizeof (struct GNUNET_MESH_Encrypted) + size];
716 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GMT_2s (t));
718 if (GNUNET_NO == is_ready (t))
720 struct MeshTunnelDelayed *tqd;
721 /* A non null existing_q indicates sending of queued data.
722 * Should only happen after tunnel becomes ready.
724 GNUNET_assert (NULL == existing_q);
725 tqd = queue_data (t, message);
728 tq = GNUNET_new (struct MeshTunnel3Queue);
732 tq->cont_cls = cont_cls;
736 GNUNET_assert (GNUNET_NO == GMT_is_loopback (t));
738 iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
739 msg = (struct GNUNET_MESH_Encrypted *) cbuf;
740 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED);
742 GNUNET_assert (t_encrypt (t, &msg[1], message, size, iv) == size);
743 msg->header.size = htons (sizeof (struct GNUNET_MESH_Encrypted) + size);
744 c = tunnel_get_connection (t);
747 if (GNUNET_YES == t->destroy || MESH_TUNNEL3_SEARCHING != t->cstate)
754 type = ntohs (message->type);
757 case GNUNET_MESSAGE_TYPE_MESH_DATA:
758 case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
759 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
760 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
761 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
762 msg->cid = *GMC_get_id (c);
763 msg->ttl = htonl (default_ttl);
766 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
771 fwd = GMC_is_origin (c, GNUNET_YES);
775 (void) GMC_send_prebuilt_message (&msg->header, c, fwd, force, NULL, NULL);
778 if (NULL == existing_q)
780 tq = GNUNET_new (struct MeshTunnel3Queue); /* FIXME valgrind: leak*/
787 tq->cq = GMC_send_prebuilt_message (&msg->header, c, fwd, force,
790 tq->cont_cls = cont_cls;
797 * Send all cached messages that we can, tunnel is online.
799 * @param t Tunnel that holds the messages. Cannot be loopback.
802 send_queued_data (struct MeshTunnel3 *t)
804 struct MeshTunnelDelayed *tqd;
805 struct MeshTunnelDelayed *next;
808 LOG (GNUNET_ERROR_TYPE_DEBUG,
809 "GMT_send_queued_data on tunnel %s\n",
812 if (GMT_is_loopback (t))
818 if (GNUNET_NO == is_ready (t))
820 LOG (GNUNET_ERROR_TYPE_DEBUG, " not ready yet: %s/%s\n",
821 estate2s (t->estate), cstate2s (t->cstate));
825 room = GMT_get_connections_buffer (t);
826 LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
827 LOG (GNUNET_ERROR_TYPE_DEBUG, " tq head: %p\n", t->tq_head);
828 for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
830 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
833 send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
835 NULL != tqd->tq ? tqd->tq->cont : NULL,
836 NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
840 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT_send_queued_data end\n", GMP_2s (t->peer));
845 * Sends key exchange message on a tunnel, choosing the best connection.
846 * Should not be called on loopback tunnels.
848 * @param t Tunnel on which this message is transmitted.
849 * @param message Message to send. Function modifies it.
852 send_kx (struct MeshTunnel3 *t,
853 const struct GNUNET_MessageHeader *message)
855 struct MeshConnection *c;
856 struct GNUNET_MESH_KX *msg;
857 size_t size = ntohs (message->size);
858 char cbuf[sizeof (struct GNUNET_MESH_KX) + size];
862 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GMT_2s (t));
864 /* Avoid loopback. */
865 if (GMT_is_loopback (t))
867 LOG (GNUNET_ERROR_TYPE_DEBUG, " loopback!\n");
872 /* Must have a connection. */
873 if (NULL == t->connection_head)
875 GNUNET_break (MESH_TUNNEL3_SEARCHING == t->cstate);
880 msg = (struct GNUNET_MESH_KX *) cbuf;
881 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX);
882 msg->header.size = htons (sizeof (struct GNUNET_MESH_KX) + size);
883 c = tunnel_get_connection (t);
886 GNUNET_break (GNUNET_YES == t->destroy || MESH_TUNNEL3_READY != t->cstate);
890 type = ntohs (message->type);
893 case GNUNET_MESSAGE_TYPE_MESH_KX_EPHEMERAL:
894 case GNUNET_MESSAGE_TYPE_MESH_KX_PING:
895 case GNUNET_MESSAGE_TYPE_MESH_KX_PONG:
896 msg->reserved = htonl (0);
897 memcpy (&msg[1], message, size);
900 LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
905 fwd = GMC_is_origin (t->connection_head->c, GNUNET_YES);
906 /* TODO save handle and cancel in case of a unneeded retransmission */
907 GMC_send_prebuilt_message (&msg->header, c, fwd, GNUNET_YES, NULL, NULL);
912 * Send the ephemeral key on a tunnel.
914 * @param t Tunnel on which to send the key.
917 send_ephemeral (struct MeshTunnel3 *t)
919 LOG (GNUNET_ERROR_TYPE_DEBUG, "%s()\n", __FUNCTION__);
921 kx_msg.sender_status = htonl (t->estate);
922 send_kx (t, &kx_msg.header);
926 * Send a ping message on a tunnel.
928 * @param t Tunnel on which to send the ping.
931 send_ping (struct MeshTunnel3 *t)
933 struct GNUNET_MESH_KX_Ping msg;
935 LOG (GNUNET_ERROR_TYPE_DEBUG, "%s()\n", __FUNCTION__);
936 msg.header.size = htons (sizeof (msg));
937 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX_PING);
938 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
939 msg.target = *GMP_get_id (t->peer);
940 msg.nonce = t->kx_ctx->challenge;
942 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
943 LOG (GNUNET_ERROR_TYPE_DEBUG, " towards %s\n", GNUNET_i2s (&msg.target));
944 t_encrypt (t, &msg.target, &msg.target, ping_encryption_size(), msg.iv);
945 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
946 LOG (GNUNET_ERROR_TYPE_DEBUG, " e towards %s\n", GNUNET_i2s (&msg.target));
948 send_kx (t, &msg.header);
953 * Send a pong message on a tunnel.
955 * @param t Tunnel on which to send the pong.
956 * @param challenge Value sent in the ping that we have to send back.
959 send_pong (struct MeshTunnel3 *t, uint32_t challenge)
961 struct GNUNET_MESH_KX_Pong msg;
963 LOG (GNUNET_ERROR_TYPE_DEBUG, "%s()\n", __FUNCTION__);
964 msg.header.size = htons (sizeof (msg));
965 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX_PONG);
966 msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
967 msg.nonce = challenge;
968 LOG (GNUNET_ERROR_TYPE_DEBUG, " sending %u\n", msg.nonce);
969 t_encrypt (t, &msg.nonce, &msg.nonce, sizeof (msg.nonce), msg.iv);
970 LOG (GNUNET_ERROR_TYPE_DEBUG, " e sending %u\n", msg.nonce);
972 send_kx (t, &msg.header);
977 * Initiate a rekey with the remote peer.
979 * @param cls Closure (tunnel).
980 * @param tc TaskContext.
983 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
985 struct MeshTunnel3 *t = cls;
987 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
989 LOG (GNUNET_ERROR_TYPE_DEBUG, "Re-key Tunnel %s\n", GMT_2s (t));
990 if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
993 if (NULL == t->kx_ctx)
995 LOG (GNUNET_ERROR_TYPE_DEBUG, " new kx ctx\n");
996 t->kx_ctx = GNUNET_new (struct MeshTunnelKXCtx);
997 t->kx_ctx->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
999 t->kx_ctx->d_key_old = t->d_key;
1004 case MESH_TUNNEL3_KEY_UNINITIALIZED:
1005 t->estate = MESH_TUNNEL3_KEY_SENT;
1007 case MESH_TUNNEL3_KEY_SENT:
1009 case MESH_TUNNEL3_KEY_PING:
1010 case MESH_TUNNEL3_KEY_OK:
1012 t->estate = MESH_TUNNEL3_KEY_PING;
1015 LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
1018 LOG (GNUNET_ERROR_TYPE_DEBUG, " next call in %s\n",
1019 GNUNET_STRINGS_relative_time_to_string (REKEY_WAIT, GNUNET_YES));
1020 t->rekey_task = GNUNET_SCHEDULER_add_delayed (REKEY_WAIT, &rekey_tunnel, t);
1025 * Out ephemeral key has changed, create new session key on all tunnels.
1027 * @param cls Closure (size of the hashmap).
1028 * @param key Current public key.
1029 * @param value Value in the hash map (tunnel).
1031 * @return #GNUNET_YES, so we should continue to iterate,
1034 rekey_iterator (void *cls,
1035 const struct GNUNET_PeerIdentity *key,
1038 struct MeshTunnel3 *t = value;
1039 struct GNUNET_TIME_Relative delay;
1040 long n = (long) cls;
1043 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
1046 r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
1047 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
1048 t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1055 * Create a new ephemeral key and key message, schedule next rekeying.
1057 * @param cls Closure (unused).
1058 * @param tc TaskContext.
1061 rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1063 struct GNUNET_TIME_Absolute time;
1066 rekey_task = GNUNET_SCHEDULER_NO_TASK;
1068 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1071 GNUNET_free_non_null (my_ephemeral_key);
1072 my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
1074 time = GNUNET_TIME_absolute_get ();
1075 kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
1076 time = GNUNET_TIME_absolute_add (time, rekey_period);
1077 time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
1078 kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
1079 GNUNET_CRYPTO_ecdhe_key_get_public (my_ephemeral_key, &kx_msg.ephemeral_key);
1081 GNUNET_assert (GNUNET_OK ==
1082 GNUNET_CRYPTO_eddsa_sign (my_private_key,
1084 &kx_msg.signature));
1086 n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
1087 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
1089 rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period, &rekey, NULL);
1094 * Called only on shutdown, destroy every tunnel.
1096 * @param cls Closure (unused).
1097 * @param key Current public key.
1098 * @param value Value in the hash map (tunnel).
1100 * @return #GNUNET_YES, so we should continue to iterate,
1103 destroy_iterator (void *cls,
1104 const struct GNUNET_PeerIdentity *key,
1107 struct MeshTunnel3 *t = value;
1115 * Demultiplex data per channel and call appropriate channel handler.
1117 * @param t Tunnel on which the data came.
1118 * @param msg Data message.
1119 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1120 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1121 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1122 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1125 handle_data (struct MeshTunnel3 *t,
1126 const struct GNUNET_MESH_Data *msg,
1129 struct MeshChannel *ch;
1133 size = ntohs (msg->header.size);
1135 sizeof (struct GNUNET_MESH_Data) +
1136 sizeof (struct GNUNET_MessageHeader))
1141 LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
1142 GM_m2s (ntohs (msg[1].header.type)));
1145 ch = GMT_get_channel (t, ntohl (msg->chid));
1148 GNUNET_STATISTICS_update (stats, "# data on unknown channel",
1150 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1155 GMCH_handle_data (ch, msg, fwd);
1160 * Demultiplex data ACKs per channel and update appropriate channel buffer info.
1162 * @param t Tunnel on which the DATA ACK came.
1163 * @param msg DATA ACK message.
1164 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1165 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1166 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1167 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1170 handle_data_ack (struct MeshTunnel3 *t,
1171 const struct GNUNET_MESH_DataACK *msg,
1174 struct MeshChannel *ch;
1178 size = ntohs (msg->header.size);
1179 if (size != sizeof (struct GNUNET_MESH_DataACK))
1186 ch = GMT_get_channel (t, ntohl (msg->chid));
1189 GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
1191 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1196 GMCH_handle_data_ack (ch, msg, fwd);
1201 * Handle channel create.
1203 * @param t Tunnel on which the data came.
1204 * @param msg Data message.
1207 handle_ch_create (struct MeshTunnel3 *t,
1208 const struct GNUNET_MESH_ChannelCreate *msg)
1210 struct MeshChannel *ch;
1214 size = ntohs (msg->header.size);
1215 if (size != sizeof (struct GNUNET_MESH_ChannelCreate))
1222 ch = GMT_get_channel (t, ntohl (msg->chid));
1223 if (NULL != ch && ! GMT_is_loopback (t))
1225 /* Probably a retransmission, safe to ignore */
1226 LOG (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
1230 ch = GMCH_handle_create (t, msg);
1233 GMT_add_channel (t, ch);
1239 * Handle channel NACK: check correctness and call channel handler for NACKs.
1241 * @param t Tunnel on which the NACK came.
1242 * @param msg NACK message.
1245 handle_ch_nack (struct MeshTunnel3 *t,
1246 const struct GNUNET_MESH_ChannelManage *msg)
1248 struct MeshChannel *ch;
1252 size = ntohs (msg->header.size);
1253 if (size != sizeof (struct GNUNET_MESH_ChannelManage))
1260 ch = GMT_get_channel (t, ntohl (msg->chid));
1263 GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
1265 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1270 GMCH_handle_nack (ch);
1275 * Handle a CHANNEL ACK (SYNACK/ACK).
1277 * @param t Tunnel on which the CHANNEL ACK came.
1278 * @param msg CHANNEL ACK message.
1279 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1280 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1281 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1282 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1285 handle_ch_ack (struct MeshTunnel3 *t,
1286 const struct GNUNET_MESH_ChannelManage *msg,
1289 struct MeshChannel *ch;
1293 size = ntohs (msg->header.size);
1294 if (size != sizeof (struct GNUNET_MESH_ChannelManage))
1301 ch = GMT_get_channel (t, ntohl (msg->chid));
1304 GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
1306 LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1311 GMCH_handle_ack (ch, msg, fwd);
1317 * Handle a channel destruction message.
1319 * @param t Tunnel on which the message came.
1320 * @param msg Channel destroy message.
1321 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1322 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1323 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1324 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1327 handle_ch_destroy (struct MeshTunnel3 *t,
1328 const struct GNUNET_MESH_ChannelManage *msg,
1331 struct MeshChannel *ch;
1335 size = ntohs (msg->header.size);
1336 if (size != sizeof (struct GNUNET_MESH_ChannelManage))
1343 ch = GMT_get_channel (t, ntohl (msg->chid));
1346 /* Probably a retransmission, safe to ignore */
1350 GMCH_handle_destroy (ch, msg, fwd);
1355 * The peer's ephemeral key has changed: update the symmetrical keys.
1357 * @param t Tunnel this message came on.
1358 * @param msg Key eXchange message.
1361 handle_ephemeral (struct MeshTunnel3 *t,
1362 const struct GNUNET_MESH_KX_Ephemeral *msg)
1364 struct GNUNET_HashCode km;
1365 LOG (GNUNET_ERROR_TYPE_DEBUG, " ephemeral key message\n");
1367 if (GNUNET_OK != check_ephemeral (t, msg))
1369 GNUNET_break_op (0);
1372 derive_key_material (&km, &msg->ephemeral_key);
1373 LOG (GNUNET_ERROR_TYPE_DEBUG, " km is %s\n", GNUNET_h2s (&km));
1374 derive_symmertic (&t->e_key, &my_full_id, GMP_get_id (t->peer), &km);
1375 derive_symmertic (&t->d_key, GMP_get_id (t->peer), &my_full_id, &km);
1376 if (MESH_TUNNEL3_KEY_SENT == t->estate)
1378 LOG (GNUNET_ERROR_TYPE_DEBUG, " our key was sent, send ping\n");
1380 t->estate = MESH_TUNNEL3_KEY_PING;
1386 * Peer wants to check our symmetrical keys by sending an encrypted challenge.
1387 * Answer with by retransmitting the challenge with the "opposite" key.
1389 * @param t Tunnel this message came on.
1390 * @param msg Key eXchange Ping message.
1393 handle_ping (struct MeshTunnel3 *t,
1394 const struct GNUNET_MESH_KX_Ping *msg)
1396 struct GNUNET_MESH_KX_Ping res;
1398 if (ntohs (msg->header.size) != sizeof (res))
1400 GNUNET_break_op (0);
1404 LOG (GNUNET_ERROR_TYPE_DEBUG, " ping message\n");
1405 t_decrypt (t, &res.target, &msg->target, ping_encryption_size (), msg->iv);
1406 if (0 != memcmp (&my_full_id, &res.target, sizeof (my_full_id)))
1408 GNUNET_break_op (0);
1409 LOG (GNUNET_ERROR_TYPE_DEBUG, " e got %u\n", msg->nonce);
1410 LOG (GNUNET_ERROR_TYPE_DEBUG, " e towards %s\n", GNUNET_i2s (&msg->target));
1411 LOG (GNUNET_ERROR_TYPE_DEBUG, " got %u\n", res.nonce);
1412 LOG (GNUNET_ERROR_TYPE_DEBUG, " towards %s\n", GNUNET_i2s (&res.target));
1416 send_pong (t, res.nonce);
1421 * Peer has answer to our challenge.
1422 * If answer is successful, consider the key exchange finished and clean
1423 * up all related state.
1425 * @param t Tunnel this message came on.
1426 * @param msg Key eXchange Pong message.
1429 handle_pong (struct MeshTunnel3 *t,
1430 const struct GNUNET_MESH_KX_Pong *msg)
1434 LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG received\n");
1435 if (GNUNET_SCHEDULER_NO_TASK == t->rekey_task)
1437 GNUNET_break_op (GNUNET_NO != t->destroy);
1440 t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
1442 if (challenge != t->kx_ctx->challenge)
1444 LOG (GNUNET_ERROR_TYPE_DEBUG,
1445 "Wrong PONG challenge: %u (e: %u). Expected: %u.\n",
1446 challenge, msg->nonce, t->kx_ctx->challenge);
1447 GNUNET_break_op (0);
1450 GNUNET_SCHEDULER_cancel (t->rekey_task);
1451 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1452 GNUNET_free (t->kx_ctx);
1454 GMT_change_estate (t, MESH_TUNNEL3_KEY_OK);
1459 * Demultiplex by message type and call appropriate handler for a message
1460 * towards a channel of a local tunnel.
1462 * @param t Tunnel this message came on.
1463 * @param msgh Message header.
1464 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1465 * #GNUNET_YES if message is FWD on the respective channel (loopback)
1466 * #GNUNET_NO if message is BCK on the respective channel (loopback)
1467 * #GNUNET_SYSERR if message on a one-ended channel (remote)
1470 handle_decrypted (struct MeshTunnel3 *t,
1471 const struct GNUNET_MessageHeader *msgh,
1476 type = ntohs (msgh->type);
1477 LOG (GNUNET_ERROR_TYPE_DEBUG,
1478 "Got a %s message!\n",
1483 case GNUNET_MESSAGE_TYPE_MESH_DATA:
1484 /* Don't send hop ACK, wait for client to ACK */
1485 handle_data (t, (struct GNUNET_MESH_Data *) msgh, fwd);
1488 case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
1489 handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh, fwd);
1492 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
1493 handle_ch_create (t,
1494 (struct GNUNET_MESH_ChannelCreate *) msgh);
1497 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_NACK:
1499 (struct GNUNET_MESH_ChannelManage *) msgh);
1502 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
1504 (struct GNUNET_MESH_ChannelManage *) msgh,
1508 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
1509 handle_ch_destroy (t,
1510 (struct GNUNET_MESH_ChannelManage *) msgh,
1515 GNUNET_break_op (0);
1516 LOG (GNUNET_ERROR_TYPE_DEBUG,
1517 "end-to-end message not known (%u)\n",
1518 ntohs (msgh->type));
1522 /******************************************************************************/
1523 /******************************** API ***********************************/
1524 /******************************************************************************/
1527 * Decrypt and demultiplex by message type. Call appropriate handler
1528 * for every message.
1530 * @param t Tunnel this message came on.
1531 * @param msg Encrypted message.
1534 GMT_handle_encrypted (struct MeshTunnel3 *t,
1535 const struct GNUNET_MESH_Encrypted *msg)
1537 size_t size = ntohs (msg->header.size);
1538 size_t payload_size = size - sizeof (struct GNUNET_MESH_Encrypted);
1539 size_t decrypted_size;
1540 char cbuf [payload_size];
1541 struct GNUNET_MessageHeader *msgh;
1544 decrypted_size = t_decrypt (t, cbuf, &msg[1], payload_size, msg->iv);
1546 while (off < decrypted_size)
1548 msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
1549 handle_decrypted (t, msgh, GNUNET_SYSERR);
1550 off += ntohs (msgh->size);
1556 * Demultiplex an encapsulated KX message by message type.
1558 * @param t Tunnel on which the message came.
1559 * @param message Payload of KX message.
1562 GMT_handle_kx (struct MeshTunnel3 *t,
1563 const struct GNUNET_MessageHeader *message)
1567 type = ntohs (message->type);
1568 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received\n", type);
1571 case GNUNET_MESSAGE_TYPE_MESH_KX_EPHEMERAL:
1572 handle_ephemeral (t, (struct GNUNET_MESH_KX_Ephemeral *) message);
1575 case GNUNET_MESSAGE_TYPE_MESH_KX_PING:
1576 handle_ping (t, (struct GNUNET_MESH_KX_Ping *) message);
1579 case GNUNET_MESSAGE_TYPE_MESH_KX_PONG:
1580 handle_pong (t, (struct GNUNET_MESH_KX_Pong *) message);
1584 GNUNET_break_op (0);
1585 LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message not known (%u)\n", type);
1591 * Initialize the tunnel subsystem.
1593 * @param c Configuration handle.
1594 * @param key ECC private key, to derive all other keys and do crypto.
1597 GMT_init (const struct GNUNET_CONFIGURATION_Handle *c,
1598 const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
1600 LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
1602 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
1605 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1606 "MESH", "DEFAULT_TTL", "USING DEFAULT");
1610 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REKEY_PERIOD",
1613 rekey_period = GNUNET_TIME_UNIT_DAYS;
1616 my_private_key = key;
1617 kx_msg.header.size = htons (sizeof (kx_msg));
1618 kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX_EPHEMERAL);
1619 kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_MESH_KX);
1620 kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
1621 kx_msg.origin_identity = my_full_id;
1622 rekey_task = GNUNET_SCHEDULER_add_now (&rekey, NULL);
1624 tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
1629 * Shut down the tunnel subsystem.
1634 if (GNUNET_SCHEDULER_NO_TASK != rekey_task)
1636 GNUNET_SCHEDULER_cancel (rekey_task);
1637 rekey_task = GNUNET_SCHEDULER_NO_TASK;
1639 GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
1640 GNUNET_CONTAINER_multipeermap_destroy (tunnels);
1647 * @param destination Peer this tunnel is towards.
1649 struct MeshTunnel3 *
1650 GMT_new (struct MeshPeer *destination)
1652 struct MeshTunnel3 *t;
1654 t = GNUNET_new (struct MeshTunnel3);
1656 t->peer = destination;
1659 GNUNET_CONTAINER_multipeermap_put (tunnels, GMP_get_id (destination), t,
1660 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
1671 * Change the tunnel's connection state.
1673 * @param t Tunnel whose connection state to change.
1674 * @param cstate New connection state.
1677 GMT_change_cstate (struct MeshTunnel3* t, enum MeshTunnel3CState cstate)
1681 LOG (GNUNET_ERROR_TYPE_DEBUG,
1682 "Tunnel %s cstate was %s\n",
1683 GMP_2s (t->peer), cstate2s (t->cstate));
1684 LOG (GNUNET_ERROR_TYPE_DEBUG,
1685 "Tunnel %s cstate is now %s\n",
1686 GMP_2s (t->peer), cstate2s (cstate));
1687 if (myid != GMP_get_short_id (t->peer) &&
1688 MESH_TUNNEL3_READY != t->cstate &&
1689 MESH_TUNNEL3_READY == cstate)
1692 if (MESH_TUNNEL3_KEY_OK == t->estate)
1694 LOG (GNUNET_ERROR_TYPE_DEBUG, " triggered send queued data\n");
1695 send_queued_data (t);
1697 else if (MESH_TUNNEL3_KEY_UNINITIALIZED == t->estate)
1699 LOG (GNUNET_ERROR_TYPE_DEBUG, " triggered rekey\n");
1700 rekey_tunnel (t, NULL);
1705 if (MESH_TUNNEL3_READY == cstate && 3 <= GMT_count_connections (t))
1707 GMP_stop_search (t->peer);
1712 * Change the tunnel encryption state.
1714 * @param t Tunnel whose encryption state to change.
1715 * @param state New encryption state.
1718 GMT_change_estate (struct MeshTunnel3* t, enum MeshTunnel3EState state)
1722 LOG (GNUNET_ERROR_TYPE_DEBUG,
1723 "Tunnel %s estate was %s\n",
1724 GMP_2s (t->peer), estate2s (t->estate));
1725 LOG (GNUNET_ERROR_TYPE_DEBUG,
1726 "Tunnel %s estate is now %s\n",
1727 GMP_2s (t->peer), estate2s (state));
1728 if (myid != GMP_get_short_id (t->peer) &&
1729 MESH_TUNNEL3_KEY_OK != t->estate && MESH_TUNNEL3_KEY_OK == state)
1732 send_queued_data (t);
1740 * Add a connection to a tunnel.
1743 * @param c Connection.
1746 GMT_add_connection (struct MeshTunnel3 *t, struct MeshConnection *c)
1748 struct MeshTConnection *aux;
1750 GNUNET_assert (NULL != c);
1752 for (aux = t->connection_head; aux != NULL; aux = aux->next)
1756 aux = GNUNET_new (struct MeshTConnection);
1758 GNUNET_CONTAINER_DLL_insert_tail (t->connection_head, t->connection_tail, aux);
1763 * Mark a path as no longer valid for this tunnel: has been tried and failed.
1765 * @param t Tunnel to update.
1766 * @param path Invalid path to remove. Is destroyed after removal.
1769 GMT_remove_path (struct MeshTunnel3 *t, struct MeshPeerPath *path)
1771 GMP_remove_path (t->peer, path);
1776 * Remove a connection from a tunnel.
1779 * @param c Connection.
1782 GMT_remove_connection (struct MeshTunnel3 *t,
1783 struct MeshConnection *c)
1785 struct MeshTConnection *aux;
1786 struct MeshTConnection *next;
1788 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
1789 GMC_2s (c), GMT_2s (t));
1790 for (aux = t->connection_head; aux != NULL; aux = next)
1795 GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
1800 /* Start new connections if needed */
1801 if (NULL == t->connection_head
1802 && GNUNET_NO == t->destroy
1803 && GNUNET_NO == shutting_down)
1805 LOG (GNUNET_ERROR_TYPE_DEBUG, " no more connections, getting new ones\n");
1806 GMP_connect (t->peer);
1807 t->cstate = MESH_TUNNEL3_SEARCHING;
1811 /* If not marked as ready, no change is needed */
1812 if (MESH_TUNNEL3_READY != t->cstate)
1815 /* Check if any connection is ready to maintaing cstate */
1816 for (aux = t->connection_head; aux != NULL; aux = aux->next)
1817 if (MESH_CONNECTION_READY == GMC_get_state (aux->c))
1820 t->cstate = MESH_TUNNEL3_WAITING;
1825 * Add a channel to a tunnel.
1828 * @param ch Channel.
1831 GMT_add_channel (struct MeshTunnel3 *t, struct MeshChannel *ch)
1833 struct MeshTChannel *aux;
1835 GNUNET_assert (NULL != ch);
1837 LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
1839 for (aux = t->channel_head; aux != NULL; aux = aux->next)
1841 LOG (GNUNET_ERROR_TYPE_DEBUG, " already there %p\n", aux->ch);
1846 aux = GNUNET_new (struct MeshTChannel);
1848 LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
1849 GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
1851 if (GNUNET_YES == t->destroy)
1853 t->destroy = GNUNET_NO;
1854 LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
1860 * Remove a channel from a tunnel.
1863 * @param ch Channel.
1866 GMT_remove_channel (struct MeshTunnel3 *t, struct MeshChannel *ch)
1868 struct MeshTChannel *aux;
1870 LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
1871 for (aux = t->channel_head; aux != NULL; aux = aux->next)
1875 LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GMCH_2s (ch));
1876 GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
1885 * Search for a channel by global ID.
1887 * @param t Tunnel containing the channel.
1888 * @param chid Public channel number.
1890 * @return channel handler, NULL if doesn't exist
1892 struct MeshChannel *
1893 GMT_get_channel (struct MeshTunnel3 *t, MESH_ChannelNumber chid)
1895 struct MeshTChannel *iter;
1900 for (iter = t->channel_head; NULL != iter; iter = iter->next)
1902 if (GMCH_get_id (iter->ch) == chid)
1906 return NULL == iter ? NULL : iter->ch;
1911 * Tunnel is empty: destroy it.
1913 * Notifies all connections about the destruction.
1915 * @param t Tunnel to destroy.
1918 GMT_destroy_empty (struct MeshTunnel3 *t)
1920 struct MeshTConnection *iter;
1922 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel empty: destroying scheduled\n");
1923 for (iter = t->connection_head; NULL != iter; iter = iter->next)
1925 GMC_send_destroy (iter->c);
1928 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
1930 t->estate = MESH_TUNNEL3_KEY_UNINITIALIZED;
1931 GNUNET_SCHEDULER_cancel (t->rekey_task);
1932 t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1933 GNUNET_free (t->kx_ctx);
1936 t->cstate = MESH_TUNNEL3_NEW;
1937 t->destroy = GNUNET_YES;
1942 * Destroy tunnel if empty (no more channels).
1944 * @param t Tunnel to destroy if empty.
1947 GMT_destroy_if_empty (struct MeshTunnel3 *t)
1949 if (1 < GMT_count_channels (t))
1952 GMT_destroy_empty (t);
1957 * Destroy the tunnel.
1959 * This function does not generate any warning traffic to clients or peers.
1962 * Cancel messages belonging to this tunnel queued to neighbors.
1963 * Free any allocated resources linked to the tunnel.
1965 * @param t The tunnel to destroy.
1968 GMT_destroy (struct MeshTunnel3 *t)
1970 struct MeshTConnection *iter_c;
1971 struct MeshTConnection *next_c;
1972 struct MeshTChannel *iter_ch;
1973 struct MeshTChannel *next_ch;
1980 LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GMP_2s (t->peer));
1982 GNUNET_break (GNUNET_YES ==
1983 GNUNET_CONTAINER_multipeermap_remove (tunnels,
1984 GMP_get_id (t->peer), t));
1986 for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
1988 next_c = iter_c->next;
1989 GMC_destroy (iter_c->c);
1991 for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
1993 next_ch = iter_ch->next;
1994 GMCH_destroy (iter_ch->ch);
1995 /* Should only happen on shutdown, but it's ok. */
1998 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
1999 GMP_set_tunnel (t->peer, NULL);
2001 if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
2002 GNUNET_SCHEDULER_cancel (t->rekey_task);
2009 * @brief Use the given path for the tunnel.
2010 * Update the next and prev hops (and RCs).
2011 * (Re)start the path refresh in case the tunnel is locally owned.
2013 * @param t Tunnel to update.
2014 * @param p Path to use.
2016 * @return Connection created.
2018 struct MeshConnection *
2019 GMT_use_path (struct MeshTunnel3 *t, struct MeshPeerPath *p)
2021 struct MeshConnection *c;
2022 struct GNUNET_HashCode cid;
2023 unsigned int own_pos;
2025 if (NULL == t || NULL == p)
2031 for (own_pos = 0; own_pos < p->length; own_pos++)
2033 if (p->peers[own_pos] == myid)
2036 if (own_pos > p->length - 1)
2038 GNUNET_break_op (0);
2042 GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE, &cid);
2043 c = GMC_new (&cid, t, p, own_pos);
2046 /* Path was flawed */
2049 GMT_add_connection (t, c);
2055 * Count established (ready) connections of a tunnel.
2057 * @param t Tunnel on which to count.
2059 * @return Number of connections.
2062 GMT_count_connections (struct MeshTunnel3 *t)
2064 struct MeshTConnection *iter;
2067 for (count = 0, iter = t->connection_head;
2069 iter = iter->next, count++);
2075 * Count channels of a tunnel.
2077 * @param t Tunnel on which to count.
2079 * @return Number of channels.
2082 GMT_count_channels (struct MeshTunnel3 *t)
2084 struct MeshTChannel *iter;
2087 for (count = 0, iter = t->channel_head;
2089 iter = iter->next, count++) /* skip */;
2096 * Get the connectivity state of a tunnel.
2100 * @return Tunnel's connectivity state.
2102 enum MeshTunnel3CState
2103 GMT_get_cstate (struct MeshTunnel3 *t)
2108 return (enum MeshTunnel3CState) -1;
2115 * Get the maximum buffer space for a tunnel towards a local client.
2119 * @return Biggest buffer space offered by any channel in the tunnel.
2122 GMT_get_channels_buffer (struct MeshTunnel3 *t)
2124 struct MeshTChannel *iter;
2125 unsigned int buffer;
2126 unsigned int ch_buf;
2128 if (NULL == t->channel_head)
2130 /* Probably getting buffer for a channel create/handshake. */
2135 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2137 ch_buf = get_channel_buffer (iter);
2138 if (ch_buf > buffer)
2146 * Get the total buffer space for a tunnel for P2P traffic.
2150 * @return Buffer space offered by all connections in the tunnel.
2153 GMT_get_connections_buffer (struct MeshTunnel3 *t)
2155 struct MeshTConnection *iter;
2156 unsigned int buffer;
2159 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2161 if (GMC_get_state (iter->c) != MESH_CONNECTION_READY)
2165 buffer += get_connection_buffer (iter);
2173 * Get the tunnel's destination.
2177 * @return ID of the destination peer.
2179 const struct GNUNET_PeerIdentity *
2180 GMT_get_destination (struct MeshTunnel3 *t)
2182 return GMP_get_id (t->peer);
2187 * Get the tunnel's next free global channel ID.
2191 * @return GID of a channel free to use.
2194 GMT_get_next_chid (struct MeshTunnel3 *t)
2196 MESH_ChannelNumber chid;
2197 MESH_ChannelNumber mask;
2200 /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
2201 * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
2202 * If peer's ID is bigger, start at 0x4... bit 30 = 1
2204 result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GMP_get_id (t->peer));
2210 while (NULL != GMT_get_channel (t, t->next_chid))
2212 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
2213 t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
2214 t->next_chid |= mask;
2216 chid = t->next_chid;
2217 t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
2218 t->next_chid |= mask;
2225 * Send ACK on one or more channels due to buffer in connections.
2227 * @param t Channel which has some free buffer space.
2230 GMT_unchoke_channels (struct MeshTunnel3 *t)
2232 struct MeshTChannel *iter;
2233 unsigned int buffer;
2234 unsigned int channels = GMT_count_channels (t);
2235 unsigned int choked_n;
2236 struct MeshChannel *choked[channels];
2238 LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT_unchoke_channels on %s\n", GMT_2s (t));
2239 LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
2240 if (NULL != t->channel_head)
2241 LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
2243 /* Get buffer space */
2244 buffer = GMT_get_connections_buffer (t);
2250 /* Count and remember choked channels */
2252 for (iter = t->channel_head; NULL != iter; iter = iter->next)
2254 if (GNUNET_NO == get_channel_allowed (iter))
2256 choked[choked_n++] = iter->ch;
2260 /* Unchoke random channels */
2261 while (0 < buffer && 0 < choked_n)
2263 unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2265 GMCH_allow_client (choked[r], GMCH_is_origin (choked[r], GNUNET_YES));
2268 choked[r] = choked[choked_n];
2274 * Send ACK on one or more connections due to buffer space to the client.
2276 * Iterates all connections of the tunnel and sends ACKs appropriately.
2281 GMT_send_connection_acks (struct MeshTunnel3 *t)
2283 struct MeshTConnection *iter;
2286 uint32_t allow_per_connection;
2288 unsigned int buffer;
2290 LOG (GNUNET_ERROR_TYPE_DEBUG,
2291 "Tunnel send connection ACKs on %s\n",
2300 buffer = GMT_get_channels_buffer (t);
2302 /* Count connections, how many messages are already allowed */
2303 cs = GMT_count_connections (t);
2304 for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2306 allowed += get_connection_allowed (iter);
2309 /* Make sure there is no overflow */
2310 if (allowed > buffer)
2315 /* Authorize connections to send more data */
2316 to_allow = buffer; /* - allowed; */
2318 for (iter = t->connection_head; NULL != iter && to_allow > 0; iter = iter->next)
2320 allow_per_connection = to_allow/cs;
2321 to_allow -= allow_per_connection;
2323 if (get_connection_allowed (iter) > 64 / 3)
2327 GMC_allow (iter->c, buffer, GMC_is_origin (iter->c, GNUNET_YES));
2330 GNUNET_break (to_allow == 0);
2335 * Cancel a previously sent message while it's in the queue.
2337 * ONLY can be called before the continuation given to the send function
2338 * is called. Once the continuation is called, the message is no longer in the
2341 * @param q Handle to the queue.
2344 GMT_cancel (struct MeshTunnel3Queue *q)
2349 /* message_sent() will be called and free q */
2351 else if (NULL != q->tqd)
2353 unqueue_data (q->tqd);
2363 * Sends an already built message on a tunnel, encrypting it and
2364 * choosing the best connection.
2366 * @param message Message to send. Function modifies it.
2367 * @param t Tunnel on which this message is transmitted.
2368 * @param force Force the tunnel to take the message (buffer overfill).
2369 * @param cont Continuation to call once message is really sent.
2370 * @param cont_cls Closure for @c cont.
2372 * @return Handle to cancel message. NULL if @c cont is NULL.
2374 struct MeshTunnel3Queue *
2375 GMT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
2376 struct MeshTunnel3 *t, int force,
2377 GMT_sent cont, void *cont_cls)
2379 return send_prebuilt_message (message, t, force, cont, cont_cls, NULL);
2384 * Is the tunnel directed towards the local peer?
2388 * @return #GNUNET_YES if it is loopback.
2391 GMT_is_loopback (const struct MeshTunnel3 *t)
2393 return (myid == GMP_get_short_id (t->peer));
2398 * Is the tunnel this path already?
2403 * @return #GNUNET_YES a connection uses this path.
2406 GMT_is_path_used (const struct MeshTunnel3 *t, const struct MeshPeerPath *p)
2408 struct MeshTConnection *iter;
2410 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2411 if (GMC_get_path (iter->c) == p)
2419 * Get a cost of a path for a tunnel considering existing connections.
2422 * @param path Candidate path.
2424 * @return Cost of the path (path length + number of overlapping nodes)
2427 GMT_get_path_cost (const struct MeshTunnel3 *t,
2428 const struct MeshPeerPath *path)
2430 struct MeshTConnection *iter;
2431 const struct MeshPeerPath *aux;
2432 unsigned int overlap;
2440 GNUNET_assert (NULL != t);
2442 for (i = 0; i < path->length; i++)
2444 for (iter = t->connection_head; NULL != iter; iter = iter->next)
2446 aux = GMC_get_path (iter->c);
2450 for (j = 0; j < aux->length; j++)
2452 if (path->peers[i] == aux->peers[j])
2460 return (path->length + overlap) * (path->score * -1);
2465 * Get the static string for the peer this tunnel is directed.
2469 * @return Static string the destination peer's ID.
2472 GMT_2s (const struct MeshTunnel3 *t)
2477 return GMP_2s (t->peer);
2482 * Log all possible info about the tunnel state.
2484 * @param t Tunnel to debug.
2487 GMT_debug (const struct MeshTunnel3 *t)
2489 struct MeshTChannel *iterch;
2490 struct MeshTConnection *iterc;
2492 LOG (GNUNET_ERROR_TYPE_DEBUG, "DEBUG %s\n", GMT_2s (t));
2493 LOG (GNUNET_ERROR_TYPE_DEBUG, " cstate %s, estate %s\n",
2494 cstate2s (t->cstate), estate2s (t->estate));
2496 LOG (GNUNET_ERROR_TYPE_DEBUG, " channels:\n");
2497 for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
2499 LOG (GNUNET_ERROR_TYPE_DEBUG, " - %s\n", GMCH_2s (iterch->ch));
2502 LOG (GNUNET_ERROR_TYPE_DEBUG, " connections:\n");
2503 for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
2505 LOG (GNUNET_ERROR_TYPE_DEBUG, " - %s\n", GMC_2s (iterc->c));
2508 LOG (GNUNET_ERROR_TYPE_DEBUG, "DEBUG END\n");