2 This file is part of GNUnet.
3 (C) 2001-2013 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file mesh/gnunet-service-mesh-enc.c
23 * @brief GNUnet MESH service with encryption
24 * @author Bartlomiej Polot
27 * - when sending in-order buffered data, wait for client ACKs
30 * - set connection IDs independently from tunnel, tunnel has no ID
33 * - relay corking down to core
34 * - set ttl relative to path length
38 * - peer: other mesh instance. If there is direct connection it's a neighbor.
39 * - tunnel: encrypted connection to a peer, neighbor or not.
40 * - channel: connection between two clients, on the same or different peers.
41 * have properties like reliability.
42 * - path: series of directly connected peer from one peer to another.
43 * - connection: path which is being used in a tunnel.
47 #include "gnunet_crypto_lib.h"
49 #include "mesh_protocol_enc.h"
50 #include "mesh_path.h"
51 #include "block_mesh.h"
52 #include "gnunet_dht_service.h"
53 #include "gnunet_statistics_service.h"
55 #define MESH_BLOOM_SIZE 128
56 #define MESH_MAX_POLL_TIME GNUNET_TIME_relative_multiply (\
57 GNUNET_TIME_UNIT_MINUTES,\
59 #define MESH_RETRANSMIT_TIME GNUNET_TIME_UNIT_SECONDS
60 #define MESH_RETRANSMIT_MARGIN 4
62 #define MESH_DEBUG_DHT GNUNET_NO
63 #define MESH_DEBUG_CONNECTION GNUNET_NO
64 #define MESH_DEBUG_TIMING __LINUX__ && GNUNET_NO
67 #define DEBUG_DHT(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
69 #define DEBUG_DHT(...)
72 #if MESH_DEBUG_CONNECTION
73 #define DEBUG_CONN(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
75 #define DEBUG_CONN(...)
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 ACK sent, waiting for ACK.
155 * Connection confirmed, ready to carry traffic.
157 MESH_CONNECTION_READY,
162 * All the states a connection can be in.
164 enum MeshChannelState
167 * Uninitialized status, should never appear in operation.
172 * Connection create message sent, waiting for ACK.
177 * Connection confirmed, ready to carry traffic..
183 /******************************************************************************/
184 /************************ DATA STRUCTURES ****************************/
185 /******************************************************************************/
187 /** FWD declaration */
191 struct MeshConnection;
193 struct MeshChannelReliability;
197 * Struct containing info about a queued transmission to this peer
204 struct MeshPeerQueue *next;
209 struct MeshPeerQueue *prev;
212 * Peer this transmission is directed to.
214 struct MeshPeer *peer;
217 * Connection this message belongs to.
219 struct MeshConnection *c;
227 * Channel this message belongs to, if known.
229 struct MeshChannel *ch;
232 * Pointer to info stucture used as cls.
242 * Size of the message
249 * Struct to encapsulate all the Flow Control information to a peer to which
250 * we are directly connected (on a core level).
252 struct MeshFlowControl
255 * Connection this controls.
257 struct MeshConnection *c;
260 * How many messages are in the queue on this connection.
262 unsigned int queue_n;
265 * How many messages do we accept in the queue.
267 unsigned int queue_max;
275 * ID of the last packet sent towards the peer.
277 uint32_t last_pid_sent;
280 * ID of the last packet received from the peer.
282 uint32_t last_pid_recv;
285 * Last ACK sent to the peer (peer can't send more than this PID).
287 uint32_t last_ack_sent;
290 * Last ACK sent towards the origin (for traffic towards leaf node).
292 uint32_t last_ack_recv;
295 * Task to poll the peer in case of a lost ACK causes stall.
297 GNUNET_SCHEDULER_TaskIdentifier poll_task;
300 * How frequently to poll for ACKs.
302 struct GNUNET_TIME_Relative poll_time;
307 * Struct containing all information regarding a given peer
317 * Last time we heard from this peer
319 struct GNUNET_TIME_Absolute last_contact;
322 * Paths to reach the peer, ordered by ascending hop count
324 struct MeshPeerPath *path_head;
327 * Paths to reach the peer, ordered by ascending hop count
329 struct MeshPeerPath *path_tail;
332 * Handle to stop the DHT search for paths to this peer
334 struct GNUNET_DHT_GetHandle *dhtget;
337 * Tunnel to this peer, if any.
339 struct MeshTunnel2 *tunnel;
342 * Connections that go through this peer, indexed by tid;
344 struct GNUNET_CONTAINER_MultiHashMap *connections;
347 * Handle for queued transmissions
349 struct GNUNET_CORE_TransmitHandle *core_transmit;
352 * Transmission queue to core DLL head
354 struct MeshPeerQueue *queue_head;
357 * Transmission queue to core DLL tail
359 struct MeshPeerQueue *queue_tail;
362 * How many messages are in the queue to this peer.
364 unsigned int queue_n;
369 * Info needed to retry a message in case it gets lost.
371 struct MeshReliableMessage
374 * Double linked list, FIFO style
376 struct MeshReliableMessage *next;
377 struct MeshReliableMessage *prev;
380 * Type of message (payload, channel management).
385 * Tunnel Reliability queue this message is in.
387 struct MeshChannelReliability *rel;
390 * ID of the message (ACK needed to free)
395 * When was this message issued (to calculate ACK delay)
397 struct GNUNET_TIME_Absolute timestamp;
399 /* struct GNUNET_MESH_Data with payload */
404 * Info about the traffic state for a client in a channel.
406 struct MeshChannelReliability
409 * Channel this is about.
411 struct MeshChannel *ch;
414 * DLL of messages sent and not yet ACK'd.
416 struct MeshReliableMessage *head_sent;
417 struct MeshReliableMessage *tail_sent;
420 * Messages pending to send.
425 * DLL of messages received out of order.
427 struct MeshReliableMessage *head_recv;
428 struct MeshReliableMessage *tail_recv;
436 * Next MID to use for outgoing traffic.
441 * Next MID expected for incoming traffic.
446 * Can we send data to the client?
451 * Task to resend/poll in case no ACK is received.
453 GNUNET_SCHEDULER_TaskIdentifier retry_task;
456 * Counter for exponential backoff.
458 struct GNUNET_TIME_Relative retry_timer;
461 * How long does it usually take to get an ACK.
463 struct GNUNET_TIME_Relative expected_delay;
468 * Struct containing all information regarding a channel to a remote client.
473 * Tunnel this channel is in.
475 struct MeshTunnel2 *t;
478 * Double linked list.
480 struct MeshChannel *next;
481 struct MeshChannel *prev;
484 * Destination port of the channel.
489 * Global channel number ( < GNUNET_MESH_LOCAL_CHANNEL_ID_CLI)
491 MESH_ChannelNumber gid;
494 * Local tunnel number for root (owner) client.
495 * ( >= GNUNET_MESH_LOCAL_CHANNEL_ID_CLI or 0 )
497 MESH_ChannelNumber lid_root;
500 * Local tunnel number for local destination clients (incoming number)
501 * ( >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV or 0).
503 MESH_ChannelNumber lid_dest;
508 enum MeshChannelState state;
511 * Is the tunnel bufferless (minimum latency)?
516 * Is the tunnel reliable?
521 * Last time the channel was used
523 struct GNUNET_TIME_Absolute timestamp;
526 * Client owner of the tunnel, if any
528 struct MeshClient *root;
531 * Client destination of the tunnel, if any.
533 struct MeshClient *dest;
536 * Flag to signal the destruction of the channel.
537 * If this is set GNUNET_YES the channel will be destroyed
538 * when the queue is empty.
543 * Total messages pending for this channel, payload or not.
545 unsigned int pending_messages;
549 * Only present (non-NULL) at the owner of a tunnel.
551 struct MeshChannelReliability *root_rel;
555 * Only present (non-NULL) at the destination of a tunnel.
557 struct MeshChannelReliability *dest_rel;
563 * Struct containing all information regarding a connection to a peer.
565 struct MeshConnection
570 struct MeshConnection *next;
571 struct MeshConnection *prev;
574 * Tunnel this connection is part of.
576 struct MeshTunnel2 *t;
579 * Flow control information for traffic fwd.
581 struct MeshFlowControl fwd_fc;
584 * Flow control information for traffic bck.
586 struct MeshFlowControl bck_fc;
589 * ID of the connection.
591 struct GNUNET_HashCode id;
594 * State of the connection.
596 enum MeshConnectionState state;
599 * Path being used for the tunnel.
601 struct MeshPeerPath *path;
604 * Position of the local peer in the path.
606 unsigned int own_pos;
609 * Task to keep the used paths alive at the owner,
610 * time tunnel out on all the other peers.
612 GNUNET_SCHEDULER_TaskIdentifier fwd_maintenance_task;
615 * Task to keep the used paths alive at the destination,
616 * time tunnel out on all the other peers.
618 GNUNET_SCHEDULER_TaskIdentifier bck_maintenance_task;
621 * Pending message count.
623 int pending_messages;
626 * Destroy flag: if true, destroy on last message.
633 * Struct used to queue messages in a tunnel.
635 struct MeshTunnelQueue
640 struct MeshTunnelQueue *next;
641 struct MeshTunnelQueue *prev;
646 struct MeshChannel *ch;
651 /* struct GNUNET_MessageHeader *msg; */
656 * Struct containing all information regarding a tunnel to a peer.
661 * Endpoint of the tunnel.
663 struct MeshPeer *peer;
666 * State of the tunnel.
668 enum MeshTunnelState state;
671 * Local peer ephemeral private key
673 struct GNUNET_CRYPTO_EccPrivateKey *my_eph_key;
676 * Local peer ephemeral public key
678 struct GNUNET_CRYPTO_EccPublicKey *my_eph;
681 * Remote peer's public key.
683 struct GNUNET_CRYPTO_EccPublicKey *peers_eph;
686 * Encryption ("our") key.
688 struct GNUNET_CRYPTO_AesSessionKey e_key;
691 * Decryption ("their") key.
693 struct GNUNET_CRYPTO_AesSessionKey d_key;
696 * Paths that are actively used to reach the destination peer.
698 struct MeshConnection *connection_head;
699 struct MeshConnection *connection_tail;
702 * Next connection number.
707 * Channels inside this tunnel.
709 struct MeshChannel *channel_head;
710 struct MeshChannel *channel_tail;
713 * Channel ID for the next created channel.
715 MESH_ChannelNumber next_chid;
718 * Channel ID for the next incoming channel.
720 MESH_ChannelNumber next_local_chid;
723 * Pending message count.
725 int pending_messages;
728 * Destroy flag: if true, destroy on last message.
733 * Queued messages, to transmit once tunnel gets connected.
735 struct MeshTunnelQueue *tq_head;
736 struct MeshTunnelQueue *tq_tail;
742 * Struct containing information about a client of the service
744 * TODO: add a list of 'waiting' ports
751 struct MeshClient *next;
756 struct MeshClient *prev;
759 * Tunnels that belong to this client, indexed by local id
761 struct GNUNET_CONTAINER_MultiHashMap32 *own_channels;
764 * Tunnels this client has accepted, indexed by incoming local id
766 struct GNUNET_CONTAINER_MultiHashMap32 *incoming_channels;
769 * Handle to communicate with the client
771 struct GNUNET_SERVER_Client *handle;
774 * Ports that this client has declared interest in.
775 * Indexed by port, contains *Client.
777 struct GNUNET_CONTAINER_MultiHashMap32 *ports;
780 * Whether the client is active or shutting down (don't send confirmations
781 * to a client that is shutting down.
786 * ID of the client, mainly for debug messages
792 /******************************************************************************/
793 /************************ DEBUG FUNCTIONS ****************************/
794 /******************************************************************************/
798 * GNUNET_SCHEDULER_Task for printing a message after some operation is done
799 * @param cls string to print
800 * @param success GNUNET_OK if the PUT was transmitted,
801 * GNUNET_NO on timeout,
802 * GNUNET_SYSERR on disconnect from service
803 * after the PUT message was transmitted
804 * (so we don't know if it was received or not)
809 mesh_debug (void *cls, int success)
813 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s (%d)\n", s, success);
819 /******************************************************************************/
820 /*********************** GLOBAL VARIABLES ****************************/
821 /******************************************************************************/
823 /************************** Configuration parameters **************************/
826 * How often to send path keepalives. Paths timeout after 4 missed.
828 static struct GNUNET_TIME_Relative refresh_connection_time;
831 * How often to PUT own ID in the DHT.
833 static struct GNUNET_TIME_Relative id_announce_time;
836 * Maximum time allowed to connect to a peer found by string.
838 static struct GNUNET_TIME_Relative connect_timeout;
841 * Default TTL for payload packets.
843 static unsigned long long default_ttl;
846 * DHT replication level, see DHT API: GNUNET_DHT_get_start, GNUNET_DHT_put.
848 static unsigned long long dht_replication_level;
851 * How many connections are we willing to maintain.
852 * Local connections are always allowed, even if there are more connections than max.
854 static unsigned long long max_connections;
857 * How many messages *in total* are we willing to queue, divide by number of
858 * connections to get connection queue size.
860 static unsigned long long max_msgs_queue;
863 * How many peers do we want to remember?
865 static unsigned long long max_peers;
868 * Percentage of messages that will be dropped (for test purposes only).
870 static unsigned long long drop_percent;
872 /*************************** Static global variables **************************/
875 * DLL with all the clients, head.
877 static struct MeshClient *clients_head;
880 * DLL with all the clients, tail.
882 static struct MeshClient *clients_tail;
885 * Connections known, indexed by cid (MeshConnection).
887 static struct GNUNET_CONTAINER_MultiHashMap *connections;
890 * Peers known, indexed by PeerIdentity (MeshPeer).
892 static struct GNUNET_CONTAINER_MultiHashMap *peers;
895 * Handle to communicate with core.
897 static struct GNUNET_CORE_Handle *core_handle;
902 static struct GNUNET_DHT_Handle *dht_handle;
905 * Handle to server lib.
907 static struct GNUNET_SERVER_Handle *server_handle;
910 * Handle to the statistics service.
912 static struct GNUNET_STATISTICS_Handle *stats;
915 * Notification context, to send messages to local clients.
917 static struct GNUNET_SERVER_NotificationContext *nc;
920 * Local peer own ID (memory efficient handle).
922 static GNUNET_PEER_Id myid;
925 * Local peer own ID (full value).
927 static struct GNUNET_PeerIdentity my_full_id;
932 static struct GNUNET_CRYPTO_EccPrivateKey *my_private_key;
937 static struct GNUNET_CRYPTO_EccPublicKey my_public_key;
940 * All ports clients of this peer have opened.
942 static struct GNUNET_CONTAINER_MultiHashMap32 *ports;
945 * Task to periodically announce itself in the network.
947 GNUNET_SCHEDULER_TaskIdentifier announce_id_task;
950 * Next ID to assign to a client.
952 unsigned int next_client_id;
955 /******************************************************************************/
956 /*********************** DECLARATIONS **************************/
957 /******************************************************************************/
960 * Function to process paths received for a new peer addition. The recorded
961 * paths form the initial tunnel, which can be optimized later.
962 * Called on each result obtained for the DHT search.
965 * @param exp when will this value expire
966 * @param key key of the result
967 * @param type type of the result
968 * @param size number of bytes in data
969 * @param data pointer to the result data
972 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
973 const struct GNUNET_HashCode * key,
974 const struct GNUNET_PeerIdentity *get_path,
975 unsigned int get_path_length,
976 const struct GNUNET_PeerIdentity *put_path,
977 unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
978 size_t size, const void *data);
982 * Retrieve the MeshPeer stucture associated with the peer, create one
983 * and insert it in the appropriate structures if the peer is not known yet.
985 * @param peer Full identity of the peer.
987 * @return Existing or newly created peer info.
989 static struct MeshPeer *
990 peer_get (const struct GNUNET_PeerIdentity *peer);
994 * Retrieve the MeshPeer stucture associated with the peer, create one
995 * and insert it in the appropriate structures if the peer is not known yet.
997 * @param peer Short identity of the peer.
999 * @return Existing or newly created peer info.
1001 static struct MeshPeer *
1002 peer_get_short (const GNUNET_PEER_Id peer);
1006 * Build a PeerPath from the paths returned from the DHT, reversing the paths
1007 * to obtain a local peer -> destination path and interning the peer ids.
1009 * @return Newly allocated and created path
1011 static struct MeshPeerPath *
1012 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
1013 unsigned int get_path_length,
1014 const struct GNUNET_PeerIdentity *put_path,
1015 unsigned int put_path_length);
1019 * Adds a path to the data structs of all the peers in the path
1021 * @param p Path to process.
1022 * @param confirmed Whether we know if the path works or not.
1025 path_add_to_peers (struct MeshPeerPath *p, int confirmed);
1029 * Search for a tunnel by global ID using full PeerIdentities.
1031 * @param t Tunnel containing the channel.
1032 * @param chid Public channel number.
1034 * @return channel handler, NULL if doesn't exist
1036 static struct MeshChannel *
1037 channel_get (struct MeshTunnel2 *t, MESH_ChannelNumber chid);
1040 * Modify the data message ID from global to local and send to client.
1042 * @param ch Channel on which to send the message.
1043 * @param msg Message to modify and send.
1044 * @param fwd Forward?
1047 channel_send_client_data (struct MeshChannel *ch,
1048 const struct GNUNET_MESH_Data *msg,
1053 * Change the tunnel state.
1055 * @param t Tunnel whose state to change.
1056 * @param state New state.
1059 tunnel_change_state (struct MeshTunnel2 *t, enum MeshTunnelState state);
1063 * Notify a tunnel that a connection has broken that affects at least
1064 * some of its peers.
1066 * @param t Tunnel affected.
1067 * @param p1 Peer that got disconnected from p2.
1068 * @param p2 Peer that got disconnected from p1.
1070 * @return Short ID of the peer disconnected (either p1 or p2).
1071 * 0 if the tunnel remained unaffected.
1073 static GNUNET_PEER_Id
1074 tunnel_notify_connection_broken (struct MeshTunnel2 *t,
1075 GNUNET_PEER_Id p1, GNUNET_PEER_Id p2);
1078 * @brief Use the given path for the tunnel.
1079 * Update the next and prev hops (and RCs).
1080 * (Re)start the path refresh in case the tunnel is locally owned.
1082 * @param t Tunnel to update.
1083 * @param p Path to use.
1085 * @return Connection created.
1087 static struct MeshConnection *
1088 tunnel_use_path (struct MeshTunnel2 *t, struct MeshPeerPath *p);
1091 * Tunnel is empty: destroy it.
1093 * Notifies all participants (peers, cleints) about the destruction.
1095 * @param t Tunnel to destroy.
1098 tunnel_destroy_empty (struct MeshTunnel2 *t);
1101 * Destroy the tunnel.
1103 * This function does not generate any warning traffic to clients or peers.
1106 * Cancel messages belonging to this tunnel queued to neighbors.
1107 * Free any allocated resources linked to the tunnel.
1109 * @param t The tunnel to destroy.
1112 tunnel_destroy (struct MeshTunnel2 *t);
1115 * Create a connection.
1117 * @param cid Connection ID.
1119 static struct MeshConnection *
1120 connection_new (const struct GNUNET_HashCode *cid);
1123 * Connection is no longer needed: destroy it and remove from tunnel.
1125 * @param c Connection to destroy.
1128 connection_destroy (struct MeshConnection *c);
1131 * Send FWD keepalive packets for a connection.
1133 * @param cls Closure (connection for which to send the keepalive).
1134 * @param tc Notification context.
1137 connection_fwd_keepalive (void *cls,
1138 const struct GNUNET_SCHEDULER_TaskContext *tc);
1141 * Send BCK keepalive packets for a connection.
1143 * @param cls Closure (connection for which to send the keepalive).
1144 * @param tc Notification context.
1147 connection_bck_keepalive (void *cls,
1148 const struct GNUNET_SCHEDULER_TaskContext *tc);
1152 * Change the tunnel state.
1154 * @param c Connection whose state to change.
1155 * @param state New state.
1158 connection_change_state (struct MeshConnection* c,
1159 enum MeshConnectionState state);
1164 * @brief Queue and pass message to core when possible.
1166 * @param cls Closure (@c type dependant). It will be used by queue_send to
1167 * build the message to be sent if not already prebuilt.
1168 * @param type Type of the message, 0 for a raw message.
1169 * @param size Size of the message.
1170 * @param c Connection this message belongs to (cannot be NULL).
1171 * @param ch Channel this message belongs to, if applicable (otherwise NULL).
1172 * @param fwd Is this a message going root->dest? (FWD ACK are NOT FWD!)
1175 queue_add (void* cls,
1178 struct MeshConnection* c,
1179 struct MeshChannel* ch,
1184 * Free a transmission that was already queued with all resources
1185 * associated to the request.
1187 * @param queue Queue handler to cancel.
1188 * @param clear_cls Is it necessary to free associated cls?
1191 queue_destroy (struct MeshPeerQueue *queue, int clear_cls);
1195 * Core callback to write a queued packet to core buffer
1197 * @param cls Closure (peer info).
1198 * @param size Number of bytes available in buf.
1199 * @param buf Where the to write the message.
1201 * @return number of bytes written to buf
1204 queue_send (void *cls, size_t size, void *buf);
1208 * Demultiplex by message type and call appropriate handler for a message
1209 * towards a channel of a local tunnel.
1211 * @param t Tunnel this message came on.
1212 * @param msgh Message header.
1213 * @param fwd Is this message fwd?
1216 handle_decrypted (struct MeshTunnel2 *t,
1217 const struct GNUNET_MessageHeader *msgh,
1222 * Dummy function to separate declarations from definitions in function list.
1225 __mesh_divider______________________________________________________________();
1229 * Get string description for tunnel state.
1231 * @param s Tunnel state.
1233 * @return String representation.
1236 GNUNET_MESH_DEBUG_TS2S (enum MeshTunnelState s)
1238 static char buf[128];
1242 case MESH_TUNNEL_NEW:
1243 return "MESH_TUNNEL_NEW";
1244 case MESH_TUNNEL_SEARCHING:
1245 return "MESH_TUNNEL_SEARCHING";
1246 case MESH_TUNNEL_WAITING:
1247 return "MESH_TUNNEL_WAITING";
1248 case MESH_TUNNEL_READY:
1249 return "MESH_TUNNEL_READY";
1250 case MESH_TUNNEL_RECONNECTING:
1251 return "MESH_TUNNEL_RECONNECTING";
1254 sprintf (buf, "%u (UNKNOWN STATE)", s);
1261 * Get string description for tunnel state.
1263 * @param s Tunnel state.
1265 * @return String representation.
1268 GNUNET_MESH_DEBUG_CS2S (enum MeshTunnelState s)
1272 case MESH_CONNECTION_NEW:
1273 return "MESH_CONNECTION_NEW";
1274 case MESH_CONNECTION_SENT:
1275 return "MESH_CONNECTION_SENT";
1276 case MESH_CONNECTION_ACK:
1277 return "MESH_CONNECTION_ACK";
1278 case MESH_CONNECTION_READY:
1279 return "MESH_CONNECTION_READY";
1281 return "MESH_CONNECTION_STATE_ERROR";
1287 /******************************************************************************/
1288 /************************ PERIODIC FUNCTIONS ****************************/
1289 /******************************************************************************/
1292 * Periodically announce self id in the DHT
1294 * @param cls closure
1295 * @param tc task context
1298 announce_id (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1300 struct PBlock block;
1302 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1304 announce_id_task = GNUNET_SCHEDULER_NO_TASK;
1308 * - Set data expiration in function of X
1309 * - Adapt X to churn
1311 DEBUG_DHT ("DHT_put for ID %s started.\n", GNUNET_i2s (&my_full_id));
1313 block.id = my_full_id;
1314 GNUNET_DHT_put (dht_handle, /* DHT handle */
1315 &my_full_id.hashPubKey, /* Key to use */
1316 dht_replication_level, /* Replication level */
1317 GNUNET_DHT_RO_RECORD_ROUTE | GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, /* DHT options */
1318 GNUNET_BLOCK_TYPE_MESH_PEER, /* Block type */
1319 sizeof (block), /* Size of the data */
1320 (const char *) &block, /* Data itself */
1321 GNUNET_TIME_UNIT_FOREVER_ABS, /* Data expiration */
1322 GNUNET_TIME_UNIT_FOREVER_REL, /* Retry time */
1323 NULL, /* Continuation */
1324 NULL); /* Continuation closure */
1326 GNUNET_SCHEDULER_add_delayed (id_announce_time, &announce_id, cls);
1330 /******************************************************************************/
1331 /****************** GENERAL HELPER FUNCTIONS ************************/
1332 /******************************************************************************/
1336 * Get the static string for a peer ID.
1340 * @return Static string for it's ID.
1343 peer2s (const struct MeshPeer *peer)
1347 return GNUNET_i2s (GNUNET_PEER_resolve2 (peer->id));
1352 * Get the previous hop in a connection
1354 * @param c Connection.
1356 * @return Previous peer in the connection.
1358 static struct MeshPeer *
1359 connection_get_prev_hop (struct MeshConnection *c)
1363 if (0 == c->own_pos || c->path->length < 2)
1364 id = c->path->peers[0];
1366 id = c->path->peers[c->own_pos - 1];
1368 return peer_get_short (id);
1373 * Get the next hop in a connection
1375 * @param c Connection.
1377 * @return Next peer in the connection.
1379 static struct MeshPeer *
1380 connection_get_next_hop (struct MeshConnection *c)
1384 if ((c->path->length - 1) == c->own_pos || c->path->length < 2)
1385 id = c->path->peers[c->path->length - 1];
1387 id = c->path->peers[c->own_pos + 1];
1389 return peer_get_short (id);
1394 * Get the hop in a connection.
1396 * @param c Connection.
1397 * @param fwd Next hop?
1399 * @return Next peer in the connection.
1401 static struct MeshPeer *
1402 connection_get_hop (struct MeshConnection *c, int fwd)
1405 return connection_get_next_hop (c);
1406 return connection_get_prev_hop (c);
1410 * Check if client has registered with the service and has not disconnected
1412 * @param client the client to check
1414 * @return non-NULL if client exists in the global DLL
1416 static struct MeshClient *
1417 client_get (struct GNUNET_SERVER_Client *client)
1419 return GNUNET_SERVER_client_get_user_context (client, struct MeshClient);
1424 * Deletes a tunnel from a client (either owner or destination).
1426 * @param c Client whose tunnel to delete.
1427 * @param ch Channel which should be deleted.
1430 client_delete_channel (struct MeshClient *c, struct MeshChannel *ch)
1436 res = GNUNET_CONTAINER_multihashmap32_remove (c->own_channels,
1438 if (GNUNET_YES != res)
1439 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client_delete_channel owner KO\n");
1443 res = GNUNET_CONTAINER_multihashmap32_remove (c->incoming_channels,
1445 if (GNUNET_YES != res)
1446 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client_delete_tunnel client KO\n");
1452 * Notify the appropriate client that a new incoming channel was created.
1454 * @param ch Channel that was created.
1457 send_local_channel_create (struct MeshChannel *ch)
1459 struct GNUNET_MESH_ChannelMessage msg;
1460 struct MeshTunnel2 *t = ch->t;
1462 if (NULL == ch->dest)
1464 msg.header.size = htons (sizeof (msg));
1465 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
1466 msg.channel_id = htonl (ch->lid_dest);
1467 msg.port = htonl (ch->port);
1469 msg.opt |= GNUNET_YES == ch->reliable ? GNUNET_MESH_OPTION_RELIABLE : 0;
1470 msg.opt |= GNUNET_YES == ch->nobuffer ? GNUNET_MESH_OPTION_NOBUFFER : 0;
1471 msg.opt = htonl (msg.opt);
1472 GNUNET_PEER_resolve (t->peer->id, &msg.peer);
1473 GNUNET_SERVER_notification_context_unicast (nc, ch->dest->handle,
1474 &msg.header, GNUNET_NO);
1479 * Notify a client that the incoming tunnel is no longer valid.
1481 * @param ch Channel that is destroyed.
1482 * @param fwd Forward notification (owner->dest)?
1485 send_local_channel_destroy (struct MeshChannel *ch, int fwd)
1487 struct GNUNET_MESH_ChannelMessage msg;
1488 struct MeshClient *c;
1490 c = fwd ? ch->dest : ch->root;
1496 msg.header.size = htons (sizeof (msg));
1497 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1498 msg.channel_id = htonl (fwd ? ch->lid_dest : ch->lid_root);
1499 msg.port = htonl (0);
1500 memset (&msg.peer, 0, sizeof (msg.peer));
1501 msg.opt = htonl (0);
1502 GNUNET_SERVER_notification_context_unicast (nc, c->handle,
1503 &msg.header, GNUNET_NO);
1508 * Build a local ACK message and send it to a local client, if needed.
1510 * If the client was already allowed to send data, do nothing.
1512 * @param ch Channel on which to send the ACK.
1513 * @param c Client to whom send the ACK.
1514 * @param fwd Set to GNUNET_YES for FWD ACK (dest->root)
1517 send_local_ack (struct MeshChannel *ch, int fwd)
1519 struct GNUNET_MESH_LocalAck msg;
1520 struct MeshChannelReliability *rel;
1521 struct MeshClient *c;
1523 c = fwd ? ch->root : ch->dest;
1524 rel = fwd ? ch->root_rel : ch->dest_rel;
1526 if (GNUNET_YES == rel->client_ready)
1527 return; /* don't send double ACKs to client */
1529 rel->client_ready = GNUNET_YES;
1531 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1532 "send local %s ack on %s:%X towards %p\n",
1533 fwd ? "FWD" : "BCK", peer2s (ch->t->peer), ch->gid, c);
1536 || ( fwd && (0 == ch->lid_root || c != ch->root))
1537 || (!fwd && (0 == ch->lid_dest || c != ch->dest)) )
1542 msg.header.size = htons (sizeof (msg));
1543 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
1544 msg.channel_id = htonl (fwd ? ch->lid_root : ch->lid_dest);
1545 GNUNET_SERVER_notification_context_unicast (nc,
1554 * Count established (ready) connections of a tunnel.
1556 * @param t Tunnel on which to send the message.
1558 * @return Number of connections.
1561 tunnel_count_connections (struct MeshTunnel2 *t)
1563 struct MeshConnection *c;
1566 for (c = t->connection_head, i = 0; NULL != c; c = c->next, i++);
1573 * Pick a connection on which send the next data message.
1575 * @param t Tunnel on which to send the message.
1576 * @param fwd Is this a fwd message?
1578 * @return The connection on which to send the next message.
1580 static struct MeshConnection *
1581 tunnel_get_connection (struct MeshTunnel2 *t, int fwd)
1583 struct MeshConnection *c;
1584 struct MeshConnection *best;
1585 struct MeshFlowControl *fc;
1586 unsigned int lowest_q;
1588 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n",
1591 lowest_q = UINT_MAX;
1592 for (c = t->connection_head; NULL != c; c = c->next)
1594 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " connection %s: %u\n",
1595 GNUNET_h2s (&c->id), c->state);
1596 if (MESH_CONNECTION_READY == c->state)
1598 fc = fwd ? &c->fwd_fc : &c->bck_fc;
1604 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " q_n %u, \n", fc->queue_n);
1605 if (fc->queue_n < lowest_q)
1608 lowest_q = fc->queue_n;
1617 * Is this peer the first one on the connection?
1619 * @param c Connection.
1620 * @param fwd Is this about fwd traffic?
1622 * @return GNUNET_YES if origin, GNUNET_NO if relay/terminal.
1625 connection_is_origin (struct MeshConnection *c, int fwd)
1627 if (!fwd && c->own_pos == c->path->length - 1)
1629 if (fwd && c->own_pos == 0)
1636 * Is this peer the last one on the connection?
1638 * @param c Connection.
1639 * @param fwd Is this about fwd traffic?
1640 * Note that the ROOT is the terminal for BCK traffic!
1642 * @return GNUNET_YES if terminal, GNUNET_NO if relay/origin.
1645 connection_is_terminal (struct MeshConnection *c, int fwd)
1647 if (fwd && c->own_pos == c->path->length - 1)
1649 if (!fwd && c->own_pos == 0)
1656 * Is the recipient client for this channel on this peer?
1658 * @param ch Channel.
1659 * @param fwd Is this for fwd traffic?
1661 * @return GNUNET_YES in case it is.
1664 channel_is_terminal (struct MeshChannel *ch, int fwd)
1666 if (NULL == ch->t || NULL == ch->t->connection_head)
1671 return connection_is_terminal (ch->t->connection_head, fwd);
1676 * Get free buffer space towards the client on a specific channel.
1678 * @param ch Channel.
1679 * @param fwd Is query about FWD traffic?
1681 * @return Free buffer space [0 - 64]
1684 channel_get_buffer (struct MeshChannel *ch, int fwd)
1686 struct MeshChannelReliability *rel;
1688 rel = fwd ? ch->dest_rel : ch->root_rel;
1690 /* If rel is NULL it means that the end is not yet created,
1691 * most probably is a loopback channel at the point of sending
1692 * the ChannelCreate to itself.
1697 return (64 - rel->n_recv);
1702 * Get free buffer space in a connection.
1704 * @param c Connection.
1705 * @param fwd Is query about FWD traffic?
1707 * @return Free buffer space [0 - max_msgs_queue/max_connections]
1710 connection_get_buffer (struct MeshConnection *c, int fwd)
1712 struct MeshFlowControl *fc;
1714 fc = fwd ? &c->fwd_fc : &c->bck_fc;
1716 return (fc->queue_max - fc->queue_n);
1721 * Get the total buffer space for a tunnel.
1724 tunnel_get_buffer (struct MeshTunnel2 *t, int fwd)
1726 struct MeshConnection *c;
1727 struct MeshFlowControl *fc;
1728 unsigned int buffer;
1730 c = t->connection_head;
1739 /* If terminal, return biggest channel buffer */
1740 if (connection_is_terminal (c, fwd))
1742 struct MeshChannel *ch;
1743 unsigned int ch_buf;
1745 if (NULL == t->channel_head)
1748 for (ch = t->channel_head; NULL != ch; ch = ch->next)
1750 ch_buf = channel_get_buffer (ch, fwd);
1751 if (ch_buf > buffer)
1757 /* If not terminal, return sum of connection buffers */
1760 if (c->state != MESH_CONNECTION_READY)
1766 fc = fwd ? &c->fwd_fc : &c->bck_fc;
1767 buffer += fc->last_ack_recv - fc->last_pid_sent;
1776 * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
1777 * Encrypt data with the tunnel key.
1779 * @param t Tunnel whose key to use.
1780 * @param dst Destination for the encrypted data.
1781 * @param src Source of the plaintext.
1782 * @param size Size of the plaintext.
1783 * @param iv Initialization Vector to use.
1784 * @param fwd Is this a fwd message?
1787 tunnel_encrypt (struct MeshTunnel2 *t,
1788 void *dst, const void *src,
1789 size_t size, uint64_t iv, int fwd)
1791 memcpy (dst, src, size);
1796 * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
1797 * Decrypt data with the tunnel key.
1799 * @param t Tunnel whose key to use.
1800 * @param dst Destination for the plaintext.
1801 * @param src Source of the encrypted data.
1802 * @param size Size of the encrypted data.
1803 * @param iv Initialization Vector to use.
1804 * @param fwd Is this a fwd message?
1807 tunnel_decrypt (struct MeshTunnel2 *t,
1808 void *dst, const void *src,
1809 size_t size, uint64_t iv, int fwd)
1811 memcpy (dst, src, size);
1816 * Sends an already built message on a connection, properly registering
1817 * all used resources.
1819 * @param message Message to send. Function makes a copy of it.
1820 * If message is not hop-by-hop, decrements TTL of copy.
1821 * @param c Connection on which this message is transmitted.
1822 * @param ch Channel on which this message is transmitted, or NULL.
1823 * @param fwd Is this a fwd message?
1826 send_prebuilt_message_connection (const struct GNUNET_MessageHeader *message,
1827 struct MeshConnection *c,
1828 struct MeshChannel *ch,
1835 size = ntohs (message->size);
1836 data = GNUNET_malloc (size);
1837 memcpy (data, message, size);
1838 type = ntohs (message->type);
1839 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send %s (%u) on connection %s\n",
1840 GNUNET_MESH_DEBUG_M2S (type), size, GNUNET_h2s (&c->id));
1844 struct GNUNET_MESH_Encrypted *emsg;
1845 struct GNUNET_MESH_ACK *amsg;
1846 struct GNUNET_MESH_Poll *pmsg;
1847 struct GNUNET_MESH_ConnectionDestroy *dmsg;
1848 struct GNUNET_MESH_ConnectionBroken *bmsg;
1851 case GNUNET_MESSAGE_TYPE_MESH_FWD:
1852 case GNUNET_MESSAGE_TYPE_MESH_BCK:
1853 emsg = (struct GNUNET_MESH_Encrypted *) data;
1854 ttl = ntohl (emsg->ttl);
1857 GNUNET_break_op (0);
1861 emsg->ttl = htonl (ttl - 1);
1862 emsg->pid = htonl (fwd ? c->fwd_fc.next_pid++ : c->bck_fc.next_pid++);
1863 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " pid %u\n", ntohl (emsg->pid));
1866 case GNUNET_MESSAGE_TYPE_MESH_ACK:
1867 amsg = (struct GNUNET_MESH_ACK *) data;
1869 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ack %u\n", ntohl (amsg->ack));
1872 case GNUNET_MESSAGE_TYPE_MESH_POLL:
1873 pmsg = (struct GNUNET_MESH_Poll *) data;
1875 pmsg->pid = htonl (fwd ? c->fwd_fc.last_pid_sent : c->bck_fc.last_pid_sent);
1876 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " poll %u\n", ntohl (pmsg->pid));
1879 case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
1880 dmsg = (struct GNUNET_MESH_ConnectionDestroy *) data;
1885 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
1886 bmsg = (struct GNUNET_MESH_ConnectionBroken *) data;
1891 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
1892 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
1909 * Sends an already built message on a tunnel, choosing the best connection.
1911 * @param message Message to send. Function modifies it.
1912 * @param t Tunnel on which this message is transmitted.
1913 * @param ch Channel on which this message is transmitted.
1914 * @param fwd Is this a fwd message?
1917 send_prebuilt_message_tunnel (struct GNUNET_MESH_Encrypted *msg,
1918 struct MeshTunnel2 *t,
1919 struct MeshChannel *ch,
1922 struct MeshConnection *c;
1925 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send on Tunnel %s\n",
1927 c = tunnel_get_connection (t, fwd);
1930 GNUNET_break (GNUNET_YES == t->destroy);
1933 type = ntohs (msg->header.type);
1936 case GNUNET_MESSAGE_TYPE_MESH_FWD:
1937 case GNUNET_MESSAGE_TYPE_MESH_BCK:
1938 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
1939 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
1941 msg->ttl = htonl (default_ttl);
1944 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
1945 GNUNET_MESH_DEBUG_M2S (type));
1950 send_prebuilt_message_connection (&msg->header, c, ch, fwd);
1955 * Sends an already built message on a channel, properly registering
1956 * all used resources and encrypting the message with the tunnel's key.
1958 * @param message Message to send. Function makes a copy of it.
1959 * @param ch Channel on which this message is transmitted.
1960 * @param fwd Is this a fwd message?
1963 send_prebuilt_message_channel (const struct GNUNET_MessageHeader *message,
1964 struct MeshChannel *ch,
1967 struct GNUNET_MESH_Encrypted *msg;
1968 size_t size = ntohs (message->size);
1969 char *cbuf[sizeof (struct GNUNET_MESH_Encrypted) + size];
1973 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send on Channel %s:%X %s\n",
1974 peer2s (ch->t->peer), ch->gid, fwd ? "FWD" : "BCK");
1975 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " %s\n",
1976 GNUNET_MESH_DEBUG_M2S (ntohs (message->type)));
1978 if (channel_is_terminal (ch, fwd))
1980 handle_decrypted (ch->t, message, fwd);
1984 type = fwd ? GNUNET_MESSAGE_TYPE_MESH_FWD : GNUNET_MESSAGE_TYPE_MESH_BCK;
1985 iv = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_NONCE, UINT64_MAX);
1987 msg = (struct GNUNET_MESH_Encrypted *) cbuf;
1988 msg->header.type = htons (type);
1989 msg->header.size = htons (sizeof (struct GNUNET_MESH_Encrypted) + size);
1990 msg->iv = GNUNET_htonll (iv);
1991 tunnel_encrypt (ch->t, &msg[1], message, size, iv, fwd);
1992 send_prebuilt_message_tunnel (msg, ch->t, ch, fwd);
1997 * Sends a CREATE CONNECTION message for a path to a peer.
1998 * Changes the connection and tunnel states if necessary.
2000 * @param connection Connection to create.
2003 send_connection_create (struct MeshConnection *connection)
2005 struct MeshTunnel2 *t;
2008 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send connection create\n");
2010 GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
2011 sizeof (struct GNUNET_MESH_ConnectionCreate) +
2012 (connection->path->length *
2013 sizeof (struct GNUNET_PeerIdentity)),
2018 (MESH_TUNNEL_SEARCHING == t->state || MESH_TUNNEL_NEW == t->state))
2019 tunnel_change_state (t, MESH_TUNNEL_WAITING);
2020 if (MESH_CONNECTION_NEW == connection->state)
2021 connection_change_state (connection, MESH_CONNECTION_SENT);
2026 * Sends a CONNECTION ACK message in reponse to a received CONNECTION_CREATE
2029 * @param connection Connection to confirm.
2030 * @param fwd Is this a fwd ACK? (First is bck (SYNACK), second is fwd (ACK))
2033 send_connection_ack (struct MeshConnection *connection, int fwd)
2035 struct MeshTunnel2 *t;
2038 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send connection ack\n");
2040 GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
2041 sizeof (struct GNUNET_MESH_ConnectionACK),
2045 if (MESH_TUNNEL_NEW == t->state)
2046 tunnel_change_state (t, MESH_TUNNEL_WAITING);
2047 if (MESH_CONNECTION_READY != connection->state)
2048 connection_change_state (connection, MESH_CONNECTION_SENT);
2053 * Core callback to write a pre-constructed data packet to core buffer
2055 * @param cls Closure (MeshTransmissionDescriptor with data in "data" member).
2056 * @param size Number of bytes available in buf.
2057 * @param buf Where the to write the message.
2059 * @return number of bytes written to buf
2062 send_core_data_raw (void *cls, size_t size, void *buf)
2064 struct GNUNET_MessageHeader *msg = cls;
2067 GNUNET_assert (NULL != msg);
2068 total_size = ntohs (msg->size);
2070 if (total_size > size)
2075 memcpy (buf, msg, total_size);
2082 * Function to send a create connection message to a peer.
2084 * @param c Connection to create.
2085 * @param size number of bytes available in buf
2086 * @param buf where the callee should write the message
2087 * @return number of bytes written to buf
2090 send_core_connection_create (struct MeshConnection *c, size_t size, void *buf)
2092 struct GNUNET_MESH_ConnectionCreate *msg;
2093 struct GNUNET_PeerIdentity *peer_ptr;
2094 struct MeshPeerPath *p = c->path;
2098 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION CREATE...\n");
2100 sizeof (struct GNUNET_MESH_ConnectionCreate) +
2101 p->length * sizeof (struct GNUNET_PeerIdentity);
2103 if (size < size_needed || NULL == buf)
2108 msg = (struct GNUNET_MESH_ConnectionCreate *) buf;
2109 msg->header.size = htons (size_needed);
2110 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE);
2113 peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
2114 for (i = 0; i < p->length; i++)
2116 GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
2119 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2120 "CONNECTION CREATE (%u bytes long) sent!\n", size_needed);
2126 * Creates a path ack message in buf and frees all unused resources.
2128 * @param c Connection to send an ACK on.
2129 * @param size number of bytes available in buf
2130 * @param buf where the callee should write the message
2132 * @return number of bytes written to buf
2135 send_core_connection_ack (struct MeshConnection *c, size_t size, void *buf)
2137 struct GNUNET_MESH_ConnectionACK *msg = buf;
2138 struct MeshTunnel2 *t = c->t;
2140 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION ACK...\n");
2141 GNUNET_assert (NULL != t);
2142 if (sizeof (struct GNUNET_MESH_ConnectionACK) > size)
2147 msg->header.size = htons (sizeof (struct GNUNET_MESH_ConnectionACK));
2148 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK);
2152 /* TODO add signature */
2154 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CONNECTION ACK sent!\n");
2155 return sizeof (struct GNUNET_MESH_ConnectionACK);
2160 * Destroy the peer_info and free any allocated resources linked to it
2162 * @param peer The peer_info to destroy.
2164 * @return GNUNET_OK on success
2167 peer_destroy (struct MeshPeer *peer)
2169 struct GNUNET_PeerIdentity id;
2170 struct MeshPeerPath *p;
2171 struct MeshPeerPath *nextp;
2173 GNUNET_PEER_resolve (peer->id, &id);
2174 GNUNET_PEER_change_rc (peer->id, -1);
2177 GNUNET_CONTAINER_multihashmap_remove (peers, &id.hashPubKey, peer))
2180 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2181 "removing peer %s, not in hashmap\n", GNUNET_i2s (&id));
2183 if (NULL != peer->dhtget)
2185 GNUNET_DHT_get_stop (peer->dhtget);
2187 p = peer->path_head;
2191 GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
2195 tunnel_destroy_empty (peer->tunnel);
2202 * Returns if peer is used (has a tunnel, is neighbor).
2204 * @peer Peer to check.
2206 * @return GNUNET_YES if peer is in use.
2209 peer_is_used (struct MeshPeer *peer)
2211 struct MeshPeerPath *p;
2213 if (NULL != peer->tunnel)
2216 for (p = peer->path_head; NULL != p; p = p->next)
2225 * Iterator over all the peers to get the oldest timestamp.
2227 * @param cls Closure (unsued).
2228 * @param key ID of the peer.
2229 * @param value Peer_Info of the peer.
2232 peer_get_oldest (void *cls,
2233 const struct GNUNET_HashCode *key,
2236 struct MeshPeer *p = value;
2237 struct GNUNET_TIME_Absolute *abs = cls;
2239 /* Don't count active peers */
2240 if (GNUNET_YES == peer_is_used (p))
2243 if (abs->abs_value_us < p->last_contact.abs_value_us)
2244 abs->abs_value_us = p->last_contact.abs_value_us;
2251 * Iterator over all the peers to remove the oldest entry.
2253 * @param cls Closure (unsued).
2254 * @param key ID of the peer.
2255 * @param value Peer_Info of the peer.
2258 peer_timeout (void *cls,
2259 const struct GNUNET_HashCode *key,
2262 struct MeshPeer *p = value;
2263 struct GNUNET_TIME_Absolute *abs = cls;
2265 if (p->last_contact.abs_value_us == abs->abs_value_us &&
2266 GNUNET_NO == peer_is_used (p))
2276 * Delete oldest unused peer.
2279 peer_delete_oldest (void)
2281 struct GNUNET_TIME_Absolute abs;
2283 abs = GNUNET_TIME_UNIT_FOREVER_ABS;
2285 GNUNET_CONTAINER_multihashmap_iterate (peers,
2288 GNUNET_CONTAINER_multihashmap_iterate (peers,
2295 * Retrieve the MeshPeer stucture associated with the peer, create one
2296 * and insert it in the appropriate structures if the peer is not known yet.
2298 * @param peer Full identity of the peer.
2300 * @return Existing or newly created peer info.
2302 static struct MeshPeer *
2303 peer_get (const struct GNUNET_PeerIdentity *peer_id)
2305 struct MeshPeer *peer;
2307 peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer_id->hashPubKey);
2310 peer = GNUNET_new (struct MeshPeer);
2311 if (GNUNET_CONTAINER_multihashmap_size (peers) > max_peers)
2313 peer_delete_oldest ();
2315 GNUNET_CONTAINER_multihashmap_put (peers, &peer_id->hashPubKey, peer,
2316 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
2317 peer->id = GNUNET_PEER_intern (peer_id);
2319 peer->last_contact = GNUNET_TIME_absolute_get();
2326 * Retrieve the MeshPeer stucture associated with the peer, create one
2327 * and insert it in the appropriate structures if the peer is not known yet.
2329 * @param peer Short identity of the peer.
2331 * @return Existing or newly created peer info.
2333 static struct MeshPeer *
2334 peer_get_short (const GNUNET_PEER_Id peer)
2336 return peer_get (GNUNET_PEER_resolve2 (peer));
2341 * Get a cost of a path for a peer considering existing tunnel connections.
2343 * @param peer Peer towards which the path is considered.
2344 * @param path Candidate path.
2346 * @return Cost of the path (path length + number of overlapping nodes)
2349 peer_get_path_cost (const struct MeshPeer *peer,
2350 const struct MeshPeerPath *path)
2352 struct MeshConnection *c;
2353 unsigned int overlap;
2361 GNUNET_assert (NULL != peer->tunnel);
2363 for (i = 0; i < path->length; i++)
2365 for (c = peer->tunnel->connection_head; NULL != c; c = c->next)
2367 for (j = 0; j < c->path->length; j++)
2369 if (path->peers[i] == c->path->peers[j])
2377 return (path->length + overlap) * (path->score * -1);
2382 * Choose the best path towards a peer considering the tunnel properties.
2384 * @param peer The destination peer.
2386 * @return Best current known path towards the peer, if any.
2388 static struct MeshPeerPath *
2389 peer_get_best_path (const struct MeshPeer *peer)
2391 struct MeshPeerPath *best_p;
2392 struct MeshPeerPath *p;
2393 struct MeshConnection *c;
2394 unsigned int best_cost;
2397 best_cost = UINT_MAX;
2399 for (p = peer->path_head; NULL != p; p = p->next)
2401 for (c = peer->tunnel->connection_head; NULL != c; c = c->next)
2405 continue; /* If path is in use in a connection, skip it. */
2407 if ((cost = peer_get_path_cost (peer, p)) < best_cost)
2417 queue_is_sendable (struct MeshPeerQueue *q)
2419 struct MeshFlowControl *fc;
2421 /* Is PID-independent? */
2424 case GNUNET_MESSAGE_TYPE_MESH_ACK:
2425 case GNUNET_MESSAGE_TYPE_MESH_POLL:
2429 /* Is PID allowed? */
2430 fc = q->fwd ? &q->c->fwd_fc : &q->c->bck_fc;
2431 if (GMC_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
2439 * Get first sendable message.
2441 * @param peer The destination peer.
2443 * @return Best current known path towards the peer, if any.
2445 static struct MeshPeerQueue *
2446 peer_get_first_message (const struct MeshPeer *peer)
2448 struct MeshPeerQueue *q;
2450 for (q = peer->queue_head; NULL != q; q = q->next)
2452 if (queue_is_sendable (q))
2461 * Try to establish a new connection to this peer in the given tunnel.
2462 * If the peer doesn't have any path to it yet, try to get one.
2463 * If the peer already has some path, send a CREATE CONNECTION towards it.
2465 * @param peer PeerInfo of the peer.
2468 peer_connect (struct MeshPeer *peer)
2470 struct MeshTunnel2 *t;
2471 struct MeshPeerPath *p;
2472 struct MeshConnection *c;
2475 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2476 "peer_connect towards %s\n",
2480 rerun_dhtget = GNUNET_NO;
2482 if (NULL != peer->path_head)
2484 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "path exists\n");
2485 p = peer_get_best_path (peer);
2488 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " %u hops\n", p->length);
2489 c = tunnel_use_path (t, p);
2492 /* This case can happen when the path includes a first hop that is
2493 * not yet known to be connected.
2495 * This happens quite often during testing when running mesh
2496 * under valgrind: core connect notifications come very late and the
2497 * DHT result has already come and created a valid path.
2498 * In this case, the peer->connections hashmap will be NULL and
2499 * tunnel_use_path will not be able to create a connection from that
2502 * Re-running the DHT GET should give core time to callback.
2505 rerun_dhtget = GNUNET_YES;
2509 send_connection_create (c);
2515 if (NULL != peer->dhtget && GNUNET_YES == rerun_dhtget)
2517 GNUNET_DHT_get_stop (peer->dhtget);
2518 peer->dhtget = NULL;
2519 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2520 " Stopping DHT GET for peer %s\n", peer2s (peer));
2523 if (NULL == peer->dhtget)
2525 const struct GNUNET_PeerIdentity *id;
2527 id = GNUNET_PEER_resolve2 (peer->id);
2528 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2529 " Starting DHT GET for peer %s\n", peer2s (peer));
2530 peer->dhtget = GNUNET_DHT_get_start (dht_handle, /* handle */
2531 GNUNET_BLOCK_TYPE_MESH_PEER, /* type */
2532 &id->hashPubKey, /* key to search */
2533 dht_replication_level, /* replication level */
2534 GNUNET_DHT_RO_RECORD_ROUTE |
2535 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
2537 0, /* xquery bits */
2538 &dht_get_id_handler, peer);
2539 if (MESH_TUNNEL_NEW == t->state)
2540 tunnel_change_state (t, MESH_TUNNEL_SEARCHING);
2546 * Get the first transmittable message for a connection.
2548 * @param c Connection.
2549 * @param fwd Is this FWD?
2551 * @return First transmittable message.
2553 static struct MeshPeerQueue *
2554 connection_get_first_message (struct MeshConnection *c, int fwd)
2556 struct MeshPeerQueue *q;
2559 p = connection_get_hop (c, fwd);
2561 for (q = p->queue_head; NULL != q; q = q->next)
2565 if (queue_is_sendable (q))
2574 * @brief Re-initiate traffic on this connection if necessary.
2576 * Check if there is traffic queued towards this peer
2577 * and the core transmit handle is NULL (traffic was stalled).
2578 * If so, call core tmt rdy.
2580 * @param c Connection on which initiate traffic.
2581 * @param fwd Is this about fwd traffic?
2584 connection_unlock_queue (struct MeshConnection *c, int fwd)
2586 struct MeshPeer *peer;
2587 struct MeshPeerQueue *q;
2590 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2591 "connection_unlock_queue %s on %s\n",
2592 fwd ? "FWD" : "BCK", GNUNET_h2s (&c->id));
2594 if (connection_is_terminal (c, fwd))
2596 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " is terminal!\n");
2600 peer = connection_get_hop (c, fwd);
2602 if (NULL != peer->core_transmit)
2604 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " already unlocked!\n");
2605 return; /* Already unlocked */
2608 q = connection_get_first_message (c, fwd);
2611 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " queue empty!\n");
2612 return; /* Nothing to transmit */
2616 peer->core_transmit =
2617 GNUNET_CORE_notify_transmit_ready (core_handle,
2620 GNUNET_TIME_UNIT_FOREVER_REL,
2621 GNUNET_PEER_resolve2 (peer->id),
2629 * Cancel all transmissions that belong to a certain connection.
2631 * @param c Connection which to cancel.
2632 * @param fwd Cancel fwd traffic?
2635 connection_cancel_queues (struct MeshConnection *c, int fwd)
2637 struct MeshPeerQueue *q;
2638 struct MeshPeerQueue *next;
2639 struct MeshFlowControl *fc;
2640 struct MeshPeer *peer;
2647 fc = fwd ? &c->fwd_fc : &c->bck_fc;
2648 peer = connection_get_hop (c, fwd);
2650 for (q = peer->queue_head; NULL != q; q = next)
2655 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2656 "connection_cancel_queue %s\n",
2657 GNUNET_MESH_DEBUG_M2S (q->type));
2658 queue_destroy (q, GNUNET_YES);
2661 if (NULL == peer->queue_head)
2663 if (NULL != peer->core_transmit)
2665 GNUNET_CORE_notify_transmit_ready_cancel (peer->core_transmit);
2666 peer->core_transmit = NULL;
2668 if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
2670 GNUNET_SCHEDULER_cancel (fc->poll_task);
2671 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2678 * Add the path to the peer and update the path used to reach it in case this
2681 * @param peer_info Destination peer to add the path to.
2682 * @param path New path to add. Last peer must be the peer in arg 1.
2683 * Path will be either used of freed if already known.
2684 * @param trusted Do we trust that this path is real?
2687 peer_add_path (struct MeshPeer *peer_info, struct MeshPeerPath *path,
2690 struct MeshPeerPath *aux;
2694 if ((NULL == peer_info) || (NULL == path))
2697 path_destroy (path);
2700 if (path->peers[path->length - 1] != peer_info->id)
2703 path_destroy (path);
2706 if (2 >= path->length && GNUNET_NO == trusted)
2708 /* Only allow CORE to tell us about direct paths */
2709 path_destroy (path);
2712 for (l = 1; l < path->length; l++)
2714 if (path->peers[l] == myid)
2716 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shortening path by %u\n", l);
2717 for (l2 = 0; l2 < path->length - l; l2++)
2719 path->peers[l2] = path->peers[l + l2];
2724 GNUNET_realloc (path->peers, path->length * sizeof (GNUNET_PEER_Id));
2728 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "adding path [%u] to peer %s\n",
2729 path->length, peer2s (peer_info));
2731 l = path_get_length (path);
2734 path_destroy (path);
2738 GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
2739 for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
2741 l2 = path_get_length (aux);
2744 GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
2745 peer_info->path_tail, aux, path);
2750 if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
2752 path_destroy (path);
2757 GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head, peer_info->path_tail,
2764 * Add the path to the origin peer and update the path used to reach it in case
2765 * this is the shortest.
2766 * The path is given in peer_info -> destination, therefore we turn the path
2767 * upside down first.
2769 * @param peer_info Peer to add the path to, being the origin of the path.
2770 * @param path New path to add after being inversed.
2771 * Path will be either used or freed.
2772 * @param trusted Do we trust that this path is real?
2775 peer_add_path_to_origin (struct MeshPeer *peer_info,
2776 struct MeshPeerPath *path, int trusted)
2781 peer_add_path (peer_info, path, trusted);
2787 * Function called if a connection has been stalled for a while,
2788 * possibly due to a missed ACK. Poll the neighbor about its ACK status.
2790 * @param cls Closure (poll ctx).
2791 * @param tc TaskContext.
2794 connection_poll (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2796 struct MeshFlowControl *fc = cls;
2797 struct GNUNET_MESH_Poll msg;
2798 struct MeshConnection *c;
2800 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2801 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2807 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** Polling!\n");
2808 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** connection %s[%X]\n",
2809 peer2s (c->t->peer), c->id);
2810 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** %s\n",
2811 fc == &c->fwd_fc ? "FWD" : "BCK");
2813 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_POLL);
2814 msg.header.size = htons (sizeof (msg));
2815 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** pid (%u)!\n", fc->last_pid_sent);
2816 send_prebuilt_message_connection (&msg.header, c, NULL, fc == &c->fwd_fc);
2817 fc->poll_time = GNUNET_TIME_STD_BACKOFF (fc->poll_time);
2818 fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
2819 &connection_poll, fc);
2824 * Build a PeerPath from the paths returned from the DHT, reversing the paths
2825 * to obtain a local peer -> destination path and interning the peer ids.
2827 * @return Newly allocated and created path
2829 static struct MeshPeerPath *
2830 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
2831 unsigned int get_path_length,
2832 const struct GNUNET_PeerIdentity *put_path,
2833 unsigned int put_path_length)
2835 struct MeshPeerPath *p;
2841 GNUNET_PEER_change_rc (myid, 1);
2842 i = get_path_length;
2843 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " GET has %d hops.\n", i);
2844 for (i--; i >= 0; i--)
2846 id = GNUNET_PEER_intern (&get_path[i]);
2847 if (p->length > 0 && id == p->peers[p->length - 1])
2849 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Optimizing 1 hop out.\n");
2850 GNUNET_PEER_change_rc (id, -1);
2854 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Adding from GET: %s.\n",
2855 GNUNET_i2s (&get_path[i]));
2857 p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2858 p->peers[p->length - 1] = id;
2861 i = put_path_length;
2862 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " PUT has %d hops.\n", i);
2863 for (i--; i >= 0; i--)
2865 id = GNUNET_PEER_intern (&put_path[i]);
2868 /* PUT path went through us, so discard the path up until now and start
2869 * from here to get a much shorter (and loop-free) path.
2874 if (p->length > 0 && id == p->peers[p->length - 1])
2876 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Optimizing 1 hop out.\n");
2877 GNUNET_PEER_change_rc (id, -1);
2881 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Adding from PUT: %s.\n",
2882 GNUNET_i2s (&put_path[i]));
2884 p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2885 p->peers[p->length - 1] = id;
2889 if (get_path_length > 0)
2890 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " (first of GET: %s)\n",
2891 GNUNET_i2s (&get_path[0]));
2892 if (put_path_length > 0)
2893 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " (first of PUT: %s)\n",
2894 GNUNET_i2s (&put_path[0]));
2895 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " In total: %d hops\n",
2897 for (i = 0; i < p->length; i++)
2899 struct GNUNET_PeerIdentity peer_id;
2901 GNUNET_PEER_resolve (p->peers[i], &peer_id);
2902 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " %u: %s\n", p->peers[i],
2903 GNUNET_i2s (&peer_id));
2911 * Adds a path to the peer_infos of all the peers in the path
2913 * @param p Path to process.
2914 * @param confirmed Whether we know if the path works or not.
2917 path_add_to_peers (struct MeshPeerPath *p, int confirmed)
2921 /* TODO: invert and add */
2922 for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
2923 for (i++; i < p->length; i++)
2925 struct MeshPeer *aux;
2926 struct MeshPeerPath *copy;
2928 aux = peer_get_short (p->peers[i]);
2929 copy = path_duplicate (p);
2930 copy->length = i + 1;
2931 peer_add_path (aux, copy, p->length < 3 ? GNUNET_NO : confirmed);
2937 * Search for a channel among the channels for a client
2939 * @param c the client whose channels to search in
2940 * @param chid the local id of the channel
2942 * @return channel handler, NULL if doesn't exist
2944 static struct MeshChannel *
2945 channel_get_by_local_id (struct MeshClient *c, MESH_ChannelNumber chid)
2947 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " -- get CHID %X\n", chid);
2948 if (0 == (chid & GNUNET_MESH_LOCAL_CHANNEL_ID_CLI))
2950 GNUNET_break_op (0);
2951 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CHID %X not a local chid\n", chid);
2954 if (chid >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV)
2955 return GNUNET_CONTAINER_multihashmap32_get (c->incoming_channels, chid);
2956 return GNUNET_CONTAINER_multihashmap32_get (c->own_channels, chid);
2962 channel_debug (struct MeshChannel *ch)
2966 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*** DEBUG NULL CHANNEL ***\n");
2969 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Channel %s:%X\n",
2970 peer2s (ch->t->peer), ch->gid);
2971 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " root %p/%p\n",
2972 ch->root, ch->root_rel);
2973 if (NULL != ch->root)
2975 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " cli %u\n", ch->root->id);
2976 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ready %s\n",
2977 ch->root_rel->client_ready ? "YES" : "NO");
2978 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " id %X\n", ch->lid_root);
2980 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " root %p/%p\n",
2981 ch->dest, ch->dest_rel);
2982 if (NULL != ch->dest)
2984 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " cli %u\n", ch->dest->id);
2985 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ready %s\n",
2986 ch->dest_rel->client_ready ? "YES" : "NO");
2987 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " id %X\n", ch->lid_dest);
2992 fc_debug (struct MeshFlowControl *fc)
2994 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " IN: %u/%u\n",
2995 fc->last_pid_recv, fc->last_ack_sent);
2996 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " OUT: %u/%u\n",
2997 fc->last_pid_sent, fc->last_ack_recv);
2998 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " QUEUE: %u/%u\n",
2999 fc->queue_n, fc->queue_max);
3003 connection_debug (struct MeshConnection *c)
3007 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*** DEBUG NULL CONNECTION ***\n");
3010 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connection %s:%X\n",
3011 peer2s (c->t->peer), GNUNET_h2s (&c->id));
3012 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " state: %u, pending msgs: %u\n",
3013 c->state, c->pending_messages);
3014 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " FWD FC\n");
3015 fc_debug (&c->fwd_fc);
3016 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " BCK FC\n");
3017 fc_debug (&c->bck_fc);
3022 static struct MeshChannel *
3023 channel_get (struct MeshTunnel2 *t, MESH_ChannelNumber chid)
3025 struct MeshChannel *ch;
3030 for (ch = t->channel_head; NULL != ch; ch = ch->next)
3032 if (ch->gid == chid)
3041 * Change the tunnel state.
3043 * @param t Tunnel whose state to change.
3044 * @param state New state.
3047 tunnel_change_state (struct MeshTunnel2* t, enum MeshTunnelState state)
3051 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3052 "Tunnel %s state was %s\n",
3054 GNUNET_MESH_DEBUG_TS2S (t->state));
3055 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3056 "Tunnel %s state is now %s\n",
3058 GNUNET_MESH_DEBUG_TS2S (state));
3064 * Cache a message to be sent once tunnel is online.
3066 * @param t Tunnel to hold the message.
3067 * @param ch Channel the message is about.
3068 * @param msg Message itself (copy will be made).
3069 * @param fwd Is this fwd?
3072 tunnel_queue_data (struct MeshTunnel2 *t,
3073 struct MeshChannel *ch,
3074 struct GNUNET_MessageHeader *msg,
3077 struct MeshTunnelQueue *tq;
3078 uint16_t size = ntohs (msg->size);
3080 tq = GNUNET_malloc (sizeof (struct MeshTunnelQueue) + size);
3083 memcpy (&tq[1], msg, size);
3084 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tq);
3089 * Send all cached messages that we can, tunnel is online.
3091 * @param t Tunnel that holds the messages.
3092 * @param fwd Is this fwd?
3095 tunnel_send_queued_data (struct MeshTunnel2 *t, int fwd)
3097 struct MeshTunnelQueue *tq;
3098 struct MeshTunnelQueue *next;
3101 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3102 "tunnel_send_queued_data on tunnel %s\n",
3104 room = tunnel_get_buffer (t, fwd);
3105 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
3106 for (tq = t->tq_head; NULL != tq && room > 0; tq = next)
3110 GNUNET_CONTAINER_DLL_remove (t->tq_head, t->tq_tail, tq);
3111 send_prebuilt_message_channel ((struct GNUNET_MessageHeader *) &tq[1],
3120 connection_change_state (struct MeshConnection* c,
3121 enum MeshConnectionState state)
3123 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3124 "Connection %s state was %s\n",
3125 GNUNET_h2s (&c->id), GNUNET_MESH_DEBUG_CS2S (c->state));
3126 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3127 "Connection %s state is now %s\n",
3128 GNUNET_h2s (&c->id), GNUNET_MESH_DEBUG_CS2S (state));
3134 * Add a client to a channel, initializing all needed data structures.
3136 * @param ch Channel to which add the client.
3137 * @param c Client which to add to the channel.
3140 channel_add_client (struct MeshChannel *ch, struct MeshClient *c)
3142 struct MeshTunnel2 *t = ch->t;
3144 if (NULL != ch->dest)
3150 /* Assign local id as destination */
3151 while (NULL != channel_get_by_local_id (c, t->next_local_chid))
3152 t->next_local_chid = (t->next_local_chid + 1) | GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
3153 ch->lid_dest = t->next_local_chid++;
3154 t->next_local_chid = t->next_local_chid | GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
3156 /* Store in client's hashmap */
3158 GNUNET_CONTAINER_multihashmap32_put (c->incoming_channels,
3160 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3166 GNUNET_break (NULL == ch->dest_rel);
3167 ch->dest_rel = GNUNET_new (struct MeshChannelReliability);
3168 ch->dest_rel->ch = ch;
3169 ch->dest_rel->expected_delay = MESH_RETRANSMIT_TIME;
3175 static struct MeshConnection *
3176 tunnel_use_path (struct MeshTunnel2 *t, struct MeshPeerPath *p)
3178 struct MeshConnection *c;
3179 struct GNUNET_HashCode cid;
3180 struct MeshPeer *peer;
3181 unsigned int own_pos;
3183 if (NULL == t || NULL == p)
3189 GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE, &cid);
3191 c = connection_new (&cid);
3193 GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, c);
3194 for (own_pos = 0; own_pos < p->length; own_pos++)
3196 if (p->peers[own_pos] == myid)
3199 if (own_pos > p->length - 1)
3202 connection_destroy (c);
3205 c->own_pos = own_pos;
3210 c->fwd_maintenance_task =
3211 GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
3212 &connection_fwd_keepalive, c);
3215 peer = connection_get_next_hop (c);
3216 if (NULL == peer->connections)
3218 connection_destroy (c);
3221 GNUNET_CONTAINER_multihashmap_put (peer->connections, &c->id, c,
3222 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
3223 peer = connection_get_prev_hop (c);
3224 if (NULL == peer->connections)
3226 connection_destroy (c);
3229 GNUNET_CONTAINER_multihashmap_put (peer->connections, &c->id, c,
3230 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
3236 * Notifies a tunnel that a connection has broken that affects at least
3237 * some of its peers. Sends a notification towards the root of the tree.
3238 * In case the peer is the owner of the tree, notifies the client that owns
3239 * the tunnel and tries to reconnect.
3241 * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
3243 * @param t Tunnel affected.
3244 * @param p1 Peer that got disconnected from p2.
3245 * @param p2 Peer that got disconnected from p1.
3247 * @return Short ID of the peer disconnected (either p1 or p2).
3248 * 0 if the tunnel remained unaffected.
3250 static GNUNET_PEER_Id
3251 tunnel_notify_connection_broken (struct MeshTunnel2* t,
3252 GNUNET_PEER_Id p1, GNUNET_PEER_Id p2)
3254 // if (myid != p1 && myid != p2) FIXME
3259 // if (tree_get_predecessor (t->tree) != 0)
3261 // /* We are the peer still connected, notify owner of the disconnection. */
3262 // struct GNUNET_MESH_PathBroken msg;
3263 // struct GNUNET_PeerIdentity neighbor;
3265 // msg.header.size = htons (sizeof (msg));
3266 // msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN);
3267 // GNUNET_PEER_resolve (t->id.oid, &msg.oid);
3268 // msg.tid = htonl (t->id.tid);
3269 // msg.peer1 = my_full_id;
3270 // GNUNET_PEER_resolve (pid, &msg.peer2);
3271 // GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &neighbor);
3272 // send_prebuilt_message (&msg.header, &neighbor, t);
3279 * Send an end-to-end ACK message for the most recent in-sequence payload.
3281 * If channel is not reliable, do nothing.
3283 * @param ch Channel this is about.
3284 * @param fwd Is for FWD traffic? (ACK dest->owner)
3287 channel_send_data_ack (struct MeshChannel *ch, int fwd)
3289 struct GNUNET_MESH_DataACK msg;
3290 struct MeshChannelReliability *rel;
3291 struct MeshReliableMessage *copy;
3296 if (GNUNET_NO == ch->reliable)
3300 rel = fwd ? ch->dest_rel : ch->root_rel;
3301 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3302 "send_data_ack for %u\n",
3305 type = GNUNET_MESSAGE_TYPE_MESH_DATA_ACK;
3306 msg.header.type = htons (type);
3307 msg.header.size = htons (sizeof (msg));
3308 msg.chid = htonl (ch->gid);
3309 msg.mid = htonl (rel->mid_recv - 1);
3311 for (copy = rel->head_recv; NULL != copy; copy = copy->next)
3313 if (copy->type != type)
3315 delta = copy->mid - rel->mid_recv;
3318 mask = 0x1LL << delta;
3319 msg.futures |= mask;
3320 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3321 " setting bit for %u (delta %u) (%llX) -> %llX\n",
3322 copy->mid, delta, mask, msg.futures);
3324 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " final futures %llX\n", msg.futures);
3326 send_prebuilt_message_channel (&msg.header, ch, fwd);
3327 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_data_ack END\n");
3332 * Send an ACK informing the predecessor about the available buffer space.
3334 * Note that for fwd ack, the FWD mean forward *traffic* (root->dest),
3335 * the ACK itself goes "back" (dest->root).
3337 * @param c Connection on which to send the ACK.
3338 * @param buffer How much space free to advertise?
3339 * @param fwd Is this FWD ACK? (Going dest->owner)
3342 connection_send_ack (struct MeshConnection *c, unsigned int buffer, int fwd)
3344 struct MeshFlowControl *next_fc;
3345 struct MeshFlowControl *prev_fc;
3346 struct GNUNET_MESH_ACK msg;
3350 next_fc = fwd ? &c->fwd_fc : &c->bck_fc;
3351 prev_fc = fwd ? &c->bck_fc : &c->fwd_fc;
3353 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3354 "connection send %s ack on %s\n",
3355 fwd ? "FWD" : "BCK", GNUNET_h2s (&c->id));
3357 /* Check if we need to transmit the ACK */
3358 if (prev_fc->last_ack_sent - prev_fc->last_pid_recv > 3)
3360 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer > 3\n");
3361 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3362 " last pid recv: %u, last ack sent: %u\n",
3363 prev_fc->last_pid_recv, prev_fc->last_ack_sent);
3367 /* Ok, ACK might be necessary, what PID to ACK? */
3368 delta = next_fc->queue_max - next_fc->queue_n;
3369 ack = prev_fc->last_pid_recv + delta;
3370 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", ack);
3371 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3372 " last pid %u, last ack %u, qmax %u, q %u\n",
3373 prev_fc->last_pid_recv, prev_fc->last_ack_sent,
3374 next_fc->queue_max, next_fc->queue_n);
3375 if (ack == prev_fc->last_ack_sent)
3377 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not needed\n");
3381 prev_fc->last_ack_sent = ack;
3383 /* Build ACK message and send on connection */
3384 msg.header.size = htons (sizeof (msg));
3385 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ACK);
3386 msg.ack = htonl (ack);
3389 send_prebuilt_message_connection (&msg.header, c, NULL, !fwd);
3394 * Modify the mesh message TID from global to local and send to client.
3396 * @param ch Channel on which to send the message.
3397 * @param msg Message to modify and send.
3398 * @param c Client to send to.
3399 * @param tid Tunnel ID to use (c can be both owner and client).
3402 channel_send_client_to_tid (struct MeshChannel *ch,
3403 const struct GNUNET_MESH_Data *msg,
3404 struct MeshClient *c, MESH_ChannelNumber id)
3406 struct GNUNET_MESH_LocalData *copy;
3407 uint16_t size = ntohs (msg->header.size) - sizeof (struct GNUNET_MESH_Data);
3408 char cbuf[size + sizeof (struct GNUNET_MESH_LocalData)];
3410 if (size < sizeof (struct GNUNET_MessageHeader))
3412 GNUNET_break_op (0);
3420 copy = (struct GNUNET_MESH_LocalData *) cbuf;
3421 memcpy (©[1], &msg[1], size);
3422 copy->header.size = htons (sizeof (struct GNUNET_MESH_LocalData) + size);
3423 copy->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA);
3424 copy->id = htonl (id);
3425 GNUNET_SERVER_notification_context_unicast (nc, c->handle,
3426 ©->header, GNUNET_NO);
3431 * We have received a message out of order, or the client is not ready.
3432 * Buffer it until we receive an ACK from the client or the missing
3433 * message from the channel.
3435 * @param msg Message to buffer (MUST be of type MESH_DATA).
3436 * @param rel Reliability data to the corresponding direction.
3439 channel_rel_add_buffered_data (const struct GNUNET_MESH_Data *msg,
3440 struct MeshChannelReliability *rel)
3442 struct MeshReliableMessage *copy;
3443 struct MeshReliableMessage *prev;
3447 size = ntohs (msg->header.size);
3448 mid = ntohl (msg->mid);
3450 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data %u\n", mid);
3452 copy = GNUNET_malloc (sizeof (*copy) + size);
3455 memcpy (©[1], msg, size);
3459 // FIXME do something better than O(n), although n < 64...
3460 // FIXME start from the end (most messages are the latest ones)
3461 for (prev = rel->head_recv; NULL != prev; prev = prev->next)
3463 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " prev %u\n", prev->mid);
3464 if (GMC_is_pid_bigger (prev->mid, mid))
3466 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " bingo!\n");
3467 GNUNET_CONTAINER_DLL_insert_before (rel->head_recv, rel->tail_recv,
3472 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " insert at tail!\n");
3473 GNUNET_CONTAINER_DLL_insert_tail (rel->head_recv, rel->tail_recv, copy);
3474 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data END\n");
3479 channel_send_client_data (struct MeshChannel *ch,
3480 const struct GNUNET_MESH_Data *msg,
3485 if (ch->dest_rel->client_ready)
3486 channel_send_client_to_tid (ch, msg, ch->dest, ch->lid_dest);
3488 channel_rel_add_buffered_data (msg, ch->dest_rel);
3492 if (ch->root_rel->client_ready)
3493 channel_send_client_to_tid (ch, msg, ch->root, ch->lid_root);
3495 channel_rel_add_buffered_data (msg, ch->root_rel);
3501 * Send a buffered message to the client, for in order delivery or
3502 * as result of client ACK.
3504 * @param ch Channel on which to empty the message buffer.
3505 * @param c Client to send to.
3506 * @param rel Reliability structure to corresponding peer.
3507 * If rel == bck_rel, this is FWD data.
3510 channel_send_client_buffered_data (struct MeshChannel *ch,
3511 struct MeshClient *c,
3514 struct MeshReliableMessage *copy;
3515 struct MeshChannelReliability *rel;
3517 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data\n");
3518 rel = fwd ? ch->dest_rel : ch->root_rel;
3519 if (GNUNET_NO == rel->client_ready)
3521 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client not ready\n");
3525 copy = rel->head_recv;
3526 /* We never buffer channel management messages */
3529 if (copy->mid == rel->mid_recv || GNUNET_NO == ch->reliable)
3531 struct GNUNET_MESH_Data *msg = (struct GNUNET_MESH_Data *) ©[1];
3533 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3534 " have %u! now expecting %u\n",
3535 copy->mid, rel->mid_recv + 1);
3536 channel_send_client_data (ch, msg, fwd);
3539 GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
3544 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3545 " reliable && don't have %u, next is %u\n",
3551 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data END\n");
3556 * Destroy a reliable message after it has been acknowledged, either by
3557 * direct mid ACK or bitfield. Updates the appropriate data structures and
3558 * timers and frees all memory.
3560 * @param copy Message that is no longer needed: remote peer got it.
3563 rel_message_free (struct MeshReliableMessage *copy)
3565 struct MeshChannelReliability *rel;
3566 struct GNUNET_TIME_Relative time;
3569 time = GNUNET_TIME_absolute_get_duration (copy->timestamp);
3570 rel->expected_delay.rel_value_us *= 7;
3571 rel->expected_delay.rel_value_us += time.rel_value_us;
3572 rel->expected_delay.rel_value_us /= 8;
3574 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Freeing %u\n", copy->mid);
3575 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " n_sent %u\n", rel->n_sent);
3576 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! took %s\n",
3577 GNUNET_STRINGS_relative_time_to_string (time, GNUNET_NO));
3578 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! new expected delay %s\n",
3579 GNUNET_STRINGS_relative_time_to_string (rel->expected_delay,
3581 rel->retry_timer = rel->expected_delay;
3582 GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
3588 * Destroy all reliable messages queued for a channel,
3589 * during a channel destruction.
3590 * Frees the reliability structure itself.
3592 * @param rel Reliability data for a channel.
3595 channel_rel_free_all (struct MeshChannelReliability *rel)
3597 struct MeshReliableMessage *copy;
3598 struct MeshReliableMessage *next;
3603 for (copy = rel->head_recv; NULL != copy; copy = next)
3606 GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
3609 for (copy = rel->head_sent; NULL != copy; copy = next)
3612 GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
3615 if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
3616 GNUNET_SCHEDULER_cancel (rel->retry_task);
3622 * Mark future messages as ACK'd.
3624 * @param rel Reliability data.
3625 * @param msg DataACK message with a bitfield of future ACK'd messages.
3628 channel_rel_free_sent (struct MeshChannelReliability *rel,
3629 const struct GNUNET_MESH_DataACK *msg)
3631 struct MeshReliableMessage *copy;
3632 struct MeshReliableMessage *next;
3639 bitfield = msg->futures;
3640 mid = ntohl (msg->mid);
3641 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3642 "free_sent_reliable %u %llX\n",
3644 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3645 " rel %p, head %p\n",
3646 rel, rel->head_sent);
3647 for (i = 0, copy = rel->head_sent;
3648 i < 64 && NULL != copy && 0 != bitfield;
3651 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3652 " trying bit %u (mid %u)\n",
3655 if (0 == (bitfield & mask))
3658 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " set!\n");
3659 /* Bit was set, clear the bit from the bitfield */
3662 /* The i-th bit was set. Do we have that copy? */
3663 /* Skip copies with mid < target */
3664 target = mid + i + 1;
3665 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " target %u\n", target);
3666 while (NULL != copy && GMC_is_pid_bigger (target, copy->mid))
3669 /* Did we run out of copies? (previously freed, it's ok) */
3672 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "run out of copies...\n");
3676 /* Did we overshoot the target? (previously freed, it's ok) */
3677 if (GMC_is_pid_bigger (copy->mid, target))
3679 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " next copy %u\n", copy->mid);
3683 /* Now copy->mid == target, free it */
3685 rel_message_free (copy);
3688 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "free_sent_reliable END\n");
3693 * We haven't received an ACK after a certain time: restransmit the message.
3695 * @param cls Closure (MeshReliableMessage with the message to restransmit)
3696 * @param tc TaskContext.
3699 channel_retransmit_message (void *cls,
3700 const struct GNUNET_SCHEDULER_TaskContext *tc)
3702 struct MeshChannelReliability *rel = cls;
3703 struct MeshReliableMessage *copy;
3704 struct MeshPeerQueue *q;
3705 struct MeshChannel *ch;
3706 struct MeshConnection *c;
3707 struct GNUNET_MESH_Data *payload;
3708 struct MeshPeer *hop;
3711 rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
3712 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3716 copy = rel->head_sent;
3723 /* Search the message to be retransmitted in the outgoing queue.
3724 * Check only the queue for the connection that is going to be used,
3725 * if the message is stuck in some other connection's queue we shouldn't
3727 * - cancelling it and sending the new one doesn't guarantee it's delivery,
3728 * the old connection could be temporary stalled or the queue happened to
3729 * be long at time of insertion.
3730 * - not sending the new one could cause terrible delays the old connection
3733 payload = (struct GNUNET_MESH_Data *) ©[1];
3734 fwd = (rel == ch->root_rel);
3735 c = tunnel_get_connection (ch->t, fwd);
3736 hop = connection_get_hop (c, fwd);
3737 for (q = hop->queue_head; NULL != q; q = q->next)
3739 if (ntohs (payload->header.type) == q->type && ch == q->ch)
3741 struct GNUNET_MESH_Data *queued_data = q->cls;
3743 if (queued_data->mid == payload->mid)
3748 /* Message not found in the queue that we are going to use. */
3751 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! RETRANSMIT %u\n", copy->mid);
3753 send_prebuilt_message_channel (&payload->header, ch, fwd);
3754 GNUNET_STATISTICS_update (stats, "# data retransmitted", 1, GNUNET_NO);
3758 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! ALREADY IN QUEUE %u\n", copy->mid);
3761 rel->retry_timer = GNUNET_TIME_STD_BACKOFF (rel->retry_timer);
3762 rel->retry_task = GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
3763 &channel_retransmit_message,
3769 * Send ACK on one or more connections due to buffer space to the client.
3771 * Iterates all connections of the tunnel and sends ACKs appropriately.
3773 * @param ch Channel which has some free buffer space.
3774 * @param fwd Is this in for FWD traffic? (ACK goes dest->root)
3777 channel_send_connections_ack (struct MeshChannel *ch,
3778 unsigned int buffer,
3781 struct MeshTunnel2 *t = ch->t;
3782 struct MeshConnection *c;
3783 struct MeshFlowControl *fc;
3786 uint32_t allow_per_connection;
3789 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3790 "Channel send connection %s ack on %s:%X\n",
3791 fwd ? "FWD" : "BCK", peer2s (ch->t->peer), ch->gid);
3793 /* Count connections, how many messages are already allowed */
3794 for (cs = 0, allowed = 0, c = t->connection_head; NULL != c; c = c->next)
3796 fc = fwd ? &c->fwd_fc : &c->bck_fc;
3797 if (GMC_is_pid_bigger(fc->last_pid_recv, fc->last_ack_sent))
3802 allowed += fc->last_ack_sent - fc->last_pid_recv;
3806 /* Make sure there is no overflow */
3807 if (allowed > buffer)
3813 /* Authorize connections to send more data */
3814 to_allow = buffer - allowed;
3816 for (c = t->connection_head; NULL != c && to_allow > 0; c = c->next)
3818 allow_per_connection = to_allow/cs;
3819 to_allow -= allow_per_connection;
3821 fc = fwd ? &c->fwd_fc : &c->bck_fc;
3822 if (fc->last_ack_sent - fc->last_pid_recv > 64 / 3)
3826 connection_send_ack (c, allow_per_connection, fwd);
3829 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3830 "Channel send connection %s ack on %s:%X\n",
3831 fwd ? "FWD" : "BCK", peer2s (ch->t->peer), ch->gid);
3832 GNUNET_break (to_allow == 0);
3837 * Send an ACK on the appropriate connection/channel, depending on
3838 * the direction and the position of the peer.
3840 * @param c Which connection to send the hop-by-hop ACK.
3841 * @param ch Channel, if any.
3842 * @param fwd Is this a fwd ACK? (will go dest->root)
3845 send_ack (struct MeshConnection *c, struct MeshChannel *ch, int fwd)
3847 unsigned int buffer;
3849 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3850 "send ack %s on %p %p\n",
3851 fwd ? "FWD" : "BCK", c, ch);
3852 if (NULL == c || connection_is_terminal (c, fwd))
3854 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " getting from Channel\n");
3855 buffer = tunnel_get_buffer (NULL == c ? ch->t : c->t, fwd);
3859 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " getting from Connection\n");
3860 GNUNET_assert (NULL != c);
3861 buffer = connection_get_buffer (c, fwd);
3863 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " buffer available: %u\n", buffer);
3867 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " sending on all connections\n");
3868 GNUNET_assert (NULL != ch);
3869 channel_send_connections_ack (ch, buffer, fwd);
3871 else if (connection_is_origin (c, fwd))
3873 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " sending on channel...\n");
3876 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " really sending!\n");
3877 GNUNET_assert (NULL != ch);
3878 send_local_ack (ch, fwd);
3883 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " sending on connection\n");
3884 connection_send_ack (c, buffer, fwd);
3890 * Channel was ACK'd by remote peer, mark as ready and cancel retransmission.
3892 * @param ch Channel to mark as ready.
3893 * @param fwd Was the CREATE message sent fwd?
3896 channel_confirm (struct MeshChannel *ch, int fwd)
3898 struct MeshChannelReliability *rel;
3899 struct MeshReliableMessage *copy;
3900 struct MeshReliableMessage *next;
3902 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3903 " channel confirm %s %s:%X\n",
3904 fwd ? "FWD" : "BCK", peer2s (ch->t->peer), ch->gid);
3905 ch->state = MESH_CHANNEL_READY;
3907 rel = fwd ? ch->root_rel : ch->dest_rel;
3908 for (copy = rel->head_sent; NULL != copy; copy = next)
3910 struct GNUNET_MessageHeader *msg;
3913 msg = (struct GNUNET_MessageHeader *) ©[1];
3914 if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE)
3916 rel_message_free (copy);
3920 if (GNUNET_NO == rel->client_ready)
3921 send_local_ack (ch, fwd);
3926 * Save a copy to retransmit in case it gets lost.
3928 * Initializes all needed callbacks and timers.
3930 * @param ch Channel this message goes on.
3931 * @param msg Message to copy.
3932 * @param fwd Is this fwd traffic?
3935 channel_save_copy (struct MeshChannel *ch,
3936 const struct GNUNET_MessageHeader *msg,
3939 struct MeshChannelReliability *rel;
3940 struct MeshReliableMessage *copy;
3945 rel = fwd ? ch->root_rel : ch->dest_rel;
3946 mid = rel->mid_send;
3947 type = ntohs (msg->type);
3948 size = ntohs (msg->size);
3950 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! SAVE %u\n", mid);
3951 copy = GNUNET_malloc (sizeof (struct MeshReliableMessage) + size);
3953 copy->timestamp = GNUNET_TIME_absolute_get ();
3956 memcpy (©[1], msg, size);
3958 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " n_sent %u\n", rel->n_sent);
3959 GNUNET_CONTAINER_DLL_insert_tail (rel->head_sent, rel->tail_sent, copy);
3960 if (GNUNET_SCHEDULER_NO_TASK == rel->retry_task)
3963 GNUNET_TIME_relative_multiply (rel->expected_delay,
3964 MESH_RETRANSMIT_MARGIN);
3966 GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
3967 &channel_retransmit_message,
3974 * Send keepalive packets for a connection.
3976 * @param c Connection to keep alive..
3977 * @param fwd Is this a FWD keepalive? (owner -> dest).
3980 connection_keepalive (struct MeshConnection *c, int fwd)
3982 struct GNUNET_MESH_ConnectionKeepAlive *msg;
3983 size_t size = sizeof (struct GNUNET_MESH_ConnectionKeepAlive);
3987 type = fwd ? GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE :
3988 GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE;
3990 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3991 "sending %s keepalive for connection %s[%d]\n",
3992 fwd ? "FWD" : "BCK",
3993 peer2s (c->t->peer),
3996 msg = (struct GNUNET_MESH_ConnectionKeepAlive *) cbuf;
3997 msg->header.size = htons (size);
3998 msg->header.type = htons (type);
4001 send_prebuilt_message_connection (&msg->header, c, NULL, fwd);
4006 * Send CONNECTION_{CREATE/ACK} packets for a connection.
4008 * @param c Connection for which to send the message.
4009 * @param fwd If GNUNET_YES, send CREATE, otherwise send ACK.
4012 connection_recreate (struct MeshConnection *c, int fwd)
4014 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "sending connection recreate\n");
4016 send_connection_create (c);
4018 send_connection_ack (c, GNUNET_NO);
4023 * Generic connection timer management.
4024 * Depending on the role of the peer in the connection will send the
4025 * appropriate message (build or keepalive)
4027 * @param c Conncetion to maintain.
4028 * @param fwd Is FWD?
4031 connection_maintain (struct MeshConnection *c, int fwd)
4033 if (MESH_TUNNEL_SEARCHING == c->t->state)
4035 /* TODO DHT GET with RO_BART */
4040 case MESH_CONNECTION_NEW:
4042 case MESH_CONNECTION_SENT:
4043 connection_recreate (c, fwd);
4045 case MESH_CONNECTION_READY:
4046 connection_keepalive (c, fwd);
4055 connection_fwd_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4057 struct MeshConnection *c = cls;
4059 c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4060 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4063 connection_maintain (c, GNUNET_YES);
4064 c->fwd_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
4065 &connection_fwd_keepalive,
4071 connection_bck_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4073 struct MeshConnection *c = cls;
4075 c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4076 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4079 connection_maintain (c, GNUNET_NO);
4080 c->bck_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
4081 &connection_bck_keepalive,
4087 * Send a message to all peers in this connection that the connection
4088 * is no longer valid.
4090 * If some peer should not receive the message, it should be zero'ed out
4091 * before calling this function.
4093 * @param c The connection whose peers to notify.
4096 connection_send_destroy (struct MeshConnection *c)
4098 struct GNUNET_MESH_ConnectionDestroy msg;
4100 msg.header.size = htons (sizeof (msg));
4101 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);;
4103 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4104 " sending connection destroy for connection %s[%X]\n",
4105 peer2s (c->t->peer),
4108 if (GNUNET_NO == connection_is_terminal (c, GNUNET_YES))
4109 send_prebuilt_message_connection (&msg.header, c, NULL, GNUNET_YES);
4110 if (GNUNET_NO == connection_is_terminal (c, GNUNET_NO))
4111 send_prebuilt_message_connection (&msg.header, c, NULL, GNUNET_NO);
4112 c->destroy = GNUNET_YES;
4117 * Confirm we got a channel create.
4119 * @param ch The channel to confirm.
4120 * @param fwd Should we send the ACK fwd?
4123 channel_send_ack (struct MeshChannel *ch, int fwd)
4125 struct GNUNET_MESH_ChannelManage msg;
4127 msg.header.size = htons (sizeof (msg));
4128 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK);
4129 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4130 " sending channel %s ack for channel %s:%X\n",
4131 fwd ? "FWD" : "BCK", peer2s (ch->t->peer),
4134 msg.chid = htonl (ch->gid);
4135 send_prebuilt_message_channel (&msg.header, ch, !fwd);
4140 * Send a message to all clients (local and remote) of this channel
4141 * notifying that the channel is no longer valid.
4143 * If some peer or client should not receive the message,
4144 * should be zero'ed out before calling this function.
4146 * @param ch The channel whose clients to notify.
4149 channel_send_destroy (struct MeshChannel *ch)
4151 struct GNUNET_MESH_ChannelManage msg;
4153 msg.header.size = htons (sizeof (msg));
4154 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY);
4155 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4156 " sending channel destroy for channel %s:%X\n",
4157 peer2s (ch->t->peer),
4160 if (channel_is_terminal (ch, GNUNET_NO))
4162 if (NULL != ch->root && GNUNET_NO == ch->root->shutting_down)
4164 msg.chid = htonl (ch->lid_root);
4165 send_local_channel_destroy (ch, GNUNET_NO);
4170 msg.chid = htonl (ch->gid);
4171 send_prebuilt_message_channel (&msg.header, ch, GNUNET_NO);
4174 if (channel_is_terminal (ch, GNUNET_YES))
4176 if (NULL != ch->dest && GNUNET_NO == ch->dest->shutting_down)
4178 msg.chid = htonl (ch->lid_dest);
4179 send_local_channel_destroy (ch, GNUNET_YES);
4184 msg.chid = htonl (ch->gid);
4185 send_prebuilt_message_channel (&msg.header, ch, GNUNET_YES);
4193 static struct MeshTunnel2 *
4196 struct MeshTunnel2 *t;
4198 t = GNUNET_new (struct MeshTunnel2);
4200 t->next_local_chid = GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
4202 // GNUNET_CONTAINER_multihashmap_put (tunnels, tid, t,
4203 // GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
4205 // GNUNET_break (0);
4206 // tunnel_destroy (t);
4210 // char salt[] = "salt";
4211 // GNUNET_CRYPTO_kdf (&t->e_key, sizeof (struct GNUNET_CRYPTO_AesSessionKey),
4212 // salt, sizeof (salt),
4213 // &t->e_key, sizeof (struct GNUNET_CRYPTO_AesSessionKey),
4214 // &my_full_id, sizeof (struct GNUNET_PeerIdentity),
4215 // GNUNET_PEER_resolve2 (t->peer->id), sizeof (struct GNUNET_PeerIdentity),
4217 // GNUNET_CRYPTO_kdf (&t->d_key, sizeof (struct GNUNET_CRYPTO_AesSessionKey),
4218 // salt, sizeof (salt),
4219 // &t->d_key, sizeof (struct GNUNET_CRYPTO_AesSessionKey),
4220 // GNUNET_PEER_resolve2 (t->peer->id), sizeof (struct GNUNET_PeerIdentity),
4221 // &my_full_id, sizeof (struct GNUNET_PeerIdentity),
4229 * Add a connection to a tunnel.
4232 * @param c Connection.
4235 tunnel_add_connection (struct MeshTunnel2 *t, struct MeshConnection *c)
4237 struct MeshConnection *aux;
4239 for (aux = t->connection_head; aux != NULL; aux = aux->next)
4242 GNUNET_CONTAINER_DLL_insert_tail (t->connection_head, t->connection_tail, c);
4247 * Initialize a Flow Control structure to the initial state.
4249 * @param fc Flow Control structure to initialize.
4252 fc_init (struct MeshFlowControl *fc)
4255 fc->last_pid_sent = (uint32_t) -1; /* Next (expected) = 0 */
4256 fc->last_pid_recv = (uint32_t) -1;
4257 fc->last_ack_sent = (uint32_t) 0;
4258 fc->last_ack_recv = (uint32_t) 0;
4259 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
4260 fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
4262 fc->queue_max = (max_msgs_queue / max_connections) + 1;
4266 static struct MeshConnection *
4267 connection_new (const struct GNUNET_HashCode *cid)
4269 struct MeshConnection *c;
4271 c = GNUNET_new (struct MeshConnection);
4273 GNUNET_CONTAINER_multihashmap_put (connections, &c->id, c,
4274 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
4275 fc_init (&c->fwd_fc);
4276 fc_init (&c->bck_fc);
4285 * Find a connection.
4287 * @param cid Connection ID.
4289 static struct MeshConnection *
4290 connection_get (const struct GNUNET_HashCode *cid)
4292 return GNUNET_CONTAINER_multihashmap_get (connections, cid);
4297 connection_destroy (struct MeshConnection *c)
4299 struct MeshPeer *peer;
4304 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying connection %s[%X]\n",
4305 peer2s (c->t->peer),
4308 /* Cancel all traffic */
4309 connection_cancel_queues (c, GNUNET_YES);
4310 connection_cancel_queues (c, GNUNET_NO);
4312 /* Cancel maintainance task (keepalive/timeout) */
4313 if (GNUNET_SCHEDULER_NO_TASK != c->fwd_maintenance_task)
4314 GNUNET_SCHEDULER_cancel (c->fwd_maintenance_task);
4315 if (GNUNET_SCHEDULER_NO_TASK != c->bck_maintenance_task)
4316 GNUNET_SCHEDULER_cancel (c->bck_maintenance_task);
4318 /* Deregister from neighbors */
4319 peer = connection_get_next_hop (c);
4320 if (NULL != peer && NULL != peer->connections)
4321 GNUNET_CONTAINER_multihashmap_remove (peer->connections, &c->id, c);
4322 peer = connection_get_prev_hop (c);
4323 if (NULL != peer && NULL != peer->connections)
4324 GNUNET_CONTAINER_multihashmap_remove (peer->connections, &c->id, c);
4327 GNUNET_STATISTICS_update (stats, "# connections", -1, GNUNET_NO);
4328 GNUNET_CONTAINER_DLL_remove (c->t->connection_head, c->t->connection_tail, c);
4334 tunnel_destroy (struct MeshTunnel2 *t)
4336 struct MeshConnection *c;
4337 struct MeshConnection *next;
4342 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n",
4345 // if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &t->id, t))
4346 // GNUNET_break (0);
4348 for (c = t->connection_head; NULL != c; c = next)
4351 connection_destroy (c);
4354 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
4361 * Tunnel is empty: destroy it.
4363 * Notifies all connections about the destruction.
4365 * @param t Tunnel to destroy.
4368 tunnel_destroy_empty (struct MeshTunnel2 *t)
4370 struct MeshConnection *c;
4372 for (c = t->connection_head; NULL != c; c = c->next)
4374 if (GNUNET_NO == c->destroy)
4375 connection_send_destroy (c);
4378 if (0 == t->pending_messages)
4381 t->destroy = GNUNET_YES;
4386 * Destroy tunnel if empty (no more channels).
4388 * @param t Tunnel to destroy if empty.
4391 tunnel_destroy_if_empty (struct MeshTunnel2 *t)
4393 if (NULL != t->channel_head)
4396 tunnel_destroy_empty (t);
4401 * Destroy a channel and free all resources.
4403 * @param ch Channel to destroy.
4406 channel_destroy (struct MeshChannel *ch)
4408 struct MeshClient *c;
4416 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap32_remove (c->own_channels,
4427 GNUNET_CONTAINER_multihashmap32_remove (c->incoming_channels,
4434 channel_rel_free_all (ch->root_rel);
4435 channel_rel_free_all (ch->dest_rel);
4437 GNUNET_CONTAINER_DLL_remove (ch->t->channel_head, ch->t->channel_tail, ch);
4438 GNUNET_STATISTICS_update (stats, "# channels", -1, GNUNET_NO);
4444 * Create a new channel.
4446 * @param t Tunnel this channel is in.
4447 * @param owner Client that owns the channel, NULL for foreign channels.
4448 * @param lid_root Local ID for root client.
4450 * @return A new initialized channel. NULL on error.
4452 static struct MeshChannel *
4453 channel_new (struct MeshTunnel2 *t,
4454 struct MeshClient *owner, MESH_ChannelNumber lid_root)
4456 struct MeshChannel *ch;
4458 ch = GNUNET_new (struct MeshChannel);
4460 ch->lid_root = lid_root;
4463 GNUNET_STATISTICS_update (stats, "# channels", 1, GNUNET_NO);
4467 while (NULL != channel_get (t, t->next_chid))
4469 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists (%p)...\n",
4470 t->next_chid, channel_get (t, t->next_chid));
4471 t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
4473 ch->gid = t->next_chid;
4474 t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
4477 GNUNET_CONTAINER_multihashmap32_put (owner->own_channels, lid_root, ch,
4478 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
4481 channel_destroy (ch);
4482 GNUNET_SERVER_receive_done (owner->handle, GNUNET_SYSERR);
4486 GNUNET_CONTAINER_DLL_insert (t->channel_head, t->channel_tail, ch);
4493 * Set options in a channel, extracted from a bit flag field
4495 * @param ch Channel to set options to.
4496 * @param options Bit array in host byte order.
4499 channel_set_options (struct MeshChannel *ch, uint32_t options)
4501 ch->nobuffer = (options & GNUNET_MESH_OPTION_NOBUFFER) != 0 ?
4502 GNUNET_YES : GNUNET_NO;
4503 ch->reliable = (options & GNUNET_MESH_OPTION_RELIABLE) != 0 ?
4504 GNUNET_YES : GNUNET_NO;
4509 * Iterator for deleting each channel whose client endpoint disconnected.
4511 * @param cls Closure (client that has disconnected).
4512 * @param key The local channel id (used to access the hashmap).
4513 * @param value The value stored at the key (channel to destroy).
4515 * @return GNUNET_OK, keep iterating.
4518 channel_destroy_iterator (void *cls,
4522 struct MeshChannel *ch = value;
4523 struct MeshClient *c = cls;
4524 struct MeshTunnel2 *t;
4526 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4527 " Channel %X (%X / %X) destroy, due to client %u shutdown.\n",
4528 ch->gid, ch->lid_root, ch->lid_dest, c->id);
4532 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is destination.\n", c->id);
4536 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is owner.\n", c->id);
4540 channel_send_destroy (ch);
4541 channel_destroy (ch);
4542 tunnel_destroy_if_empty (t);
4549 * Remove client's ports from the global hashmap on disconnect.
4551 * @param cls Closure (unused).
4553 * @param value Client structure.
4555 * @return GNUNET_OK, keep iterating.
4558 client_release_ports (void *cls,
4564 res = GNUNET_CONTAINER_multihashmap32_remove (ports, key, value);
4565 if (GNUNET_YES != res)
4568 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4569 "Port %u by client %p was not registered.\n",
4577 * Timeout function due to lack of keepalive/traffic from the owner.
4578 * Destroys connection if called.
4580 * @param cls Closure (connection to destroy).
4581 * @param tc TaskContext.
4584 connection_fwd_timeout (void *cls,
4585 const struct GNUNET_SCHEDULER_TaskContext *tc)
4587 struct MeshConnection *c = cls;
4589 c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4590 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4592 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4593 "Connection %s[%X] FWD timed out. Destroying.\n",
4594 peer2s (c->t->peer),
4597 if (connection_is_origin (c, GNUNET_YES)) /* If local, leave. */
4600 connection_destroy (c);
4605 * Timeout function due to lack of keepalive/traffic from the destination.
4606 * Destroys connection if called.
4608 * @param cls Closure (connection to destroy).
4609 * @param tc TaskContext
4612 connection_bck_timeout (void *cls,
4613 const struct GNUNET_SCHEDULER_TaskContext *tc)
4615 struct MeshConnection *c = cls;
4617 c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4618 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4621 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4622 "Connection %s[%X] FWD timed out. Destroying.\n",
4623 peer2s (c->t->peer),
4626 if (connection_is_origin (c, GNUNET_NO)) /* If local, leave. */
4629 connection_destroy (c);
4634 * Resets the connection timeout task, some other message has done the
4636 * - For the first peer on the direction this means to send
4637 * a keepalive or a path confirmation message (either create or ACK).
4638 * - For all other peers, this means to destroy the connection,
4639 * due to lack of activity.
4640 * Starts the tiemout if no timeout was running (connection just created).
4642 * @param c Connection whose timeout to reset.
4643 * @param fwd Is this forward?
4645 * TODO use heap to improve efficiency of scheduler.
4648 connection_reset_timeout (struct MeshConnection *c, int fwd)
4650 GNUNET_SCHEDULER_TaskIdentifier *ti;
4651 GNUNET_SCHEDULER_Task f;
4653 ti = fwd ? &c->fwd_maintenance_task : &c->bck_maintenance_task;
4655 if (GNUNET_SCHEDULER_NO_TASK != *ti)
4656 GNUNET_SCHEDULER_cancel (*ti);
4658 if (connection_is_origin (c, fwd)) /* Endpoint */
4660 f = fwd ? &connection_fwd_keepalive : &connection_bck_keepalive;
4661 *ti = GNUNET_SCHEDULER_add_delayed (refresh_connection_time, f, c);
4665 struct GNUNET_TIME_Relative delay;
4667 delay = GNUNET_TIME_relative_multiply (refresh_connection_time, 4);
4668 f = fwd ? &connection_fwd_timeout : &connection_bck_timeout;
4669 *ti = GNUNET_SCHEDULER_add_delayed (delay, f, c);
4675 * Iterator to notify all connections of a broken link. Mark connections
4676 * to destroy after all traffic has been sent.
4678 * @param cls Closure (peer disconnected).
4679 * @param key Current key code (tid).
4680 * @param value Value in the hash map (connection).
4682 * @return GNUNET_YES if we should continue to iterate,
4686 connection_broken (void *cls,
4687 const struct GNUNET_HashCode *key,
4690 struct MeshPeer *peer = cls;
4691 struct MeshConnection *c = value;
4692 struct GNUNET_MESH_ConnectionBroken msg;
4695 fwd = peer == connection_get_prev_hop (c);
4697 connection_cancel_queues (c, !fwd);
4698 if (connection_is_terminal (c, fwd))
4700 /* Local shutdown, no one to notify about this. */
4701 connection_destroy (c);
4705 msg.header.size = htons (sizeof (struct GNUNET_MESH_ConnectionBroken));
4706 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN);
4708 msg.peer1 = my_full_id;
4709 msg.peer2 = *GNUNET_PEER_resolve2 (peer->id);
4710 send_prebuilt_message_connection (&msg.header, c, NULL, fwd);
4711 c->destroy = GNUNET_YES;
4716 /******************************************************************************/
4717 /**************** MESH NETWORK HANDLER HELPERS ***********************/
4718 /******************************************************************************/
4721 * Free a transmission that was already queued with all resources
4722 * associated to the request.
4724 * @param queue Queue handler to cancel.
4725 * @param clear_cls Is it necessary to free associated cls?
4728 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
4730 struct MeshPeer *peer;
4731 struct MeshFlowControl *fc;
4736 GNUNET_assert (NULL != queue->c);
4737 fc = fwd ? &queue->c->fwd_fc : &queue->c->bck_fc;
4739 if (GNUNET_YES == clear_cls)
4741 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " queue destroy type %s\n",
4742 GNUNET_MESH_DEBUG_M2S (queue->type));
4743 switch (queue->type)
4745 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
4746 case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
4747 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "destroying a DESTROY message\n");
4748 GNUNET_break (GNUNET_YES == queue->c->destroy);
4750 case GNUNET_MESSAGE_TYPE_MESH_FWD:
4751 case GNUNET_MESSAGE_TYPE_MESH_BCK:
4752 case GNUNET_MESSAGE_TYPE_MESH_ACK:
4753 case GNUNET_MESSAGE_TYPE_MESH_POLL:
4754 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
4755 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
4756 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
4757 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " prebuilt message\n");;
4758 GNUNET_free_non_null (queue->cls);
4763 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, " type %s unknown!\n",
4764 GNUNET_MESH_DEBUG_M2S (queue->type));
4768 GNUNET_CONTAINER_DLL_remove (peer->queue_head, peer->queue_tail, queue);
4770 if (queue->type != GNUNET_MESSAGE_TYPE_MESH_ACK &&
4771 queue->type != GNUNET_MESSAGE_TYPE_MESH_POLL)
4773 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Q_N- %p %u\n", fc, fc->queue_n);
4777 if (NULL != queue->c)
4779 queue->c->pending_messages--;
4780 if (NULL != queue->c->t)
4782 queue->c->t->pending_messages--;
4786 GNUNET_free (queue);
4791 queue_send (void *cls, size_t size, void *buf)
4793 struct MeshPeer *peer = cls;
4794 struct MeshFlowControl *fc;
4795 struct MeshConnection *c;
4796 struct GNUNET_MessageHeader *msg;
4797 struct MeshPeerQueue *queue;
4798 struct MeshTunnel2 *t;
4799 struct MeshChannel *ch;
4800 const struct GNUNET_PeerIdentity *dst_id;
4806 peer->core_transmit = NULL;
4807 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Queue send (max %u)\n", size);
4809 if (NULL == buf || 0 == size)
4811 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Buffer size 0.\n");
4816 queue = peer_get_first_message (peer);
4819 GNUNET_break (0); /* Core tmt_rdy should've been canceled */
4824 fc = fwd ? &c->fwd_fc : &c->bck_fc;
4827 dst_id = GNUNET_PEER_resolve2 (peer->id);
4828 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* towards %s\n", GNUNET_i2s (dst_id));
4829 /* Check if buffer size is enough for the message */
4830 if (queue->size > size)
4832 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* not enough room, reissue\n");
4833 peer->core_transmit =
4834 GNUNET_CORE_notify_transmit_ready (core_handle,
4837 GNUNET_TIME_UNIT_FOREVER_REL,
4844 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* size %u ok\n", queue->size);
4846 t = (NULL != c) ? c->t : NULL;
4850 switch (queue->type)
4852 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
4853 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
4854 case GNUNET_MESSAGE_TYPE_MESH_FWD:
4855 case GNUNET_MESSAGE_TYPE_MESH_BCK:
4856 case GNUNET_MESSAGE_TYPE_MESH_ACK:
4857 case GNUNET_MESSAGE_TYPE_MESH_POLL:
4858 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4860 GNUNET_MESH_DEBUG_M2S (queue->type));
4861 data_size = send_core_data_raw (queue->cls, size, buf);
4862 msg = (struct GNUNET_MessageHeader *) buf;
4863 type = ntohs (msg->type);
4865 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
4866 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* path create\n");
4867 if (connection_is_origin (c, GNUNET_YES))
4868 data_size = send_core_connection_create (queue->c, size, buf);
4870 data_size = send_core_data_raw (queue->cls, size, buf);
4872 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
4873 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* path ack\n");
4874 if (connection_is_origin (c, GNUNET_NO) ||
4875 connection_is_origin (c, GNUNET_YES))
4876 data_size = send_core_connection_ack (queue->c, size, buf);
4878 data_size = send_core_data_raw (queue->cls, size, buf);
4880 case GNUNET_MESSAGE_TYPE_MESH_DATA:
4881 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
4882 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
4883 /* This should be encapsulted */
4889 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "* type unknown: %u\n",
4894 if (0 < drop_percent &&
4895 GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 101) < drop_percent)
4897 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4898 "Dropping message of type %s\n",
4899 GNUNET_MESH_DEBUG_M2S (queue->type));
4903 /* Free queue, but cls was freed by send_core_* */
4905 queue_destroy (queue, GNUNET_NO);
4907 /* Send ACK if needed, after accounting for sent ID in fc->queue_n */
4910 case GNUNET_MESSAGE_TYPE_MESH_FWD:
4911 case GNUNET_MESSAGE_TYPE_MESH_BCK:
4912 pid = ntohl ( ((struct GNUNET_MESH_Encrypted *) buf)->pid );
4913 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* accounting pid %u\n", pid);
4914 fc->last_pid_sent = pid;
4915 send_ack (c, ch, fwd);
4921 /* If more data in queue, send next */
4922 queue = peer_get_first_message (peer);
4925 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* more data!\n");
4926 if (NULL == peer->core_transmit) {
4927 peer->core_transmit =
4928 GNUNET_CORE_notify_transmit_ready(core_handle,
4931 GNUNET_TIME_UNIT_FOREVER_REL,
4939 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4940 "* tmt rdy called somewhere else\n");
4942 if (GNUNET_SCHEDULER_NO_TASK == fc->poll_task)
4944 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* starting poll timeout\n");
4946 GNUNET_SCHEDULER_add_delayed (fc->poll_time, &connection_poll, fc);
4951 if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
4953 GNUNET_SCHEDULER_cancel (fc->poll_task);
4954 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
4959 c->pending_messages--;
4960 if (GNUNET_YES == c->destroy && 0 == c->pending_messages)
4962 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* destroying connection!\n");
4963 connection_destroy (c);
4969 t->pending_messages--;
4970 if (GNUNET_YES == t->destroy && 0 == t->pending_messages)
4972 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* destroying tunnel!\n");
4976 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Return %d\n", data_size);
4982 queue_add (void *cls, uint16_t type, size_t size,
4983 struct MeshConnection *c,
4984 struct MeshChannel *ch,
4987 struct MeshPeerQueue *queue;
4988 struct MeshFlowControl *fc;
4989 struct MeshPeer *peer;
4993 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4994 "queue add %s %s (%u) on c %p, ch %p\n",
4995 fwd ? "FWD" : "BCK", GNUNET_MESH_DEBUG_M2S (type), size, c, ch);
4996 GNUNET_assert (NULL != c);
4998 fc = fwd ? &c->fwd_fc : &c->bck_fc;
4999 peer = fwd ? connection_get_next_hop (c) : connection_get_prev_hop (c);
5009 if (GNUNET_MESSAGE_TYPE_MESH_POLL == type ||
5010 GNUNET_MESSAGE_TYPE_MESH_ACK == type)
5015 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "priority %d\n", priority);
5016 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "fc %p\n", fc);
5017 if (fc->queue_n >= fc->queue_max && 0 == priority)
5019 GNUNET_STATISTICS_update (stats, "# messages dropped (buffer full)",
5022 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5023 "queue full: %u/%u\n",
5024 fc->queue_n, fc->queue_max);
5025 return; /* Drop this message */
5028 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "last pid %u\n", fc->last_pid_sent);
5029 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ack %u\n", fc->last_ack_recv);
5030 if (GMC_is_pid_bigger (fc->last_pid_sent + 1, fc->last_ack_recv))
5032 call_core = GNUNET_NO;
5033 if (GNUNET_SCHEDULER_NO_TASK == fc->poll_task &&
5034 GNUNET_MESSAGE_TYPE_MESH_POLL != type)
5036 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5037 "no buffer space (%u > %u): starting poll\n",
5038 fc->last_pid_sent + 1, fc->last_ack_recv);
5039 fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
5045 call_core = GNUNET_YES;
5046 queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
5054 if (100 <= priority)
5056 GNUNET_CONTAINER_DLL_insert (peer->queue_head, peer->queue_tail, queue);
5060 GNUNET_CONTAINER_DLL_insert_tail (peer->queue_head, peer->queue_tail, queue);
5061 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Q_N+ %p %u\n", fc, fc->queue_n);
5066 if (NULL == peer->core_transmit && GNUNET_YES == call_core)
5068 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5069 "calling core tmt rdy towards %s for %u bytes\n",
5070 peer2s (peer), size);
5071 peer->core_transmit =
5072 GNUNET_CORE_notify_transmit_ready (core_handle,
5075 GNUNET_TIME_UNIT_FOREVER_REL,
5076 GNUNET_PEER_resolve2 (peer->id),
5083 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5084 "core tmt rdy towards %s already called\n",
5088 c->pending_messages++;
5090 c->t->pending_messages++;
5094 /******************************************************************************/
5095 /******************** MESH NETWORK HANDLERS **************************/
5096 /******************************************************************************/
5100 * Generic handler for mesh network payload traffic.
5102 * @param t Tunnel on which we got this message.
5103 * @param message Unencryted data message.
5104 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5107 handle_data (struct MeshTunnel2 *t, const struct GNUNET_MESH_Data *msg, int fwd)
5109 struct MeshChannelReliability *rel;
5110 struct MeshChannel *ch;
5111 struct MeshClient *c;
5117 size = ntohs (msg->header.size);
5119 sizeof (struct GNUNET_MESH_Data) +
5120 sizeof (struct GNUNET_MessageHeader))
5125 type = ntohs (msg->header.type);
5126 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message\n",
5127 GNUNET_MESH_DEBUG_M2S (type));
5128 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
5129 GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5132 ch = channel_get (t, ntohl (msg->chid));
5135 GNUNET_STATISTICS_update (stats, "# data on unknown channel", 1, GNUNET_NO);
5136 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
5141 /* Initialize FWD/BCK data */
5142 c = fwd ? ch->dest : ch->root;
5143 rel = fwd ? ch->dest_rel : ch->root_rel;
5151 tunnel_change_state (t, MESH_TUNNEL_READY);
5153 GNUNET_STATISTICS_update (stats, "# data received", 1, GNUNET_NO);
5155 mid = ntohl (msg->mid);
5156 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " mid %u\n", mid);
5158 if (GNUNET_NO == ch->reliable ||
5159 ( !GMC_is_pid_bigger (rel->mid_recv, mid) &&
5160 GMC_is_pid_bigger (rel->mid_recv + 64, mid) ) )
5162 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! RECV %u\n", mid);
5163 if (GNUNET_YES == ch->reliable)
5165 /* Is this the exact next expected messasge? */
5166 if (mid == rel->mid_recv)
5168 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "as expected\n");
5170 channel_send_client_data (ch, msg, fwd);
5174 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "save for later\n");
5175 channel_rel_add_buffered_data (msg, rel);
5180 /* Tunnel is unreliable: send to clients directly */
5181 /* FIXME: accept Out Of Order traffic */
5182 rel->mid_recv = mid + 1;
5183 channel_send_client_data (ch, msg, fwd);
5188 GNUNET_break_op (0);
5189 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5190 " MID %u not expected (%u - %u), dropping!\n",
5191 mid, rel->mid_recv, rel->mid_recv + 64);
5194 channel_send_data_ack (ch, fwd);
5198 * Handler for mesh network traffic end-to-end ACKs.
5200 * @param t Tunnel on which we got this message.
5201 * @param message Data message.
5202 * @param fwd Is this a fwd ACK? (dest->orig)
5205 handle_data_ack (struct MeshTunnel2 *t,
5206 const struct GNUNET_MESH_DataACK *msg, int fwd)
5208 struct MeshChannelReliability *rel;
5209 struct MeshReliableMessage *copy;
5210 struct MeshReliableMessage *next;
5211 struct MeshChannel *ch;
5216 type = ntohs (msg->header.type);
5217 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a %s message!\n",
5218 GNUNET_MESH_DEBUG_M2S (type));
5219 ch = channel_get (t, ntohl (msg->chid));
5222 GNUNET_STATISTICS_update (stats, "# ack on unknown channel", 1, GNUNET_NO);
5225 ack = ntohl (msg->mid);
5226 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! %s ACK %u\n",
5227 (GNUNET_YES == fwd) ? "FWD" : "BCK", ack);
5229 if (GNUNET_YES == fwd)
5243 for (work = GNUNET_NO, copy = rel->head_sent; copy != NULL; copy = next)
5245 if (GMC_is_pid_bigger (copy->mid, ack))
5247 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! head %u, out!\n", copy->mid);
5248 channel_rel_free_sent (rel, msg);
5252 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! id %u\n", copy->mid);
5254 rel_message_free (copy);
5256 /* ACK client if needed */
5257 // channel_send_ack (t, type, GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK == type);
5259 /* If some message was free'd, update the retransmission delay*/
5260 if (GNUNET_YES == work)
5262 if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
5264 GNUNET_SCHEDULER_cancel (rel->retry_task);
5265 if (NULL == rel->head_sent)
5267 rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
5271 struct GNUNET_TIME_Absolute new_target;
5272 struct GNUNET_TIME_Relative delay;
5274 delay = GNUNET_TIME_relative_multiply (rel->retry_timer,
5275 MESH_RETRANSMIT_MARGIN);
5276 new_target = GNUNET_TIME_absolute_add (rel->head_sent->timestamp,
5278 delay = GNUNET_TIME_absolute_get_remaining (new_target);
5280 GNUNET_SCHEDULER_add_delayed (delay,
5281 &channel_retransmit_message,
5292 * Core handler for connection creation.
5294 * @param cls Closure (unused).
5295 * @param peer Sender (neighbor).
5296 * @param message Message.
5298 * @return GNUNET_OK to keep the connection open,
5299 * GNUNET_SYSERR to close it (signal serious error)
5302 handle_mesh_connection_create (void *cls,
5303 const struct GNUNET_PeerIdentity *peer,
5304 const struct GNUNET_MessageHeader *message)
5306 struct GNUNET_MESH_ConnectionCreate *msg;
5307 struct GNUNET_PeerIdentity *id;
5308 struct GNUNET_HashCode *cid;
5309 struct MeshPeerPath *path;
5310 struct MeshPeer *dest_peer;
5311 struct MeshPeer *orig_peer;
5312 struct MeshConnection *c;
5313 unsigned int own_pos;
5317 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
5318 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection create msg\n");
5321 size = ntohs (message->size);
5322 if (size < sizeof (struct GNUNET_MESH_ConnectionCreate))
5324 GNUNET_break_op (0);
5328 /* Calculate hops */
5329 size -= sizeof (struct GNUNET_MESH_ConnectionCreate);
5330 if (size % sizeof (struct GNUNET_PeerIdentity))
5332 GNUNET_break_op (0);
5335 size /= sizeof (struct GNUNET_PeerIdentity);
5338 GNUNET_break_op (0);
5341 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " path has %u hops.\n", size);
5343 /* Get parameters */
5344 msg = (struct GNUNET_MESH_ConnectionCreate *) message;
5346 id = (struct GNUNET_PeerIdentity *) &msg[1];
5347 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5348 " connection %s (%s).\n",
5349 GNUNET_h2s (cid), GNUNET_i2s (id));
5351 /* Create connection */
5352 c = connection_get (cid);
5355 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Creating connection\n");
5356 c = connection_new (cid);
5359 connection_reset_timeout (c, GNUNET_YES);
5362 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Creating path...\n");
5363 path = path_new (size);
5365 for (i = 0; i < size; i++)
5367 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... adding %s\n",
5368 GNUNET_i2s (&id[i]));
5369 path->peers[i] = GNUNET_PEER_intern (&id[i]);
5370 if (path->peers[i] == myid)
5373 if (own_pos == 0 && path->peers[own_pos] != myid)
5375 /* create path: self not found in path through self */
5376 GNUNET_break_op (0);
5377 path_destroy (path);
5378 connection_destroy (c);
5381 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Own position: %u\n", own_pos);
5382 path_add_to_peers (path, GNUNET_NO);
5383 c->path = path_duplicate (path);
5384 c->own_pos = own_pos;
5390 if (MESH_CONNECTION_NEW == c->state)
5391 connection_change_state (c, MESH_CONNECTION_SENT);
5393 /* Remember peers */
5394 dest_peer = peer_get (&id[size - 1]);
5395 orig_peer = peer_get (&id[0]);
5397 /* Is it a connection to us? */
5398 if (c->own_pos == size - 1)
5400 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " It's for us!\n");
5401 peer_add_path_to_origin (orig_peer, path, GNUNET_YES);
5403 if (NULL == orig_peer->tunnel)
5405 orig_peer->tunnel = tunnel_new ();
5406 orig_peer->tunnel->peer = orig_peer;
5408 tunnel_add_connection (orig_peer->tunnel, c);
5409 if (MESH_TUNNEL_NEW == c->t->state)
5410 tunnel_change_state (c->t, MESH_TUNNEL_WAITING);
5412 send_connection_ack (c, GNUNET_NO);
5413 if (MESH_CONNECTION_SENT == c->state)
5414 connection_change_state (c, MESH_CONNECTION_ACK);
5416 /* Keep tunnel alive in direction dest->owner*/
5417 connection_reset_timeout (c, GNUNET_NO);
5421 /* It's for somebody else! Retransmit. */
5422 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Retransmitting.\n");
5423 peer_add_path (dest_peer, path_duplicate (path), GNUNET_NO);
5424 peer_add_path_to_origin (orig_peer, path, GNUNET_NO);
5425 send_prebuilt_message_connection (message, c, NULL, GNUNET_YES);
5432 * Core handler for path ACKs
5434 * @param cls closure
5435 * @param message message
5436 * @param peer peer identity this notification is about
5438 * @return GNUNET_OK to keep the connection open,
5439 * GNUNET_SYSERR to close it (signal serious error)
5442 handle_mesh_connection_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5443 const struct GNUNET_MessageHeader *message)
5445 struct GNUNET_MESH_ConnectionACK *msg;
5446 struct MeshConnection *c;
5447 struct MeshPeerPath *p;
5448 struct MeshPeer *pi;
5451 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
5452 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection ACK msg\n");
5453 msg = (struct GNUNET_MESH_ConnectionACK *) message;
5454 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " on connection %s\n",
5455 GNUNET_h2s (&msg->cid));
5456 c = connection_get (&msg->cid);
5459 GNUNET_STATISTICS_update (stats, "# control on unknown connection",
5461 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " don't know the connection!\n");
5466 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " via peer %s\n",
5468 pi = peer_get (peer);
5469 if (connection_get_next_hop (c) == pi)
5471 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " SYNACK\n");
5473 if (MESH_CONNECTION_SENT == c->state)
5474 connection_change_state (c, MESH_CONNECTION_ACK);
5476 else if (connection_get_prev_hop (c) == pi)
5478 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ACK\n");
5480 connection_change_state (c, MESH_CONNECTION_READY);
5484 GNUNET_break_op (0);
5487 connection_reset_timeout (c, fwd);
5489 /* Add path to peers? */
5493 path_add_to_peers (p, GNUNET_YES);
5500 /* Message for us as creator? */
5501 if (connection_is_origin (c, GNUNET_YES))
5503 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Connection (SYN)ACK for us!\n");
5504 connection_change_state (c, MESH_CONNECTION_READY);
5505 if (MESH_TUNNEL_READY != c->t->state)
5506 tunnel_change_state (c->t, MESH_TUNNEL_READY);
5507 send_connection_ack (c, GNUNET_YES);
5508 tunnel_send_queued_data (c->t, GNUNET_YES);
5509 if (3 <= tunnel_count_connections (c->t) && NULL != c->t->peer->dhtget)
5511 GNUNET_DHT_get_stop (c->t->peer->dhtget);
5512 c->t->peer->dhtget = NULL;
5517 /* Message for us as destination? */
5518 if (connection_is_terminal (c, GNUNET_YES))
5520 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Connection ACK for us!\n");
5521 if (MESH_TUNNEL_READY != c->t->state)
5522 tunnel_change_state (c->t, MESH_TUNNEL_READY);
5523 connection_change_state (c, MESH_CONNECTION_READY);
5524 tunnel_send_queued_data (c->t, GNUNET_NO);
5528 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " not for us, retransmitting...\n");
5529 send_prebuilt_message_connection (message, c, NULL, fwd);
5535 * Core handler for notifications of broken paths
5537 * @param cls Closure (unused).
5538 * @param peer Peer identity of sending neighbor.
5539 * @param message Message.
5541 * @return GNUNET_OK to keep the connection open,
5542 * GNUNET_SYSERR to close it (signal serious error)
5545 handle_mesh_connection_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
5546 const struct GNUNET_MessageHeader *message)
5548 struct GNUNET_MESH_ConnectionBroken *msg;
5549 struct MeshConnection *c;
5551 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5552 "Received a CONNECTION BROKEN msg from %s\n", GNUNET_i2s (peer));
5553 msg = (struct GNUNET_MESH_ConnectionBroken *) message;
5554 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " regarding %s\n",
5555 GNUNET_i2s (&msg->peer1));
5556 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " regarding %s\n",
5557 GNUNET_i2s (&msg->peer2));
5558 c = connection_get (&msg->cid);
5561 GNUNET_break_op (0);
5564 tunnel_notify_connection_broken (c->t, GNUNET_PEER_search (&msg->peer1),
5565 GNUNET_PEER_search (&msg->peer2));
5572 * Core handler for tunnel destruction
5574 * @param cls Closure (unused).
5575 * @param peer Peer identity of sending neighbor.
5576 * @param message Message.
5578 * @return GNUNET_OK to keep the connection open,
5579 * GNUNET_SYSERR to close it (signal serious error)
5582 handle_mesh_connection_destroy (void *cls,
5583 const struct GNUNET_PeerIdentity *peer,
5584 const struct GNUNET_MessageHeader *message)
5586 struct GNUNET_MESH_ConnectionDestroy *msg;
5587 struct MeshConnection *c;
5591 msg = (struct GNUNET_MESH_ConnectionDestroy *) message;
5592 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5593 "Got a CONNECTION DESTROY message from %s\n",
5595 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5596 " for connection %s\n",
5597 GNUNET_h2s (&msg->cid));
5598 c = connection_get (&msg->cid);
5601 /* Probably already got the message from another path,
5602 * destroyed the tunnel and retransmitted to children.
5605 GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
5609 id = GNUNET_PEER_search (peer);
5610 if (id == connection_get_prev_hop (c)->id)
5612 else if (id == connection_get_next_hop (c)->id)
5616 GNUNET_break_op (0);
5619 send_prebuilt_message_connection (message, c, NULL, fwd);
5620 c->destroy = GNUNET_YES;
5627 * Handler for channel create messages.
5629 * @param t Tunnel this channel is to be created in.
5630 * @param msg Message.
5631 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5634 handle_channel_create (struct MeshTunnel2 *t,
5635 struct GNUNET_MESH_ChannelCreate *msg,
5638 MESH_ChannelNumber chid;
5639 struct MeshChannel *ch;
5640 struct MeshClient *c;
5643 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received Channel Create\n");
5644 /* Check message size */
5645 if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelCreate))
5647 GNUNET_break_op (0);
5651 /* Check if channel exists */
5652 chid = ntohl (msg->chid);
5653 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " chid %u\n", chid);
5654 ch = channel_get (t, chid);
5657 /* Probably a retransmission, safe to ignore */
5658 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
5659 if (NULL != ch->dest)
5661 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " duplicate CC!!\n");
5662 channel_send_ack (ch, !fwd);
5668 /* Create channel */
5669 ch = channel_new (t, NULL, 0);
5671 channel_set_options (ch, ntohl (msg->opt));
5674 /* Find a destination client */
5675 port = ntohl (msg->port);
5676 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " port %u\n", port);
5677 c = GNUNET_CONTAINER_multihashmap32_get (ports, port);
5680 /* TODO send reject */
5681 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " no client has port registered\n");
5686 channel_add_client (ch, c);
5687 if (GNUNET_YES == ch->reliable)
5688 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
5690 send_local_channel_create (ch);
5691 channel_send_ack (ch, fwd);
5692 send_local_ack (ch, !fwd);
5697 * Handler for channel ack messages.
5699 * @param t Tunnel this channel is to be created in.
5700 * @param msg Message.
5701 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5704 handle_channel_ack (struct MeshTunnel2 *t,
5705 struct GNUNET_MESH_ChannelManage *msg,
5708 MESH_ChannelNumber chid;
5709 struct MeshChannel *ch;
5711 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received Channel ACK\n");
5712 /* Check message size */
5713 if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelManage))
5715 GNUNET_break_op (0);
5719 /* Check if channel exists */
5720 chid = ntohl (msg->chid);
5721 ch = channel_get (t, chid);
5724 GNUNET_break_op (0);
5725 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " channel %u unknown!!\n", chid);
5729 channel_confirm (ch, !fwd);
5734 * Handler for channel destroy messages.
5736 * @param t Tunnel this channel is to be destroyed of.
5737 * @param msg Message.
5738 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5741 handle_channel_destroy (struct MeshTunnel2 *t,
5742 struct GNUNET_MESH_ChannelManage *msg,
5745 MESH_ChannelNumber chid;
5746 struct MeshChannel *ch;
5748 /* Check message size */
5749 if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelManage))
5751 GNUNET_break_op (0);
5755 /* Check if channel exists */
5756 chid = ntohl (msg->chid);
5757 ch = channel_get (t, chid);
5760 /* Probably a retransmission, safe to ignore */
5764 send_local_channel_destroy (ch, fwd);
5765 channel_destroy (ch);
5770 handle_decrypted (struct MeshTunnel2 *t,
5771 const struct GNUNET_MessageHeader *msgh,
5774 switch (ntohs (msgh->type))
5776 case GNUNET_MESSAGE_TYPE_MESH_DATA:
5777 /* Don't send hop ACK, wait for client to ACK */
5778 handle_data (t, (struct GNUNET_MESH_Data *) msgh, fwd);
5781 case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
5782 handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh, fwd);
5785 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
5786 handle_channel_create (t,
5787 (struct GNUNET_MESH_ChannelCreate *) msgh,
5791 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
5792 handle_channel_ack (t,
5793 (struct GNUNET_MESH_ChannelManage *) msgh,
5797 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
5798 handle_channel_destroy (t,
5799 (struct GNUNET_MESH_ChannelManage *) msgh,
5804 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5805 "end-to-end message not known (%u)\n",
5806 ntohs (msgh->type));
5812 * Generic handler for mesh network encrypted traffic.
5814 * @param peer Peer identity this notification is about.
5815 * @param message Encrypted message.
5816 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5818 * @return GNUNET_OK to keep the connection open,
5819 * GNUNET_SYSERR to close it (signal serious error)
5822 handle_mesh_encrypted (const struct GNUNET_PeerIdentity *peer,
5823 const struct GNUNET_MESH_Encrypted *msg,
5826 struct MeshConnection *c;
5827 struct MeshTunnel2 *t;
5828 struct MeshPeer *neighbor;
5829 struct MeshFlowControl *fc;
5836 size = ntohs (msg->header.size);
5838 sizeof (struct GNUNET_MESH_Encrypted) +
5839 sizeof (struct GNUNET_MessageHeader))
5841 GNUNET_break_op (0);
5844 type = ntohs (msg->header.type);
5845 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
5846 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message from %s\n",
5847 GNUNET_MESH_DEBUG_M2S (type), GNUNET_i2s (peer));
5849 /* Check connection */
5850 c = connection_get (&msg->cid);
5853 GNUNET_STATISTICS_update (stats, "# unknown connection", 1, GNUNET_NO);
5854 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING connection unknown\n");
5858 fc = fwd ? &c->bck_fc : &c->fwd_fc;
5860 /* Check if origin is as expected */
5861 neighbor = connection_get_hop (c, !fwd);
5862 if (peer_get (peer)->id != neighbor->id)
5864 GNUNET_break_op (0);
5869 pid = ntohl (msg->pid);
5870 if (GMC_is_pid_bigger (pid, fc->last_ack_sent))
5872 GNUNET_STATISTICS_update (stats, "# unsolicited message", 1, GNUNET_NO);
5873 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5874 "WARNING Received PID %u, (prev %u), ACK %u\n",
5875 pid, fc->last_pid_recv, fc->last_ack_sent);
5878 if (GNUNET_NO == GMC_is_pid_bigger (pid, fc->last_pid_recv))
5880 GNUNET_STATISTICS_update (stats, "# duplicate PID", 1, GNUNET_NO);
5881 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5882 " Pid %u not expected (%u+), dropping!\n",
5883 pid, fc->last_pid_recv + 1);
5886 if (MESH_CONNECTION_SENT == c->state)
5887 connection_change_state (c, MESH_CONNECTION_READY);
5888 connection_reset_timeout (c, fwd);
5889 fc->last_pid_recv = pid;
5891 /* Is this message for us? */
5892 if (connection_is_terminal (c, fwd))
5894 size_t dsize = size - sizeof (struct GNUNET_MESH_Encrypted);
5896 struct GNUNET_MessageHeader *msgh;
5899 /* TODO signature verification */
5900 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " message for us!\n");
5901 GNUNET_STATISTICS_update (stats, "# messages received", 1, GNUNET_NO);
5903 fc->last_pid_recv = pid;
5904 tunnel_decrypt (t, cbuf, &msg[1], dsize, msg->iv, fwd);
5908 msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
5909 handle_decrypted (t, msgh, fwd);
5910 off += ntohs (msgh->size);
5912 send_ack (c, NULL, fwd);
5916 /* Message not for us: forward to next hop */
5917 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " not for us, retransmitting...\n");
5918 ttl = ntohl (msg->ttl);
5919 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ttl: %u\n", ttl);
5922 GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5923 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5924 send_ack (c, NULL, fwd);
5927 GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
5929 send_prebuilt_message_connection (&msg->header, c, NULL, fwd);
5936 * Core handler for mesh network traffic going orig->dest.
5938 * @param cls Closure (unused).
5939 * @param message Message received.
5940 * @param peer Peer who sent the message.
5942 * @return GNUNET_OK to keep the connection open,
5943 * GNUNET_SYSERR to close it (signal serious error)
5946 handle_mesh_fwd (void *cls, const struct GNUNET_PeerIdentity *peer,
5947 const struct GNUNET_MessageHeader *message)
5949 return handle_mesh_encrypted (peer,
5950 (struct GNUNET_MESH_Encrypted *)message,
5955 * Core handler for mesh network traffic going dest->orig.
5957 * @param cls Closure (unused).
5958 * @param message Message received.
5959 * @param peer Peer who sent the message.
5961 * @return GNUNET_OK to keep the connection open,
5962 * GNUNET_SYSERR to close it (signal serious error)
5965 handle_mesh_bck (void *cls, const struct GNUNET_PeerIdentity *peer,
5966 const struct GNUNET_MessageHeader *message)
5968 return handle_mesh_encrypted (peer,
5969 (struct GNUNET_MESH_Encrypted *)message,
5975 * Core handler for mesh network traffic point-to-point acks.
5977 * @param cls closure
5978 * @param message message
5979 * @param peer peer identity this notification is about
5981 * @return GNUNET_OK to keep the connection open,
5982 * GNUNET_SYSERR to close it (signal serious error)
5985 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5986 const struct GNUNET_MessageHeader *message)
5988 struct GNUNET_MESH_ACK *msg;
5989 struct MeshConnection *c;
5990 struct MeshFlowControl *fc;
5994 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
5995 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
5997 msg = (struct GNUNET_MESH_ACK *) message;
5999 c = connection_get (&msg->cid);
6003 GNUNET_STATISTICS_update (stats, "# ack on unknown connection", 1,
6008 /* Is this a forward or backward ACK? */
6009 id = GNUNET_PEER_search (peer);
6010 if (connection_get_next_hop (c)->id == id)
6012 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " FWD ACK\n");
6016 else if (connection_get_prev_hop (c)->id == id)
6018 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " BCK ACK\n");
6024 GNUNET_break_op (0);
6028 fc->last_ack_recv = ntohl (msg->ack);
6029 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", fc->last_ack_recv);
6032 /* Cancel polling if the ACK is big enough. */
6033 if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task &&
6034 GMC_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
6036 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Cancel poll\n");
6037 GNUNET_SCHEDULER_cancel (fc->poll_task);
6038 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
6039 fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
6042 connection_unlock_queue (c, fwd);
6049 * Core handler for mesh network traffic point-to-point ack polls.
6051 * @param cls closure
6052 * @param message message
6053 * @param peer peer identity this notification is about
6055 * @return GNUNET_OK to keep the connection open,
6056 * GNUNET_SYSERR to close it (signal serious error)
6059 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
6060 const struct GNUNET_MessageHeader *message)
6062 struct GNUNET_MESH_Poll *msg;
6063 struct MeshConnection *c;
6064 struct MeshFlowControl *fc;
6069 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
6070 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a POLL packet from %s!\n",
6073 msg = (struct GNUNET_MESH_Poll *) message;
6075 c = connection_get (&msg->cid);
6079 GNUNET_STATISTICS_update (stats, "# poll on unknown connection", 1,
6081 GNUNET_break_op (0);
6085 /* Is this a forward or backward ACK?
6086 * Note: a poll should never be needed in a loopback case,
6087 * since there is no possiblility of packet loss there, so
6088 * this way of discerining FWD/BCK should not be a problem.
6090 id = GNUNET_PEER_search (peer);
6091 if (connection_get_next_hop (c)->id == id)
6093 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " FWD ACK\n");
6096 else if (connection_get_prev_hop (c)->id == id)
6098 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " BCK ACK\n");
6103 GNUNET_break_op (0);
6107 pid = ntohl (msg->pid);
6108 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " PID %u, OLD %u\n",
6109 pid, fc->last_pid_recv);
6110 fc->last_pid_recv = pid;
6111 fwd = fc == &c->fwd_fc;
6112 send_ack (c, NULL, fwd);
6119 * Core handler for mesh keepalives.
6121 * @param cls closure
6122 * @param message message
6123 * @param peer peer identity this notification is about
6124 * @return GNUNET_OK to keep the connection open,
6125 * GNUNET_SYSERR to close it (signal serious error)
6127 * TODO: Check who we got this from, to validate route.
6130 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
6131 const struct GNUNET_MessageHeader *message)
6133 struct GNUNET_MESH_ConnectionKeepAlive *msg;
6134 struct MeshConnection *c;
6135 struct MeshPeer *neighbor;
6138 msg = (struct GNUNET_MESH_ConnectionKeepAlive *) message;
6139 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
6142 c = connection_get (&msg->cid);
6145 GNUNET_STATISTICS_update (stats, "# keepalive on unknown connection", 1,
6150 fwd = GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE == ntohs (message->type) ?
6151 GNUNET_YES : GNUNET_NO;
6153 /* Check if origin is as expected */
6154 neighbor = connection_get_hop (c, fwd);
6155 if (peer_get (peer)->id != neighbor->id)
6157 GNUNET_break_op (0);
6161 connection_change_state (c, MESH_CONNECTION_READY);
6162 connection_reset_timeout (c, fwd);
6164 if (connection_is_terminal (c, fwd))
6167 GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
6168 send_prebuilt_message_connection (message, c, NULL, fwd);
6176 * Functions to handle messages from core
6178 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
6179 {&handle_mesh_connection_create, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
6181 {&handle_mesh_connection_ack, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
6182 sizeof (struct GNUNET_MESH_ConnectionACK)},
6183 {&handle_mesh_connection_broken, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN,
6184 sizeof (struct GNUNET_MESH_ConnectionBroken)},
6185 {&handle_mesh_connection_destroy, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY,
6186 sizeof (struct GNUNET_MESH_ConnectionDestroy)},
6187 {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE,
6188 sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
6189 {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE,
6190 sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
6191 {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
6192 sizeof (struct GNUNET_MESH_ACK)},
6193 {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
6194 sizeof (struct GNUNET_MESH_Poll)},
6195 {&handle_mesh_fwd, GNUNET_MESSAGE_TYPE_MESH_FWD, 0},
6196 {&handle_mesh_bck, GNUNET_MESSAGE_TYPE_MESH_BCK, 0},
6202 * Function to process paths received for a new peer addition. The recorded
6203 * paths form the initial tunnel, which can be optimized later.
6204 * Called on each result obtained for the DHT search.
6206 * @param cls closure
6207 * @param exp when will this value expire
6208 * @param key key of the result
6209 * @param get_path path of the get request
6210 * @param get_path_length lenght of get_path
6211 * @param put_path path of the put request
6212 * @param put_path_length length of the put_path
6213 * @param type type of the result
6214 * @param size number of bytes in data
6215 * @param data pointer to the result data
6218 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6219 const struct GNUNET_HashCode * key,
6220 const struct GNUNET_PeerIdentity *get_path,
6221 unsigned int get_path_length,
6222 const struct GNUNET_PeerIdentity *put_path,
6223 unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
6224 size_t size, const void *data)
6226 struct MeshPeer *peer = cls;
6227 struct MeshPeerPath *p;
6228 struct MeshConnection *c;
6229 struct GNUNET_PeerIdentity pi;
6232 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
6233 GNUNET_PEER_resolve (peer->id, &pi);
6234 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " for %s\n", GNUNET_i2s (&pi));
6236 p = path_build_from_dht (get_path, get_path_length,
6237 put_path, put_path_length);
6238 path_add_to_peers (p, GNUNET_NO);
6241 /* Count connections */
6242 for (c = peer->tunnel->connection_head, i = 0; NULL != c; c = c->next, i++);
6244 /* If we already have 3 (or more (?!)) connections, it's enough */
6248 if (peer->tunnel->state == MESH_TUNNEL_SEARCHING)
6250 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... connect!\n");
6251 peer_connect (peer);
6257 /******************************************************************************/
6258 /********************* MESH LOCAL HANDLES **************************/
6259 /******************************************************************************/
6263 * Handler for client connection.
6265 * @param cls Closure (unused).
6266 * @param client Client handler.
6269 handle_local_client_connect (void *cls, struct GNUNET_SERVER_Client *client)
6271 struct MeshClient *c;
6275 c = GNUNET_malloc (sizeof (struct MeshClient));
6277 c->id = next_client_id++; /* overflow not important: just for debug */
6278 GNUNET_SERVER_client_keep (client);
6279 GNUNET_SERVER_client_set_user_context (client, c);
6280 GNUNET_CONTAINER_DLL_insert (clients_head, clients_tail, c);
6285 * Handler for client disconnection
6287 * @param cls closure
6288 * @param client identification of the client; NULL
6289 * for the last call when the server is destroyed
6292 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
6294 struct MeshClient *c;
6296 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected: %p\n", client);
6299 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " (SERVER DOWN)\n");
6303 c = client_get (client);
6306 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u, %p)\n",
6308 GNUNET_SERVER_client_drop (c->handle);
6309 c->shutting_down = GNUNET_YES;
6310 if (NULL != c->own_channels)
6312 GNUNET_CONTAINER_multihashmap32_iterate (c->own_channels,
6313 &channel_destroy_iterator, c);
6314 GNUNET_CONTAINER_multihashmap32_destroy (c->own_channels);
6317 if (NULL != c->incoming_channels)
6319 GNUNET_CONTAINER_multihashmap32_iterate (c->incoming_channels,
6320 &channel_destroy_iterator, c);
6321 GNUNET_CONTAINER_multihashmap32_destroy (c->incoming_channels);
6324 if (NULL != c->ports)
6326 GNUNET_CONTAINER_multihashmap32_iterate (c->ports,
6327 &client_release_ports, c);
6328 GNUNET_CONTAINER_multihashmap32_destroy (c->ports);
6330 GNUNET_CONTAINER_DLL_remove (clients_head, clients_tail, c);
6331 GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
6332 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " client free (%p)\n", c);
6337 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " context NULL!\n");
6339 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "done!\n");
6345 * Handler for new clients
6347 * @param cls closure
6348 * @param client identification of the client
6349 * @param message the actual message, which includes messages the client wants
6352 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
6353 const struct GNUNET_MessageHeader *message)
6355 struct GNUNET_MESH_ClientConnect *cc_msg;
6356 struct MeshClient *c;
6361 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected %p\n", client);
6363 /* Check data sanity */
6364 size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
6365 cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
6366 if (0 != (size % sizeof (uint32_t)))
6369 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6372 size /= sizeof (uint32_t);
6374 /* Initialize new client structure */
6375 c = GNUNET_SERVER_client_get_user_context (client, struct MeshClient);
6376 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " client id %u\n", c->id);
6377 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " client has %u ports\n", size);
6382 p = (uint32_t *) &cc_msg[1];
6383 c->ports = GNUNET_CONTAINER_multihashmap32_create (size);
6384 for (i = 0; i < size; i++)
6387 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " port: %u\n", u32);
6389 /* store in client's hashmap */
6390 GNUNET_CONTAINER_multihashmap32_put (c->ports, u32, c,
6391 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
6392 /* store in global hashmap */
6393 /* FIXME only allow one client to have the port open,
6394 * have a backup hashmap with waiting clients */
6395 GNUNET_CONTAINER_multihashmap32_put (ports, u32, c,
6396 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6400 c->own_channels = GNUNET_CONTAINER_multihashmap32_create (32);
6401 c->incoming_channels = GNUNET_CONTAINER_multihashmap32_create (32);
6402 GNUNET_SERVER_notification_context_add (nc, client);
6403 GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
6405 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6406 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
6411 * Handler for requests of new tunnels
6413 * @param cls Closure.
6414 * @param client Identification of the client.
6415 * @param message The actual message.
6418 handle_local_channel_create (void *cls, struct GNUNET_SERVER_Client *client,
6419 const struct GNUNET_MessageHeader *message)
6421 struct GNUNET_MESH_ChannelMessage *msg;
6422 struct MeshPeer *peer;
6423 struct MeshTunnel2 *t;
6424 struct MeshChannel *ch;
6425 struct MeshClient *c;
6426 MESH_ChannelNumber chid;
6428 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new channel requested\n");
6430 /* Sanity check for client registration */
6431 if (NULL == (c = client_get (client)))
6434 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6437 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
6439 /* Message size sanity check */
6440 if (sizeof (struct GNUNET_MESH_ChannelMessage) != ntohs (message->size))
6443 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6447 msg = (struct GNUNET_MESH_ChannelMessage *) message;
6448 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " towards %s:%u\n",
6449 GNUNET_i2s (&msg->peer), ntohl (msg->port));
6450 chid = ntohl (msg->channel_id);
6452 /* Sanity check for duplicate channel IDs */
6453 if (NULL != channel_get_by_local_id (c, chid))
6456 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6460 peer = peer_get (&msg->peer);
6461 if (NULL == peer->tunnel)
6463 peer->tunnel = tunnel_new ();
6464 peer->tunnel->peer = peer;
6468 /* Create channel */
6469 ch = channel_new (t, c, chid);
6473 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6476 ch->port = ntohl (msg->port);
6477 channel_set_options (ch, ntohl (msg->opt));
6479 /* In unreliable channels, we'll use the DLL to buffer data for the root */
6480 ch->root_rel = GNUNET_new (struct MeshChannelReliability);
6481 ch->root_rel->ch = ch;
6482 ch->root_rel->expected_delay = MESH_RETRANSMIT_TIME;
6484 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED CHANNEL %s[%x]:%u (%x)\n",
6485 peer2s (t->peer), ch->gid, ch->port, ch->lid_root);
6486 peer_connect (peer);
6488 /* Send create channel */
6490 struct GNUNET_MESH_ChannelCreate msgcc;
6492 msgcc.header.size = htons (sizeof (msgcc));
6493 msgcc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE);
6494 msgcc.chid = htonl (ch->gid);
6495 msgcc.port = msg->port;
6496 msgcc.opt = msg->opt;
6498 tunnel_queue_data (t, ch, &msgcc.header, GNUNET_YES);
6501 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6507 * Handler for requests of deleting tunnels
6509 * @param cls closure
6510 * @param client identification of the client
6511 * @param message the actual message
6514 handle_local_channel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
6515 const struct GNUNET_MessageHeader *message)
6517 struct GNUNET_MESH_ChannelMessage *msg;
6518 struct MeshClient *c;
6519 struct MeshChannel *ch;
6520 struct MeshTunnel2 *t;
6521 MESH_ChannelNumber chid;
6523 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6524 "Got a DESTROY CHANNEL from client!\n");
6526 /* Sanity check for client registration */
6527 if (NULL == (c = client_get (client)))
6530 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6533 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
6535 /* Message sanity check */
6536 if (sizeof (struct GNUNET_MESH_ChannelMessage) != ntohs (message->size))
6539 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6543 msg = (struct GNUNET_MESH_ChannelMessage *) message;
6545 /* Retrieve tunnel */
6546 chid = ntohl (msg->channel_id);
6547 ch = channel_get_by_local_id (c, chid);
6550 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, " channel %X not found\n", chid);
6552 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6556 /* Cleanup after the tunnel */
6557 client_delete_channel (c, ch);
6558 if (c == ch->dest && GNUNET_MESH_LOCAL_CHANNEL_ID_SERV <= chid)
6562 else if (c == ch->root && GNUNET_MESH_LOCAL_CHANNEL_ID_SERV > chid)
6568 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6569 " channel %X client %p (%p, %p)\n",
6570 chid, c, ch->root, ch->dest);
6575 channel_destroy (ch);
6576 tunnel_destroy_if_empty (t);
6578 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6584 * Handler for client traffic
6586 * @param cls closure
6587 * @param client identification of the client
6588 * @param message the actual message
6591 handle_local_data (void *cls, struct GNUNET_SERVER_Client *client,
6592 const struct GNUNET_MessageHeader *message)
6594 struct GNUNET_MESH_LocalData *msg;
6595 struct MeshClient *c;
6596 struct MeshChannel *ch;
6597 struct MeshChannelReliability *rel;
6598 MESH_ChannelNumber chid;
6602 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6603 "Got data from a client!\n");
6605 /* Sanity check for client registration */
6606 if (NULL == (c = client_get (client)))
6609 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6612 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
6614 msg = (struct GNUNET_MESH_LocalData *) message;
6616 /* Sanity check for message size */
6617 size = ntohs (message->size) - sizeof (struct GNUNET_MESH_LocalData);
6618 if (size < sizeof (struct GNUNET_MessageHeader))
6621 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6625 /* Channel exists? */
6626 chid = ntohl (msg->id);
6627 fwd = chid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
6628 ch = channel_get_by_local_id (c, chid);
6632 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6636 /* Is the client in the channel? */
6639 ch->root->handle == client)
6643 ch->dest->handle == client) ) )
6646 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6650 rel = fwd ? ch->root_rel : ch->dest_rel;
6651 rel->client_ready = GNUNET_NO;
6653 /* Ok, everything is correct, send the message. */
6655 struct GNUNET_MESH_Data *payload;
6656 uint16_t p2p_size = sizeof(struct GNUNET_MESH_Data) + size;
6657 unsigned char cbuf[p2p_size];
6659 payload = (struct GNUNET_MESH_Data *) cbuf;
6660 payload->mid = htonl (rel->mid_send);
6662 memcpy (&payload[1], &msg[1], size);
6663 payload->header.size = htons (p2p_size);
6664 payload->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_DATA);
6665 payload->chid = htonl (ch->gid);
6666 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " sending on channel...\n");
6667 send_prebuilt_message_channel (&payload->header, ch, fwd);
6669 if (GNUNET_YES == ch->reliable)
6670 channel_save_copy (ch, &payload->header, fwd);
6672 if (tunnel_get_buffer (ch->t, fwd) > 0)
6673 send_local_ack (ch, fwd);
6674 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
6675 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6682 * Handler for client's ACKs for payload traffic.
6684 * @param cls Closure (unused).
6685 * @param client Identification of the client.
6686 * @param message The actual message.
6689 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
6690 const struct GNUNET_MessageHeader *message)
6692 struct GNUNET_MESH_LocalAck *msg;
6693 struct MeshChannelReliability *rel;
6694 struct MeshChannel *ch;
6695 struct MeshClient *c;
6696 MESH_ChannelNumber chid;
6699 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
6701 /* Sanity check for client registration */
6702 if (NULL == (c = client_get (client)))
6705 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6708 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
6710 msg = (struct GNUNET_MESH_LocalAck *) message;
6712 /* Channel exists? */
6713 chid = ntohl (msg->channel_id);
6714 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " on channel %X\n", chid);
6715 ch = channel_get_by_local_id (c, chid);
6716 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " -- ch %p\n", ch);
6720 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Channel %X unknown.\n", chid);
6721 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " for client %u.\n", c->id);
6722 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6726 /* If client is root, the ACK is going FWD, therefore this is "BCK". */
6727 /* If client is dest, the ACK is going BCK, therefore this is "FWD" */
6728 fwd = chid >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
6729 rel = fwd ? ch->dest_rel : ch->root_rel;
6731 rel->client_ready = GNUNET_YES;
6732 channel_send_client_buffered_data (ch, c, fwd);
6733 send_ack (NULL, ch, fwd);
6735 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6742 * Iterator over all tunnels to send a monitoring client info about each tunnel.
6744 * @param cls Closure (client handle).
6745 * @param key Key (hashed tunnel ID, unused).
6746 * @param value Tunnel info.
6748 * @return GNUNET_YES, to keep iterating.
6751 // monitor_all_tunnels_iterator (void *cls,
6752 // const struct GNUNET_HashCode * key,
6755 // struct GNUNET_SERVER_Client *client = cls;
6756 // struct MeshChannel *ch = value;
6757 // struct GNUNET_MESH_LocalMonitor *msg;
6759 // msg = GNUNET_malloc (sizeof(struct GNUNET_MESH_LocalMonitor));
6760 // msg->channel_id = htonl (ch->gid);
6761 // msg->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
6762 // msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
6764 // GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6765 // "* sending info about tunnel %s\n",
6766 // GNUNET_i2s (&msg->owner));
6768 // GNUNET_SERVER_notification_context_unicast (nc, client,
6769 // &msg->header, GNUNET_NO);
6770 // return GNUNET_YES;
6775 * Handler for client's MONITOR request.
6777 * @param cls Closure (unused).
6778 * @param client Identification of the client.
6779 * @param message The actual message.
6782 handle_local_get_tunnels (void *cls, struct GNUNET_SERVER_Client *client,
6783 const struct GNUNET_MessageHeader *message)
6785 struct MeshClient *c;
6787 /* Sanity check for client registration */
6788 if (NULL == (c = client_get (client)))
6791 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6795 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6796 "Received get tunnels request from client %u\n",
6798 // GNUNET_CONTAINER_multihashmap_iterate (tunnels,
6799 // monitor_all_tunnels_iterator,
6801 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6802 "Get tunnels request from client %u completed\n",
6804 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6809 * Handler for client's MONITOR_TUNNEL request.
6811 * @param cls Closure (unused).
6812 * @param client Identification of the client.
6813 * @param message The actual message.
6816 handle_local_show_tunnel (void *cls, struct GNUNET_SERVER_Client *client,
6817 const struct GNUNET_MessageHeader *message)
6819 const struct GNUNET_MESH_LocalMonitor *msg;
6820 struct GNUNET_MESH_LocalMonitor *resp;
6821 struct MeshClient *c;
6822 struct MeshChannel *ch;
6824 /* Sanity check for client registration */
6825 if (NULL == (c = client_get (client)))
6828 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6832 msg = (struct GNUNET_MESH_LocalMonitor *) message;
6833 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6834 "Received tunnel info request from client %u for tunnel %s[%X]\n",
6837 ntohl (msg->channel_id));
6838 // ch = channel_get (&msg->owner, ntohl (msg->channel_id));
6842 /* We don't know the tunnel */
6843 struct GNUNET_MESH_LocalMonitor warn;
6846 GNUNET_SERVER_notification_context_unicast (nc, client,
6849 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6853 /* Initialize context */
6854 resp = GNUNET_malloc (sizeof (struct GNUNET_MESH_LocalMonitor));
6856 resp->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
6857 GNUNET_SERVER_notification_context_unicast (nc, c->handle,
6858 &resp->header, GNUNET_NO);
6861 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6862 "Monitor tunnel request from client %u completed\n",
6864 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6869 * Functions to handle messages from clients
6871 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
6872 {&handle_local_new_client, NULL,
6873 GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
6874 {&handle_local_channel_create, NULL,
6875 GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE,
6876 sizeof (struct GNUNET_MESH_ChannelMessage)},
6877 {&handle_local_channel_destroy, NULL,
6878 GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY,
6879 sizeof (struct GNUNET_MESH_ChannelMessage)},
6880 {&handle_local_data, NULL,
6881 GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA, 0},
6882 {&handle_local_ack, NULL,
6883 GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
6884 sizeof (struct GNUNET_MESH_LocalAck)},
6885 {&handle_local_get_tunnels, NULL,
6886 GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS,
6887 sizeof (struct GNUNET_MessageHeader)},
6888 {&handle_local_show_tunnel, NULL,
6889 GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL,
6890 sizeof (struct GNUNET_MESH_LocalMonitor)},
6896 * Method called whenever a given peer connects.
6898 * @param cls closure
6899 * @param peer peer identity this notification is about
6902 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
6904 struct MeshPeer *pi;
6905 struct MeshPeerPath *path;
6907 DEBUG_CONN ("Peer connected\n");
6908 DEBUG_CONN (" %s\n", GNUNET_i2s (&my_full_id));
6909 pi = peer_get (peer);
6912 DEBUG_CONN (" (self)\n");
6913 path = path_new (1);
6917 DEBUG_CONN (" %s\n", GNUNET_i2s (peer));
6918 path = path_new (2);
6919 path->peers[1] = pi->id;
6920 GNUNET_PEER_change_rc (pi->id, 1);
6921 GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
6923 path->peers[0] = myid;
6924 GNUNET_PEER_change_rc (myid, 1);
6925 peer_add_path (pi, path, GNUNET_YES);
6927 pi->connections = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_YES);
6933 * Method called whenever a peer disconnects.
6935 * @param cls closure
6936 * @param peer peer identity this notification is about
6939 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
6941 struct MeshPeer *pi;
6943 DEBUG_CONN ("Peer disconnected\n");
6944 pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
6951 GNUNET_CONTAINER_multihashmap_iterate (pi->connections,
6954 GNUNET_CONTAINER_multihashmap_destroy (pi->connections);
6955 pi->connections = NULL;
6958 DEBUG_CONN (" (self)\n");
6960 GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
6967 * Install server (service) handlers and start listening to clients.
6972 GNUNET_SERVER_add_handlers (server_handle, client_handlers);
6973 GNUNET_SERVER_connect_notify (server_handle,
6974 &handle_local_client_connect, NULL);
6975 GNUNET_SERVER_disconnect_notify (server_handle,
6976 &handle_local_client_disconnect, NULL);
6977 nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
6979 clients_head = NULL;
6980 clients_tail = NULL;
6982 GNUNET_SERVER_resume (server_handle);
6987 * To be called on core init/fail.
6989 * @param cls Closure (config)
6990 * @param identity the public identity of this peer
6993 core_init (void *cls,
6994 const struct GNUNET_PeerIdentity *identity)
6996 const struct GNUNET_CONFIGURATION_Handle *c = cls;
6999 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
7000 if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)))
7002 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
7003 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7005 GNUNET_i2s (identity));
7006 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7008 GNUNET_i2s (&my_full_id));
7009 GNUNET_CORE_disconnect (core_handle);
7010 core_handle = GNUNET_CORE_connect (c, /* Main configuration */
7011 NULL, /* Closure passed to MESH functions */
7012 &core_init, /* Call core_init once connected */
7013 &core_connect, /* Handle connects */
7014 &core_disconnect, /* remove peers on disconnects */
7015 NULL, /* Don't notify about all incoming messages */
7016 GNUNET_NO, /* For header only in notification */
7017 NULL, /* Don't notify about all outbound messages */
7018 GNUNET_NO, /* For header-only out notification */
7019 core_handlers); /* Register these handlers */
7028 /******************************************************************************/
7029 /************************ MAIN FUNCTIONS ****************************/
7030 /******************************************************************************/
7033 * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
7035 * @param cls closure
7036 * @param key current key code
7037 * @param value value in the hash map
7038 * @return GNUNET_YES if we should continue to iterate,
7042 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
7044 struct MeshPeer *p = value;
7045 struct MeshTunnel2 *t = p->tunnel;
7054 * Task run during shutdown.
7060 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
7062 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
7064 if (core_handle != NULL)
7066 GNUNET_CORE_disconnect (core_handle);
7069 GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_tunnel, NULL);
7070 if (dht_handle != NULL)
7072 GNUNET_DHT_disconnect (dht_handle);
7077 GNUNET_SERVER_notification_context_destroy (nc);
7080 if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
7082 GNUNET_SCHEDULER_cancel (announce_id_task);
7083 announce_id_task = GNUNET_SCHEDULER_NO_TASK;
7085 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
7090 * Process mesh requests.
7092 * @param cls closure
7093 * @param server the initialized server
7094 * @param c configuration to use
7097 run (void *cls, struct GNUNET_SERVER_Handle *server,
7098 const struct GNUNET_CONFIGURATION_Handle *c)
7101 struct GNUNET_CRYPTO_EccPrivateKey *pk;
7103 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
7104 server_handle = server;
7105 GNUNET_SERVER_suspend (server_handle);
7108 GNUNET_CONFIGURATION_get_value_filename (c, "PEER", "PRIVATE_KEY",
7111 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7113 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
7114 "mesh", "peer/privatekey");
7115 GNUNET_SCHEDULER_shutdown ();
7120 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_CONNECTION_TIME",
7121 &refresh_connection_time))
7123 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7125 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
7126 "mesh", "refresh path time");
7127 GNUNET_SCHEDULER_shutdown ();
7132 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
7135 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7137 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
7138 "mesh", "id announce time");
7139 GNUNET_SCHEDULER_shutdown ();
7144 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
7147 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7149 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
7150 "mesh", "connect timeout");
7151 GNUNET_SCHEDULER_shutdown ();
7156 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
7159 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7161 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
7162 "mesh", "max msgs queue");
7163 GNUNET_SCHEDULER_shutdown ();
7168 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_CONNECTIONS",
7171 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7173 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
7174 "mesh", "max tunnels");
7175 GNUNET_SCHEDULER_shutdown ();
7180 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
7183 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7185 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
7186 "mesh", "default ttl", 64);
7191 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
7194 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7195 _("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
7196 "mesh", "max peers", 1000);
7201 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DROP_PERCENT",
7208 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7209 "Mesh is running with drop mode enabled. "
7210 "This is NOT a good idea! "
7211 "Remove the DROP_PERCENT option from your configuration.\n");
7215 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
7216 &dht_replication_level))
7218 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7220 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
7221 "mesh", "dht replication level", 3);
7222 dht_replication_level = 3;
7225 connections = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_YES);
7226 peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
7227 ports = GNUNET_CONTAINER_multihashmap32_create (32);
7229 dht_handle = GNUNET_DHT_connect (c, 64);
7230 if (NULL == dht_handle)
7234 stats = GNUNET_STATISTICS_create ("mesh", c);
7236 /* Scheduled the task to clean up when shutdown is called */
7237 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
7239 pk = GNUNET_CRYPTO_ecc_key_create_from_file (keyfile);
7240 GNUNET_free (keyfile);
7241 GNUNET_assert (NULL != pk);
7242 my_private_key = pk;
7243 GNUNET_CRYPTO_ecc_key_get_public (my_private_key, &my_public_key);
7244 GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
7245 &my_full_id.hashPubKey);
7246 myid = GNUNET_PEER_intern (&my_full_id);
7247 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7248 "Mesh for peer [%s] starting\n",
7249 GNUNET_i2s(&my_full_id));
7251 core_handle = GNUNET_CORE_connect (c, /* Main configuration */
7252 NULL, /* Closure passed to MESH functions */
7253 &core_init, /* Call core_init once connected */
7254 &core_connect, /* Handle connects */
7255 &core_disconnect, /* remove peers on disconnects */
7256 NULL, /* Don't notify about all incoming messages */
7257 GNUNET_NO, /* For header only in notification */
7258 NULL, /* Don't notify about all outbound messages */
7259 GNUNET_NO, /* For header-only out notification */
7260 core_handlers); /* Register these handlers */
7261 if (NULL == core_handle)
7264 GNUNET_SCHEDULER_shutdown ();
7267 announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
7268 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
7273 * The main function for the mesh service.
7275 * @param argc number of arguments from the command line
7276 * @param argv command line arguments
7277 * @return 0 ok, 1 on error
7280 main (int argc, char *const *argv)
7285 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
7286 r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
7288 ret = (GNUNET_OK == r) ? 0 : 1;
7289 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");