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_origin (c, fwd))
2596 struct MeshTunnel2 *t = c->t;
2597 struct MeshChannel *ch;
2598 struct MeshChannelReliability *rel;
2600 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " is origin!\n");
2601 /* FIXME randomize channel selection, not always first channel */
2602 for (ch = t->channel_head; NULL != ch; ch = ch->next)
2604 rel = fwd ? ch->root_rel : ch->dest_rel;
2606 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " channel %X - %s\n",
2607 ch->gid, rel->client_ready ? "ready " : "not ready");
2608 if (GNUNET_NO == rel->client_ready)
2610 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " sending local ack!\n");
2611 send_local_ack (ch, fwd);
2612 return; /* FIXME authorize all channels? */
2618 peer = connection_get_hop (c, fwd);
2620 if (NULL != peer->core_transmit)
2622 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " already unlocked!\n");
2623 return; /* Already unlocked */
2626 q = connection_get_first_message (c, fwd);
2629 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " queue empty!\n");
2630 return; /* Nothing to transmit */
2634 peer->core_transmit =
2635 GNUNET_CORE_notify_transmit_ready (core_handle,
2638 GNUNET_TIME_UNIT_FOREVER_REL,
2639 GNUNET_PEER_resolve2 (peer->id),
2647 * Cancel all transmissions that belong to a certain connection.
2649 * @param c Connection which to cancel.
2650 * @param fwd Cancel fwd traffic?
2653 connection_cancel_queues (struct MeshConnection *c, int fwd)
2655 struct MeshPeerQueue *q;
2656 struct MeshPeerQueue *next;
2657 struct MeshFlowControl *fc;
2658 struct MeshPeer *peer;
2665 fc = fwd ? &c->fwd_fc : &c->bck_fc;
2666 peer = connection_get_hop (c, fwd);
2668 for (q = peer->queue_head; NULL != q; q = next)
2673 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2674 "connection_cancel_queue %s\n",
2675 GNUNET_MESH_DEBUG_M2S (q->type));
2676 queue_destroy (q, GNUNET_YES);
2679 if (NULL == peer->queue_head)
2681 if (NULL != peer->core_transmit)
2683 GNUNET_CORE_notify_transmit_ready_cancel (peer->core_transmit);
2684 peer->core_transmit = NULL;
2686 if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
2688 GNUNET_SCHEDULER_cancel (fc->poll_task);
2689 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2696 * Add the path to the peer and update the path used to reach it in case this
2699 * @param peer_info Destination peer to add the path to.
2700 * @param path New path to add. Last peer must be the peer in arg 1.
2701 * Path will be either used of freed if already known.
2702 * @param trusted Do we trust that this path is real?
2705 peer_add_path (struct MeshPeer *peer_info, struct MeshPeerPath *path,
2708 struct MeshPeerPath *aux;
2712 if ((NULL == peer_info) || (NULL == path))
2715 path_destroy (path);
2718 if (path->peers[path->length - 1] != peer_info->id)
2721 path_destroy (path);
2724 if (2 >= path->length && GNUNET_NO == trusted)
2726 /* Only allow CORE to tell us about direct paths */
2727 path_destroy (path);
2730 for (l = 1; l < path->length; l++)
2732 if (path->peers[l] == myid)
2734 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shortening path by %u\n", l);
2735 for (l2 = 0; l2 < path->length - l; l2++)
2737 path->peers[l2] = path->peers[l + l2];
2742 GNUNET_realloc (path->peers, path->length * sizeof (GNUNET_PEER_Id));
2746 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "adding path [%u] to peer %s\n",
2747 path->length, peer2s (peer_info));
2749 l = path_get_length (path);
2752 path_destroy (path);
2756 GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
2757 for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
2759 l2 = path_get_length (aux);
2762 GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
2763 peer_info->path_tail, aux, path);
2768 if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
2770 path_destroy (path);
2775 GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head, peer_info->path_tail,
2782 * Add the path to the origin peer and update the path used to reach it in case
2783 * this is the shortest.
2784 * The path is given in peer_info -> destination, therefore we turn the path
2785 * upside down first.
2787 * @param peer_info Peer to add the path to, being the origin of the path.
2788 * @param path New path to add after being inversed.
2789 * Path will be either used or freed.
2790 * @param trusted Do we trust that this path is real?
2793 peer_add_path_to_origin (struct MeshPeer *peer_info,
2794 struct MeshPeerPath *path, int trusted)
2799 peer_add_path (peer_info, path, trusted);
2805 * Function called if a connection has been stalled for a while,
2806 * possibly due to a missed ACK. Poll the neighbor about its ACK status.
2808 * @param cls Closure (poll ctx).
2809 * @param tc TaskContext.
2812 connection_poll (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2814 struct MeshFlowControl *fc = cls;
2815 struct GNUNET_MESH_Poll msg;
2816 struct MeshConnection *c;
2818 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2819 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2825 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** Polling!\n");
2826 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** connection %s[%X]\n",
2827 peer2s (c->t->peer), c->id);
2828 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** %s\n",
2829 fc == &c->fwd_fc ? "FWD" : "BCK");
2831 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_POLL);
2832 msg.header.size = htons (sizeof (msg));
2833 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** pid (%u)!\n", fc->last_pid_sent);
2834 send_prebuilt_message_connection (&msg.header, c, NULL, fc == &c->fwd_fc);
2835 fc->poll_time = GNUNET_TIME_STD_BACKOFF (fc->poll_time);
2836 fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
2837 &connection_poll, fc);
2842 * Build a PeerPath from the paths returned from the DHT, reversing the paths
2843 * to obtain a local peer -> destination path and interning the peer ids.
2845 * @return Newly allocated and created path
2847 static struct MeshPeerPath *
2848 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
2849 unsigned int get_path_length,
2850 const struct GNUNET_PeerIdentity *put_path,
2851 unsigned int put_path_length)
2853 struct MeshPeerPath *p;
2859 GNUNET_PEER_change_rc (myid, 1);
2860 i = get_path_length;
2861 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " GET has %d hops.\n", i);
2862 for (i--; i >= 0; i--)
2864 id = GNUNET_PEER_intern (&get_path[i]);
2865 if (p->length > 0 && id == p->peers[p->length - 1])
2867 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Optimizing 1 hop out.\n");
2868 GNUNET_PEER_change_rc (id, -1);
2872 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Adding from GET: %s.\n",
2873 GNUNET_i2s (&get_path[i]));
2875 p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2876 p->peers[p->length - 1] = id;
2879 i = put_path_length;
2880 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " PUT has %d hops.\n", i);
2881 for (i--; i >= 0; i--)
2883 id = GNUNET_PEER_intern (&put_path[i]);
2886 /* PUT path went through us, so discard the path up until now and start
2887 * from here to get a much shorter (and loop-free) path.
2892 if (p->length > 0 && id == p->peers[p->length - 1])
2894 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Optimizing 1 hop out.\n");
2895 GNUNET_PEER_change_rc (id, -1);
2899 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Adding from PUT: %s.\n",
2900 GNUNET_i2s (&put_path[i]));
2902 p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2903 p->peers[p->length - 1] = id;
2907 if (get_path_length > 0)
2908 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " (first of GET: %s)\n",
2909 GNUNET_i2s (&get_path[0]));
2910 if (put_path_length > 0)
2911 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " (first of PUT: %s)\n",
2912 GNUNET_i2s (&put_path[0]));
2913 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " In total: %d hops\n",
2915 for (i = 0; i < p->length; i++)
2917 struct GNUNET_PeerIdentity peer_id;
2919 GNUNET_PEER_resolve (p->peers[i], &peer_id);
2920 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " %u: %s\n", p->peers[i],
2921 GNUNET_i2s (&peer_id));
2929 * Adds a path to the peer_infos of all the peers in the path
2931 * @param p Path to process.
2932 * @param confirmed Whether we know if the path works or not.
2935 path_add_to_peers (struct MeshPeerPath *p, int confirmed)
2939 /* TODO: invert and add */
2940 for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
2941 for (i++; i < p->length; i++)
2943 struct MeshPeer *aux;
2944 struct MeshPeerPath *copy;
2946 aux = peer_get_short (p->peers[i]);
2947 copy = path_duplicate (p);
2948 copy->length = i + 1;
2949 peer_add_path (aux, copy, p->length < 3 ? GNUNET_NO : confirmed);
2955 * Search for a channel among the channels for a client
2957 * @param c the client whose channels to search in
2958 * @param chid the local id of the channel
2960 * @return channel handler, NULL if doesn't exist
2962 static struct MeshChannel *
2963 channel_get_by_local_id (struct MeshClient *c, MESH_ChannelNumber chid)
2965 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " -- get CHID %X\n", chid);
2966 if (0 == (chid & GNUNET_MESH_LOCAL_CHANNEL_ID_CLI))
2968 GNUNET_break_op (0);
2969 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CHID %X not a local chid\n", chid);
2972 if (chid >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV)
2973 return GNUNET_CONTAINER_multihashmap32_get (c->incoming_channels, chid);
2974 return GNUNET_CONTAINER_multihashmap32_get (c->own_channels, chid);
2980 channel_debug (struct MeshChannel *ch)
2984 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*** DEBUG NULL CHANNEL ***\n");
2987 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Channel %s:%X\n",
2988 peer2s (ch->t->peer), ch->gid);
2989 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " root %p/%p\n",
2990 ch->root, ch->root_rel);
2991 if (NULL != ch->root)
2993 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " cli %u\n", ch->root->id);
2994 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ready %s\n",
2995 ch->root_rel->client_ready ? "YES" : "NO");
2996 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " id %X\n", ch->lid_root);
2998 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " root %p/%p\n",
2999 ch->dest, ch->dest_rel);
3000 if (NULL != ch->dest)
3002 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " cli %u\n", ch->dest->id);
3003 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ready %s\n",
3004 ch->dest_rel->client_ready ? "YES" : "NO");
3005 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " id %X\n", ch->lid_dest);
3010 fc_debug (struct MeshFlowControl *fc)
3012 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " IN: %u/%u\n",
3013 fc->last_pid_recv, fc->last_ack_sent);
3014 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " OUT: %u/%u\n",
3015 fc->last_pid_sent, fc->last_ack_recv);
3016 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " QUEUE: %u/%u\n",
3017 fc->queue_n, fc->queue_max);
3021 connection_debug (struct MeshConnection *c)
3025 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*** DEBUG NULL CONNECTION ***\n");
3028 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connection %s:%X\n",
3029 peer2s (c->t->peer), GNUNET_h2s (&c->id));
3030 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " state: %u, pending msgs: %u\n",
3031 c->state, c->pending_messages);
3032 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " FWD FC\n");
3033 fc_debug (&c->fwd_fc);
3034 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " BCK FC\n");
3035 fc_debug (&c->bck_fc);
3040 static struct MeshChannel *
3041 channel_get (struct MeshTunnel2 *t, MESH_ChannelNumber chid)
3043 struct MeshChannel *ch;
3048 for (ch = t->channel_head; NULL != ch; ch = ch->next)
3050 if (ch->gid == chid)
3059 * Change the tunnel state.
3061 * @param t Tunnel whose state to change.
3062 * @param state New state.
3065 tunnel_change_state (struct MeshTunnel2* t, enum MeshTunnelState state)
3069 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3070 "Tunnel %s state was %s\n",
3072 GNUNET_MESH_DEBUG_TS2S (t->state));
3073 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3074 "Tunnel %s state is now %s\n",
3076 GNUNET_MESH_DEBUG_TS2S (state));
3082 * Cache a message to be sent once tunnel is online.
3084 * @param t Tunnel to hold the message.
3085 * @param ch Channel the message is about.
3086 * @param msg Message itself (copy will be made).
3087 * @param fwd Is this fwd?
3090 tunnel_queue_data (struct MeshTunnel2 *t,
3091 struct MeshChannel *ch,
3092 struct GNUNET_MessageHeader *msg,
3095 struct MeshTunnelQueue *tq;
3096 uint16_t size = ntohs (msg->size);
3098 tq = GNUNET_malloc (sizeof (struct MeshTunnelQueue) + size);
3101 memcpy (&tq[1], msg, size);
3102 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tq);
3107 * Send all cached messages that we can, tunnel is online.
3109 * @param t Tunnel that holds the messages.
3110 * @param fwd Is this fwd?
3113 tunnel_send_queued_data (struct MeshTunnel2 *t, int fwd)
3115 struct MeshTunnelQueue *tq;
3116 struct MeshTunnelQueue *next;
3119 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3120 "tunnel_send_queued_data on tunnel %s\n",
3122 room = tunnel_get_buffer (t, fwd);
3123 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
3124 for (tq = t->tq_head; NULL != tq && room > 0; tq = next)
3128 GNUNET_CONTAINER_DLL_remove (t->tq_head, t->tq_tail, tq);
3129 send_prebuilt_message_channel ((struct GNUNET_MessageHeader *) &tq[1],
3138 connection_change_state (struct MeshConnection* c,
3139 enum MeshConnectionState state)
3141 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3142 "Connection %s state was %s\n",
3143 GNUNET_h2s (&c->id), GNUNET_MESH_DEBUG_CS2S (c->state));
3144 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3145 "Connection %s state is now %s\n",
3146 GNUNET_h2s (&c->id), GNUNET_MESH_DEBUG_CS2S (state));
3152 * Add a client to a channel, initializing all needed data structures.
3154 * @param ch Channel to which add the client.
3155 * @param c Client which to add to the channel.
3158 channel_add_client (struct MeshChannel *ch, struct MeshClient *c)
3160 struct MeshTunnel2 *t = ch->t;
3162 if (NULL != ch->dest)
3168 /* Assign local id as destination */
3169 while (NULL != channel_get_by_local_id (c, t->next_local_chid))
3170 t->next_local_chid = (t->next_local_chid + 1) | GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
3171 ch->lid_dest = t->next_local_chid++;
3172 t->next_local_chid = t->next_local_chid | GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
3174 /* Store in client's hashmap */
3176 GNUNET_CONTAINER_multihashmap32_put (c->incoming_channels,
3178 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3184 GNUNET_break (NULL == ch->dest_rel);
3185 ch->dest_rel = GNUNET_new (struct MeshChannelReliability);
3186 ch->dest_rel->ch = ch;
3187 ch->dest_rel->expected_delay = MESH_RETRANSMIT_TIME;
3193 static struct MeshConnection *
3194 tunnel_use_path (struct MeshTunnel2 *t, struct MeshPeerPath *p)
3196 struct MeshConnection *c;
3197 struct GNUNET_HashCode cid;
3198 struct MeshPeer *peer;
3199 unsigned int own_pos;
3201 if (NULL == t || NULL == p)
3207 GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE, &cid);
3209 c = connection_new (&cid);
3211 GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, c);
3212 for (own_pos = 0; own_pos < p->length; own_pos++)
3214 if (p->peers[own_pos] == myid)
3217 if (own_pos > p->length - 1)
3220 connection_destroy (c);
3223 c->own_pos = own_pos;
3228 c->fwd_maintenance_task =
3229 GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
3230 &connection_fwd_keepalive, c);
3233 peer = connection_get_next_hop (c);
3234 if (NULL == peer->connections)
3236 connection_destroy (c);
3239 GNUNET_CONTAINER_multihashmap_put (peer->connections, &c->id, c,
3240 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
3241 peer = connection_get_prev_hop (c);
3242 if (NULL == peer->connections)
3244 connection_destroy (c);
3247 GNUNET_CONTAINER_multihashmap_put (peer->connections, &c->id, c,
3248 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
3254 * Notifies a tunnel that a connection has broken that affects at least
3255 * some of its peers. Sends a notification towards the root of the tree.
3256 * In case the peer is the owner of the tree, notifies the client that owns
3257 * the tunnel and tries to reconnect.
3259 * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
3261 * @param t Tunnel affected.
3262 * @param p1 Peer that got disconnected from p2.
3263 * @param p2 Peer that got disconnected from p1.
3265 * @return Short ID of the peer disconnected (either p1 or p2).
3266 * 0 if the tunnel remained unaffected.
3268 static GNUNET_PEER_Id
3269 tunnel_notify_connection_broken (struct MeshTunnel2* t,
3270 GNUNET_PEER_Id p1, GNUNET_PEER_Id p2)
3272 // if (myid != p1 && myid != p2) FIXME
3277 // if (tree_get_predecessor (t->tree) != 0)
3279 // /* We are the peer still connected, notify owner of the disconnection. */
3280 // struct GNUNET_MESH_PathBroken msg;
3281 // struct GNUNET_PeerIdentity neighbor;
3283 // msg.header.size = htons (sizeof (msg));
3284 // msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN);
3285 // GNUNET_PEER_resolve (t->id.oid, &msg.oid);
3286 // msg.tid = htonl (t->id.tid);
3287 // msg.peer1 = my_full_id;
3288 // GNUNET_PEER_resolve (pid, &msg.peer2);
3289 // GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &neighbor);
3290 // send_prebuilt_message (&msg.header, &neighbor, t);
3297 * Send an end-to-end ACK message for the most recent in-sequence payload.
3299 * If channel is not reliable, do nothing.
3301 * @param ch Channel this is about.
3302 * @param fwd Is for FWD traffic? (ACK dest->owner)
3305 channel_send_data_ack (struct MeshChannel *ch, int fwd)
3307 struct GNUNET_MESH_DataACK msg;
3308 struct MeshChannelReliability *rel;
3309 struct MeshReliableMessage *copy;
3314 if (GNUNET_NO == ch->reliable)
3318 rel = fwd ? ch->dest_rel : ch->root_rel;
3319 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3320 "send_data_ack for %u\n",
3323 type = GNUNET_MESSAGE_TYPE_MESH_DATA_ACK;
3324 msg.header.type = htons (type);
3325 msg.header.size = htons (sizeof (msg));
3326 msg.chid = htonl (ch->gid);
3327 msg.mid = htonl (rel->mid_recv - 1);
3329 for (copy = rel->head_recv; NULL != copy; copy = copy->next)
3331 if (copy->type != type)
3333 delta = copy->mid - rel->mid_recv;
3336 mask = 0x1LL << delta;
3337 msg.futures |= mask;
3338 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3339 " setting bit for %u (delta %u) (%llX) -> %llX\n",
3340 copy->mid, delta, mask, msg.futures);
3342 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " final futures %llX\n", msg.futures);
3344 send_prebuilt_message_channel (&msg.header, ch, fwd);
3345 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_data_ack END\n");
3350 * Send an ACK informing the predecessor about the available buffer space.
3352 * Note that for fwd ack, the FWD mean forward *traffic* (root->dest),
3353 * the ACK itself goes "back" (dest->root).
3355 * @param c Connection on which to send the ACK.
3356 * @param buffer How much space free to advertise?
3357 * @param fwd Is this FWD ACK? (Going dest->owner)
3360 connection_send_ack (struct MeshConnection *c, unsigned int buffer, int fwd)
3362 struct MeshFlowControl *next_fc;
3363 struct MeshFlowControl *prev_fc;
3364 struct GNUNET_MESH_ACK msg;
3368 next_fc = fwd ? &c->fwd_fc : &c->bck_fc;
3369 prev_fc = fwd ? &c->bck_fc : &c->fwd_fc;
3371 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3372 "connection send %s ack on %s\n",
3373 fwd ? "FWD" : "BCK", GNUNET_h2s (&c->id));
3375 /* Check if we need to transmit the ACK */
3376 if (prev_fc->last_ack_sent - prev_fc->last_pid_recv > 3)
3378 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer > 3\n");
3379 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3380 " last pid recv: %u, last ack sent: %u\n",
3381 prev_fc->last_pid_recv, prev_fc->last_ack_sent);
3385 /* Ok, ACK might be necessary, what PID to ACK? */
3386 delta = next_fc->queue_max - next_fc->queue_n;
3387 ack = prev_fc->last_pid_recv + delta;
3388 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", ack);
3389 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3390 " last pid %u, last ack %u, qmax %u, q %u\n",
3391 prev_fc->last_pid_recv, prev_fc->last_ack_sent,
3392 next_fc->queue_max, next_fc->queue_n);
3393 if (ack == prev_fc->last_ack_sent)
3395 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not needed\n");
3399 prev_fc->last_ack_sent = ack;
3401 /* Build ACK message and send on connection */
3402 msg.header.size = htons (sizeof (msg));
3403 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ACK);
3404 msg.ack = htonl (ack);
3407 send_prebuilt_message_connection (&msg.header, c, NULL, !fwd);
3412 * Modify the mesh message TID from global to local and send to client.
3414 * @param ch Channel on which to send the message.
3415 * @param msg Message to modify and send.
3416 * @param c Client to send to.
3417 * @param tid Tunnel ID to use (c can be both owner and client).
3420 channel_send_client_to_tid (struct MeshChannel *ch,
3421 const struct GNUNET_MESH_Data *msg,
3422 struct MeshClient *c, MESH_ChannelNumber id)
3424 struct GNUNET_MESH_LocalData *copy;
3425 uint16_t size = ntohs (msg->header.size) - sizeof (struct GNUNET_MESH_Data);
3426 char cbuf[size + sizeof (struct GNUNET_MESH_LocalData)];
3428 if (size < sizeof (struct GNUNET_MessageHeader))
3430 GNUNET_break_op (0);
3438 copy = (struct GNUNET_MESH_LocalData *) cbuf;
3439 memcpy (©[1], &msg[1], size);
3440 copy->header.size = htons (sizeof (struct GNUNET_MESH_LocalData) + size);
3441 copy->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA);
3442 copy->id = htonl (id);
3443 GNUNET_SERVER_notification_context_unicast (nc, c->handle,
3444 ©->header, GNUNET_NO);
3449 * We have received a message out of order, or the client is not ready.
3450 * Buffer it until we receive an ACK from the client or the missing
3451 * message from the channel.
3453 * @param msg Message to buffer (MUST be of type MESH_DATA).
3454 * @param rel Reliability data to the corresponding direction.
3457 channel_rel_add_buffered_data (const struct GNUNET_MESH_Data *msg,
3458 struct MeshChannelReliability *rel)
3460 struct MeshReliableMessage *copy;
3461 struct MeshReliableMessage *prev;
3465 size = ntohs (msg->header.size);
3466 mid = ntohl (msg->mid);
3468 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data %u\n", mid);
3470 copy = GNUNET_malloc (sizeof (*copy) + size);
3473 memcpy (©[1], msg, size);
3477 // FIXME do something better than O(n), although n < 64...
3478 // FIXME start from the end (most messages are the latest ones)
3479 for (prev = rel->head_recv; NULL != prev; prev = prev->next)
3481 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " prev %u\n", prev->mid);
3482 if (GMC_is_pid_bigger (prev->mid, mid))
3484 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " bingo!\n");
3485 GNUNET_CONTAINER_DLL_insert_before (rel->head_recv, rel->tail_recv,
3490 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " insert at tail!\n");
3491 GNUNET_CONTAINER_DLL_insert_tail (rel->head_recv, rel->tail_recv, copy);
3492 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data END\n");
3497 channel_send_client_data (struct MeshChannel *ch,
3498 const struct GNUNET_MESH_Data *msg,
3503 if (ch->dest_rel->client_ready)
3504 channel_send_client_to_tid (ch, msg, ch->dest, ch->lid_dest);
3506 channel_rel_add_buffered_data (msg, ch->dest_rel);
3510 if (ch->root_rel->client_ready)
3511 channel_send_client_to_tid (ch, msg, ch->root, ch->lid_root);
3513 channel_rel_add_buffered_data (msg, ch->root_rel);
3519 * Send a buffered message to the client, for in order delivery or
3520 * as result of client ACK.
3522 * @param ch Channel on which to empty the message buffer.
3523 * @param c Client to send to.
3524 * @param rel Reliability structure to corresponding peer.
3525 * If rel == bck_rel, this is FWD data.
3528 channel_send_client_buffered_data (struct MeshChannel *ch,
3529 struct MeshClient *c,
3532 struct MeshReliableMessage *copy;
3533 struct MeshChannelReliability *rel;
3535 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data\n");
3536 rel = fwd ? ch->dest_rel : ch->root_rel;
3537 if (GNUNET_NO == rel->client_ready)
3539 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client not ready\n");
3543 copy = rel->head_recv;
3544 /* We never buffer channel management messages */
3547 if (copy->mid == rel->mid_recv || GNUNET_NO == ch->reliable)
3549 struct GNUNET_MESH_Data *msg = (struct GNUNET_MESH_Data *) ©[1];
3551 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3552 " have %u! now expecting %u\n",
3553 copy->mid, rel->mid_recv + 1);
3554 channel_send_client_data (ch, msg, fwd);
3557 GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
3562 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3563 " reliable && don't have %u, next is %u\n",
3569 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data END\n");
3574 * Destroy a reliable message after it has been acknowledged, either by
3575 * direct mid ACK or bitfield. Updates the appropriate data structures and
3576 * timers and frees all memory.
3578 * @param copy Message that is no longer needed: remote peer got it.
3581 rel_message_free (struct MeshReliableMessage *copy)
3583 struct MeshChannelReliability *rel;
3584 struct GNUNET_TIME_Relative time;
3587 time = GNUNET_TIME_absolute_get_duration (copy->timestamp);
3588 rel->expected_delay.rel_value_us *= 7;
3589 rel->expected_delay.rel_value_us += time.rel_value_us;
3590 rel->expected_delay.rel_value_us /= 8;
3592 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Freeing %u\n", copy->mid);
3593 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " n_sent %u\n", rel->n_sent);
3594 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! took %s\n",
3595 GNUNET_STRINGS_relative_time_to_string (time, GNUNET_NO));
3596 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! new expected delay %s\n",
3597 GNUNET_STRINGS_relative_time_to_string (rel->expected_delay,
3599 rel->retry_timer = rel->expected_delay;
3600 GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
3606 * Destroy all reliable messages queued for a channel,
3607 * during a channel destruction.
3608 * Frees the reliability structure itself.
3610 * @param rel Reliability data for a channel.
3613 channel_rel_free_all (struct MeshChannelReliability *rel)
3615 struct MeshReliableMessage *copy;
3616 struct MeshReliableMessage *next;
3621 for (copy = rel->head_recv; NULL != copy; copy = next)
3624 GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
3627 for (copy = rel->head_sent; NULL != copy; copy = next)
3630 GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
3633 if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
3634 GNUNET_SCHEDULER_cancel (rel->retry_task);
3640 * Mark future messages as ACK'd.
3642 * @param rel Reliability data.
3643 * @param msg DataACK message with a bitfield of future ACK'd messages.
3646 channel_rel_free_sent (struct MeshChannelReliability *rel,
3647 const struct GNUNET_MESH_DataACK *msg)
3649 struct MeshReliableMessage *copy;
3650 struct MeshReliableMessage *next;
3657 bitfield = msg->futures;
3658 mid = ntohl (msg->mid);
3659 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3660 "free_sent_reliable %u %llX\n",
3662 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3663 " rel %p, head %p\n",
3664 rel, rel->head_sent);
3665 for (i = 0, copy = rel->head_sent;
3666 i < 64 && NULL != copy && 0 != bitfield;
3669 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3670 " trying bit %u (mid %u)\n",
3673 if (0 == (bitfield & mask))
3676 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " set!\n");
3677 /* Bit was set, clear the bit from the bitfield */
3680 /* The i-th bit was set. Do we have that copy? */
3681 /* Skip copies with mid < target */
3682 target = mid + i + 1;
3683 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " target %u\n", target);
3684 while (NULL != copy && GMC_is_pid_bigger (target, copy->mid))
3687 /* Did we run out of copies? (previously freed, it's ok) */
3690 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "run out of copies...\n");
3694 /* Did we overshoot the target? (previously freed, it's ok) */
3695 if (GMC_is_pid_bigger (copy->mid, target))
3697 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " next copy %u\n", copy->mid);
3701 /* Now copy->mid == target, free it */
3703 rel_message_free (copy);
3706 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "free_sent_reliable END\n");
3711 * We haven't received an ACK after a certain time: restransmit the message.
3713 * @param cls Closure (MeshReliableMessage with the message to restransmit)
3714 * @param tc TaskContext.
3717 channel_retransmit_message (void *cls,
3718 const struct GNUNET_SCHEDULER_TaskContext *tc)
3720 struct MeshChannelReliability *rel = cls;
3721 struct MeshReliableMessage *copy;
3722 struct MeshPeerQueue *q;
3723 struct MeshChannel *ch;
3724 struct MeshConnection *c;
3725 struct GNUNET_MESH_Data *payload;
3726 struct MeshPeer *hop;
3729 rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
3730 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3734 copy = rel->head_sent;
3741 /* Search the message to be retransmitted in the outgoing queue.
3742 * Check only the queue for the connection that is going to be used,
3743 * if the message is stuck in some other connection's queue we shouldn't
3745 * - cancelling it and sending the new one doesn't guarantee it's delivery,
3746 * the old connection could be temporary stalled or the queue happened to
3747 * be long at time of insertion.
3748 * - not sending the new one could cause terrible delays the old connection
3751 payload = (struct GNUNET_MESH_Data *) ©[1];
3752 fwd = (rel == ch->root_rel);
3753 c = tunnel_get_connection (ch->t, fwd);
3754 hop = connection_get_hop (c, fwd);
3755 for (q = hop->queue_head; NULL != q; q = q->next)
3757 if (ntohs (payload->header.type) == q->type && ch == q->ch)
3759 struct GNUNET_MESH_Data *queued_data = q->cls;
3761 if (queued_data->mid == payload->mid)
3766 /* Message not found in the queue that we are going to use. */
3769 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! RETRANSMIT %u\n", copy->mid);
3771 send_prebuilt_message_channel (&payload->header, ch, fwd);
3772 GNUNET_STATISTICS_update (stats, "# data retransmitted", 1, GNUNET_NO);
3776 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! ALREADY IN QUEUE %u\n", copy->mid);
3779 rel->retry_timer = GNUNET_TIME_STD_BACKOFF (rel->retry_timer);
3780 rel->retry_task = GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
3781 &channel_retransmit_message,
3787 * Send ACK on one or more connections due to buffer space to the client.
3789 * Iterates all connections of the tunnel and sends ACKs appropriately.
3791 * @param ch Channel which has some free buffer space.
3792 * @param fwd Is this in for FWD traffic? (ACK goes dest->root)
3795 channel_send_connections_ack (struct MeshChannel *ch,
3796 unsigned int buffer,
3799 struct MeshTunnel2 *t = ch->t;
3800 struct MeshConnection *c;
3801 struct MeshFlowControl *fc;
3804 uint32_t allow_per_connection;
3807 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3808 "Channel send connection %s ack on %s:%X\n",
3809 fwd ? "FWD" : "BCK", peer2s (ch->t->peer), ch->gid);
3811 /* Count connections, how many messages are already allowed */
3812 for (cs = 0, allowed = 0, c = t->connection_head; NULL != c; c = c->next)
3814 fc = fwd ? &c->fwd_fc : &c->bck_fc;
3815 if (GMC_is_pid_bigger(fc->last_pid_recv, fc->last_ack_sent))
3820 allowed += fc->last_ack_sent - fc->last_pid_recv;
3824 /* Make sure there is no overflow */
3825 if (allowed > buffer)
3831 /* Authorize connections to send more data */
3832 to_allow = buffer - allowed;
3834 for (c = t->connection_head; NULL != c && to_allow > 0; c = c->next)
3836 allow_per_connection = to_allow/cs;
3837 to_allow -= allow_per_connection;
3839 fc = fwd ? &c->fwd_fc : &c->bck_fc;
3840 if (fc->last_ack_sent - fc->last_pid_recv > 64 / 3)
3844 connection_send_ack (c, allow_per_connection, fwd);
3847 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3848 "Channel send connection %s ack on %s:%X\n",
3849 fwd ? "FWD" : "BCK", peer2s (ch->t->peer), ch->gid);
3850 GNUNET_break (to_allow == 0);
3855 * Send an ACK on the appropriate connection/channel, depending on
3856 * the direction and the position of the peer.
3858 * @param c Which connection to send the hop-by-hop ACK.
3859 * @param ch Channel, if any.
3860 * @param fwd Is this a fwd ACK? (will go dest->root)
3863 send_ack (struct MeshConnection *c, struct MeshChannel *ch, int fwd)
3865 unsigned int buffer;
3867 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3868 "send ack %s on %p %p\n",
3869 fwd ? "FWD" : "BCK", c, ch);
3870 if (NULL == c || connection_is_terminal (c, fwd))
3872 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " getting from Channel\n");
3873 buffer = tunnel_get_buffer (NULL == c ? ch->t : c->t, fwd);
3877 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " getting from Connection\n");
3878 GNUNET_assert (NULL != c);
3879 buffer = connection_get_buffer (c, fwd);
3881 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " buffer available: %u\n", buffer);
3885 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " sending on all connections\n");
3886 GNUNET_assert (NULL != ch);
3887 channel_send_connections_ack (ch, buffer, fwd);
3889 else if (connection_is_origin (c, fwd))
3891 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " sending on channel...\n");
3894 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " really sending!\n");
3895 GNUNET_assert (NULL != ch);
3896 send_local_ack (ch, fwd);
3901 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " sending on connection\n");
3902 connection_send_ack (c, buffer, fwd);
3908 * Channel was ACK'd by remote peer, mark as ready and cancel retransmission.
3910 * @param ch Channel to mark as ready.
3911 * @param fwd Was the CREATE message sent fwd?
3914 channel_confirm (struct MeshChannel *ch, int fwd)
3916 struct MeshChannelReliability *rel;
3917 struct MeshReliableMessage *copy;
3918 struct MeshReliableMessage *next;
3920 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3921 " channel confirm %s %s:%X\n",
3922 fwd ? "FWD" : "BCK", peer2s (ch->t->peer), ch->gid);
3923 ch->state = MESH_CHANNEL_READY;
3925 rel = fwd ? ch->root_rel : ch->dest_rel;
3926 for (copy = rel->head_sent; NULL != copy; copy = next)
3928 struct GNUNET_MessageHeader *msg;
3931 msg = (struct GNUNET_MessageHeader *) ©[1];
3932 if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE)
3934 rel_message_free (copy);
3938 if (GNUNET_NO == rel->client_ready)
3939 send_local_ack (ch, fwd);
3944 * Save a copy to retransmit in case it gets lost.
3946 * Initializes all needed callbacks and timers.
3948 * @param ch Channel this message goes on.
3949 * @param msg Message to copy.
3950 * @param fwd Is this fwd traffic?
3953 channel_save_copy (struct MeshChannel *ch,
3954 const struct GNUNET_MessageHeader *msg,
3957 struct MeshChannelReliability *rel;
3958 struct MeshReliableMessage *copy;
3963 rel = fwd ? ch->root_rel : ch->dest_rel;
3964 mid = rel->mid_send;
3965 type = ntohs (msg->type);
3966 size = ntohs (msg->size);
3968 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! SAVE %u\n", mid);
3969 copy = GNUNET_malloc (sizeof (struct MeshReliableMessage) + size);
3971 copy->timestamp = GNUNET_TIME_absolute_get ();
3974 memcpy (©[1], msg, size);
3976 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " n_sent %u\n", rel->n_sent);
3977 GNUNET_CONTAINER_DLL_insert_tail (rel->head_sent, rel->tail_sent, copy);
3978 if (GNUNET_SCHEDULER_NO_TASK == rel->retry_task)
3981 GNUNET_TIME_relative_multiply (rel->expected_delay,
3982 MESH_RETRANSMIT_MARGIN);
3984 GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
3985 &channel_retransmit_message,
3992 * Send keepalive packets for a connection.
3994 * @param c Connection to keep alive..
3995 * @param fwd Is this a FWD keepalive? (owner -> dest).
3998 connection_keepalive (struct MeshConnection *c, int fwd)
4000 struct GNUNET_MESH_ConnectionKeepAlive *msg;
4001 size_t size = sizeof (struct GNUNET_MESH_ConnectionKeepAlive);
4005 type = fwd ? GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE :
4006 GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE;
4008 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4009 "sending %s keepalive for connection %s[%d]\n",
4010 fwd ? "FWD" : "BCK",
4011 peer2s (c->t->peer),
4014 msg = (struct GNUNET_MESH_ConnectionKeepAlive *) cbuf;
4015 msg->header.size = htons (size);
4016 msg->header.type = htons (type);
4019 send_prebuilt_message_connection (&msg->header, c, NULL, fwd);
4024 * Send CONNECTION_{CREATE/ACK} packets for a connection.
4026 * @param c Connection for which to send the message.
4027 * @param fwd If GNUNET_YES, send CREATE, otherwise send ACK.
4030 connection_recreate (struct MeshConnection *c, int fwd)
4032 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "sending connection recreate\n");
4034 send_connection_create (c);
4036 send_connection_ack (c, GNUNET_NO);
4041 * Generic connection timer management.
4042 * Depending on the role of the peer in the connection will send the
4043 * appropriate message (build or keepalive)
4045 * @param c Conncetion to maintain.
4046 * @param fwd Is FWD?
4049 connection_maintain (struct MeshConnection *c, int fwd)
4051 if (MESH_TUNNEL_SEARCHING == c->t->state)
4053 /* TODO DHT GET with RO_BART */
4058 case MESH_CONNECTION_NEW:
4060 case MESH_CONNECTION_SENT:
4061 connection_recreate (c, fwd);
4063 case MESH_CONNECTION_READY:
4064 connection_keepalive (c, fwd);
4073 connection_fwd_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4075 struct MeshConnection *c = cls;
4077 c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4078 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4081 connection_maintain (c, GNUNET_YES);
4082 c->fwd_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
4083 &connection_fwd_keepalive,
4089 connection_bck_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4091 struct MeshConnection *c = cls;
4093 c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4094 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4097 connection_maintain (c, GNUNET_NO);
4098 c->bck_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
4099 &connection_bck_keepalive,
4105 * Send a message to all peers in this connection that the connection
4106 * is no longer valid.
4108 * If some peer should not receive the message, it should be zero'ed out
4109 * before calling this function.
4111 * @param c The connection whose peers to notify.
4114 connection_send_destroy (struct MeshConnection *c)
4116 struct GNUNET_MESH_ConnectionDestroy msg;
4118 msg.header.size = htons (sizeof (msg));
4119 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);;
4121 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4122 " sending connection destroy for connection %s[%X]\n",
4123 peer2s (c->t->peer),
4126 if (GNUNET_NO == connection_is_terminal (c, GNUNET_YES))
4127 send_prebuilt_message_connection (&msg.header, c, NULL, GNUNET_YES);
4128 if (GNUNET_NO == connection_is_terminal (c, GNUNET_NO))
4129 send_prebuilt_message_connection (&msg.header, c, NULL, GNUNET_NO);
4130 c->destroy = GNUNET_YES;
4135 * Confirm we got a channel create.
4137 * @param ch The channel to confirm.
4138 * @param fwd Should we send the ACK fwd?
4141 channel_send_ack (struct MeshChannel *ch, int fwd)
4143 struct GNUNET_MESH_ChannelManage msg;
4145 msg.header.size = htons (sizeof (msg));
4146 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK);
4147 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4148 " sending channel %s ack for channel %s:%X\n",
4149 fwd ? "FWD" : "BCK", peer2s (ch->t->peer),
4152 msg.chid = htonl (ch->gid);
4153 send_prebuilt_message_channel (&msg.header, ch, !fwd);
4158 * Send a message to all clients (local and remote) of this channel
4159 * notifying that the channel is no longer valid.
4161 * If some peer or client should not receive the message,
4162 * should be zero'ed out before calling this function.
4164 * @param ch The channel whose clients to notify.
4167 channel_send_destroy (struct MeshChannel *ch)
4169 struct GNUNET_MESH_ChannelManage msg;
4171 msg.header.size = htons (sizeof (msg));
4172 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY);
4173 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4174 " sending channel destroy for channel %s:%X\n",
4175 peer2s (ch->t->peer),
4178 if (channel_is_terminal (ch, GNUNET_NO))
4180 if (NULL != ch->root && GNUNET_NO == ch->root->shutting_down)
4182 msg.chid = htonl (ch->lid_root);
4183 send_local_channel_destroy (ch, GNUNET_NO);
4188 msg.chid = htonl (ch->gid);
4189 send_prebuilt_message_channel (&msg.header, ch, GNUNET_NO);
4192 if (channel_is_terminal (ch, GNUNET_YES))
4194 if (NULL != ch->dest && GNUNET_NO == ch->dest->shutting_down)
4196 msg.chid = htonl (ch->lid_dest);
4197 send_local_channel_destroy (ch, GNUNET_YES);
4202 msg.chid = htonl (ch->gid);
4203 send_prebuilt_message_channel (&msg.header, ch, GNUNET_YES);
4211 static struct MeshTunnel2 *
4214 struct MeshTunnel2 *t;
4216 t = GNUNET_new (struct MeshTunnel2);
4218 t->next_local_chid = GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
4220 // GNUNET_CONTAINER_multihashmap_put (tunnels, tid, t,
4221 // GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
4223 // GNUNET_break (0);
4224 // tunnel_destroy (t);
4228 // char salt[] = "salt";
4229 // GNUNET_CRYPTO_kdf (&t->e_key, sizeof (struct GNUNET_CRYPTO_AesSessionKey),
4230 // salt, sizeof (salt),
4231 // &t->e_key, sizeof (struct GNUNET_CRYPTO_AesSessionKey),
4232 // &my_full_id, sizeof (struct GNUNET_PeerIdentity),
4233 // GNUNET_PEER_resolve2 (t->peer->id), sizeof (struct GNUNET_PeerIdentity),
4235 // GNUNET_CRYPTO_kdf (&t->d_key, sizeof (struct GNUNET_CRYPTO_AesSessionKey),
4236 // salt, sizeof (salt),
4237 // &t->d_key, sizeof (struct GNUNET_CRYPTO_AesSessionKey),
4238 // GNUNET_PEER_resolve2 (t->peer->id), sizeof (struct GNUNET_PeerIdentity),
4239 // &my_full_id, sizeof (struct GNUNET_PeerIdentity),
4247 * Add a connection to a tunnel.
4250 * @param c Connection.
4253 tunnel_add_connection (struct MeshTunnel2 *t, struct MeshConnection *c)
4255 struct MeshConnection *aux;
4257 for (aux = t->connection_head; aux != NULL; aux = aux->next)
4260 GNUNET_CONTAINER_DLL_insert_tail (t->connection_head, t->connection_tail, c);
4265 * Initialize a Flow Control structure to the initial state.
4267 * @param fc Flow Control structure to initialize.
4270 fc_init (struct MeshFlowControl *fc)
4273 fc->last_pid_sent = (uint32_t) -1; /* Next (expected) = 0 */
4274 fc->last_pid_recv = (uint32_t) -1;
4275 fc->last_ack_sent = (uint32_t) 0;
4276 fc->last_ack_recv = (uint32_t) 0;
4277 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
4278 fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
4280 fc->queue_max = (max_msgs_queue / max_connections) + 1;
4284 static struct MeshConnection *
4285 connection_new (const struct GNUNET_HashCode *cid)
4287 struct MeshConnection *c;
4289 c = GNUNET_new (struct MeshConnection);
4291 GNUNET_CONTAINER_multihashmap_put (connections, &c->id, c,
4292 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
4293 fc_init (&c->fwd_fc);
4294 fc_init (&c->bck_fc);
4303 * Find a connection.
4305 * @param cid Connection ID.
4307 static struct MeshConnection *
4308 connection_get (const struct GNUNET_HashCode *cid)
4310 return GNUNET_CONTAINER_multihashmap_get (connections, cid);
4315 connection_destroy (struct MeshConnection *c)
4317 struct MeshPeer *peer;
4322 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying connection %s[%X]\n",
4323 peer2s (c->t->peer),
4326 /* Cancel all traffic */
4327 connection_cancel_queues (c, GNUNET_YES);
4328 connection_cancel_queues (c, GNUNET_NO);
4330 /* Cancel maintainance task (keepalive/timeout) */
4331 if (GNUNET_SCHEDULER_NO_TASK != c->fwd_maintenance_task)
4332 GNUNET_SCHEDULER_cancel (c->fwd_maintenance_task);
4333 if (GNUNET_SCHEDULER_NO_TASK != c->bck_maintenance_task)
4334 GNUNET_SCHEDULER_cancel (c->bck_maintenance_task);
4336 /* Deregister from neighbors */
4337 peer = connection_get_next_hop (c);
4338 if (NULL != peer && NULL != peer->connections)
4339 GNUNET_CONTAINER_multihashmap_remove (peer->connections, &c->id, c);
4340 peer = connection_get_prev_hop (c);
4341 if (NULL != peer && NULL != peer->connections)
4342 GNUNET_CONTAINER_multihashmap_remove (peer->connections, &c->id, c);
4345 GNUNET_STATISTICS_update (stats, "# connections", -1, GNUNET_NO);
4346 GNUNET_CONTAINER_DLL_remove (c->t->connection_head, c->t->connection_tail, c);
4352 tunnel_destroy (struct MeshTunnel2 *t)
4354 struct MeshConnection *c;
4355 struct MeshConnection *next;
4360 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n",
4363 // if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &t->id, t))
4364 // GNUNET_break (0);
4366 for (c = t->connection_head; NULL != c; c = next)
4369 connection_destroy (c);
4372 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
4379 * Tunnel is empty: destroy it.
4381 * Notifies all connections about the destruction.
4383 * @param t Tunnel to destroy.
4386 tunnel_destroy_empty (struct MeshTunnel2 *t)
4388 struct MeshConnection *c;
4390 for (c = t->connection_head; NULL != c; c = c->next)
4392 if (GNUNET_NO == c->destroy)
4393 connection_send_destroy (c);
4396 if (0 == t->pending_messages)
4399 t->destroy = GNUNET_YES;
4404 * Destroy tunnel if empty (no more channels).
4406 * @param t Tunnel to destroy if empty.
4409 tunnel_destroy_if_empty (struct MeshTunnel2 *t)
4411 if (NULL != t->channel_head)
4414 tunnel_destroy_empty (t);
4419 * Destroy a channel and free all resources.
4421 * @param ch Channel to destroy.
4424 channel_destroy (struct MeshChannel *ch)
4426 struct MeshClient *c;
4434 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap32_remove (c->own_channels,
4445 GNUNET_CONTAINER_multihashmap32_remove (c->incoming_channels,
4452 channel_rel_free_all (ch->root_rel);
4453 channel_rel_free_all (ch->dest_rel);
4455 GNUNET_CONTAINER_DLL_remove (ch->t->channel_head, ch->t->channel_tail, ch);
4456 GNUNET_STATISTICS_update (stats, "# channels", -1, GNUNET_NO);
4462 * Create a new channel.
4464 * @param t Tunnel this channel is in.
4465 * @param owner Client that owns the channel, NULL for foreign channels.
4466 * @param lid_root Local ID for root client.
4468 * @return A new initialized channel. NULL on error.
4470 static struct MeshChannel *
4471 channel_new (struct MeshTunnel2 *t,
4472 struct MeshClient *owner, MESH_ChannelNumber lid_root)
4474 struct MeshChannel *ch;
4476 ch = GNUNET_new (struct MeshChannel);
4478 ch->lid_root = lid_root;
4481 GNUNET_CONTAINER_DLL_insert (t->channel_head, t->channel_tail, ch);
4483 GNUNET_STATISTICS_update (stats, "# channels", 1, GNUNET_NO);
4487 while (NULL != channel_get (t, t->next_chid))
4488 t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
4489 ch->gid = t->next_chid;
4490 t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
4493 GNUNET_CONTAINER_multihashmap32_put (owner->own_channels, lid_root, ch,
4494 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
4497 channel_destroy (ch);
4498 GNUNET_SERVER_receive_done (owner->handle, GNUNET_SYSERR);
4508 * Set options in a channel, extracted from a bit flag field
4510 * @param ch Channel to set options to.
4511 * @param options Bit array in host byte order.
4514 channel_set_options (struct MeshChannel *ch, uint32_t options)
4516 ch->nobuffer = (options & GNUNET_MESH_OPTION_NOBUFFER) != 0 ?
4517 GNUNET_YES : GNUNET_NO;
4518 ch->reliable = (options & GNUNET_MESH_OPTION_RELIABLE) != 0 ?
4519 GNUNET_YES : GNUNET_NO;
4524 * Iterator for deleting each channel whose client endpoint disconnected.
4526 * @param cls Closure (client that has disconnected).
4527 * @param key The local channel id (used to access the hashmap).
4528 * @param value The value stored at the key (channel to destroy).
4530 * @return GNUNET_OK, keep iterating.
4533 channel_destroy_iterator (void *cls,
4537 struct MeshChannel *ch = value;
4538 struct MeshClient *c = cls;
4539 struct MeshTunnel2 *t;
4541 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4542 " Channel %X (%X / %X) destroy, due to client %u shutdown.\n",
4543 ch->gid, ch->lid_root, ch->lid_dest, c->id);
4547 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is destination.\n", c->id);
4551 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is owner.\n", c->id);
4555 channel_send_destroy (ch);
4556 channel_destroy (ch);
4557 tunnel_destroy_if_empty (t);
4564 * Remove client's ports from the global hashmap on disconnect.
4566 * @param cls Closure (unused).
4568 * @param value Client structure.
4570 * @return GNUNET_OK, keep iterating.
4573 client_release_ports (void *cls,
4579 res = GNUNET_CONTAINER_multihashmap32_remove (ports, key, value);
4580 if (GNUNET_YES != res)
4583 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4584 "Port %u by client %p was not registered.\n",
4592 * Timeout function due to lack of keepalive/traffic from the owner.
4593 * Destroys connection if called.
4595 * @param cls Closure (connection to destroy).
4596 * @param tc TaskContext.
4599 connection_fwd_timeout (void *cls,
4600 const struct GNUNET_SCHEDULER_TaskContext *tc)
4602 struct MeshConnection *c = cls;
4604 c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4605 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4607 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4608 "Connection %s[%X] FWD timed out. Destroying.\n",
4609 peer2s (c->t->peer),
4612 if (connection_is_origin (c, GNUNET_YES)) /* If local, leave. */
4615 connection_destroy (c);
4620 * Timeout function due to lack of keepalive/traffic from the destination.
4621 * Destroys connection if called.
4623 * @param cls Closure (connection to destroy).
4624 * @param tc TaskContext
4627 connection_bck_timeout (void *cls,
4628 const struct GNUNET_SCHEDULER_TaskContext *tc)
4630 struct MeshConnection *c = cls;
4632 c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4633 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4636 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4637 "Connection %s[%X] FWD timed out. Destroying.\n",
4638 peer2s (c->t->peer),
4641 if (connection_is_origin (c, GNUNET_NO)) /* If local, leave. */
4644 connection_destroy (c);
4649 * Resets the connection timeout task, some other message has done the
4651 * - For the first peer on the direction this means to send
4652 * a keepalive or a path confirmation message (either create or ACK).
4653 * - For all other peers, this means to destroy the connection,
4654 * due to lack of activity.
4655 * Starts the tiemout if no timeout was running (connection just created).
4657 * @param c Connection whose timeout to reset.
4658 * @param fwd Is this forward?
4660 * TODO use heap to improve efficiency of scheduler.
4663 connection_reset_timeout (struct MeshConnection *c, int fwd)
4665 GNUNET_SCHEDULER_TaskIdentifier *ti;
4666 GNUNET_SCHEDULER_Task f;
4668 ti = fwd ? &c->fwd_maintenance_task : &c->bck_maintenance_task;
4670 if (GNUNET_SCHEDULER_NO_TASK != *ti)
4671 GNUNET_SCHEDULER_cancel (*ti);
4673 if (connection_is_origin (c, fwd)) /* Endpoint */
4675 f = fwd ? &connection_fwd_keepalive : &connection_bck_keepalive;
4676 *ti = GNUNET_SCHEDULER_add_delayed (refresh_connection_time, f, c);
4680 struct GNUNET_TIME_Relative delay;
4682 delay = GNUNET_TIME_relative_multiply (refresh_connection_time, 4);
4683 f = fwd ? &connection_fwd_timeout : &connection_bck_timeout;
4684 *ti = GNUNET_SCHEDULER_add_delayed (delay, f, c);
4690 * Iterator to notify all connections of a broken link. Mark connections
4691 * to destroy after all traffic has been sent.
4693 * @param cls Closure (peer disconnected).
4694 * @param key Current key code (tid).
4695 * @param value Value in the hash map (connection).
4697 * @return GNUNET_YES if we should continue to iterate,
4701 connection_broken (void *cls,
4702 const struct GNUNET_HashCode *key,
4705 struct MeshPeer *peer = cls;
4706 struct MeshConnection *c = value;
4707 struct GNUNET_MESH_ConnectionBroken msg;
4710 fwd = peer == connection_get_prev_hop (c);
4712 connection_cancel_queues (c, !fwd);
4713 if (connection_is_terminal (c, fwd))
4715 /* Local shutdown, no one to notify about this. */
4716 connection_destroy (c);
4720 msg.header.size = htons (sizeof (struct GNUNET_MESH_ConnectionBroken));
4721 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN);
4723 msg.peer1 = my_full_id;
4724 msg.peer2 = *GNUNET_PEER_resolve2 (peer->id);
4725 send_prebuilt_message_connection (&msg.header, c, NULL, fwd);
4726 c->destroy = GNUNET_YES;
4731 /******************************************************************************/
4732 /**************** MESH NETWORK HANDLER HELPERS ***********************/
4733 /******************************************************************************/
4736 * Free a transmission that was already queued with all resources
4737 * associated to the request.
4739 * @param queue Queue handler to cancel.
4740 * @param clear_cls Is it necessary to free associated cls?
4743 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
4745 struct MeshPeer *peer;
4746 struct MeshFlowControl *fc;
4751 GNUNET_assert (NULL != queue->c);
4752 fc = fwd ? &queue->c->fwd_fc : &queue->c->bck_fc;
4754 if (GNUNET_YES == clear_cls)
4756 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " queue destroy type %s\n",
4757 GNUNET_MESH_DEBUG_M2S (queue->type));
4758 switch (queue->type)
4760 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
4761 case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
4762 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "destroying a DESTROY message\n");
4763 GNUNET_break (GNUNET_YES == queue->c->destroy);
4765 case GNUNET_MESSAGE_TYPE_MESH_FWD:
4766 case GNUNET_MESSAGE_TYPE_MESH_BCK:
4767 case GNUNET_MESSAGE_TYPE_MESH_ACK:
4768 case GNUNET_MESSAGE_TYPE_MESH_POLL:
4769 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
4770 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
4771 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
4772 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " prebuilt message\n");;
4773 GNUNET_free_non_null (queue->cls);
4778 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, " type %s unknown!\n",
4779 GNUNET_MESH_DEBUG_M2S (queue->type));
4783 GNUNET_CONTAINER_DLL_remove (peer->queue_head, peer->queue_tail, queue);
4785 if (queue->type != GNUNET_MESSAGE_TYPE_MESH_ACK &&
4786 queue->type != GNUNET_MESSAGE_TYPE_MESH_POLL)
4788 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Q_N- %p %u\n", fc, fc->queue_n);
4792 if (NULL != queue->c)
4794 queue->c->pending_messages--;
4795 if (NULL != queue->c->t)
4797 queue->c->t->pending_messages--;
4801 GNUNET_free (queue);
4806 queue_send (void *cls, size_t size, void *buf)
4808 struct MeshPeer *peer = cls;
4809 struct MeshFlowControl *fc;
4810 struct MeshConnection *c;
4811 struct GNUNET_MessageHeader *msg;
4812 struct MeshPeerQueue *queue;
4813 struct MeshTunnel2 *t;
4814 struct MeshChannel *ch;
4815 const struct GNUNET_PeerIdentity *dst_id;
4821 peer->core_transmit = NULL;
4822 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Queue send (max %u)\n", size);
4824 if (NULL == buf || 0 == size)
4826 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Buffer size 0.\n");
4831 queue = peer_get_first_message (peer);
4834 GNUNET_break (0); /* Core tmt_rdy should've been canceled */
4839 fc = fwd ? &c->fwd_fc : &c->bck_fc;
4842 dst_id = GNUNET_PEER_resolve2 (peer->id);
4843 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* towards %s\n", GNUNET_i2s (dst_id));
4844 /* Check if buffer size is enough for the message */
4845 if (queue->size > size)
4847 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* not enough room, reissue\n");
4848 peer->core_transmit =
4849 GNUNET_CORE_notify_transmit_ready (core_handle,
4852 GNUNET_TIME_UNIT_FOREVER_REL,
4859 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* size %u ok\n", queue->size);
4861 t = (NULL != c) ? c->t : NULL;
4865 switch (queue->type)
4867 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
4868 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
4869 case GNUNET_MESSAGE_TYPE_MESH_FWD:
4870 case GNUNET_MESSAGE_TYPE_MESH_BCK:
4871 case GNUNET_MESSAGE_TYPE_MESH_ACK:
4872 case GNUNET_MESSAGE_TYPE_MESH_POLL:
4873 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4875 GNUNET_MESH_DEBUG_M2S (queue->type));
4876 data_size = send_core_data_raw (queue->cls, size, buf);
4877 msg = (struct GNUNET_MessageHeader *) buf;
4878 type = ntohs (msg->type);
4880 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
4881 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* path create\n");
4882 if (connection_is_origin (c, GNUNET_YES))
4883 data_size = send_core_connection_create (queue->c, size, buf);
4885 data_size = send_core_data_raw (queue->cls, size, buf);
4887 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
4888 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* path ack\n");
4889 if (connection_is_origin (c, GNUNET_NO) ||
4890 connection_is_origin (c, GNUNET_YES))
4891 data_size = send_core_connection_ack (queue->c, size, buf);
4893 data_size = send_core_data_raw (queue->cls, size, buf);
4895 case GNUNET_MESSAGE_TYPE_MESH_DATA:
4896 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
4897 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
4898 /* This should be encapsulted */
4904 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "* type unknown: %u\n",
4909 if (0 < drop_percent &&
4910 GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 101) < drop_percent)
4912 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4913 "Dropping message of type %s\n",
4914 GNUNET_MESH_DEBUG_M2S (queue->type));
4918 /* Free queue, but cls was freed by send_core_* */
4920 queue_destroy (queue, GNUNET_NO);
4922 /* Send ACK if needed, after accounting for sent ID in fc->queue_n */
4925 case GNUNET_MESSAGE_TYPE_MESH_FWD:
4926 case GNUNET_MESSAGE_TYPE_MESH_BCK:
4927 pid = ntohl ( ((struct GNUNET_MESH_Encrypted *) buf)->pid );
4928 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* accounting pid %u\n", pid);
4929 fc->last_pid_sent = pid;
4930 send_ack (c, ch, fwd);
4936 /* If more data in queue, send next */
4937 queue = peer_get_first_message (peer);
4940 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* more data!\n");
4941 if (NULL == peer->core_transmit) {
4942 peer->core_transmit =
4943 GNUNET_CORE_notify_transmit_ready(core_handle,
4946 GNUNET_TIME_UNIT_FOREVER_REL,
4954 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4955 "* tmt rdy called somewhere else\n");
4957 if (GNUNET_SCHEDULER_NO_TASK == fc->poll_task)
4959 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* starting poll timeout\n");
4961 GNUNET_SCHEDULER_add_delayed (fc->poll_time, &connection_poll, fc);
4966 if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
4968 GNUNET_SCHEDULER_cancel (fc->poll_task);
4969 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
4974 c->pending_messages--;
4975 if (GNUNET_YES == c->destroy && 0 == c->pending_messages)
4977 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* destroying connection!\n");
4978 connection_destroy (c);
4984 t->pending_messages--;
4985 if (GNUNET_YES == t->destroy && 0 == t->pending_messages)
4987 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* destroying tunnel!\n");
4991 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Return %d\n", data_size);
4997 queue_add (void *cls, uint16_t type, size_t size,
4998 struct MeshConnection *c,
4999 struct MeshChannel *ch,
5002 struct MeshPeerQueue *queue;
5003 struct MeshFlowControl *fc;
5004 struct MeshPeer *peer;
5008 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5009 "queue add %s %s (%u) on c %p, ch %p\n",
5010 fwd ? "FWD" : "BCK", GNUNET_MESH_DEBUG_M2S (type), size, c, ch);
5011 GNUNET_assert (NULL != c);
5013 fc = fwd ? &c->fwd_fc : &c->bck_fc;
5014 peer = fwd ? connection_get_next_hop (c) : connection_get_prev_hop (c);
5024 if (GNUNET_MESSAGE_TYPE_MESH_POLL == type ||
5025 GNUNET_MESSAGE_TYPE_MESH_ACK == type)
5030 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "priority %d\n", priority);
5031 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "fc %p\n", fc);
5032 if (fc->queue_n >= fc->queue_max && 0 == priority)
5034 GNUNET_STATISTICS_update (stats, "# messages dropped (buffer full)",
5037 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5038 "queue full: %u/%u\n",
5039 fc->queue_n, fc->queue_max);
5040 return; /* Drop this message */
5043 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "last pid %u\n", fc->last_pid_sent);
5044 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ack %u\n", fc->last_ack_recv);
5045 if (GMC_is_pid_bigger (fc->last_pid_sent + 1, fc->last_ack_recv))
5047 call_core = GNUNET_NO;
5048 if (GNUNET_SCHEDULER_NO_TASK == fc->poll_task &&
5049 GNUNET_MESSAGE_TYPE_MESH_POLL != type)
5051 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5052 "no buffer space (%u > %u): starting poll\n",
5053 fc->last_pid_sent + 1, fc->last_ack_recv);
5054 fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
5060 call_core = GNUNET_YES;
5061 queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
5069 if (100 <= priority)
5071 GNUNET_CONTAINER_DLL_insert (peer->queue_head, peer->queue_tail, queue);
5075 GNUNET_CONTAINER_DLL_insert_tail (peer->queue_head, peer->queue_tail, queue);
5076 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Q_N+ %p %u\n", fc, fc->queue_n);
5081 if (NULL == peer->core_transmit && GNUNET_YES == call_core)
5083 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5084 "calling core tmt rdy towards %s for %u bytes\n",
5085 peer2s (peer), size);
5086 peer->core_transmit =
5087 GNUNET_CORE_notify_transmit_ready (core_handle,
5090 GNUNET_TIME_UNIT_FOREVER_REL,
5091 GNUNET_PEER_resolve2 (peer->id),
5098 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5099 "core tmt rdy towards %s already called\n",
5103 c->pending_messages++;
5105 c->t->pending_messages++;
5109 /******************************************************************************/
5110 /******************** MESH NETWORK HANDLERS **************************/
5111 /******************************************************************************/
5115 * Generic handler for mesh network payload traffic.
5117 * @param t Tunnel on which we got this message.
5118 * @param message Unencryted data message.
5119 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5122 handle_data (struct MeshTunnel2 *t, const struct GNUNET_MESH_Data *msg, int fwd)
5124 struct MeshChannelReliability *rel;
5125 struct MeshChannel *ch;
5126 struct MeshClient *c;
5132 size = ntohs (msg->header.size);
5134 sizeof (struct GNUNET_MESH_Data) +
5135 sizeof (struct GNUNET_MessageHeader))
5140 type = ntohs (msg->header.type);
5141 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message\n",
5142 GNUNET_MESH_DEBUG_M2S (type));
5143 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
5144 GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5147 ch = channel_get (t, ntohl (msg->chid));
5150 GNUNET_STATISTICS_update (stats, "# data on unknown channel", 1, GNUNET_NO);
5151 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel unknown\n");
5155 /* Initialize FWD/BCK data */
5156 c = fwd ? ch->dest : ch->root;
5157 rel = fwd ? ch->dest_rel : ch->root_rel;
5165 tunnel_change_state (t, MESH_TUNNEL_READY);
5167 GNUNET_STATISTICS_update (stats, "# data received", 1, GNUNET_NO);
5169 mid = ntohl (msg->mid);
5170 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " mid %u\n", mid);
5172 if (GNUNET_NO == ch->reliable ||
5173 ( !GMC_is_pid_bigger (rel->mid_recv, mid) &&
5174 GMC_is_pid_bigger (rel->mid_recv + 64, mid) ) )
5176 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! RECV %u\n", mid);
5177 if (GNUNET_YES == ch->reliable)
5179 /* Is this the exact next expected messasge? */
5180 if (mid == rel->mid_recv)
5182 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "as expected\n");
5184 channel_send_client_data (ch, msg, fwd);
5188 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "save for later\n");
5189 channel_rel_add_buffered_data (msg, rel);
5194 /* Tunnel is unreliable: send to clients directly */
5195 /* FIXME: accept Out Of Order traffic */
5196 rel->mid_recv = mid + 1;
5197 channel_send_client_data (ch, msg, fwd);
5202 GNUNET_break_op (0);
5203 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5204 " MID %u not expected (%u - %u), dropping!\n",
5205 mid, rel->mid_recv, rel->mid_recv + 64);
5208 channel_send_data_ack (ch, fwd);
5212 * Handler for mesh network traffic end-to-end ACKs.
5214 * @param t Tunnel on which we got this message.
5215 * @param message Data message.
5216 * @param fwd Is this a fwd ACK? (dest->orig)
5219 handle_data_ack (struct MeshTunnel2 *t,
5220 const struct GNUNET_MESH_DataACK *msg, int fwd)
5222 struct MeshChannelReliability *rel;
5223 struct MeshReliableMessage *copy;
5224 struct MeshReliableMessage *next;
5225 struct MeshChannel *ch;
5230 type = ntohs (msg->header.type);
5231 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a %s message!\n",
5232 GNUNET_MESH_DEBUG_M2S (type));
5233 ch = channel_get (t, ntohl (msg->chid));
5236 GNUNET_STATISTICS_update (stats, "# ack on unknown channel", 1, GNUNET_NO);
5239 ack = ntohl (msg->mid);
5240 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! %s ACK %u\n",
5241 (GNUNET_YES == fwd) ? "FWD" : "BCK", ack);
5243 if (GNUNET_YES == fwd)
5257 for (work = GNUNET_NO, copy = rel->head_sent; copy != NULL; copy = next)
5259 if (GMC_is_pid_bigger (copy->mid, ack))
5261 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! head %u, out!\n", copy->mid);
5262 channel_rel_free_sent (rel, msg);
5266 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! id %u\n", copy->mid);
5268 rel_message_free (copy);
5270 /* ACK client if needed */
5271 // channel_send_ack (t, type, GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK == type);
5273 /* If some message was free'd, update the retransmission delay*/
5274 if (GNUNET_YES == work)
5276 if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
5278 GNUNET_SCHEDULER_cancel (rel->retry_task);
5279 if (NULL == rel->head_sent)
5281 rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
5285 struct GNUNET_TIME_Absolute new_target;
5286 struct GNUNET_TIME_Relative delay;
5288 delay = GNUNET_TIME_relative_multiply (rel->retry_timer,
5289 MESH_RETRANSMIT_MARGIN);
5290 new_target = GNUNET_TIME_absolute_add (rel->head_sent->timestamp,
5292 delay = GNUNET_TIME_absolute_get_remaining (new_target);
5294 GNUNET_SCHEDULER_add_delayed (delay,
5295 &channel_retransmit_message,
5306 * Core handler for connection creation.
5308 * @param cls Closure (unused).
5309 * @param peer Sender (neighbor).
5310 * @param message Message.
5312 * @return GNUNET_OK to keep the connection open,
5313 * GNUNET_SYSERR to close it (signal serious error)
5316 handle_mesh_connection_create (void *cls,
5317 const struct GNUNET_PeerIdentity *peer,
5318 const struct GNUNET_MessageHeader *message)
5320 struct GNUNET_MESH_ConnectionCreate *msg;
5321 struct GNUNET_PeerIdentity *id;
5322 struct GNUNET_HashCode *cid;
5323 struct MeshPeerPath *path;
5324 struct MeshPeer *dest_peer;
5325 struct MeshPeer *orig_peer;
5326 struct MeshConnection *c;
5327 unsigned int own_pos;
5331 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
5332 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection create msg\n");
5335 size = ntohs (message->size);
5336 if (size < sizeof (struct GNUNET_MESH_ConnectionCreate))
5338 GNUNET_break_op (0);
5342 /* Calculate hops */
5343 size -= sizeof (struct GNUNET_MESH_ConnectionCreate);
5344 if (size % sizeof (struct GNUNET_PeerIdentity))
5346 GNUNET_break_op (0);
5349 size /= sizeof (struct GNUNET_PeerIdentity);
5352 GNUNET_break_op (0);
5355 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " path has %u hops.\n", size);
5357 /* Get parameters */
5358 msg = (struct GNUNET_MESH_ConnectionCreate *) message;
5360 id = (struct GNUNET_PeerIdentity *) &msg[1];
5361 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5362 " connection %s (%s).\n",
5363 GNUNET_h2s (cid), GNUNET_i2s (id));
5365 /* Create connection */
5366 c = connection_get (cid);
5369 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Creating connection\n");
5370 c = connection_new (cid);
5373 connection_reset_timeout (c, GNUNET_YES);
5376 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Creating path...\n");
5377 path = path_new (size);
5379 for (i = 0; i < size; i++)
5381 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... adding %s\n",
5382 GNUNET_i2s (&id[i]));
5383 path->peers[i] = GNUNET_PEER_intern (&id[i]);
5384 if (path->peers[i] == myid)
5387 if (own_pos == 0 && path->peers[own_pos] != myid)
5389 /* create path: self not found in path through self */
5390 GNUNET_break_op (0);
5391 path_destroy (path);
5392 connection_destroy (c);
5395 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Own position: %u\n", own_pos);
5396 path_add_to_peers (path, GNUNET_NO);
5397 c->path = path_duplicate (path);
5398 c->own_pos = own_pos;
5404 if (MESH_CONNECTION_NEW == c->state)
5405 connection_change_state (c, MESH_CONNECTION_SENT);
5407 /* Remember peers */
5408 dest_peer = peer_get (&id[size - 1]);
5409 orig_peer = peer_get (&id[0]);
5411 /* Is it a connection to us? */
5412 if (c->own_pos == size - 1)
5414 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " It's for us!\n");
5415 peer_add_path_to_origin (orig_peer, path, GNUNET_YES);
5417 if (NULL == orig_peer->tunnel)
5419 orig_peer->tunnel = tunnel_new ();
5420 orig_peer->tunnel->peer = orig_peer;
5422 tunnel_add_connection (orig_peer->tunnel, c);
5423 if (MESH_TUNNEL_NEW == c->t->state)
5424 tunnel_change_state (c->t, MESH_TUNNEL_WAITING);
5426 send_connection_ack (c, GNUNET_NO);
5427 if (MESH_CONNECTION_SENT == c->state)
5428 connection_change_state (c, MESH_CONNECTION_ACK);
5430 /* Keep tunnel alive in direction dest->owner*/
5431 connection_reset_timeout (c, GNUNET_NO);
5435 /* It's for somebody else! Retransmit. */
5436 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Retransmitting.\n");
5437 peer_add_path (dest_peer, path_duplicate (path), GNUNET_NO);
5438 peer_add_path_to_origin (orig_peer, path, GNUNET_NO);
5439 send_prebuilt_message_connection (message, c, NULL, GNUNET_YES);
5446 * Core handler for path ACKs
5448 * @param cls closure
5449 * @param message message
5450 * @param peer peer identity this notification is about
5452 * @return GNUNET_OK to keep the connection open,
5453 * GNUNET_SYSERR to close it (signal serious error)
5456 handle_mesh_connection_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5457 const struct GNUNET_MessageHeader *message)
5459 struct GNUNET_MESH_ConnectionACK *msg;
5460 struct MeshConnection *c;
5461 struct MeshPeerPath *p;
5462 struct MeshPeer *pi;
5465 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
5466 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection ACK msg\n");
5467 msg = (struct GNUNET_MESH_ConnectionACK *) message;
5468 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " on connection %s\n",
5469 GNUNET_h2s (&msg->cid));
5470 c = connection_get (&msg->cid);
5473 GNUNET_STATISTICS_update (stats, "# control on unknown connection",
5475 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " don't know the connection!\n");
5480 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " via peer %s\n",
5482 pi = peer_get (peer);
5483 if (connection_get_next_hop (c) == pi)
5485 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " SYNACK\n");
5487 if (MESH_CONNECTION_SENT == c->state)
5488 connection_change_state (c, MESH_CONNECTION_ACK);
5490 else if (connection_get_prev_hop (c) == pi)
5492 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ACK\n");
5494 connection_change_state (c, MESH_CONNECTION_READY);
5498 GNUNET_break_op (0);
5501 connection_reset_timeout (c, fwd);
5503 /* Add path to peers? */
5507 path_add_to_peers (p, GNUNET_YES);
5514 /* Message for us as creator? */
5515 if (connection_is_origin (c, GNUNET_YES))
5517 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Connection (SYN)ACK for us!\n");
5518 connection_change_state (c, MESH_CONNECTION_READY);
5519 if (MESH_TUNNEL_READY != c->t->state)
5520 tunnel_change_state (c->t, MESH_TUNNEL_READY);
5521 send_connection_ack (c, GNUNET_YES);
5522 tunnel_send_queued_data (c->t, GNUNET_YES);
5523 if (3 <= tunnel_count_connections (c->t) && NULL != c->t->peer->dhtget)
5525 GNUNET_DHT_get_stop (c->t->peer->dhtget);
5526 c->t->peer->dhtget = NULL;
5531 /* Message for us as destination? */
5532 if (connection_is_terminal (c, GNUNET_YES))
5534 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Connection ACK for us!\n");
5535 if (MESH_TUNNEL_READY != c->t->state)
5536 tunnel_change_state (c->t, MESH_TUNNEL_READY);
5537 connection_change_state (c, MESH_CONNECTION_READY);
5538 tunnel_send_queued_data (c->t, GNUNET_NO);
5542 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " not for us, retransmitting...\n");
5543 send_prebuilt_message_connection (message, c, NULL, fwd);
5549 * Core handler for notifications of broken paths
5551 * @param cls Closure (unused).
5552 * @param peer Peer identity of sending neighbor.
5553 * @param message Message.
5555 * @return GNUNET_OK to keep the connection open,
5556 * GNUNET_SYSERR to close it (signal serious error)
5559 handle_mesh_connection_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
5560 const struct GNUNET_MessageHeader *message)
5562 struct GNUNET_MESH_ConnectionBroken *msg;
5563 struct MeshConnection *c;
5565 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5566 "Received a CONNECTION BROKEN msg from %s\n", GNUNET_i2s (peer));
5567 msg = (struct GNUNET_MESH_ConnectionBroken *) message;
5568 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " regarding %s\n",
5569 GNUNET_i2s (&msg->peer1));
5570 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " regarding %s\n",
5571 GNUNET_i2s (&msg->peer2));
5572 c = connection_get (&msg->cid);
5575 GNUNET_break_op (0);
5578 tunnel_notify_connection_broken (c->t, GNUNET_PEER_search (&msg->peer1),
5579 GNUNET_PEER_search (&msg->peer2));
5586 * Core handler for tunnel destruction
5588 * @param cls Closure (unused).
5589 * @param peer Peer identity of sending neighbor.
5590 * @param message Message.
5592 * @return GNUNET_OK to keep the connection open,
5593 * GNUNET_SYSERR to close it (signal serious error)
5596 handle_mesh_connection_destroy (void *cls,
5597 const struct GNUNET_PeerIdentity *peer,
5598 const struct GNUNET_MessageHeader *message)
5600 struct GNUNET_MESH_ConnectionDestroy *msg;
5601 struct MeshConnection *c;
5605 msg = (struct GNUNET_MESH_ConnectionDestroy *) message;
5606 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5607 "Got a CONNECTION DESTROY message from %s\n",
5609 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5610 " for connection %s\n",
5611 GNUNET_h2s (&msg->cid));
5612 c = connection_get (&msg->cid);
5615 /* Probably already got the message from another path,
5616 * destroyed the tunnel and retransmitted to children.
5619 GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
5623 id = GNUNET_PEER_search (peer);
5624 if (id == connection_get_prev_hop (c)->id)
5626 else if (id == connection_get_next_hop (c)->id)
5630 GNUNET_break_op (0);
5633 send_prebuilt_message_connection (message, c, NULL, fwd);
5634 c->destroy = GNUNET_YES;
5641 * Handler for channel create messages.
5643 * @param t Tunnel this channel is to be created in.
5644 * @param msg Message.
5645 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5648 handle_channel_create (struct MeshTunnel2 *t,
5649 struct GNUNET_MESH_ChannelCreate *msg,
5652 MESH_ChannelNumber chid;
5653 struct MeshChannel *ch;
5654 struct MeshClient *c;
5657 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received Channel Create\n");
5658 /* Check message size */
5659 if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelCreate))
5661 GNUNET_break_op (0);
5665 /* Check if channel exists */
5666 chid = ntohl (msg->chid);
5667 ch = channel_get (t, chid);
5670 /* Probably a retransmission, safe to ignore */
5671 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
5672 if (NULL != ch->dest)
5674 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " duplicate CC!!\n");
5675 channel_send_ack (ch, !fwd);
5681 /* Create channel */
5682 ch = channel_new (t, NULL, 0);
5683 channel_set_options (ch, ntohl (msg->opt));
5686 /* Find a destination client */
5687 port = ntohl (msg->port);
5688 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " port %u\n", port);
5689 c = GNUNET_CONTAINER_multihashmap32_get (ports, port);
5692 /* TODO send reject */
5693 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " no client has port registered\n");
5698 channel_add_client (ch, c);
5699 if (GNUNET_YES == ch->reliable)
5700 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
5702 send_local_channel_create (ch);
5703 channel_send_ack (ch, fwd);
5704 send_local_ack (ch, !fwd);
5709 * Handler for channel ack messages.
5711 * @param t Tunnel this channel is to be created in.
5712 * @param msg Message.
5713 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5716 handle_channel_ack (struct MeshTunnel2 *t,
5717 struct GNUNET_MESH_ChannelManage *msg,
5720 MESH_ChannelNumber chid;
5721 struct MeshChannel *ch;
5723 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received Channel ACK\n");
5724 /* Check message size */
5725 if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelManage))
5727 GNUNET_break_op (0);
5731 /* Check if channel exists */
5732 chid = ntohl (msg->chid);
5733 ch = channel_get (t, chid);
5736 GNUNET_break_op (0);
5737 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " channel %u unknown!!\n", chid);
5741 channel_confirm (ch, !fwd);
5746 * Handler for channel destroy messages.
5748 * @param t Tunnel this channel is to be destroyed of.
5749 * @param msg Message.
5750 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5753 handle_channel_destroy (struct MeshTunnel2 *t,
5754 struct GNUNET_MESH_ChannelManage *msg,
5757 MESH_ChannelNumber chid;
5758 struct MeshChannel *ch;
5760 /* Check message size */
5761 if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelManage))
5763 GNUNET_break_op (0);
5767 /* Check if channel exists */
5768 chid = ntohl (msg->chid);
5769 ch = channel_get (t, chid);
5772 /* Probably a retransmission, safe to ignore */
5776 send_local_channel_destroy (ch, fwd);
5777 channel_destroy (ch);
5782 handle_decrypted (struct MeshTunnel2 *t,
5783 const struct GNUNET_MessageHeader *msgh,
5786 switch (ntohs (msgh->type))
5788 case GNUNET_MESSAGE_TYPE_MESH_DATA:
5789 /* Don't send hop ACK, wait for client to ACK */
5790 handle_data (t, (struct GNUNET_MESH_Data *) msgh, fwd);
5793 case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
5794 handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh, fwd);
5797 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
5798 handle_channel_create (t,
5799 (struct GNUNET_MESH_ChannelCreate *) msgh,
5803 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
5804 handle_channel_ack (t,
5805 (struct GNUNET_MESH_ChannelManage *) msgh,
5809 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
5810 handle_channel_destroy (t,
5811 (struct GNUNET_MESH_ChannelManage *) msgh,
5816 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5817 "end-to-end message not known (%u)\n",
5818 ntohs (msgh->type));
5824 * Generic handler for mesh network encrypted traffic.
5826 * @param peer Peer identity this notification is about.
5827 * @param message Encrypted message.
5828 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5830 * @return GNUNET_OK to keep the connection open,
5831 * GNUNET_SYSERR to close it (signal serious error)
5834 handle_mesh_encrypted (const struct GNUNET_PeerIdentity *peer,
5835 const struct GNUNET_MESH_Encrypted *msg,
5838 struct MeshConnection *c;
5839 struct MeshTunnel2 *t;
5840 struct MeshPeer *neighbor;
5841 struct MeshFlowControl *fc;
5848 size = ntohs (msg->header.size);
5850 sizeof (struct GNUNET_MESH_Encrypted) +
5851 sizeof (struct GNUNET_MessageHeader))
5853 GNUNET_break_op (0);
5856 type = ntohs (msg->header.type);
5857 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
5858 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message from %s\n",
5859 GNUNET_MESH_DEBUG_M2S (type), GNUNET_i2s (peer));
5861 /* Check connection */
5862 c = connection_get (&msg->cid);
5865 GNUNET_STATISTICS_update (stats, "# unknown connection", 1, GNUNET_NO);
5866 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING connection unknown\n");
5870 fc = fwd ? &c->bck_fc : &c->fwd_fc;
5872 /* Check if origin is as expected */
5873 neighbor = connection_get_hop (c, !fwd);
5874 if (peer_get (peer)->id != neighbor->id)
5876 GNUNET_break_op (0);
5881 pid = ntohl (msg->pid);
5882 if (GMC_is_pid_bigger (pid, fc->last_ack_sent))
5884 GNUNET_STATISTICS_update (stats, "# unsolicited message", 1, GNUNET_NO);
5885 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5886 "WARNING Received PID %u, (prev %u), ACK %u\n",
5887 pid, fc->last_pid_recv, fc->last_ack_sent);
5890 if (GNUNET_NO == GMC_is_pid_bigger (pid, fc->last_pid_recv))
5892 GNUNET_STATISTICS_update (stats, "# duplicate PID", 1, GNUNET_NO);
5893 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5894 " Pid %u not expected (%u+), dropping!\n",
5895 pid, fc->last_pid_recv + 1);
5898 if (MESH_CONNECTION_SENT == c->state)
5899 connection_change_state (c, MESH_CONNECTION_READY);
5900 connection_reset_timeout (c, fwd);
5901 fc->last_pid_recv = pid;
5903 /* Is this message for us? */
5904 if (connection_is_terminal (c, fwd))
5906 size_t dsize = size - sizeof (struct GNUNET_MESH_Encrypted);
5908 struct GNUNET_MessageHeader *msgh;
5911 /* TODO signature verification */
5912 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " message for us!\n");
5913 GNUNET_STATISTICS_update (stats, "# messages received", 1, GNUNET_NO);
5915 fc->last_pid_recv = pid;
5916 tunnel_decrypt (t, cbuf, &msg[1], dsize, msg->iv, fwd);
5920 msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
5921 handle_decrypted (t, msgh, fwd);
5922 off += ntohs (msgh->size);
5924 send_ack (c, NULL, fwd);
5928 /* Message not for us: forward to next hop */
5929 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " not for us, retransmitting...\n");
5930 ttl = ntohl (msg->ttl);
5931 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ttl: %u\n", ttl);
5934 GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5935 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5936 send_ack (c, NULL, fwd);
5939 GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
5941 send_prebuilt_message_connection (&msg->header, c, NULL, fwd);
5948 * Core handler for mesh network traffic going orig->dest.
5950 * @param cls Closure (unused).
5951 * @param message Message received.
5952 * @param peer Peer who sent the message.
5954 * @return GNUNET_OK to keep the connection open,
5955 * GNUNET_SYSERR to close it (signal serious error)
5958 handle_mesh_fwd (void *cls, const struct GNUNET_PeerIdentity *peer,
5959 const struct GNUNET_MessageHeader *message)
5961 return handle_mesh_encrypted (peer,
5962 (struct GNUNET_MESH_Encrypted *)message,
5967 * Core handler for mesh network traffic going dest->orig.
5969 * @param cls Closure (unused).
5970 * @param message Message received.
5971 * @param peer Peer who sent the message.
5973 * @return GNUNET_OK to keep the connection open,
5974 * GNUNET_SYSERR to close it (signal serious error)
5977 handle_mesh_bck (void *cls, const struct GNUNET_PeerIdentity *peer,
5978 const struct GNUNET_MessageHeader *message)
5980 return handle_mesh_encrypted (peer,
5981 (struct GNUNET_MESH_Encrypted *)message,
5987 * Core handler for mesh network traffic point-to-point acks.
5989 * @param cls closure
5990 * @param message message
5991 * @param peer peer identity this notification is about
5993 * @return GNUNET_OK to keep the connection open,
5994 * GNUNET_SYSERR to close it (signal serious error)
5997 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5998 const struct GNUNET_MessageHeader *message)
6000 struct GNUNET_MESH_ACK *msg;
6001 struct MeshConnection *c;
6002 struct MeshFlowControl *fc;
6006 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
6007 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
6009 msg = (struct GNUNET_MESH_ACK *) message;
6011 c = connection_get (&msg->cid);
6015 GNUNET_STATISTICS_update (stats, "# ack on unknown connection", 1,
6020 /* Is this a forward or backward ACK? */
6021 id = GNUNET_PEER_search (peer);
6022 if (connection_get_next_hop (c)->id == id)
6024 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " FWD ACK\n");
6027 else if (connection_get_prev_hop (c)->id == id)
6029 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " BCK ACK\n");
6034 GNUNET_break_op (0);
6038 ack = ntohl (msg->ack);
6039 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", ack);
6041 /* Cancel polling if the ACK is bigger than before. */
6042 if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task &&
6043 GMC_is_pid_bigger (ack, fc->last_ack_recv))
6045 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Cancel poll\n");
6046 GNUNET_SCHEDULER_cancel (fc->poll_task);
6047 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
6048 fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
6051 fc->last_ack_recv = ack;
6052 connection_unlock_queue (c, fc == &c->fwd_fc);
6059 * Core handler for mesh network traffic point-to-point ack polls.
6061 * @param cls closure
6062 * @param message message
6063 * @param peer peer identity this notification is about
6065 * @return GNUNET_OK to keep the connection open,
6066 * GNUNET_SYSERR to close it (signal serious error)
6069 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
6070 const struct GNUNET_MessageHeader *message)
6072 struct GNUNET_MESH_Poll *msg;
6073 struct MeshConnection *c;
6074 struct MeshFlowControl *fc;
6079 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
6080 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a POLL packet from %s!\n",
6083 msg = (struct GNUNET_MESH_Poll *) message;
6085 c = connection_get (&msg->cid);
6089 GNUNET_STATISTICS_update (stats, "# poll on unknown connection", 1,
6091 GNUNET_break_op (0);
6095 /* Is this a forward or backward ACK?
6096 * Note: a poll should never be needed in a loopback case,
6097 * since there is no possiblility of packet loss there, so
6098 * this way of discerining FWD/BCK should not be a problem.
6100 id = GNUNET_PEER_search (peer);
6101 if (connection_get_next_hop (c)->id == id)
6103 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " FWD ACK\n");
6106 else if (connection_get_prev_hop (c)->id == id)
6108 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " BCK ACK\n");
6113 GNUNET_break_op (0);
6117 pid = ntohl (msg->pid);
6118 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " PID %u, OLD %u\n",
6119 pid, fc->last_pid_recv);
6120 fc->last_pid_recv = pid;
6121 fwd = fc == &c->fwd_fc;
6122 send_ack (c, NULL, fwd);
6129 * Core handler for mesh keepalives.
6131 * @param cls closure
6132 * @param message message
6133 * @param peer peer identity this notification is about
6134 * @return GNUNET_OK to keep the connection open,
6135 * GNUNET_SYSERR to close it (signal serious error)
6137 * TODO: Check who we got this from, to validate route.
6140 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
6141 const struct GNUNET_MessageHeader *message)
6143 struct GNUNET_MESH_ConnectionKeepAlive *msg;
6144 struct MeshConnection *c;
6145 struct MeshPeer *neighbor;
6148 msg = (struct GNUNET_MESH_ConnectionKeepAlive *) message;
6149 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
6152 c = connection_get (&msg->cid);
6155 GNUNET_STATISTICS_update (stats, "# keepalive on unknown connection", 1,
6160 fwd = GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE == ntohs (message->type) ?
6161 GNUNET_YES : GNUNET_NO;
6163 /* Check if origin is as expected */
6164 neighbor = connection_get_hop (c, fwd);
6165 if (peer_get (peer)->id != neighbor->id)
6167 GNUNET_break_op (0);
6171 connection_change_state (c, MESH_CONNECTION_READY);
6172 connection_reset_timeout (c, fwd);
6174 if (connection_is_terminal (c, fwd))
6177 GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
6178 send_prebuilt_message_connection (message, c, NULL, fwd);
6186 * Functions to handle messages from core
6188 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
6189 {&handle_mesh_connection_create, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
6191 {&handle_mesh_connection_ack, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
6192 sizeof (struct GNUNET_MESH_ConnectionACK)},
6193 {&handle_mesh_connection_broken, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN,
6194 sizeof (struct GNUNET_MESH_ConnectionBroken)},
6195 {&handle_mesh_connection_destroy, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY,
6196 sizeof (struct GNUNET_MESH_ConnectionDestroy)},
6197 {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE,
6198 sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
6199 {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE,
6200 sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
6201 {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
6202 sizeof (struct GNUNET_MESH_ACK)},
6203 {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
6204 sizeof (struct GNUNET_MESH_Poll)},
6205 {&handle_mesh_fwd, GNUNET_MESSAGE_TYPE_MESH_FWD, 0},
6206 {&handle_mesh_bck, GNUNET_MESSAGE_TYPE_MESH_BCK, 0},
6212 * Function to process paths received for a new peer addition. The recorded
6213 * paths form the initial tunnel, which can be optimized later.
6214 * Called on each result obtained for the DHT search.
6216 * @param cls closure
6217 * @param exp when will this value expire
6218 * @param key key of the result
6219 * @param get_path path of the get request
6220 * @param get_path_length lenght of get_path
6221 * @param put_path path of the put request
6222 * @param put_path_length length of the put_path
6223 * @param type type of the result
6224 * @param size number of bytes in data
6225 * @param data pointer to the result data
6228 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6229 const struct GNUNET_HashCode * key,
6230 const struct GNUNET_PeerIdentity *get_path,
6231 unsigned int get_path_length,
6232 const struct GNUNET_PeerIdentity *put_path,
6233 unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
6234 size_t size, const void *data)
6236 struct MeshPeer *peer = cls;
6237 struct MeshPeerPath *p;
6238 struct MeshConnection *c;
6239 struct GNUNET_PeerIdentity pi;
6242 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
6243 GNUNET_PEER_resolve (peer->id, &pi);
6244 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " for %s\n", GNUNET_i2s (&pi));
6246 p = path_build_from_dht (get_path, get_path_length,
6247 put_path, put_path_length);
6248 path_add_to_peers (p, GNUNET_NO);
6251 /* Count connections */
6252 for (c = peer->tunnel->connection_head, i = 0; NULL != c; c = c->next, i++);
6254 /* If we already have 3 (or more (?!)) connections, it's enough */
6258 if (peer->tunnel->state == MESH_TUNNEL_SEARCHING)
6260 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... connect!\n");
6261 peer_connect (peer);
6267 /******************************************************************************/
6268 /********************* MESH LOCAL HANDLES **************************/
6269 /******************************************************************************/
6273 * Handler for client connection.
6275 * @param cls Closure (unused).
6276 * @param client Client handler.
6279 handle_local_client_connect (void *cls, struct GNUNET_SERVER_Client *client)
6281 struct MeshClient *c;
6285 c = GNUNET_malloc (sizeof (struct MeshClient));
6287 c->id = next_client_id++; /* overflow not important: just for debug */
6288 GNUNET_SERVER_client_keep (client);
6289 GNUNET_SERVER_client_set_user_context (client, c);
6290 GNUNET_CONTAINER_DLL_insert (clients_head, clients_tail, c);
6295 * Handler for client disconnection
6297 * @param cls closure
6298 * @param client identification of the client; NULL
6299 * for the last call when the server is destroyed
6302 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
6304 struct MeshClient *c;
6306 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected: %p\n", client);
6309 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " (SERVER DOWN)\n");
6313 c = client_get (client);
6316 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u, %p)\n",
6318 GNUNET_SERVER_client_drop (c->handle);
6319 c->shutting_down = GNUNET_YES;
6320 if (NULL != c->own_channels)
6322 GNUNET_CONTAINER_multihashmap32_iterate (c->own_channels,
6323 &channel_destroy_iterator, c);
6324 GNUNET_CONTAINER_multihashmap32_destroy (c->own_channels);
6327 if (NULL != c->incoming_channels)
6329 GNUNET_CONTAINER_multihashmap32_iterate (c->incoming_channels,
6330 &channel_destroy_iterator, c);
6331 GNUNET_CONTAINER_multihashmap32_destroy (c->incoming_channels);
6334 if (NULL != c->ports)
6336 GNUNET_CONTAINER_multihashmap32_iterate (c->ports,
6337 &client_release_ports, c);
6338 GNUNET_CONTAINER_multihashmap32_destroy (c->ports);
6340 GNUNET_CONTAINER_DLL_remove (clients_head, clients_tail, c);
6341 GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
6342 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " client free (%p)\n", c);
6347 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " context NULL!\n");
6349 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "done!\n");
6355 * Handler for new clients
6357 * @param cls closure
6358 * @param client identification of the client
6359 * @param message the actual message, which includes messages the client wants
6362 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
6363 const struct GNUNET_MessageHeader *message)
6365 struct GNUNET_MESH_ClientConnect *cc_msg;
6366 struct MeshClient *c;
6371 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected %p\n", client);
6373 /* Check data sanity */
6374 size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
6375 cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
6376 if (0 != (size % sizeof (uint32_t)))
6379 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6382 size /= sizeof (uint32_t);
6384 /* Initialize new client structure */
6385 c = GNUNET_SERVER_client_get_user_context (client, struct MeshClient);
6386 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " client id %u\n", c->id);
6387 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " client has %u ports\n", size);
6392 p = (uint32_t *) &cc_msg[1];
6393 c->ports = GNUNET_CONTAINER_multihashmap32_create (size);
6394 for (i = 0; i < size; i++)
6397 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " port: %u\n", u32);
6399 /* store in client's hashmap */
6400 GNUNET_CONTAINER_multihashmap32_put (c->ports, u32, c,
6401 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
6402 /* store in global hashmap */
6403 /* FIXME only allow one client to have the port open,
6404 * have a backup hashmap with waiting clients */
6405 GNUNET_CONTAINER_multihashmap32_put (ports, u32, c,
6406 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6410 c->own_channels = GNUNET_CONTAINER_multihashmap32_create (32);
6411 c->incoming_channels = GNUNET_CONTAINER_multihashmap32_create (32);
6412 GNUNET_SERVER_notification_context_add (nc, client);
6413 GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
6415 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6416 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
6421 * Handler for requests of new tunnels
6423 * @param cls Closure.
6424 * @param client Identification of the client.
6425 * @param message The actual message.
6428 handle_local_channel_create (void *cls, struct GNUNET_SERVER_Client *client,
6429 const struct GNUNET_MessageHeader *message)
6431 struct GNUNET_MESH_ChannelMessage *msg;
6432 struct MeshPeer *peer;
6433 struct MeshTunnel2 *t;
6434 struct MeshChannel *ch;
6435 struct MeshClient *c;
6436 MESH_ChannelNumber chid;
6438 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new channel requested\n");
6440 /* Sanity check for client registration */
6441 if (NULL == (c = client_get (client)))
6444 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6447 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
6449 /* Message size sanity check */
6450 if (sizeof (struct GNUNET_MESH_ChannelMessage) != ntohs (message->size))
6453 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6457 msg = (struct GNUNET_MESH_ChannelMessage *) message;
6458 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " towards %s:%u\n",
6459 GNUNET_i2s (&msg->peer), ntohl (msg->port));
6460 chid = ntohl (msg->channel_id);
6462 /* Sanity check for duplicate channel IDs */
6463 if (NULL != channel_get_by_local_id (c, chid))
6466 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6470 peer = peer_get (&msg->peer);
6471 if (NULL == peer->tunnel)
6473 peer->tunnel = tunnel_new ();
6474 peer->tunnel->peer = peer;
6478 /* Create channel */
6479 ch = channel_new (t, c, chid);
6483 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6486 ch->port = ntohl (msg->port);
6487 channel_set_options (ch, ntohl (msg->opt));
6489 /* In unreliable channels, we'll use the DLL to buffer data for the root */
6490 ch->root_rel = GNUNET_new (struct MeshChannelReliability);
6491 ch->root_rel->ch = ch;
6492 ch->root_rel->expected_delay = MESH_RETRANSMIT_TIME;
6494 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED CHANNEL %s[%x]:%u (%x)\n",
6495 peer2s (t->peer), ch->gid, ch->port, ch->lid_root);
6496 peer_connect (peer);
6498 /* Send create channel */
6500 struct GNUNET_MESH_ChannelCreate msgcc;
6502 msgcc.header.size = htons (sizeof (msgcc));
6503 msgcc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE);
6504 msgcc.chid = htonl (ch->gid);
6505 msgcc.port = msg->port;
6506 msgcc.opt = msg->opt;
6508 tunnel_queue_data (t, ch, &msgcc.header, GNUNET_YES);
6511 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6517 * Handler for requests of deleting tunnels
6519 * @param cls closure
6520 * @param client identification of the client
6521 * @param message the actual message
6524 handle_local_channel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
6525 const struct GNUNET_MessageHeader *message)
6527 struct GNUNET_MESH_ChannelMessage *msg;
6528 struct MeshClient *c;
6529 struct MeshChannel *ch;
6530 struct MeshTunnel2 *t;
6531 MESH_ChannelNumber chid;
6533 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6534 "Got a DESTROY CHANNEL from client!\n");
6536 /* Sanity check for client registration */
6537 if (NULL == (c = client_get (client)))
6540 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6543 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
6545 /* Message sanity check */
6546 if (sizeof (struct GNUNET_MESH_ChannelMessage) != ntohs (message->size))
6549 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6553 msg = (struct GNUNET_MESH_ChannelMessage *) message;
6555 /* Retrieve tunnel */
6556 chid = ntohl (msg->channel_id);
6557 ch = channel_get_by_local_id (c, chid);
6560 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, " channel %X not found\n", chid);
6562 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6566 /* Cleanup after the tunnel */
6567 client_delete_channel (c, ch);
6568 if (c == ch->dest && GNUNET_MESH_LOCAL_CHANNEL_ID_SERV <= chid)
6572 else if (c == ch->root && GNUNET_MESH_LOCAL_CHANNEL_ID_SERV > chid)
6578 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6579 " channel %X client %p (%p, %p)\n",
6580 chid, c, ch->root, ch->dest);
6585 channel_destroy (ch);
6586 tunnel_destroy_if_empty (t);
6588 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6594 * Handler for client traffic
6596 * @param cls closure
6597 * @param client identification of the client
6598 * @param message the actual message
6601 handle_local_data (void *cls, struct GNUNET_SERVER_Client *client,
6602 const struct GNUNET_MessageHeader *message)
6604 struct GNUNET_MESH_LocalData *msg;
6605 struct MeshClient *c;
6606 struct MeshChannel *ch;
6607 struct MeshChannelReliability *rel;
6608 MESH_ChannelNumber chid;
6612 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6613 "Got data from a client!\n");
6615 /* Sanity check for client registration */
6616 if (NULL == (c = client_get (client)))
6619 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6622 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
6624 msg = (struct GNUNET_MESH_LocalData *) message;
6626 /* Sanity check for message size */
6627 size = ntohs (message->size) - sizeof (struct GNUNET_MESH_LocalData);
6628 if (size < sizeof (struct GNUNET_MessageHeader))
6631 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6635 /* Channel exists? */
6636 chid = ntohl (msg->id);
6637 fwd = chid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
6638 ch = channel_get_by_local_id (c, chid);
6642 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6646 /* Is the client in the channel? */
6649 ch->root->handle == client)
6653 ch->dest->handle == client) ) )
6656 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6660 rel = fwd ? ch->root_rel : ch->dest_rel;
6661 rel->client_ready = GNUNET_NO;
6663 /* Ok, everything is correct, send the message. */
6665 struct GNUNET_MESH_Data *payload;
6666 uint16_t p2p_size = sizeof(struct GNUNET_MESH_Data) + size;
6667 unsigned char cbuf[p2p_size];
6669 payload = (struct GNUNET_MESH_Data *) cbuf;
6670 payload->mid = htonl (rel->mid_send);
6672 memcpy (&payload[1], &msg[1], size);
6673 payload->header.size = htons (p2p_size);
6674 payload->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_DATA);
6675 payload->chid = htonl (ch->gid);
6676 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " sending on channel...\n");
6677 send_prebuilt_message_channel (&payload->header, ch, fwd);
6679 if (GNUNET_YES == ch->reliable)
6680 channel_save_copy (ch, &payload->header, fwd);
6682 if (tunnel_get_buffer (ch->t, fwd) > 0)
6683 send_local_ack (ch, fwd);
6684 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
6685 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6692 * Handler for client's ACKs for payload traffic.
6694 * @param cls Closure (unused).
6695 * @param client Identification of the client.
6696 * @param message The actual message.
6699 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
6700 const struct GNUNET_MessageHeader *message)
6702 struct GNUNET_MESH_LocalAck *msg;
6703 struct MeshChannelReliability *rel;
6704 struct MeshChannel *ch;
6705 struct MeshClient *c;
6706 MESH_ChannelNumber chid;
6709 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
6711 /* Sanity check for client registration */
6712 if (NULL == (c = client_get (client)))
6715 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6718 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
6720 msg = (struct GNUNET_MESH_LocalAck *) message;
6722 /* Channel exists? */
6723 chid = ntohl (msg->channel_id);
6724 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " on channel %X\n", chid);
6725 ch = channel_get_by_local_id (c, chid);
6726 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " -- ch %p\n", ch);
6730 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Channel %X unknown.\n", chid);
6731 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " for client %u.\n", c->id);
6732 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6736 /* If client is root, the ACK is going FWD, therefore this is "BCK". */
6737 /* If client is dest, the ACK is going BCK, therefore this is "FWD" */
6738 fwd = chid >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
6739 rel = fwd ? ch->dest_rel : ch->root_rel;
6741 rel->client_ready = GNUNET_YES;
6742 channel_send_client_buffered_data (ch, c, fwd);
6743 send_ack (NULL, ch, fwd);
6745 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6752 * Iterator over all tunnels to send a monitoring client info about each tunnel.
6754 * @param cls Closure (client handle).
6755 * @param key Key (hashed tunnel ID, unused).
6756 * @param value Tunnel info.
6758 * @return GNUNET_YES, to keep iterating.
6761 // monitor_all_tunnels_iterator (void *cls,
6762 // const struct GNUNET_HashCode * key,
6765 // struct GNUNET_SERVER_Client *client = cls;
6766 // struct MeshChannel *ch = value;
6767 // struct GNUNET_MESH_LocalMonitor *msg;
6769 // msg = GNUNET_malloc (sizeof(struct GNUNET_MESH_LocalMonitor));
6770 // msg->channel_id = htonl (ch->gid);
6771 // msg->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
6772 // msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
6774 // GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6775 // "* sending info about tunnel %s\n",
6776 // GNUNET_i2s (&msg->owner));
6778 // GNUNET_SERVER_notification_context_unicast (nc, client,
6779 // &msg->header, GNUNET_NO);
6780 // return GNUNET_YES;
6785 * Handler for client's MONITOR request.
6787 * @param cls Closure (unused).
6788 * @param client Identification of the client.
6789 * @param message The actual message.
6792 handle_local_get_tunnels (void *cls, struct GNUNET_SERVER_Client *client,
6793 const struct GNUNET_MessageHeader *message)
6795 struct MeshClient *c;
6797 /* Sanity check for client registration */
6798 if (NULL == (c = client_get (client)))
6801 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6805 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6806 "Received get tunnels request from client %u\n",
6808 // GNUNET_CONTAINER_multihashmap_iterate (tunnels,
6809 // monitor_all_tunnels_iterator,
6811 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6812 "Get tunnels request from client %u completed\n",
6814 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6819 * Handler for client's MONITOR_TUNNEL request.
6821 * @param cls Closure (unused).
6822 * @param client Identification of the client.
6823 * @param message The actual message.
6826 handle_local_show_tunnel (void *cls, struct GNUNET_SERVER_Client *client,
6827 const struct GNUNET_MessageHeader *message)
6829 const struct GNUNET_MESH_LocalMonitor *msg;
6830 struct GNUNET_MESH_LocalMonitor *resp;
6831 struct MeshClient *c;
6832 struct MeshChannel *ch;
6834 /* Sanity check for client registration */
6835 if (NULL == (c = client_get (client)))
6838 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6842 msg = (struct GNUNET_MESH_LocalMonitor *) message;
6843 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6844 "Received tunnel info request from client %u for tunnel %s[%X]\n",
6847 ntohl (msg->channel_id));
6848 // ch = channel_get (&msg->owner, ntohl (msg->channel_id));
6852 /* We don't know the tunnel */
6853 struct GNUNET_MESH_LocalMonitor warn;
6856 GNUNET_SERVER_notification_context_unicast (nc, client,
6859 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6863 /* Initialize context */
6864 resp = GNUNET_malloc (sizeof (struct GNUNET_MESH_LocalMonitor));
6866 resp->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
6867 GNUNET_SERVER_notification_context_unicast (nc, c->handle,
6868 &resp->header, GNUNET_NO);
6871 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6872 "Monitor tunnel request from client %u completed\n",
6874 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6879 * Functions to handle messages from clients
6881 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
6882 {&handle_local_new_client, NULL,
6883 GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
6884 {&handle_local_channel_create, NULL,
6885 GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE,
6886 sizeof (struct GNUNET_MESH_ChannelMessage)},
6887 {&handle_local_channel_destroy, NULL,
6888 GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY,
6889 sizeof (struct GNUNET_MESH_ChannelMessage)},
6890 {&handle_local_data, NULL,
6891 GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA, 0},
6892 {&handle_local_ack, NULL,
6893 GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
6894 sizeof (struct GNUNET_MESH_LocalAck)},
6895 {&handle_local_get_tunnels, NULL,
6896 GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS,
6897 sizeof (struct GNUNET_MessageHeader)},
6898 {&handle_local_show_tunnel, NULL,
6899 GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL,
6900 sizeof (struct GNUNET_MESH_LocalMonitor)},
6906 * Method called whenever a given peer connects.
6908 * @param cls closure
6909 * @param peer peer identity this notification is about
6912 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
6914 struct MeshPeer *pi;
6915 struct MeshPeerPath *path;
6917 DEBUG_CONN ("Peer connected\n");
6918 DEBUG_CONN (" %s\n", GNUNET_i2s (&my_full_id));
6919 pi = peer_get (peer);
6922 DEBUG_CONN (" (self)\n");
6923 path = path_new (1);
6927 DEBUG_CONN (" %s\n", GNUNET_i2s (peer));
6928 path = path_new (2);
6929 path->peers[1] = pi->id;
6930 GNUNET_PEER_change_rc (pi->id, 1);
6931 GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
6933 path->peers[0] = myid;
6934 GNUNET_PEER_change_rc (myid, 1);
6935 peer_add_path (pi, path, GNUNET_YES);
6937 pi->connections = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_YES);
6943 * Method called whenever a peer disconnects.
6945 * @param cls closure
6946 * @param peer peer identity this notification is about
6949 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
6951 struct MeshPeer *pi;
6953 DEBUG_CONN ("Peer disconnected\n");
6954 pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
6961 GNUNET_CONTAINER_multihashmap_iterate (pi->connections,
6964 GNUNET_CONTAINER_multihashmap_destroy (pi->connections);
6965 pi->connections = NULL;
6968 DEBUG_CONN (" (self)\n");
6970 GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
6977 * Install server (service) handlers and start listening to clients.
6982 GNUNET_SERVER_add_handlers (server_handle, client_handlers);
6983 GNUNET_SERVER_connect_notify (server_handle,
6984 &handle_local_client_connect, NULL);
6985 GNUNET_SERVER_disconnect_notify (server_handle,
6986 &handle_local_client_disconnect, NULL);
6987 nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
6989 clients_head = NULL;
6990 clients_tail = NULL;
6992 GNUNET_SERVER_resume (server_handle);
6997 * To be called on core init/fail.
6999 * @param cls Closure (config)
7000 * @param identity the public identity of this peer
7003 core_init (void *cls,
7004 const struct GNUNET_PeerIdentity *identity)
7006 const struct GNUNET_CONFIGURATION_Handle *c = cls;
7009 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
7010 if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)))
7012 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
7013 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7015 GNUNET_i2s (identity));
7016 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7018 GNUNET_i2s (&my_full_id));
7019 GNUNET_CORE_disconnect (core_handle);
7020 core_handle = GNUNET_CORE_connect (c, /* Main configuration */
7021 NULL, /* Closure passed to MESH functions */
7022 &core_init, /* Call core_init once connected */
7023 &core_connect, /* Handle connects */
7024 &core_disconnect, /* remove peers on disconnects */
7025 NULL, /* Don't notify about all incoming messages */
7026 GNUNET_NO, /* For header only in notification */
7027 NULL, /* Don't notify about all outbound messages */
7028 GNUNET_NO, /* For header-only out notification */
7029 core_handlers); /* Register these handlers */
7038 /******************************************************************************/
7039 /************************ MAIN FUNCTIONS ****************************/
7040 /******************************************************************************/
7043 * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
7045 * @param cls closure
7046 * @param key current key code
7047 * @param value value in the hash map
7048 * @return GNUNET_YES if we should continue to iterate,
7052 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
7054 struct MeshPeer *p = value;
7055 struct MeshTunnel2 *t = p->tunnel;
7064 * Task run during shutdown.
7070 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
7072 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
7074 if (core_handle != NULL)
7076 GNUNET_CORE_disconnect (core_handle);
7079 GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_tunnel, NULL);
7080 if (dht_handle != NULL)
7082 GNUNET_DHT_disconnect (dht_handle);
7087 GNUNET_SERVER_notification_context_destroy (nc);
7090 if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
7092 GNUNET_SCHEDULER_cancel (announce_id_task);
7093 announce_id_task = GNUNET_SCHEDULER_NO_TASK;
7095 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
7100 * Process mesh requests.
7102 * @param cls closure
7103 * @param server the initialized server
7104 * @param c configuration to use
7107 run (void *cls, struct GNUNET_SERVER_Handle *server,
7108 const struct GNUNET_CONFIGURATION_Handle *c)
7111 struct GNUNET_CRYPTO_EccPrivateKey *pk;
7113 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
7114 server_handle = server;
7115 GNUNET_SERVER_suspend (server_handle);
7118 GNUNET_CONFIGURATION_get_value_filename (c, "PEER", "PRIVATE_KEY",
7121 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7123 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
7124 "mesh", "peer/privatekey");
7125 GNUNET_SCHEDULER_shutdown ();
7130 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_CONNECTION_TIME",
7131 &refresh_connection_time))
7133 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7135 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
7136 "mesh", "refresh path time");
7137 GNUNET_SCHEDULER_shutdown ();
7142 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
7145 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7147 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
7148 "mesh", "id announce time");
7149 GNUNET_SCHEDULER_shutdown ();
7154 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
7157 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7159 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
7160 "mesh", "connect timeout");
7161 GNUNET_SCHEDULER_shutdown ();
7166 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
7169 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7171 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
7172 "mesh", "max msgs queue");
7173 GNUNET_SCHEDULER_shutdown ();
7178 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_CONNECTIONS",
7181 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7183 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
7184 "mesh", "max tunnels");
7185 GNUNET_SCHEDULER_shutdown ();
7190 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
7193 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7195 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
7196 "mesh", "default ttl", 64);
7201 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
7204 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7205 _("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
7206 "mesh", "max peers", 1000);
7211 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DROP_PERCENT",
7218 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7219 "Mesh is running with drop mode enabled. "
7220 "This is NOT a good idea! "
7221 "Remove the DROP_PERCENT option from your configuration.\n");
7225 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
7226 &dht_replication_level))
7228 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7230 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
7231 "mesh", "dht replication level", 3);
7232 dht_replication_level = 3;
7235 connections = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_YES);
7236 peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
7237 ports = GNUNET_CONTAINER_multihashmap32_create (32);
7239 dht_handle = GNUNET_DHT_connect (c, 64);
7240 if (NULL == dht_handle)
7244 stats = GNUNET_STATISTICS_create ("mesh", c);
7246 /* Scheduled the task to clean up when shutdown is called */
7247 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
7249 pk = GNUNET_CRYPTO_ecc_key_create_from_file (keyfile);
7250 GNUNET_free (keyfile);
7251 GNUNET_assert (NULL != pk);
7252 my_private_key = pk;
7253 GNUNET_CRYPTO_ecc_key_get_public (my_private_key, &my_public_key);
7254 GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
7255 &my_full_id.hashPubKey);
7256 myid = GNUNET_PEER_intern (&my_full_id);
7257 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7258 "Mesh for peer [%s] starting\n",
7259 GNUNET_i2s(&my_full_id));
7261 core_handle = GNUNET_CORE_connect (c, /* Main configuration */
7262 NULL, /* Closure passed to MESH functions */
7263 &core_init, /* Call core_init once connected */
7264 &core_connect, /* Handle connects */
7265 &core_disconnect, /* remove peers on disconnects */
7266 NULL, /* Don't notify about all incoming messages */
7267 GNUNET_NO, /* For header only in notification */
7268 NULL, /* Don't notify about all outbound messages */
7269 GNUNET_NO, /* For header-only out notification */
7270 core_handlers); /* Register these handlers */
7271 if (NULL == core_handle)
7274 GNUNET_SCHEDULER_shutdown ();
7277 announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
7278 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
7283 * The main function for the mesh service.
7285 * @param argc number of arguments from the command line
7286 * @param argv command line arguments
7287 * @return 0 ok, 1 on error
7290 main (int argc, char *const *argv)
7295 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
7296 r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
7298 ret = (GNUNET_OK == r) ? 0 : 1;
7299 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");