2 This file is part of GNUnet.
3 (C) 2009, 2010 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 2, 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 fs/gnunet-service-fs.c
23 * @brief gnunet anonymity protocol implementation
24 * @author Christian Grothoff
27 * - TTL/priority calculations are absent!
29 * - have non-zero preference / priority for requests we initiate!
30 * - track stats for hot-path routing
31 * - implement hot-path routing decision procedure
32 * - implement: bound_priority, test_load_too_high, validate_nblock
33 * - add content migration support (store locally) [or create new service]
38 #include "gnunet_constants.h"
39 #include "gnunet_core_service.h"
40 #include "gnunet_datastore_service.h"
41 #include "gnunet_peer_lib.h"
42 #include "gnunet_protocols.h"
43 #include "gnunet_signatures.h"
44 #include "gnunet_statistics_service.h"
45 #include "gnunet_util_lib.h"
46 #include "gnunet-service-fs_indexing.h"
49 #define DEBUG_FS GNUNET_NO
52 * Maximum number of outgoing messages we queue per peer.
53 * FIXME: make configurable?
55 #define MAX_QUEUE_PER_PEER 16
58 * Inverse of the probability that we will submit the same query
59 * to the same peer again. If the same peer already got the query
60 * repeatedly recently, the probability is multiplied by the inverse
61 * of this number each time. Note that we only try about every TTL_DECREMENT/2
62 * plus MAX_CORK_DELAY (so roughly every 3.5s).
64 #define RETRY_PROBABILITY_INV 3
67 * What is the maximum delay for a P2P FS message (in our interaction
68 * with core)? FS-internal delays are another story. The value is
69 * chosen based on the 32k block size. Given that peers typcially
70 * have at least 1 kb/s bandwidth, 45s waits give us a chance to
71 * transmit one message even to the lowest-bandwidth peers.
73 #define MAX_TRANSMIT_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 45)
78 * Maximum number of requests (from other peers) that we're
79 * willing to have pending at any given point in time.
80 * FIXME: set from configuration.
82 static uint64_t max_pending_requests = (32 * 1024);
86 * Information we keep for each pending reply. The
87 * actual message follows at the end of this struct.
89 struct PendingMessage;
92 * Our connection to the datastore.
94 static struct GNUNET_DATASTORE_Handle *dsh;
98 * Function called upon completion of a transmission.
101 * @param pid ID of receiving peer, 0 on transmission error
103 typedef void (*TransmissionContinuation)(void * cls,
104 GNUNET_PEER_Id tpid);
108 * Information we keep for each pending message (GET/PUT). The
109 * actual message follows at the end of this struct.
111 struct PendingMessage
114 * This is a doubly-linked list of messages to the same peer.
116 struct PendingMessage *next;
119 * This is a doubly-linked list of messages to the same peer.
121 struct PendingMessage *prev;
124 * Entry in pending message list for this pending message.
126 struct PendingMessageList *pml;
129 * Function to call immediately once we have transmitted this
132 TransmissionContinuation cont;
140 * Size of the reply; actual reply message follows
141 * at the end of this struct.
146 * How important is this message for us?
154 * Information about a peer that we are connected to.
155 * We track data that is useful for determining which
156 * peers should receive our requests. We also keep
157 * a list of messages to transmit to this peer.
163 * List of the last clients for which this peer successfully
166 struct GNUNET_SERVER_Client *last_client_replies[CS2P_SUCCESS_LIST_SIZE];
169 * List of the last PIDs for which
170 * this peer successfully answered a query;
171 * We use 0 to indicate no successful reply.
173 GNUNET_PEER_Id last_p2p_replies[P2P_SUCCESS_LIST_SIZE];
176 * Average delay between sending the peer a request and
177 * getting a reply (only calculated over the requests for
178 * which we actually got a reply). Calculated
179 * as a moving average: new_delay = ((n-1)*last_delay+curr_delay) / n
181 struct GNUNET_TIME_Relative avg_delay;
184 * Handle for an active request for transmission to this
187 struct GNUNET_CORE_TransmitHandle *cth;
190 * Messages (replies, queries, content migration) we would like to
191 * send to this peer in the near future. Sorted by priority, head.
193 struct PendingMessage *pending_messages_head;
196 * Messages (replies, queries, content migration) we would like to
197 * send to this peer in the near future. Sorted by priority, tail.
199 struct PendingMessage *pending_messages_tail;
202 * Average priority of successful replies. Calculated
203 * as a moving average: new_avg = ((n-1)*last_avg+curr_prio) / n
208 * Increase in traffic preference still to be submitted
209 * to the core service for this peer. FIXME: double or 'uint64_t'?
211 double inc_preference;
214 * The peer's identity.
219 * Size of the linked list of 'pending_messages'.
221 unsigned int pending_requests;
224 * Which offset in "last_p2p_replies" will be updated next?
225 * (we go round-robin).
227 unsigned int last_p2p_replies_woff;
230 * Which offset in "last_client_replies" will be updated next?
231 * (we go round-robin).
233 unsigned int last_client_replies_woff;
239 * Information we keep for each pending request. We should try to
240 * keep this struct as small as possible since its memory consumption
241 * is key to how many requests we can have pending at once.
243 struct PendingRequest;
247 * Doubly-linked list of requests we are performing
248 * on behalf of the same client.
250 struct ClientRequestList
254 * This is a doubly-linked list.
256 struct ClientRequestList *next;
259 * This is a doubly-linked list.
261 struct ClientRequestList *prev;
264 * Request this entry represents.
266 struct PendingRequest *req;
269 * Client list this request belongs to.
271 struct ClientList *client_list;
277 * Replies to be transmitted to the client. The actual
278 * response message is allocated after this struct.
280 struct ClientResponseMessage
283 * This is a doubly-linked list.
285 struct ClientResponseMessage *next;
288 * This is a doubly-linked list.
290 struct ClientResponseMessage *prev;
293 * Client list entry this response belongs to.
295 struct ClientList *client_list;
298 * Number of bytes in the response.
305 * Linked list of clients we are performing requests
311 * This is a linked list.
313 struct ClientList *next;
316 * ID of a client making a request, NULL if this entry is for a
319 struct GNUNET_SERVER_Client *client;
322 * Head of list of requests performed on behalf
323 * of this client right now.
325 struct ClientRequestList *rl_head;
328 * Tail of list of requests performed on behalf
329 * of this client right now.
331 struct ClientRequestList *rl_tail;
334 * Head of linked list of responses.
336 struct ClientResponseMessage *res_head;
339 * Tail of linked list of responses.
341 struct ClientResponseMessage *res_tail;
344 * Context for sending replies.
346 struct GNUNET_CONNECTION_TransmitHandle *th;
352 * Doubly-linked list of messages we are performing
353 * due to a pending request.
355 struct PendingMessageList
359 * This is a doubly-linked list of messages on behalf of the same request.
361 struct PendingMessageList *next;
364 * This is a doubly-linked list of messages on behalf of the same request.
366 struct PendingMessageList *prev;
369 * Message this entry represents.
371 struct PendingMessage *pm;
374 * Request this entry belongs to.
376 struct PendingRequest *req;
379 * Peer this message is targeted for.
381 struct ConnectedPeer *target;
387 * Information we keep for each pending request. We should try to
388 * keep this struct as small as possible since its memory consumption
389 * is key to how many requests we can have pending at once.
391 struct PendingRequest
395 * If this request was made by a client, this is our entry in the
396 * client request list; otherwise NULL.
398 struct ClientRequestList *client_request_list;
401 * Entry of peer responsible for this entry (if this request
402 * was made by a peer).
404 struct ConnectedPeer *cp;
407 * If this is a namespace query, pointer to the hash of the public
408 * key of the namespace; otherwise NULL. Pointer will be to the
409 * end of this struct (so no need to free it).
411 const GNUNET_HashCode *namespace;
414 * Bloomfilter we use to filter out replies that we don't care about
415 * (anymore). NULL as long as we are interested in all replies.
417 struct GNUNET_CONTAINER_BloomFilter *bf;
420 * Context of our GNUNET_CORE_peer_change_preference call.
422 struct GNUNET_CORE_InformationRequestContext *irc;
425 * Hash code of all replies that we have seen so far (only valid
426 * if client is not NULL since we only track replies like this for
429 GNUNET_HashCode *replies_seen;
432 * Node in the heap representing this entry; NULL
433 * if we have no heap node.
435 struct GNUNET_CONTAINER_HeapNode *hnode;
438 * Head of list of messages being performed on behalf of this
441 struct PendingMessageList *pending_head;
444 * Tail of list of messages being performed on behalf of this
447 struct PendingMessageList *pending_tail;
450 * When did we first see this request (form this peer), or, if our
451 * client is initiating, when did we last initiate a search?
453 struct GNUNET_TIME_Absolute start_time;
456 * The query that this request is for.
458 GNUNET_HashCode query;
461 * The task responsible for transmitting queries
464 GNUNET_SCHEDULER_TaskIdentifier task;
467 * (Interned) Peer identifier that identifies a preferred target
470 GNUNET_PEER_Id target_pid;
473 * (Interned) Peer identifiers of peers that have already
474 * received our query for this content.
476 GNUNET_PEER_Id *used_pids;
479 * Our entry in the queue (non-NULL while we wait for our
480 * turn to interact with the local database).
482 struct GNUNET_DATASTORE_QueueEntry *qe;
485 * Size of the 'bf' (in bytes).
490 * Desired anonymity level; only valid for requests from a local client.
492 uint32_t anonymity_level;
495 * How many entries in "used_pids" are actually valid?
497 unsigned int used_pids_off;
500 * How long is the "used_pids" array?
502 unsigned int used_pids_size;
505 * Number of results found for this request.
507 unsigned int results_found;
510 * How many entries in "replies_seen" are actually valid?
512 unsigned int replies_seen_off;
515 * How long is the "replies_seen" array?
517 unsigned int replies_seen_size;
520 * Priority with which this request was made. If one of our clients
521 * made the request, then this is the current priority that we are
522 * using when initiating the request. This value is used when
523 * we decide to reward other peers with trust for providing a reply.
528 * Priority points left for us to spend when forwarding this request
531 uint32_t remaining_priority;
534 * Number to mingle hashes for bloom-filter tests with.
539 * TTL with which we saw this request (or, if we initiated, TTL that
540 * we used for the request).
545 * Type of the content that this request is for.
547 enum GNUNET_BLOCK_Type type;
550 * Remove this request after transmission of the current response.
555 * GNUNET_YES if we should not forward this request to other peers.
563 * Block that is ready for migration to other peers. Actual data is at the end of the block.
565 struct MigrationReadyBlock
569 * This is a doubly-linked list.
571 struct MigrationReadyBlock *next;
574 * This is a doubly-linked list.
576 struct MigrationReadyBlock *prev;
579 * Query for the block.
581 GNUNET_HashCode query;
584 * When does this block expire?
586 struct GNUNET_TIME_Absolute expiration;
596 enum GNUNET_BLOCK_Type type;
603 static struct GNUNET_SCHEDULER_Handle *sched;
608 static const struct GNUNET_CONFIGURATION_Handle *cfg;
611 * Map of peer identifiers to "struct ConnectedPeer" (for that peer).
613 static struct GNUNET_CONTAINER_MultiHashMap *connected_peers;
616 * Map of peer identifiers to "struct PendingRequest" (for that peer).
618 static struct GNUNET_CONTAINER_MultiHashMap *peer_request_map;
621 * Map of query identifiers to "struct PendingRequest" (for that query).
623 static struct GNUNET_CONTAINER_MultiHashMap *query_request_map;
626 * Heap with the request that will expire next at the top. Contains
627 * pointers of type "struct PendingRequest*"; these will *also* be
628 * aliased from the "requests_by_peer" data structures and the
629 * "requests_by_query" table. Note that requests from our clients
630 * don't expire and are thus NOT in the "requests_by_expiration"
631 * (or the "requests_by_peer" tables).
633 static struct GNUNET_CONTAINER_Heap *requests_by_expiration_heap;
636 * Handle for reporting statistics.
638 static struct GNUNET_STATISTICS_Handle *stats;
641 * Linked list of clients we are currently processing requests for.
643 static struct ClientList *client_list;
646 * Pointer to handle to the core service (points to NULL until we've
649 static struct GNUNET_CORE_Handle *core;
652 * Head of linked list of blocks that can be migrated.
654 static struct MigrationReadyBlock *mig_head;
657 * Tail of linked list of blocks that can be migrated.
659 static struct MigrationReadyBlock *mig_tail;
662 * Request to datastore for migration (or NULL).
664 static struct GNUNET_DATASTORE_QueueEntry *mig_qe;
667 * ID of task that collects blocks for migration.
669 static GNUNET_SCHEDULER_TaskIdentifier mig_task;
672 * What is the maximum frequency at which we are allowed to
673 * poll the datastore for migration content?
675 static struct GNUNET_TIME_Relative min_migration_delay;
678 * Size of the doubly-linked list of migration blocks.
680 static unsigned int mig_size;
683 * Are we allowed to migrate content to this peer.
685 static int active_migration;
687 /* ******************* clean up functions ************************ */
691 * Delete the given migration block.
693 * @param mb block to delete
696 delete_migration_block (struct MigrationReadyBlock *mb)
698 GNUNET_CONTAINER_DLL_remove (mig_head,
707 * Consider migrating content to a given peer.
709 * @param cls not used
710 * @param key ID of the peer (not used)
711 * @param value 'struct ConnectedPeer' of the peer
712 * @return GNUNET_YES (always continue iteration)2
715 consider_migration (void *cls,
716 const GNUNET_HashCode *key,
719 struct ConnectedPeer *cp = value;
722 return GNUNET_YES; /* or what? */
723 /* FIXME: not implemented! */
731 * Task that is run periodically to obtain blocks for content
735 * @param tc scheduler context (also unused)
738 gather_migration_blocks (void *cls,
739 const struct GNUNET_SCHEDULER_TaskContext *tc);
743 * Process content offered for migration.
746 * @param key key for the content
747 * @param size number of bytes in data
748 * @param data content stored
749 * @param type type of the content
750 * @param priority priority of the content
751 * @param anonymity anonymity-level for the content
752 * @param expiration expiration time for the content
753 * @param uid unique identifier for the datum;
754 * maybe 0 if no unique identifier is available
757 process_migration_content (void *cls,
758 const GNUNET_HashCode * key,
761 enum GNUNET_BLOCK_Type type,
764 struct GNUNET_TIME_Absolute
765 expiration, uint64_t uid)
767 struct MigrationReadyBlock *mb;
768 struct GNUNET_TIME_Relative delay;
773 if (mig_size < MAX_MIGRATION_QUEUE)
775 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
777 delay = GNUNET_TIME_relative_divide (GNUNET_TIME_UNIT_SECONDS,
778 MAX_MIGRATION_QUEUE);
779 delay = GNUNET_TIME_relative_max (delay,
780 min_migration_delay);
781 mig_task = GNUNET_SCHEDULER_add_delayed (sched,
783 &gather_migration_blocks,
788 mb = GNUNET_malloc (sizeof (struct MigrationReadyBlock) + size);
790 mb->expiration = expiration;
793 memcpy (&mb[1], data, size);
794 GNUNET_CONTAINER_DLL_insert_after (mig_head,
800 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
803 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
808 * Task that is run periodically to obtain blocks for content
812 * @param tc scheduler context (also unused)
815 gather_migration_blocks (void *cls,
816 const struct GNUNET_SCHEDULER_TaskContext *tc)
818 mig_task = GNUNET_SCHEDULER_NO_TASK;
819 mig_qe = GNUNET_DATASTORE_get_random (dsh, 0, -1,
820 GNUNET_TIME_UNIT_FOREVER_REL,
821 &process_migration_content, NULL);
826 * We're done with a particular message list entry.
827 * Free all associated resources.
829 * @param pml entry to destroy
832 destroy_pending_message_list_entry (struct PendingMessageList *pml)
834 GNUNET_CONTAINER_DLL_remove (pml->req->pending_head,
835 pml->req->pending_tail,
837 GNUNET_CONTAINER_DLL_remove (pml->target->pending_messages_head,
838 pml->target->pending_messages_tail,
840 pml->target->pending_requests--;
841 GNUNET_free (pml->pm);
847 * Destroy the given pending message (and call the respective
850 * @param pm message to destroy
851 * @param tpid id of peer that the message was delivered to, or 0 for none
854 destroy_pending_message (struct PendingMessage *pm,
857 struct PendingMessageList *pml = pm->pml;
858 TransmissionContinuation cont;
861 GNUNET_assert (pml->pm == pm);
862 GNUNET_assert ( (tpid == 0) || (tpid == pml->target->pid) );
864 cont_cls = pm->cont_cls;
865 destroy_pending_message_list_entry (pml);
866 cont (cont_cls, tpid);
871 * We're done processing a particular request.
872 * Free all associated resources.
874 * @param pr request to destroy
877 destroy_pending_request (struct PendingRequest *pr)
879 struct GNUNET_PeerIdentity pid;
881 if (pr->hnode != NULL)
883 GNUNET_CONTAINER_heap_remove_node (requests_by_expiration_heap,
887 if (NULL == pr->client_request_list)
889 GNUNET_STATISTICS_update (stats,
890 gettext_noop ("# P2P searches active"),
896 GNUNET_STATISTICS_update (stats,
897 gettext_noop ("# client searches active"),
901 /* might have already been removed from map in 'process_reply' (if
902 there was a unique reply) or never inserted if it was a
903 duplicate; hence ignore the return value here */
904 (void) GNUNET_CONTAINER_multihashmap_remove (query_request_map,
909 GNUNET_DATASTORE_cancel (pr->qe);
912 if (pr->client_request_list != NULL)
914 GNUNET_CONTAINER_DLL_remove (pr->client_request_list->client_list->rl_head,
915 pr->client_request_list->client_list->rl_tail,
916 pr->client_request_list);
917 GNUNET_free (pr->client_request_list);
918 pr->client_request_list = NULL;
922 GNUNET_PEER_resolve (pr->cp->pid,
924 (void) GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
931 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
936 GNUNET_CORE_peer_change_preference_cancel (pr->irc);
939 if (pr->replies_seen != NULL)
941 GNUNET_free (pr->replies_seen);
942 pr->replies_seen = NULL;
944 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
946 GNUNET_SCHEDULER_cancel (sched,
948 pr->task = GNUNET_SCHEDULER_NO_TASK;
950 while (NULL != pr->pending_head)
951 destroy_pending_message_list_entry (pr->pending_head);
952 GNUNET_PEER_change_rc (pr->target_pid, -1);
953 if (pr->used_pids != NULL)
955 GNUNET_PEER_decrement_rcs (pr->used_pids, pr->used_pids_off);
956 GNUNET_free (pr->used_pids);
957 pr->used_pids_off = 0;
958 pr->used_pids_size = 0;
959 pr->used_pids = NULL;
966 * Method called whenever a given peer connects.
968 * @param cls closure, not used
969 * @param peer peer identity this notification is about
970 * @param latency reported latency of the connection with 'other'
971 * @param distance reported distance (DV) to 'other'
974 peer_connect_handler (void *cls,
976 GNUNET_PeerIdentity * peer,
977 struct GNUNET_TIME_Relative latency,
980 struct ConnectedPeer *cp;
982 cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
983 cp->pid = GNUNET_PEER_intern (peer);
984 GNUNET_break (GNUNET_OK ==
985 GNUNET_CONTAINER_multihashmap_put (connected_peers,
988 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
990 (void) consider_migration (NULL, &peer->hashPubKey, cp);
996 * Free (each) request made by the peer.
998 * @param cls closure, points to peer that the request belongs to
999 * @param key current key code
1000 * @param value value in the hash map
1001 * @return GNUNET_YES (we should continue to iterate)
1004 destroy_request (void *cls,
1005 const GNUNET_HashCode * key,
1008 const struct GNUNET_PeerIdentity * peer = cls;
1009 struct PendingRequest *pr = value;
1011 GNUNET_break (GNUNET_YES ==
1012 GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
1015 destroy_pending_request (pr);
1021 * Method called whenever a peer disconnects.
1023 * @param cls closure, not used
1024 * @param peer peer identity this notification is about
1027 peer_disconnect_handler (void *cls,
1029 GNUNET_PeerIdentity * peer)
1031 struct ConnectedPeer *cp;
1032 struct PendingMessage *pm;
1035 GNUNET_CONTAINER_multihashmap_get_multiple (peer_request_map,
1039 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1043 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1045 if (NULL != cp->last_client_replies[i])
1047 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
1048 cp->last_client_replies[i] = NULL;
1051 GNUNET_break (GNUNET_YES ==
1052 GNUNET_CONTAINER_multihashmap_remove (connected_peers,
1055 GNUNET_PEER_change_rc (cp->pid, -1);
1056 GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
1057 if (NULL != cp->cth)
1058 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
1059 while (NULL != (pm = cp->pending_messages_head))
1060 destroy_pending_message (pm, 0 /* delivery failed */);
1061 GNUNET_break (0 == cp->pending_requests);
1067 * Iterator over hash map entries that removes all occurences
1068 * of the given 'client' from the 'last_client_replies' of the
1069 * given connected peer.
1071 * @param cls closure, the 'struct GNUNET_SERVER_Client*' to remove
1072 * @param key current key code (unused)
1073 * @param value value in the hash map (the 'struct ConnectedPeer*' to change)
1074 * @return GNUNET_YES (we should continue to iterate)
1077 remove_client_from_last_client_replies (void *cls,
1078 const GNUNET_HashCode * key,
1081 struct GNUNET_SERVER_Client *client = cls;
1082 struct ConnectedPeer *cp = value;
1085 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1087 if (cp->last_client_replies[i] == client)
1089 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
1090 cp->last_client_replies[i] = NULL;
1098 * A client disconnected. Remove all of its pending queries.
1100 * @param cls closure, NULL
1101 * @param client identification of the client
1104 handle_client_disconnect (void *cls,
1105 struct GNUNET_SERVER_Client
1108 struct ClientList *pos;
1109 struct ClientList *prev;
1110 struct ClientRequestList *rcl;
1111 struct ClientResponseMessage *creply;
1117 while ( (NULL != pos) &&
1118 (pos->client != client) )
1124 return; /* no requests pending for this client */
1125 while (NULL != (rcl = pos->rl_head))
1127 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1128 "Destroying pending request `%s' on disconnect\n",
1129 GNUNET_h2s (&rcl->req->query));
1130 destroy_pending_request (rcl->req);
1133 client_list = pos->next;
1135 prev->next = pos->next;
1136 if (pos->th != NULL)
1138 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
1141 while (NULL != (creply = pos->res_head))
1143 GNUNET_CONTAINER_DLL_remove (pos->res_head,
1146 GNUNET_free (creply);
1148 GNUNET_SERVER_client_drop (pos->client);
1150 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1151 &remove_client_from_last_client_replies,
1157 * Iterator to free peer entries.
1159 * @param cls closure, unused
1160 * @param key current key code
1161 * @param value value in the hash map (peer entry)
1162 * @return GNUNET_YES (we should continue to iterate)
1165 clean_peer (void *cls,
1166 const GNUNET_HashCode * key,
1169 peer_disconnect_handler (NULL, (const struct GNUNET_PeerIdentity*) key);
1175 * Task run during shutdown.
1181 shutdown_task (void *cls,
1182 const struct GNUNET_SCHEDULER_TaskContext *tc)
1186 GNUNET_DATASTORE_cancel (mig_qe);
1189 if (GNUNET_SCHEDULER_NO_TASK != mig_task)
1191 GNUNET_SCHEDULER_cancel (sched, mig_task);
1192 mig_task = GNUNET_SCHEDULER_NO_TASK;
1194 while (client_list != NULL)
1195 handle_client_disconnect (NULL,
1196 client_list->client);
1197 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1200 GNUNET_break (0 == GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap));
1201 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
1202 requests_by_expiration_heap = 0;
1203 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
1204 connected_peers = NULL;
1205 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (query_request_map));
1206 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
1207 query_request_map = NULL;
1208 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (peer_request_map));
1209 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
1210 peer_request_map = NULL;
1211 GNUNET_assert (NULL != core);
1212 GNUNET_CORE_disconnect (core);
1216 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1219 GNUNET_DATASTORE_disconnect (dsh,
1221 while (mig_head != NULL)
1222 delete_migration_block (mig_head);
1223 GNUNET_assert (0 == mig_size);
1230 /* ******************* Utility functions ******************** */
1234 * Transmit the given message by copying it to the target buffer
1235 * "buf". "buf" will be NULL and "size" zero if the socket was closed
1236 * for writing in the meantime. In that case, do nothing
1237 * (the disconnect or shutdown handler will take care of the rest).
1238 * If we were able to transmit messages and there are still more
1239 * pending, ask core again for further calls to this function.
1241 * @param cls closure, pointer to the 'struct ConnectedPeer*'
1242 * @param size number of bytes available in buf
1243 * @param buf where the callee should write the message
1244 * @return number of bytes written to buf
1247 transmit_to_peer (void *cls,
1248 size_t size, void *buf)
1250 struct ConnectedPeer *cp = cls;
1252 struct GNUNET_PeerIdentity pid;
1253 struct PendingMessage *pm;
1260 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1261 "Dropping message, core too busy.\n");
1266 while ( (NULL != (pm = cp->pending_messages_head) ) &&
1267 (pm->msize <= size) )
1269 memcpy (&cbuf[msize], &pm[1], pm->msize);
1272 destroy_pending_message (pm, cp->pid);
1276 GNUNET_PEER_resolve (cp->pid,
1278 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1280 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1287 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1288 "Transmitting %u bytes to peer %u\n",
1297 * Add a message to the set of pending messages for the given peer.
1299 * @param cp peer to send message to
1300 * @param pm message to queue
1301 * @param pr request on which behalf this message is being queued
1304 add_to_pending_messages_for_peer (struct ConnectedPeer *cp,
1305 struct PendingMessage *pm,
1306 struct PendingRequest *pr)
1308 struct PendingMessage *pos;
1309 struct PendingMessageList *pml;
1310 struct GNUNET_PeerIdentity pid;
1312 GNUNET_assert (pm->next == NULL);
1313 GNUNET_assert (pm->pml == NULL);
1314 pml = GNUNET_malloc (sizeof (struct PendingMessageList));
1319 GNUNET_CONTAINER_DLL_insert (pr->pending_head,
1322 pos = cp->pending_messages_head;
1323 while ( (pos != NULL) &&
1324 (pm->priority < pos->priority) )
1326 GNUNET_CONTAINER_DLL_insert_after (cp->pending_messages_head,
1327 cp->pending_messages_tail,
1330 cp->pending_requests++;
1331 if (cp->pending_requests > MAX_QUEUE_PER_PEER)
1332 destroy_pending_message (cp->pending_messages_tail, 0);
1333 if (cp->cth == NULL)
1335 /* need to schedule transmission */
1336 GNUNET_PEER_resolve (cp->pid, &pid);
1337 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1338 cp->pending_messages_head->priority,
1341 cp->pending_messages_head->msize,
1345 if (cp->cth == NULL)
1348 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1349 "Failed to schedule transmission with core!\n");
1351 /* FIXME: call stats (rare, bad case) */
1357 * Mingle hash with the mingle_number to produce different bits.
1360 mingle_hash (const GNUNET_HashCode * in,
1361 int32_t mingle_number,
1362 GNUNET_HashCode * hc)
1366 GNUNET_CRYPTO_hash (&mingle_number,
1369 GNUNET_CRYPTO_hash_xor (&m, in, hc);
1374 * Test if the load on this peer is too high
1375 * to even consider processing the query at
1378 * @return GNUNET_YES if the load is too high, GNUNET_NO otherwise
1381 test_load_too_high ()
1383 return GNUNET_NO; // FIXME
1387 /* ******************* Pending Request Refresh Task ******************** */
1392 * We use a random delay to make the timing of requests less
1393 * predictable. This function returns such a random delay. We add a base
1394 * delay of MAX_CORK_DELAY (1s).
1396 * FIXME: make schedule dependent on the specifics of the request?
1397 * Or bandwidth and number of connected peers and load?
1399 * @return random delay to use for some request, between 1s and 1000+TTL_DECREMENT ms
1401 static struct GNUNET_TIME_Relative
1402 get_processing_delay ()
1405 GNUNET_TIME_relative_add (GNUNET_CONSTANTS_MAX_CORK_DELAY,
1406 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1407 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1413 * We're processing a GET request from another peer and have decided
1414 * to forward it to other peers. This function is called periodically
1415 * and should forward the request to other peers until we have all
1416 * possible replies. If we have transmitted the *only* reply to
1417 * the initiator we should destroy the pending request. If we have
1418 * many replies in the queue to the initiator, we should delay sending
1419 * out more queries until the reply queue has shrunk some.
1421 * @param cls our "struct ProcessGetContext *"
1425 forward_request_task (void *cls,
1426 const struct GNUNET_SCHEDULER_TaskContext *tc);
1430 * Function called after we either failed or succeeded
1431 * at transmitting a query to a peer.
1433 * @param cls the requests "struct PendingRequest*"
1434 * @param tpid ID of receiving peer, 0 on transmission error
1437 transmit_query_continuation (void *cls,
1438 GNUNET_PEER_Id tpid)
1440 struct PendingRequest *pr = cls;
1442 GNUNET_STATISTICS_update (stats,
1443 gettext_noop ("# queries scheduled for forwarding"),
1449 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1450 "Transmission of request failed, will try again later.\n");
1452 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1453 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1454 get_processing_delay (),
1455 &forward_request_task,
1459 GNUNET_STATISTICS_update (stats,
1460 gettext_noop ("# queries forwarded"),
1463 GNUNET_PEER_change_rc (tpid, 1);
1464 if (pr->used_pids_off == pr->used_pids_size)
1465 GNUNET_array_grow (pr->used_pids,
1467 pr->used_pids_size * 2 + 2);
1468 pr->used_pids[pr->used_pids_off++] = tpid;
1469 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1470 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1471 get_processing_delay (),
1472 &forward_request_task,
1478 * How many bytes should a bloomfilter be if we have already seen
1479 * entry_count responses? Note that BLOOMFILTER_K gives us the number
1480 * of bits set per entry. Furthermore, we should not re-size the
1481 * filter too often (to keep it cheap).
1483 * Since other peers will also add entries but not resize the filter,
1484 * we should generally pick a slightly larger size than what the
1485 * strict math would suggest.
1487 * @return must be a power of two and smaller or equal to 2^15.
1490 compute_bloomfilter_size (unsigned int entry_count)
1493 unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
1494 uint16_t max = 1 << 15;
1496 if (entry_count > max)
1499 while ((size < max) && (size < ideal))
1508 * Recalculate our bloom filter for filtering replies. This function
1509 * will create a new bloom filter from scratch, so it should only be
1510 * called if we have no bloomfilter at all (and hence can create a
1511 * fresh one of minimal size without problems) OR if our peer is the
1512 * initiator (in which case we may resize to larger than mimimum size).
1514 * @param pr request for which the BF is to be recomputed
1517 refresh_bloomfilter (struct PendingRequest *pr)
1521 GNUNET_HashCode mhash;
1523 nsize = compute_bloomfilter_size (pr->replies_seen_off);
1524 if (nsize == pr->bf_size)
1525 return; /* size not changed */
1527 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
1528 pr->bf_size = nsize;
1529 pr->mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
1530 pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
1533 for (i=0;i<pr->replies_seen_off;i++)
1535 mingle_hash (&pr->replies_seen[i], pr->mingle, &mhash);
1536 GNUNET_CONTAINER_bloomfilter_add (pr->bf, &mhash);
1542 * Function called after we've tried to reserve a certain amount of
1543 * bandwidth for a reply. Check if we succeeded and if so send our
1546 * @param cls the requests "struct PendingRequest*"
1547 * @param peer identifies the peer
1548 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1549 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1550 * @param amount set to the amount that was actually reserved or unreserved
1551 * @param preference current traffic preference for the given peer
1554 target_reservation_cb (void *cls,
1556 GNUNET_PeerIdentity * peer,
1557 struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
1558 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1560 uint64_t preference)
1562 struct PendingRequest *pr = cls;
1563 struct ConnectedPeer *cp;
1564 struct PendingMessage *pm;
1565 struct GetMessage *gm;
1566 GNUNET_HashCode *ext;
1576 /* error in communication with core, try again later */
1577 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1578 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1579 get_processing_delay (),
1580 &forward_request_task,
1584 // (3) transmit, update ttl/priority
1585 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1589 /* Peer must have just left */
1591 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1592 "Selected peer disconnected!\n");
1594 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1595 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1596 get_processing_delay (),
1597 &forward_request_task,
1601 no_route = GNUNET_NO;
1602 /* FIXME: check against DBLOCK_SIZE and possibly return
1603 amount to reserve; however, this also needs to work
1604 with testcases which currently start out with a far
1605 too low per-peer bw limit, so they would never send
1606 anything. Big issue. */
1612 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1613 "Failed to reserve bandwidth for reply (got %d/%u bytes only)!\n",
1617 GNUNET_STATISTICS_update (stats,
1618 gettext_noop ("# reply bandwidth reservation requests failed"),
1621 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1622 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1623 get_processing_delay (),
1624 &forward_request_task,
1626 return; /* this target round failed */
1628 /* FIXME: if we are "quite" busy, we may still want to skip
1629 this round; need more load detection code! */
1630 no_route = GNUNET_YES;
1633 GNUNET_STATISTICS_update (stats,
1634 gettext_noop ("# queries scheduled for forwarding"),
1637 /* build message and insert message into priority queue */
1639 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1640 "Forwarding request `%s' to `%4s'!\n",
1641 GNUNET_h2s (&pr->query),
1646 if (GNUNET_YES == no_route)
1648 bm |= GET_MESSAGE_BIT_RETURN_TO;
1651 if (pr->namespace != NULL)
1653 bm |= GET_MESSAGE_BIT_SKS_NAMESPACE;
1656 if (pr->target_pid != 0)
1658 bm |= GET_MESSAGE_BIT_TRANSMIT_TO;
1661 msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
1662 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1663 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1665 gm = (struct GetMessage*) &pm[1];
1666 gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
1667 gm->header.size = htons (msize);
1668 gm->type = htonl (pr->type);
1669 pr->remaining_priority /= 2;
1670 gm->priority = htonl (pr->remaining_priority);
1671 gm->ttl = htonl (pr->ttl);
1672 gm->filter_mutator = htonl(pr->mingle);
1673 gm->hash_bitmap = htonl (bm);
1674 gm->query = pr->query;
1675 ext = (GNUNET_HashCode*) &gm[1];
1677 if (GNUNET_YES == no_route)
1678 GNUNET_PEER_resolve (pr->cp->pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1679 if (pr->namespace != NULL)
1680 memcpy (&ext[k++], pr->namespace, sizeof (GNUNET_HashCode));
1681 if (pr->target_pid != 0)
1682 GNUNET_PEER_resolve (pr->target_pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1683 bfdata = (char *) &ext[k];
1685 GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
1688 pm->cont = &transmit_query_continuation;
1690 add_to_pending_messages_for_peer (cp, pm, pr);
1695 * Closure used for "target_peer_select_cb".
1697 struct PeerSelectionContext
1700 * The request for which we are selecting
1703 struct PendingRequest *pr;
1706 * Current "prime" target.
1708 struct GNUNET_PeerIdentity target;
1711 * How much do we like this target?
1713 double target_score;
1719 * Function called for each connected peer to determine
1720 * which one(s) would make good targets for forwarding.
1722 * @param cls closure (struct PeerSelectionContext)
1723 * @param key current key code (peer identity)
1724 * @param value value in the hash map (struct ConnectedPeer)
1725 * @return GNUNET_YES if we should continue to
1730 target_peer_select_cb (void *cls,
1731 const GNUNET_HashCode * key,
1734 struct PeerSelectionContext *psc = cls;
1735 struct ConnectedPeer *cp = value;
1736 struct PendingRequest *pr = psc->pr;
1741 /* 1) check that this peer is not the initiator */
1743 return GNUNET_YES; /* skip */
1745 /* 2) check if we have already (recently) forwarded to this peer */
1747 for (i=0;i<pr->used_pids_off;i++)
1748 if (pr->used_pids[i] == cp->pid)
1751 if (0 != GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1752 RETRY_PROBABILITY_INV))
1755 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1756 "NOT re-trying query that was previously transmitted %u times\n",
1757 (unsigned int) pr->used_pids_off);
1759 return GNUNET_YES; /* skip */
1764 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1765 "Re-trying query that was previously transmitted %u times to this peer\n",
1768 // 3) calculate how much we'd like to forward to this peer
1769 score = 42; // FIXME!
1770 // FIXME: also need API to gather data on responsiveness
1771 // of this peer (we have fields for that in 'cp', but
1772 // they are never set!)
1774 /* store best-fit in closure */
1775 if (score > psc->target_score)
1777 psc->target_score = score;
1778 psc->target.hashPubKey = *key;
1785 * The priority level imposes a bound on the maximum
1786 * value for the ttl that can be requested.
1788 * @param ttl_in requested ttl
1789 * @param prio given priority
1790 * @return ttl_in if ttl_in is below the limit,
1791 * otherwise the ttl-limit for the given priority
1794 bound_ttl (int32_t ttl_in, uint32_t prio)
1796 unsigned long long allowed;
1800 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
1801 if (ttl_in > allowed)
1803 if (allowed >= (1 << 30))
1812 * We're processing a GET request from another peer and have decided
1813 * to forward it to other peers. This function is called periodically
1814 * and should forward the request to other peers until we have all
1815 * possible replies. If we have transmitted the *only* reply to
1816 * the initiator we should destroy the pending request. If we have
1817 * many replies in the queue to the initiator, we should delay sending
1818 * out more queries until the reply queue has shrunk some.
1820 * @param cls our "struct ProcessGetContext *"
1824 forward_request_task (void *cls,
1825 const struct GNUNET_SCHEDULER_TaskContext *tc)
1827 struct PendingRequest *pr = cls;
1828 struct PeerSelectionContext psc;
1829 struct ConnectedPeer *cp;
1830 struct GNUNET_TIME_Relative delay;
1832 pr->task = GNUNET_SCHEDULER_NO_TASK;
1833 if (pr->irc != NULL)
1836 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1837 "Forwarding of query `%s' not attempted due to pending local lookup!\n",
1838 GNUNET_h2s (&pr->query));
1840 return; /* already pending */
1842 if (GNUNET_YES == pr->local_only)
1843 return; /* configured to not do P2P search */
1844 /* (1) select target */
1846 psc.target_score = DBL_MIN;
1847 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1848 &target_peer_select_cb,
1850 if (psc.target_score == DBL_MIN)
1852 delay = get_processing_delay ();
1854 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1855 "No peer selected for forwarding of query `%s', will try again in %llu ms!\n",
1856 GNUNET_h2s (&pr->query),
1859 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1861 &forward_request_task,
1863 return; /* nobody selected */
1865 /* (3) update TTL/priority */
1867 if (pr->client_request_list != NULL)
1869 /* FIXME: use better algorithm!? */
1870 if (0 == GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1873 /* FIXME: bound priority by "customary" priority used by other peers
1875 pr->ttl = bound_ttl (pr->ttl + TTL_DECREMENT * 2,
1878 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1879 "Trying query `%s' with priority %u and TTL %d.\n",
1880 GNUNET_h2s (&pr->query),
1887 /* FIXME: should we do something here as well!? */
1890 /* (3) reserve reply bandwidth */
1891 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1892 &psc.target.hashPubKey);
1893 GNUNET_assert (NULL != cp);
1894 pr->irc = GNUNET_CORE_peer_change_preference (sched, cfg,
1896 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1897 GNUNET_BANDWIDTH_value_init ((uint32_t) -1 /* no limit */),
1899 (uint64_t) cp->inc_preference,
1900 &target_reservation_cb,
1902 cp->inc_preference = 0.0;
1906 /* **************************** P2P PUT Handling ************************ */
1910 * Function called after we either failed or succeeded
1911 * at transmitting a reply to a peer.
1913 * @param cls the requests "struct PendingRequest*"
1914 * @param tpid ID of receiving peer, 0 on transmission error
1917 transmit_reply_continuation (void *cls,
1918 GNUNET_PEER_Id tpid)
1920 struct PendingRequest *pr = cls;
1924 case GNUNET_BLOCK_TYPE_DBLOCK:
1925 case GNUNET_BLOCK_TYPE_IBLOCK:
1926 /* only one reply expected, done with the request! */
1927 destroy_pending_request (pr);
1929 case GNUNET_BLOCK_TYPE_ANY:
1930 case GNUNET_BLOCK_TYPE_KBLOCK:
1931 case GNUNET_BLOCK_TYPE_SBLOCK:
1941 * Transmit the given message by copying it to the target buffer
1942 * "buf". "buf" will be NULL and "size" zero if the socket was closed
1943 * for writing in the meantime. In that case, do nothing
1944 * (the disconnect or shutdown handler will take care of the rest).
1945 * If we were able to transmit messages and there are still more
1946 * pending, ask core again for further calls to this function.
1948 * @param cls closure, pointer to the 'struct ClientList*'
1949 * @param size number of bytes available in buf
1950 * @param buf where the callee should write the message
1951 * @return number of bytes written to buf
1954 transmit_to_client (void *cls,
1955 size_t size, void *buf)
1957 struct ClientList *cl = cls;
1959 struct ClientResponseMessage *creply;
1966 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1967 "Not sending reply, client communication problem.\n");
1972 while ( (NULL != (creply = cl->res_head) ) &&
1973 (creply->msize <= size) )
1975 memcpy (&cbuf[msize], &creply[1], creply->msize);
1976 msize += creply->msize;
1977 size -= creply->msize;
1978 GNUNET_CONTAINER_DLL_remove (cl->res_head,
1981 GNUNET_free (creply);
1984 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
1986 GNUNET_TIME_UNIT_FOREVER_REL,
1987 &transmit_to_client,
1990 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1991 "Transmitted %u bytes to client\n",
1992 (unsigned int) msize);
1999 * Closure for "process_reply" function.
2001 struct ProcessReplyClosure
2004 * The data for the reply.
2008 // FIXME: add 'struct ConnectedPeer' to track 'last_xxx_replies' here!
2011 * When the reply expires.
2013 struct GNUNET_TIME_Absolute expiration;
2021 * Namespace that this reply belongs to
2022 * (if it is of type SBLOCK).
2024 GNUNET_HashCode namespace;
2027 * Type of the block.
2029 enum GNUNET_BLOCK_Type type;
2032 * How much was this reply worth to us?
2039 * We have received a reply; handle it!
2041 * @param cls response (struct ProcessReplyClosure)
2042 * @param key our query
2043 * @param value value in the hash map (info about the query)
2044 * @return GNUNET_YES (we should continue to iterate)
2047 process_reply (void *cls,
2048 const GNUNET_HashCode * key,
2051 struct ProcessReplyClosure *prq = cls;
2052 struct PendingRequest *pr = value;
2053 struct PendingMessage *reply;
2054 struct ClientResponseMessage *creply;
2055 struct ClientList *cl;
2056 struct PutMessage *pm;
2057 struct ConnectedPeer *cp;
2058 GNUNET_HashCode chash;
2059 GNUNET_HashCode mhash;
2063 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2064 "Matched result (type %u) for query `%s' with pending request\n",
2065 (unsigned int) prq->type,
2068 GNUNET_STATISTICS_update (stats,
2069 gettext_noop ("# replies received and matched"),
2072 GNUNET_CRYPTO_hash (prq->data,
2077 case GNUNET_BLOCK_TYPE_DBLOCK:
2078 case GNUNET_BLOCK_TYPE_IBLOCK:
2079 /* only possible reply, stop requesting! */
2080 while (NULL != pr->pending_head)
2081 destroy_pending_message_list_entry (pr->pending_head);
2084 if (pr->client_request_list != NULL)
2085 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
2087 GNUNET_DATASTORE_cancel (pr->qe);
2090 pr->do_remove = GNUNET_YES;
2091 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
2093 GNUNET_SCHEDULER_cancel (sched,
2095 pr->task = GNUNET_SCHEDULER_NO_TASK;
2097 GNUNET_break (GNUNET_YES ==
2098 GNUNET_CONTAINER_multihashmap_remove (query_request_map,
2102 case GNUNET_BLOCK_TYPE_SBLOCK:
2103 if (pr->namespace == NULL)
2108 if (0 != memcmp (pr->namespace,
2110 sizeof (GNUNET_HashCode)))
2112 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2113 _("Reply mismatched in terms of namespace. Discarded.\n"));
2114 return GNUNET_YES; /* wrong namespace */
2116 /* then: fall-through! */
2117 case GNUNET_BLOCK_TYPE_KBLOCK:
2118 case GNUNET_BLOCK_TYPE_NBLOCK:
2121 mingle_hash (&chash, pr->mingle, &mhash);
2122 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
2125 GNUNET_STATISTICS_update (stats,
2126 gettext_noop ("# duplicate replies discarded (bloomfilter)"),
2130 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2131 "Duplicate response `%s', discarding.\n",
2132 GNUNET_h2s (&mhash));
2134 return GNUNET_YES; /* duplicate */
2137 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2138 "New response `%s', adding to filter.\n",
2139 GNUNET_h2s (&mhash));
2142 if (pr->client_request_list != NULL)
2144 if (pr->replies_seen_size == pr->replies_seen_off)
2145 GNUNET_array_grow (pr->replies_seen,
2146 pr->replies_seen_size,
2147 pr->replies_seen_size * 2 + 4);
2148 pr->replies_seen[pr->replies_seen_off++] = chash;
2150 if ( (pr->bf == NULL) ||
2151 (pr->client_request_list != NULL) )
2152 refresh_bloomfilter (pr);
2153 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
2160 prq->priority += pr->remaining_priority;
2161 pr->remaining_priority = 0;
2162 if (pr->client_request_list != NULL)
2164 GNUNET_STATISTICS_update (stats,
2165 gettext_noop ("# replies received for local clients"),
2168 cl = pr->client_request_list->client_list;
2169 msize = sizeof (struct PutMessage) + prq->size;
2170 creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
2171 creply->msize = msize;
2172 creply->client_list = cl;
2173 GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
2177 pm = (struct PutMessage*) &creply[1];
2178 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2179 pm->header.size = htons (msize);
2180 pm->type = htonl (prq->type);
2181 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
2182 memcpy (&pm[1], prq->data, prq->size);
2186 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2187 "Transmitting result for query `%s' to client\n",
2190 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
2192 GNUNET_TIME_UNIT_FOREVER_REL,
2193 &transmit_to_client,
2196 GNUNET_break (cl->th != NULL);
2198 destroy_pending_request (pr);
2204 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2205 "Transmitting result for query `%s' to other peer (PID=%u)\n",
2207 (unsigned int) cp->pid);
2209 GNUNET_STATISTICS_update (stats,
2210 gettext_noop ("# replies received for other peers"),
2213 msize = sizeof (struct PutMessage) + prq->size;
2214 reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
2215 reply->cont = &transmit_reply_continuation;
2216 reply->cont_cls = pr;
2217 reply->msize = msize;
2218 reply->priority = (uint32_t) -1; /* send replies first! */
2219 pm = (struct PutMessage*) &reply[1];
2220 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2221 pm->header.size = htons (msize);
2222 pm->type = htonl (prq->type);
2223 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
2224 memcpy (&pm[1], prq->data, prq->size);
2225 add_to_pending_messages_for_peer (cp, reply, pr);
2227 // FIXME: implement hot-path routing statistics keeping!
2234 * Continuation called to notify client about result of the
2237 * @param cls closure
2238 * @param success GNUNET_SYSERR on failure
2239 * @param msg NULL on success, otherwise an error message
2242 put_migration_continuation (void *cls,
2251 * Handle P2P "PUT" message.
2253 * @param cls closure, always NULL
2254 * @param other the other peer involved (sender or receiver, NULL
2255 * for loopback messages where we are both sender and receiver)
2256 * @param message the actual message
2257 * @param latency reported latency of the connection with 'other'
2258 * @param distance reported distance (DV) to 'other'
2259 * @return GNUNET_OK to keep the connection open,
2260 * GNUNET_SYSERR to close it (signal serious error)
2263 handle_p2p_put (void *cls,
2264 const struct GNUNET_PeerIdentity *other,
2265 const struct GNUNET_MessageHeader *message,
2266 struct GNUNET_TIME_Relative latency,
2269 const struct PutMessage *put;
2272 enum GNUNET_BLOCK_Type type;
2273 struct GNUNET_TIME_Absolute expiration;
2274 GNUNET_HashCode query;
2275 struct ProcessReplyClosure prq;
2276 const struct SBlock *sb;
2278 msize = ntohs (message->size);
2279 if (msize < sizeof (struct PutMessage))
2282 return GNUNET_SYSERR;
2284 put = (const struct PutMessage*) message;
2285 dsize = msize - sizeof (struct PutMessage);
2286 type = ntohl (put->type);
2287 expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
2290 GNUNET_BLOCK_check_block (type,
2295 GNUNET_break_op (0);
2296 return GNUNET_SYSERR;
2298 if (type == GNUNET_BLOCK_TYPE_ONDEMAND)
2299 return GNUNET_SYSERR;
2300 if (GNUNET_BLOCK_TYPE_SBLOCK == type)
2302 sb = (const struct SBlock*) &put[1];
2303 GNUNET_CRYPTO_hash (&sb->subspace,
2304 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2309 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2310 "Received result for query `%s' from peer `%4s'\n",
2311 GNUNET_h2s (&query),
2312 GNUNET_i2s (other));
2314 GNUNET_STATISTICS_update (stats,
2315 gettext_noop ("# replies received (overall)"),
2318 /* now, lookup 'query' */
2319 prq.data = (const void*) &put[1];
2322 prq.expiration = expiration;
2324 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2328 if (GNUNET_YES == active_migration)
2330 GNUNET_DATASTORE_put (dsh,
2331 0, &query, dsize, &put[1],
2332 type, prq.priority, 1 /* anonymity */,
2334 1 + prq.priority, MAX_DATASTORE_QUEUE,
2335 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
2336 &put_migration_continuation,
2343 /* **************************** P2P GET Handling ************************ */
2347 * Closure for 'check_duplicate_request_{peer,client}'.
2349 struct CheckDuplicateRequestClosure
2352 * The new request we should check if it already exists.
2354 const struct PendingRequest *pr;
2357 * Existing request found by the checker, NULL if none.
2359 struct PendingRequest *have;
2364 * Iterator over entries in the 'query_request_map' that
2365 * tries to see if we have the same request pending from
2366 * the same client already.
2368 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
2369 * @param key current key code (query, ignored, must match)
2370 * @param value value in the hash map (a 'struct PendingRequest'
2371 * that already exists)
2372 * @return GNUNET_YES if we should continue to
2373 * iterate (no match yet)
2374 * GNUNET_NO if not (match found).
2377 check_duplicate_request_client (void *cls,
2378 const GNUNET_HashCode * key,
2381 struct CheckDuplicateRequestClosure *cdc = cls;
2382 struct PendingRequest *have = value;
2384 if (have->client_request_list == NULL)
2386 if ( (cdc->pr->client_request_list->client_list->client == have->client_request_list->client_list->client) &&
2397 * We're processing (local) results for a search request
2398 * from another peer. Pass applicable results to the
2399 * peer and if we are done either clean up (operation
2400 * complete) or forward to other peers (more results possible).
2402 * @param cls our closure (struct LocalGetContext)
2403 * @param key key for the content
2404 * @param size number of bytes in data
2405 * @param data content stored
2406 * @param type type of the content
2407 * @param priority priority of the content
2408 * @param anonymity anonymity-level for the content
2409 * @param expiration expiration time for the content
2410 * @param uid unique identifier for the datum;
2411 * maybe 0 if no unique identifier is available
2414 process_local_reply (void *cls,
2415 const GNUNET_HashCode * key,
2418 enum GNUNET_BLOCK_Type type,
2421 struct GNUNET_TIME_Absolute
2425 struct PendingRequest *pr = cls;
2426 struct ProcessReplyClosure prq;
2427 struct CheckDuplicateRequestClosure cdrc;
2428 const struct SBlock *sb;
2429 GNUNET_HashCode dhash;
2430 GNUNET_HashCode mhash;
2431 GNUNET_HashCode query;
2436 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2437 "Done processing local replies, forwarding request to other peers.\n");
2440 if (pr->client_request_list != NULL)
2442 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
2444 /* Figure out if this is a duplicate request and possibly
2445 merge 'struct PendingRequest' entries */
2448 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2450 &check_duplicate_request_client,
2452 if (cdrc.have != NULL)
2455 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2456 "Received request for block `%s' twice from client, will only request once.\n",
2457 GNUNET_h2s (&pr->query));
2460 destroy_pending_request (pr);
2465 /* no more results */
2466 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2467 pr->task = GNUNET_SCHEDULER_add_now (sched,
2468 &forward_request_task,
2473 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2474 "New local response to `%s' of type %u.\n",
2478 if (type == GNUNET_BLOCK_TYPE_ONDEMAND)
2481 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2482 "Found ONDEMAND block, performing on-demand encoding\n");
2484 GNUNET_STATISTICS_update (stats,
2485 gettext_noop ("# on-demand blocks matched requests"),
2489 GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
2490 anonymity, expiration, uid,
2491 &process_local_reply,
2494 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2497 /* check for duplicates */
2498 GNUNET_CRYPTO_hash (data, size, &dhash);
2499 mingle_hash (&dhash,
2502 if ( (pr->bf != NULL) &&
2504 GNUNET_CONTAINER_bloomfilter_test (pr->bf,
2508 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2509 "Result from datastore filtered by bloomfilter (duplicate).\n");
2511 GNUNET_STATISTICS_update (stats,
2512 gettext_noop ("# results filtered by query bloomfilter"),
2516 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2520 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2521 "Found result for query `%s' in local datastore\n",
2524 GNUNET_STATISTICS_update (stats,
2525 gettext_noop ("# results found locally"),
2528 pr->results_found++;
2529 memset (&prq, 0, sizeof (prq));
2531 prq.expiration = expiration;
2533 if (GNUNET_BLOCK_TYPE_SBLOCK == type)
2535 sb = (const struct SBlock*) data;
2536 GNUNET_CRYPTO_hash (&sb->subspace,
2537 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2540 if (GNUNET_OK != GNUNET_BLOCK_check_block (type,
2546 GNUNET_DATASTORE_remove (dsh,
2550 GNUNET_TIME_UNIT_FOREVER_REL,
2552 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2556 prq.priority = priority;
2557 process_reply (&prq, key, pr);
2559 if ( (type == GNUNET_BLOCK_TYPE_DBLOCK) ||
2560 (type == GNUNET_BLOCK_TYPE_IBLOCK) )
2563 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
2566 if ( (pr->client_request_list == NULL) &&
2567 ( (GNUNET_YES == test_load_too_high()) ||
2568 (pr->results_found > 5 + 2 * pr->priority) ) )
2571 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2572 "Load too high, done with request\n");
2574 GNUNET_STATISTICS_update (stats,
2575 gettext_noop ("# processing result set cut short due to load"),
2579 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
2583 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2588 * We've received a request with the specified priority. Bound it
2589 * according to how much we trust the given peer.
2591 * @param prio_in requested priority
2592 * @param cp the peer making the request
2593 * @return effective priority
2596 bound_priority (uint32_t prio_in,
2597 struct ConnectedPeer *cp)
2604 * Iterator over entries in the 'query_request_map' that
2605 * tries to see if we have the same request pending from
2606 * the same peer already.
2608 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
2609 * @param key current key code (query, ignored, must match)
2610 * @param value value in the hash map (a 'struct PendingRequest'
2611 * that already exists)
2612 * @return GNUNET_YES if we should continue to
2613 * iterate (no match yet)
2614 * GNUNET_NO if not (match found).
2617 check_duplicate_request_peer (void *cls,
2618 const GNUNET_HashCode * key,
2621 struct CheckDuplicateRequestClosure *cdc = cls;
2622 struct PendingRequest *have = value;
2624 if (cdc->pr->target_pid == have->target_pid)
2634 * Handle P2P "GET" request.
2636 * @param cls closure, always NULL
2637 * @param other the other peer involved (sender or receiver, NULL
2638 * for loopback messages where we are both sender and receiver)
2639 * @param message the actual message
2640 * @param latency reported latency of the connection with 'other'
2641 * @param distance reported distance (DV) to 'other'
2642 * @return GNUNET_OK to keep the connection open,
2643 * GNUNET_SYSERR to close it (signal serious error)
2646 handle_p2p_get (void *cls,
2647 const struct GNUNET_PeerIdentity *other,
2648 const struct GNUNET_MessageHeader *message,
2649 struct GNUNET_TIME_Relative latency,
2652 struct PendingRequest *pr;
2653 struct ConnectedPeer *cp;
2654 struct ConnectedPeer *cps;
2655 struct CheckDuplicateRequestClosure cdc;
2656 struct GNUNET_TIME_Relative timeout;
2658 const struct GetMessage *gm;
2660 const GNUNET_HashCode *opt;
2663 uint32_t ttl_decrement;
2664 enum GNUNET_BLOCK_Type type;
2668 msize = ntohs(message->size);
2669 if (msize < sizeof (struct GetMessage))
2671 GNUNET_break_op (0);
2672 return GNUNET_SYSERR;
2674 gm = (const struct GetMessage*) message;
2675 type = ntohl (gm->type);
2678 case GNUNET_BLOCK_TYPE_ANY:
2679 case GNUNET_BLOCK_TYPE_DBLOCK:
2680 case GNUNET_BLOCK_TYPE_IBLOCK:
2681 case GNUNET_BLOCK_TYPE_KBLOCK:
2682 case GNUNET_BLOCK_TYPE_SBLOCK:
2685 GNUNET_break_op (0);
2686 return GNUNET_SYSERR;
2688 bm = ntohl (gm->hash_bitmap);
2696 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
2698 GNUNET_break_op (0);
2699 return GNUNET_SYSERR;
2701 opt = (const GNUNET_HashCode*) &gm[1];
2702 bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
2703 bm = ntohl (gm->hash_bitmap);
2704 if ( (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)) &&
2705 (type != GNUNET_BLOCK_TYPE_SBLOCK) )
2707 GNUNET_break_op (0);
2708 return GNUNET_SYSERR;
2711 cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2712 &other->hashPubKey);
2715 /* peer must have just disconnected */
2716 GNUNET_STATISTICS_update (stats,
2717 gettext_noop ("# requests dropped due to initiator not being connected"),
2720 return GNUNET_SYSERR;
2722 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
2723 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2730 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
2731 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2732 "Failed to find RETURN-TO peer `%4s' in connection set. Dropping query.\n",
2733 GNUNET_i2s ((const struct GNUNET_PeerIdentity*) &opt[bits-1]));
2736 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2737 "Failed to find peer `%4s' in connection set. Dropping query.\n",
2738 GNUNET_i2s (other));
2740 GNUNET_STATISTICS_update (stats,
2741 gettext_noop ("# requests dropped due to missing reverse route"),
2744 /* FIXME: try connect? */
2747 /* note that we can really only check load here since otherwise
2748 peers could find out that we are overloaded by not being
2749 disconnected after sending us a malformed query... */
2750 if (GNUNET_YES == test_load_too_high ())
2753 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2754 "Dropping query from `%s', this peer is too busy.\n",
2755 GNUNET_i2s (other));
2757 GNUNET_STATISTICS_update (stats,
2758 gettext_noop ("# requests dropped due to high load"),
2765 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2766 "Received request for `%s' of type %u from peer `%4s' with flags %u\n",
2767 GNUNET_h2s (&gm->query),
2768 (unsigned int) type,
2772 have_ns = (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE));
2773 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
2774 (have_ns ? sizeof(GNUNET_HashCode) : 0));
2776 pr->namespace = (GNUNET_HashCode*) &pr[1];
2778 pr->mingle = ntohl (gm->filter_mutator);
2779 if (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2780 memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
2781 if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
2782 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
2784 pr->anonymity_level = 1;
2785 pr->priority = bound_priority (ntohl (gm->priority), cps);
2786 pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
2787 pr->query = gm->query;
2788 /* decrement ttl (always) */
2789 ttl_decrement = 2 * TTL_DECREMENT +
2790 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2792 if ( (pr->ttl < 0) &&
2793 (((int32_t)(pr->ttl - ttl_decrement)) > 0) )
2796 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2797 "Dropping query from `%s' due to TTL underflow (%d - %u).\n",
2802 GNUNET_STATISTICS_update (stats,
2803 gettext_noop ("# requests dropped due TTL underflow"),
2806 /* integer underflow => drop (should be very rare)! */
2810 pr->ttl -= ttl_decrement;
2811 pr->start_time = GNUNET_TIME_absolute_get ();
2813 /* get bloom filter */
2816 pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
2819 pr->bf_size = bfsize;
2824 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2826 &check_duplicate_request_peer,
2828 if (cdc.have != NULL)
2830 if (cdc.have->start_time.value + cdc.have->ttl >=
2831 pr->start_time.value + pr->ttl)
2833 /* existing request has higher TTL, drop new one! */
2834 cdc.have->priority += pr->priority;
2835 destroy_pending_request (pr);
2837 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2838 "Have existing request with higher TTL, dropping new request.\n",
2839 GNUNET_i2s (other));
2841 GNUNET_STATISTICS_update (stats,
2842 gettext_noop ("# requests dropped due to higher-TTL request"),
2849 /* existing request has lower TTL, drop old one! */
2850 pr->priority += cdc.have->priority;
2851 /* Possible optimization: if we have applicable pending
2852 replies in 'cdc.have', we might want to move those over
2853 (this is a really rare special-case, so it is not clear
2854 that this would be worth it) */
2855 destroy_pending_request (cdc.have);
2856 /* keep processing 'pr'! */
2861 GNUNET_break (GNUNET_OK ==
2862 GNUNET_CONTAINER_multihashmap_put (query_request_map,
2865 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
2866 GNUNET_break (GNUNET_OK ==
2867 GNUNET_CONTAINER_multihashmap_put (peer_request_map,
2870 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
2872 pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
2874 pr->start_time.value + pr->ttl);
2876 GNUNET_STATISTICS_update (stats,
2877 gettext_noop ("# P2P searches received"),
2880 GNUNET_STATISTICS_update (stats,
2881 gettext_noop ("# P2P searches active"),
2885 /* calculate change in traffic preference */
2886 preference = (double) pr->priority;
2887 if (preference < QUERY_BANDWIDTH_VALUE)
2888 preference = QUERY_BANDWIDTH_VALUE;
2889 cps->inc_preference += preference;
2891 /* process locally */
2892 if (type == GNUNET_BLOCK_TYPE_DBLOCK)
2893 type = GNUNET_BLOCK_TYPE_ANY; /* to get on-demand as well */
2894 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
2895 (pr->priority + 1));
2896 pr->qe = GNUNET_DATASTORE_get (dsh,
2900 MAX_DATASTORE_QUEUE,
2902 &process_local_reply,
2905 /* Are multiple results possible? If so, start processing remotely now! */
2908 case GNUNET_BLOCK_TYPE_DBLOCK:
2909 case GNUNET_BLOCK_TYPE_IBLOCK:
2910 /* only one result, wait for datastore */
2913 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2914 pr->task = GNUNET_SCHEDULER_add_now (sched,
2915 &forward_request_task,
2919 /* make sure we don't track too many requests */
2920 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
2922 pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
2923 destroy_pending_request (pr);
2929 /* **************************** CS GET Handling ************************ */
2933 * Handle START_SEARCH-message (search request from client).
2935 * @param cls closure
2936 * @param client identification of the client
2937 * @param message the actual message
2940 handle_start_search (void *cls,
2941 struct GNUNET_SERVER_Client *client,
2942 const struct GNUNET_MessageHeader *message)
2944 static GNUNET_HashCode all_zeros;
2945 const struct SearchMessage *sm;
2946 struct ClientList *cl;
2947 struct ClientRequestList *crl;
2948 struct PendingRequest *pr;
2951 enum GNUNET_BLOCK_Type type;
2953 msize = ntohs (message->size);
2954 if ( (msize < sizeof (struct SearchMessage)) ||
2955 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
2958 GNUNET_SERVER_receive_done (client,
2962 GNUNET_STATISTICS_update (stats,
2963 gettext_noop ("# client searches received"),
2966 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
2967 sm = (const struct SearchMessage*) message;
2968 type = ntohl (sm->type);
2970 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2971 "Received request for `%s' of type %u from local client\n",
2972 GNUNET_h2s (&sm->query),
2973 (unsigned int) type);
2977 case GNUNET_BLOCK_TYPE_ANY:
2978 case GNUNET_BLOCK_TYPE_DBLOCK:
2979 case GNUNET_BLOCK_TYPE_IBLOCK:
2980 case GNUNET_BLOCK_TYPE_KBLOCK:
2981 case GNUNET_BLOCK_TYPE_SBLOCK:
2982 case GNUNET_BLOCK_TYPE_NBLOCK:
2986 GNUNET_SERVER_receive_done (client,
2992 while ( (cl != NULL) &&
2993 (cl->client != client) )
2997 cl = GNUNET_malloc (sizeof (struct ClientList));
2998 cl->client = client;
2999 GNUNET_SERVER_client_keep (client);
3000 cl->next = client_list;
3003 /* detect duplicate KBLOCK requests */
3004 if ( (type == GNUNET_BLOCK_TYPE_KBLOCK) ||
3005 (type == GNUNET_BLOCK_TYPE_NBLOCK) ||
3006 (type == GNUNET_BLOCK_TYPE_ANY) )
3009 while ( (crl != NULL) &&
3010 ( (0 != memcmp (&crl->req->query,
3012 sizeof (GNUNET_HashCode))) ||
3013 (crl->req->type != type) ) )
3018 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3019 "Have existing request, merging content-seen lists.\n");
3022 /* Duplicate request (used to send long list of
3023 known/blocked results); merge 'pr->replies_seen'
3024 and update bloom filter */
3025 GNUNET_array_grow (pr->replies_seen,
3026 pr->replies_seen_size,
3027 pr->replies_seen_off + sc);
3028 memcpy (&pr->replies_seen[pr->replies_seen_off],
3030 sc * sizeof (GNUNET_HashCode));
3031 pr->replies_seen_off += sc;
3032 refresh_bloomfilter (pr);
3033 GNUNET_STATISTICS_update (stats,
3034 gettext_noop ("# client searches updated (merged content seen list)"),
3037 GNUNET_SERVER_receive_done (client,
3042 GNUNET_STATISTICS_update (stats,
3043 gettext_noop ("# client searches active"),
3046 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
3047 ((type == GNUNET_BLOCK_TYPE_SBLOCK) ? sizeof(GNUNET_HashCode) : 0));
3048 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
3049 memset (crl, 0, sizeof (struct ClientRequestList));
3050 crl->client_list = cl;
3051 GNUNET_CONTAINER_DLL_insert (cl->rl_head,
3056 pr->client_request_list = crl;
3057 GNUNET_array_grow (pr->replies_seen,
3058 pr->replies_seen_size,
3060 memcpy (pr->replies_seen,
3062 sc * sizeof (GNUNET_HashCode));
3063 pr->replies_seen_off = sc;
3064 pr->anonymity_level = ntohl (sm->anonymity_level);
3065 refresh_bloomfilter (pr);
3066 pr->query = sm->query;
3067 if (0 == (1 & ntohl (sm->options)))
3068 pr->local_only = GNUNET_NO;
3070 pr->local_only = GNUNET_YES;
3073 case GNUNET_BLOCK_TYPE_DBLOCK:
3074 case GNUNET_BLOCK_TYPE_IBLOCK:
3075 if (0 != memcmp (&sm->target,
3077 sizeof (GNUNET_HashCode)))
3078 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
3080 case GNUNET_BLOCK_TYPE_SBLOCK:
3081 pr->namespace = (GNUNET_HashCode*) &pr[1];
3082 memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
3087 GNUNET_break (GNUNET_OK ==
3088 GNUNET_CONTAINER_multihashmap_put (query_request_map,
3091 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
3092 if (type == GNUNET_BLOCK_TYPE_DBLOCK)
3093 type = GNUNET_BLOCK_TYPE_ANY; /* get on-demand blocks too! */
3094 pr->qe = GNUNET_DATASTORE_get (dsh,
3098 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
3099 &process_local_reply,
3104 /* **************************** Startup ************************ */
3108 * List of handlers for P2P messages
3109 * that we care about.
3111 static struct GNUNET_CORE_MessageHandler p2p_handlers[] =
3114 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
3116 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
3122 * List of handlers for the messages understood by this
3125 static struct GNUNET_SERVER_MessageHandler handlers[] = {
3126 {&GNUNET_FS_handle_index_start, NULL,
3127 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
3128 {&GNUNET_FS_handle_index_list_get, NULL,
3129 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
3130 {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
3131 sizeof (struct UnindexMessage) },
3132 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
3139 * Process fs requests.
3141 * @param s scheduler to use
3142 * @param server the initialized server
3143 * @param c configuration to use
3146 main_init (struct GNUNET_SCHEDULER_Handle *s,
3147 struct GNUNET_SERVER_Handle *server,
3148 const struct GNUNET_CONFIGURATION_Handle *c)
3152 stats = GNUNET_STATISTICS_create (sched, "fs", cfg);
3153 min_migration_delay = GNUNET_TIME_UNIT_SECONDS; // FIXME: get from config
3154 connected_peers = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3155 query_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3156 peer_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3157 requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
3158 core = GNUNET_CORE_connect (sched,
3160 GNUNET_TIME_UNIT_FOREVER_REL,
3163 &peer_connect_handler,
3164 &peer_disconnect_handler,
3170 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3171 _("Failed to connect to `%s' service.\n"),
3173 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
3174 connected_peers = NULL;
3175 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
3176 query_request_map = NULL;
3177 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
3178 requests_by_expiration_heap = NULL;
3179 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
3180 peer_request_map = NULL;
3183 GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
3186 return GNUNET_SYSERR;
3188 /* FIXME: distinguish between sending and storing in options? */
3189 if (active_migration)
3191 mig_task = GNUNET_SCHEDULER_add_now (sched,
3192 &gather_migration_blocks,
3195 GNUNET_SERVER_disconnect_notify (server,
3196 &handle_client_disconnect,
3198 GNUNET_SERVER_add_handlers (server, handlers);
3199 GNUNET_SCHEDULER_add_delayed (sched,
3200 GNUNET_TIME_UNIT_FOREVER_REL,
3208 * Process fs requests.
3210 * @param cls closure
3211 * @param sched scheduler to use
3212 * @param server the initialized server
3213 * @param cfg configuration to use
3217 struct GNUNET_SCHEDULER_Handle *sched,
3218 struct GNUNET_SERVER_Handle *server,
3219 const struct GNUNET_CONFIGURATION_Handle *cfg)
3221 active_migration = GNUNET_CONFIGURATION_get_value_yesno (cfg,
3224 dsh = GNUNET_DATASTORE_connect (cfg,
3228 GNUNET_SCHEDULER_shutdown (sched);
3231 if ( (GNUNET_OK != GNUNET_FS_indexing_init (sched, cfg, dsh)) ||
3232 (GNUNET_OK != main_init (sched, server, cfg)) )
3234 GNUNET_SCHEDULER_shutdown (sched);
3235 GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
3243 * The main function for the fs service.
3245 * @param argc number of arguments from the command line
3246 * @param argv command line arguments
3247 * @return 0 ok, 1 on error
3250 main (int argc, char *const *argv)
3252 return (GNUNET_OK ==
3253 GNUNET_SERVICE_run (argc,
3256 GNUNET_SERVICE_OPTION_NONE,
3257 &run, NULL)) ? 0 : 1;
3260 /* end of gnunet-service-fs.c */