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 tunnels are we willing to maintain.
789 * Local tunnels are always allowed, even if there are more tunnels than max.
791 static unsigned long long max_tunnels;
794 * How many messages *in total* are we willing to queue, divided by number of
795 * tunnels 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 * Send FWD keepalive packets for a connection.
1042 * @param cls Closure (connection for which to send the keepalive).
1043 * @param tc Notification context.
1046 connection_fwd_keepalive (void *cls,
1047 const struct GNUNET_SCHEDULER_TaskContext *tc);
1050 * Send BCK keepalive packets for a connection.
1052 * @param cls Closure (connection for which to send the keepalive).
1053 * @param tc Notification context.
1056 connection_bck_keepalive (void *cls,
1057 const struct GNUNET_SCHEDULER_TaskContext *tc);
1061 * Change the tunnel state.
1063 * @param c Connection whose state to change.
1064 * @param state New state.
1067 connection_change_state (struct MeshConnection* c,
1068 enum MeshConnectionState state);
1073 * @brief Queue and pass message to core when possible.
1075 * @param cls Closure (@c type dependant). It will be used by queue_send to
1076 * build the message to be sent if not already prebuilt.
1077 * @param type Type of the message, 0 for a raw message.
1078 * @param size Size of the message.
1079 * @param dst Neighbor to send message to.
1080 * @param c Connection this message belongs to, if any.
1081 * @param ch Channel this message belongs to, if applicable (otherwise NULL).
1084 queue_add (void *cls, uint16_t type, size_t size,
1085 struct MeshPeer *dst,
1086 struct MeshConnection *c,
1087 struct MeshChannel *ch);
1091 * Free a transmission that was already queued with all resources
1092 * associated to the request.
1094 * @param queue Queue handler to cancel.
1095 * @param clear_cls Is it necessary to free associated cls?
1098 queue_destroy (struct MeshPeerQueue *queue, int clear_cls);
1102 * Core callback to write a queued packet to core buffer
1104 * @param cls Closure (peer info).
1105 * @param size Number of bytes available in buf.
1106 * @param buf Where the to write the message.
1108 * @return number of bytes written to buf
1111 queue_send (void *cls, size_t size, void *buf);
1115 * Dummy function to separate declarations from definitions in function list.
1118 __mesh_divider______________________________________________________________();
1122 * Get string description for tunnel state.
1124 * @param s Tunnel state.
1126 * @return String representation.
1129 GNUNET_MESH_DEBUG_TS2S (enum MeshTunnelState s)
1131 static char buf[128];
1135 case MESH_TUNNEL_NEW:
1136 return "MESH_TUNNEL_NEW";
1137 case MESH_TUNNEL_SEARCHING:
1138 return "MESH_TUNNEL_SEARCHING";
1139 case MESH_TUNNEL_WAITING:
1140 return "MESH_TUNNEL_WAITING";
1141 case MESH_TUNNEL_READY:
1142 return "MESH_TUNNEL_READY";
1143 case MESH_TUNNEL_RECONNECTING:
1144 return "MESH_TUNNEL_RECONNECTING";
1147 sprintf (buf, "%u (UNKNOWN STATE)", s);
1154 * Get string description for tunnel state.
1156 * @param s Tunnel state.
1158 * @return String representation.
1161 GNUNET_MESH_DEBUG_CS2S (enum MeshTunnelState s)
1165 case MESH_CONNECTION_NEW:
1166 return "MESH_CONNECTION_NEW";
1167 case MESH_CONNECTION_SENT:
1168 return "MESH_CONNECTION_SENT";
1169 case MESH_CONNECTION_READY:
1170 return "MESH_CONNECTION_READY";
1172 return "MESH_CONNECTION_STATE_ERROR";
1178 /******************************************************************************/
1179 /************************ PERIODIC FUNCTIONS ****************************/
1180 /******************************************************************************/
1183 * Periodically announce self id in the DHT
1185 * @param cls closure
1186 * @param tc task context
1189 announce_id (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1191 struct PBlock block;
1193 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1195 announce_id_task = GNUNET_SCHEDULER_NO_TASK;
1199 * - Set data expiration in function of X
1200 * - Adapt X to churn
1202 DEBUG_DHT ("DHT_put for ID %s started.\n", GNUNET_i2s (&my_full_id));
1204 block.id = my_full_id;
1205 GNUNET_DHT_put (dht_handle, /* DHT handle */
1206 &my_full_id.hashPubKey, /* Key to use */
1207 dht_replication_level, /* Replication level */
1208 GNUNET_DHT_RO_RECORD_ROUTE | GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, /* DHT options */
1209 GNUNET_BLOCK_TYPE_MESH_PEER, /* Block type */
1210 sizeof (block), /* Size of the data */
1211 (const char *) &block, /* Data itself */
1212 GNUNET_TIME_UNIT_FOREVER_ABS, /* Data expiration */
1213 GNUNET_TIME_UNIT_FOREVER_REL, /* Retry time */
1214 NULL, /* Continuation */
1215 NULL); /* Continuation closure */
1217 GNUNET_SCHEDULER_add_delayed (id_announce_time, &announce_id, cls);
1221 /******************************************************************************/
1222 /****************** GENERAL HELPER FUNCTIONS ************************/
1223 /******************************************************************************/
1227 * Get the static string for a peer ID.
1231 * @return Static string for it's ID.
1234 peer2s (const struct MeshPeer *peer)
1238 return GNUNET_i2s (GNUNET_PEER_resolve2 (peer->id));
1243 * Get the previous hop in a connection
1245 * @param c Connection.
1247 * @return Previous peer in the connection.
1249 static struct MeshPeer *
1250 connection_get_prev_hop (struct MeshConnection *c)
1254 if (0 == c->own_pos || c->path->length < 2)
1255 id = c->path->peers[0];
1257 id = c->path->peers[c->own_pos - 1];
1259 return peer_get_short (id);
1264 * Get the next hop in a connection
1266 * @param c Connection.
1268 * @return Next peer in the connection.
1270 static struct MeshPeer *
1271 connection_get_next_hop (struct MeshConnection *c)
1275 if ((c->path->length - 1) == c->own_pos || c->path->length < 2)
1276 id = c->path->peers[c->path->length - 1];
1278 id = c->path->peers[c->own_pos + 1];
1280 return peer_get_short (id);
1285 * Get the hop in a connection.
1287 * @param c Connection.
1288 * @param fwd Next hop?
1290 * @return Next peer in the connection.
1292 static struct MeshPeer *
1293 connection_get_hop (struct MeshConnection *c, int fwd)
1296 return connection_get_next_hop (c);
1297 return connection_get_prev_hop (c);
1301 * Check if client has registered with the service and has not disconnected
1303 * @param client the client to check
1305 * @return non-NULL if client exists in the global DLL
1307 static struct MeshClient *
1308 client_get (struct GNUNET_SERVER_Client *client)
1310 return GNUNET_SERVER_client_get_user_context (client, struct MeshClient);
1315 * Deletes a tunnel from a client (either owner or destination).
1317 * @param c Client whose tunnel to delete.
1318 * @param ch Channel which should be deleted.
1321 client_delete_channel (struct MeshClient *c, struct MeshChannel *ch)
1327 res = GNUNET_CONTAINER_multihashmap32_remove (c->own_channels,
1329 if (GNUNET_YES != res)
1330 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client_delete_channel owner KO\n");
1334 res = GNUNET_CONTAINER_multihashmap32_remove (c->incoming_channels,
1336 if (GNUNET_YES != res)
1337 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client_delete_tunnel client KO\n");
1343 * Notify the appropriate client that a new incoming channel was created.
1345 * @param ch Channel that was created.
1348 send_local_channel_create (struct MeshChannel *ch)
1350 struct GNUNET_MESH_ChannelMessage msg;
1351 struct MeshTunnel2 *t = ch->t;
1353 if (NULL == ch->dest)
1355 msg.header.size = htons (sizeof (msg));
1356 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
1357 msg.channel_id = htonl (ch->lid_dest);
1358 msg.port = htonl (ch->port);
1360 msg.opt |= GNUNET_YES == ch->reliable ? GNUNET_MESH_OPTION_RELIABLE : 0;
1361 msg.opt |= GNUNET_YES == ch->nobuffer ? GNUNET_MESH_OPTION_NOBUFFER : 0;
1362 msg.opt = htonl (msg.opt);
1363 GNUNET_PEER_resolve (t->peer->id, &msg.peer);
1364 GNUNET_SERVER_notification_context_unicast (nc, ch->dest->handle,
1365 &msg.header, GNUNET_NO);
1370 * Notify a client that the incoming tunnel is no longer valid.
1372 * @param ch Channel that is destroyed.
1373 * @param fwd Forward notification (owner->dest)?
1376 send_local_channel_destroy (struct MeshChannel *ch, int fwd)
1378 struct GNUNET_MESH_ChannelMessage msg;
1379 struct MeshClient *c;
1381 c = fwd ? ch->dest : ch->root;
1387 msg.header.size = htons (sizeof (msg));
1388 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1389 msg.channel_id = htonl (fwd ? ch->lid_dest : ch->lid_root);
1390 msg.port = htonl (0);
1391 memset (&msg.peer, 0, sizeof (msg.peer));
1392 msg.opt = htonl (0);
1393 GNUNET_SERVER_notification_context_unicast (nc, c->handle,
1394 &msg.header, GNUNET_NO);
1399 * Build a local ACK message and send it to a local client.
1401 * @param ch Channel on which to send the ACK.
1402 * @param c Client to whom send the ACK.
1403 * @param is_fwd Set to GNUNET_YES for FWD ACK (dest->owner)
1406 send_local_ack (struct MeshChannel *ch,
1407 struct MeshClient *c,
1410 struct GNUNET_MESH_LocalAck msg;
1412 msg.header.size = htons (sizeof (msg));
1413 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
1414 msg.channel_id = htonl (is_fwd ? ch->lid_root : ch->lid_dest);
1415 GNUNET_SERVER_notification_context_unicast (nc,
1423 * Count established (ready) connections of a tunnel.
1425 * @param t Tunnel on which to send the message.
1427 * @return Number of connections.
1430 tunnel_count_connections (struct MeshTunnel2 *t)
1432 struct MeshConnection *c;
1435 for (c = t->connection_head, i = 0; NULL != c; c = c->next, i++);
1442 * Pick a connection on which send the next data message.
1444 * @param t Tunnel on which to send the message.
1445 * @param fwd Is this a fwd message?
1447 * @return The connection on which to send the next message.
1449 static struct MeshConnection *
1450 tunnel_get_connection (struct MeshTunnel2 *t, int fwd)
1452 struct MeshConnection *c;
1453 struct MeshConnection *best;
1454 struct MeshFlowControl *fc;
1455 unsigned int lowest_q;
1458 lowest_q = UINT_MAX;
1459 for (c = t->connection_head; NULL != c; c = c->next)
1461 if (MESH_CONNECTION_READY == c->state)
1463 fc = fwd ? &c->fwd_fc : &c->bck_fc;
1469 if (fc->queue_n < lowest_q)
1472 lowest_q = fc->queue_n;
1481 * Get the total buffer space for a tunnel
1484 tunnel_get_buffer (struct MeshTunnel2 *t, int fwd)
1486 struct MeshConnection *c;
1487 struct MeshFlowControl *fc;
1488 unsigned int buffer;
1490 for (buffer = 0, c = t->connection_head; NULL != c; c = c->next)
1492 if (c->state != MESH_CONNECTION_READY)
1495 fc = fwd ? &c->fwd_fc : &c->bck_fc;
1496 buffer += fc->last_ack_recv - fc->last_pid_sent;
1504 * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
1505 * Encrypt data with the tunnel key.
1507 * @param t Tunnel whose key to use.
1508 * @param dst Destination for the encrypted data.
1509 * @param src Source of the plaintext.
1510 * @param size Size of the plaintext.
1511 * @param iv Initialization Vector to use.
1512 * @param fwd Is this a fwd message?
1515 tunnel_encrypt (struct MeshTunnel2 *t,
1516 void *dst, const void *src,
1517 size_t size, uint64_t iv, int fwd)
1519 memcpy (dst, src, size);
1524 * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
1525 * Decrypt data with the tunnel key.
1527 * @param t Tunnel whose key to use.
1528 * @param dst Destination for the plaintext.
1529 * @param src Source of the encrypted data.
1530 * @param size Size of the encrypted data.
1531 * @param iv Initialization Vector to use.
1532 * @param fwd Is this a fwd message?
1535 tunnel_decrypt (struct MeshTunnel2 *t,
1536 void *dst, const void *src,
1537 size_t size, uint64_t iv, int fwd)
1539 memcpy (dst, src, size);
1544 * Sends an already built message on a connection, properly registering
1545 * all used resources.
1547 * @param message Message to send. Function makes a copy of it.
1548 * If message is not hop-by-hop, decrements TTL of copy.
1549 * @param c Connection on which this message is transmitted.
1550 * @param ch Channel on which this message is transmitted, or NULL.
1551 * @param fwd Is this a fwd message?
1554 send_prebuilt_message_connection (const struct GNUNET_MessageHeader *message,
1555 struct MeshConnection *c,
1556 struct MeshChannel *ch,
1559 struct MeshPeer *neighbor;
1564 neighbor = connection_get_hop (c, fwd);
1565 if (NULL == neighbor)
1571 size = ntohs (message->size);
1572 data = GNUNET_malloc (size);
1573 memcpy (data, message, size);
1574 type = ntohs(message->type);
1576 if (GNUNET_MESSAGE_TYPE_MESH_FWD == type ||
1577 GNUNET_MESSAGE_TYPE_MESH_BCK == type)
1579 struct GNUNET_MESH_Encrypted *msg;
1582 msg = (struct GNUNET_MESH_Encrypted *) data;
1583 ttl = ntohl (msg->ttl);
1586 GNUNET_break_op (0);
1589 msg->ttl = htonl (ttl - 1);
1602 * Sends an already built message on a tunnel, choosing the best connection.
1604 * @param message Message to send. Function modifies it.
1605 * @param t Tunnel on which this message is transmitted.
1606 * @param ch Channel on which this message is transmitted.
1607 * @param fwd Is this a fwd message?
1610 send_prebuilt_message_tunnel (struct GNUNET_MESH_Encrypted *msg,
1611 struct MeshTunnel2 *t,
1612 struct MeshChannel *ch,
1615 struct MeshConnection *c;
1618 c = tunnel_get_connection (t, fwd);
1624 type = ntohs (msg->header.size);
1627 case GNUNET_MESSAGE_TYPE_MESH_FWD:
1628 case GNUNET_MESSAGE_TYPE_MESH_BCK:
1629 msg->cid = htonl (c->id);
1631 msg->ttl = default_ttl;
1637 send_prebuilt_message_connection (&msg->header, c, ch, fwd);
1642 * Sends an already built message on a channel, properly registering
1643 * all used resources and encrypting the message with the tunnel's key.
1645 * @param message Message to send. Function makes a copy of it.
1646 * @param ch Channel on which this message is transmitted.
1647 * @param fwd Is this a fwd message?
1650 send_prebuilt_message_channel (const struct GNUNET_MessageHeader *message,
1651 struct MeshChannel *ch,
1654 struct GNUNET_MESH_Encrypted *msg;
1655 size_t size = ntohs (message->size);
1656 char *cbuf[size + sizeof (struct GNUNET_MESH_Encrypted)];
1660 type = fwd ? GNUNET_MESSAGE_TYPE_MESH_FWD : GNUNET_MESSAGE_TYPE_MESH_BCK;
1661 iv = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
1663 msg = (struct GNUNET_MESH_Encrypted *) cbuf;
1664 msg->header.type = htons (type);
1665 msg->header.size = htons (size);
1666 msg->iv = GNUNET_htonll (iv);
1667 tunnel_encrypt (ch->t, &msg[1], message, size, iv, fwd);
1669 send_prebuilt_message_tunnel (msg, ch->t, ch, fwd);
1674 * Sends a CREATE CONNECTION message for a path to a peer.
1675 * Changes the connection and tunnel states if necessary.
1677 * @param connection Connection to create.
1680 send_connection_create (struct MeshConnection *connection)
1682 struct MeshPeer *neighbor;
1683 struct MeshTunnel2 *t;
1686 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send connection create\n");
1687 neighbor = connection_get_next_hop (connection);
1688 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " to %s\n", peer2s (neighbor));
1689 queue_add (connection,
1690 GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
1691 sizeof (struct GNUNET_MESH_ConnectionCreate) +
1692 (connection->path->length *
1693 sizeof (struct GNUNET_PeerIdentity)),
1697 if (MESH_TUNNEL_SEARCHING == t->state)
1698 tunnel_change_state (t, MESH_TUNNEL_WAITING);
1699 if (MESH_CONNECTION_NEW == connection->state)
1700 connection_change_state (connection, MESH_CONNECTION_SENT);
1705 * Sends a CONNECTION ACK message in reponse to a received CONNECTION_CREATE
1708 * @param connection Connection to confirm.
1711 send_connection_ack (struct MeshConnection *connection)
1713 struct MeshPeer *neighbor;
1714 struct MeshTunnel2 *t;
1717 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send connection ack\n");
1718 neighbor = connection_get_prev_hop (connection);
1719 queue_add (connection,
1720 GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
1721 sizeof (struct GNUNET_MESH_ConnectionACK),
1725 if (MESH_TUNNEL_NEW == t->state)
1726 tunnel_change_state (t, MESH_TUNNEL_WAITING);
1731 * Build a hop-by-hop ACK message and queue it to send for the given connection.
1733 * @param c Which connection to send the hop-by-hop ACK.
1734 * @param ack Value of the ACK.
1735 * @param fwd Is this fwd?
1738 send_ack (struct MeshConnection *c, uint32_t ack, int fwd)
1740 struct GNUNET_MESH_ACK msg;
1742 msg.header.size = htons (sizeof (msg));
1743 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ACK);
1744 msg.ack = htonl (ack);
1746 msg.cid = htonl (c->id);
1748 send_prebuilt_message_connection (&msg.header, c, NULL, fwd);
1753 * Core callback to write a pre-constructed data packet to core buffer
1755 * @param cls Closure (MeshTransmissionDescriptor with data in "data" member).
1756 * @param size Number of bytes available in buf.
1757 * @param buf Where the to write the message.
1759 * @return number of bytes written to buf
1762 send_core_data_raw (void *cls, size_t size, void *buf)
1764 struct GNUNET_MessageHeader *msg = cls;
1767 GNUNET_assert (NULL != msg);
1768 total_size = ntohs (msg->size);
1770 if (total_size > size)
1775 memcpy (buf, msg, total_size);
1782 * Function to send a create path packet to a peer.
1784 * @param cls closure
1785 * @param size number of bytes available in buf
1786 * @param buf where the callee should write the message
1787 * @return number of bytes written to buf
1790 send_core_connection_create (void *cls, size_t size, void *buf)
1792 struct MeshConnection *c = cls;
1793 struct GNUNET_MESH_ConnectionCreate *msg;
1794 struct GNUNET_PeerIdentity *peer_ptr;
1795 struct MeshPeerPath *p = c->path;
1799 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION CREATE...\n");
1801 sizeof (struct GNUNET_MESH_ConnectionCreate) +
1802 p->length * sizeof (struct GNUNET_PeerIdentity);
1804 if (size < size_needed || NULL == buf)
1809 msg = (struct GNUNET_MESH_ConnectionCreate *) buf;
1810 msg->header.size = htons (size_needed);
1811 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE);
1812 msg->cid = htonl (c->id);
1814 peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
1815 for (i = 0; i < p->length; i++)
1817 GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
1820 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1821 "CONNECTION CREATE (%u bytes long) sent!\n", size_needed);
1827 * Creates a path ack message in buf and frees all unused resources.
1829 * @param cls closure (MeshTransmissionDescriptor)
1830 * @param size number of bytes available in buf
1831 * @param buf where the callee should write the message
1832 * @return number of bytes written to buf
1835 send_core_connection_ack (void *cls, size_t size, void *buf)
1837 struct GNUNET_MESH_ConnectionACK *msg = buf;
1838 struct MeshConnection *c = cls;
1839 struct MeshTunnel2 *t = c->t;
1841 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION ACK...\n");
1842 GNUNET_assert (NULL != t);
1843 if (sizeof (struct GNUNET_MESH_ConnectionACK) > size)
1848 msg->header.size = htons (sizeof (struct GNUNET_MESH_ConnectionACK));
1849 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK);
1850 GNUNET_CRYPTO_hash_xor (&GNUNET_PEER_resolve2 (t->peer->id)->hashPubKey,
1851 &my_full_id.hashPubKey,
1853 msg->cid = htonl (c->id);
1855 /* TODO add signature */
1857 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CONNECTION ACK sent!\n");
1858 return sizeof (struct GNUNET_MESH_ConnectionACK);
1863 * Destroy the peer_info and free any allocated resources linked to it
1865 * @param peer The peer_info to destroy.
1867 * @return GNUNET_OK on success
1870 peer_destroy (struct MeshPeer *peer)
1872 struct GNUNET_PeerIdentity id;
1873 struct MeshPeerPath *p;
1874 struct MeshPeerPath *nextp;
1876 GNUNET_PEER_resolve (peer->id, &id);
1877 GNUNET_PEER_change_rc (peer->id, -1);
1880 GNUNET_CONTAINER_multihashmap_remove (peers, &id.hashPubKey, peer))
1883 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1884 "removing peer %s, not in hashmap\n", GNUNET_i2s (&id));
1886 if (NULL != peer->dhtget)
1888 GNUNET_DHT_get_stop (peer->dhtget);
1890 p = peer->path_head;
1894 GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
1898 tunnel_destroy_empty (peer->tunnel);
1905 * Returns if peer is used (has a tunnel, is neighbor).
1907 * @peer Peer to check.
1909 * @return GNUNET_YES if peer is in use.
1912 peer_is_used (struct MeshPeer *peer)
1914 struct MeshPeerPath *p;
1916 if (NULL != peer->tunnel)
1919 for (p = peer->path_head; NULL != p; p = p->next)
1928 * Iterator over all the peers to get the oldest timestamp.
1930 * @param cls Closure (unsued).
1931 * @param key ID of the peer.
1932 * @param value Peer_Info of the peer.
1935 peer_get_oldest (void *cls,
1936 const struct GNUNET_HashCode *key,
1939 struct MeshPeer *p = value;
1940 struct GNUNET_TIME_Absolute *abs = cls;
1942 /* Don't count active peers */
1943 if (GNUNET_YES == peer_is_used (p))
1946 if (abs->abs_value_us < p->last_contact.abs_value_us)
1947 abs->abs_value_us = p->last_contact.abs_value_us;
1954 * Iterator over all the peers to remove the oldest entry.
1956 * @param cls Closure (unsued).
1957 * @param key ID of the peer.
1958 * @param value Peer_Info of the peer.
1961 peer_timeout (void *cls,
1962 const struct GNUNET_HashCode *key,
1965 struct MeshPeer *p = value;
1966 struct GNUNET_TIME_Absolute *abs = cls;
1968 if (p->last_contact.abs_value_us == abs->abs_value_us &&
1969 GNUNET_NO == peer_is_used (p))
1979 * Delete oldest unused peer.
1982 peer_delete_oldest (void)
1984 struct GNUNET_TIME_Absolute abs;
1986 abs = GNUNET_TIME_UNIT_FOREVER_ABS;
1988 GNUNET_CONTAINER_multihashmap_iterate (peers,
1991 GNUNET_CONTAINER_multihashmap_iterate (peers,
1998 * Retrieve the MeshPeer stucture associated with the peer, create one
1999 * and insert it in the appropriate structures if the peer is not known yet.
2001 * @param peer Full identity of the peer.
2003 * @return Existing or newly created peer info.
2005 static struct MeshPeer *
2006 peer_get (const struct GNUNET_PeerIdentity *peer_id)
2008 struct MeshPeer *peer;
2010 peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer_id->hashPubKey);
2013 peer = GNUNET_new (struct MeshPeer);
2014 if (GNUNET_CONTAINER_multihashmap_size (peers) > max_peers)
2016 peer_delete_oldest ();
2018 GNUNET_CONTAINER_multihashmap_put (peers, &peer_id->hashPubKey, peer,
2019 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
2020 peer->id = GNUNET_PEER_intern (peer_id);
2022 peer->last_contact = GNUNET_TIME_absolute_get();
2029 * Retrieve the MeshPeer stucture associated with the peer, create one
2030 * and insert it in the appropriate structures if the peer is not known yet.
2032 * @param peer Short identity of the peer.
2034 * @return Existing or newly created peer info.
2036 static struct MeshPeer *
2037 peer_get_short (const GNUNET_PEER_Id peer)
2039 return peer_get (GNUNET_PEER_resolve2 (peer));
2044 * Get a cost of a path for a peer considering existing tunnel connections.
2046 * @param peer Peer towards which the path is considered.
2047 * @param path Candidate path.
2049 * @return Cost of the path (path length + number of overlapping nodes)
2052 peer_get_path_cost (const struct MeshPeer *peer,
2053 const struct MeshPeerPath *path)
2055 struct MeshConnection *c;
2056 unsigned int overlap;
2064 GNUNET_assert (NULL != peer->tunnel);
2066 for (i = 0; i < path->length; i++)
2068 for (c = peer->tunnel->connection_head; NULL != c; c = c->next)
2070 for (j = 0; j < c->path->length; j++)
2072 if (path->peers[i] == c->path->peers[j])
2080 return (path->length + overlap) * (path->score * -1);
2085 * Choose the best path towards a peer considering the tunnel properties.
2087 * @param peer The destination peer.
2089 * @return Best current known path towards the peer, if any.
2091 static struct MeshPeerPath *
2092 peer_get_best_path (const struct MeshPeer *peer)
2094 struct MeshPeerPath *best_p;
2095 struct MeshPeerPath *p;
2096 struct MeshConnection *c;
2097 unsigned int best_cost;
2100 best_cost = UINT_MAX;
2102 for (p = peer->path_head; NULL != p; p = p->next)
2104 for (c = peer->tunnel->connection_head; NULL != c; c = c->next)
2108 continue; /* If path is in use in a connection, skip it. */
2110 if ((cost = peer_get_path_cost (peer, p)) < best_cost)
2120 queue_is_sendable (struct MeshPeerQueue *q)
2122 struct MeshFlowControl *fc;
2124 /* Is PID-independent? */
2127 case GNUNET_MESSAGE_TYPE_MESH_ACK:
2128 case GNUNET_MESSAGE_TYPE_MESH_POLL:
2132 /* Is PID allowed? */
2133 fc = q->fwd ? &q->c->fwd_fc : &q->c->bck_fc;
2134 if (GMC_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
2142 * Get first sendable message.
2144 * @param peer The destination peer.
2146 * @return Best current known path towards the peer, if any.
2148 static struct MeshPeerQueue *
2149 peer_get_first_message (const struct MeshPeer *peer)
2151 struct MeshPeerQueue *q;
2153 for (q = peer->queue_head; NULL != q; q = q->next)
2155 if (queue_is_sendable (q))
2164 * Try to establish a new connection to this peer in the given tunnel.
2165 * If the peer doesn't have any path to it yet, try to get one.
2166 * If the peer already has some path, send a CREATE CONNECTION towards it.
2168 * @param peer PeerInfo of the peer.
2171 peer_connect (struct MeshPeer *peer)
2173 struct MeshTunnel2 *t;
2174 struct MeshPeerPath *p;
2175 struct MeshConnection *c;
2177 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2178 "peer_connect towards %s\n",
2181 if (NULL != peer->path_head)
2183 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "path exists\n");
2184 p = peer_get_best_path (peer);
2187 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " %u hops\n", p->length);
2188 c = tunnel_use_path (t, p);
2189 send_connection_create (c);
2192 else if (NULL == peer->dhtget)
2194 const struct GNUNET_PeerIdentity *id;
2196 id = GNUNET_PEER_resolve2 (peer->id);
2197 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2198 " Starting DHT GET for peer %s\n", peer2s (peer));
2199 peer->dhtget = GNUNET_DHT_get_start (dht_handle, /* handle */
2200 GNUNET_BLOCK_TYPE_MESH_PEER, /* type */
2201 &id->hashPubKey, /* key to search */
2202 dht_replication_level, /* replication level */
2203 GNUNET_DHT_RO_RECORD_ROUTE |
2204 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
2206 0, /* xquery bits */
2207 &dht_get_id_handler, peer);
2208 if (MESH_TUNNEL_NEW == t->state)
2209 tunnel_change_state (t, MESH_TUNNEL_SEARCHING);
2213 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2214 "There is no path but the DHT GET is already started.\n");
2220 * Get the first transmittable message for a connection.
2222 * @param c Connection.
2223 * @param fwd Is this FWD?
2225 * @return First transmittable message.
2227 static struct MeshPeerQueue *
2228 connection_get_first_message (struct MeshConnection *c, int fwd)
2230 struct MeshPeerQueue *q;
2233 p = connection_get_hop (c, fwd);
2235 for (q = p->queue_head; NULL != q; q = q->next)
2239 if (queue_is_sendable (q))
2249 * @brief Re-initiate traffic on this connection if necessary.
2251 * Check if there is traffic queued towards this peer
2252 * and the core transmit handle is NULL (traffic was stalled).
2253 * If so, call core tmt rdy.
2255 * @param c Connection on which initiate traffic.
2256 * @param fwd Is this about fwd traffic?
2259 connection_unlock_queue (struct MeshConnection *c, int fwd)
2261 struct MeshPeer *peer;
2262 struct MeshPeerQueue *q;
2265 peer = connection_get_hop (c, fwd);
2267 if (NULL != peer->core_transmit)
2268 return; /* Already unlocked */
2270 q = connection_get_first_message (c, fwd);
2272 return; /* Nothing to transmit */
2275 peer->core_transmit =
2276 GNUNET_CORE_notify_transmit_ready (core_handle,
2279 GNUNET_TIME_UNIT_FOREVER_REL,
2280 GNUNET_PEER_resolve2 (peer->id),
2288 * Cancel all transmissions that belong to a certain connection.
2290 * @param c Connection which to cancel.
2291 * @param fwd Cancel fwd traffic?
2294 connection_cancel_queues (struct MeshConnection *c, int fwd)
2296 struct MeshPeerQueue *q;
2297 struct MeshPeerQueue *next;
2298 struct MeshFlowControl *fc;
2299 struct MeshPeer *peer;
2306 fc = fwd ? &c->fwd_fc : &c->bck_fc;
2307 peer = connection_get_hop (c, fwd);
2309 for (q = peer->queue_head; NULL != q; q = next)
2314 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2315 "connection_cancel_queue %s\n",
2316 GNUNET_MESH_DEBUG_M2S (q->type));
2317 queue_destroy (q, GNUNET_YES);
2320 if (NULL == peer->queue_head)
2322 if (NULL != peer->core_transmit)
2324 GNUNET_CORE_notify_transmit_ready_cancel (peer->core_transmit);
2325 peer->core_transmit = NULL;
2327 if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
2329 GNUNET_SCHEDULER_cancel (fc->poll_task);
2330 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2337 * Remove all paths that rely on a direct connection between p1 and p2
2338 * from the peer itself and notify all tunnels about it.
2340 * @param peer PeerInfo of affected peer.
2341 * @param p1 GNUNET_PEER_Id of one peer.
2342 * @param p2 GNUNET_PEER_Id of another peer that was connected to the first and
2345 * TODO: optimize (see below)
2348 peer_remove_path (struct MeshPeer *peer, GNUNET_PEER_Id p1,
2351 struct MeshPeerPath *p;
2352 struct MeshPeerPath *next;
2353 struct MeshPeer *peer_d;
2355 unsigned int destroyed;
2358 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path\n");
2360 for (p = peer->path_head; NULL != p; p = next)
2363 for (i = 0; i < (p->length - 1); i++)
2365 if ((p->peers[i] == p1 && p->peers[i + 1] == p2) ||
2366 (p->peers[i] == p2 && p->peers[i + 1] == p1))
2368 GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
2379 d = tunnel_notify_connection_broken (peer->tunnel, p1, p2);
2381 peer_d = peer_get_short (d); // FIXME
2382 next = peer_get_best_path (peer_d);
2383 tunnel_use_path (peer->tunnel, next);
2384 peer_connect (peer_d);
2386 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path END\n");
2391 * Add the path to the peer and update the path used to reach it in case this
2394 * @param peer_info Destination peer to add the path to.
2395 * @param path New path to add. Last peer must be the peer in arg 1.
2396 * Path will be either used of freed if already known.
2397 * @param trusted Do we trust that this path is real?
2400 peer_add_path (struct MeshPeer *peer_info, struct MeshPeerPath *path,
2403 struct MeshPeerPath *aux;
2407 if ((NULL == peer_info) || (NULL == path))
2410 path_destroy (path);
2413 if (path->peers[path->length - 1] != peer_info->id)
2416 path_destroy (path);
2419 if (2 >= path->length && GNUNET_NO == trusted)
2421 /* Only allow CORE to tell us about direct paths */
2422 path_destroy (path);
2425 for (l = 1; l < path->length; l++)
2427 if (path->peers[l] == myid)
2429 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shortening path by %u\n", l);
2430 for (l2 = 0; l2 < path->length - l; l2++)
2432 path->peers[l2] = path->peers[l + l2];
2437 GNUNET_realloc (path->peers, path->length * sizeof (GNUNET_PEER_Id));
2441 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "adding path [%u] to peer %s\n",
2442 path->length, peer2s (peer_info));
2444 l = path_get_length (path);
2447 path_destroy (path);
2451 GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
2452 for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
2454 l2 = path_get_length (aux);
2457 GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
2458 peer_info->path_tail, aux, path);
2463 if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
2465 path_destroy (path);
2470 GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head, peer_info->path_tail,
2477 * Add the path to the origin peer and update the path used to reach it in case
2478 * this is the shortest.
2479 * The path is given in peer_info -> destination, therefore we turn the path
2480 * upside down first.
2482 * @param peer_info Peer to add the path to, being the origin of the path.
2483 * @param path New path to add after being inversed.
2484 * Path will be either used or freed.
2485 * @param trusted Do we trust that this path is real?
2488 peer_add_path_to_origin (struct MeshPeer *peer_info,
2489 struct MeshPeerPath *path, int trusted)
2492 peer_add_path (peer_info, path, trusted);
2498 * Function called if a connection has been stalled for a while,
2499 * possibly due to a missed ACK. Poll the neighbor about its ACK status.
2501 * @param cls Closure (poll ctx).
2502 * @param tc TaskContext.
2505 connection_poll (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2507 struct MeshFlowControl *fc = cls;
2508 struct GNUNET_MESH_Poll msg;
2509 struct MeshConnection *c;
2511 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2512 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2518 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** Polling!\n");
2519 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** connection %s[%X]\n",
2520 peer2s (c->t->peer), c->id);
2522 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_POLL);
2523 msg.header.size = htons (sizeof (msg));
2524 msg.pid = htonl (fc->last_pid_sent);
2525 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** pid (%u)!\n", fc->last_pid_sent);
2526 send_prebuilt_message_connection (&msg.header, c, NULL, fc == &c->fwd_fc);
2527 fc->poll_time = GNUNET_TIME_STD_BACKOFF (fc->poll_time);
2528 fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
2529 &connection_poll, fc);
2534 * Build a PeerPath from the paths returned from the DHT, reversing the paths
2535 * to obtain a local peer -> destination path and interning the peer ids.
2537 * @return Newly allocated and created path
2539 static struct MeshPeerPath *
2540 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
2541 unsigned int get_path_length,
2542 const struct GNUNET_PeerIdentity *put_path,
2543 unsigned int put_path_length)
2545 struct MeshPeerPath *p;
2551 GNUNET_PEER_change_rc (myid, 1);
2552 i = get_path_length;
2553 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " GET has %d hops.\n", i);
2554 for (i--; i >= 0; i--)
2556 id = GNUNET_PEER_intern (&get_path[i]);
2557 if (p->length > 0 && id == p->peers[p->length - 1])
2559 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Optimizing 1 hop out.\n");
2560 GNUNET_PEER_change_rc (id, -1);
2564 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Adding from GET: %s.\n",
2565 GNUNET_i2s (&get_path[i]));
2567 p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2568 p->peers[p->length - 1] = id;
2571 i = put_path_length;
2572 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " PUT has %d hops.\n", i);
2573 for (i--; i >= 0; i--)
2575 id = GNUNET_PEER_intern (&put_path[i]);
2578 /* PUT path went through us, so discard the path up until now and start
2579 * from here to get a much shorter (and loop-free) path.
2584 if (p->length > 0 && id == p->peers[p->length - 1])
2586 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Optimizing 1 hop out.\n");
2587 GNUNET_PEER_change_rc (id, -1);
2591 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Adding from PUT: %s.\n",
2592 GNUNET_i2s (&put_path[i]));
2594 p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2595 p->peers[p->length - 1] = id;
2599 if (get_path_length > 0)
2600 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " (first of GET: %s)\n",
2601 GNUNET_i2s (&get_path[0]));
2602 if (put_path_length > 0)
2603 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " (first of PUT: %s)\n",
2604 GNUNET_i2s (&put_path[0]));
2605 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " In total: %d hops\n",
2607 for (i = 0; i < p->length; i++)
2609 struct GNUNET_PeerIdentity peer_id;
2611 GNUNET_PEER_resolve (p->peers[i], &peer_id);
2612 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " %u: %s\n", p->peers[i],
2613 GNUNET_i2s (&peer_id));
2621 * Adds a path to the peer_infos of all the peers in the path
2623 * @param p Path to process.
2624 * @param confirmed Whether we know if the path works or not.
2627 path_add_to_peers (struct MeshPeerPath *p, int confirmed)
2631 /* TODO: invert and add */
2632 for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
2633 for (i++; i < p->length; i++)
2635 struct MeshPeer *aux;
2636 struct MeshPeerPath *copy;
2638 aux = peer_get_short (p->peers[i]);
2639 copy = path_duplicate (p);
2640 copy->length = i + 1;
2641 peer_add_path (aux, copy, p->length < 3 ? GNUNET_NO : confirmed);
2647 * Search for a channel among the channels for a client
2649 * @param c the client whose channels to search in
2650 * @param chid the local id of the channel
2652 * @return channel handler, NULL if doesn't exist
2654 static struct MeshChannel *
2655 channel_get_by_local_id (struct MeshClient *c, MESH_ChannelNumber chid)
2657 if (0 == (chid & GNUNET_MESH_LOCAL_CHANNEL_ID_CLI))
2659 GNUNET_break_op (0);
2660 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CHID %X not a local chid\n", chid);
2663 if (chid >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV)
2664 return GNUNET_CONTAINER_multihashmap32_get (c->incoming_channels, chid);
2665 return GNUNET_CONTAINER_multihashmap32_get (c->own_channels, chid);
2669 * Search for a tunnel by global ID using full PeerIdentities.
2671 * @param t Tunnel containing the channel.
2672 * @param chid Public channel number.
2674 * @return channel handler, NULL if doesn't exist
2676 static struct MeshChannel *
2677 channel_get (struct MeshTunnel2 *t, MESH_ChannelNumber chid)
2679 struct MeshChannel *ch;
2684 for (ch = t->channel_head; NULL != ch; ch = ch->next)
2686 if (ch->gid == chid)
2695 * Change the tunnel state.
2697 * @param t Tunnel whose state to change.
2698 * @param state New state.
2701 tunnel_change_state (struct MeshTunnel2* t, enum MeshTunnelState state)
2703 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2704 "Tunnel %s state was %s\n",
2706 GNUNET_MESH_DEBUG_TS2S (t->state));
2707 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2708 "Tunnel %s state is now %s\n",
2710 GNUNET_MESH_DEBUG_TS2S (state));
2716 connection_change_state (struct MeshConnection* c,
2717 enum MeshConnectionState state)
2719 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2720 "Connection %s[%X] state was %s\n",
2721 peer2s (c->t->peer), c->id,
2722 GNUNET_MESH_DEBUG_CS2S (c->state));
2723 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2724 "Connection %s[%X] state is now %s\n",
2725 peer2s (c->t->peer), c->id,
2726 GNUNET_MESH_DEBUG_CS2S (state));
2732 * Add a client to a channel, initializing all needed data structures.
2734 * @param ch Channel to which add the client.
2735 * @param c Client which to add to the channel.
2738 channel_add_client (struct MeshChannel *ch, struct MeshClient *c)
2740 struct MeshTunnel2 *t = ch->t;
2742 if (NULL != ch->dest)
2748 /* Assign local id as destination */
2749 while (NULL != channel_get_by_local_id (c, t->next_local_chid))
2750 t->next_local_chid = (t->next_local_chid + 1) | GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
2751 ch->lid_dest = t->next_local_chid++;
2752 t->next_local_chid = t->next_local_chid | GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
2754 /* Store in client's hashmap */
2756 GNUNET_CONTAINER_multihashmap32_put (c->incoming_channels,
2758 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2767 static struct MeshConnection *
2768 tunnel_use_path (struct MeshTunnel2 *t, struct MeshPeerPath *p)
2770 struct MeshConnection *c;
2771 unsigned int own_pos;
2773 c = GNUNET_new (struct MeshConnection);
2774 for (own_pos = 0; own_pos < p->length; own_pos++)
2776 if (p->peers[own_pos] == myid)
2779 if (own_pos > p->length - 1)
2784 c->own_pos = own_pos;
2786 c->id = t->next_cid++;
2788 GNUNET_CONTAINER_DLL_insert_tail (t->connection_head, t->connection_tail, c);
2792 c->fwd_maintenance_task =
2793 GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
2794 &connection_fwd_keepalive, c);
2801 * Notifies a tunnel that a connection has broken that affects at least
2802 * some of its peers. Sends a notification towards the root of the tree.
2803 * In case the peer is the owner of the tree, notifies the client that owns
2804 * the tunnel and tries to reconnect.
2806 * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
2808 * @param t Tunnel affected.
2809 * @param p1 Peer that got disconnected from p2.
2810 * @param p2 Peer that got disconnected from p1.
2812 * @return Short ID of the peer disconnected (either p1 or p2).
2813 * 0 if the tunnel remained unaffected.
2815 static GNUNET_PEER_Id
2816 tunnel_notify_connection_broken (struct MeshTunnel2* t,
2817 GNUNET_PEER_Id p1, GNUNET_PEER_Id p2)
2819 // if (myid != p1 && myid != p2) FIXME
2824 // if (tree_get_predecessor (t->tree) != 0)
2826 // /* We are the peer still connected, notify owner of the disconnection. */
2827 // struct GNUNET_MESH_PathBroken msg;
2828 // struct GNUNET_PeerIdentity neighbor;
2830 // msg.header.size = htons (sizeof (msg));
2831 // msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN);
2832 // GNUNET_PEER_resolve (t->id.oid, &msg.oid);
2833 // msg.tid = htonl (t->id.tid);
2834 // msg.peer1 = my_full_id;
2835 // GNUNET_PEER_resolve (pid, &msg.peer2);
2836 // GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &neighbor);
2837 // send_prebuilt_message (&msg.header, &neighbor, t);
2844 * Send an end-to-end FWD ACK message for the most recent in-sequence payload.
2846 * @param ch Channel this is about.
2847 * @param fwd Is for FWD traffic? (ACK dest->owner)
2850 channel_send_data_ack (struct MeshChannel *ch, int fwd)
2852 struct GNUNET_MESH_DataACK msg;
2853 struct MeshChannelReliability *rel;
2854 struct MeshReliableMessage *copy;
2859 if (GNUNET_NO == ch->reliable)
2864 rel = fwd ? ch->bck_rel : ch->fwd_rel;
2865 mid = fwd ? &ch->mid_recv_fwd : &ch->mid_recv_bck;
2866 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2867 "send_data_ack for %u\n",
2870 msg.header.type = htons (fwd ? GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK :
2871 GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK);
2872 msg.header.size = htons (sizeof (msg));
2873 msg.chid = htonl (ch->gid);
2874 msg.mid = htonl (*mid - 1);
2876 for (copy = rel->head_recv; NULL != copy; copy = copy->next)
2878 delta = copy->mid - *mid;
2881 mask = 0x1LL << delta;
2882 msg.futures |= mask;
2883 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2884 " setting bit for %u (delta %u) (%llX) -> %llX\n",
2885 copy->mid, delta, mask, msg.futures);
2887 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " final futures %llX\n", msg.futures);
2889 send_prebuilt_message_channel (&msg.header, ch, fwd);
2890 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_data_ack END\n");
2895 * Send an ACK informing the predecessor about the available buffer space.
2897 * Note that for fwd ack, the FWD mean forward *traffic* (root->dest),
2898 * the ACK itself goes "back" (dest->root).
2900 * @param c Connection on which to send the ACK.
2901 * @param fwd Is this FWD ACK? (Going dest->owner)
2904 connection_send_ack (struct MeshConnection *c, int fwd)
2906 struct MeshFlowControl *next_fc;
2907 struct MeshFlowControl *prev_fc;
2911 next_fc = fwd ? &c->fwd_fc : &c->bck_fc;
2912 prev_fc = fwd ? &c->bck_fc : &c->fwd_fc;
2914 /* Check if we need to transmit the ACK */
2915 if (prev_fc->last_ack_sent - prev_fc->last_pid_recv > 3)
2917 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer > 3\n");
2918 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2919 " last pid recv: %u, last ack sent: %u\n",
2920 prev_fc->last_pid_recv, prev_fc->last_ack_sent);
2924 /* Ok, ACK might be necessary, what PID to ACK? */
2925 delta = next_fc->queue_max - next_fc->queue_n;
2926 ack = prev_fc->last_pid_recv + delta;
2927 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", ack);
2928 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2929 " last pid %u, last ack %u, qmax %u, q %u\n",
2930 prev_fc->last_pid_recv, prev_fc->last_ack_sent,
2931 next_fc->queue_max, next_fc->queue_n);
2932 if (ack == prev_fc->last_ack_sent)
2934 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not needed\n");
2938 prev_fc->last_ack_sent = ack;
2939 send_ack (c, ack, fwd);
2944 * Send an ACK informing the client about available buffer space.
2946 * Note that although the name is fwd_ack, the FWD mean forward *traffic*,
2947 * the ACK itself goes "back" (towards root).
2949 * @param ch Channel on which to send the ACK, NULL if unknown.
2950 * @param fwd Is this FWD ACK? (Going dest->owner)
2953 // channel_send_ack (struct MeshChannel *ch, uint16_t type, int fwd)
2955 // struct MeshChannelReliability *rel;
2956 // struct MeshFlowControl *next_fc;
2957 // struct MeshFlowControl *prev_fc;
2958 // struct MeshClient *c;
2959 // struct MeshClient *o;
2960 // GNUNET_PEER_Id hop;
2961 // uint32_t delta_mid;
2965 // rel = fwd ? ch->fwd_rel : ch->bck_rel;
2966 // c = fwd ? ch->client : ch->owner;
2967 // o = fwd ? ch->owner : ch->client;
2968 // hop = fwd ? connection_get_prev_hop (cn) : connection_get_next_hop (cn);
2969 // next_fc = fwd ? &t->next_fc : &t->prev_fc;
2970 // prev_fc = fwd ? &t->prev_fc : &t->next_fc;
2974 // case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
2975 // case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
2976 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2977 // "ACK due to %s\n",
2978 // GNUNET_MESH_DEBUG_M2S (type));
2979 // if (GNUNET_YES == t->nobuffer && (GNUNET_NO == t->reliable || NULL == c))
2981 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, nobuffer\n");
2984 // if (GNUNET_YES == t->reliable && NULL != c)
2985 // tunnel_send_data_ack (t, fwd);
2987 // case GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK:
2988 // case GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK:
2989 // case GNUNET_MESSAGE_TYPE_MESH_ACK:
2990 // case GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK:
2992 // case GNUNET_MESSAGE_TYPE_MESH_POLL:
2993 // case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
2994 // t->force_ack = GNUNET_YES;
2997 // GNUNET_break (0);
3000 // /* Check if we need to transmit the ACK */
3002 // prev_fc->last_ack_sent - prev_fc->last_pid_recv > 3 &&
3003 // GNUNET_NO == t->force_ack)
3005 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer free\n");
3006 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3007 // " last pid recv: %u, last ack sent: %u\n",
3008 // prev_fc->last_pid_recv, prev_fc->last_ack_sent);
3012 // /* Ok, ACK might be necessary, what PID to ACK? */
3013 // delta = t->queue_max - next_fc->queue_n;
3014 // if (NULL != o && GNUNET_YES == t->reliable && NULL != rel->head_sent)
3015 // delta_mid = rel->mid_sent - rel->head_sent->mid;
3018 // if (0 > delta || (GNUNET_YES == t->reliable &&
3020 // (10 < rel->n_sent || 64 <= delta_mid)))
3022 // if (NULL != o && delta > 1)
3024 // ack = prev_fc->last_pid_recv + delta;
3025 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", ack);
3026 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3027 // " last pid %u, last ack %u, qmax %u, q %u\n",
3028 // prev_fc->last_pid_recv, prev_fc->last_ack_sent,
3029 // t->queue_max, next_fc->queue_n);
3030 // if (ack == prev_fc->last_ack_sent && GNUNET_NO == t->force_ack)
3032 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not needed\n");
3036 // prev_fc->last_ack_sent = ack;
3038 // send_local_ack (t, o, fwd);
3039 // else if (0 != hop)
3040 // send_ack (t, hop, ack);
3042 // GNUNET_break (GNUNET_YES == t->destroy);
3043 // t->force_ack = GNUNET_NO;
3048 * Modify the mesh message TID from global to local and send to client.
3050 * @param ch Channel on which to send the message.
3051 * @param msg Message to modify and send.
3052 * @param c Client to send to.
3053 * @param tid Tunnel ID to use (c can be both owner and client).
3056 channel_send_client_to_tid (struct MeshChannel *ch,
3057 const struct GNUNET_MESH_Data *msg,
3058 struct MeshClient *c, MESH_ChannelNumber id)
3060 struct GNUNET_MESH_LocalData *copy;
3061 uint16_t size = ntohs (msg->header.size) - sizeof (struct GNUNET_MESH_Data);
3062 char cbuf[size + sizeof (struct GNUNET_MESH_LocalData)];
3064 if (size < sizeof (struct GNUNET_MessageHeader))
3066 GNUNET_break_op (0);
3074 copy = (struct GNUNET_MESH_LocalData *) cbuf;
3075 memcpy (©[1], &msg[1], size);
3076 copy->header.size = htons (sizeof (struct GNUNET_MESH_LocalData) + size);
3077 copy->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA);
3078 copy->id = htonl (id);
3079 GNUNET_SERVER_notification_context_unicast (nc, c->handle,
3080 ©->header, GNUNET_NO);
3084 * Modify the data message ID from global to local and send to client.
3086 * @param ch Channel on which to send the message.
3087 * @param msg Message to modify and send.
3088 * @param fwd Forward?
3091 channel_send_client_data (struct MeshChannel *ch,
3092 const struct GNUNET_MESH_Data *msg,
3096 channel_send_client_to_tid (ch, msg, ch->dest, ch->lid_dest);
3098 channel_send_client_to_tid (ch, msg, ch->root, ch->lid_root);
3103 * Send a buffered message to the client, for in order delivery or
3104 * as result of client ACK.
3106 * @param ch Channel on which to empty the message buffer.
3107 * @param c Client to send to.
3108 * @param rel Reliability structure to corresponding peer.
3109 * If rel == bck_rel, this is FWD data.
3112 channel_send_client_buffered_data (struct MeshChannel *ch,
3113 struct MeshClient *c,
3114 struct MeshChannelReliability *rel)
3116 struct MeshReliableMessage *copy;
3119 if (GNUNET_NO == rel->client_ready)
3121 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client not ready\n");
3125 mid = rel == ch->bck_rel ? &ch->mid_recv_fwd : &ch->mid_recv_bck;
3127 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data\n");
3128 copy = rel->head_recv;
3131 if (copy->mid == *mid || GNUNET_NO == ch->reliable)
3133 struct GNUNET_MESH_Data *msg = (struct GNUNET_MESH_Data *) ©[1];
3135 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3136 " have %u! now expecting %u\n",
3137 copy->mid, *mid + 1);
3138 channel_send_client_data (ch, msg, (rel == ch->bck_rel));
3141 GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
3146 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3147 " reliable && don't have %u, next is %u\n",
3153 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data END\n");
3158 * We have received a message out of order, or the client is not ready.
3159 * Buffer it until we receive an ACK from the client or the missing
3160 * message from the channel.
3162 * @param msg Message to buffer.
3163 * @param rel Reliability data to the corresponding direction.
3166 channel_rel_add_buffered_data (const struct GNUNET_MESH_Data *msg,
3167 struct MeshChannelReliability *rel)
3169 struct MeshReliableMessage *copy;
3170 struct MeshReliableMessage *prev;
3174 size = ntohs (msg->header.size);
3175 mid = ntohl (msg->mid);
3176 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data %u\n", mid);
3178 copy = GNUNET_malloc (sizeof (*copy) + size);
3181 memcpy (©[1], msg, size);
3185 // FIXME do something better than O(n), although n < 64...
3186 // FIXME start from the end (most messages are the latest ones)
3187 for (prev = rel->head_recv; NULL != prev; prev = prev->next)
3189 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " prev %u\n", prev->mid);
3190 if (GMC_is_pid_bigger (prev->mid, mid))
3192 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " bingo!\n");
3193 GNUNET_CONTAINER_DLL_insert_before (rel->head_recv, rel->tail_recv,
3198 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " insert at tail!\n");
3199 GNUNET_CONTAINER_DLL_insert_tail (rel->head_recv, rel->tail_recv, copy);
3200 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data END\n");
3205 * Destroy a reliable message after it has been acknowledged, either by
3206 * direct mid ACK or bitfield. Updates the appropriate data structures and
3207 * timers and frees all memory.
3209 * @param copy Message that is no longer needed: remote peer got it.
3212 rel_message_free (struct MeshReliableMessage *copy)
3214 struct MeshChannelReliability *rel;
3215 struct GNUNET_TIME_Relative time;
3218 time = GNUNET_TIME_absolute_get_duration (copy->timestamp);
3219 rel->expected_delay.rel_value_us *= 7;
3220 rel->expected_delay.rel_value_us += time.rel_value_us;
3221 rel->expected_delay.rel_value_us /= 8;
3223 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Freeing %u\n", copy->mid);
3224 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " n_sent %u\n", rel->n_sent);
3225 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! took %s\n",
3226 GNUNET_STRINGS_relative_time_to_string (time, GNUNET_NO));
3227 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! new expected delay %s\n",
3228 GNUNET_STRINGS_relative_time_to_string (rel->expected_delay,
3230 rel->retry_timer = rel->expected_delay;
3231 GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
3237 * Destroy all reliable messages queued for a channel,
3238 * during a channel destruction.
3239 * Frees the reliability structure itself.
3241 * @param rel Reliability data for a channel.
3244 channel_rel_free_all (struct MeshChannelReliability *rel)
3246 struct MeshReliableMessage *copy;
3247 struct MeshReliableMessage *next;
3252 for (copy = rel->head_recv; NULL != copy; copy = next)
3255 GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
3258 for (copy = rel->head_sent; NULL != copy; copy = next)
3261 GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
3264 if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
3265 GNUNET_SCHEDULER_cancel (rel->retry_task);
3271 * Mark future messages as ACK'd.
3273 * @param rel Reliability data.
3274 * @param msg DataACK message with a bitfield of future ACK'd messages.
3277 channel_rel_free_sent (struct MeshChannelReliability *rel,
3278 const struct GNUNET_MESH_DataACK *msg)
3280 struct MeshReliableMessage *copy;
3281 struct MeshReliableMessage *next;
3288 bitfield = msg->futures;
3289 mid = ntohl (msg->mid);
3290 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3291 "free_sent_reliable %u %llX\n",
3293 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3294 " rel %p, head %p\n",
3295 rel, rel->head_sent);
3296 for (i = 0, copy = rel->head_sent;
3297 i < 64 && NULL != copy && 0 != bitfield;
3300 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3301 " trying bit %u (mid %u)\n",
3304 if (0 == (bitfield & mask))
3307 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " set!\n");
3308 /* Bit was set, clear the bit from the bitfield */
3311 /* The i-th bit was set. Do we have that copy? */
3312 /* Skip copies with mid < target */
3313 target = mid + i + 1;
3314 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " target %u\n", target);
3315 while (NULL != copy && GMC_is_pid_bigger (target, copy->mid))
3318 /* Did we run out of copies? (previously freed, it's ok) */
3321 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "run out of copies...\n");
3325 /* Did we overshoot the target? (previously freed, it's ok) */
3326 if (GMC_is_pid_bigger (copy->mid, target))
3328 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " next copy %u\n", copy->mid);
3332 /* Now copy->mid == target, free it */
3334 rel_message_free (copy);
3337 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "free_sent_reliable END\n");
3342 * We haven't received an ACK after a certain time: restransmit the message.
3344 * @param cls Closure (MeshReliableMessage with the message to restransmit)
3345 * @param tc TaskContext.
3348 channel_retransmit_message (void *cls,
3349 const struct GNUNET_SCHEDULER_TaskContext *tc)
3351 struct MeshChannelReliability *rel = cls;
3352 struct MeshReliableMessage *copy;
3353 struct MeshPeerQueue *q;
3354 struct MeshChannel *ch;
3355 struct MeshConnection *c;
3356 struct GNUNET_MESH_Data *payload;
3357 struct MeshPeer *hop;
3360 rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
3361 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3365 copy = rel->head_sent;
3372 /* Search the message to be retransmitted in the outgoing queue.
3373 * Check only the queue for the connection that is going to be used,
3374 * if the message is stuck in some other connection's queue we shouldn't
3376 * - cancelling it and sending the new one doesn't guarantee it's delivery,
3377 * the old connection could be temporary stalled or the queue happened to
3378 * be long at time of insertion.
3379 * - not sending the new one could cause terrible delays the old connection
3382 payload = (struct GNUNET_MESH_Data *) ©[1];
3383 fwd = (rel == ch->fwd_rel);
3384 c = tunnel_get_connection (ch->t, fwd);
3385 hop = connection_get_hop (c, fwd);
3386 for (q = hop->queue_head; NULL != q; q = q->next)
3388 if (ntohs (payload->header.type) == q->type && ch == q->ch)
3390 struct GNUNET_MESH_Data *queued_data = q->cls;
3392 if (queued_data->mid == payload->mid)
3397 /* Message not found in the queue that we are going to use. */
3400 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! RETRANSMIT %u\n", copy->mid);
3402 send_prebuilt_message_channel (&payload->header, ch, ch->fwd_rel == rel);
3403 GNUNET_STATISTICS_update (stats, "# data retransmitted", 1, GNUNET_NO);
3407 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! ALREADY IN QUEUE %u\n", copy->mid);
3410 rel->retry_timer = GNUNET_TIME_STD_BACKOFF (rel->retry_timer);
3411 rel->retry_task = GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
3412 &channel_retransmit_message,
3419 * Send ACK on one or more connections due to buffer space to the client.
3422 channel_send_ack (struct MeshChannel *ch, uint32_t buffer, int fwd)
3424 struct MeshTunnel2 *t = ch->t;
3425 struct MeshConnection *c;
3426 struct MeshFlowControl *fc;
3431 /* Count connections, how many messages are already allowed */
3432 for (cs = 0, allowed = 0, c = t->connection_head; NULL != c; c = c->next)
3434 fc = fwd ? &c->fwd_fc : &c->bck_fc;
3435 if (GMC_is_pid_bigger(fc->last_pid_recv, fc->last_ack_sent))
3440 allowed += fc->last_ack_sent - fc->last_pid_recv;
3444 /* Make sure there is no overflow */
3445 if (allowed > buffer)
3451 /* Authorize connections to send more data */
3452 to_allow = buffer - allowed;
3453 for (c = t->connection_head; NULL != c && to_allow > 0; c = c->next)
3455 fc = fwd ? &c->fwd_fc : &c->bck_fc;
3456 if (fc->last_ack_sent - fc->last_pid_recv > 64 / 3)
3460 send_ack (c, fc->last_ack_sent + 1, fwd);
3464 GNUNET_break (to_allow == 0);
3469 * Send keepalive packets for a connection.
3471 * @param c Connection to keep alive..
3472 * @param fwd Is this a FWD keepalive? (owner -> dest).
3475 connection_keepalive (struct MeshConnection *c, int fwd)
3477 struct GNUNET_MESH_ConnectionKeepAlive *msg;
3478 size_t size = sizeof (struct GNUNET_MESH_ConnectionKeepAlive);
3482 type = fwd ? GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE :
3483 GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE;
3485 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3486 "sending %s keepalive for connection %s[%d]\n",
3487 fwd ? "FWD" : "BCK",
3488 peer2s (c->t->peer),
3491 msg = (struct GNUNET_MESH_ConnectionKeepAlive *) cbuf;
3492 msg->header.size = htons (size);
3493 msg->header.type = htons (type);
3494 msg->cid = htonl (c->id);
3495 msg->tid = c->t->id;
3497 send_prebuilt_message_connection (&msg->header, c, NULL, fwd);
3502 * Send CONNECTION_{CREATE/ACK} packets for a connection.
3504 * @param c Connection for which to send the message.
3505 * @param fwd If GNUNET_YES, send CREATE, otherwise send ACK.
3508 connection_recreate (struct MeshConnection *c, int fwd)
3510 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "sending connection recreate\n");
3512 send_connection_create (c);
3514 send_connection_ack (c);
3519 * Generic connection timer management.
3520 * Depending on the role of the peer in the connection will send the
3521 * appropriate message (build or keepalive)
3523 * @param c Conncetion to maintain.
3524 * @param fwd Is FWD?
3527 connection_maintain (struct MeshConnection *c, int fwd)
3529 if (MESH_TUNNEL_SEARCHING == c->t->state)
3531 /* TODO DHT GET with RO_BART */
3536 case MESH_CONNECTION_NEW:
3538 case MESH_CONNECTION_SENT:
3539 connection_recreate (c, fwd);
3541 case MESH_CONNECTION_READY:
3542 connection_keepalive (c, fwd);
3551 connection_fwd_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3553 struct MeshConnection *c = cls;
3555 c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
3556 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3559 connection_maintain (c, GNUNET_YES);
3560 c->fwd_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
3561 &connection_fwd_keepalive,
3567 connection_bck_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3569 struct MeshConnection *c = cls;
3571 c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
3572 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3575 connection_maintain (c, GNUNET_NO);
3576 c->bck_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
3577 &connection_bck_keepalive,
3583 * Send a message to all peers in this connection that the connection
3584 * is no longer valid.
3586 * If some peer should not receive the message, it should be zero'ed out
3587 * before calling this function.
3589 * @param c The connection whose peers to notify.
3592 connection_send_destroy (struct MeshConnection *c)
3594 struct GNUNET_MESH_ConnectionDestroy msg;
3596 msg.header.size = htons (sizeof (msg));
3597 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);;
3598 msg.cid = htonl (c->id);
3600 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3601 " sending tunnel destroy for connection %s[%X]\n",
3602 peer2s (c->t->peer),
3605 send_prebuilt_message_connection (&msg.header, c, NULL, GNUNET_YES);
3606 send_prebuilt_message_connection (&msg.header, c, NULL, GNUNET_NO);
3607 c->destroy = GNUNET_YES;
3612 * Send a message to all clients (local and remote) of this channel
3613 * notifying that the channel is no longer valid.
3615 * If some peer or client should not receive the message,
3616 * should be zero'ed out before calling this function.
3618 * @param ch The channel whose clients to notify.
3621 channel_send_destroy (struct MeshChannel *ch)
3623 struct GNUNET_MESH_ChannelDestroy msg;
3625 msg.header.size = htons (sizeof (msg));
3626 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY);
3627 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3628 " sending tunnel destroy for channel %s:%X\n",
3629 peer2s (ch->t->peer),
3632 if (NULL != ch->root)
3634 msg.chid = htonl (ch->lid_root);
3635 send_local_channel_destroy (ch, GNUNET_NO);
3639 msg.chid = htonl (ch->gid);
3640 send_prebuilt_message_channel (&msg.header, ch, GNUNET_NO);
3643 if (NULL != ch->dest)
3645 msg.chid = htonl (ch->lid_dest);
3646 send_local_channel_destroy (ch, GNUNET_YES);
3650 msg.chid = htonl (ch->gid);
3651 send_prebuilt_message_channel (&msg.header, ch, GNUNET_YES);
3659 * @param tid Tunnel ID.
3661 static struct MeshTunnel2 *
3662 tunnel_new (const struct GNUNET_HashCode *tid)
3664 struct MeshTunnel2 *t;
3666 t = GNUNET_new (struct MeshTunnel2);
3668 t->next_chid = GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
3670 GNUNET_CONTAINER_multihashmap_put (tunnels, tid, t,
3671 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3685 * @param tid Tunnel ID.
3687 static struct MeshTunnel2 *
3688 tunnel_get (const struct GNUNET_HashCode *tid)
3690 return GNUNET_CONTAINER_multihashmap_get (tunnels, tid);
3695 * Add a connection to a tunnel.
3698 * @param c Connection.
3701 tunnel_add_connection (struct MeshTunnel2 *t, struct MeshConnection *c)
3704 GNUNET_CONTAINER_DLL_insert_tail (t->connection_head, t->connection_tail, c);
3709 * Initialize a Flow Control structure to the initial state.
3711 * @param fc Flow Control structure to initialize.
3714 fc_init (struct MeshFlowControl *fc)
3716 fc->last_pid_sent = (uint32_t) -1; /* Next (expected) = 0 */
3717 fc->last_pid_recv = (uint32_t) -1;
3718 fc->last_ack_sent = (uint32_t) -1; /* No traffic allowed yet */
3719 fc->last_ack_recv = (uint32_t) -1;
3720 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
3721 fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
3727 * Create a connection.
3729 * @param tid Tunnel ID.
3730 * @param cid Connection ID.
3732 static struct MeshConnection *
3733 connection_new (struct GNUNET_HashCode *tid, uint32_t cid)
3735 struct MeshConnection *c;
3736 struct MeshTunnel2 *t;
3738 t = tunnel_get (tid);
3741 t = tunnel_new (tid);
3749 c = GNUNET_new (struct MeshConnection);
3751 fc_init (&c->fwd_fc);
3752 fc_init (&c->bck_fc);
3753 tunnel_add_connection (t, c);
3760 * Find a connection.
3762 * @param tid Tunnel ID.
3763 * @param cid Connection ID.
3765 static struct MeshConnection *
3766 connection_get (const struct GNUNET_HashCode *tid, uint32_t cid)
3768 struct MeshConnection *c;
3769 struct MeshTunnel2 *t;
3771 t = tunnel_get (tid);
3772 for (c = t->connection_head; NULL != c; c = c->next)
3781 * Connection is no longer needed: destroy it and remove from tunnel.
3783 * @param c Connection to destroy.
3786 connection_destroy (struct MeshConnection *c)
3791 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying connection %s[%X]\n",
3792 peer2s (c->t->peer),
3795 connection_cancel_queues (c, GNUNET_YES);
3796 connection_cancel_queues (c, GNUNET_NO);
3798 if (GNUNET_SCHEDULER_NO_TASK != c->fwd_maintenance_task)
3799 GNUNET_SCHEDULER_cancel (c->fwd_maintenance_task);
3800 if (GNUNET_SCHEDULER_NO_TASK != c->bck_maintenance_task)
3801 GNUNET_SCHEDULER_cancel (c->bck_maintenance_task);
3803 GNUNET_CONTAINER_DLL_remove (c->t->connection_head, c->t->connection_tail, c);
3805 GNUNET_STATISTICS_update (stats, "# connections", -1, GNUNET_NO);
3811 tunnel_destroy (struct MeshTunnel2 *t)
3813 struct MeshConnection *c;
3814 struct MeshConnection *next;
3819 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n",
3822 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &t->id, t))
3825 for (c = t->connection_head; NULL != c; c = next)
3828 connection_destroy (c);
3831 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
3838 * Tunnel is empty: destroy it.
3840 * Notifies all connections about the destruction.
3842 * @param t Tunnel to destroy.
3845 tunnel_destroy_empty (struct MeshTunnel2 *t)
3847 struct MeshConnection *c;
3849 for (c = t->connection_head; NULL != c; c = c->next)
3851 if (GNUNET_NO == c->destroy)
3852 connection_send_destroy (c);
3855 if (0 == t->pending_messages)
3858 t->destroy = GNUNET_YES;
3863 * Destroy tunnel if empty (no more channels).
3865 * @param t Tunnel to destroy if empty.
3868 tunnel_destroy_if_empty (struct MeshTunnel2 *t)
3870 if (NULL != t->channel_head)
3873 tunnel_destroy_empty (t);
3878 * Destroy a channel and free all resources.
3880 * @param ch Channel to destroy.
3883 channel_destroy (struct MeshChannel *ch)
3885 struct MeshClient *c;
3893 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap32_remove (c->own_channels,
3904 GNUNET_CONTAINER_multihashmap32_remove (c->incoming_channels,
3911 if (GNUNET_YES == ch->reliable)
3913 channel_rel_free_all (ch->fwd_rel);
3914 channel_rel_free_all (ch->bck_rel);
3917 GNUNET_CONTAINER_DLL_remove (ch->t->channel_head, ch->t->channel_tail, ch);
3918 GNUNET_STATISTICS_update (stats, "# channels", -1, GNUNET_NO);
3924 * Create a new channel.
3926 * @param t Tunnel this channel is in.
3927 * @param owner Client that owns the channel, NULL for foreign channels.
3928 * @param lid_root Local ID for root client.
3930 * @return A new initialized channel. NULL on error.
3932 static struct MeshChannel *
3933 channel_new (struct MeshTunnel2 *t,
3934 struct MeshClient *owner, MESH_ChannelNumber lid_root)
3936 struct MeshChannel *ch;
3938 ch = GNUNET_new (struct MeshChannel);
3940 ch->lid_root = lid_root;
3943 GNUNET_STATISTICS_update (stats, "# channels", 1, GNUNET_NO);
3947 while (NULL != channel_get_by_local_id (owner, t->next_chid))
3948 t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
3949 ch->gid = t->next_chid;
3950 t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
3953 GNUNET_CONTAINER_multihashmap32_put (owner->own_channels, lid_root, ch,
3954 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
3957 channel_destroy (ch);
3958 GNUNET_SERVER_receive_done (owner->handle, GNUNET_SYSERR);
3968 * Set options in a channel, extracted from a bit flag field
3970 * @param ch Channel to set options to.
3971 * @param options Bit array in host byte order.
3974 channel_set_options (struct MeshChannel *ch, uint32_t options)
3976 ch->nobuffer = (options & GNUNET_MESH_OPTION_NOBUFFER) != 0 ?
3977 GNUNET_YES : GNUNET_NO;
3978 ch->reliable = (options & GNUNET_MESH_OPTION_RELIABLE) != 0 ?
3979 GNUNET_YES : GNUNET_NO;
3984 * Iterator for deleting each channel whose client endpoint disconnected.
3986 * @param cls Closure (client that has disconnected).
3987 * @param key The local channel id (used to access the hashmap).
3988 * @param value The value stored at the key (channel to destroy).
3990 * @return GNUNET_OK, keep iterating.
3993 channel_destroy_iterator (void *cls,
3997 struct MeshChannel *ch = value;
3998 struct MeshClient *c = cls;
3999 struct MeshTunnel2 *t;
4001 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4002 " Channel %X (%X / %X) destroy, due to client %u shutdown.\n",
4003 ch->gid, ch->lid_root, ch->lid_dest, c->id);
4007 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is destination.\n", c->id);
4012 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is owner.\n", c->id);
4017 channel_send_destroy (ch);
4018 channel_destroy (ch);
4019 tunnel_destroy_if_empty (t);
4026 * Remove client's ports from the global hashmap on disconnect.
4028 * @param cls Closure (unused).
4030 * @param value Client structure.
4032 * @return GNUNET_OK, keep iterating.
4035 client_release_ports (void *cls,
4041 res = GNUNET_CONTAINER_multihashmap32_remove (ports, key, value);
4042 if (GNUNET_YES != res)
4045 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4046 "Port %u by client %p was not registered.\n",
4054 * Timeout function due to lack of keepalive/traffic from the owner.
4055 * Destroys connection if called.
4057 * @param cls Closure (connection to destroy).
4058 * @param tc TaskContext.
4061 connection_fwd_timeout (void *cls,
4062 const struct GNUNET_SCHEDULER_TaskContext *tc)
4064 struct MeshConnection *c = cls;
4066 c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4067 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4069 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4070 "Connection %s[%X] FWD timed out. Destroying.\n",
4071 peer2s (c->t->peer),
4074 if (NULL != c->t->channel_head) /* If local, leave TODO review */
4077 connection_destroy (c);
4082 * Timeout function due to lack of keepalive/traffic from the destination.
4083 * Destroys connection if called.
4085 * @param cls Closure (connection to destroy).
4086 * @param tc TaskContext
4089 connection_bck_timeout (void *cls,
4090 const struct GNUNET_SCHEDULER_TaskContext *tc)
4092 struct MeshConnection *c = cls;
4094 c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4095 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4098 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4099 "Connection %s[%X] FWD timed out. Destroying.\n",
4100 peer2s (c->t->peer),
4103 if (NULL != c->t->channel_head) /* If local, leave TODO review */
4106 connection_destroy (c);
4111 * Resets the connection timeout task, some other message has done the
4113 * - For the first peer on the direction this means to send
4114 * a keepalive or a path confirmation message (either create or ACK).
4115 * - For all other peers, this means to destroy the connection,
4116 * due to lack of activity.
4117 * Starts the tiemout if no timeout was running (connection just created).
4119 * @param c Connection whose timeout to reset.
4120 * @param fwd Is this forward?
4122 * TODO use heap to improve efficiency of scheduler.
4125 connection_reset_timeout (struct MeshConnection *c, int fwd)
4127 GNUNET_SCHEDULER_TaskIdentifier *ti;
4128 GNUNET_SCHEDULER_Task f;
4130 ti = fwd ? &c->fwd_maintenance_task : &c->bck_maintenance_task;
4132 if (GNUNET_SCHEDULER_NO_TASK != *ti)
4133 GNUNET_SCHEDULER_cancel (*ti);
4135 if (NULL != c->t->channel_head) /* Endpoint */
4137 f = fwd ? &connection_fwd_keepalive : &connection_bck_keepalive;
4138 *ti = GNUNET_SCHEDULER_add_delayed (refresh_connection_time, f, c);
4142 struct GNUNET_TIME_Relative delay;
4144 delay = GNUNET_TIME_relative_multiply (refresh_connection_time, 4);
4145 f = fwd ? &connection_fwd_timeout : &connection_bck_timeout;
4146 *ti = GNUNET_SCHEDULER_add_delayed (delay, f, c);
4152 * Iterator to notify all connections of a broken link. Mark connections
4153 * to destroy after all traffic has been sent.
4155 * @param cls Closure (peer disconnected).
4156 * @param key Current key code (tid).
4157 * @param value Value in the hash map (connection).
4159 * @return GNUNET_YES if we should continue to iterate,
4163 connection_broken (void *cls,
4164 const struct GNUNET_HashCode *key,
4167 struct MeshPeer *peer = cls;
4168 struct MeshConnection *c = value;
4169 struct GNUNET_MESH_ConnectionBroken msg;
4172 fwd = peer == connection_get_prev_hop (c);
4173 connection_cancel_queues (c, !fwd);
4175 msg.header.size = htons (sizeof (struct GNUNET_MESH_ConnectionBroken));
4176 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN);
4177 msg.cid = htonl (c->id);
4179 msg.peer1 = my_full_id;
4180 msg.peer2 = *GNUNET_PEER_resolve2 (peer->id);
4181 send_prebuilt_message_connection (&msg.header, c, NULL, fwd);
4182 c->destroy = GNUNET_YES;
4187 /******************************************************************************/
4188 /**************** MESH NETWORK HANDLER HELPERS ***********************/
4189 /******************************************************************************/
4192 * Free a transmission that was already queued with all resources
4193 * associated to the request.
4195 * @param queue Queue handler to cancel.
4196 * @param clear_cls Is it necessary to free associated cls?
4199 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
4201 struct MeshPeer *peer;
4202 struct MeshFlowControl *fc;
4207 fc = fwd ? &queue->c->fwd_fc : &queue->c->bck_fc;
4209 if (GNUNET_YES == clear_cls)
4211 switch (queue->type)
4213 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
4214 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "destroying CONNECTION_DESTROY\n");
4215 GNUNET_break (GNUNET_YES == queue->c->destroy);
4217 case GNUNET_MESSAGE_TYPE_MESH_FWD:
4218 case GNUNET_MESSAGE_TYPE_MESH_BCK:
4219 case GNUNET_MESSAGE_TYPE_MESH_ACK:
4220 case GNUNET_MESSAGE_TYPE_MESH_POLL:
4221 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
4222 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " prebuilt message\n");
4223 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type %s\n",
4224 GNUNET_MESH_DEBUG_M2S (queue->type));
4227 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
4228 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type create path\n");
4233 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, " type %s unknown!\n",
4234 GNUNET_MESH_DEBUG_M2S (queue->type));
4236 GNUNET_free_non_null (queue->cls);
4238 GNUNET_CONTAINER_DLL_remove (peer->queue_head, peer->queue_tail, queue);
4242 if (NULL != queue->c)
4244 queue->c->pending_messages--;
4245 if (NULL != queue->c->t)
4247 queue->c->t->pending_messages--;
4251 GNUNET_free (queue);
4256 queue_send (void *cls, size_t size, void *buf)
4258 struct MeshPeer *peer = cls;
4259 struct MeshFlowControl *fc;
4260 struct MeshConnection *c;
4261 struct GNUNET_MessageHeader *msg;
4262 struct MeshPeerQueue *queue;
4263 struct MeshTunnel2 *t;
4264 const struct GNUNET_PeerIdentity *dst_id;
4270 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Queue send\n");
4272 if (NULL == buf || 0 == size)
4274 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Buffer size 0.\n");
4279 queue = peer_get_first_message (peer);
4282 GNUNET_break (0); /* Core tmt_rdy should've been canceled */
4285 queue->peer->core_transmit = NULL;
4288 fc = fwd ? &c->fwd_fc : &c->bck_fc;
4291 dst_id = GNUNET_PEER_resolve2 (peer->id);
4292 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* towards %s\n", GNUNET_i2s (dst_id));
4293 /* Check if buffer size is enough for the message */
4294 if (queue->size > size)
4296 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* not enough room, reissue\n");
4297 peer->core_transmit =
4298 GNUNET_CORE_notify_transmit_ready (core_handle,
4301 GNUNET_TIME_UNIT_FOREVER_REL,
4308 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* size ok\n");
4310 t = (NULL != c) ? c->t : NULL;
4314 switch (queue->type)
4316 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
4317 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
4318 case GNUNET_MESSAGE_TYPE_MESH_FWD:
4319 case GNUNET_MESSAGE_TYPE_MESH_BCK:
4320 case GNUNET_MESSAGE_TYPE_MESH_ACK:
4321 case GNUNET_MESSAGE_TYPE_MESH_POLL:
4322 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4324 GNUNET_MESH_DEBUG_M2S (queue->type));
4326 case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4327 case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4328 data_size = send_core_data_raw (queue->cls, size, buf);
4329 msg = (struct GNUNET_MessageHeader *) buf;
4330 type = ntohs (msg->type);
4332 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
4333 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* path create\n");
4334 if (NULL != c->t->channel_head)
4335 data_size = send_core_connection_create (queue->cls, size, buf);
4337 data_size = send_core_data_raw (queue->cls, size, buf);
4339 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
4340 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* path ack\n");
4341 if (NULL != c->t->channel_head)
4342 data_size = send_core_connection_ack (queue->cls, size, buf);
4344 data_size = send_core_data_raw (queue->cls, size, buf);
4348 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "* type unknown: %u\n",
4353 if (0 < drop_percent &&
4354 GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 101) < drop_percent)
4356 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4357 "Dropping message of type %s\n",
4358 GNUNET_MESH_DEBUG_M2S (queue->type));
4361 /* Free queue, but cls was freed by send_core_* */
4362 queue_destroy (queue, GNUNET_NO);
4364 /* Send ACK if needed, after accounting for sent ID in fc->queue_n */
4367 case GNUNET_MESSAGE_TYPE_MESH_FWD:
4368 case GNUNET_MESSAGE_TYPE_MESH_BCK:
4369 pid = ntohl ( ((struct GNUNET_MESH_Encrypted *) buf)->pid );
4370 fc->last_pid_sent = pid;
4371 connection_send_ack (c, fwd);
4377 /* If more data in queue, send next */
4378 queue = peer_get_first_message (peer);
4381 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* more data!\n");
4382 if (NULL == peer->core_transmit) {
4383 peer->core_transmit =
4384 GNUNET_CORE_notify_transmit_ready(core_handle,
4387 GNUNET_TIME_UNIT_FOREVER_REL,
4395 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4396 "* tmt rdy called somewhere else\n");
4398 if (GNUNET_SCHEDULER_NO_TASK == fc->poll_task)
4400 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "* %s starting poll timeout\n");
4402 GNUNET_SCHEDULER_add_delayed (fc->poll_time, &connection_poll, fc);
4407 if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
4409 GNUNET_SCHEDULER_cancel (fc->poll_task);
4410 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
4415 c->pending_messages--;
4416 if (GNUNET_YES == c->destroy && 0 == c->pending_messages)
4418 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* destroying connection!\n");
4419 connection_destroy (c);
4425 t->pending_messages--;
4426 if (GNUNET_YES == t->destroy && 0 == t->pending_messages)
4428 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* destroying tunnel!\n");
4432 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Return %d\n", data_size);
4438 queue_add (void *cls, uint16_t type, size_t size,
4439 struct MeshPeer *dst,
4440 struct MeshConnection *c,
4441 struct MeshChannel *ch)
4443 struct MeshPeerQueue *queue;
4444 struct MeshFlowControl *fc;
4448 fwd = (dst == connection_get_next_hop (c));
4449 fc = fwd ? &c->fwd_fc : &c->bck_fc;
4459 if (GNUNET_MESSAGE_TYPE_MESH_POLL == type ||
4460 GNUNET_MESSAGE_TYPE_MESH_ACK == type)
4464 ( (NULL != ch->root && GNUNET_MESSAGE_TYPE_MESH_FWD == type) ||
4465 (NULL != ch->dest && GNUNET_MESSAGE_TYPE_MESH_BCK == type) ))
4468 if (fc->queue_n >= fc->queue_max && 0 == priority)
4470 GNUNET_STATISTICS_update (stats, "# messages dropped (buffer full)",
4473 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4474 "queue full: %u/%u\n",
4475 fc->queue_n, fc->queue_max);
4476 return; /* Drop this message */
4479 if (GMC_is_pid_bigger(fc->last_pid_sent + 1, fc->last_ack_recv) &&
4480 GNUNET_SCHEDULER_NO_TASK == fc->poll_task)
4481 fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
4484 queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
4492 if (100 <= priority)
4493 GNUNET_CONTAINER_DLL_insert (dst->queue_head, dst->queue_tail, queue);
4495 GNUNET_CONTAINER_DLL_insert_tail (dst->queue_head, dst->queue_tail, queue);
4497 if (NULL == dst->core_transmit)
4499 dst->core_transmit =
4500 GNUNET_CORE_notify_transmit_ready (core_handle,
4503 GNUNET_TIME_UNIT_FOREVER_REL,
4504 GNUNET_PEER_resolve2 (dst->id),
4509 c->pending_messages++;
4510 c->t->pending_messages++;
4516 /******************************************************************************/
4517 /******************** MESH NETWORK HANDLERS **************************/
4518 /******************************************************************************/
4522 * Generic handler for mesh network payload traffic.
4524 * @param t Tunnel on which we got this message.
4525 * @param message Unencryted data message.
4526 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
4528 * @return GNUNET_OK to keep the connection open,
4529 * GNUNET_SYSERR to close it (signal serious error)
4532 handle_data (struct MeshTunnel2 *t, const struct GNUNET_MESH_Data *msg, int fwd)
4534 struct MeshChannelReliability *rel;
4535 struct MeshChannel *ch;
4536 struct MeshClient *c;
4543 size = ntohs (msg->header.size);
4545 sizeof (struct GNUNET_MESH_Data) +
4546 sizeof (struct GNUNET_MessageHeader))
4551 type = ntohs (msg->header.type);
4552 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message\n",
4553 GNUNET_MESH_DEBUG_M2S (type));
4554 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
4555 GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
4558 ch = channel_get (t, ntohl (msg->chid));
4561 GNUNET_STATISTICS_update (stats, "# data on unknown channel", 1, GNUNET_NO);
4562 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel unknown\n");
4566 /* Initialize FWD/BCK data */
4567 c = fwd ? ch->dest : ch->root;
4568 rel = fwd ? ch->bck_rel : ch->fwd_rel;
4569 mid_recv = fwd ? &ch->mid_recv_fwd : &ch->mid_recv_bck;
4577 tunnel_change_state (t, MESH_TUNNEL_READY);
4579 GNUNET_STATISTICS_update (stats, "# data received", 1, GNUNET_NO);
4581 mid = ntohl (msg->mid);
4582 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " mid %u\n", mid);
4584 if (GNUNET_NO == ch->reliable ||
4585 ( !GMC_is_pid_bigger (*mid_recv, mid) &&
4586 GMC_is_pid_bigger (*mid_recv + 64, mid) ) )
4588 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! RECV %u\n", mid);
4589 if (GNUNET_YES == ch->reliable)
4591 /* Is this the exact next expected messasge? */
4592 if (mid == *mid_recv)
4594 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "as expected\n");
4595 *mid_recv = *mid_recv + 1;
4596 channel_send_client_data (ch, msg, fwd);
4597 channel_send_client_buffered_data (ch, c, rel);
4601 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "save for later\n");
4602 channel_rel_add_buffered_data (msg, rel);
4605 else /* Tunnel unreliable, send to clients directly */
4607 channel_send_client_data (ch, msg, fwd);
4612 GNUNET_break_op (0);
4613 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4614 " MID %u not expected (%u - %u), dropping!\n",
4615 mid, *mid_recv, *mid_recv + 64);
4618 channel_send_data_ack (ch, fwd);
4623 * Handler for mesh network traffic end-to-end ACKs.
4625 * @param t Tunnel on which we got this message.
4626 * @param message Data message.
4627 * @param fwd Is this a fwd ACK? (dest->orig)
4629 * @return GNUNET_OK to keep the connection open,
4630 * GNUNET_SYSERR to close it (signal serious error)
4633 handle_data_ack (struct MeshTunnel2 *t,
4634 const struct GNUNET_MESH_DataACK *msg, int fwd)
4636 struct MeshChannelReliability *rel;
4637 struct MeshReliableMessage *copy;
4638 struct MeshReliableMessage *next;
4639 struct MeshChannel *ch;
4644 type = ntohs (msg->header.type);
4645 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a %s message!\n",
4646 GNUNET_MESH_DEBUG_M2S (type));
4647 ch = channel_get (t, ntohl (msg->chid));
4650 GNUNET_STATISTICS_update (stats, "# ack on unknown channel", 1, GNUNET_NO);
4653 ack = ntohl (msg->mid);
4654 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! %s ACK %u\n",
4655 (GNUNET_YES == fwd) ? "FWD" : "BCK", ack);
4657 if (GNUNET_YES == fwd)
4670 for (work = GNUNET_NO, copy = rel->head_sent; copy != NULL; copy = next)
4672 if (GMC_is_pid_bigger (copy->mid, ack))
4674 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! head %u, out!\n", copy->mid);
4675 channel_rel_free_sent (rel, msg);
4679 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! id %u\n", copy->mid);
4681 rel_message_free (copy);
4683 /* ACK client if needed */
4684 // channel_send_ack (t, type, GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK == type);
4686 /* If some message was free'd, update the retransmission delay*/
4687 if (GNUNET_YES == work)
4689 if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
4691 GNUNET_SCHEDULER_cancel (rel->retry_task);
4692 if (NULL == rel->head_sent)
4694 rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
4698 struct GNUNET_TIME_Absolute new_target;
4699 struct GNUNET_TIME_Relative delay;
4701 delay = GNUNET_TIME_relative_multiply (rel->retry_timer,
4702 MESH_RETRANSMIT_MARGIN);
4703 new_target = GNUNET_TIME_absolute_add (rel->head_sent->timestamp,
4705 delay = GNUNET_TIME_absolute_get_remaining (new_target);
4707 GNUNET_SCHEDULER_add_delayed (delay,
4708 &channel_retransmit_message,
4720 * Core handler for connection creation.
4722 * @param cls Closure (unused).
4723 * @param peer Sender (neighbor).
4724 * @param message Message.
4726 * @return GNUNET_OK to keep the connection open,
4727 * GNUNET_SYSERR to close it (signal serious error)
4730 handle_mesh_connection_create (void *cls,
4731 const struct GNUNET_PeerIdentity *peer,
4732 const struct GNUNET_MessageHeader *message)
4734 struct GNUNET_MESH_ConnectionCreate *msg;
4735 struct GNUNET_PeerIdentity *id;
4736 struct GNUNET_HashCode *tid;
4737 struct MeshPeerPath *path;
4738 struct MeshPeer *dest_peer;
4739 struct MeshPeer *orig_peer;
4740 struct MeshConnection *c;
4741 unsigned int own_pos;
4746 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection create msg\n");
4749 size = ntohs (message->size);
4750 if (size < sizeof (struct GNUNET_MESH_ConnectionCreate))
4752 GNUNET_break_op (0);
4756 /* Calculate hops */
4757 size -= sizeof (struct GNUNET_MESH_ConnectionCreate);
4758 if (size % sizeof (struct GNUNET_PeerIdentity))
4760 GNUNET_break_op (0);
4763 size /= sizeof (struct GNUNET_PeerIdentity);
4766 GNUNET_break_op (0);
4769 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " path has %u hops.\n", size);
4771 /* Get parameters */
4772 msg = (struct GNUNET_MESH_ConnectionCreate *) message;
4773 cid = ntohl (msg->cid);
4775 id = (struct GNUNET_PeerIdentity *) &msg[1];
4776 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4777 " connection %s[%X] (%s).\n",
4778 GNUNET_h2s (tid), cid, GNUNET_i2s (id));
4780 /* Create connection */
4781 c = connection_get (tid, cid);
4784 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Creating connection\n");
4785 c = connection_new (tid, cid);
4789 connection_reset_timeout (c, GNUNET_YES);
4790 tunnel_change_state (c->t, MESH_TUNNEL_WAITING);
4792 /* Remember peers */
4793 dest_peer = peer_get (&id[size - 1]);
4794 orig_peer = peer_get (&id[0]);
4797 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Creating path...\n");
4798 path = path_new (size);
4800 for (i = 0; i < size; i++)
4802 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... adding %s\n",
4803 GNUNET_i2s (&id[i]));
4804 path->peers[i] = GNUNET_PEER_intern (&id[i]);
4805 if (path->peers[i] == myid)
4808 if (own_pos == 0 && path->peers[own_pos] != myid)
4810 /* create path: self not found in path through self */
4811 GNUNET_break_op (0);
4812 path_destroy (path);
4813 connection_destroy (c);
4816 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Own position: %u\n", own_pos);
4817 path_add_to_peers (path, GNUNET_NO);
4819 c->own_pos = own_pos;
4821 /* Is it a connection to us? */
4822 if (own_pos == size - 1)
4824 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " It's for us!\n");
4825 peer_add_path_to_origin (orig_peer, path, GNUNET_YES);
4827 send_connection_ack (c);
4829 /* Keep tunnel alive in direction dest->owner*/
4830 connection_reset_timeout (c, GNUNET_NO);
4834 /* It's for somebody else! Retransmit. */
4835 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Retransmitting.\n");
4836 peer_add_path (dest_peer, path_duplicate (path), GNUNET_NO);
4837 peer_add_path_to_origin (orig_peer, path, GNUNET_NO);
4838 send_prebuilt_message_connection (message, c, NULL, GNUNET_YES);
4845 * Core handler for path ACKs
4847 * @param cls closure
4848 * @param message message
4849 * @param peer peer identity this notification is about
4851 * @return GNUNET_OK to keep the connection open,
4852 * GNUNET_SYSERR to close it (signal serious error)
4855 handle_mesh_connection_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
4856 const struct GNUNET_MessageHeader *message)
4858 struct GNUNET_MESH_ConnectionACK *msg;
4859 struct MeshPeerPath *p;
4860 struct MeshConnection *c;
4863 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection ACK msg\n");
4864 msg = (struct GNUNET_MESH_ConnectionACK *) message;
4865 cid = ntohl(msg->cid);
4866 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " on connection %s[%X]\n",
4867 GNUNET_h2s (&msg->tid), cid);
4868 c = connection_get (&msg->tid, cid);
4871 GNUNET_STATISTICS_update (stats, "# control on unknown connection",
4873 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " don't know the connection!\n");
4877 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " via peer %s\n",
4880 /* Add path to peers? */
4884 path_add_to_peers (p, GNUNET_YES);
4890 connection_change_state (c, MESH_CONNECTION_READY);
4891 connection_reset_timeout (c, GNUNET_NO);
4893 /* Message for us? */
4894 if (NULL != c->t->channel_head)
4896 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " It's for us!\n");
4897 if (3 <= tunnel_count_connections(c->t) && NULL != c->t->peer->dhtget)
4899 GNUNET_DHT_get_stop (c->t->peer->dhtget);
4900 c->t->peer->dhtget = NULL;
4902 //connection_send_ack (c, GNUNET_NO); /* FIXME */
4906 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " not for us, retransmitting...\n");
4907 send_prebuilt_message_connection (message, c, NULL, GNUNET_NO);
4913 * Core handler for notifications of broken paths
4915 * @param cls Closure (unused).
4916 * @param peer Peer identity of sending neighbor.
4917 * @param message Message.
4919 * @return GNUNET_OK to keep the connection open,
4920 * GNUNET_SYSERR to close it (signal serious error)
4923 handle_mesh_connection_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
4924 const struct GNUNET_MessageHeader *message)
4926 struct GNUNET_MESH_ConnectionBroken *msg;
4927 struct MeshConnection *c;
4929 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4930 "Received a CONNECTION BROKEN msg from %s\n", GNUNET_i2s (peer));
4931 msg = (struct GNUNET_MESH_ConnectionBroken *) message;
4932 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " regarding %s\n",
4933 GNUNET_i2s (&msg->peer1));
4934 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " regarding %s\n",
4935 GNUNET_i2s (&msg->peer2));
4936 c = connection_get (&msg->tid, ntohl (msg->cid));
4939 GNUNET_break_op (0);
4942 tunnel_notify_connection_broken (c->t, GNUNET_PEER_search (&msg->peer1),
4943 GNUNET_PEER_search (&msg->peer2));
4950 * Core handler for tunnel destruction
4952 * @param cls Closure (unused).
4953 * @param peer Peer identity of sending neighbor.
4954 * @param message Message.
4956 * @return GNUNET_OK to keep the connection open,
4957 * GNUNET_SYSERR to close it (signal serious error)
4960 handle_mesh_connection_destroy (void *cls,
4961 const struct GNUNET_PeerIdentity *peer,
4962 const struct GNUNET_MessageHeader *message)
4964 struct GNUNET_MESH_ConnectionDestroy *msg;
4965 struct MeshConnection *c;
4969 msg = (struct GNUNET_MESH_ConnectionDestroy *) message;
4970 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4971 "Got a CONNECTION DESTROY message from %s\n",
4973 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4974 " for connection %s[%X]\n",
4975 GNUNET_h2s (&msg->tid), ntohl (msg->cid));
4976 c = connection_get (&msg->tid, ntohl (msg->cid));
4979 /* Probably already got the message from another path,
4980 * destroyed the tunnel and retransmitted to children.
4983 GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
4987 id = GNUNET_PEER_search (peer);
4988 if (id == connection_get_prev_hop (c)->id)
4990 else if (id == connection_get_next_hop (c)->id)
4994 GNUNET_break_op (0);
4997 send_prebuilt_message_connection (message, c, NULL, fwd);
4998 c->destroy = GNUNET_YES;
5004 * Handler for channel create messages.
5006 * @param t Tunnel this channel is to be created in.
5007 * @param msg Message.
5008 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5010 * @return GNUNET_OK to keep the connection open,
5011 * GNUNET_SYSERR to close it (signal serious error)
5014 handle_channel_create (struct MeshTunnel2 *t,
5015 struct GNUNET_MESH_ChannelCreate *msg,
5018 MESH_ChannelNumber chid;
5019 struct MeshChannel *ch;
5020 struct MeshClient *c;
5022 /* Check message size */
5023 if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelCreate))
5025 GNUNET_break_op (0);
5029 /* Check if channel exists */
5030 chid = ntohl (msg->chid);
5031 ch = channel_get (t, chid);
5034 /* Probably a retransmission, safe to ignore */
5038 /* Find a destination client */
5039 c = GNUNET_CONTAINER_multihashmap32_get (ports, msg->port);
5042 /* TODO send reject */
5046 /* Create channel */
5047 ch = channel_new (t, NULL, 0);
5048 channel_set_options (ch, ntohl (msg->opt));
5049 channel_add_client (ch, c);
5050 if (GNUNET_YES == ch->reliable)
5052 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
5053 ch->bck_rel = GNUNET_malloc (sizeof (struct MeshChannelReliability));
5054 ch->bck_rel->ch = ch;
5055 ch->bck_rel->expected_delay = MESH_RETRANSMIT_TIME;
5058 send_local_channel_create (ch);
5065 * Handler for channel destroy messages.
5067 * @param t Tunnel this channel is to be destroyed of.
5068 * @param msg Message.
5069 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5071 * @return GNUNET_OK to keep the connection open,
5072 * GNUNET_SYSERR to close it (signal serious error)
5075 handle_channel_destroy (struct MeshTunnel2 *t,
5076 struct GNUNET_MESH_ChannelDestroy *msg,
5079 MESH_ChannelNumber chid;
5080 struct MeshChannel *ch;
5082 /* Check message size */
5083 if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelDestroy))
5085 GNUNET_break_op (0);
5089 /* Check if channel exists */
5090 chid = ntohl (msg->chid);
5091 ch = channel_get (t, chid);
5094 /* Probably a retransmission, safe to ignore */
5098 send_local_channel_destroy (ch, fwd);
5099 channel_destroy (ch);
5106 * Generic handler for mesh network encrypted traffic.
5108 * @param peer Peer identity this notification is about.
5109 * @param message Encrypted message.
5110 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5112 * @return GNUNET_OK to keep the connection open,
5113 * GNUNET_SYSERR to close it (signal serious error)
5116 handle_mesh_encrypted (const struct GNUNET_PeerIdentity *peer,
5117 const struct GNUNET_MESH_Encrypted *msg,
5120 struct MeshConnection *c;
5121 struct MeshTunnel2 *t;
5122 struct MeshPeer *neighbor;
5123 struct MeshFlowControl *fc;
5130 size = ntohs (msg->header.size);
5132 sizeof (struct GNUNET_MESH_Encrypted) +
5133 sizeof (struct GNUNET_MessageHeader))
5138 type = ntohs (msg->header.type);
5139 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message from %s\n",
5140 GNUNET_MESH_DEBUG_M2S (type), GNUNET_i2s (peer));
5142 /* Check connection */
5143 c = connection_get (&msg->tid, ntohl (msg->cid));
5146 GNUNET_STATISTICS_update (stats, "# unknown connection", 1, GNUNET_NO);
5147 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING connection unknown\n");
5151 fc = fwd ? &c->fwd_fc : &c->bck_fc;
5153 /* Check if origin is as expected */
5154 neighbor = connection_get_hop (c, fwd);
5155 if (peer_get (peer)->id != neighbor->id)
5157 GNUNET_break_op (0);
5162 pid = ntohl (msg->pid);
5163 if (GMC_is_pid_bigger (pid, fc->last_ack_sent))
5165 GNUNET_STATISTICS_update (stats, "# unsolicited message", 1, GNUNET_NO);
5166 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5167 "WARNING Received PID %u, (prev %u), ACK %u\n",
5168 pid, fc->last_pid_recv, fc->last_ack_sent);
5171 if (GNUNET_NO == GMC_is_pid_bigger (pid, fc->last_pid_recv))
5173 GNUNET_STATISTICS_update (stats, "# duplicate PID", 1, GNUNET_NO);
5174 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5175 " Pid %u not expected (%u+), dropping!\n",
5176 pid, fc->last_pid_recv + 1);
5179 if (MESH_CONNECTION_SENT == c->state)
5180 connection_change_state (c, MESH_CONNECTION_READY);
5181 connection_reset_timeout (c, fwd);
5182 fc->last_pid_recv = pid;
5184 /* Is this message for us? */
5185 if (NULL != c->t->channel_head)
5187 size_t dsize = size - sizeof (struct GNUNET_MESH_Encrypted);
5189 struct GNUNET_MessageHeader *msgh;
5191 /* TODO signature verification */
5192 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " it's for us!\n");
5193 GNUNET_STATISTICS_update (stats, "# messages received", 1, GNUNET_NO);
5195 fc->last_pid_recv = pid;
5196 tunnel_decrypt (t, cbuf, &msg[1], dsize, msg->iv, fwd);
5197 msgh = (struct GNUNET_MessageHeader *) cbuf;
5198 switch (ntohs (msgh->type))
5200 case GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK:
5201 if (GNUNET_YES == fwd)
5202 return handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh,
5204 GNUNET_break_op (0);
5206 case GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK:
5207 if (GNUNET_NO == fwd)
5208 return handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh,
5210 GNUNET_break_op (0);
5212 case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
5213 if (GNUNET_YES == fwd)
5214 handle_data (t, (struct GNUNET_MESH_Data *) msgh, GNUNET_YES);
5215 GNUNET_break_op (0);
5217 case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
5218 if (GNUNET_NO == fwd)
5219 handle_data (t, (struct GNUNET_MESH_Data *) msgh, GNUNET_NO);
5220 GNUNET_break_op (0);
5222 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
5223 return handle_channel_create (t,
5224 (struct GNUNET_MESH_ChannelCreate *) msgh,
5227 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
5228 return handle_channel_destroy (t,
5229 (struct GNUNET_MESH_ChannelDestroy *)
5234 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5235 "end-to-end message not known (%u)\n",
5236 ntohs (msgh->type));
5239 connection_send_ack (c, fwd);
5243 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " not for us, retransmitting...\n");
5244 ttl = ntohl (msg->ttl);
5245 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ttl: %u\n", ttl);
5248 GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5249 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5250 connection_send_ack (c, fwd);
5253 GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
5255 send_prebuilt_message_connection (&msg->header, c, NULL, fwd);
5256 connection_send_ack (c, fwd);
5263 * Core handler for mesh network traffic going orig->dest.
5265 * @param cls Closure (unused).
5266 * @param message Message received.
5267 * @param peer Peer who sent the message.
5269 * @return GNUNET_OK to keep the connection open,
5270 * GNUNET_SYSERR to close it (signal serious error)
5273 handle_mesh_fwd (void *cls, const struct GNUNET_PeerIdentity *peer,
5274 const struct GNUNET_MessageHeader *message)
5276 return handle_mesh_encrypted (peer,
5277 (struct GNUNET_MESH_Encrypted *)message,
5282 * Core handler for mesh network traffic going dest->orig.
5284 * @param cls Closure (unused).
5285 * @param message Message received.
5286 * @param peer Peer who sent the message.
5288 * @return GNUNET_OK to keep the connection open,
5289 * GNUNET_SYSERR to close it (signal serious error)
5292 handle_mesh_bck (void *cls, const struct GNUNET_PeerIdentity *peer,
5293 const struct GNUNET_MessageHeader *message)
5295 return handle_mesh_encrypted (peer,
5296 (struct GNUNET_MESH_Encrypted *)message,
5302 * Core handler for mesh network traffic point-to-point acks.
5304 * @param cls closure
5305 * @param message message
5306 * @param peer peer identity this notification is about
5308 * @return GNUNET_OK to keep the connection open,
5309 * GNUNET_SYSERR to close it (signal serious error)
5312 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5313 const struct GNUNET_MessageHeader *message)
5315 struct GNUNET_MESH_ACK *msg;
5316 struct MeshConnection *c;
5317 struct MeshFlowControl *fc;
5321 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
5323 msg = (struct GNUNET_MESH_ACK *) message;
5325 c = connection_get (&msg->tid, ntohl (msg->cid));
5329 GNUNET_STATISTICS_update (stats, "# ack on unknown connection", 1,
5334 ack = ntohl (msg->ack);
5335 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", ack);
5337 /* Is this a forward or backward ACK? */
5338 id = GNUNET_PEER_search (peer);
5339 if (connection_get_next_hop (c)->id == id)
5341 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " FWD ACK\n");
5344 else if (connection_get_prev_hop (c)->id == id)
5346 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " BCK ACK\n");
5351 GNUNET_break_op (0);
5355 /* Cancel polling if the ACK is bigger than before. */
5356 if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task &&
5357 GMC_is_pid_bigger (ack, fc->last_ack_recv))
5359 GNUNET_SCHEDULER_cancel (fc->poll_task);
5360 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
5361 fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
5364 fc->last_ack_recv = ack;
5365 connection_unlock_queue (c, fc == &c->fwd_fc);
5372 * Core handler for mesh network traffic point-to-point ack polls.
5374 * @param cls closure
5375 * @param message message
5376 * @param peer peer identity this notification is about
5378 * @return GNUNET_OK to keep the connection open,
5379 * GNUNET_SYSERR to close it (signal serious error)
5382 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
5383 const struct GNUNET_MessageHeader *message)
5385 struct GNUNET_MESH_Poll *msg;
5386 struct MeshConnection *c;
5387 struct MeshFlowControl *fc;
5391 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a POLL packet from %s!\n",
5394 msg = (struct GNUNET_MESH_Poll *) message;
5396 c = connection_get (&msg->tid, ntohl (msg->cid));
5400 GNUNET_STATISTICS_update (stats, "# poll on unknown connection", 1,
5402 GNUNET_break_op (0);
5406 /* Is this a forward or backward ACK? */
5407 id = GNUNET_PEER_search (peer);
5408 if (connection_get_next_hop (c)->id == id)
5410 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " FWD ACK\n");
5413 else if (connection_get_prev_hop (c)->id == id)
5415 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " BCK ACK\n");
5420 GNUNET_break_op (0);
5424 pid = ntohl (msg->pid);
5425 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " PID %u, OLD %u\n",
5426 pid, fc->last_pid_recv);
5427 fc->last_pid_recv = pid;
5428 connection_send_ack (c, fc == &c->fwd_fc);
5435 * Core handler for mesh keepalives.
5437 * @param cls closure
5438 * @param message message
5439 * @param peer peer identity this notification is about
5440 * @return GNUNET_OK to keep the connection open,
5441 * GNUNET_SYSERR to close it (signal serious error)
5443 * TODO: Check who we got this from, to validate route.
5446 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
5447 const struct GNUNET_MessageHeader *message)
5449 struct GNUNET_MESH_ConnectionKeepAlive *msg;
5450 struct MeshConnection *c;
5451 struct MeshPeer *neighbor;
5454 msg = (struct GNUNET_MESH_ConnectionKeepAlive *) message;
5455 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
5458 c = connection_get (&msg->tid, ntohl (msg->cid));
5461 GNUNET_STATISTICS_update (stats, "# keepalive on unknown connection", 1,
5466 fwd = GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE == ntohs (message->type) ?
5467 GNUNET_YES : GNUNET_NO;
5469 /* Check if origin is as expected */
5470 neighbor = connection_get_hop (c, fwd);
5471 if (peer_get (peer)->id != neighbor->id)
5473 GNUNET_break_op (0);
5477 connection_change_state (c, MESH_CONNECTION_READY);
5478 connection_reset_timeout (c, fwd);
5480 if (NULL != c->t->channel_head)
5483 GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
5484 send_prebuilt_message_connection (message, c, NULL, fwd);
5492 * Functions to handle messages from core
5494 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
5495 {&handle_mesh_connection_create, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
5497 {&handle_mesh_connection_ack, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
5498 sizeof (struct GNUNET_MESH_ConnectionACK)},
5499 {&handle_mesh_connection_broken, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN,
5500 sizeof (struct GNUNET_MESH_ConnectionBroken)},
5501 {&handle_mesh_connection_destroy, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY,
5502 sizeof (struct GNUNET_MESH_ConnectionDestroy)},
5503 {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE,
5504 sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
5505 {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE,
5506 sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
5507 {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
5508 sizeof (struct GNUNET_MESH_ACK)},
5509 {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
5510 sizeof (struct GNUNET_MESH_Poll)},
5511 {&handle_mesh_fwd, GNUNET_MESSAGE_TYPE_MESH_FWD, 0},
5512 {&handle_mesh_bck, GNUNET_MESSAGE_TYPE_MESH_BCK, 0},
5518 * Function to process paths received for a new peer addition. The recorded
5519 * paths form the initial tunnel, which can be optimized later.
5520 * Called on each result obtained for the DHT search.
5522 * @param cls closure
5523 * @param exp when will this value expire
5524 * @param key key of the result
5525 * @param get_path path of the get request
5526 * @param get_path_length lenght of get_path
5527 * @param put_path path of the put request
5528 * @param put_path_length length of the put_path
5529 * @param type type of the result
5530 * @param size number of bytes in data
5531 * @param data pointer to the result data
5534 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5535 const struct GNUNET_HashCode * key,
5536 const struct GNUNET_PeerIdentity *get_path,
5537 unsigned int get_path_length,
5538 const struct GNUNET_PeerIdentity *put_path,
5539 unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5540 size_t size, const void *data)
5542 struct MeshPeer *peer = cls;
5543 struct MeshPeerPath *p;
5544 struct MeshConnection *c;
5545 struct GNUNET_PeerIdentity pi;
5548 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
5549 GNUNET_PEER_resolve (peer->id, &pi);
5550 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " for %s\n", GNUNET_i2s (&pi));
5552 p = path_build_from_dht (get_path, get_path_length,
5553 put_path, put_path_length);
5554 path_add_to_peers (p, GNUNET_NO);
5557 /* Count connections */
5558 for (c = peer->tunnel->connection_head, i = 0; NULL != c; c = c->next, i++);
5560 /* If we already have 3 (or more (?!)) connections, it's enough */
5564 if (peer->tunnel->state == MESH_TUNNEL_SEARCHING)
5566 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... connect!\n");
5567 peer_connect (peer);
5573 /******************************************************************************/
5574 /********************* MESH LOCAL HANDLES **************************/
5575 /******************************************************************************/
5579 * Handler for client connection.
5581 * @param cls Closure (unused).
5582 * @param client Client handler.
5585 handle_local_client_connect (void *cls, struct GNUNET_SERVER_Client *client)
5587 struct MeshClient *c;
5591 c = GNUNET_malloc (sizeof (struct MeshClient));
5593 c->id = next_client_id++; /* overflow not important: just for debug */
5594 GNUNET_SERVER_client_keep (client);
5595 GNUNET_SERVER_client_set_user_context (client, c);
5596 GNUNET_CONTAINER_DLL_insert (clients_head, clients_tail, c);
5601 * Handler for client disconnection
5603 * @param cls closure
5604 * @param client identification of the client; NULL
5605 * for the last call when the server is destroyed
5608 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
5610 struct MeshClient *c;
5611 struct MeshClient *next;
5613 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected: %p\n", client);
5616 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " (SERVER DOWN)\n");
5620 c = client_get (client);
5623 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u, %p)\n",
5625 GNUNET_SERVER_client_drop (c->handle);
5626 c->shutting_down = GNUNET_YES;
5627 if (NULL != c->own_channels)
5629 GNUNET_CONTAINER_multihashmap32_iterate (c->own_channels,
5630 &channel_destroy_iterator, c);
5631 GNUNET_CONTAINER_multihashmap32_destroy (c->own_channels);
5634 if (NULL != c->incoming_channels)
5636 GNUNET_CONTAINER_multihashmap32_iterate (c->incoming_channels,
5637 &channel_destroy_iterator, c);
5638 GNUNET_CONTAINER_multihashmap32_destroy (c->incoming_channels);
5641 if (NULL != c->ports)
5643 GNUNET_CONTAINER_multihashmap32_iterate (c->ports,
5644 &client_release_ports, c);
5645 GNUNET_CONTAINER_multihashmap32_destroy (c->ports);
5648 GNUNET_CONTAINER_DLL_remove (clients_head, clients_tail, c);
5649 GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
5650 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " client free (%p)\n", c);
5656 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " context NULL!\n");
5658 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "done!\n");
5664 * Handler for new clients
5666 * @param cls closure
5667 * @param client identification of the client
5668 * @param message the actual message, which includes messages the client wants
5671 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
5672 const struct GNUNET_MessageHeader *message)
5674 struct GNUNET_MESH_ClientConnect *cc_msg;
5675 struct MeshClient *c;
5680 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected %p\n", client);
5682 /* Check data sanity */
5683 size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
5684 cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
5685 if (0 != (size % sizeof (uint32_t)))
5688 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5691 size /= sizeof (uint32_t);
5693 /* Initialize new client structure */
5694 c = GNUNET_SERVER_client_get_user_context (client, struct MeshClient);
5695 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " client id %u\n", c->id);
5696 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " client has %u ports\n", size);
5701 p = (uint32_t *) &cc_msg[1];
5702 c->ports = GNUNET_CONTAINER_multihashmap32_create (size);
5703 for (i = 0; i < size; i++)
5706 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " port: %u\n", u32);
5708 /* store in client's hashmap */
5709 GNUNET_CONTAINER_multihashmap32_put (c->ports, u32, c,
5710 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
5711 /* store in global hashmap */
5712 /* FIXME only allow one client to have the port open,
5713 * have a backup hashmap with waiting clients */
5714 GNUNET_CONTAINER_multihashmap32_put (ports, u32, c,
5715 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
5719 c->own_channels = GNUNET_CONTAINER_multihashmap32_create (32);
5720 c->incoming_channels = GNUNET_CONTAINER_multihashmap32_create (32);
5721 GNUNET_SERVER_notification_context_add (nc, client);
5722 GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
5724 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5725 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
5730 * Handler for requests of new tunnels
5732 * @param cls Closure.
5733 * @param client Identification of the client.
5734 * @param message The actual message.
5737 handle_local_channel_create (void *cls, struct GNUNET_SERVER_Client *client,
5738 const struct GNUNET_MessageHeader *message)
5740 struct GNUNET_MESH_ChannelMessage *msg;
5741 struct MeshPeer *peer;
5742 struct MeshTunnel2 *t;
5743 struct MeshChannel *ch;
5744 struct MeshClient *c;
5745 MESH_ChannelNumber chid;
5747 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new channel requested\n");
5749 /* Sanity check for client registration */
5750 if (NULL == (c = client_get (client)))
5753 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5756 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
5758 /* Message size sanity check */
5759 if (sizeof (struct GNUNET_MESH_ChannelMessage) != ntohs (message->size))
5762 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5766 msg = (struct GNUNET_MESH_ChannelMessage *) message;
5767 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " towards %s:%u\n",
5768 GNUNET_i2s (&msg->peer), ntohl (msg->port));
5769 chid = ntohl (msg->channel_id);
5771 /* Sanity check for duplicate channel IDs */
5772 if (NULL != channel_get_by_local_id (c, chid))
5775 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5779 peer = peer_get (&msg->peer);
5780 if (NULL == peer->tunnel)
5782 struct GNUNET_HashCode tid;
5784 GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE, &tid);
5785 peer->tunnel = tunnel_new (&tid);
5789 /* Create channel */
5790 ch = channel_new (t, c, chid);
5794 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5797 ch->port = ntohl (msg->port);
5798 channel_set_options (ch, ntohl (msg->opt));
5800 /* In unreliable channels, we'll use the DLL to buffer data for the root */
5801 ch->fwd_rel = GNUNET_malloc (sizeof (struct MeshChannelReliability));
5802 ch->fwd_rel->ch = ch;
5803 ch->fwd_rel->expected_delay = MESH_RETRANSMIT_TIME;
5805 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED CHANNEL %s[%x]:%u (%x)\n",
5806 GNUNET_h2s (&t->id), ch->gid, ch->port, ch->lid_root);
5807 peer_connect (peer);
5808 /* FIXME send create channel */
5810 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5816 * Handler for requests of deleting tunnels
5818 * @param cls closure
5819 * @param client identification of the client
5820 * @param message the actual message
5823 handle_local_channel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
5824 const struct GNUNET_MessageHeader *message)
5826 struct GNUNET_MESH_ChannelMessage *msg;
5827 struct MeshClient *c;
5828 struct MeshChannel *ch;
5829 struct MeshTunnel2 *t;
5830 MESH_ChannelNumber chid;
5832 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5833 "Got a DESTROY CHANNEL from client!\n");
5835 /* Sanity check for client registration */
5836 if (NULL == (c = client_get (client)))
5839 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5842 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
5844 /* Message sanity check */
5845 if (sizeof (struct GNUNET_MESH_ChannelMessage) != ntohs (message->size))
5848 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5852 msg = (struct GNUNET_MESH_ChannelMessage *) message;
5854 /* Retrieve tunnel */
5855 chid = ntohl (msg->channel_id);
5856 ch = channel_get_by_local_id (c, chid);
5859 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, " channel %X not found\n", chid);
5861 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5865 /* Cleanup after the tunnel */
5866 client_delete_channel (c, ch);
5867 if (c == ch->dest && GNUNET_MESH_LOCAL_CHANNEL_ID_SERV <= chid)
5871 else if (c == ch->root && GNUNET_MESH_LOCAL_CHANNEL_ID_SERV > chid)
5877 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5878 " channel %X client %p (%p, %p)\n",
5879 chid, c, ch->root, ch->dest);
5884 channel_destroy (ch);
5885 tunnel_destroy_if_empty (t);
5887 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5893 * Handler for client traffic
5895 * @param cls closure
5896 * @param client identification of the client
5897 * @param message the actual message
5900 handle_local_data (void *cls, struct GNUNET_SERVER_Client *client,
5901 const struct GNUNET_MessageHeader *message)
5903 struct GNUNET_MESH_LocalData *msg;
5904 struct MeshClient *c;
5905 struct MeshChannel *ch;
5906 MESH_ChannelNumber chid;
5910 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5911 "Got data from a client!\n");
5913 /* Sanity check for client registration */
5914 if (NULL == (c = client_get (client)))
5917 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5920 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
5922 msg = (struct GNUNET_MESH_LocalData *) message;
5924 /* Sanity check for message size */
5925 size = ntohs (message->size) - sizeof (struct GNUNET_MESH_LocalData);
5926 if (size < sizeof (struct GNUNET_MessageHeader))
5929 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5933 /* Channel exists? */
5934 chid = ntohl (msg->id);
5935 fwd = chid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
5936 ch = channel_get_by_local_id (c, chid);
5940 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5944 /* Is the client in the channel? */
5947 ch->root->handle == client)
5951 ch->dest->handle == client) ) )
5954 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5958 /* Ok, everything is correct, send the message
5959 * (pretend we got it from a mesh peer)
5962 struct GNUNET_MESH_Data *payload;
5963 char cbuf[sizeof(struct GNUNET_MESH_Data) + size];
5966 mid = fwd ? &ch->mid_send_fwd : &ch->mid_send_bck;
5967 if (GNUNET_YES == ch->reliable)
5969 struct MeshChannelReliability *rel;
5970 struct MeshReliableMessage *copy;
5972 rel = fwd ? ch->fwd_rel : ch->bck_rel;
5973 copy = GNUNET_malloc (sizeof (struct MeshReliableMessage)
5974 + sizeof(struct GNUNET_MESH_Data)
5977 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! DATA %u\n", copy->mid);
5978 copy->timestamp = GNUNET_TIME_absolute_get ();
5981 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " n_sent %u\n", rel->n_sent);
5982 GNUNET_CONTAINER_DLL_insert_tail (rel->head_sent, rel->tail_sent, copy);
5983 if (GNUNET_SCHEDULER_NO_TASK == rel->retry_task)
5986 GNUNET_TIME_relative_multiply (rel->expected_delay,
5987 MESH_RETRANSMIT_MARGIN);
5989 GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
5990 &channel_retransmit_message,
5993 payload = (struct GNUNET_MESH_Data *) ©[1];
5997 payload = (struct GNUNET_MESH_Data *) cbuf;
5999 payload->mid = htonl (*mid);
6001 memcpy (&payload[1], &msg[1], size);
6002 payload->header.size = htons (sizeof (struct GNUNET_MESH_Data) + size);
6003 payload->header.type = htons (chid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV ?
6004 GNUNET_MESSAGE_TYPE_MESH_UNICAST :
6005 GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
6006 payload->chid = htonl (ch->gid);
6007 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6008 " calling generic handler...\n");
6009 send_prebuilt_message_channel (&payload->header, ch, fwd);
6011 if (tunnel_get_buffer (ch->t, fwd) > 0)
6012 send_local_ack (ch, c, fwd);
6013 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
6014 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6021 * Handler for client's ACKs for payload traffic.
6023 * @param cls Closure (unused).
6024 * @param client Identification of the client.
6025 * @param message The actual message.
6028 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
6029 const struct GNUNET_MessageHeader *message)
6031 struct GNUNET_MESH_LocalAck *msg;
6032 struct MeshChannelReliability *rel;
6033 struct MeshChannel *ch;
6034 struct MeshClient *c;
6035 MESH_ChannelNumber chid;
6038 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
6040 /* Sanity check for client registration */
6041 if (NULL == (c = client_get (client)))
6044 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6047 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
6049 msg = (struct GNUNET_MESH_LocalAck *) message;
6051 /* Channel exists? */
6052 chid = ntohl (msg->channel_id);
6053 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " on channel %X\n", chid);
6054 ch = channel_get_by_local_id (c, chid);
6058 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Channel %X unknown.\n", chid);
6059 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " for client %u.\n", c->id);
6060 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6064 fwd = chid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
6065 rel = fwd ? ch->fwd_rel : ch->bck_rel;
6067 rel->client_ready = GNUNET_YES;
6068 channel_send_client_buffered_data (ch, c, rel);
6069 channel_send_ack (ch, 64 - rel->n_recv, fwd);
6071 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6078 * Iterator over all tunnels to send a monitoring client info about each tunnel.
6080 * @param cls Closure (client handle).
6081 * @param key Key (hashed tunnel ID, unused).
6082 * @param value Tunnel info.
6084 * @return GNUNET_YES, to keep iterating.
6087 monitor_all_tunnels_iterator (void *cls,
6088 const struct GNUNET_HashCode * key,
6091 struct GNUNET_SERVER_Client *client = cls;
6092 struct MeshChannel *ch = value;
6093 struct GNUNET_MESH_LocalMonitor *msg;
6095 msg = GNUNET_malloc (sizeof(struct GNUNET_MESH_LocalMonitor));
6096 msg->channel_id = htonl (ch->gid);
6097 msg->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
6098 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
6100 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6101 "* sending info about tunnel %s\n",
6102 GNUNET_i2s (&msg->owner));
6104 GNUNET_SERVER_notification_context_unicast (nc, client,
6105 &msg->header, GNUNET_NO);
6111 * Handler for client's MONITOR request.
6113 * @param cls Closure (unused).
6114 * @param client Identification of the client.
6115 * @param message The actual message.
6118 handle_local_get_tunnels (void *cls, struct GNUNET_SERVER_Client *client,
6119 const struct GNUNET_MessageHeader *message)
6121 struct MeshClient *c;
6123 /* Sanity check for client registration */
6124 if (NULL == (c = client_get (client)))
6127 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6131 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6132 "Received get tunnels request from client %u\n",
6134 GNUNET_CONTAINER_multihashmap_iterate (tunnels,
6135 monitor_all_tunnels_iterator,
6137 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6138 "Get tunnels request from client %u completed\n",
6140 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6145 * Handler for client's MONITOR_TUNNEL request.
6147 * @param cls Closure (unused).
6148 * @param client Identification of the client.
6149 * @param message The actual message.
6152 handle_local_show_tunnel (void *cls, struct GNUNET_SERVER_Client *client,
6153 const struct GNUNET_MessageHeader *message)
6155 const struct GNUNET_MESH_LocalMonitor *msg;
6156 struct GNUNET_MESH_LocalMonitor *resp;
6157 struct MeshClient *c;
6158 struct MeshChannel *ch;
6160 /* Sanity check for client registration */
6161 if (NULL == (c = client_get (client)))
6164 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6168 msg = (struct GNUNET_MESH_LocalMonitor *) message;
6169 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6170 "Received tunnel info request from client %u for tunnel %s[%X]\n",
6173 ntohl (msg->channel_id));
6174 // ch = channel_get (&msg->owner, ntohl (msg->channel_id));
6178 /* We don't know the tunnel */
6179 struct GNUNET_MESH_LocalMonitor warn;
6182 GNUNET_SERVER_notification_context_unicast (nc, client,
6185 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6189 /* Initialize context */
6190 resp = GNUNET_malloc (sizeof (struct GNUNET_MESH_LocalMonitor));
6192 resp->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
6193 GNUNET_SERVER_notification_context_unicast (nc, c->handle,
6194 &resp->header, GNUNET_NO);
6197 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6198 "Monitor tunnel request from client %u completed\n",
6200 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6205 * Functions to handle messages from clients
6207 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
6208 {&handle_local_new_client, NULL,
6209 GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
6210 {&handle_local_channel_create, NULL,
6211 GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE,
6212 sizeof (struct GNUNET_MESH_ChannelMessage)},
6213 {&handle_local_channel_destroy, NULL,
6214 GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY,
6215 sizeof (struct GNUNET_MESH_ChannelMessage)},
6216 {&handle_local_data, NULL,
6217 GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA, 0},
6218 {&handle_local_ack, NULL,
6219 GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
6220 sizeof (struct GNUNET_MESH_LocalAck)},
6221 {&handle_local_get_tunnels, NULL,
6222 GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS,
6223 sizeof (struct GNUNET_MessageHeader)},
6224 {&handle_local_show_tunnel, NULL,
6225 GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL,
6226 sizeof (struct GNUNET_MESH_LocalMonitor)},
6232 * Method called whenever a given peer connects.
6234 * @param cls closure
6235 * @param peer peer identity this notification is about
6238 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
6240 struct MeshPeer *pi;
6241 struct MeshPeerPath *path;
6243 DEBUG_CONN ("Peer connected\n");
6244 DEBUG_CONN (" %s\n", GNUNET_i2s (&my_full_id));
6245 pi = peer_get (peer);
6248 DEBUG_CONN (" (self)\n");
6249 path = path_new (1);
6253 DEBUG_CONN (" %s\n", GNUNET_i2s (peer));
6254 path = path_new (2);
6255 path->peers[1] = pi->id;
6256 GNUNET_PEER_change_rc (pi->id, 1);
6257 GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
6259 path->peers[0] = myid;
6260 GNUNET_PEER_change_rc (myid, 1);
6261 peer_add_path (pi, path, GNUNET_YES);
6263 pi->connections = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_YES);
6269 * Method called whenever a peer disconnects.
6271 * @param cls closure
6272 * @param peer peer identity this notification is about
6275 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
6277 struct MeshPeer *pi;
6279 DEBUG_CONN ("Peer disconnected\n");
6280 pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
6287 peer_remove_path (pi, myid, pi->id);
6289 GNUNET_CONTAINER_multihashmap_iterate (pi->connections,
6292 GNUNET_CONTAINER_multihashmap_destroy (pi->connections);
6293 pi->connections = NULL;
6296 DEBUG_CONN (" (self)\n");
6298 GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
6305 * Install server (service) handlers and start listening to clients.
6310 GNUNET_SERVER_add_handlers (server_handle, client_handlers);
6311 GNUNET_SERVER_connect_notify (server_handle,
6312 &handle_local_client_connect, NULL);
6313 GNUNET_SERVER_disconnect_notify (server_handle,
6314 &handle_local_client_disconnect, NULL);
6315 nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
6317 clients_head = NULL;
6318 clients_tail = NULL;
6320 GNUNET_SERVER_resume (server_handle);
6325 * To be called on core init/fail.
6327 * @param cls Closure (config)
6328 * @param server handle to the server for this service
6329 * @param identity the public identity of this peer
6332 core_init (void *cls, struct GNUNET_CORE_Handle *server,
6333 const struct GNUNET_PeerIdentity *identity)
6335 const struct GNUNET_CONFIGURATION_Handle *c = cls;
6338 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
6339 GNUNET_break (core_handle == server);
6340 if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
6343 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
6344 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6346 GNUNET_i2s (identity));
6347 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6349 GNUNET_i2s (&my_full_id));
6350 GNUNET_CORE_disconnect (core_handle);
6351 core_handle = GNUNET_CORE_connect (c, /* Main configuration */
6352 NULL, /* Closure passed to MESH functions */
6353 &core_init, /* Call core_init once connected */
6354 &core_connect, /* Handle connects */
6355 &core_disconnect, /* remove peers on disconnects */
6356 NULL, /* Don't notify about all incoming messages */
6357 GNUNET_NO, /* For header only in notification */
6358 NULL, /* Don't notify about all outbound messages */
6359 GNUNET_NO, /* For header-only out notification */
6360 core_handlers); /* Register these handlers */
6369 /******************************************************************************/
6370 /************************ MAIN FUNCTIONS ****************************/
6371 /******************************************************************************/
6374 * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
6376 * @param cls closure
6377 * @param key current key code
6378 * @param value value in the hash map
6379 * @return GNUNET_YES if we should continue to iterate,
6383 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
6385 struct MeshTunnel2 *t = value;
6393 * Task run during shutdown.
6399 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
6401 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
6403 if (core_handle != NULL)
6405 GNUNET_CORE_disconnect (core_handle);
6408 GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
6409 if (dht_handle != NULL)
6411 GNUNET_DHT_disconnect (dht_handle);
6416 GNUNET_SERVER_notification_context_destroy (nc);
6419 if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
6421 GNUNET_SCHEDULER_cancel (announce_id_task);
6422 announce_id_task = GNUNET_SCHEDULER_NO_TASK;
6424 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
6429 * Process mesh requests.
6431 * @param cls closure
6432 * @param server the initialized server
6433 * @param c configuration to use
6436 run (void *cls, struct GNUNET_SERVER_Handle *server,
6437 const struct GNUNET_CONFIGURATION_Handle *c)
6440 struct GNUNET_CRYPTO_EccPrivateKey *pk;
6442 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
6443 server_handle = server;
6444 GNUNET_SERVER_suspend (server_handle);
6447 GNUNET_CONFIGURATION_get_value_filename (c, "PEER", "PRIVATE_KEY",
6450 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6452 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6453 "mesh", "peer/privatekey");
6454 GNUNET_SCHEDULER_shutdown ();
6459 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_CONNECTION_TIME",
6460 &refresh_connection_time))
6462 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6464 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6465 "mesh", "refresh path time");
6466 GNUNET_SCHEDULER_shutdown ();
6471 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
6474 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6476 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6477 "mesh", "id announce time");
6478 GNUNET_SCHEDULER_shutdown ();
6483 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
6486 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6488 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6489 "mesh", "connect timeout");
6490 GNUNET_SCHEDULER_shutdown ();
6495 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
6498 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6500 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6501 "mesh", "max msgs queue");
6502 GNUNET_SCHEDULER_shutdown ();
6507 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_TUNNELS",
6510 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6512 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6513 "mesh", "max tunnels");
6514 GNUNET_SCHEDULER_shutdown ();
6519 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
6522 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6524 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
6525 "mesh", "default ttl", 64);
6530 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
6533 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6534 _("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
6535 "mesh", "max peers", 1000);
6540 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DROP_PERCENT",
6547 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6548 "Mesh is running with drop mode enabled. "
6549 "This is NOT a good idea! "
6550 "Remove the DROP_PERCENT option from your configuration.\n");
6554 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
6555 &dht_replication_level))
6557 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6559 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
6560 "mesh", "dht replication level", 3);
6561 dht_replication_level = 3;
6564 tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6565 peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6566 ports = GNUNET_CONTAINER_multihashmap32_create (32);
6568 dht_handle = GNUNET_DHT_connect (c, 64);
6569 if (NULL == dht_handle)
6573 stats = GNUNET_STATISTICS_create ("mesh", c);
6575 /* Scheduled the task to clean up when shutdown is called */
6576 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
6578 pk = GNUNET_CRYPTO_ecc_key_create_from_file (keyfile);
6579 GNUNET_free (keyfile);
6580 GNUNET_assert (NULL != pk);
6581 my_private_key = pk;
6582 GNUNET_CRYPTO_ecc_key_get_public (my_private_key, &my_public_key);
6583 GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
6584 &my_full_id.hashPubKey);
6585 myid = GNUNET_PEER_intern (&my_full_id);
6586 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6587 "Mesh for peer [%s] starting\n",
6588 GNUNET_i2s(&my_full_id));
6590 core_handle = GNUNET_CORE_connect (c, /* Main configuration */
6591 NULL, /* Closure passed to MESH functions */
6592 &core_init, /* Call core_init once connected */
6593 &core_connect, /* Handle connects */
6594 &core_disconnect, /* remove peers on disconnects */
6595 NULL, /* Don't notify about all incoming messages */
6596 GNUNET_NO, /* For header only in notification */
6597 NULL, /* Don't notify about all outbound messages */
6598 GNUNET_NO, /* For header-only out notification */
6599 core_handlers); /* Register these handlers */
6600 if (NULL == core_handle)
6603 GNUNET_SCHEDULER_shutdown ();
6606 announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
6607 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
6612 * The main function for the mesh service.
6614 * @param argc number of arguments from the command line
6615 * @param argv command line arguments
6616 * @return 0 ok, 1 on error
6619 main (int argc, char *const *argv)
6624 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
6625 r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
6627 ret = (GNUNET_OK == r) ? 0 : 1;
6628 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");