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 * - code not clear in terms of which function initializes bloomfilter when!
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_drq.h"
47 #include "gnunet-service-fs_indexing.h"
50 #define DEBUG_FS GNUNET_NO
53 * Maximum number of outgoing messages we queue per peer.
54 * FIXME: make configurable?
56 #define MAX_QUEUE_PER_PEER 16
59 * Inverse of the probability that we will submit the same query
60 * to the same peer again. If the same peer already got the query
61 * repeatedly recently, the probability is multiplied by the inverse
62 * of this number each time. Note that we only try about every TTL_DECREMENT/2
63 * plus MAX_CORK_DELAY (so roughly every 3.5s).
65 #define RETRY_PROBABILITY_INV 3
68 * What is the maximum delay for a P2P FS message (in our interaction
69 * with core)? FS-internal delays are another story. The value is
70 * chosen based on the 32k block size. Given that peers typcially
71 * have at least 1 kb/s bandwidth, 45s waits give us a chance to
72 * transmit one message even to the lowest-bandwidth peers.
74 #define MAX_TRANSMIT_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 45)
79 * Maximum number of requests (from other peers) that we're
80 * willing to have pending at any given point in time.
81 * FIXME: set from configuration.
83 static uint64_t max_pending_requests = (32 * 1024);
87 * Information we keep for each pending reply. The
88 * actual message follows at the end of this struct.
90 struct PendingMessage;
94 * Function called upon completion of a transmission.
97 * @param pid ID of receiving peer, 0 on transmission error
99 typedef void (*TransmissionContinuation)(void * cls,
100 GNUNET_PEER_Id tpid);
104 * Information we keep for each pending message (GET/PUT). The
105 * actual message follows at the end of this struct.
107 struct PendingMessage
110 * This is a doubly-linked list of messages to the same peer.
112 struct PendingMessage *next;
115 * This is a doubly-linked list of messages to the same peer.
117 struct PendingMessage *prev;
120 * Entry in pending message list for this pending message.
122 struct PendingMessageList *pml;
125 * Function to call immediately once we have transmitted this
128 TransmissionContinuation cont;
136 * Size of the reply; actual reply message follows
137 * at the end of this struct.
142 * How important is this message for us?
150 * Information about a peer that we are connected to.
151 * We track data that is useful for determining which
152 * peers should receive our requests. We also keep
153 * a list of messages to transmit to this peer.
159 * List of the last clients for which this peer successfully
162 struct GNUNET_SERVER_Client *last_client_replies[CS2P_SUCCESS_LIST_SIZE];
165 * List of the last PIDs for which
166 * this peer successfully answered a query;
167 * We use 0 to indicate no successful reply.
169 GNUNET_PEER_Id last_p2p_replies[P2P_SUCCESS_LIST_SIZE];
172 * Average delay between sending the peer a request and
173 * getting a reply (only calculated over the requests for
174 * which we actually got a reply). Calculated
175 * as a moving average: new_delay = ((n-1)*last_delay+curr_delay) / n
177 struct GNUNET_TIME_Relative avg_delay;
180 * Handle for an active request for transmission to this
183 struct GNUNET_CORE_TransmitHandle *cth;
186 * Messages (replies, queries, content migration) we would like to
187 * send to this peer in the near future. Sorted by priority, head.
189 struct PendingMessage *pending_messages_head;
192 * Messages (replies, queries, content migration) we would like to
193 * send to this peer in the near future. Sorted by priority, tail.
195 struct PendingMessage *pending_messages_tail;
198 * Average priority of successful replies. Calculated
199 * as a moving average: new_avg = ((n-1)*last_avg+curr_prio) / n
204 * Increase in traffic preference still to be submitted
205 * to the core service for this peer. FIXME: double or 'uint64_t'?
207 double inc_preference;
210 * The peer's identity.
215 * Size of the linked list of 'pending_messages'.
217 unsigned int pending_requests;
220 * Which offset in "last_p2p_replies" will be updated next?
221 * (we go round-robin).
223 unsigned int last_p2p_replies_woff;
226 * Which offset in "last_client_replies" will be updated next?
227 * (we go round-robin).
229 unsigned int last_client_replies_woff;
235 * Information we keep for each pending request. We should try to
236 * keep this struct as small as possible since its memory consumption
237 * is key to how many requests we can have pending at once.
239 struct PendingRequest;
243 * Doubly-linked list of requests we are performing
244 * on behalf of the same client.
246 struct ClientRequestList
250 * This is a doubly-linked list.
252 struct ClientRequestList *next;
255 * This is a doubly-linked list.
257 struct ClientRequestList *prev;
260 * Request this entry represents.
262 struct PendingRequest *req;
265 * Client list this request belongs to.
267 struct ClientList *client_list;
273 * Replies to be transmitted to the client. The actual
274 * response message is allocated after this struct.
276 struct ClientResponseMessage
279 * This is a doubly-linked list.
281 struct ClientResponseMessage *next;
284 * This is a doubly-linked list.
286 struct ClientResponseMessage *prev;
289 * Client list entry this response belongs to.
291 struct ClientList *client_list;
294 * Number of bytes in the response.
301 * Linked list of clients we are performing requests
307 * This is a linked list.
309 struct ClientList *next;
312 * ID of a client making a request, NULL if this entry is for a
315 struct GNUNET_SERVER_Client *client;
318 * Head of list of requests performed on behalf
319 * of this client right now.
321 struct ClientRequestList *rl_head;
324 * Tail of list of requests performed on behalf
325 * of this client right now.
327 struct ClientRequestList *rl_tail;
330 * Head of linked list of responses.
332 struct ClientResponseMessage *res_head;
335 * Tail of linked list of responses.
337 struct ClientResponseMessage *res_tail;
340 * Context for sending replies.
342 struct GNUNET_CONNECTION_TransmitHandle *th;
348 * Doubly-linked list of messages we are performing
349 * due to a pending request.
351 struct PendingMessageList
355 * This is a doubly-linked list of messages on behalf of the same request.
357 struct PendingMessageList *next;
360 * This is a doubly-linked list of messages on behalf of the same request.
362 struct PendingMessageList *prev;
365 * Message this entry represents.
367 struct PendingMessage *pm;
370 * Request this entry belongs to.
372 struct PendingRequest *req;
375 * Peer this message is targeted for.
377 struct ConnectedPeer *target;
383 * Information we keep for each pending request. We should try to
384 * keep this struct as small as possible since its memory consumption
385 * is key to how many requests we can have pending at once.
387 struct PendingRequest
391 * If this request was made by a client, this is our entry in the
392 * client request list; otherwise NULL.
394 struct ClientRequestList *client_request_list;
397 * Entry of peer responsible for this entry (if this request
398 * was made by a peer).
400 struct ConnectedPeer *cp;
403 * If this is a namespace query, pointer to the hash of the public
404 * key of the namespace; otherwise NULL. Pointer will be to the
405 * end of this struct (so no need to free it).
407 const GNUNET_HashCode *namespace;
410 * Bloomfilter we use to filter out replies that we don't care about
411 * (anymore). NULL as long as we are interested in all replies.
413 struct GNUNET_CONTAINER_BloomFilter *bf;
416 * Context of our GNUNET_CORE_peer_change_preference call.
418 struct GNUNET_CORE_InformationRequestContext *irc;
421 * Hash code of all replies that we have seen so far (only valid
422 * if client is not NULL since we only track replies like this for
425 GNUNET_HashCode *replies_seen;
428 * Node in the heap representing this entry; NULL
429 * if we have no heap node.
431 struct GNUNET_CONTAINER_HeapNode *hnode;
434 * Head of list of messages being performed on behalf of this
437 struct PendingMessageList *pending_head;
440 * Tail of list of messages being performed on behalf of this
443 struct PendingMessageList *pending_tail;
446 * When did we first see this request (form this peer), or, if our
447 * client is initiating, when did we last initiate a search?
449 struct GNUNET_TIME_Absolute start_time;
452 * The query that this request is for.
454 GNUNET_HashCode query;
457 * The task responsible for transmitting queries
460 GNUNET_SCHEDULER_TaskIdentifier task;
463 * (Interned) Peer identifier that identifies a preferred target
466 GNUNET_PEER_Id target_pid;
469 * (Interned) Peer identifiers of peers that have already
470 * received our query for this content.
472 GNUNET_PEER_Id *used_pids;
475 * Our entry in the DRQ (non-NULL while we wait for our
476 * turn to interact with the local database).
478 struct DatastoreRequestQueue *drq;
481 * Size of the 'bf' (in bytes).
486 * Desired anonymity level; only valid for requests from a local client.
488 uint32_t anonymity_level;
491 * How many entries in "used_pids" are actually valid?
493 unsigned int used_pids_off;
496 * How long is the "used_pids" array?
498 unsigned int used_pids_size;
501 * Number of results found for this request.
503 unsigned int results_found;
506 * How many entries in "replies_seen" are actually valid?
508 unsigned int replies_seen_off;
511 * How long is the "replies_seen" array?
513 unsigned int replies_seen_size;
516 * Priority with which this request was made. If one of our clients
517 * made the request, then this is the current priority that we are
518 * using when initiating the request. This value is used when
519 * we decide to reward other peers with trust for providing a reply.
524 * Priority points left for us to spend when forwarding this request
527 uint32_t remaining_priority;
530 * Number to mingle hashes for bloom-filter tests with.
535 * TTL with which we saw this request (or, if we initiated, TTL that
536 * we used for the request).
541 * Type of the content that this request is for.
546 * Remove this request after transmission of the current response.
556 static struct GNUNET_SCHEDULER_Handle *sched;
561 static const struct GNUNET_CONFIGURATION_Handle *cfg;
564 * Map of peer identifiers to "struct ConnectedPeer" (for that peer).
566 static struct GNUNET_CONTAINER_MultiHashMap *connected_peers;
569 * Map of peer identifiers to "struct PendingRequest" (for that peer).
571 static struct GNUNET_CONTAINER_MultiHashMap *peer_request_map;
574 * Map of query identifiers to "struct PendingRequest" (for that query).
576 static struct GNUNET_CONTAINER_MultiHashMap *query_request_map;
579 * Heap with the request that will expire next at the top. Contains
580 * pointers of type "struct PendingRequest*"; these will *also* be
581 * aliased from the "requests_by_peer" data structures and the
582 * "requests_by_query" table. Note that requests from our clients
583 * don't expire and are thus NOT in the "requests_by_expiration"
584 * (or the "requests_by_peer" tables).
586 static struct GNUNET_CONTAINER_Heap *requests_by_expiration_heap;
589 * Handle for reporting statistics.
591 static struct GNUNET_STATISTICS_Handle *stats;
594 * Linked list of clients we are currently processing requests for.
596 static struct ClientList *client_list;
599 * Pointer to handle to the core service (points to NULL until we've
602 static struct GNUNET_CORE_Handle *core;
605 /* ******************* clean up functions ************************ */
609 * We're done with a particular message list entry.
610 * Free all associated resources.
612 * @param pml entry to destroy
615 destroy_pending_message_list_entry (struct PendingMessageList *pml)
617 GNUNET_CONTAINER_DLL_remove (pml->req->pending_head,
618 pml->req->pending_tail,
620 GNUNET_CONTAINER_DLL_remove (pml->target->pending_messages_head,
621 pml->target->pending_messages_tail,
623 pml->target->pending_requests--;
624 GNUNET_free (pml->pm);
630 * Destroy the given pending message (and call the respective
633 * @param pm message to destroy
634 * @param tpid id of peer that the message was delivered to, or 0 for none
637 destroy_pending_message (struct PendingMessage *pm,
640 struct PendingMessageList *pml = pm->pml;
641 TransmissionContinuation cont;
644 GNUNET_assert (pml->pm == pm);
645 GNUNET_assert ( (tpid == 0) || (tpid == pml->target->pid) );
647 cont_cls = pm->cont_cls;
648 destroy_pending_message_list_entry (pml);
649 cont (cont_cls, tpid);
654 * We're done processing a particular request.
655 * Free all associated resources.
657 * @param pr request to destroy
660 destroy_pending_request (struct PendingRequest *pr)
662 struct GNUNET_PeerIdentity pid;
664 if (pr->hnode != NULL)
666 GNUNET_CONTAINER_heap_remove_node (requests_by_expiration_heap,
669 GNUNET_STATISTICS_update (stats,
670 gettext_noop ("# P2P searches active"),
676 GNUNET_STATISTICS_update (stats,
677 gettext_noop ("# client searches active"),
681 /* might have already been removed from map in 'process_reply' (if
682 there was a unique reply) or never inserted if it was a
683 duplicate; hence ignore the return value here */
684 (void) GNUNET_CONTAINER_multihashmap_remove (query_request_map,
689 GNUNET_FS_drq_get_cancel (pr->drq);
692 if (pr->client_request_list != NULL)
694 GNUNET_CONTAINER_DLL_remove (pr->client_request_list->client_list->rl_head,
695 pr->client_request_list->client_list->rl_tail,
696 pr->client_request_list);
697 GNUNET_free (pr->client_request_list);
698 pr->client_request_list = NULL;
702 GNUNET_PEER_resolve (pr->cp->pid,
704 (void) GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
711 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
716 GNUNET_CORE_peer_change_preference_cancel (pr->irc);
719 if (pr->replies_seen != NULL)
721 GNUNET_free (pr->replies_seen);
722 pr->replies_seen = NULL;
724 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
726 GNUNET_SCHEDULER_cancel (sched,
728 pr->task = GNUNET_SCHEDULER_NO_TASK;
730 while (NULL != pr->pending_head)
731 destroy_pending_message_list_entry (pr->pending_head);
732 GNUNET_PEER_change_rc (pr->target_pid, -1);
733 if (pr->used_pids != NULL)
735 GNUNET_PEER_decrement_rcs (pr->used_pids, pr->used_pids_off);
736 GNUNET_free (pr->used_pids);
737 pr->used_pids_off = 0;
738 pr->used_pids_size = 0;
739 pr->used_pids = NULL;
746 * Method called whenever a given peer connects.
748 * @param cls closure, not used
749 * @param peer peer identity this notification is about
750 * @param latency reported latency of the connection with 'other'
751 * @param distance reported distance (DV) to 'other'
754 peer_connect_handler (void *cls,
756 GNUNET_PeerIdentity * peer,
757 struct GNUNET_TIME_Relative latency,
760 struct ConnectedPeer *cp;
762 cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
763 cp->pid = GNUNET_PEER_intern (peer);
764 GNUNET_CONTAINER_multihashmap_put (connected_peers,
767 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
772 * Free (each) request made by the peer.
774 * @param cls closure, points to peer that the request belongs to
775 * @param key current key code
776 * @param value value in the hash map
777 * @return GNUNET_YES (we should continue to iterate)
780 destroy_request (void *cls,
781 const GNUNET_HashCode * key,
784 const struct GNUNET_PeerIdentity * peer = cls;
785 struct PendingRequest *pr = value;
787 GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
790 destroy_pending_request (pr);
796 * Method called whenever a peer disconnects.
798 * @param cls closure, not used
799 * @param peer peer identity this notification is about
802 peer_disconnect_handler (void *cls,
804 GNUNET_PeerIdentity * peer)
806 struct ConnectedPeer *cp;
807 struct PendingMessage *pm;
810 GNUNET_CONTAINER_multihashmap_get_multiple (peer_request_map,
814 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
818 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
820 if (NULL != cp->last_client_replies[i])
822 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
823 cp->last_client_replies[i] = NULL;
826 GNUNET_CONTAINER_multihashmap_remove (connected_peers,
829 GNUNET_PEER_change_rc (cp->pid, -1);
830 GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
832 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
833 while (NULL != (pm = cp->pending_messages_head))
834 destroy_pending_message (pm, 0 /* delivery failed */);
835 GNUNET_break (0 == cp->pending_requests);
841 * Iterator over hash map entries that removes all occurences
842 * of the given 'client' from the 'last_client_replies' of the
843 * given connected peer.
845 * @param cls closure, the 'struct GNUNET_SERVER_Client*' to remove
846 * @param key current key code (unused)
847 * @param value value in the hash map (the 'struct ConnectedPeer*' to change)
848 * @return GNUNET_YES (we should continue to iterate)
851 remove_client_from_last_client_replies (void *cls,
852 const GNUNET_HashCode * key,
855 struct GNUNET_SERVER_Client *client = cls;
856 struct ConnectedPeer *cp = value;
859 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
861 if (cp->last_client_replies[i] == client)
863 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
864 cp->last_client_replies[i] = NULL;
872 * A client disconnected. Remove all of its pending queries.
874 * @param cls closure, NULL
875 * @param client identification of the client
878 handle_client_disconnect (void *cls,
879 struct GNUNET_SERVER_Client
882 struct ClientList *pos;
883 struct ClientList *prev;
884 struct ClientRequestList *rcl;
885 struct ClientResponseMessage *creply;
891 while ( (NULL != pos) &&
892 (pos->client != client) )
898 return; /* no requests pending for this client */
899 while (NULL != (rcl = pos->rl_head))
901 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
902 "Destroying pending request `%s' on disconnect\n",
903 GNUNET_h2s (&rcl->req->query));
904 destroy_pending_request (rcl->req);
907 client_list = pos->next;
909 prev->next = pos->next;
912 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
915 while (NULL != (creply = pos->res_head))
917 GNUNET_CONTAINER_DLL_remove (pos->res_head,
920 GNUNET_free (creply);
922 GNUNET_SERVER_client_drop (pos->client);
924 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
925 &remove_client_from_last_client_replies,
931 * Iterator to free peer entries.
933 * @param cls closure, unused
934 * @param key current key code
935 * @param value value in the hash map (peer entry)
936 * @return GNUNET_YES (we should continue to iterate)
939 clean_peer (void *cls,
940 const GNUNET_HashCode * key,
943 peer_disconnect_handler (NULL, (const struct GNUNET_PeerIdentity*) key);
949 * Task run during shutdown.
955 shutdown_task (void *cls,
956 const struct GNUNET_SCHEDULER_TaskContext *tc)
958 while (client_list != NULL)
959 handle_client_disconnect (NULL,
960 client_list->client);
961 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
964 GNUNET_break (0 == GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap));
965 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
966 requests_by_expiration_heap = 0;
967 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
968 connected_peers = NULL;
969 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (query_request_map));
970 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
971 query_request_map = NULL;
972 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (peer_request_map));
973 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
974 peer_request_map = NULL;
975 GNUNET_assert (NULL != core);
976 GNUNET_CORE_disconnect (core);
980 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
988 /* ******************* Utility functions ******************** */
992 * Transmit the given message by copying it to the target buffer
993 * "buf". "buf" will be NULL and "size" zero if the socket was closed
994 * for writing in the meantime. In that case, do nothing
995 * (the disconnect or shutdown handler will take care of the rest).
996 * If we were able to transmit messages and there are still more
997 * pending, ask core again for further calls to this function.
999 * @param cls closure, pointer to the 'struct ConnectedPeer*'
1000 * @param size number of bytes available in buf
1001 * @param buf where the callee should write the message
1002 * @return number of bytes written to buf
1005 transmit_to_peer (void *cls,
1006 size_t size, void *buf)
1008 struct ConnectedPeer *cp = cls;
1010 struct GNUNET_PeerIdentity pid;
1011 struct PendingMessage *pm;
1018 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1019 "Dropping message, core too busy.\n");
1024 while ( (NULL != (pm = cp->pending_messages_head) ) &&
1025 (pm->msize <= size) )
1027 memcpy (&cbuf[msize], &pm[1], pm->msize);
1030 destroy_pending_message (pm, cp->pid);
1034 GNUNET_PEER_resolve (cp->pid,
1036 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1038 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1045 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1046 "Transmitting %u bytes to peer %u.\n",
1055 * Add a message to the set of pending messages for the given peer.
1057 * @param cp peer to send message to
1058 * @param pm message to queue
1059 * @param pr request on which behalf this message is being queued
1062 add_to_pending_messages_for_peer (struct ConnectedPeer *cp,
1063 struct PendingMessage *pm,
1064 struct PendingRequest *pr)
1066 struct PendingMessage *pos;
1067 struct PendingMessageList *pml;
1068 struct GNUNET_PeerIdentity pid;
1070 GNUNET_assert (pm->next == NULL);
1071 GNUNET_assert (pm->pml == NULL);
1072 pml = GNUNET_malloc (sizeof (struct PendingMessageList));
1077 GNUNET_CONTAINER_DLL_insert (pr->pending_head,
1080 pos = cp->pending_messages_head;
1081 while ( (pos != NULL) &&
1082 (pm->priority < pos->priority) )
1084 GNUNET_CONTAINER_DLL_insert_after (cp->pending_messages_head,
1085 cp->pending_messages_tail,
1088 cp->pending_requests++;
1089 if (cp->pending_requests > MAX_QUEUE_PER_PEER)
1090 destroy_pending_message (cp->pending_messages_tail, 0);
1091 if (cp->cth == NULL)
1093 /* need to schedule transmission */
1094 GNUNET_PEER_resolve (cp->pid, &pid);
1095 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1096 cp->pending_messages_head->priority,
1099 cp->pending_messages_head->msize,
1103 if (cp->cth == NULL)
1106 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1107 "Failed to schedule transmission with core!\n");
1109 /* FIXME: call stats (rare, bad case) */
1115 * Mingle hash with the mingle_number to produce different bits.
1118 mingle_hash (const GNUNET_HashCode * in,
1119 int32_t mingle_number,
1120 GNUNET_HashCode * hc)
1124 GNUNET_CRYPTO_hash (&mingle_number,
1127 GNUNET_CRYPTO_hash_xor (&m, in, hc);
1132 * Test if the load on this peer is too high
1133 * to even consider processing the query at
1136 * @return GNUNET_YES if the load is too high, GNUNET_NO otherwise
1139 test_load_too_high ()
1141 return GNUNET_NO; // FIXME
1145 /* ******************* Pending Request Refresh Task ******************** */
1150 * We use a random delay to make the timing of requests less
1151 * predictable. This function returns such a random delay. We add a base
1152 * delay of MAX_CORK_DELAY (1s).
1154 * FIXME: make schedule dependent on the specifics of the request?
1155 * Or bandwidth and number of connected peers and load?
1157 * @return random delay to use for some request, between 1s and 1000+TTL_DECREMENT ms
1159 static struct GNUNET_TIME_Relative
1160 get_processing_delay ()
1163 GNUNET_TIME_relative_add (GNUNET_CONSTANTS_MAX_CORK_DELAY,
1164 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1165 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1171 * We're processing a GET request from another peer and have decided
1172 * to forward it to other peers. This function is called periodically
1173 * and should forward the request to other peers until we have all
1174 * possible replies. If we have transmitted the *only* reply to
1175 * the initiator we should destroy the pending request. If we have
1176 * many replies in the queue to the initiator, we should delay sending
1177 * out more queries until the reply queue has shrunk some.
1179 * @param cls our "struct ProcessGetContext *"
1183 forward_request_task (void *cls,
1184 const struct GNUNET_SCHEDULER_TaskContext *tc);
1188 * Function called after we either failed or succeeded
1189 * at transmitting a query to a peer.
1191 * @param cls the requests "struct PendingRequest*"
1192 * @param tpid ID of receiving peer, 0 on transmission error
1195 transmit_query_continuation (void *cls,
1196 GNUNET_PEER_Id tpid)
1198 struct PendingRequest *pr = cls;
1203 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1204 "Transmission of request failed, will try again later.\n");
1206 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1207 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1208 get_processing_delay (),
1209 &forward_request_task,
1213 GNUNET_STATISTICS_update (stats,
1214 gettext_noop ("# queries forwarded"),
1217 GNUNET_PEER_change_rc (tpid, 1);
1218 if (pr->used_pids_off == pr->used_pids_size)
1219 GNUNET_array_grow (pr->used_pids,
1221 pr->used_pids_size * 2 + 2);
1222 pr->used_pids[pr->used_pids_off++] = tpid;
1223 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1224 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1225 get_processing_delay (),
1226 &forward_request_task,
1232 * How many bytes should a bloomfilter be if we have already seen
1233 * entry_count responses? Note that BLOOMFILTER_K gives us the number
1234 * of bits set per entry. Furthermore, we should not re-size the
1235 * filter too often (to keep it cheap).
1237 * Since other peers will also add entries but not resize the filter,
1238 * we should generally pick a slightly larger size than what the
1239 * strict math would suggest.
1241 * @return must be a power of two and smaller or equal to 2^15.
1244 compute_bloomfilter_size (unsigned int entry_count)
1247 unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
1248 uint16_t max = 1 << 15;
1250 if (entry_count > max)
1253 while ((size < max) && (size < ideal))
1262 * Recalculate our bloom filter for filtering replies.
1264 * @param count number of entries we are filtering right now
1265 * @param mingle set to our new mingling value
1266 * @param bf_size set to the size of the bloomfilter
1267 * @param entries the entries to filter
1268 * @return updated bloomfilter, NULL for none
1270 static struct GNUNET_CONTAINER_BloomFilter *
1271 refresh_bloomfilter (unsigned int count,
1274 const GNUNET_HashCode *entries)
1276 struct GNUNET_CONTAINER_BloomFilter *bf;
1279 GNUNET_HashCode mhash;
1283 nsize = compute_bloomfilter_size (count);
1284 *mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
1286 bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
1289 for (i=0;i<count;i++)
1291 mingle_hash (&entries[i], *mingle, &mhash);
1292 GNUNET_CONTAINER_bloomfilter_add (bf, &mhash);
1299 * Function called after we've tried to reserve a certain amount of
1300 * bandwidth for a reply. Check if we succeeded and if so send our
1303 * @param cls the requests "struct PendingRequest*"
1304 * @param peer identifies the peer
1305 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1306 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1307 * @param amount set to the amount that was actually reserved or unreserved
1308 * @param preference current traffic preference for the given peer
1311 target_reservation_cb (void *cls,
1313 GNUNET_PeerIdentity * peer,
1314 struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
1315 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1317 uint64_t preference)
1319 struct PendingRequest *pr = cls;
1320 struct ConnectedPeer *cp;
1321 struct PendingMessage *pm;
1322 struct GetMessage *gm;
1323 GNUNET_HashCode *ext;
1333 /* error in communication with core, try again later */
1334 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1335 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1336 get_processing_delay (),
1337 &forward_request_task,
1341 // (3) transmit, update ttl/priority
1342 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1346 /* Peer must have just left */
1348 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1349 "Selected peer disconnected!\n");
1351 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1352 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1353 get_processing_delay (),
1354 &forward_request_task,
1358 no_route = GNUNET_NO;
1359 /* FIXME: check against DBLOCK_SIZE and possibly return
1360 amount to reserve; however, this also needs to work
1361 with testcases which currently start out with a far
1362 too low per-peer bw limit, so they would never send
1363 anything. Big issue. */
1369 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1370 "Failed to reserve bandwidth for reply (got %d/%u bytes only)!\n",
1374 GNUNET_STATISTICS_update (stats,
1375 gettext_noop ("# reply bandwidth reservation requests failed"),
1378 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1379 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1380 get_processing_delay (),
1381 &forward_request_task,
1383 return; /* this target round failed */
1385 /* FIXME: if we are "quite" busy, we may still want to skip
1386 this round; need more load detection code! */
1387 no_route = GNUNET_YES;
1390 GNUNET_STATISTICS_update (stats,
1391 gettext_noop ("# requests forwarded"),
1394 /* build message and insert message into priority queue */
1396 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1397 "Forwarding request `%s' to `%4s'!\n",
1398 GNUNET_h2s (&pr->query),
1403 if (GNUNET_YES == no_route)
1405 bm |= GET_MESSAGE_BIT_RETURN_TO;
1408 if (pr->namespace != NULL)
1410 bm |= GET_MESSAGE_BIT_SKS_NAMESPACE;
1413 if (pr->target_pid != 0)
1415 bm |= GET_MESSAGE_BIT_TRANSMIT_TO;
1418 msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
1419 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1420 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1422 gm = (struct GetMessage*) &pm[1];
1423 gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
1424 gm->header.size = htons (msize);
1425 gm->type = htonl (pr->type);
1426 pr->remaining_priority /= 2;
1427 gm->priority = htonl (pr->remaining_priority);
1428 gm->ttl = htonl (pr->ttl);
1429 gm->filter_mutator = htonl(pr->mingle);
1430 gm->hash_bitmap = htonl (bm);
1431 gm->query = pr->query;
1432 ext = (GNUNET_HashCode*) &gm[1];
1434 if (GNUNET_YES == no_route)
1435 GNUNET_PEER_resolve (pr->cp->pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1436 if (pr->namespace != NULL)
1437 memcpy (&ext[k++], pr->namespace, sizeof (GNUNET_HashCode));
1438 if (pr->target_pid != 0)
1439 GNUNET_PEER_resolve (pr->target_pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1440 bfdata = (char *) &ext[k];
1442 GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
1445 pm->cont = &transmit_query_continuation;
1447 add_to_pending_messages_for_peer (cp, pm, pr);
1452 * Closure used for "target_peer_select_cb".
1454 struct PeerSelectionContext
1457 * The request for which we are selecting
1460 struct PendingRequest *pr;
1463 * Current "prime" target.
1465 struct GNUNET_PeerIdentity target;
1468 * How much do we like this target?
1470 double target_score;
1476 * Function called for each connected peer to determine
1477 * which one(s) would make good targets for forwarding.
1479 * @param cls closure (struct PeerSelectionContext)
1480 * @param key current key code (peer identity)
1481 * @param value value in the hash map (struct ConnectedPeer)
1482 * @return GNUNET_YES if we should continue to
1487 target_peer_select_cb (void *cls,
1488 const GNUNET_HashCode * key,
1491 struct PeerSelectionContext *psc = cls;
1492 struct ConnectedPeer *cp = value;
1493 struct PendingRequest *pr = psc->pr;
1498 /* 1) check if we have already (recently) forwarded to this peer */
1500 for (i=0;i<pr->used_pids_off;i++)
1501 if (pr->used_pids[i] == cp->pid)
1504 if (0 != GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1505 RETRY_PROBABILITY_INV))
1508 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1509 "NOT re-trying query that was previously transmitted %u times\n",
1510 (unsigned int) pr->used_pids_off);
1512 return GNUNET_YES; /* skip */
1517 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1518 "Re-trying query that was previously transmitted %u times to this peer\n",
1521 // 2) calculate how much we'd like to forward to this peer
1522 score = 42; // FIXME!
1523 // FIXME: also need API to gather data on responsiveness
1524 // of this peer (we have fields for that in 'cp', but
1525 // they are never set!)
1527 /* store best-fit in closure */
1528 if (score > psc->target_score)
1530 psc->target_score = score;
1531 psc->target.hashPubKey = *key;
1538 * We're processing a GET request from another peer and have decided
1539 * to forward it to other peers. This function is called periodically
1540 * and should forward the request to other peers until we have all
1541 * possible replies. If we have transmitted the *only* reply to
1542 * the initiator we should destroy the pending request. If we have
1543 * many replies in the queue to the initiator, we should delay sending
1544 * out more queries until the reply queue has shrunk some.
1546 * @param cls our "struct ProcessGetContext *"
1550 forward_request_task (void *cls,
1551 const struct GNUNET_SCHEDULER_TaskContext *tc)
1553 struct PendingRequest *pr = cls;
1554 struct PeerSelectionContext psc;
1555 struct ConnectedPeer *cp;
1556 struct GNUNET_TIME_Relative delay;
1558 pr->task = GNUNET_SCHEDULER_NO_TASK;
1559 if (pr->irc != NULL)
1562 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1563 "Forwarding of query `%s' not attempted due to pending local lookup!\n",
1564 GNUNET_h2s (&pr->query));
1566 return; /* already pending */
1568 /* (1) select target */
1570 psc.target_score = DBL_MIN;
1571 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1572 &target_peer_select_cb,
1574 if (psc.target_score == DBL_MIN)
1576 delay = get_processing_delay ();
1578 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1579 "No peer selected for forwarding of query `%s', will try again in %llu ms!\n",
1580 GNUNET_h2s (&pr->query),
1583 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1585 &forward_request_task,
1587 return; /* nobody selected */
1590 /* (2) reserve reply bandwidth */
1591 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1592 &psc.target.hashPubKey);
1593 pr->irc = GNUNET_CORE_peer_change_preference (sched, cfg,
1595 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1596 GNUNET_BANDWIDTH_value_init ((uint32_t) -1 /* no limit */),
1598 (uint64_t) cp->inc_preference,
1599 &target_reservation_cb,
1601 cp->inc_preference = 0.0;
1605 /* **************************** P2P PUT Handling ************************ */
1609 * Function called after we either failed or succeeded
1610 * at transmitting a reply to a peer.
1612 * @param cls the requests "struct PendingRequest*"
1613 * @param tpid ID of receiving peer, 0 on transmission error
1616 transmit_reply_continuation (void *cls,
1617 GNUNET_PEER_Id tpid)
1619 struct PendingRequest *pr = cls;
1623 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1624 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1625 /* only one reply expected, done with the request! */
1626 destroy_pending_request (pr);
1628 case GNUNET_DATASTORE_BLOCKTYPE_ANY:
1629 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1630 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1640 * Check if the given KBlock is well-formed.
1642 * @param kb the kblock data (or at least "dsize" bytes claiming to be one)
1643 * @param dsize size of "kb" in bytes; check for < sizeof(struct KBlock)!
1644 * @param query where to store the query that this block answers
1645 * @return GNUNET_OK if this is actually a well-formed KBlock
1648 check_kblock (const struct KBlock *kb,
1650 GNUNET_HashCode *query)
1652 if (dsize < sizeof (struct KBlock))
1654 GNUNET_break_op (0);
1655 return GNUNET_SYSERR;
1657 if (dsize - sizeof (struct KBlock) !=
1658 ntohl (kb->purpose.size)
1659 - sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose)
1660 - sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) )
1662 GNUNET_break_op (0);
1663 return GNUNET_SYSERR;
1666 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_KBLOCK,
1671 GNUNET_break_op (0);
1672 return GNUNET_SYSERR;
1675 GNUNET_CRYPTO_hash (&kb->keyspace,
1676 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1683 * Check if the given NBlock is well-formed.
1685 * @param nb the nblock data (or at least "dsize" bytes claiming to be one)
1686 * @param dsize size of "nb" in bytes; check for < sizeof(struct NBlock)!
1687 * @param query where to store the query that this block answers
1688 * @return GNUNET_OK if this is actually a well-formed NBlock
1691 check_nblock (const struct NBlock *nb,
1693 GNUNET_HashCode *query)
1695 if (dsize < sizeof (struct NBlock))
1697 GNUNET_break_op (0);
1698 return GNUNET_SYSERR;
1700 if (dsize - sizeof (struct NBlock) !=
1701 ntohl (nb->ns_purpose.size)
1702 - sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose)
1703 - sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) )
1705 GNUNET_break_op (0);
1706 return GNUNET_SYSERR;
1709 ntohl (nb->ksk_purpose.size) + sizeof (struct GNUNET_CRYPTO_RsaSignature))
1711 GNUNET_break_op (0);
1712 return GNUNET_SYSERR;
1715 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_NBLOCK_KSIG,
1720 GNUNET_break_op (0);
1721 return GNUNET_SYSERR;
1724 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_NBLOCK,
1729 GNUNET_break_op (0);
1730 return GNUNET_SYSERR;
1733 GNUNET_CRYPTO_hash (&nb->keyspace,
1734 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1741 * Check if the given SBlock is well-formed.
1743 * @param sb the sblock data (or at least "dsize" bytes claiming to be one)
1744 * @param dsize size of "kb" in bytes; check for < sizeof(struct SBlock)!
1745 * @param query where to store the query that this block answers
1746 * @param namespace where to store the namespace that this block belongs to
1747 * @return GNUNET_OK if this is actually a well-formed SBlock
1750 check_sblock (const struct SBlock *sb,
1752 GNUNET_HashCode *query,
1753 GNUNET_HashCode *namespace)
1755 if (dsize < sizeof (struct SBlock))
1757 GNUNET_break_op (0);
1758 return GNUNET_SYSERR;
1761 ntohl (sb->purpose.size) + sizeof (struct GNUNET_CRYPTO_RsaSignature))
1763 GNUNET_break_op (0);
1764 return GNUNET_SYSERR;
1767 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_SBLOCK,
1772 GNUNET_break_op (0);
1773 return GNUNET_SYSERR;
1776 *query = sb->identifier;
1777 if (namespace != NULL)
1778 GNUNET_CRYPTO_hash (&sb->subspace,
1779 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1786 * Transmit the given message by copying it to the target buffer
1787 * "buf". "buf" will be NULL and "size" zero if the socket was closed
1788 * for writing in the meantime. In that case, do nothing
1789 * (the disconnect or shutdown handler will take care of the rest).
1790 * If we were able to transmit messages and there are still more
1791 * pending, ask core again for further calls to this function.
1793 * @param cls closure, pointer to the 'struct ClientList*'
1794 * @param size number of bytes available in buf
1795 * @param buf where the callee should write the message
1796 * @return number of bytes written to buf
1799 transmit_to_client (void *cls,
1800 size_t size, void *buf)
1802 struct ClientList *cl = cls;
1804 struct ClientResponseMessage *creply;
1811 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1812 "Not sending reply, client communication problem.\n");
1817 while ( (NULL != (creply = cl->res_head) ) &&
1818 (creply->msize <= size) )
1820 memcpy (&cbuf[msize], &creply[1], creply->msize);
1821 msize += creply->msize;
1822 size -= creply->msize;
1823 GNUNET_CONTAINER_DLL_remove (cl->res_head,
1826 GNUNET_free (creply);
1829 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
1831 GNUNET_TIME_UNIT_FOREVER_REL,
1832 &transmit_to_client,
1835 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1836 "Transmitted %u bytes to client\n",
1837 (unsigned int) msize);
1844 * Closure for "process_reply" function.
1846 struct ProcessReplyClosure
1849 * The data for the reply.
1853 // FIXME: add 'struct ConnectedPeer' to track 'last_xxx_replies' here!
1856 * When the reply expires.
1858 struct GNUNET_TIME_Absolute expiration;
1866 * Namespace that this reply belongs to
1867 * (if it is of type SBLOCK).
1869 GNUNET_HashCode namespace;
1872 * Type of the block.
1877 * How much was this reply worth to us?
1884 * We have received a reply; handle it!
1886 * @param cls response (struct ProcessReplyClosure)
1887 * @param key our query
1888 * @param value value in the hash map (info about the query)
1889 * @return GNUNET_YES (we should continue to iterate)
1892 process_reply (void *cls,
1893 const GNUNET_HashCode * key,
1896 struct ProcessReplyClosure *prq = cls;
1897 struct PendingRequest *pr = value;
1898 struct PendingMessage *reply;
1899 struct ClientResponseMessage *creply;
1900 struct ClientList *cl;
1901 struct PutMessage *pm;
1902 struct ConnectedPeer *cp;
1903 GNUNET_HashCode chash;
1904 GNUNET_HashCode mhash;
1908 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1909 "Matched result (type %u) for query `%s' with pending request\n",
1910 (unsigned int) prq->type,
1913 GNUNET_STATISTICS_update (stats,
1914 gettext_noop ("# replies received and matched"),
1917 GNUNET_CRYPTO_hash (prq->data,
1922 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1923 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1924 /* only possible reply, stop requesting! */
1925 while (NULL != pr->pending_head)
1926 destroy_pending_message_list_entry (pr->pending_head);
1927 if (pr->drq != NULL)
1929 if (pr->client_request_list != NULL)
1930 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
1932 GNUNET_FS_drq_get_cancel (pr->drq);
1935 pr->do_remove = GNUNET_YES;
1936 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
1938 GNUNET_SCHEDULER_cancel (sched,
1940 pr->task = GNUNET_SCHEDULER_NO_TASK;
1942 GNUNET_break (GNUNET_YES ==
1943 GNUNET_CONTAINER_multihashmap_remove (query_request_map,
1947 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1948 if (pr->namespace == NULL)
1953 if (0 != memcmp (pr->namespace,
1955 sizeof (GNUNET_HashCode)))
1957 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1958 _("Reply mismatched in terms of namespace. Discarded.\n"));
1959 return GNUNET_YES; /* wrong namespace */
1961 /* then: fall-through! */
1962 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1963 case GNUNET_DATASTORE_BLOCKTYPE_NBLOCK:
1966 mingle_hash (&chash, pr->mingle, &mhash);
1967 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
1970 GNUNET_STATISTICS_update (stats,
1971 gettext_noop ("# duplicate replies discarded (bloomfilter)"),
1975 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1976 "Duplicate response `%s', discarding.\n",
1977 GNUNET_h2s (&mhash));
1979 return GNUNET_YES; /* duplicate */
1982 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1983 "New response `%s', adding to filter.\n",
1984 GNUNET_h2s (&mhash));
1986 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
1989 if (pr->client_request_list != NULL)
1991 if (pr->replies_seen_size == pr->replies_seen_off)
1993 GNUNET_array_grow (pr->replies_seen,
1994 pr->replies_seen_size,
1995 pr->replies_seen_size * 2 + 4);
1997 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
1998 pr->bf = refresh_bloomfilter (pr->replies_seen_off,
2003 pr->replies_seen[pr->replies_seen_off++] = chash;
2010 prq->priority += pr->remaining_priority;
2011 pr->remaining_priority = 0;
2012 if (pr->client_request_list != NULL)
2014 GNUNET_STATISTICS_update (stats,
2015 gettext_noop ("# replies received for local clients"),
2018 cl = pr->client_request_list->client_list;
2019 msize = sizeof (struct PutMessage) + prq->size;
2020 creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
2021 creply->msize = msize;
2022 creply->client_list = cl;
2023 GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
2027 pm = (struct PutMessage*) &creply[1];
2028 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2029 pm->header.size = htons (msize);
2030 pm->type = htonl (prq->type);
2031 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
2032 memcpy (&pm[1], prq->data, prq->size);
2036 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2037 "Transmitting result for query `%s' to client\n",
2040 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
2042 GNUNET_TIME_UNIT_FOREVER_REL,
2043 &transmit_to_client,
2046 GNUNET_break (cl->th != NULL);
2048 destroy_pending_request (pr);
2054 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2055 "Transmitting result for query `%s' to other peer (PID=%u)\n",
2057 (unsigned int) cp->pid);
2059 GNUNET_STATISTICS_update (stats,
2060 gettext_noop ("# replies received for other peers"),
2063 msize = sizeof (struct PutMessage) + prq->size;
2064 reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
2065 reply->cont = &transmit_reply_continuation;
2066 reply->cont_cls = pr;
2067 reply->msize = msize;
2068 reply->priority = (uint32_t) -1; /* send replies first! */
2069 pm = (struct PutMessage*) &reply[1];
2070 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2071 pm->header.size = htons (msize);
2072 pm->type = htonl (prq->type);
2073 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
2074 memcpy (&pm[1], prq->data, prq->size);
2075 add_to_pending_messages_for_peer (cp, reply, pr);
2077 // FIXME: implement hot-path routing statistics keeping!
2083 * Handle P2P "PUT" message.
2085 * @param cls closure, always NULL
2086 * @param other the other peer involved (sender or receiver, NULL
2087 * for loopback messages where we are both sender and receiver)
2088 * @param message the actual message
2089 * @param latency reported latency of the connection with 'other'
2090 * @param distance reported distance (DV) to 'other'
2091 * @return GNUNET_OK to keep the connection open,
2092 * GNUNET_SYSERR to close it (signal serious error)
2095 handle_p2p_put (void *cls,
2096 const struct GNUNET_PeerIdentity *other,
2097 const struct GNUNET_MessageHeader *message,
2098 struct GNUNET_TIME_Relative latency,
2101 const struct PutMessage *put;
2105 struct GNUNET_TIME_Absolute expiration;
2106 GNUNET_HashCode query;
2107 struct ProcessReplyClosure prq;
2109 msize = ntohs (message->size);
2110 if (msize < sizeof (struct PutMessage))
2113 return GNUNET_SYSERR;
2115 put = (const struct PutMessage*) message;
2116 dsize = msize - sizeof (struct PutMessage);
2117 type = ntohl (put->type);
2118 expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
2120 /* first, validate! */
2123 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2124 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2125 GNUNET_CRYPTO_hash (&put[1], dsize, &query);
2127 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
2129 check_kblock ((const struct KBlock*) &put[1],
2132 return GNUNET_SYSERR;
2134 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2136 check_sblock ((const struct SBlock*) &put[1],
2140 return GNUNET_SYSERR;
2142 case GNUNET_DATASTORE_BLOCKTYPE_NBLOCK:
2144 check_nblock ((const struct NBlock*) &put[1],
2147 return GNUNET_SYSERR;
2150 /* unknown block type */
2151 GNUNET_break_op (0);
2152 return GNUNET_SYSERR;
2156 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2157 "Received result for query `%s' from peer `%4s'\n",
2158 GNUNET_h2s (&query),
2159 GNUNET_i2s (other));
2161 GNUNET_STATISTICS_update (stats,
2162 gettext_noop ("# replies received (overall)"),
2165 /* now, lookup 'query' */
2166 prq.data = (const void*) &put[1];
2169 prq.expiration = expiration;
2171 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2175 // FIXME: if migration is on and load is low,
2176 // queue to store data in datastore;
2177 // use "prq.priority" for that!
2182 /* **************************** P2P GET Handling ************************ */
2186 * Closure for 'check_duplicate_request_{peer,client}'.
2188 struct CheckDuplicateRequestClosure
2191 * The new request we should check if it already exists.
2193 const struct PendingRequest *pr;
2196 * Existing request found by the checker, NULL if none.
2198 struct PendingRequest *have;
2203 * Iterator over entries in the 'query_request_map' that
2204 * tries to see if we have the same request pending from
2205 * the same client already.
2207 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
2208 * @param key current key code (query, ignored, must match)
2209 * @param value value in the hash map (a 'struct PendingRequest'
2210 * that already exists)
2211 * @return GNUNET_YES if we should continue to
2212 * iterate (no match yet)
2213 * GNUNET_NO if not (match found).
2216 check_duplicate_request_client (void *cls,
2217 const GNUNET_HashCode * key,
2220 struct CheckDuplicateRequestClosure *cdc = cls;
2221 struct PendingRequest *have = value;
2223 if (have->client_request_list == NULL)
2225 if ( (cdc->pr->client_request_list->client_list->client == have->client_request_list->client_list->client) &&
2236 * We're processing (local) results for a search request
2237 * from another peer. Pass applicable results to the
2238 * peer and if we are done either clean up (operation
2239 * complete) or forward to other peers (more results possible).
2241 * @param cls our closure (struct LocalGetContext)
2242 * @param key key for the content
2243 * @param size number of bytes in data
2244 * @param data content stored
2245 * @param type type of the content
2246 * @param priority priority of the content
2247 * @param anonymity anonymity-level for the content
2248 * @param expiration expiration time for the content
2249 * @param uid unique identifier for the datum;
2250 * maybe 0 if no unique identifier is available
2253 process_local_reply (void *cls,
2254 const GNUNET_HashCode * key,
2260 struct GNUNET_TIME_Absolute
2264 struct PendingRequest *pr = cls;
2265 struct ProcessReplyClosure prq;
2266 struct CheckDuplicateRequestClosure cdrc;
2267 GNUNET_HashCode dhash;
2268 GNUNET_HashCode mhash;
2269 GNUNET_HashCode query;
2274 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2275 "Done processing local replies, forwarding request to other peers.\n");
2278 if (pr->client_request_list != NULL)
2280 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
2282 /* Figure out if this is a duplicate request and possibly
2283 merge 'struct PendingRequest' entries */
2286 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2288 &check_duplicate_request_client,
2290 if (cdrc.have != NULL)
2293 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2294 "Received request for block `%s' twice from client, will only request once.\n",
2295 GNUNET_h2s (&pr->query));
2298 destroy_pending_request (pr);
2303 /* no more results */
2304 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2305 pr->task = GNUNET_SCHEDULER_add_now (sched,
2306 &forward_request_task,
2311 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2312 "New local response to `%s' of type %u.\n",
2316 if (type == GNUNET_DATASTORE_BLOCKTYPE_ONDEMAND)
2319 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2320 "Found ONDEMAND block, performing on-demand encoding\n");
2322 GNUNET_STATISTICS_update (stats,
2323 gettext_noop ("# on-demand blocks matched requests"),
2327 GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
2328 anonymity, expiration, uid,
2329 &process_local_reply,
2331 GNUNET_FS_drq_get_next (GNUNET_YES);
2334 /* check for duplicates */
2335 GNUNET_CRYPTO_hash (data, size, &dhash);
2336 mingle_hash (&dhash,
2339 if ( (pr->bf != NULL) &&
2341 GNUNET_CONTAINER_bloomfilter_test (pr->bf,
2345 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2346 "Result from datastore filtered by bloomfilter (duplicate).\n");
2348 GNUNET_STATISTICS_update (stats,
2349 gettext_noop ("# results filtered by query bloomfilter"),
2352 GNUNET_FS_drq_get_next (GNUNET_YES);
2356 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2357 "Found result for query `%s' in local datastore\n",
2360 GNUNET_STATISTICS_update (stats,
2361 gettext_noop ("# results found locally"),
2364 pr->results_found++;
2365 if ( (pr->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
2366 (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
2367 (pr->type == GNUNET_DATASTORE_BLOCKTYPE_NBLOCK) )
2372 pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
2377 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2378 "New local response `%s', adding to filter.\n",
2379 GNUNET_h2s (&mhash));
2382 /* this would break stuff since we will check the bf later
2383 again (and would then discard the reply!) */
2384 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
2388 memset (&prq, 0, sizeof (prq));
2390 prq.expiration = expiration;
2392 if ( (type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) &&
2393 (GNUNET_OK != check_sblock ((const struct SBlock*) data,
2399 /* FIXME: consider removing the block? */
2400 GNUNET_FS_drq_get_next (GNUNET_YES);
2404 prq.priority = priority;
2405 process_reply (&prq, key, pr);
2407 if ( (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK) ||
2408 (type == GNUNET_DATASTORE_BLOCKTYPE_IBLOCK) )
2410 GNUNET_FS_drq_get_next (GNUNET_NO);
2413 if ( (pr->client_request_list == NULL) &&
2414 ( (GNUNET_YES == test_load_too_high()) ||
2415 (pr->results_found > 5 + 2 * pr->priority) ) )
2418 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2419 "Load too high, done with request\n");
2421 GNUNET_STATISTICS_update (stats,
2422 gettext_noop ("# processing result set cut short due to load"),
2425 GNUNET_FS_drq_get_next (GNUNET_NO);
2428 GNUNET_FS_drq_get_next (GNUNET_YES);
2433 * The priority level imposes a bound on the maximum
2434 * value for the ttl that can be requested.
2436 * @param ttl_in requested ttl
2437 * @param prio given priority
2438 * @return ttl_in if ttl_in is below the limit,
2439 * otherwise the ttl-limit for the given priority
2442 bound_ttl (int32_t ttl_in, uint32_t prio)
2444 unsigned long long allowed;
2448 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
2449 if (ttl_in > allowed)
2451 if (allowed >= (1 << 30))
2460 * We've received a request with the specified priority. Bound it
2461 * according to how much we trust the given peer.
2463 * @param prio_in requested priority
2464 * @param cp the peer making the request
2465 * @return effective priority
2468 bound_priority (uint32_t prio_in,
2469 struct ConnectedPeer *cp)
2476 * Iterator over entries in the 'query_request_map' that
2477 * tries to see if we have the same request pending from
2478 * the same peer already.
2480 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
2481 * @param key current key code (query, ignored, must match)
2482 * @param value value in the hash map (a 'struct PendingRequest'
2483 * that already exists)
2484 * @return GNUNET_YES if we should continue to
2485 * iterate (no match yet)
2486 * GNUNET_NO if not (match found).
2489 check_duplicate_request_peer (void *cls,
2490 const GNUNET_HashCode * key,
2493 struct CheckDuplicateRequestClosure *cdc = cls;
2494 struct PendingRequest *have = value;
2496 if (cdc->pr->target_pid == have->target_pid)
2506 * Handle P2P "GET" request.
2508 * @param cls closure, always NULL
2509 * @param other the other peer involved (sender or receiver, NULL
2510 * for loopback messages where we are both sender and receiver)
2511 * @param message the actual message
2512 * @param latency reported latency of the connection with 'other'
2513 * @param distance reported distance (DV) to 'other'
2514 * @return GNUNET_OK to keep the connection open,
2515 * GNUNET_SYSERR to close it (signal serious error)
2518 handle_p2p_get (void *cls,
2519 const struct GNUNET_PeerIdentity *other,
2520 const struct GNUNET_MessageHeader *message,
2521 struct GNUNET_TIME_Relative latency,
2524 struct PendingRequest *pr;
2525 struct ConnectedPeer *cp;
2526 struct ConnectedPeer *cps;
2527 struct CheckDuplicateRequestClosure cdc;
2528 struct GNUNET_TIME_Relative timeout;
2530 const struct GetMessage *gm;
2532 const GNUNET_HashCode *opt;
2535 uint32_t ttl_decrement;
2540 msize = ntohs(message->size);
2541 if (msize < sizeof (struct GetMessage))
2543 GNUNET_break_op (0);
2544 return GNUNET_SYSERR;
2546 gm = (const struct GetMessage*) message;
2547 type = ntohl (gm->type);
2550 case GNUNET_DATASTORE_BLOCKTYPE_ANY:
2551 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2552 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2553 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
2554 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2557 GNUNET_break_op (0);
2558 return GNUNET_SYSERR;
2560 bm = ntohl (gm->hash_bitmap);
2568 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
2570 GNUNET_break_op (0);
2571 return GNUNET_SYSERR;
2573 opt = (const GNUNET_HashCode*) &gm[1];
2574 bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
2575 bm = ntohl (gm->hash_bitmap);
2576 if ( (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)) &&
2577 (type != GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) )
2579 GNUNET_break_op (0);
2580 return GNUNET_SYSERR;
2583 cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2584 &other->hashPubKey);
2585 GNUNET_assert (NULL != cps);
2586 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
2587 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2594 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
2595 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2596 "Failed to find RETURN-TO peer `%4s' in connection set. Dropping query.\n",
2597 GNUNET_i2s ((const struct GNUNET_PeerIdentity*) &opt[bits-1]));
2600 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2601 "Failed to find peer `%4s' in connection set. Dropping query.\n",
2602 GNUNET_i2s (other));
2604 GNUNET_STATISTICS_update (stats,
2605 gettext_noop ("# requests dropped due to missing reverse route"),
2608 /* FIXME: try connect? */
2611 /* note that we can really only check load here since otherwise
2612 peers could find out that we are overloaded by not being
2613 disconnected after sending us a malformed query... */
2614 if (GNUNET_YES == test_load_too_high ())
2617 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2618 "Dropping query from `%s', this peer is too busy.\n",
2619 GNUNET_i2s (other));
2621 GNUNET_STATISTICS_update (stats,
2622 gettext_noop ("# requests dropped due to high load"),
2629 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2630 "Received request for `%s' of type %u from peer `%4s' with flags %u\n",
2631 GNUNET_h2s (&gm->query),
2632 (unsigned int) type,
2636 have_ns = (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE));
2637 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
2638 (have_ns ? sizeof(GNUNET_HashCode) : 0));
2640 pr->namespace = (GNUNET_HashCode*) &pr[1];
2642 pr->mingle = ntohl (gm->filter_mutator);
2643 if (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2644 memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
2645 if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
2646 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
2648 pr->anonymity_level = 1;
2649 pr->priority = bound_priority (ntohl (gm->priority), cps);
2650 pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
2651 pr->query = gm->query;
2652 /* decrement ttl (always) */
2653 ttl_decrement = 2 * TTL_DECREMENT +
2654 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2656 if ( (pr->ttl < 0) &&
2657 (pr->ttl - ttl_decrement > 0) )
2660 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2661 "Dropping query from `%s' due to TTL underflow.\n",
2662 GNUNET_i2s (other));
2664 GNUNET_STATISTICS_update (stats,
2665 gettext_noop ("# requests dropped due TTL underflow"),
2668 /* integer underflow => drop (should be very rare)! */
2672 pr->ttl -= ttl_decrement;
2673 pr->start_time = GNUNET_TIME_absolute_get ();
2675 /* get bloom filter */
2678 pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
2681 pr->bf_size = bfsize;
2686 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2688 &check_duplicate_request_peer,
2690 if (cdc.have != NULL)
2692 if (cdc.have->start_time.value + cdc.have->ttl >=
2693 pr->start_time.value + pr->ttl)
2695 /* existing request has higher TTL, drop new one! */
2696 cdc.have->priority += pr->priority;
2697 destroy_pending_request (pr);
2699 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2700 "Have existing request with higher TTL, dropping new request.\n",
2701 GNUNET_i2s (other));
2703 GNUNET_STATISTICS_update (stats,
2704 gettext_noop ("# requests dropped due to existing request with higher TTL"),
2711 /* existing request has lower TTL, drop old one! */
2712 pr->priority += cdc.have->priority;
2713 /* Possible optimization: if we have applicable pending
2714 replies in 'cdc.have', we might want to move those over
2715 (this is a really rare special-case, so it is not clear
2716 that this would be worth it) */
2717 destroy_pending_request (cdc.have);
2718 /* keep processing 'pr'! */
2723 GNUNET_CONTAINER_multihashmap_put (query_request_map,
2726 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2727 GNUNET_CONTAINER_multihashmap_put (peer_request_map,
2730 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2732 pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
2734 pr->start_time.value + pr->ttl);
2736 GNUNET_STATISTICS_update (stats,
2737 gettext_noop ("# P2P searches active"),
2741 /* calculate change in traffic preference */
2742 preference = (double) pr->priority;
2743 if (preference < QUERY_BANDWIDTH_VALUE)
2744 preference = QUERY_BANDWIDTH_VALUE;
2745 cps->inc_preference += preference;
2747 /* process locally */
2748 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2749 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* to get on-demand as well */
2750 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
2751 (pr->priority + 1));
2752 pr->drq = GNUNET_FS_drq_get (&gm->query,
2754 &process_local_reply,
2759 /* Are multiple results possible? If so, start processing remotely now! */
2762 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2763 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2764 /* only one result, wait for datastore */
2767 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2768 pr->task = GNUNET_SCHEDULER_add_now (sched,
2769 &forward_request_task,
2773 /* make sure we don't track too many requests */
2774 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
2776 pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
2777 destroy_pending_request (pr);
2783 /* **************************** CS GET Handling ************************ */
2787 * Handle START_SEARCH-message (search request from client).
2789 * @param cls closure
2790 * @param client identification of the client
2791 * @param message the actual message
2794 handle_start_search (void *cls,
2795 struct GNUNET_SERVER_Client *client,
2796 const struct GNUNET_MessageHeader *message)
2798 static GNUNET_HashCode all_zeros;
2799 const struct SearchMessage *sm;
2800 struct ClientList *cl;
2801 struct ClientRequestList *crl;
2802 struct PendingRequest *pr;
2807 msize = ntohs (message->size);
2808 if ( (msize < sizeof (struct SearchMessage)) ||
2809 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
2812 GNUNET_SERVER_receive_done (client,
2816 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
2817 sm = (const struct SearchMessage*) message;
2820 while ( (cl != NULL) &&
2821 (cl->client != client) )
2825 cl = GNUNET_malloc (sizeof (struct ClientList));
2826 cl->client = client;
2827 GNUNET_SERVER_client_keep (client);
2828 cl->next = client_list;
2831 type = ntohl (sm->type);
2833 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2834 "Received request for `%s' of type %u from local client\n",
2835 GNUNET_h2s (&sm->query),
2836 (unsigned int) type);
2840 case GNUNET_DATASTORE_BLOCKTYPE_ANY:
2841 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2842 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2843 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
2844 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2845 case GNUNET_DATASTORE_BLOCKTYPE_NBLOCK:
2849 GNUNET_SERVER_receive_done (client,
2854 /* detect duplicate KBLOCK requests */
2855 if ( (type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
2856 (type == GNUNET_DATASTORE_BLOCKTYPE_NBLOCK) ||
2857 (type == GNUNET_DATASTORE_BLOCKTYPE_ANY) )
2860 while ( (crl != NULL) &&
2861 ( (0 != memcmp (&crl->req->query,
2863 sizeof (GNUNET_HashCode))) ||
2864 (crl->req->type != type) ) )
2869 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2870 "Have existing request, merging content-seen lists.\n");
2873 /* Duplicate request (used to send long list of
2874 known/blocked results); merge 'pr->replies_seen'
2875 and update bloom filter */
2876 GNUNET_array_grow (pr->replies_seen,
2877 pr->replies_seen_size,
2878 pr->replies_seen_off + sc);
2879 memcpy (&pr->replies_seen[pr->replies_seen_off],
2881 sc * sizeof (GNUNET_HashCode));
2882 pr->replies_seen_off += sc;
2884 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
2885 pr->bf = refresh_bloomfilter (pr->replies_seen_off,
2889 GNUNET_STATISTICS_update (stats,
2890 gettext_noop ("# client searches updated (merged content seen list)"),
2893 GNUNET_SERVER_receive_done (client,
2898 GNUNET_STATISTICS_update (stats,
2899 gettext_noop ("# client searches active"),
2902 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
2903 ((type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)?sizeof(GNUNET_HashCode):0));
2904 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
2905 memset (crl, 0, sizeof (struct ClientRequestList));
2906 crl->client_list = cl;
2907 GNUNET_CONTAINER_DLL_insert (cl->rl_head,
2912 pr->client_request_list = crl;
2913 GNUNET_array_grow (pr->replies_seen,
2914 pr->replies_seen_size,
2916 memcpy (pr->replies_seen,
2918 sc * sizeof (GNUNET_HashCode));
2919 pr->replies_seen_off = sc;
2920 pr->anonymity_level = ntohl (sm->anonymity_level);
2921 pr->bf = refresh_bloomfilter (pr->replies_seen_off,
2925 pr->query = sm->query;
2928 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2929 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2930 if (0 != memcmp (&sm->target,
2932 sizeof (GNUNET_HashCode)))
2933 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
2935 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2936 pr->namespace = (GNUNET_HashCode*) &pr[1];
2937 memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
2942 GNUNET_CONTAINER_multihashmap_put (query_request_map,
2945 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2946 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2947 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* get on-demand blocks too! */
2948 pr->drq = GNUNET_FS_drq_get (&sm->query,
2950 &process_local_reply,
2952 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
2957 /* **************************** Startup ************************ */
2961 * List of handlers for P2P messages
2962 * that we care about.
2964 static struct GNUNET_CORE_MessageHandler p2p_handlers[] =
2967 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
2969 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
2975 * List of handlers for the messages understood by this
2978 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2979 {&GNUNET_FS_handle_index_start, NULL,
2980 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
2981 {&GNUNET_FS_handle_index_list_get, NULL,
2982 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
2983 {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
2984 sizeof (struct UnindexMessage) },
2985 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
2992 * Process fs requests.
2994 * @param s scheduler to use
2995 * @param server the initialized server
2996 * @param c configuration to use
2999 main_init (struct GNUNET_SCHEDULER_Handle *s,
3000 struct GNUNET_SERVER_Handle *server,
3001 const struct GNUNET_CONFIGURATION_Handle *c)
3005 stats = GNUNET_STATISTICS_create (sched, "fs", cfg);
3006 connected_peers = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3007 query_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3008 peer_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3009 requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
3010 core = GNUNET_CORE_connect (sched,
3012 GNUNET_TIME_UNIT_FOREVER_REL,
3016 &peer_connect_handler,
3017 &peer_disconnect_handler,
3023 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3024 _("Failed to connect to `%s' service.\n"),
3026 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
3027 connected_peers = NULL;
3028 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
3029 query_request_map = NULL;
3030 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
3031 requests_by_expiration_heap = NULL;
3032 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
3033 peer_request_map = NULL;
3035 return GNUNET_SYSERR;
3037 GNUNET_SERVER_disconnect_notify (server,
3038 &handle_client_disconnect,
3040 GNUNET_SERVER_add_handlers (server, handlers);
3041 GNUNET_SCHEDULER_add_delayed (sched,
3042 GNUNET_TIME_UNIT_FOREVER_REL,
3050 * Process fs requests.
3052 * @param cls closure
3053 * @param sched scheduler to use
3054 * @param server the initialized server
3055 * @param cfg configuration to use
3059 struct GNUNET_SCHEDULER_Handle *sched,
3060 struct GNUNET_SERVER_Handle *server,
3061 const struct GNUNET_CONFIGURATION_Handle *cfg)
3063 if ( (GNUNET_OK != GNUNET_FS_drq_init (sched, cfg)) ||
3064 (GNUNET_OK != GNUNET_FS_indexing_init (sched, cfg)) ||
3065 (GNUNET_OK != main_init (sched, server, cfg)) )
3067 GNUNET_SCHEDULER_shutdown (sched);
3074 * The main function for the fs service.
3076 * @param argc number of arguments from the command line
3077 * @param argv command line arguments
3078 * @return 0 ok, 1 on error
3081 main (int argc, char *const *argv)
3083 return (GNUNET_OK ==
3084 GNUNET_SERVICE_run (argc,
3087 GNUNET_SERVICE_OPTION_NONE,
3088 &run, NULL)) ? 0 : 1;
3091 /* end of gnunet-service-fs.c */