2 This file is part of GNUnet.
3 (C) 2001-2013 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file mesh/gnunet-service-mesh-enc.c
23 * @brief GNUnet MESH service with encryption
24 * @author Bartlomiej Polot
27 * - when sending in-order buffered data, wait for client ACKs
32 * - relay corking down to core
33 * - set ttl relative to path length
37 * - peer: other mesh instance. If there is direct connection it's a neighbor.
38 * - tunnel: encrypted connection to a peer, neighbor or not.
39 * - channel: connection between two clients, on the same or different peers.
40 * have properties like reliability.
41 * - path: series of directly connected peer from one peer to another.
42 * - connection: path which is being used in a tunnel.
46 #include "gnunet_crypto_lib.h"
48 #include "mesh_protocol_enc.h"
49 #include "mesh_path.h"
50 #include "block_mesh.h"
51 #include "gnunet_dht_service.h"
52 #include "gnunet_statistics_service.h"
54 #define MESH_BLOOM_SIZE 128
56 #define MESH_DEBUG_DHT GNUNET_NO
57 #define MESH_DEBUG_CONNECTION GNUNET_NO
58 #define MESH_DEBUG_TIMING __LINUX__ && GNUNET_NO
60 #define MESH_MAX_POLL_TIME GNUNET_TIME_relative_multiply (\
61 GNUNET_TIME_UNIT_MINUTES,\
63 #define MESH_RETRANSMIT_TIME GNUNET_TIME_UNIT_SECONDS
64 #define MESH_RETRANSMIT_MARGIN 4
66 #if MESH_DEBUG_CONNECTION
67 #define DEBUG_CONN(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
69 #define DEBUG_CONN(...)
73 #define DEBUG_DHT(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
75 #define DEBUG_DHT(...)
82 struct timespec __mesh_start;
83 struct timespec __mesh_end;
84 #define INTERVAL_START clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &(__mesh_start))
85 #define INTERVAL_END \
87 clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &(__mesh_end));\
88 double __diff = __mesh_end.tv_nsec - __mesh_start.tv_nsec;\
89 if (__diff < 0) __diff += 1000000000;\
93 #define INTERVAL_SHOW \
95 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "AVG process time: %f ns\n", __sum/__count)
97 #define INTERVAL_START
103 * All the states a tunnel can be in.
108 * Uninitialized status, should never appear in operation.
113 * Path to the peer not known yet
115 MESH_TUNNEL_SEARCHING,
118 * Request sent, not yet answered.
123 * Peer connected and ready to accept data
128 * Peer connected previosly but not responding
130 MESH_TUNNEL_RECONNECTING
135 * All the states a connection can be in.
137 enum MeshConnectionState
140 * Uninitialized status, should never appear in operation.
145 * Connection created, waiting for ACK.
147 MESH_CONNECTION_SENT,
150 * Connection confirmed, ready to carry traffic..
152 MESH_CONNECTION_READY,
156 /******************************************************************************/
157 /************************ DATA STRUCTURES ****************************/
158 /******************************************************************************/
160 /** FWD declaration */
164 struct MeshConnection;
166 struct MeshChannelReliability;
170 * Struct containing info about a queued transmission to this peer
177 struct MeshPeerQueue *next;
182 struct MeshPeerQueue *prev;
185 * Peer this transmission is directed to.
187 struct MeshPeer *peer;
190 * Connection this message belongs to.
192 struct MeshConnection *c;
200 * Channel this message belongs to, if known.
202 struct MeshChannel *ch;
205 * Pointer to info stucture used as cls.
215 * Size of the message
222 * Struct to encapsulate all the Flow Control information to a peer to which
223 * we are directly connected (on a core level).
225 struct MeshFlowControl
228 * Connection this controls.
230 struct MeshConnection *c;
233 * How many messages are in the queue on this connection.
235 unsigned int queue_n;
238 * How many messages do we accept in the queue.
240 unsigned int queue_max;
243 * ID of the last packet sent towards the peer.
245 uint32_t last_pid_sent;
248 * ID of the last packet received from the peer.
250 uint32_t last_pid_recv;
253 * Last ACK sent to the peer (peer can't send more than this PID).
255 uint32_t last_ack_sent;
258 * Last ACK sent towards the origin (for traffic towards leaf node).
260 uint32_t last_ack_recv;
263 * Task to poll the peer in case of a lost ACK causes stall.
265 GNUNET_SCHEDULER_TaskIdentifier poll_task;
268 * How frequently to poll for ACKs.
270 struct GNUNET_TIME_Relative poll_time;
275 * Struct containing all information regarding a given peer
285 * Last time we heard from this peer
287 struct GNUNET_TIME_Absolute last_contact;
290 * Paths to reach the peer, ordered by ascending hop count
292 struct MeshPeerPath *path_head;
295 * Paths to reach the peer, ordered by ascending hop count
297 struct MeshPeerPath *path_tail;
300 * Handle to stop the DHT search for paths to this peer
302 struct GNUNET_DHT_GetHandle *dhtget;
305 * Tunnel to this peer, if any.
307 struct MeshTunnel2 *tunnel;
310 * Connections that go through this peer, indexed by tid;
312 struct GNUNET_CONTAINER_MultiHashMap *connections;
315 * Handle for queued transmissions
317 struct GNUNET_CORE_TransmitHandle *core_transmit;
320 * Transmission queue to core DLL head
322 struct MeshPeerQueue *queue_head;
325 * Transmission queue to core DLL tail
327 struct MeshPeerQueue *queue_tail;
330 * How many messages are in the queue to this peer.
332 unsigned int queue_n;
337 * Info needed to retry a message in case it gets lost.
339 struct MeshReliableMessage
342 * Double linked list, FIFO style
344 struct MeshReliableMessage *next;
345 struct MeshReliableMessage *prev;
348 * Tunnel Reliability queue this message is in.
350 struct MeshChannelReliability *rel;
353 * ID of the message (ACK needed to free)
358 * When was this message issued (to calculate ACK delay)
360 struct GNUNET_TIME_Absolute timestamp;
362 /* struct GNUNET_MESH_Data with payload */
366 struct MeshChannelReliability
369 * Channel this is about.
371 struct MeshChannel *ch;
374 * DLL of messages sent and not yet ACK'd.
376 struct MeshReliableMessage *head_sent;
377 struct MeshReliableMessage *tail_sent;
380 * Messages pending to send.
385 * DLL of messages received out of order.
387 struct MeshReliableMessage *head_recv;
388 struct MeshReliableMessage *tail_recv;
396 * Can we send data to the client?
401 * Task to resend/poll in case no ACK is received.
403 GNUNET_SCHEDULER_TaskIdentifier retry_task;
406 * Counter for exponential backoff.
408 struct GNUNET_TIME_Relative retry_timer;
411 * How long does it usually take to get an ACK.
413 struct GNUNET_TIME_Relative expected_delay;
418 * Struct containing all information regarding a channel to a remote client.
423 * Tunnel this channel is in.
425 struct MeshTunnel2 *t;
428 * Double linked list.
430 struct MeshChannel *next;
431 struct MeshChannel *prev;
434 * Destination port of the channel.
439 * Global channel number ( < GNUNET_MESH_LOCAL_CHANNEL_ID_CLI)
441 MESH_ChannelNumber gid;
444 * Local tunnel number for root (owner) client.
445 * ( >= GNUNET_MESH_LOCAL_CHANNEL_ID_CLI or 0 )
447 MESH_ChannelNumber lid_root;
450 * Local tunnel number for local destination clients (incoming number)
451 * ( >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV or 0).
453 MESH_ChannelNumber lid_dest;
456 * Next MID to use for fwd traffic.
458 uint32_t mid_send_fwd;
461 * Next MID expected for fwd traffic.
463 uint32_t mid_recv_fwd;
466 * Next MID to use for bck traffic.
468 uint32_t mid_send_bck;
471 * Next MID expected for bck traffic.
473 uint32_t mid_recv_bck;
476 * Is the tunnel bufferless (minimum latency)?
481 * Is the tunnel reliable?
486 * Last time the channel was used
488 struct GNUNET_TIME_Absolute timestamp;
491 * Client owner of the tunnel, if any
493 struct MeshClient *root;
496 * Client destination of the tunnel, if any.
498 struct MeshClient *dest;
501 * Flag to signal the destruction of the channel.
502 * If this is set GNUNET_YES the channel will be destroyed
503 * when the queue is empty.
508 * Total messages pending for this channel, payload or not.
510 unsigned int pending_messages;
514 * Only present (non-NULL) at the owner of a tunnel.
516 struct MeshChannelReliability *fwd_rel;
520 * Only present (non-NULL) at the destination of a tunnel.
522 struct MeshChannelReliability *bck_rel;
526 struct MeshConnection
531 struct MeshConnection *next;
532 struct MeshConnection *prev;
535 * Tunnel this connection is part of.
537 struct MeshTunnel2 *t;
540 * Flow control information for traffic fwd.
542 struct MeshFlowControl fwd_fc;
545 * Flow control information for traffic bck.
547 struct MeshFlowControl bck_fc;
555 * State of the connection.
557 enum MeshConnectionState state;
560 * Path being used for the tunnel.
562 struct MeshPeerPath *path;
565 * Position of the local peer in the path.
567 unsigned int own_pos;
570 * Task to keep the used paths alive at the owner,
571 * time tunnel out on all the other peers.
573 GNUNET_SCHEDULER_TaskIdentifier fwd_maintenance_task;
576 * Task to keep the used paths alive at the destination,
577 * time tunnel out on all the other peers.
579 GNUNET_SCHEDULER_TaskIdentifier bck_maintenance_task;
582 * Pending message count.
584 int pending_messages;
587 * Destroy flag: if true, destroy on last message.
594 * Struct containing all information regarding a tunnel to a peer.
599 * Endpoint of the tunnel.
601 struct MeshPeer *peer;
606 struct GNUNET_HashCode id;
609 * State of the tunnel.
611 enum MeshTunnelState state;
614 * Local peer ephemeral private key
616 struct GNUNET_CRYPTO_EccPrivateKey *my_eph_key;
619 * Local peer ephemeral public key
621 struct GNUNET_CRYPTO_EccPublicKey *my_eph;
624 * Remote peer's public key.
626 struct GNUNET_CRYPTO_EccPublicKey *peers_eph;
629 * Encryption ("our") key.
631 struct GNUNET_CRYPTO_AesSessionKey e_key;
634 * Decryption ("their") key.
636 struct GNUNET_CRYPTO_AesSessionKey d_key;
639 * Paths that are actively used to reach the destination peer.
641 struct MeshConnection *connection_head;
642 struct MeshConnection *connection_tail;
645 * Next connection number.
650 * Channels inside this tunnel.
652 struct MeshChannel *channel_head;
653 struct MeshChannel *channel_tail;
656 * Channel ID for the next created channel.
658 MESH_ChannelNumber next_chid;
661 * Channel ID for the next incoming channel.
663 MESH_ChannelNumber next_local_chid;
666 * Pending message count.
668 int pending_messages;
671 * Destroy flag: if true, destroy on last message.
679 * Struct containing information about a client of the service
681 * TODO: add a list of 'waiting' ports
688 struct MeshClient *next;
693 struct MeshClient *prev;
696 * Tunnels that belong to this client, indexed by local id
698 struct GNUNET_CONTAINER_MultiHashMap32 *own_channels;
701 * Tunnels this client has accepted, indexed by incoming local id
703 struct GNUNET_CONTAINER_MultiHashMap32 *incoming_channels;
706 * Handle to communicate with the client
708 struct GNUNET_SERVER_Client *handle;
711 * Ports that this client has declared interest in.
712 * Indexed by port, contains *Client.
714 struct GNUNET_CONTAINER_MultiHashMap32 *ports;
717 * Whether the client is active or shutting down (don't send confirmations
718 * to a client that is shutting down.
723 * ID of the client, mainly for debug messages
729 /******************************************************************************/
730 /************************ DEBUG FUNCTIONS ****************************/
731 /******************************************************************************/
735 * GNUNET_SCHEDULER_Task for printing a message after some operation is done
736 * @param cls string to print
737 * @param success GNUNET_OK if the PUT was transmitted,
738 * GNUNET_NO on timeout,
739 * GNUNET_SYSERR on disconnect from service
740 * after the PUT message was transmitted
741 * (so we don't know if it was received or not)
746 mesh_debug (void *cls, int success)
750 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s (%d)\n", s, success);
756 /******************************************************************************/
757 /*********************** GLOBAL VARIABLES ****************************/
758 /******************************************************************************/
760 /************************** Configuration parameters **************************/
763 * How often to send path keepalives. Paths timeout after 4 missed.
765 static struct GNUNET_TIME_Relative refresh_connection_time;
768 * How often to PUT own ID in the DHT.
770 static struct GNUNET_TIME_Relative id_announce_time;
773 * Maximum time allowed to connect to a peer found by string.
775 static struct GNUNET_TIME_Relative connect_timeout;
778 * Default TTL for payload packets.
780 static unsigned long long default_ttl;
783 * DHT replication level, see DHT API: GNUNET_DHT_get_start, GNUNET_DHT_put.
785 static unsigned long long dht_replication_level;
788 * How many connections are we willing to maintain.
789 * Local connections are always allowed, even if there are more connections than max.
791 static unsigned long long max_connections;
794 * How many messages *in total* are we willing to queue, divided by number of
795 * connections to get tunnel queue size.
797 static unsigned long long max_msgs_queue;
800 * How many peers do we want to remember?
802 static unsigned long long max_peers;
805 * Percentage of messages that will be dropped (for test purposes only).
807 static unsigned long long drop_percent;
809 /*************************** Static global variables **************************/
812 * DLL with all the clients, head.
814 static struct MeshClient *clients_head;
817 * DLL with all the clients, tail.
819 static struct MeshClient *clients_tail;
822 * Tunnels known, indexed by MESH_TunnelID (MeshTunnel).
824 static struct GNUNET_CONTAINER_MultiHashMap *tunnels;
827 * Peers known, indexed by PeerIdentity (MeshPeer).
829 static struct GNUNET_CONTAINER_MultiHashMap *peers;
832 * Handle to communicate with core.
834 static struct GNUNET_CORE_Handle *core_handle;
839 static struct GNUNET_DHT_Handle *dht_handle;
842 * Handle to server lib.
844 static struct GNUNET_SERVER_Handle *server_handle;
847 * Handle to the statistics service.
849 static struct GNUNET_STATISTICS_Handle *stats;
852 * Notification context, to send messages to local clients.
854 static struct GNUNET_SERVER_NotificationContext *nc;
857 * Local peer own ID (memory efficient handle).
859 static GNUNET_PEER_Id myid;
862 * Local peer own ID (full value).
864 static struct GNUNET_PeerIdentity my_full_id;
869 static struct GNUNET_CRYPTO_EccPrivateKey *my_private_key;
874 static struct GNUNET_CRYPTO_EccPublicKey my_public_key;
877 * All ports clients of this peer have opened.
879 static struct GNUNET_CONTAINER_MultiHashMap32 *ports;
882 * Task to periodically announce itself in the network.
884 GNUNET_SCHEDULER_TaskIdentifier announce_id_task;
887 * Next ID to assign to a client.
889 unsigned int next_client_id;
892 /******************************************************************************/
893 /*********************** DECLARATIONS **************************/
894 /******************************************************************************/
897 * Function to process paths received for a new peer addition. The recorded
898 * paths form the initial tunnel, which can be optimized later.
899 * Called on each result obtained for the DHT search.
902 * @param exp when will this value expire
903 * @param key key of the result
904 * @param type type of the result
905 * @param size number of bytes in data
906 * @param data pointer to the result data
909 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
910 const struct GNUNET_HashCode * key,
911 const struct GNUNET_PeerIdentity *get_path,
912 unsigned int get_path_length,
913 const struct GNUNET_PeerIdentity *put_path,
914 unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
915 size_t size, const void *data);
919 * Retrieve the MeshPeer stucture associated with the peer, create one
920 * and insert it in the appropriate structures if the peer is not known yet.
922 * @param peer Full identity of the peer.
924 * @return Existing or newly created peer info.
926 static struct MeshPeer *
927 peer_get (const struct GNUNET_PeerIdentity *peer);
931 * Retrieve the MeshPeer stucture associated with the peer, create one
932 * and insert it in the appropriate structures if the peer is not known yet.
934 * @param peer Short identity of the peer.
936 * @return Existing or newly created peer info.
938 static struct MeshPeer *
939 peer_get_short (const GNUNET_PEER_Id peer);
943 * Build a PeerPath from the paths returned from the DHT, reversing the paths
944 * to obtain a local peer -> destination path and interning the peer ids.
946 * @return Newly allocated and created path
948 static struct MeshPeerPath *
949 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
950 unsigned int get_path_length,
951 const struct GNUNET_PeerIdentity *put_path,
952 unsigned int put_path_length);
956 * Adds a path to the data structs of all the peers in the path
958 * @param p Path to process.
959 * @param confirmed Whether we know if the path works or not.
962 path_add_to_peers (struct MeshPeerPath *p, int confirmed);
966 * Search for a tunnel by global ID using full PeerIdentities.
968 * @param t Tunnel containing the channel.
969 * @param chid Public channel number.
971 * @return channel handler, NULL if doesn't exist
973 static struct MeshChannel *
974 channel_get (struct MeshTunnel2 *t, MESH_ChannelNumber chid);
978 * Change the tunnel state.
980 * @param t Tunnel whose state to change.
981 * @param state New state.
984 tunnel_change_state (struct MeshTunnel2 *t, enum MeshTunnelState state);
988 * Notify a tunnel that a connection has broken that affects at least
991 * @param t Tunnel affected.
992 * @param p1 Peer that got disconnected from p2.
993 * @param p2 Peer that got disconnected from p1.
995 * @return Short ID of the peer disconnected (either p1 or p2).
996 * 0 if the tunnel remained unaffected.
998 static GNUNET_PEER_Id
999 tunnel_notify_connection_broken (struct MeshTunnel2 *t,
1000 GNUNET_PEER_Id p1, GNUNET_PEER_Id p2);
1003 * @brief Use the given path for the tunnel.
1004 * Update the next and prev hops (and RCs).
1005 * (Re)start the path refresh in case the tunnel is locally owned.
1007 * @param t Tunnel to update.
1008 * @param p Path to use.
1010 * @return Connection created.
1012 static struct MeshConnection *
1013 tunnel_use_path (struct MeshTunnel2 *t, struct MeshPeerPath *p);
1016 * Tunnel is empty: destroy it.
1018 * Notifies all participants (peers, cleints) about the destruction.
1020 * @param t Tunnel to destroy.
1023 tunnel_destroy_empty (struct MeshTunnel2 *t);
1026 * Destroy the tunnel.
1028 * This function does not generate any warning traffic to clients or peers.
1031 * Cancel messages belonging to this tunnel queued to neighbors.
1032 * Free any allocated resources linked to the tunnel.
1034 * @param t The tunnel to destroy.
1037 tunnel_destroy (struct MeshTunnel2 *t);
1040 * Create a connection.
1042 * @param tid Tunnel ID.
1043 * @param cid Connection ID.
1045 static struct MeshConnection *
1046 connection_new (struct GNUNET_HashCode *tid, uint32_t cid);
1049 * Connection is no longer needed: destroy it and remove from tunnel.
1051 * @param c Connection to destroy.
1054 connection_destroy (struct MeshConnection *c);
1057 * Send FWD keepalive packets for a connection.
1059 * @param cls Closure (connection for which to send the keepalive).
1060 * @param tc Notification context.
1063 connection_fwd_keepalive (void *cls,
1064 const struct GNUNET_SCHEDULER_TaskContext *tc);
1067 * Send BCK keepalive packets for a connection.
1069 * @param cls Closure (connection for which to send the keepalive).
1070 * @param tc Notification context.
1073 connection_bck_keepalive (void *cls,
1074 const struct GNUNET_SCHEDULER_TaskContext *tc);
1078 * Change the tunnel state.
1080 * @param c Connection whose state to change.
1081 * @param state New state.
1084 connection_change_state (struct MeshConnection* c,
1085 enum MeshConnectionState state);
1090 * @brief Queue and pass message to core when possible.
1092 * @param cls Closure (@c type dependant). It will be used by queue_send to
1093 * build the message to be sent if not already prebuilt.
1094 * @param type Type of the message, 0 for a raw message.
1095 * @param size Size of the message.
1096 * @param dst Neighbor to send message to.
1097 * @param c Connection this message belongs to, if any.
1098 * @param ch Channel this message belongs to, if applicable (otherwise NULL).
1101 queue_add (void *cls, uint16_t type, size_t size,
1102 struct MeshPeer *dst,
1103 struct MeshConnection *c,
1104 struct MeshChannel *ch);
1108 * Free a transmission that was already queued with all resources
1109 * associated to the request.
1111 * @param queue Queue handler to cancel.
1112 * @param clear_cls Is it necessary to free associated cls?
1115 queue_destroy (struct MeshPeerQueue *queue, int clear_cls);
1119 * Core callback to write a queued packet to core buffer
1121 * @param cls Closure (peer info).
1122 * @param size Number of bytes available in buf.
1123 * @param buf Where the to write the message.
1125 * @return number of bytes written to buf
1128 queue_send (void *cls, size_t size, void *buf);
1132 * Dummy function to separate declarations from definitions in function list.
1135 __mesh_divider______________________________________________________________();
1139 * Get string description for tunnel state.
1141 * @param s Tunnel state.
1143 * @return String representation.
1146 GNUNET_MESH_DEBUG_TS2S (enum MeshTunnelState s)
1148 static char buf[128];
1152 case MESH_TUNNEL_NEW:
1153 return "MESH_TUNNEL_NEW";
1154 case MESH_TUNNEL_SEARCHING:
1155 return "MESH_TUNNEL_SEARCHING";
1156 case MESH_TUNNEL_WAITING:
1157 return "MESH_TUNNEL_WAITING";
1158 case MESH_TUNNEL_READY:
1159 return "MESH_TUNNEL_READY";
1160 case MESH_TUNNEL_RECONNECTING:
1161 return "MESH_TUNNEL_RECONNECTING";
1164 sprintf (buf, "%u (UNKNOWN STATE)", s);
1171 * Get string description for tunnel state.
1173 * @param s Tunnel state.
1175 * @return String representation.
1178 GNUNET_MESH_DEBUG_CS2S (enum MeshTunnelState s)
1182 case MESH_CONNECTION_NEW:
1183 return "MESH_CONNECTION_NEW";
1184 case MESH_CONNECTION_SENT:
1185 return "MESH_CONNECTION_SENT";
1186 case MESH_CONNECTION_READY:
1187 return "MESH_CONNECTION_READY";
1189 return "MESH_CONNECTION_STATE_ERROR";
1195 /******************************************************************************/
1196 /************************ PERIODIC FUNCTIONS ****************************/
1197 /******************************************************************************/
1200 * Periodically announce self id in the DHT
1202 * @param cls closure
1203 * @param tc task context
1206 announce_id (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1208 struct PBlock block;
1210 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1212 announce_id_task = GNUNET_SCHEDULER_NO_TASK;
1216 * - Set data expiration in function of X
1217 * - Adapt X to churn
1219 DEBUG_DHT ("DHT_put for ID %s started.\n", GNUNET_i2s (&my_full_id));
1221 block.id = my_full_id;
1222 GNUNET_DHT_put (dht_handle, /* DHT handle */
1223 &my_full_id.hashPubKey, /* Key to use */
1224 dht_replication_level, /* Replication level */
1225 GNUNET_DHT_RO_RECORD_ROUTE | GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, /* DHT options */
1226 GNUNET_BLOCK_TYPE_MESH_PEER, /* Block type */
1227 sizeof (block), /* Size of the data */
1228 (const char *) &block, /* Data itself */
1229 GNUNET_TIME_UNIT_FOREVER_ABS, /* Data expiration */
1230 GNUNET_TIME_UNIT_FOREVER_REL, /* Retry time */
1231 NULL, /* Continuation */
1232 NULL); /* Continuation closure */
1234 GNUNET_SCHEDULER_add_delayed (id_announce_time, &announce_id, cls);
1238 /******************************************************************************/
1239 /****************** GENERAL HELPER FUNCTIONS ************************/
1240 /******************************************************************************/
1244 * Get the static string for a peer ID.
1248 * @return Static string for it's ID.
1251 peer2s (const struct MeshPeer *peer)
1255 return GNUNET_i2s (GNUNET_PEER_resolve2 (peer->id));
1260 * Get the previous hop in a connection
1262 * @param c Connection.
1264 * @return Previous peer in the connection.
1266 static struct MeshPeer *
1267 connection_get_prev_hop (struct MeshConnection *c)
1271 if (0 == c->own_pos || c->path->length < 2)
1272 id = c->path->peers[0];
1274 id = c->path->peers[c->own_pos - 1];
1276 return peer_get_short (id);
1281 * Get the next hop in a connection
1283 * @param c Connection.
1285 * @return Next peer in the connection.
1287 static struct MeshPeer *
1288 connection_get_next_hop (struct MeshConnection *c)
1292 if ((c->path->length - 1) == c->own_pos || c->path->length < 2)
1293 id = c->path->peers[c->path->length - 1];
1295 id = c->path->peers[c->own_pos + 1];
1297 return peer_get_short (id);
1302 * Get the hop in a connection.
1304 * @param c Connection.
1305 * @param fwd Next hop?
1307 * @return Next peer in the connection.
1309 static struct MeshPeer *
1310 connection_get_hop (struct MeshConnection *c, int fwd)
1313 return connection_get_next_hop (c);
1314 return connection_get_prev_hop (c);
1318 * Check if client has registered with the service and has not disconnected
1320 * @param client the client to check
1322 * @return non-NULL if client exists in the global DLL
1324 static struct MeshClient *
1325 client_get (struct GNUNET_SERVER_Client *client)
1327 return GNUNET_SERVER_client_get_user_context (client, struct MeshClient);
1332 * Deletes a tunnel from a client (either owner or destination).
1334 * @param c Client whose tunnel to delete.
1335 * @param ch Channel which should be deleted.
1338 client_delete_channel (struct MeshClient *c, struct MeshChannel *ch)
1344 res = GNUNET_CONTAINER_multihashmap32_remove (c->own_channels,
1346 if (GNUNET_YES != res)
1347 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client_delete_channel owner KO\n");
1351 res = GNUNET_CONTAINER_multihashmap32_remove (c->incoming_channels,
1353 if (GNUNET_YES != res)
1354 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client_delete_tunnel client KO\n");
1360 * Notify the appropriate client that a new incoming channel was created.
1362 * @param ch Channel that was created.
1365 send_local_channel_create (struct MeshChannel *ch)
1367 struct GNUNET_MESH_ChannelMessage msg;
1368 struct MeshTunnel2 *t = ch->t;
1370 if (NULL == ch->dest)
1372 msg.header.size = htons (sizeof (msg));
1373 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
1374 msg.channel_id = htonl (ch->lid_dest);
1375 msg.port = htonl (ch->port);
1377 msg.opt |= GNUNET_YES == ch->reliable ? GNUNET_MESH_OPTION_RELIABLE : 0;
1378 msg.opt |= GNUNET_YES == ch->nobuffer ? GNUNET_MESH_OPTION_NOBUFFER : 0;
1379 msg.opt = htonl (msg.opt);
1380 GNUNET_PEER_resolve (t->peer->id, &msg.peer);
1381 GNUNET_SERVER_notification_context_unicast (nc, ch->dest->handle,
1382 &msg.header, GNUNET_NO);
1387 * Notify a client that the incoming tunnel is no longer valid.
1389 * @param ch Channel that is destroyed.
1390 * @param fwd Forward notification (owner->dest)?
1393 send_local_channel_destroy (struct MeshChannel *ch, int fwd)
1395 struct GNUNET_MESH_ChannelMessage msg;
1396 struct MeshClient *c;
1398 c = fwd ? ch->dest : ch->root;
1404 msg.header.size = htons (sizeof (msg));
1405 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1406 msg.channel_id = htonl (fwd ? ch->lid_dest : ch->lid_root);
1407 msg.port = htonl (0);
1408 memset (&msg.peer, 0, sizeof (msg.peer));
1409 msg.opt = htonl (0);
1410 GNUNET_SERVER_notification_context_unicast (nc, c->handle,
1411 &msg.header, GNUNET_NO);
1416 * Build a local ACK message and send it to a local client.
1418 * @param ch Channel on which to send the ACK.
1419 * @param c Client to whom send the ACK.
1420 * @param is_fwd Set to GNUNET_YES for FWD ACK (dest->owner)
1423 send_local_ack (struct MeshChannel *ch,
1424 struct MeshClient *c,
1427 struct GNUNET_MESH_LocalAck msg;
1429 msg.header.size = htons (sizeof (msg));
1430 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
1431 msg.channel_id = htonl (is_fwd ? ch->lid_root : ch->lid_dest);
1432 GNUNET_SERVER_notification_context_unicast (nc,
1440 * Count established (ready) connections of a tunnel.
1442 * @param t Tunnel on which to send the message.
1444 * @return Number of connections.
1447 tunnel_count_connections (struct MeshTunnel2 *t)
1449 struct MeshConnection *c;
1452 for (c = t->connection_head, i = 0; NULL != c; c = c->next, i++);
1459 * Pick a connection on which send the next data message.
1461 * @param t Tunnel on which to send the message.
1462 * @param fwd Is this a fwd message?
1464 * @return The connection on which to send the next message.
1466 static struct MeshConnection *
1467 tunnel_get_connection (struct MeshTunnel2 *t, int fwd)
1469 struct MeshConnection *c;
1470 struct MeshConnection *best;
1471 struct MeshFlowControl *fc;
1472 unsigned int lowest_q;
1475 lowest_q = UINT_MAX;
1476 for (c = t->connection_head; NULL != c; c = c->next)
1478 if (MESH_CONNECTION_READY == c->state)
1480 fc = fwd ? &c->fwd_fc : &c->bck_fc;
1486 if (fc->queue_n < lowest_q)
1489 lowest_q = fc->queue_n;
1498 * Get the total buffer space for a tunnel
1501 tunnel_get_buffer (struct MeshTunnel2 *t, int fwd)
1503 struct MeshConnection *c;
1504 struct MeshFlowControl *fc;
1505 unsigned int buffer;
1507 for (buffer = 0, c = t->connection_head; NULL != c; c = c->next)
1509 if (c->state != MESH_CONNECTION_READY)
1512 fc = fwd ? &c->fwd_fc : &c->bck_fc;
1513 buffer += fc->last_ack_recv - fc->last_pid_sent;
1521 * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
1522 * Encrypt data with the tunnel key.
1524 * @param t Tunnel whose key to use.
1525 * @param dst Destination for the encrypted data.
1526 * @param src Source of the plaintext.
1527 * @param size Size of the plaintext.
1528 * @param iv Initialization Vector to use.
1529 * @param fwd Is this a fwd message?
1532 tunnel_encrypt (struct MeshTunnel2 *t,
1533 void *dst, const void *src,
1534 size_t size, uint64_t iv, int fwd)
1536 memcpy (dst, src, size);
1541 * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
1542 * Decrypt data with the tunnel key.
1544 * @param t Tunnel whose key to use.
1545 * @param dst Destination for the plaintext.
1546 * @param src Source of the encrypted data.
1547 * @param size Size of the encrypted data.
1548 * @param iv Initialization Vector to use.
1549 * @param fwd Is this a fwd message?
1552 tunnel_decrypt (struct MeshTunnel2 *t,
1553 void *dst, const void *src,
1554 size_t size, uint64_t iv, int fwd)
1556 memcpy (dst, src, size);
1561 * Sends an already built message on a connection, properly registering
1562 * all used resources.
1564 * @param message Message to send. Function makes a copy of it.
1565 * If message is not hop-by-hop, decrements TTL of copy.
1566 * @param c Connection on which this message is transmitted.
1567 * @param ch Channel on which this message is transmitted, or NULL.
1568 * @param fwd Is this a fwd message?
1571 send_prebuilt_message_connection (const struct GNUNET_MessageHeader *message,
1572 struct MeshConnection *c,
1573 struct MeshChannel *ch,
1576 struct MeshPeer *neighbor;
1581 neighbor = connection_get_hop (c, fwd);
1582 if (NULL == neighbor)
1588 size = ntohs (message->size);
1589 data = GNUNET_malloc (size);
1590 memcpy (data, message, size);
1591 type = ntohs(message->type);
1593 if (GNUNET_MESSAGE_TYPE_MESH_FWD == type ||
1594 GNUNET_MESSAGE_TYPE_MESH_BCK == type)
1596 struct GNUNET_MESH_Encrypted *msg;
1599 msg = (struct GNUNET_MESH_Encrypted *) data;
1600 ttl = ntohl (msg->ttl);
1603 GNUNET_break_op (0);
1606 msg->ttl = htonl (ttl - 1);
1619 * Sends an already built message on a tunnel, choosing the best connection.
1621 * @param message Message to send. Function modifies it.
1622 * @param t Tunnel on which this message is transmitted.
1623 * @param ch Channel on which this message is transmitted.
1624 * @param fwd Is this a fwd message?
1627 send_prebuilt_message_tunnel (struct GNUNET_MESH_Encrypted *msg,
1628 struct MeshTunnel2 *t,
1629 struct MeshChannel *ch,
1632 struct MeshConnection *c;
1635 c = tunnel_get_connection (t, fwd);
1641 type = ntohs (msg->header.size);
1644 case GNUNET_MESSAGE_TYPE_MESH_FWD:
1645 case GNUNET_MESSAGE_TYPE_MESH_BCK:
1646 msg->cid = htonl (c->id);
1648 msg->ttl = default_ttl;
1654 send_prebuilt_message_connection (&msg->header, c, ch, fwd);
1659 * Sends an already built message on a channel, properly registering
1660 * all used resources and encrypting the message with the tunnel's key.
1662 * @param message Message to send. Function makes a copy of it.
1663 * @param ch Channel on which this message is transmitted.
1664 * @param fwd Is this a fwd message?
1667 send_prebuilt_message_channel (const struct GNUNET_MessageHeader *message,
1668 struct MeshChannel *ch,
1671 struct GNUNET_MESH_Encrypted *msg;
1672 size_t size = ntohs (message->size);
1673 char *cbuf[size + sizeof (struct GNUNET_MESH_Encrypted)];
1677 type = fwd ? GNUNET_MESSAGE_TYPE_MESH_FWD : GNUNET_MESSAGE_TYPE_MESH_BCK;
1678 iv = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
1680 msg = (struct GNUNET_MESH_Encrypted *) cbuf;
1681 msg->header.type = htons (type);
1682 msg->header.size = htons (size);
1683 msg->iv = GNUNET_htonll (iv);
1684 tunnel_encrypt (ch->t, &msg[1], message, size, iv, fwd);
1686 send_prebuilt_message_tunnel (msg, ch->t, ch, fwd);
1691 * Sends a CREATE CONNECTION message for a path to a peer.
1692 * Changes the connection and tunnel states if necessary.
1694 * @param connection Connection to create.
1697 send_connection_create (struct MeshConnection *connection)
1699 struct MeshPeer *neighbor;
1700 struct MeshTunnel2 *t;
1703 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send connection create\n");
1704 neighbor = connection_get_next_hop (connection);
1705 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " to %s\n", peer2s (neighbor));
1706 queue_add (connection,
1707 GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
1708 sizeof (struct GNUNET_MESH_ConnectionCreate) +
1709 (connection->path->length *
1710 sizeof (struct GNUNET_PeerIdentity)),
1714 if (MESH_TUNNEL_SEARCHING == t->state || MESH_TUNNEL_NEW == t->state)
1715 tunnel_change_state (t, MESH_TUNNEL_WAITING);
1716 if (MESH_CONNECTION_NEW == connection->state)
1717 connection_change_state (connection, MESH_CONNECTION_SENT);
1722 * Sends a CONNECTION ACK message in reponse to a received CONNECTION_CREATE
1725 * @param connection Connection to confirm.
1728 send_connection_ack (struct MeshConnection *connection)
1730 struct MeshPeer *neighbor;
1731 struct MeshTunnel2 *t;
1734 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send connection ack\n");
1735 neighbor = connection_get_prev_hop (connection);
1736 queue_add (connection,
1737 GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
1738 sizeof (struct GNUNET_MESH_ConnectionACK),
1742 if (MESH_TUNNEL_NEW == t->state)
1743 tunnel_change_state (t, MESH_TUNNEL_WAITING);
1748 * Build a hop-by-hop ACK message and queue it to send for the given connection.
1750 * @param c Which connection to send the hop-by-hop ACK.
1751 * @param ack Value of the ACK.
1752 * @param fwd Is this fwd?
1755 send_ack (struct MeshConnection *c, uint32_t ack, int fwd)
1757 struct GNUNET_MESH_ACK msg;
1759 msg.header.size = htons (sizeof (msg));
1760 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ACK);
1761 msg.ack = htonl (ack);
1763 msg.cid = htonl (c->id);
1765 send_prebuilt_message_connection (&msg.header, c, NULL, fwd);
1770 * Core callback to write a pre-constructed data packet to core buffer
1772 * @param cls Closure (MeshTransmissionDescriptor with data in "data" member).
1773 * @param size Number of bytes available in buf.
1774 * @param buf Where the to write the message.
1776 * @return number of bytes written to buf
1779 send_core_data_raw (void *cls, size_t size, void *buf)
1781 struct GNUNET_MessageHeader *msg = cls;
1784 GNUNET_assert (NULL != msg);
1785 total_size = ntohs (msg->size);
1787 if (total_size > size)
1792 memcpy (buf, msg, total_size);
1799 * Function to send a create connection message to a peer.
1801 * @param cls closure
1802 * @param size number of bytes available in buf
1803 * @param buf where the callee should write the message
1804 * @return number of bytes written to buf
1807 send_core_connection_create (void *cls, size_t size, void *buf)
1809 struct MeshConnection *c = cls;
1810 struct GNUNET_MESH_ConnectionCreate *msg;
1811 struct GNUNET_PeerIdentity *peer_ptr;
1812 struct MeshPeerPath *p = c->path;
1816 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION CREATE...\n");
1818 sizeof (struct GNUNET_MESH_ConnectionCreate) +
1819 p->length * sizeof (struct GNUNET_PeerIdentity);
1821 if (size < size_needed || NULL == buf)
1826 msg = (struct GNUNET_MESH_ConnectionCreate *) buf;
1827 msg->header.size = htons (size_needed);
1828 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE);
1829 msg->cid = htonl (c->id);
1830 msg->tid = c->t->id;
1832 peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
1833 for (i = 0; i < p->length; i++)
1835 GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
1838 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1839 "CONNECTION CREATE (%u bytes long) sent!\n", size_needed);
1845 * Creates a path ack message in buf and frees all unused resources.
1847 * @param cls closure (MeshTransmissionDescriptor)
1848 * @param size number of bytes available in buf
1849 * @param buf where the callee should write the message
1850 * @return number of bytes written to buf
1853 send_core_connection_ack (void *cls, size_t size, void *buf)
1855 struct GNUNET_MESH_ConnectionACK *msg = buf;
1856 struct MeshConnection *c = cls;
1857 struct MeshTunnel2 *t = c->t;
1859 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION ACK...\n");
1860 GNUNET_assert (NULL != t);
1861 if (sizeof (struct GNUNET_MESH_ConnectionACK) > size)
1866 msg->header.size = htons (sizeof (struct GNUNET_MESH_ConnectionACK));
1867 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK);
1868 GNUNET_CRYPTO_hash_xor (&GNUNET_PEER_resolve2 (t->peer->id)->hashPubKey,
1869 &my_full_id.hashPubKey,
1871 msg->cid = htonl (c->id);
1873 /* TODO add signature */
1875 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CONNECTION ACK sent!\n");
1876 return sizeof (struct GNUNET_MESH_ConnectionACK);
1881 * Destroy the peer_info and free any allocated resources linked to it
1883 * @param peer The peer_info to destroy.
1885 * @return GNUNET_OK on success
1888 peer_destroy (struct MeshPeer *peer)
1890 struct GNUNET_PeerIdentity id;
1891 struct MeshPeerPath *p;
1892 struct MeshPeerPath *nextp;
1894 GNUNET_PEER_resolve (peer->id, &id);
1895 GNUNET_PEER_change_rc (peer->id, -1);
1898 GNUNET_CONTAINER_multihashmap_remove (peers, &id.hashPubKey, peer))
1901 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1902 "removing peer %s, not in hashmap\n", GNUNET_i2s (&id));
1904 if (NULL != peer->dhtget)
1906 GNUNET_DHT_get_stop (peer->dhtget);
1908 p = peer->path_head;
1912 GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
1916 tunnel_destroy_empty (peer->tunnel);
1923 * Returns if peer is used (has a tunnel, is neighbor).
1925 * @peer Peer to check.
1927 * @return GNUNET_YES if peer is in use.
1930 peer_is_used (struct MeshPeer *peer)
1932 struct MeshPeerPath *p;
1934 if (NULL != peer->tunnel)
1937 for (p = peer->path_head; NULL != p; p = p->next)
1946 * Iterator over all the peers to get the oldest timestamp.
1948 * @param cls Closure (unsued).
1949 * @param key ID of the peer.
1950 * @param value Peer_Info of the peer.
1953 peer_get_oldest (void *cls,
1954 const struct GNUNET_HashCode *key,
1957 struct MeshPeer *p = value;
1958 struct GNUNET_TIME_Absolute *abs = cls;
1960 /* Don't count active peers */
1961 if (GNUNET_YES == peer_is_used (p))
1964 if (abs->abs_value_us < p->last_contact.abs_value_us)
1965 abs->abs_value_us = p->last_contact.abs_value_us;
1972 * Iterator over all the peers to remove the oldest entry.
1974 * @param cls Closure (unsued).
1975 * @param key ID of the peer.
1976 * @param value Peer_Info of the peer.
1979 peer_timeout (void *cls,
1980 const struct GNUNET_HashCode *key,
1983 struct MeshPeer *p = value;
1984 struct GNUNET_TIME_Absolute *abs = cls;
1986 if (p->last_contact.abs_value_us == abs->abs_value_us &&
1987 GNUNET_NO == peer_is_used (p))
1997 * Delete oldest unused peer.
2000 peer_delete_oldest (void)
2002 struct GNUNET_TIME_Absolute abs;
2004 abs = GNUNET_TIME_UNIT_FOREVER_ABS;
2006 GNUNET_CONTAINER_multihashmap_iterate (peers,
2009 GNUNET_CONTAINER_multihashmap_iterate (peers,
2016 * Retrieve the MeshPeer stucture associated with the peer, create one
2017 * and insert it in the appropriate structures if the peer is not known yet.
2019 * @param peer Full identity of the peer.
2021 * @return Existing or newly created peer info.
2023 static struct MeshPeer *
2024 peer_get (const struct GNUNET_PeerIdentity *peer_id)
2026 struct MeshPeer *peer;
2028 peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer_id->hashPubKey);
2031 peer = GNUNET_new (struct MeshPeer);
2032 if (GNUNET_CONTAINER_multihashmap_size (peers) > max_peers)
2034 peer_delete_oldest ();
2036 GNUNET_CONTAINER_multihashmap_put (peers, &peer_id->hashPubKey, peer,
2037 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
2038 peer->id = GNUNET_PEER_intern (peer_id);
2040 peer->last_contact = GNUNET_TIME_absolute_get();
2047 * Retrieve the MeshPeer stucture associated with the peer, create one
2048 * and insert it in the appropriate structures if the peer is not known yet.
2050 * @param peer Short identity of the peer.
2052 * @return Existing or newly created peer info.
2054 static struct MeshPeer *
2055 peer_get_short (const GNUNET_PEER_Id peer)
2057 return peer_get (GNUNET_PEER_resolve2 (peer));
2062 * Get a cost of a path for a peer considering existing tunnel connections.
2064 * @param peer Peer towards which the path is considered.
2065 * @param path Candidate path.
2067 * @return Cost of the path (path length + number of overlapping nodes)
2070 peer_get_path_cost (const struct MeshPeer *peer,
2071 const struct MeshPeerPath *path)
2073 struct MeshConnection *c;
2074 unsigned int overlap;
2082 GNUNET_assert (NULL != peer->tunnel);
2084 for (i = 0; i < path->length; i++)
2086 for (c = peer->tunnel->connection_head; NULL != c; c = c->next)
2088 for (j = 0; j < c->path->length; j++)
2090 if (path->peers[i] == c->path->peers[j])
2098 return (path->length + overlap) * (path->score * -1);
2103 * Choose the best path towards a peer considering the tunnel properties.
2105 * @param peer The destination peer.
2107 * @return Best current known path towards the peer, if any.
2109 static struct MeshPeerPath *
2110 peer_get_best_path (const struct MeshPeer *peer)
2112 struct MeshPeerPath *best_p;
2113 struct MeshPeerPath *p;
2114 struct MeshConnection *c;
2115 unsigned int best_cost;
2118 best_cost = UINT_MAX;
2120 for (p = peer->path_head; NULL != p; p = p->next)
2122 for (c = peer->tunnel->connection_head; NULL != c; c = c->next)
2126 continue; /* If path is in use in a connection, skip it. */
2128 if ((cost = peer_get_path_cost (peer, p)) < best_cost)
2138 queue_is_sendable (struct MeshPeerQueue *q)
2140 struct MeshFlowControl *fc;
2142 /* Is PID-independent? */
2145 case GNUNET_MESSAGE_TYPE_MESH_ACK:
2146 case GNUNET_MESSAGE_TYPE_MESH_POLL:
2150 /* Is PID allowed? */
2151 fc = q->fwd ? &q->c->fwd_fc : &q->c->bck_fc;
2152 if (GMC_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
2160 * Get first sendable message.
2162 * @param peer The destination peer.
2164 * @return Best current known path towards the peer, if any.
2166 static struct MeshPeerQueue *
2167 peer_get_first_message (const struct MeshPeer *peer)
2169 struct MeshPeerQueue *q;
2171 for (q = peer->queue_head; NULL != q; q = q->next)
2173 if (queue_is_sendable (q))
2182 * Try to establish a new connection to this peer in the given tunnel.
2183 * If the peer doesn't have any path to it yet, try to get one.
2184 * If the peer already has some path, send a CREATE CONNECTION towards it.
2186 * @param peer PeerInfo of the peer.
2189 peer_connect (struct MeshPeer *peer)
2191 struct MeshTunnel2 *t;
2192 struct MeshPeerPath *p;
2193 struct MeshConnection *c;
2195 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2196 "peer_connect towards %s\n",
2199 if (NULL != peer->path_head)
2201 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "path exists\n");
2202 p = peer_get_best_path (peer);
2205 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " %u hops\n", p->length);
2206 c = tunnel_use_path (t, p);
2207 send_connection_create (c);
2210 else if (NULL == peer->dhtget)
2212 const struct GNUNET_PeerIdentity *id;
2214 id = GNUNET_PEER_resolve2 (peer->id);
2215 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2216 " Starting DHT GET for peer %s\n", peer2s (peer));
2217 peer->dhtget = GNUNET_DHT_get_start (dht_handle, /* handle */
2218 GNUNET_BLOCK_TYPE_MESH_PEER, /* type */
2219 &id->hashPubKey, /* key to search */
2220 dht_replication_level, /* replication level */
2221 GNUNET_DHT_RO_RECORD_ROUTE |
2222 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
2224 0, /* xquery bits */
2225 &dht_get_id_handler, peer);
2226 if (MESH_TUNNEL_NEW == t->state)
2227 tunnel_change_state (t, MESH_TUNNEL_SEARCHING);
2231 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2232 "There is no path but the DHT GET is already started.\n");
2238 * Get the first transmittable message for a connection.
2240 * @param c Connection.
2241 * @param fwd Is this FWD?
2243 * @return First transmittable message.
2245 static struct MeshPeerQueue *
2246 connection_get_first_message (struct MeshConnection *c, int fwd)
2248 struct MeshPeerQueue *q;
2251 p = connection_get_hop (c, fwd);
2253 for (q = p->queue_head; NULL != q; q = q->next)
2257 if (queue_is_sendable (q))
2267 * @brief Re-initiate traffic on this connection if necessary.
2269 * Check if there is traffic queued towards this peer
2270 * and the core transmit handle is NULL (traffic was stalled).
2271 * If so, call core tmt rdy.
2273 * @param c Connection on which initiate traffic.
2274 * @param fwd Is this about fwd traffic?
2277 connection_unlock_queue (struct MeshConnection *c, int fwd)
2279 struct MeshPeer *peer;
2280 struct MeshPeerQueue *q;
2283 peer = connection_get_hop (c, fwd);
2285 if (NULL != peer->core_transmit)
2286 return; /* Already unlocked */
2288 q = connection_get_first_message (c, fwd);
2290 return; /* Nothing to transmit */
2293 peer->core_transmit =
2294 GNUNET_CORE_notify_transmit_ready (core_handle,
2297 GNUNET_TIME_UNIT_FOREVER_REL,
2298 GNUNET_PEER_resolve2 (peer->id),
2306 * Cancel all transmissions that belong to a certain connection.
2308 * @param c Connection which to cancel.
2309 * @param fwd Cancel fwd traffic?
2312 connection_cancel_queues (struct MeshConnection *c, int fwd)
2314 struct MeshPeerQueue *q;
2315 struct MeshPeerQueue *next;
2316 struct MeshFlowControl *fc;
2317 struct MeshPeer *peer;
2324 fc = fwd ? &c->fwd_fc : &c->bck_fc;
2325 peer = connection_get_hop (c, fwd);
2327 for (q = peer->queue_head; NULL != q; q = next)
2332 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2333 "connection_cancel_queue %s\n",
2334 GNUNET_MESH_DEBUG_M2S (q->type));
2335 queue_destroy (q, GNUNET_YES);
2338 if (NULL == peer->queue_head)
2340 if (NULL != peer->core_transmit)
2342 GNUNET_CORE_notify_transmit_ready_cancel (peer->core_transmit);
2343 peer->core_transmit = NULL;
2345 if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
2347 GNUNET_SCHEDULER_cancel (fc->poll_task);
2348 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2355 * Remove all paths that rely on a direct connection between p1 and p2
2356 * from the peer itself and notify all tunnels about it.
2358 * @param peer PeerInfo of affected peer.
2359 * @param p1 GNUNET_PEER_Id of one peer.
2360 * @param p2 GNUNET_PEER_Id of another peer that was connected to the first and
2363 * TODO: optimize (see below)
2366 peer_remove_path (struct MeshPeer *peer, GNUNET_PEER_Id p1,
2369 struct MeshPeerPath *p;
2370 struct MeshPeerPath *next;
2371 struct MeshPeer *peer_d;
2373 unsigned int destroyed;
2376 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path\n");
2378 for (p = peer->path_head; NULL != p; p = next)
2381 for (i = 0; i < (p->length - 1); i++)
2383 if ((p->peers[i] == p1 && p->peers[i + 1] == p2) ||
2384 (p->peers[i] == p2 && p->peers[i + 1] == p1))
2386 GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
2397 d = tunnel_notify_connection_broken (peer->tunnel, p1, p2);
2399 peer_d = peer_get_short (d); // FIXME
2400 next = peer_get_best_path (peer_d);
2401 tunnel_use_path (peer->tunnel, next);
2402 peer_connect (peer_d);
2404 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path END\n");
2409 * Add the path to the peer and update the path used to reach it in case this
2412 * @param peer_info Destination peer to add the path to.
2413 * @param path New path to add. Last peer must be the peer in arg 1.
2414 * Path will be either used of freed if already known.
2415 * @param trusted Do we trust that this path is real?
2418 peer_add_path (struct MeshPeer *peer_info, struct MeshPeerPath *path,
2421 struct MeshPeerPath *aux;
2425 if ((NULL == peer_info) || (NULL == path))
2428 path_destroy (path);
2431 if (path->peers[path->length - 1] != peer_info->id)
2434 path_destroy (path);
2437 if (2 >= path->length && GNUNET_NO == trusted)
2439 /* Only allow CORE to tell us about direct paths */
2440 path_destroy (path);
2443 for (l = 1; l < path->length; l++)
2445 if (path->peers[l] == myid)
2447 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shortening path by %u\n", l);
2448 for (l2 = 0; l2 < path->length - l; l2++)
2450 path->peers[l2] = path->peers[l + l2];
2455 GNUNET_realloc (path->peers, path->length * sizeof (GNUNET_PEER_Id));
2459 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "adding path [%u] to peer %s\n",
2460 path->length, peer2s (peer_info));
2462 l = path_get_length (path);
2465 path_destroy (path);
2469 GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
2470 for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
2472 l2 = path_get_length (aux);
2475 GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
2476 peer_info->path_tail, aux, path);
2481 if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
2483 path_destroy (path);
2488 GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head, peer_info->path_tail,
2495 * Add the path to the origin peer and update the path used to reach it in case
2496 * this is the shortest.
2497 * The path is given in peer_info -> destination, therefore we turn the path
2498 * upside down first.
2500 * @param peer_info Peer to add the path to, being the origin of the path.
2501 * @param path New path to add after being inversed.
2502 * Path will be either used or freed.
2503 * @param trusted Do we trust that this path is real?
2506 peer_add_path_to_origin (struct MeshPeer *peer_info,
2507 struct MeshPeerPath *path, int trusted)
2510 peer_add_path (peer_info, path, trusted);
2516 * Function called if a connection has been stalled for a while,
2517 * possibly due to a missed ACK. Poll the neighbor about its ACK status.
2519 * @param cls Closure (poll ctx).
2520 * @param tc TaskContext.
2523 connection_poll (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2525 struct MeshFlowControl *fc = cls;
2526 struct GNUNET_MESH_Poll msg;
2527 struct MeshConnection *c;
2529 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2530 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2536 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** Polling!\n");
2537 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** connection %s[%X]\n",
2538 peer2s (c->t->peer), c->id);
2540 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_POLL);
2541 msg.header.size = htons (sizeof (msg));
2542 msg.pid = htonl (fc->last_pid_sent);
2543 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** pid (%u)!\n", fc->last_pid_sent);
2544 send_prebuilt_message_connection (&msg.header, c, NULL, fc == &c->fwd_fc);
2545 fc->poll_time = GNUNET_TIME_STD_BACKOFF (fc->poll_time);
2546 fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
2547 &connection_poll, fc);
2552 * Build a PeerPath from the paths returned from the DHT, reversing the paths
2553 * to obtain a local peer -> destination path and interning the peer ids.
2555 * @return Newly allocated and created path
2557 static struct MeshPeerPath *
2558 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
2559 unsigned int get_path_length,
2560 const struct GNUNET_PeerIdentity *put_path,
2561 unsigned int put_path_length)
2563 struct MeshPeerPath *p;
2569 GNUNET_PEER_change_rc (myid, 1);
2570 i = get_path_length;
2571 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " GET has %d hops.\n", i);
2572 for (i--; i >= 0; i--)
2574 id = GNUNET_PEER_intern (&get_path[i]);
2575 if (p->length > 0 && id == p->peers[p->length - 1])
2577 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Optimizing 1 hop out.\n");
2578 GNUNET_PEER_change_rc (id, -1);
2582 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Adding from GET: %s.\n",
2583 GNUNET_i2s (&get_path[i]));
2585 p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2586 p->peers[p->length - 1] = id;
2589 i = put_path_length;
2590 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " PUT has %d hops.\n", i);
2591 for (i--; i >= 0; i--)
2593 id = GNUNET_PEER_intern (&put_path[i]);
2596 /* PUT path went through us, so discard the path up until now and start
2597 * from here to get a much shorter (and loop-free) path.
2602 if (p->length > 0 && id == p->peers[p->length - 1])
2604 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Optimizing 1 hop out.\n");
2605 GNUNET_PEER_change_rc (id, -1);
2609 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Adding from PUT: %s.\n",
2610 GNUNET_i2s (&put_path[i]));
2612 p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2613 p->peers[p->length - 1] = id;
2617 if (get_path_length > 0)
2618 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " (first of GET: %s)\n",
2619 GNUNET_i2s (&get_path[0]));
2620 if (put_path_length > 0)
2621 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " (first of PUT: %s)\n",
2622 GNUNET_i2s (&put_path[0]));
2623 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " In total: %d hops\n",
2625 for (i = 0; i < p->length; i++)
2627 struct GNUNET_PeerIdentity peer_id;
2629 GNUNET_PEER_resolve (p->peers[i], &peer_id);
2630 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " %u: %s\n", p->peers[i],
2631 GNUNET_i2s (&peer_id));
2639 * Adds a path to the peer_infos of all the peers in the path
2641 * @param p Path to process.
2642 * @param confirmed Whether we know if the path works or not.
2645 path_add_to_peers (struct MeshPeerPath *p, int confirmed)
2649 /* TODO: invert and add */
2650 for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
2651 for (i++; i < p->length; i++)
2653 struct MeshPeer *aux;
2654 struct MeshPeerPath *copy;
2656 aux = peer_get_short (p->peers[i]);
2657 copy = path_duplicate (p);
2658 copy->length = i + 1;
2659 peer_add_path (aux, copy, p->length < 3 ? GNUNET_NO : confirmed);
2665 * Search for a channel among the channels for a client
2667 * @param c the client whose channels to search in
2668 * @param chid the local id of the channel
2670 * @return channel handler, NULL if doesn't exist
2672 static struct MeshChannel *
2673 channel_get_by_local_id (struct MeshClient *c, MESH_ChannelNumber chid)
2675 if (0 == (chid & GNUNET_MESH_LOCAL_CHANNEL_ID_CLI))
2677 GNUNET_break_op (0);
2678 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CHID %X not a local chid\n", chid);
2681 if (chid >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV)
2682 return GNUNET_CONTAINER_multihashmap32_get (c->incoming_channels, chid);
2683 return GNUNET_CONTAINER_multihashmap32_get (c->own_channels, chid);
2687 * Search for a tunnel by global ID using full PeerIdentities.
2689 * @param t Tunnel containing the channel.
2690 * @param chid Public channel number.
2692 * @return channel handler, NULL if doesn't exist
2694 static struct MeshChannel *
2695 channel_get (struct MeshTunnel2 *t, MESH_ChannelNumber chid)
2697 struct MeshChannel *ch;
2702 for (ch = t->channel_head; NULL != ch; ch = ch->next)
2704 if (ch->gid == chid)
2713 * Change the tunnel state.
2715 * @param t Tunnel whose state to change.
2716 * @param state New state.
2719 tunnel_change_state (struct MeshTunnel2* t, enum MeshTunnelState state)
2721 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2722 "Tunnel %s state was %s\n",
2724 GNUNET_MESH_DEBUG_TS2S (t->state));
2725 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2726 "Tunnel %s state is now %s\n",
2728 GNUNET_MESH_DEBUG_TS2S (state));
2734 connection_change_state (struct MeshConnection* c,
2735 enum MeshConnectionState state)
2737 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2738 "Connection %s[%X] state was %s\n",
2739 peer2s (c->t->peer), c->id,
2740 GNUNET_MESH_DEBUG_CS2S (c->state));
2741 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2742 "Connection %s[%X] state is now %s\n",
2743 peer2s (c->t->peer), c->id,
2744 GNUNET_MESH_DEBUG_CS2S (state));
2750 * Add a client to a channel, initializing all needed data structures.
2752 * @param ch Channel to which add the client.
2753 * @param c Client which to add to the channel.
2756 channel_add_client (struct MeshChannel *ch, struct MeshClient *c)
2758 struct MeshTunnel2 *t = ch->t;
2760 if (NULL != ch->dest)
2766 /* Assign local id as destination */
2767 while (NULL != channel_get_by_local_id (c, t->next_local_chid))
2768 t->next_local_chid = (t->next_local_chid + 1) | GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
2769 ch->lid_dest = t->next_local_chid++;
2770 t->next_local_chid = t->next_local_chid | GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
2772 /* Store in client's hashmap */
2774 GNUNET_CONTAINER_multihashmap32_put (c->incoming_channels,
2776 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2785 static struct MeshConnection *
2786 tunnel_use_path (struct MeshTunnel2 *t, struct MeshPeerPath *p)
2788 struct MeshConnection *c;
2789 unsigned int own_pos;
2791 c = connection_new (&t->id, t->next_cid++);
2792 for (own_pos = 0; own_pos < p->length; own_pos++)
2794 if (p->peers[own_pos] == myid)
2797 if (own_pos > p->length - 1)
2800 connection_destroy (c);
2803 c->own_pos = own_pos;
2808 c->fwd_maintenance_task =
2809 GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
2810 &connection_fwd_keepalive, c);
2817 * Notifies a tunnel that a connection has broken that affects at least
2818 * some of its peers. Sends a notification towards the root of the tree.
2819 * In case the peer is the owner of the tree, notifies the client that owns
2820 * the tunnel and tries to reconnect.
2822 * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
2824 * @param t Tunnel affected.
2825 * @param p1 Peer that got disconnected from p2.
2826 * @param p2 Peer that got disconnected from p1.
2828 * @return Short ID of the peer disconnected (either p1 or p2).
2829 * 0 if the tunnel remained unaffected.
2831 static GNUNET_PEER_Id
2832 tunnel_notify_connection_broken (struct MeshTunnel2* t,
2833 GNUNET_PEER_Id p1, GNUNET_PEER_Id p2)
2835 // if (myid != p1 && myid != p2) FIXME
2840 // if (tree_get_predecessor (t->tree) != 0)
2842 // /* We are the peer still connected, notify owner of the disconnection. */
2843 // struct GNUNET_MESH_PathBroken msg;
2844 // struct GNUNET_PeerIdentity neighbor;
2846 // msg.header.size = htons (sizeof (msg));
2847 // msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN);
2848 // GNUNET_PEER_resolve (t->id.oid, &msg.oid);
2849 // msg.tid = htonl (t->id.tid);
2850 // msg.peer1 = my_full_id;
2851 // GNUNET_PEER_resolve (pid, &msg.peer2);
2852 // GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &neighbor);
2853 // send_prebuilt_message (&msg.header, &neighbor, t);
2860 * Send an end-to-end FWD ACK message for the most recent in-sequence payload.
2862 * @param ch Channel this is about.
2863 * @param fwd Is for FWD traffic? (ACK dest->owner)
2866 channel_send_data_ack (struct MeshChannel *ch, int fwd)
2868 struct GNUNET_MESH_DataACK msg;
2869 struct MeshChannelReliability *rel;
2870 struct MeshReliableMessage *copy;
2875 if (GNUNET_NO == ch->reliable)
2880 rel = fwd ? ch->bck_rel : ch->fwd_rel;
2881 mid = fwd ? &ch->mid_recv_fwd : &ch->mid_recv_bck;
2882 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2883 "send_data_ack for %u\n",
2886 msg.header.type = htons (fwd ? GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK :
2887 GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK);
2888 msg.header.size = htons (sizeof (msg));
2889 msg.chid = htonl (ch->gid);
2890 msg.mid = htonl (*mid - 1);
2892 for (copy = rel->head_recv; NULL != copy; copy = copy->next)
2894 delta = copy->mid - *mid;
2897 mask = 0x1LL << delta;
2898 msg.futures |= mask;
2899 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2900 " setting bit for %u (delta %u) (%llX) -> %llX\n",
2901 copy->mid, delta, mask, msg.futures);
2903 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " final futures %llX\n", msg.futures);
2905 send_prebuilt_message_channel (&msg.header, ch, fwd);
2906 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_data_ack END\n");
2911 * Send an ACK informing the predecessor about the available buffer space.
2913 * Note that for fwd ack, the FWD mean forward *traffic* (root->dest),
2914 * the ACK itself goes "back" (dest->root).
2916 * @param c Connection on which to send the ACK.
2917 * @param fwd Is this FWD ACK? (Going dest->owner)
2920 connection_send_ack (struct MeshConnection *c, int fwd)
2922 struct MeshFlowControl *next_fc;
2923 struct MeshFlowControl *prev_fc;
2927 next_fc = fwd ? &c->fwd_fc : &c->bck_fc;
2928 prev_fc = fwd ? &c->bck_fc : &c->fwd_fc;
2930 /* Check if we need to transmit the ACK */
2931 if (prev_fc->last_ack_sent - prev_fc->last_pid_recv > 3)
2933 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer > 3\n");
2934 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2935 " last pid recv: %u, last ack sent: %u\n",
2936 prev_fc->last_pid_recv, prev_fc->last_ack_sent);
2940 /* Ok, ACK might be necessary, what PID to ACK? */
2941 delta = next_fc->queue_max - next_fc->queue_n;
2942 ack = prev_fc->last_pid_recv + delta;
2943 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", ack);
2944 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2945 " last pid %u, last ack %u, qmax %u, q %u\n",
2946 prev_fc->last_pid_recv, prev_fc->last_ack_sent,
2947 next_fc->queue_max, next_fc->queue_n);
2948 if (ack == prev_fc->last_ack_sent)
2950 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not needed\n");
2954 prev_fc->last_ack_sent = ack;
2955 send_ack (c, ack, fwd);
2960 * Send an ACK informing the client about available buffer space.
2962 * Note that although the name is fwd_ack, the FWD mean forward *traffic*,
2963 * the ACK itself goes "back" (towards root).
2965 * @param ch Channel on which to send the ACK, NULL if unknown.
2966 * @param fwd Is this FWD ACK? (Going dest->owner)
2969 // channel_send_ack (struct MeshChannel *ch, uint16_t type, int fwd)
2971 // struct MeshChannelReliability *rel;
2972 // struct MeshFlowControl *next_fc;
2973 // struct MeshFlowControl *prev_fc;
2974 // struct MeshClient *c;
2975 // struct MeshClient *o;
2976 // GNUNET_PEER_Id hop;
2977 // uint32_t delta_mid;
2981 // rel = fwd ? ch->fwd_rel : ch->bck_rel;
2982 // c = fwd ? ch->client : ch->owner;
2983 // o = fwd ? ch->owner : ch->client;
2984 // hop = fwd ? connection_get_prev_hop (cn) : connection_get_next_hop (cn);
2985 // next_fc = fwd ? &t->next_fc : &t->prev_fc;
2986 // prev_fc = fwd ? &t->prev_fc : &t->next_fc;
2990 // case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
2991 // case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
2992 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2993 // "ACK due to %s\n",
2994 // GNUNET_MESH_DEBUG_M2S (type));
2995 // if (GNUNET_YES == t->nobuffer && (GNUNET_NO == t->reliable || NULL == c))
2997 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, nobuffer\n");
3000 // if (GNUNET_YES == t->reliable && NULL != c)
3001 // tunnel_send_data_ack (t, fwd);
3003 // case GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK:
3004 // case GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK:
3005 // case GNUNET_MESSAGE_TYPE_MESH_ACK:
3006 // case GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK:
3008 // case GNUNET_MESSAGE_TYPE_MESH_POLL:
3009 // case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
3010 // t->force_ack = GNUNET_YES;
3013 // GNUNET_break (0);
3016 // /* Check if we need to transmit the ACK */
3018 // prev_fc->last_ack_sent - prev_fc->last_pid_recv > 3 &&
3019 // GNUNET_NO == t->force_ack)
3021 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer free\n");
3022 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3023 // " last pid recv: %u, last ack sent: %u\n",
3024 // prev_fc->last_pid_recv, prev_fc->last_ack_sent);
3028 // /* Ok, ACK might be necessary, what PID to ACK? */
3029 // delta = t->queue_max - next_fc->queue_n;
3030 // if (NULL != o && GNUNET_YES == t->reliable && NULL != rel->head_sent)
3031 // delta_mid = rel->mid_sent - rel->head_sent->mid;
3034 // if (0 > delta || (GNUNET_YES == t->reliable &&
3036 // (10 < rel->n_sent || 64 <= delta_mid)))
3038 // if (NULL != o && delta > 1)
3040 // ack = prev_fc->last_pid_recv + delta;
3041 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", ack);
3042 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3043 // " last pid %u, last ack %u, qmax %u, q %u\n",
3044 // prev_fc->last_pid_recv, prev_fc->last_ack_sent,
3045 // t->queue_max, next_fc->queue_n);
3046 // if (ack == prev_fc->last_ack_sent && GNUNET_NO == t->force_ack)
3048 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not needed\n");
3052 // prev_fc->last_ack_sent = ack;
3054 // send_local_ack (t, o, fwd);
3055 // else if (0 != hop)
3056 // send_ack (t, hop, ack);
3058 // GNUNET_break (GNUNET_YES == t->destroy);
3059 // t->force_ack = GNUNET_NO;
3064 * Modify the mesh message TID from global to local and send to client.
3066 * @param ch Channel on which to send the message.
3067 * @param msg Message to modify and send.
3068 * @param c Client to send to.
3069 * @param tid Tunnel ID to use (c can be both owner and client).
3072 channel_send_client_to_tid (struct MeshChannel *ch,
3073 const struct GNUNET_MESH_Data *msg,
3074 struct MeshClient *c, MESH_ChannelNumber id)
3076 struct GNUNET_MESH_LocalData *copy;
3077 uint16_t size = ntohs (msg->header.size) - sizeof (struct GNUNET_MESH_Data);
3078 char cbuf[size + sizeof (struct GNUNET_MESH_LocalData)];
3080 if (size < sizeof (struct GNUNET_MessageHeader))
3082 GNUNET_break_op (0);
3090 copy = (struct GNUNET_MESH_LocalData *) cbuf;
3091 memcpy (©[1], &msg[1], size);
3092 copy->header.size = htons (sizeof (struct GNUNET_MESH_LocalData) + size);
3093 copy->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA);
3094 copy->id = htonl (id);
3095 GNUNET_SERVER_notification_context_unicast (nc, c->handle,
3096 ©->header, GNUNET_NO);
3100 * Modify the data message ID from global to local and send to client.
3102 * @param ch Channel on which to send the message.
3103 * @param msg Message to modify and send.
3104 * @param fwd Forward?
3107 channel_send_client_data (struct MeshChannel *ch,
3108 const struct GNUNET_MESH_Data *msg,
3112 channel_send_client_to_tid (ch, msg, ch->dest, ch->lid_dest);
3114 channel_send_client_to_tid (ch, msg, ch->root, ch->lid_root);
3119 * Send a buffered message to the client, for in order delivery or
3120 * as result of client ACK.
3122 * @param ch Channel on which to empty the message buffer.
3123 * @param c Client to send to.
3124 * @param rel Reliability structure to corresponding peer.
3125 * If rel == bck_rel, this is FWD data.
3128 channel_send_client_buffered_data (struct MeshChannel *ch,
3129 struct MeshClient *c,
3130 struct MeshChannelReliability *rel)
3132 struct MeshReliableMessage *copy;
3135 if (GNUNET_NO == rel->client_ready)
3137 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client not ready\n");
3141 mid = rel == ch->bck_rel ? &ch->mid_recv_fwd : &ch->mid_recv_bck;
3143 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data\n");
3144 copy = rel->head_recv;
3147 if (copy->mid == *mid || GNUNET_NO == ch->reliable)
3149 struct GNUNET_MESH_Data *msg = (struct GNUNET_MESH_Data *) ©[1];
3151 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3152 " have %u! now expecting %u\n",
3153 copy->mid, *mid + 1);
3154 channel_send_client_data (ch, msg, (rel == ch->bck_rel));
3157 GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
3162 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3163 " reliable && don't have %u, next is %u\n",
3169 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data END\n");
3174 * We have received a message out of order, or the client is not ready.
3175 * Buffer it until we receive an ACK from the client or the missing
3176 * message from the channel.
3178 * @param msg Message to buffer.
3179 * @param rel Reliability data to the corresponding direction.
3182 channel_rel_add_buffered_data (const struct GNUNET_MESH_Data *msg,
3183 struct MeshChannelReliability *rel)
3185 struct MeshReliableMessage *copy;
3186 struct MeshReliableMessage *prev;
3190 size = ntohs (msg->header.size);
3191 mid = ntohl (msg->mid);
3192 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data %u\n", mid);
3194 copy = GNUNET_malloc (sizeof (*copy) + size);
3197 memcpy (©[1], msg, size);
3201 // FIXME do something better than O(n), although n < 64...
3202 // FIXME start from the end (most messages are the latest ones)
3203 for (prev = rel->head_recv; NULL != prev; prev = prev->next)
3205 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " prev %u\n", prev->mid);
3206 if (GMC_is_pid_bigger (prev->mid, mid))
3208 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " bingo!\n");
3209 GNUNET_CONTAINER_DLL_insert_before (rel->head_recv, rel->tail_recv,
3214 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " insert at tail!\n");
3215 GNUNET_CONTAINER_DLL_insert_tail (rel->head_recv, rel->tail_recv, copy);
3216 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data END\n");
3221 * Destroy a reliable message after it has been acknowledged, either by
3222 * direct mid ACK or bitfield. Updates the appropriate data structures and
3223 * timers and frees all memory.
3225 * @param copy Message that is no longer needed: remote peer got it.
3228 rel_message_free (struct MeshReliableMessage *copy)
3230 struct MeshChannelReliability *rel;
3231 struct GNUNET_TIME_Relative time;
3234 time = GNUNET_TIME_absolute_get_duration (copy->timestamp);
3235 rel->expected_delay.rel_value_us *= 7;
3236 rel->expected_delay.rel_value_us += time.rel_value_us;
3237 rel->expected_delay.rel_value_us /= 8;
3239 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Freeing %u\n", copy->mid);
3240 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " n_sent %u\n", rel->n_sent);
3241 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! took %s\n",
3242 GNUNET_STRINGS_relative_time_to_string (time, GNUNET_NO));
3243 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! new expected delay %s\n",
3244 GNUNET_STRINGS_relative_time_to_string (rel->expected_delay,
3246 rel->retry_timer = rel->expected_delay;
3247 GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
3253 * Destroy all reliable messages queued for a channel,
3254 * during a channel destruction.
3255 * Frees the reliability structure itself.
3257 * @param rel Reliability data for a channel.
3260 channel_rel_free_all (struct MeshChannelReliability *rel)
3262 struct MeshReliableMessage *copy;
3263 struct MeshReliableMessage *next;
3268 for (copy = rel->head_recv; NULL != copy; copy = next)
3271 GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
3274 for (copy = rel->head_sent; NULL != copy; copy = next)
3277 GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
3280 if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
3281 GNUNET_SCHEDULER_cancel (rel->retry_task);
3287 * Mark future messages as ACK'd.
3289 * @param rel Reliability data.
3290 * @param msg DataACK message with a bitfield of future ACK'd messages.
3293 channel_rel_free_sent (struct MeshChannelReliability *rel,
3294 const struct GNUNET_MESH_DataACK *msg)
3296 struct MeshReliableMessage *copy;
3297 struct MeshReliableMessage *next;
3304 bitfield = msg->futures;
3305 mid = ntohl (msg->mid);
3306 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3307 "free_sent_reliable %u %llX\n",
3309 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3310 " rel %p, head %p\n",
3311 rel, rel->head_sent);
3312 for (i = 0, copy = rel->head_sent;
3313 i < 64 && NULL != copy && 0 != bitfield;
3316 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3317 " trying bit %u (mid %u)\n",
3320 if (0 == (bitfield & mask))
3323 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " set!\n");
3324 /* Bit was set, clear the bit from the bitfield */
3327 /* The i-th bit was set. Do we have that copy? */
3328 /* Skip copies with mid < target */
3329 target = mid + i + 1;
3330 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " target %u\n", target);
3331 while (NULL != copy && GMC_is_pid_bigger (target, copy->mid))
3334 /* Did we run out of copies? (previously freed, it's ok) */
3337 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "run out of copies...\n");
3341 /* Did we overshoot the target? (previously freed, it's ok) */
3342 if (GMC_is_pid_bigger (copy->mid, target))
3344 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " next copy %u\n", copy->mid);
3348 /* Now copy->mid == target, free it */
3350 rel_message_free (copy);
3353 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "free_sent_reliable END\n");
3358 * We haven't received an ACK after a certain time: restransmit the message.
3360 * @param cls Closure (MeshReliableMessage with the message to restransmit)
3361 * @param tc TaskContext.
3364 channel_retransmit_message (void *cls,
3365 const struct GNUNET_SCHEDULER_TaskContext *tc)
3367 struct MeshChannelReliability *rel = cls;
3368 struct MeshReliableMessage *copy;
3369 struct MeshPeerQueue *q;
3370 struct MeshChannel *ch;
3371 struct MeshConnection *c;
3372 struct GNUNET_MESH_Data *payload;
3373 struct MeshPeer *hop;
3376 rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
3377 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3381 copy = rel->head_sent;
3388 /* Search the message to be retransmitted in the outgoing queue.
3389 * Check only the queue for the connection that is going to be used,
3390 * if the message is stuck in some other connection's queue we shouldn't
3392 * - cancelling it and sending the new one doesn't guarantee it's delivery,
3393 * the old connection could be temporary stalled or the queue happened to
3394 * be long at time of insertion.
3395 * - not sending the new one could cause terrible delays the old connection
3398 payload = (struct GNUNET_MESH_Data *) ©[1];
3399 fwd = (rel == ch->fwd_rel);
3400 c = tunnel_get_connection (ch->t, fwd);
3401 hop = connection_get_hop (c, fwd);
3402 for (q = hop->queue_head; NULL != q; q = q->next)
3404 if (ntohs (payload->header.type) == q->type && ch == q->ch)
3406 struct GNUNET_MESH_Data *queued_data = q->cls;
3408 if (queued_data->mid == payload->mid)
3413 /* Message not found in the queue that we are going to use. */
3416 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! RETRANSMIT %u\n", copy->mid);
3418 send_prebuilt_message_channel (&payload->header, ch, ch->fwd_rel == rel);
3419 GNUNET_STATISTICS_update (stats, "# data retransmitted", 1, GNUNET_NO);
3423 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! ALREADY IN QUEUE %u\n", copy->mid);
3426 rel->retry_timer = GNUNET_TIME_STD_BACKOFF (rel->retry_timer);
3427 rel->retry_task = GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
3428 &channel_retransmit_message,
3435 * Send ACK on one or more connections due to buffer space to the client.
3438 channel_send_ack (struct MeshChannel *ch, uint32_t buffer, int fwd)
3440 struct MeshTunnel2 *t = ch->t;
3441 struct MeshConnection *c;
3442 struct MeshFlowControl *fc;
3447 /* Count connections, how many messages are already allowed */
3448 for (cs = 0, allowed = 0, c = t->connection_head; NULL != c; c = c->next)
3450 fc = fwd ? &c->fwd_fc : &c->bck_fc;
3451 if (GMC_is_pid_bigger(fc->last_pid_recv, fc->last_ack_sent))
3456 allowed += fc->last_ack_sent - fc->last_pid_recv;
3460 /* Make sure there is no overflow */
3461 if (allowed > buffer)
3467 /* Authorize connections to send more data */
3468 to_allow = buffer - allowed;
3469 for (c = t->connection_head; NULL != c && to_allow > 0; c = c->next)
3471 fc = fwd ? &c->fwd_fc : &c->bck_fc;
3472 if (fc->last_ack_sent - fc->last_pid_recv > 64 / 3)
3476 send_ack (c, fc->last_ack_sent + 1, fwd);
3480 GNUNET_break (to_allow == 0);
3485 * Send keepalive packets for a connection.
3487 * @param c Connection to keep alive..
3488 * @param fwd Is this a FWD keepalive? (owner -> dest).
3491 connection_keepalive (struct MeshConnection *c, int fwd)
3493 struct GNUNET_MESH_ConnectionKeepAlive *msg;
3494 size_t size = sizeof (struct GNUNET_MESH_ConnectionKeepAlive);
3498 type = fwd ? GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE :
3499 GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE;
3501 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3502 "sending %s keepalive for connection %s[%d]\n",
3503 fwd ? "FWD" : "BCK",
3504 peer2s (c->t->peer),
3507 msg = (struct GNUNET_MESH_ConnectionKeepAlive *) cbuf;
3508 msg->header.size = htons (size);
3509 msg->header.type = htons (type);
3510 msg->cid = htonl (c->id);
3511 msg->tid = c->t->id;
3513 send_prebuilt_message_connection (&msg->header, c, NULL, fwd);
3518 * Send CONNECTION_{CREATE/ACK} packets for a connection.
3520 * @param c Connection for which to send the message.
3521 * @param fwd If GNUNET_YES, send CREATE, otherwise send ACK.
3524 connection_recreate (struct MeshConnection *c, int fwd)
3526 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "sending connection recreate\n");
3528 send_connection_create (c);
3530 send_connection_ack (c);
3535 * Generic connection timer management.
3536 * Depending on the role of the peer in the connection will send the
3537 * appropriate message (build or keepalive)
3539 * @param c Conncetion to maintain.
3540 * @param fwd Is FWD?
3543 connection_maintain (struct MeshConnection *c, int fwd)
3545 if (MESH_TUNNEL_SEARCHING == c->t->state)
3547 /* TODO DHT GET with RO_BART */
3552 case MESH_CONNECTION_NEW:
3554 case MESH_CONNECTION_SENT:
3555 connection_recreate (c, fwd);
3557 case MESH_CONNECTION_READY:
3558 connection_keepalive (c, fwd);
3567 connection_fwd_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3569 struct MeshConnection *c = cls;
3571 c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
3572 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3575 connection_maintain (c, GNUNET_YES);
3576 c->fwd_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
3577 &connection_fwd_keepalive,
3583 connection_bck_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3585 struct MeshConnection *c = cls;
3587 c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
3588 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3591 connection_maintain (c, GNUNET_NO);
3592 c->bck_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
3593 &connection_bck_keepalive,
3599 * Send a message to all peers in this connection that the connection
3600 * is no longer valid.
3602 * If some peer should not receive the message, it should be zero'ed out
3603 * before calling this function.
3605 * @param c The connection whose peers to notify.
3608 connection_send_destroy (struct MeshConnection *c)
3610 struct GNUNET_MESH_ConnectionDestroy msg;
3612 msg.header.size = htons (sizeof (msg));
3613 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);;
3614 msg.cid = htonl (c->id);
3616 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3617 " sending tunnel destroy for connection %s[%X]\n",
3618 peer2s (c->t->peer),
3621 send_prebuilt_message_connection (&msg.header, c, NULL, GNUNET_YES);
3622 send_prebuilt_message_connection (&msg.header, c, NULL, GNUNET_NO);
3623 c->destroy = GNUNET_YES;
3628 * Send a message to all clients (local and remote) of this channel
3629 * notifying that the channel is no longer valid.
3631 * If some peer or client should not receive the message,
3632 * should be zero'ed out before calling this function.
3634 * @param ch The channel whose clients to notify.
3637 channel_send_destroy (struct MeshChannel *ch)
3639 struct GNUNET_MESH_ChannelDestroy msg;
3641 msg.header.size = htons (sizeof (msg));
3642 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY);
3643 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3644 " sending tunnel destroy for channel %s:%X\n",
3645 peer2s (ch->t->peer),
3648 if (NULL != ch->root)
3650 msg.chid = htonl (ch->lid_root);
3651 send_local_channel_destroy (ch, GNUNET_NO);
3655 msg.chid = htonl (ch->gid);
3656 send_prebuilt_message_channel (&msg.header, ch, GNUNET_NO);
3659 if (NULL != ch->dest)
3661 msg.chid = htonl (ch->lid_dest);
3662 send_local_channel_destroy (ch, GNUNET_YES);
3666 msg.chid = htonl (ch->gid);
3667 send_prebuilt_message_channel (&msg.header, ch, GNUNET_YES);
3675 * @param tid Tunnel ID.
3677 static struct MeshTunnel2 *
3678 tunnel_new (const struct GNUNET_HashCode *tid)
3680 struct MeshTunnel2 *t;
3682 t = GNUNET_new (struct MeshTunnel2);
3684 t->next_chid = GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
3686 GNUNET_CONTAINER_multihashmap_put (tunnels, tid, t,
3687 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3701 * @param tid Tunnel ID.
3703 static struct MeshTunnel2 *
3704 tunnel_get (const struct GNUNET_HashCode *tid)
3706 return GNUNET_CONTAINER_multihashmap_get (tunnels, tid);
3711 * Add a connection to a tunnel.
3714 * @param c Connection.
3717 tunnel_add_connection (struct MeshTunnel2 *t, struct MeshConnection *c)
3720 GNUNET_CONTAINER_DLL_insert_tail (t->connection_head, t->connection_tail, c);
3725 * Initialize a Flow Control structure to the initial state.
3727 * @param fc Flow Control structure to initialize.
3730 fc_init (struct MeshFlowControl *fc)
3732 fc->last_pid_sent = (uint32_t) -1; /* Next (expected) = 0 */
3733 fc->last_pid_recv = (uint32_t) -1;
3734 fc->last_ack_sent = (uint32_t) 0;
3735 fc->last_ack_recv = (uint32_t) 0;
3736 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
3737 fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
3739 fc->queue_max = (max_msgs_queue / max_connections) + 1;
3743 static struct MeshConnection *
3744 connection_new (struct GNUNET_HashCode *tid, uint32_t cid)
3746 struct MeshConnection *c;
3747 struct MeshTunnel2 *t;
3749 t = tunnel_get (tid);
3752 t = tunnel_new (tid);
3760 c = GNUNET_new (struct MeshConnection);
3762 fc_init (&c->fwd_fc);
3763 fc_init (&c->bck_fc);
3764 tunnel_add_connection (t, c);
3771 * Find a connection.
3773 * @param tid Tunnel ID.
3774 * @param cid Connection ID.
3776 static struct MeshConnection *
3777 connection_get (const struct GNUNET_HashCode *tid, uint32_t cid)
3779 struct MeshConnection *c;
3780 struct MeshTunnel2 *t;
3782 t = tunnel_get (tid);
3783 for (c = t->connection_head; NULL != c; c = c->next)
3792 connection_destroy (struct MeshConnection *c)
3797 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying connection %s[%X]\n",
3798 peer2s (c->t->peer),
3801 connection_cancel_queues (c, GNUNET_YES);
3802 connection_cancel_queues (c, GNUNET_NO);
3804 if (GNUNET_SCHEDULER_NO_TASK != c->fwd_maintenance_task)
3805 GNUNET_SCHEDULER_cancel (c->fwd_maintenance_task);
3806 if (GNUNET_SCHEDULER_NO_TASK != c->bck_maintenance_task)
3807 GNUNET_SCHEDULER_cancel (c->bck_maintenance_task);
3809 GNUNET_CONTAINER_DLL_remove (c->t->connection_head, c->t->connection_tail, c);
3811 GNUNET_STATISTICS_update (stats, "# connections", -1, GNUNET_NO);
3817 tunnel_destroy (struct MeshTunnel2 *t)
3819 struct MeshConnection *c;
3820 struct MeshConnection *next;
3825 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n",
3828 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &t->id, t))
3831 for (c = t->connection_head; NULL != c; c = next)
3834 connection_destroy (c);
3837 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
3844 * Tunnel is empty: destroy it.
3846 * Notifies all connections about the destruction.
3848 * @param t Tunnel to destroy.
3851 tunnel_destroy_empty (struct MeshTunnel2 *t)
3853 struct MeshConnection *c;
3855 for (c = t->connection_head; NULL != c; c = c->next)
3857 if (GNUNET_NO == c->destroy)
3858 connection_send_destroy (c);
3861 if (0 == t->pending_messages)
3864 t->destroy = GNUNET_YES;
3869 * Destroy tunnel if empty (no more channels).
3871 * @param t Tunnel to destroy if empty.
3874 tunnel_destroy_if_empty (struct MeshTunnel2 *t)
3876 if (NULL != t->channel_head)
3879 tunnel_destroy_empty (t);
3884 * Destroy a channel and free all resources.
3886 * @param ch Channel to destroy.
3889 channel_destroy (struct MeshChannel *ch)
3891 struct MeshClient *c;
3899 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap32_remove (c->own_channels,
3910 GNUNET_CONTAINER_multihashmap32_remove (c->incoming_channels,
3917 if (GNUNET_YES == ch->reliable)
3919 channel_rel_free_all (ch->fwd_rel);
3920 channel_rel_free_all (ch->bck_rel);
3923 GNUNET_CONTAINER_DLL_remove (ch->t->channel_head, ch->t->channel_tail, ch);
3924 GNUNET_STATISTICS_update (stats, "# channels", -1, GNUNET_NO);
3930 * Create a new channel.
3932 * @param t Tunnel this channel is in.
3933 * @param owner Client that owns the channel, NULL for foreign channels.
3934 * @param lid_root Local ID for root client.
3936 * @return A new initialized channel. NULL on error.
3938 static struct MeshChannel *
3939 channel_new (struct MeshTunnel2 *t,
3940 struct MeshClient *owner, MESH_ChannelNumber lid_root)
3942 struct MeshChannel *ch;
3944 ch = GNUNET_new (struct MeshChannel);
3946 ch->lid_root = lid_root;
3949 GNUNET_CONTAINER_DLL_insert (t->channel_head, t->channel_tail, ch);
3951 GNUNET_STATISTICS_update (stats, "# channels", 1, GNUNET_NO);
3955 while (NULL != channel_get_by_local_id (owner, t->next_chid))
3956 t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
3957 ch->gid = t->next_chid;
3958 t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
3961 GNUNET_CONTAINER_multihashmap32_put (owner->own_channels, lid_root, ch,
3962 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
3965 channel_destroy (ch);
3966 GNUNET_SERVER_receive_done (owner->handle, GNUNET_SYSERR);
3976 * Set options in a channel, extracted from a bit flag field
3978 * @param ch Channel to set options to.
3979 * @param options Bit array in host byte order.
3982 channel_set_options (struct MeshChannel *ch, uint32_t options)
3984 ch->nobuffer = (options & GNUNET_MESH_OPTION_NOBUFFER) != 0 ?
3985 GNUNET_YES : GNUNET_NO;
3986 ch->reliable = (options & GNUNET_MESH_OPTION_RELIABLE) != 0 ?
3987 GNUNET_YES : GNUNET_NO;
3992 * Iterator for deleting each channel whose client endpoint disconnected.
3994 * @param cls Closure (client that has disconnected).
3995 * @param key The local channel id (used to access the hashmap).
3996 * @param value The value stored at the key (channel to destroy).
3998 * @return GNUNET_OK, keep iterating.
4001 channel_destroy_iterator (void *cls,
4005 struct MeshChannel *ch = value;
4006 struct MeshClient *c = cls;
4007 struct MeshTunnel2 *t;
4009 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4010 " Channel %X (%X / %X) destroy, due to client %u shutdown.\n",
4011 ch->gid, ch->lid_root, ch->lid_dest, c->id);
4015 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is destination.\n", c->id);
4020 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is owner.\n", c->id);
4025 channel_send_destroy (ch);
4026 channel_destroy (ch);
4027 tunnel_destroy_if_empty (t);
4034 * Remove client's ports from the global hashmap on disconnect.
4036 * @param cls Closure (unused).
4038 * @param value Client structure.
4040 * @return GNUNET_OK, keep iterating.
4043 client_release_ports (void *cls,
4049 res = GNUNET_CONTAINER_multihashmap32_remove (ports, key, value);
4050 if (GNUNET_YES != res)
4053 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4054 "Port %u by client %p was not registered.\n",
4062 * Timeout function due to lack of keepalive/traffic from the owner.
4063 * Destroys connection if called.
4065 * @param cls Closure (connection to destroy).
4066 * @param tc TaskContext.
4069 connection_fwd_timeout (void *cls,
4070 const struct GNUNET_SCHEDULER_TaskContext *tc)
4072 struct MeshConnection *c = cls;
4074 c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4075 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4077 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4078 "Connection %s[%X] FWD timed out. Destroying.\n",
4079 peer2s (c->t->peer),
4082 if (NULL != c->t->channel_head) /* If local, leave TODO review */
4085 connection_destroy (c);
4090 * Timeout function due to lack of keepalive/traffic from the destination.
4091 * Destroys connection if called.
4093 * @param cls Closure (connection to destroy).
4094 * @param tc TaskContext
4097 connection_bck_timeout (void *cls,
4098 const struct GNUNET_SCHEDULER_TaskContext *tc)
4100 struct MeshConnection *c = cls;
4102 c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4103 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4106 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4107 "Connection %s[%X] FWD timed out. Destroying.\n",
4108 peer2s (c->t->peer),
4111 if (NULL != c->t->channel_head) /* If local, leave TODO review */
4114 connection_destroy (c);
4119 * Resets the connection timeout task, some other message has done the
4121 * - For the first peer on the direction this means to send
4122 * a keepalive or a path confirmation message (either create or ACK).
4123 * - For all other peers, this means to destroy the connection,
4124 * due to lack of activity.
4125 * Starts the tiemout if no timeout was running (connection just created).
4127 * @param c Connection whose timeout to reset.
4128 * @param fwd Is this forward?
4130 * TODO use heap to improve efficiency of scheduler.
4133 connection_reset_timeout (struct MeshConnection *c, int fwd)
4135 GNUNET_SCHEDULER_TaskIdentifier *ti;
4136 GNUNET_SCHEDULER_Task f;
4138 ti = fwd ? &c->fwd_maintenance_task : &c->bck_maintenance_task;
4140 if (GNUNET_SCHEDULER_NO_TASK != *ti)
4141 GNUNET_SCHEDULER_cancel (*ti);
4143 if (NULL != c->t->channel_head) /* Endpoint */
4145 f = fwd ? &connection_fwd_keepalive : &connection_bck_keepalive;
4146 *ti = GNUNET_SCHEDULER_add_delayed (refresh_connection_time, f, c);
4150 struct GNUNET_TIME_Relative delay;
4152 delay = GNUNET_TIME_relative_multiply (refresh_connection_time, 4);
4153 f = fwd ? &connection_fwd_timeout : &connection_bck_timeout;
4154 *ti = GNUNET_SCHEDULER_add_delayed (delay, f, c);
4160 * Iterator to notify all connections of a broken link. Mark connections
4161 * to destroy after all traffic has been sent.
4163 * @param cls Closure (peer disconnected).
4164 * @param key Current key code (tid).
4165 * @param value Value in the hash map (connection).
4167 * @return GNUNET_YES if we should continue to iterate,
4171 connection_broken (void *cls,
4172 const struct GNUNET_HashCode *key,
4175 struct MeshPeer *peer = cls;
4176 struct MeshConnection *c = value;
4177 struct GNUNET_MESH_ConnectionBroken msg;
4180 fwd = peer == connection_get_prev_hop (c);
4181 connection_cancel_queues (c, !fwd);
4183 msg.header.size = htons (sizeof (struct GNUNET_MESH_ConnectionBroken));
4184 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN);
4185 msg.cid = htonl (c->id);
4187 msg.peer1 = my_full_id;
4188 msg.peer2 = *GNUNET_PEER_resolve2 (peer->id);
4189 send_prebuilt_message_connection (&msg.header, c, NULL, fwd);
4190 c->destroy = GNUNET_YES;
4195 /******************************************************************************/
4196 /**************** MESH NETWORK HANDLER HELPERS ***********************/
4197 /******************************************************************************/
4200 * Free a transmission that was already queued with all resources
4201 * associated to the request.
4203 * @param queue Queue handler to cancel.
4204 * @param clear_cls Is it necessary to free associated cls?
4207 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
4209 struct MeshPeer *peer;
4210 struct MeshFlowControl *fc;
4215 fc = fwd ? &queue->c->fwd_fc : &queue->c->bck_fc;
4217 if (GNUNET_YES == clear_cls)
4219 switch (queue->type)
4221 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
4222 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "destroying CONNECTION_DESTROY\n");
4223 GNUNET_break (GNUNET_YES == queue->c->destroy);
4225 case GNUNET_MESSAGE_TYPE_MESH_FWD:
4226 case GNUNET_MESSAGE_TYPE_MESH_BCK:
4227 case GNUNET_MESSAGE_TYPE_MESH_ACK:
4228 case GNUNET_MESSAGE_TYPE_MESH_POLL:
4229 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
4230 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " prebuilt message\n");
4231 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type %s\n",
4232 GNUNET_MESH_DEBUG_M2S (queue->type));
4235 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
4236 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type create path\n");
4241 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, " type %s unknown!\n",
4242 GNUNET_MESH_DEBUG_M2S (queue->type));
4244 GNUNET_free_non_null (queue->cls);
4246 GNUNET_CONTAINER_DLL_remove (peer->queue_head, peer->queue_tail, queue);
4250 if (NULL != queue->c)
4252 queue->c->pending_messages--;
4253 if (NULL != queue->c->t)
4255 queue->c->t->pending_messages--;
4259 GNUNET_free (queue);
4264 queue_send (void *cls, size_t size, void *buf)
4266 struct MeshPeer *peer = cls;
4267 struct MeshFlowControl *fc;
4268 struct MeshConnection *c;
4269 struct GNUNET_MessageHeader *msg;
4270 struct MeshPeerQueue *queue;
4271 struct MeshTunnel2 *t;
4272 const struct GNUNET_PeerIdentity *dst_id;
4278 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Queue send\n");
4280 if (NULL == buf || 0 == size)
4282 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Buffer size 0.\n");
4287 queue = peer_get_first_message (peer);
4290 GNUNET_break (0); /* Core tmt_rdy should've been canceled */
4293 queue->peer->core_transmit = NULL;
4296 fc = fwd ? &c->fwd_fc : &c->bck_fc;
4299 dst_id = GNUNET_PEER_resolve2 (peer->id);
4300 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* towards %s\n", GNUNET_i2s (dst_id));
4301 /* Check if buffer size is enough for the message */
4302 if (queue->size > size)
4304 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* not enough room, reissue\n");
4305 peer->core_transmit =
4306 GNUNET_CORE_notify_transmit_ready (core_handle,
4309 GNUNET_TIME_UNIT_FOREVER_REL,
4316 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* size ok\n");
4318 t = (NULL != c) ? c->t : NULL;
4322 switch (queue->type)
4324 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
4325 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
4326 case GNUNET_MESSAGE_TYPE_MESH_FWD:
4327 case GNUNET_MESSAGE_TYPE_MESH_BCK:
4328 case GNUNET_MESSAGE_TYPE_MESH_ACK:
4329 case GNUNET_MESSAGE_TYPE_MESH_POLL:
4330 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4332 GNUNET_MESH_DEBUG_M2S (queue->type));
4334 case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4335 case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4336 data_size = send_core_data_raw (queue->cls, size, buf);
4337 msg = (struct GNUNET_MessageHeader *) buf;
4338 type = ntohs (msg->type);
4340 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
4341 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* path create\n");
4342 if (NULL != c->t->channel_head)
4343 data_size = send_core_connection_create (queue->cls, size, buf);
4345 data_size = send_core_data_raw (queue->cls, size, buf);
4347 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
4348 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* path ack\n");
4349 if (NULL != c->t->channel_head)
4350 data_size = send_core_connection_ack (queue->cls, size, buf);
4352 data_size = send_core_data_raw (queue->cls, size, buf);
4356 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "* type unknown: %u\n",
4361 if (0 < drop_percent &&
4362 GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 101) < drop_percent)
4364 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4365 "Dropping message of type %s\n",
4366 GNUNET_MESH_DEBUG_M2S (queue->type));
4369 /* Free queue, but cls was freed by send_core_* */
4370 queue_destroy (queue, GNUNET_NO);
4372 /* Send ACK if needed, after accounting for sent ID in fc->queue_n */
4375 case GNUNET_MESSAGE_TYPE_MESH_FWD:
4376 case GNUNET_MESSAGE_TYPE_MESH_BCK:
4377 pid = ntohl ( ((struct GNUNET_MESH_Encrypted *) buf)->pid );
4378 fc->last_pid_sent = pid;
4379 connection_send_ack (c, fwd);
4385 /* If more data in queue, send next */
4386 queue = peer_get_first_message (peer);
4389 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* more data!\n");
4390 if (NULL == peer->core_transmit) {
4391 peer->core_transmit =
4392 GNUNET_CORE_notify_transmit_ready(core_handle,
4395 GNUNET_TIME_UNIT_FOREVER_REL,
4403 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4404 "* tmt rdy called somewhere else\n");
4406 if (GNUNET_SCHEDULER_NO_TASK == fc->poll_task)
4408 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "* %s starting poll timeout\n");
4410 GNUNET_SCHEDULER_add_delayed (fc->poll_time, &connection_poll, fc);
4415 if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
4417 GNUNET_SCHEDULER_cancel (fc->poll_task);
4418 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
4423 c->pending_messages--;
4424 if (GNUNET_YES == c->destroy && 0 == c->pending_messages)
4426 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* destroying connection!\n");
4427 connection_destroy (c);
4433 t->pending_messages--;
4434 if (GNUNET_YES == t->destroy && 0 == t->pending_messages)
4436 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* destroying tunnel!\n");
4440 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Return %d\n", data_size);
4446 queue_add (void *cls, uint16_t type, size_t size,
4447 struct MeshPeer *dst,
4448 struct MeshConnection *c,
4449 struct MeshChannel *ch)
4451 struct MeshPeerQueue *queue;
4452 struct MeshFlowControl *fc;
4456 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4457 "queue add %s (%u bytes) on c %p, ch %p\n",
4458 GNUNET_MESH_DEBUG_M2S (type), size, c, ch);
4460 fwd = (dst == connection_get_next_hop (c));
4461 fc = fwd ? &c->fwd_fc : &c->bck_fc;
4471 if (GNUNET_MESSAGE_TYPE_MESH_POLL == type ||
4472 GNUNET_MESSAGE_TYPE_MESH_ACK == type)
4476 ( (NULL != ch->root && GNUNET_MESSAGE_TYPE_MESH_FWD == type) ||
4477 (NULL != ch->dest && GNUNET_MESSAGE_TYPE_MESH_BCK == type) ))
4480 if (fc->queue_n >= fc->queue_max && 0 == priority)
4482 GNUNET_STATISTICS_update (stats, "# messages dropped (buffer full)",
4485 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4486 "queue full: %u/%u\n",
4487 fc->queue_n, fc->queue_max);
4488 return; /* Drop this message */
4491 if (GMC_is_pid_bigger(fc->last_pid_sent + 1, fc->last_ack_recv) &&
4492 GNUNET_SCHEDULER_NO_TASK == fc->poll_task)
4493 fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
4496 queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
4504 if (100 <= priority)
4505 GNUNET_CONTAINER_DLL_insert (dst->queue_head, dst->queue_tail, queue);
4507 GNUNET_CONTAINER_DLL_insert_tail (dst->queue_head, dst->queue_tail, queue);
4509 if (NULL == dst->core_transmit)
4511 dst->core_transmit =
4512 GNUNET_CORE_notify_transmit_ready (core_handle,
4515 GNUNET_TIME_UNIT_FOREVER_REL,
4516 GNUNET_PEER_resolve2 (dst->id),
4521 c->pending_messages++;
4522 c->t->pending_messages++;
4528 /******************************************************************************/
4529 /******************** MESH NETWORK HANDLERS **************************/
4530 /******************************************************************************/
4534 * Generic handler for mesh network payload traffic.
4536 * @param t Tunnel on which we got this message.
4537 * @param message Unencryted data message.
4538 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
4540 * @return GNUNET_OK to keep the connection open,
4541 * GNUNET_SYSERR to close it (signal serious error)
4544 handle_data (struct MeshTunnel2 *t, const struct GNUNET_MESH_Data *msg, int fwd)
4546 struct MeshChannelReliability *rel;
4547 struct MeshChannel *ch;
4548 struct MeshClient *c;
4555 size = ntohs (msg->header.size);
4557 sizeof (struct GNUNET_MESH_Data) +
4558 sizeof (struct GNUNET_MessageHeader))
4563 type = ntohs (msg->header.type);
4564 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message\n",
4565 GNUNET_MESH_DEBUG_M2S (type));
4566 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
4567 GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
4570 ch = channel_get (t, ntohl (msg->chid));
4573 GNUNET_STATISTICS_update (stats, "# data on unknown channel", 1, GNUNET_NO);
4574 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel unknown\n");
4578 /* Initialize FWD/BCK data */
4579 c = fwd ? ch->dest : ch->root;
4580 rel = fwd ? ch->bck_rel : ch->fwd_rel;
4581 mid_recv = fwd ? &ch->mid_recv_fwd : &ch->mid_recv_bck;
4589 tunnel_change_state (t, MESH_TUNNEL_READY);
4591 GNUNET_STATISTICS_update (stats, "# data received", 1, GNUNET_NO);
4593 mid = ntohl (msg->mid);
4594 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " mid %u\n", mid);
4596 if (GNUNET_NO == ch->reliable ||
4597 ( !GMC_is_pid_bigger (*mid_recv, mid) &&
4598 GMC_is_pid_bigger (*mid_recv + 64, mid) ) )
4600 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! RECV %u\n", mid);
4601 if (GNUNET_YES == ch->reliable)
4603 /* Is this the exact next expected messasge? */
4604 if (mid == *mid_recv)
4606 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "as expected\n");
4607 *mid_recv = *mid_recv + 1;
4608 channel_send_client_data (ch, msg, fwd);
4609 channel_send_client_buffered_data (ch, c, rel);
4613 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "save for later\n");
4614 channel_rel_add_buffered_data (msg, rel);
4617 else /* Tunnel unreliable, send to clients directly */
4619 channel_send_client_data (ch, msg, fwd);
4624 GNUNET_break_op (0);
4625 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4626 " MID %u not expected (%u - %u), dropping!\n",
4627 mid, *mid_recv, *mid_recv + 64);
4630 channel_send_data_ack (ch, fwd);
4635 * Handler for mesh network traffic end-to-end ACKs.
4637 * @param t Tunnel on which we got this message.
4638 * @param message Data message.
4639 * @param fwd Is this a fwd ACK? (dest->orig)
4641 * @return GNUNET_OK to keep the connection open,
4642 * GNUNET_SYSERR to close it (signal serious error)
4645 handle_data_ack (struct MeshTunnel2 *t,
4646 const struct GNUNET_MESH_DataACK *msg, int fwd)
4648 struct MeshChannelReliability *rel;
4649 struct MeshReliableMessage *copy;
4650 struct MeshReliableMessage *next;
4651 struct MeshChannel *ch;
4656 type = ntohs (msg->header.type);
4657 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a %s message!\n",
4658 GNUNET_MESH_DEBUG_M2S (type));
4659 ch = channel_get (t, ntohl (msg->chid));
4662 GNUNET_STATISTICS_update (stats, "# ack on unknown channel", 1, GNUNET_NO);
4665 ack = ntohl (msg->mid);
4666 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! %s ACK %u\n",
4667 (GNUNET_YES == fwd) ? "FWD" : "BCK", ack);
4669 if (GNUNET_YES == fwd)
4682 for (work = GNUNET_NO, copy = rel->head_sent; copy != NULL; copy = next)
4684 if (GMC_is_pid_bigger (copy->mid, ack))
4686 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! head %u, out!\n", copy->mid);
4687 channel_rel_free_sent (rel, msg);
4691 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! id %u\n", copy->mid);
4693 rel_message_free (copy);
4695 /* ACK client if needed */
4696 // channel_send_ack (t, type, GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK == type);
4698 /* If some message was free'd, update the retransmission delay*/
4699 if (GNUNET_YES == work)
4701 if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
4703 GNUNET_SCHEDULER_cancel (rel->retry_task);
4704 if (NULL == rel->head_sent)
4706 rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
4710 struct GNUNET_TIME_Absolute new_target;
4711 struct GNUNET_TIME_Relative delay;
4713 delay = GNUNET_TIME_relative_multiply (rel->retry_timer,
4714 MESH_RETRANSMIT_MARGIN);
4715 new_target = GNUNET_TIME_absolute_add (rel->head_sent->timestamp,
4717 delay = GNUNET_TIME_absolute_get_remaining (new_target);
4719 GNUNET_SCHEDULER_add_delayed (delay,
4720 &channel_retransmit_message,
4732 * Core handler for connection creation.
4734 * @param cls Closure (unused).
4735 * @param peer Sender (neighbor).
4736 * @param message Message.
4738 * @return GNUNET_OK to keep the connection open,
4739 * GNUNET_SYSERR to close it (signal serious error)
4742 handle_mesh_connection_create (void *cls,
4743 const struct GNUNET_PeerIdentity *peer,
4744 const struct GNUNET_MessageHeader *message)
4746 struct GNUNET_MESH_ConnectionCreate *msg;
4747 struct GNUNET_PeerIdentity *id;
4748 struct GNUNET_HashCode *tid;
4749 struct MeshPeerPath *path;
4750 struct MeshPeer *dest_peer;
4751 struct MeshPeer *orig_peer;
4752 struct MeshConnection *c;
4753 unsigned int own_pos;
4758 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection create msg\n");
4761 size = ntohs (message->size);
4762 if (size < sizeof (struct GNUNET_MESH_ConnectionCreate))
4764 GNUNET_break_op (0);
4768 /* Calculate hops */
4769 size -= sizeof (struct GNUNET_MESH_ConnectionCreate);
4770 if (size % sizeof (struct GNUNET_PeerIdentity))
4772 GNUNET_break_op (0);
4775 size /= sizeof (struct GNUNET_PeerIdentity);
4778 GNUNET_break_op (0);
4781 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " path has %u hops.\n", size);
4783 /* Get parameters */
4784 msg = (struct GNUNET_MESH_ConnectionCreate *) message;
4785 cid = ntohl (msg->cid);
4787 id = (struct GNUNET_PeerIdentity *) &msg[1];
4788 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4789 " connection %s[%X] (%s).\n",
4790 GNUNET_h2s (tid), cid, GNUNET_i2s (id));
4792 /* Create connection */
4793 c = connection_get (tid, cid);
4796 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Creating connection\n");
4797 c = connection_new (tid, cid);
4801 connection_reset_timeout (c, GNUNET_YES);
4802 tunnel_change_state (c->t, MESH_TUNNEL_WAITING);
4804 /* Remember peers */
4805 dest_peer = peer_get (&id[size - 1]);
4806 orig_peer = peer_get (&id[0]);
4809 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Creating path...\n");
4810 path = path_new (size);
4812 for (i = 0; i < size; i++)
4814 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... adding %s\n",
4815 GNUNET_i2s (&id[i]));
4816 path->peers[i] = GNUNET_PEER_intern (&id[i]);
4817 if (path->peers[i] == myid)
4820 if (own_pos == 0 && path->peers[own_pos] != myid)
4822 /* create path: self not found in path through self */
4823 GNUNET_break_op (0);
4824 path_destroy (path);
4825 connection_destroy (c);
4828 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Own position: %u\n", own_pos);
4829 path_add_to_peers (path, GNUNET_NO);
4831 c->own_pos = own_pos;
4833 /* Is it a connection to us? */
4834 if (own_pos == size - 1)
4836 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " It's for us!\n");
4837 peer_add_path_to_origin (orig_peer, path, GNUNET_YES);
4839 send_connection_ack (c);
4841 /* Keep tunnel alive in direction dest->owner*/
4842 connection_reset_timeout (c, GNUNET_NO);
4846 /* It's for somebody else! Retransmit. */
4847 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Retransmitting.\n");
4848 peer_add_path (dest_peer, path_duplicate (path), GNUNET_NO);
4849 peer_add_path_to_origin (orig_peer, path, GNUNET_NO);
4850 send_prebuilt_message_connection (message, c, NULL, GNUNET_YES);
4857 * Core handler for path ACKs
4859 * @param cls closure
4860 * @param message message
4861 * @param peer peer identity this notification is about
4863 * @return GNUNET_OK to keep the connection open,
4864 * GNUNET_SYSERR to close it (signal serious error)
4867 handle_mesh_connection_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
4868 const struct GNUNET_MessageHeader *message)
4870 struct GNUNET_MESH_ConnectionACK *msg;
4871 struct MeshPeerPath *p;
4872 struct MeshConnection *c;
4875 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection ACK msg\n");
4876 msg = (struct GNUNET_MESH_ConnectionACK *) message;
4877 cid = ntohl(msg->cid);
4878 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " on connection %s[%X]\n",
4879 GNUNET_h2s (&msg->tid), cid);
4880 c = connection_get (&msg->tid, cid);
4883 GNUNET_STATISTICS_update (stats, "# control on unknown connection",
4885 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " don't know the connection!\n");
4889 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " via peer %s\n",
4892 /* Add path to peers? */
4896 path_add_to_peers (p, GNUNET_YES);
4902 connection_change_state (c, MESH_CONNECTION_READY);
4903 connection_reset_timeout (c, GNUNET_NO);
4905 /* Message for us? */
4906 if (NULL != c->t->channel_head)
4908 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " It's for us!\n");
4909 if (3 <= tunnel_count_connections(c->t) && NULL != c->t->peer->dhtget)
4911 GNUNET_DHT_get_stop (c->t->peer->dhtget);
4912 c->t->peer->dhtget = NULL;
4914 //connection_send_ack (c, GNUNET_NO); /* FIXME */
4918 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " not for us, retransmitting...\n");
4919 send_prebuilt_message_connection (message, c, NULL, GNUNET_NO);
4925 * Core handler for notifications of broken paths
4927 * @param cls Closure (unused).
4928 * @param peer Peer identity of sending neighbor.
4929 * @param message Message.
4931 * @return GNUNET_OK to keep the connection open,
4932 * GNUNET_SYSERR to close it (signal serious error)
4935 handle_mesh_connection_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
4936 const struct GNUNET_MessageHeader *message)
4938 struct GNUNET_MESH_ConnectionBroken *msg;
4939 struct MeshConnection *c;
4941 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4942 "Received a CONNECTION BROKEN msg from %s\n", GNUNET_i2s (peer));
4943 msg = (struct GNUNET_MESH_ConnectionBroken *) message;
4944 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " regarding %s\n",
4945 GNUNET_i2s (&msg->peer1));
4946 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " regarding %s\n",
4947 GNUNET_i2s (&msg->peer2));
4948 c = connection_get (&msg->tid, ntohl (msg->cid));
4951 GNUNET_break_op (0);
4954 tunnel_notify_connection_broken (c->t, GNUNET_PEER_search (&msg->peer1),
4955 GNUNET_PEER_search (&msg->peer2));
4962 * Core handler for tunnel destruction
4964 * @param cls Closure (unused).
4965 * @param peer Peer identity of sending neighbor.
4966 * @param message Message.
4968 * @return GNUNET_OK to keep the connection open,
4969 * GNUNET_SYSERR to close it (signal serious error)
4972 handle_mesh_connection_destroy (void *cls,
4973 const struct GNUNET_PeerIdentity *peer,
4974 const struct GNUNET_MessageHeader *message)
4976 struct GNUNET_MESH_ConnectionDestroy *msg;
4977 struct MeshConnection *c;
4981 msg = (struct GNUNET_MESH_ConnectionDestroy *) message;
4982 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4983 "Got a CONNECTION DESTROY message from %s\n",
4985 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4986 " for connection %s[%X]\n",
4987 GNUNET_h2s (&msg->tid), ntohl (msg->cid));
4988 c = connection_get (&msg->tid, ntohl (msg->cid));
4991 /* Probably already got the message from another path,
4992 * destroyed the tunnel and retransmitted to children.
4995 GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
4999 id = GNUNET_PEER_search (peer);
5000 if (id == connection_get_prev_hop (c)->id)
5002 else if (id == connection_get_next_hop (c)->id)
5006 GNUNET_break_op (0);
5009 send_prebuilt_message_connection (message, c, NULL, fwd);
5010 c->destroy = GNUNET_YES;
5016 * Handler for channel create messages.
5018 * @param t Tunnel this channel is to be created in.
5019 * @param msg Message.
5020 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5022 * @return GNUNET_OK to keep the connection open,
5023 * GNUNET_SYSERR to close it (signal serious error)
5026 handle_channel_create (struct MeshTunnel2 *t,
5027 struct GNUNET_MESH_ChannelCreate *msg,
5030 MESH_ChannelNumber chid;
5031 struct MeshChannel *ch;
5032 struct MeshClient *c;
5034 /* Check message size */
5035 if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelCreate))
5037 GNUNET_break_op (0);
5041 /* Check if channel exists */
5042 chid = ntohl (msg->chid);
5043 ch = channel_get (t, chid);
5046 /* Probably a retransmission, safe to ignore */
5050 /* Find a destination client */
5051 c = GNUNET_CONTAINER_multihashmap32_get (ports, msg->port);
5054 /* TODO send reject */
5058 /* Create channel */
5059 ch = channel_new (t, NULL, 0);
5060 channel_set_options (ch, ntohl (msg->opt));
5061 channel_add_client (ch, c);
5062 if (GNUNET_YES == ch->reliable)
5064 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
5065 ch->bck_rel = GNUNET_malloc (sizeof (struct MeshChannelReliability));
5066 ch->bck_rel->ch = ch;
5067 ch->bck_rel->expected_delay = MESH_RETRANSMIT_TIME;
5070 send_local_channel_create (ch);
5077 * Handler for channel destroy messages.
5079 * @param t Tunnel this channel is to be destroyed of.
5080 * @param msg Message.
5081 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5083 * @return GNUNET_OK to keep the connection open,
5084 * GNUNET_SYSERR to close it (signal serious error)
5087 handle_channel_destroy (struct MeshTunnel2 *t,
5088 struct GNUNET_MESH_ChannelDestroy *msg,
5091 MESH_ChannelNumber chid;
5092 struct MeshChannel *ch;
5094 /* Check message size */
5095 if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelDestroy))
5097 GNUNET_break_op (0);
5101 /* Check if channel exists */
5102 chid = ntohl (msg->chid);
5103 ch = channel_get (t, chid);
5106 /* Probably a retransmission, safe to ignore */
5110 send_local_channel_destroy (ch, fwd);
5111 channel_destroy (ch);
5118 * Generic handler for mesh network encrypted traffic.
5120 * @param peer Peer identity this notification is about.
5121 * @param message Encrypted message.
5122 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5124 * @return GNUNET_OK to keep the connection open,
5125 * GNUNET_SYSERR to close it (signal serious error)
5128 handle_mesh_encrypted (const struct GNUNET_PeerIdentity *peer,
5129 const struct GNUNET_MESH_Encrypted *msg,
5132 struct MeshConnection *c;
5133 struct MeshTunnel2 *t;
5134 struct MeshPeer *neighbor;
5135 struct MeshFlowControl *fc;
5142 size = ntohs (msg->header.size);
5144 sizeof (struct GNUNET_MESH_Encrypted) +
5145 sizeof (struct GNUNET_MessageHeader))
5150 type = ntohs (msg->header.type);
5151 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message from %s\n",
5152 GNUNET_MESH_DEBUG_M2S (type), GNUNET_i2s (peer));
5154 /* Check connection */
5155 c = connection_get (&msg->tid, ntohl (msg->cid));
5158 GNUNET_STATISTICS_update (stats, "# unknown connection", 1, GNUNET_NO);
5159 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING connection unknown\n");
5163 fc = fwd ? &c->fwd_fc : &c->bck_fc;
5165 /* Check if origin is as expected */
5166 neighbor = connection_get_hop (c, fwd);
5167 if (peer_get (peer)->id != neighbor->id)
5169 GNUNET_break_op (0);
5174 pid = ntohl (msg->pid);
5175 if (GMC_is_pid_bigger (pid, fc->last_ack_sent))
5177 GNUNET_STATISTICS_update (stats, "# unsolicited message", 1, GNUNET_NO);
5178 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5179 "WARNING Received PID %u, (prev %u), ACK %u\n",
5180 pid, fc->last_pid_recv, fc->last_ack_sent);
5183 if (GNUNET_NO == GMC_is_pid_bigger (pid, fc->last_pid_recv))
5185 GNUNET_STATISTICS_update (stats, "# duplicate PID", 1, GNUNET_NO);
5186 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5187 " Pid %u not expected (%u+), dropping!\n",
5188 pid, fc->last_pid_recv + 1);
5191 if (MESH_CONNECTION_SENT == c->state)
5192 connection_change_state (c, MESH_CONNECTION_READY);
5193 connection_reset_timeout (c, fwd);
5194 fc->last_pid_recv = pid;
5196 /* Is this message for us? */
5197 if (NULL != c->t->channel_head)
5199 size_t dsize = size - sizeof (struct GNUNET_MESH_Encrypted);
5201 struct GNUNET_MessageHeader *msgh;
5203 /* TODO signature verification */
5204 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " it's for us!\n");
5205 GNUNET_STATISTICS_update (stats, "# messages received", 1, GNUNET_NO);
5207 fc->last_pid_recv = pid;
5208 tunnel_decrypt (t, cbuf, &msg[1], dsize, msg->iv, fwd);
5209 msgh = (struct GNUNET_MessageHeader *) cbuf;
5210 switch (ntohs (msgh->type))
5212 case GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK:
5213 if (GNUNET_YES == fwd)
5214 return handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh,
5216 GNUNET_break_op (0);
5218 case GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK:
5219 if (GNUNET_NO == fwd)
5220 return handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh,
5222 GNUNET_break_op (0);
5224 case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
5225 if (GNUNET_YES == fwd)
5226 handle_data (t, (struct GNUNET_MESH_Data *) msgh, GNUNET_YES);
5227 GNUNET_break_op (0);
5229 case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
5230 if (GNUNET_NO == fwd)
5231 handle_data (t, (struct GNUNET_MESH_Data *) msgh, GNUNET_NO);
5232 GNUNET_break_op (0);
5234 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
5235 return handle_channel_create (t,
5236 (struct GNUNET_MESH_ChannelCreate *) msgh,
5239 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
5240 return handle_channel_destroy (t,
5241 (struct GNUNET_MESH_ChannelDestroy *)
5246 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5247 "end-to-end message not known (%u)\n",
5248 ntohs (msgh->type));
5251 connection_send_ack (c, fwd);
5255 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " not for us, retransmitting...\n");
5256 ttl = ntohl (msg->ttl);
5257 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ttl: %u\n", ttl);
5260 GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5261 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5262 connection_send_ack (c, fwd);
5265 GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
5267 send_prebuilt_message_connection (&msg->header, c, NULL, fwd);
5268 connection_send_ack (c, fwd);
5275 * Core handler for mesh network traffic going orig->dest.
5277 * @param cls Closure (unused).
5278 * @param message Message received.
5279 * @param peer Peer who sent the message.
5281 * @return GNUNET_OK to keep the connection open,
5282 * GNUNET_SYSERR to close it (signal serious error)
5285 handle_mesh_fwd (void *cls, const struct GNUNET_PeerIdentity *peer,
5286 const struct GNUNET_MessageHeader *message)
5288 return handle_mesh_encrypted (peer,
5289 (struct GNUNET_MESH_Encrypted *)message,
5294 * Core handler for mesh network traffic going dest->orig.
5296 * @param cls Closure (unused).
5297 * @param message Message received.
5298 * @param peer Peer who sent the message.
5300 * @return GNUNET_OK to keep the connection open,
5301 * GNUNET_SYSERR to close it (signal serious error)
5304 handle_mesh_bck (void *cls, const struct GNUNET_PeerIdentity *peer,
5305 const struct GNUNET_MessageHeader *message)
5307 return handle_mesh_encrypted (peer,
5308 (struct GNUNET_MESH_Encrypted *)message,
5314 * Core handler for mesh network traffic point-to-point acks.
5316 * @param cls closure
5317 * @param message message
5318 * @param peer peer identity this notification is about
5320 * @return GNUNET_OK to keep the connection open,
5321 * GNUNET_SYSERR to close it (signal serious error)
5324 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5325 const struct GNUNET_MessageHeader *message)
5327 struct GNUNET_MESH_ACK *msg;
5328 struct MeshConnection *c;
5329 struct MeshFlowControl *fc;
5333 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
5335 msg = (struct GNUNET_MESH_ACK *) message;
5337 c = connection_get (&msg->tid, ntohl (msg->cid));
5341 GNUNET_STATISTICS_update (stats, "# ack on unknown connection", 1,
5346 ack = ntohl (msg->ack);
5347 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", ack);
5349 /* Is this a forward or backward ACK? */
5350 id = GNUNET_PEER_search (peer);
5351 if (connection_get_next_hop (c)->id == id)
5353 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " FWD ACK\n");
5356 else if (connection_get_prev_hop (c)->id == id)
5358 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " BCK ACK\n");
5363 GNUNET_break_op (0);
5367 /* Cancel polling if the ACK is bigger than before. */
5368 if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task &&
5369 GMC_is_pid_bigger (ack, fc->last_ack_recv))
5371 GNUNET_SCHEDULER_cancel (fc->poll_task);
5372 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
5373 fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
5376 fc->last_ack_recv = ack;
5377 connection_unlock_queue (c, fc == &c->fwd_fc);
5384 * Core handler for mesh network traffic point-to-point ack polls.
5386 * @param cls closure
5387 * @param message message
5388 * @param peer peer identity this notification is about
5390 * @return GNUNET_OK to keep the connection open,
5391 * GNUNET_SYSERR to close it (signal serious error)
5394 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
5395 const struct GNUNET_MessageHeader *message)
5397 struct GNUNET_MESH_Poll *msg;
5398 struct MeshConnection *c;
5399 struct MeshFlowControl *fc;
5403 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a POLL packet from %s!\n",
5406 msg = (struct GNUNET_MESH_Poll *) message;
5408 c = connection_get (&msg->tid, ntohl (msg->cid));
5412 GNUNET_STATISTICS_update (stats, "# poll on unknown connection", 1,
5414 GNUNET_break_op (0);
5418 /* Is this a forward or backward ACK? */
5419 id = GNUNET_PEER_search (peer);
5420 if (connection_get_next_hop (c)->id == id)
5422 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " FWD ACK\n");
5425 else if (connection_get_prev_hop (c)->id == id)
5427 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " BCK ACK\n");
5432 GNUNET_break_op (0);
5436 pid = ntohl (msg->pid);
5437 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " PID %u, OLD %u\n",
5438 pid, fc->last_pid_recv);
5439 fc->last_pid_recv = pid;
5440 connection_send_ack (c, fc == &c->fwd_fc);
5447 * Core handler for mesh keepalives.
5449 * @param cls closure
5450 * @param message message
5451 * @param peer peer identity this notification is about
5452 * @return GNUNET_OK to keep the connection open,
5453 * GNUNET_SYSERR to close it (signal serious error)
5455 * TODO: Check who we got this from, to validate route.
5458 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
5459 const struct GNUNET_MessageHeader *message)
5461 struct GNUNET_MESH_ConnectionKeepAlive *msg;
5462 struct MeshConnection *c;
5463 struct MeshPeer *neighbor;
5466 msg = (struct GNUNET_MESH_ConnectionKeepAlive *) message;
5467 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
5470 c = connection_get (&msg->tid, ntohl (msg->cid));
5473 GNUNET_STATISTICS_update (stats, "# keepalive on unknown connection", 1,
5478 fwd = GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE == ntohs (message->type) ?
5479 GNUNET_YES : GNUNET_NO;
5481 /* Check if origin is as expected */
5482 neighbor = connection_get_hop (c, fwd);
5483 if (peer_get (peer)->id != neighbor->id)
5485 GNUNET_break_op (0);
5489 connection_change_state (c, MESH_CONNECTION_READY);
5490 connection_reset_timeout (c, fwd);
5492 if (NULL != c->t->channel_head)
5495 GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
5496 send_prebuilt_message_connection (message, c, NULL, fwd);
5504 * Functions to handle messages from core
5506 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
5507 {&handle_mesh_connection_create, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
5509 {&handle_mesh_connection_ack, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
5510 sizeof (struct GNUNET_MESH_ConnectionACK)},
5511 {&handle_mesh_connection_broken, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN,
5512 sizeof (struct GNUNET_MESH_ConnectionBroken)},
5513 {&handle_mesh_connection_destroy, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY,
5514 sizeof (struct GNUNET_MESH_ConnectionDestroy)},
5515 {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE,
5516 sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
5517 {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE,
5518 sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
5519 {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
5520 sizeof (struct GNUNET_MESH_ACK)},
5521 {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
5522 sizeof (struct GNUNET_MESH_Poll)},
5523 {&handle_mesh_fwd, GNUNET_MESSAGE_TYPE_MESH_FWD, 0},
5524 {&handle_mesh_bck, GNUNET_MESSAGE_TYPE_MESH_BCK, 0},
5530 * Function to process paths received for a new peer addition. The recorded
5531 * paths form the initial tunnel, which can be optimized later.
5532 * Called on each result obtained for the DHT search.
5534 * @param cls closure
5535 * @param exp when will this value expire
5536 * @param key key of the result
5537 * @param get_path path of the get request
5538 * @param get_path_length lenght of get_path
5539 * @param put_path path of the put request
5540 * @param put_path_length length of the put_path
5541 * @param type type of the result
5542 * @param size number of bytes in data
5543 * @param data pointer to the result data
5546 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5547 const struct GNUNET_HashCode * key,
5548 const struct GNUNET_PeerIdentity *get_path,
5549 unsigned int get_path_length,
5550 const struct GNUNET_PeerIdentity *put_path,
5551 unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5552 size_t size, const void *data)
5554 struct MeshPeer *peer = cls;
5555 struct MeshPeerPath *p;
5556 struct MeshConnection *c;
5557 struct GNUNET_PeerIdentity pi;
5560 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
5561 GNUNET_PEER_resolve (peer->id, &pi);
5562 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " for %s\n", GNUNET_i2s (&pi));
5564 p = path_build_from_dht (get_path, get_path_length,
5565 put_path, put_path_length);
5566 path_add_to_peers (p, GNUNET_NO);
5569 /* Count connections */
5570 for (c = peer->tunnel->connection_head, i = 0; NULL != c; c = c->next, i++);
5572 /* If we already have 3 (or more (?!)) connections, it's enough */
5576 if (peer->tunnel->state == MESH_TUNNEL_SEARCHING)
5578 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... connect!\n");
5579 peer_connect (peer);
5585 /******************************************************************************/
5586 /********************* MESH LOCAL HANDLES **************************/
5587 /******************************************************************************/
5591 * Handler for client connection.
5593 * @param cls Closure (unused).
5594 * @param client Client handler.
5597 handle_local_client_connect (void *cls, struct GNUNET_SERVER_Client *client)
5599 struct MeshClient *c;
5603 c = GNUNET_malloc (sizeof (struct MeshClient));
5605 c->id = next_client_id++; /* overflow not important: just for debug */
5606 GNUNET_SERVER_client_keep (client);
5607 GNUNET_SERVER_client_set_user_context (client, c);
5608 GNUNET_CONTAINER_DLL_insert (clients_head, clients_tail, c);
5613 * Handler for client disconnection
5615 * @param cls closure
5616 * @param client identification of the client; NULL
5617 * for the last call when the server is destroyed
5620 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
5622 struct MeshClient *c;
5623 struct MeshClient *next;
5625 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected: %p\n", client);
5628 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " (SERVER DOWN)\n");
5632 c = client_get (client);
5635 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u, %p)\n",
5637 GNUNET_SERVER_client_drop (c->handle);
5638 c->shutting_down = GNUNET_YES;
5639 if (NULL != c->own_channels)
5641 GNUNET_CONTAINER_multihashmap32_iterate (c->own_channels,
5642 &channel_destroy_iterator, c);
5643 GNUNET_CONTAINER_multihashmap32_destroy (c->own_channels);
5646 if (NULL != c->incoming_channels)
5648 GNUNET_CONTAINER_multihashmap32_iterate (c->incoming_channels,
5649 &channel_destroy_iterator, c);
5650 GNUNET_CONTAINER_multihashmap32_destroy (c->incoming_channels);
5653 if (NULL != c->ports)
5655 GNUNET_CONTAINER_multihashmap32_iterate (c->ports,
5656 &client_release_ports, c);
5657 GNUNET_CONTAINER_multihashmap32_destroy (c->ports);
5660 GNUNET_CONTAINER_DLL_remove (clients_head, clients_tail, c);
5661 GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
5662 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " client free (%p)\n", c);
5668 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " context NULL!\n");
5670 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "done!\n");
5676 * Handler for new clients
5678 * @param cls closure
5679 * @param client identification of the client
5680 * @param message the actual message, which includes messages the client wants
5683 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
5684 const struct GNUNET_MessageHeader *message)
5686 struct GNUNET_MESH_ClientConnect *cc_msg;
5687 struct MeshClient *c;
5692 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected %p\n", client);
5694 /* Check data sanity */
5695 size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
5696 cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
5697 if (0 != (size % sizeof (uint32_t)))
5700 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5703 size /= sizeof (uint32_t);
5705 /* Initialize new client structure */
5706 c = GNUNET_SERVER_client_get_user_context (client, struct MeshClient);
5707 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " client id %u\n", c->id);
5708 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " client has %u ports\n", size);
5713 p = (uint32_t *) &cc_msg[1];
5714 c->ports = GNUNET_CONTAINER_multihashmap32_create (size);
5715 for (i = 0; i < size; i++)
5718 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " port: %u\n", u32);
5720 /* store in client's hashmap */
5721 GNUNET_CONTAINER_multihashmap32_put (c->ports, u32, c,
5722 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
5723 /* store in global hashmap */
5724 /* FIXME only allow one client to have the port open,
5725 * have a backup hashmap with waiting clients */
5726 GNUNET_CONTAINER_multihashmap32_put (ports, u32, c,
5727 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
5731 c->own_channels = GNUNET_CONTAINER_multihashmap32_create (32);
5732 c->incoming_channels = GNUNET_CONTAINER_multihashmap32_create (32);
5733 GNUNET_SERVER_notification_context_add (nc, client);
5734 GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
5736 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5737 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
5742 * Handler for requests of new tunnels
5744 * @param cls Closure.
5745 * @param client Identification of the client.
5746 * @param message The actual message.
5749 handle_local_channel_create (void *cls, struct GNUNET_SERVER_Client *client,
5750 const struct GNUNET_MessageHeader *message)
5752 struct GNUNET_MESH_ChannelMessage *msg;
5753 struct MeshPeer *peer;
5754 struct MeshTunnel2 *t;
5755 struct MeshChannel *ch;
5756 struct MeshClient *c;
5757 MESH_ChannelNumber chid;
5759 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new channel requested\n");
5761 /* Sanity check for client registration */
5762 if (NULL == (c = client_get (client)))
5765 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5768 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
5770 /* Message size sanity check */
5771 if (sizeof (struct GNUNET_MESH_ChannelMessage) != ntohs (message->size))
5774 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5778 msg = (struct GNUNET_MESH_ChannelMessage *) message;
5779 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " towards %s:%u\n",
5780 GNUNET_i2s (&msg->peer), ntohl (msg->port));
5781 chid = ntohl (msg->channel_id);
5783 /* Sanity check for duplicate channel IDs */
5784 if (NULL != channel_get_by_local_id (c, chid))
5787 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5791 peer = peer_get (&msg->peer);
5792 if (NULL == peer->tunnel)
5794 struct GNUNET_HashCode tid;
5796 GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE, &tid);
5797 peer->tunnel = tunnel_new (&tid);
5798 peer->tunnel->peer = peer;
5802 /* Create channel */
5803 ch = channel_new (t, c, chid);
5807 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5810 ch->port = ntohl (msg->port);
5811 channel_set_options (ch, ntohl (msg->opt));
5813 /* In unreliable channels, we'll use the DLL to buffer data for the root */
5814 ch->fwd_rel = GNUNET_malloc (sizeof (struct MeshChannelReliability));
5815 ch->fwd_rel->ch = ch;
5816 ch->fwd_rel->expected_delay = MESH_RETRANSMIT_TIME;
5818 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED CHANNEL %s[%x]:%u (%x)\n",
5819 GNUNET_h2s (&t->id), ch->gid, ch->port, ch->lid_root);
5820 peer_connect (peer);
5821 /* FIXME send create channel */
5823 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5829 * Handler for requests of deleting tunnels
5831 * @param cls closure
5832 * @param client identification of the client
5833 * @param message the actual message
5836 handle_local_channel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
5837 const struct GNUNET_MessageHeader *message)
5839 struct GNUNET_MESH_ChannelMessage *msg;
5840 struct MeshClient *c;
5841 struct MeshChannel *ch;
5842 struct MeshTunnel2 *t;
5843 MESH_ChannelNumber chid;
5845 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5846 "Got a DESTROY CHANNEL from client!\n");
5848 /* Sanity check for client registration */
5849 if (NULL == (c = client_get (client)))
5852 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5855 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
5857 /* Message sanity check */
5858 if (sizeof (struct GNUNET_MESH_ChannelMessage) != ntohs (message->size))
5861 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5865 msg = (struct GNUNET_MESH_ChannelMessage *) message;
5867 /* Retrieve tunnel */
5868 chid = ntohl (msg->channel_id);
5869 ch = channel_get_by_local_id (c, chid);
5872 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, " channel %X not found\n", chid);
5874 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5878 /* Cleanup after the tunnel */
5879 client_delete_channel (c, ch);
5880 if (c == ch->dest && GNUNET_MESH_LOCAL_CHANNEL_ID_SERV <= chid)
5884 else if (c == ch->root && GNUNET_MESH_LOCAL_CHANNEL_ID_SERV > chid)
5890 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5891 " channel %X client %p (%p, %p)\n",
5892 chid, c, ch->root, ch->dest);
5897 channel_destroy (ch);
5898 tunnel_destroy_if_empty (t);
5900 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5906 * Handler for client traffic
5908 * @param cls closure
5909 * @param client identification of the client
5910 * @param message the actual message
5913 handle_local_data (void *cls, struct GNUNET_SERVER_Client *client,
5914 const struct GNUNET_MessageHeader *message)
5916 struct GNUNET_MESH_LocalData *msg;
5917 struct MeshClient *c;
5918 struct MeshChannel *ch;
5919 MESH_ChannelNumber chid;
5923 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5924 "Got data from a client!\n");
5926 /* Sanity check for client registration */
5927 if (NULL == (c = client_get (client)))
5930 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5933 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
5935 msg = (struct GNUNET_MESH_LocalData *) message;
5937 /* Sanity check for message size */
5938 size = ntohs (message->size) - sizeof (struct GNUNET_MESH_LocalData);
5939 if (size < sizeof (struct GNUNET_MessageHeader))
5942 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5946 /* Channel exists? */
5947 chid = ntohl (msg->id);
5948 fwd = chid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
5949 ch = channel_get_by_local_id (c, chid);
5953 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5957 /* Is the client in the channel? */
5960 ch->root->handle == client)
5964 ch->dest->handle == client) ) )
5967 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5971 /* Ok, everything is correct, send the message
5972 * (pretend we got it from a mesh peer)
5975 struct GNUNET_MESH_Data *payload;
5976 char cbuf[sizeof(struct GNUNET_MESH_Data) + size];
5979 mid = fwd ? &ch->mid_send_fwd : &ch->mid_send_bck;
5980 if (GNUNET_YES == ch->reliable)
5982 struct MeshChannelReliability *rel;
5983 struct MeshReliableMessage *copy;
5985 rel = fwd ? ch->fwd_rel : ch->bck_rel;
5986 copy = GNUNET_malloc (sizeof (struct MeshReliableMessage)
5987 + sizeof(struct GNUNET_MESH_Data)
5990 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! DATA %u\n", copy->mid);
5991 copy->timestamp = GNUNET_TIME_absolute_get ();
5994 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " n_sent %u\n", rel->n_sent);
5995 GNUNET_CONTAINER_DLL_insert_tail (rel->head_sent, rel->tail_sent, copy);
5996 if (GNUNET_SCHEDULER_NO_TASK == rel->retry_task)
5999 GNUNET_TIME_relative_multiply (rel->expected_delay,
6000 MESH_RETRANSMIT_MARGIN);
6002 GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
6003 &channel_retransmit_message,
6006 payload = (struct GNUNET_MESH_Data *) ©[1];
6010 payload = (struct GNUNET_MESH_Data *) cbuf;
6012 payload->mid = htonl (*mid);
6014 memcpy (&payload[1], &msg[1], size);
6015 payload->header.size = htons (sizeof (struct GNUNET_MESH_Data) + size);
6016 payload->header.type = htons (chid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV ?
6017 GNUNET_MESSAGE_TYPE_MESH_UNICAST :
6018 GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
6019 payload->chid = htonl (ch->gid);
6020 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6021 " calling generic handler...\n");
6022 send_prebuilt_message_channel (&payload->header, ch, fwd);
6024 if (tunnel_get_buffer (ch->t, fwd) > 0)
6025 send_local_ack (ch, c, fwd);
6026 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
6027 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6034 * Handler for client's ACKs for payload traffic.
6036 * @param cls Closure (unused).
6037 * @param client Identification of the client.
6038 * @param message The actual message.
6041 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
6042 const struct GNUNET_MessageHeader *message)
6044 struct GNUNET_MESH_LocalAck *msg;
6045 struct MeshChannelReliability *rel;
6046 struct MeshChannel *ch;
6047 struct MeshClient *c;
6048 MESH_ChannelNumber chid;
6051 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
6053 /* Sanity check for client registration */
6054 if (NULL == (c = client_get (client)))
6057 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6060 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
6062 msg = (struct GNUNET_MESH_LocalAck *) message;
6064 /* Channel exists? */
6065 chid = ntohl (msg->channel_id);
6066 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " on channel %X\n", chid);
6067 ch = channel_get_by_local_id (c, chid);
6071 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Channel %X unknown.\n", chid);
6072 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " for client %u.\n", c->id);
6073 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6077 fwd = chid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
6078 rel = fwd ? ch->fwd_rel : ch->bck_rel;
6080 rel->client_ready = GNUNET_YES;
6081 channel_send_client_buffered_data (ch, c, rel);
6082 channel_send_ack (ch, 64 - rel->n_recv, fwd);
6084 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6091 * Iterator over all tunnels to send a monitoring client info about each tunnel.
6093 * @param cls Closure (client handle).
6094 * @param key Key (hashed tunnel ID, unused).
6095 * @param value Tunnel info.
6097 * @return GNUNET_YES, to keep iterating.
6100 monitor_all_tunnels_iterator (void *cls,
6101 const struct GNUNET_HashCode * key,
6104 struct GNUNET_SERVER_Client *client = cls;
6105 struct MeshChannel *ch = value;
6106 struct GNUNET_MESH_LocalMonitor *msg;
6108 msg = GNUNET_malloc (sizeof(struct GNUNET_MESH_LocalMonitor));
6109 msg->channel_id = htonl (ch->gid);
6110 msg->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
6111 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
6113 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6114 "* sending info about tunnel %s\n",
6115 GNUNET_i2s (&msg->owner));
6117 GNUNET_SERVER_notification_context_unicast (nc, client,
6118 &msg->header, GNUNET_NO);
6124 * Handler for client's MONITOR request.
6126 * @param cls Closure (unused).
6127 * @param client Identification of the client.
6128 * @param message The actual message.
6131 handle_local_get_tunnels (void *cls, struct GNUNET_SERVER_Client *client,
6132 const struct GNUNET_MessageHeader *message)
6134 struct MeshClient *c;
6136 /* Sanity check for client registration */
6137 if (NULL == (c = client_get (client)))
6140 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6144 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6145 "Received get tunnels request from client %u\n",
6147 GNUNET_CONTAINER_multihashmap_iterate (tunnels,
6148 monitor_all_tunnels_iterator,
6150 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6151 "Get tunnels request from client %u completed\n",
6153 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6158 * Handler for client's MONITOR_TUNNEL request.
6160 * @param cls Closure (unused).
6161 * @param client Identification of the client.
6162 * @param message The actual message.
6165 handle_local_show_tunnel (void *cls, struct GNUNET_SERVER_Client *client,
6166 const struct GNUNET_MessageHeader *message)
6168 const struct GNUNET_MESH_LocalMonitor *msg;
6169 struct GNUNET_MESH_LocalMonitor *resp;
6170 struct MeshClient *c;
6171 struct MeshChannel *ch;
6173 /* Sanity check for client registration */
6174 if (NULL == (c = client_get (client)))
6177 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6181 msg = (struct GNUNET_MESH_LocalMonitor *) message;
6182 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6183 "Received tunnel info request from client %u for tunnel %s[%X]\n",
6186 ntohl (msg->channel_id));
6187 // ch = channel_get (&msg->owner, ntohl (msg->channel_id));
6191 /* We don't know the tunnel */
6192 struct GNUNET_MESH_LocalMonitor warn;
6195 GNUNET_SERVER_notification_context_unicast (nc, client,
6198 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6202 /* Initialize context */
6203 resp = GNUNET_malloc (sizeof (struct GNUNET_MESH_LocalMonitor));
6205 resp->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
6206 GNUNET_SERVER_notification_context_unicast (nc, c->handle,
6207 &resp->header, GNUNET_NO);
6210 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6211 "Monitor tunnel request from client %u completed\n",
6213 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6218 * Functions to handle messages from clients
6220 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
6221 {&handle_local_new_client, NULL,
6222 GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
6223 {&handle_local_channel_create, NULL,
6224 GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE,
6225 sizeof (struct GNUNET_MESH_ChannelMessage)},
6226 {&handle_local_channel_destroy, NULL,
6227 GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY,
6228 sizeof (struct GNUNET_MESH_ChannelMessage)},
6229 {&handle_local_data, NULL,
6230 GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA, 0},
6231 {&handle_local_ack, NULL,
6232 GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
6233 sizeof (struct GNUNET_MESH_LocalAck)},
6234 {&handle_local_get_tunnels, NULL,
6235 GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS,
6236 sizeof (struct GNUNET_MessageHeader)},
6237 {&handle_local_show_tunnel, NULL,
6238 GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL,
6239 sizeof (struct GNUNET_MESH_LocalMonitor)},
6245 * Method called whenever a given peer connects.
6247 * @param cls closure
6248 * @param peer peer identity this notification is about
6251 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
6253 struct MeshPeer *pi;
6254 struct MeshPeerPath *path;
6256 DEBUG_CONN ("Peer connected\n");
6257 DEBUG_CONN (" %s\n", GNUNET_i2s (&my_full_id));
6258 pi = peer_get (peer);
6261 DEBUG_CONN (" (self)\n");
6262 path = path_new (1);
6266 DEBUG_CONN (" %s\n", GNUNET_i2s (peer));
6267 path = path_new (2);
6268 path->peers[1] = pi->id;
6269 GNUNET_PEER_change_rc (pi->id, 1);
6270 GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
6272 path->peers[0] = myid;
6273 GNUNET_PEER_change_rc (myid, 1);
6274 peer_add_path (pi, path, GNUNET_YES);
6276 pi->connections = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_YES);
6282 * Method called whenever a peer disconnects.
6284 * @param cls closure
6285 * @param peer peer identity this notification is about
6288 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
6290 struct MeshPeer *pi;
6292 DEBUG_CONN ("Peer disconnected\n");
6293 pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
6300 peer_remove_path (pi, myid, pi->id);
6302 GNUNET_CONTAINER_multihashmap_iterate (pi->connections,
6305 GNUNET_CONTAINER_multihashmap_destroy (pi->connections);
6306 pi->connections = NULL;
6309 DEBUG_CONN (" (self)\n");
6311 GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
6318 * Install server (service) handlers and start listening to clients.
6323 GNUNET_SERVER_add_handlers (server_handle, client_handlers);
6324 GNUNET_SERVER_connect_notify (server_handle,
6325 &handle_local_client_connect, NULL);
6326 GNUNET_SERVER_disconnect_notify (server_handle,
6327 &handle_local_client_disconnect, NULL);
6328 nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
6330 clients_head = NULL;
6331 clients_tail = NULL;
6333 GNUNET_SERVER_resume (server_handle);
6338 * To be called on core init/fail.
6340 * @param cls Closure (config)
6341 * @param server handle to the server for this service
6342 * @param identity the public identity of this peer
6345 core_init (void *cls, struct GNUNET_CORE_Handle *server,
6346 const struct GNUNET_PeerIdentity *identity)
6348 const struct GNUNET_CONFIGURATION_Handle *c = cls;
6351 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
6352 GNUNET_break (core_handle == server);
6353 if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
6356 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
6357 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6359 GNUNET_i2s (identity));
6360 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6362 GNUNET_i2s (&my_full_id));
6363 GNUNET_CORE_disconnect (core_handle);
6364 core_handle = GNUNET_CORE_connect (c, /* Main configuration */
6365 NULL, /* Closure passed to MESH functions */
6366 &core_init, /* Call core_init once connected */
6367 &core_connect, /* Handle connects */
6368 &core_disconnect, /* remove peers on disconnects */
6369 NULL, /* Don't notify about all incoming messages */
6370 GNUNET_NO, /* For header only in notification */
6371 NULL, /* Don't notify about all outbound messages */
6372 GNUNET_NO, /* For header-only out notification */
6373 core_handlers); /* Register these handlers */
6382 /******************************************************************************/
6383 /************************ MAIN FUNCTIONS ****************************/
6384 /******************************************************************************/
6387 * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
6389 * @param cls closure
6390 * @param key current key code
6391 * @param value value in the hash map
6392 * @return GNUNET_YES if we should continue to iterate,
6396 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
6398 struct MeshTunnel2 *t = value;
6406 * Task run during shutdown.
6412 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
6414 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
6416 if (core_handle != NULL)
6418 GNUNET_CORE_disconnect (core_handle);
6421 GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
6422 if (dht_handle != NULL)
6424 GNUNET_DHT_disconnect (dht_handle);
6429 GNUNET_SERVER_notification_context_destroy (nc);
6432 if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
6434 GNUNET_SCHEDULER_cancel (announce_id_task);
6435 announce_id_task = GNUNET_SCHEDULER_NO_TASK;
6437 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
6442 * Process mesh requests.
6444 * @param cls closure
6445 * @param server the initialized server
6446 * @param c configuration to use
6449 run (void *cls, struct GNUNET_SERVER_Handle *server,
6450 const struct GNUNET_CONFIGURATION_Handle *c)
6453 struct GNUNET_CRYPTO_EccPrivateKey *pk;
6455 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
6456 server_handle = server;
6457 GNUNET_SERVER_suspend (server_handle);
6460 GNUNET_CONFIGURATION_get_value_filename (c, "PEER", "PRIVATE_KEY",
6463 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6465 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6466 "mesh", "peer/privatekey");
6467 GNUNET_SCHEDULER_shutdown ();
6472 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_CONNECTION_TIME",
6473 &refresh_connection_time))
6475 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6477 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6478 "mesh", "refresh path time");
6479 GNUNET_SCHEDULER_shutdown ();
6484 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
6487 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6489 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6490 "mesh", "id announce time");
6491 GNUNET_SCHEDULER_shutdown ();
6496 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
6499 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6501 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6502 "mesh", "connect timeout");
6503 GNUNET_SCHEDULER_shutdown ();
6508 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
6511 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6513 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6514 "mesh", "max msgs queue");
6515 GNUNET_SCHEDULER_shutdown ();
6520 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_CONNECTIONS",
6523 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6525 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6526 "mesh", "max tunnels");
6527 GNUNET_SCHEDULER_shutdown ();
6532 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
6535 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6537 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
6538 "mesh", "default ttl", 64);
6543 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
6546 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6547 _("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
6548 "mesh", "max peers", 1000);
6553 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DROP_PERCENT",
6560 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6561 "Mesh is running with drop mode enabled. "
6562 "This is NOT a good idea! "
6563 "Remove the DROP_PERCENT option from your configuration.\n");
6567 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
6568 &dht_replication_level))
6570 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6572 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
6573 "mesh", "dht replication level", 3);
6574 dht_replication_level = 3;
6577 tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6578 peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6579 ports = GNUNET_CONTAINER_multihashmap32_create (32);
6581 dht_handle = GNUNET_DHT_connect (c, 64);
6582 if (NULL == dht_handle)
6586 stats = GNUNET_STATISTICS_create ("mesh", c);
6588 /* Scheduled the task to clean up when shutdown is called */
6589 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
6591 pk = GNUNET_CRYPTO_ecc_key_create_from_file (keyfile);
6592 GNUNET_free (keyfile);
6593 GNUNET_assert (NULL != pk);
6594 my_private_key = pk;
6595 GNUNET_CRYPTO_ecc_key_get_public (my_private_key, &my_public_key);
6596 GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
6597 &my_full_id.hashPubKey);
6598 myid = GNUNET_PEER_intern (&my_full_id);
6599 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6600 "Mesh for peer [%s] starting\n",
6601 GNUNET_i2s(&my_full_id));
6603 core_handle = GNUNET_CORE_connect (c, /* Main configuration */
6604 NULL, /* Closure passed to MESH functions */
6605 &core_init, /* Call core_init once connected */
6606 &core_connect, /* Handle connects */
6607 &core_disconnect, /* remove peers on disconnects */
6608 NULL, /* Don't notify about all incoming messages */
6609 GNUNET_NO, /* For header only in notification */
6610 NULL, /* Don't notify about all outbound messages */
6611 GNUNET_NO, /* For header-only out notification */
6612 core_handlers); /* Register these handlers */
6613 if (NULL == core_handle)
6616 GNUNET_SCHEDULER_shutdown ();
6619 announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
6620 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
6625 * The main function for the mesh service.
6627 * @param argc number of arguments from the command line
6628 * @param argv command line arguments
6629 * @return 0 ok, 1 on error
6632 main (int argc, char *const *argv)
6637 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
6638 r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
6640 ret = (GNUNET_OK == r) ? 0 : 1;
6641 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");