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
32 * - relay corking down to core
33 * - set ttl relative to path length
37 * - peer: other mesh instance. If there is direct connection it's a neighbor.
38 * - tunnel: encrypted connection to a peer, neighbor or not.
39 * - channel: connection between two clients, on the same or different peers.
40 * have properties like reliability.
41 * - path: series of directly connected peer from one peer to another.
42 * - connection: path which is being used in a tunnel.
46 #include "gnunet_crypto_lib.h"
48 #include "mesh_protocol_enc.h"
49 #include "mesh_path.h"
50 #include "block_mesh.h"
51 #include "gnunet_dht_service.h"
52 #include "gnunet_statistics_service.h"
54 #define MESH_BLOOM_SIZE 128
56 #define MESH_DEBUG_DHT GNUNET_NO
57 #define MESH_DEBUG_CONNECTION GNUNET_YES
58 #define MESH_DEBUG_TIMING __LINUX__ && GNUNET_NO
60 #define MESH_MAX_POLL_TIME GNUNET_TIME_relative_multiply (\
61 GNUNET_TIME_UNIT_MINUTES,\
63 #define MESH_RETRANSMIT_TIME GNUNET_TIME_UNIT_SECONDS
64 #define MESH_RETRANSMIT_MARGIN 4
66 #if MESH_DEBUG_CONNECTION
67 #define DEBUG_CONN(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
69 #define DEBUG_CONN(...)
73 #define DEBUG_DHT(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
75 #define DEBUG_DHT(...)
82 struct timespec __mesh_start;
83 struct timespec __mesh_end;
84 #define INTERVAL_START clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &(__mesh_start))
85 #define INTERVAL_END \
87 clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &(__mesh_end));\
88 double __diff = __mesh_end.tv_nsec - __mesh_start.tv_nsec;\
89 if (__diff < 0) __diff += 1000000000;\
93 #define INTERVAL_SHOW \
95 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "AVG process time: %f ns\n", __sum/__count)
97 #define INTERVAL_START
103 * All the states a tunnel can be in.
108 * Uninitialized status, should never appear in operation.
113 * Path to the peer not known yet
115 MESH_TUNNEL_SEARCHING,
118 * Request sent, not yet answered.
123 * Peer connected and ready to accept data
128 * Peer connected previosly but not responding
130 MESH_TUNNEL_RECONNECTING
135 * All the states a connection can be in.
137 enum MeshConnectionState
140 * Uninitialized status, should never appear in operation.
145 * Connection create message sent, waiting for ACK.
147 MESH_CONNECTION_SENT,
150 * Connection confirmed, ready to carry traffic..
152 MESH_CONNECTION_READY,
156 /******************************************************************************/
157 /************************ DATA STRUCTURES ****************************/
158 /******************************************************************************/
160 /** FWD declaration */
164 struct MeshConnection;
166 struct MeshChannelReliability;
170 * Struct containing info about a queued transmission to this peer
177 struct MeshPeerQueue *next;
182 struct MeshPeerQueue *prev;
185 * Peer this transmission is directed to.
187 struct MeshPeer *peer;
190 * Connection this message belongs to.
192 struct MeshConnection *c;
200 * Channel this message belongs to, if known.
202 struct MeshChannel *ch;
205 * Pointer to info stucture used as cls.
215 * Size of the message
222 * Struct to encapsulate all the Flow Control information to a peer to which
223 * we are directly connected (on a core level).
225 struct MeshFlowControl
228 * Connection this controls.
230 struct MeshConnection *c;
233 * How many messages are in the queue on this connection.
235 unsigned int queue_n;
238 * How many messages do we accept in the queue.
240 unsigned int queue_max;
248 * ID of the last packet sent towards the peer.
250 uint32_t last_pid_sent;
253 * ID of the last packet received from the peer.
255 uint32_t last_pid_recv;
258 * Last ACK sent to the peer (peer can't send more than this PID).
260 uint32_t last_ack_sent;
263 * Last ACK sent towards the origin (for traffic towards leaf node).
265 uint32_t last_ack_recv;
268 * Task to poll the peer in case of a lost ACK causes stall.
270 GNUNET_SCHEDULER_TaskIdentifier poll_task;
273 * How frequently to poll for ACKs.
275 struct GNUNET_TIME_Relative poll_time;
280 * Struct containing all information regarding a given peer
290 * Last time we heard from this peer
292 struct GNUNET_TIME_Absolute last_contact;
295 * Paths to reach the peer, ordered by ascending hop count
297 struct MeshPeerPath *path_head;
300 * Paths to reach the peer, ordered by ascending hop count
302 struct MeshPeerPath *path_tail;
305 * Handle to stop the DHT search for paths to this peer
307 struct GNUNET_DHT_GetHandle *dhtget;
310 * Tunnel to this peer, if any.
312 struct MeshTunnel2 *tunnel;
315 * Connections that go through this peer, indexed by tid;
317 struct GNUNET_CONTAINER_MultiHashMap *connections;
320 * Handle for queued transmissions
322 struct GNUNET_CORE_TransmitHandle *core_transmit;
325 * Transmission queue to core DLL head
327 struct MeshPeerQueue *queue_head;
330 * Transmission queue to core DLL tail
332 struct MeshPeerQueue *queue_tail;
335 * How many messages are in the queue to this peer.
337 unsigned int queue_n;
342 * Info needed to retry a message in case it gets lost.
344 struct MeshReliableMessage
347 * Double linked list, FIFO style
349 struct MeshReliableMessage *next;
350 struct MeshReliableMessage *prev;
353 * Tunnel Reliability queue this message is in.
355 struct MeshChannelReliability *rel;
358 * ID of the message (ACK needed to free)
363 * When was this message issued (to calculate ACK delay)
365 struct GNUNET_TIME_Absolute timestamp;
367 /* struct GNUNET_MESH_Data with payload */
371 struct MeshChannelReliability
374 * Channel this is about.
376 struct MeshChannel *ch;
379 * DLL of messages sent and not yet ACK'd.
381 struct MeshReliableMessage *head_sent;
382 struct MeshReliableMessage *tail_sent;
385 * Messages pending to send.
390 * DLL of messages received out of order.
392 struct MeshReliableMessage *head_recv;
393 struct MeshReliableMessage *tail_recv;
401 * Can we send data to the client?
406 * Task to resend/poll in case no ACK is received.
408 GNUNET_SCHEDULER_TaskIdentifier retry_task;
411 * Counter for exponential backoff.
413 struct GNUNET_TIME_Relative retry_timer;
416 * How long does it usually take to get an ACK.
418 struct GNUNET_TIME_Relative expected_delay;
423 * Struct containing all information regarding a channel to a remote client.
428 * Tunnel this channel is in.
430 struct MeshTunnel2 *t;
433 * Double linked list.
435 struct MeshChannel *next;
436 struct MeshChannel *prev;
439 * Destination port of the channel.
444 * Global channel number ( < GNUNET_MESH_LOCAL_CHANNEL_ID_CLI)
446 MESH_ChannelNumber gid;
449 * Local tunnel number for root (owner) client.
450 * ( >= GNUNET_MESH_LOCAL_CHANNEL_ID_CLI or 0 )
452 MESH_ChannelNumber lid_root;
455 * Local tunnel number for local destination clients (incoming number)
456 * ( >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV or 0).
458 MESH_ChannelNumber lid_dest;
461 * Next MID to use for fwd traffic.
463 uint32_t mid_send_fwd;
466 * Next MID expected for fwd traffic.
468 uint32_t mid_recv_fwd;
471 * Next MID to use for bck traffic.
473 uint32_t mid_send_bck;
476 * Next MID expected for bck traffic.
478 uint32_t mid_recv_bck;
481 * Is the tunnel bufferless (minimum latency)?
486 * Is the tunnel reliable?
491 * Last time the channel was used
493 struct GNUNET_TIME_Absolute timestamp;
496 * Client owner of the tunnel, if any
498 struct MeshClient *root;
501 * Client destination of the tunnel, if any.
503 struct MeshClient *dest;
506 * Flag to signal the destruction of the channel.
507 * If this is set GNUNET_YES the channel will be destroyed
508 * when the queue is empty.
513 * Total messages pending for this channel, payload or not.
515 unsigned int pending_messages;
519 * Only present (non-NULL) at the owner of a tunnel.
521 struct MeshChannelReliability *fwd_rel;
525 * Only present (non-NULL) at the destination of a tunnel.
527 struct MeshChannelReliability *bck_rel;
532 * Struct containing all information regarding a connection to a peer.
534 struct MeshConnection
539 struct MeshConnection *next;
540 struct MeshConnection *prev;
543 * Tunnel this connection is part of.
545 struct MeshTunnel2 *t;
548 * Flow control information for traffic fwd.
550 struct MeshFlowControl fwd_fc;
553 * Flow control information for traffic bck.
555 struct MeshFlowControl bck_fc;
563 * State of the connection.
565 enum MeshConnectionState state;
568 * Path being used for the tunnel.
570 struct MeshPeerPath *path;
573 * Position of the local peer in the path.
575 unsigned int own_pos;
578 * Task to keep the used paths alive at the owner,
579 * time tunnel out on all the other peers.
581 GNUNET_SCHEDULER_TaskIdentifier fwd_maintenance_task;
584 * Task to keep the used paths alive at the destination,
585 * time tunnel out on all the other peers.
587 GNUNET_SCHEDULER_TaskIdentifier bck_maintenance_task;
590 * Pending message count.
592 int pending_messages;
595 * Destroy flag: if true, destroy on last message.
602 * Struct used to queue messages in a tunnel.
604 struct MeshTunnelQueue
609 struct MeshTunnelQueue *next;
610 struct MeshTunnelQueue *prev;
615 struct MeshChannel *ch;
620 /* struct GNUNET_MessageHeader *msg; */
625 * Struct containing all information regarding a tunnel to a peer.
630 * Endpoint of the tunnel.
632 struct MeshPeer *peer;
637 struct GNUNET_HashCode id;
640 * State of the tunnel.
642 enum MeshTunnelState state;
645 * Local peer ephemeral private key
647 struct GNUNET_CRYPTO_EccPrivateKey *my_eph_key;
650 * Local peer ephemeral public key
652 struct GNUNET_CRYPTO_EccPublicKey *my_eph;
655 * Remote peer's public key.
657 struct GNUNET_CRYPTO_EccPublicKey *peers_eph;
660 * Encryption ("our") key.
662 struct GNUNET_CRYPTO_AesSessionKey e_key;
665 * Decryption ("their") key.
667 struct GNUNET_CRYPTO_AesSessionKey d_key;
670 * Paths that are actively used to reach the destination peer.
672 struct MeshConnection *connection_head;
673 struct MeshConnection *connection_tail;
676 * Next connection number.
681 * Channels inside this tunnel.
683 struct MeshChannel *channel_head;
684 struct MeshChannel *channel_tail;
687 * Channel ID for the next created channel.
689 MESH_ChannelNumber next_chid;
692 * Channel ID for the next incoming channel.
694 MESH_ChannelNumber next_local_chid;
697 * Pending message count.
699 int pending_messages;
702 * Destroy flag: if true, destroy on last message.
707 * Queued messages, to transmit once tunnel gets connected.
709 struct MeshTunnelQueue *tq_head;
710 struct MeshTunnelQueue *tq_tail;
716 * Struct containing information about a client of the service
718 * TODO: add a list of 'waiting' ports
725 struct MeshClient *next;
730 struct MeshClient *prev;
733 * Tunnels that belong to this client, indexed by local id
735 struct GNUNET_CONTAINER_MultiHashMap32 *own_channels;
738 * Tunnels this client has accepted, indexed by incoming local id
740 struct GNUNET_CONTAINER_MultiHashMap32 *incoming_channels;
743 * Handle to communicate with the client
745 struct GNUNET_SERVER_Client *handle;
748 * Ports that this client has declared interest in.
749 * Indexed by port, contains *Client.
751 struct GNUNET_CONTAINER_MultiHashMap32 *ports;
754 * Whether the client is active or shutting down (don't send confirmations
755 * to a client that is shutting down.
760 * ID of the client, mainly for debug messages
765 * Is this client prevented from sending more data? (We "owe" him an ACK).
771 /******************************************************************************/
772 /************************ DEBUG FUNCTIONS ****************************/
773 /******************************************************************************/
777 * GNUNET_SCHEDULER_Task for printing a message after some operation is done
778 * @param cls string to print
779 * @param success GNUNET_OK if the PUT was transmitted,
780 * GNUNET_NO on timeout,
781 * GNUNET_SYSERR on disconnect from service
782 * after the PUT message was transmitted
783 * (so we don't know if it was received or not)
788 mesh_debug (void *cls, int success)
792 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s (%d)\n", s, success);
798 /******************************************************************************/
799 /*********************** GLOBAL VARIABLES ****************************/
800 /******************************************************************************/
802 /************************** Configuration parameters **************************/
805 * How often to send path keepalives. Paths timeout after 4 missed.
807 static struct GNUNET_TIME_Relative refresh_connection_time;
810 * How often to PUT own ID in the DHT.
812 static struct GNUNET_TIME_Relative id_announce_time;
815 * Maximum time allowed to connect to a peer found by string.
817 static struct GNUNET_TIME_Relative connect_timeout;
820 * Default TTL for payload packets.
822 static unsigned long long default_ttl;
825 * DHT replication level, see DHT API: GNUNET_DHT_get_start, GNUNET_DHT_put.
827 static unsigned long long dht_replication_level;
830 * How many connections are we willing to maintain.
831 * Local connections are always allowed, even if there are more connections than max.
833 static unsigned long long max_connections;
836 * How many messages *in total* are we willing to queue, divide by number of
837 * connections to get connection queue size.
839 static unsigned long long max_msgs_queue;
842 * How many peers do we want to remember?
844 static unsigned long long max_peers;
847 * Percentage of messages that will be dropped (for test purposes only).
849 static unsigned long long drop_percent;
851 /*************************** Static global variables **************************/
854 * DLL with all the clients, head.
856 static struct MeshClient *clients_head;
859 * DLL with all the clients, tail.
861 static struct MeshClient *clients_tail;
864 * Tunnels known, indexed by MESH_TunnelID (MeshTunnel).
866 static struct GNUNET_CONTAINER_MultiHashMap *tunnels;
869 * Peers known, indexed by PeerIdentity (MeshPeer).
871 static struct GNUNET_CONTAINER_MultiHashMap *peers;
874 * Handle to communicate with core.
876 static struct GNUNET_CORE_Handle *core_handle;
881 static struct GNUNET_DHT_Handle *dht_handle;
884 * Handle to server lib.
886 static struct GNUNET_SERVER_Handle *server_handle;
889 * Handle to the statistics service.
891 static struct GNUNET_STATISTICS_Handle *stats;
894 * Notification context, to send messages to local clients.
896 static struct GNUNET_SERVER_NotificationContext *nc;
899 * Local peer own ID (memory efficient handle).
901 static GNUNET_PEER_Id myid;
904 * Local peer own ID (full value).
906 static struct GNUNET_PeerIdentity my_full_id;
911 static struct GNUNET_CRYPTO_EccPrivateKey *my_private_key;
916 static struct GNUNET_CRYPTO_EccPublicKey my_public_key;
919 * All ports clients of this peer have opened.
921 static struct GNUNET_CONTAINER_MultiHashMap32 *ports;
924 * Task to periodically announce itself in the network.
926 GNUNET_SCHEDULER_TaskIdentifier announce_id_task;
929 * Next ID to assign to a client.
931 unsigned int next_client_id;
934 /******************************************************************************/
935 /*********************** DECLARATIONS **************************/
936 /******************************************************************************/
939 * Function to process paths received for a new peer addition. The recorded
940 * paths form the initial tunnel, which can be optimized later.
941 * Called on each result obtained for the DHT search.
944 * @param exp when will this value expire
945 * @param key key of the result
946 * @param type type of the result
947 * @param size number of bytes in data
948 * @param data pointer to the result data
951 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
952 const struct GNUNET_HashCode * key,
953 const struct GNUNET_PeerIdentity *get_path,
954 unsigned int get_path_length,
955 const struct GNUNET_PeerIdentity *put_path,
956 unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
957 size_t size, const void *data);
961 * Retrieve the MeshPeer stucture associated with the peer, create one
962 * and insert it in the appropriate structures if the peer is not known yet.
964 * @param peer Full identity of the peer.
966 * @return Existing or newly created peer info.
968 static struct MeshPeer *
969 peer_get (const struct GNUNET_PeerIdentity *peer);
973 * Retrieve the MeshPeer stucture associated with the peer, create one
974 * and insert it in the appropriate structures if the peer is not known yet.
976 * @param peer Short identity of the peer.
978 * @return Existing or newly created peer info.
980 static struct MeshPeer *
981 peer_get_short (const GNUNET_PEER_Id peer);
985 * Build a PeerPath from the paths returned from the DHT, reversing the paths
986 * to obtain a local peer -> destination path and interning the peer ids.
988 * @return Newly allocated and created path
990 static struct MeshPeerPath *
991 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
992 unsigned int get_path_length,
993 const struct GNUNET_PeerIdentity *put_path,
994 unsigned int put_path_length);
998 * Adds a path to the data structs of all the peers in the path
1000 * @param p Path to process.
1001 * @param confirmed Whether we know if the path works or not.
1004 path_add_to_peers (struct MeshPeerPath *p, int confirmed);
1008 * Search for a tunnel by global ID using full PeerIdentities.
1010 * @param t Tunnel containing the channel.
1011 * @param chid Public channel number.
1013 * @return channel handler, NULL if doesn't exist
1015 static struct MeshChannel *
1016 channel_get (struct MeshTunnel2 *t, MESH_ChannelNumber chid);
1020 * Change the tunnel state.
1022 * @param t Tunnel whose state to change.
1023 * @param state New state.
1026 tunnel_change_state (struct MeshTunnel2 *t, enum MeshTunnelState state);
1030 * Notify a tunnel that a connection has broken that affects at least
1031 * some of its peers.
1033 * @param t Tunnel affected.
1034 * @param p1 Peer that got disconnected from p2.
1035 * @param p2 Peer that got disconnected from p1.
1037 * @return Short ID of the peer disconnected (either p1 or p2).
1038 * 0 if the tunnel remained unaffected.
1040 static GNUNET_PEER_Id
1041 tunnel_notify_connection_broken (struct MeshTunnel2 *t,
1042 GNUNET_PEER_Id p1, GNUNET_PEER_Id p2);
1045 * @brief Use the given path for the tunnel.
1046 * Update the next and prev hops (and RCs).
1047 * (Re)start the path refresh in case the tunnel is locally owned.
1049 * @param t Tunnel to update.
1050 * @param p Path to use.
1052 * @return Connection created.
1054 static struct MeshConnection *
1055 tunnel_use_path (struct MeshTunnel2 *t, struct MeshPeerPath *p);
1058 * Tunnel is empty: destroy it.
1060 * Notifies all participants (peers, cleints) about the destruction.
1062 * @param t Tunnel to destroy.
1065 tunnel_destroy_empty (struct MeshTunnel2 *t);
1068 * Destroy the tunnel.
1070 * This function does not generate any warning traffic to clients or peers.
1073 * Cancel messages belonging to this tunnel queued to neighbors.
1074 * Free any allocated resources linked to the tunnel.
1076 * @param t The tunnel to destroy.
1079 tunnel_destroy (struct MeshTunnel2 *t);
1082 * Create a connection.
1084 * @param tid Tunnel ID.
1085 * @param cid Connection ID.
1087 static struct MeshConnection *
1088 connection_new (struct GNUNET_HashCode *tid, uint32_t cid);
1091 * Connection is no longer needed: destroy it and remove from tunnel.
1093 * @param c Connection to destroy.
1096 connection_destroy (struct MeshConnection *c);
1099 * Send FWD keepalive packets for a connection.
1101 * @param cls Closure (connection for which to send the keepalive).
1102 * @param tc Notification context.
1105 connection_fwd_keepalive (void *cls,
1106 const struct GNUNET_SCHEDULER_TaskContext *tc);
1109 * Send BCK keepalive packets for a connection.
1111 * @param cls Closure (connection for which to send the keepalive).
1112 * @param tc Notification context.
1115 connection_bck_keepalive (void *cls,
1116 const struct GNUNET_SCHEDULER_TaskContext *tc);
1120 * Change the tunnel state.
1122 * @param c Connection whose state to change.
1123 * @param state New state.
1126 connection_change_state (struct MeshConnection* c,
1127 enum MeshConnectionState state);
1132 * @brief Queue and pass message to core when possible.
1134 * @param cls Closure (@c type dependant). It will be used by queue_send to
1135 * build the message to be sent if not already prebuilt.
1136 * @param type Type of the message, 0 for a raw message.
1137 * @param size Size of the message.
1138 * @param c Connection this message belongs to (cannot be NULL).
1139 * @param ch Channel this message belongs to, if applicable (otherwise NULL).
1140 * @param fwd Is this a message going root->dest? (FWD ACK are NOT FWD!)
1143 queue_add (void* cls,
1146 struct MeshConnection* c,
1147 struct MeshChannel* ch,
1152 * Free a transmission that was already queued with all resources
1153 * associated to the request.
1155 * @param queue Queue handler to cancel.
1156 * @param clear_cls Is it necessary to free associated cls?
1159 queue_destroy (struct MeshPeerQueue *queue, int clear_cls);
1163 * Core callback to write a queued packet to core buffer
1165 * @param cls Closure (peer info).
1166 * @param size Number of bytes available in buf.
1167 * @param buf Where the to write the message.
1169 * @return number of bytes written to buf
1172 queue_send (void *cls, size_t size, void *buf);
1176 * Dummy function to separate declarations from definitions in function list.
1179 __mesh_divider______________________________________________________________();
1183 * Get string description for tunnel state.
1185 * @param s Tunnel state.
1187 * @return String representation.
1190 GNUNET_MESH_DEBUG_TS2S (enum MeshTunnelState s)
1192 static char buf[128];
1196 case MESH_TUNNEL_NEW:
1197 return "MESH_TUNNEL_NEW";
1198 case MESH_TUNNEL_SEARCHING:
1199 return "MESH_TUNNEL_SEARCHING";
1200 case MESH_TUNNEL_WAITING:
1201 return "MESH_TUNNEL_WAITING";
1202 case MESH_TUNNEL_READY:
1203 return "MESH_TUNNEL_READY";
1204 case MESH_TUNNEL_RECONNECTING:
1205 return "MESH_TUNNEL_RECONNECTING";
1208 sprintf (buf, "%u (UNKNOWN STATE)", s);
1215 * Get string description for tunnel state.
1217 * @param s Tunnel state.
1219 * @return String representation.
1222 GNUNET_MESH_DEBUG_CS2S (enum MeshTunnelState s)
1226 case MESH_CONNECTION_NEW:
1227 return "MESH_CONNECTION_NEW";
1228 case MESH_CONNECTION_SENT:
1229 return "MESH_CONNECTION_SENT";
1230 case MESH_CONNECTION_READY:
1231 return "MESH_CONNECTION_READY";
1233 return "MESH_CONNECTION_STATE_ERROR";
1239 /******************************************************************************/
1240 /************************ PERIODIC FUNCTIONS ****************************/
1241 /******************************************************************************/
1244 * Periodically announce self id in the DHT
1246 * @param cls closure
1247 * @param tc task context
1250 announce_id (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1252 struct PBlock block;
1254 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1256 announce_id_task = GNUNET_SCHEDULER_NO_TASK;
1260 * - Set data expiration in function of X
1261 * - Adapt X to churn
1263 DEBUG_DHT ("DHT_put for ID %s started.\n", GNUNET_i2s (&my_full_id));
1265 block.id = my_full_id;
1266 GNUNET_DHT_put (dht_handle, /* DHT handle */
1267 &my_full_id.hashPubKey, /* Key to use */
1268 dht_replication_level, /* Replication level */
1269 GNUNET_DHT_RO_RECORD_ROUTE | GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, /* DHT options */
1270 GNUNET_BLOCK_TYPE_MESH_PEER, /* Block type */
1271 sizeof (block), /* Size of the data */
1272 (const char *) &block, /* Data itself */
1273 GNUNET_TIME_UNIT_FOREVER_ABS, /* Data expiration */
1274 GNUNET_TIME_UNIT_FOREVER_REL, /* Retry time */
1275 NULL, /* Continuation */
1276 NULL); /* Continuation closure */
1278 GNUNET_SCHEDULER_add_delayed (id_announce_time, &announce_id, cls);
1282 /******************************************************************************/
1283 /****************** GENERAL HELPER FUNCTIONS ************************/
1284 /******************************************************************************/
1288 * Get the static string for a peer ID.
1292 * @return Static string for it's ID.
1295 peer2s (const struct MeshPeer *peer)
1299 return GNUNET_i2s (GNUNET_PEER_resolve2 (peer->id));
1304 * Get the previous hop in a connection
1306 * @param c Connection.
1308 * @return Previous peer in the connection.
1310 static struct MeshPeer *
1311 connection_get_prev_hop (struct MeshConnection *c)
1315 if (0 == c->own_pos || c->path->length < 2)
1316 id = c->path->peers[0];
1318 id = c->path->peers[c->own_pos - 1];
1320 return peer_get_short (id);
1325 * Get the next hop in a connection
1327 * @param c Connection.
1329 * @return Next peer in the connection.
1331 static struct MeshPeer *
1332 connection_get_next_hop (struct MeshConnection *c)
1336 if ((c->path->length - 1) == c->own_pos || c->path->length < 2)
1337 id = c->path->peers[c->path->length - 1];
1339 id = c->path->peers[c->own_pos + 1];
1341 return peer_get_short (id);
1346 * Get the hop in a connection.
1348 * @param c Connection.
1349 * @param fwd Next hop?
1351 * @return Next peer in the connection.
1353 static struct MeshPeer *
1354 connection_get_hop (struct MeshConnection *c, int fwd)
1357 return connection_get_next_hop (c);
1358 return connection_get_prev_hop (c);
1362 * Check if client has registered with the service and has not disconnected
1364 * @param client the client to check
1366 * @return non-NULL if client exists in the global DLL
1368 static struct MeshClient *
1369 client_get (struct GNUNET_SERVER_Client *client)
1371 return GNUNET_SERVER_client_get_user_context (client, struct MeshClient);
1376 * Deletes a tunnel from a client (either owner or destination).
1378 * @param c Client whose tunnel to delete.
1379 * @param ch Channel which should be deleted.
1382 client_delete_channel (struct MeshClient *c, struct MeshChannel *ch)
1388 res = GNUNET_CONTAINER_multihashmap32_remove (c->own_channels,
1390 if (GNUNET_YES != res)
1391 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client_delete_channel owner KO\n");
1395 res = GNUNET_CONTAINER_multihashmap32_remove (c->incoming_channels,
1397 if (GNUNET_YES != res)
1398 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client_delete_tunnel client KO\n");
1404 * Notify the appropriate client that a new incoming channel was created.
1406 * @param ch Channel that was created.
1409 send_local_channel_create (struct MeshChannel *ch)
1411 struct GNUNET_MESH_ChannelMessage msg;
1412 struct MeshTunnel2 *t = ch->t;
1414 if (NULL == ch->dest)
1416 msg.header.size = htons (sizeof (msg));
1417 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
1418 msg.channel_id = htonl (ch->lid_dest);
1419 msg.port = htonl (ch->port);
1421 msg.opt |= GNUNET_YES == ch->reliable ? GNUNET_MESH_OPTION_RELIABLE : 0;
1422 msg.opt |= GNUNET_YES == ch->nobuffer ? GNUNET_MESH_OPTION_NOBUFFER : 0;
1423 msg.opt = htonl (msg.opt);
1424 GNUNET_PEER_resolve (t->peer->id, &msg.peer);
1425 GNUNET_SERVER_notification_context_unicast (nc, ch->dest->handle,
1426 &msg.header, GNUNET_NO);
1431 * Notify a client that the incoming tunnel is no longer valid.
1433 * @param ch Channel that is destroyed.
1434 * @param fwd Forward notification (owner->dest)?
1437 send_local_channel_destroy (struct MeshChannel *ch, int fwd)
1439 struct GNUNET_MESH_ChannelMessage msg;
1440 struct MeshClient *c;
1442 c = fwd ? ch->dest : ch->root;
1448 msg.header.size = htons (sizeof (msg));
1449 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1450 msg.channel_id = htonl (fwd ? ch->lid_dest : ch->lid_root);
1451 msg.port = htonl (0);
1452 memset (&msg.peer, 0, sizeof (msg.peer));
1453 msg.opt = htonl (0);
1454 GNUNET_SERVER_notification_context_unicast (nc, c->handle,
1455 &msg.header, GNUNET_NO);
1460 * Build a local ACK message and send it to a local client.
1462 * @param ch Channel on which to send the ACK.
1463 * @param c Client to whom send the ACK.
1464 * @param fwd Set to GNUNET_YES for FWD ACK (dest->owner)
1467 send_local_ack (struct MeshChannel *ch,
1468 struct MeshClient *c,
1471 struct GNUNET_MESH_LocalAck msg;
1474 || ( fwd && (0 == ch->lid_root || c != ch->root))
1475 || (!fwd && (0 == ch->lid_dest || c != ch->dest)) )
1480 msg.header.size = htons (sizeof (msg));
1481 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
1482 msg.channel_id = htonl (fwd ? ch->lid_root : ch->lid_dest);
1483 GNUNET_SERVER_notification_context_unicast (nc,
1487 c->blocked = GNUNET_NO;
1492 * Count established (ready) connections of a tunnel.
1494 * @param t Tunnel on which to send the message.
1496 * @return Number of connections.
1499 tunnel_count_connections (struct MeshTunnel2 *t)
1501 struct MeshConnection *c;
1504 for (c = t->connection_head, i = 0; NULL != c; c = c->next, i++);
1511 * Pick a connection on which send the next data message.
1513 * @param t Tunnel on which to send the message.
1514 * @param fwd Is this a fwd message?
1516 * @return The connection on which to send the next message.
1518 static struct MeshConnection *
1519 tunnel_get_connection (struct MeshTunnel2 *t, int fwd)
1521 struct MeshConnection *c;
1522 struct MeshConnection *best;
1523 struct MeshFlowControl *fc;
1524 unsigned int lowest_q;
1527 lowest_q = UINT_MAX;
1528 for (c = t->connection_head; NULL != c; c = c->next)
1530 if (MESH_CONNECTION_READY == c->state)
1532 fc = fwd ? &c->fwd_fc : &c->bck_fc;
1538 if (fc->queue_n < lowest_q)
1541 lowest_q = fc->queue_n;
1550 * Get the total buffer space for a tunnel.
1553 tunnel_get_buffer (struct MeshTunnel2 *t, int fwd)
1555 struct MeshConnection *c;
1556 struct MeshFlowControl *fc;
1557 unsigned int buffer;
1559 for (buffer = 0, c = t->connection_head; NULL != c; c = c->next)
1561 if (c->state != MESH_CONNECTION_READY)
1564 fc = fwd ? &c->fwd_fc : &c->bck_fc;
1565 buffer += fc->last_ack_recv - fc->last_pid_sent;
1573 * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
1574 * Encrypt data with the tunnel key.
1576 * @param t Tunnel whose key to use.
1577 * @param dst Destination for the encrypted data.
1578 * @param src Source of the plaintext.
1579 * @param size Size of the plaintext.
1580 * @param iv Initialization Vector to use.
1581 * @param fwd Is this a fwd message?
1584 tunnel_encrypt (struct MeshTunnel2 *t,
1585 void *dst, const void *src,
1586 size_t size, uint64_t iv, int fwd)
1588 memcpy (dst, src, size);
1593 * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
1594 * Decrypt data with the tunnel key.
1596 * @param t Tunnel whose key to use.
1597 * @param dst Destination for the plaintext.
1598 * @param src Source of the encrypted data.
1599 * @param size Size of the encrypted data.
1600 * @param iv Initialization Vector to use.
1601 * @param fwd Is this a fwd message?
1604 tunnel_decrypt (struct MeshTunnel2 *t,
1605 void *dst, const void *src,
1606 size_t size, uint64_t iv, int fwd)
1608 memcpy (dst, src, size);
1613 * Sends an already built message on a connection, properly registering
1614 * all used resources.
1616 * @param message Message to send. Function makes a copy of it.
1617 * If message is not hop-by-hop, decrements TTL of copy.
1618 * @param c Connection on which this message is transmitted.
1619 * @param ch Channel on which this message is transmitted, or NULL.
1620 * @param fwd Is this a fwd message?
1623 send_prebuilt_message_connection (const struct GNUNET_MessageHeader *message,
1624 struct MeshConnection *c,
1625 struct MeshChannel *ch,
1632 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send on Connection %s[%X]\n",
1633 GNUNET_h2s (&c->t->id), c->id);
1635 size = ntohs (message->size);
1636 data = GNUNET_malloc (size);
1637 memcpy (data, message, size);
1638 type = ntohs (message->type);
1640 if (GNUNET_MESSAGE_TYPE_MESH_FWD == type ||
1641 GNUNET_MESSAGE_TYPE_MESH_BCK == type)
1643 struct GNUNET_MESH_Encrypted *msg;
1646 msg = (struct GNUNET_MESH_Encrypted *) data;
1647 ttl = ntohl (msg->ttl);
1650 GNUNET_break_op (0);
1653 msg->ttl = htonl (ttl - 1);
1654 msg->pid = htonl (fwd ? c->fwd_fc.next_pid++ : c->bck_fc.next_pid++);
1655 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " pid %u\n", ntohl (msg->pid));
1668 * Sends an already built message on a tunnel, choosing the best connection.
1670 * @param message Message to send. Function modifies it.
1671 * @param t Tunnel on which this message is transmitted.
1672 * @param ch Channel on which this message is transmitted.
1673 * @param fwd Is this a fwd message?
1676 send_prebuilt_message_tunnel (struct GNUNET_MESH_Encrypted *msg,
1677 struct MeshTunnel2 *t,
1678 struct MeshChannel *ch,
1681 struct MeshConnection *c;
1684 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send on Tunnel %s\n",
1685 GNUNET_h2s (&t->id));
1686 c = tunnel_get_connection (t, fwd);
1689 GNUNET_break (GNUNET_YES == t->destroy);
1692 type = ntohs (msg->header.type);
1695 case GNUNET_MESSAGE_TYPE_MESH_FWD:
1696 case GNUNET_MESSAGE_TYPE_MESH_BCK:
1697 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
1698 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
1699 msg->cid = htonl (c->id);
1701 msg->ttl = htonl (default_ttl);
1704 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
1705 GNUNET_MESH_DEBUG_M2S (type));
1709 send_prebuilt_message_connection (&msg->header, c, ch, fwd);
1714 * Sends an already built message on a channel, properly registering
1715 * all used resources and encrypting the message with the tunnel's key.
1717 * @param message Message to send. Function makes a copy of it.
1718 * @param ch Channel on which this message is transmitted.
1719 * @param fwd Is this a fwd message?
1722 send_prebuilt_message_channel (const struct GNUNET_MessageHeader *message,
1723 struct MeshChannel *ch,
1726 struct GNUNET_MESH_Encrypted *msg;
1727 size_t size = ntohs (message->size);
1728 char *cbuf[sizeof (struct GNUNET_MESH_Encrypted) + size];
1732 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send on Channel %s:%X\n",
1733 GNUNET_h2s (&ch->t->id), ch->gid);
1734 type = fwd ? GNUNET_MESSAGE_TYPE_MESH_FWD : GNUNET_MESSAGE_TYPE_MESH_BCK;
1735 iv = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_NONCE, UINT64_MAX);
1737 msg = (struct GNUNET_MESH_Encrypted *) cbuf;
1738 msg->header.type = htons (type);
1739 msg->header.size = htons (sizeof (struct GNUNET_MESH_Encrypted) + size);
1740 msg->iv = GNUNET_htonll (iv);
1741 tunnel_encrypt (ch->t, &msg[1], message, size, iv, fwd);
1743 send_prebuilt_message_tunnel (msg, ch->t, ch, fwd);
1748 * Sends a CREATE CONNECTION message for a path to a peer.
1749 * Changes the connection and tunnel states if necessary.
1751 * @param connection Connection to create.
1754 send_connection_create (struct MeshConnection *connection)
1756 struct MeshTunnel2 *t;
1759 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send connection create\n");
1761 GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
1762 sizeof (struct GNUNET_MESH_ConnectionCreate) +
1763 (connection->path->length *
1764 sizeof (struct GNUNET_PeerIdentity)),
1768 if (MESH_TUNNEL_SEARCHING == t->state || MESH_TUNNEL_NEW == t->state)
1769 tunnel_change_state (t, MESH_TUNNEL_WAITING);
1770 if (MESH_CONNECTION_NEW == connection->state)
1771 connection_change_state (connection, MESH_CONNECTION_SENT);
1776 * Sends a CONNECTION ACK message in reponse to a received CONNECTION_CREATE
1779 * @param connection Connection to confirm.
1780 * @param fwd Is this a fwd ACK? (First is bck (SYNACK), second is fwd (ACK))
1783 send_connection_ack (struct MeshConnection *connection, int fwd)
1785 struct MeshTunnel2 *t;
1788 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send connection ack\n");
1790 GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
1791 sizeof (struct GNUNET_MESH_ConnectionACK),
1795 if (MESH_TUNNEL_NEW == t->state)
1796 tunnel_change_state (t, MESH_TUNNEL_WAITING);
1801 * Build a hop-by-hop ACK message and queue it to send for the given connection.
1803 * @param c Which connection to send the hop-by-hop ACK.
1804 * @param ack Value of the ACK.
1805 * @param fwd Is this fwd?
1808 send_ack (struct MeshConnection *c, uint32_t ack, int fwd)
1810 struct GNUNET_MESH_ACK msg;
1812 msg.header.size = htons (sizeof (msg));
1813 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ACK);
1814 msg.ack = htonl (ack);
1816 msg.cid = htonl (c->id);
1818 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1819 "connection send %s ack %u on %s[%X]\n",
1820 fwd ? "FWD" : "BCK", ack, GNUNET_h2s (&c->t->id), c->id);
1822 send_prebuilt_message_connection (&msg.header, c, NULL, fwd);
1827 * Core callback to write a pre-constructed data packet to core buffer
1829 * @param cls Closure (MeshTransmissionDescriptor with data in "data" member).
1830 * @param size Number of bytes available in buf.
1831 * @param buf Where the to write the message.
1833 * @return number of bytes written to buf
1836 send_core_data_raw (void *cls, size_t size, void *buf)
1838 struct GNUNET_MessageHeader *msg = cls;
1841 GNUNET_assert (NULL != msg);
1842 total_size = ntohs (msg->size);
1844 if (total_size > size)
1849 memcpy (buf, msg, total_size);
1856 * Function to send a create connection message to a peer.
1858 * @param c Connection to create.
1859 * @param size number of bytes available in buf
1860 * @param buf where the callee should write the message
1861 * @return number of bytes written to buf
1864 send_core_connection_create (struct MeshConnection *c, size_t size, void *buf)
1866 struct GNUNET_MESH_ConnectionCreate *msg;
1867 struct GNUNET_PeerIdentity *peer_ptr;
1868 struct MeshPeerPath *p = c->path;
1872 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION CREATE...\n");
1874 sizeof (struct GNUNET_MESH_ConnectionCreate) +
1875 p->length * sizeof (struct GNUNET_PeerIdentity);
1877 if (size < size_needed || NULL == buf)
1882 msg = (struct GNUNET_MESH_ConnectionCreate *) buf;
1883 msg->header.size = htons (size_needed);
1884 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE);
1885 msg->cid = htonl (c->id);
1886 msg->tid = c->t->id;
1888 peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
1889 for (i = 0; i < p->length; i++)
1891 GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
1894 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1895 "CONNECTION CREATE (%u bytes long) sent!\n", size_needed);
1901 * Creates a path ack message in buf and frees all unused resources.
1903 * @param c Connection to send an ACK on.
1904 * @param size number of bytes available in buf
1905 * @param buf where the callee should write the message
1907 * @return number of bytes written to buf
1910 send_core_connection_ack (struct MeshConnection *c, size_t size, void *buf)
1912 struct GNUNET_MESH_ConnectionACK *msg = buf;
1913 struct MeshTunnel2 *t = c->t;
1915 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION ACK...\n");
1916 GNUNET_assert (NULL != t);
1917 if (sizeof (struct GNUNET_MESH_ConnectionACK) > size)
1922 msg->header.size = htons (sizeof (struct GNUNET_MESH_ConnectionACK));
1923 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK);
1924 msg->cid = htonl (c->id);
1927 /* TODO add signature */
1929 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CONNECTION ACK sent!\n");
1930 return sizeof (struct GNUNET_MESH_ConnectionACK);
1935 * Destroy the peer_info and free any allocated resources linked to it
1937 * @param peer The peer_info to destroy.
1939 * @return GNUNET_OK on success
1942 peer_destroy (struct MeshPeer *peer)
1944 struct GNUNET_PeerIdentity id;
1945 struct MeshPeerPath *p;
1946 struct MeshPeerPath *nextp;
1948 GNUNET_PEER_resolve (peer->id, &id);
1949 GNUNET_PEER_change_rc (peer->id, -1);
1952 GNUNET_CONTAINER_multihashmap_remove (peers, &id.hashPubKey, peer))
1955 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1956 "removing peer %s, not in hashmap\n", GNUNET_i2s (&id));
1958 if (NULL != peer->dhtget)
1960 GNUNET_DHT_get_stop (peer->dhtget);
1962 p = peer->path_head;
1966 GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
1970 tunnel_destroy_empty (peer->tunnel);
1977 * Returns if peer is used (has a tunnel, is neighbor).
1979 * @peer Peer to check.
1981 * @return GNUNET_YES if peer is in use.
1984 peer_is_used (struct MeshPeer *peer)
1986 struct MeshPeerPath *p;
1988 if (NULL != peer->tunnel)
1991 for (p = peer->path_head; NULL != p; p = p->next)
2000 * Iterator over all the peers to get the oldest timestamp.
2002 * @param cls Closure (unsued).
2003 * @param key ID of the peer.
2004 * @param value Peer_Info of the peer.
2007 peer_get_oldest (void *cls,
2008 const struct GNUNET_HashCode *key,
2011 struct MeshPeer *p = value;
2012 struct GNUNET_TIME_Absolute *abs = cls;
2014 /* Don't count active peers */
2015 if (GNUNET_YES == peer_is_used (p))
2018 if (abs->abs_value_us < p->last_contact.abs_value_us)
2019 abs->abs_value_us = p->last_contact.abs_value_us;
2026 * Iterator over all the peers to remove the oldest entry.
2028 * @param cls Closure (unsued).
2029 * @param key ID of the peer.
2030 * @param value Peer_Info of the peer.
2033 peer_timeout (void *cls,
2034 const struct GNUNET_HashCode *key,
2037 struct MeshPeer *p = value;
2038 struct GNUNET_TIME_Absolute *abs = cls;
2040 if (p->last_contact.abs_value_us == abs->abs_value_us &&
2041 GNUNET_NO == peer_is_used (p))
2051 * Delete oldest unused peer.
2054 peer_delete_oldest (void)
2056 struct GNUNET_TIME_Absolute abs;
2058 abs = GNUNET_TIME_UNIT_FOREVER_ABS;
2060 GNUNET_CONTAINER_multihashmap_iterate (peers,
2063 GNUNET_CONTAINER_multihashmap_iterate (peers,
2070 * Retrieve the MeshPeer stucture associated with the peer, create one
2071 * and insert it in the appropriate structures if the peer is not known yet.
2073 * @param peer Full identity of the peer.
2075 * @return Existing or newly created peer info.
2077 static struct MeshPeer *
2078 peer_get (const struct GNUNET_PeerIdentity *peer_id)
2080 struct MeshPeer *peer;
2082 peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer_id->hashPubKey);
2085 peer = GNUNET_new (struct MeshPeer);
2086 if (GNUNET_CONTAINER_multihashmap_size (peers) > max_peers)
2088 peer_delete_oldest ();
2090 GNUNET_CONTAINER_multihashmap_put (peers, &peer_id->hashPubKey, peer,
2091 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
2092 peer->id = GNUNET_PEER_intern (peer_id);
2094 peer->last_contact = GNUNET_TIME_absolute_get();
2101 * Retrieve the MeshPeer stucture associated with the peer, create one
2102 * and insert it in the appropriate structures if the peer is not known yet.
2104 * @param peer Short identity of the peer.
2106 * @return Existing or newly created peer info.
2108 static struct MeshPeer *
2109 peer_get_short (const GNUNET_PEER_Id peer)
2111 return peer_get (GNUNET_PEER_resolve2 (peer));
2116 * Get a cost of a path for a peer considering existing tunnel connections.
2118 * @param peer Peer towards which the path is considered.
2119 * @param path Candidate path.
2121 * @return Cost of the path (path length + number of overlapping nodes)
2124 peer_get_path_cost (const struct MeshPeer *peer,
2125 const struct MeshPeerPath *path)
2127 struct MeshConnection *c;
2128 unsigned int overlap;
2136 GNUNET_assert (NULL != peer->tunnel);
2138 for (i = 0; i < path->length; i++)
2140 for (c = peer->tunnel->connection_head; NULL != c; c = c->next)
2142 for (j = 0; j < c->path->length; j++)
2144 if (path->peers[i] == c->path->peers[j])
2152 return (path->length + overlap) * (path->score * -1);
2157 * Choose the best path towards a peer considering the tunnel properties.
2159 * @param peer The destination peer.
2161 * @return Best current known path towards the peer, if any.
2163 static struct MeshPeerPath *
2164 peer_get_best_path (const struct MeshPeer *peer)
2166 struct MeshPeerPath *best_p;
2167 struct MeshPeerPath *p;
2168 struct MeshConnection *c;
2169 unsigned int best_cost;
2172 best_cost = UINT_MAX;
2174 for (p = peer->path_head; NULL != p; p = p->next)
2176 for (c = peer->tunnel->connection_head; NULL != c; c = c->next)
2180 continue; /* If path is in use in a connection, skip it. */
2182 if ((cost = peer_get_path_cost (peer, p)) < best_cost)
2192 queue_is_sendable (struct MeshPeerQueue *q)
2194 struct MeshFlowControl *fc;
2196 /* Is PID-independent? */
2199 case GNUNET_MESSAGE_TYPE_MESH_ACK:
2200 case GNUNET_MESSAGE_TYPE_MESH_POLL:
2204 /* Is PID allowed? */
2205 fc = q->fwd ? &q->c->fwd_fc : &q->c->bck_fc;
2206 if (GMC_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
2214 * Get first sendable message.
2216 * @param peer The destination peer.
2218 * @return Best current known path towards the peer, if any.
2220 static struct MeshPeerQueue *
2221 peer_get_first_message (const struct MeshPeer *peer)
2223 struct MeshPeerQueue *q;
2225 for (q = peer->queue_head; NULL != q; q = q->next)
2227 if (queue_is_sendable (q))
2236 * Try to establish a new connection to this peer in the given tunnel.
2237 * If the peer doesn't have any path to it yet, try to get one.
2238 * If the peer already has some path, send a CREATE CONNECTION towards it.
2240 * @param peer PeerInfo of the peer.
2243 peer_connect (struct MeshPeer *peer)
2245 struct MeshTunnel2 *t;
2246 struct MeshPeerPath *p;
2247 struct MeshConnection *c;
2249 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2250 "peer_connect towards %s\n",
2253 if (NULL != peer->path_head)
2255 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "path exists\n");
2256 p = peer_get_best_path (peer);
2259 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " %u hops\n", p->length);
2260 c = tunnel_use_path (t, p);
2261 send_connection_create (c);
2264 else if (NULL == peer->dhtget)
2266 const struct GNUNET_PeerIdentity *id;
2268 id = GNUNET_PEER_resolve2 (peer->id);
2269 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2270 " Starting DHT GET for peer %s\n", peer2s (peer));
2271 peer->dhtget = GNUNET_DHT_get_start (dht_handle, /* handle */
2272 GNUNET_BLOCK_TYPE_MESH_PEER, /* type */
2273 &id->hashPubKey, /* key to search */
2274 dht_replication_level, /* replication level */
2275 GNUNET_DHT_RO_RECORD_ROUTE |
2276 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
2278 0, /* xquery bits */
2279 &dht_get_id_handler, peer);
2280 if (MESH_TUNNEL_NEW == t->state)
2281 tunnel_change_state (t, MESH_TUNNEL_SEARCHING);
2285 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2286 "There is no path but the DHT GET is already started.\n");
2292 * Get the first transmittable message for a connection.
2294 * @param c Connection.
2295 * @param fwd Is this FWD?
2297 * @return First transmittable message.
2299 static struct MeshPeerQueue *
2300 connection_get_first_message (struct MeshConnection *c, int fwd)
2302 struct MeshPeerQueue *q;
2305 p = connection_get_hop (c, fwd);
2307 for (q = p->queue_head; NULL != q; q = q->next)
2311 if (queue_is_sendable (q))
2320 * Is this peer the first one on the connection?
2322 * @param c Connection.
2323 * @param fwd Is this about fwd traffic?
2325 * @return GNUNET_YES if origin, GNUNET_NO if relay/terminal.
2328 connection_is_origin (struct MeshConnection *c, int fwd)
2330 if (!fwd && c->own_pos == c->path->length - 1)
2332 if (fwd && c->own_pos == 0)
2339 * Is this peer the last one on the connection?
2341 * @param c Connection.
2342 * @param fwd Is this about fwd traffic?
2343 * Note that the ROOT is the terminal for BCK traffic!
2345 * @return GNUNET_YES if terminal, GNUNET_NO if relay/origin.
2348 connection_is_terminal (struct MeshConnection *c, int fwd)
2350 if (fwd && c->own_pos == c->path->length - 1)
2352 if (!fwd && c->own_pos == 0)
2359 * @brief Re-initiate traffic on this connection if necessary.
2361 * Check if there is traffic queued towards this peer
2362 * and the core transmit handle is NULL (traffic was stalled).
2363 * If so, call core tmt rdy.
2365 * @param c Connection on which initiate traffic.
2366 * @param fwd Is this about fwd traffic?
2369 connection_unlock_queue (struct MeshConnection *c, int fwd)
2371 struct MeshPeer *peer;
2372 struct MeshPeerQueue *q;
2375 peer = connection_get_hop (c, fwd);
2377 if (NULL != peer->core_transmit)
2378 return; /* Already unlocked */
2380 q = connection_get_first_message (c, fwd);
2382 return; /* Nothing to transmit */
2385 peer->core_transmit =
2386 GNUNET_CORE_notify_transmit_ready (core_handle,
2389 GNUNET_TIME_UNIT_FOREVER_REL,
2390 GNUNET_PEER_resolve2 (peer->id),
2398 * Cancel all transmissions that belong to a certain connection.
2400 * @param c Connection which to cancel.
2401 * @param fwd Cancel fwd traffic?
2404 connection_cancel_queues (struct MeshConnection *c, int fwd)
2406 struct MeshPeerQueue *q;
2407 struct MeshPeerQueue *next;
2408 struct MeshFlowControl *fc;
2409 struct MeshPeer *peer;
2416 fc = fwd ? &c->fwd_fc : &c->bck_fc;
2417 peer = connection_get_hop (c, fwd);
2419 for (q = peer->queue_head; NULL != q; q = next)
2424 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2425 "connection_cancel_queue %s\n",
2426 GNUNET_MESH_DEBUG_M2S (q->type));
2427 queue_destroy (q, GNUNET_YES);
2430 if (NULL == peer->queue_head)
2432 if (NULL != peer->core_transmit)
2434 GNUNET_CORE_notify_transmit_ready_cancel (peer->core_transmit);
2435 peer->core_transmit = NULL;
2437 if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
2439 GNUNET_SCHEDULER_cancel (fc->poll_task);
2440 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2447 * Remove all paths that rely on a direct connection between p1 and p2
2448 * from the peer itself and notify all tunnels about it.
2450 * @param peer PeerInfo of affected peer.
2451 * @param p1 GNUNET_PEER_Id of one peer.
2452 * @param p2 GNUNET_PEER_Id of another peer that was connected to the first and
2455 * TODO: optimize (see below)
2458 peer_remove_path (struct MeshPeer *peer, GNUNET_PEER_Id p1,
2461 struct MeshPeerPath *p;
2462 struct MeshPeerPath *next;
2463 struct MeshPeer *peer_d;
2465 unsigned int destroyed;
2468 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path\n");
2470 for (p = peer->path_head; NULL != p; p = next)
2473 for (i = 0; i < (p->length - 1); i++)
2475 if ((p->peers[i] == p1 && p->peers[i + 1] == p2) ||
2476 (p->peers[i] == p2 && p->peers[i + 1] == p1))
2478 GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
2489 d = tunnel_notify_connection_broken (peer->tunnel, p1, p2);
2491 peer_d = peer_get_short (d); // FIXME
2492 next = peer_get_best_path (peer_d);
2493 tunnel_use_path (peer->tunnel, next);
2494 peer_connect (peer_d);
2496 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path END\n");
2501 * Add the path to the peer and update the path used to reach it in case this
2504 * @param peer_info Destination peer to add the path to.
2505 * @param path New path to add. Last peer must be the peer in arg 1.
2506 * Path will be either used of freed if already known.
2507 * @param trusted Do we trust that this path is real?
2510 peer_add_path (struct MeshPeer *peer_info, struct MeshPeerPath *path,
2513 struct MeshPeerPath *aux;
2517 if ((NULL == peer_info) || (NULL == path))
2520 path_destroy (path);
2523 if (path->peers[path->length - 1] != peer_info->id)
2526 path_destroy (path);
2529 if (2 >= path->length && GNUNET_NO == trusted)
2531 /* Only allow CORE to tell us about direct paths */
2532 path_destroy (path);
2535 for (l = 1; l < path->length; l++)
2537 if (path->peers[l] == myid)
2539 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shortening path by %u\n", l);
2540 for (l2 = 0; l2 < path->length - l; l2++)
2542 path->peers[l2] = path->peers[l + l2];
2547 GNUNET_realloc (path->peers, path->length * sizeof (GNUNET_PEER_Id));
2551 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "adding path [%u] to peer %s\n",
2552 path->length, peer2s (peer_info));
2554 l = path_get_length (path);
2557 path_destroy (path);
2561 GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
2562 for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
2564 l2 = path_get_length (aux);
2567 GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
2568 peer_info->path_tail, aux, path);
2573 if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
2575 path_destroy (path);
2580 GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head, peer_info->path_tail,
2587 * Add the path to the origin peer and update the path used to reach it in case
2588 * this is the shortest.
2589 * The path is given in peer_info -> destination, therefore we turn the path
2590 * upside down first.
2592 * @param peer_info Peer to add the path to, being the origin of the path.
2593 * @param path New path to add after being inversed.
2594 * Path will be either used or freed.
2595 * @param trusted Do we trust that this path is real?
2598 peer_add_path_to_origin (struct MeshPeer *peer_info,
2599 struct MeshPeerPath *path, int trusted)
2602 peer_add_path (peer_info, path, trusted);
2608 * Function called if a connection has been stalled for a while,
2609 * possibly due to a missed ACK. Poll the neighbor about its ACK status.
2611 * @param cls Closure (poll ctx).
2612 * @param tc TaskContext.
2615 connection_poll (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2617 struct MeshFlowControl *fc = cls;
2618 struct GNUNET_MESH_Poll msg;
2619 struct MeshConnection *c;
2621 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2622 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2628 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** Polling!\n");
2629 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** connection %s[%X]\n",
2630 peer2s (c->t->peer), c->id);
2632 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_POLL);
2633 msg.header.size = htons (sizeof (msg));
2634 msg.pid = htonl (fc->last_pid_sent);
2635 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** pid (%u)!\n", fc->last_pid_sent);
2636 send_prebuilt_message_connection (&msg.header, c, NULL, fc == &c->fwd_fc);
2637 fc->poll_time = GNUNET_TIME_STD_BACKOFF (fc->poll_time);
2638 fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
2639 &connection_poll, fc);
2644 * Build a PeerPath from the paths returned from the DHT, reversing the paths
2645 * to obtain a local peer -> destination path and interning the peer ids.
2647 * @return Newly allocated and created path
2649 static struct MeshPeerPath *
2650 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
2651 unsigned int get_path_length,
2652 const struct GNUNET_PeerIdentity *put_path,
2653 unsigned int put_path_length)
2655 struct MeshPeerPath *p;
2661 GNUNET_PEER_change_rc (myid, 1);
2662 i = get_path_length;
2663 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " GET has %d hops.\n", i);
2664 for (i--; i >= 0; i--)
2666 id = GNUNET_PEER_intern (&get_path[i]);
2667 if (p->length > 0 && id == p->peers[p->length - 1])
2669 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Optimizing 1 hop out.\n");
2670 GNUNET_PEER_change_rc (id, -1);
2674 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Adding from GET: %s.\n",
2675 GNUNET_i2s (&get_path[i]));
2677 p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2678 p->peers[p->length - 1] = id;
2681 i = put_path_length;
2682 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " PUT has %d hops.\n", i);
2683 for (i--; i >= 0; i--)
2685 id = GNUNET_PEER_intern (&put_path[i]);
2688 /* PUT path went through us, so discard the path up until now and start
2689 * from here to get a much shorter (and loop-free) path.
2694 if (p->length > 0 && id == p->peers[p->length - 1])
2696 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Optimizing 1 hop out.\n");
2697 GNUNET_PEER_change_rc (id, -1);
2701 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Adding from PUT: %s.\n",
2702 GNUNET_i2s (&put_path[i]));
2704 p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2705 p->peers[p->length - 1] = id;
2709 if (get_path_length > 0)
2710 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " (first of GET: %s)\n",
2711 GNUNET_i2s (&get_path[0]));
2712 if (put_path_length > 0)
2713 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " (first of PUT: %s)\n",
2714 GNUNET_i2s (&put_path[0]));
2715 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " In total: %d hops\n",
2717 for (i = 0; i < p->length; i++)
2719 struct GNUNET_PeerIdentity peer_id;
2721 GNUNET_PEER_resolve (p->peers[i], &peer_id);
2722 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " %u: %s\n", p->peers[i],
2723 GNUNET_i2s (&peer_id));
2731 * Adds a path to the peer_infos of all the peers in the path
2733 * @param p Path to process.
2734 * @param confirmed Whether we know if the path works or not.
2737 path_add_to_peers (struct MeshPeerPath *p, int confirmed)
2741 /* TODO: invert and add */
2742 for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
2743 for (i++; i < p->length; i++)
2745 struct MeshPeer *aux;
2746 struct MeshPeerPath *copy;
2748 aux = peer_get_short (p->peers[i]);
2749 copy = path_duplicate (p);
2750 copy->length = i + 1;
2751 peer_add_path (aux, copy, p->length < 3 ? GNUNET_NO : confirmed);
2757 * Search for a channel among the channels for a client
2759 * @param c the client whose channels to search in
2760 * @param chid the local id of the channel
2762 * @return channel handler, NULL if doesn't exist
2764 static struct MeshChannel *
2765 channel_get_by_local_id (struct MeshClient *c, MESH_ChannelNumber chid)
2767 if (0 == (chid & GNUNET_MESH_LOCAL_CHANNEL_ID_CLI))
2769 GNUNET_break_op (0);
2770 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CHID %X not a local chid\n", chid);
2773 if (chid >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV)
2774 return GNUNET_CONTAINER_multihashmap32_get (c->incoming_channels, chid);
2775 return GNUNET_CONTAINER_multihashmap32_get (c->own_channels, chid);
2779 * Search for a tunnel by global ID using full PeerIdentities.
2781 * @param t Tunnel containing the channel.
2782 * @param chid Public channel number.
2784 * @return channel handler, NULL if doesn't exist
2786 static struct MeshChannel *
2787 channel_get (struct MeshTunnel2 *t, MESH_ChannelNumber chid)
2789 struct MeshChannel *ch;
2794 for (ch = t->channel_head; NULL != ch; ch = ch->next)
2796 if (ch->gid == chid)
2805 * Change the tunnel state.
2807 * @param t Tunnel whose state to change.
2808 * @param state New state.
2811 tunnel_change_state (struct MeshTunnel2* t, enum MeshTunnelState state)
2813 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2814 "Tunnel %s state was %s\n",
2816 GNUNET_MESH_DEBUG_TS2S (t->state));
2817 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2818 "Tunnel %s state is now %s\n",
2820 GNUNET_MESH_DEBUG_TS2S (state));
2826 * Cache a message to be sent once tunnel is online.
2828 * @param t Tunnel to hold the message.
2829 * @param ch Channel the message is about.
2830 * @param msg Message itself (copy will be made).
2831 * @param fwd Is this fwd?
2834 tunnel_queue_data (struct MeshTunnel2 *t,
2835 struct MeshChannel *ch,
2836 struct GNUNET_MessageHeader *msg,
2839 struct MeshTunnelQueue *tq;
2840 uint16_t size = ntohs (msg->size);
2842 tq = GNUNET_malloc (sizeof (struct MeshTunnelQueue) + size);
2845 memcpy (&tq[1], msg, size);
2846 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tq);
2851 * Send all cached messages that we can, tunnel is online.
2853 * @param t Tunnel that holds the messages.
2854 * @param fwd Is this fwd?
2857 tunnel_send_queued_data (struct MeshTunnel2 *t, int fwd)
2859 struct MeshTunnelQueue *tq;
2860 struct MeshTunnelQueue *next;
2863 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2864 "tunnel_send_queued_data on %s\n",
2865 GNUNET_h2s (&t->id));
2866 room = tunnel_get_buffer (t, fwd);
2867 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
2868 for (tq = t->tq_head; NULL != tq && room > 0; tq = next)
2872 GNUNET_CONTAINER_DLL_remove (t->tq_head, t->tq_tail, tq);
2873 send_prebuilt_message_channel ((struct GNUNET_MessageHeader *) &tq[1],
2882 connection_change_state (struct MeshConnection* c,
2883 enum MeshConnectionState state)
2885 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2886 "Connection %s[%X] state was %s\n",
2887 peer2s (c->t->peer), c->id,
2888 GNUNET_MESH_DEBUG_CS2S (c->state));
2889 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2890 "Connection %s[%X] state is now %s\n",
2891 peer2s (c->t->peer), c->id,
2892 GNUNET_MESH_DEBUG_CS2S (state));
2898 * Add a client to a channel, initializing all needed data structures.
2900 * @param ch Channel to which add the client.
2901 * @param c Client which to add to the channel.
2904 channel_add_client (struct MeshChannel *ch, struct MeshClient *c)
2906 struct MeshTunnel2 *t = ch->t;
2908 if (NULL != ch->dest)
2914 /* Assign local id as destination */
2915 while (NULL != channel_get_by_local_id (c, t->next_local_chid))
2916 t->next_local_chid = (t->next_local_chid + 1) | GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
2917 ch->lid_dest = t->next_local_chid++;
2918 t->next_local_chid = t->next_local_chid | GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
2920 /* Store in client's hashmap */
2922 GNUNET_CONTAINER_multihashmap32_put (c->incoming_channels,
2924 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2933 static struct MeshConnection *
2934 tunnel_use_path (struct MeshTunnel2 *t, struct MeshPeerPath *p)
2936 struct MeshConnection *c;
2937 struct MeshPeer *peer;
2938 unsigned int own_pos;
2940 c = connection_new (&t->id, t->next_cid++);
2941 for (own_pos = 0; own_pos < p->length; own_pos++)
2943 if (p->peers[own_pos] == myid)
2946 if (own_pos > p->length - 1)
2949 connection_destroy (c);
2952 c->own_pos = own_pos;
2957 c->fwd_maintenance_task =
2958 GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
2959 &connection_fwd_keepalive, c);
2962 peer = connection_get_next_hop (c);
2963 GNUNET_CONTAINER_multihashmap_put (peer->connections, &c->t->id, c,
2964 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2965 peer = connection_get_prev_hop (c);
2966 GNUNET_CONTAINER_multihashmap_put (peer->connections, &c->t->id, c,
2967 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2973 * Notifies a tunnel that a connection has broken that affects at least
2974 * some of its peers. Sends a notification towards the root of the tree.
2975 * In case the peer is the owner of the tree, notifies the client that owns
2976 * the tunnel and tries to reconnect.
2978 * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
2980 * @param t Tunnel affected.
2981 * @param p1 Peer that got disconnected from p2.
2982 * @param p2 Peer that got disconnected from p1.
2984 * @return Short ID of the peer disconnected (either p1 or p2).
2985 * 0 if the tunnel remained unaffected.
2987 static GNUNET_PEER_Id
2988 tunnel_notify_connection_broken (struct MeshTunnel2* t,
2989 GNUNET_PEER_Id p1, GNUNET_PEER_Id p2)
2991 // if (myid != p1 && myid != p2) FIXME
2996 // if (tree_get_predecessor (t->tree) != 0)
2998 // /* We are the peer still connected, notify owner of the disconnection. */
2999 // struct GNUNET_MESH_PathBroken msg;
3000 // struct GNUNET_PeerIdentity neighbor;
3002 // msg.header.size = htons (sizeof (msg));
3003 // msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN);
3004 // GNUNET_PEER_resolve (t->id.oid, &msg.oid);
3005 // msg.tid = htonl (t->id.tid);
3006 // msg.peer1 = my_full_id;
3007 // GNUNET_PEER_resolve (pid, &msg.peer2);
3008 // GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &neighbor);
3009 // send_prebuilt_message (&msg.header, &neighbor, t);
3016 * Send an end-to-end FWD ACK message for the most recent in-sequence payload.
3018 * @param ch Channel this is about.
3019 * @param fwd Is for FWD traffic? (ACK dest->owner)
3022 channel_send_data_ack (struct MeshChannel *ch, int fwd)
3024 struct GNUNET_MESH_DataACK msg;
3025 struct MeshChannelReliability *rel;
3026 struct MeshReliableMessage *copy;
3031 if (GNUNET_NO == ch->reliable)
3036 rel = fwd ? ch->bck_rel : ch->fwd_rel;
3037 mid = fwd ? &ch->mid_recv_fwd : &ch->mid_recv_bck;
3038 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3039 "send_data_ack for %u\n",
3042 msg.header.type = htons (fwd ? GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK :
3043 GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK);
3044 msg.header.size = htons (sizeof (msg));
3045 msg.chid = htonl (ch->gid);
3046 msg.mid = htonl (*mid - 1);
3048 for (copy = rel->head_recv; NULL != copy; copy = copy->next)
3050 delta = copy->mid - *mid;
3053 mask = 0x1LL << delta;
3054 msg.futures |= mask;
3055 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3056 " setting bit for %u (delta %u) (%llX) -> %llX\n",
3057 copy->mid, delta, mask, msg.futures);
3059 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " final futures %llX\n", msg.futures);
3061 send_prebuilt_message_channel (&msg.header, ch, fwd);
3062 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_data_ack END\n");
3067 * Send an ACK informing the predecessor about the available buffer space.
3069 * Note that for fwd ack, the FWD mean forward *traffic* (root->dest),
3070 * the ACK itself goes "back" (dest->root).
3072 * @param c Connection on which to send the ACK.
3073 * @param fwd Is this FWD ACK? (Going dest->owner)
3076 connection_send_ack (struct MeshConnection *c, int fwd)
3078 struct MeshFlowControl *next_fc;
3079 struct MeshFlowControl *prev_fc;
3083 next_fc = fwd ? &c->fwd_fc : &c->bck_fc;
3084 prev_fc = fwd ? &c->bck_fc : &c->fwd_fc;
3086 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3087 "connection send %s ack on %s[%X]\n",
3088 fwd ? "FWD" : "BCK", GNUNET_h2s (&c->t->id), c->id);
3090 /* Check if we need to transmit the ACK */
3091 if (prev_fc->last_ack_sent - prev_fc->last_pid_recv > 3)
3093 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer > 3\n");
3094 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3095 " last pid recv: %u, last ack sent: %u\n",
3096 prev_fc->last_pid_recv, prev_fc->last_ack_sent);
3100 /* Ok, ACK might be necessary, what PID to ACK? */
3101 delta = next_fc->queue_max - next_fc->queue_n;
3102 ack = prev_fc->last_pid_recv + delta;
3103 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", ack);
3104 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3105 " last pid %u, last ack %u, qmax %u, q %u\n",
3106 prev_fc->last_pid_recv, prev_fc->last_ack_sent,
3107 next_fc->queue_max, next_fc->queue_n);
3108 if (ack == prev_fc->last_ack_sent)
3110 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not needed\n");
3114 prev_fc->last_ack_sent = ack;
3115 send_ack (c, ack, fwd);
3120 * Modify the mesh message TID from global to local and send to client.
3122 * @param ch Channel on which to send the message.
3123 * @param msg Message to modify and send.
3124 * @param c Client to send to.
3125 * @param tid Tunnel ID to use (c can be both owner and client).
3128 channel_send_client_to_tid (struct MeshChannel *ch,
3129 const struct GNUNET_MESH_Data *msg,
3130 struct MeshClient *c, MESH_ChannelNumber id)
3132 struct GNUNET_MESH_LocalData *copy;
3133 uint16_t size = ntohs (msg->header.size) - sizeof (struct GNUNET_MESH_Data);
3134 char cbuf[size + sizeof (struct GNUNET_MESH_LocalData)];
3136 if (size < sizeof (struct GNUNET_MessageHeader))
3138 GNUNET_break_op (0);
3146 copy = (struct GNUNET_MESH_LocalData *) cbuf;
3147 memcpy (©[1], &msg[1], size);
3148 copy->header.size = htons (sizeof (struct GNUNET_MESH_LocalData) + size);
3149 copy->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA);
3150 copy->id = htonl (id);
3151 GNUNET_SERVER_notification_context_unicast (nc, c->handle,
3152 ©->header, GNUNET_NO);
3156 * Modify the data message ID from global to local and send to client.
3158 * @param ch Channel on which to send the message.
3159 * @param msg Message to modify and send.
3160 * @param fwd Forward?
3163 channel_send_client_data (struct MeshChannel *ch,
3164 const struct GNUNET_MESH_Data *msg,
3168 channel_send_client_to_tid (ch, msg, ch->dest, ch->lid_dest);
3170 channel_send_client_to_tid (ch, msg, ch->root, ch->lid_root);
3175 * Send a buffered message to the client, for in order delivery or
3176 * as result of client ACK.
3178 * @param ch Channel on which to empty the message buffer.
3179 * @param c Client to send to.
3180 * @param rel Reliability structure to corresponding peer.
3181 * If rel == bck_rel, this is FWD data.
3184 channel_send_client_buffered_data (struct MeshChannel *ch,
3185 struct MeshClient *c,
3186 struct MeshChannelReliability *rel)
3188 struct MeshReliableMessage *copy;
3191 if (GNUNET_NO == rel->client_ready)
3193 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client not ready\n");
3197 mid = rel == ch->bck_rel ? &ch->mid_recv_fwd : &ch->mid_recv_bck;
3199 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data\n");
3200 copy = rel->head_recv;
3203 if (copy->mid == *mid || GNUNET_NO == ch->reliable)
3205 struct GNUNET_MESH_Data *msg = (struct GNUNET_MESH_Data *) ©[1];
3207 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3208 " have %u! now expecting %u\n",
3209 copy->mid, *mid + 1);
3210 channel_send_client_data (ch, msg, (rel == ch->bck_rel));
3213 GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
3218 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3219 " reliable && don't have %u, next is %u\n",
3225 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data END\n");
3230 * We have received a message out of order, or the client is not ready.
3231 * Buffer it until we receive an ACK from the client or the missing
3232 * message from the channel.
3234 * @param msg Message to buffer.
3235 * @param rel Reliability data to the corresponding direction.
3238 channel_rel_add_buffered_data (const struct GNUNET_MESH_Data *msg,
3239 struct MeshChannelReliability *rel)
3241 struct MeshReliableMessage *copy;
3242 struct MeshReliableMessage *prev;
3246 size = ntohs (msg->header.size);
3247 mid = ntohl (msg->mid);
3248 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data %u\n", mid);
3250 copy = GNUNET_malloc (sizeof (*copy) + size);
3253 memcpy (©[1], msg, size);
3257 // FIXME do something better than O(n), although n < 64...
3258 // FIXME start from the end (most messages are the latest ones)
3259 for (prev = rel->head_recv; NULL != prev; prev = prev->next)
3261 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " prev %u\n", prev->mid);
3262 if (GMC_is_pid_bigger (prev->mid, mid))
3264 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " bingo!\n");
3265 GNUNET_CONTAINER_DLL_insert_before (rel->head_recv, rel->tail_recv,
3270 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " insert at tail!\n");
3271 GNUNET_CONTAINER_DLL_insert_tail (rel->head_recv, rel->tail_recv, copy);
3272 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data END\n");
3277 * Destroy a reliable message after it has been acknowledged, either by
3278 * direct mid ACK or bitfield. Updates the appropriate data structures and
3279 * timers and frees all memory.
3281 * @param copy Message that is no longer needed: remote peer got it.
3284 rel_message_free (struct MeshReliableMessage *copy)
3286 struct MeshChannelReliability *rel;
3287 struct GNUNET_TIME_Relative time;
3290 time = GNUNET_TIME_absolute_get_duration (copy->timestamp);
3291 rel->expected_delay.rel_value_us *= 7;
3292 rel->expected_delay.rel_value_us += time.rel_value_us;
3293 rel->expected_delay.rel_value_us /= 8;
3295 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Freeing %u\n", copy->mid);
3296 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " n_sent %u\n", rel->n_sent);
3297 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! took %s\n",
3298 GNUNET_STRINGS_relative_time_to_string (time, GNUNET_NO));
3299 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! new expected delay %s\n",
3300 GNUNET_STRINGS_relative_time_to_string (rel->expected_delay,
3302 rel->retry_timer = rel->expected_delay;
3303 GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
3309 * Destroy all reliable messages queued for a channel,
3310 * during a channel destruction.
3311 * Frees the reliability structure itself.
3313 * @param rel Reliability data for a channel.
3316 channel_rel_free_all (struct MeshChannelReliability *rel)
3318 struct MeshReliableMessage *copy;
3319 struct MeshReliableMessage *next;
3324 for (copy = rel->head_recv; NULL != copy; copy = next)
3327 GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
3330 for (copy = rel->head_sent; NULL != copy; copy = next)
3333 GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
3336 if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
3337 GNUNET_SCHEDULER_cancel (rel->retry_task);
3343 * Mark future messages as ACK'd.
3345 * @param rel Reliability data.
3346 * @param msg DataACK message with a bitfield of future ACK'd messages.
3349 channel_rel_free_sent (struct MeshChannelReliability *rel,
3350 const struct GNUNET_MESH_DataACK *msg)
3352 struct MeshReliableMessage *copy;
3353 struct MeshReliableMessage *next;
3360 bitfield = msg->futures;
3361 mid = ntohl (msg->mid);
3362 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3363 "free_sent_reliable %u %llX\n",
3365 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3366 " rel %p, head %p\n",
3367 rel, rel->head_sent);
3368 for (i = 0, copy = rel->head_sent;
3369 i < 64 && NULL != copy && 0 != bitfield;
3372 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3373 " trying bit %u (mid %u)\n",
3376 if (0 == (bitfield & mask))
3379 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " set!\n");
3380 /* Bit was set, clear the bit from the bitfield */
3383 /* The i-th bit was set. Do we have that copy? */
3384 /* Skip copies with mid < target */
3385 target = mid + i + 1;
3386 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " target %u\n", target);
3387 while (NULL != copy && GMC_is_pid_bigger (target, copy->mid))
3390 /* Did we run out of copies? (previously freed, it's ok) */
3393 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "run out of copies...\n");
3397 /* Did we overshoot the target? (previously freed, it's ok) */
3398 if (GMC_is_pid_bigger (copy->mid, target))
3400 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " next copy %u\n", copy->mid);
3404 /* Now copy->mid == target, free it */
3406 rel_message_free (copy);
3409 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "free_sent_reliable END\n");
3414 * We haven't received an ACK after a certain time: restransmit the message.
3416 * @param cls Closure (MeshReliableMessage with the message to restransmit)
3417 * @param tc TaskContext.
3420 channel_retransmit_message (void *cls,
3421 const struct GNUNET_SCHEDULER_TaskContext *tc)
3423 struct MeshChannelReliability *rel = cls;
3424 struct MeshReliableMessage *copy;
3425 struct MeshPeerQueue *q;
3426 struct MeshChannel *ch;
3427 struct MeshConnection *c;
3428 struct GNUNET_MESH_Data *payload;
3429 struct MeshPeer *hop;
3432 rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
3433 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3437 copy = rel->head_sent;
3444 /* Search the message to be retransmitted in the outgoing queue.
3445 * Check only the queue for the connection that is going to be used,
3446 * if the message is stuck in some other connection's queue we shouldn't
3448 * - cancelling it and sending the new one doesn't guarantee it's delivery,
3449 * the old connection could be temporary stalled or the queue happened to
3450 * be long at time of insertion.
3451 * - not sending the new one could cause terrible delays the old connection
3454 payload = (struct GNUNET_MESH_Data *) ©[1];
3455 fwd = (rel == ch->fwd_rel);
3456 c = tunnel_get_connection (ch->t, fwd);
3457 hop = connection_get_hop (c, fwd);
3458 for (q = hop->queue_head; NULL != q; q = q->next)
3460 if (ntohs (payload->header.type) == q->type && ch == q->ch)
3462 struct GNUNET_MESH_Data *queued_data = q->cls;
3464 if (queued_data->mid == payload->mid)
3469 /* Message not found in the queue that we are going to use. */
3472 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! RETRANSMIT %u\n", copy->mid);
3474 send_prebuilt_message_channel (&payload->header, ch, ch->fwd_rel == rel);
3475 GNUNET_STATISTICS_update (stats, "# data retransmitted", 1, GNUNET_NO);
3479 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! ALREADY IN QUEUE %u\n", copy->mid);
3482 rel->retry_timer = GNUNET_TIME_STD_BACKOFF (rel->retry_timer);
3483 rel->retry_task = GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
3484 &channel_retransmit_message,
3490 * Send an ACK to a client is needed.
3492 * @param ch Channel this is regarding.
3493 * @param fwd Is this about fwd traffic? (ACk goes the opposite direction).
3496 channel_send_client_ack (struct MeshChannel *ch, int fwd)
3498 struct MeshClient *c;
3500 /* Client to receive the ACK (fwd indicates traffic to be ACK'd) */
3501 c = fwd ? ch->root : ch->dest;
3503 if (GNUNET_YES == c->blocked)
3504 send_local_ack (ch, c, fwd);
3509 * Send ACK on one or more connections due to buffer space to the client.
3511 * @param ch Channel which has some free buffer space.
3512 * @param buffer Buffer space.
3513 * @param fwd Is this in the FWD direction?
3516 channel_send_connection_ack (struct MeshChannel *ch, uint32_t buffer, int fwd)
3518 struct MeshTunnel2 *t = ch->t;
3519 struct MeshConnection *c;
3520 struct MeshFlowControl *fc;
3525 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3526 "Channel send %s ack on %s:%X\n",
3527 fwd ? "FWD" : "BCK", GNUNET_h2s (&ch->t->id), ch->gid);
3529 /* Count connections, how many messages are already allowed */
3530 for (cs = 0, allowed = 0, c = t->connection_head; NULL != c; c = c->next)
3532 fc = fwd ? &c->fwd_fc : &c->bck_fc;
3533 if (GMC_is_pid_bigger(fc->last_pid_recv, fc->last_ack_sent))
3538 allowed += fc->last_ack_sent - fc->last_pid_recv;
3542 /* Make sure there is no overflow */
3543 if (allowed > buffer)
3549 /* Authorize connections to send more data */
3550 to_allow = buffer - allowed;
3551 for (c = t->connection_head; NULL != c && to_allow > 0; c = c->next)
3553 fc = fwd ? &c->fwd_fc : &c->bck_fc;
3554 if (fc->last_ack_sent - fc->last_pid_recv > 64 / 3)
3558 send_ack (c, fc->last_ack_sent + 1, fwd);
3562 GNUNET_break (to_allow == 0);
3567 * Send keepalive packets for a connection.
3569 * @param c Connection to keep alive..
3570 * @param fwd Is this a FWD keepalive? (owner -> dest).
3573 connection_keepalive (struct MeshConnection *c, int fwd)
3575 struct GNUNET_MESH_ConnectionKeepAlive *msg;
3576 size_t size = sizeof (struct GNUNET_MESH_ConnectionKeepAlive);
3580 type = fwd ? GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE :
3581 GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE;
3583 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3584 "sending %s keepalive for connection %s[%d]\n",
3585 fwd ? "FWD" : "BCK",
3586 peer2s (c->t->peer),
3589 msg = (struct GNUNET_MESH_ConnectionKeepAlive *) cbuf;
3590 msg->header.size = htons (size);
3591 msg->header.type = htons (type);
3592 msg->cid = htonl (c->id);
3593 msg->tid = c->t->id;
3595 send_prebuilt_message_connection (&msg->header, c, NULL, fwd);
3600 * Send CONNECTION_{CREATE/ACK} packets for a connection.
3602 * @param c Connection for which to send the message.
3603 * @param fwd If GNUNET_YES, send CREATE, otherwise send ACK.
3606 connection_recreate (struct MeshConnection *c, int fwd)
3608 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "sending connection recreate\n");
3610 send_connection_create (c);
3612 send_connection_ack (c, GNUNET_NO);
3617 * Generic connection timer management.
3618 * Depending on the role of the peer in the connection will send the
3619 * appropriate message (build or keepalive)
3621 * @param c Conncetion to maintain.
3622 * @param fwd Is FWD?
3625 connection_maintain (struct MeshConnection *c, int fwd)
3627 if (MESH_TUNNEL_SEARCHING == c->t->state)
3629 /* TODO DHT GET with RO_BART */
3634 case MESH_CONNECTION_NEW:
3636 case MESH_CONNECTION_SENT:
3637 connection_recreate (c, fwd);
3639 case MESH_CONNECTION_READY:
3640 connection_keepalive (c, fwd);
3649 connection_fwd_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3651 struct MeshConnection *c = cls;
3653 c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
3654 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3657 connection_maintain (c, GNUNET_YES);
3658 c->fwd_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
3659 &connection_fwd_keepalive,
3665 connection_bck_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3667 struct MeshConnection *c = cls;
3669 c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
3670 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3673 connection_maintain (c, GNUNET_NO);
3674 c->bck_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
3675 &connection_bck_keepalive,
3681 * Send a message to all peers in this connection that the connection
3682 * is no longer valid.
3684 * If some peer should not receive the message, it should be zero'ed out
3685 * before calling this function.
3687 * @param c The connection whose peers to notify.
3690 connection_send_destroy (struct MeshConnection *c)
3692 struct GNUNET_MESH_ConnectionDestroy msg;
3694 msg.header.size = htons (sizeof (msg));
3695 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);;
3696 msg.cid = htonl (c->id);
3698 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3699 " sending connection destroy for connection %s[%X]\n",
3700 peer2s (c->t->peer),
3703 send_prebuilt_message_connection (&msg.header, c, NULL, GNUNET_YES);
3704 send_prebuilt_message_connection (&msg.header, c, NULL, GNUNET_NO);
3705 c->destroy = GNUNET_YES;
3710 * Send a message to all clients (local and remote) of this channel
3711 * notifying that the channel is no longer valid.
3713 * If some peer or client should not receive the message,
3714 * should be zero'ed out before calling this function.
3716 * @param ch The channel whose clients to notify.
3719 channel_send_destroy (struct MeshChannel *ch)
3721 struct GNUNET_MESH_ChannelDestroy msg;
3723 msg.header.size = htons (sizeof (msg));
3724 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY);
3725 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3726 " sending channel destroy for channel %s:%X\n",
3727 peer2s (ch->t->peer),
3730 if (NULL != ch->root)
3732 msg.chid = htonl (ch->lid_root);
3733 send_local_channel_destroy (ch, GNUNET_NO);
3737 msg.chid = htonl (ch->gid);
3738 send_prebuilt_message_channel (&msg.header, ch, GNUNET_NO);
3741 if (NULL != ch->dest)
3743 msg.chid = htonl (ch->lid_dest);
3744 send_local_channel_destroy (ch, GNUNET_YES);
3748 msg.chid = htonl (ch->gid);
3749 send_prebuilt_message_channel (&msg.header, ch, GNUNET_YES);
3757 * @param tid Tunnel ID.
3759 static struct MeshTunnel2 *
3760 tunnel_new (const struct GNUNET_HashCode *tid)
3762 struct MeshTunnel2 *t;
3764 t = GNUNET_new (struct MeshTunnel2);
3768 GNUNET_CONTAINER_multihashmap_put (tunnels, tid, t,
3769 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3783 * @param tid Tunnel ID.
3785 static struct MeshTunnel2 *
3786 tunnel_get (const struct GNUNET_HashCode *tid)
3788 return GNUNET_CONTAINER_multihashmap_get (tunnels, tid);
3793 * Add a connection to a tunnel.
3796 * @param c Connection.
3799 tunnel_add_connection (struct MeshTunnel2 *t, struct MeshConnection *c)
3802 GNUNET_CONTAINER_DLL_insert_tail (t->connection_head, t->connection_tail, c);
3807 * Initialize a Flow Control structure to the initial state.
3809 * @param fc Flow Control structure to initialize.
3812 fc_init (struct MeshFlowControl *fc)
3815 fc->last_pid_sent = (uint32_t) -1; /* Next (expected) = 0 */
3816 fc->last_pid_recv = (uint32_t) -1;
3817 fc->last_ack_sent = (uint32_t) 0;
3818 fc->last_ack_recv = (uint32_t) 0;
3819 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
3820 fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
3822 fc->queue_max = (max_msgs_queue / max_connections) + 1;
3826 static struct MeshConnection *
3827 connection_new (struct GNUNET_HashCode *tid, uint32_t cid)
3829 struct MeshConnection *c;
3830 struct MeshTunnel2 *t;
3832 t = tunnel_get (tid);
3835 t = tunnel_new (tid);
3843 c = GNUNET_new (struct MeshConnection);
3845 fc_init (&c->fwd_fc);
3846 fc_init (&c->bck_fc);
3849 tunnel_add_connection (t, c);
3856 * Find a connection.
3858 * @param tid Tunnel ID.
3859 * @param cid Connection ID.
3861 static struct MeshConnection *
3862 connection_get (const struct GNUNET_HashCode *tid, uint32_t cid)
3864 struct MeshConnection *c;
3865 struct MeshTunnel2 *t;
3867 t = tunnel_get (tid);
3870 for (c = t->connection_head; NULL != c; c = c->next)
3879 connection_destroy (struct MeshConnection *c)
3881 struct MeshPeer *peer;
3886 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying connection %s[%X]\n",
3887 peer2s (c->t->peer),
3890 /* Cancel all traffic */
3891 connection_cancel_queues (c, GNUNET_YES);
3892 connection_cancel_queues (c, GNUNET_NO);
3894 /* Cancel maintainance task (keepalive/timeout) */
3895 if (GNUNET_SCHEDULER_NO_TASK != c->fwd_maintenance_task)
3896 GNUNET_SCHEDULER_cancel (c->fwd_maintenance_task);
3897 if (GNUNET_SCHEDULER_NO_TASK != c->bck_maintenance_task)
3898 GNUNET_SCHEDULER_cancel (c->bck_maintenance_task);
3900 /* Deregister from neighbors */
3901 peer = connection_get_next_hop (c);
3903 GNUNET_CONTAINER_multihashmap_remove (peer->connections, &c->t->id, c);
3904 peer = connection_get_prev_hop (c);
3906 GNUNET_CONTAINER_multihashmap_remove (peer->connections, &c->t->id, c);
3909 GNUNET_STATISTICS_update (stats, "# connections", -1, GNUNET_NO);
3910 GNUNET_CONTAINER_DLL_remove (c->t->connection_head, c->t->connection_tail, c);
3916 tunnel_destroy (struct MeshTunnel2 *t)
3918 struct MeshConnection *c;
3919 struct MeshConnection *next;
3924 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n",
3927 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &t->id, t))
3930 for (c = t->connection_head; NULL != c; c = next)
3933 connection_destroy (c);
3936 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
3943 * Tunnel is empty: destroy it.
3945 * Notifies all connections about the destruction.
3947 * @param t Tunnel to destroy.
3950 tunnel_destroy_empty (struct MeshTunnel2 *t)
3952 struct MeshConnection *c;
3954 for (c = t->connection_head; NULL != c; c = c->next)
3956 if (GNUNET_NO == c->destroy)
3957 connection_send_destroy (c);
3960 if (0 == t->pending_messages)
3963 t->destroy = GNUNET_YES;
3968 * Destroy tunnel if empty (no more channels).
3970 * @param t Tunnel to destroy if empty.
3973 tunnel_destroy_if_empty (struct MeshTunnel2 *t)
3975 if (NULL != t->channel_head)
3978 tunnel_destroy_empty (t);
3983 * Destroy a channel and free all resources.
3985 * @param ch Channel to destroy.
3988 channel_destroy (struct MeshChannel *ch)
3990 struct MeshClient *c;
3998 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap32_remove (c->own_channels,
4009 GNUNET_CONTAINER_multihashmap32_remove (c->incoming_channels,
4016 channel_rel_free_all (ch->fwd_rel);
4017 channel_rel_free_all (ch->bck_rel);
4019 GNUNET_CONTAINER_DLL_remove (ch->t->channel_head, ch->t->channel_tail, ch);
4020 GNUNET_STATISTICS_update (stats, "# channels", -1, GNUNET_NO);
4026 * Create a new channel.
4028 * @param t Tunnel this channel is in.
4029 * @param owner Client that owns the channel, NULL for foreign channels.
4030 * @param lid_root Local ID for root client.
4032 * @return A new initialized channel. NULL on error.
4034 static struct MeshChannel *
4035 channel_new (struct MeshTunnel2 *t,
4036 struct MeshClient *owner, MESH_ChannelNumber lid_root)
4038 struct MeshChannel *ch;
4040 ch = GNUNET_new (struct MeshChannel);
4042 ch->lid_root = lid_root;
4045 GNUNET_CONTAINER_DLL_insert (t->channel_head, t->channel_tail, ch);
4047 GNUNET_STATISTICS_update (stats, "# channels", 1, GNUNET_NO);
4051 while (NULL != channel_get (t, t->next_chid))
4052 t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
4053 ch->gid = t->next_chid;
4054 t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
4057 GNUNET_CONTAINER_multihashmap32_put (owner->own_channels, lid_root, ch,
4058 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
4061 channel_destroy (ch);
4062 GNUNET_SERVER_receive_done (owner->handle, GNUNET_SYSERR);
4072 * Set options in a channel, extracted from a bit flag field
4074 * @param ch Channel to set options to.
4075 * @param options Bit array in host byte order.
4078 channel_set_options (struct MeshChannel *ch, uint32_t options)
4080 ch->nobuffer = (options & GNUNET_MESH_OPTION_NOBUFFER) != 0 ?
4081 GNUNET_YES : GNUNET_NO;
4082 ch->reliable = (options & GNUNET_MESH_OPTION_RELIABLE) != 0 ?
4083 GNUNET_YES : GNUNET_NO;
4088 * Iterator for deleting each channel whose client endpoint disconnected.
4090 * @param cls Closure (client that has disconnected).
4091 * @param key The local channel id (used to access the hashmap).
4092 * @param value The value stored at the key (channel to destroy).
4094 * @return GNUNET_OK, keep iterating.
4097 channel_destroy_iterator (void *cls,
4101 struct MeshChannel *ch = value;
4102 struct MeshClient *c = cls;
4103 struct MeshTunnel2 *t;
4105 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4106 " Channel %X (%X / %X) destroy, due to client %u shutdown.\n",
4107 ch->gid, ch->lid_root, ch->lid_dest, c->id);
4111 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is destination.\n", c->id);
4116 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is owner.\n", c->id);
4121 channel_send_destroy (ch);
4122 channel_destroy (ch);
4123 tunnel_destroy_if_empty (t);
4130 * Remove client's ports from the global hashmap on disconnect.
4132 * @param cls Closure (unused).
4134 * @param value Client structure.
4136 * @return GNUNET_OK, keep iterating.
4139 client_release_ports (void *cls,
4145 res = GNUNET_CONTAINER_multihashmap32_remove (ports, key, value);
4146 if (GNUNET_YES != res)
4149 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4150 "Port %u by client %p was not registered.\n",
4158 * Timeout function due to lack of keepalive/traffic from the owner.
4159 * Destroys connection if called.
4161 * @param cls Closure (connection to destroy).
4162 * @param tc TaskContext.
4165 connection_fwd_timeout (void *cls,
4166 const struct GNUNET_SCHEDULER_TaskContext *tc)
4168 struct MeshConnection *c = cls;
4170 c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4171 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4173 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4174 "Connection %s[%X] FWD timed out. Destroying.\n",
4175 peer2s (c->t->peer),
4178 if (connection_is_origin (c, GNUNET_YES)) /* If local, leave. */
4181 connection_destroy (c);
4186 * Timeout function due to lack of keepalive/traffic from the destination.
4187 * Destroys connection if called.
4189 * @param cls Closure (connection to destroy).
4190 * @param tc TaskContext
4193 connection_bck_timeout (void *cls,
4194 const struct GNUNET_SCHEDULER_TaskContext *tc)
4196 struct MeshConnection *c = cls;
4198 c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4199 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4202 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4203 "Connection %s[%X] FWD timed out. Destroying.\n",
4204 peer2s (c->t->peer),
4207 if (connection_is_origin (c, GNUNET_NO)) /* If local, leave. */
4210 connection_destroy (c);
4215 * Resets the connection timeout task, some other message has done the
4217 * - For the first peer on the direction this means to send
4218 * a keepalive or a path confirmation message (either create or ACK).
4219 * - For all other peers, this means to destroy the connection,
4220 * due to lack of activity.
4221 * Starts the tiemout if no timeout was running (connection just created).
4223 * @param c Connection whose timeout to reset.
4224 * @param fwd Is this forward?
4226 * TODO use heap to improve efficiency of scheduler.
4229 connection_reset_timeout (struct MeshConnection *c, int fwd)
4231 GNUNET_SCHEDULER_TaskIdentifier *ti;
4232 GNUNET_SCHEDULER_Task f;
4234 ti = fwd ? &c->fwd_maintenance_task : &c->bck_maintenance_task;
4236 if (GNUNET_SCHEDULER_NO_TASK != *ti)
4237 GNUNET_SCHEDULER_cancel (*ti);
4239 if (connection_is_origin (c, fwd)) /* Endpoint */
4241 f = fwd ? &connection_fwd_keepalive : &connection_bck_keepalive;
4242 *ti = GNUNET_SCHEDULER_add_delayed (refresh_connection_time, f, c);
4246 struct GNUNET_TIME_Relative delay;
4248 delay = GNUNET_TIME_relative_multiply (refresh_connection_time, 4);
4249 f = fwd ? &connection_fwd_timeout : &connection_bck_timeout;
4250 *ti = GNUNET_SCHEDULER_add_delayed (delay, f, c);
4256 * Iterator to notify all connections of a broken link. Mark connections
4257 * to destroy after all traffic has been sent.
4259 * @param cls Closure (peer disconnected).
4260 * @param key Current key code (tid).
4261 * @param value Value in the hash map (connection).
4263 * @return GNUNET_YES if we should continue to iterate,
4267 connection_broken (void *cls,
4268 const struct GNUNET_HashCode *key,
4271 struct MeshPeer *peer = cls;
4272 struct MeshConnection *c = value;
4273 struct GNUNET_MESH_ConnectionBroken msg;
4276 fwd = peer == connection_get_prev_hop (c);
4277 connection_cancel_queues (c, !fwd);
4279 msg.header.size = htons (sizeof (struct GNUNET_MESH_ConnectionBroken));
4280 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN);
4281 msg.cid = htonl (c->id);
4283 msg.peer1 = my_full_id;
4284 msg.peer2 = *GNUNET_PEER_resolve2 (peer->id);
4285 send_prebuilt_message_connection (&msg.header, c, NULL, fwd);
4286 c->destroy = GNUNET_YES;
4291 /******************************************************************************/
4292 /**************** MESH NETWORK HANDLER HELPERS ***********************/
4293 /******************************************************************************/
4296 * Free a transmission that was already queued with all resources
4297 * associated to the request.
4299 * @param queue Queue handler to cancel.
4300 * @param clear_cls Is it necessary to free associated cls?
4303 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
4305 struct MeshPeer *peer;
4306 struct MeshFlowControl *fc;
4311 GNUNET_assert (NULL != queue->c);
4312 fc = fwd ? &queue->c->fwd_fc : &queue->c->bck_fc;
4314 if (GNUNET_YES == clear_cls)
4316 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " queue destroy type %s\n",
4317 GNUNET_MESH_DEBUG_M2S (queue->type));
4318 switch (queue->type)
4320 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
4321 case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
4322 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "destroying a DESTROY message\n");
4323 GNUNET_break (GNUNET_YES == queue->c->destroy);
4325 case GNUNET_MESSAGE_TYPE_MESH_FWD:
4326 case GNUNET_MESSAGE_TYPE_MESH_BCK:
4327 case GNUNET_MESSAGE_TYPE_MESH_ACK:
4328 case GNUNET_MESSAGE_TYPE_MESH_POLL:
4329 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
4330 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
4331 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " prebuilt message\n");;
4332 GNUNET_free_non_null (queue->cls);
4337 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, " type %s unknown!\n",
4338 GNUNET_MESH_DEBUG_M2S (queue->type));
4342 GNUNET_CONTAINER_DLL_remove (peer->queue_head, peer->queue_tail, queue);
4346 if (NULL != queue->c)
4348 queue->c->pending_messages--;
4349 if (NULL != queue->c->t)
4351 queue->c->t->pending_messages--;
4355 GNUNET_free (queue);
4360 queue_send (void *cls, size_t size, void *buf)
4362 struct MeshPeer *peer = cls;
4363 struct MeshFlowControl *fc;
4364 struct MeshConnection *c;
4365 struct GNUNET_MessageHeader *msg;
4366 struct MeshPeerQueue *queue;
4367 struct MeshTunnel2 *t;
4368 const struct GNUNET_PeerIdentity *dst_id;
4374 peer->core_transmit = NULL;
4375 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Queue send\n");
4377 if (NULL == buf || 0 == size)
4379 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Buffer size 0.\n");
4384 queue = peer_get_first_message (peer);
4387 GNUNET_break (0); /* Core tmt_rdy should've been canceled */
4392 fc = fwd ? &c->fwd_fc : &c->bck_fc;
4395 dst_id = GNUNET_PEER_resolve2 (peer->id);
4396 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* towards %s\n", GNUNET_i2s (dst_id));
4397 /* Check if buffer size is enough for the message */
4398 if (queue->size > size)
4400 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* not enough room, reissue\n");
4401 peer->core_transmit =
4402 GNUNET_CORE_notify_transmit_ready (core_handle,
4405 GNUNET_TIME_UNIT_FOREVER_REL,
4412 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* size ok\n");
4414 t = (NULL != c) ? c->t : NULL;
4418 switch (queue->type)
4420 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
4421 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
4422 case GNUNET_MESSAGE_TYPE_MESH_FWD:
4423 case GNUNET_MESSAGE_TYPE_MESH_BCK:
4424 case GNUNET_MESSAGE_TYPE_MESH_ACK:
4425 case GNUNET_MESSAGE_TYPE_MESH_POLL:
4426 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4428 GNUNET_MESH_DEBUG_M2S (queue->type));
4430 case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4431 case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4432 data_size = send_core_data_raw (queue->cls, size, buf);
4433 msg = (struct GNUNET_MessageHeader *) buf;
4434 type = ntohs (msg->type);
4436 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
4437 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* path create\n");
4438 if (connection_is_origin (c, GNUNET_YES))
4439 data_size = send_core_connection_create (queue->c, size, buf);
4441 data_size = send_core_data_raw (queue->cls, size, buf);
4443 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
4444 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* path ack\n");
4445 if (connection_is_origin (c, GNUNET_NO))
4446 data_size = send_core_connection_ack (queue->c, size, buf);
4448 data_size = send_core_data_raw (queue->cls, size, buf);
4452 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "* type unknown: %u\n",
4457 if (0 < drop_percent &&
4458 GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 101) < drop_percent)
4460 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4461 "Dropping message of type %s\n",
4462 GNUNET_MESH_DEBUG_M2S (queue->type));
4466 /* Send ACK if needed, after accounting for sent ID in fc->queue_n */
4469 case GNUNET_MESSAGE_TYPE_MESH_FWD:
4470 case GNUNET_MESSAGE_TYPE_MESH_BCK:
4471 pid = ntohl ( ((struct GNUNET_MESH_Encrypted *) buf)->pid );
4472 fc->last_pid_sent = pid;
4473 if (NULL != queue->ch)
4474 channel_send_client_ack (queue->ch, fwd);
4476 connection_send_ack (c, fwd);
4482 /* Free queue, but cls was freed by send_core_* */
4483 queue_destroy (queue, GNUNET_NO);
4485 /* If more data in queue, send next */
4486 queue = peer_get_first_message (peer);
4489 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* more data!\n");
4490 if (NULL == peer->core_transmit) {
4491 peer->core_transmit =
4492 GNUNET_CORE_notify_transmit_ready(core_handle,
4495 GNUNET_TIME_UNIT_FOREVER_REL,
4503 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4504 "* tmt rdy called somewhere else\n");
4506 if (GNUNET_SCHEDULER_NO_TASK == fc->poll_task)
4508 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "* %s starting poll timeout\n");
4510 GNUNET_SCHEDULER_add_delayed (fc->poll_time, &connection_poll, fc);
4515 if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
4517 GNUNET_SCHEDULER_cancel (fc->poll_task);
4518 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
4523 c->pending_messages--;
4524 if (GNUNET_YES == c->destroy && 0 == c->pending_messages)
4526 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* destroying connection!\n");
4527 connection_destroy (c);
4533 t->pending_messages--;
4534 if (GNUNET_YES == t->destroy && 0 == t->pending_messages)
4536 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* destroying tunnel!\n");
4540 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Return %d\n", data_size);
4546 queue_add (void *cls, uint16_t type, size_t size,
4547 struct MeshConnection *c,
4548 struct MeshChannel *ch,
4551 struct MeshPeerQueue *queue;
4552 struct MeshFlowControl *fc;
4553 struct MeshPeer *peer;
4556 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4557 "queue add %s %s (%u) on c %p, ch %p\n",
4558 fwd ? "FWD" : "BCK", GNUNET_MESH_DEBUG_M2S (type), size, c, ch);
4559 GNUNET_assert (NULL != c);
4561 fc = fwd ? &c->fwd_fc : &c->bck_fc;
4562 peer = fwd ? connection_get_next_hop (c) : connection_get_prev_hop (c);
4572 if (GNUNET_MESSAGE_TYPE_MESH_POLL == type ||
4573 GNUNET_MESSAGE_TYPE_MESH_ACK == type)
4577 ( (NULL != ch->root && GNUNET_MESSAGE_TYPE_MESH_FWD == type) ||
4578 (NULL != ch->dest && GNUNET_MESSAGE_TYPE_MESH_BCK == type) ))
4581 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "priority %d\n", priority);
4582 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "fc %p\n", fc);
4583 if (fc->queue_n >= fc->queue_max && 0 == priority)
4585 GNUNET_STATISTICS_update (stats, "# messages dropped (buffer full)",
4588 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4589 "queue full: %u/%u\n",
4590 fc->queue_n, fc->queue_max);
4591 return; /* Drop this message */
4594 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "pid %u\n", fc->last_pid_sent);
4595 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "ack %u\n", fc->last_ack_recv);
4596 if (GMC_is_pid_bigger (fc->last_pid_sent + 1, fc->last_ack_recv) &&
4597 GNUNET_SCHEDULER_NO_TASK == fc->poll_task)
4599 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4600 "no buffer space (%u > %u): starting poll\n",
4601 fc->last_pid_sent + 1, fc->last_ack_recv);
4602 fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
4606 queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
4614 if (100 <= priority)
4615 GNUNET_CONTAINER_DLL_insert (peer->queue_head, peer->queue_tail, queue);
4617 GNUNET_CONTAINER_DLL_insert_tail (peer->queue_head, peer->queue_tail, queue);
4619 if (NULL == peer->core_transmit)
4621 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4622 "calling core tmt rdy towards %s\n",
4624 peer->core_transmit =
4625 GNUNET_CORE_notify_transmit_ready (core_handle,
4628 GNUNET_TIME_UNIT_FOREVER_REL,
4629 GNUNET_PEER_resolve2 (peer->id),
4636 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4637 "core tmt rdy towards %s already called\n",
4641 c->pending_messages++;
4642 c->t->pending_messages++;
4648 /******************************************************************************/
4649 /******************** MESH NETWORK HANDLERS **************************/
4650 /******************************************************************************/
4654 * Generic handler for mesh network payload traffic.
4656 * @param t Tunnel on which we got this message.
4657 * @param message Unencryted data message.
4658 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
4660 * @return GNUNET_OK to keep the connection open,
4661 * GNUNET_SYSERR to close it (signal serious error)
4664 handle_data (struct MeshTunnel2 *t, const struct GNUNET_MESH_Data *msg, int fwd)
4666 struct MeshChannelReliability *rel;
4667 struct MeshChannel *ch;
4668 struct MeshClient *c;
4675 size = ntohs (msg->header.size);
4677 sizeof (struct GNUNET_MESH_Data) +
4678 sizeof (struct GNUNET_MessageHeader))
4683 type = ntohs (msg->header.type);
4684 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message\n",
4685 GNUNET_MESH_DEBUG_M2S (type));
4686 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
4687 GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
4690 ch = channel_get (t, ntohl (msg->chid));
4693 GNUNET_STATISTICS_update (stats, "# data on unknown channel", 1, GNUNET_NO);
4694 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel unknown\n");
4698 /* Initialize FWD/BCK data */
4699 c = fwd ? ch->dest : ch->root;
4700 rel = fwd ? ch->bck_rel : ch->fwd_rel;
4701 mid_recv = fwd ? &ch->mid_recv_fwd : &ch->mid_recv_bck;
4709 tunnel_change_state (t, MESH_TUNNEL_READY);
4711 GNUNET_STATISTICS_update (stats, "# data received", 1, GNUNET_NO);
4713 mid = ntohl (msg->mid);
4714 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " mid %u\n", mid);
4716 if (GNUNET_NO == ch->reliable ||
4717 ( !GMC_is_pid_bigger (*mid_recv, mid) &&
4718 GMC_is_pid_bigger (*mid_recv + 64, mid) ) )
4720 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! RECV %u\n", mid);
4721 if (GNUNET_YES == ch->reliable)
4723 /* Is this the exact next expected messasge? */
4724 if (mid == *mid_recv)
4726 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "as expected\n");
4727 *mid_recv = *mid_recv + 1;
4728 channel_send_client_data (ch, msg, fwd);
4729 channel_send_client_buffered_data (ch, c, rel);
4733 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "save for later\n");
4734 channel_rel_add_buffered_data (msg, rel);
4737 else /* Tunnel unreliable, send to clients directly */
4739 channel_send_client_data (ch, msg, fwd);
4744 GNUNET_break_op (0);
4745 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4746 " MID %u not expected (%u - %u), dropping!\n",
4747 mid, *mid_recv, *mid_recv + 64);
4750 channel_send_data_ack (ch, fwd);
4755 * Handler for mesh network traffic end-to-end ACKs.
4757 * @param t Tunnel on which we got this message.
4758 * @param message Data message.
4759 * @param fwd Is this a fwd ACK? (dest->orig)
4761 * @return GNUNET_OK to keep the connection open,
4762 * GNUNET_SYSERR to close it (signal serious error)
4765 handle_data_ack (struct MeshTunnel2 *t,
4766 const struct GNUNET_MESH_DataACK *msg, int fwd)
4768 struct MeshChannelReliability *rel;
4769 struct MeshReliableMessage *copy;
4770 struct MeshReliableMessage *next;
4771 struct MeshChannel *ch;
4776 type = ntohs (msg->header.type);
4777 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a %s message!\n",
4778 GNUNET_MESH_DEBUG_M2S (type));
4779 ch = channel_get (t, ntohl (msg->chid));
4782 GNUNET_STATISTICS_update (stats, "# ack on unknown channel", 1, GNUNET_NO);
4785 ack = ntohl (msg->mid);
4786 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! %s ACK %u\n",
4787 (GNUNET_YES == fwd) ? "FWD" : "BCK", ack);
4789 if (GNUNET_YES == fwd)
4802 for (work = GNUNET_NO, copy = rel->head_sent; copy != NULL; copy = next)
4804 if (GMC_is_pid_bigger (copy->mid, ack))
4806 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! head %u, out!\n", copy->mid);
4807 channel_rel_free_sent (rel, msg);
4811 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! id %u\n", copy->mid);
4813 rel_message_free (copy);
4815 /* ACK client if needed */
4816 // channel_send_ack (t, type, GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK == type);
4818 /* If some message was free'd, update the retransmission delay*/
4819 if (GNUNET_YES == work)
4821 if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
4823 GNUNET_SCHEDULER_cancel (rel->retry_task);
4824 if (NULL == rel->head_sent)
4826 rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
4830 struct GNUNET_TIME_Absolute new_target;
4831 struct GNUNET_TIME_Relative delay;
4833 delay = GNUNET_TIME_relative_multiply (rel->retry_timer,
4834 MESH_RETRANSMIT_MARGIN);
4835 new_target = GNUNET_TIME_absolute_add (rel->head_sent->timestamp,
4837 delay = GNUNET_TIME_absolute_get_remaining (new_target);
4839 GNUNET_SCHEDULER_add_delayed (delay,
4840 &channel_retransmit_message,
4852 * Core handler for connection creation.
4854 * @param cls Closure (unused).
4855 * @param peer Sender (neighbor).
4856 * @param message Message.
4858 * @return GNUNET_OK to keep the connection open,
4859 * GNUNET_SYSERR to close it (signal serious error)
4862 handle_mesh_connection_create (void *cls,
4863 const struct GNUNET_PeerIdentity *peer,
4864 const struct GNUNET_MessageHeader *message)
4866 struct GNUNET_MESH_ConnectionCreate *msg;
4867 struct GNUNET_PeerIdentity *id;
4868 struct GNUNET_HashCode *tid;
4869 struct MeshPeerPath *path;
4870 struct MeshPeer *dest_peer;
4871 struct MeshPeer *orig_peer;
4872 struct MeshConnection *c;
4873 unsigned int own_pos;
4878 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection create msg\n");
4881 size = ntohs (message->size);
4882 if (size < sizeof (struct GNUNET_MESH_ConnectionCreate))
4884 GNUNET_break_op (0);
4888 /* Calculate hops */
4889 size -= sizeof (struct GNUNET_MESH_ConnectionCreate);
4890 if (size % sizeof (struct GNUNET_PeerIdentity))
4892 GNUNET_break_op (0);
4895 size /= sizeof (struct GNUNET_PeerIdentity);
4898 GNUNET_break_op (0);
4901 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " path has %u hops.\n", size);
4903 /* Get parameters */
4904 msg = (struct GNUNET_MESH_ConnectionCreate *) message;
4905 cid = ntohl (msg->cid);
4907 id = (struct GNUNET_PeerIdentity *) &msg[1];
4908 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4909 " connection %s[%X] (%s).\n",
4910 GNUNET_h2s (tid), cid, GNUNET_i2s (id));
4912 /* Create connection */
4913 c = connection_get (tid, cid);
4916 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Creating connection\n");
4917 c = connection_new (tid, cid);
4921 connection_reset_timeout (c, GNUNET_YES);
4922 tunnel_change_state (c->t, MESH_TUNNEL_WAITING);
4924 /* Remember peers */
4925 dest_peer = peer_get (&id[size - 1]);
4926 orig_peer = peer_get (&id[0]);
4929 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Creating path...\n");
4930 path = path_new (size);
4932 for (i = 0; i < size; i++)
4934 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... adding %s\n",
4935 GNUNET_i2s (&id[i]));
4936 path->peers[i] = GNUNET_PEER_intern (&id[i]);
4937 if (path->peers[i] == myid)
4940 if (own_pos == 0 && path->peers[own_pos] != myid)
4942 /* create path: self not found in path through self */
4943 GNUNET_break_op (0);
4944 path_destroy (path);
4945 connection_destroy (c);
4948 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Own position: %u\n", own_pos);
4949 path_add_to_peers (path, GNUNET_NO);
4950 c->path = path_duplicate (path);
4951 c->own_pos = own_pos;
4953 /* Is it a connection to us? */
4954 if (own_pos == size - 1)
4956 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " It's for us!\n");
4957 peer_add_path_to_origin (orig_peer, path, GNUNET_YES);
4959 send_connection_ack (c, GNUNET_NO);
4961 /* Keep tunnel alive in direction dest->owner*/
4962 connection_reset_timeout (c, GNUNET_NO);
4966 /* It's for somebody else! Retransmit. */
4967 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Retransmitting.\n");
4968 peer_add_path (dest_peer, path_duplicate (path), GNUNET_NO);
4969 peer_add_path_to_origin (orig_peer, path, GNUNET_NO);
4970 send_prebuilt_message_connection (message, c, NULL, GNUNET_YES);
4977 * Core handler for path ACKs
4979 * @param cls closure
4980 * @param message message
4981 * @param peer peer identity this notification is about
4983 * @return GNUNET_OK to keep the connection open,
4984 * GNUNET_SYSERR to close it (signal serious error)
4987 handle_mesh_connection_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
4988 const struct GNUNET_MessageHeader *message)
4990 struct GNUNET_MESH_ConnectionACK *msg;
4991 struct MeshPeerPath *p;
4992 struct MeshConnection *c;
4995 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection ACK msg\n");
4996 msg = (struct GNUNET_MESH_ConnectionACK *) message;
4997 cid = ntohl(msg->cid);
4998 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " on connection %s[%X]\n",
4999 GNUNET_h2s (&msg->tid), cid);
5000 c = connection_get (&msg->tid, cid);
5003 GNUNET_STATISTICS_update (stats, "# control on unknown connection",
5005 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " don't know the connection!\n");
5009 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " via peer %s\n",
5012 /* Add path to peers? */
5016 path_add_to_peers (p, GNUNET_YES);
5022 connection_change_state (c, MESH_CONNECTION_READY);
5023 connection_reset_timeout (c, GNUNET_NO);
5024 if (MESH_TUNNEL_READY != c->t->state)
5025 tunnel_change_state (c->t, MESH_TUNNEL_READY);
5026 tunnel_send_queued_data (c->t, GNUNET_YES);
5028 /* Message for us? */
5029 if (connection_is_terminal (c, GNUNET_NO))
5031 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " It's for us!\n");
5032 if (3 <= tunnel_count_connections (c->t) && NULL != c->t->peer->dhtget)
5034 GNUNET_DHT_get_stop (c->t->peer->dhtget);
5035 c->t->peer->dhtget = NULL;
5037 //connection_send_ack (c, GNUNET_NO); /* FIXME */
5041 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " not for us, retransmitting...\n");
5042 send_prebuilt_message_connection (message, c, NULL, GNUNET_NO);
5048 * Core handler for notifications of broken paths
5050 * @param cls Closure (unused).
5051 * @param peer Peer identity of sending neighbor.
5052 * @param message Message.
5054 * @return GNUNET_OK to keep the connection open,
5055 * GNUNET_SYSERR to close it (signal serious error)
5058 handle_mesh_connection_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
5059 const struct GNUNET_MessageHeader *message)
5061 struct GNUNET_MESH_ConnectionBroken *msg;
5062 struct MeshConnection *c;
5064 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5065 "Received a CONNECTION BROKEN msg from %s\n", GNUNET_i2s (peer));
5066 msg = (struct GNUNET_MESH_ConnectionBroken *) message;
5067 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " regarding %s\n",
5068 GNUNET_i2s (&msg->peer1));
5069 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " regarding %s\n",
5070 GNUNET_i2s (&msg->peer2));
5071 c = connection_get (&msg->tid, ntohl (msg->cid));
5074 GNUNET_break_op (0);
5077 tunnel_notify_connection_broken (c->t, GNUNET_PEER_search (&msg->peer1),
5078 GNUNET_PEER_search (&msg->peer2));
5085 * Core handler for tunnel destruction
5087 * @param cls Closure (unused).
5088 * @param peer Peer identity of sending neighbor.
5089 * @param message Message.
5091 * @return GNUNET_OK to keep the connection open,
5092 * GNUNET_SYSERR to close it (signal serious error)
5095 handle_mesh_connection_destroy (void *cls,
5096 const struct GNUNET_PeerIdentity *peer,
5097 const struct GNUNET_MessageHeader *message)
5099 struct GNUNET_MESH_ConnectionDestroy *msg;
5100 struct MeshConnection *c;
5104 msg = (struct GNUNET_MESH_ConnectionDestroy *) message;
5105 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5106 "Got a CONNECTION DESTROY message from %s\n",
5108 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5109 " for connection %s[%X]\n",
5110 GNUNET_h2s (&msg->tid), ntohl (msg->cid));
5111 c = connection_get (&msg->tid, ntohl (msg->cid));
5114 /* Probably already got the message from another path,
5115 * destroyed the tunnel and retransmitted to children.
5118 GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
5122 id = GNUNET_PEER_search (peer);
5123 if (id == connection_get_prev_hop (c)->id)
5125 else if (id == connection_get_next_hop (c)->id)
5129 GNUNET_break_op (0);
5132 send_prebuilt_message_connection (message, c, NULL, fwd);
5133 c->destroy = GNUNET_YES;
5139 * Handler for channel create messages.
5141 * @param t Tunnel this channel is to be created in.
5142 * @param msg Message.
5143 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5145 * @return GNUNET_OK to keep the connection open,
5146 * GNUNET_SYSERR to close it (signal serious error)
5149 handle_channel_create (struct MeshTunnel2 *t,
5150 struct GNUNET_MESH_ChannelCreate *msg,
5153 MESH_ChannelNumber chid;
5154 struct MeshChannel *ch;
5155 struct MeshClient *c;
5157 /* Check message size */
5158 if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelCreate))
5160 GNUNET_break_op (0);
5164 /* Check if channel exists */
5165 chid = ntohl (msg->chid);
5166 ch = channel_get (t, chid);
5169 /* Probably a retransmission, safe to ignore */
5173 /* Find a destination client */
5174 c = GNUNET_CONTAINER_multihashmap32_get (ports, msg->port);
5177 /* TODO send reject */
5181 /* Create channel */
5182 ch = channel_new (t, NULL, 0);
5183 channel_set_options (ch, ntohl (msg->opt));
5184 channel_add_client (ch, c);
5185 if (GNUNET_YES == ch->reliable)
5187 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
5188 ch->bck_rel = GNUNET_malloc (sizeof (struct MeshChannelReliability));
5189 ch->bck_rel->ch = ch;
5190 ch->bck_rel->expected_delay = MESH_RETRANSMIT_TIME;
5193 send_local_channel_create (ch);
5200 * Handler for channel destroy messages.
5202 * @param t Tunnel this channel is to be destroyed of.
5203 * @param msg Message.
5204 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5206 * @return GNUNET_OK to keep the connection open,
5207 * GNUNET_SYSERR to close it (signal serious error)
5210 handle_channel_destroy (struct MeshTunnel2 *t,
5211 struct GNUNET_MESH_ChannelDestroy *msg,
5214 MESH_ChannelNumber chid;
5215 struct MeshChannel *ch;
5217 /* Check message size */
5218 if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelDestroy))
5220 GNUNET_break_op (0);
5224 /* Check if channel exists */
5225 chid = ntohl (msg->chid);
5226 ch = channel_get (t, chid);
5229 /* Probably a retransmission, safe to ignore */
5233 send_local_channel_destroy (ch, fwd);
5234 channel_destroy (ch);
5241 * Generic handler for mesh network encrypted traffic.
5243 * @param peer Peer identity this notification is about.
5244 * @param message Encrypted message.
5245 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5247 * @return GNUNET_OK to keep the connection open,
5248 * GNUNET_SYSERR to close it (signal serious error)
5251 handle_mesh_encrypted (const struct GNUNET_PeerIdentity *peer,
5252 const struct GNUNET_MESH_Encrypted *msg,
5255 struct MeshConnection *c;
5256 struct MeshTunnel2 *t;
5257 struct MeshPeer *neighbor;
5258 struct MeshFlowControl *fc;
5265 size = ntohs (msg->header.size);
5267 sizeof (struct GNUNET_MESH_Encrypted) +
5268 sizeof (struct GNUNET_MessageHeader))
5273 type = ntohs (msg->header.type);
5274 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message from %s\n",
5275 GNUNET_MESH_DEBUG_M2S (type), GNUNET_i2s (peer));
5277 /* Check connection */
5278 c = connection_get (&msg->tid, ntohl (msg->cid));
5281 GNUNET_STATISTICS_update (stats, "# unknown connection", 1, GNUNET_NO);
5282 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING connection unknown\n");
5286 fc = fwd ? &c->fwd_fc : &c->bck_fc;
5288 /* Check if origin is as expected */
5289 neighbor = connection_get_hop (c, fwd);
5290 if (peer_get (peer)->id != neighbor->id)
5292 GNUNET_break_op (0);
5297 pid = ntohl (msg->pid);
5298 if (GMC_is_pid_bigger (pid, fc->last_ack_sent))
5300 GNUNET_STATISTICS_update (stats, "# unsolicited message", 1, GNUNET_NO);
5301 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5302 "WARNING Received PID %u, (prev %u), ACK %u\n",
5303 pid, fc->last_pid_recv, fc->last_ack_sent);
5306 if (GNUNET_NO == GMC_is_pid_bigger (pid, fc->last_pid_recv))
5308 GNUNET_STATISTICS_update (stats, "# duplicate PID", 1, GNUNET_NO);
5309 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5310 " Pid %u not expected (%u+), dropping!\n",
5311 pid, fc->last_pid_recv + 1);
5314 if (MESH_CONNECTION_SENT == c->state)
5315 connection_change_state (c, MESH_CONNECTION_READY);
5316 connection_reset_timeout (c, fwd);
5317 fc->last_pid_recv = pid;
5319 /* Is this message for us? */
5320 if (connection_is_terminal (c, fwd))
5322 size_t dsize = size - sizeof (struct GNUNET_MESH_Encrypted);
5324 struct GNUNET_MessageHeader *msgh;
5326 /* TODO signature verification */
5327 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " it's for us!\n");
5328 GNUNET_STATISTICS_update (stats, "# messages received", 1, GNUNET_NO);
5330 fc->last_pid_recv = pid;
5331 tunnel_decrypt (t, cbuf, &msg[1], dsize, msg->iv, fwd);
5332 msgh = (struct GNUNET_MessageHeader *) cbuf;
5333 switch (ntohs (msgh->type))
5335 case GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK:
5336 if (GNUNET_YES == fwd)
5337 return handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh,
5339 GNUNET_break_op (0);
5341 case GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK:
5342 if (GNUNET_NO == fwd)
5343 return handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh,
5345 GNUNET_break_op (0);
5347 case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
5348 if (GNUNET_YES == fwd)
5349 handle_data (t, (struct GNUNET_MESH_Data *) msgh, GNUNET_YES);
5350 GNUNET_break_op (0);
5352 case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
5353 if (GNUNET_NO == fwd)
5354 handle_data (t, (struct GNUNET_MESH_Data *) msgh, GNUNET_NO);
5355 GNUNET_break_op (0);
5357 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
5358 return handle_channel_create (t,
5359 (struct GNUNET_MESH_ChannelCreate *) msgh,
5362 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
5363 return handle_channel_destroy (t,
5364 (struct GNUNET_MESH_ChannelDestroy *)
5369 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5370 "end-to-end message not known (%u)\n",
5371 ntohs (msgh->type));
5374 connection_send_ack (c, fwd);
5378 /* Message not for us: forward to next hop */
5379 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " not for us, retransmitting...\n");
5380 ttl = ntohl (msg->ttl);
5381 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ttl: %u\n", ttl);
5384 GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5385 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5386 connection_send_ack (c, fwd);
5389 GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
5391 send_prebuilt_message_connection (&msg->header, c, NULL, fwd);
5398 * Core handler for mesh network traffic going orig->dest.
5400 * @param cls Closure (unused).
5401 * @param message Message received.
5402 * @param peer Peer who sent the message.
5404 * @return GNUNET_OK to keep the connection open,
5405 * GNUNET_SYSERR to close it (signal serious error)
5408 handle_mesh_fwd (void *cls, const struct GNUNET_PeerIdentity *peer,
5409 const struct GNUNET_MessageHeader *message)
5411 return handle_mesh_encrypted (peer,
5412 (struct GNUNET_MESH_Encrypted *)message,
5417 * Core handler for mesh network traffic going dest->orig.
5419 * @param cls Closure (unused).
5420 * @param message Message received.
5421 * @param peer Peer who sent the message.
5423 * @return GNUNET_OK to keep the connection open,
5424 * GNUNET_SYSERR to close it (signal serious error)
5427 handle_mesh_bck (void *cls, const struct GNUNET_PeerIdentity *peer,
5428 const struct GNUNET_MessageHeader *message)
5430 return handle_mesh_encrypted (peer,
5431 (struct GNUNET_MESH_Encrypted *)message,
5437 * Core handler for mesh network traffic point-to-point acks.
5439 * @param cls closure
5440 * @param message message
5441 * @param peer peer identity this notification is about
5443 * @return GNUNET_OK to keep the connection open,
5444 * GNUNET_SYSERR to close it (signal serious error)
5447 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5448 const struct GNUNET_MessageHeader *message)
5450 struct GNUNET_MESH_ACK *msg;
5451 struct MeshConnection *c;
5452 struct MeshFlowControl *fc;
5456 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
5458 msg = (struct GNUNET_MESH_ACK *) message;
5460 c = connection_get (&msg->tid, ntohl (msg->cid));
5464 GNUNET_STATISTICS_update (stats, "# ack on unknown connection", 1,
5469 ack = ntohl (msg->ack);
5470 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", ack);
5472 /* Is this a forward or backward ACK? */
5473 id = GNUNET_PEER_search (peer);
5474 if (connection_get_next_hop (c)->id == id)
5476 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " FWD ACK\n");
5479 else if (connection_get_prev_hop (c)->id == id)
5481 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " BCK ACK\n");
5486 GNUNET_break_op (0);
5490 /* Cancel polling if the ACK is bigger than before. */
5491 if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task &&
5492 GMC_is_pid_bigger (ack, fc->last_ack_recv))
5494 GNUNET_SCHEDULER_cancel (fc->poll_task);
5495 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
5496 fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
5499 fc->last_ack_recv = ack;
5500 connection_unlock_queue (c, fc == &c->fwd_fc);
5507 * Core handler for mesh network traffic point-to-point ack polls.
5509 * @param cls closure
5510 * @param message message
5511 * @param peer peer identity this notification is about
5513 * @return GNUNET_OK to keep the connection open,
5514 * GNUNET_SYSERR to close it (signal serious error)
5517 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
5518 const struct GNUNET_MessageHeader *message)
5520 struct GNUNET_MESH_Poll *msg;
5521 struct MeshConnection *c;
5522 struct MeshFlowControl *fc;
5526 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a POLL packet from %s!\n",
5529 msg = (struct GNUNET_MESH_Poll *) message;
5531 c = connection_get (&msg->tid, ntohl (msg->cid));
5535 GNUNET_STATISTICS_update (stats, "# poll on unknown connection", 1,
5537 GNUNET_break_op (0);
5541 /* Is this a forward or backward ACK? */
5542 id = GNUNET_PEER_search (peer);
5543 if (connection_get_next_hop (c)->id == id)
5545 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " FWD ACK\n");
5548 else if (connection_get_prev_hop (c)->id == id)
5550 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " BCK ACK\n");
5555 GNUNET_break_op (0);
5559 pid = ntohl (msg->pid);
5560 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " PID %u, OLD %u\n",
5561 pid, fc->last_pid_recv);
5562 fc->last_pid_recv = pid;
5563 connection_send_ack (c, fc == &c->fwd_fc);
5570 * Core handler for mesh keepalives.
5572 * @param cls closure
5573 * @param message message
5574 * @param peer peer identity this notification is about
5575 * @return GNUNET_OK to keep the connection open,
5576 * GNUNET_SYSERR to close it (signal serious error)
5578 * TODO: Check who we got this from, to validate route.
5581 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
5582 const struct GNUNET_MessageHeader *message)
5584 struct GNUNET_MESH_ConnectionKeepAlive *msg;
5585 struct MeshConnection *c;
5586 struct MeshPeer *neighbor;
5589 msg = (struct GNUNET_MESH_ConnectionKeepAlive *) message;
5590 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
5593 c = connection_get (&msg->tid, ntohl (msg->cid));
5596 GNUNET_STATISTICS_update (stats, "# keepalive on unknown connection", 1,
5601 fwd = GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE == ntohs (message->type) ?
5602 GNUNET_YES : GNUNET_NO;
5604 /* Check if origin is as expected */
5605 neighbor = connection_get_hop (c, fwd);
5606 if (peer_get (peer)->id != neighbor->id)
5608 GNUNET_break_op (0);
5612 connection_change_state (c, MESH_CONNECTION_READY);
5613 connection_reset_timeout (c, fwd);
5615 if (connection_is_terminal (c, fwd))
5618 GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
5619 send_prebuilt_message_connection (message, c, NULL, fwd);
5627 * Functions to handle messages from core
5629 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
5630 {&handle_mesh_connection_create, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
5632 {&handle_mesh_connection_ack, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
5633 sizeof (struct GNUNET_MESH_ConnectionACK)},
5634 {&handle_mesh_connection_broken, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN,
5635 sizeof (struct GNUNET_MESH_ConnectionBroken)},
5636 {&handle_mesh_connection_destroy, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY,
5637 sizeof (struct GNUNET_MESH_ConnectionDestroy)},
5638 {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE,
5639 sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
5640 {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE,
5641 sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
5642 {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
5643 sizeof (struct GNUNET_MESH_ACK)},
5644 {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
5645 sizeof (struct GNUNET_MESH_Poll)},
5646 {&handle_mesh_fwd, GNUNET_MESSAGE_TYPE_MESH_FWD, 0},
5647 {&handle_mesh_bck, GNUNET_MESSAGE_TYPE_MESH_BCK, 0},
5653 * Function to process paths received for a new peer addition. The recorded
5654 * paths form the initial tunnel, which can be optimized later.
5655 * Called on each result obtained for the DHT search.
5657 * @param cls closure
5658 * @param exp when will this value expire
5659 * @param key key of the result
5660 * @param get_path path of the get request
5661 * @param get_path_length lenght of get_path
5662 * @param put_path path of the put request
5663 * @param put_path_length length of the put_path
5664 * @param type type of the result
5665 * @param size number of bytes in data
5666 * @param data pointer to the result data
5669 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5670 const struct GNUNET_HashCode * key,
5671 const struct GNUNET_PeerIdentity *get_path,
5672 unsigned int get_path_length,
5673 const struct GNUNET_PeerIdentity *put_path,
5674 unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5675 size_t size, const void *data)
5677 struct MeshPeer *peer = cls;
5678 struct MeshPeerPath *p;
5679 struct MeshConnection *c;
5680 struct GNUNET_PeerIdentity pi;
5683 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
5684 GNUNET_PEER_resolve (peer->id, &pi);
5685 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " for %s\n", GNUNET_i2s (&pi));
5687 p = path_build_from_dht (get_path, get_path_length,
5688 put_path, put_path_length);
5689 path_add_to_peers (p, GNUNET_NO);
5692 /* Count connections */
5693 for (c = peer->tunnel->connection_head, i = 0; NULL != c; c = c->next, i++);
5695 /* If we already have 3 (or more (?!)) connections, it's enough */
5699 if (peer->tunnel->state == MESH_TUNNEL_SEARCHING)
5701 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... connect!\n");
5702 peer_connect (peer);
5708 /******************************************************************************/
5709 /********************* MESH LOCAL HANDLES **************************/
5710 /******************************************************************************/
5714 * Handler for client connection.
5716 * @param cls Closure (unused).
5717 * @param client Client handler.
5720 handle_local_client_connect (void *cls, struct GNUNET_SERVER_Client *client)
5722 struct MeshClient *c;
5726 c = GNUNET_malloc (sizeof (struct MeshClient));
5728 c->id = next_client_id++; /* overflow not important: just for debug */
5729 GNUNET_SERVER_client_keep (client);
5730 GNUNET_SERVER_client_set_user_context (client, c);
5731 GNUNET_CONTAINER_DLL_insert (clients_head, clients_tail, c);
5736 * Handler for client disconnection
5738 * @param cls closure
5739 * @param client identification of the client; NULL
5740 * for the last call when the server is destroyed
5743 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
5745 struct MeshClient *c;
5747 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected: %p\n", client);
5750 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " (SERVER DOWN)\n");
5754 c = client_get (client);
5757 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u, %p)\n",
5759 GNUNET_SERVER_client_drop (c->handle);
5760 c->shutting_down = GNUNET_YES;
5761 if (NULL != c->own_channels)
5763 GNUNET_CONTAINER_multihashmap32_iterate (c->own_channels,
5764 &channel_destroy_iterator, c);
5765 GNUNET_CONTAINER_multihashmap32_destroy (c->own_channels);
5768 if (NULL != c->incoming_channels)
5770 GNUNET_CONTAINER_multihashmap32_iterate (c->incoming_channels,
5771 &channel_destroy_iterator, c);
5772 GNUNET_CONTAINER_multihashmap32_destroy (c->incoming_channels);
5775 if (NULL != c->ports)
5777 GNUNET_CONTAINER_multihashmap32_iterate (c->ports,
5778 &client_release_ports, c);
5779 GNUNET_CONTAINER_multihashmap32_destroy (c->ports);
5781 GNUNET_CONTAINER_DLL_remove (clients_head, clients_tail, c);
5782 GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
5783 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " client free (%p)\n", c);
5788 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " context NULL!\n");
5790 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "done!\n");
5796 * Handler for new clients
5798 * @param cls closure
5799 * @param client identification of the client
5800 * @param message the actual message, which includes messages the client wants
5803 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
5804 const struct GNUNET_MessageHeader *message)
5806 struct GNUNET_MESH_ClientConnect *cc_msg;
5807 struct MeshClient *c;
5812 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected %p\n", client);
5814 /* Check data sanity */
5815 size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
5816 cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
5817 if (0 != (size % sizeof (uint32_t)))
5820 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5823 size /= sizeof (uint32_t);
5825 /* Initialize new client structure */
5826 c = GNUNET_SERVER_client_get_user_context (client, struct MeshClient);
5827 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " client id %u\n", c->id);
5828 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " client has %u ports\n", size);
5833 p = (uint32_t *) &cc_msg[1];
5834 c->ports = GNUNET_CONTAINER_multihashmap32_create (size);
5835 for (i = 0; i < size; i++)
5838 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " port: %u\n", u32);
5840 /* store in client's hashmap */
5841 GNUNET_CONTAINER_multihashmap32_put (c->ports, u32, c,
5842 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
5843 /* store in global hashmap */
5844 /* FIXME only allow one client to have the port open,
5845 * have a backup hashmap with waiting clients */
5846 GNUNET_CONTAINER_multihashmap32_put (ports, u32, c,
5847 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
5851 c->own_channels = GNUNET_CONTAINER_multihashmap32_create (32);
5852 c->incoming_channels = GNUNET_CONTAINER_multihashmap32_create (32);
5853 GNUNET_SERVER_notification_context_add (nc, client);
5854 GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
5856 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5857 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
5862 * Handler for requests of new tunnels
5864 * @param cls Closure.
5865 * @param client Identification of the client.
5866 * @param message The actual message.
5869 handle_local_channel_create (void *cls, struct GNUNET_SERVER_Client *client,
5870 const struct GNUNET_MessageHeader *message)
5872 struct GNUNET_MESH_ChannelMessage *msg;
5873 struct MeshPeer *peer;
5874 struct MeshTunnel2 *t;
5875 struct MeshChannel *ch;
5876 struct MeshClient *c;
5877 MESH_ChannelNumber chid;
5879 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new channel requested\n");
5881 /* Sanity check for client registration */
5882 if (NULL == (c = client_get (client)))
5885 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5888 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
5890 /* Message size sanity check */
5891 if (sizeof (struct GNUNET_MESH_ChannelMessage) != ntohs (message->size))
5894 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5898 msg = (struct GNUNET_MESH_ChannelMessage *) message;
5899 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " towards %s:%u\n",
5900 GNUNET_i2s (&msg->peer), ntohl (msg->port));
5901 chid = ntohl (msg->channel_id);
5903 /* Sanity check for duplicate channel IDs */
5904 if (NULL != channel_get_by_local_id (c, chid))
5907 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5911 peer = peer_get (&msg->peer);
5912 if (NULL == peer->tunnel)
5914 struct GNUNET_HashCode tid;
5916 GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE, &tid);
5917 peer->tunnel = tunnel_new (&tid);
5918 peer->tunnel->peer = peer;
5922 /* Create channel */
5923 ch = channel_new (t, c, chid);
5927 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5930 ch->port = ntohl (msg->port);
5931 channel_set_options (ch, ntohl (msg->opt));
5933 /* In unreliable channels, we'll use the DLL to buffer data for the root */
5934 ch->fwd_rel = GNUNET_malloc (sizeof (struct MeshChannelReliability));
5935 ch->fwd_rel->ch = ch;
5936 ch->fwd_rel->expected_delay = MESH_RETRANSMIT_TIME;
5938 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED CHANNEL %s[%x]:%u (%x)\n",
5939 GNUNET_h2s (&t->id), ch->gid, ch->port, ch->lid_root);
5940 peer_connect (peer);
5942 /* Send create channel */
5944 struct GNUNET_MESH_ChannelCreate msgcc;
5946 msgcc.header.size = htons (sizeof (msgcc));
5947 msgcc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE);
5948 msgcc.chid = htonl (ch->gid);
5949 msgcc.port = msg->port;
5950 msgcc.opt = msg->opt;
5952 tunnel_queue_data (t, ch, &msgcc.header, GNUNET_YES);
5955 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5961 * Handler for requests of deleting tunnels
5963 * @param cls closure
5964 * @param client identification of the client
5965 * @param message the actual message
5968 handle_local_channel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
5969 const struct GNUNET_MessageHeader *message)
5971 struct GNUNET_MESH_ChannelMessage *msg;
5972 struct MeshClient *c;
5973 struct MeshChannel *ch;
5974 struct MeshTunnel2 *t;
5975 MESH_ChannelNumber chid;
5977 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5978 "Got a DESTROY CHANNEL from client!\n");
5980 /* Sanity check for client registration */
5981 if (NULL == (c = client_get (client)))
5984 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5987 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
5989 /* Message sanity check */
5990 if (sizeof (struct GNUNET_MESH_ChannelMessage) != ntohs (message->size))
5993 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5997 msg = (struct GNUNET_MESH_ChannelMessage *) message;
5999 /* Retrieve tunnel */
6000 chid = ntohl (msg->channel_id);
6001 ch = channel_get_by_local_id (c, chid);
6004 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, " channel %X not found\n", chid);
6006 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6010 /* Cleanup after the tunnel */
6011 client_delete_channel (c, ch);
6012 if (c == ch->dest && GNUNET_MESH_LOCAL_CHANNEL_ID_SERV <= chid)
6016 else if (c == ch->root && GNUNET_MESH_LOCAL_CHANNEL_ID_SERV > chid)
6022 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6023 " channel %X client %p (%p, %p)\n",
6024 chid, c, ch->root, ch->dest);
6029 channel_destroy (ch);
6030 tunnel_destroy_if_empty (t);
6032 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6038 * Handler for client traffic
6040 * @param cls closure
6041 * @param client identification of the client
6042 * @param message the actual message
6045 handle_local_data (void *cls, struct GNUNET_SERVER_Client *client,
6046 const struct GNUNET_MessageHeader *message)
6048 struct GNUNET_MESH_LocalData *msg;
6049 struct MeshClient *c;
6050 struct MeshChannel *ch;
6051 MESH_ChannelNumber chid;
6055 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6056 "Got data from a client!\n");
6058 /* Sanity check for client registration */
6059 if (NULL == (c = client_get (client)))
6062 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6065 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
6066 c->blocked = GNUNET_YES;
6068 msg = (struct GNUNET_MESH_LocalData *) message;
6070 /* Sanity check for message size */
6071 size = ntohs (message->size) - sizeof (struct GNUNET_MESH_LocalData);
6072 if (size < sizeof (struct GNUNET_MessageHeader))
6075 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6079 /* Channel exists? */
6080 chid = ntohl (msg->id);
6081 fwd = chid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
6082 ch = channel_get_by_local_id (c, chid);
6086 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6090 /* Is the client in the channel? */
6093 ch->root->handle == client)
6097 ch->dest->handle == client) ) )
6100 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6104 /* Ok, everything is correct, send the message
6105 * (pretend we got it from a mesh peer)
6108 struct GNUNET_MESH_Data *payload;
6109 char cbuf[sizeof(struct GNUNET_MESH_Data) + size];
6112 mid = fwd ? &ch->mid_send_fwd : &ch->mid_send_bck;
6113 if (GNUNET_YES == ch->reliable)
6115 struct MeshChannelReliability *rel;
6116 struct MeshReliableMessage *copy;
6118 rel = fwd ? ch->fwd_rel : ch->bck_rel;
6119 copy = GNUNET_malloc (sizeof (struct MeshReliableMessage)
6120 + sizeof(struct GNUNET_MESH_Data)
6123 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! DATA %u\n", copy->mid);
6124 copy->timestamp = GNUNET_TIME_absolute_get ();
6127 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " n_sent %u\n", rel->n_sent);
6128 GNUNET_CONTAINER_DLL_insert_tail (rel->head_sent, rel->tail_sent, copy);
6129 if (GNUNET_SCHEDULER_NO_TASK == rel->retry_task)
6132 GNUNET_TIME_relative_multiply (rel->expected_delay,
6133 MESH_RETRANSMIT_MARGIN);
6135 GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
6136 &channel_retransmit_message,
6139 payload = (struct GNUNET_MESH_Data *) ©[1];
6143 payload = (struct GNUNET_MESH_Data *) cbuf;
6145 payload->mid = htonl (*mid);
6147 memcpy (&payload[1], &msg[1], size);
6148 payload->header.size = htons (sizeof (struct GNUNET_MESH_Data) + size);
6149 payload->header.type = htons (chid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV ?
6150 GNUNET_MESSAGE_TYPE_MESH_UNICAST :
6151 GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
6152 payload->chid = htonl (ch->gid);
6153 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6154 " calling generic handler...\n");
6155 send_prebuilt_message_channel (&payload->header, ch, fwd);
6157 if (tunnel_get_buffer (ch->t, fwd) > 0)
6158 send_local_ack (ch, c, fwd);
6159 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
6160 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6167 * Handler for client's ACKs for payload traffic.
6169 * @param cls Closure (unused).
6170 * @param client Identification of the client.
6171 * @param message The actual message.
6174 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
6175 const struct GNUNET_MessageHeader *message)
6177 struct GNUNET_MESH_LocalAck *msg;
6178 struct MeshChannelReliability *rel;
6179 struct MeshChannel *ch;
6180 struct MeshClient *c;
6181 MESH_ChannelNumber chid;
6184 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
6186 /* Sanity check for client registration */
6187 if (NULL == (c = client_get (client)))
6190 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6193 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
6195 msg = (struct GNUNET_MESH_LocalAck *) message;
6197 /* Channel exists? */
6198 chid = ntohl (msg->channel_id);
6199 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " on channel %X\n", chid);
6200 ch = channel_get_by_local_id (c, chid);
6204 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Channel %X unknown.\n", chid);
6205 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " for client %u.\n", c->id);
6206 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6210 fwd = chid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
6211 rel = fwd ? ch->fwd_rel : ch->bck_rel;
6213 rel->client_ready = GNUNET_YES;
6214 channel_send_client_buffered_data (ch, c, rel);
6215 channel_send_connection_ack (ch, 64 - rel->n_recv, fwd);
6217 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6224 * Iterator over all tunnels to send a monitoring client info about each tunnel.
6226 * @param cls Closure (client handle).
6227 * @param key Key (hashed tunnel ID, unused).
6228 * @param value Tunnel info.
6230 * @return GNUNET_YES, to keep iterating.
6233 monitor_all_tunnels_iterator (void *cls,
6234 const struct GNUNET_HashCode * key,
6237 struct GNUNET_SERVER_Client *client = cls;
6238 struct MeshChannel *ch = value;
6239 struct GNUNET_MESH_LocalMonitor *msg;
6241 msg = GNUNET_malloc (sizeof(struct GNUNET_MESH_LocalMonitor));
6242 msg->channel_id = htonl (ch->gid);
6243 msg->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
6244 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
6246 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6247 "* sending info about tunnel %s\n",
6248 GNUNET_i2s (&msg->owner));
6250 GNUNET_SERVER_notification_context_unicast (nc, client,
6251 &msg->header, GNUNET_NO);
6257 * Handler for client's MONITOR request.
6259 * @param cls Closure (unused).
6260 * @param client Identification of the client.
6261 * @param message The actual message.
6264 handle_local_get_tunnels (void *cls, struct GNUNET_SERVER_Client *client,
6265 const struct GNUNET_MessageHeader *message)
6267 struct MeshClient *c;
6269 /* Sanity check for client registration */
6270 if (NULL == (c = client_get (client)))
6273 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6277 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6278 "Received get tunnels request from client %u\n",
6280 GNUNET_CONTAINER_multihashmap_iterate (tunnels,
6281 monitor_all_tunnels_iterator,
6283 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6284 "Get tunnels request from client %u completed\n",
6286 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6291 * Handler for client's MONITOR_TUNNEL request.
6293 * @param cls Closure (unused).
6294 * @param client Identification of the client.
6295 * @param message The actual message.
6298 handle_local_show_tunnel (void *cls, struct GNUNET_SERVER_Client *client,
6299 const struct GNUNET_MessageHeader *message)
6301 const struct GNUNET_MESH_LocalMonitor *msg;
6302 struct GNUNET_MESH_LocalMonitor *resp;
6303 struct MeshClient *c;
6304 struct MeshChannel *ch;
6306 /* Sanity check for client registration */
6307 if (NULL == (c = client_get (client)))
6310 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6314 msg = (struct GNUNET_MESH_LocalMonitor *) message;
6315 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6316 "Received tunnel info request from client %u for tunnel %s[%X]\n",
6319 ntohl (msg->channel_id));
6320 // ch = channel_get (&msg->owner, ntohl (msg->channel_id));
6324 /* We don't know the tunnel */
6325 struct GNUNET_MESH_LocalMonitor warn;
6328 GNUNET_SERVER_notification_context_unicast (nc, client,
6331 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6335 /* Initialize context */
6336 resp = GNUNET_malloc (sizeof (struct GNUNET_MESH_LocalMonitor));
6338 resp->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
6339 GNUNET_SERVER_notification_context_unicast (nc, c->handle,
6340 &resp->header, GNUNET_NO);
6343 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6344 "Monitor tunnel request from client %u completed\n",
6346 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6351 * Functions to handle messages from clients
6353 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
6354 {&handle_local_new_client, NULL,
6355 GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
6356 {&handle_local_channel_create, NULL,
6357 GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE,
6358 sizeof (struct GNUNET_MESH_ChannelMessage)},
6359 {&handle_local_channel_destroy, NULL,
6360 GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY,
6361 sizeof (struct GNUNET_MESH_ChannelMessage)},
6362 {&handle_local_data, NULL,
6363 GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA, 0},
6364 {&handle_local_ack, NULL,
6365 GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
6366 sizeof (struct GNUNET_MESH_LocalAck)},
6367 {&handle_local_get_tunnels, NULL,
6368 GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS,
6369 sizeof (struct GNUNET_MessageHeader)},
6370 {&handle_local_show_tunnel, NULL,
6371 GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL,
6372 sizeof (struct GNUNET_MESH_LocalMonitor)},
6378 * Method called whenever a given peer connects.
6380 * @param cls closure
6381 * @param peer peer identity this notification is about
6384 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
6386 struct MeshPeer *pi;
6387 struct MeshPeerPath *path;
6389 DEBUG_CONN ("Peer connected\n");
6390 DEBUG_CONN (" %s\n", GNUNET_i2s (&my_full_id));
6391 pi = peer_get (peer);
6394 DEBUG_CONN (" (self)\n");
6395 path = path_new (1);
6399 DEBUG_CONN (" %s\n", GNUNET_i2s (peer));
6400 path = path_new (2);
6401 path->peers[1] = pi->id;
6402 GNUNET_PEER_change_rc (pi->id, 1);
6403 GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
6405 path->peers[0] = myid;
6406 GNUNET_PEER_change_rc (myid, 1);
6407 peer_add_path (pi, path, GNUNET_YES);
6409 pi->connections = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_YES);
6415 * Method called whenever a peer disconnects.
6417 * @param cls closure
6418 * @param peer peer identity this notification is about
6421 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
6423 struct MeshPeer *pi;
6425 DEBUG_CONN ("Peer disconnected\n");
6426 pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
6433 peer_remove_path (pi, myid, pi->id);
6435 GNUNET_CONTAINER_multihashmap_iterate (pi->connections,
6438 GNUNET_CONTAINER_multihashmap_destroy (pi->connections);
6439 pi->connections = NULL;
6442 DEBUG_CONN (" (self)\n");
6444 GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
6451 * Install server (service) handlers and start listening to clients.
6456 GNUNET_SERVER_add_handlers (server_handle, client_handlers);
6457 GNUNET_SERVER_connect_notify (server_handle,
6458 &handle_local_client_connect, NULL);
6459 GNUNET_SERVER_disconnect_notify (server_handle,
6460 &handle_local_client_disconnect, NULL);
6461 nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
6463 clients_head = NULL;
6464 clients_tail = NULL;
6466 GNUNET_SERVER_resume (server_handle);
6471 * To be called on core init/fail.
6473 * @param cls Closure (config)
6474 * @param server handle to the server for this service
6475 * @param identity the public identity of this peer
6478 core_init (void *cls, struct GNUNET_CORE_Handle *server,
6479 const struct GNUNET_PeerIdentity *identity)
6481 const struct GNUNET_CONFIGURATION_Handle *c = cls;
6484 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
6485 GNUNET_break (core_handle == server);
6486 if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
6489 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
6490 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6492 GNUNET_i2s (identity));
6493 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6495 GNUNET_i2s (&my_full_id));
6496 GNUNET_CORE_disconnect (core_handle);
6497 core_handle = GNUNET_CORE_connect (c, /* Main configuration */
6498 NULL, /* Closure passed to MESH functions */
6499 &core_init, /* Call core_init once connected */
6500 &core_connect, /* Handle connects */
6501 &core_disconnect, /* remove peers on disconnects */
6502 NULL, /* Don't notify about all incoming messages */
6503 GNUNET_NO, /* For header only in notification */
6504 NULL, /* Don't notify about all outbound messages */
6505 GNUNET_NO, /* For header-only out notification */
6506 core_handlers); /* Register these handlers */
6515 /******************************************************************************/
6516 /************************ MAIN FUNCTIONS ****************************/
6517 /******************************************************************************/
6520 * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
6522 * @param cls closure
6523 * @param key current key code
6524 * @param value value in the hash map
6525 * @return GNUNET_YES if we should continue to iterate,
6529 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
6531 struct MeshTunnel2 *t = value;
6539 * Task run during shutdown.
6545 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
6547 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
6549 if (core_handle != NULL)
6551 GNUNET_CORE_disconnect (core_handle);
6554 GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
6555 if (dht_handle != NULL)
6557 GNUNET_DHT_disconnect (dht_handle);
6562 GNUNET_SERVER_notification_context_destroy (nc);
6565 if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
6567 GNUNET_SCHEDULER_cancel (announce_id_task);
6568 announce_id_task = GNUNET_SCHEDULER_NO_TASK;
6570 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
6575 * Process mesh requests.
6577 * @param cls closure
6578 * @param server the initialized server
6579 * @param c configuration to use
6582 run (void *cls, struct GNUNET_SERVER_Handle *server,
6583 const struct GNUNET_CONFIGURATION_Handle *c)
6586 struct GNUNET_CRYPTO_EccPrivateKey *pk;
6588 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
6589 server_handle = server;
6590 GNUNET_SERVER_suspend (server_handle);
6593 GNUNET_CONFIGURATION_get_value_filename (c, "PEER", "PRIVATE_KEY",
6596 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6598 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6599 "mesh", "peer/privatekey");
6600 GNUNET_SCHEDULER_shutdown ();
6605 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_CONNECTION_TIME",
6606 &refresh_connection_time))
6608 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6610 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6611 "mesh", "refresh path time");
6612 GNUNET_SCHEDULER_shutdown ();
6617 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
6620 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6622 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6623 "mesh", "id announce time");
6624 GNUNET_SCHEDULER_shutdown ();
6629 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
6632 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6634 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6635 "mesh", "connect timeout");
6636 GNUNET_SCHEDULER_shutdown ();
6641 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
6644 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6646 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6647 "mesh", "max msgs queue");
6648 GNUNET_SCHEDULER_shutdown ();
6653 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_CONNECTIONS",
6656 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6658 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6659 "mesh", "max tunnels");
6660 GNUNET_SCHEDULER_shutdown ();
6665 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
6668 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6670 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
6671 "mesh", "default ttl", 64);
6676 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
6679 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6680 _("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
6681 "mesh", "max peers", 1000);
6686 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DROP_PERCENT",
6693 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6694 "Mesh is running with drop mode enabled. "
6695 "This is NOT a good idea! "
6696 "Remove the DROP_PERCENT option from your configuration.\n");
6700 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
6701 &dht_replication_level))
6703 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6705 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
6706 "mesh", "dht replication level", 3);
6707 dht_replication_level = 3;
6710 tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6711 peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6712 ports = GNUNET_CONTAINER_multihashmap32_create (32);
6714 dht_handle = GNUNET_DHT_connect (c, 64);
6715 if (NULL == dht_handle)
6719 stats = GNUNET_STATISTICS_create ("mesh", c);
6721 /* Scheduled the task to clean up when shutdown is called */
6722 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
6724 pk = GNUNET_CRYPTO_ecc_key_create_from_file (keyfile);
6725 GNUNET_free (keyfile);
6726 GNUNET_assert (NULL != pk);
6727 my_private_key = pk;
6728 GNUNET_CRYPTO_ecc_key_get_public (my_private_key, &my_public_key);
6729 GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
6730 &my_full_id.hashPubKey);
6731 myid = GNUNET_PEER_intern (&my_full_id);
6732 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6733 "Mesh for peer [%s] starting\n",
6734 GNUNET_i2s(&my_full_id));
6736 core_handle = GNUNET_CORE_connect (c, /* Main configuration */
6737 NULL, /* Closure passed to MESH functions */
6738 &core_init, /* Call core_init once connected */
6739 &core_connect, /* Handle connects */
6740 &core_disconnect, /* remove peers on disconnects */
6741 NULL, /* Don't notify about all incoming messages */
6742 GNUNET_NO, /* For header only in notification */
6743 NULL, /* Don't notify about all outbound messages */
6744 GNUNET_NO, /* For header-only out notification */
6745 core_handlers); /* Register these handlers */
6746 if (NULL == core_handle)
6749 GNUNET_SCHEDULER_shutdown ();
6752 announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
6753 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
6758 * The main function for the mesh service.
6760 * @param argc number of arguments from the command line
6761 * @param argv command line arguments
6762 * @return 0 ok, 1 on error
6765 main (int argc, char *const *argv)
6770 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
6771 r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
6773 ret = (GNUNET_OK == r) ? 0 : 1;
6774 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");