2 This file is part of GNUnet.
3 (C) 2001-2013 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file mesh/gnunet-service-mesh-enc.c
23 * @brief GNUnet MESH service with encryption
24 * @author Bartlomiej Polot
27 * - when sending in-order buffered data, wait for client ACKs
32 * - relay corking down to core
33 * - set ttl relative to path length
37 * - peer: other mesh instance. If there is direct connection it's a neighbor.
38 * - tunnel: encrypted connection to a peer, neighbor or not.
39 * - channel: connection between two clients, on the same or different peers.
40 * have properties like reliability.
41 * - path: series of directly connected peer from one peer to another.
42 * - connection: path which is being used in a tunnel.
46 #include "gnunet_crypto_lib.h"
48 #include "mesh_protocol_enc.h"
49 #include "mesh_path.h"
50 #include "block_mesh.h"
51 #include "gnunet_dht_service.h"
52 #include "gnunet_statistics_service.h"
54 #define MESH_BLOOM_SIZE 128
56 #define MESH_DEBUG_DHT GNUNET_NO
57 #define MESH_DEBUG_CONNECTION GNUNET_YES
58 #define MESH_DEBUG_TIMING __LINUX__ && GNUNET_NO
60 #define MESH_MAX_POLL_TIME GNUNET_TIME_relative_multiply (\
61 GNUNET_TIME_UNIT_MINUTES,\
63 #define MESH_RETRANSMIT_TIME GNUNET_TIME_UNIT_SECONDS
64 #define MESH_RETRANSMIT_MARGIN 4
66 #if MESH_DEBUG_CONNECTION
67 #define DEBUG_CONN(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
69 #define DEBUG_CONN(...)
73 #define DEBUG_DHT(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
75 #define DEBUG_DHT(...)
82 struct timespec __mesh_start;
83 struct timespec __mesh_end;
84 #define INTERVAL_START clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &(__mesh_start))
85 #define INTERVAL_END \
87 clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &(__mesh_end));\
88 double __diff = __mesh_end.tv_nsec - __mesh_start.tv_nsec;\
89 if (__diff < 0) __diff += 1000000000;\
93 #define INTERVAL_SHOW \
95 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "AVG process time: %f ns\n", __sum/__count)
97 #define INTERVAL_START
103 * All the states a tunnel can be in.
108 * Uninitialized status, should never appear in operation.
113 * Path to the peer not known yet
115 MESH_TUNNEL_SEARCHING,
118 * Request sent, not yet answered.
123 * Peer connected and ready to accept data
128 * Peer connected previosly but not responding
130 MESH_TUNNEL_RECONNECTING
135 * All the states a connection can be in.
137 enum MeshConnectionState
140 * Uninitialized status, should never appear in operation.
145 * Connection create message sent, waiting for ACK.
147 MESH_CONNECTION_SENT,
150 * Connection confirmed, ready to carry traffic..
152 MESH_CONNECTION_READY,
156 /******************************************************************************/
157 /************************ DATA STRUCTURES ****************************/
158 /******************************************************************************/
160 /** FWD declaration */
164 struct MeshConnection;
166 struct MeshChannelReliability;
170 * Struct containing info about a queued transmission to this peer
177 struct MeshPeerQueue *next;
182 struct MeshPeerQueue *prev;
185 * Peer this transmission is directed to.
187 struct MeshPeer *peer;
190 * Connection this message belongs to.
192 struct MeshConnection *c;
200 * Channel this message belongs to, if known.
202 struct MeshChannel *ch;
205 * Pointer to info stucture used as cls.
215 * Size of the message
222 * Struct to encapsulate all the Flow Control information to a peer to which
223 * we are directly connected (on a core level).
225 struct MeshFlowControl
228 * Connection this controls.
230 struct MeshConnection *c;
233 * How many messages are in the queue on this connection.
235 unsigned int queue_n;
238 * How many messages do we accept in the queue.
240 unsigned int queue_max;
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 c Connection this message belongs to (cannot be NULL).
1129 * @param ch Channel this message belongs to, if applicable (otherwise NULL).
1130 * @param fwd Is this a message going root->dest? (FWD ACK are NOT FWD!)
1133 queue_add (void* cls,
1136 struct MeshConnection* c,
1137 struct MeshChannel* ch,
1142 * Free a transmission that was already queued with all resources
1143 * associated to the request.
1145 * @param queue Queue handler to cancel.
1146 * @param clear_cls Is it necessary to free associated cls?
1149 queue_destroy (struct MeshPeerQueue *queue, int clear_cls);
1153 * Core callback to write a queued packet to core buffer
1155 * @param cls Closure (peer info).
1156 * @param size Number of bytes available in buf.
1157 * @param buf Where the to write the message.
1159 * @return number of bytes written to buf
1162 queue_send (void *cls, size_t size, void *buf);
1166 * Dummy function to separate declarations from definitions in function list.
1169 __mesh_divider______________________________________________________________();
1173 * Get string description for tunnel state.
1175 * @param s Tunnel state.
1177 * @return String representation.
1180 GNUNET_MESH_DEBUG_TS2S (enum MeshTunnelState s)
1182 static char buf[128];
1186 case MESH_TUNNEL_NEW:
1187 return "MESH_TUNNEL_NEW";
1188 case MESH_TUNNEL_SEARCHING:
1189 return "MESH_TUNNEL_SEARCHING";
1190 case MESH_TUNNEL_WAITING:
1191 return "MESH_TUNNEL_WAITING";
1192 case MESH_TUNNEL_READY:
1193 return "MESH_TUNNEL_READY";
1194 case MESH_TUNNEL_RECONNECTING:
1195 return "MESH_TUNNEL_RECONNECTING";
1198 sprintf (buf, "%u (UNKNOWN STATE)", s);
1205 * Get string description for tunnel state.
1207 * @param s Tunnel state.
1209 * @return String representation.
1212 GNUNET_MESH_DEBUG_CS2S (enum MeshTunnelState s)
1216 case MESH_CONNECTION_NEW:
1217 return "MESH_CONNECTION_NEW";
1218 case MESH_CONNECTION_SENT:
1219 return "MESH_CONNECTION_SENT";
1220 case MESH_CONNECTION_READY:
1221 return "MESH_CONNECTION_READY";
1223 return "MESH_CONNECTION_STATE_ERROR";
1229 /******************************************************************************/
1230 /************************ PERIODIC FUNCTIONS ****************************/
1231 /******************************************************************************/
1234 * Periodically announce self id in the DHT
1236 * @param cls closure
1237 * @param tc task context
1240 announce_id (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1242 struct PBlock block;
1244 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1246 announce_id_task = GNUNET_SCHEDULER_NO_TASK;
1250 * - Set data expiration in function of X
1251 * - Adapt X to churn
1253 DEBUG_DHT ("DHT_put for ID %s started.\n", GNUNET_i2s (&my_full_id));
1255 block.id = my_full_id;
1256 GNUNET_DHT_put (dht_handle, /* DHT handle */
1257 &my_full_id.hashPubKey, /* Key to use */
1258 dht_replication_level, /* Replication level */
1259 GNUNET_DHT_RO_RECORD_ROUTE | GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, /* DHT options */
1260 GNUNET_BLOCK_TYPE_MESH_PEER, /* Block type */
1261 sizeof (block), /* Size of the data */
1262 (const char *) &block, /* Data itself */
1263 GNUNET_TIME_UNIT_FOREVER_ABS, /* Data expiration */
1264 GNUNET_TIME_UNIT_FOREVER_REL, /* Retry time */
1265 NULL, /* Continuation */
1266 NULL); /* Continuation closure */
1268 GNUNET_SCHEDULER_add_delayed (id_announce_time, &announce_id, cls);
1272 /******************************************************************************/
1273 /****************** GENERAL HELPER FUNCTIONS ************************/
1274 /******************************************************************************/
1278 * Get the static string for a peer ID.
1282 * @return Static string for it's ID.
1285 peer2s (const struct MeshPeer *peer)
1289 return GNUNET_i2s (GNUNET_PEER_resolve2 (peer->id));
1294 * Get the previous hop in a connection
1296 * @param c Connection.
1298 * @return Previous peer in the connection.
1300 static struct MeshPeer *
1301 connection_get_prev_hop (struct MeshConnection *c)
1305 if (0 == c->own_pos || c->path->length < 2)
1306 id = c->path->peers[0];
1308 id = c->path->peers[c->own_pos - 1];
1310 return peer_get_short (id);
1315 * Get the next hop in a connection
1317 * @param c Connection.
1319 * @return Next peer in the connection.
1321 static struct MeshPeer *
1322 connection_get_next_hop (struct MeshConnection *c)
1326 if ((c->path->length - 1) == c->own_pos || c->path->length < 2)
1327 id = c->path->peers[c->path->length - 1];
1329 id = c->path->peers[c->own_pos + 1];
1331 return peer_get_short (id);
1336 * Get the hop in a connection.
1338 * @param c Connection.
1339 * @param fwd Next hop?
1341 * @return Next peer in the connection.
1343 static struct MeshPeer *
1344 connection_get_hop (struct MeshConnection *c, int fwd)
1347 return connection_get_next_hop (c);
1348 return connection_get_prev_hop (c);
1352 * Check if client has registered with the service and has not disconnected
1354 * @param client the client to check
1356 * @return non-NULL if client exists in the global DLL
1358 static struct MeshClient *
1359 client_get (struct GNUNET_SERVER_Client *client)
1361 return GNUNET_SERVER_client_get_user_context (client, struct MeshClient);
1366 * Deletes a tunnel from a client (either owner or destination).
1368 * @param c Client whose tunnel to delete.
1369 * @param ch Channel which should be deleted.
1372 client_delete_channel (struct MeshClient *c, struct MeshChannel *ch)
1378 res = GNUNET_CONTAINER_multihashmap32_remove (c->own_channels,
1380 if (GNUNET_YES != res)
1381 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client_delete_channel owner KO\n");
1385 res = GNUNET_CONTAINER_multihashmap32_remove (c->incoming_channels,
1387 if (GNUNET_YES != res)
1388 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client_delete_tunnel client KO\n");
1394 * Notify the appropriate client that a new incoming channel was created.
1396 * @param ch Channel that was created.
1399 send_local_channel_create (struct MeshChannel *ch)
1401 struct GNUNET_MESH_ChannelMessage msg;
1402 struct MeshTunnel2 *t = ch->t;
1404 if (NULL == ch->dest)
1406 msg.header.size = htons (sizeof (msg));
1407 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
1408 msg.channel_id = htonl (ch->lid_dest);
1409 msg.port = htonl (ch->port);
1411 msg.opt |= GNUNET_YES == ch->reliable ? GNUNET_MESH_OPTION_RELIABLE : 0;
1412 msg.opt |= GNUNET_YES == ch->nobuffer ? GNUNET_MESH_OPTION_NOBUFFER : 0;
1413 msg.opt = htonl (msg.opt);
1414 GNUNET_PEER_resolve (t->peer->id, &msg.peer);
1415 GNUNET_SERVER_notification_context_unicast (nc, ch->dest->handle,
1416 &msg.header, GNUNET_NO);
1421 * Notify a client that the incoming tunnel is no longer valid.
1423 * @param ch Channel that is destroyed.
1424 * @param fwd Forward notification (owner->dest)?
1427 send_local_channel_destroy (struct MeshChannel *ch, int fwd)
1429 struct GNUNET_MESH_ChannelMessage msg;
1430 struct MeshClient *c;
1432 c = fwd ? ch->dest : ch->root;
1438 msg.header.size = htons (sizeof (msg));
1439 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1440 msg.channel_id = htonl (fwd ? ch->lid_dest : ch->lid_root);
1441 msg.port = htonl (0);
1442 memset (&msg.peer, 0, sizeof (msg.peer));
1443 msg.opt = htonl (0);
1444 GNUNET_SERVER_notification_context_unicast (nc, c->handle,
1445 &msg.header, GNUNET_NO);
1450 * Build a local ACK message and send it to a local client.
1452 * @param ch Channel on which to send the ACK.
1453 * @param c Client to whom send the ACK.
1454 * @param is_fwd Set to GNUNET_YES for FWD ACK (dest->owner)
1457 send_local_ack (struct MeshChannel *ch,
1458 struct MeshClient *c,
1461 struct GNUNET_MESH_LocalAck msg;
1463 msg.header.size = htons (sizeof (msg));
1464 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
1465 msg.channel_id = htonl (is_fwd ? ch->lid_root : ch->lid_dest);
1466 GNUNET_SERVER_notification_context_unicast (nc,
1474 * Count established (ready) connections of a tunnel.
1476 * @param t Tunnel on which to send the message.
1478 * @return Number of connections.
1481 tunnel_count_connections (struct MeshTunnel2 *t)
1483 struct MeshConnection *c;
1486 for (c = t->connection_head, i = 0; NULL != c; c = c->next, i++);
1493 * Pick a connection on which send the next data message.
1495 * @param t Tunnel on which to send the message.
1496 * @param fwd Is this a fwd message?
1498 * @return The connection on which to send the next message.
1500 static struct MeshConnection *
1501 tunnel_get_connection (struct MeshTunnel2 *t, int fwd)
1503 struct MeshConnection *c;
1504 struct MeshConnection *best;
1505 struct MeshFlowControl *fc;
1506 unsigned int lowest_q;
1509 lowest_q = UINT_MAX;
1510 for (c = t->connection_head; NULL != c; c = c->next)
1512 if (MESH_CONNECTION_READY == c->state)
1514 fc = fwd ? &c->fwd_fc : &c->bck_fc;
1520 if (fc->queue_n < lowest_q)
1523 lowest_q = fc->queue_n;
1532 * Get the total buffer space for a tunnel.
1535 tunnel_get_buffer (struct MeshTunnel2 *t, int fwd)
1537 struct MeshConnection *c;
1538 struct MeshFlowControl *fc;
1539 unsigned int buffer;
1541 for (buffer = 0, c = t->connection_head; NULL != c; c = c->next)
1543 if (c->state != MESH_CONNECTION_READY)
1546 fc = fwd ? &c->fwd_fc : &c->bck_fc;
1547 buffer += fc->last_ack_recv - fc->last_pid_sent;
1555 * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
1556 * Encrypt data with the tunnel key.
1558 * @param t Tunnel whose key to use.
1559 * @param dst Destination for the encrypted data.
1560 * @param src Source of the plaintext.
1561 * @param size Size of the plaintext.
1562 * @param iv Initialization Vector to use.
1563 * @param fwd Is this a fwd message?
1566 tunnel_encrypt (struct MeshTunnel2 *t,
1567 void *dst, const void *src,
1568 size_t size, uint64_t iv, int fwd)
1570 memcpy (dst, src, size);
1575 * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
1576 * Decrypt data with the tunnel key.
1578 * @param t Tunnel whose key to use.
1579 * @param dst Destination for the plaintext.
1580 * @param src Source of the encrypted data.
1581 * @param size Size of the encrypted data.
1582 * @param iv Initialization Vector to use.
1583 * @param fwd Is this a fwd message?
1586 tunnel_decrypt (struct MeshTunnel2 *t,
1587 void *dst, const void *src,
1588 size_t size, uint64_t iv, int fwd)
1590 memcpy (dst, src, size);
1595 * Sends an already built message on a connection, properly registering
1596 * all used resources.
1598 * @param message Message to send. Function makes a copy of it.
1599 * If message is not hop-by-hop, decrements TTL of copy.
1600 * @param c Connection on which this message is transmitted.
1601 * @param ch Channel on which this message is transmitted, or NULL.
1602 * @param fwd Is this a fwd message?
1605 send_prebuilt_message_connection (const struct GNUNET_MessageHeader *message,
1606 struct MeshConnection *c,
1607 struct MeshChannel *ch,
1614 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send on Connection %s[%X]\n",
1615 GNUNET_h2s (&c->t->id), c->id);
1617 size = ntohs (message->size);
1618 data = GNUNET_malloc (size);
1619 memcpy (data, message, size);
1620 type = ntohs (message->type);
1622 if (GNUNET_MESSAGE_TYPE_MESH_FWD == type ||
1623 GNUNET_MESSAGE_TYPE_MESH_BCK == type)
1625 struct GNUNET_MESH_Encrypted *msg;
1628 msg = (struct GNUNET_MESH_Encrypted *) data;
1629 ttl = ntohl (msg->ttl);
1632 GNUNET_break_op (0);
1635 msg->ttl = htonl (ttl - 1);
1648 * Sends an already built message on a tunnel, choosing the best connection.
1650 * @param message Message to send. Function modifies it.
1651 * @param t Tunnel on which this message is transmitted.
1652 * @param ch Channel on which this message is transmitted.
1653 * @param fwd Is this a fwd message?
1656 send_prebuilt_message_tunnel (struct GNUNET_MESH_Encrypted *msg,
1657 struct MeshTunnel2 *t,
1658 struct MeshChannel *ch,
1661 struct MeshConnection *c;
1664 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send on Tunnel %s\n",
1665 GNUNET_h2s (&t->id));
1666 c = tunnel_get_connection (t, fwd);
1669 GNUNET_break (GNUNET_YES == t->destroy);
1672 type = ntohs (msg->header.type);
1675 case GNUNET_MESSAGE_TYPE_MESH_FWD:
1676 case GNUNET_MESSAGE_TYPE_MESH_BCK:
1677 msg->cid = htonl (c->id);
1679 msg->ttl = default_ttl;
1682 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
1683 GNUNET_MESH_DEBUG_M2S (type));
1687 send_prebuilt_message_connection (&msg->header, c, ch, fwd);
1692 * Sends an already built message on a channel, properly registering
1693 * all used resources and encrypting the message with the tunnel's key.
1695 * @param message Message to send. Function makes a copy of it.
1696 * @param ch Channel on which this message is transmitted.
1697 * @param fwd Is this a fwd message?
1700 send_prebuilt_message_channel (const struct GNUNET_MessageHeader *message,
1701 struct MeshChannel *ch,
1704 struct GNUNET_MESH_Encrypted *msg;
1705 size_t size = ntohs (message->size);
1706 char *cbuf[sizeof (struct GNUNET_MESH_Encrypted) + size];
1710 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send on Channel %s:%X\n",
1711 GNUNET_h2s (&ch->t->id), ch->gid);
1712 type = fwd ? GNUNET_MESSAGE_TYPE_MESH_FWD : GNUNET_MESSAGE_TYPE_MESH_BCK;
1713 iv = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_NONCE, UINT64_MAX);
1715 msg = (struct GNUNET_MESH_Encrypted *) cbuf;
1716 msg->header.type = htons (type);
1717 msg->header.size = htons (sizeof (struct GNUNET_MESH_Encrypted) + size);
1718 msg->iv = GNUNET_htonll (iv);
1719 tunnel_encrypt (ch->t, &msg[1], message, size, iv, fwd);
1721 send_prebuilt_message_tunnel (msg, ch->t, ch, fwd);
1726 * Sends a CREATE CONNECTION message for a path to a peer.
1727 * Changes the connection and tunnel states if necessary.
1729 * @param connection Connection to create.
1732 send_connection_create (struct MeshConnection *connection)
1734 struct MeshTunnel2 *t;
1737 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send connection create\n");
1739 GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
1740 sizeof (struct GNUNET_MESH_ConnectionCreate) +
1741 (connection->path->length *
1742 sizeof (struct GNUNET_PeerIdentity)),
1746 if (MESH_TUNNEL_SEARCHING == t->state || MESH_TUNNEL_NEW == t->state)
1747 tunnel_change_state (t, MESH_TUNNEL_WAITING);
1748 if (MESH_CONNECTION_NEW == connection->state)
1749 connection_change_state (connection, MESH_CONNECTION_SENT);
1754 * Sends a CONNECTION ACK message in reponse to a received CONNECTION_CREATE
1757 * @param connection Connection to confirm.
1758 * @param fwd Is this a fwd ACK? (First is bck (SYNACK), second is fwd (ACK))
1761 send_connection_ack (struct MeshConnection *connection, int fwd)
1763 struct MeshTunnel2 *t;
1766 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send connection ack\n");
1768 GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
1769 sizeof (struct GNUNET_MESH_ConnectionACK),
1773 if (MESH_TUNNEL_NEW == t->state)
1774 tunnel_change_state (t, MESH_TUNNEL_WAITING);
1779 * Build a hop-by-hop ACK message and queue it to send for the given connection.
1781 * @param c Which connection to send the hop-by-hop ACK.
1782 * @param ack Value of the ACK.
1783 * @param fwd Is this fwd?
1786 send_ack (struct MeshConnection *c, uint32_t ack, int fwd)
1788 struct GNUNET_MESH_ACK msg;
1790 msg.header.size = htons (sizeof (msg));
1791 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ACK);
1792 msg.ack = htonl (ack);
1794 msg.cid = htonl (c->id);
1796 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1797 "connection send %s ack %u on %s[%X]\n",
1798 fwd ? "FWD" : "BCK", ack, GNUNET_h2s (&c->t->id), c->id);
1800 send_prebuilt_message_connection (&msg.header, c, NULL, fwd);
1805 * Core callback to write a pre-constructed data packet to core buffer
1807 * @param cls Closure (MeshTransmissionDescriptor with data in "data" member).
1808 * @param size Number of bytes available in buf.
1809 * @param buf Where the to write the message.
1811 * @return number of bytes written to buf
1814 send_core_data_raw (void *cls, size_t size, void *buf)
1816 struct GNUNET_MessageHeader *msg = cls;
1819 GNUNET_assert (NULL != msg);
1820 total_size = ntohs (msg->size);
1822 if (total_size > size)
1827 memcpy (buf, msg, total_size);
1834 * Function to send a create connection message to a peer.
1836 * @param c Connection to create.
1837 * @param size number of bytes available in buf
1838 * @param buf where the callee should write the message
1839 * @return number of bytes written to buf
1842 send_core_connection_create (struct MeshConnection *c, size_t size, void *buf)
1844 struct GNUNET_MESH_ConnectionCreate *msg;
1845 struct GNUNET_PeerIdentity *peer_ptr;
1846 struct MeshPeerPath *p = c->path;
1850 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION CREATE...\n");
1852 sizeof (struct GNUNET_MESH_ConnectionCreate) +
1853 p->length * sizeof (struct GNUNET_PeerIdentity);
1855 if (size < size_needed || NULL == buf)
1860 msg = (struct GNUNET_MESH_ConnectionCreate *) buf;
1861 msg->header.size = htons (size_needed);
1862 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE);
1863 msg->cid = htonl (c->id);
1864 msg->tid = c->t->id;
1866 peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
1867 for (i = 0; i < p->length; i++)
1869 GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
1872 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1873 "CONNECTION CREATE (%u bytes long) sent!\n", size_needed);
1879 * Creates a path ack message in buf and frees all unused resources.
1881 * @param c Connection to send an ACK on.
1882 * @param size number of bytes available in buf
1883 * @param buf where the callee should write the message
1885 * @return number of bytes written to buf
1888 send_core_connection_ack (struct MeshConnection *c, size_t size, void *buf)
1890 struct GNUNET_MESH_ConnectionACK *msg = buf;
1891 struct MeshTunnel2 *t = c->t;
1893 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION ACK...\n");
1894 GNUNET_assert (NULL != t);
1895 if (sizeof (struct GNUNET_MESH_ConnectionACK) > size)
1900 msg->header.size = htons (sizeof (struct GNUNET_MESH_ConnectionACK));
1901 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK);
1902 msg->cid = htonl (c->id);
1905 /* TODO add signature */
1907 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CONNECTION ACK sent!\n");
1908 return sizeof (struct GNUNET_MESH_ConnectionACK);
1913 * Destroy the peer_info and free any allocated resources linked to it
1915 * @param peer The peer_info to destroy.
1917 * @return GNUNET_OK on success
1920 peer_destroy (struct MeshPeer *peer)
1922 struct GNUNET_PeerIdentity id;
1923 struct MeshPeerPath *p;
1924 struct MeshPeerPath *nextp;
1926 GNUNET_PEER_resolve (peer->id, &id);
1927 GNUNET_PEER_change_rc (peer->id, -1);
1930 GNUNET_CONTAINER_multihashmap_remove (peers, &id.hashPubKey, peer))
1933 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1934 "removing peer %s, not in hashmap\n", GNUNET_i2s (&id));
1936 if (NULL != peer->dhtget)
1938 GNUNET_DHT_get_stop (peer->dhtget);
1940 p = peer->path_head;
1944 GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
1948 tunnel_destroy_empty (peer->tunnel);
1955 * Returns if peer is used (has a tunnel, is neighbor).
1957 * @peer Peer to check.
1959 * @return GNUNET_YES if peer is in use.
1962 peer_is_used (struct MeshPeer *peer)
1964 struct MeshPeerPath *p;
1966 if (NULL != peer->tunnel)
1969 for (p = peer->path_head; NULL != p; p = p->next)
1978 * Iterator over all the peers to get the oldest timestamp.
1980 * @param cls Closure (unsued).
1981 * @param key ID of the peer.
1982 * @param value Peer_Info of the peer.
1985 peer_get_oldest (void *cls,
1986 const struct GNUNET_HashCode *key,
1989 struct MeshPeer *p = value;
1990 struct GNUNET_TIME_Absolute *abs = cls;
1992 /* Don't count active peers */
1993 if (GNUNET_YES == peer_is_used (p))
1996 if (abs->abs_value_us < p->last_contact.abs_value_us)
1997 abs->abs_value_us = p->last_contact.abs_value_us;
2004 * Iterator over all the peers to remove the oldest entry.
2006 * @param cls Closure (unsued).
2007 * @param key ID of the peer.
2008 * @param value Peer_Info of the peer.
2011 peer_timeout (void *cls,
2012 const struct GNUNET_HashCode *key,
2015 struct MeshPeer *p = value;
2016 struct GNUNET_TIME_Absolute *abs = cls;
2018 if (p->last_contact.abs_value_us == abs->abs_value_us &&
2019 GNUNET_NO == peer_is_used (p))
2029 * Delete oldest unused peer.
2032 peer_delete_oldest (void)
2034 struct GNUNET_TIME_Absolute abs;
2036 abs = GNUNET_TIME_UNIT_FOREVER_ABS;
2038 GNUNET_CONTAINER_multihashmap_iterate (peers,
2041 GNUNET_CONTAINER_multihashmap_iterate (peers,
2048 * Retrieve the MeshPeer stucture associated with the peer, create one
2049 * and insert it in the appropriate structures if the peer is not known yet.
2051 * @param peer Full identity of the peer.
2053 * @return Existing or newly created peer info.
2055 static struct MeshPeer *
2056 peer_get (const struct GNUNET_PeerIdentity *peer_id)
2058 struct MeshPeer *peer;
2060 peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer_id->hashPubKey);
2063 peer = GNUNET_new (struct MeshPeer);
2064 if (GNUNET_CONTAINER_multihashmap_size (peers) > max_peers)
2066 peer_delete_oldest ();
2068 GNUNET_CONTAINER_multihashmap_put (peers, &peer_id->hashPubKey, peer,
2069 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
2070 peer->id = GNUNET_PEER_intern (peer_id);
2072 peer->last_contact = GNUNET_TIME_absolute_get();
2079 * Retrieve the MeshPeer stucture associated with the peer, create one
2080 * and insert it in the appropriate structures if the peer is not known yet.
2082 * @param peer Short identity of the peer.
2084 * @return Existing or newly created peer info.
2086 static struct MeshPeer *
2087 peer_get_short (const GNUNET_PEER_Id peer)
2089 return peer_get (GNUNET_PEER_resolve2 (peer));
2094 * Get a cost of a path for a peer considering existing tunnel connections.
2096 * @param peer Peer towards which the path is considered.
2097 * @param path Candidate path.
2099 * @return Cost of the path (path length + number of overlapping nodes)
2102 peer_get_path_cost (const struct MeshPeer *peer,
2103 const struct MeshPeerPath *path)
2105 struct MeshConnection *c;
2106 unsigned int overlap;
2114 GNUNET_assert (NULL != peer->tunnel);
2116 for (i = 0; i < path->length; i++)
2118 for (c = peer->tunnel->connection_head; NULL != c; c = c->next)
2120 for (j = 0; j < c->path->length; j++)
2122 if (path->peers[i] == c->path->peers[j])
2130 return (path->length + overlap) * (path->score * -1);
2135 * Choose the best path towards a peer considering the tunnel properties.
2137 * @param peer The destination peer.
2139 * @return Best current known path towards the peer, if any.
2141 static struct MeshPeerPath *
2142 peer_get_best_path (const struct MeshPeer *peer)
2144 struct MeshPeerPath *best_p;
2145 struct MeshPeerPath *p;
2146 struct MeshConnection *c;
2147 unsigned int best_cost;
2150 best_cost = UINT_MAX;
2152 for (p = peer->path_head; NULL != p; p = p->next)
2154 for (c = peer->tunnel->connection_head; NULL != c; c = c->next)
2158 continue; /* If path is in use in a connection, skip it. */
2160 if ((cost = peer_get_path_cost (peer, p)) < best_cost)
2170 queue_is_sendable (struct MeshPeerQueue *q)
2172 struct MeshFlowControl *fc;
2174 /* Is PID-independent? */
2177 case GNUNET_MESSAGE_TYPE_MESH_ACK:
2178 case GNUNET_MESSAGE_TYPE_MESH_POLL:
2182 /* Is PID allowed? */
2183 fc = q->fwd ? &q->c->fwd_fc : &q->c->bck_fc;
2184 if (GMC_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
2192 * Get first sendable message.
2194 * @param peer The destination peer.
2196 * @return Best current known path towards the peer, if any.
2198 static struct MeshPeerQueue *
2199 peer_get_first_message (const struct MeshPeer *peer)
2201 struct MeshPeerQueue *q;
2203 for (q = peer->queue_head; NULL != q; q = q->next)
2205 if (queue_is_sendable (q))
2214 * Try to establish a new connection to this peer in the given tunnel.
2215 * If the peer doesn't have any path to it yet, try to get one.
2216 * If the peer already has some path, send a CREATE CONNECTION towards it.
2218 * @param peer PeerInfo of the peer.
2221 peer_connect (struct MeshPeer *peer)
2223 struct MeshTunnel2 *t;
2224 struct MeshPeerPath *p;
2225 struct MeshConnection *c;
2227 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2228 "peer_connect towards %s\n",
2231 if (NULL != peer->path_head)
2233 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "path exists\n");
2234 p = peer_get_best_path (peer);
2237 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " %u hops\n", p->length);
2238 c = tunnel_use_path (t, p);
2239 send_connection_create (c);
2242 else if (NULL == peer->dhtget)
2244 const struct GNUNET_PeerIdentity *id;
2246 id = GNUNET_PEER_resolve2 (peer->id);
2247 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2248 " Starting DHT GET for peer %s\n", peer2s (peer));
2249 peer->dhtget = GNUNET_DHT_get_start (dht_handle, /* handle */
2250 GNUNET_BLOCK_TYPE_MESH_PEER, /* type */
2251 &id->hashPubKey, /* key to search */
2252 dht_replication_level, /* replication level */
2253 GNUNET_DHT_RO_RECORD_ROUTE |
2254 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
2256 0, /* xquery bits */
2257 &dht_get_id_handler, peer);
2258 if (MESH_TUNNEL_NEW == t->state)
2259 tunnel_change_state (t, MESH_TUNNEL_SEARCHING);
2263 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2264 "There is no path but the DHT GET is already started.\n");
2270 * Get the first transmittable message for a connection.
2272 * @param c Connection.
2273 * @param fwd Is this FWD?
2275 * @return First transmittable message.
2277 static struct MeshPeerQueue *
2278 connection_get_first_message (struct MeshConnection *c, int fwd)
2280 struct MeshPeerQueue *q;
2283 p = connection_get_hop (c, fwd);
2285 for (q = p->queue_head; NULL != q; q = q->next)
2289 if (queue_is_sendable (q))
2298 * Is this peer the last one on the connection?
2300 * @param c Connection.
2301 * @param fwd Is this about fwd traffic?
2302 * Note that the ROOT is the terminal for BCK traffic!
2304 * @return GNUNET_YES if terminal, GNUNET_NO if relay/origin.
2307 connection_is_terminal (struct MeshConnection *c, int fwd)
2309 if (fwd && c->own_pos == c->path->length - 1)
2311 if (!fwd && c->own_pos == 0)
2318 * @brief Re-initiate traffic on this connection if necessary.
2320 * Check if there is traffic queued towards this peer
2321 * and the core transmit handle is NULL (traffic was stalled).
2322 * If so, call core tmt rdy.
2324 * @param c Connection on which initiate traffic.
2325 * @param fwd Is this about fwd traffic?
2328 connection_unlock_queue (struct MeshConnection *c, int fwd)
2330 struct MeshPeer *peer;
2331 struct MeshPeerQueue *q;
2334 peer = connection_get_hop (c, fwd);
2336 if (NULL != peer->core_transmit)
2337 return; /* Already unlocked */
2339 q = connection_get_first_message (c, fwd);
2341 return; /* Nothing to transmit */
2344 peer->core_transmit =
2345 GNUNET_CORE_notify_transmit_ready (core_handle,
2348 GNUNET_TIME_UNIT_FOREVER_REL,
2349 GNUNET_PEER_resolve2 (peer->id),
2357 * Cancel all transmissions that belong to a certain connection.
2359 * @param c Connection which to cancel.
2360 * @param fwd Cancel fwd traffic?
2363 connection_cancel_queues (struct MeshConnection *c, int fwd)
2365 struct MeshPeerQueue *q;
2366 struct MeshPeerQueue *next;
2367 struct MeshFlowControl *fc;
2368 struct MeshPeer *peer;
2375 fc = fwd ? &c->fwd_fc : &c->bck_fc;
2376 peer = connection_get_hop (c, fwd);
2378 for (q = peer->queue_head; NULL != q; q = next)
2383 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2384 "connection_cancel_queue %s\n",
2385 GNUNET_MESH_DEBUG_M2S (q->type));
2386 queue_destroy (q, GNUNET_YES);
2389 if (NULL == peer->queue_head)
2391 if (NULL != peer->core_transmit)
2393 GNUNET_CORE_notify_transmit_ready_cancel (peer->core_transmit);
2394 peer->core_transmit = NULL;
2396 if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
2398 GNUNET_SCHEDULER_cancel (fc->poll_task);
2399 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2406 * Remove all paths that rely on a direct connection between p1 and p2
2407 * from the peer itself and notify all tunnels about it.
2409 * @param peer PeerInfo of affected peer.
2410 * @param p1 GNUNET_PEER_Id of one peer.
2411 * @param p2 GNUNET_PEER_Id of another peer that was connected to the first and
2414 * TODO: optimize (see below)
2417 peer_remove_path (struct MeshPeer *peer, GNUNET_PEER_Id p1,
2420 struct MeshPeerPath *p;
2421 struct MeshPeerPath *next;
2422 struct MeshPeer *peer_d;
2424 unsigned int destroyed;
2427 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path\n");
2429 for (p = peer->path_head; NULL != p; p = next)
2432 for (i = 0; i < (p->length - 1); i++)
2434 if ((p->peers[i] == p1 && p->peers[i + 1] == p2) ||
2435 (p->peers[i] == p2 && p->peers[i + 1] == p1))
2437 GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
2448 d = tunnel_notify_connection_broken (peer->tunnel, p1, p2);
2450 peer_d = peer_get_short (d); // FIXME
2451 next = peer_get_best_path (peer_d);
2452 tunnel_use_path (peer->tunnel, next);
2453 peer_connect (peer_d);
2455 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path END\n");
2460 * Add the path to the peer and update the path used to reach it in case this
2463 * @param peer_info Destination peer to add the path to.
2464 * @param path New path to add. Last peer must be the peer in arg 1.
2465 * Path will be either used of freed if already known.
2466 * @param trusted Do we trust that this path is real?
2469 peer_add_path (struct MeshPeer *peer_info, struct MeshPeerPath *path,
2472 struct MeshPeerPath *aux;
2476 if ((NULL == peer_info) || (NULL == path))
2479 path_destroy (path);
2482 if (path->peers[path->length - 1] != peer_info->id)
2485 path_destroy (path);
2488 if (2 >= path->length && GNUNET_NO == trusted)
2490 /* Only allow CORE to tell us about direct paths */
2491 path_destroy (path);
2494 for (l = 1; l < path->length; l++)
2496 if (path->peers[l] == myid)
2498 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shortening path by %u\n", l);
2499 for (l2 = 0; l2 < path->length - l; l2++)
2501 path->peers[l2] = path->peers[l + l2];
2506 GNUNET_realloc (path->peers, path->length * sizeof (GNUNET_PEER_Id));
2510 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "adding path [%u] to peer %s\n",
2511 path->length, peer2s (peer_info));
2513 l = path_get_length (path);
2516 path_destroy (path);
2520 GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
2521 for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
2523 l2 = path_get_length (aux);
2526 GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
2527 peer_info->path_tail, aux, path);
2532 if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
2534 path_destroy (path);
2539 GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head, peer_info->path_tail,
2546 * Add the path to the origin peer and update the path used to reach it in case
2547 * this is the shortest.
2548 * The path is given in peer_info -> destination, therefore we turn the path
2549 * upside down first.
2551 * @param peer_info Peer to add the path to, being the origin of the path.
2552 * @param path New path to add after being inversed.
2553 * Path will be either used or freed.
2554 * @param trusted Do we trust that this path is real?
2557 peer_add_path_to_origin (struct MeshPeer *peer_info,
2558 struct MeshPeerPath *path, int trusted)
2561 peer_add_path (peer_info, path, trusted);
2567 * Function called if a connection has been stalled for a while,
2568 * possibly due to a missed ACK. Poll the neighbor about its ACK status.
2570 * @param cls Closure (poll ctx).
2571 * @param tc TaskContext.
2574 connection_poll (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2576 struct MeshFlowControl *fc = cls;
2577 struct GNUNET_MESH_Poll msg;
2578 struct MeshConnection *c;
2580 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2581 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2587 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** Polling!\n");
2588 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** connection %s[%X]\n",
2589 peer2s (c->t->peer), c->id);
2591 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_POLL);
2592 msg.header.size = htons (sizeof (msg));
2593 msg.pid = htonl (fc->last_pid_sent);
2594 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** pid (%u)!\n", fc->last_pid_sent);
2595 send_prebuilt_message_connection (&msg.header, c, NULL, fc == &c->fwd_fc);
2596 fc->poll_time = GNUNET_TIME_STD_BACKOFF (fc->poll_time);
2597 fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
2598 &connection_poll, fc);
2603 * Build a PeerPath from the paths returned from the DHT, reversing the paths
2604 * to obtain a local peer -> destination path and interning the peer ids.
2606 * @return Newly allocated and created path
2608 static struct MeshPeerPath *
2609 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
2610 unsigned int get_path_length,
2611 const struct GNUNET_PeerIdentity *put_path,
2612 unsigned int put_path_length)
2614 struct MeshPeerPath *p;
2620 GNUNET_PEER_change_rc (myid, 1);
2621 i = get_path_length;
2622 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " GET has %d hops.\n", i);
2623 for (i--; i >= 0; i--)
2625 id = GNUNET_PEER_intern (&get_path[i]);
2626 if (p->length > 0 && id == p->peers[p->length - 1])
2628 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Optimizing 1 hop out.\n");
2629 GNUNET_PEER_change_rc (id, -1);
2633 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Adding from GET: %s.\n",
2634 GNUNET_i2s (&get_path[i]));
2636 p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2637 p->peers[p->length - 1] = id;
2640 i = put_path_length;
2641 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " PUT has %d hops.\n", i);
2642 for (i--; i >= 0; i--)
2644 id = GNUNET_PEER_intern (&put_path[i]);
2647 /* PUT path went through us, so discard the path up until now and start
2648 * from here to get a much shorter (and loop-free) path.
2653 if (p->length > 0 && id == p->peers[p->length - 1])
2655 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Optimizing 1 hop out.\n");
2656 GNUNET_PEER_change_rc (id, -1);
2660 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Adding from PUT: %s.\n",
2661 GNUNET_i2s (&put_path[i]));
2663 p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2664 p->peers[p->length - 1] = id;
2668 if (get_path_length > 0)
2669 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " (first of GET: %s)\n",
2670 GNUNET_i2s (&get_path[0]));
2671 if (put_path_length > 0)
2672 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " (first of PUT: %s)\n",
2673 GNUNET_i2s (&put_path[0]));
2674 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " In total: %d hops\n",
2676 for (i = 0; i < p->length; i++)
2678 struct GNUNET_PeerIdentity peer_id;
2680 GNUNET_PEER_resolve (p->peers[i], &peer_id);
2681 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " %u: %s\n", p->peers[i],
2682 GNUNET_i2s (&peer_id));
2690 * Adds a path to the peer_infos of all the peers in the path
2692 * @param p Path to process.
2693 * @param confirmed Whether we know if the path works or not.
2696 path_add_to_peers (struct MeshPeerPath *p, int confirmed)
2700 /* TODO: invert and add */
2701 for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
2702 for (i++; i < p->length; i++)
2704 struct MeshPeer *aux;
2705 struct MeshPeerPath *copy;
2707 aux = peer_get_short (p->peers[i]);
2708 copy = path_duplicate (p);
2709 copy->length = i + 1;
2710 peer_add_path (aux, copy, p->length < 3 ? GNUNET_NO : confirmed);
2716 * Search for a channel among the channels for a client
2718 * @param c the client whose channels to search in
2719 * @param chid the local id of the channel
2721 * @return channel handler, NULL if doesn't exist
2723 static struct MeshChannel *
2724 channel_get_by_local_id (struct MeshClient *c, MESH_ChannelNumber chid)
2726 if (0 == (chid & GNUNET_MESH_LOCAL_CHANNEL_ID_CLI))
2728 GNUNET_break_op (0);
2729 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CHID %X not a local chid\n", chid);
2732 if (chid >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV)
2733 return GNUNET_CONTAINER_multihashmap32_get (c->incoming_channels, chid);
2734 return GNUNET_CONTAINER_multihashmap32_get (c->own_channels, chid);
2738 * Search for a tunnel by global ID using full PeerIdentities.
2740 * @param t Tunnel containing the channel.
2741 * @param chid Public channel number.
2743 * @return channel handler, NULL if doesn't exist
2745 static struct MeshChannel *
2746 channel_get (struct MeshTunnel2 *t, MESH_ChannelNumber chid)
2748 struct MeshChannel *ch;
2753 for (ch = t->channel_head; NULL != ch; ch = ch->next)
2755 if (ch->gid == chid)
2764 * Change the tunnel state.
2766 * @param t Tunnel whose state to change.
2767 * @param state New state.
2770 tunnel_change_state (struct MeshTunnel2* t, enum MeshTunnelState state)
2772 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2773 "Tunnel %s state was %s\n",
2775 GNUNET_MESH_DEBUG_TS2S (t->state));
2776 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2777 "Tunnel %s state is now %s\n",
2779 GNUNET_MESH_DEBUG_TS2S (state));
2785 * Cache a message to be sent once tunnel is online.
2787 * @param t Tunnel to hold the message.
2788 * @param ch Channel the message is about.
2789 * @param msg Message itself (copy will be made).
2790 * @param fwd Is this fwd?
2793 tunnel_queue_data (struct MeshTunnel2 *t,
2794 struct MeshChannel *ch,
2795 struct GNUNET_MessageHeader *msg,
2798 struct MeshTunnelQueue *tq;
2799 uint16_t size = ntohs (msg->size);
2801 tq = GNUNET_malloc (sizeof (struct MeshTunnelQueue) + size);
2804 memcpy (&tq[1], msg, size);
2805 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tq);
2810 * Send all cached messages that we can, tunnel is online.
2812 * @param t Tunnel that holds the messages.
2813 * @param fwd Is this fwd?
2816 tunnel_send_queued_data (struct MeshTunnel2 *t, int fwd)
2818 struct MeshTunnelQueue *tq;
2819 struct MeshTunnelQueue *next;
2822 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2823 "tunnel_send_queued_data on %s\n",
2824 GNUNET_h2s (&t->id));
2825 room = tunnel_get_buffer (t, fwd);
2826 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
2827 for (tq = t->tq_head; NULL != tq && room > 0; tq = next)
2831 GNUNET_CONTAINER_DLL_remove (t->tq_head, t->tq_tail, tq);
2832 send_prebuilt_message_channel ((struct GNUNET_MessageHeader *) &tq[1],
2841 connection_change_state (struct MeshConnection* c,
2842 enum MeshConnectionState state)
2844 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2845 "Connection %s[%X] state was %s\n",
2846 peer2s (c->t->peer), c->id,
2847 GNUNET_MESH_DEBUG_CS2S (c->state));
2848 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2849 "Connection %s[%X] state is now %s\n",
2850 peer2s (c->t->peer), c->id,
2851 GNUNET_MESH_DEBUG_CS2S (state));
2857 * Add a client to a channel, initializing all needed data structures.
2859 * @param ch Channel to which add the client.
2860 * @param c Client which to add to the channel.
2863 channel_add_client (struct MeshChannel *ch, struct MeshClient *c)
2865 struct MeshTunnel2 *t = ch->t;
2867 if (NULL != ch->dest)
2873 /* Assign local id as destination */
2874 while (NULL != channel_get_by_local_id (c, t->next_local_chid))
2875 t->next_local_chid = (t->next_local_chid + 1) | GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
2876 ch->lid_dest = t->next_local_chid++;
2877 t->next_local_chid = t->next_local_chid | GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
2879 /* Store in client's hashmap */
2881 GNUNET_CONTAINER_multihashmap32_put (c->incoming_channels,
2883 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2892 static struct MeshConnection *
2893 tunnel_use_path (struct MeshTunnel2 *t, struct MeshPeerPath *p)
2895 struct MeshConnection *c;
2896 struct MeshPeer *peer;
2897 unsigned int own_pos;
2899 c = connection_new (&t->id, t->next_cid++);
2900 for (own_pos = 0; own_pos < p->length; own_pos++)
2902 if (p->peers[own_pos] == myid)
2905 if (own_pos > p->length - 1)
2908 connection_destroy (c);
2911 c->own_pos = own_pos;
2916 c->fwd_maintenance_task =
2917 GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
2918 &connection_fwd_keepalive, c);
2921 peer = connection_get_next_hop (c);
2922 GNUNET_CONTAINER_multihashmap_put (peer->connections, &c->t->id, c,
2923 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2924 peer = connection_get_prev_hop (c);
2925 GNUNET_CONTAINER_multihashmap_put (peer->connections, &c->t->id, c,
2926 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2932 * Notifies a tunnel that a connection has broken that affects at least
2933 * some of its peers. Sends a notification towards the root of the tree.
2934 * In case the peer is the owner of the tree, notifies the client that owns
2935 * the tunnel and tries to reconnect.
2937 * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
2939 * @param t Tunnel affected.
2940 * @param p1 Peer that got disconnected from p2.
2941 * @param p2 Peer that got disconnected from p1.
2943 * @return Short ID of the peer disconnected (either p1 or p2).
2944 * 0 if the tunnel remained unaffected.
2946 static GNUNET_PEER_Id
2947 tunnel_notify_connection_broken (struct MeshTunnel2* t,
2948 GNUNET_PEER_Id p1, GNUNET_PEER_Id p2)
2950 // if (myid != p1 && myid != p2) FIXME
2955 // if (tree_get_predecessor (t->tree) != 0)
2957 // /* We are the peer still connected, notify owner of the disconnection. */
2958 // struct GNUNET_MESH_PathBroken msg;
2959 // struct GNUNET_PeerIdentity neighbor;
2961 // msg.header.size = htons (sizeof (msg));
2962 // msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN);
2963 // GNUNET_PEER_resolve (t->id.oid, &msg.oid);
2964 // msg.tid = htonl (t->id.tid);
2965 // msg.peer1 = my_full_id;
2966 // GNUNET_PEER_resolve (pid, &msg.peer2);
2967 // GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &neighbor);
2968 // send_prebuilt_message (&msg.header, &neighbor, t);
2975 * Send an end-to-end FWD ACK message for the most recent in-sequence payload.
2977 * @param ch Channel this is about.
2978 * @param fwd Is for FWD traffic? (ACK dest->owner)
2981 channel_send_data_ack (struct MeshChannel *ch, int fwd)
2983 struct GNUNET_MESH_DataACK msg;
2984 struct MeshChannelReliability *rel;
2985 struct MeshReliableMessage *copy;
2990 if (GNUNET_NO == ch->reliable)
2995 rel = fwd ? ch->bck_rel : ch->fwd_rel;
2996 mid = fwd ? &ch->mid_recv_fwd : &ch->mid_recv_bck;
2997 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2998 "send_data_ack for %u\n",
3001 msg.header.type = htons (fwd ? GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK :
3002 GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK);
3003 msg.header.size = htons (sizeof (msg));
3004 msg.chid = htonl (ch->gid);
3005 msg.mid = htonl (*mid - 1);
3007 for (copy = rel->head_recv; NULL != copy; copy = copy->next)
3009 delta = copy->mid - *mid;
3012 mask = 0x1LL << delta;
3013 msg.futures |= mask;
3014 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3015 " setting bit for %u (delta %u) (%llX) -> %llX\n",
3016 copy->mid, delta, mask, msg.futures);
3018 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " final futures %llX\n", msg.futures);
3020 send_prebuilt_message_channel (&msg.header, ch, fwd);
3021 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_data_ack END\n");
3026 * Send an ACK informing the predecessor about the available buffer space.
3028 * Note that for fwd ack, the FWD mean forward *traffic* (root->dest),
3029 * the ACK itself goes "back" (dest->root).
3031 * @param c Connection on which to send the ACK.
3032 * @param fwd Is this FWD ACK? (Going dest->owner)
3035 connection_send_ack (struct MeshConnection *c, int fwd)
3037 struct MeshFlowControl *next_fc;
3038 struct MeshFlowControl *prev_fc;
3042 next_fc = fwd ? &c->fwd_fc : &c->bck_fc;
3043 prev_fc = fwd ? &c->bck_fc : &c->fwd_fc;
3045 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3046 "connection send %s ack on %s[%X]\n",
3047 fwd ? "FWD" : "BCK", GNUNET_h2s (&c->t->id), c->id);
3049 /* Check if we need to transmit the ACK */
3050 if (prev_fc->last_ack_sent - prev_fc->last_pid_recv > 3)
3052 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer > 3\n");
3053 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3054 " last pid recv: %u, last ack sent: %u\n",
3055 prev_fc->last_pid_recv, prev_fc->last_ack_sent);
3059 /* Ok, ACK might be necessary, what PID to ACK? */
3060 delta = next_fc->queue_max - next_fc->queue_n;
3061 ack = prev_fc->last_pid_recv + delta;
3062 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", ack);
3063 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3064 " last pid %u, last ack %u, qmax %u, q %u\n",
3065 prev_fc->last_pid_recv, prev_fc->last_ack_sent,
3066 next_fc->queue_max, next_fc->queue_n);
3067 if (ack == prev_fc->last_ack_sent)
3069 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not needed\n");
3073 prev_fc->last_ack_sent = ack;
3074 send_ack (c, ack, fwd);
3079 * Modify the mesh message TID from global to local and send to client.
3081 * @param ch Channel on which to send the message.
3082 * @param msg Message to modify and send.
3083 * @param c Client to send to.
3084 * @param tid Tunnel ID to use (c can be both owner and client).
3087 channel_send_client_to_tid (struct MeshChannel *ch,
3088 const struct GNUNET_MESH_Data *msg,
3089 struct MeshClient *c, MESH_ChannelNumber id)
3091 struct GNUNET_MESH_LocalData *copy;
3092 uint16_t size = ntohs (msg->header.size) - sizeof (struct GNUNET_MESH_Data);
3093 char cbuf[size + sizeof (struct GNUNET_MESH_LocalData)];
3095 if (size < sizeof (struct GNUNET_MessageHeader))
3097 GNUNET_break_op (0);
3105 copy = (struct GNUNET_MESH_LocalData *) cbuf;
3106 memcpy (©[1], &msg[1], size);
3107 copy->header.size = htons (sizeof (struct GNUNET_MESH_LocalData) + size);
3108 copy->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA);
3109 copy->id = htonl (id);
3110 GNUNET_SERVER_notification_context_unicast (nc, c->handle,
3111 ©->header, GNUNET_NO);
3115 * Modify the data message ID from global to local and send to client.
3117 * @param ch Channel on which to send the message.
3118 * @param msg Message to modify and send.
3119 * @param fwd Forward?
3122 channel_send_client_data (struct MeshChannel *ch,
3123 const struct GNUNET_MESH_Data *msg,
3127 channel_send_client_to_tid (ch, msg, ch->dest, ch->lid_dest);
3129 channel_send_client_to_tid (ch, msg, ch->root, ch->lid_root);
3134 * Send a buffered message to the client, for in order delivery or
3135 * as result of client ACK.
3137 * @param ch Channel on which to empty the message buffer.
3138 * @param c Client to send to.
3139 * @param rel Reliability structure to corresponding peer.
3140 * If rel == bck_rel, this is FWD data.
3143 channel_send_client_buffered_data (struct MeshChannel *ch,
3144 struct MeshClient *c,
3145 struct MeshChannelReliability *rel)
3147 struct MeshReliableMessage *copy;
3150 if (GNUNET_NO == rel->client_ready)
3152 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client not ready\n");
3156 mid = rel == ch->bck_rel ? &ch->mid_recv_fwd : &ch->mid_recv_bck;
3158 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data\n");
3159 copy = rel->head_recv;
3162 if (copy->mid == *mid || GNUNET_NO == ch->reliable)
3164 struct GNUNET_MESH_Data *msg = (struct GNUNET_MESH_Data *) ©[1];
3166 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3167 " have %u! now expecting %u\n",
3168 copy->mid, *mid + 1);
3169 channel_send_client_data (ch, msg, (rel == ch->bck_rel));
3172 GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
3177 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3178 " reliable && don't have %u, next is %u\n",
3184 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data END\n");
3189 * We have received a message out of order, or the client is not ready.
3190 * Buffer it until we receive an ACK from the client or the missing
3191 * message from the channel.
3193 * @param msg Message to buffer.
3194 * @param rel Reliability data to the corresponding direction.
3197 channel_rel_add_buffered_data (const struct GNUNET_MESH_Data *msg,
3198 struct MeshChannelReliability *rel)
3200 struct MeshReliableMessage *copy;
3201 struct MeshReliableMessage *prev;
3205 size = ntohs (msg->header.size);
3206 mid = ntohl (msg->mid);
3207 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data %u\n", mid);
3209 copy = GNUNET_malloc (sizeof (*copy) + size);
3212 memcpy (©[1], msg, size);
3216 // FIXME do something better than O(n), although n < 64...
3217 // FIXME start from the end (most messages are the latest ones)
3218 for (prev = rel->head_recv; NULL != prev; prev = prev->next)
3220 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " prev %u\n", prev->mid);
3221 if (GMC_is_pid_bigger (prev->mid, mid))
3223 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " bingo!\n");
3224 GNUNET_CONTAINER_DLL_insert_before (rel->head_recv, rel->tail_recv,
3229 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " insert at tail!\n");
3230 GNUNET_CONTAINER_DLL_insert_tail (rel->head_recv, rel->tail_recv, copy);
3231 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data END\n");
3236 * Destroy a reliable message after it has been acknowledged, either by
3237 * direct mid ACK or bitfield. Updates the appropriate data structures and
3238 * timers and frees all memory.
3240 * @param copy Message that is no longer needed: remote peer got it.
3243 rel_message_free (struct MeshReliableMessage *copy)
3245 struct MeshChannelReliability *rel;
3246 struct GNUNET_TIME_Relative time;
3249 time = GNUNET_TIME_absolute_get_duration (copy->timestamp);
3250 rel->expected_delay.rel_value_us *= 7;
3251 rel->expected_delay.rel_value_us += time.rel_value_us;
3252 rel->expected_delay.rel_value_us /= 8;
3254 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Freeing %u\n", copy->mid);
3255 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " n_sent %u\n", rel->n_sent);
3256 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! took %s\n",
3257 GNUNET_STRINGS_relative_time_to_string (time, GNUNET_NO));
3258 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! new expected delay %s\n",
3259 GNUNET_STRINGS_relative_time_to_string (rel->expected_delay,
3261 rel->retry_timer = rel->expected_delay;
3262 GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
3268 * Destroy all reliable messages queued for a channel,
3269 * during a channel destruction.
3270 * Frees the reliability structure itself.
3272 * @param rel Reliability data for a channel.
3275 channel_rel_free_all (struct MeshChannelReliability *rel)
3277 struct MeshReliableMessage *copy;
3278 struct MeshReliableMessage *next;
3283 for (copy = rel->head_recv; NULL != copy; copy = next)
3286 GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
3289 for (copy = rel->head_sent; NULL != copy; copy = next)
3292 GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
3295 if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
3296 GNUNET_SCHEDULER_cancel (rel->retry_task);
3302 * Mark future messages as ACK'd.
3304 * @param rel Reliability data.
3305 * @param msg DataACK message with a bitfield of future ACK'd messages.
3308 channel_rel_free_sent (struct MeshChannelReliability *rel,
3309 const struct GNUNET_MESH_DataACK *msg)
3311 struct MeshReliableMessage *copy;
3312 struct MeshReliableMessage *next;
3319 bitfield = msg->futures;
3320 mid = ntohl (msg->mid);
3321 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3322 "free_sent_reliable %u %llX\n",
3324 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3325 " rel %p, head %p\n",
3326 rel, rel->head_sent);
3327 for (i = 0, copy = rel->head_sent;
3328 i < 64 && NULL != copy && 0 != bitfield;
3331 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3332 " trying bit %u (mid %u)\n",
3335 if (0 == (bitfield & mask))
3338 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " set!\n");
3339 /* Bit was set, clear the bit from the bitfield */
3342 /* The i-th bit was set. Do we have that copy? */
3343 /* Skip copies with mid < target */
3344 target = mid + i + 1;
3345 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " target %u\n", target);
3346 while (NULL != copy && GMC_is_pid_bigger (target, copy->mid))
3349 /* Did we run out of copies? (previously freed, it's ok) */
3352 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "run out of copies...\n");
3356 /* Did we overshoot the target? (previously freed, it's ok) */
3357 if (GMC_is_pid_bigger (copy->mid, target))
3359 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " next copy %u\n", copy->mid);
3363 /* Now copy->mid == target, free it */
3365 rel_message_free (copy);
3368 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "free_sent_reliable END\n");
3373 * We haven't received an ACK after a certain time: restransmit the message.
3375 * @param cls Closure (MeshReliableMessage with the message to restransmit)
3376 * @param tc TaskContext.
3379 channel_retransmit_message (void *cls,
3380 const struct GNUNET_SCHEDULER_TaskContext *tc)
3382 struct MeshChannelReliability *rel = cls;
3383 struct MeshReliableMessage *copy;
3384 struct MeshPeerQueue *q;
3385 struct MeshChannel *ch;
3386 struct MeshConnection *c;
3387 struct GNUNET_MESH_Data *payload;
3388 struct MeshPeer *hop;
3391 rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
3392 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3396 copy = rel->head_sent;
3403 /* Search the message to be retransmitted in the outgoing queue.
3404 * Check only the queue for the connection that is going to be used,
3405 * if the message is stuck in some other connection's queue we shouldn't
3407 * - cancelling it and sending the new one doesn't guarantee it's delivery,
3408 * the old connection could be temporary stalled or the queue happened to
3409 * be long at time of insertion.
3410 * - not sending the new one could cause terrible delays the old connection
3413 payload = (struct GNUNET_MESH_Data *) ©[1];
3414 fwd = (rel == ch->fwd_rel);
3415 c = tunnel_get_connection (ch->t, fwd);
3416 hop = connection_get_hop (c, fwd);
3417 for (q = hop->queue_head; NULL != q; q = q->next)
3419 if (ntohs (payload->header.type) == q->type && ch == q->ch)
3421 struct GNUNET_MESH_Data *queued_data = q->cls;
3423 if (queued_data->mid == payload->mid)
3428 /* Message not found in the queue that we are going to use. */
3431 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! RETRANSMIT %u\n", copy->mid);
3433 send_prebuilt_message_channel (&payload->header, ch, ch->fwd_rel == rel);
3434 GNUNET_STATISTICS_update (stats, "# data retransmitted", 1, GNUNET_NO);
3438 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! ALREADY IN QUEUE %u\n", copy->mid);
3441 rel->retry_timer = GNUNET_TIME_STD_BACKOFF (rel->retry_timer);
3442 rel->retry_task = GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
3443 &channel_retransmit_message,
3450 * Send ACK on one or more connections due to buffer space to the client.
3453 channel_send_ack (struct MeshChannel *ch, uint32_t buffer, int fwd)
3455 struct MeshTunnel2 *t = ch->t;
3456 struct MeshConnection *c;
3457 struct MeshFlowControl *fc;
3462 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3463 "Channel send %s ack on %s:%X\n",
3464 fwd ? "FWD" : "BCK", GNUNET_h2s (&ch->t->id), ch->gid);
3466 /* Count connections, how many messages are already allowed */
3467 for (cs = 0, allowed = 0, c = t->connection_head; NULL != c; c = c->next)
3469 fc = fwd ? &c->fwd_fc : &c->bck_fc;
3470 if (GMC_is_pid_bigger(fc->last_pid_recv, fc->last_ack_sent))
3475 allowed += fc->last_ack_sent - fc->last_pid_recv;
3479 /* Make sure there is no overflow */
3480 if (allowed > buffer)
3486 /* Authorize connections to send more data */
3487 to_allow = buffer - allowed;
3488 for (c = t->connection_head; NULL != c && to_allow > 0; c = c->next)
3490 fc = fwd ? &c->fwd_fc : &c->bck_fc;
3491 if (fc->last_ack_sent - fc->last_pid_recv > 64 / 3)
3495 send_ack (c, fc->last_ack_sent + 1, fwd);
3499 GNUNET_break (to_allow == 0);
3504 * Send keepalive packets for a connection.
3506 * @param c Connection to keep alive..
3507 * @param fwd Is this a FWD keepalive? (owner -> dest).
3510 connection_keepalive (struct MeshConnection *c, int fwd)
3512 struct GNUNET_MESH_ConnectionKeepAlive *msg;
3513 size_t size = sizeof (struct GNUNET_MESH_ConnectionKeepAlive);
3517 type = fwd ? GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE :
3518 GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE;
3520 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3521 "sending %s keepalive for connection %s[%d]\n",
3522 fwd ? "FWD" : "BCK",
3523 peer2s (c->t->peer),
3526 msg = (struct GNUNET_MESH_ConnectionKeepAlive *) cbuf;
3527 msg->header.size = htons (size);
3528 msg->header.type = htons (type);
3529 msg->cid = htonl (c->id);
3530 msg->tid = c->t->id;
3532 send_prebuilt_message_connection (&msg->header, c, NULL, fwd);
3537 * Send CONNECTION_{CREATE/ACK} packets for a connection.
3539 * @param c Connection for which to send the message.
3540 * @param fwd If GNUNET_YES, send CREATE, otherwise send ACK.
3543 connection_recreate (struct MeshConnection *c, int fwd)
3545 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "sending connection recreate\n");
3547 send_connection_create (c);
3549 send_connection_ack (c, GNUNET_NO);
3554 * Generic connection timer management.
3555 * Depending on the role of the peer in the connection will send the
3556 * appropriate message (build or keepalive)
3558 * @param c Conncetion to maintain.
3559 * @param fwd Is FWD?
3562 connection_maintain (struct MeshConnection *c, int fwd)
3564 if (MESH_TUNNEL_SEARCHING == c->t->state)
3566 /* TODO DHT GET with RO_BART */
3571 case MESH_CONNECTION_NEW:
3573 case MESH_CONNECTION_SENT:
3574 connection_recreate (c, fwd);
3576 case MESH_CONNECTION_READY:
3577 connection_keepalive (c, fwd);
3586 connection_fwd_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3588 struct MeshConnection *c = cls;
3590 c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
3591 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3594 connection_maintain (c, GNUNET_YES);
3595 c->fwd_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
3596 &connection_fwd_keepalive,
3602 connection_bck_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3604 struct MeshConnection *c = cls;
3606 c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
3607 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3610 connection_maintain (c, GNUNET_NO);
3611 c->bck_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
3612 &connection_bck_keepalive,
3618 * Send a message to all peers in this connection that the connection
3619 * is no longer valid.
3621 * If some peer should not receive the message, it should be zero'ed out
3622 * before calling this function.
3624 * @param c The connection whose peers to notify.
3627 connection_send_destroy (struct MeshConnection *c)
3629 struct GNUNET_MESH_ConnectionDestroy msg;
3631 msg.header.size = htons (sizeof (msg));
3632 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);;
3633 msg.cid = htonl (c->id);
3635 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3636 " sending connection destroy for connection %s[%X]\n",
3637 peer2s (c->t->peer),
3640 send_prebuilt_message_connection (&msg.header, c, NULL, GNUNET_YES);
3641 send_prebuilt_message_connection (&msg.header, c, NULL, GNUNET_NO);
3642 c->destroy = GNUNET_YES;
3647 * Send a message to all clients (local and remote) of this channel
3648 * notifying that the channel is no longer valid.
3650 * If some peer or client should not receive the message,
3651 * should be zero'ed out before calling this function.
3653 * @param ch The channel whose clients to notify.
3656 channel_send_destroy (struct MeshChannel *ch)
3658 struct GNUNET_MESH_ChannelDestroy msg;
3660 msg.header.size = htons (sizeof (msg));
3661 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY);
3662 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3663 " sending channel destroy for channel %s:%X\n",
3664 peer2s (ch->t->peer),
3667 if (NULL != ch->root)
3669 msg.chid = htonl (ch->lid_root);
3670 send_local_channel_destroy (ch, GNUNET_NO);
3674 msg.chid = htonl (ch->gid);
3675 send_prebuilt_message_channel (&msg.header, ch, GNUNET_NO);
3678 if (NULL != ch->dest)
3680 msg.chid = htonl (ch->lid_dest);
3681 send_local_channel_destroy (ch, GNUNET_YES);
3685 msg.chid = htonl (ch->gid);
3686 send_prebuilt_message_channel (&msg.header, ch, GNUNET_YES);
3694 * @param tid Tunnel ID.
3696 static struct MeshTunnel2 *
3697 tunnel_new (const struct GNUNET_HashCode *tid)
3699 struct MeshTunnel2 *t;
3701 t = GNUNET_new (struct MeshTunnel2);
3705 GNUNET_CONTAINER_multihashmap_put (tunnels, tid, t,
3706 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3720 * @param tid Tunnel ID.
3722 static struct MeshTunnel2 *
3723 tunnel_get (const struct GNUNET_HashCode *tid)
3725 return GNUNET_CONTAINER_multihashmap_get (tunnels, tid);
3730 * Add a connection to a tunnel.
3733 * @param c Connection.
3736 tunnel_add_connection (struct MeshTunnel2 *t, struct MeshConnection *c)
3739 GNUNET_CONTAINER_DLL_insert_tail (t->connection_head, t->connection_tail, c);
3744 * Initialize a Flow Control structure to the initial state.
3746 * @param fc Flow Control structure to initialize.
3749 fc_init (struct MeshFlowControl *fc)
3751 fc->last_pid_sent = (uint32_t) -1; /* Next (expected) = 0 */
3752 fc->last_pid_recv = (uint32_t) -1;
3753 fc->last_ack_sent = (uint32_t) 0;
3754 fc->last_ack_recv = (uint32_t) 0;
3755 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
3756 fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
3758 fc->queue_max = (max_msgs_queue / max_connections) + 1;
3762 static struct MeshConnection *
3763 connection_new (struct GNUNET_HashCode *tid, uint32_t cid)
3765 struct MeshConnection *c;
3766 struct MeshTunnel2 *t;
3768 t = tunnel_get (tid);
3771 t = tunnel_new (tid);
3779 c = GNUNET_new (struct MeshConnection);
3781 fc_init (&c->fwd_fc);
3782 fc_init (&c->bck_fc);
3785 tunnel_add_connection (t, c);
3792 * Find a connection.
3794 * @param tid Tunnel ID.
3795 * @param cid Connection ID.
3797 static struct MeshConnection *
3798 connection_get (const struct GNUNET_HashCode *tid, uint32_t cid)
3800 struct MeshConnection *c;
3801 struct MeshTunnel2 *t;
3803 t = tunnel_get (tid);
3806 for (c = t->connection_head; NULL != c; c = c->next)
3815 connection_destroy (struct MeshConnection *c)
3817 struct MeshPeer *peer;
3822 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying connection %s[%X]\n",
3823 peer2s (c->t->peer),
3826 /* Cancel all traffic */
3827 connection_cancel_queues (c, GNUNET_YES);
3828 connection_cancel_queues (c, GNUNET_NO);
3830 /* Cancel maintainance task (keepalive/timeout) */
3831 if (GNUNET_SCHEDULER_NO_TASK != c->fwd_maintenance_task)
3832 GNUNET_SCHEDULER_cancel (c->fwd_maintenance_task);
3833 if (GNUNET_SCHEDULER_NO_TASK != c->bck_maintenance_task)
3834 GNUNET_SCHEDULER_cancel (c->bck_maintenance_task);
3836 /* Deregister from neighbors */
3837 peer = connection_get_next_hop (c);
3839 GNUNET_CONTAINER_multihashmap_remove (peer->connections, &c->t->id, c);
3840 peer = connection_get_prev_hop (c);
3842 GNUNET_CONTAINER_multihashmap_remove (peer->connections, &c->t->id, c);
3845 GNUNET_STATISTICS_update (stats, "# connections", -1, GNUNET_NO);
3846 GNUNET_CONTAINER_DLL_remove (c->t->connection_head, c->t->connection_tail, c);
3852 tunnel_destroy (struct MeshTunnel2 *t)
3854 struct MeshConnection *c;
3855 struct MeshConnection *next;
3860 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n",
3863 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &t->id, t))
3866 for (c = t->connection_head; NULL != c; c = next)
3869 connection_destroy (c);
3872 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
3879 * Tunnel is empty: destroy it.
3881 * Notifies all connections about the destruction.
3883 * @param t Tunnel to destroy.
3886 tunnel_destroy_empty (struct MeshTunnel2 *t)
3888 struct MeshConnection *c;
3890 for (c = t->connection_head; NULL != c; c = c->next)
3892 if (GNUNET_NO == c->destroy)
3893 connection_send_destroy (c);
3896 if (0 == t->pending_messages)
3899 t->destroy = GNUNET_YES;
3904 * Destroy tunnel if empty (no more channels).
3906 * @param t Tunnel to destroy if empty.
3909 tunnel_destroy_if_empty (struct MeshTunnel2 *t)
3911 if (NULL != t->channel_head)
3914 tunnel_destroy_empty (t);
3919 * Destroy a channel and free all resources.
3921 * @param ch Channel to destroy.
3924 channel_destroy (struct MeshChannel *ch)
3926 struct MeshClient *c;
3934 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap32_remove (c->own_channels,
3945 GNUNET_CONTAINER_multihashmap32_remove (c->incoming_channels,
3952 channel_rel_free_all (ch->fwd_rel);
3953 channel_rel_free_all (ch->bck_rel);
3955 GNUNET_CONTAINER_DLL_remove (ch->t->channel_head, ch->t->channel_tail, ch);
3956 GNUNET_STATISTICS_update (stats, "# channels", -1, GNUNET_NO);
3962 * Create a new channel.
3964 * @param t Tunnel this channel is in.
3965 * @param owner Client that owns the channel, NULL for foreign channels.
3966 * @param lid_root Local ID for root client.
3968 * @return A new initialized channel. NULL on error.
3970 static struct MeshChannel *
3971 channel_new (struct MeshTunnel2 *t,
3972 struct MeshClient *owner, MESH_ChannelNumber lid_root)
3974 struct MeshChannel *ch;
3976 ch = GNUNET_new (struct MeshChannel);
3978 ch->lid_root = lid_root;
3981 GNUNET_CONTAINER_DLL_insert (t->channel_head, t->channel_tail, ch);
3983 GNUNET_STATISTICS_update (stats, "# channels", 1, GNUNET_NO);
3987 while (NULL != channel_get (t, t->next_chid))
3988 t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
3989 ch->gid = t->next_chid;
3990 t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
3993 GNUNET_CONTAINER_multihashmap32_put (owner->own_channels, lid_root, ch,
3994 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
3997 channel_destroy (ch);
3998 GNUNET_SERVER_receive_done (owner->handle, GNUNET_SYSERR);
4008 * Set options in a channel, extracted from a bit flag field
4010 * @param ch Channel to set options to.
4011 * @param options Bit array in host byte order.
4014 channel_set_options (struct MeshChannel *ch, uint32_t options)
4016 ch->nobuffer = (options & GNUNET_MESH_OPTION_NOBUFFER) != 0 ?
4017 GNUNET_YES : GNUNET_NO;
4018 ch->reliable = (options & GNUNET_MESH_OPTION_RELIABLE) != 0 ?
4019 GNUNET_YES : GNUNET_NO;
4024 * Iterator for deleting each channel whose client endpoint disconnected.
4026 * @param cls Closure (client that has disconnected).
4027 * @param key The local channel id (used to access the hashmap).
4028 * @param value The value stored at the key (channel to destroy).
4030 * @return GNUNET_OK, keep iterating.
4033 channel_destroy_iterator (void *cls,
4037 struct MeshChannel *ch = value;
4038 struct MeshClient *c = cls;
4039 struct MeshTunnel2 *t;
4041 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4042 " Channel %X (%X / %X) destroy, due to client %u shutdown.\n",
4043 ch->gid, ch->lid_root, ch->lid_dest, c->id);
4047 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is destination.\n", c->id);
4052 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is owner.\n", c->id);
4057 channel_send_destroy (ch);
4058 channel_destroy (ch);
4059 tunnel_destroy_if_empty (t);
4066 * Remove client's ports from the global hashmap on disconnect.
4068 * @param cls Closure (unused).
4070 * @param value Client structure.
4072 * @return GNUNET_OK, keep iterating.
4075 client_release_ports (void *cls,
4081 res = GNUNET_CONTAINER_multihashmap32_remove (ports, key, value);
4082 if (GNUNET_YES != res)
4085 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4086 "Port %u by client %p was not registered.\n",
4094 * Timeout function due to lack of keepalive/traffic from the owner.
4095 * Destroys connection if called.
4097 * @param cls Closure (connection to destroy).
4098 * @param tc TaskContext.
4101 connection_fwd_timeout (void *cls,
4102 const struct GNUNET_SCHEDULER_TaskContext *tc)
4104 struct MeshConnection *c = cls;
4106 c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4107 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4109 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4110 "Connection %s[%X] FWD timed out. Destroying.\n",
4111 peer2s (c->t->peer),
4114 if (connection_is_terminal (c, GNUNET_NO)) /* If local, leave. */
4117 connection_destroy (c);
4122 * Timeout function due to lack of keepalive/traffic from the destination.
4123 * Destroys connection if called.
4125 * @param cls Closure (connection to destroy).
4126 * @param tc TaskContext
4129 connection_bck_timeout (void *cls,
4130 const struct GNUNET_SCHEDULER_TaskContext *tc)
4132 struct MeshConnection *c = cls;
4134 c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4135 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4138 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4139 "Connection %s[%X] FWD timed out. Destroying.\n",
4140 peer2s (c->t->peer),
4143 if (connection_is_terminal (c, GNUNET_YES)) /* If local, leave. */
4146 connection_destroy (c);
4151 * Resets the connection timeout task, some other message has done the
4153 * - For the first peer on the direction this means to send
4154 * a keepalive or a path confirmation message (either create or ACK).
4155 * - For all other peers, this means to destroy the connection,
4156 * due to lack of activity.
4157 * Starts the tiemout if no timeout was running (connection just created).
4159 * @param c Connection whose timeout to reset.
4160 * @param fwd Is this forward?
4162 * TODO use heap to improve efficiency of scheduler.
4165 connection_reset_timeout (struct MeshConnection *c, int fwd)
4167 GNUNET_SCHEDULER_TaskIdentifier *ti;
4168 GNUNET_SCHEDULER_Task f;
4170 ti = fwd ? &c->fwd_maintenance_task : &c->bck_maintenance_task;
4172 if (GNUNET_SCHEDULER_NO_TASK != *ti)
4173 GNUNET_SCHEDULER_cancel (*ti);
4175 if (connection_is_terminal (c, !fwd)) /* Endpoint */
4177 f = fwd ? &connection_fwd_keepalive : &connection_bck_keepalive;
4178 *ti = GNUNET_SCHEDULER_add_delayed (refresh_connection_time, f, c);
4182 struct GNUNET_TIME_Relative delay;
4184 delay = GNUNET_TIME_relative_multiply (refresh_connection_time, 4);
4185 f = fwd ? &connection_fwd_timeout : &connection_bck_timeout;
4186 *ti = GNUNET_SCHEDULER_add_delayed (delay, f, c);
4192 * Iterator to notify all connections of a broken link. Mark connections
4193 * to destroy after all traffic has been sent.
4195 * @param cls Closure (peer disconnected).
4196 * @param key Current key code (tid).
4197 * @param value Value in the hash map (connection).
4199 * @return GNUNET_YES if we should continue to iterate,
4203 connection_broken (void *cls,
4204 const struct GNUNET_HashCode *key,
4207 struct MeshPeer *peer = cls;
4208 struct MeshConnection *c = value;
4209 struct GNUNET_MESH_ConnectionBroken msg;
4212 fwd = peer == connection_get_prev_hop (c);
4213 connection_cancel_queues (c, !fwd);
4215 msg.header.size = htons (sizeof (struct GNUNET_MESH_ConnectionBroken));
4216 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN);
4217 msg.cid = htonl (c->id);
4219 msg.peer1 = my_full_id;
4220 msg.peer2 = *GNUNET_PEER_resolve2 (peer->id);
4221 send_prebuilt_message_connection (&msg.header, c, NULL, fwd);
4222 c->destroy = GNUNET_YES;
4227 /******************************************************************************/
4228 /**************** MESH NETWORK HANDLER HELPERS ***********************/
4229 /******************************************************************************/
4232 * Free a transmission that was already queued with all resources
4233 * associated to the request.
4235 * @param queue Queue handler to cancel.
4236 * @param clear_cls Is it necessary to free associated cls?
4239 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
4241 struct MeshPeer *peer;
4242 struct MeshFlowControl *fc;
4247 GNUNET_assert (NULL != queue->c);
4248 fc = fwd ? &queue->c->fwd_fc : &queue->c->bck_fc;
4250 if (GNUNET_YES == clear_cls)
4252 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type %s\n",
4253 GNUNET_MESH_DEBUG_M2S (queue->type));
4254 switch (queue->type)
4256 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
4257 case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
4258 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "destroying a DESTROY message\n");
4259 GNUNET_break (GNUNET_YES == queue->c->destroy);
4261 case GNUNET_MESSAGE_TYPE_MESH_FWD:
4262 case GNUNET_MESSAGE_TYPE_MESH_BCK:
4263 case GNUNET_MESSAGE_TYPE_MESH_ACK:
4264 case GNUNET_MESSAGE_TYPE_MESH_POLL:
4265 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
4266 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
4267 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " prebuilt message\n");;
4268 GNUNET_free_non_null (queue->cls);
4273 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, " type %s unknown!\n",
4274 GNUNET_MESH_DEBUG_M2S (queue->type));
4278 GNUNET_CONTAINER_DLL_remove (peer->queue_head, peer->queue_tail, queue);
4282 if (NULL != queue->c)
4284 queue->c->pending_messages--;
4285 if (NULL != queue->c->t)
4287 queue->c->t->pending_messages--;
4291 GNUNET_free (queue);
4296 queue_send (void *cls, size_t size, void *buf)
4298 struct MeshPeer *peer = cls;
4299 struct MeshFlowControl *fc;
4300 struct MeshConnection *c;
4301 struct GNUNET_MessageHeader *msg;
4302 struct MeshPeerQueue *queue;
4303 struct MeshTunnel2 *t;
4304 const struct GNUNET_PeerIdentity *dst_id;
4310 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Queue send\n");
4312 if (NULL == buf || 0 == size)
4314 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Buffer size 0.\n");
4319 queue = peer_get_first_message (peer);
4322 GNUNET_break (0); /* Core tmt_rdy should've been canceled */
4327 fc = fwd ? &c->fwd_fc : &c->bck_fc;
4330 dst_id = GNUNET_PEER_resolve2 (peer->id);
4331 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* towards %s\n", GNUNET_i2s (dst_id));
4332 /* Check if buffer size is enough for the message */
4333 if (queue->size > size)
4335 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* not enough room, reissue\n");
4336 peer->core_transmit =
4337 GNUNET_CORE_notify_transmit_ready (core_handle,
4340 GNUNET_TIME_UNIT_FOREVER_REL,
4347 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* size ok\n");
4349 t = (NULL != c) ? c->t : NULL;
4353 switch (queue->type)
4355 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
4356 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
4357 case GNUNET_MESSAGE_TYPE_MESH_FWD:
4358 case GNUNET_MESSAGE_TYPE_MESH_BCK:
4359 case GNUNET_MESSAGE_TYPE_MESH_ACK:
4360 case GNUNET_MESSAGE_TYPE_MESH_POLL:
4361 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4363 GNUNET_MESH_DEBUG_M2S (queue->type));
4365 case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4366 case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4367 data_size = send_core_data_raw (queue->cls, size, buf);
4368 msg = (struct GNUNET_MessageHeader *) buf;
4369 type = ntohs (msg->type);
4371 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
4372 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* path create\n");
4373 if (connection_is_terminal (c, GNUNET_NO))
4374 data_size = send_core_connection_create (queue->c, size, buf);
4376 data_size = send_core_data_raw (queue->cls, size, buf);
4378 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
4379 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* path ack\n");
4380 if (connection_is_terminal (c, GNUNET_YES))
4381 data_size = send_core_connection_ack (queue->c, size, buf);
4383 data_size = send_core_data_raw (queue->cls, size, buf);
4387 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "* type unknown: %u\n",
4392 if (0 < drop_percent &&
4393 GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 101) < drop_percent)
4395 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4396 "Dropping message of type %s\n",
4397 GNUNET_MESH_DEBUG_M2S (queue->type));
4400 /* Free queue, but cls was freed by send_core_* */
4401 queue_destroy (queue, GNUNET_NO);
4403 /* Send ACK if needed, after accounting for sent ID in fc->queue_n */
4406 case GNUNET_MESSAGE_TYPE_MESH_FWD:
4407 case GNUNET_MESSAGE_TYPE_MESH_BCK:
4408 pid = ntohl ( ((struct GNUNET_MESH_Encrypted *) buf)->pid );
4409 fc->last_pid_sent = pid;
4410 connection_send_ack (c, fwd);
4416 /* If more data in queue, send next */
4417 queue = peer_get_first_message (peer);
4420 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* more data!\n");
4421 if (NULL == peer->core_transmit) {
4422 peer->core_transmit =
4423 GNUNET_CORE_notify_transmit_ready(core_handle,
4426 GNUNET_TIME_UNIT_FOREVER_REL,
4434 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4435 "* tmt rdy called somewhere else\n");
4437 if (GNUNET_SCHEDULER_NO_TASK == fc->poll_task)
4439 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "* %s starting poll timeout\n");
4441 GNUNET_SCHEDULER_add_delayed (fc->poll_time, &connection_poll, fc);
4446 if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
4448 GNUNET_SCHEDULER_cancel (fc->poll_task);
4449 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
4454 c->pending_messages--;
4455 if (GNUNET_YES == c->destroy && 0 == c->pending_messages)
4457 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* destroying connection!\n");
4458 connection_destroy (c);
4464 t->pending_messages--;
4465 if (GNUNET_YES == t->destroy && 0 == t->pending_messages)
4467 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* destroying tunnel!\n");
4471 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Return %d\n", data_size);
4477 queue_add (void *cls, uint16_t type, size_t size,
4478 struct MeshConnection *c,
4479 struct MeshChannel *ch,
4482 struct MeshPeerQueue *queue;
4483 struct MeshFlowControl *fc;
4484 struct MeshPeer *dst;
4487 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4488 "queue add %s (%u bytes) on c %p, ch %p\n",
4489 GNUNET_MESH_DEBUG_M2S (type), size, c, ch);
4490 GNUNET_assert (NULL != c);
4492 fc = fwd ? &c->fwd_fc : &c->bck_fc;
4493 dst = fwd ? connection_get_next_hop (c) : connection_get_prev_hop (c);
4503 if (GNUNET_MESSAGE_TYPE_MESH_POLL == type ||
4504 GNUNET_MESSAGE_TYPE_MESH_ACK == type)
4508 ( (NULL != ch->root && GNUNET_MESSAGE_TYPE_MESH_FWD == type) ||
4509 (NULL != ch->dest && GNUNET_MESSAGE_TYPE_MESH_BCK == type) ))
4512 if (fc->queue_n >= fc->queue_max && 0 == priority)
4514 GNUNET_STATISTICS_update (stats, "# messages dropped (buffer full)",
4517 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4518 "queue full: %u/%u\n",
4519 fc->queue_n, fc->queue_max);
4520 return; /* Drop this message */
4523 if (GMC_is_pid_bigger (fc->last_pid_sent + 1, fc->last_ack_recv) &&
4524 GNUNET_SCHEDULER_NO_TASK == fc->poll_task)
4525 fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
4528 queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
4536 if (100 <= priority)
4537 GNUNET_CONTAINER_DLL_insert (dst->queue_head, dst->queue_tail, queue);
4539 GNUNET_CONTAINER_DLL_insert_tail (dst->queue_head, dst->queue_tail, queue);
4541 if (NULL == dst->core_transmit)
4543 dst->core_transmit =
4544 GNUNET_CORE_notify_transmit_ready (core_handle,
4547 GNUNET_TIME_UNIT_FOREVER_REL,
4548 GNUNET_PEER_resolve2 (dst->id),
4553 c->pending_messages++;
4554 c->t->pending_messages++;
4560 /******************************************************************************/
4561 /******************** MESH NETWORK HANDLERS **************************/
4562 /******************************************************************************/
4566 * Generic handler for mesh network payload traffic.
4568 * @param t Tunnel on which we got this message.
4569 * @param message Unencryted data message.
4570 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
4572 * @return GNUNET_OK to keep the connection open,
4573 * GNUNET_SYSERR to close it (signal serious error)
4576 handle_data (struct MeshTunnel2 *t, const struct GNUNET_MESH_Data *msg, int fwd)
4578 struct MeshChannelReliability *rel;
4579 struct MeshChannel *ch;
4580 struct MeshClient *c;
4587 size = ntohs (msg->header.size);
4589 sizeof (struct GNUNET_MESH_Data) +
4590 sizeof (struct GNUNET_MessageHeader))
4595 type = ntohs (msg->header.type);
4596 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message\n",
4597 GNUNET_MESH_DEBUG_M2S (type));
4598 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
4599 GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
4602 ch = channel_get (t, ntohl (msg->chid));
4605 GNUNET_STATISTICS_update (stats, "# data on unknown channel", 1, GNUNET_NO);
4606 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel unknown\n");
4610 /* Initialize FWD/BCK data */
4611 c = fwd ? ch->dest : ch->root;
4612 rel = fwd ? ch->bck_rel : ch->fwd_rel;
4613 mid_recv = fwd ? &ch->mid_recv_fwd : &ch->mid_recv_bck;
4621 tunnel_change_state (t, MESH_TUNNEL_READY);
4623 GNUNET_STATISTICS_update (stats, "# data received", 1, GNUNET_NO);
4625 mid = ntohl (msg->mid);
4626 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " mid %u\n", mid);
4628 if (GNUNET_NO == ch->reliable ||
4629 ( !GMC_is_pid_bigger (*mid_recv, mid) &&
4630 GMC_is_pid_bigger (*mid_recv + 64, mid) ) )
4632 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! RECV %u\n", mid);
4633 if (GNUNET_YES == ch->reliable)
4635 /* Is this the exact next expected messasge? */
4636 if (mid == *mid_recv)
4638 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "as expected\n");
4639 *mid_recv = *mid_recv + 1;
4640 channel_send_client_data (ch, msg, fwd);
4641 channel_send_client_buffered_data (ch, c, rel);
4645 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "save for later\n");
4646 channel_rel_add_buffered_data (msg, rel);
4649 else /* Tunnel unreliable, send to clients directly */
4651 channel_send_client_data (ch, msg, fwd);
4656 GNUNET_break_op (0);
4657 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4658 " MID %u not expected (%u - %u), dropping!\n",
4659 mid, *mid_recv, *mid_recv + 64);
4662 channel_send_data_ack (ch, fwd);
4667 * Handler for mesh network traffic end-to-end ACKs.
4669 * @param t Tunnel on which we got this message.
4670 * @param message Data message.
4671 * @param fwd Is this a fwd ACK? (dest->orig)
4673 * @return GNUNET_OK to keep the connection open,
4674 * GNUNET_SYSERR to close it (signal serious error)
4677 handle_data_ack (struct MeshTunnel2 *t,
4678 const struct GNUNET_MESH_DataACK *msg, int fwd)
4680 struct MeshChannelReliability *rel;
4681 struct MeshReliableMessage *copy;
4682 struct MeshReliableMessage *next;
4683 struct MeshChannel *ch;
4688 type = ntohs (msg->header.type);
4689 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a %s message!\n",
4690 GNUNET_MESH_DEBUG_M2S (type));
4691 ch = channel_get (t, ntohl (msg->chid));
4694 GNUNET_STATISTICS_update (stats, "# ack on unknown channel", 1, GNUNET_NO);
4697 ack = ntohl (msg->mid);
4698 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! %s ACK %u\n",
4699 (GNUNET_YES == fwd) ? "FWD" : "BCK", ack);
4701 if (GNUNET_YES == fwd)
4714 for (work = GNUNET_NO, copy = rel->head_sent; copy != NULL; copy = next)
4716 if (GMC_is_pid_bigger (copy->mid, ack))
4718 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! head %u, out!\n", copy->mid);
4719 channel_rel_free_sent (rel, msg);
4723 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! id %u\n", copy->mid);
4725 rel_message_free (copy);
4727 /* ACK client if needed */
4728 // channel_send_ack (t, type, GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK == type);
4730 /* If some message was free'd, update the retransmission delay*/
4731 if (GNUNET_YES == work)
4733 if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
4735 GNUNET_SCHEDULER_cancel (rel->retry_task);
4736 if (NULL == rel->head_sent)
4738 rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
4742 struct GNUNET_TIME_Absolute new_target;
4743 struct GNUNET_TIME_Relative delay;
4745 delay = GNUNET_TIME_relative_multiply (rel->retry_timer,
4746 MESH_RETRANSMIT_MARGIN);
4747 new_target = GNUNET_TIME_absolute_add (rel->head_sent->timestamp,
4749 delay = GNUNET_TIME_absolute_get_remaining (new_target);
4751 GNUNET_SCHEDULER_add_delayed (delay,
4752 &channel_retransmit_message,
4764 * Core handler for connection creation.
4766 * @param cls Closure (unused).
4767 * @param peer Sender (neighbor).
4768 * @param message Message.
4770 * @return GNUNET_OK to keep the connection open,
4771 * GNUNET_SYSERR to close it (signal serious error)
4774 handle_mesh_connection_create (void *cls,
4775 const struct GNUNET_PeerIdentity *peer,
4776 const struct GNUNET_MessageHeader *message)
4778 struct GNUNET_MESH_ConnectionCreate *msg;
4779 struct GNUNET_PeerIdentity *id;
4780 struct GNUNET_HashCode *tid;
4781 struct MeshPeerPath *path;
4782 struct MeshPeer *dest_peer;
4783 struct MeshPeer *orig_peer;
4784 struct MeshConnection *c;
4785 unsigned int own_pos;
4790 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection create msg\n");
4793 size = ntohs (message->size);
4794 if (size < sizeof (struct GNUNET_MESH_ConnectionCreate))
4796 GNUNET_break_op (0);
4800 /* Calculate hops */
4801 size -= sizeof (struct GNUNET_MESH_ConnectionCreate);
4802 if (size % sizeof (struct GNUNET_PeerIdentity))
4804 GNUNET_break_op (0);
4807 size /= sizeof (struct GNUNET_PeerIdentity);
4810 GNUNET_break_op (0);
4813 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " path has %u hops.\n", size);
4815 /* Get parameters */
4816 msg = (struct GNUNET_MESH_ConnectionCreate *) message;
4817 cid = ntohl (msg->cid);
4819 id = (struct GNUNET_PeerIdentity *) &msg[1];
4820 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4821 " connection %s[%X] (%s).\n",
4822 GNUNET_h2s (tid), cid, GNUNET_i2s (id));
4824 /* Create connection */
4825 c = connection_get (tid, cid);
4828 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Creating connection\n");
4829 c = connection_new (tid, cid);
4833 connection_reset_timeout (c, GNUNET_YES);
4834 tunnel_change_state (c->t, MESH_TUNNEL_WAITING);
4836 /* Remember peers */
4837 dest_peer = peer_get (&id[size - 1]);
4838 orig_peer = peer_get (&id[0]);
4841 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Creating path...\n");
4842 path = path_new (size);
4844 for (i = 0; i < size; i++)
4846 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... adding %s\n",
4847 GNUNET_i2s (&id[i]));
4848 path->peers[i] = GNUNET_PEER_intern (&id[i]);
4849 if (path->peers[i] == myid)
4852 if (own_pos == 0 && path->peers[own_pos] != myid)
4854 /* create path: self not found in path through self */
4855 GNUNET_break_op (0);
4856 path_destroy (path);
4857 connection_destroy (c);
4860 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Own position: %u\n", own_pos);
4861 path_add_to_peers (path, GNUNET_NO);
4862 c->path = path_duplicate (path);
4863 c->own_pos = own_pos;
4865 /* Is it a connection to us? */
4866 if (own_pos == size - 1)
4868 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " It's for us!\n");
4869 peer_add_path_to_origin (orig_peer, path, GNUNET_YES);
4871 send_connection_ack (c, GNUNET_NO);
4873 /* Keep tunnel alive in direction dest->owner*/
4874 connection_reset_timeout (c, GNUNET_NO);
4878 /* It's for somebody else! Retransmit. */
4879 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Retransmitting.\n");
4880 peer_add_path (dest_peer, path_duplicate (path), GNUNET_NO);
4881 peer_add_path_to_origin (orig_peer, path, GNUNET_NO);
4882 send_prebuilt_message_connection (message, c, NULL, GNUNET_YES);
4889 * Core handler for path ACKs
4891 * @param cls closure
4892 * @param message message
4893 * @param peer peer identity this notification is about
4895 * @return GNUNET_OK to keep the connection open,
4896 * GNUNET_SYSERR to close it (signal serious error)
4899 handle_mesh_connection_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
4900 const struct GNUNET_MessageHeader *message)
4902 struct GNUNET_MESH_ConnectionACK *msg;
4903 struct MeshPeerPath *p;
4904 struct MeshConnection *c;
4907 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection ACK msg\n");
4908 msg = (struct GNUNET_MESH_ConnectionACK *) message;
4909 cid = ntohl(msg->cid);
4910 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " on connection %s[%X]\n",
4911 GNUNET_h2s (&msg->tid), cid);
4912 c = connection_get (&msg->tid, cid);
4915 GNUNET_STATISTICS_update (stats, "# control on unknown connection",
4917 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " don't know the connection!\n");
4921 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " via peer %s\n",
4924 /* Add path to peers? */
4928 path_add_to_peers (p, GNUNET_YES);
4934 connection_change_state (c, MESH_CONNECTION_READY);
4935 connection_reset_timeout (c, GNUNET_NO);
4936 if (MESH_TUNNEL_READY != c->t->state)
4937 tunnel_change_state (c->t, MESH_TUNNEL_READY);
4938 tunnel_send_queued_data (c->t, GNUNET_YES);
4940 /* Message for us? */
4941 if (connection_is_terminal (c, GNUNET_NO))
4943 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " It's for us!\n");
4944 if (3 <= tunnel_count_connections (c->t) && NULL != c->t->peer->dhtget)
4946 GNUNET_DHT_get_stop (c->t->peer->dhtget);
4947 c->t->peer->dhtget = NULL;
4949 //connection_send_ack (c, GNUNET_NO); /* FIXME */
4953 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " not for us, retransmitting...\n");
4954 send_prebuilt_message_connection (message, c, NULL, GNUNET_NO);
4960 * Core handler for notifications of broken paths
4962 * @param cls Closure (unused).
4963 * @param peer Peer identity of sending neighbor.
4964 * @param message Message.
4966 * @return GNUNET_OK to keep the connection open,
4967 * GNUNET_SYSERR to close it (signal serious error)
4970 handle_mesh_connection_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
4971 const struct GNUNET_MessageHeader *message)
4973 struct GNUNET_MESH_ConnectionBroken *msg;
4974 struct MeshConnection *c;
4976 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4977 "Received a CONNECTION BROKEN msg from %s\n", GNUNET_i2s (peer));
4978 msg = (struct GNUNET_MESH_ConnectionBroken *) message;
4979 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " regarding %s\n",
4980 GNUNET_i2s (&msg->peer1));
4981 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " regarding %s\n",
4982 GNUNET_i2s (&msg->peer2));
4983 c = connection_get (&msg->tid, ntohl (msg->cid));
4986 GNUNET_break_op (0);
4989 tunnel_notify_connection_broken (c->t, GNUNET_PEER_search (&msg->peer1),
4990 GNUNET_PEER_search (&msg->peer2));
4997 * Core handler for tunnel destruction
4999 * @param cls Closure (unused).
5000 * @param peer Peer identity of sending neighbor.
5001 * @param message Message.
5003 * @return GNUNET_OK to keep the connection open,
5004 * GNUNET_SYSERR to close it (signal serious error)
5007 handle_mesh_connection_destroy (void *cls,
5008 const struct GNUNET_PeerIdentity *peer,
5009 const struct GNUNET_MessageHeader *message)
5011 struct GNUNET_MESH_ConnectionDestroy *msg;
5012 struct MeshConnection *c;
5016 msg = (struct GNUNET_MESH_ConnectionDestroy *) message;
5017 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5018 "Got a CONNECTION DESTROY message from %s\n",
5020 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5021 " for connection %s[%X]\n",
5022 GNUNET_h2s (&msg->tid), ntohl (msg->cid));
5023 c = connection_get (&msg->tid, ntohl (msg->cid));
5026 /* Probably already got the message from another path,
5027 * destroyed the tunnel and retransmitted to children.
5030 GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
5034 id = GNUNET_PEER_search (peer);
5035 if (id == connection_get_prev_hop (c)->id)
5037 else if (id == connection_get_next_hop (c)->id)
5041 GNUNET_break_op (0);
5044 send_prebuilt_message_connection (message, c, NULL, fwd);
5045 c->destroy = GNUNET_YES;
5051 * Handler for channel create messages.
5053 * @param t Tunnel this channel is to be created in.
5054 * @param msg Message.
5055 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5057 * @return GNUNET_OK to keep the connection open,
5058 * GNUNET_SYSERR to close it (signal serious error)
5061 handle_channel_create (struct MeshTunnel2 *t,
5062 struct GNUNET_MESH_ChannelCreate *msg,
5065 MESH_ChannelNumber chid;
5066 struct MeshChannel *ch;
5067 struct MeshClient *c;
5069 /* Check message size */
5070 if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelCreate))
5072 GNUNET_break_op (0);
5076 /* Check if channel exists */
5077 chid = ntohl (msg->chid);
5078 ch = channel_get (t, chid);
5081 /* Probably a retransmission, safe to ignore */
5085 /* Find a destination client */
5086 c = GNUNET_CONTAINER_multihashmap32_get (ports, msg->port);
5089 /* TODO send reject */
5093 /* Create channel */
5094 ch = channel_new (t, NULL, 0);
5095 channel_set_options (ch, ntohl (msg->opt));
5096 channel_add_client (ch, c);
5097 if (GNUNET_YES == ch->reliable)
5099 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
5100 ch->bck_rel = GNUNET_malloc (sizeof (struct MeshChannelReliability));
5101 ch->bck_rel->ch = ch;
5102 ch->bck_rel->expected_delay = MESH_RETRANSMIT_TIME;
5105 send_local_channel_create (ch);
5112 * Handler for channel destroy messages.
5114 * @param t Tunnel this channel is to be destroyed of.
5115 * @param msg Message.
5116 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5118 * @return GNUNET_OK to keep the connection open,
5119 * GNUNET_SYSERR to close it (signal serious error)
5122 handle_channel_destroy (struct MeshTunnel2 *t,
5123 struct GNUNET_MESH_ChannelDestroy *msg,
5126 MESH_ChannelNumber chid;
5127 struct MeshChannel *ch;
5129 /* Check message size */
5130 if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelDestroy))
5132 GNUNET_break_op (0);
5136 /* Check if channel exists */
5137 chid = ntohl (msg->chid);
5138 ch = channel_get (t, chid);
5141 /* Probably a retransmission, safe to ignore */
5145 send_local_channel_destroy (ch, fwd);
5146 channel_destroy (ch);
5153 * Generic handler for mesh network encrypted traffic.
5155 * @param peer Peer identity this notification is about.
5156 * @param message Encrypted message.
5157 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5159 * @return GNUNET_OK to keep the connection open,
5160 * GNUNET_SYSERR to close it (signal serious error)
5163 handle_mesh_encrypted (const struct GNUNET_PeerIdentity *peer,
5164 const struct GNUNET_MESH_Encrypted *msg,
5167 struct MeshConnection *c;
5168 struct MeshTunnel2 *t;
5169 struct MeshPeer *neighbor;
5170 struct MeshFlowControl *fc;
5177 size = ntohs (msg->header.size);
5179 sizeof (struct GNUNET_MESH_Encrypted) +
5180 sizeof (struct GNUNET_MessageHeader))
5185 type = ntohs (msg->header.type);
5186 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message from %s\n",
5187 GNUNET_MESH_DEBUG_M2S (type), GNUNET_i2s (peer));
5189 /* Check connection */
5190 c = connection_get (&msg->tid, ntohl (msg->cid));
5193 GNUNET_STATISTICS_update (stats, "# unknown connection", 1, GNUNET_NO);
5194 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING connection unknown\n");
5198 fc = fwd ? &c->fwd_fc : &c->bck_fc;
5200 /* Check if origin is as expected */
5201 neighbor = connection_get_hop (c, fwd);
5202 if (peer_get (peer)->id != neighbor->id)
5204 GNUNET_break_op (0);
5209 pid = ntohl (msg->pid);
5210 if (GMC_is_pid_bigger (pid, fc->last_ack_sent))
5212 GNUNET_STATISTICS_update (stats, "# unsolicited message", 1, GNUNET_NO);
5213 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5214 "WARNING Received PID %u, (prev %u), ACK %u\n",
5215 pid, fc->last_pid_recv, fc->last_ack_sent);
5218 if (GNUNET_NO == GMC_is_pid_bigger (pid, fc->last_pid_recv))
5220 GNUNET_STATISTICS_update (stats, "# duplicate PID", 1, GNUNET_NO);
5221 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5222 " Pid %u not expected (%u+), dropping!\n",
5223 pid, fc->last_pid_recv + 1);
5226 if (MESH_CONNECTION_SENT == c->state)
5227 connection_change_state (c, MESH_CONNECTION_READY);
5228 connection_reset_timeout (c, fwd);
5229 fc->last_pid_recv = pid;
5231 /* Is this message for us? */
5232 if (connection_is_terminal (c, fwd))
5234 size_t dsize = size - sizeof (struct GNUNET_MESH_Encrypted);
5236 struct GNUNET_MessageHeader *msgh;
5238 /* TODO signature verification */
5239 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " it's for us!\n");
5240 GNUNET_STATISTICS_update (stats, "# messages received", 1, GNUNET_NO);
5242 fc->last_pid_recv = pid;
5243 tunnel_decrypt (t, cbuf, &msg[1], dsize, msg->iv, fwd);
5244 msgh = (struct GNUNET_MessageHeader *) cbuf;
5245 switch (ntohs (msgh->type))
5247 case GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK:
5248 if (GNUNET_YES == fwd)
5249 return handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh,
5251 GNUNET_break_op (0);
5253 case GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK:
5254 if (GNUNET_NO == fwd)
5255 return handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh,
5257 GNUNET_break_op (0);
5259 case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
5260 if (GNUNET_YES == fwd)
5261 handle_data (t, (struct GNUNET_MESH_Data *) msgh, GNUNET_YES);
5262 GNUNET_break_op (0);
5264 case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
5265 if (GNUNET_NO == fwd)
5266 handle_data (t, (struct GNUNET_MESH_Data *) msgh, GNUNET_NO);
5267 GNUNET_break_op (0);
5269 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
5270 return handle_channel_create (t,
5271 (struct GNUNET_MESH_ChannelCreate *) msgh,
5274 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
5275 return handle_channel_destroy (t,
5276 (struct GNUNET_MESH_ChannelDestroy *)
5281 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5282 "end-to-end message not known (%u)\n",
5283 ntohs (msgh->type));
5286 connection_send_ack (c, fwd);
5290 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " not for us, retransmitting...\n");
5291 ttl = ntohl (msg->ttl);
5292 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ttl: %u\n", ttl);
5295 GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5296 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5297 connection_send_ack (c, fwd);
5300 GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
5302 send_prebuilt_message_connection (&msg->header, c, NULL, fwd);
5303 connection_send_ack (c, fwd);
5310 * Core handler for mesh network traffic going orig->dest.
5312 * @param cls Closure (unused).
5313 * @param message Message received.
5314 * @param peer Peer who sent the message.
5316 * @return GNUNET_OK to keep the connection open,
5317 * GNUNET_SYSERR to close it (signal serious error)
5320 handle_mesh_fwd (void *cls, const struct GNUNET_PeerIdentity *peer,
5321 const struct GNUNET_MessageHeader *message)
5323 return handle_mesh_encrypted (peer,
5324 (struct GNUNET_MESH_Encrypted *)message,
5329 * Core handler for mesh network traffic going dest->orig.
5331 * @param cls Closure (unused).
5332 * @param message Message received.
5333 * @param peer Peer who sent the message.
5335 * @return GNUNET_OK to keep the connection open,
5336 * GNUNET_SYSERR to close it (signal serious error)
5339 handle_mesh_bck (void *cls, const struct GNUNET_PeerIdentity *peer,
5340 const struct GNUNET_MessageHeader *message)
5342 return handle_mesh_encrypted (peer,
5343 (struct GNUNET_MESH_Encrypted *)message,
5349 * Core handler for mesh network traffic point-to-point acks.
5351 * @param cls closure
5352 * @param message message
5353 * @param peer peer identity this notification is about
5355 * @return GNUNET_OK to keep the connection open,
5356 * GNUNET_SYSERR to close it (signal serious error)
5359 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5360 const struct GNUNET_MessageHeader *message)
5362 struct GNUNET_MESH_ACK *msg;
5363 struct MeshConnection *c;
5364 struct MeshFlowControl *fc;
5368 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
5370 msg = (struct GNUNET_MESH_ACK *) message;
5372 c = connection_get (&msg->tid, ntohl (msg->cid));
5376 GNUNET_STATISTICS_update (stats, "# ack on unknown connection", 1,
5381 ack = ntohl (msg->ack);
5382 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", ack);
5384 /* Is this a forward or backward ACK? */
5385 id = GNUNET_PEER_search (peer);
5386 if (connection_get_next_hop (c)->id == id)
5388 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " FWD ACK\n");
5391 else if (connection_get_prev_hop (c)->id == id)
5393 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " BCK ACK\n");
5398 GNUNET_break_op (0);
5402 /* Cancel polling if the ACK is bigger than before. */
5403 if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task &&
5404 GMC_is_pid_bigger (ack, fc->last_ack_recv))
5406 GNUNET_SCHEDULER_cancel (fc->poll_task);
5407 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
5408 fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
5411 fc->last_ack_recv = ack;
5412 connection_unlock_queue (c, fc == &c->fwd_fc);
5419 * Core handler for mesh network traffic point-to-point ack polls.
5421 * @param cls closure
5422 * @param message message
5423 * @param peer peer identity this notification is about
5425 * @return GNUNET_OK to keep the connection open,
5426 * GNUNET_SYSERR to close it (signal serious error)
5429 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
5430 const struct GNUNET_MessageHeader *message)
5432 struct GNUNET_MESH_Poll *msg;
5433 struct MeshConnection *c;
5434 struct MeshFlowControl *fc;
5438 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a POLL packet from %s!\n",
5441 msg = (struct GNUNET_MESH_Poll *) message;
5443 c = connection_get (&msg->tid, ntohl (msg->cid));
5447 GNUNET_STATISTICS_update (stats, "# poll on unknown connection", 1,
5449 GNUNET_break_op (0);
5453 /* Is this a forward or backward ACK? */
5454 id = GNUNET_PEER_search (peer);
5455 if (connection_get_next_hop (c)->id == id)
5457 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " FWD ACK\n");
5460 else if (connection_get_prev_hop (c)->id == id)
5462 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " BCK ACK\n");
5467 GNUNET_break_op (0);
5471 pid = ntohl (msg->pid);
5472 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " PID %u, OLD %u\n",
5473 pid, fc->last_pid_recv);
5474 fc->last_pid_recv = pid;
5475 connection_send_ack (c, fc == &c->fwd_fc);
5482 * Core handler for mesh keepalives.
5484 * @param cls closure
5485 * @param message message
5486 * @param peer peer identity this notification is about
5487 * @return GNUNET_OK to keep the connection open,
5488 * GNUNET_SYSERR to close it (signal serious error)
5490 * TODO: Check who we got this from, to validate route.
5493 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
5494 const struct GNUNET_MessageHeader *message)
5496 struct GNUNET_MESH_ConnectionKeepAlive *msg;
5497 struct MeshConnection *c;
5498 struct MeshPeer *neighbor;
5501 msg = (struct GNUNET_MESH_ConnectionKeepAlive *) message;
5502 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
5505 c = connection_get (&msg->tid, ntohl (msg->cid));
5508 GNUNET_STATISTICS_update (stats, "# keepalive on unknown connection", 1,
5513 fwd = GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE == ntohs (message->type) ?
5514 GNUNET_YES : GNUNET_NO;
5516 /* Check if origin is as expected */
5517 neighbor = connection_get_hop (c, fwd);
5518 if (peer_get (peer)->id != neighbor->id)
5520 GNUNET_break_op (0);
5524 connection_change_state (c, MESH_CONNECTION_READY);
5525 connection_reset_timeout (c, fwd);
5527 if (connection_is_terminal (c, fwd))
5530 GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
5531 send_prebuilt_message_connection (message, c, NULL, fwd);
5539 * Functions to handle messages from core
5541 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
5542 {&handle_mesh_connection_create, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
5544 {&handle_mesh_connection_ack, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
5545 sizeof (struct GNUNET_MESH_ConnectionACK)},
5546 {&handle_mesh_connection_broken, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN,
5547 sizeof (struct GNUNET_MESH_ConnectionBroken)},
5548 {&handle_mesh_connection_destroy, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY,
5549 sizeof (struct GNUNET_MESH_ConnectionDestroy)},
5550 {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE,
5551 sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
5552 {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE,
5553 sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
5554 {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
5555 sizeof (struct GNUNET_MESH_ACK)},
5556 {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
5557 sizeof (struct GNUNET_MESH_Poll)},
5558 {&handle_mesh_fwd, GNUNET_MESSAGE_TYPE_MESH_FWD, 0},
5559 {&handle_mesh_bck, GNUNET_MESSAGE_TYPE_MESH_BCK, 0},
5565 * Function to process paths received for a new peer addition. The recorded
5566 * paths form the initial tunnel, which can be optimized later.
5567 * Called on each result obtained for the DHT search.
5569 * @param cls closure
5570 * @param exp when will this value expire
5571 * @param key key of the result
5572 * @param get_path path of the get request
5573 * @param get_path_length lenght of get_path
5574 * @param put_path path of the put request
5575 * @param put_path_length length of the put_path
5576 * @param type type of the result
5577 * @param size number of bytes in data
5578 * @param data pointer to the result data
5581 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5582 const struct GNUNET_HashCode * key,
5583 const struct GNUNET_PeerIdentity *get_path,
5584 unsigned int get_path_length,
5585 const struct GNUNET_PeerIdentity *put_path,
5586 unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5587 size_t size, const void *data)
5589 struct MeshPeer *peer = cls;
5590 struct MeshPeerPath *p;
5591 struct MeshConnection *c;
5592 struct GNUNET_PeerIdentity pi;
5595 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
5596 GNUNET_PEER_resolve (peer->id, &pi);
5597 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " for %s\n", GNUNET_i2s (&pi));
5599 p = path_build_from_dht (get_path, get_path_length,
5600 put_path, put_path_length);
5601 path_add_to_peers (p, GNUNET_NO);
5604 /* Count connections */
5605 for (c = peer->tunnel->connection_head, i = 0; NULL != c; c = c->next, i++);
5607 /* If we already have 3 (or more (?!)) connections, it's enough */
5611 if (peer->tunnel->state == MESH_TUNNEL_SEARCHING)
5613 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... connect!\n");
5614 peer_connect (peer);
5620 /******************************************************************************/
5621 /********************* MESH LOCAL HANDLES **************************/
5622 /******************************************************************************/
5626 * Handler for client connection.
5628 * @param cls Closure (unused).
5629 * @param client Client handler.
5632 handle_local_client_connect (void *cls, struct GNUNET_SERVER_Client *client)
5634 struct MeshClient *c;
5638 c = GNUNET_malloc (sizeof (struct MeshClient));
5640 c->id = next_client_id++; /* overflow not important: just for debug */
5641 GNUNET_SERVER_client_keep (client);
5642 GNUNET_SERVER_client_set_user_context (client, c);
5643 GNUNET_CONTAINER_DLL_insert (clients_head, clients_tail, c);
5648 * Handler for client disconnection
5650 * @param cls closure
5651 * @param client identification of the client; NULL
5652 * for the last call when the server is destroyed
5655 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
5657 struct MeshClient *c;
5658 struct MeshClient *next;
5660 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected: %p\n", client);
5663 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " (SERVER DOWN)\n");
5667 c = client_get (client);
5670 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u, %p)\n",
5672 GNUNET_SERVER_client_drop (c->handle);
5673 c->shutting_down = GNUNET_YES;
5674 if (NULL != c->own_channels)
5676 GNUNET_CONTAINER_multihashmap32_iterate (c->own_channels,
5677 &channel_destroy_iterator, c);
5678 GNUNET_CONTAINER_multihashmap32_destroy (c->own_channels);
5681 if (NULL != c->incoming_channels)
5683 GNUNET_CONTAINER_multihashmap32_iterate (c->incoming_channels,
5684 &channel_destroy_iterator, c);
5685 GNUNET_CONTAINER_multihashmap32_destroy (c->incoming_channels);
5688 if (NULL != c->ports)
5690 GNUNET_CONTAINER_multihashmap32_iterate (c->ports,
5691 &client_release_ports, c);
5692 GNUNET_CONTAINER_multihashmap32_destroy (c->ports);
5695 GNUNET_CONTAINER_DLL_remove (clients_head, clients_tail, c);
5696 GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
5697 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " client free (%p)\n", c);
5703 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " context NULL!\n");
5705 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "done!\n");
5711 * Handler for new clients
5713 * @param cls closure
5714 * @param client identification of the client
5715 * @param message the actual message, which includes messages the client wants
5718 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
5719 const struct GNUNET_MessageHeader *message)
5721 struct GNUNET_MESH_ClientConnect *cc_msg;
5722 struct MeshClient *c;
5727 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected %p\n", client);
5729 /* Check data sanity */
5730 size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
5731 cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
5732 if (0 != (size % sizeof (uint32_t)))
5735 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5738 size /= sizeof (uint32_t);
5740 /* Initialize new client structure */
5741 c = GNUNET_SERVER_client_get_user_context (client, struct MeshClient);
5742 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " client id %u\n", c->id);
5743 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " client has %u ports\n", size);
5748 p = (uint32_t *) &cc_msg[1];
5749 c->ports = GNUNET_CONTAINER_multihashmap32_create (size);
5750 for (i = 0; i < size; i++)
5753 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " port: %u\n", u32);
5755 /* store in client's hashmap */
5756 GNUNET_CONTAINER_multihashmap32_put (c->ports, u32, c,
5757 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
5758 /* store in global hashmap */
5759 /* FIXME only allow one client to have the port open,
5760 * have a backup hashmap with waiting clients */
5761 GNUNET_CONTAINER_multihashmap32_put (ports, u32, c,
5762 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
5766 c->own_channels = GNUNET_CONTAINER_multihashmap32_create (32);
5767 c->incoming_channels = GNUNET_CONTAINER_multihashmap32_create (32);
5768 GNUNET_SERVER_notification_context_add (nc, client);
5769 GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
5771 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5772 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
5777 * Handler for requests of new tunnels
5779 * @param cls Closure.
5780 * @param client Identification of the client.
5781 * @param message The actual message.
5784 handle_local_channel_create (void *cls, struct GNUNET_SERVER_Client *client,
5785 const struct GNUNET_MessageHeader *message)
5787 struct GNUNET_MESH_ChannelMessage *msg;
5788 struct MeshPeer *peer;
5789 struct MeshTunnel2 *t;
5790 struct MeshChannel *ch;
5791 struct MeshClient *c;
5792 MESH_ChannelNumber chid;
5794 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new channel requested\n");
5796 /* Sanity check for client registration */
5797 if (NULL == (c = client_get (client)))
5800 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5803 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
5805 /* Message size sanity check */
5806 if (sizeof (struct GNUNET_MESH_ChannelMessage) != ntohs (message->size))
5809 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5813 msg = (struct GNUNET_MESH_ChannelMessage *) message;
5814 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " towards %s:%u\n",
5815 GNUNET_i2s (&msg->peer), ntohl (msg->port));
5816 chid = ntohl (msg->channel_id);
5818 /* Sanity check for duplicate channel IDs */
5819 if (NULL != channel_get_by_local_id (c, chid))
5822 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5826 peer = peer_get (&msg->peer);
5827 if (NULL == peer->tunnel)
5829 struct GNUNET_HashCode tid;
5831 GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE, &tid);
5832 peer->tunnel = tunnel_new (&tid);
5833 peer->tunnel->peer = peer;
5837 /* Create channel */
5838 ch = channel_new (t, c, chid);
5842 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5845 ch->port = ntohl (msg->port);
5846 channel_set_options (ch, ntohl (msg->opt));
5848 /* In unreliable channels, we'll use the DLL to buffer data for the root */
5849 ch->fwd_rel = GNUNET_malloc (sizeof (struct MeshChannelReliability));
5850 ch->fwd_rel->ch = ch;
5851 ch->fwd_rel->expected_delay = MESH_RETRANSMIT_TIME;
5853 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED CHANNEL %s[%x]:%u (%x)\n",
5854 GNUNET_h2s (&t->id), ch->gid, ch->port, ch->lid_root);
5855 peer_connect (peer);
5857 /* Send create channel */
5859 struct GNUNET_MESH_ChannelCreate msgcc;
5861 msgcc.header.size = htons (sizeof (msgcc));
5862 msgcc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE);
5863 msgcc.chid = htonl (ch->gid);
5864 msgcc.port = msg->port;
5865 msgcc.opt = msg->opt;
5867 tunnel_queue_data (t, ch, &msgcc.header, GNUNET_YES);
5870 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5876 * Handler for requests of deleting tunnels
5878 * @param cls closure
5879 * @param client identification of the client
5880 * @param message the actual message
5883 handle_local_channel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
5884 const struct GNUNET_MessageHeader *message)
5886 struct GNUNET_MESH_ChannelMessage *msg;
5887 struct MeshClient *c;
5888 struct MeshChannel *ch;
5889 struct MeshTunnel2 *t;
5890 MESH_ChannelNumber chid;
5892 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5893 "Got a DESTROY CHANNEL from client!\n");
5895 /* Sanity check for client registration */
5896 if (NULL == (c = client_get (client)))
5899 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5902 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
5904 /* Message sanity check */
5905 if (sizeof (struct GNUNET_MESH_ChannelMessage) != ntohs (message->size))
5908 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5912 msg = (struct GNUNET_MESH_ChannelMessage *) message;
5914 /* Retrieve tunnel */
5915 chid = ntohl (msg->channel_id);
5916 ch = channel_get_by_local_id (c, chid);
5919 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, " channel %X not found\n", chid);
5921 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5925 /* Cleanup after the tunnel */
5926 client_delete_channel (c, ch);
5927 if (c == ch->dest && GNUNET_MESH_LOCAL_CHANNEL_ID_SERV <= chid)
5931 else if (c == ch->root && GNUNET_MESH_LOCAL_CHANNEL_ID_SERV > chid)
5937 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5938 " channel %X client %p (%p, %p)\n",
5939 chid, c, ch->root, ch->dest);
5944 channel_destroy (ch);
5945 tunnel_destroy_if_empty (t);
5947 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5953 * Handler for client traffic
5955 * @param cls closure
5956 * @param client identification of the client
5957 * @param message the actual message
5960 handle_local_data (void *cls, struct GNUNET_SERVER_Client *client,
5961 const struct GNUNET_MessageHeader *message)
5963 struct GNUNET_MESH_LocalData *msg;
5964 struct MeshClient *c;
5965 struct MeshChannel *ch;
5966 MESH_ChannelNumber chid;
5970 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5971 "Got data from a client!\n");
5973 /* Sanity check for client registration */
5974 if (NULL == (c = client_get (client)))
5977 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5980 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
5982 msg = (struct GNUNET_MESH_LocalData *) message;
5984 /* Sanity check for message size */
5985 size = ntohs (message->size) - sizeof (struct GNUNET_MESH_LocalData);
5986 if (size < sizeof (struct GNUNET_MessageHeader))
5989 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5993 /* Channel exists? */
5994 chid = ntohl (msg->id);
5995 fwd = chid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
5996 ch = channel_get_by_local_id (c, chid);
6000 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6004 /* Is the client in the channel? */
6007 ch->root->handle == client)
6011 ch->dest->handle == client) ) )
6014 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6018 /* Ok, everything is correct, send the message
6019 * (pretend we got it from a mesh peer)
6022 struct GNUNET_MESH_Data *payload;
6023 char cbuf[sizeof(struct GNUNET_MESH_Data) + size];
6026 mid = fwd ? &ch->mid_send_fwd : &ch->mid_send_bck;
6027 if (GNUNET_YES == ch->reliable)
6029 struct MeshChannelReliability *rel;
6030 struct MeshReliableMessage *copy;
6032 rel = fwd ? ch->fwd_rel : ch->bck_rel;
6033 copy = GNUNET_malloc (sizeof (struct MeshReliableMessage)
6034 + sizeof(struct GNUNET_MESH_Data)
6037 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! DATA %u\n", copy->mid);
6038 copy->timestamp = GNUNET_TIME_absolute_get ();
6041 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " n_sent %u\n", rel->n_sent);
6042 GNUNET_CONTAINER_DLL_insert_tail (rel->head_sent, rel->tail_sent, copy);
6043 if (GNUNET_SCHEDULER_NO_TASK == rel->retry_task)
6046 GNUNET_TIME_relative_multiply (rel->expected_delay,
6047 MESH_RETRANSMIT_MARGIN);
6049 GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
6050 &channel_retransmit_message,
6053 payload = (struct GNUNET_MESH_Data *) ©[1];
6057 payload = (struct GNUNET_MESH_Data *) cbuf;
6059 payload->mid = htonl (*mid);
6061 memcpy (&payload[1], &msg[1], size);
6062 payload->header.size = htons (sizeof (struct GNUNET_MESH_Data) + size);
6063 payload->header.type = htons (chid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV ?
6064 GNUNET_MESSAGE_TYPE_MESH_UNICAST :
6065 GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
6066 payload->chid = htonl (ch->gid);
6067 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6068 " calling generic handler...\n");
6069 send_prebuilt_message_channel (&payload->header, ch, fwd);
6071 if (tunnel_get_buffer (ch->t, fwd) > 0)
6072 send_local_ack (ch, c, fwd);
6073 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
6074 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6081 * Handler for client's ACKs for payload traffic.
6083 * @param cls Closure (unused).
6084 * @param client Identification of the client.
6085 * @param message The actual message.
6088 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
6089 const struct GNUNET_MessageHeader *message)
6091 struct GNUNET_MESH_LocalAck *msg;
6092 struct MeshChannelReliability *rel;
6093 struct MeshChannel *ch;
6094 struct MeshClient *c;
6095 MESH_ChannelNumber chid;
6098 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
6100 /* Sanity check for client registration */
6101 if (NULL == (c = client_get (client)))
6104 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6107 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
6109 msg = (struct GNUNET_MESH_LocalAck *) message;
6111 /* Channel exists? */
6112 chid = ntohl (msg->channel_id);
6113 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " on channel %X\n", chid);
6114 ch = channel_get_by_local_id (c, chid);
6118 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Channel %X unknown.\n", chid);
6119 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " for client %u.\n", c->id);
6120 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6124 fwd = chid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
6125 rel = fwd ? ch->fwd_rel : ch->bck_rel;
6127 rel->client_ready = GNUNET_YES;
6128 channel_send_client_buffered_data (ch, c, rel);
6129 channel_send_ack (ch, 64 - rel->n_recv, fwd);
6131 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6138 * Iterator over all tunnels to send a monitoring client info about each tunnel.
6140 * @param cls Closure (client handle).
6141 * @param key Key (hashed tunnel ID, unused).
6142 * @param value Tunnel info.
6144 * @return GNUNET_YES, to keep iterating.
6147 monitor_all_tunnels_iterator (void *cls,
6148 const struct GNUNET_HashCode * key,
6151 struct GNUNET_SERVER_Client *client = cls;
6152 struct MeshChannel *ch = value;
6153 struct GNUNET_MESH_LocalMonitor *msg;
6155 msg = GNUNET_malloc (sizeof(struct GNUNET_MESH_LocalMonitor));
6156 msg->channel_id = htonl (ch->gid);
6157 msg->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
6158 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
6160 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6161 "* sending info about tunnel %s\n",
6162 GNUNET_i2s (&msg->owner));
6164 GNUNET_SERVER_notification_context_unicast (nc, client,
6165 &msg->header, GNUNET_NO);
6171 * Handler for client's MONITOR request.
6173 * @param cls Closure (unused).
6174 * @param client Identification of the client.
6175 * @param message The actual message.
6178 handle_local_get_tunnels (void *cls, struct GNUNET_SERVER_Client *client,
6179 const struct GNUNET_MessageHeader *message)
6181 struct MeshClient *c;
6183 /* Sanity check for client registration */
6184 if (NULL == (c = client_get (client)))
6187 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6191 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6192 "Received get tunnels request from client %u\n",
6194 GNUNET_CONTAINER_multihashmap_iterate (tunnels,
6195 monitor_all_tunnels_iterator,
6197 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6198 "Get tunnels request from client %u completed\n",
6200 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6205 * Handler for client's MONITOR_TUNNEL request.
6207 * @param cls Closure (unused).
6208 * @param client Identification of the client.
6209 * @param message The actual message.
6212 handle_local_show_tunnel (void *cls, struct GNUNET_SERVER_Client *client,
6213 const struct GNUNET_MessageHeader *message)
6215 const struct GNUNET_MESH_LocalMonitor *msg;
6216 struct GNUNET_MESH_LocalMonitor *resp;
6217 struct MeshClient *c;
6218 struct MeshChannel *ch;
6220 /* Sanity check for client registration */
6221 if (NULL == (c = client_get (client)))
6224 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6228 msg = (struct GNUNET_MESH_LocalMonitor *) message;
6229 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6230 "Received tunnel info request from client %u for tunnel %s[%X]\n",
6233 ntohl (msg->channel_id));
6234 // ch = channel_get (&msg->owner, ntohl (msg->channel_id));
6238 /* We don't know the tunnel */
6239 struct GNUNET_MESH_LocalMonitor warn;
6242 GNUNET_SERVER_notification_context_unicast (nc, client,
6245 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6249 /* Initialize context */
6250 resp = GNUNET_malloc (sizeof (struct GNUNET_MESH_LocalMonitor));
6252 resp->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
6253 GNUNET_SERVER_notification_context_unicast (nc, c->handle,
6254 &resp->header, GNUNET_NO);
6257 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6258 "Monitor tunnel request from client %u completed\n",
6260 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6265 * Functions to handle messages from clients
6267 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
6268 {&handle_local_new_client, NULL,
6269 GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
6270 {&handle_local_channel_create, NULL,
6271 GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE,
6272 sizeof (struct GNUNET_MESH_ChannelMessage)},
6273 {&handle_local_channel_destroy, NULL,
6274 GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY,
6275 sizeof (struct GNUNET_MESH_ChannelMessage)},
6276 {&handle_local_data, NULL,
6277 GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA, 0},
6278 {&handle_local_ack, NULL,
6279 GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
6280 sizeof (struct GNUNET_MESH_LocalAck)},
6281 {&handle_local_get_tunnels, NULL,
6282 GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS,
6283 sizeof (struct GNUNET_MessageHeader)},
6284 {&handle_local_show_tunnel, NULL,
6285 GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL,
6286 sizeof (struct GNUNET_MESH_LocalMonitor)},
6292 * Method called whenever a given peer connects.
6294 * @param cls closure
6295 * @param peer peer identity this notification is about
6298 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
6300 struct MeshPeer *pi;
6301 struct MeshPeerPath *path;
6303 DEBUG_CONN ("Peer connected\n");
6304 DEBUG_CONN (" %s\n", GNUNET_i2s (&my_full_id));
6305 pi = peer_get (peer);
6308 DEBUG_CONN (" (self)\n");
6309 path = path_new (1);
6313 DEBUG_CONN (" %s\n", GNUNET_i2s (peer));
6314 path = path_new (2);
6315 path->peers[1] = pi->id;
6316 GNUNET_PEER_change_rc (pi->id, 1);
6317 GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
6319 path->peers[0] = myid;
6320 GNUNET_PEER_change_rc (myid, 1);
6321 peer_add_path (pi, path, GNUNET_YES);
6323 pi->connections = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_YES);
6329 * Method called whenever a peer disconnects.
6331 * @param cls closure
6332 * @param peer peer identity this notification is about
6335 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
6337 struct MeshPeer *pi;
6339 DEBUG_CONN ("Peer disconnected\n");
6340 pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
6347 peer_remove_path (pi, myid, pi->id);
6349 GNUNET_CONTAINER_multihashmap_iterate (pi->connections,
6352 GNUNET_CONTAINER_multihashmap_destroy (pi->connections);
6353 pi->connections = NULL;
6356 DEBUG_CONN (" (self)\n");
6358 GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
6365 * Install server (service) handlers and start listening to clients.
6370 GNUNET_SERVER_add_handlers (server_handle, client_handlers);
6371 GNUNET_SERVER_connect_notify (server_handle,
6372 &handle_local_client_connect, NULL);
6373 GNUNET_SERVER_disconnect_notify (server_handle,
6374 &handle_local_client_disconnect, NULL);
6375 nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
6377 clients_head = NULL;
6378 clients_tail = NULL;
6380 GNUNET_SERVER_resume (server_handle);
6385 * To be called on core init/fail.
6387 * @param cls Closure (config)
6388 * @param server handle to the server for this service
6389 * @param identity the public identity of this peer
6392 core_init (void *cls, struct GNUNET_CORE_Handle *server,
6393 const struct GNUNET_PeerIdentity *identity)
6395 const struct GNUNET_CONFIGURATION_Handle *c = cls;
6398 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
6399 GNUNET_break (core_handle == server);
6400 if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
6403 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
6404 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6406 GNUNET_i2s (identity));
6407 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6409 GNUNET_i2s (&my_full_id));
6410 GNUNET_CORE_disconnect (core_handle);
6411 core_handle = GNUNET_CORE_connect (c, /* Main configuration */
6412 NULL, /* Closure passed to MESH functions */
6413 &core_init, /* Call core_init once connected */
6414 &core_connect, /* Handle connects */
6415 &core_disconnect, /* remove peers on disconnects */
6416 NULL, /* Don't notify about all incoming messages */
6417 GNUNET_NO, /* For header only in notification */
6418 NULL, /* Don't notify about all outbound messages */
6419 GNUNET_NO, /* For header-only out notification */
6420 core_handlers); /* Register these handlers */
6429 /******************************************************************************/
6430 /************************ MAIN FUNCTIONS ****************************/
6431 /******************************************************************************/
6434 * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
6436 * @param cls closure
6437 * @param key current key code
6438 * @param value value in the hash map
6439 * @return GNUNET_YES if we should continue to iterate,
6443 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
6445 struct MeshTunnel2 *t = value;
6453 * Task run during shutdown.
6459 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
6461 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
6463 if (core_handle != NULL)
6465 GNUNET_CORE_disconnect (core_handle);
6468 GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
6469 if (dht_handle != NULL)
6471 GNUNET_DHT_disconnect (dht_handle);
6476 GNUNET_SERVER_notification_context_destroy (nc);
6479 if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
6481 GNUNET_SCHEDULER_cancel (announce_id_task);
6482 announce_id_task = GNUNET_SCHEDULER_NO_TASK;
6484 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
6489 * Process mesh requests.
6491 * @param cls closure
6492 * @param server the initialized server
6493 * @param c configuration to use
6496 run (void *cls, struct GNUNET_SERVER_Handle *server,
6497 const struct GNUNET_CONFIGURATION_Handle *c)
6500 struct GNUNET_CRYPTO_EccPrivateKey *pk;
6502 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
6503 server_handle = server;
6504 GNUNET_SERVER_suspend (server_handle);
6507 GNUNET_CONFIGURATION_get_value_filename (c, "PEER", "PRIVATE_KEY",
6510 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6512 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6513 "mesh", "peer/privatekey");
6514 GNUNET_SCHEDULER_shutdown ();
6519 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_CONNECTION_TIME",
6520 &refresh_connection_time))
6522 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6524 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6525 "mesh", "refresh path time");
6526 GNUNET_SCHEDULER_shutdown ();
6531 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
6534 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6536 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6537 "mesh", "id announce time");
6538 GNUNET_SCHEDULER_shutdown ();
6543 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
6546 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6548 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6549 "mesh", "connect timeout");
6550 GNUNET_SCHEDULER_shutdown ();
6555 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
6558 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6560 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6561 "mesh", "max msgs queue");
6562 GNUNET_SCHEDULER_shutdown ();
6567 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_CONNECTIONS",
6570 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6572 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6573 "mesh", "max tunnels");
6574 GNUNET_SCHEDULER_shutdown ();
6579 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
6582 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6584 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
6585 "mesh", "default ttl", 64);
6590 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
6593 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6594 _("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
6595 "mesh", "max peers", 1000);
6600 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DROP_PERCENT",
6607 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6608 "Mesh is running with drop mode enabled. "
6609 "This is NOT a good idea! "
6610 "Remove the DROP_PERCENT option from your configuration.\n");
6614 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
6615 &dht_replication_level))
6617 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6619 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
6620 "mesh", "dht replication level", 3);
6621 dht_replication_level = 3;
6624 tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6625 peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6626 ports = GNUNET_CONTAINER_multihashmap32_create (32);
6628 dht_handle = GNUNET_DHT_connect (c, 64);
6629 if (NULL == dht_handle)
6633 stats = GNUNET_STATISTICS_create ("mesh", c);
6635 /* Scheduled the task to clean up when shutdown is called */
6636 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
6638 pk = GNUNET_CRYPTO_ecc_key_create_from_file (keyfile);
6639 GNUNET_free (keyfile);
6640 GNUNET_assert (NULL != pk);
6641 my_private_key = pk;
6642 GNUNET_CRYPTO_ecc_key_get_public (my_private_key, &my_public_key);
6643 GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
6644 &my_full_id.hashPubKey);
6645 myid = GNUNET_PEER_intern (&my_full_id);
6646 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6647 "Mesh for peer [%s] starting\n",
6648 GNUNET_i2s(&my_full_id));
6650 core_handle = GNUNET_CORE_connect (c, /* Main configuration */
6651 NULL, /* Closure passed to MESH functions */
6652 &core_init, /* Call core_init once connected */
6653 &core_connect, /* Handle connects */
6654 &core_disconnect, /* remove peers on disconnects */
6655 NULL, /* Don't notify about all incoming messages */
6656 GNUNET_NO, /* For header only in notification */
6657 NULL, /* Don't notify about all outbound messages */
6658 GNUNET_NO, /* For header-only out notification */
6659 core_handlers); /* Register these handlers */
6660 if (NULL == core_handle)
6663 GNUNET_SCHEDULER_shutdown ();
6666 announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
6667 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
6672 * The main function for the mesh service.
6674 * @param argc number of arguments from the command line
6675 * @param argv command line arguments
6676 * @return 0 ok, 1 on error
6679 main (int argc, char *const *argv)
6684 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
6685 r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
6687 ret = (GNUNET_OK == r) ? 0 : 1;
6688 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");