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 msg->cid = htonl (c->id);
1871 /* TODO add signature */
1873 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CONNECTION ACK sent!\n");
1874 return sizeof (struct GNUNET_MESH_ConnectionACK);
1879 * Destroy the peer_info and free any allocated resources linked to it
1881 * @param peer The peer_info to destroy.
1883 * @return GNUNET_OK on success
1886 peer_destroy (struct MeshPeer *peer)
1888 struct GNUNET_PeerIdentity id;
1889 struct MeshPeerPath *p;
1890 struct MeshPeerPath *nextp;
1892 GNUNET_PEER_resolve (peer->id, &id);
1893 GNUNET_PEER_change_rc (peer->id, -1);
1896 GNUNET_CONTAINER_multihashmap_remove (peers, &id.hashPubKey, peer))
1899 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1900 "removing peer %s, not in hashmap\n", GNUNET_i2s (&id));
1902 if (NULL != peer->dhtget)
1904 GNUNET_DHT_get_stop (peer->dhtget);
1906 p = peer->path_head;
1910 GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
1914 tunnel_destroy_empty (peer->tunnel);
1921 * Returns if peer is used (has a tunnel, is neighbor).
1923 * @peer Peer to check.
1925 * @return GNUNET_YES if peer is in use.
1928 peer_is_used (struct MeshPeer *peer)
1930 struct MeshPeerPath *p;
1932 if (NULL != peer->tunnel)
1935 for (p = peer->path_head; NULL != p; p = p->next)
1944 * Iterator over all the peers to get the oldest timestamp.
1946 * @param cls Closure (unsued).
1947 * @param key ID of the peer.
1948 * @param value Peer_Info of the peer.
1951 peer_get_oldest (void *cls,
1952 const struct GNUNET_HashCode *key,
1955 struct MeshPeer *p = value;
1956 struct GNUNET_TIME_Absolute *abs = cls;
1958 /* Don't count active peers */
1959 if (GNUNET_YES == peer_is_used (p))
1962 if (abs->abs_value_us < p->last_contact.abs_value_us)
1963 abs->abs_value_us = p->last_contact.abs_value_us;
1970 * Iterator over all the peers to remove the oldest entry.
1972 * @param cls Closure (unsued).
1973 * @param key ID of the peer.
1974 * @param value Peer_Info of the peer.
1977 peer_timeout (void *cls,
1978 const struct GNUNET_HashCode *key,
1981 struct MeshPeer *p = value;
1982 struct GNUNET_TIME_Absolute *abs = cls;
1984 if (p->last_contact.abs_value_us == abs->abs_value_us &&
1985 GNUNET_NO == peer_is_used (p))
1995 * Delete oldest unused peer.
1998 peer_delete_oldest (void)
2000 struct GNUNET_TIME_Absolute abs;
2002 abs = GNUNET_TIME_UNIT_FOREVER_ABS;
2004 GNUNET_CONTAINER_multihashmap_iterate (peers,
2007 GNUNET_CONTAINER_multihashmap_iterate (peers,
2014 * Retrieve the MeshPeer stucture associated with the peer, create one
2015 * and insert it in the appropriate structures if the peer is not known yet.
2017 * @param peer Full identity of the peer.
2019 * @return Existing or newly created peer info.
2021 static struct MeshPeer *
2022 peer_get (const struct GNUNET_PeerIdentity *peer_id)
2024 struct MeshPeer *peer;
2026 peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer_id->hashPubKey);
2029 peer = GNUNET_new (struct MeshPeer);
2030 if (GNUNET_CONTAINER_multihashmap_size (peers) > max_peers)
2032 peer_delete_oldest ();
2034 GNUNET_CONTAINER_multihashmap_put (peers, &peer_id->hashPubKey, peer,
2035 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
2036 peer->id = GNUNET_PEER_intern (peer_id);
2038 peer->last_contact = GNUNET_TIME_absolute_get();
2045 * Retrieve the MeshPeer stucture associated with the peer, create one
2046 * and insert it in the appropriate structures if the peer is not known yet.
2048 * @param peer Short identity of the peer.
2050 * @return Existing or newly created peer info.
2052 static struct MeshPeer *
2053 peer_get_short (const GNUNET_PEER_Id peer)
2055 return peer_get (GNUNET_PEER_resolve2 (peer));
2060 * Get a cost of a path for a peer considering existing tunnel connections.
2062 * @param peer Peer towards which the path is considered.
2063 * @param path Candidate path.
2065 * @return Cost of the path (path length + number of overlapping nodes)
2068 peer_get_path_cost (const struct MeshPeer *peer,
2069 const struct MeshPeerPath *path)
2071 struct MeshConnection *c;
2072 unsigned int overlap;
2080 GNUNET_assert (NULL != peer->tunnel);
2082 for (i = 0; i < path->length; i++)
2084 for (c = peer->tunnel->connection_head; NULL != c; c = c->next)
2086 for (j = 0; j < c->path->length; j++)
2088 if (path->peers[i] == c->path->peers[j])
2096 return (path->length + overlap) * (path->score * -1);
2101 * Choose the best path towards a peer considering the tunnel properties.
2103 * @param peer The destination peer.
2105 * @return Best current known path towards the peer, if any.
2107 static struct MeshPeerPath *
2108 peer_get_best_path (const struct MeshPeer *peer)
2110 struct MeshPeerPath *best_p;
2111 struct MeshPeerPath *p;
2112 struct MeshConnection *c;
2113 unsigned int best_cost;
2116 best_cost = UINT_MAX;
2118 for (p = peer->path_head; NULL != p; p = p->next)
2120 for (c = peer->tunnel->connection_head; NULL != c; c = c->next)
2124 continue; /* If path is in use in a connection, skip it. */
2126 if ((cost = peer_get_path_cost (peer, p)) < best_cost)
2136 queue_is_sendable (struct MeshPeerQueue *q)
2138 struct MeshFlowControl *fc;
2140 /* Is PID-independent? */
2143 case GNUNET_MESSAGE_TYPE_MESH_ACK:
2144 case GNUNET_MESSAGE_TYPE_MESH_POLL:
2148 /* Is PID allowed? */
2149 fc = q->fwd ? &q->c->fwd_fc : &q->c->bck_fc;
2150 if (GMC_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
2158 * Get first sendable message.
2160 * @param peer The destination peer.
2162 * @return Best current known path towards the peer, if any.
2164 static struct MeshPeerQueue *
2165 peer_get_first_message (const struct MeshPeer *peer)
2167 struct MeshPeerQueue *q;
2169 for (q = peer->queue_head; NULL != q; q = q->next)
2171 if (queue_is_sendable (q))
2180 * Try to establish a new connection to this peer in the given tunnel.
2181 * If the peer doesn't have any path to it yet, try to get one.
2182 * If the peer already has some path, send a CREATE CONNECTION towards it.
2184 * @param peer PeerInfo of the peer.
2187 peer_connect (struct MeshPeer *peer)
2189 struct MeshTunnel2 *t;
2190 struct MeshPeerPath *p;
2191 struct MeshConnection *c;
2193 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2194 "peer_connect towards %s\n",
2197 if (NULL != peer->path_head)
2199 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "path exists\n");
2200 p = peer_get_best_path (peer);
2203 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " %u hops\n", p->length);
2204 c = tunnel_use_path (t, p);
2205 send_connection_create (c);
2208 else if (NULL == peer->dhtget)
2210 const struct GNUNET_PeerIdentity *id;
2212 id = GNUNET_PEER_resolve2 (peer->id);
2213 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2214 " Starting DHT GET for peer %s\n", peer2s (peer));
2215 peer->dhtget = GNUNET_DHT_get_start (dht_handle, /* handle */
2216 GNUNET_BLOCK_TYPE_MESH_PEER, /* type */
2217 &id->hashPubKey, /* key to search */
2218 dht_replication_level, /* replication level */
2219 GNUNET_DHT_RO_RECORD_ROUTE |
2220 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
2222 0, /* xquery bits */
2223 &dht_get_id_handler, peer);
2224 if (MESH_TUNNEL_NEW == t->state)
2225 tunnel_change_state (t, MESH_TUNNEL_SEARCHING);
2229 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2230 "There is no path but the DHT GET is already started.\n");
2236 * Get the first transmittable message for a connection.
2238 * @param c Connection.
2239 * @param fwd Is this FWD?
2241 * @return First transmittable message.
2243 static struct MeshPeerQueue *
2244 connection_get_first_message (struct MeshConnection *c, int fwd)
2246 struct MeshPeerQueue *q;
2249 p = connection_get_hop (c, fwd);
2251 for (q = p->queue_head; NULL != q; q = q->next)
2255 if (queue_is_sendable (q))
2264 * Is this peer the last one on the connection?
2266 * @param c Connection.
2267 * @param fwd Is this about fwd traffic?
2268 * Note that the ROOT is the terminal for BCK traffic!
2270 * @return GNUNET_YES if terminal, GNUNET_NO if relay/origin.
2273 connection_is_terminal (struct MeshConnection *c, int fwd)
2275 if (fwd && c->own_pos == c->path->length - 1)
2277 if (!fwd && c->own_pos == 0)
2284 * @brief Re-initiate traffic on this connection if necessary.
2286 * Check if there is traffic queued towards this peer
2287 * and the core transmit handle is NULL (traffic was stalled).
2288 * If so, call core tmt rdy.
2290 * @param c Connection on which initiate traffic.
2291 * @param fwd Is this about fwd traffic?
2294 connection_unlock_queue (struct MeshConnection *c, int fwd)
2296 struct MeshPeer *peer;
2297 struct MeshPeerQueue *q;
2300 peer = connection_get_hop (c, fwd);
2302 if (NULL != peer->core_transmit)
2303 return; /* Already unlocked */
2305 q = connection_get_first_message (c, fwd);
2307 return; /* Nothing to transmit */
2310 peer->core_transmit =
2311 GNUNET_CORE_notify_transmit_ready (core_handle,
2314 GNUNET_TIME_UNIT_FOREVER_REL,
2315 GNUNET_PEER_resolve2 (peer->id),
2323 * Cancel all transmissions that belong to a certain connection.
2325 * @param c Connection which to cancel.
2326 * @param fwd Cancel fwd traffic?
2329 connection_cancel_queues (struct MeshConnection *c, int fwd)
2331 struct MeshPeerQueue *q;
2332 struct MeshPeerQueue *next;
2333 struct MeshFlowControl *fc;
2334 struct MeshPeer *peer;
2341 fc = fwd ? &c->fwd_fc : &c->bck_fc;
2342 peer = connection_get_hop (c, fwd);
2344 for (q = peer->queue_head; NULL != q; q = next)
2349 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2350 "connection_cancel_queue %s\n",
2351 GNUNET_MESH_DEBUG_M2S (q->type));
2352 queue_destroy (q, GNUNET_YES);
2355 if (NULL == peer->queue_head)
2357 if (NULL != peer->core_transmit)
2359 GNUNET_CORE_notify_transmit_ready_cancel (peer->core_transmit);
2360 peer->core_transmit = NULL;
2362 if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
2364 GNUNET_SCHEDULER_cancel (fc->poll_task);
2365 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2372 * Remove all paths that rely on a direct connection between p1 and p2
2373 * from the peer itself and notify all tunnels about it.
2375 * @param peer PeerInfo of affected peer.
2376 * @param p1 GNUNET_PEER_Id of one peer.
2377 * @param p2 GNUNET_PEER_Id of another peer that was connected to the first and
2380 * TODO: optimize (see below)
2383 peer_remove_path (struct MeshPeer *peer, GNUNET_PEER_Id p1,
2386 struct MeshPeerPath *p;
2387 struct MeshPeerPath *next;
2388 struct MeshPeer *peer_d;
2390 unsigned int destroyed;
2393 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path\n");
2395 for (p = peer->path_head; NULL != p; p = next)
2398 for (i = 0; i < (p->length - 1); i++)
2400 if ((p->peers[i] == p1 && p->peers[i + 1] == p2) ||
2401 (p->peers[i] == p2 && p->peers[i + 1] == p1))
2403 GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
2414 d = tunnel_notify_connection_broken (peer->tunnel, p1, p2);
2416 peer_d = peer_get_short (d); // FIXME
2417 next = peer_get_best_path (peer_d);
2418 tunnel_use_path (peer->tunnel, next);
2419 peer_connect (peer_d);
2421 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path END\n");
2426 * Add the path to the peer and update the path used to reach it in case this
2429 * @param peer_info Destination peer to add the path to.
2430 * @param path New path to add. Last peer must be the peer in arg 1.
2431 * Path will be either used of freed if already known.
2432 * @param trusted Do we trust that this path is real?
2435 peer_add_path (struct MeshPeer *peer_info, struct MeshPeerPath *path,
2438 struct MeshPeerPath *aux;
2442 if ((NULL == peer_info) || (NULL == path))
2445 path_destroy (path);
2448 if (path->peers[path->length - 1] != peer_info->id)
2451 path_destroy (path);
2454 if (2 >= path->length && GNUNET_NO == trusted)
2456 /* Only allow CORE to tell us about direct paths */
2457 path_destroy (path);
2460 for (l = 1; l < path->length; l++)
2462 if (path->peers[l] == myid)
2464 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shortening path by %u\n", l);
2465 for (l2 = 0; l2 < path->length - l; l2++)
2467 path->peers[l2] = path->peers[l + l2];
2472 GNUNET_realloc (path->peers, path->length * sizeof (GNUNET_PEER_Id));
2476 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "adding path [%u] to peer %s\n",
2477 path->length, peer2s (peer_info));
2479 l = path_get_length (path);
2482 path_destroy (path);
2486 GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
2487 for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
2489 l2 = path_get_length (aux);
2492 GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
2493 peer_info->path_tail, aux, path);
2498 if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
2500 path_destroy (path);
2505 GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head, peer_info->path_tail,
2512 * Add the path to the origin peer and update the path used to reach it in case
2513 * this is the shortest.
2514 * The path is given in peer_info -> destination, therefore we turn the path
2515 * upside down first.
2517 * @param peer_info Peer to add the path to, being the origin of the path.
2518 * @param path New path to add after being inversed.
2519 * Path will be either used or freed.
2520 * @param trusted Do we trust that this path is real?
2523 peer_add_path_to_origin (struct MeshPeer *peer_info,
2524 struct MeshPeerPath *path, int trusted)
2527 peer_add_path (peer_info, path, trusted);
2533 * Function called if a connection has been stalled for a while,
2534 * possibly due to a missed ACK. Poll the neighbor about its ACK status.
2536 * @param cls Closure (poll ctx).
2537 * @param tc TaskContext.
2540 connection_poll (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2542 struct MeshFlowControl *fc = cls;
2543 struct GNUNET_MESH_Poll msg;
2544 struct MeshConnection *c;
2546 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2547 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2553 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** Polling!\n");
2554 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** connection %s[%X]\n",
2555 peer2s (c->t->peer), c->id);
2557 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_POLL);
2558 msg.header.size = htons (sizeof (msg));
2559 msg.pid = htonl (fc->last_pid_sent);
2560 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** pid (%u)!\n", fc->last_pid_sent);
2561 send_prebuilt_message_connection (&msg.header, c, NULL, fc == &c->fwd_fc);
2562 fc->poll_time = GNUNET_TIME_STD_BACKOFF (fc->poll_time);
2563 fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
2564 &connection_poll, fc);
2569 * Build a PeerPath from the paths returned from the DHT, reversing the paths
2570 * to obtain a local peer -> destination path and interning the peer ids.
2572 * @return Newly allocated and created path
2574 static struct MeshPeerPath *
2575 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
2576 unsigned int get_path_length,
2577 const struct GNUNET_PeerIdentity *put_path,
2578 unsigned int put_path_length)
2580 struct MeshPeerPath *p;
2586 GNUNET_PEER_change_rc (myid, 1);
2587 i = get_path_length;
2588 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " GET has %d hops.\n", i);
2589 for (i--; i >= 0; i--)
2591 id = GNUNET_PEER_intern (&get_path[i]);
2592 if (p->length > 0 && id == p->peers[p->length - 1])
2594 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Optimizing 1 hop out.\n");
2595 GNUNET_PEER_change_rc (id, -1);
2599 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Adding from GET: %s.\n",
2600 GNUNET_i2s (&get_path[i]));
2602 p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2603 p->peers[p->length - 1] = id;
2606 i = put_path_length;
2607 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " PUT has %d hops.\n", i);
2608 for (i--; i >= 0; i--)
2610 id = GNUNET_PEER_intern (&put_path[i]);
2613 /* PUT path went through us, so discard the path up until now and start
2614 * from here to get a much shorter (and loop-free) path.
2619 if (p->length > 0 && id == p->peers[p->length - 1])
2621 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Optimizing 1 hop out.\n");
2622 GNUNET_PEER_change_rc (id, -1);
2626 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Adding from PUT: %s.\n",
2627 GNUNET_i2s (&put_path[i]));
2629 p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2630 p->peers[p->length - 1] = id;
2634 if (get_path_length > 0)
2635 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " (first of GET: %s)\n",
2636 GNUNET_i2s (&get_path[0]));
2637 if (put_path_length > 0)
2638 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " (first of PUT: %s)\n",
2639 GNUNET_i2s (&put_path[0]));
2640 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " In total: %d hops\n",
2642 for (i = 0; i < p->length; i++)
2644 struct GNUNET_PeerIdentity peer_id;
2646 GNUNET_PEER_resolve (p->peers[i], &peer_id);
2647 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " %u: %s\n", p->peers[i],
2648 GNUNET_i2s (&peer_id));
2656 * Adds a path to the peer_infos of all the peers in the path
2658 * @param p Path to process.
2659 * @param confirmed Whether we know if the path works or not.
2662 path_add_to_peers (struct MeshPeerPath *p, int confirmed)
2666 /* TODO: invert and add */
2667 for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
2668 for (i++; i < p->length; i++)
2670 struct MeshPeer *aux;
2671 struct MeshPeerPath *copy;
2673 aux = peer_get_short (p->peers[i]);
2674 copy = path_duplicate (p);
2675 copy->length = i + 1;
2676 peer_add_path (aux, copy, p->length < 3 ? GNUNET_NO : confirmed);
2682 * Search for a channel among the channels for a client
2684 * @param c the client whose channels to search in
2685 * @param chid the local id of the channel
2687 * @return channel handler, NULL if doesn't exist
2689 static struct MeshChannel *
2690 channel_get_by_local_id (struct MeshClient *c, MESH_ChannelNumber chid)
2692 if (0 == (chid & GNUNET_MESH_LOCAL_CHANNEL_ID_CLI))
2694 GNUNET_break_op (0);
2695 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CHID %X not a local chid\n", chid);
2698 if (chid >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV)
2699 return GNUNET_CONTAINER_multihashmap32_get (c->incoming_channels, chid);
2700 return GNUNET_CONTAINER_multihashmap32_get (c->own_channels, chid);
2704 * Search for a tunnel by global ID using full PeerIdentities.
2706 * @param t Tunnel containing the channel.
2707 * @param chid Public channel number.
2709 * @return channel handler, NULL if doesn't exist
2711 static struct MeshChannel *
2712 channel_get (struct MeshTunnel2 *t, MESH_ChannelNumber chid)
2714 struct MeshChannel *ch;
2719 for (ch = t->channel_head; NULL != ch; ch = ch->next)
2721 if (ch->gid == chid)
2730 * Change the tunnel state.
2732 * @param t Tunnel whose state to change.
2733 * @param state New state.
2736 tunnel_change_state (struct MeshTunnel2* t, enum MeshTunnelState state)
2738 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2739 "Tunnel %s state was %s\n",
2741 GNUNET_MESH_DEBUG_TS2S (t->state));
2742 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2743 "Tunnel %s state is now %s\n",
2745 GNUNET_MESH_DEBUG_TS2S (state));
2751 connection_change_state (struct MeshConnection* c,
2752 enum MeshConnectionState state)
2754 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2755 "Connection %s[%X] state was %s\n",
2756 peer2s (c->t->peer), c->id,
2757 GNUNET_MESH_DEBUG_CS2S (c->state));
2758 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2759 "Connection %s[%X] state is now %s\n",
2760 peer2s (c->t->peer), c->id,
2761 GNUNET_MESH_DEBUG_CS2S (state));
2767 * Add a client to a channel, initializing all needed data structures.
2769 * @param ch Channel to which add the client.
2770 * @param c Client which to add to the channel.
2773 channel_add_client (struct MeshChannel *ch, struct MeshClient *c)
2775 struct MeshTunnel2 *t = ch->t;
2777 if (NULL != ch->dest)
2783 /* Assign local id as destination */
2784 while (NULL != channel_get_by_local_id (c, t->next_local_chid))
2785 t->next_local_chid = (t->next_local_chid + 1) | GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
2786 ch->lid_dest = t->next_local_chid++;
2787 t->next_local_chid = t->next_local_chid | GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
2789 /* Store in client's hashmap */
2791 GNUNET_CONTAINER_multihashmap32_put (c->incoming_channels,
2793 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2802 static struct MeshConnection *
2803 tunnel_use_path (struct MeshTunnel2 *t, struct MeshPeerPath *p)
2805 struct MeshConnection *c;
2806 unsigned int own_pos;
2808 c = connection_new (&t->id, t->next_cid++);
2809 for (own_pos = 0; own_pos < p->length; own_pos++)
2811 if (p->peers[own_pos] == myid)
2814 if (own_pos > p->length - 1)
2817 connection_destroy (c);
2820 c->own_pos = own_pos;
2825 c->fwd_maintenance_task =
2826 GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
2827 &connection_fwd_keepalive, c);
2834 * Notifies a tunnel that a connection has broken that affects at least
2835 * some of its peers. Sends a notification towards the root of the tree.
2836 * In case the peer is the owner of the tree, notifies the client that owns
2837 * the tunnel and tries to reconnect.
2839 * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
2841 * @param t Tunnel affected.
2842 * @param p1 Peer that got disconnected from p2.
2843 * @param p2 Peer that got disconnected from p1.
2845 * @return Short ID of the peer disconnected (either p1 or p2).
2846 * 0 if the tunnel remained unaffected.
2848 static GNUNET_PEER_Id
2849 tunnel_notify_connection_broken (struct MeshTunnel2* t,
2850 GNUNET_PEER_Id p1, GNUNET_PEER_Id p2)
2852 // if (myid != p1 && myid != p2) FIXME
2857 // if (tree_get_predecessor (t->tree) != 0)
2859 // /* We are the peer still connected, notify owner of the disconnection. */
2860 // struct GNUNET_MESH_PathBroken msg;
2861 // struct GNUNET_PeerIdentity neighbor;
2863 // msg.header.size = htons (sizeof (msg));
2864 // msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN);
2865 // GNUNET_PEER_resolve (t->id.oid, &msg.oid);
2866 // msg.tid = htonl (t->id.tid);
2867 // msg.peer1 = my_full_id;
2868 // GNUNET_PEER_resolve (pid, &msg.peer2);
2869 // GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &neighbor);
2870 // send_prebuilt_message (&msg.header, &neighbor, t);
2877 * Send an end-to-end FWD ACK message for the most recent in-sequence payload.
2879 * @param ch Channel this is about.
2880 * @param fwd Is for FWD traffic? (ACK dest->owner)
2883 channel_send_data_ack (struct MeshChannel *ch, int fwd)
2885 struct GNUNET_MESH_DataACK msg;
2886 struct MeshChannelReliability *rel;
2887 struct MeshReliableMessage *copy;
2892 if (GNUNET_NO == ch->reliable)
2897 rel = fwd ? ch->bck_rel : ch->fwd_rel;
2898 mid = fwd ? &ch->mid_recv_fwd : &ch->mid_recv_bck;
2899 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2900 "send_data_ack for %u\n",
2903 msg.header.type = htons (fwd ? GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK :
2904 GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK);
2905 msg.header.size = htons (sizeof (msg));
2906 msg.chid = htonl (ch->gid);
2907 msg.mid = htonl (*mid - 1);
2909 for (copy = rel->head_recv; NULL != copy; copy = copy->next)
2911 delta = copy->mid - *mid;
2914 mask = 0x1LL << delta;
2915 msg.futures |= mask;
2916 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2917 " setting bit for %u (delta %u) (%llX) -> %llX\n",
2918 copy->mid, delta, mask, msg.futures);
2920 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " final futures %llX\n", msg.futures);
2922 send_prebuilt_message_channel (&msg.header, ch, fwd);
2923 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_data_ack END\n");
2928 * Send an ACK informing the predecessor about the available buffer space.
2930 * Note that for fwd ack, the FWD mean forward *traffic* (root->dest),
2931 * the ACK itself goes "back" (dest->root).
2933 * @param c Connection on which to send the ACK.
2934 * @param fwd Is this FWD ACK? (Going dest->owner)
2937 connection_send_ack (struct MeshConnection *c, int fwd)
2939 struct MeshFlowControl *next_fc;
2940 struct MeshFlowControl *prev_fc;
2944 next_fc = fwd ? &c->fwd_fc : &c->bck_fc;
2945 prev_fc = fwd ? &c->bck_fc : &c->fwd_fc;
2947 /* Check if we need to transmit the ACK */
2948 if (prev_fc->last_ack_sent - prev_fc->last_pid_recv > 3)
2950 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer > 3\n");
2951 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2952 " last pid recv: %u, last ack sent: %u\n",
2953 prev_fc->last_pid_recv, prev_fc->last_ack_sent);
2957 /* Ok, ACK might be necessary, what PID to ACK? */
2958 delta = next_fc->queue_max - next_fc->queue_n;
2959 ack = prev_fc->last_pid_recv + delta;
2960 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", ack);
2961 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2962 " last pid %u, last ack %u, qmax %u, q %u\n",
2963 prev_fc->last_pid_recv, prev_fc->last_ack_sent,
2964 next_fc->queue_max, next_fc->queue_n);
2965 if (ack == prev_fc->last_ack_sent)
2967 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not needed\n");
2971 prev_fc->last_ack_sent = ack;
2972 send_ack (c, ack, fwd);
2977 * Send an ACK informing the client about available buffer space.
2979 * Note that although the name is fwd_ack, the FWD mean forward *traffic*,
2980 * the ACK itself goes "back" (towards root).
2982 * @param ch Channel on which to send the ACK, NULL if unknown.
2983 * @param fwd Is this FWD ACK? (Going dest->owner)
2986 // channel_send_ack (struct MeshChannel *ch, uint16_t type, int fwd)
2988 // struct MeshChannelReliability *rel;
2989 // struct MeshFlowControl *next_fc;
2990 // struct MeshFlowControl *prev_fc;
2991 // struct MeshClient *c;
2992 // struct MeshClient *o;
2993 // GNUNET_PEER_Id hop;
2994 // uint32_t delta_mid;
2998 // rel = fwd ? ch->fwd_rel : ch->bck_rel;
2999 // c = fwd ? ch->client : ch->owner;
3000 // o = fwd ? ch->owner : ch->client;
3001 // hop = fwd ? connection_get_prev_hop (cn) : connection_get_next_hop (cn);
3002 // next_fc = fwd ? &t->next_fc : &t->prev_fc;
3003 // prev_fc = fwd ? &t->prev_fc : &t->next_fc;
3007 // case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3008 // case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3009 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3010 // "ACK due to %s\n",
3011 // GNUNET_MESH_DEBUG_M2S (type));
3012 // if (GNUNET_YES == t->nobuffer && (GNUNET_NO == t->reliable || NULL == c))
3014 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, nobuffer\n");
3017 // if (GNUNET_YES == t->reliable && NULL != c)
3018 // tunnel_send_data_ack (t, fwd);
3020 // case GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK:
3021 // case GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK:
3022 // case GNUNET_MESSAGE_TYPE_MESH_ACK:
3023 // case GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK:
3025 // case GNUNET_MESSAGE_TYPE_MESH_POLL:
3026 // case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
3027 // t->force_ack = GNUNET_YES;
3030 // GNUNET_break (0);
3033 // /* Check if we need to transmit the ACK */
3035 // prev_fc->last_ack_sent - prev_fc->last_pid_recv > 3 &&
3036 // GNUNET_NO == t->force_ack)
3038 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer free\n");
3039 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3040 // " last pid recv: %u, last ack sent: %u\n",
3041 // prev_fc->last_pid_recv, prev_fc->last_ack_sent);
3045 // /* Ok, ACK might be necessary, what PID to ACK? */
3046 // delta = t->queue_max - next_fc->queue_n;
3047 // if (NULL != o && GNUNET_YES == t->reliable && NULL != rel->head_sent)
3048 // delta_mid = rel->mid_sent - rel->head_sent->mid;
3051 // if (0 > delta || (GNUNET_YES == t->reliable &&
3053 // (10 < rel->n_sent || 64 <= delta_mid)))
3055 // if (NULL != o && delta > 1)
3057 // ack = prev_fc->last_pid_recv + delta;
3058 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", ack);
3059 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3060 // " last pid %u, last ack %u, qmax %u, q %u\n",
3061 // prev_fc->last_pid_recv, prev_fc->last_ack_sent,
3062 // t->queue_max, next_fc->queue_n);
3063 // if (ack == prev_fc->last_ack_sent && GNUNET_NO == t->force_ack)
3065 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not needed\n");
3069 // prev_fc->last_ack_sent = ack;
3071 // send_local_ack (t, o, fwd);
3072 // else if (0 != hop)
3073 // send_ack (t, hop, ack);
3075 // GNUNET_break (GNUNET_YES == t->destroy);
3076 // t->force_ack = GNUNET_NO;
3081 * Modify the mesh message TID from global to local and send to client.
3083 * @param ch Channel on which to send the message.
3084 * @param msg Message to modify and send.
3085 * @param c Client to send to.
3086 * @param tid Tunnel ID to use (c can be both owner and client).
3089 channel_send_client_to_tid (struct MeshChannel *ch,
3090 const struct GNUNET_MESH_Data *msg,
3091 struct MeshClient *c, MESH_ChannelNumber id)
3093 struct GNUNET_MESH_LocalData *copy;
3094 uint16_t size = ntohs (msg->header.size) - sizeof (struct GNUNET_MESH_Data);
3095 char cbuf[size + sizeof (struct GNUNET_MESH_LocalData)];
3097 if (size < sizeof (struct GNUNET_MessageHeader))
3099 GNUNET_break_op (0);
3107 copy = (struct GNUNET_MESH_LocalData *) cbuf;
3108 memcpy (©[1], &msg[1], size);
3109 copy->header.size = htons (sizeof (struct GNUNET_MESH_LocalData) + size);
3110 copy->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA);
3111 copy->id = htonl (id);
3112 GNUNET_SERVER_notification_context_unicast (nc, c->handle,
3113 ©->header, GNUNET_NO);
3117 * Modify the data message ID from global to local and send to client.
3119 * @param ch Channel on which to send the message.
3120 * @param msg Message to modify and send.
3121 * @param fwd Forward?
3124 channel_send_client_data (struct MeshChannel *ch,
3125 const struct GNUNET_MESH_Data *msg,
3129 channel_send_client_to_tid (ch, msg, ch->dest, ch->lid_dest);
3131 channel_send_client_to_tid (ch, msg, ch->root, ch->lid_root);
3136 * Send a buffered message to the client, for in order delivery or
3137 * as result of client ACK.
3139 * @param ch Channel on which to empty the message buffer.
3140 * @param c Client to send to.
3141 * @param rel Reliability structure to corresponding peer.
3142 * If rel == bck_rel, this is FWD data.
3145 channel_send_client_buffered_data (struct MeshChannel *ch,
3146 struct MeshClient *c,
3147 struct MeshChannelReliability *rel)
3149 struct MeshReliableMessage *copy;
3152 if (GNUNET_NO == rel->client_ready)
3154 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client not ready\n");
3158 mid = rel == ch->bck_rel ? &ch->mid_recv_fwd : &ch->mid_recv_bck;
3160 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data\n");
3161 copy = rel->head_recv;
3164 if (copy->mid == *mid || GNUNET_NO == ch->reliable)
3166 struct GNUNET_MESH_Data *msg = (struct GNUNET_MESH_Data *) ©[1];
3168 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3169 " have %u! now expecting %u\n",
3170 copy->mid, *mid + 1);
3171 channel_send_client_data (ch, msg, (rel == ch->bck_rel));
3174 GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
3179 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3180 " reliable && don't have %u, next is %u\n",
3186 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data END\n");
3191 * We have received a message out of order, or the client is not ready.
3192 * Buffer it until we receive an ACK from the client or the missing
3193 * message from the channel.
3195 * @param msg Message to buffer.
3196 * @param rel Reliability data to the corresponding direction.
3199 channel_rel_add_buffered_data (const struct GNUNET_MESH_Data *msg,
3200 struct MeshChannelReliability *rel)
3202 struct MeshReliableMessage *copy;
3203 struct MeshReliableMessage *prev;
3207 size = ntohs (msg->header.size);
3208 mid = ntohl (msg->mid);
3209 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data %u\n", mid);
3211 copy = GNUNET_malloc (sizeof (*copy) + size);
3214 memcpy (©[1], msg, size);
3218 // FIXME do something better than O(n), although n < 64...
3219 // FIXME start from the end (most messages are the latest ones)
3220 for (prev = rel->head_recv; NULL != prev; prev = prev->next)
3222 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " prev %u\n", prev->mid);
3223 if (GMC_is_pid_bigger (prev->mid, mid))
3225 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " bingo!\n");
3226 GNUNET_CONTAINER_DLL_insert_before (rel->head_recv, rel->tail_recv,
3231 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " insert at tail!\n");
3232 GNUNET_CONTAINER_DLL_insert_tail (rel->head_recv, rel->tail_recv, copy);
3233 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data END\n");
3238 * Destroy a reliable message after it has been acknowledged, either by
3239 * direct mid ACK or bitfield. Updates the appropriate data structures and
3240 * timers and frees all memory.
3242 * @param copy Message that is no longer needed: remote peer got it.
3245 rel_message_free (struct MeshReliableMessage *copy)
3247 struct MeshChannelReliability *rel;
3248 struct GNUNET_TIME_Relative time;
3251 time = GNUNET_TIME_absolute_get_duration (copy->timestamp);
3252 rel->expected_delay.rel_value_us *= 7;
3253 rel->expected_delay.rel_value_us += time.rel_value_us;
3254 rel->expected_delay.rel_value_us /= 8;
3256 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Freeing %u\n", copy->mid);
3257 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " n_sent %u\n", rel->n_sent);
3258 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! took %s\n",
3259 GNUNET_STRINGS_relative_time_to_string (time, GNUNET_NO));
3260 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! new expected delay %s\n",
3261 GNUNET_STRINGS_relative_time_to_string (rel->expected_delay,
3263 rel->retry_timer = rel->expected_delay;
3264 GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
3270 * Destroy all reliable messages queued for a channel,
3271 * during a channel destruction.
3272 * Frees the reliability structure itself.
3274 * @param rel Reliability data for a channel.
3277 channel_rel_free_all (struct MeshChannelReliability *rel)
3279 struct MeshReliableMessage *copy;
3280 struct MeshReliableMessage *next;
3285 for (copy = rel->head_recv; NULL != copy; copy = next)
3288 GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
3291 for (copy = rel->head_sent; NULL != copy; copy = next)
3294 GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
3297 if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
3298 GNUNET_SCHEDULER_cancel (rel->retry_task);
3304 * Mark future messages as ACK'd.
3306 * @param rel Reliability data.
3307 * @param msg DataACK message with a bitfield of future ACK'd messages.
3310 channel_rel_free_sent (struct MeshChannelReliability *rel,
3311 const struct GNUNET_MESH_DataACK *msg)
3313 struct MeshReliableMessage *copy;
3314 struct MeshReliableMessage *next;
3321 bitfield = msg->futures;
3322 mid = ntohl (msg->mid);
3323 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3324 "free_sent_reliable %u %llX\n",
3326 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3327 " rel %p, head %p\n",
3328 rel, rel->head_sent);
3329 for (i = 0, copy = rel->head_sent;
3330 i < 64 && NULL != copy && 0 != bitfield;
3333 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3334 " trying bit %u (mid %u)\n",
3337 if (0 == (bitfield & mask))
3340 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " set!\n");
3341 /* Bit was set, clear the bit from the bitfield */
3344 /* The i-th bit was set. Do we have that copy? */
3345 /* Skip copies with mid < target */
3346 target = mid + i + 1;
3347 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " target %u\n", target);
3348 while (NULL != copy && GMC_is_pid_bigger (target, copy->mid))
3351 /* Did we run out of copies? (previously freed, it's ok) */
3354 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "run out of copies...\n");
3358 /* Did we overshoot the target? (previously freed, it's ok) */
3359 if (GMC_is_pid_bigger (copy->mid, target))
3361 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " next copy %u\n", copy->mid);
3365 /* Now copy->mid == target, free it */
3367 rel_message_free (copy);
3370 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "free_sent_reliable END\n");
3375 * We haven't received an ACK after a certain time: restransmit the message.
3377 * @param cls Closure (MeshReliableMessage with the message to restransmit)
3378 * @param tc TaskContext.
3381 channel_retransmit_message (void *cls,
3382 const struct GNUNET_SCHEDULER_TaskContext *tc)
3384 struct MeshChannelReliability *rel = cls;
3385 struct MeshReliableMessage *copy;
3386 struct MeshPeerQueue *q;
3387 struct MeshChannel *ch;
3388 struct MeshConnection *c;
3389 struct GNUNET_MESH_Data *payload;
3390 struct MeshPeer *hop;
3393 rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
3394 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3398 copy = rel->head_sent;
3405 /* Search the message to be retransmitted in the outgoing queue.
3406 * Check only the queue for the connection that is going to be used,
3407 * if the message is stuck in some other connection's queue we shouldn't
3409 * - cancelling it and sending the new one doesn't guarantee it's delivery,
3410 * the old connection could be temporary stalled or the queue happened to
3411 * be long at time of insertion.
3412 * - not sending the new one could cause terrible delays the old connection
3415 payload = (struct GNUNET_MESH_Data *) ©[1];
3416 fwd = (rel == ch->fwd_rel);
3417 c = tunnel_get_connection (ch->t, fwd);
3418 hop = connection_get_hop (c, fwd);
3419 for (q = hop->queue_head; NULL != q; q = q->next)
3421 if (ntohs (payload->header.type) == q->type && ch == q->ch)
3423 struct GNUNET_MESH_Data *queued_data = q->cls;
3425 if (queued_data->mid == payload->mid)
3430 /* Message not found in the queue that we are going to use. */
3433 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! RETRANSMIT %u\n", copy->mid);
3435 send_prebuilt_message_channel (&payload->header, ch, ch->fwd_rel == rel);
3436 GNUNET_STATISTICS_update (stats, "# data retransmitted", 1, GNUNET_NO);
3440 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! ALREADY IN QUEUE %u\n", copy->mid);
3443 rel->retry_timer = GNUNET_TIME_STD_BACKOFF (rel->retry_timer);
3444 rel->retry_task = GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
3445 &channel_retransmit_message,
3452 * Send ACK on one or more connections due to buffer space to the client.
3455 channel_send_ack (struct MeshChannel *ch, uint32_t buffer, int fwd)
3457 struct MeshTunnel2 *t = ch->t;
3458 struct MeshConnection *c;
3459 struct MeshFlowControl *fc;
3464 /* Count connections, how many messages are already allowed */
3465 for (cs = 0, allowed = 0, c = t->connection_head; NULL != c; c = c->next)
3467 fc = fwd ? &c->fwd_fc : &c->bck_fc;
3468 if (GMC_is_pid_bigger(fc->last_pid_recv, fc->last_ack_sent))
3473 allowed += fc->last_ack_sent - fc->last_pid_recv;
3477 /* Make sure there is no overflow */
3478 if (allowed > buffer)
3484 /* Authorize connections to send more data */
3485 to_allow = buffer - allowed;
3486 for (c = t->connection_head; NULL != c && to_allow > 0; c = c->next)
3488 fc = fwd ? &c->fwd_fc : &c->bck_fc;
3489 if (fc->last_ack_sent - fc->last_pid_recv > 64 / 3)
3493 send_ack (c, fc->last_ack_sent + 1, fwd);
3497 GNUNET_break (to_allow == 0);
3502 * Send keepalive packets for a connection.
3504 * @param c Connection to keep alive..
3505 * @param fwd Is this a FWD keepalive? (owner -> dest).
3508 connection_keepalive (struct MeshConnection *c, int fwd)
3510 struct GNUNET_MESH_ConnectionKeepAlive *msg;
3511 size_t size = sizeof (struct GNUNET_MESH_ConnectionKeepAlive);
3515 type = fwd ? GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE :
3516 GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE;
3518 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3519 "sending %s keepalive for connection %s[%d]\n",
3520 fwd ? "FWD" : "BCK",
3521 peer2s (c->t->peer),
3524 msg = (struct GNUNET_MESH_ConnectionKeepAlive *) cbuf;
3525 msg->header.size = htons (size);
3526 msg->header.type = htons (type);
3527 msg->cid = htonl (c->id);
3528 msg->tid = c->t->id;
3530 send_prebuilt_message_connection (&msg->header, c, NULL, fwd);
3535 * Send CONNECTION_{CREATE/ACK} packets for a connection.
3537 * @param c Connection for which to send the message.
3538 * @param fwd If GNUNET_YES, send CREATE, otherwise send ACK.
3541 connection_recreate (struct MeshConnection *c, int fwd)
3543 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "sending connection recreate\n");
3545 send_connection_create (c);
3547 send_connection_ack (c);
3552 * Generic connection timer management.
3553 * Depending on the role of the peer in the connection will send the
3554 * appropriate message (build or keepalive)
3556 * @param c Conncetion to maintain.
3557 * @param fwd Is FWD?
3560 connection_maintain (struct MeshConnection *c, int fwd)
3562 if (MESH_TUNNEL_SEARCHING == c->t->state)
3564 /* TODO DHT GET with RO_BART */
3569 case MESH_CONNECTION_NEW:
3571 case MESH_CONNECTION_SENT:
3572 connection_recreate (c, fwd);
3574 case MESH_CONNECTION_READY:
3575 connection_keepalive (c, fwd);
3584 connection_fwd_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3586 struct MeshConnection *c = cls;
3588 c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
3589 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3592 connection_maintain (c, GNUNET_YES);
3593 c->fwd_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
3594 &connection_fwd_keepalive,
3600 connection_bck_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3602 struct MeshConnection *c = cls;
3604 c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
3605 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3608 connection_maintain (c, GNUNET_NO);
3609 c->bck_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
3610 &connection_bck_keepalive,
3616 * Send a message to all peers in this connection that the connection
3617 * is no longer valid.
3619 * If some peer should not receive the message, it should be zero'ed out
3620 * before calling this function.
3622 * @param c The connection whose peers to notify.
3625 connection_send_destroy (struct MeshConnection *c)
3627 struct GNUNET_MESH_ConnectionDestroy msg;
3629 msg.header.size = htons (sizeof (msg));
3630 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);;
3631 msg.cid = htonl (c->id);
3633 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3634 " sending tunnel destroy for connection %s[%X]\n",
3635 peer2s (c->t->peer),
3638 send_prebuilt_message_connection (&msg.header, c, NULL, GNUNET_YES);
3639 send_prebuilt_message_connection (&msg.header, c, NULL, GNUNET_NO);
3640 c->destroy = GNUNET_YES;
3645 * Send a message to all clients (local and remote) of this channel
3646 * notifying that the channel is no longer valid.
3648 * If some peer or client should not receive the message,
3649 * should be zero'ed out before calling this function.
3651 * @param ch The channel whose clients to notify.
3654 channel_send_destroy (struct MeshChannel *ch)
3656 struct GNUNET_MESH_ChannelDestroy msg;
3658 msg.header.size = htons (sizeof (msg));
3659 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY);
3660 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3661 " sending tunnel destroy for channel %s:%X\n",
3662 peer2s (ch->t->peer),
3665 if (NULL != ch->root)
3667 msg.chid = htonl (ch->lid_root);
3668 send_local_channel_destroy (ch, GNUNET_NO);
3672 msg.chid = htonl (ch->gid);
3673 send_prebuilt_message_channel (&msg.header, ch, GNUNET_NO);
3676 if (NULL != ch->dest)
3678 msg.chid = htonl (ch->lid_dest);
3679 send_local_channel_destroy (ch, GNUNET_YES);
3683 msg.chid = htonl (ch->gid);
3684 send_prebuilt_message_channel (&msg.header, ch, GNUNET_YES);
3692 * @param tid Tunnel ID.
3694 static struct MeshTunnel2 *
3695 tunnel_new (const struct GNUNET_HashCode *tid)
3697 struct MeshTunnel2 *t;
3699 t = GNUNET_new (struct MeshTunnel2);
3701 t->next_chid = GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
3703 GNUNET_CONTAINER_multihashmap_put (tunnels, tid, t,
3704 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3718 * @param tid Tunnel ID.
3720 static struct MeshTunnel2 *
3721 tunnel_get (const struct GNUNET_HashCode *tid)
3723 return GNUNET_CONTAINER_multihashmap_get (tunnels, tid);
3728 * Add a connection to a tunnel.
3731 * @param c Connection.
3734 tunnel_add_connection (struct MeshTunnel2 *t, struct MeshConnection *c)
3737 GNUNET_CONTAINER_DLL_insert_tail (t->connection_head, t->connection_tail, c);
3742 * Initialize a Flow Control structure to the initial state.
3744 * @param fc Flow Control structure to initialize.
3747 fc_init (struct MeshFlowControl *fc)
3749 fc->last_pid_sent = (uint32_t) -1; /* Next (expected) = 0 */
3750 fc->last_pid_recv = (uint32_t) -1;
3751 fc->last_ack_sent = (uint32_t) 0;
3752 fc->last_ack_recv = (uint32_t) 0;
3753 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
3754 fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
3756 fc->queue_max = (max_msgs_queue / max_connections) + 1;
3760 static struct MeshConnection *
3761 connection_new (struct GNUNET_HashCode *tid, uint32_t cid)
3763 struct MeshConnection *c;
3764 struct MeshTunnel2 *t;
3766 t = tunnel_get (tid);
3769 t = tunnel_new (tid);
3777 c = GNUNET_new (struct MeshConnection);
3779 fc_init (&c->fwd_fc);
3780 fc_init (&c->bck_fc);
3781 tunnel_add_connection (t, c);
3788 * Find a connection.
3790 * @param tid Tunnel ID.
3791 * @param cid Connection ID.
3793 static struct MeshConnection *
3794 connection_get (const struct GNUNET_HashCode *tid, uint32_t cid)
3796 struct MeshConnection *c;
3797 struct MeshTunnel2 *t;
3799 t = tunnel_get (tid);
3802 for (c = t->connection_head; NULL != c; c = c->next)
3811 connection_destroy (struct MeshConnection *c)
3816 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying connection %s[%X]\n",
3817 peer2s (c->t->peer),
3820 connection_cancel_queues (c, GNUNET_YES);
3821 connection_cancel_queues (c, GNUNET_NO);
3823 if (GNUNET_SCHEDULER_NO_TASK != c->fwd_maintenance_task)
3824 GNUNET_SCHEDULER_cancel (c->fwd_maintenance_task);
3825 if (GNUNET_SCHEDULER_NO_TASK != c->bck_maintenance_task)
3826 GNUNET_SCHEDULER_cancel (c->bck_maintenance_task);
3828 GNUNET_CONTAINER_DLL_remove (c->t->connection_head, c->t->connection_tail, c);
3830 GNUNET_STATISTICS_update (stats, "# connections", -1, GNUNET_NO);
3836 tunnel_destroy (struct MeshTunnel2 *t)
3838 struct MeshConnection *c;
3839 struct MeshConnection *next;
3844 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n",
3847 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &t->id, t))
3850 for (c = t->connection_head; NULL != c; c = next)
3853 connection_destroy (c);
3856 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
3863 * Tunnel is empty: destroy it.
3865 * Notifies all connections about the destruction.
3867 * @param t Tunnel to destroy.
3870 tunnel_destroy_empty (struct MeshTunnel2 *t)
3872 struct MeshConnection *c;
3874 for (c = t->connection_head; NULL != c; c = c->next)
3876 if (GNUNET_NO == c->destroy)
3877 connection_send_destroy (c);
3880 if (0 == t->pending_messages)
3883 t->destroy = GNUNET_YES;
3888 * Destroy tunnel if empty (no more channels).
3890 * @param t Tunnel to destroy if empty.
3893 tunnel_destroy_if_empty (struct MeshTunnel2 *t)
3895 if (NULL != t->channel_head)
3898 tunnel_destroy_empty (t);
3903 * Destroy a channel and free all resources.
3905 * @param ch Channel to destroy.
3908 channel_destroy (struct MeshChannel *ch)
3910 struct MeshClient *c;
3918 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap32_remove (c->own_channels,
3929 GNUNET_CONTAINER_multihashmap32_remove (c->incoming_channels,
3936 if (GNUNET_YES == ch->reliable)
3938 channel_rel_free_all (ch->fwd_rel);
3939 channel_rel_free_all (ch->bck_rel);
3942 GNUNET_CONTAINER_DLL_remove (ch->t->channel_head, ch->t->channel_tail, ch);
3943 GNUNET_STATISTICS_update (stats, "# channels", -1, GNUNET_NO);
3949 * Create a new channel.
3951 * @param t Tunnel this channel is in.
3952 * @param owner Client that owns the channel, NULL for foreign channels.
3953 * @param lid_root Local ID for root client.
3955 * @return A new initialized channel. NULL on error.
3957 static struct MeshChannel *
3958 channel_new (struct MeshTunnel2 *t,
3959 struct MeshClient *owner, MESH_ChannelNumber lid_root)
3961 struct MeshChannel *ch;
3963 ch = GNUNET_new (struct MeshChannel);
3965 ch->lid_root = lid_root;
3968 GNUNET_CONTAINER_DLL_insert (t->channel_head, t->channel_tail, ch);
3970 GNUNET_STATISTICS_update (stats, "# channels", 1, GNUNET_NO);
3974 while (NULL != channel_get_by_local_id (owner, t->next_chid))
3975 t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
3976 ch->gid = t->next_chid;
3977 t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
3980 GNUNET_CONTAINER_multihashmap32_put (owner->own_channels, lid_root, ch,
3981 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
3984 channel_destroy (ch);
3985 GNUNET_SERVER_receive_done (owner->handle, GNUNET_SYSERR);
3995 * Set options in a channel, extracted from a bit flag field
3997 * @param ch Channel to set options to.
3998 * @param options Bit array in host byte order.
4001 channel_set_options (struct MeshChannel *ch, uint32_t options)
4003 ch->nobuffer = (options & GNUNET_MESH_OPTION_NOBUFFER) != 0 ?
4004 GNUNET_YES : GNUNET_NO;
4005 ch->reliable = (options & GNUNET_MESH_OPTION_RELIABLE) != 0 ?
4006 GNUNET_YES : GNUNET_NO;
4011 * Iterator for deleting each channel whose client endpoint disconnected.
4013 * @param cls Closure (client that has disconnected).
4014 * @param key The local channel id (used to access the hashmap).
4015 * @param value The value stored at the key (channel to destroy).
4017 * @return GNUNET_OK, keep iterating.
4020 channel_destroy_iterator (void *cls,
4024 struct MeshChannel *ch = value;
4025 struct MeshClient *c = cls;
4026 struct MeshTunnel2 *t;
4028 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4029 " Channel %X (%X / %X) destroy, due to client %u shutdown.\n",
4030 ch->gid, ch->lid_root, ch->lid_dest, c->id);
4034 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is destination.\n", c->id);
4039 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is owner.\n", c->id);
4044 channel_send_destroy (ch);
4045 channel_destroy (ch);
4046 tunnel_destroy_if_empty (t);
4053 * Remove client's ports from the global hashmap on disconnect.
4055 * @param cls Closure (unused).
4057 * @param value Client structure.
4059 * @return GNUNET_OK, keep iterating.
4062 client_release_ports (void *cls,
4068 res = GNUNET_CONTAINER_multihashmap32_remove (ports, key, value);
4069 if (GNUNET_YES != res)
4072 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4073 "Port %u by client %p was not registered.\n",
4081 * Timeout function due to lack of keepalive/traffic from the owner.
4082 * Destroys connection if called.
4084 * @param cls Closure (connection to destroy).
4085 * @param tc TaskContext.
4088 connection_fwd_timeout (void *cls,
4089 const struct GNUNET_SCHEDULER_TaskContext *tc)
4091 struct MeshConnection *c = cls;
4093 c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4094 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4096 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4097 "Connection %s[%X] FWD timed out. Destroying.\n",
4098 peer2s (c->t->peer),
4101 if (connection_is_terminal (c, GNUNET_NO)) /* If local, leave. */
4104 connection_destroy (c);
4109 * Timeout function due to lack of keepalive/traffic from the destination.
4110 * Destroys connection if called.
4112 * @param cls Closure (connection to destroy).
4113 * @param tc TaskContext
4116 connection_bck_timeout (void *cls,
4117 const struct GNUNET_SCHEDULER_TaskContext *tc)
4119 struct MeshConnection *c = cls;
4121 c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4122 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4125 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4126 "Connection %s[%X] FWD timed out. Destroying.\n",
4127 peer2s (c->t->peer),
4130 if (connection_is_terminal (c, GNUNET_YES)) /* If local, leave. */
4133 connection_destroy (c);
4138 * Resets the connection timeout task, some other message has done the
4140 * - For the first peer on the direction this means to send
4141 * a keepalive or a path confirmation message (either create or ACK).
4142 * - For all other peers, this means to destroy the connection,
4143 * due to lack of activity.
4144 * Starts the tiemout if no timeout was running (connection just created).
4146 * @param c Connection whose timeout to reset.
4147 * @param fwd Is this forward?
4149 * TODO use heap to improve efficiency of scheduler.
4152 connection_reset_timeout (struct MeshConnection *c, int fwd)
4154 GNUNET_SCHEDULER_TaskIdentifier *ti;
4155 GNUNET_SCHEDULER_Task f;
4157 ti = fwd ? &c->fwd_maintenance_task : &c->bck_maintenance_task;
4159 if (GNUNET_SCHEDULER_NO_TASK != *ti)
4160 GNUNET_SCHEDULER_cancel (*ti);
4162 if (connection_is_terminal (c, !fwd)) /* Endpoint */
4164 f = fwd ? &connection_fwd_keepalive : &connection_bck_keepalive;
4165 *ti = GNUNET_SCHEDULER_add_delayed (refresh_connection_time, f, c);
4169 struct GNUNET_TIME_Relative delay;
4171 delay = GNUNET_TIME_relative_multiply (refresh_connection_time, 4);
4172 f = fwd ? &connection_fwd_timeout : &connection_bck_timeout;
4173 *ti = GNUNET_SCHEDULER_add_delayed (delay, f, c);
4179 * Iterator to notify all connections of a broken link. Mark connections
4180 * to destroy after all traffic has been sent.
4182 * @param cls Closure (peer disconnected).
4183 * @param key Current key code (tid).
4184 * @param value Value in the hash map (connection).
4186 * @return GNUNET_YES if we should continue to iterate,
4190 connection_broken (void *cls,
4191 const struct GNUNET_HashCode *key,
4194 struct MeshPeer *peer = cls;
4195 struct MeshConnection *c = value;
4196 struct GNUNET_MESH_ConnectionBroken msg;
4199 fwd = peer == connection_get_prev_hop (c);
4200 connection_cancel_queues (c, !fwd);
4202 msg.header.size = htons (sizeof (struct GNUNET_MESH_ConnectionBroken));
4203 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN);
4204 msg.cid = htonl (c->id);
4206 msg.peer1 = my_full_id;
4207 msg.peer2 = *GNUNET_PEER_resolve2 (peer->id);
4208 send_prebuilt_message_connection (&msg.header, c, NULL, fwd);
4209 c->destroy = GNUNET_YES;
4214 /******************************************************************************/
4215 /**************** MESH NETWORK HANDLER HELPERS ***********************/
4216 /******************************************************************************/
4219 * Free a transmission that was already queued with all resources
4220 * associated to the request.
4222 * @param queue Queue handler to cancel.
4223 * @param clear_cls Is it necessary to free associated cls?
4226 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
4228 struct MeshPeer *peer;
4229 struct MeshFlowControl *fc;
4234 fc = fwd ? &queue->c->fwd_fc : &queue->c->bck_fc;
4236 if (GNUNET_YES == clear_cls)
4238 switch (queue->type)
4240 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
4241 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "destroying CONNECTION_DESTROY\n");
4242 GNUNET_break (GNUNET_YES == queue->c->destroy);
4244 case GNUNET_MESSAGE_TYPE_MESH_FWD:
4245 case GNUNET_MESSAGE_TYPE_MESH_BCK:
4246 case GNUNET_MESSAGE_TYPE_MESH_ACK:
4247 case GNUNET_MESSAGE_TYPE_MESH_POLL:
4248 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
4249 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " prebuilt message\n");
4250 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type %s\n",
4251 GNUNET_MESH_DEBUG_M2S (queue->type));
4254 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
4255 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type create path\n");
4260 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, " type %s unknown!\n",
4261 GNUNET_MESH_DEBUG_M2S (queue->type));
4263 GNUNET_free_non_null (queue->cls);
4265 GNUNET_CONTAINER_DLL_remove (peer->queue_head, peer->queue_tail, queue);
4269 if (NULL != queue->c)
4271 queue->c->pending_messages--;
4272 if (NULL != queue->c->t)
4274 queue->c->t->pending_messages--;
4278 GNUNET_free (queue);
4283 queue_send (void *cls, size_t size, void *buf)
4285 struct MeshPeer *peer = cls;
4286 struct MeshFlowControl *fc;
4287 struct MeshConnection *c;
4288 struct GNUNET_MessageHeader *msg;
4289 struct MeshPeerQueue *queue;
4290 struct MeshTunnel2 *t;
4291 const struct GNUNET_PeerIdentity *dst_id;
4297 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Queue send\n");
4299 if (NULL == buf || 0 == size)
4301 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Buffer size 0.\n");
4306 queue = peer_get_first_message (peer);
4309 GNUNET_break (0); /* Core tmt_rdy should've been canceled */
4312 queue->peer->core_transmit = NULL;
4315 fc = fwd ? &c->fwd_fc : &c->bck_fc;
4318 dst_id = GNUNET_PEER_resolve2 (peer->id);
4319 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* towards %s\n", GNUNET_i2s (dst_id));
4320 /* Check if buffer size is enough for the message */
4321 if (queue->size > size)
4323 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* not enough room, reissue\n");
4324 peer->core_transmit =
4325 GNUNET_CORE_notify_transmit_ready (core_handle,
4328 GNUNET_TIME_UNIT_FOREVER_REL,
4335 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* size ok\n");
4337 t = (NULL != c) ? c->t : NULL;
4341 switch (queue->type)
4343 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
4344 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
4345 case GNUNET_MESSAGE_TYPE_MESH_FWD:
4346 case GNUNET_MESSAGE_TYPE_MESH_BCK:
4347 case GNUNET_MESSAGE_TYPE_MESH_ACK:
4348 case GNUNET_MESSAGE_TYPE_MESH_POLL:
4349 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4351 GNUNET_MESH_DEBUG_M2S (queue->type));
4353 case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4354 case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4355 data_size = send_core_data_raw (queue->cls, size, buf);
4356 msg = (struct GNUNET_MessageHeader *) buf;
4357 type = ntohs (msg->type);
4359 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
4360 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* path create\n");
4361 if (connection_is_terminal (c, GNUNET_NO))
4362 data_size = send_core_connection_create (queue->cls, size, buf);
4364 data_size = send_core_data_raw (queue->cls, size, buf);
4366 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
4367 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* path ack\n");
4368 if (connection_is_terminal (c, GNUNET_YES))
4369 data_size = send_core_connection_ack (queue->cls, size, buf);
4371 data_size = send_core_data_raw (queue->cls, size, buf);
4375 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "* type unknown: %u\n",
4380 if (0 < drop_percent &&
4381 GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 101) < drop_percent)
4383 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4384 "Dropping message of type %s\n",
4385 GNUNET_MESH_DEBUG_M2S (queue->type));
4388 /* Free queue, but cls was freed by send_core_* */
4389 queue_destroy (queue, GNUNET_NO);
4391 /* Send ACK if needed, after accounting for sent ID in fc->queue_n */
4394 case GNUNET_MESSAGE_TYPE_MESH_FWD:
4395 case GNUNET_MESSAGE_TYPE_MESH_BCK:
4396 pid = ntohl ( ((struct GNUNET_MESH_Encrypted *) buf)->pid );
4397 fc->last_pid_sent = pid;
4398 connection_send_ack (c, fwd);
4404 /* If more data in queue, send next */
4405 queue = peer_get_first_message (peer);
4408 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* more data!\n");
4409 if (NULL == peer->core_transmit) {
4410 peer->core_transmit =
4411 GNUNET_CORE_notify_transmit_ready(core_handle,
4414 GNUNET_TIME_UNIT_FOREVER_REL,
4422 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4423 "* tmt rdy called somewhere else\n");
4425 if (GNUNET_SCHEDULER_NO_TASK == fc->poll_task)
4427 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "* %s starting poll timeout\n");
4429 GNUNET_SCHEDULER_add_delayed (fc->poll_time, &connection_poll, fc);
4434 if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
4436 GNUNET_SCHEDULER_cancel (fc->poll_task);
4437 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
4442 c->pending_messages--;
4443 if (GNUNET_YES == c->destroy && 0 == c->pending_messages)
4445 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* destroying connection!\n");
4446 connection_destroy (c);
4452 t->pending_messages--;
4453 if (GNUNET_YES == t->destroy && 0 == t->pending_messages)
4455 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* destroying tunnel!\n");
4459 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Return %d\n", data_size);
4465 queue_add (void *cls, uint16_t type, size_t size,
4466 struct MeshPeer *dst,
4467 struct MeshConnection *c,
4468 struct MeshChannel *ch)
4470 struct MeshPeerQueue *queue;
4471 struct MeshFlowControl *fc;
4475 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4476 "queue add %s (%u bytes) on c %p, ch %p\n",
4477 GNUNET_MESH_DEBUG_M2S (type), size, c, ch);
4479 fwd = (dst == connection_get_next_hop (c));
4480 fc = fwd ? &c->fwd_fc : &c->bck_fc;
4490 if (GNUNET_MESSAGE_TYPE_MESH_POLL == type ||
4491 GNUNET_MESSAGE_TYPE_MESH_ACK == type)
4495 ( (NULL != ch->root && GNUNET_MESSAGE_TYPE_MESH_FWD == type) ||
4496 (NULL != ch->dest && GNUNET_MESSAGE_TYPE_MESH_BCK == type) ))
4499 if (fc->queue_n >= fc->queue_max && 0 == priority)
4501 GNUNET_STATISTICS_update (stats, "# messages dropped (buffer full)",
4504 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4505 "queue full: %u/%u\n",
4506 fc->queue_n, fc->queue_max);
4507 return; /* Drop this message */
4510 if (GMC_is_pid_bigger(fc->last_pid_sent + 1, fc->last_ack_recv) &&
4511 GNUNET_SCHEDULER_NO_TASK == fc->poll_task)
4512 fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
4515 queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
4523 if (100 <= priority)
4524 GNUNET_CONTAINER_DLL_insert (dst->queue_head, dst->queue_tail, queue);
4526 GNUNET_CONTAINER_DLL_insert_tail (dst->queue_head, dst->queue_tail, queue);
4528 if (NULL == dst->core_transmit)
4530 dst->core_transmit =
4531 GNUNET_CORE_notify_transmit_ready (core_handle,
4534 GNUNET_TIME_UNIT_FOREVER_REL,
4535 GNUNET_PEER_resolve2 (dst->id),
4540 c->pending_messages++;
4541 c->t->pending_messages++;
4547 /******************************************************************************/
4548 /******************** MESH NETWORK HANDLERS **************************/
4549 /******************************************************************************/
4553 * Generic handler for mesh network payload traffic.
4555 * @param t Tunnel on which we got this message.
4556 * @param message Unencryted data message.
4557 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
4559 * @return GNUNET_OK to keep the connection open,
4560 * GNUNET_SYSERR to close it (signal serious error)
4563 handle_data (struct MeshTunnel2 *t, const struct GNUNET_MESH_Data *msg, int fwd)
4565 struct MeshChannelReliability *rel;
4566 struct MeshChannel *ch;
4567 struct MeshClient *c;
4574 size = ntohs (msg->header.size);
4576 sizeof (struct GNUNET_MESH_Data) +
4577 sizeof (struct GNUNET_MessageHeader))
4582 type = ntohs (msg->header.type);
4583 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message\n",
4584 GNUNET_MESH_DEBUG_M2S (type));
4585 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
4586 GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
4589 ch = channel_get (t, ntohl (msg->chid));
4592 GNUNET_STATISTICS_update (stats, "# data on unknown channel", 1, GNUNET_NO);
4593 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel unknown\n");
4597 /* Initialize FWD/BCK data */
4598 c = fwd ? ch->dest : ch->root;
4599 rel = fwd ? ch->bck_rel : ch->fwd_rel;
4600 mid_recv = fwd ? &ch->mid_recv_fwd : &ch->mid_recv_bck;
4608 tunnel_change_state (t, MESH_TUNNEL_READY);
4610 GNUNET_STATISTICS_update (stats, "# data received", 1, GNUNET_NO);
4612 mid = ntohl (msg->mid);
4613 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " mid %u\n", mid);
4615 if (GNUNET_NO == ch->reliable ||
4616 ( !GMC_is_pid_bigger (*mid_recv, mid) &&
4617 GMC_is_pid_bigger (*mid_recv + 64, mid) ) )
4619 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! RECV %u\n", mid);
4620 if (GNUNET_YES == ch->reliable)
4622 /* Is this the exact next expected messasge? */
4623 if (mid == *mid_recv)
4625 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "as expected\n");
4626 *mid_recv = *mid_recv + 1;
4627 channel_send_client_data (ch, msg, fwd);
4628 channel_send_client_buffered_data (ch, c, rel);
4632 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "save for later\n");
4633 channel_rel_add_buffered_data (msg, rel);
4636 else /* Tunnel unreliable, send to clients directly */
4638 channel_send_client_data (ch, msg, fwd);
4643 GNUNET_break_op (0);
4644 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4645 " MID %u not expected (%u - %u), dropping!\n",
4646 mid, *mid_recv, *mid_recv + 64);
4649 channel_send_data_ack (ch, fwd);
4654 * Handler for mesh network traffic end-to-end ACKs.
4656 * @param t Tunnel on which we got this message.
4657 * @param message Data message.
4658 * @param fwd Is this a fwd ACK? (dest->orig)
4660 * @return GNUNET_OK to keep the connection open,
4661 * GNUNET_SYSERR to close it (signal serious error)
4664 handle_data_ack (struct MeshTunnel2 *t,
4665 const struct GNUNET_MESH_DataACK *msg, int fwd)
4667 struct MeshChannelReliability *rel;
4668 struct MeshReliableMessage *copy;
4669 struct MeshReliableMessage *next;
4670 struct MeshChannel *ch;
4675 type = ntohs (msg->header.type);
4676 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a %s message!\n",
4677 GNUNET_MESH_DEBUG_M2S (type));
4678 ch = channel_get (t, ntohl (msg->chid));
4681 GNUNET_STATISTICS_update (stats, "# ack on unknown channel", 1, GNUNET_NO);
4684 ack = ntohl (msg->mid);
4685 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! %s ACK %u\n",
4686 (GNUNET_YES == fwd) ? "FWD" : "BCK", ack);
4688 if (GNUNET_YES == fwd)
4701 for (work = GNUNET_NO, copy = rel->head_sent; copy != NULL; copy = next)
4703 if (GMC_is_pid_bigger (copy->mid, ack))
4705 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! head %u, out!\n", copy->mid);
4706 channel_rel_free_sent (rel, msg);
4710 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! id %u\n", copy->mid);
4712 rel_message_free (copy);
4714 /* ACK client if needed */
4715 // channel_send_ack (t, type, GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK == type);
4717 /* If some message was free'd, update the retransmission delay*/
4718 if (GNUNET_YES == work)
4720 if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
4722 GNUNET_SCHEDULER_cancel (rel->retry_task);
4723 if (NULL == rel->head_sent)
4725 rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
4729 struct GNUNET_TIME_Absolute new_target;
4730 struct GNUNET_TIME_Relative delay;
4732 delay = GNUNET_TIME_relative_multiply (rel->retry_timer,
4733 MESH_RETRANSMIT_MARGIN);
4734 new_target = GNUNET_TIME_absolute_add (rel->head_sent->timestamp,
4736 delay = GNUNET_TIME_absolute_get_remaining (new_target);
4738 GNUNET_SCHEDULER_add_delayed (delay,
4739 &channel_retransmit_message,
4751 * Core handler for connection creation.
4753 * @param cls Closure (unused).
4754 * @param peer Sender (neighbor).
4755 * @param message Message.
4757 * @return GNUNET_OK to keep the connection open,
4758 * GNUNET_SYSERR to close it (signal serious error)
4761 handle_mesh_connection_create (void *cls,
4762 const struct GNUNET_PeerIdentity *peer,
4763 const struct GNUNET_MessageHeader *message)
4765 struct GNUNET_MESH_ConnectionCreate *msg;
4766 struct GNUNET_PeerIdentity *id;
4767 struct GNUNET_HashCode *tid;
4768 struct MeshPeerPath *path;
4769 struct MeshPeer *dest_peer;
4770 struct MeshPeer *orig_peer;
4771 struct MeshConnection *c;
4772 unsigned int own_pos;
4777 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection create msg\n");
4780 size = ntohs (message->size);
4781 if (size < sizeof (struct GNUNET_MESH_ConnectionCreate))
4783 GNUNET_break_op (0);
4787 /* Calculate hops */
4788 size -= sizeof (struct GNUNET_MESH_ConnectionCreate);
4789 if (size % sizeof (struct GNUNET_PeerIdentity))
4791 GNUNET_break_op (0);
4794 size /= sizeof (struct GNUNET_PeerIdentity);
4797 GNUNET_break_op (0);
4800 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " path has %u hops.\n", size);
4802 /* Get parameters */
4803 msg = (struct GNUNET_MESH_ConnectionCreate *) message;
4804 cid = ntohl (msg->cid);
4806 id = (struct GNUNET_PeerIdentity *) &msg[1];
4807 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4808 " connection %s[%X] (%s).\n",
4809 GNUNET_h2s (tid), cid, GNUNET_i2s (id));
4811 /* Create connection */
4812 c = connection_get (tid, cid);
4815 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Creating connection\n");
4816 c = connection_new (tid, cid);
4820 connection_reset_timeout (c, GNUNET_YES);
4821 tunnel_change_state (c->t, MESH_TUNNEL_WAITING);
4823 /* Remember peers */
4824 dest_peer = peer_get (&id[size - 1]);
4825 orig_peer = peer_get (&id[0]);
4828 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Creating path...\n");
4829 path = path_new (size);
4831 for (i = 0; i < size; i++)
4833 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... adding %s\n",
4834 GNUNET_i2s (&id[i]));
4835 path->peers[i] = GNUNET_PEER_intern (&id[i]);
4836 if (path->peers[i] == myid)
4839 if (own_pos == 0 && path->peers[own_pos] != myid)
4841 /* create path: self not found in path through self */
4842 GNUNET_break_op (0);
4843 path_destroy (path);
4844 connection_destroy (c);
4847 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Own position: %u\n", own_pos);
4848 path_add_to_peers (path, GNUNET_NO);
4849 c->path = path_duplicate (path);
4850 c->own_pos = own_pos;
4852 /* Is it a connection to us? */
4853 if (own_pos == size - 1)
4855 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " It's for us!\n");
4856 peer_add_path_to_origin (orig_peer, path, GNUNET_YES);
4858 send_connection_ack (c);
4860 /* Keep tunnel alive in direction dest->owner*/
4861 connection_reset_timeout (c, GNUNET_NO);
4865 /* It's for somebody else! Retransmit. */
4866 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Retransmitting.\n");
4867 peer_add_path (dest_peer, path_duplicate (path), GNUNET_NO);
4868 peer_add_path_to_origin (orig_peer, path, GNUNET_NO);
4869 send_prebuilt_message_connection (message, c, NULL, GNUNET_YES);
4876 * Core handler for path ACKs
4878 * @param cls closure
4879 * @param message message
4880 * @param peer peer identity this notification is about
4882 * @return GNUNET_OK to keep the connection open,
4883 * GNUNET_SYSERR to close it (signal serious error)
4886 handle_mesh_connection_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
4887 const struct GNUNET_MessageHeader *message)
4889 struct GNUNET_MESH_ConnectionACK *msg;
4890 struct MeshPeerPath *p;
4891 struct MeshConnection *c;
4894 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection ACK msg\n");
4895 msg = (struct GNUNET_MESH_ConnectionACK *) message;
4896 cid = ntohl(msg->cid);
4897 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " on connection %s[%X]\n",
4898 GNUNET_h2s (&msg->tid), cid);
4899 c = connection_get (&msg->tid, cid);
4902 GNUNET_STATISTICS_update (stats, "# control on unknown connection",
4904 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " don't know the connection!\n");
4908 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " via peer %s\n",
4911 /* Add path to peers? */
4915 path_add_to_peers (p, GNUNET_YES);
4921 connection_change_state (c, MESH_CONNECTION_READY);
4922 connection_reset_timeout (c, GNUNET_NO);
4924 /* Message for us? */
4925 if (connection_is_terminal (c, GNUNET_NO))
4927 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " It's for us!\n");
4928 if (3 <= tunnel_count_connections(c->t) && NULL != c->t->peer->dhtget)
4930 GNUNET_DHT_get_stop (c->t->peer->dhtget);
4931 c->t->peer->dhtget = NULL;
4933 //connection_send_ack (c, GNUNET_NO); /* FIXME */
4937 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " not for us, retransmitting...\n");
4938 send_prebuilt_message_connection (message, c, NULL, GNUNET_NO);
4944 * Core handler for notifications of broken paths
4946 * @param cls Closure (unused).
4947 * @param peer Peer identity of sending neighbor.
4948 * @param message Message.
4950 * @return GNUNET_OK to keep the connection open,
4951 * GNUNET_SYSERR to close it (signal serious error)
4954 handle_mesh_connection_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
4955 const struct GNUNET_MessageHeader *message)
4957 struct GNUNET_MESH_ConnectionBroken *msg;
4958 struct MeshConnection *c;
4960 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4961 "Received a CONNECTION BROKEN msg from %s\n", GNUNET_i2s (peer));
4962 msg = (struct GNUNET_MESH_ConnectionBroken *) message;
4963 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " regarding %s\n",
4964 GNUNET_i2s (&msg->peer1));
4965 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " regarding %s\n",
4966 GNUNET_i2s (&msg->peer2));
4967 c = connection_get (&msg->tid, ntohl (msg->cid));
4970 GNUNET_break_op (0);
4973 tunnel_notify_connection_broken (c->t, GNUNET_PEER_search (&msg->peer1),
4974 GNUNET_PEER_search (&msg->peer2));
4981 * Core handler for tunnel destruction
4983 * @param cls Closure (unused).
4984 * @param peer Peer identity of sending neighbor.
4985 * @param message Message.
4987 * @return GNUNET_OK to keep the connection open,
4988 * GNUNET_SYSERR to close it (signal serious error)
4991 handle_mesh_connection_destroy (void *cls,
4992 const struct GNUNET_PeerIdentity *peer,
4993 const struct GNUNET_MessageHeader *message)
4995 struct GNUNET_MESH_ConnectionDestroy *msg;
4996 struct MeshConnection *c;
5000 msg = (struct GNUNET_MESH_ConnectionDestroy *) message;
5001 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5002 "Got a CONNECTION DESTROY message from %s\n",
5004 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5005 " for connection %s[%X]\n",
5006 GNUNET_h2s (&msg->tid), ntohl (msg->cid));
5007 c = connection_get (&msg->tid, ntohl (msg->cid));
5010 /* Probably already got the message from another path,
5011 * destroyed the tunnel and retransmitted to children.
5014 GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
5018 id = GNUNET_PEER_search (peer);
5019 if (id == connection_get_prev_hop (c)->id)
5021 else if (id == connection_get_next_hop (c)->id)
5025 GNUNET_break_op (0);
5028 send_prebuilt_message_connection (message, c, NULL, fwd);
5029 c->destroy = GNUNET_YES;
5035 * Handler for channel create messages.
5037 * @param t Tunnel this channel is to be created in.
5038 * @param msg Message.
5039 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5041 * @return GNUNET_OK to keep the connection open,
5042 * GNUNET_SYSERR to close it (signal serious error)
5045 handle_channel_create (struct MeshTunnel2 *t,
5046 struct GNUNET_MESH_ChannelCreate *msg,
5049 MESH_ChannelNumber chid;
5050 struct MeshChannel *ch;
5051 struct MeshClient *c;
5053 /* Check message size */
5054 if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelCreate))
5056 GNUNET_break_op (0);
5060 /* Check if channel exists */
5061 chid = ntohl (msg->chid);
5062 ch = channel_get (t, chid);
5065 /* Probably a retransmission, safe to ignore */
5069 /* Find a destination client */
5070 c = GNUNET_CONTAINER_multihashmap32_get (ports, msg->port);
5073 /* TODO send reject */
5077 /* Create channel */
5078 ch = channel_new (t, NULL, 0);
5079 channel_set_options (ch, ntohl (msg->opt));
5080 channel_add_client (ch, c);
5081 if (GNUNET_YES == ch->reliable)
5083 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
5084 ch->bck_rel = GNUNET_malloc (sizeof (struct MeshChannelReliability));
5085 ch->bck_rel->ch = ch;
5086 ch->bck_rel->expected_delay = MESH_RETRANSMIT_TIME;
5089 send_local_channel_create (ch);
5096 * Handler for channel destroy messages.
5098 * @param t Tunnel this channel is to be destroyed of.
5099 * @param msg Message.
5100 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5102 * @return GNUNET_OK to keep the connection open,
5103 * GNUNET_SYSERR to close it (signal serious error)
5106 handle_channel_destroy (struct MeshTunnel2 *t,
5107 struct GNUNET_MESH_ChannelDestroy *msg,
5110 MESH_ChannelNumber chid;
5111 struct MeshChannel *ch;
5113 /* Check message size */
5114 if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelDestroy))
5116 GNUNET_break_op (0);
5120 /* Check if channel exists */
5121 chid = ntohl (msg->chid);
5122 ch = channel_get (t, chid);
5125 /* Probably a retransmission, safe to ignore */
5129 send_local_channel_destroy (ch, fwd);
5130 channel_destroy (ch);
5137 * Generic handler for mesh network encrypted traffic.
5139 * @param peer Peer identity this notification is about.
5140 * @param message Encrypted message.
5141 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5143 * @return GNUNET_OK to keep the connection open,
5144 * GNUNET_SYSERR to close it (signal serious error)
5147 handle_mesh_encrypted (const struct GNUNET_PeerIdentity *peer,
5148 const struct GNUNET_MESH_Encrypted *msg,
5151 struct MeshConnection *c;
5152 struct MeshTunnel2 *t;
5153 struct MeshPeer *neighbor;
5154 struct MeshFlowControl *fc;
5161 size = ntohs (msg->header.size);
5163 sizeof (struct GNUNET_MESH_Encrypted) +
5164 sizeof (struct GNUNET_MessageHeader))
5169 type = ntohs (msg->header.type);
5170 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message from %s\n",
5171 GNUNET_MESH_DEBUG_M2S (type), GNUNET_i2s (peer));
5173 /* Check connection */
5174 c = connection_get (&msg->tid, ntohl (msg->cid));
5177 GNUNET_STATISTICS_update (stats, "# unknown connection", 1, GNUNET_NO);
5178 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING connection unknown\n");
5182 fc = fwd ? &c->fwd_fc : &c->bck_fc;
5184 /* Check if origin is as expected */
5185 neighbor = connection_get_hop (c, fwd);
5186 if (peer_get (peer)->id != neighbor->id)
5188 GNUNET_break_op (0);
5193 pid = ntohl (msg->pid);
5194 if (GMC_is_pid_bigger (pid, fc->last_ack_sent))
5196 GNUNET_STATISTICS_update (stats, "# unsolicited message", 1, GNUNET_NO);
5197 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5198 "WARNING Received PID %u, (prev %u), ACK %u\n",
5199 pid, fc->last_pid_recv, fc->last_ack_sent);
5202 if (GNUNET_NO == GMC_is_pid_bigger (pid, fc->last_pid_recv))
5204 GNUNET_STATISTICS_update (stats, "# duplicate PID", 1, GNUNET_NO);
5205 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5206 " Pid %u not expected (%u+), dropping!\n",
5207 pid, fc->last_pid_recv + 1);
5210 if (MESH_CONNECTION_SENT == c->state)
5211 connection_change_state (c, MESH_CONNECTION_READY);
5212 connection_reset_timeout (c, fwd);
5213 fc->last_pid_recv = pid;
5215 /* Is this message for us? */
5216 if (connection_is_terminal (c, fwd))
5218 size_t dsize = size - sizeof (struct GNUNET_MESH_Encrypted);
5220 struct GNUNET_MessageHeader *msgh;
5222 /* TODO signature verification */
5223 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " it's for us!\n");
5224 GNUNET_STATISTICS_update (stats, "# messages received", 1, GNUNET_NO);
5226 fc->last_pid_recv = pid;
5227 tunnel_decrypt (t, cbuf, &msg[1], dsize, msg->iv, fwd);
5228 msgh = (struct GNUNET_MessageHeader *) cbuf;
5229 switch (ntohs (msgh->type))
5231 case GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK:
5232 if (GNUNET_YES == fwd)
5233 return handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh,
5235 GNUNET_break_op (0);
5237 case GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK:
5238 if (GNUNET_NO == fwd)
5239 return handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh,
5241 GNUNET_break_op (0);
5243 case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
5244 if (GNUNET_YES == fwd)
5245 handle_data (t, (struct GNUNET_MESH_Data *) msgh, GNUNET_YES);
5246 GNUNET_break_op (0);
5248 case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
5249 if (GNUNET_NO == fwd)
5250 handle_data (t, (struct GNUNET_MESH_Data *) msgh, GNUNET_NO);
5251 GNUNET_break_op (0);
5253 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
5254 return handle_channel_create (t,
5255 (struct GNUNET_MESH_ChannelCreate *) msgh,
5258 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
5259 return handle_channel_destroy (t,
5260 (struct GNUNET_MESH_ChannelDestroy *)
5265 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5266 "end-to-end message not known (%u)\n",
5267 ntohs (msgh->type));
5270 connection_send_ack (c, fwd);
5274 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " not for us, retransmitting...\n");
5275 ttl = ntohl (msg->ttl);
5276 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ttl: %u\n", ttl);
5279 GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5280 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5281 connection_send_ack (c, fwd);
5284 GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
5286 send_prebuilt_message_connection (&msg->header, c, NULL, fwd);
5287 connection_send_ack (c, fwd);
5294 * Core handler for mesh network traffic going orig->dest.
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_fwd (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,
5313 * Core handler for mesh network traffic going dest->orig.
5315 * @param cls Closure (unused).
5316 * @param message Message received.
5317 * @param peer Peer who sent the message.
5319 * @return GNUNET_OK to keep the connection open,
5320 * GNUNET_SYSERR to close it (signal serious error)
5323 handle_mesh_bck (void *cls, const struct GNUNET_PeerIdentity *peer,
5324 const struct GNUNET_MessageHeader *message)
5326 return handle_mesh_encrypted (peer,
5327 (struct GNUNET_MESH_Encrypted *)message,
5333 * Core handler for mesh network traffic point-to-point acks.
5335 * @param cls closure
5336 * @param message message
5337 * @param peer peer identity this notification is about
5339 * @return GNUNET_OK to keep the connection open,
5340 * GNUNET_SYSERR to close it (signal serious error)
5343 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5344 const struct GNUNET_MessageHeader *message)
5346 struct GNUNET_MESH_ACK *msg;
5347 struct MeshConnection *c;
5348 struct MeshFlowControl *fc;
5352 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
5354 msg = (struct GNUNET_MESH_ACK *) message;
5356 c = connection_get (&msg->tid, ntohl (msg->cid));
5360 GNUNET_STATISTICS_update (stats, "# ack on unknown connection", 1,
5365 ack = ntohl (msg->ack);
5366 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", ack);
5368 /* Is this a forward or backward ACK? */
5369 id = GNUNET_PEER_search (peer);
5370 if (connection_get_next_hop (c)->id == id)
5372 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " FWD ACK\n");
5375 else if (connection_get_prev_hop (c)->id == id)
5377 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " BCK ACK\n");
5382 GNUNET_break_op (0);
5386 /* Cancel polling if the ACK is bigger than before. */
5387 if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task &&
5388 GMC_is_pid_bigger (ack, fc->last_ack_recv))
5390 GNUNET_SCHEDULER_cancel (fc->poll_task);
5391 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
5392 fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
5395 fc->last_ack_recv = ack;
5396 connection_unlock_queue (c, fc == &c->fwd_fc);
5403 * Core handler for mesh network traffic point-to-point ack polls.
5405 * @param cls closure
5406 * @param message message
5407 * @param peer peer identity this notification is about
5409 * @return GNUNET_OK to keep the connection open,
5410 * GNUNET_SYSERR to close it (signal serious error)
5413 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
5414 const struct GNUNET_MessageHeader *message)
5416 struct GNUNET_MESH_Poll *msg;
5417 struct MeshConnection *c;
5418 struct MeshFlowControl *fc;
5422 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a POLL packet from %s!\n",
5425 msg = (struct GNUNET_MESH_Poll *) message;
5427 c = connection_get (&msg->tid, ntohl (msg->cid));
5431 GNUNET_STATISTICS_update (stats, "# poll on unknown connection", 1,
5433 GNUNET_break_op (0);
5437 /* Is this a forward or backward ACK? */
5438 id = GNUNET_PEER_search (peer);
5439 if (connection_get_next_hop (c)->id == id)
5441 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " FWD ACK\n");
5444 else if (connection_get_prev_hop (c)->id == id)
5446 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " BCK ACK\n");
5451 GNUNET_break_op (0);
5455 pid = ntohl (msg->pid);
5456 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " PID %u, OLD %u\n",
5457 pid, fc->last_pid_recv);
5458 fc->last_pid_recv = pid;
5459 connection_send_ack (c, fc == &c->fwd_fc);
5466 * Core handler for mesh keepalives.
5468 * @param cls closure
5469 * @param message message
5470 * @param peer peer identity this notification is about
5471 * @return GNUNET_OK to keep the connection open,
5472 * GNUNET_SYSERR to close it (signal serious error)
5474 * TODO: Check who we got this from, to validate route.
5477 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
5478 const struct GNUNET_MessageHeader *message)
5480 struct GNUNET_MESH_ConnectionKeepAlive *msg;
5481 struct MeshConnection *c;
5482 struct MeshPeer *neighbor;
5485 msg = (struct GNUNET_MESH_ConnectionKeepAlive *) message;
5486 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
5489 c = connection_get (&msg->tid, ntohl (msg->cid));
5492 GNUNET_STATISTICS_update (stats, "# keepalive on unknown connection", 1,
5497 fwd = GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE == ntohs (message->type) ?
5498 GNUNET_YES : GNUNET_NO;
5500 /* Check if origin is as expected */
5501 neighbor = connection_get_hop (c, fwd);
5502 if (peer_get (peer)->id != neighbor->id)
5504 GNUNET_break_op (0);
5508 connection_change_state (c, MESH_CONNECTION_READY);
5509 connection_reset_timeout (c, fwd);
5511 if (connection_is_terminal (c, fwd))
5514 GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
5515 send_prebuilt_message_connection (message, c, NULL, fwd);
5523 * Functions to handle messages from core
5525 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
5526 {&handle_mesh_connection_create, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
5528 {&handle_mesh_connection_ack, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
5529 sizeof (struct GNUNET_MESH_ConnectionACK)},
5530 {&handle_mesh_connection_broken, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN,
5531 sizeof (struct GNUNET_MESH_ConnectionBroken)},
5532 {&handle_mesh_connection_destroy, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY,
5533 sizeof (struct GNUNET_MESH_ConnectionDestroy)},
5534 {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE,
5535 sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
5536 {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE,
5537 sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
5538 {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
5539 sizeof (struct GNUNET_MESH_ACK)},
5540 {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
5541 sizeof (struct GNUNET_MESH_Poll)},
5542 {&handle_mesh_fwd, GNUNET_MESSAGE_TYPE_MESH_FWD, 0},
5543 {&handle_mesh_bck, GNUNET_MESSAGE_TYPE_MESH_BCK, 0},
5549 * Function to process paths received for a new peer addition. The recorded
5550 * paths form the initial tunnel, which can be optimized later.
5551 * Called on each result obtained for the DHT search.
5553 * @param cls closure
5554 * @param exp when will this value expire
5555 * @param key key of the result
5556 * @param get_path path of the get request
5557 * @param get_path_length lenght of get_path
5558 * @param put_path path of the put request
5559 * @param put_path_length length of the put_path
5560 * @param type type of the result
5561 * @param size number of bytes in data
5562 * @param data pointer to the result data
5565 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5566 const struct GNUNET_HashCode * key,
5567 const struct GNUNET_PeerIdentity *get_path,
5568 unsigned int get_path_length,
5569 const struct GNUNET_PeerIdentity *put_path,
5570 unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5571 size_t size, const void *data)
5573 struct MeshPeer *peer = cls;
5574 struct MeshPeerPath *p;
5575 struct MeshConnection *c;
5576 struct GNUNET_PeerIdentity pi;
5579 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
5580 GNUNET_PEER_resolve (peer->id, &pi);
5581 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " for %s\n", GNUNET_i2s (&pi));
5583 p = path_build_from_dht (get_path, get_path_length,
5584 put_path, put_path_length);
5585 path_add_to_peers (p, GNUNET_NO);
5588 /* Count connections */
5589 for (c = peer->tunnel->connection_head, i = 0; NULL != c; c = c->next, i++);
5591 /* If we already have 3 (or more (?!)) connections, it's enough */
5595 if (peer->tunnel->state == MESH_TUNNEL_SEARCHING)
5597 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... connect!\n");
5598 peer_connect (peer);
5604 /******************************************************************************/
5605 /********************* MESH LOCAL HANDLES **************************/
5606 /******************************************************************************/
5610 * Handler for client connection.
5612 * @param cls Closure (unused).
5613 * @param client Client handler.
5616 handle_local_client_connect (void *cls, struct GNUNET_SERVER_Client *client)
5618 struct MeshClient *c;
5622 c = GNUNET_malloc (sizeof (struct MeshClient));
5624 c->id = next_client_id++; /* overflow not important: just for debug */
5625 GNUNET_SERVER_client_keep (client);
5626 GNUNET_SERVER_client_set_user_context (client, c);
5627 GNUNET_CONTAINER_DLL_insert (clients_head, clients_tail, c);
5632 * Handler for client disconnection
5634 * @param cls closure
5635 * @param client identification of the client; NULL
5636 * for the last call when the server is destroyed
5639 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
5641 struct MeshClient *c;
5642 struct MeshClient *next;
5644 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected: %p\n", client);
5647 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " (SERVER DOWN)\n");
5651 c = client_get (client);
5654 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u, %p)\n",
5656 GNUNET_SERVER_client_drop (c->handle);
5657 c->shutting_down = GNUNET_YES;
5658 if (NULL != c->own_channels)
5660 GNUNET_CONTAINER_multihashmap32_iterate (c->own_channels,
5661 &channel_destroy_iterator, c);
5662 GNUNET_CONTAINER_multihashmap32_destroy (c->own_channels);
5665 if (NULL != c->incoming_channels)
5667 GNUNET_CONTAINER_multihashmap32_iterate (c->incoming_channels,
5668 &channel_destroy_iterator, c);
5669 GNUNET_CONTAINER_multihashmap32_destroy (c->incoming_channels);
5672 if (NULL != c->ports)
5674 GNUNET_CONTAINER_multihashmap32_iterate (c->ports,
5675 &client_release_ports, c);
5676 GNUNET_CONTAINER_multihashmap32_destroy (c->ports);
5679 GNUNET_CONTAINER_DLL_remove (clients_head, clients_tail, c);
5680 GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
5681 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " client free (%p)\n", c);
5687 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " context NULL!\n");
5689 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "done!\n");
5695 * Handler for new clients
5697 * @param cls closure
5698 * @param client identification of the client
5699 * @param message the actual message, which includes messages the client wants
5702 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
5703 const struct GNUNET_MessageHeader *message)
5705 struct GNUNET_MESH_ClientConnect *cc_msg;
5706 struct MeshClient *c;
5711 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected %p\n", client);
5713 /* Check data sanity */
5714 size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
5715 cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
5716 if (0 != (size % sizeof (uint32_t)))
5719 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5722 size /= sizeof (uint32_t);
5724 /* Initialize new client structure */
5725 c = GNUNET_SERVER_client_get_user_context (client, struct MeshClient);
5726 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " client id %u\n", c->id);
5727 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " client has %u ports\n", size);
5732 p = (uint32_t *) &cc_msg[1];
5733 c->ports = GNUNET_CONTAINER_multihashmap32_create (size);
5734 for (i = 0; i < size; i++)
5737 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " port: %u\n", u32);
5739 /* store in client's hashmap */
5740 GNUNET_CONTAINER_multihashmap32_put (c->ports, u32, c,
5741 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
5742 /* store in global hashmap */
5743 /* FIXME only allow one client to have the port open,
5744 * have a backup hashmap with waiting clients */
5745 GNUNET_CONTAINER_multihashmap32_put (ports, u32, c,
5746 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
5750 c->own_channels = GNUNET_CONTAINER_multihashmap32_create (32);
5751 c->incoming_channels = GNUNET_CONTAINER_multihashmap32_create (32);
5752 GNUNET_SERVER_notification_context_add (nc, client);
5753 GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
5755 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5756 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
5761 * Handler for requests of new tunnels
5763 * @param cls Closure.
5764 * @param client Identification of the client.
5765 * @param message The actual message.
5768 handle_local_channel_create (void *cls, struct GNUNET_SERVER_Client *client,
5769 const struct GNUNET_MessageHeader *message)
5771 struct GNUNET_MESH_ChannelMessage *msg;
5772 struct MeshPeer *peer;
5773 struct MeshTunnel2 *t;
5774 struct MeshChannel *ch;
5775 struct MeshClient *c;
5776 MESH_ChannelNumber chid;
5778 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new channel requested\n");
5780 /* Sanity check for client registration */
5781 if (NULL == (c = client_get (client)))
5784 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5787 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
5789 /* Message size sanity check */
5790 if (sizeof (struct GNUNET_MESH_ChannelMessage) != ntohs (message->size))
5793 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5797 msg = (struct GNUNET_MESH_ChannelMessage *) message;
5798 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " towards %s:%u\n",
5799 GNUNET_i2s (&msg->peer), ntohl (msg->port));
5800 chid = ntohl (msg->channel_id);
5802 /* Sanity check for duplicate channel IDs */
5803 if (NULL != channel_get_by_local_id (c, chid))
5806 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5810 peer = peer_get (&msg->peer);
5811 if (NULL == peer->tunnel)
5813 struct GNUNET_HashCode tid;
5815 GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE, &tid);
5816 peer->tunnel = tunnel_new (&tid);
5817 peer->tunnel->peer = peer;
5821 /* Create channel */
5822 ch = channel_new (t, c, chid);
5826 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5829 ch->port = ntohl (msg->port);
5830 channel_set_options (ch, ntohl (msg->opt));
5832 /* In unreliable channels, we'll use the DLL to buffer data for the root */
5833 ch->fwd_rel = GNUNET_malloc (sizeof (struct MeshChannelReliability));
5834 ch->fwd_rel->ch = ch;
5835 ch->fwd_rel->expected_delay = MESH_RETRANSMIT_TIME;
5837 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED CHANNEL %s[%x]:%u (%x)\n",
5838 GNUNET_h2s (&t->id), ch->gid, ch->port, ch->lid_root);
5839 peer_connect (peer);
5840 /* FIXME send create channel */
5842 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5848 * Handler for requests of deleting tunnels
5850 * @param cls closure
5851 * @param client identification of the client
5852 * @param message the actual message
5855 handle_local_channel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
5856 const struct GNUNET_MessageHeader *message)
5858 struct GNUNET_MESH_ChannelMessage *msg;
5859 struct MeshClient *c;
5860 struct MeshChannel *ch;
5861 struct MeshTunnel2 *t;
5862 MESH_ChannelNumber chid;
5864 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5865 "Got a DESTROY CHANNEL from client!\n");
5867 /* Sanity check for client registration */
5868 if (NULL == (c = client_get (client)))
5871 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5874 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
5876 /* Message sanity check */
5877 if (sizeof (struct GNUNET_MESH_ChannelMessage) != ntohs (message->size))
5880 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5884 msg = (struct GNUNET_MESH_ChannelMessage *) message;
5886 /* Retrieve tunnel */
5887 chid = ntohl (msg->channel_id);
5888 ch = channel_get_by_local_id (c, chid);
5891 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, " channel %X not found\n", chid);
5893 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5897 /* Cleanup after the tunnel */
5898 client_delete_channel (c, ch);
5899 if (c == ch->dest && GNUNET_MESH_LOCAL_CHANNEL_ID_SERV <= chid)
5903 else if (c == ch->root && GNUNET_MESH_LOCAL_CHANNEL_ID_SERV > chid)
5909 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5910 " channel %X client %p (%p, %p)\n",
5911 chid, c, ch->root, ch->dest);
5916 channel_destroy (ch);
5917 tunnel_destroy_if_empty (t);
5919 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5925 * Handler for client traffic
5927 * @param cls closure
5928 * @param client identification of the client
5929 * @param message the actual message
5932 handle_local_data (void *cls, struct GNUNET_SERVER_Client *client,
5933 const struct GNUNET_MessageHeader *message)
5935 struct GNUNET_MESH_LocalData *msg;
5936 struct MeshClient *c;
5937 struct MeshChannel *ch;
5938 MESH_ChannelNumber chid;
5942 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5943 "Got data from a client!\n");
5945 /* Sanity check for client registration */
5946 if (NULL == (c = client_get (client)))
5949 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5952 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
5954 msg = (struct GNUNET_MESH_LocalData *) message;
5956 /* Sanity check for message size */
5957 size = ntohs (message->size) - sizeof (struct GNUNET_MESH_LocalData);
5958 if (size < sizeof (struct GNUNET_MessageHeader))
5961 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5965 /* Channel exists? */
5966 chid = ntohl (msg->id);
5967 fwd = chid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
5968 ch = channel_get_by_local_id (c, chid);
5972 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5976 /* Is the client in the channel? */
5979 ch->root->handle == client)
5983 ch->dest->handle == client) ) )
5986 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5990 /* Ok, everything is correct, send the message
5991 * (pretend we got it from a mesh peer)
5994 struct GNUNET_MESH_Data *payload;
5995 char cbuf[sizeof(struct GNUNET_MESH_Data) + size];
5998 mid = fwd ? &ch->mid_send_fwd : &ch->mid_send_bck;
5999 if (GNUNET_YES == ch->reliable)
6001 struct MeshChannelReliability *rel;
6002 struct MeshReliableMessage *copy;
6004 rel = fwd ? ch->fwd_rel : ch->bck_rel;
6005 copy = GNUNET_malloc (sizeof (struct MeshReliableMessage)
6006 + sizeof(struct GNUNET_MESH_Data)
6009 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! DATA %u\n", copy->mid);
6010 copy->timestamp = GNUNET_TIME_absolute_get ();
6013 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " n_sent %u\n", rel->n_sent);
6014 GNUNET_CONTAINER_DLL_insert_tail (rel->head_sent, rel->tail_sent, copy);
6015 if (GNUNET_SCHEDULER_NO_TASK == rel->retry_task)
6018 GNUNET_TIME_relative_multiply (rel->expected_delay,
6019 MESH_RETRANSMIT_MARGIN);
6021 GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
6022 &channel_retransmit_message,
6025 payload = (struct GNUNET_MESH_Data *) ©[1];
6029 payload = (struct GNUNET_MESH_Data *) cbuf;
6031 payload->mid = htonl (*mid);
6033 memcpy (&payload[1], &msg[1], size);
6034 payload->header.size = htons (sizeof (struct GNUNET_MESH_Data) + size);
6035 payload->header.type = htons (chid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV ?
6036 GNUNET_MESSAGE_TYPE_MESH_UNICAST :
6037 GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
6038 payload->chid = htonl (ch->gid);
6039 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6040 " calling generic handler...\n");
6041 send_prebuilt_message_channel (&payload->header, ch, fwd);
6043 if (tunnel_get_buffer (ch->t, fwd) > 0)
6044 send_local_ack (ch, c, fwd);
6045 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
6046 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6053 * Handler for client's ACKs for payload traffic.
6055 * @param cls Closure (unused).
6056 * @param client Identification of the client.
6057 * @param message The actual message.
6060 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
6061 const struct GNUNET_MessageHeader *message)
6063 struct GNUNET_MESH_LocalAck *msg;
6064 struct MeshChannelReliability *rel;
6065 struct MeshChannel *ch;
6066 struct MeshClient *c;
6067 MESH_ChannelNumber chid;
6070 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
6072 /* Sanity check for client registration */
6073 if (NULL == (c = client_get (client)))
6076 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6079 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
6081 msg = (struct GNUNET_MESH_LocalAck *) message;
6083 /* Channel exists? */
6084 chid = ntohl (msg->channel_id);
6085 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " on channel %X\n", chid);
6086 ch = channel_get_by_local_id (c, chid);
6090 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Channel %X unknown.\n", chid);
6091 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " for client %u.\n", c->id);
6092 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6096 fwd = chid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
6097 rel = fwd ? ch->fwd_rel : ch->bck_rel;
6099 rel->client_ready = GNUNET_YES;
6100 channel_send_client_buffered_data (ch, c, rel);
6101 channel_send_ack (ch, 64 - rel->n_recv, fwd);
6103 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6110 * Iterator over all tunnels to send a monitoring client info about each tunnel.
6112 * @param cls Closure (client handle).
6113 * @param key Key (hashed tunnel ID, unused).
6114 * @param value Tunnel info.
6116 * @return GNUNET_YES, to keep iterating.
6119 monitor_all_tunnels_iterator (void *cls,
6120 const struct GNUNET_HashCode * key,
6123 struct GNUNET_SERVER_Client *client = cls;
6124 struct MeshChannel *ch = value;
6125 struct GNUNET_MESH_LocalMonitor *msg;
6127 msg = GNUNET_malloc (sizeof(struct GNUNET_MESH_LocalMonitor));
6128 msg->channel_id = htonl (ch->gid);
6129 msg->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
6130 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
6132 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6133 "* sending info about tunnel %s\n",
6134 GNUNET_i2s (&msg->owner));
6136 GNUNET_SERVER_notification_context_unicast (nc, client,
6137 &msg->header, GNUNET_NO);
6143 * Handler for client's MONITOR request.
6145 * @param cls Closure (unused).
6146 * @param client Identification of the client.
6147 * @param message The actual message.
6150 handle_local_get_tunnels (void *cls, struct GNUNET_SERVER_Client *client,
6151 const struct GNUNET_MessageHeader *message)
6153 struct MeshClient *c;
6155 /* Sanity check for client registration */
6156 if (NULL == (c = client_get (client)))
6159 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6163 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6164 "Received get tunnels request from client %u\n",
6166 GNUNET_CONTAINER_multihashmap_iterate (tunnels,
6167 monitor_all_tunnels_iterator,
6169 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6170 "Get tunnels request from client %u completed\n",
6172 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6177 * Handler for client's MONITOR_TUNNEL request.
6179 * @param cls Closure (unused).
6180 * @param client Identification of the client.
6181 * @param message The actual message.
6184 handle_local_show_tunnel (void *cls, struct GNUNET_SERVER_Client *client,
6185 const struct GNUNET_MessageHeader *message)
6187 const struct GNUNET_MESH_LocalMonitor *msg;
6188 struct GNUNET_MESH_LocalMonitor *resp;
6189 struct MeshClient *c;
6190 struct MeshChannel *ch;
6192 /* Sanity check for client registration */
6193 if (NULL == (c = client_get (client)))
6196 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6200 msg = (struct GNUNET_MESH_LocalMonitor *) message;
6201 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6202 "Received tunnel info request from client %u for tunnel %s[%X]\n",
6205 ntohl (msg->channel_id));
6206 // ch = channel_get (&msg->owner, ntohl (msg->channel_id));
6210 /* We don't know the tunnel */
6211 struct GNUNET_MESH_LocalMonitor warn;
6214 GNUNET_SERVER_notification_context_unicast (nc, client,
6217 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6221 /* Initialize context */
6222 resp = GNUNET_malloc (sizeof (struct GNUNET_MESH_LocalMonitor));
6224 resp->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
6225 GNUNET_SERVER_notification_context_unicast (nc, c->handle,
6226 &resp->header, GNUNET_NO);
6229 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6230 "Monitor tunnel request from client %u completed\n",
6232 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6237 * Functions to handle messages from clients
6239 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
6240 {&handle_local_new_client, NULL,
6241 GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
6242 {&handle_local_channel_create, NULL,
6243 GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE,
6244 sizeof (struct GNUNET_MESH_ChannelMessage)},
6245 {&handle_local_channel_destroy, NULL,
6246 GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY,
6247 sizeof (struct GNUNET_MESH_ChannelMessage)},
6248 {&handle_local_data, NULL,
6249 GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA, 0},
6250 {&handle_local_ack, NULL,
6251 GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
6252 sizeof (struct GNUNET_MESH_LocalAck)},
6253 {&handle_local_get_tunnels, NULL,
6254 GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS,
6255 sizeof (struct GNUNET_MessageHeader)},
6256 {&handle_local_show_tunnel, NULL,
6257 GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL,
6258 sizeof (struct GNUNET_MESH_LocalMonitor)},
6264 * Method called whenever a given peer connects.
6266 * @param cls closure
6267 * @param peer peer identity this notification is about
6270 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
6272 struct MeshPeer *pi;
6273 struct MeshPeerPath *path;
6275 DEBUG_CONN ("Peer connected\n");
6276 DEBUG_CONN (" %s\n", GNUNET_i2s (&my_full_id));
6277 pi = peer_get (peer);
6280 DEBUG_CONN (" (self)\n");
6281 path = path_new (1);
6285 DEBUG_CONN (" %s\n", GNUNET_i2s (peer));
6286 path = path_new (2);
6287 path->peers[1] = pi->id;
6288 GNUNET_PEER_change_rc (pi->id, 1);
6289 GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
6291 path->peers[0] = myid;
6292 GNUNET_PEER_change_rc (myid, 1);
6293 peer_add_path (pi, path, GNUNET_YES);
6295 pi->connections = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_YES);
6301 * Method called whenever a peer disconnects.
6303 * @param cls closure
6304 * @param peer peer identity this notification is about
6307 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
6309 struct MeshPeer *pi;
6311 DEBUG_CONN ("Peer disconnected\n");
6312 pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
6319 peer_remove_path (pi, myid, pi->id);
6321 GNUNET_CONTAINER_multihashmap_iterate (pi->connections,
6324 GNUNET_CONTAINER_multihashmap_destroy (pi->connections);
6325 pi->connections = NULL;
6328 DEBUG_CONN (" (self)\n");
6330 GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
6337 * Install server (service) handlers and start listening to clients.
6342 GNUNET_SERVER_add_handlers (server_handle, client_handlers);
6343 GNUNET_SERVER_connect_notify (server_handle,
6344 &handle_local_client_connect, NULL);
6345 GNUNET_SERVER_disconnect_notify (server_handle,
6346 &handle_local_client_disconnect, NULL);
6347 nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
6349 clients_head = NULL;
6350 clients_tail = NULL;
6352 GNUNET_SERVER_resume (server_handle);
6357 * To be called on core init/fail.
6359 * @param cls Closure (config)
6360 * @param server handle to the server for this service
6361 * @param identity the public identity of this peer
6364 core_init (void *cls, struct GNUNET_CORE_Handle *server,
6365 const struct GNUNET_PeerIdentity *identity)
6367 const struct GNUNET_CONFIGURATION_Handle *c = cls;
6370 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
6371 GNUNET_break (core_handle == server);
6372 if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
6375 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
6376 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6378 GNUNET_i2s (identity));
6379 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6381 GNUNET_i2s (&my_full_id));
6382 GNUNET_CORE_disconnect (core_handle);
6383 core_handle = GNUNET_CORE_connect (c, /* Main configuration */
6384 NULL, /* Closure passed to MESH functions */
6385 &core_init, /* Call core_init once connected */
6386 &core_connect, /* Handle connects */
6387 &core_disconnect, /* remove peers on disconnects */
6388 NULL, /* Don't notify about all incoming messages */
6389 GNUNET_NO, /* For header only in notification */
6390 NULL, /* Don't notify about all outbound messages */
6391 GNUNET_NO, /* For header-only out notification */
6392 core_handlers); /* Register these handlers */
6401 /******************************************************************************/
6402 /************************ MAIN FUNCTIONS ****************************/
6403 /******************************************************************************/
6406 * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
6408 * @param cls closure
6409 * @param key current key code
6410 * @param value value in the hash map
6411 * @return GNUNET_YES if we should continue to iterate,
6415 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
6417 struct MeshTunnel2 *t = value;
6425 * Task run during shutdown.
6431 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
6433 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
6435 if (core_handle != NULL)
6437 GNUNET_CORE_disconnect (core_handle);
6440 GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
6441 if (dht_handle != NULL)
6443 GNUNET_DHT_disconnect (dht_handle);
6448 GNUNET_SERVER_notification_context_destroy (nc);
6451 if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
6453 GNUNET_SCHEDULER_cancel (announce_id_task);
6454 announce_id_task = GNUNET_SCHEDULER_NO_TASK;
6456 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
6461 * Process mesh requests.
6463 * @param cls closure
6464 * @param server the initialized server
6465 * @param c configuration to use
6468 run (void *cls, struct GNUNET_SERVER_Handle *server,
6469 const struct GNUNET_CONFIGURATION_Handle *c)
6472 struct GNUNET_CRYPTO_EccPrivateKey *pk;
6474 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
6475 server_handle = server;
6476 GNUNET_SERVER_suspend (server_handle);
6479 GNUNET_CONFIGURATION_get_value_filename (c, "PEER", "PRIVATE_KEY",
6482 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6484 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6485 "mesh", "peer/privatekey");
6486 GNUNET_SCHEDULER_shutdown ();
6491 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_CONNECTION_TIME",
6492 &refresh_connection_time))
6494 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6496 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6497 "mesh", "refresh path time");
6498 GNUNET_SCHEDULER_shutdown ();
6503 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
6506 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6508 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6509 "mesh", "id announce time");
6510 GNUNET_SCHEDULER_shutdown ();
6515 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
6518 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6520 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6521 "mesh", "connect timeout");
6522 GNUNET_SCHEDULER_shutdown ();
6527 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
6530 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6532 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6533 "mesh", "max msgs queue");
6534 GNUNET_SCHEDULER_shutdown ();
6539 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_CONNECTIONS",
6542 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6544 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6545 "mesh", "max tunnels");
6546 GNUNET_SCHEDULER_shutdown ();
6551 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
6554 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6556 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
6557 "mesh", "default ttl", 64);
6562 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
6565 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6566 _("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
6567 "mesh", "max peers", 1000);
6572 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DROP_PERCENT",
6579 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6580 "Mesh is running with drop mode enabled. "
6581 "This is NOT a good idea! "
6582 "Remove the DROP_PERCENT option from your configuration.\n");
6586 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
6587 &dht_replication_level))
6589 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6591 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
6592 "mesh", "dht replication level", 3);
6593 dht_replication_level = 3;
6596 tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6597 peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6598 ports = GNUNET_CONTAINER_multihashmap32_create (32);
6600 dht_handle = GNUNET_DHT_connect (c, 64);
6601 if (NULL == dht_handle)
6605 stats = GNUNET_STATISTICS_create ("mesh", c);
6607 /* Scheduled the task to clean up when shutdown is called */
6608 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
6610 pk = GNUNET_CRYPTO_ecc_key_create_from_file (keyfile);
6611 GNUNET_free (keyfile);
6612 GNUNET_assert (NULL != pk);
6613 my_private_key = pk;
6614 GNUNET_CRYPTO_ecc_key_get_public (my_private_key, &my_public_key);
6615 GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
6616 &my_full_id.hashPubKey);
6617 myid = GNUNET_PEER_intern (&my_full_id);
6618 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6619 "Mesh for peer [%s] starting\n",
6620 GNUNET_i2s(&my_full_id));
6622 core_handle = GNUNET_CORE_connect (c, /* Main configuration */
6623 NULL, /* Closure passed to MESH functions */
6624 &core_init, /* Call core_init once connected */
6625 &core_connect, /* Handle connects */
6626 &core_disconnect, /* remove peers on disconnects */
6627 NULL, /* Don't notify about all incoming messages */
6628 GNUNET_NO, /* For header only in notification */
6629 NULL, /* Don't notify about all outbound messages */
6630 GNUNET_NO, /* For header-only out notification */
6631 core_handlers); /* Register these handlers */
6632 if (NULL == core_handle)
6635 GNUNET_SCHEDULER_shutdown ();
6638 announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
6639 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
6644 * The main function for the mesh service.
6646 * @param argc number of arguments from the command line
6647 * @param argv command line arguments
6648 * @return 0 ok, 1 on error
6651 main (int argc, char *const *argv)
6656 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
6657 r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
6659 ret = (GNUNET_OK == r) ? 0 : 1;
6660 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");