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 previous hop in a connection
1229 * @param c Connection.
1231 * @return Previous peer in the connection.
1233 static struct MeshPeer *
1234 connection_get_prev_hop (struct MeshConnection *c)
1238 if (0 == c->own_pos || c->path->length < 2)
1239 id = c->path->peers[0];
1241 id = c->path->peers[c->own_pos - 1];
1243 return peer_get_short (id);
1248 * Get the next hop in a connection
1250 * @param c Connection.
1252 * @return Next peer in the connection.
1254 static struct MeshPeer *
1255 connection_get_next_hop (struct MeshConnection *c)
1259 if ((c->path->length - 1) == c->own_pos || c->path->length < 2)
1260 id = c->path->peers[c->path->length - 1];
1262 id = c->path->peers[c->own_pos + 1];
1264 return peer_get_short (id);
1269 * Get the hop in a connection.
1271 * @param c Connection.
1272 * @param fwd Next hop?
1274 * @return Next peer in the connection.
1276 static struct MeshPeer *
1277 connection_get_hop (struct MeshConnection *c, int fwd)
1280 return connection_get_next_hop (c);
1281 return connection_get_prev_hop (c);
1285 * Check if client has registered with the service and has not disconnected
1287 * @param client the client to check
1289 * @return non-NULL if client exists in the global DLL
1291 static struct MeshClient *
1292 client_get (struct GNUNET_SERVER_Client *client)
1294 return GNUNET_SERVER_client_get_user_context (client, struct MeshClient);
1299 * Deletes a tunnel from a client (either owner or destination).
1301 * @param c Client whose tunnel to delete.
1302 * @param ch Channel which should be deleted.
1305 client_delete_channel (struct MeshClient *c, struct MeshChannel *ch)
1311 res = GNUNET_CONTAINER_multihashmap32_remove (c->own_channels,
1313 if (GNUNET_YES != res)
1314 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client_delete_channel owner KO\n");
1318 res = GNUNET_CONTAINER_multihashmap32_remove (c->incoming_channels,
1320 if (GNUNET_YES != res)
1321 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client_delete_tunnel client KO\n");
1327 * Notify the appropriate client that a new incoming channel was created.
1329 * @param ch Channel that was created.
1332 send_local_channel_create (struct MeshChannel *ch)
1334 struct GNUNET_MESH_ChannelMessage msg;
1335 struct MeshTunnel2 *t = ch->t;
1337 if (NULL == ch->dest)
1339 msg.header.size = htons (sizeof (msg));
1340 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
1341 msg.channel_id = htonl (ch->lid_dest);
1342 msg.port = htonl (ch->port);
1344 msg.opt |= GNUNET_YES == ch->reliable ? GNUNET_MESH_OPTION_RELIABLE : 0;
1345 msg.opt |= GNUNET_YES == ch->nobuffer ? GNUNET_MESH_OPTION_NOBUFFER : 0;
1346 msg.opt = htonl (msg.opt);
1347 GNUNET_PEER_resolve (t->peer->id, &msg.peer);
1348 GNUNET_SERVER_notification_context_unicast (nc, ch->dest->handle,
1349 &msg.header, GNUNET_NO);
1354 * Notify a client that the incoming tunnel is no longer valid.
1356 * @param ch Channel that is destroyed.
1357 * @param fwd Forward notification (owner->dest)?
1360 send_local_channel_destroy (struct MeshChannel *ch, int fwd)
1362 struct GNUNET_MESH_ChannelMessage msg;
1363 struct MeshClient *c;
1365 c = fwd ? ch->dest : ch->root;
1371 msg.header.size = htons (sizeof (msg));
1372 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1373 msg.channel_id = htonl (fwd ? ch->lid_dest : ch->lid_root);
1374 msg.port = htonl (0);
1375 memset (&msg.peer, 0, sizeof (msg.peer));
1376 msg.opt = htonl (0);
1377 GNUNET_SERVER_notification_context_unicast (nc, c->handle,
1378 &msg.header, GNUNET_NO);
1383 * Build a local ACK message and send it to a local client.
1385 * @param ch Channel on which to send the ACK.
1386 * @param c Client to whom send the ACK.
1387 * @param is_fwd Set to GNUNET_YES for FWD ACK (dest->owner)
1390 send_local_ack (struct MeshChannel *ch,
1391 struct MeshClient *c,
1394 struct GNUNET_MESH_LocalAck msg;
1396 msg.header.size = htons (sizeof (msg));
1397 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
1398 msg.channel_id = htonl (is_fwd ? ch->lid_root : ch->lid_dest);
1399 GNUNET_SERVER_notification_context_unicast (nc,
1407 * Count established (ready) connections of a tunnel.
1409 * @param t Tunnel on which to send the message.
1411 * @return Number of connections.
1414 tunnel_count_connections (struct MeshTunnel2 *t)
1416 struct MeshConnection *c;
1419 for (c = t->connection_head, i = 0; NULL != c; c = c->next, i++);
1426 * Pick a connection on which send the next data message.
1428 * @param t Tunnel on which to send the message.
1429 * @param fwd Is this a fwd message?
1431 * @return The connection on which to send the next message.
1433 static struct MeshConnection *
1434 tunnel_get_connection (struct MeshTunnel2 *t, int fwd)
1436 struct MeshConnection *c;
1437 struct MeshConnection *best;
1438 struct MeshFlowControl *fc;
1439 unsigned int lowest_q;
1442 lowest_q = UINT_MAX;
1443 for (c = t->connection_head; NULL != c; c = c->next)
1445 if (MESH_CONNECTION_READY == c->state)
1447 fc = fwd ? &c->fwd_fc : &c->bck_fc;
1453 if (fc->queue_n < lowest_q)
1456 lowest_q = fc->queue_n;
1465 * Get the total buffer space for a tunnel
1468 tunnel_get_buffer (struct MeshTunnel2 *t, int fwd)
1470 struct MeshConnection *c;
1471 struct MeshFlowControl *fc;
1472 unsigned int buffer;
1474 for (buffer = 0, c = t->connection_head; NULL != c; c = c->next)
1476 if (c->state != MESH_CONNECTION_READY)
1479 fc = fwd ? &c->fwd_fc : &c->bck_fc;
1480 buffer += fc->last_ack_recv - fc->last_pid_sent;
1488 * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
1489 * Encrypt data with the tunnel key.
1491 * @param t Tunnel whose key to use.
1492 * @param dst Destination for the encrypted data.
1493 * @param src Source of the plaintext.
1494 * @param size Size of the plaintext.
1495 * @param iv Initialization Vector to use.
1496 * @param fwd Is this a fwd message?
1499 tunnel_encrypt (struct MeshTunnel2 *t,
1500 void *dst, const void *src,
1501 size_t size, uint64_t iv, int fwd)
1503 memcpy (dst, src, size);
1508 * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
1509 * Decrypt data with the tunnel key.
1511 * @param t Tunnel whose key to use.
1512 * @param dst Destination for the plaintext.
1513 * @param src Source of the encrypted data.
1514 * @param size Size of the encrypted data.
1515 * @param iv Initialization Vector to use.
1516 * @param fwd Is this a fwd message?
1519 tunnel_decrypt (struct MeshTunnel2 *t,
1520 void *dst, const void *src,
1521 size_t size, uint64_t iv, int fwd)
1523 memcpy (dst, src, size);
1528 * Sends an already built message on a connection, properly registering
1529 * all used resources.
1531 * @param message Message to send. Function makes a copy of it.
1532 * If message is not hop-by-hop, decrements TTL of copy.
1533 * @param c Connection on which this message is transmitted.
1534 * @param ch Channel on which this message is transmitted, or NULL.
1535 * @param fwd Is this a fwd message?
1538 send_prebuilt_message_connection (const struct GNUNET_MessageHeader *message,
1539 struct MeshConnection *c,
1540 struct MeshChannel *ch,
1543 struct MeshPeer *neighbor;
1548 neighbor = connection_get_hop (c, fwd);
1549 if (NULL == neighbor)
1555 size = ntohs (message->size);
1556 data = GNUNET_malloc (size);
1557 memcpy (data, message, size);
1558 type = ntohs(message->type);
1560 if (GNUNET_MESSAGE_TYPE_MESH_FWD == type ||
1561 GNUNET_MESSAGE_TYPE_MESH_BCK == type)
1563 struct GNUNET_MESH_Encrypted *msg;
1566 msg = (struct GNUNET_MESH_Encrypted *) data;
1567 ttl = ntohl (msg->ttl);
1570 GNUNET_break_op (0);
1573 msg->ttl = htonl (ttl - 1);
1586 * Sends an already built message on a tunnel, choosing the best connection.
1588 * @param message Message to send. Function modifies it.
1589 * @param t Tunnel on which this message is transmitted.
1590 * @param ch Channel on which this message is transmitted.
1591 * @param fwd Is this a fwd message?
1594 send_prebuilt_message_tunnel (struct GNUNET_MESH_Encrypted *msg,
1595 struct MeshTunnel2 *t,
1596 struct MeshChannel *ch,
1599 struct MeshConnection *c;
1602 c = tunnel_get_connection (t, fwd);
1608 type = ntohs (msg->header.size);
1611 case GNUNET_MESSAGE_TYPE_MESH_FWD:
1612 case GNUNET_MESSAGE_TYPE_MESH_BCK:
1613 msg->cid = htonl (c->id);
1615 msg->ttl = default_ttl;
1621 send_prebuilt_message_connection (&msg->header, c, ch, fwd);
1626 * Sends an already built message on a channel, properly registering
1627 * all used resources and encrypting the message with the tunnel's key.
1629 * @param message Message to send. Function makes a copy of it.
1630 * @param ch Channel on which this message is transmitted.
1631 * @param fwd Is this a fwd message?
1634 send_prebuilt_message_channel (const struct GNUNET_MessageHeader *message,
1635 struct MeshChannel *ch,
1638 struct GNUNET_MESH_Encrypted *msg;
1639 size_t size = ntohs (message->size);
1640 char *cbuf[size + sizeof (struct GNUNET_MESH_Encrypted)];
1644 type = fwd ? GNUNET_MESSAGE_TYPE_MESH_FWD : GNUNET_MESSAGE_TYPE_MESH_BCK;
1645 iv = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
1647 msg = (struct GNUNET_MESH_Encrypted *) cbuf;
1648 msg->header.type = htons (type);
1649 msg->header.size = htons (size);
1650 msg->iv = GNUNET_htonll (iv);
1651 tunnel_encrypt (ch->t, &msg[1], message, size, iv, fwd);
1653 send_prebuilt_message_tunnel (msg, ch->t, ch, fwd);
1658 * Sends a CREATE CONNECTION message for a path to a peer.
1659 * Changes the connection and tunnel states if necessary.
1661 * @param connection Connection to create.
1664 send_connection_create (struct MeshConnection *connection)
1666 struct MeshPeer *neighbor;
1667 struct MeshTunnel2 *t;
1670 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send connection create\n");
1671 neighbor = connection_get_next_hop (connection);
1672 queue_add (connection,
1673 GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
1674 sizeof (struct GNUNET_MESH_ConnectionCreate) +
1675 (connection->path->length *
1676 sizeof (struct GNUNET_PeerIdentity)),
1680 if (MESH_TUNNEL_SEARCHING == t->state)
1681 tunnel_change_state (t, MESH_TUNNEL_WAITING);
1682 if (MESH_CONNECTION_NEW == connection->state)
1683 connection_change_state (connection, MESH_CONNECTION_SENT);
1688 * Sends a CONNECTION ACK message in reponse to a received CONNECTION_CREATE
1691 * @param connection Connection to confirm.
1694 send_connection_ack (struct MeshConnection *connection)
1696 struct MeshPeer *neighbor;
1697 struct MeshTunnel2 *t;
1700 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send connection ack\n");
1701 neighbor = connection_get_prev_hop (connection);
1702 queue_add (connection,
1703 GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
1704 sizeof (struct GNUNET_MESH_ConnectionACK),
1708 if (MESH_TUNNEL_NEW == t->state)
1709 tunnel_change_state (t, MESH_TUNNEL_WAITING);
1714 * Build a hop-by-hop ACK message and queue it to send for the given connection.
1716 * @param c Which connection to send the hop-by-hop ACK.
1717 * @param ack Value of the ACK.
1718 * @param fwd Is this fwd?
1721 send_ack (struct MeshConnection *c, uint32_t ack, int fwd)
1723 struct GNUNET_MESH_ACK msg;
1725 msg.header.size = htons (sizeof (msg));
1726 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ACK);
1727 msg.ack = htonl (ack);
1729 msg.cid = htonl (c->id);
1731 send_prebuilt_message_connection (&msg.header, c, NULL, fwd);
1736 * Core callback to write a pre-constructed data packet to core buffer
1738 * @param cls Closure (MeshTransmissionDescriptor with data in "data" member).
1739 * @param size Number of bytes available in buf.
1740 * @param buf Where the to write the message.
1742 * @return number of bytes written to buf
1745 send_core_data_raw (void *cls, size_t size, void *buf)
1747 struct GNUNET_MessageHeader *msg = cls;
1750 GNUNET_assert (NULL != msg);
1751 total_size = ntohs (msg->size);
1753 if (total_size > size)
1758 memcpy (buf, msg, total_size);
1765 * Function to send a create path packet to a peer.
1767 * @param cls closure
1768 * @param size number of bytes available in buf
1769 * @param buf where the callee should write the message
1770 * @return number of bytes written to buf
1773 send_core_connection_create (void *cls, size_t size, void *buf)
1775 struct MeshConnection *c = cls;
1776 struct GNUNET_MESH_ConnectionCreate *msg;
1777 struct GNUNET_PeerIdentity *peer_ptr;
1778 struct MeshPeerPath *p = c->path;
1782 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION CREATE...\n");
1784 sizeof (struct GNUNET_MESH_ConnectionCreate) +
1785 p->length * sizeof (struct GNUNET_PeerIdentity);
1787 if (size < size_needed || NULL == buf)
1792 msg = (struct GNUNET_MESH_ConnectionCreate *) buf;
1793 msg->header.size = htons (size_needed);
1794 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE);
1795 msg->cid = htonl (c->id);
1797 peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
1798 for (i = 0; i < p->length; i++)
1800 GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
1803 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1804 "CONNECTION CREATE (%u bytes long) sent!\n", size_needed);
1810 * Creates a path ack message in buf and frees all unused resources.
1812 * @param cls closure (MeshTransmissionDescriptor)
1813 * @param size number of bytes available in buf
1814 * @param buf where the callee should write the message
1815 * @return number of bytes written to buf
1818 send_core_connection_ack (void *cls, size_t size, void *buf)
1820 struct GNUNET_MESH_ConnectionACK *msg = buf;
1821 struct MeshConnection *c = cls;
1822 struct MeshTunnel2 *t = c->t;
1824 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION ACK...\n");
1825 GNUNET_assert (NULL != t);
1826 if (sizeof (struct GNUNET_MESH_ConnectionACK) > size)
1831 msg->header.size = htons (sizeof (struct GNUNET_MESH_ConnectionACK));
1832 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK);
1833 GNUNET_CRYPTO_hash_xor (&GNUNET_PEER_resolve2 (t->peer->id)->hashPubKey,
1834 &my_full_id.hashPubKey,
1836 msg->cid = htonl (c->id);
1838 /* TODO add signature */
1840 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CONNECTION ACK sent!\n");
1841 return sizeof (struct GNUNET_MESH_ConnectionACK);
1846 * Destroy the peer_info and free any allocated resources linked to it
1848 * @param peer The peer_info to destroy.
1850 * @return GNUNET_OK on success
1853 peer_destroy (struct MeshPeer *peer)
1855 struct GNUNET_PeerIdentity id;
1856 struct MeshPeerPath *p;
1857 struct MeshPeerPath *nextp;
1859 GNUNET_PEER_resolve (peer->id, &id);
1860 GNUNET_PEER_change_rc (peer->id, -1);
1863 GNUNET_CONTAINER_multihashmap_remove (peers, &id.hashPubKey, peer))
1866 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1867 "removing peer %s, not in hashmap\n", GNUNET_i2s (&id));
1869 if (NULL != peer->dhtget)
1871 GNUNET_DHT_get_stop (peer->dhtget);
1873 p = peer->path_head;
1877 GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
1881 tunnel_destroy_empty (peer->tunnel);
1888 * Returns if peer is used (has a tunnel, is neighbor).
1890 * @peer Peer to check.
1892 * @return GNUNET_YES if peer is in use.
1895 peer_is_used (struct MeshPeer *peer)
1897 struct MeshPeerPath *p;
1899 if (NULL != peer->tunnel)
1902 for (p = peer->path_head; NULL != p; p = p->next)
1911 * Iterator over all the peers to get the oldest timestamp.
1913 * @param cls Closure (unsued).
1914 * @param key ID of the peer.
1915 * @param value Peer_Info of the peer.
1918 peer_get_oldest (void *cls,
1919 const struct GNUNET_HashCode *key,
1922 struct MeshPeer *p = value;
1923 struct GNUNET_TIME_Absolute *abs = cls;
1925 /* Don't count active peers */
1926 if (GNUNET_YES == peer_is_used (p))
1929 if (abs->abs_value < p->last_contact.abs_value)
1930 abs->abs_value = p->last_contact.abs_value;
1937 * Iterator over all the peers to remove the oldest entry.
1939 * @param cls Closure (unsued).
1940 * @param key ID of the peer.
1941 * @param value Peer_Info of the peer.
1944 peer_timeout (void *cls,
1945 const struct GNUNET_HashCode *key,
1948 struct MeshPeer *p = value;
1949 struct GNUNET_TIME_Absolute *abs = cls;
1951 if (p->last_contact.abs_value == abs->abs_value &&
1952 GNUNET_NO == peer_is_used (p))
1962 * Delete oldest unused peer.
1965 peer_delete_oldest (void)
1967 struct GNUNET_TIME_Absolute abs;
1969 abs = GNUNET_TIME_UNIT_FOREVER_ABS;
1971 GNUNET_CONTAINER_multihashmap_iterate (peers,
1974 GNUNET_CONTAINER_multihashmap_iterate (peers,
1981 * Retrieve the MeshPeer stucture associated with the peer, create one
1982 * and insert it in the appropriate structures if the peer is not known yet.
1984 * @param peer Full identity of the peer.
1986 * @return Existing or newly created peer info.
1988 static struct MeshPeer *
1989 peer_get (const struct GNUNET_PeerIdentity *peer_id)
1991 struct MeshPeer *peer;
1993 peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer_id->hashPubKey);
1996 peer = GNUNET_new (struct MeshPeer);
1997 if (GNUNET_CONTAINER_multihashmap_size (peers) > max_peers)
1999 peer_delete_oldest ();
2001 GNUNET_CONTAINER_multihashmap_put (peers, &peer_id->hashPubKey, peer,
2002 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
2003 peer->id = GNUNET_PEER_intern (peer_id);
2005 peer->last_contact = GNUNET_TIME_absolute_get();
2012 * Retrieve the MeshPeer stucture associated with the peer, create one
2013 * and insert it in the appropriate structures if the peer is not known yet.
2015 * @param peer Short identity of the peer.
2017 * @return Existing or newly created peer info.
2019 static struct MeshPeer *
2020 peer_get_short (const GNUNET_PEER_Id peer)
2022 return peer_get (GNUNET_PEER_resolve2 (peer));
2027 * Get a cost of a path for a peer considering existing tunnel connections.
2029 * @param peer Peer towards which the path is considered.
2030 * @param path Candidate path.
2032 * @return Cost of the path (path length + number of overlapping nodes)
2035 peer_get_path_cost (const struct MeshPeer *peer,
2036 const struct MeshPeerPath *path)
2038 struct MeshConnection *c;
2039 unsigned int overlap;
2047 GNUNET_assert (NULL != peer->tunnel);
2049 for (i = 0; i < path->length; i++)
2051 for (c = peer->tunnel->connection_head; NULL != c; c = c->next)
2053 for (j = 0; j < c->path->length; j++)
2055 if (path->peers[i] == c->path->peers[j])
2063 return (path->length + overlap) * (path->score * -1);
2068 * Choose the best path towards a peer considering the tunnel properties.
2070 * @param peer The destination peer.
2072 * @return Best current known path towards the peer, if any.
2074 static struct MeshPeerPath *
2075 peer_get_best_path (const struct MeshPeer *peer)
2077 struct MeshPeerPath *best_p;
2078 struct MeshPeerPath *p;
2079 struct MeshConnection *c;
2080 unsigned int best_cost;
2083 best_cost = UINT_MAX;
2085 for (p = peer->path_head; NULL != p; p = p->next)
2087 for (c = peer->tunnel->connection_head; NULL != c; c = c->next)
2091 continue; /* If path is in use in a connection, skip it. */
2093 if ((cost = peer_get_path_cost (peer, p)) < best_cost)
2103 queue_is_sendable (struct MeshPeerQueue *q)
2105 struct MeshFlowControl *fc;
2107 /* Is PID-independent? */
2110 case GNUNET_MESSAGE_TYPE_MESH_ACK:
2111 case GNUNET_MESSAGE_TYPE_MESH_POLL:
2115 /* Is PID allowed? */
2116 fc = q->fwd ? &q->c->fwd_fc : &q->c->bck_fc;
2117 if (GMC_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
2125 * Get first sendable message.
2127 * @param peer The destination peer.
2129 * @return Best current known path towards the peer, if any.
2131 static struct MeshPeerQueue *
2132 peer_get_first_message (const struct MeshPeer *peer)
2134 struct MeshPeerQueue *q;
2136 for (q = peer->queue_head; NULL != q; q = q->next)
2138 if (queue_is_sendable (q))
2147 * Try to establish a new connection to this peer in the given tunnel.
2148 * If the peer doesn't have any path to it yet, try to get one.
2149 * If the peer already has some path, send a CREATE CONNECTION towards it.
2151 * @param peer PeerInfo of the peer.
2154 peer_connect (struct MeshPeer *peer)
2156 struct MeshTunnel2 *t;
2157 struct MeshPeerPath *p;
2158 struct MeshConnection *c;
2161 if (NULL != peer->path_head)
2163 p = peer_get_best_path (peer);
2166 c = tunnel_use_path (t, p);
2167 send_connection_create (c);
2170 else if (NULL == peer->dhtget)
2172 const struct GNUNET_PeerIdentity *id;
2174 id = GNUNET_PEER_resolve2 (peer->id);
2175 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2176 " Starting DHT GET for peer %s\n", GNUNET_i2s (id));
2177 peer->dhtget = GNUNET_DHT_get_start (dht_handle, /* handle */
2178 GNUNET_BLOCK_TYPE_MESH_PEER, /* type */
2179 &id->hashPubKey, /* key to search */
2180 dht_replication_level, /* replication level */
2181 GNUNET_DHT_RO_RECORD_ROUTE |
2182 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
2184 0, /* xquery bits */
2185 &dht_get_id_handler, peer);
2186 if (MESH_TUNNEL_NEW == t->state)
2187 tunnel_change_state (t, MESH_TUNNEL_SEARCHING);
2191 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2192 "There is no path but the DHT GET is already started.\n");
2198 * Get the first transmittable message for a connection.
2200 * @param c Connection.
2201 * @param fwd Is this FWD?
2203 * @return First transmittable message.
2205 static struct MeshPeerQueue *
2206 connection_get_first_message (struct MeshConnection *c, int fwd)
2208 struct MeshPeerQueue *q;
2211 p = connection_get_hop (c, fwd);
2213 for (q = p->queue_head; NULL != q; q = q->next)
2217 if (queue_is_sendable (q))
2227 * @brief Re-initiate traffic on this connection if necessary.
2229 * Check if there is traffic queued towards this peer
2230 * and the core transmit handle is NULL (traffic was stalled).
2231 * If so, call core tmt rdy.
2233 * @param c Connection on which initiate traffic.
2234 * @param fwd Is this about fwd traffic?
2237 connection_unlock_queue (struct MeshConnection *c, int fwd)
2239 struct MeshPeer *peer;
2240 struct MeshPeerQueue *q;
2243 peer = connection_get_hop (c, fwd);
2245 if (NULL != peer->core_transmit)
2246 return; /* Already unlocked */
2248 q = connection_get_first_message (c, fwd);
2250 return; /* Nothing to transmit */
2253 peer->core_transmit =
2254 GNUNET_CORE_notify_transmit_ready (core_handle,
2257 GNUNET_TIME_UNIT_FOREVER_REL,
2258 GNUNET_PEER_resolve2 (peer->id),
2266 * Cancel all transmissions that belong to a certain connection.
2268 * @param c Connection which to cancel.
2269 * @param fwd Cancel fwd traffic?
2272 connection_cancel_queues (struct MeshConnection *c, int fwd)
2274 struct MeshPeerQueue *q;
2275 struct MeshPeerQueue *next;
2276 struct MeshFlowControl *fc;
2277 struct MeshPeer *peer;
2284 fc = fwd ? &c->fwd_fc : &c->bck_fc;
2285 peer = connection_get_hop (c, fwd);
2287 for (q = peer->queue_head; NULL != q; q = next)
2292 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2293 "connection_cancel_queue %s\n",
2294 GNUNET_MESH_DEBUG_M2S (q->type));
2295 queue_destroy (q, GNUNET_YES);
2298 if (NULL == peer->queue_head)
2300 if (NULL != peer->core_transmit)
2302 GNUNET_CORE_notify_transmit_ready_cancel (peer->core_transmit);
2303 peer->core_transmit = NULL;
2305 if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
2307 GNUNET_SCHEDULER_cancel (fc->poll_task);
2308 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2315 * Remove all paths that rely on a direct connection between p1 and p2
2316 * from the peer itself and notify all tunnels about it.
2318 * @param peer PeerInfo of affected peer.
2319 * @param p1 GNUNET_PEER_Id of one peer.
2320 * @param p2 GNUNET_PEER_Id of another peer that was connected to the first and
2323 * TODO: optimize (see below)
2326 peer_remove_path (struct MeshPeer *peer, GNUNET_PEER_Id p1,
2329 struct MeshPeerPath *p;
2330 struct MeshPeerPath *next;
2331 struct MeshPeer *peer_d;
2333 unsigned int destroyed;
2336 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path\n");
2338 for (p = peer->path_head; NULL != p; p = next)
2341 for (i = 0; i < (p->length - 1); i++)
2343 if ((p->peers[i] == p1 && p->peers[i + 1] == p2) ||
2344 (p->peers[i] == p2 && p->peers[i + 1] == p1))
2346 GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
2357 d = tunnel_notify_connection_broken (peer->tunnel, p1, p2);
2359 peer_d = peer_get_short (d); // FIXME
2360 next = peer_get_best_path (peer_d);
2361 tunnel_use_path (peer->tunnel, next);
2362 peer_connect (peer_d);
2364 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path END\n");
2369 * Add the path to the peer and update the path used to reach it in case this
2372 * @param peer_info Destination peer to add the path to.
2373 * @param path New path to add. Last peer must be the peer in arg 1.
2374 * Path will be either used of freed if already known.
2375 * @param trusted Do we trust that this path is real?
2378 peer_add_path (struct MeshPeer *peer_info, struct MeshPeerPath *path,
2381 struct MeshPeerPath *aux;
2385 if ((NULL == peer_info) || (NULL == path))
2388 path_destroy (path);
2391 if (path->peers[path->length - 1] != peer_info->id)
2394 path_destroy (path);
2397 if (2 >= path->length && GNUNET_NO == trusted)
2399 /* Only allow CORE to tell us about direct paths */
2400 path_destroy (path);
2403 for (l = 1; l < path->length; l++)
2405 if (path->peers[l] == myid)
2407 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shortening path by %u\n", l);
2408 for (l2 = 0; l2 < path->length - l; l2++)
2410 path->peers[l2] = path->peers[l + l2];
2415 GNUNET_realloc (path->peers, path->length * sizeof (GNUNET_PEER_Id));
2420 struct GNUNET_PeerIdentity id;
2422 GNUNET_PEER_resolve (peer_info->id, &id);
2423 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "adding path [%u] to peer %s\n",
2424 path->length, GNUNET_i2s (&id));
2427 l = path_get_length (path);
2430 path_destroy (path);
2434 GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
2435 for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
2437 l2 = path_get_length (aux);
2440 GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
2441 peer_info->path_tail, aux, path);
2446 if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
2448 path_destroy (path);
2453 GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head, peer_info->path_tail,
2460 * Add the path to the origin peer and update the path used to reach it in case
2461 * this is the shortest.
2462 * The path is given in peer_info -> destination, therefore we turn the path
2463 * upside down first.
2465 * @param peer_info Peer to add the path to, being the origin of the path.
2466 * @param path New path to add after being inversed.
2467 * Path will be either used or freed.
2468 * @param trusted Do we trust that this path is real?
2471 peer_add_path_to_origin (struct MeshPeer *peer_info,
2472 struct MeshPeerPath *path, int trusted)
2475 peer_add_path (peer_info, path, trusted);
2481 * Function called if a connection has been stalled for a while,
2482 * possibly due to a missed ACK. Poll the neighbor about its ACK status.
2484 * @param cls Closure (poll ctx).
2485 * @param tc TaskContext.
2488 connection_poll (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2490 struct MeshFlowControl *fc = cls;
2491 struct GNUNET_MESH_Poll msg;
2492 struct MeshConnection *c;
2494 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2495 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2501 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** Polling!\n");
2502 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** connection %s[%X]\n",
2503 GNUNET_i2s (GNUNET_PEER_resolve2 (c->t->peer->id)), c->id);
2505 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_POLL);
2506 msg.header.size = htons (sizeof (msg));
2507 msg.pid = htonl (fc->last_pid_sent);
2508 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** pid (%u)!\n", fc->last_pid_sent);
2509 send_prebuilt_message_connection (&msg.header, c, NULL, fc == &c->fwd_fc);
2510 fc->poll_time = GNUNET_TIME_STD_BACKOFF (fc->poll_time);
2511 fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
2512 &connection_poll, fc);
2517 * Build a PeerPath from the paths returned from the DHT, reversing the paths
2518 * to obtain a local peer -> destination path and interning the peer ids.
2520 * @return Newly allocated and created path
2522 static struct MeshPeerPath *
2523 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
2524 unsigned int get_path_length,
2525 const struct GNUNET_PeerIdentity *put_path,
2526 unsigned int put_path_length)
2528 struct MeshPeerPath *p;
2534 GNUNET_PEER_change_rc (myid, 1);
2535 i = get_path_length;
2536 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " GET has %d hops.\n", i);
2537 for (i--; i >= 0; i--)
2539 id = GNUNET_PEER_intern (&get_path[i]);
2540 if (p->length > 0 && id == p->peers[p->length - 1])
2542 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Optimizing 1 hop out.\n");
2543 GNUNET_PEER_change_rc (id, -1);
2547 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Adding from GET: %s.\n",
2548 GNUNET_i2s (&get_path[i]));
2550 p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2551 p->peers[p->length - 1] = id;
2554 i = put_path_length;
2555 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " PUT has %d hops.\n", i);
2556 for (i--; i >= 0; i--)
2558 id = GNUNET_PEER_intern (&put_path[i]);
2561 /* PUT path went through us, so discard the path up until now and start
2562 * from here to get a much shorter (and loop-free) path.
2567 if (p->length > 0 && id == p->peers[p->length - 1])
2569 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Optimizing 1 hop out.\n");
2570 GNUNET_PEER_change_rc (id, -1);
2574 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Adding from PUT: %s.\n",
2575 GNUNET_i2s (&put_path[i]));
2577 p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2578 p->peers[p->length - 1] = id;
2582 if (get_path_length > 0)
2583 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " (first of GET: %s)\n",
2584 GNUNET_i2s (&get_path[0]));
2585 if (put_path_length > 0)
2586 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " (first of PUT: %s)\n",
2587 GNUNET_i2s (&put_path[0]));
2588 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " In total: %d hops\n",
2590 for (i = 0; i < p->length; i++)
2592 struct GNUNET_PeerIdentity peer_id;
2594 GNUNET_PEER_resolve (p->peers[i], &peer_id);
2595 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " %u: %s\n", p->peers[i],
2596 GNUNET_i2s (&peer_id));
2604 * Adds a path to the peer_infos of all the peers in the path
2606 * @param p Path to process.
2607 * @param confirmed Whether we know if the path works or not.
2610 path_add_to_peers (struct MeshPeerPath *p, int confirmed)
2614 /* TODO: invert and add */
2615 for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
2616 for (i++; i < p->length; i++)
2618 struct MeshPeer *aux;
2619 struct MeshPeerPath *copy;
2621 aux = peer_get_short (p->peers[i]);
2622 copy = path_duplicate (p);
2623 copy->length = i + 1;
2624 peer_add_path (aux, copy, p->length < 3 ? GNUNET_NO : confirmed);
2630 * Search for a channel among the channels for a client
2632 * @param c the client whose channels to search in
2633 * @param chid the local id of the channel
2635 * @return channel handler, NULL if doesn't exist
2637 static struct MeshChannel *
2638 channel_get_by_local_id (struct MeshClient *c, MESH_ChannelNumber chid)
2640 if (0 == (chid & GNUNET_MESH_LOCAL_CHANNEL_ID_CLI))
2642 GNUNET_break_op (0);
2643 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CHID %X not a local chid\n", chid);
2646 if (chid >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV)
2647 return GNUNET_CONTAINER_multihashmap32_get (c->incoming_channels, chid);
2648 return GNUNET_CONTAINER_multihashmap32_get (c->own_channels, chid);
2652 * Search for a tunnel by global ID using full PeerIdentities.
2654 * @param t Tunnel containing the channel.
2655 * @param chid Public channel number.
2657 * @return channel handler, NULL if doesn't exist
2659 static struct MeshChannel *
2660 channel_get (struct MeshTunnel2 *t, MESH_ChannelNumber chid)
2662 struct MeshChannel *ch;
2667 for (ch = t->channel_head; NULL != ch; ch = ch->next)
2669 if (ch->gid == chid)
2678 * Change the tunnel state.
2680 * @param t Tunnel whose state to change.
2681 * @param state New state.
2684 tunnel_change_state (struct MeshTunnel2* t, enum MeshTunnelState state)
2686 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2687 "Tunnel %s state was %s\n",
2688 GNUNET_i2s (GNUNET_PEER_resolve2 (t->peer->id)),
2689 GNUNET_MESH_DEBUG_TS2S (t->state));
2690 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2691 "Tunnel %s state is now %s\n",
2692 GNUNET_i2s (GNUNET_PEER_resolve2 (t->peer->id)),
2693 GNUNET_MESH_DEBUG_TS2S (state));
2699 connection_change_state (struct MeshConnection* c,
2700 enum MeshConnectionState state)
2702 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2703 "Connection %s[%X] state was %s\n",
2704 GNUNET_i2s (GNUNET_PEER_resolve2 (c->t->peer->id)), c->id,
2705 GNUNET_MESH_DEBUG_CS2S (c->state));
2706 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2707 "Connection %s[%X] state is now %s\n",
2708 GNUNET_i2s (GNUNET_PEER_resolve2 (c->t->peer->id)), c->id,
2709 GNUNET_MESH_DEBUG_CS2S (state));
2715 * Add a client to a channel, initializing all needed data structures.
2717 * @param ch Channel to which add the client.
2718 * @param c Client which to add to the channel.
2721 channel_add_client (struct MeshChannel *ch, struct MeshClient *c)
2723 struct MeshTunnel2 *t = ch->t;
2725 if (NULL != ch->dest)
2731 /* Assign local id as destination */
2732 while (NULL != channel_get_by_local_id (c, t->next_local_chid))
2733 t->next_local_chid = (t->next_local_chid + 1) | GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
2734 ch->lid_dest = t->next_local_chid++;
2735 t->next_local_chid = t->next_local_chid | GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
2737 /* Store in client's hashmap */
2739 GNUNET_CONTAINER_multihashmap32_put (c->incoming_channels,
2741 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2750 static struct MeshConnection *
2751 tunnel_use_path (struct MeshTunnel2 *t, struct MeshPeerPath *p)
2753 struct MeshConnection *c;
2754 unsigned int own_pos;
2756 c = GNUNET_new (struct MeshConnection);
2757 for (own_pos = 0; own_pos < p->length; own_pos++)
2759 if (p->peers[own_pos] == myid)
2762 if (own_pos > p->length - 1)
2767 c->own_pos = own_pos;
2769 c->id = t->next_cid++;
2771 GNUNET_CONTAINER_DLL_insert_tail (t->connection_head, t->connection_tail, c);
2775 c->fwd_maintenance_task =
2776 GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
2777 &connection_fwd_keepalive, c);
2784 * Notifies a tunnel that a connection has broken that affects at least
2785 * some of its peers. Sends a notification towards the root of the tree.
2786 * In case the peer is the owner of the tree, notifies the client that owns
2787 * the tunnel and tries to reconnect.
2789 * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
2791 * @param t Tunnel affected.
2792 * @param p1 Peer that got disconnected from p2.
2793 * @param p2 Peer that got disconnected from p1.
2795 * @return Short ID of the peer disconnected (either p1 or p2).
2796 * 0 if the tunnel remained unaffected.
2798 static GNUNET_PEER_Id
2799 tunnel_notify_connection_broken (struct MeshTunnel2* t,
2800 GNUNET_PEER_Id p1, GNUNET_PEER_Id p2)
2802 // if (myid != p1 && myid != p2) FIXME
2807 // if (tree_get_predecessor (t->tree) != 0)
2809 // /* We are the peer still connected, notify owner of the disconnection. */
2810 // struct GNUNET_MESH_PathBroken msg;
2811 // struct GNUNET_PeerIdentity neighbor;
2813 // msg.header.size = htons (sizeof (msg));
2814 // msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN);
2815 // GNUNET_PEER_resolve (t->id.oid, &msg.oid);
2816 // msg.tid = htonl (t->id.tid);
2817 // msg.peer1 = my_full_id;
2818 // GNUNET_PEER_resolve (pid, &msg.peer2);
2819 // GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &neighbor);
2820 // send_prebuilt_message (&msg.header, &neighbor, t);
2827 * Send an end-to-end FWD ACK message for the most recent in-sequence payload.
2829 * @param ch Channel this is about.
2830 * @param fwd Is for FWD traffic? (ACK dest->owner)
2833 channel_send_data_ack (struct MeshChannel *ch, int fwd)
2835 struct GNUNET_MESH_DataACK msg;
2836 struct MeshChannelReliability *rel;
2837 struct MeshReliableMessage *copy;
2842 if (GNUNET_NO == ch->reliable)
2847 rel = fwd ? ch->bck_rel : ch->fwd_rel;
2848 mid = fwd ? &ch->mid_recv_fwd : &ch->mid_recv_bck;
2849 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2850 "send_data_ack for %u\n",
2853 msg.header.type = htons (fwd ? GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK :
2854 GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK);
2855 msg.header.size = htons (sizeof (msg));
2856 msg.chid = htonl (ch->gid);
2857 msg.mid = htonl (*mid - 1);
2859 for (copy = rel->head_recv; NULL != copy; copy = copy->next)
2861 delta = copy->mid - *mid;
2864 mask = 0x1LL << delta;
2865 msg.futures |= mask;
2866 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2867 " setting bit for %u (delta %u) (%llX) -> %llX\n",
2868 copy->mid, delta, mask, msg.futures);
2870 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " final futures %llX\n", msg.futures);
2872 send_prebuilt_message_channel (&msg.header, ch, fwd);
2873 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_data_ack END\n");
2878 * Send an ACK informing the predecessor about the available buffer space.
2880 * Note that for fwd ack, the FWD mean forward *traffic* (root->dest),
2881 * the ACK itself goes "back" (dest->root).
2883 * @param c Connection on which to send the ACK.
2884 * @param fwd Is this FWD ACK? (Going dest->owner)
2887 connection_send_ack (struct MeshConnection *c, int fwd)
2889 struct MeshFlowControl *next_fc;
2890 struct MeshFlowControl *prev_fc;
2894 next_fc = fwd ? &c->fwd_fc : &c->bck_fc;
2895 prev_fc = fwd ? &c->bck_fc : &c->fwd_fc;
2897 /* Check if we need to transmit the ACK */
2898 if (prev_fc->last_ack_sent - prev_fc->last_pid_recv > 3)
2900 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer > 3\n");
2901 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2902 " last pid recv: %u, last ack sent: %u\n",
2903 prev_fc->last_pid_recv, prev_fc->last_ack_sent);
2907 /* Ok, ACK might be necessary, what PID to ACK? */
2908 delta = next_fc->queue_max - next_fc->queue_n;
2909 ack = prev_fc->last_pid_recv + delta;
2910 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", ack);
2911 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2912 " last pid %u, last ack %u, qmax %u, q %u\n",
2913 prev_fc->last_pid_recv, prev_fc->last_ack_sent,
2914 next_fc->queue_max, next_fc->queue_n);
2915 if (ack == prev_fc->last_ack_sent)
2917 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not needed\n");
2921 prev_fc->last_ack_sent = ack;
2922 send_ack (c, ack, fwd);
2927 * Send an ACK informing the client about available buffer space.
2929 * Note that although the name is fwd_ack, the FWD mean forward *traffic*,
2930 * the ACK itself goes "back" (towards root).
2932 * @param ch Channel on which to send the ACK, NULL if unknown.
2933 * @param fwd Is this FWD ACK? (Going dest->owner)
2936 // channel_send_ack (struct MeshChannel *ch, uint16_t type, int fwd)
2938 // struct MeshChannelReliability *rel;
2939 // struct MeshFlowControl *next_fc;
2940 // struct MeshFlowControl *prev_fc;
2941 // struct MeshClient *c;
2942 // struct MeshClient *o;
2943 // GNUNET_PEER_Id hop;
2944 // uint32_t delta_mid;
2948 // rel = fwd ? ch->fwd_rel : ch->bck_rel;
2949 // c = fwd ? ch->client : ch->owner;
2950 // o = fwd ? ch->owner : ch->client;
2951 // hop = fwd ? connection_get_prev_hop (cn) : connection_get_next_hop (cn);
2952 // next_fc = fwd ? &t->next_fc : &t->prev_fc;
2953 // prev_fc = fwd ? &t->prev_fc : &t->next_fc;
2957 // case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
2958 // case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
2959 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2960 // "ACK due to %s\n",
2961 // GNUNET_MESH_DEBUG_M2S (type));
2962 // if (GNUNET_YES == t->nobuffer && (GNUNET_NO == t->reliable || NULL == c))
2964 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, nobuffer\n");
2967 // if (GNUNET_YES == t->reliable && NULL != c)
2968 // tunnel_send_data_ack (t, fwd);
2970 // case GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK:
2971 // case GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK:
2972 // case GNUNET_MESSAGE_TYPE_MESH_ACK:
2973 // case GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK:
2975 // case GNUNET_MESSAGE_TYPE_MESH_POLL:
2976 // case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
2977 // t->force_ack = GNUNET_YES;
2980 // GNUNET_break (0);
2983 // /* Check if we need to transmit the ACK */
2985 // prev_fc->last_ack_sent - prev_fc->last_pid_recv > 3 &&
2986 // GNUNET_NO == t->force_ack)
2988 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer free\n");
2989 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2990 // " last pid recv: %u, last ack sent: %u\n",
2991 // prev_fc->last_pid_recv, prev_fc->last_ack_sent);
2995 // /* Ok, ACK might be necessary, what PID to ACK? */
2996 // delta = t->queue_max - next_fc->queue_n;
2997 // if (NULL != o && GNUNET_YES == t->reliable && NULL != rel->head_sent)
2998 // delta_mid = rel->mid_sent - rel->head_sent->mid;
3001 // if (0 > delta || (GNUNET_YES == t->reliable &&
3003 // (10 < rel->n_sent || 64 <= delta_mid)))
3005 // if (NULL != o && delta > 1)
3007 // ack = prev_fc->last_pid_recv + delta;
3008 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", ack);
3009 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3010 // " last pid %u, last ack %u, qmax %u, q %u\n",
3011 // prev_fc->last_pid_recv, prev_fc->last_ack_sent,
3012 // t->queue_max, next_fc->queue_n);
3013 // if (ack == prev_fc->last_ack_sent && GNUNET_NO == t->force_ack)
3015 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not needed\n");
3019 // prev_fc->last_ack_sent = ack;
3021 // send_local_ack (t, o, fwd);
3022 // else if (0 != hop)
3023 // send_ack (t, hop, ack);
3025 // GNUNET_break (GNUNET_YES == t->destroy);
3026 // t->force_ack = GNUNET_NO;
3031 * Modify the mesh message TID from global to local and send to client.
3033 * @param ch Channel on which to send the message.
3034 * @param msg Message to modify and send.
3035 * @param c Client to send to.
3036 * @param tid Tunnel ID to use (c can be both owner and client).
3039 channel_send_client_to_tid (struct MeshChannel *ch,
3040 const struct GNUNET_MESH_Data *msg,
3041 struct MeshClient *c, MESH_ChannelNumber id)
3043 struct GNUNET_MESH_LocalData *copy;
3044 uint16_t size = ntohs (msg->header.size) - sizeof (struct GNUNET_MESH_Data);
3045 char cbuf[size + sizeof (struct GNUNET_MESH_LocalData)];
3047 if (size < sizeof (struct GNUNET_MessageHeader))
3049 GNUNET_break_op (0);
3057 copy = (struct GNUNET_MESH_LocalData *) cbuf;
3058 memcpy (©[1], &msg[1], size);
3059 copy->header.size = htons (sizeof (struct GNUNET_MESH_LocalData) + size);
3060 copy->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA);
3061 copy->id = htonl (id);
3062 GNUNET_SERVER_notification_context_unicast (nc, c->handle,
3063 ©->header, GNUNET_NO);
3067 * Modify the data message ID from global to local and send to client.
3069 * @param ch Channel on which to send the message.
3070 * @param msg Message to modify and send.
3071 * @param fwd Forward?
3074 channel_send_client_data (struct MeshChannel *ch,
3075 const struct GNUNET_MESH_Data *msg,
3079 channel_send_client_to_tid (ch, msg, ch->dest, ch->lid_dest);
3081 channel_send_client_to_tid (ch, msg, ch->root, ch->lid_root);
3086 * Send a buffered message to the client, for in order delivery or
3087 * as result of client ACK.
3089 * @param ch Channel on which to empty the message buffer.
3090 * @param c Client to send to.
3091 * @param rel Reliability structure to corresponding peer.
3092 * If rel == bck_rel, this is FWD data.
3095 channel_send_client_buffered_data (struct MeshChannel *ch,
3096 struct MeshClient *c,
3097 struct MeshChannelReliability *rel)
3099 struct MeshReliableMessage *copy;
3102 if (GNUNET_NO == rel->client_ready)
3104 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client not ready\n");
3108 mid = rel == ch->bck_rel ? &ch->mid_recv_fwd : &ch->mid_recv_bck;
3110 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data\n");
3111 copy = rel->head_recv;
3114 if (copy->mid == *mid || GNUNET_NO == ch->reliable)
3116 struct GNUNET_MESH_Data *msg = (struct GNUNET_MESH_Data *) ©[1];
3118 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3119 " have %u! now expecting %u\n",
3120 copy->mid, *mid + 1);
3121 channel_send_client_data (ch, msg, (rel == ch->bck_rel));
3124 GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
3129 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3130 " reliable && don't have %u, next is %u\n",
3136 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data END\n");
3141 * We have received a message out of order, or the client is not ready.
3142 * Buffer it until we receive an ACK from the client or the missing
3143 * message from the channel.
3145 * @param msg Message to buffer.
3146 * @param rel Reliability data to the corresponding direction.
3149 channel_rel_add_buffered_data (const struct GNUNET_MESH_Data *msg,
3150 struct MeshChannelReliability *rel)
3152 struct MeshReliableMessage *copy;
3153 struct MeshReliableMessage *prev;
3157 size = ntohs (msg->header.size);
3158 mid = ntohl (msg->mid);
3159 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data %u\n", mid);
3161 copy = GNUNET_malloc (sizeof (*copy) + size);
3164 memcpy (©[1], msg, size);
3168 // FIXME do something better than O(n), although n < 64...
3169 // FIXME start from the end (most messages are the latest ones)
3170 for (prev = rel->head_recv; NULL != prev; prev = prev->next)
3172 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " prev %u\n", prev->mid);
3173 if (GMC_is_pid_bigger (prev->mid, mid))
3175 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " bingo!\n");
3176 GNUNET_CONTAINER_DLL_insert_before (rel->head_recv, rel->tail_recv,
3181 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " insert at tail!\n");
3182 GNUNET_CONTAINER_DLL_insert_tail (rel->head_recv, rel->tail_recv, copy);
3183 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data END\n");
3188 * Destroy a reliable message after it has been acknowledged, either by
3189 * direct mid ACK or bitfield. Updates the appropriate data structures and
3190 * timers and frees all memory.
3192 * @param copy Message that is no longer needed: remote peer got it.
3195 rel_message_free (struct MeshReliableMessage *copy)
3197 struct MeshChannelReliability *rel;
3198 struct GNUNET_TIME_Relative time;
3201 time = GNUNET_TIME_absolute_get_duration (copy->timestamp);
3202 rel->expected_delay.rel_value *= 7;
3203 rel->expected_delay.rel_value += time.rel_value;
3204 rel->expected_delay.rel_value /= 8;
3206 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Freeing %u\n", copy->mid);
3207 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " n_sent %u\n", rel->n_sent);
3208 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! took %s\n",
3209 GNUNET_STRINGS_relative_time_to_string (time, GNUNET_NO));
3210 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! new expected delay %s\n",
3211 GNUNET_STRINGS_relative_time_to_string (rel->expected_delay,
3213 rel->retry_timer = rel->expected_delay;
3214 GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
3220 * Destroy all reliable messages queued for a channel,
3221 * during a channel destruction.
3222 * Frees the reliability structure itself.
3224 * @param rel Reliability data for a channel.
3227 channel_rel_free_all (struct MeshChannelReliability *rel)
3229 struct MeshReliableMessage *copy;
3230 struct MeshReliableMessage *next;
3235 for (copy = rel->head_recv; NULL != copy; copy = next)
3238 GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
3241 for (copy = rel->head_sent; NULL != copy; copy = next)
3244 GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
3247 if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
3248 GNUNET_SCHEDULER_cancel (rel->retry_task);
3254 * Mark future messages as ACK'd.
3256 * @param rel Reliability data.
3257 * @param msg DataACK message with a bitfield of future ACK'd messages.
3260 channel_rel_free_sent (struct MeshChannelReliability *rel,
3261 const struct GNUNET_MESH_DataACK *msg)
3263 struct MeshReliableMessage *copy;
3264 struct MeshReliableMessage *next;
3271 bitfield = msg->futures;
3272 mid = ntohl (msg->mid);
3273 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3274 "free_sent_reliable %u %llX\n",
3276 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3277 " rel %p, head %p\n",
3278 rel, rel->head_sent);
3279 for (i = 0, copy = rel->head_sent;
3280 i < 64 && NULL != copy && 0 != bitfield;
3283 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3284 " trying bit %u (mid %u)\n",
3287 if (0 == (bitfield & mask))
3290 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " set!\n");
3291 /* Bit was set, clear the bit from the bitfield */
3294 /* The i-th bit was set. Do we have that copy? */
3295 /* Skip copies with mid < target */
3296 target = mid + i + 1;
3297 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " target %u\n", target);
3298 while (NULL != copy && GMC_is_pid_bigger (target, copy->mid))
3301 /* Did we run out of copies? (previously freed, it's ok) */
3304 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "run out of copies...\n");
3308 /* Did we overshoot the target? (previously freed, it's ok) */
3309 if (GMC_is_pid_bigger (copy->mid, target))
3311 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " next copy %u\n", copy->mid);
3315 /* Now copy->mid == target, free it */
3317 rel_message_free (copy);
3320 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "free_sent_reliable END\n");
3325 * We haven't received an ACK after a certain time: restransmit the message.
3327 * @param cls Closure (MeshReliableMessage with the message to restransmit)
3328 * @param tc TaskContext.
3331 channel_retransmit_message (void *cls,
3332 const struct GNUNET_SCHEDULER_TaskContext *tc)
3334 struct MeshChannelReliability *rel = cls;
3335 struct MeshReliableMessage *copy;
3336 struct MeshPeerQueue *q;
3337 struct MeshChannel *ch;
3338 struct MeshConnection *c;
3339 struct GNUNET_MESH_Data *payload;
3340 struct MeshPeer *hop;
3343 rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
3344 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3348 copy = rel->head_sent;
3355 /* Search the message to be retransmitted in the outgoing queue.
3356 * Check only the queue for the connection that is going to be used,
3357 * if the message is stuck in some other connection's queue we shouldn't
3359 * - cancelling it and sending the new one doesn't guarantee it's delivery,
3360 * the old connection could be temporary stalled or the queue happened to
3361 * be long at time of insertion.
3362 * - not sending the new one could cause terrible delays the old connection
3365 payload = (struct GNUNET_MESH_Data *) ©[1];
3366 fwd = (rel == ch->fwd_rel);
3367 c = tunnel_get_connection (ch->t, fwd);
3368 hop = connection_get_hop (c, fwd);
3369 for (q = hop->queue_head; NULL != q; q = q->next)
3371 if (ntohs (payload->header.type) == q->type && ch == q->ch)
3373 struct GNUNET_MESH_Data *queued_data = q->cls;
3375 if (queued_data->mid == payload->mid)
3380 /* Message not found in the queue that we are going to use. */
3383 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! RETRANSMIT %u\n", copy->mid);
3385 send_prebuilt_message_channel (&payload->header, ch, ch->fwd_rel == rel);
3386 GNUNET_STATISTICS_update (stats, "# data retransmitted", 1, GNUNET_NO);
3390 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! ALREADY IN QUEUE %u\n", copy->mid);
3393 rel->retry_timer = GNUNET_TIME_STD_BACKOFF (rel->retry_timer);
3394 rel->retry_task = GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
3395 &channel_retransmit_message,
3402 * Send ACK on one or more connections due to buffer space to the client.
3405 channel_send_ack (struct MeshChannel *ch, uint32_t buffer, int fwd)
3407 struct MeshTunnel2 *t = ch->t;
3408 struct MeshConnection *c;
3409 struct MeshFlowControl *fc;
3414 /* Count connections, how many messages are already allowed */
3415 for (cs = 0, allowed = 0, c = t->connection_head; NULL != c; c = c->next)
3417 fc = fwd ? &c->fwd_fc : &c->bck_fc;
3418 if (GMC_is_pid_bigger(fc->last_pid_recv, fc->last_ack_sent))
3423 allowed += fc->last_ack_sent - fc->last_pid_recv;
3427 /* Make sure there is no overflow */
3428 if (allowed > buffer)
3434 /* Authorize connections to send more data */
3435 to_allow = buffer - allowed;
3436 for (c = t->connection_head; NULL != c && to_allow > 0; c = c->next)
3438 fc = fwd ? &c->fwd_fc : &c->bck_fc;
3439 if (fc->last_ack_sent - fc->last_pid_recv > 64 / 3)
3443 send_ack (c, fc->last_ack_sent + 1, fwd);
3447 GNUNET_break (to_allow == 0);
3452 * Send keepalive packets for a connection.
3454 * @param c Connection to keep alive..
3455 * @param fwd Is this a FWD keepalive? (owner -> dest).
3458 connection_keepalive (struct MeshConnection *c, int fwd)
3460 struct GNUNET_MESH_ConnectionKeepAlive *msg;
3461 size_t size = sizeof (struct GNUNET_MESH_ConnectionKeepAlive);
3465 type = fwd ? GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE :
3466 GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE;
3468 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3469 "sending %s keepalive for connection %s[%d]\n",
3470 fwd ? "FWD" : "BCK",
3471 GNUNET_i2s (GNUNET_PEER_resolve2 (c->t->peer->id)),
3474 msg = (struct GNUNET_MESH_ConnectionKeepAlive *) cbuf;
3475 msg->header.size = htons (size);
3476 msg->header.type = htons (type);
3477 msg->cid = htonl (c->id);
3478 msg->tid = c->t->id;
3480 send_prebuilt_message_connection (&msg->header, c, NULL, fwd);
3485 * Send CONNECTION_{CREATE/ACK} packets for a connection.
3487 * @param c Connection for which to send the message.
3488 * @param fwd If GNUNET_YES, send CREATE, otherwise send ACK.
3491 connection_recreate (struct MeshConnection *c, int fwd)
3493 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "sending connection recreate\n");
3495 send_connection_create (c);
3497 send_connection_ack (c);
3502 * Generic connection timer management.
3503 * Depending on the role of the peer in the connection will send the
3504 * appropriate message (build or keepalive)
3506 * @param c Conncetion to maintain.
3507 * @param fwd Is FWD?
3510 connection_maintain (struct MeshConnection *c, int fwd)
3512 if (MESH_TUNNEL_SEARCHING == c->t->state)
3514 /* TODO DHT GET with RO_BART */
3519 case MESH_CONNECTION_NEW:
3521 case MESH_CONNECTION_SENT:
3522 connection_recreate (c, fwd);
3524 case MESH_CONNECTION_READY:
3525 connection_keepalive (c, fwd);
3534 connection_fwd_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3536 struct MeshConnection *c = cls;
3538 c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
3539 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3542 connection_maintain (c, GNUNET_YES);
3543 c->fwd_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
3544 &connection_fwd_keepalive,
3550 connection_bck_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3552 struct MeshConnection *c = cls;
3554 c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
3555 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3558 connection_maintain (c, GNUNET_NO);
3559 c->bck_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
3560 &connection_bck_keepalive,
3566 * Send a message to all peers in this connection that the connection
3567 * is no longer valid.
3569 * If some peer should not receive the message, it should be zero'ed out
3570 * before calling this function.
3572 * @param c The connection whose peers to notify.
3575 connection_send_destroy (struct MeshConnection *c)
3577 struct GNUNET_MESH_ConnectionDestroy msg;
3579 msg.header.size = htons (sizeof (msg));
3580 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);;
3581 msg.cid = htonl (c->id);
3583 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3584 " sending tunnel destroy for connection %s[%X]\n",
3585 GNUNET_i2s (GNUNET_PEER_resolve2 (c->t->peer->id)),
3588 send_prebuilt_message_connection (&msg.header, c, NULL, GNUNET_YES);
3589 send_prebuilt_message_connection (&msg.header, c, NULL, GNUNET_NO);
3590 c->destroy = GNUNET_YES;
3595 * Send a message to all clients (local and remote) of this channel
3596 * notifying that the channel is no longer valid.
3598 * If some peer or client should not receive the message,
3599 * should be zero'ed out before calling this function.
3601 * @param ch The channel whose clients to notify.
3604 channel_send_destroy (struct MeshChannel *ch)
3606 struct GNUNET_MESH_ChannelDestroy msg;
3608 msg.header.size = htons (sizeof (msg));
3609 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY);
3610 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3611 " sending tunnel destroy for channel %s:%X\n",
3612 GNUNET_i2s (GNUNET_PEER_resolve2 (ch->t->peer->id)),
3615 if (NULL != ch->root)
3617 msg.chid = htonl (ch->lid_root);
3618 send_local_channel_destroy (ch, GNUNET_NO);
3622 msg.chid = htonl (ch->gid);
3623 send_prebuilt_message_channel (&msg.header, ch, GNUNET_NO);
3626 if (NULL != ch->dest)
3628 msg.chid = htonl (ch->lid_dest);
3629 send_local_channel_destroy (ch, GNUNET_YES);
3633 msg.chid = htonl (ch->gid);
3634 send_prebuilt_message_channel (&msg.header, ch, GNUNET_YES);
3642 * @param tid Tunnel ID.
3644 static struct MeshTunnel2 *
3645 tunnel_new (const struct GNUNET_HashCode *tid)
3647 struct MeshTunnel2 *t;
3649 t = GNUNET_new (struct MeshTunnel2);
3651 t->next_chid = GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
3653 GNUNET_CONTAINER_multihashmap_put (tunnels, tid, t,
3654 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3668 * @param tid Tunnel ID.
3670 static struct MeshTunnel2 *
3671 tunnel_get (const struct GNUNET_HashCode *tid)
3673 return GNUNET_CONTAINER_multihashmap_get (tunnels, tid);
3678 * Add a connection to a tunnel.
3681 * @param c Connection.
3684 tunnel_add_connection (struct MeshTunnel2 *t, struct MeshConnection *c)
3687 GNUNET_CONTAINER_DLL_insert_tail (t->connection_head, t->connection_tail, c);
3692 * Initialize a Flow Control structure to the initial state.
3694 * @param fc Flow Control structure to initialize.
3697 fc_init (struct MeshFlowControl *fc)
3699 fc->last_pid_sent = (uint32_t) -1; /* Next (expected) = 0 */
3700 fc->last_pid_recv = (uint32_t) -1;
3701 fc->last_ack_sent = (uint32_t) -1; /* No traffic allowed yet */
3702 fc->last_ack_recv = (uint32_t) -1;
3703 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
3704 fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
3710 * Create a connection.
3712 * @param tid Tunnel ID.
3713 * @param cid Connection ID.
3715 static struct MeshConnection *
3716 connection_new (struct GNUNET_HashCode *tid, uint32_t cid)
3718 struct MeshConnection *c;
3719 struct MeshTunnel2 *t;
3721 t = tunnel_get (tid);
3724 t = tunnel_new (tid);
3732 c = GNUNET_new (struct MeshConnection);
3734 fc_init (&c->fwd_fc);
3735 fc_init (&c->bck_fc);
3736 tunnel_add_connection (t, c);
3743 * Find a connection.
3745 * @param tid Tunnel ID.
3746 * @param cid Connection ID.
3748 static struct MeshConnection *
3749 connection_get (const struct GNUNET_HashCode *tid, uint32_t cid)
3751 struct MeshConnection *c;
3752 struct MeshTunnel2 *t;
3754 t = tunnel_get (tid);
3755 for (c = t->connection_head; NULL != c; c = c->next)
3764 * Connection is no longer needed: destroy it and remove from tunnel.
3766 * @param c Connection to destroy.
3769 connection_destroy (struct MeshConnection *c)
3774 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying connection %s[%X]\n",
3775 GNUNET_i2s (GNUNET_PEER_resolve2 (c->t->peer->id)),
3778 connection_cancel_queues (c, GNUNET_YES);
3779 connection_cancel_queues (c, GNUNET_NO);
3781 if (GNUNET_SCHEDULER_NO_TASK != c->fwd_maintenance_task)
3782 GNUNET_SCHEDULER_cancel (c->fwd_maintenance_task);
3783 if (GNUNET_SCHEDULER_NO_TASK != c->bck_maintenance_task)
3784 GNUNET_SCHEDULER_cancel (c->bck_maintenance_task);
3786 GNUNET_CONTAINER_DLL_remove (c->t->connection_head, c->t->connection_tail, c);
3788 GNUNET_STATISTICS_update (stats, "# connections", -1, GNUNET_NO);
3794 tunnel_destroy (struct MeshTunnel2 *t)
3796 struct MeshConnection *c;
3797 struct MeshConnection *next;
3802 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n",
3803 GNUNET_i2s (GNUNET_PEER_resolve2 (t->peer->id)));
3805 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &t->id, t))
3808 for (c = t->connection_head; NULL != c; c = next)
3811 connection_destroy (c);
3814 GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
3821 * Tunnel is empty: destroy it.
3823 * Notifies all connections about the destruction.
3825 * @param t Tunnel to destroy.
3828 tunnel_destroy_empty (struct MeshTunnel2 *t)
3830 struct MeshConnection *c;
3832 for (c = t->connection_head; NULL != c; c = c->next)
3834 if (GNUNET_NO == c->destroy)
3835 connection_send_destroy (c);
3838 if (0 == t->pending_messages)
3841 t->destroy = GNUNET_YES;
3846 * Destroy tunnel if empty (no more channels).
3848 * @param t Tunnel to destroy if empty.
3851 tunnel_destroy_if_empty (struct MeshTunnel2 *t)
3853 if (NULL != t->channel_head)
3856 tunnel_destroy_empty (t);
3861 * Destroy a channel and free all resources.
3863 * @param ch Channel to destroy.
3866 channel_destroy (struct MeshChannel *ch)
3868 struct MeshClient *c;
3876 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap32_remove (c->own_channels,
3887 GNUNET_CONTAINER_multihashmap32_remove (c->incoming_channels,
3894 if (GNUNET_YES == ch->reliable)
3896 channel_rel_free_all (ch->fwd_rel);
3897 channel_rel_free_all (ch->bck_rel);
3900 GNUNET_CONTAINER_DLL_remove (ch->t->channel_head, ch->t->channel_tail, ch);
3901 GNUNET_STATISTICS_update (stats, "# channels", -1, GNUNET_NO);
3907 * Create a new channel.
3909 * @param t Tunnel this channel is in.
3910 * @param owner Client that owns the channel, NULL for foreign channels.
3911 * @param lid_root Local ID for root client.
3913 * @return A new initialized channel. NULL on error.
3915 static struct MeshChannel *
3916 channel_new (struct MeshTunnel2 *t,
3917 struct MeshClient *owner, MESH_ChannelNumber lid_root)
3919 struct MeshChannel *ch;
3921 ch = GNUNET_new (struct MeshChannel);
3923 ch->lid_root = lid_root;
3926 GNUNET_STATISTICS_update (stats, "# channels", 1, GNUNET_NO);
3930 while (NULL != channel_get_by_local_id (owner, t->next_chid))
3931 t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
3932 ch->gid = t->next_chid;
3933 t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
3936 GNUNET_CONTAINER_multihashmap32_put (owner->own_channels, lid_root, ch,
3937 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
3940 channel_destroy (ch);
3941 GNUNET_SERVER_receive_done (owner->handle, GNUNET_SYSERR);
3951 * Set options in a channel, extracted from a bit flag field
3953 * @param ch Channel to set options to.
3954 * @param options Bit array in host byte order.
3957 channel_set_options (struct MeshChannel *ch, uint32_t options)
3959 ch->nobuffer = (options & GNUNET_MESH_OPTION_NOBUFFER) != 0 ?
3960 GNUNET_YES : GNUNET_NO;
3961 ch->reliable = (options & GNUNET_MESH_OPTION_RELIABLE) != 0 ?
3962 GNUNET_YES : GNUNET_NO;
3967 * Iterator for deleting each channel whose client endpoint disconnected.
3969 * @param cls Closure (client that has disconnected).
3970 * @param key The local channel id (used to access the hashmap).
3971 * @param value The value stored at the key (channel to destroy).
3973 * @return GNUNET_OK, keep iterating.
3976 channel_destroy_iterator (void *cls,
3980 struct MeshChannel *ch = value;
3981 struct MeshClient *c = cls;
3982 struct MeshTunnel2 *t;
3984 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3985 " Channel %X (%X / %X) destroy, due to client %u shutdown.\n",
3986 ch->gid, ch->lid_root, ch->lid_dest, c->id);
3990 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is destination.\n", c->id);
3995 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is owner.\n", c->id);
4000 channel_send_destroy (ch);
4001 channel_destroy (ch);
4002 tunnel_destroy_if_empty (t);
4009 * Remove client's ports from the global hashmap on disconnect.
4011 * @param cls Closure (unused).
4013 * @param value Client structure.
4015 * @return GNUNET_OK, keep iterating.
4018 client_release_ports (void *cls,
4024 res = GNUNET_CONTAINER_multihashmap32_remove (ports, key, value);
4025 if (GNUNET_YES != res)
4028 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4029 "Port %u by client %p was not registered.\n",
4037 * Timeout function due to lack of keepalive/traffic from the owner.
4038 * Destroys connection if called.
4040 * @param cls Closure (connection to destroy).
4041 * @param tc TaskContext.
4044 connection_fwd_timeout (void *cls,
4045 const struct GNUNET_SCHEDULER_TaskContext *tc)
4047 struct MeshConnection *c = cls;
4049 c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4050 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4052 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4053 "Connection %s[%X] FWD timed out. Destroying.\n",
4054 GNUNET_i2s(GNUNET_PEER_resolve2 (c->t->peer->id)),
4057 if (NULL != c->t->channel_head) /* If local, leave TODO review */
4060 connection_destroy (c);
4065 * Timeout function due to lack of keepalive/traffic from the destination.
4066 * Destroys connection if called.
4068 * @param cls Closure (connection to destroy).
4069 * @param tc TaskContext
4072 connection_bck_timeout (void *cls,
4073 const struct GNUNET_SCHEDULER_TaskContext *tc)
4075 struct MeshConnection *c = cls;
4077 c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4078 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4081 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4082 "Connection %s[%X] FWD timed out. Destroying.\n",
4083 GNUNET_i2s(GNUNET_PEER_resolve2 (c->t->peer->id)),
4086 if (NULL != c->t->channel_head) /* If local, leave TODO review */
4089 connection_destroy (c);
4094 * Resets the connection timeout task, some other message has done the
4096 * - For the first peer on the direction this means to send
4097 * a keepalive or a path confirmation message (either create or ACK).
4098 * - For all other peers, this means to destroy the connection,
4099 * due to lack of activity.
4100 * Starts the tiemout if no timeout was running (connection just created).
4102 * @param c Connection whose timeout to reset.
4103 * @param fwd Is this forward?
4105 * TODO use heap to improve efficiency of scheduler.
4108 connection_reset_timeout (struct MeshConnection *c, int fwd)
4110 GNUNET_SCHEDULER_TaskIdentifier *ti;
4111 GNUNET_SCHEDULER_Task f;
4113 ti = fwd ? &c->fwd_maintenance_task : &c->bck_maintenance_task;
4115 if (GNUNET_SCHEDULER_NO_TASK != *ti)
4116 GNUNET_SCHEDULER_cancel (*ti);
4118 if (NULL != c->t->channel_head) /* Endpoint */
4120 f = fwd ? &connection_fwd_keepalive : &connection_bck_keepalive;
4121 *ti = GNUNET_SCHEDULER_add_delayed (refresh_connection_time, f, c);
4125 struct GNUNET_TIME_Relative delay;
4127 delay = GNUNET_TIME_relative_multiply (refresh_connection_time, 4);
4128 f = fwd ? &connection_fwd_timeout : &connection_bck_timeout;
4129 *ti = GNUNET_SCHEDULER_add_delayed (delay, f, c);
4135 * Iterator to notify all connections of a broken link. Mark connections
4136 * to destroy after all traffic has been sent.
4138 * @param cls Closure (peer disconnected).
4139 * @param key Current key code (tid).
4140 * @param value Value in the hash map (connection).
4142 * @return GNUNET_YES if we should continue to iterate,
4146 connection_broken (void *cls,
4147 const struct GNUNET_HashCode *key,
4150 struct MeshPeer *peer = cls;
4151 struct MeshConnection *c = value;
4152 struct GNUNET_MESH_ConnectionBroken msg;
4155 fwd = peer == connection_get_prev_hop (c);
4156 connection_cancel_queues (c, !fwd);
4158 msg.header.size = htons (sizeof (struct GNUNET_MESH_ConnectionBroken));
4159 msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN);
4160 msg.cid = htonl (c->id);
4162 msg.peer1 = my_full_id;
4163 msg.peer2 = *GNUNET_PEER_resolve2 (peer->id);
4164 send_prebuilt_message_connection (&msg.header, c, NULL, fwd);
4165 c->destroy = GNUNET_YES;
4170 /******************************************************************************/
4171 /**************** MESH NETWORK HANDLER HELPERS ***********************/
4172 /******************************************************************************/
4175 * Free a transmission that was already queued with all resources
4176 * associated to the request.
4178 * @param queue Queue handler to cancel.
4179 * @param clear_cls Is it necessary to free associated cls?
4182 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
4184 struct MeshPeer *peer;
4185 struct MeshFlowControl *fc;
4190 fc = fwd ? &queue->c->fwd_fc : &queue->c->bck_fc;
4192 if (GNUNET_YES == clear_cls)
4194 switch (queue->type)
4196 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
4197 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "destroying CONNECTION_DESTROY\n");
4198 GNUNET_break (GNUNET_YES == queue->c->destroy);
4200 case GNUNET_MESSAGE_TYPE_MESH_FWD:
4201 case GNUNET_MESSAGE_TYPE_MESH_BCK:
4202 case GNUNET_MESSAGE_TYPE_MESH_ACK:
4203 case GNUNET_MESSAGE_TYPE_MESH_POLL:
4204 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
4205 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " prebuilt message\n");
4206 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type %s\n",
4207 GNUNET_MESH_DEBUG_M2S (queue->type));
4210 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
4211 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type create path\n");
4216 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, " type %s unknown!\n",
4217 GNUNET_MESH_DEBUG_M2S (queue->type));
4219 GNUNET_free_non_null (queue->cls);
4221 GNUNET_CONTAINER_DLL_remove (peer->queue_head, peer->queue_tail, queue);
4225 if (NULL != queue->c)
4227 queue->c->pending_messages--;
4228 if (NULL != queue->c->t)
4230 queue->c->t->pending_messages--;
4234 GNUNET_free (queue);
4239 queue_send (void *cls, size_t size, void *buf)
4241 struct MeshPeer *peer = cls;
4242 struct MeshFlowControl *fc;
4243 struct MeshConnection *c;
4244 struct GNUNET_MessageHeader *msg;
4245 struct MeshPeerQueue *queue;
4246 struct MeshTunnel2 *t;
4247 const struct GNUNET_PeerIdentity *dst_id;
4253 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Queue send\n");
4255 if (NULL == buf || 0 == size)
4257 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Buffer size 0.\n");
4262 queue = peer_get_first_message (peer);
4265 GNUNET_break (0); /* Core tmt_rdy should've been canceled */
4268 queue->peer->core_transmit = NULL;
4271 fc = fwd ? &c->fwd_fc : &c->bck_fc;
4274 dst_id = GNUNET_PEER_resolve2 (peer->id);
4275 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* towards %s\n", GNUNET_i2s (dst_id));
4276 /* Check if buffer size is enough for the message */
4277 if (queue->size > size)
4279 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* not enough room, reissue\n");
4280 peer->core_transmit =
4281 GNUNET_CORE_notify_transmit_ready (core_handle,
4284 GNUNET_TIME_UNIT_FOREVER_REL,
4291 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* size ok\n");
4293 t = (NULL != c) ? c->t : NULL;
4297 switch (queue->type)
4299 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
4300 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
4301 case GNUNET_MESSAGE_TYPE_MESH_FWD:
4302 case GNUNET_MESSAGE_TYPE_MESH_BCK:
4303 case GNUNET_MESSAGE_TYPE_MESH_ACK:
4304 case GNUNET_MESSAGE_TYPE_MESH_POLL:
4305 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4307 GNUNET_MESH_DEBUG_M2S (queue->type));
4309 case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4310 case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4311 data_size = send_core_data_raw (queue->cls, size, buf);
4312 msg = (struct GNUNET_MessageHeader *) buf;
4313 type = ntohs (msg->type);
4315 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
4316 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* path create\n");
4317 if (NULL != c->t->channel_head)
4318 data_size = send_core_connection_create (queue->cls, size, buf);
4320 data_size = send_core_data_raw (queue->cls, size, buf);
4322 case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
4323 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* path ack\n");
4324 if (NULL != c->t->channel_head)
4325 data_size = send_core_connection_ack (queue->cls, size, buf);
4327 data_size = send_core_data_raw (queue->cls, size, buf);
4331 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "* type unknown: %u\n",
4336 if (0 < drop_percent &&
4337 GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 101) < drop_percent)
4339 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4340 "Dropping message of type %s\n",
4341 GNUNET_MESH_DEBUG_M2S (queue->type));
4344 /* Free queue, but cls was freed by send_core_* */
4345 queue_destroy (queue, GNUNET_NO);
4347 /* Send ACK if needed, after accounting for sent ID in fc->queue_n */
4350 case GNUNET_MESSAGE_TYPE_MESH_FWD:
4351 case GNUNET_MESSAGE_TYPE_MESH_BCK:
4352 pid = ntohl ( ((struct GNUNET_MESH_Encrypted *) buf)->pid );
4353 fc->last_pid_sent = pid;
4354 connection_send_ack (c, fwd);
4360 /* If more data in queue, send next */
4361 queue = peer_get_first_message (peer);
4364 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* more data!\n");
4365 if (NULL == peer->core_transmit) {
4366 peer->core_transmit =
4367 GNUNET_CORE_notify_transmit_ready(core_handle,
4370 GNUNET_TIME_UNIT_FOREVER_REL,
4378 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4379 "* tmt rdy called somewhere else\n");
4381 if (GNUNET_SCHEDULER_NO_TASK == fc->poll_task)
4383 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "* %s starting poll timeout\n");
4385 GNUNET_SCHEDULER_add_delayed (fc->poll_time, &connection_poll, fc);
4390 if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
4392 GNUNET_SCHEDULER_cancel (fc->poll_task);
4393 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
4398 c->pending_messages--;
4399 if (GNUNET_YES == c->destroy && 0 == c->pending_messages)
4401 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* destroying connection!\n");
4402 connection_destroy (c);
4408 t->pending_messages--;
4409 if (GNUNET_YES == t->destroy && 0 == t->pending_messages)
4411 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* destroying tunnel!\n");
4415 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Return %d\n", data_size);
4421 queue_add (void *cls, uint16_t type, size_t size,
4422 struct MeshPeer *dst,
4423 struct MeshConnection *c,
4424 struct MeshChannel *ch)
4426 struct MeshPeerQueue *queue;
4427 struct MeshFlowControl *fc;
4431 fwd = (dst == connection_get_next_hop (c));
4432 fc = fwd ? &c->fwd_fc : &c->bck_fc;
4442 if (GNUNET_MESSAGE_TYPE_MESH_POLL == type ||
4443 GNUNET_MESSAGE_TYPE_MESH_ACK == type)
4447 ( (NULL != ch->root && GNUNET_MESSAGE_TYPE_MESH_FWD == type) ||
4448 (NULL != ch->dest && GNUNET_MESSAGE_TYPE_MESH_BCK == type) ))
4451 if (fc->queue_n >= fc->queue_max && 0 == priority)
4453 GNUNET_STATISTICS_update (stats, "# messages dropped (buffer full)",
4456 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4457 "queue full: %u/%u\n",
4458 fc->queue_n, fc->queue_max);
4459 return; /* Drop this message */
4462 if (GMC_is_pid_bigger(fc->last_pid_sent + 1, fc->last_ack_recv) &&
4463 GNUNET_SCHEDULER_NO_TASK == fc->poll_task)
4464 fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
4467 queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
4475 if (100 <= priority)
4476 GNUNET_CONTAINER_DLL_insert (dst->queue_head, dst->queue_tail, queue);
4478 GNUNET_CONTAINER_DLL_insert_tail (dst->queue_head, dst->queue_tail, queue);
4480 if (NULL == dst->core_transmit)
4482 dst->core_transmit =
4483 GNUNET_CORE_notify_transmit_ready (core_handle,
4486 GNUNET_TIME_UNIT_FOREVER_REL,
4487 GNUNET_PEER_resolve2 (dst->id),
4492 c->pending_messages++;
4493 c->t->pending_messages++;
4499 /******************************************************************************/
4500 /******************** MESH NETWORK HANDLERS **************************/
4501 /******************************************************************************/
4505 * Generic handler for mesh network payload traffic.
4507 * @param t Tunnel on which we got this message.
4508 * @param message Unencryted data message.
4509 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
4511 * @return GNUNET_OK to keep the connection open,
4512 * GNUNET_SYSERR to close it (signal serious error)
4515 handle_data (struct MeshTunnel2 *t, const struct GNUNET_MESH_Data *msg, int fwd)
4517 struct MeshChannelReliability *rel;
4518 struct MeshChannel *ch;
4519 struct MeshClient *c;
4526 size = ntohs (msg->header.size);
4528 sizeof (struct GNUNET_MESH_Data) +
4529 sizeof (struct GNUNET_MessageHeader))
4534 type = ntohs (msg->header.type);
4535 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message\n",
4536 GNUNET_MESH_DEBUG_M2S (type));
4537 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
4538 GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
4541 ch = channel_get (t, ntohl (msg->chid));
4544 GNUNET_STATISTICS_update (stats, "# data on unknown channel", 1, GNUNET_NO);
4545 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel unknown\n");
4549 /* Initialize FWD/BCK data */
4550 c = fwd ? ch->dest : ch->root;
4551 rel = fwd ? ch->bck_rel : ch->fwd_rel;
4552 mid_recv = fwd ? &ch->mid_recv_fwd : &ch->mid_recv_bck;
4560 tunnel_change_state (t, MESH_TUNNEL_READY);
4562 GNUNET_STATISTICS_update (stats, "# data received", 1, GNUNET_NO);
4564 mid = ntohl (msg->mid);
4565 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " mid %u\n", mid);
4567 if (GNUNET_NO == ch->reliable ||
4568 ( !GMC_is_pid_bigger (*mid_recv, mid) &&
4569 GMC_is_pid_bigger (*mid_recv + 64, mid) ) )
4571 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! RECV %u\n", mid);
4572 if (GNUNET_YES == ch->reliable)
4574 /* Is this the exact next expected messasge? */
4575 if (mid == *mid_recv)
4577 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "as expected\n");
4578 *mid_recv = *mid_recv + 1;
4579 channel_send_client_data (ch, msg, fwd);
4580 channel_send_client_buffered_data (ch, c, rel);
4584 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "save for later\n");
4585 channel_rel_add_buffered_data (msg, rel);
4588 else /* Tunnel unreliable, send to clients directly */
4590 channel_send_client_data (ch, msg, fwd);
4595 GNUNET_break_op (0);
4596 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4597 " MID %u not expected (%u - %u), dropping!\n",
4598 mid, *mid_recv, *mid_recv + 64);
4601 channel_send_data_ack (ch, fwd);
4606 * Handler for mesh network traffic end-to-end ACKs.
4608 * @param t Tunnel on which we got this message.
4609 * @param message Data message.
4610 * @param fwd Is this a fwd ACK? (dest->orig)
4612 * @return GNUNET_OK to keep the connection open,
4613 * GNUNET_SYSERR to close it (signal serious error)
4616 handle_data_ack (struct MeshTunnel2 *t,
4617 const struct GNUNET_MESH_DataACK *msg, int fwd)
4619 struct MeshChannelReliability *rel;
4620 struct MeshReliableMessage *copy;
4621 struct MeshReliableMessage *next;
4622 struct MeshChannel *ch;
4627 type = ntohs (msg->header.type);
4628 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a %s message!\n",
4629 GNUNET_MESH_DEBUG_M2S (type));
4630 ch = channel_get (t, ntohl (msg->chid));
4633 GNUNET_STATISTICS_update (stats, "# ack on unknown channel", 1, GNUNET_NO);
4636 ack = ntohl (msg->mid);
4637 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! %s ACK %u\n",
4638 (GNUNET_YES == fwd) ? "FWD" : "BCK", ack);
4640 if (GNUNET_YES == fwd)
4653 for (work = GNUNET_NO, copy = rel->head_sent; copy != NULL; copy = next)
4655 if (GMC_is_pid_bigger (copy->mid, ack))
4657 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! head %u, out!\n", copy->mid);
4658 channel_rel_free_sent (rel, msg);
4662 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! id %u\n", copy->mid);
4664 rel_message_free (copy);
4666 /* ACK client if needed */
4667 // channel_send_ack (t, type, GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK == type);
4669 /* If some message was free'd, update the retransmission delay*/
4670 if (GNUNET_YES == work)
4672 if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
4674 GNUNET_SCHEDULER_cancel (rel->retry_task);
4675 if (NULL == rel->head_sent)
4677 rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
4681 struct GNUNET_TIME_Absolute new_target;
4682 struct GNUNET_TIME_Relative delay;
4684 delay = GNUNET_TIME_relative_multiply (rel->retry_timer,
4685 MESH_RETRANSMIT_MARGIN);
4686 new_target = GNUNET_TIME_absolute_add (rel->head_sent->timestamp,
4688 delay = GNUNET_TIME_absolute_get_remaining (new_target);
4690 GNUNET_SCHEDULER_add_delayed (delay,
4691 &channel_retransmit_message,
4703 * Core handler for connection creation.
4705 * @param cls Closure (unused).
4706 * @param peer Sender (neighbor).
4707 * @param message Message.
4709 * @return GNUNET_OK to keep the connection open,
4710 * GNUNET_SYSERR to close it (signal serious error)
4713 handle_mesh_connection_create (void *cls,
4714 const struct GNUNET_PeerIdentity *peer,
4715 const struct GNUNET_MessageHeader *message)
4717 struct GNUNET_MESH_ConnectionCreate *msg;
4718 struct GNUNET_PeerIdentity *id;
4719 struct GNUNET_HashCode *tid;
4720 struct MeshPeerPath *path;
4721 struct MeshPeer *dest_peer;
4722 struct MeshPeer *orig_peer;
4723 struct MeshConnection *c;
4724 unsigned int own_pos;
4729 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection create msg\n");
4732 size = ntohs (message->size);
4733 if (size < sizeof (struct GNUNET_MESH_ConnectionCreate))
4735 GNUNET_break_op (0);
4739 /* Calculate hops */
4740 size -= sizeof (struct GNUNET_MESH_ConnectionCreate);
4741 if (size % sizeof (struct GNUNET_PeerIdentity))
4743 GNUNET_break_op (0);
4746 size /= sizeof (struct GNUNET_PeerIdentity);
4749 GNUNET_break_op (0);
4752 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " path has %u hops.\n", size);
4754 /* Get parameters */
4755 msg = (struct GNUNET_MESH_ConnectionCreate *) message;
4756 cid = ntohl (msg->cid);
4758 id = (struct GNUNET_PeerIdentity *) &msg[1];
4759 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4760 " connection %s[%X] (%s).\n",
4761 GNUNET_h2s (tid), cid, GNUNET_i2s (id));
4763 /* Create connection */
4764 c = connection_get (tid, cid);
4767 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Creating connection\n");
4768 c = connection_new (tid, cid);
4772 connection_reset_timeout (c, GNUNET_YES);
4773 tunnel_change_state (c->t, MESH_TUNNEL_WAITING);
4775 /* Remember peers */
4776 dest_peer = peer_get (&id[size - 1]);
4777 orig_peer = peer_get (&id[0]);
4780 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Creating path...\n");
4781 path = path_new (size);
4783 for (i = 0; i < size; i++)
4785 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... adding %s\n",
4786 GNUNET_i2s (&id[i]));
4787 path->peers[i] = GNUNET_PEER_intern (&id[i]);
4788 if (path->peers[i] == myid)
4791 if (own_pos == 0 && path->peers[own_pos] != myid)
4793 /* create path: self not found in path through self */
4794 GNUNET_break_op (0);
4795 path_destroy (path);
4796 connection_destroy (c);
4799 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Own position: %u\n", own_pos);
4800 path_add_to_peers (path, GNUNET_NO);
4802 c->own_pos = own_pos;
4804 /* Is it a connection to us? */
4805 if (own_pos == size - 1)
4807 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " It's for us!\n");
4808 peer_add_path_to_origin (orig_peer, path, GNUNET_YES);
4810 send_connection_ack (c);
4812 /* Keep tunnel alive in direction dest->owner*/
4813 connection_reset_timeout (c, GNUNET_NO);
4817 /* It's for somebody else! Retransmit. */
4818 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Retransmitting.\n");
4819 peer_add_path (dest_peer, path_duplicate (path), GNUNET_NO);
4820 peer_add_path_to_origin (orig_peer, path, GNUNET_NO);
4821 send_prebuilt_message_connection (message, c, NULL, GNUNET_YES);
4828 * Core handler for path ACKs
4830 * @param cls closure
4831 * @param message message
4832 * @param peer peer identity this notification is about
4834 * @return GNUNET_OK to keep the connection open,
4835 * GNUNET_SYSERR to close it (signal serious error)
4838 handle_mesh_connection_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
4839 const struct GNUNET_MessageHeader *message)
4841 struct GNUNET_MESH_ConnectionACK *msg;
4842 struct MeshPeerPath *p;
4843 struct MeshConnection *c;
4846 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection ACK msg\n");
4847 msg = (struct GNUNET_MESH_ConnectionACK *) message;
4848 cid = ntohl(msg->cid);
4849 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " on connection %s[%X]\n",
4850 GNUNET_h2s (&msg->tid), cid);
4851 c = connection_get (&msg->tid, cid);
4854 GNUNET_STATISTICS_update (stats, "# control on unknown connection",
4856 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " don't know the connection!\n");
4860 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " via peer %s\n",
4863 /* Add path to peers? */
4867 path_add_to_peers (p, GNUNET_YES);
4873 connection_change_state (c, MESH_CONNECTION_READY);
4874 connection_reset_timeout (c, GNUNET_NO);
4876 /* Message for us? */
4877 if (NULL != c->t->channel_head)
4879 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " It's for us!\n");
4880 if (3 <= tunnel_count_connections(c->t) && NULL != c->t->peer->dhtget)
4882 GNUNET_DHT_get_stop (c->t->peer->dhtget);
4883 c->t->peer->dhtget = NULL;
4885 //connection_send_ack (c, GNUNET_NO); /* FIXME */
4889 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " not for us, retransmitting...\n");
4890 send_prebuilt_message_connection (message, c, NULL, GNUNET_NO);
4896 * Core handler for notifications of broken paths
4898 * @param cls Closure (unused).
4899 * @param peer Peer identity of sending neighbor.
4900 * @param message Message.
4902 * @return GNUNET_OK to keep the connection open,
4903 * GNUNET_SYSERR to close it (signal serious error)
4906 handle_mesh_connection_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
4907 const struct GNUNET_MessageHeader *message)
4909 struct GNUNET_MESH_ConnectionBroken *msg;
4910 struct MeshConnection *c;
4912 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4913 "Received a CONNECTION BROKEN msg from %s\n", GNUNET_i2s (peer));
4914 msg = (struct GNUNET_MESH_ConnectionBroken *) message;
4915 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " regarding %s\n",
4916 GNUNET_i2s (&msg->peer1));
4917 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " regarding %s\n",
4918 GNUNET_i2s (&msg->peer2));
4919 c = connection_get (&msg->tid, ntohl (msg->cid));
4922 GNUNET_break_op (0);
4925 tunnel_notify_connection_broken (c->t, GNUNET_PEER_search (&msg->peer1),
4926 GNUNET_PEER_search (&msg->peer2));
4933 * Core handler for tunnel destruction
4935 * @param cls Closure (unused).
4936 * @param peer Peer identity of sending neighbor.
4937 * @param message Message.
4939 * @return GNUNET_OK to keep the connection open,
4940 * GNUNET_SYSERR to close it (signal serious error)
4943 handle_mesh_connection_destroy (void *cls,
4944 const struct GNUNET_PeerIdentity *peer,
4945 const struct GNUNET_MessageHeader *message)
4947 struct GNUNET_MESH_ConnectionDestroy *msg;
4948 struct MeshConnection *c;
4952 msg = (struct GNUNET_MESH_ConnectionDestroy *) message;
4953 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4954 "Got a CONNECTION DESTROY message from %s\n",
4956 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4957 " for connection %s[%X]\n",
4958 GNUNET_h2s (&msg->tid), ntohl (msg->cid));
4959 c = connection_get (&msg->tid, ntohl (msg->cid));
4962 /* Probably already got the message from another path,
4963 * destroyed the tunnel and retransmitted to children.
4966 GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
4970 id = GNUNET_PEER_search (peer);
4971 if (id == connection_get_prev_hop (c)->id)
4973 else if (id == connection_get_next_hop (c)->id)
4977 GNUNET_break_op (0);
4980 send_prebuilt_message_connection (message, c, NULL, fwd);
4981 c->destroy = GNUNET_YES;
4987 * Handler for channel create messages.
4989 * @param t Tunnel this channel is to be created in.
4990 * @param msg Message.
4991 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
4993 * @return GNUNET_OK to keep the connection open,
4994 * GNUNET_SYSERR to close it (signal serious error)
4997 handle_channel_create (struct MeshTunnel2 *t,
4998 struct GNUNET_MESH_ChannelCreate *msg,
5001 MESH_ChannelNumber chid;
5002 struct MeshChannel *ch;
5003 struct MeshClient *c;
5005 /* Check message size */
5006 if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelCreate))
5008 GNUNET_break_op (0);
5012 /* Check if channel exists */
5013 chid = ntohl (msg->chid);
5014 ch = channel_get (t, chid);
5017 /* Probably a retransmission, safe to ignore */
5021 /* Find a destination client */
5022 c = GNUNET_CONTAINER_multihashmap32_get (ports, msg->port);
5025 /* TODO send reject */
5029 /* Create channel */
5030 ch = channel_new (t, NULL, 0);
5031 channel_set_options (ch, ntohl (msg->opt));
5032 channel_add_client (ch, c);
5033 if (GNUNET_YES == ch->reliable)
5035 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
5036 ch->bck_rel = GNUNET_malloc (sizeof (struct MeshChannelReliability));
5037 ch->bck_rel->ch = ch;
5038 ch->bck_rel->expected_delay = MESH_RETRANSMIT_TIME;
5041 send_local_channel_create (ch);
5048 * Handler for channel destroy messages.
5050 * @param t Tunnel this channel is to be destroyed of.
5051 * @param msg Message.
5052 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5054 * @return GNUNET_OK to keep the connection open,
5055 * GNUNET_SYSERR to close it (signal serious error)
5058 handle_channel_destroy (struct MeshTunnel2 *t,
5059 struct GNUNET_MESH_ChannelDestroy *msg,
5062 MESH_ChannelNumber chid;
5063 struct MeshChannel *ch;
5065 /* Check message size */
5066 if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelDestroy))
5068 GNUNET_break_op (0);
5072 /* Check if channel exists */
5073 chid = ntohl (msg->chid);
5074 ch = channel_get (t, chid);
5077 /* Probably a retransmission, safe to ignore */
5081 send_local_channel_destroy (ch, fwd);
5082 channel_destroy (ch);
5089 * Generic handler for mesh network encrypted traffic.
5091 * @param peer Peer identity this notification is about.
5092 * @param message Encrypted message.
5093 * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5095 * @return GNUNET_OK to keep the connection open,
5096 * GNUNET_SYSERR to close it (signal serious error)
5099 handle_mesh_encrypted (const struct GNUNET_PeerIdentity *peer,
5100 const struct GNUNET_MESH_Encrypted *msg,
5103 struct MeshConnection *c;
5104 struct MeshTunnel2 *t;
5105 struct MeshPeer *neighbor;
5106 struct MeshFlowControl *fc;
5113 size = ntohs (msg->header.size);
5115 sizeof (struct GNUNET_MESH_Encrypted) +
5116 sizeof (struct GNUNET_MessageHeader))
5121 type = ntohs (msg->header.type);
5122 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message from %s\n",
5123 GNUNET_MESH_DEBUG_M2S (type), GNUNET_i2s (peer));
5125 /* Check connection */
5126 c = connection_get (&msg->tid, ntohl (msg->cid));
5129 GNUNET_STATISTICS_update (stats, "# unknown connection", 1, GNUNET_NO);
5130 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING connection unknown\n");
5134 fc = fwd ? &c->fwd_fc : &c->bck_fc;
5136 /* Check if origin is as expected */
5137 neighbor = connection_get_hop (c, fwd);
5138 if (peer_get (peer)->id != neighbor->id)
5140 GNUNET_break_op (0);
5145 pid = ntohl (msg->pid);
5146 if (GMC_is_pid_bigger (pid, fc->last_ack_sent))
5148 GNUNET_STATISTICS_update (stats, "# unsolicited message", 1, GNUNET_NO);
5149 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5150 "WARNING Received PID %u, (prev %u), ACK %u\n",
5151 pid, fc->last_pid_recv, fc->last_ack_sent);
5154 if (GNUNET_NO == GMC_is_pid_bigger (pid, fc->last_pid_recv))
5156 GNUNET_STATISTICS_update (stats, "# duplicate PID", 1, GNUNET_NO);
5157 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5158 " Pid %u not expected (%u+), dropping!\n",
5159 pid, fc->last_pid_recv + 1);
5162 if (MESH_CONNECTION_SENT == c->state)
5163 connection_change_state (c, MESH_CONNECTION_READY);
5164 connection_reset_timeout (c, fwd);
5165 fc->last_pid_recv = pid;
5167 /* Is this message for us? */
5168 if (NULL != c->t->channel_head)
5170 size_t dsize = size - sizeof (struct GNUNET_MESH_Encrypted);
5172 struct GNUNET_MessageHeader *msgh;
5174 /* TODO signature verification */
5175 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " it's for us!\n");
5176 GNUNET_STATISTICS_update (stats, "# messages received", 1, GNUNET_NO);
5178 fc->last_pid_recv = pid;
5179 tunnel_decrypt (t, cbuf, &msg[1], dsize, msg->iv, fwd);
5180 msgh = (struct GNUNET_MessageHeader *) cbuf;
5181 switch (ntohs (msgh->type))
5183 case GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK:
5184 if (GNUNET_YES == fwd)
5185 return handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh,
5187 GNUNET_break_op (0);
5189 case GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK:
5190 if (GNUNET_NO == fwd)
5191 return handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh,
5193 GNUNET_break_op (0);
5195 case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
5196 if (GNUNET_YES == fwd)
5197 handle_data (t, (struct GNUNET_MESH_Data *) msgh, GNUNET_YES);
5198 GNUNET_break_op (0);
5200 case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
5201 if (GNUNET_NO == fwd)
5202 handle_data (t, (struct GNUNET_MESH_Data *) msgh, GNUNET_NO);
5203 GNUNET_break_op (0);
5205 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
5206 return handle_channel_create (t,
5207 (struct GNUNET_MESH_ChannelCreate *) msgh,
5210 case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
5211 return handle_channel_destroy (t,
5212 (struct GNUNET_MESH_ChannelDestroy *)
5217 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5218 "end-to-end message not known (%u)\n",
5219 ntohs (msgh->type));
5222 connection_send_ack (c, fwd);
5226 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " not for us, retransmitting...\n");
5227 ttl = ntohl (msg->ttl);
5228 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ttl: %u\n", ttl);
5231 GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5232 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5233 connection_send_ack (c, fwd);
5236 GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
5238 send_prebuilt_message_connection (&msg->header, c, NULL, fwd);
5239 connection_send_ack (c, fwd);
5246 * Core handler for mesh network traffic going orig->dest.
5248 * @param cls Closure (unused).
5249 * @param message Message received.
5250 * @param peer Peer who sent the message.
5252 * @return GNUNET_OK to keep the connection open,
5253 * GNUNET_SYSERR to close it (signal serious error)
5256 handle_mesh_fwd (void *cls, const struct GNUNET_PeerIdentity *peer,
5257 const struct GNUNET_MessageHeader *message)
5259 return handle_mesh_encrypted (peer,
5260 (struct GNUNET_MESH_Encrypted *)message,
5265 * Core handler for mesh network traffic going dest->orig.
5267 * @param cls Closure (unused).
5268 * @param message Message received.
5269 * @param peer Peer who sent the message.
5271 * @return GNUNET_OK to keep the connection open,
5272 * GNUNET_SYSERR to close it (signal serious error)
5275 handle_mesh_bck (void *cls, const struct GNUNET_PeerIdentity *peer,
5276 const struct GNUNET_MessageHeader *message)
5278 return handle_mesh_encrypted (peer,
5279 (struct GNUNET_MESH_Encrypted *)message,
5285 * Core handler for mesh network traffic point-to-point acks.
5287 * @param cls closure
5288 * @param message message
5289 * @param peer peer identity this notification is about
5291 * @return GNUNET_OK to keep the connection open,
5292 * GNUNET_SYSERR to close it (signal serious error)
5295 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5296 const struct GNUNET_MessageHeader *message)
5298 struct GNUNET_MESH_ACK *msg;
5299 struct MeshConnection *c;
5300 struct MeshFlowControl *fc;
5304 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
5306 msg = (struct GNUNET_MESH_ACK *) message;
5308 c = connection_get (&msg->tid, ntohl (msg->cid));
5312 GNUNET_STATISTICS_update (stats, "# ack on unknown connection", 1,
5317 ack = ntohl (msg->ack);
5318 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", ack);
5320 /* Is this a forward or backward ACK? */
5321 id = GNUNET_PEER_search (peer);
5322 if (connection_get_next_hop (c)->id == id)
5324 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " FWD ACK\n");
5327 else if (connection_get_prev_hop (c)->id == id)
5329 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " BCK ACK\n");
5334 GNUNET_break_op (0);
5338 /* Cancel polling if the ACK is bigger than before. */
5339 if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task &&
5340 GMC_is_pid_bigger (ack, fc->last_ack_recv))
5342 GNUNET_SCHEDULER_cancel (fc->poll_task);
5343 fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
5344 fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
5347 fc->last_ack_recv = ack;
5348 connection_unlock_queue (c, fc == &c->fwd_fc);
5355 * Core handler for mesh network traffic point-to-point ack polls.
5357 * @param cls closure
5358 * @param message message
5359 * @param peer peer identity this notification is about
5361 * @return GNUNET_OK to keep the connection open,
5362 * GNUNET_SYSERR to close it (signal serious error)
5365 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
5366 const struct GNUNET_MessageHeader *message)
5368 struct GNUNET_MESH_Poll *msg;
5369 struct MeshConnection *c;
5370 struct MeshFlowControl *fc;
5374 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a POLL packet from %s!\n",
5377 msg = (struct GNUNET_MESH_Poll *) message;
5379 c = connection_get (&msg->tid, ntohl (msg->cid));
5383 GNUNET_STATISTICS_update (stats, "# poll on unknown connection", 1,
5385 GNUNET_break_op (0);
5389 /* Is this a forward or backward ACK? */
5390 id = GNUNET_PEER_search (peer);
5391 if (connection_get_next_hop (c)->id == id)
5393 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " FWD ACK\n");
5396 else if (connection_get_prev_hop (c)->id == id)
5398 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " BCK ACK\n");
5403 GNUNET_break_op (0);
5407 pid = ntohl (msg->pid);
5408 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " PID %u, OLD %u\n",
5409 pid, fc->last_pid_recv);
5410 fc->last_pid_recv = pid;
5411 connection_send_ack (c, fc == &c->fwd_fc);
5418 * Core handler for mesh keepalives.
5420 * @param cls closure
5421 * @param message message
5422 * @param peer peer identity this notification is about
5423 * @return GNUNET_OK to keep the connection open,
5424 * GNUNET_SYSERR to close it (signal serious error)
5426 * TODO: Check who we got this from, to validate route.
5429 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
5430 const struct GNUNET_MessageHeader *message)
5432 struct GNUNET_MESH_ConnectionKeepAlive *msg;
5433 struct MeshConnection *c;
5434 struct MeshPeer *neighbor;
5437 msg = (struct GNUNET_MESH_ConnectionKeepAlive *) message;
5438 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
5441 c = connection_get (&msg->tid, ntohl (msg->cid));
5444 GNUNET_STATISTICS_update (stats, "# keepalive on unknown connection", 1,
5449 fwd = GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE == ntohs (message->type) ?
5450 GNUNET_YES : GNUNET_NO;
5452 /* Check if origin is as expected */
5453 neighbor = connection_get_hop (c, fwd);
5454 if (peer_get (peer)->id != neighbor->id)
5456 GNUNET_break_op (0);
5460 connection_change_state (c, MESH_CONNECTION_READY);
5461 connection_reset_timeout (c, fwd);
5463 if (NULL != c->t->channel_head)
5466 GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
5467 send_prebuilt_message_connection (message, c, NULL, fwd);
5475 * Functions to handle messages from core
5477 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
5478 {&handle_mesh_connection_create, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
5480 {&handle_mesh_connection_ack, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
5481 sizeof (struct GNUNET_MESH_ConnectionACK)},
5482 {&handle_mesh_connection_broken, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN,
5483 sizeof (struct GNUNET_MESH_ConnectionBroken)},
5484 {&handle_mesh_connection_destroy, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY,
5485 sizeof (struct GNUNET_MESH_ConnectionDestroy)},
5486 {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE,
5487 sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
5488 {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE,
5489 sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
5490 {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
5491 sizeof (struct GNUNET_MESH_ACK)},
5492 {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
5493 sizeof (struct GNUNET_MESH_Poll)},
5494 {&handle_mesh_fwd, GNUNET_MESSAGE_TYPE_MESH_FWD, 0},
5495 {&handle_mesh_bck, GNUNET_MESSAGE_TYPE_MESH_BCK, 0},
5501 * Function to process paths received for a new peer addition. The recorded
5502 * paths form the initial tunnel, which can be optimized later.
5503 * Called on each result obtained for the DHT search.
5505 * @param cls closure
5506 * @param exp when will this value expire
5507 * @param key key of the result
5508 * @param get_path path of the get request
5509 * @param get_path_length lenght of get_path
5510 * @param put_path path of the put request
5511 * @param put_path_length length of the put_path
5512 * @param type type of the result
5513 * @param size number of bytes in data
5514 * @param data pointer to the result data
5517 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5518 const struct GNUNET_HashCode * key,
5519 const struct GNUNET_PeerIdentity *get_path,
5520 unsigned int get_path_length,
5521 const struct GNUNET_PeerIdentity *put_path,
5522 unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5523 size_t size, const void *data)
5525 struct MeshPeer *peer = cls;
5526 struct MeshPeerPath *p;
5527 struct MeshConnection *c;
5528 struct GNUNET_PeerIdentity pi;
5531 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
5532 GNUNET_PEER_resolve (peer->id, &pi);
5533 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " for %s\n", GNUNET_i2s (&pi));
5535 p = path_build_from_dht (get_path, get_path_length,
5536 put_path, put_path_length);
5537 path_add_to_peers (p, GNUNET_NO);
5540 /* Count connections */
5541 for (c = peer->tunnel->connection_head, i = 0; NULL != c; c = c->next, i++);
5543 /* If we already have 3 (or more (?!)) connections, it's enough */
5547 if (peer->tunnel->state == MESH_TUNNEL_SEARCHING)
5549 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... connect!\n");
5550 peer_connect (peer);
5556 /******************************************************************************/
5557 /********************* MESH LOCAL HANDLES **************************/
5558 /******************************************************************************/
5562 * Handler for client connection.
5564 * @param cls Closure (unused).
5565 * @param client Client handler.
5568 handle_local_client_connect (void *cls, struct GNUNET_SERVER_Client *client)
5570 struct MeshClient *c;
5574 c = GNUNET_malloc (sizeof (struct MeshClient));
5576 c->id = next_client_id++; /* overflow not important: just for debug */
5577 GNUNET_SERVER_client_keep (client);
5578 GNUNET_SERVER_client_set_user_context (client, c);
5579 GNUNET_CONTAINER_DLL_insert (clients_head, clients_tail, c);
5584 * Handler for client disconnection
5586 * @param cls closure
5587 * @param client identification of the client; NULL
5588 * for the last call when the server is destroyed
5591 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
5593 struct MeshClient *c;
5594 struct MeshClient *next;
5596 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected: %p\n", client);
5599 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " (SERVER DOWN)\n");
5603 c = client_get (client);
5606 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u, %p)\n",
5608 GNUNET_SERVER_client_drop (c->handle);
5609 c->shutting_down = GNUNET_YES;
5610 if (NULL != c->own_channels)
5612 GNUNET_CONTAINER_multihashmap32_iterate (c->own_channels,
5613 &channel_destroy_iterator, c);
5614 GNUNET_CONTAINER_multihashmap32_destroy (c->own_channels);
5617 if (NULL != c->incoming_channels)
5619 GNUNET_CONTAINER_multihashmap32_iterate (c->incoming_channels,
5620 &channel_destroy_iterator, c);
5621 GNUNET_CONTAINER_multihashmap32_destroy (c->incoming_channels);
5624 if (NULL != c->ports)
5626 GNUNET_CONTAINER_multihashmap32_iterate (c->ports,
5627 &client_release_ports, c);
5628 GNUNET_CONTAINER_multihashmap32_destroy (c->ports);
5631 GNUNET_CONTAINER_DLL_remove (clients_head, clients_tail, c);
5632 GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
5633 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " client free (%p)\n", c);
5639 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " context NULL!\n");
5641 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "done!\n");
5647 * Handler for new clients
5649 * @param cls closure
5650 * @param client identification of the client
5651 * @param message the actual message, which includes messages the client wants
5654 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
5655 const struct GNUNET_MessageHeader *message)
5657 struct GNUNET_MESH_ClientConnect *cc_msg;
5658 struct MeshClient *c;
5663 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected %p\n", client);
5665 /* Check data sanity */
5666 size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
5667 cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
5668 if (0 != (size % sizeof (uint32_t)))
5671 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5674 size /= sizeof (uint32_t);
5676 /* Initialize new client structure */
5677 c = GNUNET_SERVER_client_get_user_context (client, struct MeshClient);
5678 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " client id %u\n", c->id);
5679 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " client has %u ports\n", size);
5684 p = (uint32_t *) &cc_msg[1];
5685 c->ports = GNUNET_CONTAINER_multihashmap32_create (size);
5686 for (i = 0; i < size; i++)
5689 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " port: %u\n", u32);
5691 /* store in client's hashmap */
5692 GNUNET_CONTAINER_multihashmap32_put (c->ports, u32, c,
5693 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
5694 /* store in global hashmap */
5695 /* FIXME only allow one client to have the port open,
5696 * have a backup hashmap with waiting clients */
5697 GNUNET_CONTAINER_multihashmap32_put (ports, u32, c,
5698 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
5702 c->own_channels = GNUNET_CONTAINER_multihashmap32_create (32);
5703 c->incoming_channels = GNUNET_CONTAINER_multihashmap32_create (32);
5704 GNUNET_SERVER_notification_context_add (nc, client);
5705 GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
5707 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5708 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
5713 * Handler for requests of new tunnels
5715 * @param cls Closure.
5716 * @param client Identification of the client.
5717 * @param message The actual message.
5720 handle_local_channel_create (void *cls, struct GNUNET_SERVER_Client *client,
5721 const struct GNUNET_MessageHeader *message)
5723 struct GNUNET_MESH_ChannelMessage *msg;
5724 struct MeshPeer *peer;
5725 struct MeshTunnel2 *t;
5726 struct MeshChannel *ch;
5727 struct MeshClient *c;
5728 MESH_ChannelNumber chid;
5730 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new channel requested\n");
5732 /* Sanity check for client registration */
5733 if (NULL == (c = client_get (client)))
5736 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5739 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
5741 /* Message size sanity check */
5742 if (sizeof (struct GNUNET_MESH_ChannelMessage) != ntohs (message->size))
5745 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5749 msg = (struct GNUNET_MESH_ChannelMessage *) message;
5750 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " towards %s:%u\n",
5751 GNUNET_i2s (&msg->peer), ntohl (msg->port));
5752 chid = ntohl (msg->channel_id);
5754 /* Sanity check for duplicate channel IDs */
5755 if (NULL != channel_get_by_local_id (c, chid))
5758 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5762 peer = peer_get (&msg->peer);
5763 if (NULL == peer->tunnel)
5765 struct GNUNET_HashCode tid;
5767 GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE, &tid);
5768 peer->tunnel = tunnel_new (&tid);
5772 /* Create channel */
5773 ch = channel_new (t, c, chid);
5777 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5780 ch->port = ntohl (msg->port);
5781 channel_set_options (ch, ntohl (msg->opt));
5783 /* In unreliable channels, we'll use the DLL to buffer data for the root */
5784 ch->fwd_rel = GNUNET_malloc (sizeof (struct MeshChannelReliability));
5785 ch->fwd_rel->ch = ch;
5786 ch->fwd_rel->expected_delay = MESH_RETRANSMIT_TIME;
5788 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED CHANNEL %s[%x]:%u (%x)\n",
5789 GNUNET_h2s (&t->id), ch->gid, ch->port, ch->lid_root);
5790 peer_connect (peer);
5791 /* FIXME send create channel */
5793 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5799 * Handler for requests of deleting tunnels
5801 * @param cls closure
5802 * @param client identification of the client
5803 * @param message the actual message
5806 handle_local_channel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
5807 const struct GNUNET_MessageHeader *message)
5809 struct GNUNET_MESH_ChannelMessage *msg;
5810 struct MeshClient *c;
5811 struct MeshChannel *ch;
5812 struct MeshTunnel2 *t;
5813 MESH_ChannelNumber chid;
5815 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5816 "Got a DESTROY CHANNEL from client!\n");
5818 /* Sanity check for client registration */
5819 if (NULL == (c = client_get (client)))
5822 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5825 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
5827 /* Message sanity check */
5828 if (sizeof (struct GNUNET_MESH_ChannelMessage) != ntohs (message->size))
5831 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5835 msg = (struct GNUNET_MESH_ChannelMessage *) message;
5837 /* Retrieve tunnel */
5838 chid = ntohl (msg->channel_id);
5839 ch = channel_get_by_local_id (c, chid);
5842 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, " channel %X not found\n", chid);
5844 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5848 /* Cleanup after the tunnel */
5849 client_delete_channel (c, ch);
5850 if (c == ch->dest && GNUNET_MESH_LOCAL_CHANNEL_ID_SERV <= chid)
5854 else if (c == ch->root && GNUNET_MESH_LOCAL_CHANNEL_ID_SERV > chid)
5860 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5861 " channel %X client %p (%p, %p)\n",
5862 chid, c, ch->root, ch->dest);
5867 channel_destroy (ch);
5868 tunnel_destroy_if_empty (t);
5870 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5876 * Handler for client traffic
5878 * @param cls closure
5879 * @param client identification of the client
5880 * @param message the actual message
5883 handle_local_data (void *cls, struct GNUNET_SERVER_Client *client,
5884 const struct GNUNET_MessageHeader *message)
5886 struct GNUNET_MESH_LocalData *msg;
5887 struct MeshClient *c;
5888 struct MeshChannel *ch;
5889 MESH_ChannelNumber chid;
5893 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5894 "Got data from a client!\n");
5896 /* Sanity check for client registration */
5897 if (NULL == (c = client_get (client)))
5900 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5903 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
5905 msg = (struct GNUNET_MESH_LocalData *) message;
5907 /* Sanity check for message size */
5908 size = ntohs (message->size) - sizeof (struct GNUNET_MESH_LocalData);
5909 if (size < sizeof (struct GNUNET_MessageHeader))
5912 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5916 /* Channel exists? */
5917 chid = ntohl (msg->id);
5918 fwd = chid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
5919 ch = channel_get_by_local_id (c, chid);
5923 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5927 /* Is the client in the channel? */
5930 ch->root->handle == client)
5934 ch->dest->handle == client) ) )
5937 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5941 /* Ok, everything is correct, send the message
5942 * (pretend we got it from a mesh peer)
5945 struct GNUNET_MESH_Data *payload;
5946 char cbuf[sizeof(struct GNUNET_MESH_Data) + size];
5949 mid = fwd ? &ch->mid_send_fwd : &ch->mid_send_bck;
5950 if (GNUNET_YES == ch->reliable)
5952 struct MeshChannelReliability *rel;
5953 struct MeshReliableMessage *copy;
5955 rel = fwd ? ch->fwd_rel : ch->bck_rel;
5956 copy = GNUNET_malloc (sizeof (struct MeshReliableMessage)
5957 + sizeof(struct GNUNET_MESH_Data)
5960 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! DATA %u\n", copy->mid);
5961 copy->timestamp = GNUNET_TIME_absolute_get ();
5964 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " n_sent %u\n", rel->n_sent);
5965 GNUNET_CONTAINER_DLL_insert_tail (rel->head_sent, rel->tail_sent, copy);
5966 if (GNUNET_SCHEDULER_NO_TASK == rel->retry_task)
5969 GNUNET_TIME_relative_multiply (rel->expected_delay,
5970 MESH_RETRANSMIT_MARGIN);
5972 GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
5973 &channel_retransmit_message,
5976 payload = (struct GNUNET_MESH_Data *) ©[1];
5980 payload = (struct GNUNET_MESH_Data *) cbuf;
5982 payload->mid = htonl (*mid);
5984 memcpy (&payload[1], &msg[1], size);
5985 payload->header.size = htons (sizeof (struct GNUNET_MESH_Data) + size);
5986 payload->header.type = htons (chid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV ?
5987 GNUNET_MESSAGE_TYPE_MESH_UNICAST :
5988 GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
5989 payload->chid = htonl (ch->gid);
5990 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5991 " calling generic handler...\n");
5992 send_prebuilt_message_channel (&payload->header, ch, fwd);
5994 if (tunnel_get_buffer (ch->t, fwd) > 0)
5995 send_local_ack (ch, c, fwd);
5996 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
5997 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6004 * Handler for client's ACKs for payload traffic.
6006 * @param cls Closure (unused).
6007 * @param client Identification of the client.
6008 * @param message The actual message.
6011 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
6012 const struct GNUNET_MessageHeader *message)
6014 struct GNUNET_MESH_LocalAck *msg;
6015 struct MeshChannelReliability *rel;
6016 struct MeshChannel *ch;
6017 struct MeshClient *c;
6018 MESH_ChannelNumber chid;
6021 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
6023 /* Sanity check for client registration */
6024 if (NULL == (c = client_get (client)))
6027 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6030 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " by client %u\n", c->id);
6032 msg = (struct GNUNET_MESH_LocalAck *) message;
6034 /* Channel exists? */
6035 chid = ntohl (msg->channel_id);
6036 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " on channel %X\n", chid);
6037 ch = channel_get_by_local_id (c, chid);
6041 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Channel %X unknown.\n", chid);
6042 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " for client %u.\n", c->id);
6043 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6047 fwd = chid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
6048 rel = fwd ? ch->fwd_rel : ch->bck_rel;
6050 rel->client_ready = GNUNET_YES;
6051 channel_send_client_buffered_data (ch, c, rel);
6052 channel_send_ack (ch, 64 - rel->n_recv, fwd);
6054 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6061 * Iterator over all tunnels to send a monitoring client info about each tunnel.
6063 * @param cls Closure (client handle).
6064 * @param key Key (hashed tunnel ID, unused).
6065 * @param value Tunnel info.
6067 * @return GNUNET_YES, to keep iterating.
6070 monitor_all_tunnels_iterator (void *cls,
6071 const struct GNUNET_HashCode * key,
6074 struct GNUNET_SERVER_Client *client = cls;
6075 struct MeshChannel *ch = value;
6076 struct GNUNET_MESH_LocalMonitor *msg;
6078 msg = GNUNET_malloc (sizeof(struct GNUNET_MESH_LocalMonitor));
6079 msg->channel_id = htonl (ch->gid);
6080 msg->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
6081 msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
6083 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6084 "* sending info about tunnel %s\n",
6085 GNUNET_i2s (&msg->owner));
6087 GNUNET_SERVER_notification_context_unicast (nc, client,
6088 &msg->header, GNUNET_NO);
6094 * Handler for client's MONITOR request.
6096 * @param cls Closure (unused).
6097 * @param client Identification of the client.
6098 * @param message The actual message.
6101 handle_local_get_tunnels (void *cls, struct GNUNET_SERVER_Client *client,
6102 const struct GNUNET_MessageHeader *message)
6104 struct MeshClient *c;
6106 /* Sanity check for client registration */
6107 if (NULL == (c = client_get (client)))
6110 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6114 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6115 "Received get tunnels request from client %u\n",
6117 GNUNET_CONTAINER_multihashmap_iterate (tunnels,
6118 monitor_all_tunnels_iterator,
6120 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6121 "Get tunnels request from client %u completed\n",
6123 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6128 * Handler for client's MONITOR_TUNNEL request.
6130 * @param cls Closure (unused).
6131 * @param client Identification of the client.
6132 * @param message The actual message.
6135 handle_local_show_tunnel (void *cls, struct GNUNET_SERVER_Client *client,
6136 const struct GNUNET_MessageHeader *message)
6138 const struct GNUNET_MESH_LocalMonitor *msg;
6139 struct GNUNET_MESH_LocalMonitor *resp;
6140 struct MeshClient *c;
6141 struct MeshChannel *ch;
6143 /* Sanity check for client registration */
6144 if (NULL == (c = client_get (client)))
6147 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6151 msg = (struct GNUNET_MESH_LocalMonitor *) message;
6152 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6153 "Received tunnel info request from client %u for tunnel %s[%X]\n",
6156 ntohl (msg->channel_id));
6157 // ch = channel_get (&msg->owner, ntohl (msg->channel_id));
6161 /* We don't know the tunnel */
6162 struct GNUNET_MESH_LocalMonitor warn;
6165 GNUNET_SERVER_notification_context_unicast (nc, client,
6168 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6172 /* Initialize context */
6173 resp = GNUNET_malloc (sizeof (struct GNUNET_MESH_LocalMonitor));
6175 resp->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
6176 GNUNET_SERVER_notification_context_unicast (nc, c->handle,
6177 &resp->header, GNUNET_NO);
6180 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6181 "Monitor tunnel request from client %u completed\n",
6183 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6188 * Functions to handle messages from clients
6190 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
6191 {&handle_local_new_client, NULL,
6192 GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
6193 {&handle_local_channel_create, NULL,
6194 GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE,
6195 sizeof (struct GNUNET_MESH_ChannelMessage)},
6196 {&handle_local_channel_destroy, NULL,
6197 GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY,
6198 sizeof (struct GNUNET_MESH_ChannelMessage)},
6199 {&handle_local_data, NULL,
6200 GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA, 0},
6201 {&handle_local_ack, NULL,
6202 GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
6203 sizeof (struct GNUNET_MESH_LocalAck)},
6204 {&handle_local_get_tunnels, NULL,
6205 GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS,
6206 sizeof (struct GNUNET_MessageHeader)},
6207 {&handle_local_show_tunnel, NULL,
6208 GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL,
6209 sizeof (struct GNUNET_MESH_LocalMonitor)},
6215 * Method called whenever a given peer connects.
6217 * @param cls closure
6218 * @param peer peer identity this notification is about
6221 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
6223 struct MeshPeer *pi;
6224 struct MeshPeerPath *path;
6226 DEBUG_CONN ("Peer connected\n");
6227 DEBUG_CONN (" %s\n", GNUNET_i2s (&my_full_id));
6228 pi = peer_get (peer);
6231 DEBUG_CONN (" (self)\n");
6232 path = path_new (1);
6236 DEBUG_CONN (" %s\n", GNUNET_i2s (peer));
6237 path = path_new (2);
6238 path->peers[1] = pi->id;
6239 GNUNET_PEER_change_rc (pi->id, 1);
6240 GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
6242 path->peers[0] = myid;
6243 GNUNET_PEER_change_rc (myid, 1);
6244 peer_add_path (pi, path, GNUNET_YES);
6246 pi->connections = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_YES);
6252 * Method called whenever a peer disconnects.
6254 * @param cls closure
6255 * @param peer peer identity this notification is about
6258 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
6260 struct MeshPeer *pi;
6262 DEBUG_CONN ("Peer disconnected\n");
6263 pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
6270 peer_remove_path (pi, myid, pi->id);
6272 GNUNET_CONTAINER_multihashmap_iterate (pi->connections,
6275 GNUNET_CONTAINER_multihashmap_destroy (pi->connections);
6276 pi->connections = NULL;
6279 DEBUG_CONN (" (self)\n");
6281 GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
6288 * Install server (service) handlers and start listening to clients.
6293 GNUNET_SERVER_add_handlers (server_handle, client_handlers);
6294 GNUNET_SERVER_connect_notify (server_handle,
6295 &handle_local_client_connect, NULL);
6296 GNUNET_SERVER_disconnect_notify (server_handle,
6297 &handle_local_client_disconnect, NULL);
6298 nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
6300 clients_head = NULL;
6301 clients_tail = NULL;
6303 GNUNET_SERVER_resume (server_handle);
6308 * To be called on core init/fail.
6310 * @param cls Closure (config)
6311 * @param server handle to the server for this service
6312 * @param identity the public identity of this peer
6315 core_init (void *cls, struct GNUNET_CORE_Handle *server,
6316 const struct GNUNET_PeerIdentity *identity)
6318 const struct GNUNET_CONFIGURATION_Handle *c = cls;
6321 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
6322 GNUNET_break (core_handle == server);
6323 if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
6326 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
6327 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6329 GNUNET_i2s (identity));
6330 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6332 GNUNET_i2s (&my_full_id));
6333 GNUNET_CORE_disconnect (core_handle);
6334 core_handle = GNUNET_CORE_connect (c, /* Main configuration */
6335 NULL, /* Closure passed to MESH functions */
6336 &core_init, /* Call core_init once connected */
6337 &core_connect, /* Handle connects */
6338 &core_disconnect, /* remove peers on disconnects */
6339 NULL, /* Don't notify about all incoming messages */
6340 GNUNET_NO, /* For header only in notification */
6341 NULL, /* Don't notify about all outbound messages */
6342 GNUNET_NO, /* For header-only out notification */
6343 core_handlers); /* Register these handlers */
6352 /******************************************************************************/
6353 /************************ MAIN FUNCTIONS ****************************/
6354 /******************************************************************************/
6357 * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
6359 * @param cls closure
6360 * @param key current key code
6361 * @param value value in the hash map
6362 * @return GNUNET_YES if we should continue to iterate,
6366 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
6368 struct MeshTunnel2 *t = value;
6376 * Task run during shutdown.
6382 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
6384 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
6386 if (core_handle != NULL)
6388 GNUNET_CORE_disconnect (core_handle);
6391 GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
6392 if (dht_handle != NULL)
6394 GNUNET_DHT_disconnect (dht_handle);
6399 GNUNET_SERVER_notification_context_destroy (nc);
6402 if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
6404 GNUNET_SCHEDULER_cancel (announce_id_task);
6405 announce_id_task = GNUNET_SCHEDULER_NO_TASK;
6407 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
6412 * Process mesh requests.
6414 * @param cls closure
6415 * @param server the initialized server
6416 * @param c configuration to use
6419 run (void *cls, struct GNUNET_SERVER_Handle *server,
6420 const struct GNUNET_CONFIGURATION_Handle *c)
6423 struct GNUNET_CRYPTO_EccPrivateKey *pk;
6425 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
6426 server_handle = server;
6427 GNUNET_SERVER_suspend (server_handle);
6430 GNUNET_CONFIGURATION_get_value_filename (c, "PEER", "PRIVATE_KEY",
6433 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6435 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6436 "mesh", "peer/privatekey");
6437 GNUNET_SCHEDULER_shutdown ();
6442 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_CONNECTION_TIME",
6443 &refresh_connection_time))
6445 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6447 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6448 "mesh", "refresh path time");
6449 GNUNET_SCHEDULER_shutdown ();
6454 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
6457 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6459 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6460 "mesh", "id announce time");
6461 GNUNET_SCHEDULER_shutdown ();
6466 GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
6469 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6471 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6472 "mesh", "connect timeout");
6473 GNUNET_SCHEDULER_shutdown ();
6478 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
6481 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6483 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6484 "mesh", "max msgs queue");
6485 GNUNET_SCHEDULER_shutdown ();
6490 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_TUNNELS",
6493 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6495 ("%s service is lacking key configuration settings (%s). Exiting.\n"),
6496 "mesh", "max tunnels");
6497 GNUNET_SCHEDULER_shutdown ();
6502 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
6505 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6507 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
6508 "mesh", "default ttl", 64);
6513 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
6516 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6517 _("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
6518 "mesh", "max peers", 1000);
6523 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DROP_PERCENT",
6530 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6531 "Mesh is running with drop mode enabled. "
6532 "This is NOT a good idea! "
6533 "Remove the DROP_PERCENT option from your configuration.\n");
6537 GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
6538 &dht_replication_level))
6540 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6542 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
6543 "mesh", "dht replication level", 3);
6544 dht_replication_level = 3;
6547 tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6548 peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6549 ports = GNUNET_CONTAINER_multihashmap32_create (32);
6551 dht_handle = GNUNET_DHT_connect (c, 64);
6552 if (NULL == dht_handle)
6556 stats = GNUNET_STATISTICS_create ("mesh", c);
6558 /* Scheduled the task to clean up when shutdown is called */
6559 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
6561 pk = GNUNET_CRYPTO_ecc_key_create_from_file (keyfile);
6562 GNUNET_free (keyfile);
6563 GNUNET_assert (NULL != pk);
6564 my_private_key = pk;
6565 GNUNET_CRYPTO_ecc_key_get_public (my_private_key, &my_public_key);
6566 GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
6567 &my_full_id.hashPubKey);
6568 myid = GNUNET_PEER_intern (&my_full_id);
6569 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6570 "Mesh for peer [%s] starting\n",
6571 GNUNET_i2s(&my_full_id));
6573 core_handle = GNUNET_CORE_connect (c, /* Main configuration */
6574 NULL, /* Closure passed to MESH functions */
6575 &core_init, /* Call core_init once connected */
6576 &core_connect, /* Handle connects */
6577 &core_disconnect, /* remove peers on disconnects */
6578 NULL, /* Don't notify about all incoming messages */
6579 GNUNET_NO, /* For header only in notification */
6580 NULL, /* Don't notify about all outbound messages */
6581 GNUNET_NO, /* For header-only out notification */
6582 core_handlers); /* Register these handlers */
6583 if (NULL == core_handle)
6586 GNUNET_SCHEDULER_shutdown ();
6589 announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
6590 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
6595 * The main function for the mesh service.
6597 * @param argc number of arguments from the command line
6598 * @param argv command line arguments
6599 * @return 0 ok, 1 on error
6602 main (int argc, char *const *argv)
6607 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
6608 r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
6610 ret = (GNUNET_OK == r) ? 0 : 1;
6611 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");