2 This file is part of GNUnet.
3 (C) 2001-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 * @file mesh/gnunet-service-mesh-enc.c
23 * @brief GNUnet MESH service with encryption
24 * @author Bartlomiej Polot
27 * - when sending in-order buffered data, wait for client ACKs
30 * - set connection IDs independently from tunnel, tunnel has no ID
33 * - relay corking down to core
34 * - set ttl relative to path length
38 * - peer: other mesh instance. If there is direct connection it's a neighbor.
39 * - tunnel: encrypted connection to a peer, neighbor or not.
40 * - channel: connection between two clients, on the same or different peers.
41 * have properties like reliability.
42 * - path: series of directly connected peer from one peer to another.
43 * - connection: path which is being used in a tunnel.
47 #include "gnunet_util_lib.h"
49 #include "block_mesh.h"
50 #include "gnunet_statistics_service.h"
52 #include "gnunet-service-mesh_local.h"
53 #include "gnunet-service-mesh_channel.h"
54 #include "gnunet-service-mesh_connection.h"
55 #include "gnunet-service-mesh_dht.h"
56 #include "gnunet-service-mesh_peer.h"
58 #define MESH_BLOOM_SIZE 128
61 #define MESH_DEBUG_TIMING __LINUX__ && GNUNET_NO
68 struct timespec __mesh_start;
69 struct timespec __mesh_end;
70 #define INTERVAL_START clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &(__mesh_start))
71 #define INTERVAL_END \
73 clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &(__mesh_end));\
74 double __diff = __mesh_end.tv_nsec - __mesh_start.tv_nsec;\
75 if (__diff < 0) __diff += 1000000000;\
79 #define INTERVAL_SHOW \
81 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "AVG process time: %f ns\n", __sum/__count)
83 #define INTERVAL_START
89 * All the states a tunnel can be in.
94 * Uninitialized status, should never appear in operation.
99 * Path to the peer not known yet
101 MESH_TUNNEL_SEARCHING,
104 * Request sent, not yet answered.
109 * Peer connected and ready to accept data
114 * Peer connected previosly but not responding
116 MESH_TUNNEL_RECONNECTING
121 /******************************************************************************/
122 /************************ DATA STRUCTURES ****************************/
123 /******************************************************************************/
125 /** FWD declaration */
130 * Struct used to queue messages in a tunnel.
132 struct MeshTunnelQueue
137 struct MeshTunnelQueue *next;
138 struct MeshTunnelQueue *prev;
143 struct MeshChannel *ch;
148 /* struct GNUNET_MessageHeader *msg; */
153 * Struct containing all information regarding a tunnel to a peer.
158 * Endpoint of the tunnel.
160 struct MeshPeer *peer;
163 * State of the tunnel.
165 enum MeshTunnelState state;
168 * Local peer ephemeral private key
170 struct GNUNET_CRYPTO_EccPrivateKey *my_eph_key;
173 * Local peer ephemeral public key
175 struct GNUNET_CRYPTO_EccPublicSignKey *my_eph;
178 * Remote peer's public key.
180 struct GNUNET_CRYPTO_EccPublicSignKey *peers_eph;
183 * Encryption ("our") key.
185 struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
188 * Decryption ("their") key.
190 struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
193 * Paths that are actively used to reach the destination peer.
195 struct MeshConnection *connection_head;
196 struct MeshConnection *connection_tail;
199 * Next connection number.
204 * Channels inside this tunnel.
206 struct MeshChannel *channel_head;
207 struct MeshChannel *channel_tail;
210 * Channel ID for the next created channel.
212 MESH_ChannelNumber next_chid;
215 * Channel ID for the next incoming channel.
217 MESH_ChannelNumber next_local_chid;
220 * Pending message count.
222 int pending_messages;
225 * Destroy flag: if true, destroy on last message.
230 * Queued messages, to transmit once tunnel gets connected.
232 struct MeshTunnelQueue *tq_head;
233 struct MeshTunnelQueue *tq_tail;
238 /******************************************************************************/
239 /************************ DEBUG FUNCTIONS ****************************/
240 /******************************************************************************/
244 * GNUNET_SCHEDULER_Task for printing a message after some operation is done
245 * @param cls string to print
246 * @param success GNUNET_OK if the PUT was transmitted,
247 * GNUNET_NO on timeout,
248 * GNUNET_SYSERR on disconnect from service
249 * after the PUT message was transmitted
250 * (so we don't know if it was received or not)
255 mesh_debug (void *cls, int success)
259 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s (%d)\n", s, success);
265 /******************************************************************************/
266 /*********************** GLOBAL VARIABLES ****************************/
267 /******************************************************************************/
269 /************************** Configuration parameters **************************/
273 * Maximum time allowed to connect to a peer found by string.
275 static struct GNUNET_TIME_Relative connect_timeout;
278 * Default TTL for payload packets.
280 static unsigned long long default_ttl;
283 * Percentage of messages that will be dropped (for test purposes only).
285 static unsigned long long drop_percent;
287 /*************************** Static global variables **************************/
290 * Handle to the statistics service.
292 static struct GNUNET_STATISTICS_Handle *stats;
295 * Local peer own ID (memory efficient handle).
297 static GNUNET_PEER_Id myid;
300 * Local peer own ID (full value).
302 static struct GNUNET_PeerIdentity my_full_id;
307 static struct GNUNET_CRYPTO_EccPrivateKey *my_private_key;
310 /******************************************************************************/
311 /*********************** DECLARATIONS **************************/
312 /******************************************************************************/
315 * Function to process paths received for a new peer addition. The recorded
316 * paths form the initial tunnel, which can be optimized later.
317 * Called on each result obtained for the DHT search.
320 * @param exp when will this value expire
321 * @param key key of the result
322 * @param type type of the result
323 * @param size number of bytes in data
324 * @param data pointer to the result data
327 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
328 const struct GNUNET_HashCode * key,
329 const struct GNUNET_PeerIdentity *get_path,
330 unsigned int get_path_length,
331 const struct GNUNET_PeerIdentity *put_path,
332 unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
333 size_t size, const void *data);
337 * Retrieve the MeshPeer stucture associated with the peer, create one
338 * and insert it in the appropriate structures if the peer is not known yet.
340 * @param peer Full identity of the peer.
342 * @return Existing or newly created peer info.
344 static struct MeshPeer *
345 peer_get (const struct GNUNET_PeerIdentity *peer);
349 * Retrieve the MeshPeer stucture associated with the peer, create one
350 * and insert it in the appropriate structures if the peer is not known yet.
352 * @param peer Short identity of the peer.
354 * @return Existing or newly created peer info.
356 static struct MeshPeer *
357 peer_get_short (const GNUNET_PEER_Id peer);
361 * Build a PeerPath from the paths returned from the DHT, reversing the paths
362 * to obtain a local peer -> destination path and interning the peer ids.
364 * @return Newly allocated and created path
366 static struct MeshPeerPath *
367 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
368 unsigned int get_path_length,
369 const struct GNUNET_PeerIdentity *put_path,
370 unsigned int put_path_length);
374 * Adds a path to the data structs of all the peers in the path
376 * @param p Path to process.
377 * @param confirmed Whether we know if the path works or not.
380 path_add_to_peers (struct MeshPeerPath *p, int confirmed);
384 * Change the tunnel state.
386 * @param t Tunnel whose state to change.
387 * @param state New state.
390 tunnel_change_state (struct MeshTunnel2 *t, enum MeshTunnelState state);
394 * Notify a tunnel that a connection has broken that affects at least
397 * @param t Tunnel affected.
398 * @param p1 Peer that got disconnected from p2.
399 * @param p2 Peer that got disconnected from p1.
401 * @return Short ID of the peer disconnected (either p1 or p2).
402 * 0 if the tunnel remained unaffected.
404 static GNUNET_PEER_Id
405 tunnel_notify_connection_broken (struct MeshTunnel2 *t,
406 GNUNET_PEER_Id p1, GNUNET_PEER_Id p2);
409 * @brief Use the given path for the tunnel.
410 * Update the next and prev hops (and RCs).
411 * (Re)start the path refresh in case the tunnel is locally owned.
413 * @param t Tunnel to update.
414 * @param p Path to use.
416 * @return Connection created.
418 static struct MeshConnection *
419 tunnel_use_path (struct MeshTunnel2 *t, struct MeshPeerPath *p);
422 * Tunnel is empty: destroy it.
424 * Notifies all participants (peers, cleints) about the destruction.
426 * @param t Tunnel to destroy.
429 tunnel_destroy_empty (struct MeshTunnel2 *t);
432 * Destroy the tunnel.
434 * This function does not generate any warning traffic to clients or peers.
437 * Cancel messages belonging to this tunnel queued to neighbors.
438 * Free any allocated resources linked to the tunnel.
440 * @param t The tunnel to destroy.
443 tunnel_destroy (struct MeshTunnel2 *t);
447 * Demultiplex by message type and call appropriate handler for a message
448 * towards a channel of a local tunnel.
450 * @param t Tunnel this message came on.
451 * @param msgh Message header.
452 * @param fwd Is this message fwd?
455 handle_decrypted (struct MeshTunnel2 *t,
456 const struct GNUNET_MessageHeader *msgh,
461 * Dummy function to separate declarations from definitions in function list.
464 __mesh_divider______________________________________________________________();
468 * Get string description for tunnel state.
470 * @param s Tunnel state.
472 * @return String representation.
475 GNUNET_MESH_DEBUG_TS2S (enum MeshTunnelState s)
477 static char buf[128];
481 case MESH_TUNNEL_NEW:
482 return "MESH_TUNNEL_NEW";
483 case MESH_TUNNEL_SEARCHING:
484 return "MESH_TUNNEL_SEARCHING";
485 case MESH_TUNNEL_WAITING:
486 return "MESH_TUNNEL_WAITING";
487 case MESH_TUNNEL_READY:
488 return "MESH_TUNNEL_READY";
489 case MESH_TUNNEL_RECONNECTING:
490 return "MESH_TUNNEL_RECONNECTING";
493 sprintf (buf, "%u (UNKNOWN STATE)", s);
500 * Get string description for tunnel state.
502 * @param s Tunnel state.
504 * @return String representation.
507 GNUNET_MESH_DEBUG_CS2S (enum MeshTunnelState s)
511 case MESH_CONNECTION_NEW:
512 return "MESH_CONNECTION_NEW";
513 case MESH_CONNECTION_SENT:
514 return "MESH_CONNECTION_SENT";
515 case MESH_CONNECTION_ACK:
516 return "MESH_CONNECTION_ACK";
517 case MESH_CONNECTION_READY:
518 return "MESH_CONNECTION_READY";
520 return "MESH_CONNECTION_STATE_ERROR";
526 /******************************************************************************/
527 /****************** GENERAL HELPER FUNCTIONS ************************/
528 /******************************************************************************/
532 * Get the static string for a peer ID.
536 * @return Static string for it's ID.
539 peer2s (const struct MeshPeer *peer)
543 return GNUNET_i2s (GNUNET_PEER_resolve2 (peer->id));
549 * Count established (ready) connections of a tunnel.
551 * @param t Tunnel on which to send the message.
553 * @return Number of connections.
556 tunnel_count_connections (struct MeshTunnel2 *t)
558 struct MeshConnection *c;
561 for (c = t->connection_head, i = 0; NULL != c; c = c->next, i++);
568 * Pick a connection on which send the next data message.
570 * @param t Tunnel on which to send the message.
571 * @param fwd Is this a fwd message?
573 * @return The connection on which to send the next message.
575 static struct MeshConnection *
576 tunnel_get_connection (struct MeshTunnel2 *t, int fwd)
578 struct MeshConnection *c;
579 struct MeshConnection *best;
580 struct MeshFlowControl *fc;
581 unsigned int lowest_q;
583 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n",
587 for (c = t->connection_head; NULL != c; c = c->next)
589 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " connection %s: %u\n",
590 GNUNET_h2s (&c->id), c->state);
591 if (MESH_CONNECTION_READY == c->state)
593 fc = fwd ? &c->fwd_fc : &c->bck_fc;
599 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " q_n %u, \n", fc->queue_n);
600 if (fc->queue_n < lowest_q)
603 lowest_q = fc->queue_n;
614 * Get the total buffer space for a tunnel.
617 * @param fwd Is this for FWD traffic?
619 * @return Buffer space offered by all connections in the tunnel.
622 tunnel_get_buffer (struct MeshTunnel2 *t, int fwd)
624 struct MeshConnection *c;
625 struct MeshFlowControl *fc;
628 c = t->connection_head;
631 /* If terminal, return biggest channel buffer */
632 if (NULL == c || GMC_is_terminal (c, fwd))
634 struct MeshChannel *ch;
637 if (NULL == t->channel_head)
640 for (ch = t->channel_head; NULL != ch; ch = ch->next)
642 ch_buf = channel_get_buffer (ch, fwd);
649 /* If not terminal, return sum of connection buffers */
652 if (c->state != MESH_CONNECTION_READY)
658 fc = fwd ? &c->fwd_fc : &c->bck_fc;
659 buffer += fc->queue_max - fc->queue_n;
668 * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
669 * Encrypt data with the tunnel key.
671 * @param t Tunnel whose key to use.
672 * @param dst Destination for the encrypted data.
673 * @param src Source of the plaintext.
674 * @param size Size of the plaintext.
675 * @param iv Initialization Vector to use.
676 * @param fwd Is this a fwd message?
679 tunnel_encrypt (struct MeshTunnel2 *t,
680 void *dst, const void *src,
681 size_t size, uint64_t iv, int fwd)
683 memcpy (dst, src, size);
688 * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
689 * Decrypt data with the tunnel key.
691 * @param t Tunnel whose key to use.
692 * @param dst Destination for the plaintext.
693 * @param src Source of the encrypted data.
694 * @param size Size of the encrypted data.
695 * @param iv Initialization Vector to use.
696 * @param fwd Is this a fwd message?
699 tunnel_decrypt (struct MeshTunnel2 *t,
700 void *dst, const void *src,
701 size_t size, uint64_t iv, int fwd)
703 memcpy (dst, src, size);
708 * Sends an already built message on a tunnel, choosing the best connection.
710 * @param message Message to send. Function modifies it.
711 * @param t Tunnel on which this message is transmitted.
712 * @param ch Channel on which this message is transmitted.
713 * @param fwd Is this a fwd message?
716 send_prebuilt_message_tunnel (struct GNUNET_MESH_Encrypted *msg,
717 struct MeshTunnel2 *t,
718 struct MeshChannel *ch,
721 struct MeshConnection *c;
724 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send on Tunnel %s\n",
726 c = tunnel_get_connection (t, fwd);
729 GNUNET_break (GNUNET_YES == t->destroy);
732 type = ntohs (msg->header.type);
735 case GNUNET_MESSAGE_TYPE_MESH_FWD:
736 case GNUNET_MESSAGE_TYPE_MESH_BCK:
737 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
738 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
740 msg->ttl = htonl (default_ttl);
743 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
744 GNUNET_MESH_DEBUG_M2S (type));
749 send_prebuilt_message_connection (&msg->header, c, ch, fwd);
755 * Sends a CREATE CONNECTION message for a path to a peer.
756 * Changes the connection and tunnel states if necessary.
758 * @param connection Connection to create.
761 send_connection_create (struct MeshConnection *connection)
763 struct MeshTunnel2 *t;
766 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send connection create\n");
768 GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
769 sizeof (struct GNUNET_MESH_ConnectionCreate) +
770 (connection->path->length *
771 sizeof (struct GNUNET_PeerIdentity)),
776 (MESH_TUNNEL_SEARCHING == t->state || MESH_TUNNEL_NEW == t->state))
777 tunnel_change_state (t, MESH_TUNNEL_WAITING);
778 if (MESH_CONNECTION_NEW == connection->state)
779 connection_change_state (connection, MESH_CONNECTION_SENT);
784 * Sends a CONNECTION ACK message in reponse to a received CONNECTION_CREATE
787 * @param connection Connection to confirm.
788 * @param fwd Is this a fwd ACK? (First is bck (SYNACK), second is fwd (ACK))
791 send_connection_ack (struct MeshConnection *connection, int fwd)
793 struct MeshTunnel2 *t;
796 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send connection ack\n");
798 GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
799 sizeof (struct GNUNET_MESH_ConnectionACK),
803 if (MESH_TUNNEL_NEW == t->state)
804 tunnel_change_state (t, MESH_TUNNEL_WAITING);
805 if (MESH_CONNECTION_READY != connection->state)
806 connection_change_state (connection, MESH_CONNECTION_SENT);
811 * Core callback to write a pre-constructed data packet to core buffer
813 * @param cls Closure (MeshTransmissionDescriptor with data in "data" member).
814 * @param size Number of bytes available in buf.
815 * @param buf Where the to write the message.
817 * @return number of bytes written to buf
820 send_core_data_raw (void *cls, size_t size, void *buf)
822 struct GNUNET_MessageHeader *msg = cls;
825 GNUNET_assert (NULL != msg);
826 total_size = ntohs (msg->size);
828 if (total_size > size)
833 memcpy (buf, msg, total_size);
840 * Function to send a create connection message to a peer.
842 * @param c Connection to create.
843 * @param size number of bytes available in buf
844 * @param buf where the callee should write the message
845 * @return number of bytes written to buf
848 send_core_connection_create (struct MeshConnection *c, size_t size, void *buf)
850 struct GNUNET_MESH_ConnectionCreate *msg;
851 struct GNUNET_PeerIdentity *peer_ptr;
852 struct MeshPeerPath *p = c->path;
856 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION CREATE...\n");
858 sizeof (struct GNUNET_MESH_ConnectionCreate) +
859 p->length * sizeof (struct GNUNET_PeerIdentity);
861 if (size < size_needed || NULL == buf)
866 msg = (struct GNUNET_MESH_ConnectionCreate *) buf;
867 msg->header.size = htons (size_needed);
868 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE);
871 peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
872 for (i = 0; i < p->length; i++)
874 GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
877 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
878 "CONNECTION CREATE (%u bytes long) sent!\n", size_needed);
884 * Creates a path ack message in buf and frees all unused resources.
886 * @param c Connection to send an ACK on.
887 * @param size number of bytes available in buf
888 * @param buf where the callee should write the message
890 * @return number of bytes written to buf
893 send_core_connection_ack (struct MeshConnection *c, size_t size, void *buf)
895 struct GNUNET_MESH_ConnectionACK *msg = buf;
896 struct MeshTunnel2 *t = c->t;
898 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION ACK...\n");
899 GNUNET_assert (NULL != t);
900 if (sizeof (struct GNUNET_MESH_ConnectionACK) > size)
905 msg->header.size = htons (sizeof (struct GNUNET_MESH_ConnectionACK));
906 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK);
910 /* TODO add signature */
912 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CONNECTION ACK sent!\n");
913 return sizeof (struct GNUNET_MESH_ConnectionACK);
918 * Destroy the peer_info and free any allocated resources linked to it
920 * @param peer The peer_info to destroy.
922 * @return GNUNET_OK on success
925 peer_destroy (struct MeshPeer *peer)
927 struct GNUNET_PeerIdentity id;
928 struct MeshPeerPath *p;
929 struct MeshPeerPath *nextp;
931 GNUNET_PEER_resolve (peer->id, &id);
932 GNUNET_PEER_change_rc (peer->id, -1);
935 GNUNET_CONTAINER_multipeermap_remove (peers, &id, peer))
938 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
939 "removing peer %s, not in peermap\n", GNUNET_i2s (&id));
941 if (NULL != peer->dhtget)
943 GNUNET_DHT_get_stop (peer->dhtget);
949 GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
953 tunnel_destroy_empty (peer->tunnel);
960 * Returns if peer is used (has a tunnel, is neighbor).
962 * @peer Peer to check.
964 * @return GNUNET_YES if peer is in use.
967 peer_is_used (struct MeshPeer *peer)
969 struct MeshPeerPath *p;
971 if (NULL != peer->tunnel)
974 for (p = peer->path_head; NULL != p; p = p->next)
984 * Iterator over all the peers to get the oldest timestamp.
986 * @param cls Closure (unsued).
987 * @param key ID of the peer.
988 * @param value Peer_Info of the peer.
991 peer_get_oldest (void *cls,
992 const struct GNUNET_PeerIdentity *key,
995 struct MeshPeer *p = value;
996 struct GNUNET_TIME_Absolute *abs = cls;
998 /* Don't count active peers */
999 if (GNUNET_YES == peer_is_used (p))
1002 if (abs->abs_value_us < p->last_contact.abs_value_us)
1003 abs->abs_value_us = p->last_contact.abs_value_us;
1010 * Iterator over all the peers to remove the oldest entry.
1012 * @param cls Closure (unsued).
1013 * @param key ID of the peer.
1014 * @param value Peer_Info of the peer.
1017 peer_timeout (void *cls,
1018 const struct GNUNET_PeerIdentity *key,
1021 struct MeshPeer *p = value;
1022 struct GNUNET_TIME_Absolute *abs = cls;
1024 if (p->last_contact.abs_value_us == abs->abs_value_us &&
1025 GNUNET_NO == peer_is_used (p))
1035 * Delete oldest unused peer.
1038 peer_delete_oldest (void)
1040 struct GNUNET_TIME_Absolute abs;
1042 abs = GNUNET_TIME_UNIT_FOREVER_ABS;
1044 GNUNET_CONTAINER_multipeermap_iterate (peers,
1047 GNUNET_CONTAINER_multipeermap_iterate (peers,
1054 * Retrieve the MeshPeer stucture associated with the peer, create one
1055 * and insert it in the appropriate structures if the peer is not known yet.
1057 * @param peer Full identity of the peer.
1059 * @return Existing or newly created peer info.
1061 static struct MeshPeer *
1062 peer_get (const struct GNUNET_PeerIdentity *peer_id)
1064 struct MeshPeer *peer;
1066 peer = GNUNET_CONTAINER_multipeermap_get (peers, peer_id);
1069 peer = GNUNET_new (struct MeshPeer);
1070 if (GNUNET_CONTAINER_multipeermap_size (peers) > max_peers)
1072 peer_delete_oldest ();
1074 GNUNET_CONTAINER_multipeermap_put (peers, peer_id, peer,
1075 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1076 peer->id = GNUNET_PEER_intern (peer_id);
1078 peer->last_contact = GNUNET_TIME_absolute_get();
1085 * Retrieve the MeshPeer stucture associated with the peer, create one
1086 * and insert it in the appropriate structures if the peer is not known yet.
1088 * @param peer Short identity of the peer.
1090 * @return Existing or newly created peer info.
1092 static struct MeshPeer *
1093 peer_get_short (const GNUNET_PEER_Id peer)
1095 return peer_get (GNUNET_PEER_resolve2 (peer));
1100 * Get a cost of a path for a peer considering existing tunnel connections.
1102 * @param peer Peer towards which the path is considered.
1103 * @param path Candidate path.
1105 * @return Cost of the path (path length + number of overlapping nodes)
1108 peer_get_path_cost (const struct MeshPeer *peer,
1109 const struct MeshPeerPath *path)
1111 struct MeshConnection *c;
1112 unsigned int overlap;
1120 GNUNET_assert (NULL != peer->tunnel);
1122 for (i = 0; i < path->length; i++)
1124 for (c = peer->tunnel->connection_head; NULL != c; c = c->next)
1126 for (j = 0; j < c->path->length; j++)
1128 if (path->peers[i] == c->path->peers[j])
1136 return (path->length + overlap) * (path->score * -1);
1141 * Choose the best path towards a peer considering the tunnel properties.
1143 * @param peer The destination peer.
1145 * @return Best current known path towards the peer, if any.
1147 static struct MeshPeerPath *
1148 peer_get_best_path (const struct MeshPeer *peer)
1150 struct MeshPeerPath *best_p;
1151 struct MeshPeerPath *p;
1152 struct MeshConnection *c;
1153 unsigned int best_cost;
1156 best_cost = UINT_MAX;
1158 for (p = peer->path_head; NULL != p; p = p->next)
1160 for (c = peer->tunnel->connection_head; NULL != c; c = c->next)
1164 continue; /* If path is in use in a connection, skip it. */
1166 if ((cost = peer_get_path_cost (peer, p)) < best_cost)
1178 * Try to establish a new connection to this peer in the given tunnel.
1179 * If the peer doesn't have any path to it yet, try to get one.
1180 * If the peer already has some path, send a CREATE CONNECTION towards it.
1182 * @param peer PeerInfo of the peer.
1185 peer_connect (struct MeshPeer *peer)
1187 struct MeshTunnel2 *t;
1188 struct MeshPeerPath *p;
1189 struct MeshConnection *c;
1192 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1193 "peer_connect towards %s\n",
1197 rerun_dhtget = GNUNET_NO;
1199 if (NULL != peer->path_head)
1201 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "path exists\n");
1202 p = peer_get_best_path (peer);
1205 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " %u hops\n", p->length);
1206 c = tunnel_use_path (t, p);
1209 /* This case can happen when the path includes a first hop that is
1210 * not yet known to be connected.
1212 * This happens quite often during testing when running mesh
1213 * under valgrind: core connect notifications come very late and the
1214 * DHT result has already come and created a valid path.
1215 * In this case, the peer->connections hashmap will be NULL and
1216 * tunnel_use_path will not be able to create a connection from that
1219 * Re-running the DHT GET should give core time to callback.
1222 rerun_dhtget = GNUNET_YES;
1226 send_connection_create (c);
1232 if (NULL != peer->dhtget && GNUNET_YES == rerun_dhtget)
1234 GNUNET_DHT_get_stop (peer->dhtget);
1235 peer->dhtget = NULL;
1236 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1237 " Stopping DHT GET for peer %s\n", peer2s (peer));
1240 if (NULL == peer->dhtget)
1242 const struct GNUNET_PeerIdentity *id;
1243 struct GNUNET_HashCode phash;
1245 id = GNUNET_PEER_resolve2 (peer->id);
1246 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1247 " Starting DHT GET for peer %s\n", peer2s (peer));
1248 GNUNET_CRYPTO_hash (&id, sizeof (struct GNUNET_PeerIdentity), &phash);
1249 peer->dhtget = GNUNET_DHT_get_start (dht_handle, /* handle */
1250 GNUNET_BLOCK_TYPE_MESH_PEER, /* type */
1251 &phash, /* key to search */
1252 dht_replication_level, /* replication level */
1253 GNUNET_DHT_RO_RECORD_ROUTE |
1254 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
1256 0, /* xquery bits */
1257 &dht_get_id_handler, peer);
1258 if (MESH_TUNNEL_NEW == t->state)
1259 tunnel_change_state (t, MESH_TUNNEL_SEARCHING);
1266 * Add the path to the peer and update the path used to reach it in case this
1269 * @param peer_info Destination peer to add the path to.
1270 * @param path New path to add. Last peer must be the peer in arg 1.
1271 * Path will be either used of freed if already known.
1272 * @param trusted Do we trust that this path is real?
1275 peer_add_path (struct MeshPeer *peer_info, struct MeshPeerPath *path,
1278 struct MeshPeerPath *aux;
1282 if ((NULL == peer_info) || (NULL == path))
1285 path_destroy (path);
1288 if (path->peers[path->length - 1] != peer_info->id)
1291 path_destroy (path);
1294 if (2 >= path->length && GNUNET_NO == trusted)
1296 /* Only allow CORE to tell us about direct paths */
1297 path_destroy (path);
1300 for (l = 1; l < path->length; l++)
1302 if (path->peers[l] == myid)
1304 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shortening path by %u\n", l);
1305 for (l2 = 0; l2 < path->length - l; l2++)
1307 path->peers[l2] = path->peers[l + l2];
1312 GNUNET_realloc (path->peers, path->length * sizeof (GNUNET_PEER_Id));
1316 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "adding path [%u] to peer %s\n",
1317 path->length, peer2s (peer_info));
1319 l = path_get_length (path);
1322 path_destroy (path);
1326 GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
1327 for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
1329 l2 = path_get_length (aux);
1332 GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
1333 peer_info->path_tail, aux, path);
1338 if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
1340 path_destroy (path);
1345 GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head, peer_info->path_tail,
1352 * Add the path to the origin peer and update the path used to reach it in case
1353 * this is the shortest.
1354 * The path is given in peer_info -> destination, therefore we turn the path
1355 * upside down first.
1357 * @param peer_info Peer to add the path to, being the origin of the path.
1358 * @param path New path to add after being inversed.
1359 * Path will be either used or freed.
1360 * @param trusted Do we trust that this path is real?
1363 peer_add_path_to_origin (struct MeshPeer *peer_info,
1364 struct MeshPeerPath *path, int trusted)
1369 peer_add_path (peer_info, path, trusted);
1373 * Build a PeerPath from the paths returned from the DHT, reversing the paths
1374 * to obtain a local peer -> destination path and interning the peer ids.
1376 * @return Newly allocated and created path
1378 static struct MeshPeerPath *
1379 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
1380 unsigned int get_path_length,
1381 const struct GNUNET_PeerIdentity *put_path,
1382 unsigned int put_path_length)
1384 struct MeshPeerPath *p;
1390 GNUNET_PEER_change_rc (myid, 1);
1391 i = get_path_length;
1392 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " GET has %d hops.\n", i);
1393 for (i--; i >= 0; i--)
1395 id = GNUNET_PEER_intern (&get_path[i]);
1396 if (p->length > 0 && id == p->peers[p->length - 1])
1398 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Optimizing 1 hop out.\n");
1399 GNUNET_PEER_change_rc (id, -1);
1403 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Adding from GET: %s.\n",
1404 GNUNET_i2s (&get_path[i]));
1406 p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
1407 p->peers[p->length - 1] = id;
1410 i = put_path_length;
1411 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " PUT has %d hops.\n", i);
1412 for (i--; i >= 0; i--)
1414 id = GNUNET_PEER_intern (&put_path[i]);
1417 /* PUT path went through us, so discard the path up until now and start
1418 * from here to get a much shorter (and loop-free) path.
1423 if (p->length > 0 && id == p->peers[p->length - 1])
1425 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Optimizing 1 hop out.\n");
1426 GNUNET_PEER_change_rc (id, -1);
1430 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Adding from PUT: %s.\n",
1431 GNUNET_i2s (&put_path[i]));
1433 p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
1434 p->peers[p->length - 1] = id;
1438 if (get_path_length > 0)
1439 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " (first of GET: %s)\n",
1440 GNUNET_i2s (&get_path[0]));
1441 if (put_path_length > 0)
1442 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " (first of PUT: %s)\n",
1443 GNUNET_i2s (&put_path[0]));
1444 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " In total: %d hops\n",
1446 for (i = 0; i < p->length; i++)
1448 struct GNUNET_PeerIdentity peer_id;
1450 GNUNET_PEER_resolve (p->peers[i], &peer_id);
1451 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " %u: %s\n", p->peers[i],
1452 GNUNET_i2s (&peer_id));
1460 * Adds a path to the peer_infos of all the peers in the path
1462 * @param p Path to process.
1463 * @param confirmed Whether we know if the path works or not.
1466 path_add_to_peers (struct MeshPeerPath *p, int confirmed)
1470 /* TODO: invert and add */
1471 for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
1472 for (i++; i < p->length; i++)
1474 struct MeshPeer *aux;
1475 struct MeshPeerPath *copy;
1477 aux = peer_get_short (p->peers[i]);
1478 copy = path_duplicate (p);
1479 copy->length = i + 1;
1480 peer_add_path (aux, copy, p->length < 3 ? GNUNET_NO : confirmed);
1487 fc_debug (struct MeshFlowControl *fc)
1489 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " IN: %u/%u\n",
1490 fc->last_pid_recv, fc->last_ack_sent);
1491 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " OUT: %u/%u\n",
1492 fc->last_pid_sent, fc->last_ack_recv);
1493 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " QUEUE: %u/%u\n",
1494 fc->queue_n, fc->queue_max);
1498 connection_debug (struct MeshConnection *c)
1502 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*** DEBUG NULL CONNECTION ***\n");
1505 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connection %s:%X\n",
1506 peer2s (c->t->peer), GNUNET_h2s (&c->id));
1507 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " state: %u, pending msgs: %u\n",
1508 c->state, c->pending_messages);
1509 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " FWD FC\n");
1510 fc_debug (&c->fwd_fc);
1511 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " BCK FC\n");
1512 fc_debug (&c->bck_fc);
1519 * Change the tunnel state.
1521 * @param t Tunnel whose state to change.
1522 * @param state New state.
1525 tunnel_change_state (struct MeshTunnel2* t, enum MeshTunnelState state)
1529 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1530 "Tunnel %s state was %s\n",
1532 GNUNET_MESH_DEBUG_TS2S (t->state));
1533 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1534 "Tunnel %s state is now %s\n",
1536 GNUNET_MESH_DEBUG_TS2S (state));
1542 * Send all cached messages that we can, tunnel is online.
1544 * @param t Tunnel that holds the messages.
1545 * @param fwd Is this fwd?
1548 tunnel_send_queued_data (struct MeshTunnel2 *t, int fwd)
1550 struct MeshTunnelQueue *tq;
1551 struct MeshTunnelQueue *next;
1554 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1555 "tunnel_send_queued_data on tunnel %s\n",
1557 room = tunnel_get_buffer (t, fwd);
1558 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
1559 for (tq = t->tq_head; NULL != tq && room > 0; tq = next)
1563 GNUNET_CONTAINER_DLL_remove (t->tq_head, t->tq_tail, tq);
1564 send_prebuilt_message_channel ((struct GNUNET_MessageHeader *) &tq[1],
1573 * Cache a message to be sent once tunnel is online.
1575 * @param t Tunnel to hold the message.
1576 * @param ch Channel the message is about.
1577 * @param msg Message itself (copy will be made).
1578 * @param fwd Is this fwd?
1581 tunnel_queue_data (struct MeshTunnel2 *t,
1582 struct MeshChannel *ch,
1583 struct GNUNET_MessageHeader *msg,
1586 struct MeshTunnelQueue *tq;
1587 uint16_t size = ntohs (msg->size);
1589 tq = GNUNET_malloc (sizeof (struct MeshTunnelQueue) + size);
1592 memcpy (&tq[1], msg, size);
1593 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tq);
1595 if (MESH_TUNNEL_READY == t->state)
1596 tunnel_send_queued_data (t, fwd);
1603 static struct MeshConnection *
1604 tunnel_use_path (struct MeshTunnel2 *t, struct MeshPeerPath *p)
1606 struct MeshConnection *c;
1607 struct GNUNET_HashCode cid;
1608 struct MeshPeer *peer;
1609 unsigned int own_pos;
1611 if (NULL == t || NULL == p)
1617 GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE, &cid);
1619 c = connection_new (&cid);
1621 GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, c);
1622 for (own_pos = 0; own_pos < p->length; own_pos++)
1624 if (p->peers[own_pos] == myid)
1627 if (own_pos > p->length - 1)
1630 connection_destroy (c);
1633 c->own_pos = own_pos;
1638 c->fwd_maintenance_task =
1639 GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
1640 &connection_fwd_keepalive, c);
1643 peer = connection_get_next_hop (c);
1644 if (NULL == peer->connections)
1646 connection_destroy (c);
1649 GNUNET_CONTAINER_multihashmap_put (peer->connections, &c->id, c,
1650 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1651 peer = connection_get_prev_hop (c);
1652 if (NULL == peer->connections)
1654 connection_destroy (c);
1657 GNUNET_CONTAINER_multihashmap_put (peer->connections, &c->id, c,
1658 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1664 * Notifies a tunnel that a connection has broken that affects at least
1665 * some of its peers. Sends a notification towards the root of the tree.
1666 * In case the peer is the owner of the tree, notifies the client that owns
1667 * the tunnel and tries to reconnect.
1669 * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
1671 * @param t Tunnel affected.
1672 * @param p1 Peer that got disconnected from p2.
1673 * @param p2 Peer that got disconnected from p1.
1675 * @return Short ID of the peer disconnected (either p1 or p2).
1676 * 0 if the tunnel remained unaffected.
1678 static GNUNET_PEER_Id
1679 tunnel_notify_connection_broken (struct MeshTunnel2* t,
1680 GNUNET_PEER_Id p1, GNUNET_PEER_Id p2)
1682 // if (myid != p1 && myid != p2) FIXME
1687 // if (tree_get_predecessor (t->tree) != 0)
1689 // /* We are the peer still connected, notify owner of the disconnection. */
1690 // struct GNUNET_MESH_PathBroken msg;
1691 // struct GNUNET_PeerIdentity neighbor;
1693 // msg.header.size = htons (sizeof (msg));
1694 // msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN);
1695 // GNUNET_PEER_resolve (t->id.oid, &msg.oid);
1696 // msg.tid = htonl (t->id.tid);
1697 // msg.peer1 = my_full_id;
1698 // GNUNET_PEER_resolve (pid, &msg.peer2);
1699 // GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &neighbor);
1700 // send_prebuilt_message (&msg.header, &neighbor, t);
1709 * Send an ACK on the appropriate connection/channel, depending on
1710 * the direction and the position of the peer.
1712 * @param c Which connection to send the hop-by-hop ACK.
1713 * @param ch Channel, if any.
1714 * @param fwd Is this a fwd ACK? (will go dest->root)
1717 send_ack (struct MeshConnection *c, struct MeshChannel *ch, int fwd)
1719 unsigned int buffer;
1721 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1722 "send ack %s on %p %p\n",
1723 fwd ? "FWD" : "BCK", c, ch);
1724 if (NULL == c || GMC_is_terminal (c, fwd))
1726 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " getting from all connections\n");
1727 buffer = tunnel_get_buffer (NULL == c ? ch->t : c->t, fwd);
1731 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " getting from one connection\n");
1732 buffer = connection_get_buffer (c, fwd);
1734 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " buffer available: %u\n", buffer);
1736 if ( (NULL != ch && channel_is_origin (ch, fwd)) ||
1737 (NULL != c && connection_is_origin (c, fwd)) )
1739 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " sending on channel...\n");
1742 GNUNET_assert (NULL != ch);
1743 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " really sending!\n");
1744 send_local_ack (ch, fwd);
1749 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " sending on all connections\n");
1750 GNUNET_assert (NULL != ch);
1751 channel_send_connections_ack (ch, buffer, fwd);
1755 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " sending on connection\n");
1756 connection_send_ack (c, buffer, fwd);
1764 * Confirm we got a channel create.
1766 * @param ch The channel to confirm.
1767 * @param fwd Should we send the ACK fwd?
1770 channel_send_ack (struct MeshChannel *ch, int fwd)
1772 struct GNUNET_MESH_ChannelManage msg;
1774 msg.header.size = htons (sizeof (msg));
1775 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK);
1776 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1777 " sending channel %s ack for channel %s:%X\n",
1778 fwd ? "FWD" : "BCK", peer2s (ch->t->peer),
1781 msg.chid = htonl (ch->gid);
1782 send_prebuilt_message_channel (&msg.header, ch, !fwd);
1787 * Send a message to all clients (local and remote) of this channel
1788 * notifying that the channel is no longer valid.
1790 * If some peer or client should not receive the message,
1791 * should be zero'ed out before calling this function.
1793 * @param ch The channel whose clients to notify.
1796 channel_send_destroy (struct MeshChannel *ch)
1798 struct GNUNET_MESH_ChannelManage msg;
1800 msg.header.size = htons (sizeof (msg));
1801 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY);
1802 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1803 " sending channel destroy for channel %s:%X\n",
1804 peer2s (ch->t->peer),
1807 if (channel_is_terminal (ch, GNUNET_NO))
1809 if (NULL != ch->root && GNUNET_NO == ch->root->shutting_down)
1811 msg.chid = htonl (ch->lid_root);
1812 send_local_channel_destroy (ch, GNUNET_NO);
1817 msg.chid = htonl (ch->gid);
1818 send_prebuilt_message_channel (&msg.header, ch, GNUNET_NO);
1821 if (channel_is_terminal (ch, GNUNET_YES))
1823 if (NULL != ch->dest && GNUNET_NO == ch->dest->shutting_down)
1825 msg.chid = htonl (ch->lid_dest);
1826 send_local_channel_destroy (ch, GNUNET_YES);
1831 msg.chid = htonl (ch->gid);
1832 send_prebuilt_message_channel (&msg.header, ch, GNUNET_YES);
1840 static struct MeshTunnel2 *
1843 struct MeshTunnel2 *t;
1845 t = GNUNET_new (struct MeshTunnel2);
1847 t->next_local_chid = GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
1849 // GNUNET_CONTAINER_multihashmap_put (tunnels, tid, t,
1850 // GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
1852 // GNUNET_break (0);
1853 // tunnel_destroy (t);
1857 // char salt[] = "salt";
1858 // GNUNET_CRYPTO_kdf (&t->e_key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
1859 // salt, sizeof (salt),
1860 // &t->e_key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
1861 // &my_full_id, sizeof (struct GNUNET_PeerIdentity),
1862 // GNUNET_PEER_resolve2 (t->peer->id), sizeof (struct GNUNET_PeerIdentity),
1864 // GNUNET_CRYPTO_kdf (&t->d_key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
1865 // salt, sizeof (salt),
1866 // &t->d_key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
1867 // GNUNET_PEER_resolve2 (t->peer->id), sizeof (struct GNUNET_PeerIdentity),
1868 // &my_full_id, sizeof (struct GNUNET_PeerIdentity),
1876 * Add a connection to a tunnel.
1879 * @param c Connection.
1882 tunnel_add_connection (struct MeshTunnel2 *t, struct MeshConnection *c)
1884 struct MeshConnection *aux;
1886 for (aux = t->connection_head; aux != NULL; aux = aux->next)
1889 GNUNET_CONTAINER_DLL_insert_tail (t->connection_head, t->connection_tail, c);
1895 tunnel_destroy (struct MeshTunnel2 *t)
1897 struct MeshConnection *c;
1898 struct MeshConnection *next;
1903 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n",
1906 // if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &t->id, t))
1907 // GNUNET_break (0);
1909 for (c = t->connection_head; NULL != c; c = next)
1912 connection_destroy (c);
1915 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
1916 t->peer->tunnel = NULL;
1923 * Tunnel is empty: destroy it.
1925 * Notifies all connections about the destruction.
1927 * @param t Tunnel to destroy.
1930 tunnel_destroy_empty (struct MeshTunnel2 *t)
1932 struct MeshConnection *c;
1934 for (c = t->connection_head; NULL != c; c = c->next)
1936 if (GNUNET_NO == c->destroy)
1937 connection_send_destroy (c);
1940 if (0 == t->pending_messages)
1943 t->destroy = GNUNET_YES;
1948 * Destroy tunnel if empty (no more channels).
1950 * @param t Tunnel to destroy if empty.
1953 tunnel_destroy_if_empty (struct MeshTunnel2 *t)
1955 if (NULL != t->channel_head)
1958 tunnel_destroy_empty (t);
1962 /******************************************************************************/
1963 /**************** MESH NETWORK HANDLER HELPERS ***********************/
1964 /******************************************************************************/
1971 /******************************************************************************/
1972 /******************** MESH NETWORK HANDLERS **************************/
1973 /******************************************************************************/
1977 * Generic handler for mesh network payload traffic.
1979 * @param t Tunnel on which we got this message.
1980 * @param message Unencryted data message.
1981 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
1984 handle_data (struct MeshTunnel2 *t, const struct GNUNET_MESH_Data *msg, int fwd)
1986 struct MeshChannelReliability *rel;
1987 struct MeshChannel *ch;
1988 struct MeshClient *c;
1994 size = ntohs (msg->header.size);
1996 sizeof (struct GNUNET_MESH_Data) +
1997 sizeof (struct GNUNET_MessageHeader))
2002 type = ntohs (msg->header.type);
2003 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message\n",
2004 GNUNET_MESH_DEBUG_M2S (type));
2005 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
2006 GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
2009 ch = channel_get (t, ntohl (msg->chid));
2012 GNUNET_STATISTICS_update (stats, "# data on unknown channel", 1, GNUNET_NO);
2013 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2018 /* Initialize FWD/BCK data */
2019 c = fwd ? ch->dest : ch->root;
2020 rel = fwd ? ch->dest_rel : ch->root_rel;
2028 tunnel_change_state (t, MESH_TUNNEL_READY);
2030 GNUNET_STATISTICS_update (stats, "# data received", 1, GNUNET_NO);
2032 mid = ntohl (msg->mid);
2033 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " mid %u\n", mid);
2035 if (GNUNET_NO == ch->reliable ||
2036 ( !GMC_is_pid_bigger (rel->mid_recv, mid) &&
2037 GMC_is_pid_bigger (rel->mid_recv + 64, mid) ) )
2039 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! RECV %u\n", mid);
2040 if (GNUNET_YES == ch->reliable)
2042 /* Is this the exact next expected messasge? */
2043 if (mid == rel->mid_recv)
2045 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "as expected\n");
2047 channel_send_client_data (ch, msg, fwd);
2051 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "save for later\n");
2052 channel_rel_add_buffered_data (msg, rel);
2057 /* Tunnel is unreliable: send to clients directly */
2058 /* FIXME: accept Out Of Order traffic */
2059 rel->mid_recv = mid + 1;
2060 channel_send_client_data (ch, msg, fwd);
2065 GNUNET_break_op (0);
2066 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2067 " MID %u not expected (%u - %u), dropping!\n",
2068 mid, rel->mid_recv, rel->mid_recv + 64);
2071 channel_send_data_ack (ch, fwd);
2075 * Handler for mesh network traffic end-to-end ACKs.
2077 * @param t Tunnel on which we got this message.
2078 * @param message Data message.
2079 * @param fwd Is this a fwd ACK? (dest->orig)
2082 handle_data_ack (struct MeshTunnel2 *t,
2083 const struct GNUNET_MESH_DataACK *msg, int fwd)
2085 struct MeshChannelReliability *rel;
2086 struct MeshReliableMessage *copy;
2087 struct MeshReliableMessage *next;
2088 struct MeshChannel *ch;
2093 type = ntohs (msg->header.type);
2094 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a %s message!\n",
2095 GNUNET_MESH_DEBUG_M2S (type));
2096 ch = channel_get (t, ntohl (msg->chid));
2099 GNUNET_STATISTICS_update (stats, "# ack on unknown channel", 1, GNUNET_NO);
2102 ack = ntohl (msg->mid);
2103 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! %s ACK %u\n",
2104 (GNUNET_YES == fwd) ? "FWD" : "BCK", ack);
2106 if (GNUNET_YES == fwd)
2120 for (work = GNUNET_NO, copy = rel->head_sent; copy != NULL; copy = next)
2122 if (GMC_is_pid_bigger (copy->mid, ack))
2124 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! head %u, out!\n", copy->mid);
2125 channel_rel_free_sent (rel, msg);
2129 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! id %u\n", copy->mid);
2131 rel_message_free (copy);
2133 /* ACK client if needed */
2134 // channel_send_ack (t, type, GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK == type);
2136 /* If some message was free'd, update the retransmission delay*/
2137 if (GNUNET_YES == work)
2139 if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
2141 GNUNET_SCHEDULER_cancel (rel->retry_task);
2142 if (NULL == rel->head_sent)
2144 rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
2148 struct GNUNET_TIME_Absolute new_target;
2149 struct GNUNET_TIME_Relative delay;
2151 delay = GNUNET_TIME_relative_multiply (rel->retry_timer,
2152 MESH_RETRANSMIT_MARGIN);
2153 new_target = GNUNET_TIME_absolute_add (rel->head_sent->timestamp,
2155 delay = GNUNET_TIME_absolute_get_remaining (new_target);
2157 GNUNET_SCHEDULER_add_delayed (delay,
2158 &channel_retransmit_message,
2171 * Handler for channel create messages.
2173 * @param t Tunnel this channel is to be created in.
2174 * @param msg Message.
2175 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
2178 handle_channel_create (struct MeshTunnel2 *t,
2179 struct GNUNET_MESH_ChannelCreate *msg,
2182 MESH_ChannelNumber chid;
2183 struct MeshChannel *ch;
2184 struct MeshClient *c;
2187 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received Channel Create\n");
2188 /* Check message size */
2189 if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelCreate))
2191 GNUNET_break_op (0);
2195 /* Check if channel exists */
2196 chid = ntohl (msg->chid);
2197 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " chid %u\n", chid);
2198 ch = channel_get (t, chid);
2201 /* Probably a retransmission, safe to ignore */
2202 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
2203 if (NULL != ch->dest)
2205 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " duplicate CC!!\n");
2206 channel_send_ack (ch, !fwd);
2212 /* Create channel */
2213 ch = channel_new (t, NULL, 0);
2215 channel_set_options (ch, ntohl (msg->opt));
2218 /* Find a destination client */
2219 port = ntohl (msg->port);
2220 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " port %u\n", port);
2221 c = GNUNET_CONTAINER_multihashmap32_get (ports, port);
2224 /* TODO send reject */
2225 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " no client has port registered\n");
2230 channel_add_client (ch, c);
2231 if (GNUNET_YES == ch->reliable)
2232 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
2234 send_local_channel_create (ch);
2235 channel_send_ack (ch, fwd);
2236 send_local_ack (ch, !fwd);
2241 * Handler for channel ack messages.
2243 * @param t Tunnel this channel is to be created in.
2244 * @param msg Message.
2245 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
2248 handle_channel_ack (struct MeshTunnel2 *t,
2249 struct GNUNET_MESH_ChannelManage *msg,
2252 MESH_ChannelNumber chid;
2253 struct MeshChannel *ch;
2255 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received Channel ACK\n");
2256 /* Check message size */
2257 if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelManage))
2259 GNUNET_break_op (0);
2263 /* Check if channel exists */
2264 chid = ntohl (msg->chid);
2265 ch = channel_get (t, chid);
2268 GNUNET_break_op (0);
2269 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " channel %u unknown!!\n", chid);
2273 channel_confirm (ch, !fwd);
2278 * Handler for channel destroy messages.
2280 * @param t Tunnel this channel is to be destroyed of.
2281 * @param msg Message.
2282 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
2285 handle_channel_destroy (struct MeshTunnel2 *t,
2286 struct GNUNET_MESH_ChannelManage *msg,
2289 MESH_ChannelNumber chid;
2290 struct MeshChannel *ch;
2292 /* Check message size */
2293 if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelManage))
2295 GNUNET_break_op (0);
2299 /* Check if channel exists */
2300 chid = ntohl (msg->chid);
2301 ch = channel_get (t, chid);
2304 /* Probably a retransmission, safe to ignore */
2307 if ( (fwd && NULL == ch->dest) || (!fwd && NULL == ch->root) )
2309 /* Not for us (don't destroy twice a half-open loopback channel) */
2313 send_local_channel_destroy (ch, fwd);
2314 channel_destroy (ch);
2319 handle_decrypted (struct MeshTunnel2 *t,
2320 const struct GNUNET_MessageHeader *msgh,
2323 switch (ntohs (msgh->type))
2325 case GNUNET_MESSAGE_TYPE_MESH_DATA:
2326 /* Don't send hop ACK, wait for client to ACK */
2327 handle_data (t, (struct GNUNET_MESH_Data *) msgh, fwd);
2330 case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
2331 handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh, fwd);
2334 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
2335 handle_channel_create (t,
2336 (struct GNUNET_MESH_ChannelCreate *) msgh,
2340 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
2341 handle_channel_ack (t,
2342 (struct GNUNET_MESH_ChannelManage *) msgh,
2346 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
2347 handle_channel_destroy (t,
2348 (struct GNUNET_MESH_ChannelManage *) msgh,
2353 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2354 "end-to-end message not known (%u)\n",
2355 ntohs (msgh->type));
2361 * Function to process paths received for a new peer addition. The recorded
2362 * paths form the initial tunnel, which can be optimized later.
2363 * Called on each result obtained for the DHT search.
2365 * @param cls closure
2366 * @param exp when will this value expire
2367 * @param key key of the result
2368 * @param get_path path of the get request
2369 * @param get_path_length lenght of get_path
2370 * @param put_path path of the put request
2371 * @param put_path_length length of the put_path
2372 * @param type type of the result
2373 * @param size number of bytes in data
2374 * @param data pointer to the result data
2377 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
2378 const struct GNUNET_HashCode * key,
2379 const struct GNUNET_PeerIdentity *get_path,
2380 unsigned int get_path_length,
2381 const struct GNUNET_PeerIdentity *put_path,
2382 unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
2383 size_t size, const void *data)
2385 struct MeshPeer *peer = cls;
2386 struct MeshPeerPath *p;
2387 struct MeshConnection *c;
2388 struct GNUNET_PeerIdentity pi;
2389 unsigned int connection_count;
2391 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
2392 GNUNET_PEER_resolve (peer->id, &pi);
2393 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " for %s\n", GNUNET_i2s (&pi));
2395 p = path_build_from_dht (get_path, get_path_length,
2396 put_path, put_path_length);
2397 path_add_to_peers (p, GNUNET_NO);
2400 /* Count connections */
2401 connection_count = GMC_count (peer->tunnel->connection_head);
2403 /* If we already have 3 (or more (?!)) connections, it's enough */
2404 if (3 <= connection_count)
2407 if (peer->tunnel->state == MESH_TUNNEL_SEARCHING)
2409 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... connect!\n");
2410 peer_connect (peer);
2418 * Method called whenever a given peer connects.
2420 * @param cls closure
2421 * @param peer peer identity this notification is about
2424 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
2426 struct MeshPeer *pi;
2427 struct MeshPeerPath *path;
2429 DEBUG_CONN ("Peer connected\n");
2430 DEBUG_CONN (" %s\n", GNUNET_i2s (&my_full_id));
2431 pi = peer_get (peer);
2434 DEBUG_CONN (" (self)\n");
2435 path = path_new (1);
2439 DEBUG_CONN (" %s\n", GNUNET_i2s (peer));
2440 path = path_new (2);
2441 path->peers[1] = pi->id;
2442 GNUNET_PEER_change_rc (pi->id, 1);
2443 GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
2445 path->peers[0] = myid;
2446 GNUNET_PEER_change_rc (myid, 1);
2447 peer_add_path (pi, path, GNUNET_YES);
2449 pi->connections = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_YES);
2455 * Method called whenever a peer disconnects.
2457 * @param cls closure
2458 * @param peer peer identity this notification is about
2461 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
2463 struct MeshPeer *pi;
2465 DEBUG_CONN ("Peer disconnected\n");
2466 pi = GNUNET_CONTAINER_multipeermap_get (peers, peer);
2473 GNUNET_CONTAINER_multihashmap_iterate (pi->connections,
2476 GNUNET_CONTAINER_multihashmap_destroy (pi->connections);
2477 pi->connections = NULL;
2478 if (NULL != pi->core_transmit)
2480 GNUNET_CORE_notify_transmit_ready_cancel (pi->core_transmit);
2481 pi->core_transmit = NULL;
2485 DEBUG_CONN (" (self)\n");
2487 GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
2495 * To be called on core init/fail.
2497 * @param cls Closure (config)
2498 * @param identity the public identity of this peer
2501 core_init (void *cls,
2502 const struct GNUNET_PeerIdentity *identity)
2504 const struct GNUNET_CONFIGURATION_Handle *c = cls;
2507 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
2508 if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)))
2510 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
2511 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2513 GNUNET_i2s (identity));
2514 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2516 GNUNET_i2s (&my_full_id));
2517 GNUNET_CORE_disconnect (core_handle);
2518 core_handle = GNUNET_CORE_connect (c, /* Main configuration */
2519 NULL, /* Closure passed to MESH functions */
2520 &core_init, /* Call core_init once connected */
2521 &core_connect, /* Handle connects */
2522 &core_disconnect, /* remove peers on disconnects */
2523 NULL, /* Don't notify about all incoming messages */
2524 GNUNET_NO, /* For header only in notification */
2525 NULL, /* Don't notify about all outbound messages */
2526 GNUNET_NO, /* For header-only out notification */
2527 core_handlers); /* Register these handlers */
2536 /******************************************************************************/
2537 /************************ MAIN FUNCTIONS ****************************/
2538 /******************************************************************************/
2544 * Task run during shutdown.
2550 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2552 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
2559 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
2564 * Process mesh requests.
2566 * @param cls closure
2567 * @param server the initialized server
2568 * @param c configuration to use
2571 run (void *cls, struct GNUNET_SERVER_Handle *server,
2572 const struct GNUNET_CONFIGURATION_Handle *c)
2574 struct GNUNET_CRYPTO_EccPrivateKey *pk;
2576 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
2579 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
2582 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
2583 "MESH", "CONNECT_TIMEOUT", "MISSING");
2584 GNUNET_SCHEDULER_shutdown ();
2589 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
2592 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
2593 "MESH", "DEFAULT_TTL", "USING DEFAULT");
2598 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DROP_PERCENT",
2605 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2606 "\n***************************************\n"
2607 "Mesh is running with drop mode enabled.\n"
2608 "This is NOT a good idea!\n"
2609 "Remove the DROP_PERCENT option from your configuration.\n"
2610 "***************************************\n");
2614 stats = GNUNET_STATISTICS_create ("mesh", c);
2616 /* Scheduled the task to clean up when shutdown is called */
2617 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
2619 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "reading key\n");
2620 pk = GNUNET_CRYPTO_ecc_key_create_from_configuration (c);
2621 GNUNET_assert (NULL != pk);
2622 my_private_key = pk;
2623 GNUNET_CRYPTO_ecc_key_get_public_for_signature (my_private_key,
2624 &my_full_id.public_key);
2625 myid = GNUNET_PEER_intern (&my_full_id);
2626 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2627 "Mesh for peer [%s] starting\n",
2628 GNUNET_i2s(&my_full_id));
2630 GML_init (server); /* Local clients */
2631 GMC_init (c); /* Connections */
2632 GMP_init (c); /* Peers */
2633 GMD_init (c); /* DHT */
2635 announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
2636 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
2641 * The main function for the mesh service.
2643 * @param argc number of arguments from the command line
2644 * @param argv command line arguments
2645 * @return 0 ok, 1 on error
2648 main (int argc, char *const *argv)
2653 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
2654 r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
2656 ret = (GNUNET_OK == r) ? 0 : 1;
2657 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");