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_NO
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;
243 * ID of the last packet sent towards the peer.
245 uint32_t last_pid_sent;
248 * ID of the last packet received from the peer.
250 uint32_t last_pid_recv;
253 * Last ACK sent to the peer (peer can't send more than this PID).
255 uint32_t last_ack_sent;
258 * Last ACK sent towards the origin (for traffic towards leaf node).
260 uint32_t last_ack_recv;
263 * Task to poll the peer in case of a lost ACK causes stall.
265 GNUNET_SCHEDULER_TaskIdentifier poll_task;
268 * How frequently to poll for ACKs.
270 struct GNUNET_TIME_Relative poll_time;
275 * Struct containing all information regarding a given peer
285 * Last time we heard from this peer
287 struct GNUNET_TIME_Absolute last_contact;
290 * Paths to reach the peer, ordered by ascending hop count
292 struct MeshPeerPath *path_head;
295 * Paths to reach the peer, ordered by ascending hop count
297 struct MeshPeerPath *path_tail;
300 * Handle to stop the DHT search for paths to this peer
302 struct GNUNET_DHT_GetHandle *dhtget;
305 * Tunnel to this peer, if any.
307 struct MeshTunnel2 *tunnel;
310 * Connections that go through this peer, indexed by tid;
312 struct GNUNET_CONTAINER_MultiHashMap *connections;
315 * Handle for queued transmissions
317 struct GNUNET_CORE_TransmitHandle *core_transmit;
320 * Transmission queue to core DLL head
322 struct MeshPeerQueue *queue_head;
325 * Transmission queue to core DLL tail
327 struct MeshPeerQueue *queue_tail;
330 * How many messages are in the queue to this peer.
332 unsigned int queue_n;
337 * Info needed to retry a message in case it gets lost.
339 struct MeshReliableMessage
342 * Double linked list, FIFO style
344 struct MeshReliableMessage *next;
345 struct MeshReliableMessage *prev;
348 * Tunnel Reliability queue this message is in.
350 struct MeshChannelReliability *rel;
353 * ID of the message (ACK needed to free)
358 * When was this message issued (to calculate ACK delay)
360 struct GNUNET_TIME_Absolute timestamp;
362 /* struct GNUNET_MESH_Data with payload */
366 struct MeshChannelReliability
369 * Channel this is about.
371 struct MeshChannel *ch;
374 * DLL of messages sent and not yet ACK'd.
376 struct MeshReliableMessage *head_sent;
377 struct MeshReliableMessage *tail_sent;
380 * Messages pending to send.
385 * DLL of messages received out of order.
387 struct MeshReliableMessage *head_recv;
388 struct MeshReliableMessage *tail_recv;
396 * Can we send data to the client?
401 * Task to resend/poll in case no ACK is received.
403 GNUNET_SCHEDULER_TaskIdentifier retry_task;
406 * Counter for exponential backoff.
408 struct GNUNET_TIME_Relative retry_timer;
411 * How long does it usually take to get an ACK.
413 struct GNUNET_TIME_Relative expected_delay;
418 * Struct containing all information regarding a channel to a remote client.
423 * Tunnel this channel is in.
425 struct MeshTunnel2 *t;
428 * Double linked list.
430 struct MeshChannel *next;
431 struct MeshChannel *prev;
434 * Destination port of the channel.
439 * Global channel number ( < GNUNET_MESH_LOCAL_CHANNEL_ID_CLI)
441 MESH_ChannelNumber gid;
444 * Local tunnel number for root (owner) client.
445 * ( >= GNUNET_MESH_LOCAL_CHANNEL_ID_CLI or 0 )
447 MESH_ChannelNumber lid_root;
450 * Local tunnel number for local destination clients (incoming number)
451 * ( >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV or 0).
453 MESH_ChannelNumber lid_dest;
456 * Next MID to use for fwd traffic.
458 uint32_t mid_send_fwd;
461 * Next MID expected for fwd traffic.
463 uint32_t mid_recv_fwd;
466 * Next MID to use for bck traffic.
468 uint32_t mid_send_bck;
471 * Next MID expected for bck traffic.
473 uint32_t mid_recv_bck;
476 * Is the tunnel bufferless (minimum latency)?
481 * Is the tunnel reliable?
486 * Last time the channel was used
488 struct GNUNET_TIME_Absolute timestamp;
491 * Client owner of the tunnel, if any
493 struct MeshClient *root;
496 * Client destination of the tunnel, if any.
498 struct MeshClient *dest;
501 * Flag to signal the destruction of the channel.
502 * If this is set GNUNET_YES the channel will be destroyed
503 * when the queue is empty.
508 * Total messages pending for this channel, payload or not.
510 unsigned int pending_messages;
514 * Only present (non-NULL) at the owner of a tunnel.
516 struct MeshChannelReliability *fwd_rel;
520 * Only present (non-NULL) at the destination of a tunnel.
522 struct MeshChannelReliability *bck_rel;
527 * Struct containing all information regarding a connection to a peer.
529 struct MeshConnection
534 struct MeshConnection *next;
535 struct MeshConnection *prev;
538 * Tunnel this connection is part of.
540 struct MeshTunnel2 *t;
543 * Flow control information for traffic fwd.
545 struct MeshFlowControl fwd_fc;
548 * Flow control information for traffic bck.
550 struct MeshFlowControl bck_fc;
558 * State of the connection.
560 enum MeshConnectionState state;
563 * Path being used for the tunnel.
565 struct MeshPeerPath *path;
568 * Position of the local peer in the path.
570 unsigned int own_pos;
573 * Task to keep the used paths alive at the owner,
574 * time tunnel out on all the other peers.
576 GNUNET_SCHEDULER_TaskIdentifier fwd_maintenance_task;
579 * Task to keep the used paths alive at the destination,
580 * time tunnel out on all the other peers.
582 GNUNET_SCHEDULER_TaskIdentifier bck_maintenance_task;
585 * Pending message count.
587 int pending_messages;
590 * Destroy flag: if true, destroy on last message.
597 * Struct used to queue messages in a tunnel.
599 struct MeshTunnelQueue
604 struct MeshTunnelQueue *next;
605 struct MeshTunnelQueue *prev;
610 struct MeshChannel *ch;
615 /* struct GNUNET_MessageHeader *msg; */
620 * Struct containing all information regarding a tunnel to a peer.
625 * Endpoint of the tunnel.
627 struct MeshPeer *peer;
632 struct GNUNET_HashCode id;
635 * State of the tunnel.
637 enum MeshTunnelState state;
640 * Local peer ephemeral private key
642 struct GNUNET_CRYPTO_EccPrivateKey *my_eph_key;
645 * Local peer ephemeral public key
647 struct GNUNET_CRYPTO_EccPublicKey *my_eph;
650 * Remote peer's public key.
652 struct GNUNET_CRYPTO_EccPublicKey *peers_eph;
655 * Encryption ("our") key.
657 struct GNUNET_CRYPTO_AesSessionKey e_key;
660 * Decryption ("their") key.
662 struct GNUNET_CRYPTO_AesSessionKey d_key;
665 * Paths that are actively used to reach the destination peer.
667 struct MeshConnection *connection_head;
668 struct MeshConnection *connection_tail;
671 * Next connection number.
676 * Channels inside this tunnel.
678 struct MeshChannel *channel_head;
679 struct MeshChannel *channel_tail;
682 * Channel ID for the next created channel.
684 MESH_ChannelNumber next_chid;
687 * Channel ID for the next incoming channel.
689 MESH_ChannelNumber next_local_chid;
692 * Pending message count.
694 int pending_messages;
697 * Destroy flag: if true, destroy on last message.
702 * Queued messages, to transmit once tunnel gets connected.
704 struct MeshTunnelQueue *tq_head;
705 struct MeshTunnelQueue *tq_tail;
711 * Struct containing information about a client of the service
713 * TODO: add a list of 'waiting' ports
720 struct MeshClient *next;
725 struct MeshClient *prev;
728 * Tunnels that belong to this client, indexed by local id
730 struct GNUNET_CONTAINER_MultiHashMap32 *own_channels;
733 * Tunnels this client has accepted, indexed by incoming local id
735 struct GNUNET_CONTAINER_MultiHashMap32 *incoming_channels;
738 * Handle to communicate with the client
740 struct GNUNET_SERVER_Client *handle;
743 * Ports that this client has declared interest in.
744 * Indexed by port, contains *Client.
746 struct GNUNET_CONTAINER_MultiHashMap32 *ports;
749 * Whether the client is active or shutting down (don't send confirmations
750 * to a client that is shutting down.
755 * ID of the client, mainly for debug messages
761 /******************************************************************************/
762 /************************ DEBUG FUNCTIONS ****************************/
763 /******************************************************************************/
767 * GNUNET_SCHEDULER_Task for printing a message after some operation is done
768 * @param cls string to print
769 * @param success GNUNET_OK if the PUT was transmitted,
770 * GNUNET_NO on timeout,
771 * GNUNET_SYSERR on disconnect from service
772 * after the PUT message was transmitted
773 * (so we don't know if it was received or not)
778 mesh_debug (void *cls, int success)
782 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s (%d)\n", s, success);
788 /******************************************************************************/
789 /*********************** GLOBAL VARIABLES ****************************/
790 /******************************************************************************/
792 /************************** Configuration parameters **************************/
795 * How often to send path keepalives. Paths timeout after 4 missed.
797 static struct GNUNET_TIME_Relative refresh_connection_time;
800 * How often to PUT own ID in the DHT.
802 static struct GNUNET_TIME_Relative id_announce_time;
805 * Maximum time allowed to connect to a peer found by string.
807 static struct GNUNET_TIME_Relative connect_timeout;
810 * Default TTL for payload packets.
812 static unsigned long long default_ttl;
815 * DHT replication level, see DHT API: GNUNET_DHT_get_start, GNUNET_DHT_put.
817 static unsigned long long dht_replication_level;
820 * How many connections are we willing to maintain.
821 * Local connections are always allowed, even if there are more connections than max.
823 static unsigned long long max_connections;
826 * How many messages *in total* are we willing to queue, divide by number of
827 * connections to get connection queue size.
829 static unsigned long long max_msgs_queue;
832 * How many peers do we want to remember?
834 static unsigned long long max_peers;
837 * Percentage of messages that will be dropped (for test purposes only).
839 static unsigned long long drop_percent;
841 /*************************** Static global variables **************************/
844 * DLL with all the clients, head.
846 static struct MeshClient *clients_head;
849 * DLL with all the clients, tail.
851 static struct MeshClient *clients_tail;
854 * Tunnels known, indexed by MESH_TunnelID (MeshTunnel).
856 static struct GNUNET_CONTAINER_MultiHashMap *tunnels;
859 * Peers known, indexed by PeerIdentity (MeshPeer).
861 static struct GNUNET_CONTAINER_MultiHashMap *peers;
864 * Handle to communicate with core.
866 static struct GNUNET_CORE_Handle *core_handle;
871 static struct GNUNET_DHT_Handle *dht_handle;
874 * Handle to server lib.
876 static struct GNUNET_SERVER_Handle *server_handle;
879 * Handle to the statistics service.
881 static struct GNUNET_STATISTICS_Handle *stats;
884 * Notification context, to send messages to local clients.
886 static struct GNUNET_SERVER_NotificationContext *nc;
889 * Local peer own ID (memory efficient handle).
891 static GNUNET_PEER_Id myid;
894 * Local peer own ID (full value).
896 static struct GNUNET_PeerIdentity my_full_id;
901 static struct GNUNET_CRYPTO_EccPrivateKey *my_private_key;
906 static struct GNUNET_CRYPTO_EccPublicKey my_public_key;
909 * All ports clients of this peer have opened.
911 static struct GNUNET_CONTAINER_MultiHashMap32 *ports;
914 * Task to periodically announce itself in the network.
916 GNUNET_SCHEDULER_TaskIdentifier announce_id_task;
919 * Next ID to assign to a client.
921 unsigned int next_client_id;
924 /******************************************************************************/
925 /*********************** DECLARATIONS **************************/
926 /******************************************************************************/
929 * Function to process paths received for a new peer addition. The recorded
930 * paths form the initial tunnel, which can be optimized later.
931 * Called on each result obtained for the DHT search.
934 * @param exp when will this value expire
935 * @param key key of the result
936 * @param type type of the result
937 * @param size number of bytes in data
938 * @param data pointer to the result data
941 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
942 const struct GNUNET_HashCode * key,
943 const struct GNUNET_PeerIdentity *get_path,
944 unsigned int get_path_length,
945 const struct GNUNET_PeerIdentity *put_path,
946 unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
947 size_t size, const void *data);
951 * Retrieve the MeshPeer stucture associated with the peer, create one
952 * and insert it in the appropriate structures if the peer is not known yet.
954 * @param peer Full identity of the peer.
956 * @return Existing or newly created peer info.
958 static struct MeshPeer *
959 peer_get (const struct GNUNET_PeerIdentity *peer);
963 * Retrieve the MeshPeer stucture associated with the peer, create one
964 * and insert it in the appropriate structures if the peer is not known yet.
966 * @param peer Short identity of the peer.
968 * @return Existing or newly created peer info.
970 static struct MeshPeer *
971 peer_get_short (const GNUNET_PEER_Id peer);
975 * Build a PeerPath from the paths returned from the DHT, reversing the paths
976 * to obtain a local peer -> destination path and interning the peer ids.
978 * @return Newly allocated and created path
980 static struct MeshPeerPath *
981 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
982 unsigned int get_path_length,
983 const struct GNUNET_PeerIdentity *put_path,
984 unsigned int put_path_length);
988 * Adds a path to the data structs of all the peers in the path
990 * @param p Path to process.
991 * @param confirmed Whether we know if the path works or not.
994 path_add_to_peers (struct MeshPeerPath *p, int confirmed);
998 * Search for a tunnel by global ID using full PeerIdentities.
1000 * @param t Tunnel containing the channel.
1001 * @param chid Public channel number.
1003 * @return channel handler, NULL if doesn't exist
1005 static struct MeshChannel *
1006 channel_get (struct MeshTunnel2 *t, MESH_ChannelNumber chid);
1010 * Change the tunnel state.
1012 * @param t Tunnel whose state to change.
1013 * @param state New state.
1016 tunnel_change_state (struct MeshTunnel2 *t, enum MeshTunnelState state);
1020 * Notify a tunnel that a connection has broken that affects at least
1021 * some of its peers.
1023 * @param t Tunnel affected.
1024 * @param p1 Peer that got disconnected from p2.
1025 * @param p2 Peer that got disconnected from p1.
1027 * @return Short ID of the peer disconnected (either p1 or p2).
1028 * 0 if the tunnel remained unaffected.
1030 static GNUNET_PEER_Id
1031 tunnel_notify_connection_broken (struct MeshTunnel2 *t,
1032 GNUNET_PEER_Id p1, GNUNET_PEER_Id p2);
1035 * @brief Use the given path for the tunnel.
1036 * Update the next and prev hops (and RCs).
1037 * (Re)start the path refresh in case the tunnel is locally owned.
1039 * @param t Tunnel to update.
1040 * @param p Path to use.
1042 * @return Connection created.
1044 static struct MeshConnection *
1045 tunnel_use_path (struct MeshTunnel2 *t, struct MeshPeerPath *p);
1048 * Tunnel is empty: destroy it.
1050 * Notifies all participants (peers, cleints) about the destruction.
1052 * @param t Tunnel to destroy.
1055 tunnel_destroy_empty (struct MeshTunnel2 *t);
1058 * Destroy the tunnel.
1060 * This function does not generate any warning traffic to clients or peers.
1063 * Cancel messages belonging to this tunnel queued to neighbors.
1064 * Free any allocated resources linked to the tunnel.
1066 * @param t The tunnel to destroy.
1069 tunnel_destroy (struct MeshTunnel2 *t);
1072 * Create a connection.
1074 * @param tid Tunnel ID.
1075 * @param cid Connection ID.
1077 static struct MeshConnection *
1078 connection_new (struct GNUNET_HashCode *tid, uint32_t cid);
1081 * Connection is no longer needed: destroy it and remove from tunnel.
1083 * @param c Connection to destroy.
1086 connection_destroy (struct MeshConnection *c);
1089 * Send FWD keepalive packets for a connection.
1091 * @param cls Closure (connection for which to send the keepalive).
1092 * @param tc Notification context.
1095 connection_fwd_keepalive (void *cls,
1096 const struct GNUNET_SCHEDULER_TaskContext *tc);
1099 * Send BCK keepalive packets for a connection.
1101 * @param cls Closure (connection for which to send the keepalive).
1102 * @param tc Notification context.
1105 connection_bck_keepalive (void *cls,
1106 const struct GNUNET_SCHEDULER_TaskContext *tc);
1110 * Change the tunnel state.
1112 * @param c Connection whose state to change.
1113 * @param state New state.
1116 connection_change_state (struct MeshConnection* c,
1117 enum MeshConnectionState state);
1122 * @brief Queue and pass message to core when possible.
1124 * @param cls Closure (@c type dependant). It will be used by queue_send to
1125 * build the message to be sent if not already prebuilt.
1126 * @param type Type of the message, 0 for a raw message.
1127 * @param size Size of the message.
1128 * @param dst Neighbor to send message to.
1129 * @param c Connection this message belongs to, if any.
1130 * @param ch Channel this message belongs to, if applicable (otherwise NULL).
1133 queue_add (void *cls, uint16_t type, size_t size,
1134 struct MeshPeer *dst,
1135 struct MeshConnection *c,
1136 struct MeshChannel *ch);
1140 * Free a transmission that was already queued with all resources
1141 * associated to the request.
1143 * @param queue Queue handler to cancel.
1144 * @param clear_cls Is it necessary to free associated cls?
1147 queue_destroy (struct MeshPeerQueue *queue, int clear_cls);
1151 * Core callback to write a queued packet to core buffer
1153 * @param cls Closure (peer info).
1154 * @param size Number of bytes available in buf.
1155 * @param buf Where the to write the message.
1157 * @return number of bytes written to buf
1160 queue_send (void *cls, size_t size, void *buf);
1164 * Dummy function to separate declarations from definitions in function list.
1167 __mesh_divider______________________________________________________________();
1171 * Get string description for tunnel state.
1173 * @param s Tunnel state.
1175 * @return String representation.
1178 GNUNET_MESH_DEBUG_TS2S (enum MeshTunnelState s)
1180 static char buf[128];
1184 case MESH_TUNNEL_NEW:
1185 return "MESH_TUNNEL_NEW";
1186 case MESH_TUNNEL_SEARCHING:
1187 return "MESH_TUNNEL_SEARCHING";
1188 case MESH_TUNNEL_WAITING:
1189 return "MESH_TUNNEL_WAITING";
1190 case MESH_TUNNEL_READY:
1191 return "MESH_TUNNEL_READY";
1192 case MESH_TUNNEL_RECONNECTING:
1193 return "MESH_TUNNEL_RECONNECTING";
1196 sprintf (buf, "%u (UNKNOWN STATE)", s);
1203 * Get string description for tunnel state.
1205 * @param s Tunnel state.
1207 * @return String representation.
1210 GNUNET_MESH_DEBUG_CS2S (enum MeshTunnelState s)
1214 case MESH_CONNECTION_NEW:
1215 return "MESH_CONNECTION_NEW";
1216 case MESH_CONNECTION_SENT:
1217 return "MESH_CONNECTION_SENT";
1218 case MESH_CONNECTION_READY:
1219 return "MESH_CONNECTION_READY";
1221 return "MESH_CONNECTION_STATE_ERROR";
1227 /******************************************************************************/
1228 /************************ PERIODIC FUNCTIONS ****************************/
1229 /******************************************************************************/
1232 * Periodically announce self id in the DHT
1234 * @param cls closure
1235 * @param tc task context
1238 announce_id (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1240 struct PBlock block;
1242 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1244 announce_id_task = GNUNET_SCHEDULER_NO_TASK;
1248 * - Set data expiration in function of X
1249 * - Adapt X to churn
1251 DEBUG_DHT ("DHT_put for ID %s started.\n", GNUNET_i2s (&my_full_id));
1253 block.id = my_full_id;
1254 GNUNET_DHT_put (dht_handle, /* DHT handle */
1255 &my_full_id.hashPubKey, /* Key to use */
1256 dht_replication_level, /* Replication level */
1257 GNUNET_DHT_RO_RECORD_ROUTE | GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, /* DHT options */
1258 GNUNET_BLOCK_TYPE_MESH_PEER, /* Block type */
1259 sizeof (block), /* Size of the data */
1260 (const char *) &block, /* Data itself */
1261 GNUNET_TIME_UNIT_FOREVER_ABS, /* Data expiration */
1262 GNUNET_TIME_UNIT_FOREVER_REL, /* Retry time */
1263 NULL, /* Continuation */
1264 NULL); /* Continuation closure */
1266 GNUNET_SCHEDULER_add_delayed (id_announce_time, &announce_id, cls);
1270 /******************************************************************************/
1271 /****************** GENERAL HELPER FUNCTIONS ************************/
1272 /******************************************************************************/
1276 * Get the static string for a peer ID.
1280 * @return Static string for it's ID.
1283 peer2s (const struct MeshPeer *peer)
1287 return GNUNET_i2s (GNUNET_PEER_resolve2 (peer->id));
1292 * Get the previous hop in a connection
1294 * @param c Connection.
1296 * @return Previous peer in the connection.
1298 static struct MeshPeer *
1299 connection_get_prev_hop (struct MeshConnection *c)
1303 if (0 == c->own_pos || c->path->length < 2)
1304 id = c->path->peers[0];
1306 id = c->path->peers[c->own_pos - 1];
1308 return peer_get_short (id);
1313 * Get the next hop in a connection
1315 * @param c Connection.
1317 * @return Next peer in the connection.
1319 static struct MeshPeer *
1320 connection_get_next_hop (struct MeshConnection *c)
1324 if ((c->path->length - 1) == c->own_pos || c->path->length < 2)
1325 id = c->path->peers[c->path->length - 1];
1327 id = c->path->peers[c->own_pos + 1];
1329 return peer_get_short (id);
1334 * Get the hop in a connection.
1336 * @param c Connection.
1337 * @param fwd Next hop?
1339 * @return Next peer in the connection.
1341 static struct MeshPeer *
1342 connection_get_hop (struct MeshConnection *c, int fwd)
1345 return connection_get_next_hop (c);
1346 return connection_get_prev_hop (c);
1350 * Check if client has registered with the service and has not disconnected
1352 * @param client the client to check
1354 * @return non-NULL if client exists in the global DLL
1356 static struct MeshClient *
1357 client_get (struct GNUNET_SERVER_Client *client)
1359 return GNUNET_SERVER_client_get_user_context (client, struct MeshClient);
1364 * Deletes a tunnel from a client (either owner or destination).
1366 * @param c Client whose tunnel to delete.
1367 * @param ch Channel which should be deleted.
1370 client_delete_channel (struct MeshClient *c, struct MeshChannel *ch)
1376 res = GNUNET_CONTAINER_multihashmap32_remove (c->own_channels,
1378 if (GNUNET_YES != res)
1379 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client_delete_channel owner KO\n");
1383 res = GNUNET_CONTAINER_multihashmap32_remove (c->incoming_channels,
1385 if (GNUNET_YES != res)
1386 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client_delete_tunnel client KO\n");
1392 * Notify the appropriate client that a new incoming channel was created.
1394 * @param ch Channel that was created.
1397 send_local_channel_create (struct MeshChannel *ch)
1399 struct GNUNET_MESH_ChannelMessage msg;
1400 struct MeshTunnel2 *t = ch->t;
1402 if (NULL == ch->dest)
1404 msg.header.size = htons (sizeof (msg));
1405 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
1406 msg.channel_id = htonl (ch->lid_dest);
1407 msg.port = htonl (ch->port);
1409 msg.opt |= GNUNET_YES == ch->reliable ? GNUNET_MESH_OPTION_RELIABLE : 0;
1410 msg.opt |= GNUNET_YES == ch->nobuffer ? GNUNET_MESH_OPTION_NOBUFFER : 0;
1411 msg.opt = htonl (msg.opt);
1412 GNUNET_PEER_resolve (t->peer->id, &msg.peer);
1413 GNUNET_SERVER_notification_context_unicast (nc, ch->dest->handle,
1414 &msg.header, GNUNET_NO);
1419 * Notify a client that the incoming tunnel is no longer valid.
1421 * @param ch Channel that is destroyed.
1422 * @param fwd Forward notification (owner->dest)?
1425 send_local_channel_destroy (struct MeshChannel *ch, int fwd)
1427 struct GNUNET_MESH_ChannelMessage msg;
1428 struct MeshClient *c;
1430 c = fwd ? ch->dest : ch->root;
1436 msg.header.size = htons (sizeof (msg));
1437 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1438 msg.channel_id = htonl (fwd ? ch->lid_dest : ch->lid_root);
1439 msg.port = htonl (0);
1440 memset (&msg.peer, 0, sizeof (msg.peer));
1441 msg.opt = htonl (0);
1442 GNUNET_SERVER_notification_context_unicast (nc, c->handle,
1443 &msg.header, GNUNET_NO);
1448 * Build a local ACK message and send it to a local client.
1450 * @param ch Channel on which to send the ACK.
1451 * @param c Client to whom send the ACK.
1452 * @param is_fwd Set to GNUNET_YES for FWD ACK (dest->owner)
1455 send_local_ack (struct MeshChannel *ch,
1456 struct MeshClient *c,
1459 struct GNUNET_MESH_LocalAck msg;
1461 msg.header.size = htons (sizeof (msg));
1462 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
1463 msg.channel_id = htonl (is_fwd ? ch->lid_root : ch->lid_dest);
1464 GNUNET_SERVER_notification_context_unicast (nc,
1472 * Count established (ready) connections of a tunnel.
1474 * @param t Tunnel on which to send the message.
1476 * @return Number of connections.
1479 tunnel_count_connections (struct MeshTunnel2 *t)
1481 struct MeshConnection *c;
1484 for (c = t->connection_head, i = 0; NULL != c; c = c->next, i++);
1491 * Pick a connection on which send the next data message.
1493 * @param t Tunnel on which to send the message.
1494 * @param fwd Is this a fwd message?
1496 * @return The connection on which to send the next message.
1498 static struct MeshConnection *
1499 tunnel_get_connection (struct MeshTunnel2 *t, int fwd)
1501 struct MeshConnection *c;
1502 struct MeshConnection *best;
1503 struct MeshFlowControl *fc;
1504 unsigned int lowest_q;
1507 lowest_q = UINT_MAX;
1508 for (c = t->connection_head; NULL != c; c = c->next)
1510 if (MESH_CONNECTION_READY == c->state)
1512 fc = fwd ? &c->fwd_fc : &c->bck_fc;
1518 if (fc->queue_n < lowest_q)
1521 lowest_q = fc->queue_n;
1530 * Get the total buffer space for a tunnel.
1533 tunnel_get_buffer (struct MeshTunnel2 *t, int fwd)
1535 struct MeshConnection *c;
1536 struct MeshFlowControl *fc;
1537 unsigned int buffer;
1539 for (buffer = 0, c = t->connection_head; NULL != c; c = c->next)
1541 if (c->state != MESH_CONNECTION_READY)
1544 fc = fwd ? &c->fwd_fc : &c->bck_fc;
1545 buffer += fc->last_ack_recv - fc->last_pid_sent;
1553 * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
1554 * Encrypt data with the tunnel key.
1556 * @param t Tunnel whose key to use.
1557 * @param dst Destination for the encrypted data.
1558 * @param src Source of the plaintext.
1559 * @param size Size of the plaintext.
1560 * @param iv Initialization Vector to use.
1561 * @param fwd Is this a fwd message?
1564 tunnel_encrypt (struct MeshTunnel2 *t,
1565 void *dst, const void *src,
1566 size_t size, uint64_t iv, int fwd)
1568 memcpy (dst, src, size);
1573 * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
1574 * Decrypt data with the tunnel key.
1576 * @param t Tunnel whose key to use.
1577 * @param dst Destination for the plaintext.
1578 * @param src Source of the encrypted data.
1579 * @param size Size of the encrypted data.
1580 * @param iv Initialization Vector to use.
1581 * @param fwd Is this a fwd message?
1584 tunnel_decrypt (struct MeshTunnel2 *t,
1585 void *dst, const void *src,
1586 size_t size, uint64_t iv, int fwd)
1588 memcpy (dst, src, size);
1593 * Sends an already built message on a connection, properly registering
1594 * all used resources.
1596 * @param message Message to send. Function makes a copy of it.
1597 * If message is not hop-by-hop, decrements TTL of copy.
1598 * @param c Connection on which this message is transmitted.
1599 * @param ch Channel on which this message is transmitted, or NULL.
1600 * @param fwd Is this a fwd message?
1603 send_prebuilt_message_connection (const struct GNUNET_MessageHeader *message,
1604 struct MeshConnection *c,
1605 struct MeshChannel *ch,
1608 struct MeshPeer *neighbor;
1613 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send on Connection %s[%X]\n",
1614 GNUNET_h2s (&c->t->id), c->id);
1615 neighbor = connection_get_hop (c, fwd);
1616 if (NULL == neighbor)
1622 size = ntohs (message->size);
1623 data = GNUNET_malloc (size);
1624 memcpy (data, message, size);
1625 type = ntohs (message->type);
1627 if (GNUNET_MESSAGE_TYPE_MESH_FWD == type ||
1628 GNUNET_MESSAGE_TYPE_MESH_BCK == type)
1630 struct GNUNET_MESH_Encrypted *msg;
1633 msg = (struct GNUNET_MESH_Encrypted *) data;
1634 ttl = ntohl (msg->ttl);
1637 GNUNET_break_op (0);
1640 msg->ttl = htonl (ttl - 1);
1653 * Sends an already built message on a tunnel, choosing the best connection.
1655 * @param message Message to send. Function modifies it.
1656 * @param t Tunnel on which this message is transmitted.
1657 * @param ch Channel on which this message is transmitted.
1658 * @param fwd Is this a fwd message?
1661 send_prebuilt_message_tunnel (struct GNUNET_MESH_Encrypted *msg,
1662 struct MeshTunnel2 *t,
1663 struct MeshChannel *ch,
1666 struct MeshConnection *c;
1669 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send on Tunnel %s\n",
1670 GNUNET_h2s (&t->id));
1671 c = tunnel_get_connection (t, fwd);
1677 type = ntohs (msg->header.type);
1680 case GNUNET_MESSAGE_TYPE_MESH_FWD:
1681 case GNUNET_MESSAGE_TYPE_MESH_BCK:
1682 msg->cid = htonl (c->id);
1684 msg->ttl = default_ttl;
1687 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
1688 GNUNET_MESH_DEBUG_M2S (type));
1692 send_prebuilt_message_connection (&msg->header, c, ch, fwd);
1697 * Sends an already built message on a channel, properly registering
1698 * all used resources and encrypting the message with the tunnel's key.
1700 * @param message Message to send. Function makes a copy of it.
1701 * @param ch Channel on which this message is transmitted.
1702 * @param fwd Is this a fwd message?
1705 send_prebuilt_message_channel (const struct GNUNET_MessageHeader *message,
1706 struct MeshChannel *ch,
1709 struct GNUNET_MESH_Encrypted *msg;
1710 size_t size = ntohs (message->size);
1711 char *cbuf[sizeof (struct GNUNET_MESH_Encrypted) + size];
1715 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send on Channel %s:%X\n",
1716 GNUNET_h2s (&ch->t->id), ch->gid);
1717 type = fwd ? GNUNET_MESSAGE_TYPE_MESH_FWD : GNUNET_MESSAGE_TYPE_MESH_BCK;
1718 iv = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_NONCE, UINT64_MAX);
1720 msg = (struct GNUNET_MESH_Encrypted *) cbuf;
1721 msg->header.type = htons (type);
1722 msg->header.size = htons (sizeof (struct GNUNET_MESH_Encrypted) + size);
1723 msg->iv = GNUNET_htonll (iv);
1724 tunnel_encrypt (ch->t, &msg[1], message, size, iv, fwd);
1726 send_prebuilt_message_tunnel (msg, ch->t, ch, fwd);
1731 * Sends a CREATE CONNECTION message for a path to a peer.
1732 * Changes the connection and tunnel states if necessary.
1734 * @param connection Connection to create.
1737 send_connection_create (struct MeshConnection *connection)
1739 struct MeshPeer *neighbor;
1740 struct MeshTunnel2 *t;
1743 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send connection create\n");
1744 neighbor = connection_get_next_hop (connection);
1745 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " to %s\n", peer2s (neighbor));
1746 queue_add (connection,
1747 GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
1748 sizeof (struct GNUNET_MESH_ConnectionCreate) +
1749 (connection->path->length *
1750 sizeof (struct GNUNET_PeerIdentity)),
1754 if (MESH_TUNNEL_SEARCHING == t->state || MESH_TUNNEL_NEW == t->state)
1755 tunnel_change_state (t, MESH_TUNNEL_WAITING);
1756 if (MESH_CONNECTION_NEW == connection->state)
1757 connection_change_state (connection, MESH_CONNECTION_SENT);
1762 * Sends a CONNECTION ACK message in reponse to a received CONNECTION_CREATE
1765 * @param connection Connection to confirm.
1768 send_connection_ack (struct MeshConnection *connection)
1770 struct MeshPeer *neighbor;
1771 struct MeshTunnel2 *t;
1774 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send connection ack\n");
1775 neighbor = connection_get_prev_hop (connection);
1776 queue_add (connection,
1777 GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
1778 sizeof (struct GNUNET_MESH_ConnectionACK),
1782 if (MESH_TUNNEL_NEW == t->state)
1783 tunnel_change_state (t, MESH_TUNNEL_WAITING);
1788 * Build a hop-by-hop ACK message and queue it to send for the given connection.
1790 * @param c Which connection to send the hop-by-hop ACK.
1791 * @param ack Value of the ACK.
1792 * @param fwd Is this fwd?
1795 send_ack (struct MeshConnection *c, uint32_t ack, int fwd)
1797 struct GNUNET_MESH_ACK msg;
1799 msg.header.size = htons (sizeof (msg));
1800 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ACK);
1801 msg.ack = htonl (ack);
1803 msg.cid = htonl (c->id);
1805 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1806 "connection send %s ack %u on %s[%X]\n",
1807 fwd ? "FWD" : "BCK", ack, GNUNET_h2s (&c->t->id), c->id);
1809 send_prebuilt_message_connection (&msg.header, c, NULL, fwd);
1814 * Core callback to write a pre-constructed data packet to core buffer
1816 * @param cls Closure (MeshTransmissionDescriptor with data in "data" member).
1817 * @param size Number of bytes available in buf.
1818 * @param buf Where the to write the message.
1820 * @return number of bytes written to buf
1823 send_core_data_raw (void *cls, size_t size, void *buf)
1825 struct GNUNET_MessageHeader *msg = cls;
1828 GNUNET_assert (NULL != msg);
1829 total_size = ntohs (msg->size);
1831 if (total_size > size)
1836 memcpy (buf, msg, total_size);
1843 * Function to send a create connection message to a peer.
1845 * @param cls closure
1846 * @param size number of bytes available in buf
1847 * @param buf where the callee should write the message
1848 * @return number of bytes written to buf
1851 send_core_connection_create (void *cls, size_t size, void *buf)
1853 struct MeshConnection *c = cls;
1854 struct GNUNET_MESH_ConnectionCreate *msg;
1855 struct GNUNET_PeerIdentity *peer_ptr;
1856 struct MeshPeerPath *p = c->path;
1860 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION CREATE...\n");
1862 sizeof (struct GNUNET_MESH_ConnectionCreate) +
1863 p->length * sizeof (struct GNUNET_PeerIdentity);
1865 if (size < size_needed || NULL == buf)
1870 msg = (struct GNUNET_MESH_ConnectionCreate *) buf;
1871 msg->header.size = htons (size_needed);
1872 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE);
1873 msg->cid = htonl (c->id);
1874 msg->tid = c->t->id;
1876 peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
1877 for (i = 0; i < p->length; i++)
1879 GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
1882 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1883 "CONNECTION CREATE (%u bytes long) sent!\n", size_needed);
1889 * Creates a path ack message in buf and frees all unused resources.
1891 * @param cls closure (MeshTransmissionDescriptor)
1892 * @param size number of bytes available in buf
1893 * @param buf where the callee should write the message
1894 * @return number of bytes written to buf
1897 send_core_connection_ack (void *cls, size_t size, void *buf)
1899 struct GNUNET_MESH_ConnectionACK *msg = buf;
1900 struct MeshConnection *c = cls;
1901 struct MeshTunnel2 *t = c->t;
1903 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION ACK...\n");
1904 GNUNET_assert (NULL != t);
1905 if (sizeof (struct GNUNET_MESH_ConnectionACK) > size)
1910 msg->header.size = htons (sizeof (struct GNUNET_MESH_ConnectionACK));
1911 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK);
1912 msg->cid = htonl (c->id);
1915 /* TODO add signature */
1917 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CONNECTION ACK sent!\n");
1918 return sizeof (struct GNUNET_MESH_ConnectionACK);
1923 * Destroy the peer_info and free any allocated resources linked to it
1925 * @param peer The peer_info to destroy.
1927 * @return GNUNET_OK on success
1930 peer_destroy (struct MeshPeer *peer)
1932 struct GNUNET_PeerIdentity id;
1933 struct MeshPeerPath *p;
1934 struct MeshPeerPath *nextp;
1936 GNUNET_PEER_resolve (peer->id, &id);
1937 GNUNET_PEER_change_rc (peer->id, -1);
1940 GNUNET_CONTAINER_multihashmap_remove (peers, &id.hashPubKey, peer))
1943 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1944 "removing peer %s, not in hashmap\n", GNUNET_i2s (&id));
1946 if (NULL != peer->dhtget)
1948 GNUNET_DHT_get_stop (peer->dhtget);
1950 p = peer->path_head;
1954 GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
1958 tunnel_destroy_empty (peer->tunnel);
1965 * Returns if peer is used (has a tunnel, is neighbor).
1967 * @peer Peer to check.
1969 * @return GNUNET_YES if peer is in use.
1972 peer_is_used (struct MeshPeer *peer)
1974 struct MeshPeerPath *p;
1976 if (NULL != peer->tunnel)
1979 for (p = peer->path_head; NULL != p; p = p->next)
1988 * Iterator over all the peers to get the oldest timestamp.
1990 * @param cls Closure (unsued).
1991 * @param key ID of the peer.
1992 * @param value Peer_Info of the peer.
1995 peer_get_oldest (void *cls,
1996 const struct GNUNET_HashCode *key,
1999 struct MeshPeer *p = value;
2000 struct GNUNET_TIME_Absolute *abs = cls;
2002 /* Don't count active peers */
2003 if (GNUNET_YES == peer_is_used (p))
2006 if (abs->abs_value_us < p->last_contact.abs_value_us)
2007 abs->abs_value_us = p->last_contact.abs_value_us;
2014 * Iterator over all the peers to remove the oldest entry.
2016 * @param cls Closure (unsued).
2017 * @param key ID of the peer.
2018 * @param value Peer_Info of the peer.
2021 peer_timeout (void *cls,
2022 const struct GNUNET_HashCode *key,
2025 struct MeshPeer *p = value;
2026 struct GNUNET_TIME_Absolute *abs = cls;
2028 if (p->last_contact.abs_value_us == abs->abs_value_us &&
2029 GNUNET_NO == peer_is_used (p))
2039 * Delete oldest unused peer.
2042 peer_delete_oldest (void)
2044 struct GNUNET_TIME_Absolute abs;
2046 abs = GNUNET_TIME_UNIT_FOREVER_ABS;
2048 GNUNET_CONTAINER_multihashmap_iterate (peers,
2051 GNUNET_CONTAINER_multihashmap_iterate (peers,
2058 * Retrieve the MeshPeer stucture associated with the peer, create one
2059 * and insert it in the appropriate structures if the peer is not known yet.
2061 * @param peer Full identity of the peer.
2063 * @return Existing or newly created peer info.
2065 static struct MeshPeer *
2066 peer_get (const struct GNUNET_PeerIdentity *peer_id)
2068 struct MeshPeer *peer;
2070 peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer_id->hashPubKey);
2073 peer = GNUNET_new (struct MeshPeer);
2074 if (GNUNET_CONTAINER_multihashmap_size (peers) > max_peers)
2076 peer_delete_oldest ();
2078 GNUNET_CONTAINER_multihashmap_put (peers, &peer_id->hashPubKey, peer,
2079 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
2080 peer->id = GNUNET_PEER_intern (peer_id);
2082 peer->last_contact = GNUNET_TIME_absolute_get();
2089 * Retrieve the MeshPeer stucture associated with the peer, create one
2090 * and insert it in the appropriate structures if the peer is not known yet.
2092 * @param peer Short identity of the peer.
2094 * @return Existing or newly created peer info.
2096 static struct MeshPeer *
2097 peer_get_short (const GNUNET_PEER_Id peer)
2099 return peer_get (GNUNET_PEER_resolve2 (peer));
2104 * Get a cost of a path for a peer considering existing tunnel connections.
2106 * @param peer Peer towards which the path is considered.
2107 * @param path Candidate path.
2109 * @return Cost of the path (path length + number of overlapping nodes)
2112 peer_get_path_cost (const struct MeshPeer *peer,
2113 const struct MeshPeerPath *path)
2115 struct MeshConnection *c;
2116 unsigned int overlap;
2124 GNUNET_assert (NULL != peer->tunnel);
2126 for (i = 0; i < path->length; i++)
2128 for (c = peer->tunnel->connection_head; NULL != c; c = c->next)
2130 for (j = 0; j < c->path->length; j++)
2132 if (path->peers[i] == c->path->peers[j])
2140 return (path->length + overlap) * (path->score * -1);
2145 * Choose the best path towards a peer considering the tunnel properties.
2147 * @param peer The destination peer.
2149 * @return Best current known path towards the peer, if any.
2151 static struct MeshPeerPath *
2152 peer_get_best_path (const struct MeshPeer *peer)
2154 struct MeshPeerPath *best_p;
2155 struct MeshPeerPath *p;
2156 struct MeshConnection *c;
2157 unsigned int best_cost;
2160 best_cost = UINT_MAX;
2162 for (p = peer->path_head; NULL != p; p = p->next)
2164 for (c = peer->tunnel->connection_head; NULL != c; c = c->next)
2168 continue; /* If path is in use in a connection, skip it. */
2170 if ((cost = peer_get_path_cost (peer, p)) < best_cost)
2180 queue_is_sendable (struct MeshPeerQueue *q)
2182 struct MeshFlowControl *fc;
2184 /* Is PID-independent? */
2187 case GNUNET_MESSAGE_TYPE_MESH_ACK:
2188 case GNUNET_MESSAGE_TYPE_MESH_POLL:
2192 /* Is PID allowed? */
2193 fc = q->fwd ? &q->c->fwd_fc : &q->c->bck_fc;
2194 if (GMC_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
2202 * Get first sendable message.
2204 * @param peer The destination peer.
2206 * @return Best current known path towards the peer, if any.
2208 static struct MeshPeerQueue *
2209 peer_get_first_message (const struct MeshPeer *peer)
2211 struct MeshPeerQueue *q;
2213 for (q = peer->queue_head; NULL != q; q = q->next)
2215 if (queue_is_sendable (q))
2224 * Try to establish a new connection to this peer in the given tunnel.
2225 * If the peer doesn't have any path to it yet, try to get one.
2226 * If the peer already has some path, send a CREATE CONNECTION towards it.
2228 * @param peer PeerInfo of the peer.
2231 peer_connect (struct MeshPeer *peer)
2233 struct MeshTunnel2 *t;
2234 struct MeshPeerPath *p;
2235 struct MeshConnection *c;
2237 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2238 "peer_connect towards %s\n",
2241 if (NULL != peer->path_head)
2243 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "path exists\n");
2244 p = peer_get_best_path (peer);
2247 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " %u hops\n", p->length);
2248 c = tunnel_use_path (t, p);
2249 send_connection_create (c);
2252 else if (NULL == peer->dhtget)
2254 const struct GNUNET_PeerIdentity *id;
2256 id = GNUNET_PEER_resolve2 (peer->id);
2257 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2258 " Starting DHT GET for peer %s\n", peer2s (peer));
2259 peer->dhtget = GNUNET_DHT_get_start (dht_handle, /* handle */
2260 GNUNET_BLOCK_TYPE_MESH_PEER, /* type */
2261 &id->hashPubKey, /* key to search */
2262 dht_replication_level, /* replication level */
2263 GNUNET_DHT_RO_RECORD_ROUTE |
2264 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
2266 0, /* xquery bits */
2267 &dht_get_id_handler, peer);
2268 if (MESH_TUNNEL_NEW == t->state)
2269 tunnel_change_state (t, MESH_TUNNEL_SEARCHING);
2273 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2274 "There is no path but the DHT GET is already started.\n");
2280 * Get the first transmittable message for a connection.
2282 * @param c Connection.
2283 * @param fwd Is this FWD?
2285 * @return First transmittable message.
2287 static struct MeshPeerQueue *
2288 connection_get_first_message (struct MeshConnection *c, int fwd)
2290 struct MeshPeerQueue *q;
2293 p = connection_get_hop (c, fwd);
2295 for (q = p->queue_head; NULL != q; q = q->next)
2299 if (queue_is_sendable (q))
2308 * Is this peer the last one on the connection?
2310 * @param c Connection.
2311 * @param fwd Is this about fwd traffic?
2312 * Note that the ROOT is the terminal for BCK traffic!
2314 * @return GNUNET_YES if terminal, GNUNET_NO if relay/origin.
2317 connection_is_terminal (struct MeshConnection *c, int fwd)
2319 if (fwd && c->own_pos == c->path->length - 1)
2321 if (!fwd && c->own_pos == 0)
2328 * @brief Re-initiate traffic on this connection if necessary.
2330 * Check if there is traffic queued towards this peer
2331 * and the core transmit handle is NULL (traffic was stalled).
2332 * If so, call core tmt rdy.
2334 * @param c Connection on which initiate traffic.
2335 * @param fwd Is this about fwd traffic?
2338 connection_unlock_queue (struct MeshConnection *c, int fwd)
2340 struct MeshPeer *peer;
2341 struct MeshPeerQueue *q;
2344 peer = connection_get_hop (c, fwd);
2346 if (NULL != peer->core_transmit)
2347 return; /* Already unlocked */
2349 q = connection_get_first_message (c, fwd);
2351 return; /* Nothing to transmit */
2354 peer->core_transmit =
2355 GNUNET_CORE_notify_transmit_ready (core_handle,
2358 GNUNET_TIME_UNIT_FOREVER_REL,
2359 GNUNET_PEER_resolve2 (peer->id),
2367 * Cancel all transmissions that belong to a certain connection.
2369 * @param c Connection which to cancel.
2370 * @param fwd Cancel fwd traffic?
2373 connection_cancel_queues (struct MeshConnection *c, int fwd)
2375 struct MeshPeerQueue *q;
2376 struct MeshPeerQueue *next;
2377 struct MeshFlowControl *fc;
2378 struct MeshPeer *peer;
2385 fc = fwd ? &c->fwd_fc : &c->bck_fc;
2386 peer = connection_get_hop (c, fwd);
2388 for (q = peer->queue_head; NULL != q; q = next)
2393 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2394 "connection_cancel_queue %s\n",
2395 GNUNET_MESH_DEBUG_M2S (q->type));
2396 queue_destroy (q, GNUNET_YES);
2399 if (NULL == peer->queue_head)
2401 if (NULL != peer->core_transmit)
2403 GNUNET_CORE_notify_transmit_ready_cancel (peer->core_transmit);
2404 peer->core_transmit = NULL;
2406 if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
2408 GNUNET_SCHEDULER_cancel (fc->poll_task);
2409 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2416 * Remove all paths that rely on a direct connection between p1 and p2
2417 * from the peer itself and notify all tunnels about it.
2419 * @param peer PeerInfo of affected peer.
2420 * @param p1 GNUNET_PEER_Id of one peer.
2421 * @param p2 GNUNET_PEER_Id of another peer that was connected to the first and
2424 * TODO: optimize (see below)
2427 peer_remove_path (struct MeshPeer *peer, GNUNET_PEER_Id p1,
2430 struct MeshPeerPath *p;
2431 struct MeshPeerPath *next;
2432 struct MeshPeer *peer_d;
2434 unsigned int destroyed;
2437 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path\n");
2439 for (p = peer->path_head; NULL != p; p = next)
2442 for (i = 0; i < (p->length - 1); i++)
2444 if ((p->peers[i] == p1 && p->peers[i + 1] == p2) ||
2445 (p->peers[i] == p2 && p->peers[i + 1] == p1))
2447 GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
2458 d = tunnel_notify_connection_broken (peer->tunnel, p1, p2);
2460 peer_d = peer_get_short (d); // FIXME
2461 next = peer_get_best_path (peer_d);
2462 tunnel_use_path (peer->tunnel, next);
2463 peer_connect (peer_d);
2465 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path END\n");
2470 * Add the path to the peer and update the path used to reach it in case this
2473 * @param peer_info Destination peer to add the path to.
2474 * @param path New path to add. Last peer must be the peer in arg 1.
2475 * Path will be either used of freed if already known.
2476 * @param trusted Do we trust that this path is real?
2479 peer_add_path (struct MeshPeer *peer_info, struct MeshPeerPath *path,
2482 struct MeshPeerPath *aux;
2486 if ((NULL == peer_info) || (NULL == path))
2489 path_destroy (path);
2492 if (path->peers[path->length - 1] != peer_info->id)
2495 path_destroy (path);
2498 if (2 >= path->length && GNUNET_NO == trusted)
2500 /* Only allow CORE to tell us about direct paths */
2501 path_destroy (path);
2504 for (l = 1; l < path->length; l++)
2506 if (path->peers[l] == myid)
2508 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shortening path by %u\n", l);
2509 for (l2 = 0; l2 < path->length - l; l2++)
2511 path->peers[l2] = path->peers[l + l2];
2516 GNUNET_realloc (path->peers, path->length * sizeof (GNUNET_PEER_Id));
2520 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "adding path [%u] to peer %s\n",
2521 path->length, peer2s (peer_info));
2523 l = path_get_length (path);
2526 path_destroy (path);
2530 GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
2531 for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
2533 l2 = path_get_length (aux);
2536 GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
2537 peer_info->path_tail, aux, path);
2542 if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
2544 path_destroy (path);
2549 GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head, peer_info->path_tail,
2556 * Add the path to the origin peer and update the path used to reach it in case
2557 * this is the shortest.
2558 * The path is given in peer_info -> destination, therefore we turn the path
2559 * upside down first.
2561 * @param peer_info Peer to add the path to, being the origin of the path.
2562 * @param path New path to add after being inversed.
2563 * Path will be either used or freed.
2564 * @param trusted Do we trust that this path is real?
2567 peer_add_path_to_origin (struct MeshPeer *peer_info,
2568 struct MeshPeerPath *path, int trusted)
2571 peer_add_path (peer_info, path, trusted);
2577 * Function called if a connection has been stalled for a while,
2578 * possibly due to a missed ACK. Poll the neighbor about its ACK status.
2580 * @param cls Closure (poll ctx).
2581 * @param tc TaskContext.
2584 connection_poll (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2586 struct MeshFlowControl *fc = cls;
2587 struct GNUNET_MESH_Poll msg;
2588 struct MeshConnection *c;
2590 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2591 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2597 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** Polling!\n");
2598 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** connection %s[%X]\n",
2599 peer2s (c->t->peer), c->id);
2601 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_POLL);
2602 msg.header.size = htons (sizeof (msg));
2603 msg.pid = htonl (fc->last_pid_sent);
2604 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** pid (%u)!\n", fc->last_pid_sent);
2605 send_prebuilt_message_connection (&msg.header, c, NULL, fc == &c->fwd_fc);
2606 fc->poll_time = GNUNET_TIME_STD_BACKOFF (fc->poll_time);
2607 fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
2608 &connection_poll, fc);
2613 * Build a PeerPath from the paths returned from the DHT, reversing the paths
2614 * to obtain a local peer -> destination path and interning the peer ids.
2616 * @return Newly allocated and created path
2618 static struct MeshPeerPath *
2619 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
2620 unsigned int get_path_length,
2621 const struct GNUNET_PeerIdentity *put_path,
2622 unsigned int put_path_length)
2624 struct MeshPeerPath *p;
2630 GNUNET_PEER_change_rc (myid, 1);
2631 i = get_path_length;
2632 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " GET has %d hops.\n", i);
2633 for (i--; i >= 0; i--)
2635 id = GNUNET_PEER_intern (&get_path[i]);
2636 if (p->length > 0 && id == p->peers[p->length - 1])
2638 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Optimizing 1 hop out.\n");
2639 GNUNET_PEER_change_rc (id, -1);
2643 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Adding from GET: %s.\n",
2644 GNUNET_i2s (&get_path[i]));
2646 p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2647 p->peers[p->length - 1] = id;
2650 i = put_path_length;
2651 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " PUT has %d hops.\n", i);
2652 for (i--; i >= 0; i--)
2654 id = GNUNET_PEER_intern (&put_path[i]);
2657 /* PUT path went through us, so discard the path up until now and start
2658 * from here to get a much shorter (and loop-free) path.
2663 if (p->length > 0 && id == p->peers[p->length - 1])
2665 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Optimizing 1 hop out.\n");
2666 GNUNET_PEER_change_rc (id, -1);
2670 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Adding from PUT: %s.\n",
2671 GNUNET_i2s (&put_path[i]));
2673 p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2674 p->peers[p->length - 1] = id;
2678 if (get_path_length > 0)
2679 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " (first of GET: %s)\n",
2680 GNUNET_i2s (&get_path[0]));
2681 if (put_path_length > 0)
2682 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " (first of PUT: %s)\n",
2683 GNUNET_i2s (&put_path[0]));
2684 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " In total: %d hops\n",
2686 for (i = 0; i < p->length; i++)
2688 struct GNUNET_PeerIdentity peer_id;
2690 GNUNET_PEER_resolve (p->peers[i], &peer_id);
2691 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " %u: %s\n", p->peers[i],
2692 GNUNET_i2s (&peer_id));
2700 * Adds a path to the peer_infos of all the peers in the path
2702 * @param p Path to process.
2703 * @param confirmed Whether we know if the path works or not.
2706 path_add_to_peers (struct MeshPeerPath *p, int confirmed)
2710 /* TODO: invert and add */
2711 for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
2712 for (i++; i < p->length; i++)
2714 struct MeshPeer *aux;
2715 struct MeshPeerPath *copy;
2717 aux = peer_get_short (p->peers[i]);
2718 copy = path_duplicate (p);
2719 copy->length = i + 1;
2720 peer_add_path (aux, copy, p->length < 3 ? GNUNET_NO : confirmed);
2726 * Search for a channel among the channels for a client
2728 * @param c the client whose channels to search in
2729 * @param chid the local id of the channel
2731 * @return channel handler, NULL if doesn't exist
2733 static struct MeshChannel *
2734 channel_get_by_local_id (struct MeshClient *c, MESH_ChannelNumber chid)
2736 if (0 == (chid & GNUNET_MESH_LOCAL_CHANNEL_ID_CLI))
2738 GNUNET_break_op (0);
2739 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CHID %X not a local chid\n", chid);
2742 if (chid >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV)
2743 return GNUNET_CONTAINER_multihashmap32_get (c->incoming_channels, chid);
2744 return GNUNET_CONTAINER_multihashmap32_get (c->own_channels, chid);
2748 * Search for a tunnel by global ID using full PeerIdentities.
2750 * @param t Tunnel containing the channel.
2751 * @param chid Public channel number.
2753 * @return channel handler, NULL if doesn't exist
2755 static struct MeshChannel *
2756 channel_get (struct MeshTunnel2 *t, MESH_ChannelNumber chid)
2758 struct MeshChannel *ch;
2763 for (ch = t->channel_head; NULL != ch; ch = ch->next)
2765 if (ch->gid == chid)
2774 * Change the tunnel state.
2776 * @param t Tunnel whose state to change.
2777 * @param state New state.
2780 tunnel_change_state (struct MeshTunnel2* t, enum MeshTunnelState state)
2782 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2783 "Tunnel %s state was %s\n",
2785 GNUNET_MESH_DEBUG_TS2S (t->state));
2786 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2787 "Tunnel %s state is now %s\n",
2789 GNUNET_MESH_DEBUG_TS2S (state));
2795 * Cache a message to be sent once tunnel is online.
2797 * @param t Tunnel to hold the message.
2798 * @param ch Channel the message is about.
2799 * @param msg Message itself (copy will be made).
2800 * @param fwd Is this fwd?
2803 tunnel_queue_data (struct MeshTunnel2 *t,
2804 struct MeshChannel *ch,
2805 struct GNUNET_MessageHeader *msg,
2808 struct MeshTunnelQueue *tq;
2809 uint16_t size = ntohs (msg->size);
2811 tq = GNUNET_malloc (sizeof (struct MeshTunnelQueue) + size);
2814 memcpy (&tq[1], msg, size);
2815 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tq);
2820 * Send all cached messages that we can, tunnel is online.
2822 * @param t Tunnel that holds the messages.
2823 * @param fwd Is this fwd?
2826 tunnel_send_queued_data (struct MeshTunnel2 *t, int fwd)
2828 struct MeshTunnelQueue *tq;
2829 struct MeshTunnelQueue *next;
2832 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2833 "tunnel_send_queued_data on %s\n",
2834 GNUNET_h2s (&t->id));
2835 room = tunnel_get_buffer (t, fwd);
2836 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
2837 for (tq = t->tq_head; NULL != tq && room > 0; tq = next)
2841 GNUNET_CONTAINER_DLL_remove (t->tq_head, t->tq_tail, tq);
2842 send_prebuilt_message_channel ((struct GNUNET_MessageHeader *) &tq[1],
2851 connection_change_state (struct MeshConnection* c,
2852 enum MeshConnectionState state)
2854 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2855 "Connection %s[%X] state was %s\n",
2856 peer2s (c->t->peer), c->id,
2857 GNUNET_MESH_DEBUG_CS2S (c->state));
2858 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2859 "Connection %s[%X] state is now %s\n",
2860 peer2s (c->t->peer), c->id,
2861 GNUNET_MESH_DEBUG_CS2S (state));
2867 * Add a client to a channel, initializing all needed data structures.
2869 * @param ch Channel to which add the client.
2870 * @param c Client which to add to the channel.
2873 channel_add_client (struct MeshChannel *ch, struct MeshClient *c)
2875 struct MeshTunnel2 *t = ch->t;
2877 if (NULL != ch->dest)
2883 /* Assign local id as destination */
2884 while (NULL != channel_get_by_local_id (c, t->next_local_chid))
2885 t->next_local_chid = (t->next_local_chid + 1) | GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
2886 ch->lid_dest = t->next_local_chid++;
2887 t->next_local_chid = t->next_local_chid | GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
2889 /* Store in client's hashmap */
2891 GNUNET_CONTAINER_multihashmap32_put (c->incoming_channels,
2893 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2902 static struct MeshConnection *
2903 tunnel_use_path (struct MeshTunnel2 *t, struct MeshPeerPath *p)
2905 struct MeshConnection *c;
2906 unsigned int own_pos;
2908 c = connection_new (&t->id, t->next_cid++);
2909 for (own_pos = 0; own_pos < p->length; own_pos++)
2911 if (p->peers[own_pos] == myid)
2914 if (own_pos > p->length - 1)
2917 connection_destroy (c);
2920 c->own_pos = own_pos;
2925 c->fwd_maintenance_task =
2926 GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
2927 &connection_fwd_keepalive, c);
2934 * Notifies a tunnel that a connection has broken that affects at least
2935 * some of its peers. Sends a notification towards the root of the tree.
2936 * In case the peer is the owner of the tree, notifies the client that owns
2937 * the tunnel and tries to reconnect.
2939 * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
2941 * @param t Tunnel affected.
2942 * @param p1 Peer that got disconnected from p2.
2943 * @param p2 Peer that got disconnected from p1.
2945 * @return Short ID of the peer disconnected (either p1 or p2).
2946 * 0 if the tunnel remained unaffected.
2948 static GNUNET_PEER_Id
2949 tunnel_notify_connection_broken (struct MeshTunnel2* t,
2950 GNUNET_PEER_Id p1, GNUNET_PEER_Id p2)
2952 // if (myid != p1 && myid != p2) FIXME
2957 // if (tree_get_predecessor (t->tree) != 0)
2959 // /* We are the peer still connected, notify owner of the disconnection. */
2960 // struct GNUNET_MESH_PathBroken msg;
2961 // struct GNUNET_PeerIdentity neighbor;
2963 // msg.header.size = htons (sizeof (msg));
2964 // msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN);
2965 // GNUNET_PEER_resolve (t->id.oid, &msg.oid);
2966 // msg.tid = htonl (t->id.tid);
2967 // msg.peer1 = my_full_id;
2968 // GNUNET_PEER_resolve (pid, &msg.peer2);
2969 // GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &neighbor);
2970 // send_prebuilt_message (&msg.header, &neighbor, t);
2977 * Send an end-to-end FWD ACK message for the most recent in-sequence payload.
2979 * @param ch Channel this is about.
2980 * @param fwd Is for FWD traffic? (ACK dest->owner)
2983 channel_send_data_ack (struct MeshChannel *ch, int fwd)
2985 struct GNUNET_MESH_DataACK msg;
2986 struct MeshChannelReliability *rel;
2987 struct MeshReliableMessage *copy;
2992 if (GNUNET_NO == ch->reliable)
2997 rel = fwd ? ch->bck_rel : ch->fwd_rel;
2998 mid = fwd ? &ch->mid_recv_fwd : &ch->mid_recv_bck;
2999 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3000 "send_data_ack for %u\n",
3003 msg.header.type = htons (fwd ? GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK :
3004 GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK);
3005 msg.header.size = htons (sizeof (msg));
3006 msg.chid = htonl (ch->gid);
3007 msg.mid = htonl (*mid - 1);
3009 for (copy = rel->head_recv; NULL != copy; copy = copy->next)
3011 delta = copy->mid - *mid;
3014 mask = 0x1LL << delta;
3015 msg.futures |= mask;
3016 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3017 " setting bit for %u (delta %u) (%llX) -> %llX\n",
3018 copy->mid, delta, mask, msg.futures);
3020 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " final futures %llX\n", msg.futures);
3022 send_prebuilt_message_channel (&msg.header, ch, fwd);
3023 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_data_ack END\n");
3028 * Send an ACK informing the predecessor about the available buffer space.
3030 * Note that for fwd ack, the FWD mean forward *traffic* (root->dest),
3031 * the ACK itself goes "back" (dest->root).
3033 * @param c Connection on which to send the ACK.
3034 * @param fwd Is this FWD ACK? (Going dest->owner)
3037 connection_send_ack (struct MeshConnection *c, int fwd)
3039 struct MeshFlowControl *next_fc;
3040 struct MeshFlowControl *prev_fc;
3044 next_fc = fwd ? &c->fwd_fc : &c->bck_fc;
3045 prev_fc = fwd ? &c->bck_fc : &c->fwd_fc;
3047 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3048 "connection send %s ack on %s[%X]\n",
3049 fwd ? "FWD" : "BCK", GNUNET_h2s (&c->t->id), c->id);
3051 /* Check if we need to transmit the ACK */
3052 if (prev_fc->last_ack_sent - prev_fc->last_pid_recv > 3)
3054 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer > 3\n");
3055 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3056 " last pid recv: %u, last ack sent: %u\n",
3057 prev_fc->last_pid_recv, prev_fc->last_ack_sent);
3061 /* Ok, ACK might be necessary, what PID to ACK? */
3062 delta = next_fc->queue_max - next_fc->queue_n;
3063 ack = prev_fc->last_pid_recv + delta;
3064 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", ack);
3065 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3066 " last pid %u, last ack %u, qmax %u, q %u\n",
3067 prev_fc->last_pid_recv, prev_fc->last_ack_sent,
3068 next_fc->queue_max, next_fc->queue_n);
3069 if (ack == prev_fc->last_ack_sent)
3071 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not needed\n");
3075 prev_fc->last_ack_sent = ack;
3076 send_ack (c, ack, fwd);
3081 * Modify the mesh message TID from global to local and send to client.
3083 * @param ch Channel on which to send the message.
3084 * @param msg Message to modify and send.
3085 * @param c Client to send to.
3086 * @param tid Tunnel ID to use (c can be both owner and client).
3089 channel_send_client_to_tid (struct MeshChannel *ch,
3090 const struct GNUNET_MESH_Data *msg,
3091 struct MeshClient *c, MESH_ChannelNumber id)
3093 struct GNUNET_MESH_LocalData *copy;
3094 uint16_t size = ntohs (msg->header.size) - sizeof (struct GNUNET_MESH_Data);
3095 char cbuf[size + sizeof (struct GNUNET_MESH_LocalData)];
3097 if (size < sizeof (struct GNUNET_MessageHeader))
3099 GNUNET_break_op (0);
3107 copy = (struct GNUNET_MESH_LocalData *) cbuf;
3108 memcpy (©[1], &msg[1], size);
3109 copy->header.size = htons (sizeof (struct GNUNET_MESH_LocalData) + size);
3110 copy->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA);
3111 copy->id = htonl (id);
3112 GNUNET_SERVER_notification_context_unicast (nc, c->handle,
3113 ©->header, GNUNET_NO);
3117 * Modify the data message ID from global to local and send to client.
3119 * @param ch Channel on which to send the message.
3120 * @param msg Message to modify and send.
3121 * @param fwd Forward?
3124 channel_send_client_data (struct MeshChannel *ch,
3125 const struct GNUNET_MESH_Data *msg,
3129 channel_send_client_to_tid (ch, msg, ch->dest, ch->lid_dest);
3131 channel_send_client_to_tid (ch, msg, ch->root, ch->lid_root);
3136 * Send a buffered message to the client, for in order delivery or
3137 * as result of client ACK.
3139 * @param ch Channel on which to empty the message buffer.
3140 * @param c Client to send to.
3141 * @param rel Reliability structure to corresponding peer.
3142 * If rel == bck_rel, this is FWD data.
3145 channel_send_client_buffered_data (struct MeshChannel *ch,
3146 struct MeshClient *c,
3147 struct MeshChannelReliability *rel)
3149 struct MeshReliableMessage *copy;
3152 if (GNUNET_NO == rel->client_ready)
3154 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client not ready\n");
3158 mid = rel == ch->bck_rel ? &ch->mid_recv_fwd : &ch->mid_recv_bck;
3160 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data\n");
3161 copy = rel->head_recv;
3164 if (copy->mid == *mid || GNUNET_NO == ch->reliable)
3166 struct GNUNET_MESH_Data *msg = (struct GNUNET_MESH_Data *) ©[1];
3168 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3169 " have %u! now expecting %u\n",
3170 copy->mid, *mid + 1);
3171 channel_send_client_data (ch, msg, (rel == ch->bck_rel));
3174 GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
3179 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3180 " reliable && don't have %u, next is %u\n",
3186 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data END\n");
3191 * We have received a message out of order, or the client is not ready.
3192 * Buffer it until we receive an ACK from the client or the missing
3193 * message from the channel.
3195 * @param msg Message to buffer.
3196 * @param rel Reliability data to the corresponding direction.
3199 channel_rel_add_buffered_data (const struct GNUNET_MESH_Data *msg,
3200 struct MeshChannelReliability *rel)
3202 struct MeshReliableMessage *copy;
3203 struct MeshReliableMessage *prev;
3207 size = ntohs (msg->header.size);
3208 mid = ntohl (msg->mid);
3209 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data %u\n", mid);
3211 copy = GNUNET_malloc (sizeof (*copy) + size);
3214 memcpy (©[1], msg, size);
3218 // FIXME do something better than O(n), although n < 64...
3219 // FIXME start from the end (most messages are the latest ones)
3220 for (prev = rel->head_recv; NULL != prev; prev = prev->next)
3222 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " prev %u\n", prev->mid);
3223 if (GMC_is_pid_bigger (prev->mid, mid))
3225 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " bingo!\n");
3226 GNUNET_CONTAINER_DLL_insert_before (rel->head_recv, rel->tail_recv,
3231 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " insert at tail!\n");
3232 GNUNET_CONTAINER_DLL_insert_tail (rel->head_recv, rel->tail_recv, copy);
3233 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data END\n");
3238 * Destroy a reliable message after it has been acknowledged, either by
3239 * direct mid ACK or bitfield. Updates the appropriate data structures and
3240 * timers and frees all memory.
3242 * @param copy Message that is no longer needed: remote peer got it.
3245 rel_message_free (struct MeshReliableMessage *copy)
3247 struct MeshChannelReliability *rel;
3248 struct GNUNET_TIME_Relative time;
3251 time = GNUNET_TIME_absolute_get_duration (copy->timestamp);
3252 rel->expected_delay.rel_value_us *= 7;
3253 rel->expected_delay.rel_value_us += time.rel_value_us;
3254 rel->expected_delay.rel_value_us /= 8;
3256 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Freeing %u\n", copy->mid);
3257 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " n_sent %u\n", rel->n_sent);
3258 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! took %s\n",
3259 GNUNET_STRINGS_relative_time_to_string (time, GNUNET_NO));
3260 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! new expected delay %s\n",
3261 GNUNET_STRINGS_relative_time_to_string (rel->expected_delay,
3263 rel->retry_timer = rel->expected_delay;
3264 GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
3270 * Destroy all reliable messages queued for a channel,
3271 * during a channel destruction.
3272 * Frees the reliability structure itself.
3274 * @param rel Reliability data for a channel.
3277 channel_rel_free_all (struct MeshChannelReliability *rel)
3279 struct MeshReliableMessage *copy;
3280 struct MeshReliableMessage *next;
3285 for (copy = rel->head_recv; NULL != copy; copy = next)
3288 GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
3291 for (copy = rel->head_sent; NULL != copy; copy = next)
3294 GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
3297 if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
3298 GNUNET_SCHEDULER_cancel (rel->retry_task);
3304 * Mark future messages as ACK'd.
3306 * @param rel Reliability data.
3307 * @param msg DataACK message with a bitfield of future ACK'd messages.
3310 channel_rel_free_sent (struct MeshChannelReliability *rel,
3311 const struct GNUNET_MESH_DataACK *msg)
3313 struct MeshReliableMessage *copy;
3314 struct MeshReliableMessage *next;
3321 bitfield = msg->futures;
3322 mid = ntohl (msg->mid);
3323 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3324 "free_sent_reliable %u %llX\n",
3326 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3327 " rel %p, head %p\n",
3328 rel, rel->head_sent);
3329 for (i = 0, copy = rel->head_sent;
3330 i < 64 && NULL != copy && 0 != bitfield;
3333 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3334 " trying bit %u (mid %u)\n",
3337 if (0 == (bitfield & mask))
3340 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " set!\n");
3341 /* Bit was set, clear the bit from the bitfield */
3344 /* The i-th bit was set. Do we have that copy? */
3345 /* Skip copies with mid < target */
3346 target = mid + i + 1;
3347 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " target %u\n", target);
3348 while (NULL != copy && GMC_is_pid_bigger (target, copy->mid))
3351 /* Did we run out of copies? (previously freed, it's ok) */
3354 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "run out of copies...\n");
3358 /* Did we overshoot the target? (previously freed, it's ok) */
3359 if (GMC_is_pid_bigger (copy->mid, target))
3361 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " next copy %u\n", copy->mid);
3365 /* Now copy->mid == target, free it */
3367 rel_message_free (copy);
3370 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "free_sent_reliable END\n");
3375 * We haven't received an ACK after a certain time: restransmit the message.
3377 * @param cls Closure (MeshReliableMessage with the message to restransmit)
3378 * @param tc TaskContext.
3381 channel_retransmit_message (void *cls,
3382 const struct GNUNET_SCHEDULER_TaskContext *tc)
3384 struct MeshChannelReliability *rel = cls;
3385 struct MeshReliableMessage *copy;
3386 struct MeshPeerQueue *q;
3387 struct MeshChannel *ch;
3388 struct MeshConnection *c;
3389 struct GNUNET_MESH_Data *payload;
3390 struct MeshPeer *hop;
3393 rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
3394 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3398 copy = rel->head_sent;
3405 /* Search the message to be retransmitted in the outgoing queue.
3406 * Check only the queue for the connection that is going to be used,
3407 * if the message is stuck in some other connection's queue we shouldn't
3409 * - cancelling it and sending the new one doesn't guarantee it's delivery,
3410 * the old connection could be temporary stalled or the queue happened to
3411 * be long at time of insertion.
3412 * - not sending the new one could cause terrible delays the old connection
3415 payload = (struct GNUNET_MESH_Data *) ©[1];
3416 fwd = (rel == ch->fwd_rel);
3417 c = tunnel_get_connection (ch->t, fwd);
3418 hop = connection_get_hop (c, fwd);
3419 for (q = hop->queue_head; NULL != q; q = q->next)
3421 if (ntohs (payload->header.type) == q->type && ch == q->ch)
3423 struct GNUNET_MESH_Data *queued_data = q->cls;
3425 if (queued_data->mid == payload->mid)
3430 /* Message not found in the queue that we are going to use. */
3433 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! RETRANSMIT %u\n", copy->mid);
3435 send_prebuilt_message_channel (&payload->header, ch, ch->fwd_rel == rel);
3436 GNUNET_STATISTICS_update (stats, "# data retransmitted", 1, GNUNET_NO);
3440 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! ALREADY IN QUEUE %u\n", copy->mid);
3443 rel->retry_timer = GNUNET_TIME_STD_BACKOFF (rel->retry_timer);
3444 rel->retry_task = GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
3445 &channel_retransmit_message,
3452 * Send ACK on one or more connections due to buffer space to the client.
3455 channel_send_ack (struct MeshChannel *ch, uint32_t buffer, int fwd)
3457 struct MeshTunnel2 *t = ch->t;
3458 struct MeshConnection *c;
3459 struct MeshFlowControl *fc;
3464 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3465 "Channel send %s ack on %s:%X\n",
3466 fwd ? "FWD" : "BCK", GNUNET_h2s (&ch->t->id), ch->gid);
3468 /* Count connections, how many messages are already allowed */
3469 for (cs = 0, allowed = 0, c = t->connection_head; NULL != c; c = c->next)
3471 fc = fwd ? &c->fwd_fc : &c->bck_fc;
3472 if (GMC_is_pid_bigger(fc->last_pid_recv, fc->last_ack_sent))
3477 allowed += fc->last_ack_sent - fc->last_pid_recv;
3481 /* Make sure there is no overflow */
3482 if (allowed > buffer)
3488 /* Authorize connections to send more data */
3489 to_allow = buffer - allowed;
3490 for (c = t->connection_head; NULL != c && to_allow > 0; c = c->next)
3492 fc = fwd ? &c->fwd_fc : &c->bck_fc;
3493 if (fc->last_ack_sent - fc->last_pid_recv > 64 / 3)
3497 send_ack (c, fc->last_ack_sent + 1, fwd);
3501 GNUNET_break (to_allow == 0);
3506 * Send keepalive packets for a connection.
3508 * @param c Connection to keep alive..
3509 * @param fwd Is this a FWD keepalive? (owner -> dest).
3512 connection_keepalive (struct MeshConnection *c, int fwd)
3514 struct GNUNET_MESH_ConnectionKeepAlive *msg;
3515 size_t size = sizeof (struct GNUNET_MESH_ConnectionKeepAlive);
3519 type = fwd ? GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE :
3520 GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE;
3522 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3523 "sending %s keepalive for connection %s[%d]\n",
3524 fwd ? "FWD" : "BCK",
3525 peer2s (c->t->peer),
3528 msg = (struct GNUNET_MESH_ConnectionKeepAlive *) cbuf;
3529 msg->header.size = htons (size);
3530 msg->header.type = htons (type);
3531 msg->cid = htonl (c->id);
3532 msg->tid = c->t->id;
3534 send_prebuilt_message_connection (&msg->header, c, NULL, fwd);
3539 * Send CONNECTION_{CREATE/ACK} packets for a connection.
3541 * @param c Connection for which to send the message.
3542 * @param fwd If GNUNET_YES, send CREATE, otherwise send ACK.
3545 connection_recreate (struct MeshConnection *c, int fwd)
3547 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "sending connection recreate\n");
3549 send_connection_create (c);
3551 send_connection_ack (c);
3556 * Generic connection timer management.
3557 * Depending on the role of the peer in the connection will send the
3558 * appropriate message (build or keepalive)
3560 * @param c Conncetion to maintain.
3561 * @param fwd Is FWD?
3564 connection_maintain (struct MeshConnection *c, int fwd)
3566 if (MESH_TUNNEL_SEARCHING == c->t->state)
3568 /* TODO DHT GET with RO_BART */
3573 case MESH_CONNECTION_NEW:
3575 case MESH_CONNECTION_SENT:
3576 connection_recreate (c, fwd);
3578 case MESH_CONNECTION_READY:
3579 connection_keepalive (c, fwd);
3588 connection_fwd_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3590 struct MeshConnection *c = cls;
3592 c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
3593 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3596 connection_maintain (c, GNUNET_YES);
3597 c->fwd_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
3598 &connection_fwd_keepalive,
3604 connection_bck_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3606 struct MeshConnection *c = cls;
3608 c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
3609 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3612 connection_maintain (c, GNUNET_NO);
3613 c->bck_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
3614 &connection_bck_keepalive,
3620 * Send a message to all peers in this connection that the connection
3621 * is no longer valid.
3623 * If some peer should not receive the message, it should be zero'ed out
3624 * before calling this function.
3626 * @param c The connection whose peers to notify.
3629 connection_send_destroy (struct MeshConnection *c)
3631 struct GNUNET_MESH_ConnectionDestroy msg;
3633 msg.header.size = htons (sizeof (msg));
3634 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);;
3635 msg.cid = htonl (c->id);
3637 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3638 " sending connection destroy for connection %s[%X]\n",
3639 peer2s (c->t->peer),
3642 send_prebuilt_message_connection (&msg.header, c, NULL, GNUNET_YES);
3643 send_prebuilt_message_connection (&msg.header, c, NULL, GNUNET_NO);
3644 c->destroy = GNUNET_YES;
3649 * Send a message to all clients (local and remote) of this channel
3650 * notifying that the channel is no longer valid.
3652 * If some peer or client should not receive the message,
3653 * should be zero'ed out before calling this function.
3655 * @param ch The channel whose clients to notify.
3658 channel_send_destroy (struct MeshChannel *ch)
3660 struct GNUNET_MESH_ChannelDestroy msg;
3662 msg.header.size = htons (sizeof (msg));
3663 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY);
3664 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3665 " sending channel destroy for channel %s:%X\n",
3666 peer2s (ch->t->peer),
3669 if (NULL != ch->root)
3671 msg.chid = htonl (ch->lid_root);
3672 send_local_channel_destroy (ch, GNUNET_NO);
3676 msg.chid = htonl (ch->gid);
3677 send_prebuilt_message_channel (&msg.header, ch, GNUNET_NO);
3680 if (NULL != ch->dest)
3682 msg.chid = htonl (ch->lid_dest);
3683 send_local_channel_destroy (ch, GNUNET_YES);
3687 msg.chid = htonl (ch->gid);
3688 send_prebuilt_message_channel (&msg.header, ch, GNUNET_YES);
3696 * @param tid Tunnel ID.
3698 static struct MeshTunnel2 *
3699 tunnel_new (const struct GNUNET_HashCode *tid)
3701 struct MeshTunnel2 *t;
3703 t = GNUNET_new (struct MeshTunnel2);
3707 GNUNET_CONTAINER_multihashmap_put (tunnels, tid, t,
3708 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3722 * @param tid Tunnel ID.
3724 static struct MeshTunnel2 *
3725 tunnel_get (const struct GNUNET_HashCode *tid)
3727 return GNUNET_CONTAINER_multihashmap_get (tunnels, tid);
3732 * Add a connection to a tunnel.
3735 * @param c Connection.
3738 tunnel_add_connection (struct MeshTunnel2 *t, struct MeshConnection *c)
3741 GNUNET_CONTAINER_DLL_insert_tail (t->connection_head, t->connection_tail, c);
3746 * Initialize a Flow Control structure to the initial state.
3748 * @param fc Flow Control structure to initialize.
3751 fc_init (struct MeshFlowControl *fc)
3753 fc->last_pid_sent = (uint32_t) -1; /* Next (expected) = 0 */
3754 fc->last_pid_recv = (uint32_t) -1;
3755 fc->last_ack_sent = (uint32_t) 0;
3756 fc->last_ack_recv = (uint32_t) 0;
3757 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
3758 fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
3760 fc->queue_max = (max_msgs_queue / max_connections) + 1;
3764 static struct MeshConnection *
3765 connection_new (struct GNUNET_HashCode *tid, uint32_t cid)
3767 struct MeshConnection *c;
3768 struct MeshTunnel2 *t;
3770 t = tunnel_get (tid);
3773 t = tunnel_new (tid);
3781 c = GNUNET_new (struct MeshConnection);
3783 fc_init (&c->fwd_fc);
3784 fc_init (&c->bck_fc);
3787 tunnel_add_connection (t, c);
3794 * Find a connection.
3796 * @param tid Tunnel ID.
3797 * @param cid Connection ID.
3799 static struct MeshConnection *
3800 connection_get (const struct GNUNET_HashCode *tid, uint32_t cid)
3802 struct MeshConnection *c;
3803 struct MeshTunnel2 *t;
3805 t = tunnel_get (tid);
3808 for (c = t->connection_head; NULL != c; c = c->next)
3817 connection_destroy (struct MeshConnection *c)
3822 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying connection %s[%X]\n",
3823 peer2s (c->t->peer),
3826 connection_cancel_queues (c, GNUNET_YES);
3827 connection_cancel_queues (c, GNUNET_NO);
3829 if (GNUNET_SCHEDULER_NO_TASK != c->fwd_maintenance_task)
3830 GNUNET_SCHEDULER_cancel (c->fwd_maintenance_task);
3831 if (GNUNET_SCHEDULER_NO_TASK != c->bck_maintenance_task)
3832 GNUNET_SCHEDULER_cancel (c->bck_maintenance_task);
3834 GNUNET_CONTAINER_DLL_remove (c->t->connection_head, c->t->connection_tail, c);
3836 GNUNET_STATISTICS_update (stats, "# connections", -1, GNUNET_NO);
3842 tunnel_destroy (struct MeshTunnel2 *t)
3844 struct MeshConnection *c;
3845 struct MeshConnection *next;
3850 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n",
3853 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &t->id, t))
3856 for (c = t->connection_head; NULL != c; c = next)
3859 connection_destroy (c);
3862 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
3869 * Tunnel is empty: destroy it.
3871 * Notifies all connections about the destruction.
3873 * @param t Tunnel to destroy.
3876 tunnel_destroy_empty (struct MeshTunnel2 *t)
3878 struct MeshConnection *c;
3880 for (c = t->connection_head; NULL != c; c = c->next)
3882 if (GNUNET_NO == c->destroy)
3883 connection_send_destroy (c);
3886 if (0 == t->pending_messages)
3889 t->destroy = GNUNET_YES;
3894 * Destroy tunnel if empty (no more channels).
3896 * @param t Tunnel to destroy if empty.
3899 tunnel_destroy_if_empty (struct MeshTunnel2 *t)
3901 if (NULL != t->channel_head)
3904 tunnel_destroy_empty (t);
3909 * Destroy a channel and free all resources.
3911 * @param ch Channel to destroy.
3914 channel_destroy (struct MeshChannel *ch)
3916 struct MeshClient *c;
3924 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap32_remove (c->own_channels,
3935 GNUNET_CONTAINER_multihashmap32_remove (c->incoming_channels,
3942 if (GNUNET_YES == ch->reliable)
3944 channel_rel_free_all (ch->fwd_rel);
3945 channel_rel_free_all (ch->bck_rel);
3948 GNUNET_CONTAINER_DLL_remove (ch->t->channel_head, ch->t->channel_tail, ch);
3949 GNUNET_STATISTICS_update (stats, "# channels", -1, GNUNET_NO);
3955 * Create a new channel.
3957 * @param t Tunnel this channel is in.
3958 * @param owner Client that owns the channel, NULL for foreign channels.
3959 * @param lid_root Local ID for root client.
3961 * @return A new initialized channel. NULL on error.
3963 static struct MeshChannel *
3964 channel_new (struct MeshTunnel2 *t,
3965 struct MeshClient *owner, MESH_ChannelNumber lid_root)
3967 struct MeshChannel *ch;
3969 ch = GNUNET_new (struct MeshChannel);
3971 ch->lid_root = lid_root;
3974 GNUNET_CONTAINER_DLL_insert (t->channel_head, t->channel_tail, ch);
3976 GNUNET_STATISTICS_update (stats, "# channels", 1, GNUNET_NO);
3980 while (NULL != channel_get (t, t->next_chid))
3981 t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
3982 ch->gid = t->next_chid;
3983 t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
3986 GNUNET_CONTAINER_multihashmap32_put (owner->own_channels, lid_root, ch,
3987 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
3990 channel_destroy (ch);
3991 GNUNET_SERVER_receive_done (owner->handle, GNUNET_SYSERR);
4001 * Set options in a channel, extracted from a bit flag field
4003 * @param ch Channel to set options to.
4004 * @param options Bit array in host byte order.
4007 channel_set_options (struct MeshChannel *ch, uint32_t options)
4009 ch->nobuffer = (options & GNUNET_MESH_OPTION_NOBUFFER) != 0 ?
4010 GNUNET_YES : GNUNET_NO;
4011 ch->reliable = (options & GNUNET_MESH_OPTION_RELIABLE) != 0 ?
4012 GNUNET_YES : GNUNET_NO;
4017 * Iterator for deleting each channel whose client endpoint disconnected.
4019 * @param cls Closure (client that has disconnected).
4020 * @param key The local channel id (used to access the hashmap).
4021 * @param value The value stored at the key (channel to destroy).
4023 * @return GNUNET_OK, keep iterating.
4026 channel_destroy_iterator (void *cls,
4030 struct MeshChannel *ch = value;
4031 struct MeshClient *c = cls;
4032 struct MeshTunnel2 *t;
4034 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4035 " Channel %X (%X / %X) destroy, due to client %u shutdown.\n",
4036 ch->gid, ch->lid_root, ch->lid_dest, c->id);
4040 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is destination.\n", c->id);
4045 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is owner.\n", c->id);
4050 channel_send_destroy (ch);
4051 channel_destroy (ch);
4052 tunnel_destroy_if_empty (t);
4059 * Remove client's ports from the global hashmap on disconnect.
4061 * @param cls Closure (unused).
4063 * @param value Client structure.
4065 * @return GNUNET_OK, keep iterating.
4068 client_release_ports (void *cls,
4074 res = GNUNET_CONTAINER_multihashmap32_remove (ports, key, value);
4075 if (GNUNET_YES != res)
4078 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4079 "Port %u by client %p was not registered.\n",
4087 * Timeout function due to lack of keepalive/traffic from the owner.
4088 * Destroys connection if called.
4090 * @param cls Closure (connection to destroy).
4091 * @param tc TaskContext.
4094 connection_fwd_timeout (void *cls,
4095 const struct GNUNET_SCHEDULER_TaskContext *tc)
4097 struct MeshConnection *c = cls;
4099 c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4100 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4102 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4103 "Connection %s[%X] FWD timed out. Destroying.\n",
4104 peer2s (c->t->peer),
4107 if (connection_is_terminal (c, GNUNET_NO)) /* If local, leave. */
4110 connection_destroy (c);
4115 * Timeout function due to lack of keepalive/traffic from the destination.
4116 * Destroys connection if called.
4118 * @param cls Closure (connection to destroy).
4119 * @param tc TaskContext
4122 connection_bck_timeout (void *cls,
4123 const struct GNUNET_SCHEDULER_TaskContext *tc)
4125 struct MeshConnection *c = cls;
4127 c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4128 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4131 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4132 "Connection %s[%X] FWD timed out. Destroying.\n",
4133 peer2s (c->t->peer),
4136 if (connection_is_terminal (c, GNUNET_YES)) /* If local, leave. */
4139 connection_destroy (c);
4144 * Resets the connection timeout task, some other message has done the
4146 * - For the first peer on the direction this means to send
4147 * a keepalive or a path confirmation message (either create or ACK).
4148 * - For all other peers, this means to destroy the connection,
4149 * due to lack of activity.
4150 * Starts the tiemout if no timeout was running (connection just created).
4152 * @param c Connection whose timeout to reset.
4153 * @param fwd Is this forward?
4155 * TODO use heap to improve efficiency of scheduler.
4158 connection_reset_timeout (struct MeshConnection *c, int fwd)
4160 GNUNET_SCHEDULER_TaskIdentifier *ti;
4161 GNUNET_SCHEDULER_Task f;
4163 ti = fwd ? &c->fwd_maintenance_task : &c->bck_maintenance_task;
4165 if (GNUNET_SCHEDULER_NO_TASK != *ti)
4166 GNUNET_SCHEDULER_cancel (*ti);
4168 if (connection_is_terminal (c, !fwd)) /* Endpoint */
4170 f = fwd ? &connection_fwd_keepalive : &connection_bck_keepalive;
4171 *ti = GNUNET_SCHEDULER_add_delayed (refresh_connection_time, f, c);
4175 struct GNUNET_TIME_Relative delay;
4177 delay = GNUNET_TIME_relative_multiply (refresh_connection_time, 4);
4178 f = fwd ? &connection_fwd_timeout : &connection_bck_timeout;
4179 *ti = GNUNET_SCHEDULER_add_delayed (delay, f, c);
4185 * Iterator to notify all connections of a broken link. Mark connections
4186 * to destroy after all traffic has been sent.
4188 * @param cls Closure (peer disconnected).
4189 * @param key Current key code (tid).
4190 * @param value Value in the hash map (connection).
4192 * @return GNUNET_YES if we should continue to iterate,
4196 connection_broken (void *cls,
4197 const struct GNUNET_HashCode *key,
4200 struct MeshPeer *peer = cls;
4201 struct MeshConnection *c = value;
4202 struct GNUNET_MESH_ConnectionBroken msg;
4205 fwd = peer == connection_get_prev_hop (c);
4206 connection_cancel_queues (c, !fwd);
4208 msg.header.size = htons (sizeof (struct GNUNET_MESH_ConnectionBroken));
4209 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN);
4210 msg.cid = htonl (c->id);
4212 msg.peer1 = my_full_id;
4213 msg.peer2 = *GNUNET_PEER_resolve2 (peer->id);
4214 send_prebuilt_message_connection (&msg.header, c, NULL, fwd);
4215 c->destroy = GNUNET_YES;
4220 /******************************************************************************/
4221 /**************** MESH NETWORK HANDLER HELPERS ***********************/
4222 /******************************************************************************/
4225 * Free a transmission that was already queued with all resources
4226 * associated to the request.
4228 * @param queue Queue handler to cancel.
4229 * @param clear_cls Is it necessary to free associated cls?
4232 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
4234 struct MeshPeer *peer;
4235 struct MeshFlowControl *fc;
4240 fc = fwd ? &queue->c->fwd_fc : &queue->c->bck_fc;
4242 if (GNUNET_YES == clear_cls)
4244 switch (queue->type)
4246 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
4247 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "destroying CONNECTION_DESTROY\n");
4248 GNUNET_break (GNUNET_YES == queue->c->destroy);
4250 case GNUNET_MESSAGE_TYPE_MESH_FWD:
4251 case GNUNET_MESSAGE_TYPE_MESH_BCK:
4252 case GNUNET_MESSAGE_TYPE_MESH_ACK:
4253 case GNUNET_MESSAGE_TYPE_MESH_POLL:
4254 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
4255 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " prebuilt message\n");
4256 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type %s\n",
4257 GNUNET_MESH_DEBUG_M2S (queue->type));
4260 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
4261 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type create path\n");
4266 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, " type %s unknown!\n",
4267 GNUNET_MESH_DEBUG_M2S (queue->type));
4269 GNUNET_free_non_null (queue->cls);
4271 GNUNET_CONTAINER_DLL_remove (peer->queue_head, peer->queue_tail, queue);
4275 if (NULL != queue->c)
4277 queue->c->pending_messages--;
4278 if (NULL != queue->c->t)
4280 queue->c->t->pending_messages--;
4284 GNUNET_free (queue);
4289 queue_send (void *cls, size_t size, void *buf)
4291 struct MeshPeer *peer = cls;
4292 struct MeshFlowControl *fc;
4293 struct MeshConnection *c;
4294 struct GNUNET_MessageHeader *msg;
4295 struct MeshPeerQueue *queue;
4296 struct MeshTunnel2 *t;
4297 const struct GNUNET_PeerIdentity *dst_id;
4303 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Queue send\n");
4305 if (NULL == buf || 0 == size)
4307 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Buffer size 0.\n");
4312 queue = peer_get_first_message (peer);
4315 GNUNET_break (0); /* Core tmt_rdy should've been canceled */
4318 queue->peer->core_transmit = NULL;
4321 fc = fwd ? &c->fwd_fc : &c->bck_fc;
4324 dst_id = GNUNET_PEER_resolve2 (peer->id);
4325 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* towards %s\n", GNUNET_i2s (dst_id));
4326 /* Check if buffer size is enough for the message */
4327 if (queue->size > size)
4329 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* not enough room, reissue\n");
4330 peer->core_transmit =
4331 GNUNET_CORE_notify_transmit_ready (core_handle,
4334 GNUNET_TIME_UNIT_FOREVER_REL,
4341 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* size ok\n");
4343 t = (NULL != c) ? c->t : NULL;
4347 switch (queue->type)
4349 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
4350 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
4351 case GNUNET_MESSAGE_TYPE_MESH_FWD:
4352 case GNUNET_MESSAGE_TYPE_MESH_BCK:
4353 case GNUNET_MESSAGE_TYPE_MESH_ACK:
4354 case GNUNET_MESSAGE_TYPE_MESH_POLL:
4355 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4357 GNUNET_MESH_DEBUG_M2S (queue->type));
4359 case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4360 case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4361 data_size = send_core_data_raw (queue->cls, size, buf);
4362 msg = (struct GNUNET_MessageHeader *) buf;
4363 type = ntohs (msg->type);
4365 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
4366 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* path create\n");
4367 if (connection_is_terminal (c, GNUNET_NO))
4368 data_size = send_core_connection_create (queue->cls, size, buf);
4370 data_size = send_core_data_raw (queue->cls, size, buf);
4372 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
4373 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* path ack\n");
4374 if (connection_is_terminal (c, GNUNET_YES))
4375 data_size = send_core_connection_ack (queue->cls, size, buf);
4377 data_size = send_core_data_raw (queue->cls, size, buf);
4381 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "* type unknown: %u\n",
4386 if (0 < drop_percent &&
4387 GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 101) < drop_percent)
4389 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4390 "Dropping message of type %s\n",
4391 GNUNET_MESH_DEBUG_M2S (queue->type));
4394 /* Free queue, but cls was freed by send_core_* */
4395 queue_destroy (queue, GNUNET_NO);
4397 /* Send ACK if needed, after accounting for sent ID in fc->queue_n */
4400 case GNUNET_MESSAGE_TYPE_MESH_FWD:
4401 case GNUNET_MESSAGE_TYPE_MESH_BCK:
4402 pid = ntohl ( ((struct GNUNET_MESH_Encrypted *) buf)->pid );
4403 fc->last_pid_sent = pid;
4404 connection_send_ack (c, fwd);
4410 /* If more data in queue, send next */
4411 queue = peer_get_first_message (peer);
4414 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* more data!\n");
4415 if (NULL == peer->core_transmit) {
4416 peer->core_transmit =
4417 GNUNET_CORE_notify_transmit_ready(core_handle,
4420 GNUNET_TIME_UNIT_FOREVER_REL,
4428 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4429 "* tmt rdy called somewhere else\n");
4431 if (GNUNET_SCHEDULER_NO_TASK == fc->poll_task)
4433 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "* %s starting poll timeout\n");
4435 GNUNET_SCHEDULER_add_delayed (fc->poll_time, &connection_poll, fc);
4440 if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
4442 GNUNET_SCHEDULER_cancel (fc->poll_task);
4443 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
4448 c->pending_messages--;
4449 if (GNUNET_YES == c->destroy && 0 == c->pending_messages)
4451 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* destroying connection!\n");
4452 connection_destroy (c);
4458 t->pending_messages--;
4459 if (GNUNET_YES == t->destroy && 0 == t->pending_messages)
4461 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* destroying tunnel!\n");
4465 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Return %d\n", data_size);
4471 queue_add (void *cls, uint16_t type, size_t size,
4472 struct MeshPeer *dst,
4473 struct MeshConnection *c,
4474 struct MeshChannel *ch)
4476 struct MeshPeerQueue *queue;
4477 struct MeshFlowControl *fc;
4481 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4482 "queue add %s (%u bytes) on c %p, ch %p\n",
4483 GNUNET_MESH_DEBUG_M2S (type), size, c, ch);
4485 fwd = (dst == connection_get_next_hop (c));
4486 fc = fwd ? &c->fwd_fc : &c->bck_fc;
4496 if (GNUNET_MESSAGE_TYPE_MESH_POLL == type ||
4497 GNUNET_MESSAGE_TYPE_MESH_ACK == type)
4501 ( (NULL != ch->root && GNUNET_MESSAGE_TYPE_MESH_FWD == type) ||
4502 (NULL != ch->dest && GNUNET_MESSAGE_TYPE_MESH_BCK == type) ))
4505 if (fc->queue_n >= fc->queue_max && 0 == priority)
4507 GNUNET_STATISTICS_update (stats, "# messages dropped (buffer full)",
4510 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4511 "queue full: %u/%u\n",
4512 fc->queue_n, fc->queue_max);
4513 return; /* Drop this message */
4516 if (GMC_is_pid_bigger (fc->last_pid_sent + 1, fc->last_ack_recv) &&
4517 GNUNET_SCHEDULER_NO_TASK == fc->poll_task)
4518 fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
4521 queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
4529 if (100 <= priority)
4530 GNUNET_CONTAINER_DLL_insert (dst->queue_head, dst->queue_tail, queue);
4532 GNUNET_CONTAINER_DLL_insert_tail (dst->queue_head, dst->queue_tail, queue);
4534 if (NULL == dst->core_transmit)
4536 dst->core_transmit =
4537 GNUNET_CORE_notify_transmit_ready (core_handle,
4540 GNUNET_TIME_UNIT_FOREVER_REL,
4541 GNUNET_PEER_resolve2 (dst->id),
4546 c->pending_messages++;
4547 c->t->pending_messages++;
4553 /******************************************************************************/
4554 /******************** MESH NETWORK HANDLERS **************************/
4555 /******************************************************************************/
4559 * Generic handler for mesh network payload traffic.
4561 * @param t Tunnel on which we got this message.
4562 * @param message Unencryted data message.
4563 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
4565 * @return GNUNET_OK to keep the connection open,
4566 * GNUNET_SYSERR to close it (signal serious error)
4569 handle_data (struct MeshTunnel2 *t, const struct GNUNET_MESH_Data *msg, int fwd)
4571 struct MeshChannelReliability *rel;
4572 struct MeshChannel *ch;
4573 struct MeshClient *c;
4580 size = ntohs (msg->header.size);
4582 sizeof (struct GNUNET_MESH_Data) +
4583 sizeof (struct GNUNET_MessageHeader))
4588 type = ntohs (msg->header.type);
4589 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message\n",
4590 GNUNET_MESH_DEBUG_M2S (type));
4591 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
4592 GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
4595 ch = channel_get (t, ntohl (msg->chid));
4598 GNUNET_STATISTICS_update (stats, "# data on unknown channel", 1, GNUNET_NO);
4599 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel unknown\n");
4603 /* Initialize FWD/BCK data */
4604 c = fwd ? ch->dest : ch->root;
4605 rel = fwd ? ch->bck_rel : ch->fwd_rel;
4606 mid_recv = fwd ? &ch->mid_recv_fwd : &ch->mid_recv_bck;
4614 tunnel_change_state (t, MESH_TUNNEL_READY);
4616 GNUNET_STATISTICS_update (stats, "# data received", 1, GNUNET_NO);
4618 mid = ntohl (msg->mid);
4619 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " mid %u\n", mid);
4621 if (GNUNET_NO == ch->reliable ||
4622 ( !GMC_is_pid_bigger (*mid_recv, mid) &&
4623 GMC_is_pid_bigger (*mid_recv + 64, mid) ) )
4625 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! RECV %u\n", mid);
4626 if (GNUNET_YES == ch->reliable)
4628 /* Is this the exact next expected messasge? */
4629 if (mid == *mid_recv)
4631 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "as expected\n");
4632 *mid_recv = *mid_recv + 1;
4633 channel_send_client_data (ch, msg, fwd);
4634 channel_send_client_buffered_data (ch, c, rel);
4638 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "save for later\n");
4639 channel_rel_add_buffered_data (msg, rel);
4642 else /* Tunnel unreliable, send to clients directly */
4644 channel_send_client_data (ch, msg, fwd);
4649 GNUNET_break_op (0);
4650 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4651 " MID %u not expected (%u - %u), dropping!\n",
4652 mid, *mid_recv, *mid_recv + 64);
4655 channel_send_data_ack (ch, fwd);
4660 * Handler for mesh network traffic end-to-end ACKs.
4662 * @param t Tunnel on which we got this message.
4663 * @param message Data message.
4664 * @param fwd Is this a fwd ACK? (dest->orig)
4666 * @return GNUNET_OK to keep the connection open,
4667 * GNUNET_SYSERR to close it (signal serious error)
4670 handle_data_ack (struct MeshTunnel2 *t,
4671 const struct GNUNET_MESH_DataACK *msg, int fwd)
4673 struct MeshChannelReliability *rel;
4674 struct MeshReliableMessage *copy;
4675 struct MeshReliableMessage *next;
4676 struct MeshChannel *ch;
4681 type = ntohs (msg->header.type);
4682 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a %s message!\n",
4683 GNUNET_MESH_DEBUG_M2S (type));
4684 ch = channel_get (t, ntohl (msg->chid));
4687 GNUNET_STATISTICS_update (stats, "# ack on unknown channel", 1, GNUNET_NO);
4690 ack = ntohl (msg->mid);
4691 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! %s ACK %u\n",
4692 (GNUNET_YES == fwd) ? "FWD" : "BCK", ack);
4694 if (GNUNET_YES == fwd)
4707 for (work = GNUNET_NO, copy = rel->head_sent; copy != NULL; copy = next)
4709 if (GMC_is_pid_bigger (copy->mid, ack))
4711 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! head %u, out!\n", copy->mid);
4712 channel_rel_free_sent (rel, msg);
4716 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! id %u\n", copy->mid);
4718 rel_message_free (copy);
4720 /* ACK client if needed */
4721 // channel_send_ack (t, type, GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK == type);
4723 /* If some message was free'd, update the retransmission delay*/
4724 if (GNUNET_YES == work)
4726 if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
4728 GNUNET_SCHEDULER_cancel (rel->retry_task);
4729 if (NULL == rel->head_sent)
4731 rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
4735 struct GNUNET_TIME_Absolute new_target;
4736 struct GNUNET_TIME_Relative delay;
4738 delay = GNUNET_TIME_relative_multiply (rel->retry_timer,
4739 MESH_RETRANSMIT_MARGIN);
4740 new_target = GNUNET_TIME_absolute_add (rel->head_sent->timestamp,
4742 delay = GNUNET_TIME_absolute_get_remaining (new_target);
4744 GNUNET_SCHEDULER_add_delayed (delay,
4745 &channel_retransmit_message,
4757 * Core handler for connection creation.
4759 * @param cls Closure (unused).
4760 * @param peer Sender (neighbor).
4761 * @param message Message.
4763 * @return GNUNET_OK to keep the connection open,
4764 * GNUNET_SYSERR to close it (signal serious error)
4767 handle_mesh_connection_create (void *cls,
4768 const struct GNUNET_PeerIdentity *peer,
4769 const struct GNUNET_MessageHeader *message)
4771 struct GNUNET_MESH_ConnectionCreate *msg;
4772 struct GNUNET_PeerIdentity *id;
4773 struct GNUNET_HashCode *tid;
4774 struct MeshPeerPath *path;
4775 struct MeshPeer *dest_peer;
4776 struct MeshPeer *orig_peer;
4777 struct MeshConnection *c;
4778 unsigned int own_pos;
4783 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection create msg\n");
4786 size = ntohs (message->size);
4787 if (size < sizeof (struct GNUNET_MESH_ConnectionCreate))
4789 GNUNET_break_op (0);
4793 /* Calculate hops */
4794 size -= sizeof (struct GNUNET_MESH_ConnectionCreate);
4795 if (size % sizeof (struct GNUNET_PeerIdentity))
4797 GNUNET_break_op (0);
4800 size /= sizeof (struct GNUNET_PeerIdentity);
4803 GNUNET_break_op (0);
4806 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " path has %u hops.\n", size);
4808 /* Get parameters */
4809 msg = (struct GNUNET_MESH_ConnectionCreate *) message;
4810 cid = ntohl (msg->cid);
4812 id = (struct GNUNET_PeerIdentity *) &msg[1];
4813 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4814 " connection %s[%X] (%s).\n",
4815 GNUNET_h2s (tid), cid, GNUNET_i2s (id));
4817 /* Create connection */
4818 c = connection_get (tid, cid);
4821 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Creating connection\n");
4822 c = connection_new (tid, cid);
4826 connection_reset_timeout (c, GNUNET_YES);
4827 tunnel_change_state (c->t, MESH_TUNNEL_WAITING);
4829 /* Remember peers */
4830 dest_peer = peer_get (&id[size - 1]);
4831 orig_peer = peer_get (&id[0]);
4834 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Creating path...\n");
4835 path = path_new (size);
4837 for (i = 0; i < size; i++)
4839 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... adding %s\n",
4840 GNUNET_i2s (&id[i]));
4841 path->peers[i] = GNUNET_PEER_intern (&id[i]);
4842 if (path->peers[i] == myid)
4845 if (own_pos == 0 && path->peers[own_pos] != myid)
4847 /* create path: self not found in path through self */
4848 GNUNET_break_op (0);
4849 path_destroy (path);
4850 connection_destroy (c);
4853 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Own position: %u\n", own_pos);
4854 path_add_to_peers (path, GNUNET_NO);
4855 c->path = path_duplicate (path);
4856 c->own_pos = own_pos;
4858 /* Is it a connection to us? */
4859 if (own_pos == size - 1)
4861 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " It's for us!\n");
4862 peer_add_path_to_origin (orig_peer, path, GNUNET_YES);
4864 send_connection_ack (c);
4866 /* Keep tunnel alive in direction dest->owner*/
4867 connection_reset_timeout (c, GNUNET_NO);
4871 /* It's for somebody else! Retransmit. */
4872 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Retransmitting.\n");
4873 peer_add_path (dest_peer, path_duplicate (path), GNUNET_NO);
4874 peer_add_path_to_origin (orig_peer, path, GNUNET_NO);
4875 send_prebuilt_message_connection (message, c, NULL, GNUNET_YES);
4882 * Core handler for path ACKs
4884 * @param cls closure
4885 * @param message message
4886 * @param peer peer identity this notification is about
4888 * @return GNUNET_OK to keep the connection open,
4889 * GNUNET_SYSERR to close it (signal serious error)
4892 handle_mesh_connection_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
4893 const struct GNUNET_MessageHeader *message)
4895 struct GNUNET_MESH_ConnectionACK *msg;
4896 struct MeshPeerPath *p;
4897 struct MeshConnection *c;
4900 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection ACK msg\n");
4901 msg = (struct GNUNET_MESH_ConnectionACK *) message;
4902 cid = ntohl(msg->cid);
4903 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " on connection %s[%X]\n",
4904 GNUNET_h2s (&msg->tid), cid);
4905 c = connection_get (&msg->tid, cid);
4908 GNUNET_STATISTICS_update (stats, "# control on unknown connection",
4910 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " don't know the connection!\n");
4914 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " via peer %s\n",
4917 /* Add path to peers? */
4921 path_add_to_peers (p, GNUNET_YES);
4927 connection_change_state (c, MESH_CONNECTION_READY);
4928 connection_reset_timeout (c, GNUNET_NO);
4929 if (MESH_TUNNEL_READY != c->t->state)
4930 tunnel_change_state (c->t, MESH_TUNNEL_READY);
4931 tunnel_send_queued_data (c->t, GNUNET_YES);
4933 /* Message for us? */
4934 if (connection_is_terminal (c, GNUNET_NO))
4936 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " It's for us!\n");
4937 if (3 <= tunnel_count_connections (c->t) && NULL != c->t->peer->dhtget)
4939 GNUNET_DHT_get_stop (c->t->peer->dhtget);
4940 c->t->peer->dhtget = NULL;
4942 //connection_send_ack (c, GNUNET_NO); /* FIXME */
4946 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " not for us, retransmitting...\n");
4947 send_prebuilt_message_connection (message, c, NULL, GNUNET_NO);
4953 * Core handler for notifications of broken paths
4955 * @param cls Closure (unused).
4956 * @param peer Peer identity of sending neighbor.
4957 * @param message Message.
4959 * @return GNUNET_OK to keep the connection open,
4960 * GNUNET_SYSERR to close it (signal serious error)
4963 handle_mesh_connection_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
4964 const struct GNUNET_MessageHeader *message)
4966 struct GNUNET_MESH_ConnectionBroken *msg;
4967 struct MeshConnection *c;
4969 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4970 "Received a CONNECTION BROKEN msg from %s\n", GNUNET_i2s (peer));
4971 msg = (struct GNUNET_MESH_ConnectionBroken *) message;
4972 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " regarding %s\n",
4973 GNUNET_i2s (&msg->peer1));
4974 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " regarding %s\n",
4975 GNUNET_i2s (&msg->peer2));
4976 c = connection_get (&msg->tid, ntohl (msg->cid));
4979 GNUNET_break_op (0);
4982 tunnel_notify_connection_broken (c->t, GNUNET_PEER_search (&msg->peer1),
4983 GNUNET_PEER_search (&msg->peer2));
4990 * Core handler for tunnel destruction
4992 * @param cls Closure (unused).
4993 * @param peer Peer identity of sending neighbor.
4994 * @param message Message.
4996 * @return GNUNET_OK to keep the connection open,
4997 * GNUNET_SYSERR to close it (signal serious error)
5000 handle_mesh_connection_destroy (void *cls,
5001 const struct GNUNET_PeerIdentity *peer,
5002 const struct GNUNET_MessageHeader *message)
5004 struct GNUNET_MESH_ConnectionDestroy *msg;
5005 struct MeshConnection *c;
5009 msg = (struct GNUNET_MESH_ConnectionDestroy *) message;
5010 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5011 "Got a CONNECTION DESTROY message from %s\n",
5013 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5014 " for connection %s[%X]\n",
5015 GNUNET_h2s (&msg->tid), ntohl (msg->cid));
5016 c = connection_get (&msg->tid, ntohl (msg->cid));
5019 /* Probably already got the message from another path,
5020 * destroyed the tunnel and retransmitted to children.
5023 GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
5027 id = GNUNET_PEER_search (peer);
5028 if (id == connection_get_prev_hop (c)->id)
5030 else if (id == connection_get_next_hop (c)->id)
5034 GNUNET_break_op (0);
5037 send_prebuilt_message_connection (message, c, NULL, fwd);
5038 c->destroy = GNUNET_YES;
5044 * Handler for channel create messages.
5046 * @param t Tunnel this channel is to be created in.
5047 * @param msg Message.
5048 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5050 * @return GNUNET_OK to keep the connection open,
5051 * GNUNET_SYSERR to close it (signal serious error)
5054 handle_channel_create (struct MeshTunnel2 *t,
5055 struct GNUNET_MESH_ChannelCreate *msg,
5058 MESH_ChannelNumber chid;
5059 struct MeshChannel *ch;
5060 struct MeshClient *c;
5062 /* Check message size */
5063 if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelCreate))
5065 GNUNET_break_op (0);
5069 /* Check if channel exists */
5070 chid = ntohl (msg->chid);
5071 ch = channel_get (t, chid);
5074 /* Probably a retransmission, safe to ignore */
5078 /* Find a destination client */
5079 c = GNUNET_CONTAINER_multihashmap32_get (ports, msg->port);
5082 /* TODO send reject */
5086 /* Create channel */
5087 ch = channel_new (t, NULL, 0);
5088 channel_set_options (ch, ntohl (msg->opt));
5089 channel_add_client (ch, c);
5090 if (GNUNET_YES == ch->reliable)
5092 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
5093 ch->bck_rel = GNUNET_malloc (sizeof (struct MeshChannelReliability));
5094 ch->bck_rel->ch = ch;
5095 ch->bck_rel->expected_delay = MESH_RETRANSMIT_TIME;
5098 send_local_channel_create (ch);
5105 * Handler for channel destroy messages.
5107 * @param t Tunnel this channel is to be destroyed of.
5108 * @param msg Message.
5109 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5111 * @return GNUNET_OK to keep the connection open,
5112 * GNUNET_SYSERR to close it (signal serious error)
5115 handle_channel_destroy (struct MeshTunnel2 *t,
5116 struct GNUNET_MESH_ChannelDestroy *msg,
5119 MESH_ChannelNumber chid;
5120 struct MeshChannel *ch;
5122 /* Check message size */
5123 if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelDestroy))
5125 GNUNET_break_op (0);
5129 /* Check if channel exists */
5130 chid = ntohl (msg->chid);
5131 ch = channel_get (t, chid);
5134 /* Probably a retransmission, safe to ignore */
5138 send_local_channel_destroy (ch, fwd);
5139 channel_destroy (ch);
5146 * Generic handler for mesh network encrypted traffic.
5148 * @param peer Peer identity this notification is about.
5149 * @param message Encrypted message.
5150 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5152 * @return GNUNET_OK to keep the connection open,
5153 * GNUNET_SYSERR to close it (signal serious error)
5156 handle_mesh_encrypted (const struct GNUNET_PeerIdentity *peer,
5157 const struct GNUNET_MESH_Encrypted *msg,
5160 struct MeshConnection *c;
5161 struct MeshTunnel2 *t;
5162 struct MeshPeer *neighbor;
5163 struct MeshFlowControl *fc;
5170 size = ntohs (msg->header.size);
5172 sizeof (struct GNUNET_MESH_Encrypted) +
5173 sizeof (struct GNUNET_MessageHeader))
5178 type = ntohs (msg->header.type);
5179 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message from %s\n",
5180 GNUNET_MESH_DEBUG_M2S (type), GNUNET_i2s (peer));
5182 /* Check connection */
5183 c = connection_get (&msg->tid, ntohl (msg->cid));
5186 GNUNET_STATISTICS_update (stats, "# unknown connection", 1, GNUNET_NO);
5187 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING connection unknown\n");
5191 fc = fwd ? &c->fwd_fc : &c->bck_fc;
5193 /* Check if origin is as expected */
5194 neighbor = connection_get_hop (c, fwd);
5195 if (peer_get (peer)->id != neighbor->id)
5197 GNUNET_break_op (0);
5202 pid = ntohl (msg->pid);
5203 if (GMC_is_pid_bigger (pid, fc->last_ack_sent))
5205 GNUNET_STATISTICS_update (stats, "# unsolicited message", 1, GNUNET_NO);
5206 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5207 "WARNING Received PID %u, (prev %u), ACK %u\n",
5208 pid, fc->last_pid_recv, fc->last_ack_sent);
5211 if (GNUNET_NO == GMC_is_pid_bigger (pid, fc->last_pid_recv))
5213 GNUNET_STATISTICS_update (stats, "# duplicate PID", 1, GNUNET_NO);
5214 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5215 " Pid %u not expected (%u+), dropping!\n",
5216 pid, fc->last_pid_recv + 1);
5219 if (MESH_CONNECTION_SENT == c->state)
5220 connection_change_state (c, MESH_CONNECTION_READY);
5221 connection_reset_timeout (c, fwd);
5222 fc->last_pid_recv = pid;
5224 /* Is this message for us? */
5225 if (connection_is_terminal (c, fwd))
5227 size_t dsize = size - sizeof (struct GNUNET_MESH_Encrypted);
5229 struct GNUNET_MessageHeader *msgh;
5231 /* TODO signature verification */
5232 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " it's for us!\n");
5233 GNUNET_STATISTICS_update (stats, "# messages received", 1, GNUNET_NO);
5235 fc->last_pid_recv = pid;
5236 tunnel_decrypt (t, cbuf, &msg[1], dsize, msg->iv, fwd);
5237 msgh = (struct GNUNET_MessageHeader *) cbuf;
5238 switch (ntohs (msgh->type))
5240 case GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK:
5241 if (GNUNET_YES == fwd)
5242 return handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh,
5244 GNUNET_break_op (0);
5246 case GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK:
5247 if (GNUNET_NO == fwd)
5248 return handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh,
5250 GNUNET_break_op (0);
5252 case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
5253 if (GNUNET_YES == fwd)
5254 handle_data (t, (struct GNUNET_MESH_Data *) msgh, GNUNET_YES);
5255 GNUNET_break_op (0);
5257 case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
5258 if (GNUNET_NO == fwd)
5259 handle_data (t, (struct GNUNET_MESH_Data *) msgh, GNUNET_NO);
5260 GNUNET_break_op (0);
5262 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
5263 return handle_channel_create (t,
5264 (struct GNUNET_MESH_ChannelCreate *) msgh,
5267 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
5268 return handle_channel_destroy (t,
5269 (struct GNUNET_MESH_ChannelDestroy *)
5274 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5275 "end-to-end message not known (%u)\n",
5276 ntohs (msgh->type));
5279 connection_send_ack (c, fwd);
5283 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " not for us, retransmitting...\n");
5284 ttl = ntohl (msg->ttl);
5285 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ttl: %u\n", ttl);
5288 GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5289 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5290 connection_send_ack (c, fwd);
5293 GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
5295 send_prebuilt_message_connection (&msg->header, c, NULL, fwd);
5296 connection_send_ack (c, fwd);
5303 * Core handler for mesh network traffic going orig->dest.
5305 * @param cls Closure (unused).
5306 * @param message Message received.
5307 * @param peer Peer who sent the message.
5309 * @return GNUNET_OK to keep the connection open,
5310 * GNUNET_SYSERR to close it (signal serious error)
5313 handle_mesh_fwd (void *cls, const struct GNUNET_PeerIdentity *peer,
5314 const struct GNUNET_MessageHeader *message)
5316 return handle_mesh_encrypted (peer,
5317 (struct GNUNET_MESH_Encrypted *)message,
5322 * Core handler for mesh network traffic going dest->orig.
5324 * @param cls Closure (unused).
5325 * @param message Message received.
5326 * @param peer Peer who sent the message.
5328 * @return GNUNET_OK to keep the connection open,
5329 * GNUNET_SYSERR to close it (signal serious error)
5332 handle_mesh_bck (void *cls, const struct GNUNET_PeerIdentity *peer,
5333 const struct GNUNET_MessageHeader *message)
5335 return handle_mesh_encrypted (peer,
5336 (struct GNUNET_MESH_Encrypted *)message,
5342 * Core handler for mesh network traffic point-to-point acks.
5344 * @param cls closure
5345 * @param message message
5346 * @param peer peer identity this notification is about
5348 * @return GNUNET_OK to keep the connection open,
5349 * GNUNET_SYSERR to close it (signal serious error)
5352 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5353 const struct GNUNET_MessageHeader *message)
5355 struct GNUNET_MESH_ACK *msg;
5356 struct MeshConnection *c;
5357 struct MeshFlowControl *fc;
5361 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
5363 msg = (struct GNUNET_MESH_ACK *) message;
5365 c = connection_get (&msg->tid, ntohl (msg->cid));
5369 GNUNET_STATISTICS_update (stats, "# ack on unknown connection", 1,
5374 ack = ntohl (msg->ack);
5375 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", ack);
5377 /* Is this a forward or backward ACK? */
5378 id = GNUNET_PEER_search (peer);
5379 if (connection_get_next_hop (c)->id == id)
5381 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " FWD ACK\n");
5384 else if (connection_get_prev_hop (c)->id == id)
5386 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " BCK ACK\n");
5391 GNUNET_break_op (0);
5395 /* Cancel polling if the ACK is bigger than before. */
5396 if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task &&
5397 GMC_is_pid_bigger (ack, fc->last_ack_recv))
5399 GNUNET_SCHEDULER_cancel (fc->poll_task);
5400 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
5401 fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
5404 fc->last_ack_recv = ack;
5405 connection_unlock_queue (c, fc == &c->fwd_fc);
5412 * Core handler for mesh network traffic point-to-point ack polls.
5414 * @param cls closure
5415 * @param message message
5416 * @param peer peer identity this notification is about
5418 * @return GNUNET_OK to keep the connection open,
5419 * GNUNET_SYSERR to close it (signal serious error)
5422 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
5423 const struct GNUNET_MessageHeader *message)
5425 struct GNUNET_MESH_Poll *msg;
5426 struct MeshConnection *c;
5427 struct MeshFlowControl *fc;
5431 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a POLL packet from %s!\n",
5434 msg = (struct GNUNET_MESH_Poll *) message;
5436 c = connection_get (&msg->tid, ntohl (msg->cid));
5440 GNUNET_STATISTICS_update (stats, "# poll on unknown connection", 1,
5442 GNUNET_break_op (0);
5446 /* Is this a forward or backward ACK? */
5447 id = GNUNET_PEER_search (peer);
5448 if (connection_get_next_hop (c)->id == id)
5450 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " FWD ACK\n");
5453 else if (connection_get_prev_hop (c)->id == id)
5455 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " BCK ACK\n");
5460 GNUNET_break_op (0);
5464 pid = ntohl (msg->pid);
5465 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " PID %u, OLD %u\n",
5466 pid, fc->last_pid_recv);
5467 fc->last_pid_recv = pid;
5468 connection_send_ack (c, fc == &c->fwd_fc);
5475 * Core handler for mesh keepalives.
5477 * @param cls closure
5478 * @param message message
5479 * @param peer peer identity this notification is about
5480 * @return GNUNET_OK to keep the connection open,
5481 * GNUNET_SYSERR to close it (signal serious error)
5483 * TODO: Check who we got this from, to validate route.
5486 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
5487 const struct GNUNET_MessageHeader *message)
5489 struct GNUNET_MESH_ConnectionKeepAlive *msg;
5490 struct MeshConnection *c;
5491 struct MeshPeer *neighbor;
5494 msg = (struct GNUNET_MESH_ConnectionKeepAlive *) message;
5495 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
5498 c = connection_get (&msg->tid, ntohl (msg->cid));
5501 GNUNET_STATISTICS_update (stats, "# keepalive on unknown connection", 1,
5506 fwd = GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE == ntohs (message->type) ?
5507 GNUNET_YES : GNUNET_NO;
5509 /* Check if origin is as expected */
5510 neighbor = connection_get_hop (c, fwd);
5511 if (peer_get (peer)->id != neighbor->id)
5513 GNUNET_break_op (0);
5517 connection_change_state (c, MESH_CONNECTION_READY);
5518 connection_reset_timeout (c, fwd);
5520 if (connection_is_terminal (c, fwd))
5523 GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
5524 send_prebuilt_message_connection (message, c, NULL, fwd);
5532 * Functions to handle messages from core
5534 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
5535 {&handle_mesh_connection_create, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
5537 {&handle_mesh_connection_ack, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
5538 sizeof (struct GNUNET_MESH_ConnectionACK)},
5539 {&handle_mesh_connection_broken, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN,
5540 sizeof (struct GNUNET_MESH_ConnectionBroken)},
5541 {&handle_mesh_connection_destroy, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY,
5542 sizeof (struct GNUNET_MESH_ConnectionDestroy)},
5543 {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE,
5544 sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
5545 {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE,
5546 sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
5547 {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
5548 sizeof (struct GNUNET_MESH_ACK)},
5549 {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
5550 sizeof (struct GNUNET_MESH_Poll)},
5551 {&handle_mesh_fwd, GNUNET_MESSAGE_TYPE_MESH_FWD, 0},
5552 {&handle_mesh_bck, GNUNET_MESSAGE_TYPE_MESH_BCK, 0},
5558 * Function to process paths received for a new peer addition. The recorded
5559 * paths form the initial tunnel, which can be optimized later.
5560 * Called on each result obtained for the DHT search.
5562 * @param cls closure
5563 * @param exp when will this value expire
5564 * @param key key of the result
5565 * @param get_path path of the get request
5566 * @param get_path_length lenght of get_path
5567 * @param put_path path of the put request
5568 * @param put_path_length length of the put_path
5569 * @param type type of the result
5570 * @param size number of bytes in data
5571 * @param data pointer to the result data
5574 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5575 const struct GNUNET_HashCode * key,
5576 const struct GNUNET_PeerIdentity *get_path,
5577 unsigned int get_path_length,
5578 const struct GNUNET_PeerIdentity *put_path,
5579 unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5580 size_t size, const void *data)
5582 struct MeshPeer *peer = cls;
5583 struct MeshPeerPath *p;
5584 struct MeshConnection *c;
5585 struct GNUNET_PeerIdentity pi;
5588 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
5589 GNUNET_PEER_resolve (peer->id, &pi);
5590 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " for %s\n", GNUNET_i2s (&pi));
5592 p = path_build_from_dht (get_path, get_path_length,
5593 put_path, put_path_length);
5594 path_add_to_peers (p, GNUNET_NO);
5597 /* Count connections */
5598 for (c = peer->tunnel->connection_head, i = 0; NULL != c; c = c->next, i++);
5600 /* If we already have 3 (or more (?!)) connections, it's enough */
5604 if (peer->tunnel->state == MESH_TUNNEL_SEARCHING)
5606 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... connect!\n");
5607 peer_connect (peer);
5613 /******************************************************************************/
5614 /********************* MESH LOCAL HANDLES **************************/
5615 /******************************************************************************/
5619 * Handler for client connection.
5621 * @param cls Closure (unused).
5622 * @param client Client handler.
5625 handle_local_client_connect (void *cls, struct GNUNET_SERVER_Client *client)
5627 struct MeshClient *c;
5631 c = GNUNET_malloc (sizeof (struct MeshClient));
5633 c->id = next_client_id++; /* overflow not important: just for debug */
5634 GNUNET_SERVER_client_keep (client);
5635 GNUNET_SERVER_client_set_user_context (client, c);
5636 GNUNET_CONTAINER_DLL_insert (clients_head, clients_tail, c);
5641 * Handler for client disconnection
5643 * @param cls closure
5644 * @param client identification of the client; NULL
5645 * for the last call when the server is destroyed
5648 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
5650 struct MeshClient *c;
5651 struct MeshClient *next;
5653 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected: %p\n", client);
5656 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " (SERVER DOWN)\n");
5660 c = client_get (client);
5663 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u, %p)\n",
5665 GNUNET_SERVER_client_drop (c->handle);
5666 c->shutting_down = GNUNET_YES;
5667 if (NULL != c->own_channels)
5669 GNUNET_CONTAINER_multihashmap32_iterate (c->own_channels,
5670 &channel_destroy_iterator, c);
5671 GNUNET_CONTAINER_multihashmap32_destroy (c->own_channels);
5674 if (NULL != c->incoming_channels)
5676 GNUNET_CONTAINER_multihashmap32_iterate (c->incoming_channels,
5677 &channel_destroy_iterator, c);
5678 GNUNET_CONTAINER_multihashmap32_destroy (c->incoming_channels);
5681 if (NULL != c->ports)
5683 GNUNET_CONTAINER_multihashmap32_iterate (c->ports,
5684 &client_release_ports, c);
5685 GNUNET_CONTAINER_multihashmap32_destroy (c->ports);
5688 GNUNET_CONTAINER_DLL_remove (clients_head, clients_tail, c);
5689 GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
5690 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " client free (%p)\n", c);
5696 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " context NULL!\n");
5698 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "done!\n");
5704 * Handler for new clients
5706 * @param cls closure
5707 * @param client identification of the client
5708 * @param message the actual message, which includes messages the client wants
5711 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
5712 const struct GNUNET_MessageHeader *message)
5714 struct GNUNET_MESH_ClientConnect *cc_msg;
5715 struct MeshClient *c;
5720 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected %p\n", client);
5722 /* Check data sanity */
5723 size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
5724 cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
5725 if (0 != (size % sizeof (uint32_t)))
5728 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5731 size /= sizeof (uint32_t);
5733 /* Initialize new client structure */
5734 c = GNUNET_SERVER_client_get_user_context (client, struct MeshClient);
5735 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " client id %u\n", c->id);
5736 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " client has %u ports\n", size);
5741 p = (uint32_t *) &cc_msg[1];
5742 c->ports = GNUNET_CONTAINER_multihashmap32_create (size);
5743 for (i = 0; i < size; i++)
5746 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " port: %u\n", u32);
5748 /* store in client's hashmap */
5749 GNUNET_CONTAINER_multihashmap32_put (c->ports, u32, c,
5750 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
5751 /* store in global hashmap */
5752 /* FIXME only allow one client to have the port open,
5753 * have a backup hashmap with waiting clients */
5754 GNUNET_CONTAINER_multihashmap32_put (ports, u32, c,
5755 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
5759 c->own_channels = GNUNET_CONTAINER_multihashmap32_create (32);
5760 c->incoming_channels = GNUNET_CONTAINER_multihashmap32_create (32);
5761 GNUNET_SERVER_notification_context_add (nc, client);
5762 GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
5764 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5765 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
5770 * Handler for requests of new tunnels
5772 * @param cls Closure.
5773 * @param client Identification of the client.
5774 * @param message The actual message.
5777 handle_local_channel_create (void *cls, struct GNUNET_SERVER_Client *client,
5778 const struct GNUNET_MessageHeader *message)
5780 struct GNUNET_MESH_ChannelMessage *msg;
5781 struct MeshPeer *peer;
5782 struct MeshTunnel2 *t;
5783 struct MeshChannel *ch;
5784 struct MeshClient *c;
5785 MESH_ChannelNumber chid;
5787 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new channel requested\n");
5789 /* Sanity check for client registration */
5790 if (NULL == (c = client_get (client)))
5793 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5796 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
5798 /* Message size sanity check */
5799 if (sizeof (struct GNUNET_MESH_ChannelMessage) != ntohs (message->size))
5802 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5806 msg = (struct GNUNET_MESH_ChannelMessage *) message;
5807 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " towards %s:%u\n",
5808 GNUNET_i2s (&msg->peer), ntohl (msg->port));
5809 chid = ntohl (msg->channel_id);
5811 /* Sanity check for duplicate channel IDs */
5812 if (NULL != channel_get_by_local_id (c, chid))
5815 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5819 peer = peer_get (&msg->peer);
5820 if (NULL == peer->tunnel)
5822 struct GNUNET_HashCode tid;
5824 GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE, &tid);
5825 peer->tunnel = tunnel_new (&tid);
5826 peer->tunnel->peer = peer;
5830 /* Create channel */
5831 ch = channel_new (t, c, chid);
5835 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5838 ch->port = ntohl (msg->port);
5839 channel_set_options (ch, ntohl (msg->opt));
5841 /* In unreliable channels, we'll use the DLL to buffer data for the root */
5842 ch->fwd_rel = GNUNET_malloc (sizeof (struct MeshChannelReliability));
5843 ch->fwd_rel->ch = ch;
5844 ch->fwd_rel->expected_delay = MESH_RETRANSMIT_TIME;
5846 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED CHANNEL %s[%x]:%u (%x)\n",
5847 GNUNET_h2s (&t->id), ch->gid, ch->port, ch->lid_root);
5848 peer_connect (peer);
5850 /* Send create channel */
5852 struct GNUNET_MESH_ChannelCreate msgcc;
5854 msgcc.header.size = htons (sizeof (msgcc));
5855 msgcc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE);
5856 msgcc.chid = htonl (ch->gid);
5857 msgcc.port = msg->port;
5858 msgcc.opt = msg->opt;
5860 tunnel_queue_data (t, ch, &msgcc.header, GNUNET_YES);
5863 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5869 * Handler for requests of deleting tunnels
5871 * @param cls closure
5872 * @param client identification of the client
5873 * @param message the actual message
5876 handle_local_channel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
5877 const struct GNUNET_MessageHeader *message)
5879 struct GNUNET_MESH_ChannelMessage *msg;
5880 struct MeshClient *c;
5881 struct MeshChannel *ch;
5882 struct MeshTunnel2 *t;
5883 MESH_ChannelNumber chid;
5885 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5886 "Got a DESTROY CHANNEL from client!\n");
5888 /* Sanity check for client registration */
5889 if (NULL == (c = client_get (client)))
5892 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5895 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
5897 /* Message sanity check */
5898 if (sizeof (struct GNUNET_MESH_ChannelMessage) != ntohs (message->size))
5901 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5905 msg = (struct GNUNET_MESH_ChannelMessage *) message;
5907 /* Retrieve tunnel */
5908 chid = ntohl (msg->channel_id);
5909 ch = channel_get_by_local_id (c, chid);
5912 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, " channel %X not found\n", chid);
5914 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5918 /* Cleanup after the tunnel */
5919 client_delete_channel (c, ch);
5920 if (c == ch->dest && GNUNET_MESH_LOCAL_CHANNEL_ID_SERV <= chid)
5924 else if (c == ch->root && GNUNET_MESH_LOCAL_CHANNEL_ID_SERV > chid)
5930 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5931 " channel %X client %p (%p, %p)\n",
5932 chid, c, ch->root, ch->dest);
5937 channel_destroy (ch);
5938 tunnel_destroy_if_empty (t);
5940 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5946 * Handler for client traffic
5948 * @param cls closure
5949 * @param client identification of the client
5950 * @param message the actual message
5953 handle_local_data (void *cls, struct GNUNET_SERVER_Client *client,
5954 const struct GNUNET_MessageHeader *message)
5956 struct GNUNET_MESH_LocalData *msg;
5957 struct MeshClient *c;
5958 struct MeshChannel *ch;
5959 MESH_ChannelNumber chid;
5963 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5964 "Got data from a client!\n");
5966 /* Sanity check for client registration */
5967 if (NULL == (c = client_get (client)))
5970 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5973 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
5975 msg = (struct GNUNET_MESH_LocalData *) message;
5977 /* Sanity check for message size */
5978 size = ntohs (message->size) - sizeof (struct GNUNET_MESH_LocalData);
5979 if (size < sizeof (struct GNUNET_MessageHeader))
5982 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5986 /* Channel exists? */
5987 chid = ntohl (msg->id);
5988 fwd = chid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
5989 ch = channel_get_by_local_id (c, chid);
5993 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5997 /* Is the client in the channel? */
6000 ch->root->handle == client)
6004 ch->dest->handle == client) ) )
6007 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6011 /* Ok, everything is correct, send the message
6012 * (pretend we got it from a mesh peer)
6015 struct GNUNET_MESH_Data *payload;
6016 char cbuf[sizeof(struct GNUNET_MESH_Data) + size];
6019 mid = fwd ? &ch->mid_send_fwd : &ch->mid_send_bck;
6020 if (GNUNET_YES == ch->reliable)
6022 struct MeshChannelReliability *rel;
6023 struct MeshReliableMessage *copy;
6025 rel = fwd ? ch->fwd_rel : ch->bck_rel;
6026 copy = GNUNET_malloc (sizeof (struct MeshReliableMessage)
6027 + sizeof(struct GNUNET_MESH_Data)
6030 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! DATA %u\n", copy->mid);
6031 copy->timestamp = GNUNET_TIME_absolute_get ();
6034 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " n_sent %u\n", rel->n_sent);
6035 GNUNET_CONTAINER_DLL_insert_tail (rel->head_sent, rel->tail_sent, copy);
6036 if (GNUNET_SCHEDULER_NO_TASK == rel->retry_task)
6039 GNUNET_TIME_relative_multiply (rel->expected_delay,
6040 MESH_RETRANSMIT_MARGIN);
6042 GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
6043 &channel_retransmit_message,
6046 payload = (struct GNUNET_MESH_Data *) ©[1];
6050 payload = (struct GNUNET_MESH_Data *) cbuf;
6052 payload->mid = htonl (*mid);
6054 memcpy (&payload[1], &msg[1], size);
6055 payload->header.size = htons (sizeof (struct GNUNET_MESH_Data) + size);
6056 payload->header.type = htons (chid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV ?
6057 GNUNET_MESSAGE_TYPE_MESH_UNICAST :
6058 GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
6059 payload->chid = htonl (ch->gid);
6060 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6061 " calling generic handler...\n");
6062 send_prebuilt_message_channel (&payload->header, ch, fwd);
6064 if (tunnel_get_buffer (ch->t, fwd) > 0)
6065 send_local_ack (ch, c, fwd);
6066 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
6067 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6074 * Handler for client's ACKs for payload traffic.
6076 * @param cls Closure (unused).
6077 * @param client Identification of the client.
6078 * @param message The actual message.
6081 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
6082 const struct GNUNET_MessageHeader *message)
6084 struct GNUNET_MESH_LocalAck *msg;
6085 struct MeshChannelReliability *rel;
6086 struct MeshChannel *ch;
6087 struct MeshClient *c;
6088 MESH_ChannelNumber chid;
6091 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
6093 /* Sanity check for client registration */
6094 if (NULL == (c = client_get (client)))
6097 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6100 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
6102 msg = (struct GNUNET_MESH_LocalAck *) message;
6104 /* Channel exists? */
6105 chid = ntohl (msg->channel_id);
6106 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " on channel %X\n", chid);
6107 ch = channel_get_by_local_id (c, chid);
6111 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Channel %X unknown.\n", chid);
6112 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " for client %u.\n", c->id);
6113 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6117 fwd = chid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
6118 rel = fwd ? ch->fwd_rel : ch->bck_rel;
6120 rel->client_ready = GNUNET_YES;
6121 channel_send_client_buffered_data (ch, c, rel);
6122 channel_send_ack (ch, 64 - rel->n_recv, fwd);
6124 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6131 * Iterator over all tunnels to send a monitoring client info about each tunnel.
6133 * @param cls Closure (client handle).
6134 * @param key Key (hashed tunnel ID, unused).
6135 * @param value Tunnel info.
6137 * @return GNUNET_YES, to keep iterating.
6140 monitor_all_tunnels_iterator (void *cls,
6141 const struct GNUNET_HashCode * key,
6144 struct GNUNET_SERVER_Client *client = cls;
6145 struct MeshChannel *ch = value;
6146 struct GNUNET_MESH_LocalMonitor *msg;
6148 msg = GNUNET_malloc (sizeof(struct GNUNET_MESH_LocalMonitor));
6149 msg->channel_id = htonl (ch->gid);
6150 msg->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
6151 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
6153 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6154 "* sending info about tunnel %s\n",
6155 GNUNET_i2s (&msg->owner));
6157 GNUNET_SERVER_notification_context_unicast (nc, client,
6158 &msg->header, GNUNET_NO);
6164 * Handler for client's MONITOR request.
6166 * @param cls Closure (unused).
6167 * @param client Identification of the client.
6168 * @param message The actual message.
6171 handle_local_get_tunnels (void *cls, struct GNUNET_SERVER_Client *client,
6172 const struct GNUNET_MessageHeader *message)
6174 struct MeshClient *c;
6176 /* Sanity check for client registration */
6177 if (NULL == (c = client_get (client)))
6180 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6184 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6185 "Received get tunnels request from client %u\n",
6187 GNUNET_CONTAINER_multihashmap_iterate (tunnels,
6188 monitor_all_tunnels_iterator,
6190 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6191 "Get tunnels request from client %u completed\n",
6193 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6198 * Handler for client's MONITOR_TUNNEL request.
6200 * @param cls Closure (unused).
6201 * @param client Identification of the client.
6202 * @param message The actual message.
6205 handle_local_show_tunnel (void *cls, struct GNUNET_SERVER_Client *client,
6206 const struct GNUNET_MessageHeader *message)
6208 const struct GNUNET_MESH_LocalMonitor *msg;
6209 struct GNUNET_MESH_LocalMonitor *resp;
6210 struct MeshClient *c;
6211 struct MeshChannel *ch;
6213 /* Sanity check for client registration */
6214 if (NULL == (c = client_get (client)))
6217 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6221 msg = (struct GNUNET_MESH_LocalMonitor *) message;
6222 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6223 "Received tunnel info request from client %u for tunnel %s[%X]\n",
6226 ntohl (msg->channel_id));
6227 // ch = channel_get (&msg->owner, ntohl (msg->channel_id));
6231 /* We don't know the tunnel */
6232 struct GNUNET_MESH_LocalMonitor warn;
6235 GNUNET_SERVER_notification_context_unicast (nc, client,
6238 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6242 /* Initialize context */
6243 resp = GNUNET_malloc (sizeof (struct GNUNET_MESH_LocalMonitor));
6245 resp->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
6246 GNUNET_SERVER_notification_context_unicast (nc, c->handle,
6247 &resp->header, GNUNET_NO);
6250 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6251 "Monitor tunnel request from client %u completed\n",
6253 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6258 * Functions to handle messages from clients
6260 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
6261 {&handle_local_new_client, NULL,
6262 GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
6263 {&handle_local_channel_create, NULL,
6264 GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE,
6265 sizeof (struct GNUNET_MESH_ChannelMessage)},
6266 {&handle_local_channel_destroy, NULL,
6267 GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY,
6268 sizeof (struct GNUNET_MESH_ChannelMessage)},
6269 {&handle_local_data, NULL,
6270 GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA, 0},
6271 {&handle_local_ack, NULL,
6272 GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
6273 sizeof (struct GNUNET_MESH_LocalAck)},
6274 {&handle_local_get_tunnels, NULL,
6275 GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS,
6276 sizeof (struct GNUNET_MessageHeader)},
6277 {&handle_local_show_tunnel, NULL,
6278 GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL,
6279 sizeof (struct GNUNET_MESH_LocalMonitor)},
6285 * Method called whenever a given peer connects.
6287 * @param cls closure
6288 * @param peer peer identity this notification is about
6291 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
6293 struct MeshPeer *pi;
6294 struct MeshPeerPath *path;
6296 DEBUG_CONN ("Peer connected\n");
6297 DEBUG_CONN (" %s\n", GNUNET_i2s (&my_full_id));
6298 pi = peer_get (peer);
6301 DEBUG_CONN (" (self)\n");
6302 path = path_new (1);
6306 DEBUG_CONN (" %s\n", GNUNET_i2s (peer));
6307 path = path_new (2);
6308 path->peers[1] = pi->id;
6309 GNUNET_PEER_change_rc (pi->id, 1);
6310 GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
6312 path->peers[0] = myid;
6313 GNUNET_PEER_change_rc (myid, 1);
6314 peer_add_path (pi, path, GNUNET_YES);
6316 pi->connections = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_YES);
6322 * Method called whenever a peer disconnects.
6324 * @param cls closure
6325 * @param peer peer identity this notification is about
6328 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
6330 struct MeshPeer *pi;
6332 DEBUG_CONN ("Peer disconnected\n");
6333 pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
6340 peer_remove_path (pi, myid, pi->id);
6342 GNUNET_CONTAINER_multihashmap_iterate (pi->connections,
6345 GNUNET_CONTAINER_multihashmap_destroy (pi->connections);
6346 pi->connections = NULL;
6349 DEBUG_CONN (" (self)\n");
6351 GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
6358 * Install server (service) handlers and start listening to clients.
6363 GNUNET_SERVER_add_handlers (server_handle, client_handlers);
6364 GNUNET_SERVER_connect_notify (server_handle,
6365 &handle_local_client_connect, NULL);
6366 GNUNET_SERVER_disconnect_notify (server_handle,
6367 &handle_local_client_disconnect, NULL);
6368 nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
6370 clients_head = NULL;
6371 clients_tail = NULL;
6373 GNUNET_SERVER_resume (server_handle);
6378 * To be called on core init/fail.
6380 * @param cls Closure (config)
6381 * @param server handle to the server for this service
6382 * @param identity the public identity of this peer
6385 core_init (void *cls, struct GNUNET_CORE_Handle *server,
6386 const struct GNUNET_PeerIdentity *identity)
6388 const struct GNUNET_CONFIGURATION_Handle *c = cls;
6391 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
6392 GNUNET_break (core_handle == server);
6393 if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
6396 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
6397 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6399 GNUNET_i2s (identity));
6400 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6402 GNUNET_i2s (&my_full_id));
6403 GNUNET_CORE_disconnect (core_handle);
6404 core_handle = GNUNET_CORE_connect (c, /* Main configuration */
6405 NULL, /* Closure passed to MESH functions */
6406 &core_init, /* Call core_init once connected */
6407 &core_connect, /* Handle connects */
6408 &core_disconnect, /* remove peers on disconnects */
6409 NULL, /* Don't notify about all incoming messages */
6410 GNUNET_NO, /* For header only in notification */
6411 NULL, /* Don't notify about all outbound messages */
6412 GNUNET_NO, /* For header-only out notification */
6413 core_handlers); /* Register these handlers */
6422 /******************************************************************************/
6423 /************************ MAIN FUNCTIONS ****************************/
6424 /******************************************************************************/
6427 * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
6429 * @param cls closure
6430 * @param key current key code
6431 * @param value value in the hash map
6432 * @return GNUNET_YES if we should continue to iterate,
6436 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
6438 struct MeshTunnel2 *t = value;
6446 * Task run during shutdown.
6452 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
6454 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
6456 if (core_handle != NULL)
6458 GNUNET_CORE_disconnect (core_handle);
6461 GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
6462 if (dht_handle != NULL)
6464 GNUNET_DHT_disconnect (dht_handle);
6469 GNUNET_SERVER_notification_context_destroy (nc);
6472 if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
6474 GNUNET_SCHEDULER_cancel (announce_id_task);
6475 announce_id_task = GNUNET_SCHEDULER_NO_TASK;
6477 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
6482 * Process mesh requests.
6484 * @param cls closure
6485 * @param server the initialized server
6486 * @param c configuration to use
6489 run (void *cls, struct GNUNET_SERVER_Handle *server,
6490 const struct GNUNET_CONFIGURATION_Handle *c)
6493 struct GNUNET_CRYPTO_EccPrivateKey *pk;
6495 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
6496 server_handle = server;
6497 GNUNET_SERVER_suspend (server_handle);
6500 GNUNET_CONFIGURATION_get_value_filename (c, "PEER", "PRIVATE_KEY",
6503 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6505 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6506 "mesh", "peer/privatekey");
6507 GNUNET_SCHEDULER_shutdown ();
6512 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_CONNECTION_TIME",
6513 &refresh_connection_time))
6515 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6517 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6518 "mesh", "refresh path time");
6519 GNUNET_SCHEDULER_shutdown ();
6524 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
6527 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6529 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6530 "mesh", "id announce time");
6531 GNUNET_SCHEDULER_shutdown ();
6536 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
6539 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6541 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6542 "mesh", "connect timeout");
6543 GNUNET_SCHEDULER_shutdown ();
6548 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
6551 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6553 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6554 "mesh", "max msgs queue");
6555 GNUNET_SCHEDULER_shutdown ();
6560 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_CONNECTIONS",
6563 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6565 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6566 "mesh", "max tunnels");
6567 GNUNET_SCHEDULER_shutdown ();
6572 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
6575 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6577 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
6578 "mesh", "default ttl", 64);
6583 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
6586 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6587 _("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
6588 "mesh", "max peers", 1000);
6593 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DROP_PERCENT",
6600 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6601 "Mesh is running with drop mode enabled. "
6602 "This is NOT a good idea! "
6603 "Remove the DROP_PERCENT option from your configuration.\n");
6607 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
6608 &dht_replication_level))
6610 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6612 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
6613 "mesh", "dht replication level", 3);
6614 dht_replication_level = 3;
6617 tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6618 peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6619 ports = GNUNET_CONTAINER_multihashmap32_create (32);
6621 dht_handle = GNUNET_DHT_connect (c, 64);
6622 if (NULL == dht_handle)
6626 stats = GNUNET_STATISTICS_create ("mesh", c);
6628 /* Scheduled the task to clean up when shutdown is called */
6629 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
6631 pk = GNUNET_CRYPTO_ecc_key_create_from_file (keyfile);
6632 GNUNET_free (keyfile);
6633 GNUNET_assert (NULL != pk);
6634 my_private_key = pk;
6635 GNUNET_CRYPTO_ecc_key_get_public (my_private_key, &my_public_key);
6636 GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
6637 &my_full_id.hashPubKey);
6638 myid = GNUNET_PEER_intern (&my_full_id);
6639 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6640 "Mesh for peer [%s] starting\n",
6641 GNUNET_i2s(&my_full_id));
6643 core_handle = GNUNET_CORE_connect (c, /* Main configuration */
6644 NULL, /* Closure passed to MESH functions */
6645 &core_init, /* Call core_init once connected */
6646 &core_connect, /* Handle connects */
6647 &core_disconnect, /* remove peers on disconnects */
6648 NULL, /* Don't notify about all incoming messages */
6649 GNUNET_NO, /* For header only in notification */
6650 NULL, /* Don't notify about all outbound messages */
6651 GNUNET_NO, /* For header-only out notification */
6652 core_handlers); /* Register these handlers */
6653 if (NULL == core_handle)
6656 GNUNET_SCHEDULER_shutdown ();
6659 announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
6660 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
6665 * The main function for the mesh service.
6667 * @param argc number of arguments from the command line
6668 * @param argv command line arguments
6669 * @return 0 ok, 1 on error
6672 main (int argc, char *const *argv)
6677 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
6678 r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
6680 ret = (GNUNET_OK == r) ? 0 : 1;
6681 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");