2 This file is part of GNUnet.
3 (C) 2001-2013 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file mesh/gnunet-service-mesh-enc.c
23 * @brief GNUnet MESH service with encryption
24 * @author Bartlomiej Polot
27 * - when sending in-order buffered data, wait for client ACKs
32 * - relay corking down to core
33 * - set ttl relative to path length
37 * - peer: other mesh instance. If there is direct connection it's a neighbor.
38 * - tunnel: encrypted connection to a peer, neighbor or not.
39 * - channel: connection between two clients, on the same or different peers.
40 * have properties like reliability.
41 * - path: series of directly connected peer from one peer to another.
42 * - connection: path which is being used in a tunnel.
46 #include "gnunet_crypto_lib.h"
48 #include "mesh_protocol_enc.h"
49 #include "mesh_path.h"
50 #include "block_mesh.h"
51 #include "gnunet_dht_service.h"
52 #include "gnunet_statistics_service.h"
54 #define MESH_BLOOM_SIZE 128
56 #define MESH_DEBUG_DHT GNUNET_NO
57 #define MESH_DEBUG_CONNECTION GNUNET_YES
58 #define MESH_DEBUG_TIMING __LINUX__ && GNUNET_NO
60 #define MESH_MAX_POLL_TIME GNUNET_TIME_relative_multiply (\
61 GNUNET_TIME_UNIT_MINUTES,\
63 #define MESH_RETRANSMIT_TIME GNUNET_TIME_UNIT_SECONDS
64 #define MESH_RETRANSMIT_MARGIN 4
66 #if MESH_DEBUG_CONNECTION
67 #define DEBUG_CONN(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
69 #define DEBUG_CONN(...)
73 #define DEBUG_DHT(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
75 #define DEBUG_DHT(...)
82 struct timespec __mesh_start;
83 struct timespec __mesh_end;
84 #define INTERVAL_START clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &(__mesh_start))
85 #define INTERVAL_END \
87 clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &(__mesh_end));\
88 double __diff = __mesh_end.tv_nsec - __mesh_start.tv_nsec;\
89 if (__diff < 0) __diff += 1000000000;\
93 #define INTERVAL_SHOW \
95 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "AVG process time: %f ns\n", __sum/__count)
97 #define INTERVAL_START
103 * All the states a tunnel can be in.
108 * Uninitialized status, should never appear in operation.
113 * Path to the peer not known yet
115 MESH_TUNNEL_SEARCHING,
118 * Request sent, not yet answered.
123 * Peer connected and ready to accept data
128 * Peer connected previosly but not responding
130 MESH_TUNNEL_RECONNECTING
135 * All the states a connection can be in.
137 enum MeshConnectionState
140 * Uninitialized status, should never appear in operation.
145 * Connection create message sent, waiting for ACK.
147 MESH_CONNECTION_SENT,
150 * Connection confirmed, ready to carry traffic..
152 MESH_CONNECTION_READY,
156 /******************************************************************************/
157 /************************ DATA STRUCTURES ****************************/
158 /******************************************************************************/
160 /** FWD declaration */
164 struct MeshConnection;
166 struct MeshChannelReliability;
170 * Struct containing info about a queued transmission to this peer
177 struct MeshPeerQueue *next;
182 struct MeshPeerQueue *prev;
185 * Peer this transmission is directed to.
187 struct MeshPeer *peer;
190 * Connection this message belongs to.
192 struct MeshConnection *c;
200 * Channel this message belongs to, if known.
202 struct MeshChannel *ch;
205 * Pointer to info stucture used as cls.
215 * Size of the message
222 * Struct to encapsulate all the Flow Control information to a peer to which
223 * we are directly connected (on a core level).
225 struct MeshFlowControl
228 * Connection this controls.
230 struct MeshConnection *c;
233 * How many messages are in the queue on this connection.
235 unsigned int queue_n;
238 * How many messages do we accept in the queue.
240 unsigned int queue_max;
248 * ID of the last packet sent towards the peer.
250 uint32_t last_pid_sent;
253 * ID of the last packet received from the peer.
255 uint32_t last_pid_recv;
258 * Last ACK sent to the peer (peer can't send more than this PID).
260 uint32_t last_ack_sent;
263 * Last ACK sent towards the origin (for traffic towards leaf node).
265 uint32_t last_ack_recv;
268 * Task to poll the peer in case of a lost ACK causes stall.
270 GNUNET_SCHEDULER_TaskIdentifier poll_task;
273 * How frequently to poll for ACKs.
275 struct GNUNET_TIME_Relative poll_time;
280 * Struct containing all information regarding a given peer
290 * Last time we heard from this peer
292 struct GNUNET_TIME_Absolute last_contact;
295 * Paths to reach the peer, ordered by ascending hop count
297 struct MeshPeerPath *path_head;
300 * Paths to reach the peer, ordered by ascending hop count
302 struct MeshPeerPath *path_tail;
305 * Handle to stop the DHT search for paths to this peer
307 struct GNUNET_DHT_GetHandle *dhtget;
310 * Tunnel to this peer, if any.
312 struct MeshTunnel2 *tunnel;
315 * Connections that go through this peer, indexed by tid;
317 struct GNUNET_CONTAINER_MultiHashMap *connections;
320 * Handle for queued transmissions
322 struct GNUNET_CORE_TransmitHandle *core_transmit;
325 * Transmission queue to core DLL head
327 struct MeshPeerQueue *queue_head;
330 * Transmission queue to core DLL tail
332 struct MeshPeerQueue *queue_tail;
335 * How many messages are in the queue to this peer.
337 unsigned int queue_n;
342 * Info needed to retry a message in case it gets lost.
344 struct MeshReliableMessage
347 * Double linked list, FIFO style
349 struct MeshReliableMessage *next;
350 struct MeshReliableMessage *prev;
353 * Tunnel Reliability queue this message is in.
355 struct MeshChannelReliability *rel;
358 * ID of the message (ACK needed to free)
363 * When was this message issued (to calculate ACK delay)
365 struct GNUNET_TIME_Absolute timestamp;
367 /* struct GNUNET_MESH_Data with payload */
371 struct MeshChannelReliability
374 * Channel this is about.
376 struct MeshChannel *ch;
379 * DLL of messages sent and not yet ACK'd.
381 struct MeshReliableMessage *head_sent;
382 struct MeshReliableMessage *tail_sent;
385 * Messages pending to send.
390 * DLL of messages received out of order.
392 struct MeshReliableMessage *head_recv;
393 struct MeshReliableMessage *tail_recv;
401 * Can we send data to the client?
406 * Task to resend/poll in case no ACK is received.
408 GNUNET_SCHEDULER_TaskIdentifier retry_task;
411 * Counter for exponential backoff.
413 struct GNUNET_TIME_Relative retry_timer;
416 * How long does it usually take to get an ACK.
418 struct GNUNET_TIME_Relative expected_delay;
423 * Struct containing all information regarding a channel to a remote client.
428 * Tunnel this channel is in.
430 struct MeshTunnel2 *t;
433 * Double linked list.
435 struct MeshChannel *next;
436 struct MeshChannel *prev;
439 * Destination port of the channel.
444 * Global channel number ( < GNUNET_MESH_LOCAL_CHANNEL_ID_CLI)
446 MESH_ChannelNumber gid;
449 * Local tunnel number for root (owner) client.
450 * ( >= GNUNET_MESH_LOCAL_CHANNEL_ID_CLI or 0 )
452 MESH_ChannelNumber lid_root;
455 * Local tunnel number for local destination clients (incoming number)
456 * ( >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV or 0).
458 MESH_ChannelNumber lid_dest;
461 * Next MID to use for fwd traffic.
463 uint32_t mid_send_fwd;
466 * Next MID expected for fwd traffic.
468 uint32_t mid_recv_fwd;
471 * Next MID to use for bck traffic.
473 uint32_t mid_send_bck;
476 * Next MID expected for bck traffic.
478 uint32_t mid_recv_bck;
481 * Is the tunnel bufferless (minimum latency)?
486 * Is the tunnel reliable?
491 * Last time the channel was used
493 struct GNUNET_TIME_Absolute timestamp;
496 * Client owner of the tunnel, if any
498 struct MeshClient *root;
501 * Client destination of the tunnel, if any.
503 struct MeshClient *dest;
506 * Flag to signal the destruction of the channel.
507 * If this is set GNUNET_YES the channel will be destroyed
508 * when the queue is empty.
513 * Total messages pending for this channel, payload or not.
515 unsigned int pending_messages;
519 * Only present (non-NULL) at the owner of a tunnel.
521 struct MeshChannelReliability *fwd_rel;
525 * Only present (non-NULL) at the destination of a tunnel.
527 struct MeshChannelReliability *bck_rel;
530 * Is the root prevented from sending more data? (We "owe" him an ACK).
535 * Is the dest prevented from sending more data? (We "owe" him an ACK).
542 * Struct containing all information regarding a connection to a peer.
544 struct MeshConnection
549 struct MeshConnection *next;
550 struct MeshConnection *prev;
553 * Tunnel this connection is part of.
555 struct MeshTunnel2 *t;
558 * Flow control information for traffic fwd.
560 struct MeshFlowControl fwd_fc;
563 * Flow control information for traffic bck.
565 struct MeshFlowControl bck_fc;
573 * State of the connection.
575 enum MeshConnectionState state;
578 * Path being used for the tunnel.
580 struct MeshPeerPath *path;
583 * Position of the local peer in the path.
585 unsigned int own_pos;
588 * Task to keep the used paths alive at the owner,
589 * time tunnel out on all the other peers.
591 GNUNET_SCHEDULER_TaskIdentifier fwd_maintenance_task;
594 * Task to keep the used paths alive at the destination,
595 * time tunnel out on all the other peers.
597 GNUNET_SCHEDULER_TaskIdentifier bck_maintenance_task;
600 * Pending message count.
602 int pending_messages;
605 * Destroy flag: if true, destroy on last message.
612 * Struct used to queue messages in a tunnel.
614 struct MeshTunnelQueue
619 struct MeshTunnelQueue *next;
620 struct MeshTunnelQueue *prev;
625 struct MeshChannel *ch;
630 /* struct GNUNET_MessageHeader *msg; */
635 * Struct containing all information regarding a tunnel to a peer.
640 * Endpoint of the tunnel.
642 struct MeshPeer *peer;
647 struct GNUNET_HashCode id;
650 * State of the tunnel.
652 enum MeshTunnelState state;
655 * Local peer ephemeral private key
657 struct GNUNET_CRYPTO_EccPrivateKey *my_eph_key;
660 * Local peer ephemeral public key
662 struct GNUNET_CRYPTO_EccPublicKey *my_eph;
665 * Remote peer's public key.
667 struct GNUNET_CRYPTO_EccPublicKey *peers_eph;
670 * Encryption ("our") key.
672 struct GNUNET_CRYPTO_AesSessionKey e_key;
675 * Decryption ("their") key.
677 struct GNUNET_CRYPTO_AesSessionKey d_key;
680 * Paths that are actively used to reach the destination peer.
682 struct MeshConnection *connection_head;
683 struct MeshConnection *connection_tail;
686 * Next connection number.
691 * Channels inside this tunnel.
693 struct MeshChannel *channel_head;
694 struct MeshChannel *channel_tail;
697 * Channel ID for the next created channel.
699 MESH_ChannelNumber next_chid;
702 * Channel ID for the next incoming channel.
704 MESH_ChannelNumber next_local_chid;
707 * Pending message count.
709 int pending_messages;
712 * Destroy flag: if true, destroy on last message.
717 * Queued messages, to transmit once tunnel gets connected.
719 struct MeshTunnelQueue *tq_head;
720 struct MeshTunnelQueue *tq_tail;
726 * Struct containing information about a client of the service
728 * TODO: add a list of 'waiting' ports
735 struct MeshClient *next;
740 struct MeshClient *prev;
743 * Tunnels that belong to this client, indexed by local id
745 struct GNUNET_CONTAINER_MultiHashMap32 *own_channels;
748 * Tunnels this client has accepted, indexed by incoming local id
750 struct GNUNET_CONTAINER_MultiHashMap32 *incoming_channels;
753 * Handle to communicate with the client
755 struct GNUNET_SERVER_Client *handle;
758 * Ports that this client has declared interest in.
759 * Indexed by port, contains *Client.
761 struct GNUNET_CONTAINER_MultiHashMap32 *ports;
764 * Whether the client is active or shutting down (don't send confirmations
765 * to a client that is shutting down.
770 * ID of the client, mainly for debug messages
776 /******************************************************************************/
777 /************************ DEBUG FUNCTIONS ****************************/
778 /******************************************************************************/
782 * GNUNET_SCHEDULER_Task for printing a message after some operation is done
783 * @param cls string to print
784 * @param success GNUNET_OK if the PUT was transmitted,
785 * GNUNET_NO on timeout,
786 * GNUNET_SYSERR on disconnect from service
787 * after the PUT message was transmitted
788 * (so we don't know if it was received or not)
793 mesh_debug (void *cls, int success)
797 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s (%d)\n", s, success);
803 /******************************************************************************/
804 /*********************** GLOBAL VARIABLES ****************************/
805 /******************************************************************************/
807 /************************** Configuration parameters **************************/
810 * How often to send path keepalives. Paths timeout after 4 missed.
812 static struct GNUNET_TIME_Relative refresh_connection_time;
815 * How often to PUT own ID in the DHT.
817 static struct GNUNET_TIME_Relative id_announce_time;
820 * Maximum time allowed to connect to a peer found by string.
822 static struct GNUNET_TIME_Relative connect_timeout;
825 * Default TTL for payload packets.
827 static unsigned long long default_ttl;
830 * DHT replication level, see DHT API: GNUNET_DHT_get_start, GNUNET_DHT_put.
832 static unsigned long long dht_replication_level;
835 * How many connections are we willing to maintain.
836 * Local connections are always allowed, even if there are more connections than max.
838 static unsigned long long max_connections;
841 * How many messages *in total* are we willing to queue, divide by number of
842 * connections to get connection queue size.
844 static unsigned long long max_msgs_queue;
847 * How many peers do we want to remember?
849 static unsigned long long max_peers;
852 * Percentage of messages that will be dropped (for test purposes only).
854 static unsigned long long drop_percent;
856 /*************************** Static global variables **************************/
859 * DLL with all the clients, head.
861 static struct MeshClient *clients_head;
864 * DLL with all the clients, tail.
866 static struct MeshClient *clients_tail;
869 * Tunnels known, indexed by MESH_TunnelID (MeshTunnel).
871 static struct GNUNET_CONTAINER_MultiHashMap *tunnels;
874 * Peers known, indexed by PeerIdentity (MeshPeer).
876 static struct GNUNET_CONTAINER_MultiHashMap *peers;
879 * Handle to communicate with core.
881 static struct GNUNET_CORE_Handle *core_handle;
886 static struct GNUNET_DHT_Handle *dht_handle;
889 * Handle to server lib.
891 static struct GNUNET_SERVER_Handle *server_handle;
894 * Handle to the statistics service.
896 static struct GNUNET_STATISTICS_Handle *stats;
899 * Notification context, to send messages to local clients.
901 static struct GNUNET_SERVER_NotificationContext *nc;
904 * Local peer own ID (memory efficient handle).
906 static GNUNET_PEER_Id myid;
909 * Local peer own ID (full value).
911 static struct GNUNET_PeerIdentity my_full_id;
916 static struct GNUNET_CRYPTO_EccPrivateKey *my_private_key;
921 static struct GNUNET_CRYPTO_EccPublicKey my_public_key;
924 * All ports clients of this peer have opened.
926 static struct GNUNET_CONTAINER_MultiHashMap32 *ports;
929 * Task to periodically announce itself in the network.
931 GNUNET_SCHEDULER_TaskIdentifier announce_id_task;
934 * Next ID to assign to a client.
936 unsigned int next_client_id;
939 /******************************************************************************/
940 /*********************** DECLARATIONS **************************/
941 /******************************************************************************/
944 * Function to process paths received for a new peer addition. The recorded
945 * paths form the initial tunnel, which can be optimized later.
946 * Called on each result obtained for the DHT search.
949 * @param exp when will this value expire
950 * @param key key of the result
951 * @param type type of the result
952 * @param size number of bytes in data
953 * @param data pointer to the result data
956 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
957 const struct GNUNET_HashCode * key,
958 const struct GNUNET_PeerIdentity *get_path,
959 unsigned int get_path_length,
960 const struct GNUNET_PeerIdentity *put_path,
961 unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
962 size_t size, const void *data);
966 * Retrieve the MeshPeer stucture associated with the peer, create one
967 * and insert it in the appropriate structures if the peer is not known yet.
969 * @param peer Full identity of the peer.
971 * @return Existing or newly created peer info.
973 static struct MeshPeer *
974 peer_get (const struct GNUNET_PeerIdentity *peer);
978 * Retrieve the MeshPeer stucture associated with the peer, create one
979 * and insert it in the appropriate structures if the peer is not known yet.
981 * @param peer Short identity of the peer.
983 * @return Existing or newly created peer info.
985 static struct MeshPeer *
986 peer_get_short (const GNUNET_PEER_Id peer);
990 * Build a PeerPath from the paths returned from the DHT, reversing the paths
991 * to obtain a local peer -> destination path and interning the peer ids.
993 * @return Newly allocated and created path
995 static struct MeshPeerPath *
996 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
997 unsigned int get_path_length,
998 const struct GNUNET_PeerIdentity *put_path,
999 unsigned int put_path_length);
1003 * Adds a path to the data structs of all the peers in the path
1005 * @param p Path to process.
1006 * @param confirmed Whether we know if the path works or not.
1009 path_add_to_peers (struct MeshPeerPath *p, int confirmed);
1013 * Search for a tunnel by global ID using full PeerIdentities.
1015 * @param t Tunnel containing the channel.
1016 * @param chid Public channel number.
1018 * @return channel handler, NULL if doesn't exist
1020 static struct MeshChannel *
1021 channel_get (struct MeshTunnel2 *t, MESH_ChannelNumber chid);
1025 * Change the tunnel state.
1027 * @param t Tunnel whose state to change.
1028 * @param state New state.
1031 tunnel_change_state (struct MeshTunnel2 *t, enum MeshTunnelState state);
1035 * Notify a tunnel that a connection has broken that affects at least
1036 * some of its peers.
1038 * @param t Tunnel affected.
1039 * @param p1 Peer that got disconnected from p2.
1040 * @param p2 Peer that got disconnected from p1.
1042 * @return Short ID of the peer disconnected (either p1 or p2).
1043 * 0 if the tunnel remained unaffected.
1045 static GNUNET_PEER_Id
1046 tunnel_notify_connection_broken (struct MeshTunnel2 *t,
1047 GNUNET_PEER_Id p1, GNUNET_PEER_Id p2);
1050 * @brief Use the given path for the tunnel.
1051 * Update the next and prev hops (and RCs).
1052 * (Re)start the path refresh in case the tunnel is locally owned.
1054 * @param t Tunnel to update.
1055 * @param p Path to use.
1057 * @return Connection created.
1059 static struct MeshConnection *
1060 tunnel_use_path (struct MeshTunnel2 *t, struct MeshPeerPath *p);
1063 * Tunnel is empty: destroy it.
1065 * Notifies all participants (peers, cleints) about the destruction.
1067 * @param t Tunnel to destroy.
1070 tunnel_destroy_empty (struct MeshTunnel2 *t);
1073 * Destroy the tunnel.
1075 * This function does not generate any warning traffic to clients or peers.
1078 * Cancel messages belonging to this tunnel queued to neighbors.
1079 * Free any allocated resources linked to the tunnel.
1081 * @param t The tunnel to destroy.
1084 tunnel_destroy (struct MeshTunnel2 *t);
1087 * Create a connection.
1089 * @param tid Tunnel ID.
1090 * @param cid Connection ID.
1092 static struct MeshConnection *
1093 connection_new (struct GNUNET_HashCode *tid, uint32_t cid);
1096 * Connection is no longer needed: destroy it and remove from tunnel.
1098 * @param c Connection to destroy.
1101 connection_destroy (struct MeshConnection *c);
1104 * Send FWD keepalive packets for a connection.
1106 * @param cls Closure (connection for which to send the keepalive).
1107 * @param tc Notification context.
1110 connection_fwd_keepalive (void *cls,
1111 const struct GNUNET_SCHEDULER_TaskContext *tc);
1114 * Send BCK keepalive packets for a connection.
1116 * @param cls Closure (connection for which to send the keepalive).
1117 * @param tc Notification context.
1120 connection_bck_keepalive (void *cls,
1121 const struct GNUNET_SCHEDULER_TaskContext *tc);
1125 * Change the tunnel state.
1127 * @param c Connection whose state to change.
1128 * @param state New state.
1131 connection_change_state (struct MeshConnection* c,
1132 enum MeshConnectionState state);
1137 * @brief Queue and pass message to core when possible.
1139 * @param cls Closure (@c type dependant). It will be used by queue_send to
1140 * build the message to be sent if not already prebuilt.
1141 * @param type Type of the message, 0 for a raw message.
1142 * @param size Size of the message.
1143 * @param c Connection this message belongs to (cannot be NULL).
1144 * @param ch Channel this message belongs to, if applicable (otherwise NULL).
1145 * @param fwd Is this a message going root->dest? (FWD ACK are NOT FWD!)
1148 queue_add (void* cls,
1151 struct MeshConnection* c,
1152 struct MeshChannel* ch,
1157 * Free a transmission that was already queued with all resources
1158 * associated to the request.
1160 * @param queue Queue handler to cancel.
1161 * @param clear_cls Is it necessary to free associated cls?
1164 queue_destroy (struct MeshPeerQueue *queue, int clear_cls);
1168 * Core callback to write a queued packet to core buffer
1170 * @param cls Closure (peer info).
1171 * @param size Number of bytes available in buf.
1172 * @param buf Where the to write the message.
1174 * @return number of bytes written to buf
1177 queue_send (void *cls, size_t size, void *buf);
1181 * Dummy function to separate declarations from definitions in function list.
1184 __mesh_divider______________________________________________________________();
1188 * Get string description for tunnel state.
1190 * @param s Tunnel state.
1192 * @return String representation.
1195 GNUNET_MESH_DEBUG_TS2S (enum MeshTunnelState s)
1197 static char buf[128];
1201 case MESH_TUNNEL_NEW:
1202 return "MESH_TUNNEL_NEW";
1203 case MESH_TUNNEL_SEARCHING:
1204 return "MESH_TUNNEL_SEARCHING";
1205 case MESH_TUNNEL_WAITING:
1206 return "MESH_TUNNEL_WAITING";
1207 case MESH_TUNNEL_READY:
1208 return "MESH_TUNNEL_READY";
1209 case MESH_TUNNEL_RECONNECTING:
1210 return "MESH_TUNNEL_RECONNECTING";
1213 sprintf (buf, "%u (UNKNOWN STATE)", s);
1220 * Get string description for tunnel state.
1222 * @param s Tunnel state.
1224 * @return String representation.
1227 GNUNET_MESH_DEBUG_CS2S (enum MeshTunnelState s)
1231 case MESH_CONNECTION_NEW:
1232 return "MESH_CONNECTION_NEW";
1233 case MESH_CONNECTION_SENT:
1234 return "MESH_CONNECTION_SENT";
1235 case MESH_CONNECTION_READY:
1236 return "MESH_CONNECTION_READY";
1238 return "MESH_CONNECTION_STATE_ERROR";
1244 /******************************************************************************/
1245 /************************ PERIODIC FUNCTIONS ****************************/
1246 /******************************************************************************/
1249 * Periodically announce self id in the DHT
1251 * @param cls closure
1252 * @param tc task context
1255 announce_id (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1257 struct PBlock block;
1259 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1261 announce_id_task = GNUNET_SCHEDULER_NO_TASK;
1265 * - Set data expiration in function of X
1266 * - Adapt X to churn
1268 DEBUG_DHT ("DHT_put for ID %s started.\n", GNUNET_i2s (&my_full_id));
1270 block.id = my_full_id;
1271 GNUNET_DHT_put (dht_handle, /* DHT handle */
1272 &my_full_id.hashPubKey, /* Key to use */
1273 dht_replication_level, /* Replication level */
1274 GNUNET_DHT_RO_RECORD_ROUTE | GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, /* DHT options */
1275 GNUNET_BLOCK_TYPE_MESH_PEER, /* Block type */
1276 sizeof (block), /* Size of the data */
1277 (const char *) &block, /* Data itself */
1278 GNUNET_TIME_UNIT_FOREVER_ABS, /* Data expiration */
1279 GNUNET_TIME_UNIT_FOREVER_REL, /* Retry time */
1280 NULL, /* Continuation */
1281 NULL); /* Continuation closure */
1283 GNUNET_SCHEDULER_add_delayed (id_announce_time, &announce_id, cls);
1287 /******************************************************************************/
1288 /****************** GENERAL HELPER FUNCTIONS ************************/
1289 /******************************************************************************/
1293 * Get the static string for a peer ID.
1297 * @return Static string for it's ID.
1300 peer2s (const struct MeshPeer *peer)
1304 return GNUNET_i2s (GNUNET_PEER_resolve2 (peer->id));
1309 * Get the previous hop in a connection
1311 * @param c Connection.
1313 * @return Previous peer in the connection.
1315 static struct MeshPeer *
1316 connection_get_prev_hop (struct MeshConnection *c)
1320 if (0 == c->own_pos || c->path->length < 2)
1321 id = c->path->peers[0];
1323 id = c->path->peers[c->own_pos - 1];
1325 return peer_get_short (id);
1330 * Get the next hop in a connection
1332 * @param c Connection.
1334 * @return Next peer in the connection.
1336 static struct MeshPeer *
1337 connection_get_next_hop (struct MeshConnection *c)
1341 if ((c->path->length - 1) == c->own_pos || c->path->length < 2)
1342 id = c->path->peers[c->path->length - 1];
1344 id = c->path->peers[c->own_pos + 1];
1346 return peer_get_short (id);
1351 * Get the hop in a connection.
1353 * @param c Connection.
1354 * @param fwd Next hop?
1356 * @return Next peer in the connection.
1358 static struct MeshPeer *
1359 connection_get_hop (struct MeshConnection *c, int fwd)
1362 return connection_get_next_hop (c);
1363 return connection_get_prev_hop (c);
1367 * Check if client has registered with the service and has not disconnected
1369 * @param client the client to check
1371 * @return non-NULL if client exists in the global DLL
1373 static struct MeshClient *
1374 client_get (struct GNUNET_SERVER_Client *client)
1376 return GNUNET_SERVER_client_get_user_context (client, struct MeshClient);
1381 * Deletes a tunnel from a client (either owner or destination).
1383 * @param c Client whose tunnel to delete.
1384 * @param ch Channel which should be deleted.
1387 client_delete_channel (struct MeshClient *c, struct MeshChannel *ch)
1393 res = GNUNET_CONTAINER_multihashmap32_remove (c->own_channels,
1395 if (GNUNET_YES != res)
1396 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client_delete_channel owner KO\n");
1400 res = GNUNET_CONTAINER_multihashmap32_remove (c->incoming_channels,
1402 if (GNUNET_YES != res)
1403 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client_delete_tunnel client KO\n");
1409 * Notify the appropriate client that a new incoming channel was created.
1411 * @param ch Channel that was created.
1414 send_local_channel_create (struct MeshChannel *ch)
1416 struct GNUNET_MESH_ChannelMessage msg;
1417 struct MeshTunnel2 *t = ch->t;
1419 if (NULL == ch->dest)
1421 msg.header.size = htons (sizeof (msg));
1422 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
1423 msg.channel_id = htonl (ch->lid_dest);
1424 msg.port = htonl (ch->port);
1426 msg.opt |= GNUNET_YES == ch->reliable ? GNUNET_MESH_OPTION_RELIABLE : 0;
1427 msg.opt |= GNUNET_YES == ch->nobuffer ? GNUNET_MESH_OPTION_NOBUFFER : 0;
1428 msg.opt = htonl (msg.opt);
1429 GNUNET_PEER_resolve (t->peer->id, &msg.peer);
1430 GNUNET_SERVER_notification_context_unicast (nc, ch->dest->handle,
1431 &msg.header, GNUNET_NO);
1436 * Notify a client that the incoming tunnel is no longer valid.
1438 * @param ch Channel that is destroyed.
1439 * @param fwd Forward notification (owner->dest)?
1442 send_local_channel_destroy (struct MeshChannel *ch, int fwd)
1444 struct GNUNET_MESH_ChannelMessage msg;
1445 struct MeshClient *c;
1447 c = fwd ? ch->dest : ch->root;
1453 msg.header.size = htons (sizeof (msg));
1454 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1455 msg.channel_id = htonl (fwd ? ch->lid_dest : ch->lid_root);
1456 msg.port = htonl (0);
1457 memset (&msg.peer, 0, sizeof (msg.peer));
1458 msg.opt = htonl (0);
1459 GNUNET_SERVER_notification_context_unicast (nc, c->handle,
1460 &msg.header, GNUNET_NO);
1465 * Build a local ACK message and send it to a local client.
1467 * @param ch Channel on which to send the ACK.
1468 * @param c Client to whom send the ACK.
1469 * @param fwd Set to GNUNET_YES for FWD ACK (dest->owner)
1472 send_local_ack (struct MeshChannel *ch,
1473 struct MeshClient *c,
1476 struct GNUNET_MESH_LocalAck msg;
1478 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1479 "send local %s ack on %s:%X towards %p\n",
1480 fwd ? "FWD" : "BCK", GNUNET_h2s (&ch->t->id), ch->gid, c);
1483 || ( fwd && (0 == ch->lid_root || c != ch->root))
1484 || (!fwd && (0 == ch->lid_dest || c != ch->dest)) )
1489 msg.header.size = htons (sizeof (msg));
1490 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
1491 msg.channel_id = htonl (fwd ? ch->lid_root : ch->lid_dest);
1492 GNUNET_SERVER_notification_context_unicast (nc,
1497 ch->blocked_fwd = GNUNET_NO;
1499 ch->blocked_bck = GNUNET_NO;
1504 * Count established (ready) connections of a tunnel.
1506 * @param t Tunnel on which to send the message.
1508 * @return Number of connections.
1511 tunnel_count_connections (struct MeshTunnel2 *t)
1513 struct MeshConnection *c;
1516 for (c = t->connection_head, i = 0; NULL != c; c = c->next, i++);
1523 * Pick a connection on which send the next data message.
1525 * @param t Tunnel on which to send the message.
1526 * @param fwd Is this a fwd message?
1528 * @return The connection on which to send the next message.
1530 static struct MeshConnection *
1531 tunnel_get_connection (struct MeshTunnel2 *t, int fwd)
1533 struct MeshConnection *c;
1534 struct MeshConnection *best;
1535 struct MeshFlowControl *fc;
1536 unsigned int lowest_q;
1539 lowest_q = UINT_MAX;
1540 for (c = t->connection_head; NULL != c; c = c->next)
1542 if (MESH_CONNECTION_READY == c->state)
1544 fc = fwd ? &c->fwd_fc : &c->bck_fc;
1550 if (fc->queue_n < lowest_q)
1553 lowest_q = fc->queue_n;
1562 * Get the total buffer space for a tunnel.
1565 tunnel_get_buffer (struct MeshTunnel2 *t, int fwd)
1567 struct MeshConnection *c;
1568 struct MeshFlowControl *fc;
1569 unsigned int buffer;
1571 for (buffer = 0, c = t->connection_head; NULL != c; c = c->next)
1573 if (c->state != MESH_CONNECTION_READY)
1576 fc = fwd ? &c->fwd_fc : &c->bck_fc;
1577 buffer += fc->last_ack_recv - fc->last_pid_sent;
1585 * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
1586 * Encrypt data with the tunnel key.
1588 * @param t Tunnel whose key to use.
1589 * @param dst Destination for the encrypted data.
1590 * @param src Source of the plaintext.
1591 * @param size Size of the plaintext.
1592 * @param iv Initialization Vector to use.
1593 * @param fwd Is this a fwd message?
1596 tunnel_encrypt (struct MeshTunnel2 *t,
1597 void *dst, const void *src,
1598 size_t size, uint64_t iv, int fwd)
1600 memcpy (dst, src, size);
1605 * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
1606 * Decrypt data with the tunnel key.
1608 * @param t Tunnel whose key to use.
1609 * @param dst Destination for the plaintext.
1610 * @param src Source of the encrypted data.
1611 * @param size Size of the encrypted data.
1612 * @param iv Initialization Vector to use.
1613 * @param fwd Is this a fwd message?
1616 tunnel_decrypt (struct MeshTunnel2 *t,
1617 void *dst, const void *src,
1618 size_t size, uint64_t iv, int fwd)
1620 memcpy (dst, src, size);
1625 * Sends an already built message on a connection, properly registering
1626 * all used resources.
1628 * @param message Message to send. Function makes a copy of it.
1629 * If message is not hop-by-hop, decrements TTL of copy.
1630 * @param c Connection on which this message is transmitted.
1631 * @param ch Channel on which this message is transmitted, or NULL.
1632 * @param fwd Is this a fwd message?
1635 send_prebuilt_message_connection (const struct GNUNET_MessageHeader *message,
1636 struct MeshConnection *c,
1637 struct MeshChannel *ch,
1644 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send on Connection %s[%X]\n",
1645 GNUNET_h2s (&c->t->id), c->id);
1647 size = ntohs (message->size);
1648 data = GNUNET_malloc (size);
1649 memcpy (data, message, size);
1650 type = ntohs (message->type);
1654 struct GNUNET_MESH_Encrypted *emsg;
1655 struct GNUNET_MESH_ACK *amsg;
1656 struct GNUNET_MESH_Poll *pmsg;
1659 case GNUNET_MESSAGE_TYPE_MESH_FWD:
1660 case GNUNET_MESSAGE_TYPE_MESH_BCK:
1661 emsg = (struct GNUNET_MESH_Encrypted *) data;
1662 ttl = ntohl (emsg->ttl);
1665 GNUNET_break_op (0);
1668 emsg->tid = c->t->id;
1669 emsg->cid = htonl (c->id);
1670 emsg->ttl = htonl (ttl - 1);
1671 emsg->pid = htonl (fwd ? c->fwd_fc.next_pid++ : c->bck_fc.next_pid++);
1672 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " pid %u\n", ntohl (emsg->pid));
1675 case GNUNET_MESSAGE_TYPE_MESH_ACK:
1676 amsg = (struct GNUNET_MESH_ACK *) data;
1677 amsg->tid = c->t->id;
1678 amsg->cid = htonl (c->id);
1679 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ack %u\n", ntohl (amsg->ack));
1682 case GNUNET_MESSAGE_TYPE_MESH_POLL:
1683 pmsg = (struct GNUNET_MESH_Poll *) data;
1684 pmsg->tid = c->t->id;
1685 pmsg->cid = htonl (c->id);
1686 pmsg->pid = htonl (fwd ? c->fwd_fc.last_pid_sent : c->bck_fc.last_pid_sent);
1687 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " poll %u\n", ntohl (pmsg->pid));
1704 * Sends an already built message on a tunnel, choosing the best connection.
1706 * @param message Message to send. Function modifies it.
1707 * @param t Tunnel on which this message is transmitted.
1708 * @param ch Channel on which this message is transmitted.
1709 * @param fwd Is this a fwd message?
1712 send_prebuilt_message_tunnel (struct GNUNET_MESH_Encrypted *msg,
1713 struct MeshTunnel2 *t,
1714 struct MeshChannel *ch,
1717 struct MeshConnection *c;
1720 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send on Tunnel %s\n",
1721 GNUNET_h2s (&t->id));
1722 c = tunnel_get_connection (t, fwd);
1725 GNUNET_break (GNUNET_YES == t->destroy);
1728 type = ntohs (msg->header.type);
1731 case GNUNET_MESSAGE_TYPE_MESH_FWD:
1732 case GNUNET_MESSAGE_TYPE_MESH_BCK:
1733 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
1734 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
1735 msg->cid = htonl (c->id);
1737 msg->ttl = htonl (default_ttl);
1740 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
1741 GNUNET_MESH_DEBUG_M2S (type));
1745 send_prebuilt_message_connection (&msg->header, c, ch, fwd);
1750 * Sends an already built message on a channel, properly registering
1751 * all used resources and encrypting the message with the tunnel's key.
1753 * @param message Message to send. Function makes a copy of it.
1754 * @param ch Channel on which this message is transmitted.
1755 * @param fwd Is this a fwd message?
1758 send_prebuilt_message_channel (const struct GNUNET_MessageHeader *message,
1759 struct MeshChannel *ch,
1762 struct GNUNET_MESH_Encrypted *msg;
1763 size_t size = ntohs (message->size);
1764 char *cbuf[sizeof (struct GNUNET_MESH_Encrypted) + size];
1768 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send on Channel %s:%X\n",
1769 GNUNET_h2s (&ch->t->id), ch->gid);
1770 type = fwd ? GNUNET_MESSAGE_TYPE_MESH_FWD : GNUNET_MESSAGE_TYPE_MESH_BCK;
1771 iv = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_NONCE, UINT64_MAX);
1773 msg = (struct GNUNET_MESH_Encrypted *) cbuf;
1774 msg->header.type = htons (type);
1775 msg->header.size = htons (sizeof (struct GNUNET_MESH_Encrypted) + size);
1776 msg->iv = GNUNET_htonll (iv);
1777 tunnel_encrypt (ch->t, &msg[1], message, size, iv, fwd);
1779 send_prebuilt_message_tunnel (msg, ch->t, ch, fwd);
1784 * Sends a CREATE CONNECTION message for a path to a peer.
1785 * Changes the connection and tunnel states if necessary.
1787 * @param connection Connection to create.
1790 send_connection_create (struct MeshConnection *connection)
1792 struct MeshTunnel2 *t;
1795 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send connection create\n");
1797 GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
1798 sizeof (struct GNUNET_MESH_ConnectionCreate) +
1799 (connection->path->length *
1800 sizeof (struct GNUNET_PeerIdentity)),
1804 if (MESH_TUNNEL_SEARCHING == t->state || MESH_TUNNEL_NEW == t->state)
1805 tunnel_change_state (t, MESH_TUNNEL_WAITING);
1806 if (MESH_CONNECTION_NEW == connection->state)
1807 connection_change_state (connection, MESH_CONNECTION_SENT);
1812 * Sends a CONNECTION ACK message in reponse to a received CONNECTION_CREATE
1815 * @param connection Connection to confirm.
1816 * @param fwd Is this a fwd ACK? (First is bck (SYNACK), second is fwd (ACK))
1819 send_connection_ack (struct MeshConnection *connection, int fwd)
1821 struct MeshTunnel2 *t;
1824 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send connection ack\n");
1826 GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
1827 sizeof (struct GNUNET_MESH_ConnectionACK),
1831 if (MESH_TUNNEL_NEW == t->state)
1832 tunnel_change_state (t, MESH_TUNNEL_WAITING);
1837 * Build a hop-by-hop ACK message and queue it to send for the given connection.
1839 * @param c Which connection to send the hop-by-hop ACK.
1840 * @param ack Value of the ACK.
1841 * @param fwd Is this fwd?
1844 send_ack (struct MeshConnection *c, uint32_t ack, int fwd)
1846 struct GNUNET_MESH_ACK msg;
1848 msg.header.size = htons (sizeof (msg));
1849 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ACK);
1850 msg.ack = htonl (ack);
1852 msg.cid = htonl (c->id);
1854 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1855 "connection send %s ack %u on %s[%X]\n",
1856 fwd ? "FWD" : "BCK", ack, GNUNET_h2s (&c->t->id), c->id);
1858 send_prebuilt_message_connection (&msg.header, c, NULL, fwd);
1863 * Core callback to write a pre-constructed data packet to core buffer
1865 * @param cls Closure (MeshTransmissionDescriptor with data in "data" member).
1866 * @param size Number of bytes available in buf.
1867 * @param buf Where the to write the message.
1869 * @return number of bytes written to buf
1872 send_core_data_raw (void *cls, size_t size, void *buf)
1874 struct GNUNET_MessageHeader *msg = cls;
1877 GNUNET_assert (NULL != msg);
1878 total_size = ntohs (msg->size);
1880 if (total_size > size)
1885 memcpy (buf, msg, total_size);
1892 * Function to send a create connection message to a peer.
1894 * @param c Connection to create.
1895 * @param size number of bytes available in buf
1896 * @param buf where the callee should write the message
1897 * @return number of bytes written to buf
1900 send_core_connection_create (struct MeshConnection *c, size_t size, void *buf)
1902 struct GNUNET_MESH_ConnectionCreate *msg;
1903 struct GNUNET_PeerIdentity *peer_ptr;
1904 struct MeshPeerPath *p = c->path;
1908 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION CREATE...\n");
1910 sizeof (struct GNUNET_MESH_ConnectionCreate) +
1911 p->length * sizeof (struct GNUNET_PeerIdentity);
1913 if (size < size_needed || NULL == buf)
1918 msg = (struct GNUNET_MESH_ConnectionCreate *) buf;
1919 msg->header.size = htons (size_needed);
1920 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE);
1921 msg->cid = htonl (c->id);
1922 msg->tid = c->t->id;
1924 peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
1925 for (i = 0; i < p->length; i++)
1927 GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
1930 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1931 "CONNECTION CREATE (%u bytes long) sent!\n", size_needed);
1937 * Creates a path ack message in buf and frees all unused resources.
1939 * @param c Connection to send an ACK on.
1940 * @param size number of bytes available in buf
1941 * @param buf where the callee should write the message
1943 * @return number of bytes written to buf
1946 send_core_connection_ack (struct MeshConnection *c, size_t size, void *buf)
1948 struct GNUNET_MESH_ConnectionACK *msg = buf;
1949 struct MeshTunnel2 *t = c->t;
1951 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION ACK...\n");
1952 GNUNET_assert (NULL != t);
1953 if (sizeof (struct GNUNET_MESH_ConnectionACK) > size)
1958 msg->header.size = htons (sizeof (struct GNUNET_MESH_ConnectionACK));
1959 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK);
1960 msg->cid = htonl (c->id);
1963 /* TODO add signature */
1965 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CONNECTION ACK sent!\n");
1966 return sizeof (struct GNUNET_MESH_ConnectionACK);
1971 * Destroy the peer_info and free any allocated resources linked to it
1973 * @param peer The peer_info to destroy.
1975 * @return GNUNET_OK on success
1978 peer_destroy (struct MeshPeer *peer)
1980 struct GNUNET_PeerIdentity id;
1981 struct MeshPeerPath *p;
1982 struct MeshPeerPath *nextp;
1984 GNUNET_PEER_resolve (peer->id, &id);
1985 GNUNET_PEER_change_rc (peer->id, -1);
1988 GNUNET_CONTAINER_multihashmap_remove (peers, &id.hashPubKey, peer))
1991 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1992 "removing peer %s, not in hashmap\n", GNUNET_i2s (&id));
1994 if (NULL != peer->dhtget)
1996 GNUNET_DHT_get_stop (peer->dhtget);
1998 p = peer->path_head;
2002 GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
2006 tunnel_destroy_empty (peer->tunnel);
2013 * Returns if peer is used (has a tunnel, is neighbor).
2015 * @peer Peer to check.
2017 * @return GNUNET_YES if peer is in use.
2020 peer_is_used (struct MeshPeer *peer)
2022 struct MeshPeerPath *p;
2024 if (NULL != peer->tunnel)
2027 for (p = peer->path_head; NULL != p; p = p->next)
2036 * Iterator over all the peers to get the oldest timestamp.
2038 * @param cls Closure (unsued).
2039 * @param key ID of the peer.
2040 * @param value Peer_Info of the peer.
2043 peer_get_oldest (void *cls,
2044 const struct GNUNET_HashCode *key,
2047 struct MeshPeer *p = value;
2048 struct GNUNET_TIME_Absolute *abs = cls;
2050 /* Don't count active peers */
2051 if (GNUNET_YES == peer_is_used (p))
2054 if (abs->abs_value_us < p->last_contact.abs_value_us)
2055 abs->abs_value_us = p->last_contact.abs_value_us;
2062 * Iterator over all the peers to remove the oldest entry.
2064 * @param cls Closure (unsued).
2065 * @param key ID of the peer.
2066 * @param value Peer_Info of the peer.
2069 peer_timeout (void *cls,
2070 const struct GNUNET_HashCode *key,
2073 struct MeshPeer *p = value;
2074 struct GNUNET_TIME_Absolute *abs = cls;
2076 if (p->last_contact.abs_value_us == abs->abs_value_us &&
2077 GNUNET_NO == peer_is_used (p))
2087 * Delete oldest unused peer.
2090 peer_delete_oldest (void)
2092 struct GNUNET_TIME_Absolute abs;
2094 abs = GNUNET_TIME_UNIT_FOREVER_ABS;
2096 GNUNET_CONTAINER_multihashmap_iterate (peers,
2099 GNUNET_CONTAINER_multihashmap_iterate (peers,
2106 * Retrieve the MeshPeer stucture associated with the peer, create one
2107 * and insert it in the appropriate structures if the peer is not known yet.
2109 * @param peer Full identity of the peer.
2111 * @return Existing or newly created peer info.
2113 static struct MeshPeer *
2114 peer_get (const struct GNUNET_PeerIdentity *peer_id)
2116 struct MeshPeer *peer;
2118 peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer_id->hashPubKey);
2121 peer = GNUNET_new (struct MeshPeer);
2122 if (GNUNET_CONTAINER_multihashmap_size (peers) > max_peers)
2124 peer_delete_oldest ();
2126 GNUNET_CONTAINER_multihashmap_put (peers, &peer_id->hashPubKey, peer,
2127 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
2128 peer->id = GNUNET_PEER_intern (peer_id);
2130 peer->last_contact = GNUNET_TIME_absolute_get();
2137 * Retrieve the MeshPeer stucture associated with the peer, create one
2138 * and insert it in the appropriate structures if the peer is not known yet.
2140 * @param peer Short identity of the peer.
2142 * @return Existing or newly created peer info.
2144 static struct MeshPeer *
2145 peer_get_short (const GNUNET_PEER_Id peer)
2147 return peer_get (GNUNET_PEER_resolve2 (peer));
2152 * Get a cost of a path for a peer considering existing tunnel connections.
2154 * @param peer Peer towards which the path is considered.
2155 * @param path Candidate path.
2157 * @return Cost of the path (path length + number of overlapping nodes)
2160 peer_get_path_cost (const struct MeshPeer *peer,
2161 const struct MeshPeerPath *path)
2163 struct MeshConnection *c;
2164 unsigned int overlap;
2172 GNUNET_assert (NULL != peer->tunnel);
2174 for (i = 0; i < path->length; i++)
2176 for (c = peer->tunnel->connection_head; NULL != c; c = c->next)
2178 for (j = 0; j < c->path->length; j++)
2180 if (path->peers[i] == c->path->peers[j])
2188 return (path->length + overlap) * (path->score * -1);
2193 * Choose the best path towards a peer considering the tunnel properties.
2195 * @param peer The destination peer.
2197 * @return Best current known path towards the peer, if any.
2199 static struct MeshPeerPath *
2200 peer_get_best_path (const struct MeshPeer *peer)
2202 struct MeshPeerPath *best_p;
2203 struct MeshPeerPath *p;
2204 struct MeshConnection *c;
2205 unsigned int best_cost;
2208 best_cost = UINT_MAX;
2210 for (p = peer->path_head; NULL != p; p = p->next)
2212 for (c = peer->tunnel->connection_head; NULL != c; c = c->next)
2216 continue; /* If path is in use in a connection, skip it. */
2218 if ((cost = peer_get_path_cost (peer, p)) < best_cost)
2228 queue_is_sendable (struct MeshPeerQueue *q)
2230 struct MeshFlowControl *fc;
2232 /* Is PID-independent? */
2235 case GNUNET_MESSAGE_TYPE_MESH_ACK:
2236 case GNUNET_MESSAGE_TYPE_MESH_POLL:
2240 /* Is PID allowed? */
2241 fc = q->fwd ? &q->c->fwd_fc : &q->c->bck_fc;
2242 if (GMC_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
2250 * Get first sendable message.
2252 * @param peer The destination peer.
2254 * @return Best current known path towards the peer, if any.
2256 static struct MeshPeerQueue *
2257 peer_get_first_message (const struct MeshPeer *peer)
2259 struct MeshPeerQueue *q;
2261 for (q = peer->queue_head; NULL != q; q = q->next)
2263 if (queue_is_sendable (q))
2272 * Try to establish a new connection to this peer in the given tunnel.
2273 * If the peer doesn't have any path to it yet, try to get one.
2274 * If the peer already has some path, send a CREATE CONNECTION towards it.
2276 * @param peer PeerInfo of the peer.
2279 peer_connect (struct MeshPeer *peer)
2281 struct MeshTunnel2 *t;
2282 struct MeshPeerPath *p;
2283 struct MeshConnection *c;
2285 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2286 "peer_connect towards %s\n",
2289 if (NULL != peer->path_head)
2291 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "path exists\n");
2292 p = peer_get_best_path (peer);
2295 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " %u hops\n", p->length);
2296 c = tunnel_use_path (t, p);
2297 send_connection_create (c);
2300 else if (NULL == peer->dhtget)
2302 const struct GNUNET_PeerIdentity *id;
2304 id = GNUNET_PEER_resolve2 (peer->id);
2305 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2306 " Starting DHT GET for peer %s\n", peer2s (peer));
2307 peer->dhtget = GNUNET_DHT_get_start (dht_handle, /* handle */
2308 GNUNET_BLOCK_TYPE_MESH_PEER, /* type */
2309 &id->hashPubKey, /* key to search */
2310 dht_replication_level, /* replication level */
2311 GNUNET_DHT_RO_RECORD_ROUTE |
2312 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
2314 0, /* xquery bits */
2315 &dht_get_id_handler, peer);
2316 if (MESH_TUNNEL_NEW == t->state)
2317 tunnel_change_state (t, MESH_TUNNEL_SEARCHING);
2321 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2322 "There is no path but the DHT GET is already started.\n");
2328 * Get the first transmittable message for a connection.
2330 * @param c Connection.
2331 * @param fwd Is this FWD?
2333 * @return First transmittable message.
2335 static struct MeshPeerQueue *
2336 connection_get_first_message (struct MeshConnection *c, int fwd)
2338 struct MeshPeerQueue *q;
2341 p = connection_get_hop (c, fwd);
2343 for (q = p->queue_head; NULL != q; q = q->next)
2347 if (queue_is_sendable (q))
2356 * Is this peer the first one on the connection?
2358 * @param c Connection.
2359 * @param fwd Is this about fwd traffic?
2361 * @return GNUNET_YES if origin, GNUNET_NO if relay/terminal.
2364 connection_is_origin (struct MeshConnection *c, int fwd)
2366 if (!fwd && c->own_pos == c->path->length - 1)
2368 if (fwd && c->own_pos == 0)
2375 * Is this peer the last one on the connection?
2377 * @param c Connection.
2378 * @param fwd Is this about fwd traffic?
2379 * Note that the ROOT is the terminal for BCK traffic!
2381 * @return GNUNET_YES if terminal, GNUNET_NO if relay/origin.
2384 connection_is_terminal (struct MeshConnection *c, int fwd)
2386 if (fwd && c->own_pos == c->path->length - 1)
2388 if (!fwd && c->own_pos == 0)
2395 * @brief Re-initiate traffic on this connection if necessary.
2397 * Check if there is traffic queued towards this peer
2398 * and the core transmit handle is NULL (traffic was stalled).
2399 * If so, call core tmt rdy.
2401 * @param c Connection on which initiate traffic.
2402 * @param fwd Is this about fwd traffic?
2405 connection_unlock_queue (struct MeshConnection *c, int fwd)
2407 struct MeshPeer *peer;
2408 struct MeshPeerQueue *q;
2411 peer = connection_get_hop (c, fwd);
2413 if (NULL != peer->core_transmit)
2414 return; /* Already unlocked */
2416 q = connection_get_first_message (c, fwd);
2418 return; /* Nothing to transmit */
2421 peer->core_transmit =
2422 GNUNET_CORE_notify_transmit_ready (core_handle,
2425 GNUNET_TIME_UNIT_FOREVER_REL,
2426 GNUNET_PEER_resolve2 (peer->id),
2434 * Cancel all transmissions that belong to a certain connection.
2436 * @param c Connection which to cancel.
2437 * @param fwd Cancel fwd traffic?
2440 connection_cancel_queues (struct MeshConnection *c, int fwd)
2442 struct MeshPeerQueue *q;
2443 struct MeshPeerQueue *next;
2444 struct MeshFlowControl *fc;
2445 struct MeshPeer *peer;
2452 fc = fwd ? &c->fwd_fc : &c->bck_fc;
2453 peer = connection_get_hop (c, fwd);
2455 for (q = peer->queue_head; NULL != q; q = next)
2460 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2461 "connection_cancel_queue %s\n",
2462 GNUNET_MESH_DEBUG_M2S (q->type));
2463 queue_destroy (q, GNUNET_YES);
2466 if (NULL == peer->queue_head)
2468 if (NULL != peer->core_transmit)
2470 GNUNET_CORE_notify_transmit_ready_cancel (peer->core_transmit);
2471 peer->core_transmit = NULL;
2473 if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
2475 GNUNET_SCHEDULER_cancel (fc->poll_task);
2476 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2483 * Remove all paths that rely on a direct connection between p1 and p2
2484 * from the peer itself and notify all tunnels about it.
2486 * @param peer PeerInfo of affected peer.
2487 * @param p1 GNUNET_PEER_Id of one peer.
2488 * @param p2 GNUNET_PEER_Id of another peer that was connected to the first and
2491 * TODO: optimize (see below)
2494 peer_remove_path (struct MeshPeer *peer, GNUNET_PEER_Id p1,
2497 struct MeshPeerPath *p;
2498 struct MeshPeerPath *next;
2499 struct MeshPeer *peer_d;
2501 unsigned int destroyed;
2504 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path\n");
2506 for (p = peer->path_head; NULL != p; p = next)
2509 for (i = 0; i < (p->length - 1); i++)
2511 if ((p->peers[i] == p1 && p->peers[i + 1] == p2) ||
2512 (p->peers[i] == p2 && p->peers[i + 1] == p1))
2514 GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
2525 d = tunnel_notify_connection_broken (peer->tunnel, p1, p2);
2527 peer_d = peer_get_short (d); // FIXME
2528 next = peer_get_best_path (peer_d);
2529 tunnel_use_path (peer->tunnel, next);
2530 peer_connect (peer_d);
2532 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path END\n");
2537 * Add the path to the peer and update the path used to reach it in case this
2540 * @param peer_info Destination peer to add the path to.
2541 * @param path New path to add. Last peer must be the peer in arg 1.
2542 * Path will be either used of freed if already known.
2543 * @param trusted Do we trust that this path is real?
2546 peer_add_path (struct MeshPeer *peer_info, struct MeshPeerPath *path,
2549 struct MeshPeerPath *aux;
2553 if ((NULL == peer_info) || (NULL == path))
2556 path_destroy (path);
2559 if (path->peers[path->length - 1] != peer_info->id)
2562 path_destroy (path);
2565 if (2 >= path->length && GNUNET_NO == trusted)
2567 /* Only allow CORE to tell us about direct paths */
2568 path_destroy (path);
2571 for (l = 1; l < path->length; l++)
2573 if (path->peers[l] == myid)
2575 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shortening path by %u\n", l);
2576 for (l2 = 0; l2 < path->length - l; l2++)
2578 path->peers[l2] = path->peers[l + l2];
2583 GNUNET_realloc (path->peers, path->length * sizeof (GNUNET_PEER_Id));
2587 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "adding path [%u] to peer %s\n",
2588 path->length, peer2s (peer_info));
2590 l = path_get_length (path);
2593 path_destroy (path);
2597 GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
2598 for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
2600 l2 = path_get_length (aux);
2603 GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
2604 peer_info->path_tail, aux, path);
2609 if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
2611 path_destroy (path);
2616 GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head, peer_info->path_tail,
2623 * Add the path to the origin peer and update the path used to reach it in case
2624 * this is the shortest.
2625 * The path is given in peer_info -> destination, therefore we turn the path
2626 * upside down first.
2628 * @param peer_info Peer to add the path to, being the origin of the path.
2629 * @param path New path to add after being inversed.
2630 * Path will be either used or freed.
2631 * @param trusted Do we trust that this path is real?
2634 peer_add_path_to_origin (struct MeshPeer *peer_info,
2635 struct MeshPeerPath *path, int trusted)
2638 peer_add_path (peer_info, path, trusted);
2644 * Function called if a connection has been stalled for a while,
2645 * possibly due to a missed ACK. Poll the neighbor about its ACK status.
2647 * @param cls Closure (poll ctx).
2648 * @param tc TaskContext.
2651 connection_poll (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2653 struct MeshFlowControl *fc = cls;
2654 struct GNUNET_MESH_Poll msg;
2655 struct MeshConnection *c;
2657 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2658 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2664 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** Polling!\n");
2665 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** connection %s[%X]\n",
2666 peer2s (c->t->peer), c->id);
2668 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_POLL);
2669 msg.header.size = htons (sizeof (msg));
2670 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** pid (%u)!\n", fc->last_pid_sent);
2671 send_prebuilt_message_connection (&msg.header, c, NULL, fc == &c->fwd_fc);
2672 fc->poll_time = GNUNET_TIME_STD_BACKOFF (fc->poll_time);
2673 fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
2674 &connection_poll, fc);
2679 * Build a PeerPath from the paths returned from the DHT, reversing the paths
2680 * to obtain a local peer -> destination path and interning the peer ids.
2682 * @return Newly allocated and created path
2684 static struct MeshPeerPath *
2685 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
2686 unsigned int get_path_length,
2687 const struct GNUNET_PeerIdentity *put_path,
2688 unsigned int put_path_length)
2690 struct MeshPeerPath *p;
2696 GNUNET_PEER_change_rc (myid, 1);
2697 i = get_path_length;
2698 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " GET has %d hops.\n", i);
2699 for (i--; i >= 0; i--)
2701 id = GNUNET_PEER_intern (&get_path[i]);
2702 if (p->length > 0 && id == p->peers[p->length - 1])
2704 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Optimizing 1 hop out.\n");
2705 GNUNET_PEER_change_rc (id, -1);
2709 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Adding from GET: %s.\n",
2710 GNUNET_i2s (&get_path[i]));
2712 p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2713 p->peers[p->length - 1] = id;
2716 i = put_path_length;
2717 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " PUT has %d hops.\n", i);
2718 for (i--; i >= 0; i--)
2720 id = GNUNET_PEER_intern (&put_path[i]);
2723 /* PUT path went through us, so discard the path up until now and start
2724 * from here to get a much shorter (and loop-free) path.
2729 if (p->length > 0 && id == p->peers[p->length - 1])
2731 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Optimizing 1 hop out.\n");
2732 GNUNET_PEER_change_rc (id, -1);
2736 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Adding from PUT: %s.\n",
2737 GNUNET_i2s (&put_path[i]));
2739 p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2740 p->peers[p->length - 1] = id;
2744 if (get_path_length > 0)
2745 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " (first of GET: %s)\n",
2746 GNUNET_i2s (&get_path[0]));
2747 if (put_path_length > 0)
2748 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " (first of PUT: %s)\n",
2749 GNUNET_i2s (&put_path[0]));
2750 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " In total: %d hops\n",
2752 for (i = 0; i < p->length; i++)
2754 struct GNUNET_PeerIdentity peer_id;
2756 GNUNET_PEER_resolve (p->peers[i], &peer_id);
2757 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " %u: %s\n", p->peers[i],
2758 GNUNET_i2s (&peer_id));
2766 * Adds a path to the peer_infos of all the peers in the path
2768 * @param p Path to process.
2769 * @param confirmed Whether we know if the path works or not.
2772 path_add_to_peers (struct MeshPeerPath *p, int confirmed)
2776 /* TODO: invert and add */
2777 for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
2778 for (i++; i < p->length; i++)
2780 struct MeshPeer *aux;
2781 struct MeshPeerPath *copy;
2783 aux = peer_get_short (p->peers[i]);
2784 copy = path_duplicate (p);
2785 copy->length = i + 1;
2786 peer_add_path (aux, copy, p->length < 3 ? GNUNET_NO : confirmed);
2792 * Search for a channel among the channels for a client
2794 * @param c the client whose channels to search in
2795 * @param chid the local id of the channel
2797 * @return channel handler, NULL if doesn't exist
2799 static struct MeshChannel *
2800 channel_get_by_local_id (struct MeshClient *c, MESH_ChannelNumber chid)
2802 if (0 == (chid & GNUNET_MESH_LOCAL_CHANNEL_ID_CLI))
2804 GNUNET_break_op (0);
2805 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CHID %X not a local chid\n", chid);
2808 if (chid >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV)
2809 return GNUNET_CONTAINER_multihashmap32_get (c->incoming_channels, chid);
2810 return GNUNET_CONTAINER_multihashmap32_get (c->own_channels, chid);
2814 * Search for a tunnel by global ID using full PeerIdentities.
2816 * @param t Tunnel containing the channel.
2817 * @param chid Public channel number.
2819 * @return channel handler, NULL if doesn't exist
2821 static struct MeshChannel *
2822 channel_get (struct MeshTunnel2 *t, MESH_ChannelNumber chid)
2824 struct MeshChannel *ch;
2829 for (ch = t->channel_head; NULL != ch; ch = ch->next)
2831 if (ch->gid == chid)
2840 * Change the tunnel state.
2842 * @param t Tunnel whose state to change.
2843 * @param state New state.
2846 tunnel_change_state (struct MeshTunnel2* t, enum MeshTunnelState state)
2848 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2849 "Tunnel %s state was %s\n",
2851 GNUNET_MESH_DEBUG_TS2S (t->state));
2852 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2853 "Tunnel %s state is now %s\n",
2855 GNUNET_MESH_DEBUG_TS2S (state));
2861 * Cache a message to be sent once tunnel is online.
2863 * @param t Tunnel to hold the message.
2864 * @param ch Channel the message is about.
2865 * @param msg Message itself (copy will be made).
2866 * @param fwd Is this fwd?
2869 tunnel_queue_data (struct MeshTunnel2 *t,
2870 struct MeshChannel *ch,
2871 struct GNUNET_MessageHeader *msg,
2874 struct MeshTunnelQueue *tq;
2875 uint16_t size = ntohs (msg->size);
2877 tq = GNUNET_malloc (sizeof (struct MeshTunnelQueue) + size);
2880 memcpy (&tq[1], msg, size);
2881 GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tq);
2886 * Send all cached messages that we can, tunnel is online.
2888 * @param t Tunnel that holds the messages.
2889 * @param fwd Is this fwd?
2892 tunnel_send_queued_data (struct MeshTunnel2 *t, int fwd)
2894 struct MeshTunnelQueue *tq;
2895 struct MeshTunnelQueue *next;
2898 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2899 "tunnel_send_queued_data on %s\n",
2900 GNUNET_h2s (&t->id));
2901 room = tunnel_get_buffer (t, fwd);
2902 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " buffer space: %u\n", room);
2903 for (tq = t->tq_head; NULL != tq && room > 0; tq = next)
2907 GNUNET_CONTAINER_DLL_remove (t->tq_head, t->tq_tail, tq);
2908 send_prebuilt_message_channel ((struct GNUNET_MessageHeader *) &tq[1],
2917 connection_change_state (struct MeshConnection* c,
2918 enum MeshConnectionState state)
2920 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2921 "Connection %s[%X] state was %s\n",
2922 peer2s (c->t->peer), c->id,
2923 GNUNET_MESH_DEBUG_CS2S (c->state));
2924 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2925 "Connection %s[%X] state is now %s\n",
2926 peer2s (c->t->peer), c->id,
2927 GNUNET_MESH_DEBUG_CS2S (state));
2933 * Add a client to a channel, initializing all needed data structures.
2935 * @param ch Channel to which add the client.
2936 * @param c Client which to add to the channel.
2939 channel_add_client (struct MeshChannel *ch, struct MeshClient *c)
2941 struct MeshTunnel2 *t = ch->t;
2943 if (NULL != ch->dest)
2949 /* Assign local id as destination */
2950 while (NULL != channel_get_by_local_id (c, t->next_local_chid))
2951 t->next_local_chid = (t->next_local_chid + 1) | GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
2952 ch->lid_dest = t->next_local_chid++;
2953 t->next_local_chid = t->next_local_chid | GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
2955 /* Store in client's hashmap */
2957 GNUNET_CONTAINER_multihashmap32_put (c->incoming_channels,
2959 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2968 static struct MeshConnection *
2969 tunnel_use_path (struct MeshTunnel2 *t, struct MeshPeerPath *p)
2971 struct MeshConnection *c;
2972 struct MeshPeer *peer;
2973 unsigned int own_pos;
2975 c = connection_new (&t->id, t->next_cid++);
2976 for (own_pos = 0; own_pos < p->length; own_pos++)
2978 if (p->peers[own_pos] == myid)
2981 if (own_pos > p->length - 1)
2984 connection_destroy (c);
2987 c->own_pos = own_pos;
2992 c->fwd_maintenance_task =
2993 GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
2994 &connection_fwd_keepalive, c);
2997 peer = connection_get_next_hop (c);
2998 GNUNET_CONTAINER_multihashmap_put (peer->connections, &c->t->id, c,
2999 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3000 peer = connection_get_prev_hop (c);
3001 GNUNET_CONTAINER_multihashmap_put (peer->connections, &c->t->id, c,
3002 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3008 * Notifies a tunnel that a connection has broken that affects at least
3009 * some of its peers. Sends a notification towards the root of the tree.
3010 * In case the peer is the owner of the tree, notifies the client that owns
3011 * the tunnel and tries to reconnect.
3013 * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
3015 * @param t Tunnel affected.
3016 * @param p1 Peer that got disconnected from p2.
3017 * @param p2 Peer that got disconnected from p1.
3019 * @return Short ID of the peer disconnected (either p1 or p2).
3020 * 0 if the tunnel remained unaffected.
3022 static GNUNET_PEER_Id
3023 tunnel_notify_connection_broken (struct MeshTunnel2* t,
3024 GNUNET_PEER_Id p1, GNUNET_PEER_Id p2)
3026 // if (myid != p1 && myid != p2) FIXME
3031 // if (tree_get_predecessor (t->tree) != 0)
3033 // /* We are the peer still connected, notify owner of the disconnection. */
3034 // struct GNUNET_MESH_PathBroken msg;
3035 // struct GNUNET_PeerIdentity neighbor;
3037 // msg.header.size = htons (sizeof (msg));
3038 // msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN);
3039 // GNUNET_PEER_resolve (t->id.oid, &msg.oid);
3040 // msg.tid = htonl (t->id.tid);
3041 // msg.peer1 = my_full_id;
3042 // GNUNET_PEER_resolve (pid, &msg.peer2);
3043 // GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &neighbor);
3044 // send_prebuilt_message (&msg.header, &neighbor, t);
3051 * Send an end-to-end FWD ACK message for the most recent in-sequence payload.
3053 * @param ch Channel this is about.
3054 * @param fwd Is for FWD traffic? (ACK dest->owner)
3057 channel_send_data_ack (struct MeshChannel *ch, int fwd)
3059 struct GNUNET_MESH_DataACK msg;
3060 struct MeshChannelReliability *rel;
3061 struct MeshReliableMessage *copy;
3066 if (GNUNET_NO == ch->reliable)
3071 rel = fwd ? ch->bck_rel : ch->fwd_rel;
3072 mid = fwd ? &ch->mid_recv_fwd : &ch->mid_recv_bck;
3073 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3074 "send_data_ack for %u\n",
3077 msg.header.type = htons (fwd ? GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK :
3078 GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK);
3079 msg.header.size = htons (sizeof (msg));
3080 msg.chid = htonl (ch->gid);
3081 msg.mid = htonl (*mid - 1);
3083 for (copy = rel->head_recv; NULL != copy; copy = copy->next)
3085 delta = copy->mid - *mid;
3088 mask = 0x1LL << delta;
3089 msg.futures |= mask;
3090 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3091 " setting bit for %u (delta %u) (%llX) -> %llX\n",
3092 copy->mid, delta, mask, msg.futures);
3094 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " final futures %llX\n", msg.futures);
3096 send_prebuilt_message_channel (&msg.header, ch, fwd);
3097 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_data_ack END\n");
3102 * Send an ACK informing the predecessor about the available buffer space.
3104 * Note that for fwd ack, the FWD mean forward *traffic* (root->dest),
3105 * the ACK itself goes "back" (dest->root).
3107 * @param c Connection on which to send the ACK.
3108 * @param fwd Is this FWD ACK? (Going dest->owner)
3111 connection_send_ack (struct MeshConnection *c, int fwd)
3113 struct MeshFlowControl *next_fc;
3114 struct MeshFlowControl *prev_fc;
3118 next_fc = fwd ? &c->fwd_fc : &c->bck_fc;
3119 prev_fc = fwd ? &c->bck_fc : &c->fwd_fc;
3121 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3122 "connection send %s ack on %s[%X]\n",
3123 fwd ? "FWD" : "BCK", GNUNET_h2s (&c->t->id), c->id);
3125 /* Check if we need to transmit the ACK */
3126 if (prev_fc->last_ack_sent - prev_fc->last_pid_recv > 3)
3128 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer > 3\n");
3129 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3130 " last pid recv: %u, last ack sent: %u\n",
3131 prev_fc->last_pid_recv, prev_fc->last_ack_sent);
3135 /* Ok, ACK might be necessary, what PID to ACK? */
3136 delta = next_fc->queue_max - next_fc->queue_n;
3137 ack = prev_fc->last_pid_recv + delta;
3138 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", ack);
3139 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3140 " last pid %u, last ack %u, qmax %u, q %u\n",
3141 prev_fc->last_pid_recv, prev_fc->last_ack_sent,
3142 next_fc->queue_max, next_fc->queue_n);
3143 if (ack == prev_fc->last_ack_sent)
3145 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not needed\n");
3149 prev_fc->last_ack_sent = ack;
3150 send_ack (c, ack, fwd);
3155 * Modify the mesh message TID from global to local and send to client.
3157 * @param ch Channel on which to send the message.
3158 * @param msg Message to modify and send.
3159 * @param c Client to send to.
3160 * @param tid Tunnel ID to use (c can be both owner and client).
3163 channel_send_client_to_tid (struct MeshChannel *ch,
3164 const struct GNUNET_MESH_Data *msg,
3165 struct MeshClient *c, MESH_ChannelNumber id)
3167 struct GNUNET_MESH_LocalData *copy;
3168 uint16_t size = ntohs (msg->header.size) - sizeof (struct GNUNET_MESH_Data);
3169 char cbuf[size + sizeof (struct GNUNET_MESH_LocalData)];
3171 if (size < sizeof (struct GNUNET_MessageHeader))
3173 GNUNET_break_op (0);
3181 copy = (struct GNUNET_MESH_LocalData *) cbuf;
3182 memcpy (©[1], &msg[1], size);
3183 copy->header.size = htons (sizeof (struct GNUNET_MESH_LocalData) + size);
3184 copy->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA);
3185 copy->id = htonl (id);
3186 GNUNET_SERVER_notification_context_unicast (nc, c->handle,
3187 ©->header, GNUNET_NO);
3191 * Modify the data message ID from global to local and send to client.
3193 * @param ch Channel on which to send the message.
3194 * @param msg Message to modify and send.
3195 * @param fwd Forward?
3198 channel_send_client_data (struct MeshChannel *ch,
3199 const struct GNUNET_MESH_Data *msg,
3203 channel_send_client_to_tid (ch, msg, ch->dest, ch->lid_dest);
3205 channel_send_client_to_tid (ch, msg, ch->root, ch->lid_root);
3210 * Send a buffered message to the client, for in order delivery or
3211 * as result of client ACK.
3213 * @param ch Channel on which to empty the message buffer.
3214 * @param c Client to send to.
3215 * @param rel Reliability structure to corresponding peer.
3216 * If rel == bck_rel, this is FWD data.
3219 channel_send_client_buffered_data (struct MeshChannel *ch,
3220 struct MeshClient *c,
3221 struct MeshChannelReliability *rel)
3223 struct MeshReliableMessage *copy;
3226 if (GNUNET_NO == rel->client_ready)
3228 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client not ready\n");
3232 mid = rel == ch->bck_rel ? &ch->mid_recv_fwd : &ch->mid_recv_bck;
3234 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data\n");
3235 copy = rel->head_recv;
3238 if (copy->mid == *mid || GNUNET_NO == ch->reliable)
3240 struct GNUNET_MESH_Data *msg = (struct GNUNET_MESH_Data *) ©[1];
3242 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3243 " have %u! now expecting %u\n",
3244 copy->mid, *mid + 1);
3245 channel_send_client_data (ch, msg, (rel == ch->bck_rel));
3248 GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
3253 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3254 " reliable && don't have %u, next is %u\n",
3260 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data END\n");
3265 * We have received a message out of order, or the client is not ready.
3266 * Buffer it until we receive an ACK from the client or the missing
3267 * message from the channel.
3269 * @param msg Message to buffer.
3270 * @param rel Reliability data to the corresponding direction.
3273 channel_rel_add_buffered_data (const struct GNUNET_MESH_Data *msg,
3274 struct MeshChannelReliability *rel)
3276 struct MeshReliableMessage *copy;
3277 struct MeshReliableMessage *prev;
3281 size = ntohs (msg->header.size);
3282 mid = ntohl (msg->mid);
3283 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data %u\n", mid);
3285 copy = GNUNET_malloc (sizeof (*copy) + size);
3288 memcpy (©[1], msg, size);
3292 // FIXME do something better than O(n), although n < 64...
3293 // FIXME start from the end (most messages are the latest ones)
3294 for (prev = rel->head_recv; NULL != prev; prev = prev->next)
3296 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " prev %u\n", prev->mid);
3297 if (GMC_is_pid_bigger (prev->mid, mid))
3299 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " bingo!\n");
3300 GNUNET_CONTAINER_DLL_insert_before (rel->head_recv, rel->tail_recv,
3305 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " insert at tail!\n");
3306 GNUNET_CONTAINER_DLL_insert_tail (rel->head_recv, rel->tail_recv, copy);
3307 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data END\n");
3312 * Destroy a reliable message after it has been acknowledged, either by
3313 * direct mid ACK or bitfield. Updates the appropriate data structures and
3314 * timers and frees all memory.
3316 * @param copy Message that is no longer needed: remote peer got it.
3319 rel_message_free (struct MeshReliableMessage *copy)
3321 struct MeshChannelReliability *rel;
3322 struct GNUNET_TIME_Relative time;
3325 time = GNUNET_TIME_absolute_get_duration (copy->timestamp);
3326 rel->expected_delay.rel_value_us *= 7;
3327 rel->expected_delay.rel_value_us += time.rel_value_us;
3328 rel->expected_delay.rel_value_us /= 8;
3330 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Freeing %u\n", copy->mid);
3331 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " n_sent %u\n", rel->n_sent);
3332 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! took %s\n",
3333 GNUNET_STRINGS_relative_time_to_string (time, GNUNET_NO));
3334 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! new expected delay %s\n",
3335 GNUNET_STRINGS_relative_time_to_string (rel->expected_delay,
3337 rel->retry_timer = rel->expected_delay;
3338 GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
3344 * Destroy all reliable messages queued for a channel,
3345 * during a channel destruction.
3346 * Frees the reliability structure itself.
3348 * @param rel Reliability data for a channel.
3351 channel_rel_free_all (struct MeshChannelReliability *rel)
3353 struct MeshReliableMessage *copy;
3354 struct MeshReliableMessage *next;
3359 for (copy = rel->head_recv; NULL != copy; copy = next)
3362 GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
3365 for (copy = rel->head_sent; NULL != copy; copy = next)
3368 GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
3371 if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
3372 GNUNET_SCHEDULER_cancel (rel->retry_task);
3378 * Mark future messages as ACK'd.
3380 * @param rel Reliability data.
3381 * @param msg DataACK message with a bitfield of future ACK'd messages.
3384 channel_rel_free_sent (struct MeshChannelReliability *rel,
3385 const struct GNUNET_MESH_DataACK *msg)
3387 struct MeshReliableMessage *copy;
3388 struct MeshReliableMessage *next;
3395 bitfield = msg->futures;
3396 mid = ntohl (msg->mid);
3397 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3398 "free_sent_reliable %u %llX\n",
3400 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3401 " rel %p, head %p\n",
3402 rel, rel->head_sent);
3403 for (i = 0, copy = rel->head_sent;
3404 i < 64 && NULL != copy && 0 != bitfield;
3407 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3408 " trying bit %u (mid %u)\n",
3411 if (0 == (bitfield & mask))
3414 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " set!\n");
3415 /* Bit was set, clear the bit from the bitfield */
3418 /* The i-th bit was set. Do we have that copy? */
3419 /* Skip copies with mid < target */
3420 target = mid + i + 1;
3421 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " target %u\n", target);
3422 while (NULL != copy && GMC_is_pid_bigger (target, copy->mid))
3425 /* Did we run out of copies? (previously freed, it's ok) */
3428 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "run out of copies...\n");
3432 /* Did we overshoot the target? (previously freed, it's ok) */
3433 if (GMC_is_pid_bigger (copy->mid, target))
3435 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " next copy %u\n", copy->mid);
3439 /* Now copy->mid == target, free it */
3441 rel_message_free (copy);
3444 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "free_sent_reliable END\n");
3449 * We haven't received an ACK after a certain time: restransmit the message.
3451 * @param cls Closure (MeshReliableMessage with the message to restransmit)
3452 * @param tc TaskContext.
3455 channel_retransmit_message (void *cls,
3456 const struct GNUNET_SCHEDULER_TaskContext *tc)
3458 struct MeshChannelReliability *rel = cls;
3459 struct MeshReliableMessage *copy;
3460 struct MeshPeerQueue *q;
3461 struct MeshChannel *ch;
3462 struct MeshConnection *c;
3463 struct GNUNET_MESH_Data *payload;
3464 struct MeshPeer *hop;
3467 rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
3468 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3472 copy = rel->head_sent;
3479 /* Search the message to be retransmitted in the outgoing queue.
3480 * Check only the queue for the connection that is going to be used,
3481 * if the message is stuck in some other connection's queue we shouldn't
3483 * - cancelling it and sending the new one doesn't guarantee it's delivery,
3484 * the old connection could be temporary stalled or the queue happened to
3485 * be long at time of insertion.
3486 * - not sending the new one could cause terrible delays the old connection
3489 payload = (struct GNUNET_MESH_Data *) ©[1];
3490 fwd = (rel == ch->fwd_rel);
3491 c = tunnel_get_connection (ch->t, fwd);
3492 hop = connection_get_hop (c, fwd);
3493 for (q = hop->queue_head; NULL != q; q = q->next)
3495 if (ntohs (payload->header.type) == q->type && ch == q->ch)
3497 struct GNUNET_MESH_Data *queued_data = q->cls;
3499 if (queued_data->mid == payload->mid)
3504 /* Message not found in the queue that we are going to use. */
3507 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! RETRANSMIT %u\n", copy->mid);
3509 send_prebuilt_message_channel (&payload->header, ch, ch->fwd_rel == rel);
3510 GNUNET_STATISTICS_update (stats, "# data retransmitted", 1, GNUNET_NO);
3514 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! ALREADY IN QUEUE %u\n", copy->mid);
3517 rel->retry_timer = GNUNET_TIME_STD_BACKOFF (rel->retry_timer);
3518 rel->retry_task = GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
3519 &channel_retransmit_message,
3525 * Send an ACK to a client if needed.
3527 * @param ch Channel this is regarding.
3528 * @param fwd Is this about fwd traffic? (ACk goes the opposite direction).
3531 channel_send_client_ack (struct MeshChannel *ch, int fwd)
3533 struct MeshClient *c;
3536 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3537 "Channel send client %s ack on %s:%X\n",
3538 fwd ? "FWD" : "BCK", GNUNET_h2s (&ch->t->id), ch->gid);
3540 /* Check for buffer space */
3541 if (0 >= tunnel_get_buffer (ch->t, fwd))
3544 /* Client to receive the ACK (fwd indicates traffic to be ACK'd) */
3545 c = fwd ? ch->root : ch->dest;
3547 blocked = fwd ? ch->blocked_fwd : ch->blocked_bck;
3548 if (GNUNET_YES == blocked)
3549 send_local_ack (ch, c, fwd);
3551 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Client not blocked\n");
3556 * Send ACK on one or more connections due to buffer space to the client.
3558 * @param ch Channel which has some free buffer space.
3559 * @param buffer Buffer space.
3560 * @param fwd Is this in the FWD direction?
3563 channel_send_connection_ack (struct MeshChannel *ch, uint32_t buffer, int fwd)
3565 struct MeshTunnel2 *t = ch->t;
3566 struct MeshConnection *c;
3567 struct MeshFlowControl *fc;
3572 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3573 "Channel send connection %s ack on %s:%X\n",
3574 fwd ? "FWD" : "BCK", GNUNET_h2s (&ch->t->id), ch->gid);
3576 /* Count connections, how many messages are already allowed */
3577 for (cs = 0, allowed = 0, c = t->connection_head; NULL != c; c = c->next)
3579 fc = fwd ? &c->fwd_fc : &c->bck_fc;
3580 if (GMC_is_pid_bigger(fc->last_pid_recv, fc->last_ack_sent))
3585 allowed += fc->last_ack_sent - fc->last_pid_recv;
3589 /* Make sure there is no overflow */
3590 if (allowed > buffer)
3596 /* Authorize connections to send more data */
3597 to_allow = buffer - allowed;
3598 for (c = t->connection_head; NULL != c && to_allow > 0; c = c->next)
3600 fc = fwd ? &c->fwd_fc : &c->bck_fc;
3601 if (fc->last_ack_sent - fc->last_pid_recv > 64 / 3)
3605 send_ack (c, fc->last_ack_sent + 1, fwd);
3609 GNUNET_break (to_allow == 0);
3614 * Send keepalive packets for a connection.
3616 * @param c Connection to keep alive..
3617 * @param fwd Is this a FWD keepalive? (owner -> dest).
3620 connection_keepalive (struct MeshConnection *c, int fwd)
3622 struct GNUNET_MESH_ConnectionKeepAlive *msg;
3623 size_t size = sizeof (struct GNUNET_MESH_ConnectionKeepAlive);
3627 type = fwd ? GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE :
3628 GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE;
3630 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3631 "sending %s keepalive for connection %s[%d]\n",
3632 fwd ? "FWD" : "BCK",
3633 peer2s (c->t->peer),
3636 msg = (struct GNUNET_MESH_ConnectionKeepAlive *) cbuf;
3637 msg->header.size = htons (size);
3638 msg->header.type = htons (type);
3639 msg->cid = htonl (c->id);
3640 msg->tid = c->t->id;
3642 send_prebuilt_message_connection (&msg->header, c, NULL, fwd);
3647 * Send CONNECTION_{CREATE/ACK} packets for a connection.
3649 * @param c Connection for which to send the message.
3650 * @param fwd If GNUNET_YES, send CREATE, otherwise send ACK.
3653 connection_recreate (struct MeshConnection *c, int fwd)
3655 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "sending connection recreate\n");
3657 send_connection_create (c);
3659 send_connection_ack (c, GNUNET_NO);
3664 * Generic connection timer management.
3665 * Depending on the role of the peer in the connection will send the
3666 * appropriate message (build or keepalive)
3668 * @param c Conncetion to maintain.
3669 * @param fwd Is FWD?
3672 connection_maintain (struct MeshConnection *c, int fwd)
3674 if (MESH_TUNNEL_SEARCHING == c->t->state)
3676 /* TODO DHT GET with RO_BART */
3681 case MESH_CONNECTION_NEW:
3683 case MESH_CONNECTION_SENT:
3684 connection_recreate (c, fwd);
3686 case MESH_CONNECTION_READY:
3687 connection_keepalive (c, fwd);
3696 connection_fwd_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3698 struct MeshConnection *c = cls;
3700 c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
3701 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3704 connection_maintain (c, GNUNET_YES);
3705 c->fwd_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
3706 &connection_fwd_keepalive,
3712 connection_bck_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3714 struct MeshConnection *c = cls;
3716 c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
3717 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3720 connection_maintain (c, GNUNET_NO);
3721 c->bck_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
3722 &connection_bck_keepalive,
3728 * Send a message to all peers in this connection that the connection
3729 * is no longer valid.
3731 * If some peer should not receive the message, it should be zero'ed out
3732 * before calling this function.
3734 * @param c The connection whose peers to notify.
3737 connection_send_destroy (struct MeshConnection *c)
3739 struct GNUNET_MESH_ConnectionDestroy msg;
3741 msg.header.size = htons (sizeof (msg));
3742 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);;
3743 msg.cid = htonl (c->id);
3745 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3746 " sending connection destroy for connection %s[%X]\n",
3747 peer2s (c->t->peer),
3750 send_prebuilt_message_connection (&msg.header, c, NULL, GNUNET_YES);
3751 send_prebuilt_message_connection (&msg.header, c, NULL, GNUNET_NO);
3752 c->destroy = GNUNET_YES;
3757 * Send a message to all clients (local and remote) of this channel
3758 * notifying that the channel is no longer valid.
3760 * If some peer or client should not receive the message,
3761 * should be zero'ed out before calling this function.
3763 * @param ch The channel whose clients to notify.
3766 channel_send_destroy (struct MeshChannel *ch)
3768 struct GNUNET_MESH_ChannelDestroy msg;
3770 msg.header.size = htons (sizeof (msg));
3771 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY);
3772 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3773 " sending channel destroy for channel %s:%X\n",
3774 peer2s (ch->t->peer),
3777 if (NULL != ch->root)
3779 msg.chid = htonl (ch->lid_root);
3780 send_local_channel_destroy (ch, GNUNET_NO);
3784 msg.chid = htonl (ch->gid);
3785 send_prebuilt_message_channel (&msg.header, ch, GNUNET_NO);
3788 if (NULL != ch->dest)
3790 msg.chid = htonl (ch->lid_dest);
3791 send_local_channel_destroy (ch, GNUNET_YES);
3795 msg.chid = htonl (ch->gid);
3796 send_prebuilt_message_channel (&msg.header, ch, GNUNET_YES);
3804 * @param tid Tunnel ID.
3806 static struct MeshTunnel2 *
3807 tunnel_new (const struct GNUNET_HashCode *tid)
3809 struct MeshTunnel2 *t;
3811 t = GNUNET_new (struct MeshTunnel2);
3814 t->next_local_chid = GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
3816 GNUNET_CONTAINER_multihashmap_put (tunnels, tid, t,
3817 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3824 // char salt[] = "salt";
3825 // GNUNET_CRYPTO_kdf (&t->e_key, sizeof (struct GNUNET_CRYPTO_AesSessionKey),
3826 // salt, sizeof (salt),
3827 // &t->e_key, sizeof (struct GNUNET_CRYPTO_AesSessionKey),
3828 // &my_full_id, sizeof (struct GNUNET_PeerIdentity),
3829 // GNUNET_PEER_resolve2 (t->peer->id), sizeof (struct GNUNET_PeerIdentity),
3831 // GNUNET_CRYPTO_kdf (&t->d_key, sizeof (struct GNUNET_CRYPTO_AesSessionKey),
3832 // salt, sizeof (salt),
3833 // &t->d_key, sizeof (struct GNUNET_CRYPTO_AesSessionKey),
3834 // GNUNET_PEER_resolve2 (t->peer->id), sizeof (struct GNUNET_PeerIdentity),
3835 // &my_full_id, sizeof (struct GNUNET_PeerIdentity),
3845 * @param tid Tunnel ID.
3847 static struct MeshTunnel2 *
3848 tunnel_get (const struct GNUNET_HashCode *tid)
3850 return GNUNET_CONTAINER_multihashmap_get (tunnels, tid);
3855 * Add a connection to a tunnel.
3858 * @param c Connection.
3861 tunnel_add_connection (struct MeshTunnel2 *t, struct MeshConnection *c)
3864 GNUNET_CONTAINER_DLL_insert_tail (t->connection_head, t->connection_tail, c);
3869 * Initialize a Flow Control structure to the initial state.
3871 * @param fc Flow Control structure to initialize.
3874 fc_init (struct MeshFlowControl *fc)
3877 fc->last_pid_sent = (uint32_t) -1; /* Next (expected) = 0 */
3878 fc->last_pid_recv = (uint32_t) -1;
3879 fc->last_ack_sent = (uint32_t) 0;
3880 fc->last_ack_recv = (uint32_t) 0;
3881 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
3882 fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
3884 fc->queue_max = (max_msgs_queue / max_connections) + 1;
3888 static struct MeshConnection *
3889 connection_new (struct GNUNET_HashCode *tid, uint32_t cid)
3891 struct MeshConnection *c;
3892 struct MeshTunnel2 *t;
3894 t = tunnel_get (tid);
3897 t = tunnel_new (tid);
3905 c = GNUNET_new (struct MeshConnection);
3907 fc_init (&c->fwd_fc);
3908 fc_init (&c->bck_fc);
3911 tunnel_add_connection (t, c);
3918 * Find a connection.
3920 * @param tid Tunnel ID.
3921 * @param cid Connection ID.
3923 static struct MeshConnection *
3924 connection_get (const struct GNUNET_HashCode *tid, uint32_t cid)
3926 struct MeshConnection *c;
3927 struct MeshTunnel2 *t;
3929 t = tunnel_get (tid);
3932 for (c = t->connection_head; NULL != c; c = c->next)
3941 connection_destroy (struct MeshConnection *c)
3943 struct MeshPeer *peer;
3948 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying connection %s[%X]\n",
3949 peer2s (c->t->peer),
3952 /* Cancel all traffic */
3953 connection_cancel_queues (c, GNUNET_YES);
3954 connection_cancel_queues (c, GNUNET_NO);
3956 /* Cancel maintainance task (keepalive/timeout) */
3957 if (GNUNET_SCHEDULER_NO_TASK != c->fwd_maintenance_task)
3958 GNUNET_SCHEDULER_cancel (c->fwd_maintenance_task);
3959 if (GNUNET_SCHEDULER_NO_TASK != c->bck_maintenance_task)
3960 GNUNET_SCHEDULER_cancel (c->bck_maintenance_task);
3962 /* Deregister from neighbors */
3963 peer = connection_get_next_hop (c);
3965 GNUNET_CONTAINER_multihashmap_remove (peer->connections, &c->t->id, c);
3966 peer = connection_get_prev_hop (c);
3968 GNUNET_CONTAINER_multihashmap_remove (peer->connections, &c->t->id, c);
3971 GNUNET_STATISTICS_update (stats, "# connections", -1, GNUNET_NO);
3972 GNUNET_CONTAINER_DLL_remove (c->t->connection_head, c->t->connection_tail, c);
3978 tunnel_destroy (struct MeshTunnel2 *t)
3980 struct MeshConnection *c;
3981 struct MeshConnection *next;
3986 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n",
3989 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &t->id, t))
3992 for (c = t->connection_head; NULL != c; c = next)
3995 connection_destroy (c);
3998 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
4005 * Tunnel is empty: destroy it.
4007 * Notifies all connections about the destruction.
4009 * @param t Tunnel to destroy.
4012 tunnel_destroy_empty (struct MeshTunnel2 *t)
4014 struct MeshConnection *c;
4016 for (c = t->connection_head; NULL != c; c = c->next)
4018 if (GNUNET_NO == c->destroy)
4019 connection_send_destroy (c);
4022 if (0 == t->pending_messages)
4025 t->destroy = GNUNET_YES;
4030 * Destroy tunnel if empty (no more channels).
4032 * @param t Tunnel to destroy if empty.
4035 tunnel_destroy_if_empty (struct MeshTunnel2 *t)
4037 if (NULL != t->channel_head)
4040 tunnel_destroy_empty (t);
4045 * Destroy a channel and free all resources.
4047 * @param ch Channel to destroy.
4050 channel_destroy (struct MeshChannel *ch)
4052 struct MeshClient *c;
4060 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap32_remove (c->own_channels,
4071 GNUNET_CONTAINER_multihashmap32_remove (c->incoming_channels,
4078 channel_rel_free_all (ch->fwd_rel);
4079 channel_rel_free_all (ch->bck_rel);
4081 GNUNET_CONTAINER_DLL_remove (ch->t->channel_head, ch->t->channel_tail, ch);
4082 GNUNET_STATISTICS_update (stats, "# channels", -1, GNUNET_NO);
4088 * Create a new channel.
4090 * @param t Tunnel this channel is in.
4091 * @param owner Client that owns the channel, NULL for foreign channels.
4092 * @param lid_root Local ID for root client.
4094 * @return A new initialized channel. NULL on error.
4096 static struct MeshChannel *
4097 channel_new (struct MeshTunnel2 *t,
4098 struct MeshClient *owner, MESH_ChannelNumber lid_root)
4100 struct MeshChannel *ch;
4102 ch = GNUNET_new (struct MeshChannel);
4104 ch->lid_root = lid_root;
4106 ch->blocked_fwd = GNUNET_YES;
4107 ch->blocked_bck = GNUNET_YES;
4109 GNUNET_CONTAINER_DLL_insert (t->channel_head, t->channel_tail, ch);
4111 GNUNET_STATISTICS_update (stats, "# channels", 1, GNUNET_NO);
4115 while (NULL != channel_get (t, t->next_chid))
4116 t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
4117 ch->gid = t->next_chid;
4118 t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
4121 GNUNET_CONTAINER_multihashmap32_put (owner->own_channels, lid_root, ch,
4122 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
4125 channel_destroy (ch);
4126 GNUNET_SERVER_receive_done (owner->handle, GNUNET_SYSERR);
4136 * Set options in a channel, extracted from a bit flag field
4138 * @param ch Channel to set options to.
4139 * @param options Bit array in host byte order.
4142 channel_set_options (struct MeshChannel *ch, uint32_t options)
4144 ch->nobuffer = (options & GNUNET_MESH_OPTION_NOBUFFER) != 0 ?
4145 GNUNET_YES : GNUNET_NO;
4146 ch->reliable = (options & GNUNET_MESH_OPTION_RELIABLE) != 0 ?
4147 GNUNET_YES : GNUNET_NO;
4152 * Iterator for deleting each channel whose client endpoint disconnected.
4154 * @param cls Closure (client that has disconnected).
4155 * @param key The local channel id (used to access the hashmap).
4156 * @param value The value stored at the key (channel to destroy).
4158 * @return GNUNET_OK, keep iterating.
4161 channel_destroy_iterator (void *cls,
4165 struct MeshChannel *ch = value;
4166 struct MeshClient *c = cls;
4167 struct MeshTunnel2 *t;
4169 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4170 " Channel %X (%X / %X) destroy, due to client %u shutdown.\n",
4171 ch->gid, ch->lid_root, ch->lid_dest, c->id);
4175 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is destination.\n", c->id);
4180 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is owner.\n", c->id);
4185 channel_send_destroy (ch);
4186 channel_destroy (ch);
4187 tunnel_destroy_if_empty (t);
4194 * Remove client's ports from the global hashmap on disconnect.
4196 * @param cls Closure (unused).
4198 * @param value Client structure.
4200 * @return GNUNET_OK, keep iterating.
4203 client_release_ports (void *cls,
4209 res = GNUNET_CONTAINER_multihashmap32_remove (ports, key, value);
4210 if (GNUNET_YES != res)
4213 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4214 "Port %u by client %p was not registered.\n",
4222 * Timeout function due to lack of keepalive/traffic from the owner.
4223 * Destroys connection if called.
4225 * @param cls Closure (connection to destroy).
4226 * @param tc TaskContext.
4229 connection_fwd_timeout (void *cls,
4230 const struct GNUNET_SCHEDULER_TaskContext *tc)
4232 struct MeshConnection *c = cls;
4234 c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4235 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4237 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4238 "Connection %s[%X] FWD timed out. Destroying.\n",
4239 peer2s (c->t->peer),
4242 if (connection_is_origin (c, GNUNET_YES)) /* If local, leave. */
4245 connection_destroy (c);
4250 * Timeout function due to lack of keepalive/traffic from the destination.
4251 * Destroys connection if called.
4253 * @param cls Closure (connection to destroy).
4254 * @param tc TaskContext
4257 connection_bck_timeout (void *cls,
4258 const struct GNUNET_SCHEDULER_TaskContext *tc)
4260 struct MeshConnection *c = cls;
4262 c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4263 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4266 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4267 "Connection %s[%X] FWD timed out. Destroying.\n",
4268 peer2s (c->t->peer),
4271 if (connection_is_origin (c, GNUNET_NO)) /* If local, leave. */
4274 connection_destroy (c);
4279 * Resets the connection timeout task, some other message has done the
4281 * - For the first peer on the direction this means to send
4282 * a keepalive or a path confirmation message (either create or ACK).
4283 * - For all other peers, this means to destroy the connection,
4284 * due to lack of activity.
4285 * Starts the tiemout if no timeout was running (connection just created).
4287 * @param c Connection whose timeout to reset.
4288 * @param fwd Is this forward?
4290 * TODO use heap to improve efficiency of scheduler.
4293 connection_reset_timeout (struct MeshConnection *c, int fwd)
4295 GNUNET_SCHEDULER_TaskIdentifier *ti;
4296 GNUNET_SCHEDULER_Task f;
4298 ti = fwd ? &c->fwd_maintenance_task : &c->bck_maintenance_task;
4300 if (GNUNET_SCHEDULER_NO_TASK != *ti)
4301 GNUNET_SCHEDULER_cancel (*ti);
4303 if (connection_is_origin (c, fwd)) /* Endpoint */
4305 f = fwd ? &connection_fwd_keepalive : &connection_bck_keepalive;
4306 *ti = GNUNET_SCHEDULER_add_delayed (refresh_connection_time, f, c);
4310 struct GNUNET_TIME_Relative delay;
4312 delay = GNUNET_TIME_relative_multiply (refresh_connection_time, 4);
4313 f = fwd ? &connection_fwd_timeout : &connection_bck_timeout;
4314 *ti = GNUNET_SCHEDULER_add_delayed (delay, f, c);
4320 * Iterator to notify all connections of a broken link. Mark connections
4321 * to destroy after all traffic has been sent.
4323 * @param cls Closure (peer disconnected).
4324 * @param key Current key code (tid).
4325 * @param value Value in the hash map (connection).
4327 * @return GNUNET_YES if we should continue to iterate,
4331 connection_broken (void *cls,
4332 const struct GNUNET_HashCode *key,
4335 struct MeshPeer *peer = cls;
4336 struct MeshConnection *c = value;
4337 struct GNUNET_MESH_ConnectionBroken msg;
4340 fwd = peer == connection_get_prev_hop (c);
4341 connection_cancel_queues (c, !fwd);
4343 msg.header.size = htons (sizeof (struct GNUNET_MESH_ConnectionBroken));
4344 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN);
4345 msg.cid = htonl (c->id);
4347 msg.peer1 = my_full_id;
4348 msg.peer2 = *GNUNET_PEER_resolve2 (peer->id);
4349 send_prebuilt_message_connection (&msg.header, c, NULL, fwd);
4350 c->destroy = GNUNET_YES;
4355 /******************************************************************************/
4356 /**************** MESH NETWORK HANDLER HELPERS ***********************/
4357 /******************************************************************************/
4360 * Free a transmission that was already queued with all resources
4361 * associated to the request.
4363 * @param queue Queue handler to cancel.
4364 * @param clear_cls Is it necessary to free associated cls?
4367 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
4369 struct MeshPeer *peer;
4370 struct MeshFlowControl *fc;
4375 GNUNET_assert (NULL != queue->c);
4376 fc = fwd ? &queue->c->fwd_fc : &queue->c->bck_fc;
4378 if (GNUNET_YES == clear_cls)
4380 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " queue destroy type %s\n",
4381 GNUNET_MESH_DEBUG_M2S (queue->type));
4382 switch (queue->type)
4384 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
4385 case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
4386 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "destroying a DESTROY message\n");
4387 GNUNET_break (GNUNET_YES == queue->c->destroy);
4389 case GNUNET_MESSAGE_TYPE_MESH_FWD:
4390 case GNUNET_MESSAGE_TYPE_MESH_BCK:
4391 case GNUNET_MESSAGE_TYPE_MESH_ACK:
4392 case GNUNET_MESSAGE_TYPE_MESH_POLL:
4393 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
4394 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
4395 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " prebuilt message\n");;
4396 GNUNET_free_non_null (queue->cls);
4401 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, " type %s unknown!\n",
4402 GNUNET_MESH_DEBUG_M2S (queue->type));
4406 GNUNET_CONTAINER_DLL_remove (peer->queue_head, peer->queue_tail, queue);
4410 if (NULL != queue->c)
4412 queue->c->pending_messages--;
4413 if (NULL != queue->c->t)
4415 queue->c->t->pending_messages--;
4419 GNUNET_free (queue);
4424 queue_send (void *cls, size_t size, void *buf)
4426 struct MeshPeer *peer = cls;
4427 struct MeshFlowControl *fc;
4428 struct MeshConnection *c;
4429 struct GNUNET_MessageHeader *msg;
4430 struct MeshPeerQueue *queue;
4431 struct MeshTunnel2 *t;
4432 const struct GNUNET_PeerIdentity *dst_id;
4438 peer->core_transmit = NULL;
4439 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Queue send\n");
4441 if (NULL == buf || 0 == size)
4443 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Buffer size 0.\n");
4448 queue = peer_get_first_message (peer);
4451 GNUNET_break (0); /* Core tmt_rdy should've been canceled */
4456 fc = fwd ? &c->fwd_fc : &c->bck_fc;
4459 dst_id = GNUNET_PEER_resolve2 (peer->id);
4460 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* towards %s\n", GNUNET_i2s (dst_id));
4461 /* Check if buffer size is enough for the message */
4462 if (queue->size > size)
4464 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* not enough room, reissue\n");
4465 peer->core_transmit =
4466 GNUNET_CORE_notify_transmit_ready (core_handle,
4469 GNUNET_TIME_UNIT_FOREVER_REL,
4476 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* size ok\n");
4478 t = (NULL != c) ? c->t : NULL;
4482 switch (queue->type)
4484 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
4485 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
4486 case GNUNET_MESSAGE_TYPE_MESH_FWD:
4487 case GNUNET_MESSAGE_TYPE_MESH_BCK:
4488 case GNUNET_MESSAGE_TYPE_MESH_ACK:
4489 case GNUNET_MESSAGE_TYPE_MESH_POLL:
4490 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4492 GNUNET_MESH_DEBUG_M2S (queue->type));
4493 data_size = send_core_data_raw (queue->cls, size, buf);
4494 msg = (struct GNUNET_MessageHeader *) buf;
4495 type = ntohs (msg->type);
4497 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
4498 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* path create\n");
4499 if (connection_is_origin (c, GNUNET_YES))
4500 data_size = send_core_connection_create (queue->c, size, buf);
4502 data_size = send_core_data_raw (queue->cls, size, buf);
4504 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
4505 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* path ack\n");
4506 if (connection_is_origin (c, GNUNET_NO))
4507 data_size = send_core_connection_ack (queue->c, size, buf);
4509 data_size = send_core_data_raw (queue->cls, size, buf);
4511 case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4512 case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4513 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
4514 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
4515 /* This should be encapsulted */
4520 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "* type unknown: %u\n",
4525 if (0 < drop_percent &&
4526 GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 101) < drop_percent)
4528 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4529 "Dropping message of type %s\n",
4530 GNUNET_MESH_DEBUG_M2S (queue->type));
4534 /* Send ACK if needed, after accounting for sent ID in fc->queue_n */
4537 case GNUNET_MESSAGE_TYPE_MESH_FWD:
4538 case GNUNET_MESSAGE_TYPE_MESH_BCK:
4539 pid = ntohl ( ((struct GNUNET_MESH_Encrypted *) buf)->pid );
4540 fc->last_pid_sent = pid;
4541 if (NULL != queue->ch)
4542 channel_send_client_ack (queue->ch, fwd);
4544 connection_send_ack (c, fwd);
4550 /* Free queue, but cls was freed by send_core_* */
4551 queue_destroy (queue, GNUNET_NO);
4553 /* If more data in queue, send next */
4554 queue = peer_get_first_message (peer);
4557 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* more data!\n");
4558 if (NULL == peer->core_transmit) {
4559 peer->core_transmit =
4560 GNUNET_CORE_notify_transmit_ready(core_handle,
4563 GNUNET_TIME_UNIT_FOREVER_REL,
4571 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4572 "* tmt rdy called somewhere else\n");
4574 if (GNUNET_SCHEDULER_NO_TASK == fc->poll_task)
4576 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "* %s starting poll timeout\n");
4578 GNUNET_SCHEDULER_add_delayed (fc->poll_time, &connection_poll, fc);
4583 if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
4585 GNUNET_SCHEDULER_cancel (fc->poll_task);
4586 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
4591 c->pending_messages--;
4592 if (GNUNET_YES == c->destroy && 0 == c->pending_messages)
4594 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* destroying connection!\n");
4595 connection_destroy (c);
4601 t->pending_messages--;
4602 if (GNUNET_YES == t->destroy && 0 == t->pending_messages)
4604 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* destroying tunnel!\n");
4608 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Return %d\n", data_size);
4614 queue_add (void *cls, uint16_t type, size_t size,
4615 struct MeshConnection *c,
4616 struct MeshChannel *ch,
4619 struct MeshPeerQueue *queue;
4620 struct MeshFlowControl *fc;
4621 struct MeshPeer *peer;
4624 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4625 "queue add %s %s (%u) on c %p, ch %p\n",
4626 fwd ? "FWD" : "BCK", GNUNET_MESH_DEBUG_M2S (type), size, c, ch);
4627 GNUNET_assert (NULL != c);
4629 fc = fwd ? &c->fwd_fc : &c->bck_fc;
4630 peer = fwd ? connection_get_next_hop (c) : connection_get_prev_hop (c);
4640 if (GNUNET_MESSAGE_TYPE_MESH_POLL == type ||
4641 GNUNET_MESSAGE_TYPE_MESH_ACK == type)
4645 ( (NULL != ch->root && GNUNET_MESSAGE_TYPE_MESH_FWD == type) ||
4646 (NULL != ch->dest && GNUNET_MESSAGE_TYPE_MESH_BCK == type) ))
4649 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "priority %d\n", priority);
4650 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "fc %p\n", fc);
4651 if (fc->queue_n >= fc->queue_max && 0 == priority)
4653 GNUNET_STATISTICS_update (stats, "# messages dropped (buffer full)",
4656 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4657 "queue full: %u/%u\n",
4658 fc->queue_n, fc->queue_max);
4659 return; /* Drop this message */
4662 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "pid %u\n", fc->last_pid_sent);
4663 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "ack %u\n", fc->last_ack_recv);
4664 if (GMC_is_pid_bigger (fc->last_pid_sent + 1, fc->last_ack_recv) &&
4665 GNUNET_SCHEDULER_NO_TASK == fc->poll_task)
4667 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4668 "no buffer space (%u > %u): starting poll\n",
4669 fc->last_pid_sent + 1, fc->last_ack_recv);
4670 fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
4674 queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
4682 if (100 <= priority)
4683 GNUNET_CONTAINER_DLL_insert (peer->queue_head, peer->queue_tail, queue);
4685 GNUNET_CONTAINER_DLL_insert_tail (peer->queue_head, peer->queue_tail, queue);
4687 if (NULL == peer->core_transmit)
4689 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4690 "calling core tmt rdy towards %s\n",
4692 peer->core_transmit =
4693 GNUNET_CORE_notify_transmit_ready (core_handle,
4696 GNUNET_TIME_UNIT_FOREVER_REL,
4697 GNUNET_PEER_resolve2 (peer->id),
4704 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4705 "core tmt rdy towards %s already called\n",
4709 c->pending_messages++;
4710 c->t->pending_messages++;
4716 /******************************************************************************/
4717 /******************** MESH NETWORK HANDLERS **************************/
4718 /******************************************************************************/
4722 * Generic handler for mesh network payload traffic.
4724 * @param t Tunnel on which we got this message.
4725 * @param message Unencryted data message.
4726 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
4728 * @return GNUNET_OK to keep the connection open,
4729 * GNUNET_SYSERR to close it (signal serious error)
4732 handle_data (struct MeshTunnel2 *t, const struct GNUNET_MESH_Data *msg, int fwd)
4734 struct MeshChannelReliability *rel;
4735 struct MeshChannel *ch;
4736 struct MeshClient *c;
4743 size = ntohs (msg->header.size);
4745 sizeof (struct GNUNET_MESH_Data) +
4746 sizeof (struct GNUNET_MessageHeader))
4751 type = ntohs (msg->header.type);
4752 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message\n",
4753 GNUNET_MESH_DEBUG_M2S (type));
4754 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
4755 GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
4758 ch = channel_get (t, ntohl (msg->chid));
4761 GNUNET_STATISTICS_update (stats, "# data on unknown channel", 1, GNUNET_NO);
4762 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel unknown\n");
4766 /* Initialize FWD/BCK data */
4767 c = fwd ? ch->dest : ch->root;
4768 rel = fwd ? ch->bck_rel : ch->fwd_rel;
4769 mid_recv = fwd ? &ch->mid_recv_fwd : &ch->mid_recv_bck;
4777 tunnel_change_state (t, MESH_TUNNEL_READY);
4779 GNUNET_STATISTICS_update (stats, "# data received", 1, GNUNET_NO);
4781 mid = ntohl (msg->mid);
4782 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " mid %u\n", mid);
4784 if (GNUNET_NO == ch->reliable ||
4785 ( !GMC_is_pid_bigger (*mid_recv, mid) &&
4786 GMC_is_pid_bigger (*mid_recv + 64, mid) ) )
4788 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! RECV %u\n", mid);
4789 if (GNUNET_YES == ch->reliable)
4791 /* Is this the exact next expected messasge? */
4792 if (mid == *mid_recv)
4794 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "as expected\n");
4795 *mid_recv = *mid_recv + 1;
4796 channel_send_client_data (ch, msg, fwd);
4797 channel_send_client_buffered_data (ch, c, rel);
4801 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "save for later\n");
4802 channel_rel_add_buffered_data (msg, rel);
4805 else /* Tunnel unreliable, send to clients directly */
4807 channel_send_client_data (ch, msg, fwd);
4812 GNUNET_break_op (0);
4813 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4814 " MID %u not expected (%u - %u), dropping!\n",
4815 mid, *mid_recv, *mid_recv + 64);
4818 channel_send_data_ack (ch, fwd);
4823 * Handler for mesh network traffic end-to-end ACKs.
4825 * @param t Tunnel on which we got this message.
4826 * @param message Data message.
4827 * @param fwd Is this a fwd ACK? (dest->orig)
4829 * @return GNUNET_OK to keep the connection open,
4830 * GNUNET_SYSERR to close it (signal serious error)
4833 handle_data_ack (struct MeshTunnel2 *t,
4834 const struct GNUNET_MESH_DataACK *msg, int fwd)
4836 struct MeshChannelReliability *rel;
4837 struct MeshReliableMessage *copy;
4838 struct MeshReliableMessage *next;
4839 struct MeshChannel *ch;
4844 type = ntohs (msg->header.type);
4845 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a %s message!\n",
4846 GNUNET_MESH_DEBUG_M2S (type));
4847 ch = channel_get (t, ntohl (msg->chid));
4850 GNUNET_STATISTICS_update (stats, "# ack on unknown channel", 1, GNUNET_NO);
4853 ack = ntohl (msg->mid);
4854 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! %s ACK %u\n",
4855 (GNUNET_YES == fwd) ? "FWD" : "BCK", ack);
4857 if (GNUNET_YES == fwd)
4870 for (work = GNUNET_NO, copy = rel->head_sent; copy != NULL; copy = next)
4872 if (GMC_is_pid_bigger (copy->mid, ack))
4874 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! head %u, out!\n", copy->mid);
4875 channel_rel_free_sent (rel, msg);
4879 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! id %u\n", copy->mid);
4881 rel_message_free (copy);
4883 /* ACK client if needed */
4884 // channel_send_ack (t, type, GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK == type);
4886 /* If some message was free'd, update the retransmission delay*/
4887 if (GNUNET_YES == work)
4889 if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
4891 GNUNET_SCHEDULER_cancel (rel->retry_task);
4892 if (NULL == rel->head_sent)
4894 rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
4898 struct GNUNET_TIME_Absolute new_target;
4899 struct GNUNET_TIME_Relative delay;
4901 delay = GNUNET_TIME_relative_multiply (rel->retry_timer,
4902 MESH_RETRANSMIT_MARGIN);
4903 new_target = GNUNET_TIME_absolute_add (rel->head_sent->timestamp,
4905 delay = GNUNET_TIME_absolute_get_remaining (new_target);
4907 GNUNET_SCHEDULER_add_delayed (delay,
4908 &channel_retransmit_message,
4920 * Core handler for connection creation.
4922 * @param cls Closure (unused).
4923 * @param peer Sender (neighbor).
4924 * @param message Message.
4926 * @return GNUNET_OK to keep the connection open,
4927 * GNUNET_SYSERR to close it (signal serious error)
4930 handle_mesh_connection_create (void *cls,
4931 const struct GNUNET_PeerIdentity *peer,
4932 const struct GNUNET_MessageHeader *message)
4934 struct GNUNET_MESH_ConnectionCreate *msg;
4935 struct GNUNET_PeerIdentity *id;
4936 struct GNUNET_HashCode *tid;
4937 struct MeshPeerPath *path;
4938 struct MeshPeer *dest_peer;
4939 struct MeshPeer *orig_peer;
4940 struct MeshConnection *c;
4941 unsigned int own_pos;
4946 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection create msg\n");
4949 size = ntohs (message->size);
4950 if (size < sizeof (struct GNUNET_MESH_ConnectionCreate))
4952 GNUNET_break_op (0);
4956 /* Calculate hops */
4957 size -= sizeof (struct GNUNET_MESH_ConnectionCreate);
4958 if (size % sizeof (struct GNUNET_PeerIdentity))
4960 GNUNET_break_op (0);
4963 size /= sizeof (struct GNUNET_PeerIdentity);
4966 GNUNET_break_op (0);
4969 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " path has %u hops.\n", size);
4971 /* Get parameters */
4972 msg = (struct GNUNET_MESH_ConnectionCreate *) message;
4973 cid = ntohl (msg->cid);
4975 id = (struct GNUNET_PeerIdentity *) &msg[1];
4976 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4977 " connection %s[%X] (%s).\n",
4978 GNUNET_h2s (tid), cid, GNUNET_i2s (id));
4980 /* Create connection */
4981 c = connection_get (tid, cid);
4984 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Creating connection\n");
4985 c = connection_new (tid, cid);
4989 connection_reset_timeout (c, GNUNET_YES);
4990 tunnel_change_state (c->t, MESH_TUNNEL_WAITING);
4992 /* Remember peers */
4993 dest_peer = peer_get (&id[size - 1]);
4994 orig_peer = peer_get (&id[0]);
4997 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Creating path...\n");
4998 path = path_new (size);
5000 for (i = 0; i < size; i++)
5002 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... adding %s\n",
5003 GNUNET_i2s (&id[i]));
5004 path->peers[i] = GNUNET_PEER_intern (&id[i]);
5005 if (path->peers[i] == myid)
5008 if (own_pos == 0 && path->peers[own_pos] != myid)
5010 /* create path: self not found in path through self */
5011 GNUNET_break_op (0);
5012 path_destroy (path);
5013 connection_destroy (c);
5016 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Own position: %u\n", own_pos);
5017 path_add_to_peers (path, GNUNET_NO);
5018 c->path = path_duplicate (path);
5019 c->own_pos = own_pos;
5021 /* Is it a connection to us? */
5022 if (own_pos == size - 1)
5024 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " It's for us!\n");
5025 peer_add_path_to_origin (orig_peer, path, GNUNET_YES);
5027 send_connection_ack (c, GNUNET_NO);
5029 /* Keep tunnel alive in direction dest->owner*/
5030 connection_reset_timeout (c, GNUNET_NO);
5034 /* It's for somebody else! Retransmit. */
5035 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Retransmitting.\n");
5036 peer_add_path (dest_peer, path_duplicate (path), GNUNET_NO);
5037 peer_add_path_to_origin (orig_peer, path, GNUNET_NO);
5038 send_prebuilt_message_connection (message, c, NULL, GNUNET_YES);
5045 * Core handler for path ACKs
5047 * @param cls closure
5048 * @param message message
5049 * @param peer peer identity this notification is about
5051 * @return GNUNET_OK to keep the connection open,
5052 * GNUNET_SYSERR to close it (signal serious error)
5055 handle_mesh_connection_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5056 const struct GNUNET_MessageHeader *message)
5058 struct GNUNET_MESH_ConnectionACK *msg;
5059 struct MeshPeerPath *p;
5060 struct MeshConnection *c;
5063 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection ACK msg\n");
5064 msg = (struct GNUNET_MESH_ConnectionACK *) message;
5065 cid = ntohl(msg->cid);
5066 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " on connection %s[%X]\n",
5067 GNUNET_h2s (&msg->tid), cid);
5068 c = connection_get (&msg->tid, cid);
5071 GNUNET_STATISTICS_update (stats, "# control on unknown connection",
5073 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " don't know the connection!\n");
5077 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " via peer %s\n",
5080 /* Add path to peers? */
5084 path_add_to_peers (p, GNUNET_YES);
5090 connection_change_state (c, MESH_CONNECTION_READY);
5091 connection_reset_timeout (c, GNUNET_NO);
5092 if (MESH_TUNNEL_READY != c->t->state)
5093 tunnel_change_state (c->t, MESH_TUNNEL_READY);
5094 tunnel_send_queued_data (c->t, GNUNET_YES);
5096 /* Message for us? */
5097 if (connection_is_terminal (c, GNUNET_NO))
5099 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " It's for us!\n");
5100 if (3 <= tunnel_count_connections (c->t) && NULL != c->t->peer->dhtget)
5102 GNUNET_DHT_get_stop (c->t->peer->dhtget);
5103 c->t->peer->dhtget = NULL;
5105 //connection_send_ack (c, GNUNET_NO); /* FIXME */
5109 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " not for us, retransmitting...\n");
5110 send_prebuilt_message_connection (message, c, NULL, GNUNET_NO);
5116 * Core handler for notifications of broken paths
5118 * @param cls Closure (unused).
5119 * @param peer Peer identity of sending neighbor.
5120 * @param message Message.
5122 * @return GNUNET_OK to keep the connection open,
5123 * GNUNET_SYSERR to close it (signal serious error)
5126 handle_mesh_connection_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
5127 const struct GNUNET_MessageHeader *message)
5129 struct GNUNET_MESH_ConnectionBroken *msg;
5130 struct MeshConnection *c;
5132 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5133 "Received a CONNECTION BROKEN msg from %s\n", GNUNET_i2s (peer));
5134 msg = (struct GNUNET_MESH_ConnectionBroken *) message;
5135 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " regarding %s\n",
5136 GNUNET_i2s (&msg->peer1));
5137 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " regarding %s\n",
5138 GNUNET_i2s (&msg->peer2));
5139 c = connection_get (&msg->tid, ntohl (msg->cid));
5142 GNUNET_break_op (0);
5145 tunnel_notify_connection_broken (c->t, GNUNET_PEER_search (&msg->peer1),
5146 GNUNET_PEER_search (&msg->peer2));
5153 * Core handler for tunnel destruction
5155 * @param cls Closure (unused).
5156 * @param peer Peer identity of sending neighbor.
5157 * @param message Message.
5159 * @return GNUNET_OK to keep the connection open,
5160 * GNUNET_SYSERR to close it (signal serious error)
5163 handle_mesh_connection_destroy (void *cls,
5164 const struct GNUNET_PeerIdentity *peer,
5165 const struct GNUNET_MessageHeader *message)
5167 struct GNUNET_MESH_ConnectionDestroy *msg;
5168 struct MeshConnection *c;
5172 msg = (struct GNUNET_MESH_ConnectionDestroy *) message;
5173 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5174 "Got a CONNECTION DESTROY message from %s\n",
5176 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5177 " for connection %s[%X]\n",
5178 GNUNET_h2s (&msg->tid), ntohl (msg->cid));
5179 c = connection_get (&msg->tid, ntohl (msg->cid));
5182 /* Probably already got the message from another path,
5183 * destroyed the tunnel and retransmitted to children.
5186 GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
5190 id = GNUNET_PEER_search (peer);
5191 if (id == connection_get_prev_hop (c)->id)
5193 else if (id == connection_get_next_hop (c)->id)
5197 GNUNET_break_op (0);
5200 send_prebuilt_message_connection (message, c, NULL, fwd);
5201 c->destroy = GNUNET_YES;
5207 * Handler for channel create messages.
5209 * @param t Tunnel this channel is to be created in.
5210 * @param msg Message.
5211 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5213 * @return GNUNET_OK to keep the connection open,
5214 * GNUNET_SYSERR to close it (signal serious error)
5217 handle_channel_create (struct MeshTunnel2 *t,
5218 struct GNUNET_MESH_ChannelCreate *msg,
5221 MESH_ChannelNumber chid;
5222 struct MeshChannel *ch;
5223 struct MeshClient *c;
5226 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received Channel Create\n");
5227 /* Check message size */
5228 if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelCreate))
5230 GNUNET_break_op (0);
5234 /* Check if channel exists */
5235 chid = ntohl (msg->chid);
5236 ch = channel_get (t, chid);
5239 /* Probably a retransmission, safe to ignore */
5240 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " already exists...\n");
5244 /* Create channel */
5245 ch = channel_new (t, NULL, 0);
5246 channel_set_options (ch, ntohl (msg->opt));
5249 /* Find a destination client */
5250 port = ntohl (msg->port);
5251 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " port %u\n", port);
5252 c = GNUNET_CONTAINER_multihashmap32_get (ports, port);
5255 /* TODO send reject */
5256 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " no client has port registered\n");
5260 channel_add_client (ch, c);
5261 if (GNUNET_YES == ch->reliable)
5263 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
5264 ch->bck_rel = GNUNET_malloc (sizeof (struct MeshChannelReliability));
5265 ch->bck_rel->ch = ch;
5266 ch->bck_rel->expected_delay = MESH_RETRANSMIT_TIME;
5269 send_local_channel_create (ch);
5276 * Handler for channel destroy messages.
5278 * @param t Tunnel this channel is to be destroyed of.
5279 * @param msg Message.
5280 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5282 * @return GNUNET_OK to keep the connection open,
5283 * GNUNET_SYSERR to close it (signal serious error)
5286 handle_channel_destroy (struct MeshTunnel2 *t,
5287 struct GNUNET_MESH_ChannelDestroy *msg,
5290 MESH_ChannelNumber chid;
5291 struct MeshChannel *ch;
5293 /* Check message size */
5294 if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelDestroy))
5296 GNUNET_break_op (0);
5300 /* Check if channel exists */
5301 chid = ntohl (msg->chid);
5302 ch = channel_get (t, chid);
5305 /* Probably a retransmission, safe to ignore */
5309 send_local_channel_destroy (ch, fwd);
5310 channel_destroy (ch);
5317 * Generic handler for mesh network encrypted traffic.
5319 * @param peer Peer identity this notification is about.
5320 * @param message Encrypted message.
5321 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5323 * @return GNUNET_OK to keep the connection open,
5324 * GNUNET_SYSERR to close it (signal serious error)
5327 handle_mesh_encrypted (const struct GNUNET_PeerIdentity *peer,
5328 const struct GNUNET_MESH_Encrypted *msg,
5331 struct MeshConnection *c;
5332 struct MeshTunnel2 *t;
5333 struct MeshPeer *neighbor;
5334 struct MeshFlowControl *fc;
5341 size = ntohs (msg->header.size);
5343 sizeof (struct GNUNET_MESH_Encrypted) +
5344 sizeof (struct GNUNET_MessageHeader))
5349 type = ntohs (msg->header.type);
5350 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message from %s\n",
5351 GNUNET_MESH_DEBUG_M2S (type), GNUNET_i2s (peer));
5353 /* Check connection */
5354 c = connection_get (&msg->tid, ntohl (msg->cid));
5357 GNUNET_STATISTICS_update (stats, "# unknown connection", 1, GNUNET_NO);
5358 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING connection unknown\n");
5362 fc = fwd ? &c->fwd_fc : &c->bck_fc;
5364 /* Check if origin is as expected */
5365 neighbor = connection_get_hop (c, fwd);
5366 if (peer_get (peer)->id != neighbor->id)
5368 GNUNET_break_op (0);
5373 pid = ntohl (msg->pid);
5374 if (GMC_is_pid_bigger (pid, fc->last_ack_sent))
5376 GNUNET_STATISTICS_update (stats, "# unsolicited message", 1, GNUNET_NO);
5377 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5378 "WARNING Received PID %u, (prev %u), ACK %u\n",
5379 pid, fc->last_pid_recv, fc->last_ack_sent);
5382 if (GNUNET_NO == GMC_is_pid_bigger (pid, fc->last_pid_recv))
5384 GNUNET_STATISTICS_update (stats, "# duplicate PID", 1, GNUNET_NO);
5385 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5386 " Pid %u not expected (%u+), dropping!\n",
5387 pid, fc->last_pid_recv + 1);
5390 if (MESH_CONNECTION_SENT == c->state)
5391 connection_change_state (c, MESH_CONNECTION_READY);
5392 connection_reset_timeout (c, fwd);
5393 fc->last_pid_recv = pid;
5395 /* Is this message for us? */
5396 if (connection_is_terminal (c, fwd))
5398 size_t dsize = size - sizeof (struct GNUNET_MESH_Encrypted);
5400 struct GNUNET_MessageHeader *msgh;
5402 /* TODO signature verification */
5403 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " it's for us!\n");
5404 GNUNET_STATISTICS_update (stats, "# messages received", 1, GNUNET_NO);
5406 fc->last_pid_recv = pid;
5407 tunnel_decrypt (t, cbuf, &msg[1], dsize, msg->iv, fwd);
5408 msgh = (struct GNUNET_MessageHeader *) cbuf;
5409 switch (ntohs (msgh->type))
5411 case GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK:
5412 if (GNUNET_YES == fwd)
5413 return handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh,
5415 GNUNET_break_op (0);
5417 case GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK:
5418 if (GNUNET_NO == fwd)
5419 return handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh,
5421 GNUNET_break_op (0);
5423 case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
5424 if (GNUNET_YES == fwd)
5425 handle_data (t, (struct GNUNET_MESH_Data *) msgh, GNUNET_YES);
5426 GNUNET_break_op (0);
5428 case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
5429 if (GNUNET_NO == fwd)
5430 handle_data (t, (struct GNUNET_MESH_Data *) msgh, GNUNET_NO);
5431 GNUNET_break_op (0);
5433 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
5434 return handle_channel_create (t,
5435 (struct GNUNET_MESH_ChannelCreate *) msgh,
5438 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
5439 return handle_channel_destroy (t,
5440 (struct GNUNET_MESH_ChannelDestroy *)
5445 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5446 "end-to-end message not known (%u)\n",
5447 ntohs (msgh->type));
5450 connection_send_ack (c, fwd);
5454 /* Message not for us: forward to next hop */
5455 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " not for us, retransmitting...\n");
5456 ttl = ntohl (msg->ttl);
5457 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ttl: %u\n", ttl);
5460 GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5461 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5462 connection_send_ack (c, fwd);
5465 GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
5467 send_prebuilt_message_connection (&msg->header, c, NULL, fwd);
5474 * Core handler for mesh network traffic going orig->dest.
5476 * @param cls Closure (unused).
5477 * @param message Message received.
5478 * @param peer Peer who sent the message.
5480 * @return GNUNET_OK to keep the connection open,
5481 * GNUNET_SYSERR to close it (signal serious error)
5484 handle_mesh_fwd (void *cls, const struct GNUNET_PeerIdentity *peer,
5485 const struct GNUNET_MessageHeader *message)
5487 return handle_mesh_encrypted (peer,
5488 (struct GNUNET_MESH_Encrypted *)message,
5493 * Core handler for mesh network traffic going dest->orig.
5495 * @param cls Closure (unused).
5496 * @param message Message received.
5497 * @param peer Peer who sent the message.
5499 * @return GNUNET_OK to keep the connection open,
5500 * GNUNET_SYSERR to close it (signal serious error)
5503 handle_mesh_bck (void *cls, const struct GNUNET_PeerIdentity *peer,
5504 const struct GNUNET_MessageHeader *message)
5506 return handle_mesh_encrypted (peer,
5507 (struct GNUNET_MESH_Encrypted *)message,
5513 * Core handler for mesh network traffic point-to-point acks.
5515 * @param cls closure
5516 * @param message message
5517 * @param peer peer identity this notification is about
5519 * @return GNUNET_OK to keep the connection open,
5520 * GNUNET_SYSERR to close it (signal serious error)
5523 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5524 const struct GNUNET_MessageHeader *message)
5526 struct GNUNET_MESH_ACK *msg;
5527 struct MeshConnection *c;
5528 struct MeshFlowControl *fc;
5532 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
5534 msg = (struct GNUNET_MESH_ACK *) message;
5536 c = connection_get (&msg->tid, ntohl (msg->cid));
5540 GNUNET_STATISTICS_update (stats, "# ack on unknown connection", 1,
5545 ack = ntohl (msg->ack);
5546 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", ack);
5548 /* Is this a forward or backward ACK? */
5549 id = GNUNET_PEER_search (peer);
5550 if (connection_get_next_hop (c)->id == id)
5552 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " FWD ACK\n");
5555 else if (connection_get_prev_hop (c)->id == id)
5557 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " BCK ACK\n");
5562 GNUNET_break_op (0);
5566 /* Cancel polling if the ACK is bigger than before. */
5567 if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task &&
5568 GMC_is_pid_bigger (ack, fc->last_ack_recv))
5570 GNUNET_SCHEDULER_cancel (fc->poll_task);
5571 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
5572 fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
5575 fc->last_ack_recv = ack;
5576 connection_unlock_queue (c, fc == &c->fwd_fc);
5583 * Core handler for mesh network traffic point-to-point ack polls.
5585 * @param cls closure
5586 * @param message message
5587 * @param peer peer identity this notification is about
5589 * @return GNUNET_OK to keep the connection open,
5590 * GNUNET_SYSERR to close it (signal serious error)
5593 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
5594 const struct GNUNET_MessageHeader *message)
5596 struct GNUNET_MESH_Poll *msg;
5597 struct MeshConnection *c;
5598 struct MeshFlowControl *fc;
5602 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a POLL packet from %s!\n",
5605 msg = (struct GNUNET_MESH_Poll *) message;
5607 c = connection_get (&msg->tid, ntohl (msg->cid));
5611 GNUNET_STATISTICS_update (stats, "# poll on unknown connection", 1,
5613 GNUNET_break_op (0);
5617 /* Is this a forward or backward ACK? */
5618 id = GNUNET_PEER_search (peer);
5619 if (connection_get_next_hop (c)->id == id)
5621 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " FWD ACK\n");
5624 else if (connection_get_prev_hop (c)->id == id)
5626 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " BCK ACK\n");
5631 GNUNET_break_op (0);
5635 pid = ntohl (msg->pid);
5636 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " PID %u, OLD %u\n",
5637 pid, fc->last_pid_recv);
5638 fc->last_pid_recv = pid;
5639 connection_send_ack (c, fc == &c->fwd_fc);
5646 * Core handler for mesh keepalives.
5648 * @param cls closure
5649 * @param message message
5650 * @param peer peer identity this notification is about
5651 * @return GNUNET_OK to keep the connection open,
5652 * GNUNET_SYSERR to close it (signal serious error)
5654 * TODO: Check who we got this from, to validate route.
5657 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
5658 const struct GNUNET_MessageHeader *message)
5660 struct GNUNET_MESH_ConnectionKeepAlive *msg;
5661 struct MeshConnection *c;
5662 struct MeshPeer *neighbor;
5665 msg = (struct GNUNET_MESH_ConnectionKeepAlive *) message;
5666 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
5669 c = connection_get (&msg->tid, ntohl (msg->cid));
5672 GNUNET_STATISTICS_update (stats, "# keepalive on unknown connection", 1,
5677 fwd = GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE == ntohs (message->type) ?
5678 GNUNET_YES : GNUNET_NO;
5680 /* Check if origin is as expected */
5681 neighbor = connection_get_hop (c, fwd);
5682 if (peer_get (peer)->id != neighbor->id)
5684 GNUNET_break_op (0);
5688 connection_change_state (c, MESH_CONNECTION_READY);
5689 connection_reset_timeout (c, fwd);
5691 if (connection_is_terminal (c, fwd))
5694 GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
5695 send_prebuilt_message_connection (message, c, NULL, fwd);
5703 * Functions to handle messages from core
5705 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
5706 {&handle_mesh_connection_create, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
5708 {&handle_mesh_connection_ack, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
5709 sizeof (struct GNUNET_MESH_ConnectionACK)},
5710 {&handle_mesh_connection_broken, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN,
5711 sizeof (struct GNUNET_MESH_ConnectionBroken)},
5712 {&handle_mesh_connection_destroy, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY,
5713 sizeof (struct GNUNET_MESH_ConnectionDestroy)},
5714 {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE,
5715 sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
5716 {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE,
5717 sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
5718 {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
5719 sizeof (struct GNUNET_MESH_ACK)},
5720 {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
5721 sizeof (struct GNUNET_MESH_Poll)},
5722 {&handle_mesh_fwd, GNUNET_MESSAGE_TYPE_MESH_FWD, 0},
5723 {&handle_mesh_bck, GNUNET_MESSAGE_TYPE_MESH_BCK, 0},
5729 * Function to process paths received for a new peer addition. The recorded
5730 * paths form the initial tunnel, which can be optimized later.
5731 * Called on each result obtained for the DHT search.
5733 * @param cls closure
5734 * @param exp when will this value expire
5735 * @param key key of the result
5736 * @param get_path path of the get request
5737 * @param get_path_length lenght of get_path
5738 * @param put_path path of the put request
5739 * @param put_path_length length of the put_path
5740 * @param type type of the result
5741 * @param size number of bytes in data
5742 * @param data pointer to the result data
5745 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5746 const struct GNUNET_HashCode * key,
5747 const struct GNUNET_PeerIdentity *get_path,
5748 unsigned int get_path_length,
5749 const struct GNUNET_PeerIdentity *put_path,
5750 unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5751 size_t size, const void *data)
5753 struct MeshPeer *peer = cls;
5754 struct MeshPeerPath *p;
5755 struct MeshConnection *c;
5756 struct GNUNET_PeerIdentity pi;
5759 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
5760 GNUNET_PEER_resolve (peer->id, &pi);
5761 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " for %s\n", GNUNET_i2s (&pi));
5763 p = path_build_from_dht (get_path, get_path_length,
5764 put_path, put_path_length);
5765 path_add_to_peers (p, GNUNET_NO);
5768 /* Count connections */
5769 for (c = peer->tunnel->connection_head, i = 0; NULL != c; c = c->next, i++);
5771 /* If we already have 3 (or more (?!)) connections, it's enough */
5775 if (peer->tunnel->state == MESH_TUNNEL_SEARCHING)
5777 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... connect!\n");
5778 peer_connect (peer);
5784 /******************************************************************************/
5785 /********************* MESH LOCAL HANDLES **************************/
5786 /******************************************************************************/
5790 * Handler for client connection.
5792 * @param cls Closure (unused).
5793 * @param client Client handler.
5796 handle_local_client_connect (void *cls, struct GNUNET_SERVER_Client *client)
5798 struct MeshClient *c;
5802 c = GNUNET_malloc (sizeof (struct MeshClient));
5804 c->id = next_client_id++; /* overflow not important: just for debug */
5805 GNUNET_SERVER_client_keep (client);
5806 GNUNET_SERVER_client_set_user_context (client, c);
5807 GNUNET_CONTAINER_DLL_insert (clients_head, clients_tail, c);
5812 * Handler for client disconnection
5814 * @param cls closure
5815 * @param client identification of the client; NULL
5816 * for the last call when the server is destroyed
5819 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
5821 struct MeshClient *c;
5823 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected: %p\n", client);
5826 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " (SERVER DOWN)\n");
5830 c = client_get (client);
5833 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u, %p)\n",
5835 GNUNET_SERVER_client_drop (c->handle);
5836 c->shutting_down = GNUNET_YES;
5837 if (NULL != c->own_channels)
5839 GNUNET_CONTAINER_multihashmap32_iterate (c->own_channels,
5840 &channel_destroy_iterator, c);
5841 GNUNET_CONTAINER_multihashmap32_destroy (c->own_channels);
5844 if (NULL != c->incoming_channels)
5846 GNUNET_CONTAINER_multihashmap32_iterate (c->incoming_channels,
5847 &channel_destroy_iterator, c);
5848 GNUNET_CONTAINER_multihashmap32_destroy (c->incoming_channels);
5851 if (NULL != c->ports)
5853 GNUNET_CONTAINER_multihashmap32_iterate (c->ports,
5854 &client_release_ports, c);
5855 GNUNET_CONTAINER_multihashmap32_destroy (c->ports);
5857 GNUNET_CONTAINER_DLL_remove (clients_head, clients_tail, c);
5858 GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
5859 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " client free (%p)\n", c);
5864 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " context NULL!\n");
5866 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "done!\n");
5872 * Handler for new clients
5874 * @param cls closure
5875 * @param client identification of the client
5876 * @param message the actual message, which includes messages the client wants
5879 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
5880 const struct GNUNET_MessageHeader *message)
5882 struct GNUNET_MESH_ClientConnect *cc_msg;
5883 struct MeshClient *c;
5888 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected %p\n", client);
5890 /* Check data sanity */
5891 size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
5892 cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
5893 if (0 != (size % sizeof (uint32_t)))
5896 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5899 size /= sizeof (uint32_t);
5901 /* Initialize new client structure */
5902 c = GNUNET_SERVER_client_get_user_context (client, struct MeshClient);
5903 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " client id %u\n", c->id);
5904 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " client has %u ports\n", size);
5909 p = (uint32_t *) &cc_msg[1];
5910 c->ports = GNUNET_CONTAINER_multihashmap32_create (size);
5911 for (i = 0; i < size; i++)
5914 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " port: %u\n", u32);
5916 /* store in client's hashmap */
5917 GNUNET_CONTAINER_multihashmap32_put (c->ports, u32, c,
5918 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
5919 /* store in global hashmap */
5920 /* FIXME only allow one client to have the port open,
5921 * have a backup hashmap with waiting clients */
5922 GNUNET_CONTAINER_multihashmap32_put (ports, u32, c,
5923 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
5927 c->own_channels = GNUNET_CONTAINER_multihashmap32_create (32);
5928 c->incoming_channels = GNUNET_CONTAINER_multihashmap32_create (32);
5929 GNUNET_SERVER_notification_context_add (nc, client);
5930 GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
5932 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5933 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
5938 * Handler for requests of new tunnels
5940 * @param cls Closure.
5941 * @param client Identification of the client.
5942 * @param message The actual message.
5945 handle_local_channel_create (void *cls, struct GNUNET_SERVER_Client *client,
5946 const struct GNUNET_MessageHeader *message)
5948 struct GNUNET_MESH_ChannelMessage *msg;
5949 struct MeshPeer *peer;
5950 struct MeshTunnel2 *t;
5951 struct MeshChannel *ch;
5952 struct MeshClient *c;
5953 MESH_ChannelNumber chid;
5955 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new channel requested\n");
5957 /* Sanity check for client registration */
5958 if (NULL == (c = client_get (client)))
5961 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5964 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
5966 /* Message size sanity check */
5967 if (sizeof (struct GNUNET_MESH_ChannelMessage) != ntohs (message->size))
5970 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5974 msg = (struct GNUNET_MESH_ChannelMessage *) message;
5975 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " towards %s:%u\n",
5976 GNUNET_i2s (&msg->peer), ntohl (msg->port));
5977 chid = ntohl (msg->channel_id);
5979 /* Sanity check for duplicate channel IDs */
5980 if (NULL != channel_get_by_local_id (c, chid))
5983 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5987 peer = peer_get (&msg->peer);
5988 if (NULL == peer->tunnel)
5990 struct GNUNET_HashCode tid;
5992 GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE, &tid);
5993 peer->tunnel = tunnel_new (&tid);
5994 peer->tunnel->peer = peer;
5998 /* Create channel */
5999 ch = channel_new (t, c, chid);
6003 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6006 ch->port = ntohl (msg->port);
6007 channel_set_options (ch, ntohl (msg->opt));
6009 /* In unreliable channels, we'll use the DLL to buffer data for the root */
6010 ch->fwd_rel = GNUNET_malloc (sizeof (struct MeshChannelReliability));
6011 ch->fwd_rel->ch = ch;
6012 ch->fwd_rel->expected_delay = MESH_RETRANSMIT_TIME;
6014 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED CHANNEL %s[%x]:%u (%x)\n",
6015 GNUNET_h2s (&t->id), ch->gid, ch->port, ch->lid_root);
6016 peer_connect (peer);
6018 /* Send create channel */
6020 struct GNUNET_MESH_ChannelCreate msgcc;
6022 msgcc.header.size = htons (sizeof (msgcc));
6023 msgcc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE);
6024 msgcc.chid = htonl (ch->gid);
6025 msgcc.port = msg->port;
6026 msgcc.opt = msg->opt;
6028 tunnel_queue_data (t, ch, &msgcc.header, GNUNET_YES);
6031 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6037 * Handler for requests of deleting tunnels
6039 * @param cls closure
6040 * @param client identification of the client
6041 * @param message the actual message
6044 handle_local_channel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
6045 const struct GNUNET_MessageHeader *message)
6047 struct GNUNET_MESH_ChannelMessage *msg;
6048 struct MeshClient *c;
6049 struct MeshChannel *ch;
6050 struct MeshTunnel2 *t;
6051 MESH_ChannelNumber chid;
6053 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6054 "Got a DESTROY CHANNEL from client!\n");
6056 /* Sanity check for client registration */
6057 if (NULL == (c = client_get (client)))
6060 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6063 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
6065 /* Message sanity check */
6066 if (sizeof (struct GNUNET_MESH_ChannelMessage) != ntohs (message->size))
6069 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6073 msg = (struct GNUNET_MESH_ChannelMessage *) message;
6075 /* Retrieve tunnel */
6076 chid = ntohl (msg->channel_id);
6077 ch = channel_get_by_local_id (c, chid);
6080 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, " channel %X not found\n", chid);
6082 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6086 /* Cleanup after the tunnel */
6087 client_delete_channel (c, ch);
6088 if (c == ch->dest && GNUNET_MESH_LOCAL_CHANNEL_ID_SERV <= chid)
6092 else if (c == ch->root && GNUNET_MESH_LOCAL_CHANNEL_ID_SERV > chid)
6098 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6099 " channel %X client %p (%p, %p)\n",
6100 chid, c, ch->root, ch->dest);
6105 channel_destroy (ch);
6106 tunnel_destroy_if_empty (t);
6108 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6114 * Handler for client traffic
6116 * @param cls closure
6117 * @param client identification of the client
6118 * @param message the actual message
6121 handle_local_data (void *cls, struct GNUNET_SERVER_Client *client,
6122 const struct GNUNET_MessageHeader *message)
6124 struct GNUNET_MESH_LocalData *msg;
6125 struct MeshClient *c;
6126 struct MeshChannel *ch;
6127 MESH_ChannelNumber chid;
6131 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6132 "Got data from a client!\n");
6134 /* Sanity check for client registration */
6135 if (NULL == (c = client_get (client)))
6138 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6141 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
6143 msg = (struct GNUNET_MESH_LocalData *) message;
6145 /* Sanity check for message size */
6146 size = ntohs (message->size) - sizeof (struct GNUNET_MESH_LocalData);
6147 if (size < sizeof (struct GNUNET_MessageHeader))
6150 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6154 /* Channel exists? */
6155 chid = ntohl (msg->id);
6156 fwd = chid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
6157 ch = channel_get_by_local_id (c, chid);
6161 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6165 /* Is the client in the channel? */
6168 ch->root->handle == client)
6172 ch->dest->handle == client) ) )
6175 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6180 ch->blocked_fwd = GNUNET_YES;
6182 ch->blocked_bck = GNUNET_YES;
6184 /* Ok, everything is correct, send the message
6185 * (pretend we got it from a mesh peer)
6188 struct GNUNET_MESH_Data *payload;
6189 char cbuf[sizeof(struct GNUNET_MESH_Data) + size];
6192 mid = fwd ? &ch->mid_send_fwd : &ch->mid_send_bck;
6193 if (GNUNET_YES == ch->reliable)
6195 struct MeshChannelReliability *rel;
6196 struct MeshReliableMessage *copy;
6198 rel = fwd ? ch->fwd_rel : ch->bck_rel;
6199 copy = GNUNET_malloc (sizeof (struct MeshReliableMessage)
6200 + sizeof(struct GNUNET_MESH_Data)
6203 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! DATA %u\n", copy->mid);
6204 copy->timestamp = GNUNET_TIME_absolute_get ();
6207 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " n_sent %u\n", rel->n_sent);
6208 GNUNET_CONTAINER_DLL_insert_tail (rel->head_sent, rel->tail_sent, copy);
6209 if (GNUNET_SCHEDULER_NO_TASK == rel->retry_task)
6212 GNUNET_TIME_relative_multiply (rel->expected_delay,
6213 MESH_RETRANSMIT_MARGIN);
6215 GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
6216 &channel_retransmit_message,
6219 payload = (struct GNUNET_MESH_Data *) ©[1];
6223 payload = (struct GNUNET_MESH_Data *) cbuf;
6225 payload->mid = htonl (*mid);
6227 memcpy (&payload[1], &msg[1], size);
6228 payload->header.size = htons (sizeof (struct GNUNET_MESH_Data) + size);
6229 payload->header.type = htons (chid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV ?
6230 GNUNET_MESSAGE_TYPE_MESH_UNICAST :
6231 GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
6232 payload->chid = htonl (ch->gid);
6233 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6234 " calling generic handler...\n");
6235 send_prebuilt_message_channel (&payload->header, ch, fwd);
6237 if (tunnel_get_buffer (ch->t, fwd) > 0)
6238 send_local_ack (ch, c, fwd);
6239 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
6240 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6247 * Handler for client's ACKs for payload traffic.
6249 * @param cls Closure (unused).
6250 * @param client Identification of the client.
6251 * @param message The actual message.
6254 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
6255 const struct GNUNET_MessageHeader *message)
6257 struct GNUNET_MESH_LocalAck *msg;
6258 struct MeshChannelReliability *rel;
6259 struct MeshChannel *ch;
6260 struct MeshClient *c;
6261 MESH_ChannelNumber chid;
6264 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
6266 /* Sanity check for client registration */
6267 if (NULL == (c = client_get (client)))
6270 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6273 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
6275 msg = (struct GNUNET_MESH_LocalAck *) message;
6277 /* Channel exists? */
6278 chid = ntohl (msg->channel_id);
6279 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " on channel %X\n", chid);
6280 ch = channel_get_by_local_id (c, chid);
6284 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Channel %X unknown.\n", chid);
6285 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " for client %u.\n", c->id);
6286 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6290 fwd = chid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
6291 rel = fwd ? ch->fwd_rel : ch->bck_rel;
6293 rel->client_ready = GNUNET_YES;
6294 channel_send_client_buffered_data (ch, c, rel);
6295 channel_send_connection_ack (ch, 64 - rel->n_recv, fwd);
6297 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6304 * Iterator over all tunnels to send a monitoring client info about each tunnel.
6306 * @param cls Closure (client handle).
6307 * @param key Key (hashed tunnel ID, unused).
6308 * @param value Tunnel info.
6310 * @return GNUNET_YES, to keep iterating.
6313 monitor_all_tunnels_iterator (void *cls,
6314 const struct GNUNET_HashCode * key,
6317 struct GNUNET_SERVER_Client *client = cls;
6318 struct MeshChannel *ch = value;
6319 struct GNUNET_MESH_LocalMonitor *msg;
6321 msg = GNUNET_malloc (sizeof(struct GNUNET_MESH_LocalMonitor));
6322 msg->channel_id = htonl (ch->gid);
6323 msg->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
6324 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
6326 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6327 "* sending info about tunnel %s\n",
6328 GNUNET_i2s (&msg->owner));
6330 GNUNET_SERVER_notification_context_unicast (nc, client,
6331 &msg->header, GNUNET_NO);
6337 * Handler for client's MONITOR request.
6339 * @param cls Closure (unused).
6340 * @param client Identification of the client.
6341 * @param message The actual message.
6344 handle_local_get_tunnels (void *cls, struct GNUNET_SERVER_Client *client,
6345 const struct GNUNET_MessageHeader *message)
6347 struct MeshClient *c;
6349 /* Sanity check for client registration */
6350 if (NULL == (c = client_get (client)))
6353 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6357 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6358 "Received get tunnels request from client %u\n",
6360 GNUNET_CONTAINER_multihashmap_iterate (tunnels,
6361 monitor_all_tunnels_iterator,
6363 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6364 "Get tunnels request from client %u completed\n",
6366 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6371 * Handler for client's MONITOR_TUNNEL request.
6373 * @param cls Closure (unused).
6374 * @param client Identification of the client.
6375 * @param message The actual message.
6378 handle_local_show_tunnel (void *cls, struct GNUNET_SERVER_Client *client,
6379 const struct GNUNET_MessageHeader *message)
6381 const struct GNUNET_MESH_LocalMonitor *msg;
6382 struct GNUNET_MESH_LocalMonitor *resp;
6383 struct MeshClient *c;
6384 struct MeshChannel *ch;
6386 /* Sanity check for client registration */
6387 if (NULL == (c = client_get (client)))
6390 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6394 msg = (struct GNUNET_MESH_LocalMonitor *) message;
6395 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6396 "Received tunnel info request from client %u for tunnel %s[%X]\n",
6399 ntohl (msg->channel_id));
6400 // ch = channel_get (&msg->owner, ntohl (msg->channel_id));
6404 /* We don't know the tunnel */
6405 struct GNUNET_MESH_LocalMonitor warn;
6408 GNUNET_SERVER_notification_context_unicast (nc, client,
6411 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6415 /* Initialize context */
6416 resp = GNUNET_malloc (sizeof (struct GNUNET_MESH_LocalMonitor));
6418 resp->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
6419 GNUNET_SERVER_notification_context_unicast (nc, c->handle,
6420 &resp->header, GNUNET_NO);
6423 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6424 "Monitor tunnel request from client %u completed\n",
6426 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6431 * Functions to handle messages from clients
6433 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
6434 {&handle_local_new_client, NULL,
6435 GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
6436 {&handle_local_channel_create, NULL,
6437 GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE,
6438 sizeof (struct GNUNET_MESH_ChannelMessage)},
6439 {&handle_local_channel_destroy, NULL,
6440 GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY,
6441 sizeof (struct GNUNET_MESH_ChannelMessage)},
6442 {&handle_local_data, NULL,
6443 GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA, 0},
6444 {&handle_local_ack, NULL,
6445 GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
6446 sizeof (struct GNUNET_MESH_LocalAck)},
6447 {&handle_local_get_tunnels, NULL,
6448 GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS,
6449 sizeof (struct GNUNET_MessageHeader)},
6450 {&handle_local_show_tunnel, NULL,
6451 GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL,
6452 sizeof (struct GNUNET_MESH_LocalMonitor)},
6458 * Method called whenever a given peer connects.
6460 * @param cls closure
6461 * @param peer peer identity this notification is about
6464 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
6466 struct MeshPeer *pi;
6467 struct MeshPeerPath *path;
6469 DEBUG_CONN ("Peer connected\n");
6470 DEBUG_CONN (" %s\n", GNUNET_i2s (&my_full_id));
6471 pi = peer_get (peer);
6474 DEBUG_CONN (" (self)\n");
6475 path = path_new (1);
6479 DEBUG_CONN (" %s\n", GNUNET_i2s (peer));
6480 path = path_new (2);
6481 path->peers[1] = pi->id;
6482 GNUNET_PEER_change_rc (pi->id, 1);
6483 GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
6485 path->peers[0] = myid;
6486 GNUNET_PEER_change_rc (myid, 1);
6487 peer_add_path (pi, path, GNUNET_YES);
6489 pi->connections = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_YES);
6495 * Method called whenever a peer disconnects.
6497 * @param cls closure
6498 * @param peer peer identity this notification is about
6501 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
6503 struct MeshPeer *pi;
6505 DEBUG_CONN ("Peer disconnected\n");
6506 pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
6513 peer_remove_path (pi, myid, pi->id);
6515 GNUNET_CONTAINER_multihashmap_iterate (pi->connections,
6518 GNUNET_CONTAINER_multihashmap_destroy (pi->connections);
6519 pi->connections = NULL;
6522 DEBUG_CONN (" (self)\n");
6524 GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
6531 * Install server (service) handlers and start listening to clients.
6536 GNUNET_SERVER_add_handlers (server_handle, client_handlers);
6537 GNUNET_SERVER_connect_notify (server_handle,
6538 &handle_local_client_connect, NULL);
6539 GNUNET_SERVER_disconnect_notify (server_handle,
6540 &handle_local_client_disconnect, NULL);
6541 nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
6543 clients_head = NULL;
6544 clients_tail = NULL;
6546 GNUNET_SERVER_resume (server_handle);
6551 * To be called on core init/fail.
6553 * @param cls Closure (config)
6554 * @param server handle to the server for this service
6555 * @param identity the public identity of this peer
6558 core_init (void *cls, struct GNUNET_CORE_Handle *server,
6559 const struct GNUNET_PeerIdentity *identity)
6561 const struct GNUNET_CONFIGURATION_Handle *c = cls;
6564 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
6565 GNUNET_break (core_handle == server);
6566 if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
6569 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
6570 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6572 GNUNET_i2s (identity));
6573 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6575 GNUNET_i2s (&my_full_id));
6576 GNUNET_CORE_disconnect (core_handle);
6577 core_handle = GNUNET_CORE_connect (c, /* Main configuration */
6578 NULL, /* Closure passed to MESH functions */
6579 &core_init, /* Call core_init once connected */
6580 &core_connect, /* Handle connects */
6581 &core_disconnect, /* remove peers on disconnects */
6582 NULL, /* Don't notify about all incoming messages */
6583 GNUNET_NO, /* For header only in notification */
6584 NULL, /* Don't notify about all outbound messages */
6585 GNUNET_NO, /* For header-only out notification */
6586 core_handlers); /* Register these handlers */
6595 /******************************************************************************/
6596 /************************ MAIN FUNCTIONS ****************************/
6597 /******************************************************************************/
6600 * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
6602 * @param cls closure
6603 * @param key current key code
6604 * @param value value in the hash map
6605 * @return GNUNET_YES if we should continue to iterate,
6609 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
6611 struct MeshTunnel2 *t = value;
6619 * Task run during shutdown.
6625 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
6627 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
6629 if (core_handle != NULL)
6631 GNUNET_CORE_disconnect (core_handle);
6634 GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
6635 if (dht_handle != NULL)
6637 GNUNET_DHT_disconnect (dht_handle);
6642 GNUNET_SERVER_notification_context_destroy (nc);
6645 if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
6647 GNUNET_SCHEDULER_cancel (announce_id_task);
6648 announce_id_task = GNUNET_SCHEDULER_NO_TASK;
6650 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
6655 * Process mesh requests.
6657 * @param cls closure
6658 * @param server the initialized server
6659 * @param c configuration to use
6662 run (void *cls, struct GNUNET_SERVER_Handle *server,
6663 const struct GNUNET_CONFIGURATION_Handle *c)
6666 struct GNUNET_CRYPTO_EccPrivateKey *pk;
6668 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
6669 server_handle = server;
6670 GNUNET_SERVER_suspend (server_handle);
6673 GNUNET_CONFIGURATION_get_value_filename (c, "PEER", "PRIVATE_KEY",
6676 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6678 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6679 "mesh", "peer/privatekey");
6680 GNUNET_SCHEDULER_shutdown ();
6685 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_CONNECTION_TIME",
6686 &refresh_connection_time))
6688 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6690 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6691 "mesh", "refresh path time");
6692 GNUNET_SCHEDULER_shutdown ();
6697 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
6700 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6702 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6703 "mesh", "id announce time");
6704 GNUNET_SCHEDULER_shutdown ();
6709 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
6712 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6714 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6715 "mesh", "connect timeout");
6716 GNUNET_SCHEDULER_shutdown ();
6721 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
6724 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6726 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6727 "mesh", "max msgs queue");
6728 GNUNET_SCHEDULER_shutdown ();
6733 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_CONNECTIONS",
6736 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6738 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6739 "mesh", "max tunnels");
6740 GNUNET_SCHEDULER_shutdown ();
6745 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
6748 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6750 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
6751 "mesh", "default ttl", 64);
6756 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
6759 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6760 _("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
6761 "mesh", "max peers", 1000);
6766 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DROP_PERCENT",
6773 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6774 "Mesh is running with drop mode enabled. "
6775 "This is NOT a good idea! "
6776 "Remove the DROP_PERCENT option from your configuration.\n");
6780 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
6781 &dht_replication_level))
6783 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6785 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
6786 "mesh", "dht replication level", 3);
6787 dht_replication_level = 3;
6790 tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6791 peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6792 ports = GNUNET_CONTAINER_multihashmap32_create (32);
6794 dht_handle = GNUNET_DHT_connect (c, 64);
6795 if (NULL == dht_handle)
6799 stats = GNUNET_STATISTICS_create ("mesh", c);
6801 /* Scheduled the task to clean up when shutdown is called */
6802 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
6804 pk = GNUNET_CRYPTO_ecc_key_create_from_file (keyfile);
6805 GNUNET_free (keyfile);
6806 GNUNET_assert (NULL != pk);
6807 my_private_key = pk;
6808 GNUNET_CRYPTO_ecc_key_get_public (my_private_key, &my_public_key);
6809 GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
6810 &my_full_id.hashPubKey);
6811 myid = GNUNET_PEER_intern (&my_full_id);
6812 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6813 "Mesh for peer [%s] starting\n",
6814 GNUNET_i2s(&my_full_id));
6816 core_handle = GNUNET_CORE_connect (c, /* Main configuration */
6817 NULL, /* Closure passed to MESH functions */
6818 &core_init, /* Call core_init once connected */
6819 &core_connect, /* Handle connects */
6820 &core_disconnect, /* remove peers on disconnects */
6821 NULL, /* Don't notify about all incoming messages */
6822 GNUNET_NO, /* For header only in notification */
6823 NULL, /* Don't notify about all outbound messages */
6824 GNUNET_NO, /* For header-only out notification */
6825 core_handlers); /* Register these handlers */
6826 if (NULL == core_handle)
6829 GNUNET_SCHEDULER_shutdown ();
6832 announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
6833 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
6838 * The main function for the mesh service.
6840 * @param argc number of arguments from the command line
6841 * @param argv command line arguments
6842 * @return 0 ok, 1 on error
6845 main (int argc, char *const *argv)
6850 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
6851 r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
6853 ret = (GNUNET_OK == r) ? 0 : 1;
6854 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");