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!
28 * - TTL/priority calculations are absent!
30 * - have non-zero preference / priority for requests we initiate!
31 * - track stats for hot-path routing
32 * - implement hot-path routing decision procedure
33 * - implement: bound_priority, test_load_too_high, validate_nblock
34 * - add content migration support (store locally) [or create new service]
39 #include "gnunet_constants.h"
40 #include "gnunet_core_service.h"
41 #include "gnunet_datastore_service.h"
42 #include "gnunet_peer_lib.h"
43 #include "gnunet_protocols.h"
44 #include "gnunet_signatures.h"
45 #include "gnunet_statistics_service.h"
46 #include "gnunet_util_lib.h"
47 #include "gnunet-service-fs_drq.h"
48 #include "gnunet-service-fs_indexing.h"
51 #define DEBUG_FS GNUNET_YES
54 * Maximum number of outgoing messages we queue per peer.
55 * FIXME: make configurable?
57 #define MAX_QUEUE_PER_PEER 16
60 * Inverse of the probability that we will submit the same query
61 * to the same peer again. If the same peer already got the query
62 * repeatedly recently, the probability is multiplied by the inverse
63 * of this number each time. Note that we only try about every TTL_DECREMENT/2
64 * plus MAX_CORK_DELAY (so roughly every 3.5s).
66 #define RETRY_PROBABILITY_INV 3
69 * What is the maximum delay for a P2P FS message (in our interaction
70 * with core)? FS-internal delays are another story. The value is
71 * chosen based on the 32k block size. Given that peers typcially
72 * have at least 1 kb/s bandwidth, 45s waits give us a chance to
73 * transmit one message even to the lowest-bandwidth peers.
75 #define MAX_TRANSMIT_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 45)
80 * Maximum number of requests (from other peers) that we're
81 * willing to have pending at any given point in time.
82 * FIXME: set from configuration.
84 static uint64_t max_pending_requests = (32 * 1024);
88 * Information we keep for each pending reply. The
89 * actual message follows at the end of this struct.
91 struct PendingMessage;
95 * Function called upon completion of a transmission.
98 * @param pid ID of receiving peer, 0 on transmission error
100 typedef void (*TransmissionContinuation)(void * cls,
101 GNUNET_PEER_Id tpid);
105 * Information we keep for each pending message (GET/PUT). The
106 * actual message follows at the end of this struct.
108 struct PendingMessage
111 * This is a doubly-linked list of messages to the same peer.
113 struct PendingMessage *next;
116 * This is a doubly-linked list of messages to the same peer.
118 struct PendingMessage *prev;
121 * Entry in pending message list for this pending message.
123 struct PendingMessageList *pml;
126 * Function to call immediately once we have transmitted this
129 TransmissionContinuation cont;
137 * Size of the reply; actual reply message follows
138 * at the end of this struct.
143 * How important is this message for us?
151 * Information about a peer that we are connected to.
152 * We track data that is useful for determining which
153 * peers should receive our requests. We also keep
154 * a list of messages to transmit to this peer.
160 * List of the last clients for which this peer successfully
163 struct GNUNET_SERVER_Client *last_client_replies[CS2P_SUCCESS_LIST_SIZE];
166 * List of the last PIDs for which
167 * this peer successfully answered a query;
168 * We use 0 to indicate no successful reply.
170 GNUNET_PEER_Id last_p2p_replies[P2P_SUCCESS_LIST_SIZE];
173 * Average delay between sending the peer a request and
174 * getting a reply (only calculated over the requests for
175 * which we actually got a reply). Calculated
176 * as a moving average: new_delay = ((n-1)*last_delay+curr_delay) / n
178 struct GNUNET_TIME_Relative avg_delay;
181 * Handle for an active request for transmission to this
184 struct GNUNET_CORE_TransmitHandle *cth;
187 * Messages (replies, queries, content migration) we would like to
188 * send to this peer in the near future. Sorted by priority, head.
190 struct PendingMessage *pending_messages_head;
193 * Messages (replies, queries, content migration) we would like to
194 * send to this peer in the near future. Sorted by priority, tail.
196 struct PendingMessage *pending_messages_tail;
199 * Average priority of successful replies. Calculated
200 * as a moving average: new_avg = ((n-1)*last_avg+curr_prio) / n
205 * Increase in traffic preference still to be submitted
206 * to the core service for this peer. FIXME: double or 'uint64_t'?
208 double inc_preference;
211 * The peer's identity.
216 * Size of the linked list of 'pending_messages'.
218 unsigned int pending_requests;
221 * Which offset in "last_p2p_replies" will be updated next?
222 * (we go round-robin).
224 unsigned int last_p2p_replies_woff;
227 * Which offset in "last_client_replies" will be updated next?
228 * (we go round-robin).
230 unsigned int last_client_replies_woff;
236 * Information we keep for each pending request. We should try to
237 * keep this struct as small as possible since its memory consumption
238 * is key to how many requests we can have pending at once.
240 struct PendingRequest;
244 * Doubly-linked list of requests we are performing
245 * on behalf of the same client.
247 struct ClientRequestList
251 * This is a doubly-linked list.
253 struct ClientRequestList *next;
256 * This is a doubly-linked list.
258 struct ClientRequestList *prev;
261 * Request this entry represents.
263 struct PendingRequest *req;
266 * Client list this request belongs to.
268 struct ClientList *client_list;
274 * Replies to be transmitted to the client. The actual
275 * response message is allocated after this struct.
277 struct ClientResponseMessage
280 * This is a doubly-linked list.
282 struct ClientResponseMessage *next;
285 * This is a doubly-linked list.
287 struct ClientResponseMessage *prev;
290 * Client list entry this response belongs to.
292 struct ClientList *client_list;
295 * Number of bytes in the response.
302 * Linked list of clients we are performing requests
308 * This is a linked list.
310 struct ClientList *next;
313 * ID of a client making a request, NULL if this entry is for a
316 struct GNUNET_SERVER_Client *client;
319 * Head of list of requests performed on behalf
320 * of this client right now.
322 struct ClientRequestList *rl_head;
325 * Tail of list of requests performed on behalf
326 * of this client right now.
328 struct ClientRequestList *rl_tail;
331 * Head of linked list of responses.
333 struct ClientResponseMessage *res_head;
336 * Tail of linked list of responses.
338 struct ClientResponseMessage *res_tail;
341 * Context for sending replies.
343 struct GNUNET_CONNECTION_TransmitHandle *th;
349 * Doubly-linked list of messages we are performing
350 * due to a pending request.
352 struct PendingMessageList
356 * This is a doubly-linked list of messages on behalf of the same request.
358 struct PendingMessageList *next;
361 * This is a doubly-linked list of messages on behalf of the same request.
363 struct PendingMessageList *prev;
366 * Message this entry represents.
368 struct PendingMessage *pm;
371 * Request this entry belongs to.
373 struct PendingRequest *req;
376 * Peer this message is targeted for.
378 struct ConnectedPeer *target;
384 * Information we keep for each pending request. We should try to
385 * keep this struct as small as possible since its memory consumption
386 * is key to how many requests we can have pending at once.
388 struct PendingRequest
392 * If this request was made by a client, this is our entry in the
393 * client request list; otherwise NULL.
395 struct ClientRequestList *client_request_list;
398 * Entry of peer responsible for this entry (if this request
399 * was made by a peer).
401 struct ConnectedPeer *cp;
404 * If this is a namespace query, pointer to the hash of the public
405 * key of the namespace; otherwise NULL. Pointer will be to the
406 * end of this struct (so no need to free it).
408 const GNUNET_HashCode *namespace;
411 * Bloomfilter we use to filter out replies that we don't care about
412 * (anymore). NULL as long as we are interested in all replies.
414 struct GNUNET_CONTAINER_BloomFilter *bf;
417 * Context of our GNUNET_CORE_peer_change_preference call.
419 struct GNUNET_CORE_InformationRequestContext *irc;
422 * Hash code of all replies that we have seen so far (only valid
423 * if client is not NULL since we only track replies like this for
426 GNUNET_HashCode *replies_seen;
429 * Node in the heap representing this entry; NULL
430 * if we have no heap node.
432 struct GNUNET_CONTAINER_HeapNode *hnode;
435 * Head of list of messages being performed on behalf of this
438 struct PendingMessageList *pending_head;
441 * Tail of list of messages being performed on behalf of this
444 struct PendingMessageList *pending_tail;
447 * When did we first see this request (form this peer), or, if our
448 * client is initiating, when did we last initiate a search?
450 struct GNUNET_TIME_Absolute start_time;
453 * The query that this request is for.
455 GNUNET_HashCode query;
458 * The task responsible for transmitting queries
461 GNUNET_SCHEDULER_TaskIdentifier task;
464 * (Interned) Peer identifier that identifies a preferred target
467 GNUNET_PEER_Id target_pid;
470 * (Interned) Peer identifiers of peers that have already
471 * received our query for this content.
473 GNUNET_PEER_Id *used_pids;
476 * Our entry in the DRQ (non-NULL while we wait for our
477 * turn to interact with the local database).
479 struct DatastoreRequestQueue *drq;
482 * Size of the 'bf' (in bytes).
487 * Desired anonymity level; only valid for requests from a local client.
489 uint32_t anonymity_level;
492 * How many entries in "used_pids" are actually valid?
494 unsigned int used_pids_off;
497 * How long is the "used_pids" array?
499 unsigned int used_pids_size;
502 * Number of results found for this request.
504 unsigned int results_found;
507 * How many entries in "replies_seen" are actually valid?
509 unsigned int replies_seen_off;
512 * How long is the "replies_seen" array?
514 unsigned int replies_seen_size;
517 * Priority with which this request was made. If one of our clients
518 * made the request, then this is the current priority that we are
519 * using when initiating the request. This value is used when
520 * we decide to reward other peers with trust for providing a reply.
525 * Priority points left for us to spend when forwarding this request
528 uint32_t remaining_priority;
531 * Number to mingle hashes for bloom-filter tests with.
536 * TTL with which we saw this request (or, if we initiated, TTL that
537 * we used for the request).
542 * Type of the content that this request is for.
547 * Remove this request after transmission of the current response.
557 static struct GNUNET_SCHEDULER_Handle *sched;
562 static const struct GNUNET_CONFIGURATION_Handle *cfg;
565 * Map of peer identifiers to "struct ConnectedPeer" (for that peer).
567 static struct GNUNET_CONTAINER_MultiHashMap *connected_peers;
570 * Map of peer identifiers to "struct PendingRequest" (for that peer).
572 static struct GNUNET_CONTAINER_MultiHashMap *peer_request_map;
575 * Map of query identifiers to "struct PendingRequest" (for that query).
577 static struct GNUNET_CONTAINER_MultiHashMap *query_request_map;
580 * Heap with the request that will expire next at the top. Contains
581 * pointers of type "struct PendingRequest*"; these will *also* be
582 * aliased from the "requests_by_peer" data structures and the
583 * "requests_by_query" table. Note that requests from our clients
584 * don't expire and are thus NOT in the "requests_by_expiration"
585 * (or the "requests_by_peer" tables).
587 static struct GNUNET_CONTAINER_Heap *requests_by_expiration_heap;
590 * Handle for reporting statistics.
592 static struct GNUNET_STATISTICS_Handle *stats;
595 * Linked list of clients we are currently processing requests for.
597 static struct ClientList *client_list;
600 * Pointer to handle to the core service (points to NULL until we've
603 static struct GNUNET_CORE_Handle *core;
606 /* ******************* clean up functions ************************ */
610 * We're done with a particular message list entry.
611 * Free all associated resources.
613 * @param pml entry to destroy
616 destroy_pending_message_list_entry (struct PendingMessageList *pml)
618 GNUNET_CONTAINER_DLL_remove (pml->req->pending_head,
619 pml->req->pending_tail,
621 GNUNET_CONTAINER_DLL_remove (pml->target->pending_messages_head,
622 pml->target->pending_messages_tail,
624 pml->target->pending_requests--;
625 GNUNET_free (pml->pm);
631 * Destroy the given pending message (and call the respective
634 * @param pm message to destroy
635 * @param tpid id of peer that the message was delivered to, or 0 for none
638 destroy_pending_message (struct PendingMessage *pm,
641 struct PendingMessageList *pml = pm->pml;
642 TransmissionContinuation cont;
645 GNUNET_assert (pml->pm == pm);
646 GNUNET_assert ( (tpid == 0) || (tpid == pml->target->pid) );
648 cont_cls = pm->cont_cls;
649 destroy_pending_message_list_entry (pml);
650 cont (cont_cls, tpid);
655 * We're done processing a particular request.
656 * Free all associated resources.
658 * @param pr request to destroy
661 destroy_pending_request (struct PendingRequest *pr)
663 struct GNUNET_PeerIdentity pid;
665 if (pr->hnode != NULL)
667 GNUNET_CONTAINER_heap_remove_node (requests_by_expiration_heap,
671 if (NULL == pr->client_request_list)
673 GNUNET_STATISTICS_update (stats,
674 gettext_noop ("# P2P searches active"),
680 GNUNET_STATISTICS_update (stats,
681 gettext_noop ("# client searches active"),
685 /* might have already been removed from map in 'process_reply' (if
686 there was a unique reply) or never inserted if it was a
687 duplicate; hence ignore the return value here */
688 (void) GNUNET_CONTAINER_multihashmap_remove (query_request_map,
693 GNUNET_FS_drq_get_cancel (pr->drq);
696 if (pr->client_request_list != NULL)
698 GNUNET_CONTAINER_DLL_remove (pr->client_request_list->client_list->rl_head,
699 pr->client_request_list->client_list->rl_tail,
700 pr->client_request_list);
701 GNUNET_free (pr->client_request_list);
702 pr->client_request_list = NULL;
706 GNUNET_PEER_resolve (pr->cp->pid,
708 (void) GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
715 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
720 GNUNET_CORE_peer_change_preference_cancel (pr->irc);
723 if (pr->replies_seen != NULL)
725 GNUNET_free (pr->replies_seen);
726 pr->replies_seen = NULL;
728 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
730 GNUNET_SCHEDULER_cancel (sched,
732 pr->task = GNUNET_SCHEDULER_NO_TASK;
734 while (NULL != pr->pending_head)
735 destroy_pending_message_list_entry (pr->pending_head);
736 GNUNET_PEER_change_rc (pr->target_pid, -1);
737 if (pr->used_pids != NULL)
739 GNUNET_PEER_decrement_rcs (pr->used_pids, pr->used_pids_off);
740 GNUNET_free (pr->used_pids);
741 pr->used_pids_off = 0;
742 pr->used_pids_size = 0;
743 pr->used_pids = NULL;
750 * Method called whenever a given peer connects.
752 * @param cls closure, not used
753 * @param peer peer identity this notification is about
754 * @param latency reported latency of the connection with 'other'
755 * @param distance reported distance (DV) to 'other'
758 peer_connect_handler (void *cls,
760 GNUNET_PeerIdentity * peer,
761 struct GNUNET_TIME_Relative latency,
764 struct ConnectedPeer *cp;
766 cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
767 cp->pid = GNUNET_PEER_intern (peer);
768 GNUNET_CONTAINER_multihashmap_put (connected_peers,
771 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
776 * Free (each) request made by the peer.
778 * @param cls closure, points to peer that the request belongs to
779 * @param key current key code
780 * @param value value in the hash map
781 * @return GNUNET_YES (we should continue to iterate)
784 destroy_request (void *cls,
785 const GNUNET_HashCode * key,
788 const struct GNUNET_PeerIdentity * peer = cls;
789 struct PendingRequest *pr = value;
791 GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
794 destroy_pending_request (pr);
800 * Method called whenever a peer disconnects.
802 * @param cls closure, not used
803 * @param peer peer identity this notification is about
806 peer_disconnect_handler (void *cls,
808 GNUNET_PeerIdentity * peer)
810 struct ConnectedPeer *cp;
811 struct PendingMessage *pm;
814 GNUNET_CONTAINER_multihashmap_get_multiple (peer_request_map,
818 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
822 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
824 if (NULL != cp->last_client_replies[i])
826 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
827 cp->last_client_replies[i] = NULL;
830 GNUNET_CONTAINER_multihashmap_remove (connected_peers,
833 GNUNET_PEER_change_rc (cp->pid, -1);
834 GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
836 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
837 while (NULL != (pm = cp->pending_messages_head))
838 destroy_pending_message (pm, 0 /* delivery failed */);
839 GNUNET_break (0 == cp->pending_requests);
845 * Iterator over hash map entries that removes all occurences
846 * of the given 'client' from the 'last_client_replies' of the
847 * given connected peer.
849 * @param cls closure, the 'struct GNUNET_SERVER_Client*' to remove
850 * @param key current key code (unused)
851 * @param value value in the hash map (the 'struct ConnectedPeer*' to change)
852 * @return GNUNET_YES (we should continue to iterate)
855 remove_client_from_last_client_replies (void *cls,
856 const GNUNET_HashCode * key,
859 struct GNUNET_SERVER_Client *client = cls;
860 struct ConnectedPeer *cp = value;
863 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
865 if (cp->last_client_replies[i] == client)
867 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
868 cp->last_client_replies[i] = NULL;
876 * A client disconnected. Remove all of its pending queries.
878 * @param cls closure, NULL
879 * @param client identification of the client
882 handle_client_disconnect (void *cls,
883 struct GNUNET_SERVER_Client
886 struct ClientList *pos;
887 struct ClientList *prev;
888 struct ClientRequestList *rcl;
889 struct ClientResponseMessage *creply;
895 while ( (NULL != pos) &&
896 (pos->client != client) )
902 return; /* no requests pending for this client */
903 while (NULL != (rcl = pos->rl_head))
905 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
906 "Destroying pending request `%s' on disconnect\n",
907 GNUNET_h2s (&rcl->req->query));
908 destroy_pending_request (rcl->req);
911 client_list = pos->next;
913 prev->next = pos->next;
916 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
919 while (NULL != (creply = pos->res_head))
921 GNUNET_CONTAINER_DLL_remove (pos->res_head,
924 GNUNET_free (creply);
926 GNUNET_SERVER_client_drop (pos->client);
928 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
929 &remove_client_from_last_client_replies,
935 * Iterator to free peer entries.
937 * @param cls closure, unused
938 * @param key current key code
939 * @param value value in the hash map (peer entry)
940 * @return GNUNET_YES (we should continue to iterate)
943 clean_peer (void *cls,
944 const GNUNET_HashCode * key,
947 peer_disconnect_handler (NULL, (const struct GNUNET_PeerIdentity*) key);
953 * Task run during shutdown.
959 shutdown_task (void *cls,
960 const struct GNUNET_SCHEDULER_TaskContext *tc)
962 while (client_list != NULL)
963 handle_client_disconnect (NULL,
964 client_list->client);
965 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
968 GNUNET_break (0 == GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap));
969 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
970 requests_by_expiration_heap = 0;
971 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
972 connected_peers = NULL;
973 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (query_request_map));
974 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
975 query_request_map = NULL;
976 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (peer_request_map));
977 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
978 peer_request_map = NULL;
979 GNUNET_assert (NULL != core);
980 GNUNET_CORE_disconnect (core);
984 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
992 /* ******************* Utility functions ******************** */
996 * Transmit the given message by copying it to the target buffer
997 * "buf". "buf" will be NULL and "size" zero if the socket was closed
998 * for writing in the meantime. In that case, do nothing
999 * (the disconnect or shutdown handler will take care of the rest).
1000 * If we were able to transmit messages and there are still more
1001 * pending, ask core again for further calls to this function.
1003 * @param cls closure, pointer to the 'struct ConnectedPeer*'
1004 * @param size number of bytes available in buf
1005 * @param buf where the callee should write the message
1006 * @return number of bytes written to buf
1009 transmit_to_peer (void *cls,
1010 size_t size, void *buf)
1012 struct ConnectedPeer *cp = cls;
1014 struct GNUNET_PeerIdentity pid;
1015 struct PendingMessage *pm;
1022 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1023 "Dropping message, core too busy.\n");
1028 while ( (NULL != (pm = cp->pending_messages_head) ) &&
1029 (pm->msize <= size) )
1031 memcpy (&cbuf[msize], &pm[1], pm->msize);
1034 destroy_pending_message (pm, cp->pid);
1038 GNUNET_PEER_resolve (cp->pid,
1040 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1042 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1049 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1050 "Transmitting %u bytes to peer %u.\n",
1059 * Add a message to the set of pending messages for the given peer.
1061 * @param cp peer to send message to
1062 * @param pm message to queue
1063 * @param pr request on which behalf this message is being queued
1066 add_to_pending_messages_for_peer (struct ConnectedPeer *cp,
1067 struct PendingMessage *pm,
1068 struct PendingRequest *pr)
1070 struct PendingMessage *pos;
1071 struct PendingMessageList *pml;
1072 struct GNUNET_PeerIdentity pid;
1074 GNUNET_assert (pm->next == NULL);
1075 GNUNET_assert (pm->pml == NULL);
1076 pml = GNUNET_malloc (sizeof (struct PendingMessageList));
1081 GNUNET_CONTAINER_DLL_insert (pr->pending_head,
1084 pos = cp->pending_messages_head;
1085 while ( (pos != NULL) &&
1086 (pm->priority < pos->priority) )
1088 GNUNET_CONTAINER_DLL_insert_after (cp->pending_messages_head,
1089 cp->pending_messages_tail,
1092 cp->pending_requests++;
1093 if (cp->pending_requests > MAX_QUEUE_PER_PEER)
1094 destroy_pending_message (cp->pending_messages_tail, 0);
1095 if (cp->cth == NULL)
1097 /* need to schedule transmission */
1098 GNUNET_PEER_resolve (cp->pid, &pid);
1099 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1100 cp->pending_messages_head->priority,
1103 cp->pending_messages_head->msize,
1107 if (cp->cth == NULL)
1110 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1111 "Failed to schedule transmission with core!\n");
1113 /* FIXME: call stats (rare, bad case) */
1119 * Mingle hash with the mingle_number to produce different bits.
1122 mingle_hash (const GNUNET_HashCode * in,
1123 int32_t mingle_number,
1124 GNUNET_HashCode * hc)
1128 GNUNET_CRYPTO_hash (&mingle_number,
1131 GNUNET_CRYPTO_hash_xor (&m, in, hc);
1136 * Test if the load on this peer is too high
1137 * to even consider processing the query at
1140 * @return GNUNET_YES if the load is too high, GNUNET_NO otherwise
1143 test_load_too_high ()
1145 return GNUNET_NO; // FIXME
1149 /* ******************* Pending Request Refresh Task ******************** */
1154 * We use a random delay to make the timing of requests less
1155 * predictable. This function returns such a random delay. We add a base
1156 * delay of MAX_CORK_DELAY (1s).
1158 * FIXME: make schedule dependent on the specifics of the request?
1159 * Or bandwidth and number of connected peers and load?
1161 * @return random delay to use for some request, between 1s and 1000+TTL_DECREMENT ms
1163 static struct GNUNET_TIME_Relative
1164 get_processing_delay ()
1167 GNUNET_TIME_relative_add (GNUNET_CONSTANTS_MAX_CORK_DELAY,
1168 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1169 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1175 * We're processing a GET request from another peer and have decided
1176 * to forward it to other peers. This function is called periodically
1177 * and should forward the request to other peers until we have all
1178 * possible replies. If we have transmitted the *only* reply to
1179 * the initiator we should destroy the pending request. If we have
1180 * many replies in the queue to the initiator, we should delay sending
1181 * out more queries until the reply queue has shrunk some.
1183 * @param cls our "struct ProcessGetContext *"
1187 forward_request_task (void *cls,
1188 const struct GNUNET_SCHEDULER_TaskContext *tc);
1192 * Function called after we either failed or succeeded
1193 * at transmitting a query to a peer.
1195 * @param cls the requests "struct PendingRequest*"
1196 * @param tpid ID of receiving peer, 0 on transmission error
1199 transmit_query_continuation (void *cls,
1200 GNUNET_PEER_Id tpid)
1202 struct PendingRequest *pr = cls;
1204 GNUNET_STATISTICS_update (stats,
1205 gettext_noop ("# queries scheduled for forwarding"),
1211 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1212 "Transmission of request failed, will try again later.\n");
1214 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1215 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1216 get_processing_delay (),
1217 &forward_request_task,
1221 GNUNET_STATISTICS_update (stats,
1222 gettext_noop ("# queries forwarded"),
1225 GNUNET_PEER_change_rc (tpid, 1);
1226 if (pr->used_pids_off == pr->used_pids_size)
1227 GNUNET_array_grow (pr->used_pids,
1229 pr->used_pids_size * 2 + 2);
1230 pr->used_pids[pr->used_pids_off++] = tpid;
1231 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1232 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1233 get_processing_delay (),
1234 &forward_request_task,
1240 * How many bytes should a bloomfilter be if we have already seen
1241 * entry_count responses? Note that BLOOMFILTER_K gives us the number
1242 * of bits set per entry. Furthermore, we should not re-size the
1243 * filter too often (to keep it cheap).
1245 * Since other peers will also add entries but not resize the filter,
1246 * we should generally pick a slightly larger size than what the
1247 * strict math would suggest.
1249 * @return must be a power of two and smaller or equal to 2^15.
1252 compute_bloomfilter_size (unsigned int entry_count)
1255 unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
1256 uint16_t max = 1 << 15;
1258 if (entry_count > max)
1261 while ((size < max) && (size < ideal))
1270 * Recalculate our bloom filter for filtering replies.
1272 * @param count number of entries we are filtering right now
1273 * @param mingle set to our new mingling value
1274 * @param bf_size set to the size of the bloomfilter
1275 * @param entries the entries to filter
1276 * @return updated bloomfilter, NULL for none
1278 static struct GNUNET_CONTAINER_BloomFilter *
1279 refresh_bloomfilter (unsigned int count,
1282 const GNUNET_HashCode *entries)
1284 struct GNUNET_CONTAINER_BloomFilter *bf;
1287 GNUNET_HashCode mhash;
1291 nsize = compute_bloomfilter_size (count);
1292 *mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
1294 bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
1297 for (i=0;i<count;i++)
1299 mingle_hash (&entries[i], *mingle, &mhash);
1300 GNUNET_CONTAINER_bloomfilter_add (bf, &mhash);
1307 * Function called after we've tried to reserve a certain amount of
1308 * bandwidth for a reply. Check if we succeeded and if so send our
1311 * @param cls the requests "struct PendingRequest*"
1312 * @param peer identifies the peer
1313 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1314 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1315 * @param amount set to the amount that was actually reserved or unreserved
1316 * @param preference current traffic preference for the given peer
1319 target_reservation_cb (void *cls,
1321 GNUNET_PeerIdentity * peer,
1322 struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
1323 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1325 uint64_t preference)
1327 struct PendingRequest *pr = cls;
1328 struct ConnectedPeer *cp;
1329 struct PendingMessage *pm;
1330 struct GetMessage *gm;
1331 GNUNET_HashCode *ext;
1341 /* error in communication with core, try again later */
1342 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1343 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1344 get_processing_delay (),
1345 &forward_request_task,
1349 // (3) transmit, update ttl/priority
1350 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1354 /* Peer must have just left */
1356 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1357 "Selected peer disconnected!\n");
1359 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1360 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1361 get_processing_delay (),
1362 &forward_request_task,
1366 no_route = GNUNET_NO;
1367 /* FIXME: check against DBLOCK_SIZE and possibly return
1368 amount to reserve; however, this also needs to work
1369 with testcases which currently start out with a far
1370 too low per-peer bw limit, so they would never send
1371 anything. Big issue. */
1377 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1378 "Failed to reserve bandwidth for reply (got %d/%u bytes only)!\n",
1382 GNUNET_STATISTICS_update (stats,
1383 gettext_noop ("# reply bandwidth reservation requests failed"),
1386 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1387 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1388 get_processing_delay (),
1389 &forward_request_task,
1391 return; /* this target round failed */
1393 /* FIXME: if we are "quite" busy, we may still want to skip
1394 this round; need more load detection code! */
1395 no_route = GNUNET_YES;
1398 GNUNET_STATISTICS_update (stats,
1399 gettext_noop ("# queries scheduled for forwarding"),
1402 /* build message and insert message into priority queue */
1404 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1405 "Forwarding request `%s' to `%4s'!\n",
1406 GNUNET_h2s (&pr->query),
1411 if (GNUNET_YES == no_route)
1413 bm |= GET_MESSAGE_BIT_RETURN_TO;
1416 if (pr->namespace != NULL)
1418 bm |= GET_MESSAGE_BIT_SKS_NAMESPACE;
1421 if (pr->target_pid != 0)
1423 bm |= GET_MESSAGE_BIT_TRANSMIT_TO;
1426 msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
1427 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1428 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1430 gm = (struct GetMessage*) &pm[1];
1431 gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
1432 gm->header.size = htons (msize);
1433 gm->type = htonl (pr->type);
1434 pr->remaining_priority /= 2;
1435 gm->priority = htonl (pr->remaining_priority);
1436 gm->ttl = htonl (pr->ttl);
1437 gm->filter_mutator = htonl(pr->mingle);
1438 gm->hash_bitmap = htonl (bm);
1439 gm->query = pr->query;
1440 ext = (GNUNET_HashCode*) &gm[1];
1442 if (GNUNET_YES == no_route)
1443 GNUNET_PEER_resolve (pr->cp->pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1444 if (pr->namespace != NULL)
1445 memcpy (&ext[k++], pr->namespace, sizeof (GNUNET_HashCode));
1446 if (pr->target_pid != 0)
1447 GNUNET_PEER_resolve (pr->target_pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1448 bfdata = (char *) &ext[k];
1450 GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
1453 pm->cont = &transmit_query_continuation;
1455 add_to_pending_messages_for_peer (cp, pm, pr);
1460 * Closure used for "target_peer_select_cb".
1462 struct PeerSelectionContext
1465 * The request for which we are selecting
1468 struct PendingRequest *pr;
1471 * Current "prime" target.
1473 struct GNUNET_PeerIdentity target;
1476 * How much do we like this target?
1478 double target_score;
1484 * Function called for each connected peer to determine
1485 * which one(s) would make good targets for forwarding.
1487 * @param cls closure (struct PeerSelectionContext)
1488 * @param key current key code (peer identity)
1489 * @param value value in the hash map (struct ConnectedPeer)
1490 * @return GNUNET_YES if we should continue to
1495 target_peer_select_cb (void *cls,
1496 const GNUNET_HashCode * key,
1499 struct PeerSelectionContext *psc = cls;
1500 struct ConnectedPeer *cp = value;
1501 struct PendingRequest *pr = psc->pr;
1506 /* 1) check if we have already (recently) forwarded to this peer */
1508 for (i=0;i<pr->used_pids_off;i++)
1509 if (pr->used_pids[i] == cp->pid)
1512 if (0 != GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1513 RETRY_PROBABILITY_INV))
1516 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1517 "NOT re-trying query that was previously transmitted %u times\n",
1518 (unsigned int) pr->used_pids_off);
1520 return GNUNET_YES; /* skip */
1525 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1526 "Re-trying query that was previously transmitted %u times to this peer\n",
1529 // 2) calculate how much we'd like to forward to this peer
1530 score = 42; // FIXME!
1531 // FIXME: also need API to gather data on responsiveness
1532 // of this peer (we have fields for that in 'cp', but
1533 // they are never set!)
1535 /* store best-fit in closure */
1536 if (score > psc->target_score)
1538 psc->target_score = score;
1539 psc->target.hashPubKey = *key;
1546 * The priority level imposes a bound on the maximum
1547 * value for the ttl that can be requested.
1549 * @param ttl_in requested ttl
1550 * @param prio given priority
1551 * @return ttl_in if ttl_in is below the limit,
1552 * otherwise the ttl-limit for the given priority
1555 bound_ttl (int32_t ttl_in, uint32_t prio)
1557 unsigned long long allowed;
1561 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
1562 if (ttl_in > allowed)
1564 if (allowed >= (1 << 30))
1573 * We're processing a GET request from another peer and have decided
1574 * to forward it to other peers. This function is called periodically
1575 * and should forward the request to other peers until we have all
1576 * possible replies. If we have transmitted the *only* reply to
1577 * the initiator we should destroy the pending request. If we have
1578 * many replies in the queue to the initiator, we should delay sending
1579 * out more queries until the reply queue has shrunk some.
1581 * @param cls our "struct ProcessGetContext *"
1585 forward_request_task (void *cls,
1586 const struct GNUNET_SCHEDULER_TaskContext *tc)
1588 struct PendingRequest *pr = cls;
1589 struct PeerSelectionContext psc;
1590 struct ConnectedPeer *cp;
1591 struct GNUNET_TIME_Relative delay;
1593 pr->task = GNUNET_SCHEDULER_NO_TASK;
1594 if (pr->irc != NULL)
1597 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1598 "Forwarding of query `%s' not attempted due to pending local lookup!\n",
1599 GNUNET_h2s (&pr->query));
1601 return; /* already pending */
1603 /* (1) select target */
1605 psc.target_score = DBL_MIN;
1606 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1607 &target_peer_select_cb,
1609 if (psc.target_score == DBL_MIN)
1611 delay = get_processing_delay ();
1613 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1614 "No peer selected for forwarding of query `%s', will try again in %llu ms!\n",
1615 GNUNET_h2s (&pr->query),
1618 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1620 &forward_request_task,
1622 return; /* nobody selected */
1624 /* (3) update TTL/priority */
1626 if (pr->client_request_list != NULL)
1628 /* FIXME: use better algorithm!? */
1629 if (0 == GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1632 /* FIXME: bound priority by "customary" priority used by other peers
1634 pr->ttl = bound_ttl (pr->ttl + TTL_DECREMENT * 2,
1636 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1637 "Trying query `%s' with priority %u and TTL %d.\n",
1638 GNUNET_h2s (&pr->query),
1644 /* FIXME: should we do something here as well!? */
1647 /* (3) reserve reply bandwidth */
1648 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1649 &psc.target.hashPubKey);
1650 pr->irc = GNUNET_CORE_peer_change_preference (sched, cfg,
1652 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1653 GNUNET_BANDWIDTH_value_init ((uint32_t) -1 /* no limit */),
1655 (uint64_t) cp->inc_preference,
1656 &target_reservation_cb,
1658 cp->inc_preference = 0.0;
1662 /* **************************** P2P PUT Handling ************************ */
1666 * Function called after we either failed or succeeded
1667 * at transmitting a reply to a peer.
1669 * @param cls the requests "struct PendingRequest*"
1670 * @param tpid ID of receiving peer, 0 on transmission error
1673 transmit_reply_continuation (void *cls,
1674 GNUNET_PEER_Id tpid)
1676 struct PendingRequest *pr = cls;
1680 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1681 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1682 /* only one reply expected, done with the request! */
1683 destroy_pending_request (pr);
1685 case GNUNET_DATASTORE_BLOCKTYPE_ANY:
1686 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1687 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1697 * Check if the given KBlock is well-formed.
1699 * @param kb the kblock data (or at least "dsize" bytes claiming to be one)
1700 * @param dsize size of "kb" in bytes; check for < sizeof(struct KBlock)!
1701 * @param query where to store the query that this block answers
1702 * @return GNUNET_OK if this is actually a well-formed KBlock
1705 check_kblock (const struct KBlock *kb,
1707 GNUNET_HashCode *query)
1709 if (dsize < sizeof (struct KBlock))
1711 GNUNET_break_op (0);
1712 return GNUNET_SYSERR;
1714 if (dsize - sizeof (struct KBlock) !=
1715 ntohl (kb->purpose.size)
1716 - sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose)
1717 - sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) )
1719 GNUNET_break_op (0);
1720 return GNUNET_SYSERR;
1723 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_KBLOCK,
1728 GNUNET_break_op (0);
1729 return GNUNET_SYSERR;
1732 GNUNET_CRYPTO_hash (&kb->keyspace,
1733 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1740 * Check if the given NBlock is well-formed.
1742 * @param nb the nblock data (or at least "dsize" bytes claiming to be one)
1743 * @param dsize size of "nb" in bytes; check for < sizeof(struct NBlock)!
1744 * @param query where to store the query that this block answers
1745 * @return GNUNET_OK if this is actually a well-formed NBlock
1748 check_nblock (const struct NBlock *nb,
1750 GNUNET_HashCode *query)
1752 if (dsize < sizeof (struct NBlock))
1754 GNUNET_break_op (0);
1755 return GNUNET_SYSERR;
1757 if (dsize - sizeof (struct NBlock) !=
1758 ntohl (nb->ns_purpose.size)
1759 - sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose)
1760 - sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) )
1762 GNUNET_break_op (0);
1763 return GNUNET_SYSERR;
1766 ntohl (nb->ksk_purpose.size) + sizeof (struct GNUNET_CRYPTO_RsaSignature))
1768 GNUNET_break_op (0);
1769 return GNUNET_SYSERR;
1772 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_NBLOCK_KSIG,
1777 GNUNET_break_op (0);
1778 return GNUNET_SYSERR;
1781 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_NBLOCK,
1786 GNUNET_break_op (0);
1787 return GNUNET_SYSERR;
1790 GNUNET_CRYPTO_hash (&nb->keyspace,
1791 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1798 * Check if the given SBlock is well-formed.
1800 * @param sb the sblock data (or at least "dsize" bytes claiming to be one)
1801 * @param dsize size of "kb" in bytes; check for < sizeof(struct SBlock)!
1802 * @param query where to store the query that this block answers
1803 * @param namespace where to store the namespace that this block belongs to
1804 * @return GNUNET_OK if this is actually a well-formed SBlock
1807 check_sblock (const struct SBlock *sb,
1809 GNUNET_HashCode *query,
1810 GNUNET_HashCode *namespace)
1812 if (dsize < sizeof (struct SBlock))
1814 GNUNET_break_op (0);
1815 return GNUNET_SYSERR;
1818 ntohl (sb->purpose.size) + sizeof (struct GNUNET_CRYPTO_RsaSignature))
1820 GNUNET_break_op (0);
1821 return GNUNET_SYSERR;
1824 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_SBLOCK,
1829 GNUNET_break_op (0);
1830 return GNUNET_SYSERR;
1833 *query = sb->identifier;
1834 if (namespace != NULL)
1835 GNUNET_CRYPTO_hash (&sb->subspace,
1836 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1843 * Transmit the given message by copying it to the target buffer
1844 * "buf". "buf" will be NULL and "size" zero if the socket was closed
1845 * for writing in the meantime. In that case, do nothing
1846 * (the disconnect or shutdown handler will take care of the rest).
1847 * If we were able to transmit messages and there are still more
1848 * pending, ask core again for further calls to this function.
1850 * @param cls closure, pointer to the 'struct ClientList*'
1851 * @param size number of bytes available in buf
1852 * @param buf where the callee should write the message
1853 * @return number of bytes written to buf
1856 transmit_to_client (void *cls,
1857 size_t size, void *buf)
1859 struct ClientList *cl = cls;
1861 struct ClientResponseMessage *creply;
1868 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1869 "Not sending reply, client communication problem.\n");
1874 while ( (NULL != (creply = cl->res_head) ) &&
1875 (creply->msize <= size) )
1877 memcpy (&cbuf[msize], &creply[1], creply->msize);
1878 msize += creply->msize;
1879 size -= creply->msize;
1880 GNUNET_CONTAINER_DLL_remove (cl->res_head,
1883 GNUNET_free (creply);
1886 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
1888 GNUNET_TIME_UNIT_FOREVER_REL,
1889 &transmit_to_client,
1892 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1893 "Transmitted %u bytes to client\n",
1894 (unsigned int) msize);
1901 * Closure for "process_reply" function.
1903 struct ProcessReplyClosure
1906 * The data for the reply.
1910 // FIXME: add 'struct ConnectedPeer' to track 'last_xxx_replies' here!
1913 * When the reply expires.
1915 struct GNUNET_TIME_Absolute expiration;
1923 * Namespace that this reply belongs to
1924 * (if it is of type SBLOCK).
1926 GNUNET_HashCode namespace;
1929 * Type of the block.
1934 * How much was this reply worth to us?
1941 * We have received a reply; handle it!
1943 * @param cls response (struct ProcessReplyClosure)
1944 * @param key our query
1945 * @param value value in the hash map (info about the query)
1946 * @return GNUNET_YES (we should continue to iterate)
1949 process_reply (void *cls,
1950 const GNUNET_HashCode * key,
1953 struct ProcessReplyClosure *prq = cls;
1954 struct PendingRequest *pr = value;
1955 struct PendingMessage *reply;
1956 struct ClientResponseMessage *creply;
1957 struct ClientList *cl;
1958 struct PutMessage *pm;
1959 struct ConnectedPeer *cp;
1960 GNUNET_HashCode chash;
1961 GNUNET_HashCode mhash;
1965 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1966 "Matched result (type %u) for query `%s' with pending request\n",
1967 (unsigned int) prq->type,
1970 GNUNET_STATISTICS_update (stats,
1971 gettext_noop ("# replies received and matched"),
1974 GNUNET_CRYPTO_hash (prq->data,
1979 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1980 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1981 /* only possible reply, stop requesting! */
1982 while (NULL != pr->pending_head)
1983 destroy_pending_message_list_entry (pr->pending_head);
1984 if (pr->drq != NULL)
1986 if (pr->client_request_list != NULL)
1987 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
1989 GNUNET_FS_drq_get_cancel (pr->drq);
1992 pr->do_remove = GNUNET_YES;
1993 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
1995 GNUNET_SCHEDULER_cancel (sched,
1997 pr->task = GNUNET_SCHEDULER_NO_TASK;
1999 GNUNET_break (GNUNET_YES ==
2000 GNUNET_CONTAINER_multihashmap_remove (query_request_map,
2004 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2005 if (pr->namespace == NULL)
2010 if (0 != memcmp (pr->namespace,
2012 sizeof (GNUNET_HashCode)))
2014 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2015 _("Reply mismatched in terms of namespace. Discarded.\n"));
2016 return GNUNET_YES; /* wrong namespace */
2018 /* then: fall-through! */
2019 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
2020 case GNUNET_DATASTORE_BLOCKTYPE_NBLOCK:
2023 mingle_hash (&chash, pr->mingle, &mhash);
2024 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
2027 GNUNET_STATISTICS_update (stats,
2028 gettext_noop ("# duplicate replies discarded (bloomfilter)"),
2032 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2033 "Duplicate response `%s', discarding.\n",
2034 GNUNET_h2s (&mhash));
2036 return GNUNET_YES; /* duplicate */
2039 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2040 "New response `%s', adding to filter.\n",
2041 GNUNET_h2s (&mhash));
2043 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
2046 if (pr->client_request_list != NULL)
2048 if (pr->replies_seen_size == pr->replies_seen_off)
2050 GNUNET_array_grow (pr->replies_seen,
2051 pr->replies_seen_size,
2052 pr->replies_seen_size * 2 + 4);
2054 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
2055 pr->bf = refresh_bloomfilter (pr->replies_seen_off,
2060 pr->replies_seen[pr->replies_seen_off++] = chash;
2067 prq->priority += pr->remaining_priority;
2068 pr->remaining_priority = 0;
2069 if (pr->client_request_list != NULL)
2071 GNUNET_STATISTICS_update (stats,
2072 gettext_noop ("# replies received for local clients"),
2075 cl = pr->client_request_list->client_list;
2076 msize = sizeof (struct PutMessage) + prq->size;
2077 creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
2078 creply->msize = msize;
2079 creply->client_list = cl;
2080 GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
2084 pm = (struct PutMessage*) &creply[1];
2085 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2086 pm->header.size = htons (msize);
2087 pm->type = htonl (prq->type);
2088 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
2089 memcpy (&pm[1], prq->data, prq->size);
2093 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2094 "Transmitting result for query `%s' to client\n",
2097 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
2099 GNUNET_TIME_UNIT_FOREVER_REL,
2100 &transmit_to_client,
2103 GNUNET_break (cl->th != NULL);
2105 destroy_pending_request (pr);
2111 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2112 "Transmitting result for query `%s' to other peer (PID=%u)\n",
2114 (unsigned int) cp->pid);
2116 GNUNET_STATISTICS_update (stats,
2117 gettext_noop ("# replies received for other peers"),
2120 msize = sizeof (struct PutMessage) + prq->size;
2121 reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
2122 reply->cont = &transmit_reply_continuation;
2123 reply->cont_cls = pr;
2124 reply->msize = msize;
2125 reply->priority = (uint32_t) -1; /* send replies first! */
2126 pm = (struct PutMessage*) &reply[1];
2127 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2128 pm->header.size = htons (msize);
2129 pm->type = htonl (prq->type);
2130 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
2131 memcpy (&pm[1], prq->data, prq->size);
2132 add_to_pending_messages_for_peer (cp, reply, pr);
2134 // FIXME: implement hot-path routing statistics keeping!
2140 * Handle P2P "PUT" message.
2142 * @param cls closure, always NULL
2143 * @param other the other peer involved (sender or receiver, NULL
2144 * for loopback messages where we are both sender and receiver)
2145 * @param message the actual message
2146 * @param latency reported latency of the connection with 'other'
2147 * @param distance reported distance (DV) to 'other'
2148 * @return GNUNET_OK to keep the connection open,
2149 * GNUNET_SYSERR to close it (signal serious error)
2152 handle_p2p_put (void *cls,
2153 const struct GNUNET_PeerIdentity *other,
2154 const struct GNUNET_MessageHeader *message,
2155 struct GNUNET_TIME_Relative latency,
2158 const struct PutMessage *put;
2162 struct GNUNET_TIME_Absolute expiration;
2163 GNUNET_HashCode query;
2164 struct ProcessReplyClosure prq;
2166 msize = ntohs (message->size);
2167 if (msize < sizeof (struct PutMessage))
2170 return GNUNET_SYSERR;
2172 put = (const struct PutMessage*) message;
2173 dsize = msize - sizeof (struct PutMessage);
2174 type = ntohl (put->type);
2175 expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
2177 /* first, validate! */
2180 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2181 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2182 GNUNET_CRYPTO_hash (&put[1], dsize, &query);
2184 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
2186 check_kblock ((const struct KBlock*) &put[1],
2189 return GNUNET_SYSERR;
2191 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2193 check_sblock ((const struct SBlock*) &put[1],
2197 return GNUNET_SYSERR;
2199 case GNUNET_DATASTORE_BLOCKTYPE_NBLOCK:
2201 check_nblock ((const struct NBlock*) &put[1],
2204 return GNUNET_SYSERR;
2207 /* unknown block type */
2208 GNUNET_break_op (0);
2209 return GNUNET_SYSERR;
2213 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2214 "Received result for query `%s' from peer `%4s'\n",
2215 GNUNET_h2s (&query),
2216 GNUNET_i2s (other));
2218 GNUNET_STATISTICS_update (stats,
2219 gettext_noop ("# replies received (overall)"),
2222 /* now, lookup 'query' */
2223 prq.data = (const void*) &put[1];
2226 prq.expiration = expiration;
2228 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2232 // FIXME: if migration is on and load is low,
2233 // queue to store data in datastore;
2234 // use "prq.priority" for that!
2239 /* **************************** P2P GET Handling ************************ */
2243 * Closure for 'check_duplicate_request_{peer,client}'.
2245 struct CheckDuplicateRequestClosure
2248 * The new request we should check if it already exists.
2250 const struct PendingRequest *pr;
2253 * Existing request found by the checker, NULL if none.
2255 struct PendingRequest *have;
2260 * Iterator over entries in the 'query_request_map' that
2261 * tries to see if we have the same request pending from
2262 * the same client already.
2264 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
2265 * @param key current key code (query, ignored, must match)
2266 * @param value value in the hash map (a 'struct PendingRequest'
2267 * that already exists)
2268 * @return GNUNET_YES if we should continue to
2269 * iterate (no match yet)
2270 * GNUNET_NO if not (match found).
2273 check_duplicate_request_client (void *cls,
2274 const GNUNET_HashCode * key,
2277 struct CheckDuplicateRequestClosure *cdc = cls;
2278 struct PendingRequest *have = value;
2280 if (have->client_request_list == NULL)
2282 if ( (cdc->pr->client_request_list->client_list->client == have->client_request_list->client_list->client) &&
2293 * We're processing (local) results for a search request
2294 * from another peer. Pass applicable results to the
2295 * peer and if we are done either clean up (operation
2296 * complete) or forward to other peers (more results possible).
2298 * @param cls our closure (struct LocalGetContext)
2299 * @param key key for the content
2300 * @param size number of bytes in data
2301 * @param data content stored
2302 * @param type type of the content
2303 * @param priority priority of the content
2304 * @param anonymity anonymity-level for the content
2305 * @param expiration expiration time for the content
2306 * @param uid unique identifier for the datum;
2307 * maybe 0 if no unique identifier is available
2310 process_local_reply (void *cls,
2311 const GNUNET_HashCode * key,
2317 struct GNUNET_TIME_Absolute
2321 struct PendingRequest *pr = cls;
2322 struct ProcessReplyClosure prq;
2323 struct CheckDuplicateRequestClosure cdrc;
2324 GNUNET_HashCode dhash;
2325 GNUNET_HashCode mhash;
2326 GNUNET_HashCode query;
2331 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2332 "Done processing local replies, forwarding request to other peers.\n");
2335 if (pr->client_request_list != NULL)
2337 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
2339 /* Figure out if this is a duplicate request and possibly
2340 merge 'struct PendingRequest' entries */
2343 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2345 &check_duplicate_request_client,
2347 if (cdrc.have != NULL)
2350 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2351 "Received request for block `%s' twice from client, will only request once.\n",
2352 GNUNET_h2s (&pr->query));
2355 destroy_pending_request (pr);
2360 /* no more results */
2361 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2362 pr->task = GNUNET_SCHEDULER_add_now (sched,
2363 &forward_request_task,
2368 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2369 "New local response to `%s' of type %u.\n",
2373 if (type == GNUNET_DATASTORE_BLOCKTYPE_ONDEMAND)
2376 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2377 "Found ONDEMAND block, performing on-demand encoding\n");
2379 GNUNET_STATISTICS_update (stats,
2380 gettext_noop ("# on-demand blocks matched requests"),
2384 GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
2385 anonymity, expiration, uid,
2386 &process_local_reply,
2388 GNUNET_FS_drq_get_next (GNUNET_YES);
2391 /* check for duplicates */
2392 GNUNET_CRYPTO_hash (data, size, &dhash);
2393 mingle_hash (&dhash,
2396 if ( (pr->bf != NULL) &&
2398 GNUNET_CONTAINER_bloomfilter_test (pr->bf,
2402 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2403 "Result from datastore filtered by bloomfilter (duplicate).\n");
2405 GNUNET_STATISTICS_update (stats,
2406 gettext_noop ("# results filtered by query bloomfilter"),
2409 GNUNET_FS_drq_get_next (GNUNET_YES);
2413 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2414 "Found result for query `%s' in local datastore\n",
2417 GNUNET_STATISTICS_update (stats,
2418 gettext_noop ("# results found locally"),
2421 pr->results_found++;
2422 if ( (pr->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
2423 (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
2424 (pr->type == GNUNET_DATASTORE_BLOCKTYPE_NBLOCK) )
2429 pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
2434 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2435 "New local response `%s', adding to filter.\n",
2436 GNUNET_h2s (&mhash));
2439 /* this would break stuff since we will check the bf later
2440 again (and would then discard the reply!) */
2441 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
2445 memset (&prq, 0, sizeof (prq));
2447 prq.expiration = expiration;
2449 if ( (type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) &&
2450 (GNUNET_OK != check_sblock ((const struct SBlock*) data,
2456 /* FIXME: consider removing the block? */
2457 GNUNET_FS_drq_get_next (GNUNET_YES);
2461 prq.priority = priority;
2462 process_reply (&prq, key, pr);
2464 if ( (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK) ||
2465 (type == GNUNET_DATASTORE_BLOCKTYPE_IBLOCK) )
2467 GNUNET_FS_drq_get_next (GNUNET_NO);
2470 if ( (pr->client_request_list == NULL) &&
2471 ( (GNUNET_YES == test_load_too_high()) ||
2472 (pr->results_found > 5 + 2 * pr->priority) ) )
2475 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2476 "Load too high, done with request\n");
2478 GNUNET_STATISTICS_update (stats,
2479 gettext_noop ("# processing result set cut short due to load"),
2482 GNUNET_FS_drq_get_next (GNUNET_NO);
2485 GNUNET_FS_drq_get_next (GNUNET_YES);
2490 * We've received a request with the specified priority. Bound it
2491 * according to how much we trust the given peer.
2493 * @param prio_in requested priority
2494 * @param cp the peer making the request
2495 * @return effective priority
2498 bound_priority (uint32_t prio_in,
2499 struct ConnectedPeer *cp)
2506 * Iterator over entries in the 'query_request_map' that
2507 * tries to see if we have the same request pending from
2508 * the same peer already.
2510 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
2511 * @param key current key code (query, ignored, must match)
2512 * @param value value in the hash map (a 'struct PendingRequest'
2513 * that already exists)
2514 * @return GNUNET_YES if we should continue to
2515 * iterate (no match yet)
2516 * GNUNET_NO if not (match found).
2519 check_duplicate_request_peer (void *cls,
2520 const GNUNET_HashCode * key,
2523 struct CheckDuplicateRequestClosure *cdc = cls;
2524 struct PendingRequest *have = value;
2526 if (cdc->pr->target_pid == have->target_pid)
2536 * Handle P2P "GET" request.
2538 * @param cls closure, always NULL
2539 * @param other the other peer involved (sender or receiver, NULL
2540 * for loopback messages where we are both sender and receiver)
2541 * @param message the actual message
2542 * @param latency reported latency of the connection with 'other'
2543 * @param distance reported distance (DV) to 'other'
2544 * @return GNUNET_OK to keep the connection open,
2545 * GNUNET_SYSERR to close it (signal serious error)
2548 handle_p2p_get (void *cls,
2549 const struct GNUNET_PeerIdentity *other,
2550 const struct GNUNET_MessageHeader *message,
2551 struct GNUNET_TIME_Relative latency,
2554 struct PendingRequest *pr;
2555 struct ConnectedPeer *cp;
2556 struct ConnectedPeer *cps;
2557 struct CheckDuplicateRequestClosure cdc;
2558 struct GNUNET_TIME_Relative timeout;
2560 const struct GetMessage *gm;
2562 const GNUNET_HashCode *opt;
2565 uint32_t ttl_decrement;
2570 msize = ntohs(message->size);
2571 if (msize < sizeof (struct GetMessage))
2573 GNUNET_break_op (0);
2574 return GNUNET_SYSERR;
2576 gm = (const struct GetMessage*) message;
2577 type = ntohl (gm->type);
2580 case GNUNET_DATASTORE_BLOCKTYPE_ANY:
2581 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2582 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2583 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
2584 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2587 GNUNET_break_op (0);
2588 return GNUNET_SYSERR;
2590 bm = ntohl (gm->hash_bitmap);
2598 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
2600 GNUNET_break_op (0);
2601 return GNUNET_SYSERR;
2603 opt = (const GNUNET_HashCode*) &gm[1];
2604 bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
2605 bm = ntohl (gm->hash_bitmap);
2606 if ( (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)) &&
2607 (type != GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) )
2609 GNUNET_break_op (0);
2610 return GNUNET_SYSERR;
2613 cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2614 &other->hashPubKey);
2617 /* peer must have just disconnected */
2618 GNUNET_STATISTICS_update (stats,
2619 gettext_noop ("# requests dropped due to initiator not being connected"),
2622 return GNUNET_SYSERR;
2624 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
2625 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2632 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
2633 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2634 "Failed to find RETURN-TO peer `%4s' in connection set. Dropping query.\n",
2635 GNUNET_i2s ((const struct GNUNET_PeerIdentity*) &opt[bits-1]));
2638 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2639 "Failed to find peer `%4s' in connection set. Dropping query.\n",
2640 GNUNET_i2s (other));
2642 GNUNET_STATISTICS_update (stats,
2643 gettext_noop ("# requests dropped due to missing reverse route"),
2646 /* FIXME: try connect? */
2649 /* note that we can really only check load here since otherwise
2650 peers could find out that we are overloaded by not being
2651 disconnected after sending us a malformed query... */
2652 if (GNUNET_YES == test_load_too_high ())
2655 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2656 "Dropping query from `%s', this peer is too busy.\n",
2657 GNUNET_i2s (other));
2659 GNUNET_STATISTICS_update (stats,
2660 gettext_noop ("# requests dropped due to high load"),
2667 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2668 "Received request for `%s' of type %u from peer `%4s' with flags %u\n",
2669 GNUNET_h2s (&gm->query),
2670 (unsigned int) type,
2674 have_ns = (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE));
2675 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
2676 (have_ns ? sizeof(GNUNET_HashCode) : 0));
2678 pr->namespace = (GNUNET_HashCode*) &pr[1];
2680 pr->mingle = ntohl (gm->filter_mutator);
2681 if (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2682 memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
2683 if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
2684 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
2686 pr->anonymity_level = 1;
2687 pr->priority = bound_priority (ntohl (gm->priority), cps);
2688 pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
2689 pr->query = gm->query;
2690 /* decrement ttl (always) */
2691 ttl_decrement = 2 * TTL_DECREMENT +
2692 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2694 if ( (pr->ttl < 0) &&
2695 (((int32_t)(pr->ttl - ttl_decrement)) > 0) )
2698 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2699 "Dropping query from `%s' due to TTL underflow (%d - %u).\n",
2704 GNUNET_STATISTICS_update (stats,
2705 gettext_noop ("# requests dropped due TTL underflow"),
2708 /* integer underflow => drop (should be very rare)! */
2712 pr->ttl -= ttl_decrement;
2713 pr->start_time = GNUNET_TIME_absolute_get ();
2715 /* get bloom filter */
2718 pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
2721 pr->bf_size = bfsize;
2726 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2728 &check_duplicate_request_peer,
2730 if (cdc.have != NULL)
2732 if (cdc.have->start_time.value + cdc.have->ttl >=
2733 pr->start_time.value + pr->ttl)
2735 /* existing request has higher TTL, drop new one! */
2736 cdc.have->priority += pr->priority;
2737 destroy_pending_request (pr);
2739 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2740 "Have existing request with higher TTL, dropping new request.\n",
2741 GNUNET_i2s (other));
2743 GNUNET_STATISTICS_update (stats,
2744 gettext_noop ("# requests dropped due to higher-TTL request"),
2751 /* existing request has lower TTL, drop old one! */
2752 pr->priority += cdc.have->priority;
2753 /* Possible optimization: if we have applicable pending
2754 replies in 'cdc.have', we might want to move those over
2755 (this is a really rare special-case, so it is not clear
2756 that this would be worth it) */
2757 destroy_pending_request (cdc.have);
2758 /* keep processing 'pr'! */
2763 GNUNET_CONTAINER_multihashmap_put (query_request_map,
2766 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2767 GNUNET_CONTAINER_multihashmap_put (peer_request_map,
2770 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2772 pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
2774 pr->start_time.value + pr->ttl);
2776 GNUNET_STATISTICS_update (stats,
2777 gettext_noop ("# P2P searches received"),
2780 GNUNET_STATISTICS_update (stats,
2781 gettext_noop ("# P2P searches active"),
2785 /* calculate change in traffic preference */
2786 preference = (double) pr->priority;
2787 if (preference < QUERY_BANDWIDTH_VALUE)
2788 preference = QUERY_BANDWIDTH_VALUE;
2789 cps->inc_preference += preference;
2791 /* process locally */
2792 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2793 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* to get on-demand as well */
2794 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
2795 (pr->priority + 1));
2796 pr->drq = GNUNET_FS_drq_get (&gm->query,
2798 &process_local_reply,
2803 /* Are multiple results possible? If so, start processing remotely now! */
2806 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2807 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2808 /* only one result, wait for datastore */
2811 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2812 pr->task = GNUNET_SCHEDULER_add_now (sched,
2813 &forward_request_task,
2817 /* make sure we don't track too many requests */
2818 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
2820 pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
2821 destroy_pending_request (pr);
2827 /* **************************** CS GET Handling ************************ */
2831 * Handle START_SEARCH-message (search request from client).
2833 * @param cls closure
2834 * @param client identification of the client
2835 * @param message the actual message
2838 handle_start_search (void *cls,
2839 struct GNUNET_SERVER_Client *client,
2840 const struct GNUNET_MessageHeader *message)
2842 static GNUNET_HashCode all_zeros;
2843 const struct SearchMessage *sm;
2844 struct ClientList *cl;
2845 struct ClientRequestList *crl;
2846 struct PendingRequest *pr;
2851 msize = ntohs (message->size);
2852 if ( (msize < sizeof (struct SearchMessage)) ||
2853 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
2856 GNUNET_SERVER_receive_done (client,
2860 GNUNET_STATISTICS_update (stats,
2861 gettext_noop ("# client searches received"),
2864 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
2865 sm = (const struct SearchMessage*) message;
2866 type = ntohl (sm->type);
2868 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2869 "Received request for `%s' of type %u from local client\n",
2870 GNUNET_h2s (&sm->query),
2871 (unsigned int) type);
2875 case GNUNET_DATASTORE_BLOCKTYPE_ANY:
2876 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2877 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2878 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
2879 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2880 case GNUNET_DATASTORE_BLOCKTYPE_NBLOCK:
2884 GNUNET_SERVER_receive_done (client,
2890 while ( (cl != NULL) &&
2891 (cl->client != client) )
2895 cl = GNUNET_malloc (sizeof (struct ClientList));
2896 cl->client = client;
2897 GNUNET_SERVER_client_keep (client);
2898 cl->next = client_list;
2901 /* detect duplicate KBLOCK requests */
2902 if ( (type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
2903 (type == GNUNET_DATASTORE_BLOCKTYPE_NBLOCK) ||
2904 (type == GNUNET_DATASTORE_BLOCKTYPE_ANY) )
2907 while ( (crl != NULL) &&
2908 ( (0 != memcmp (&crl->req->query,
2910 sizeof (GNUNET_HashCode))) ||
2911 (crl->req->type != type) ) )
2916 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2917 "Have existing request, merging content-seen lists.\n");
2920 /* Duplicate request (used to send long list of
2921 known/blocked results); merge 'pr->replies_seen'
2922 and update bloom filter */
2923 GNUNET_array_grow (pr->replies_seen,
2924 pr->replies_seen_size,
2925 pr->replies_seen_off + sc);
2926 memcpy (&pr->replies_seen[pr->replies_seen_off],
2928 sc * sizeof (GNUNET_HashCode));
2929 pr->replies_seen_off += sc;
2931 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
2932 pr->bf = refresh_bloomfilter (pr->replies_seen_off,
2936 GNUNET_STATISTICS_update (stats,
2937 gettext_noop ("# client searches updated (merged content seen list)"),
2940 GNUNET_SERVER_receive_done (client,
2945 GNUNET_STATISTICS_update (stats,
2946 gettext_noop ("# client searches active"),
2949 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
2950 ((type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ? sizeof(GNUNET_HashCode) : 0));
2951 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
2952 memset (crl, 0, sizeof (struct ClientRequestList));
2953 crl->client_list = cl;
2954 GNUNET_CONTAINER_DLL_insert (cl->rl_head,
2959 pr->client_request_list = crl;
2960 GNUNET_array_grow (pr->replies_seen,
2961 pr->replies_seen_size,
2963 memcpy (pr->replies_seen,
2965 sc * sizeof (GNUNET_HashCode));
2966 pr->replies_seen_off = sc;
2967 pr->anonymity_level = ntohl (sm->anonymity_level);
2968 pr->bf = refresh_bloomfilter (pr->replies_seen_off,
2972 pr->query = sm->query;
2975 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2976 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2977 if (0 != memcmp (&sm->target,
2979 sizeof (GNUNET_HashCode)))
2980 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
2982 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2983 pr->namespace = (GNUNET_HashCode*) &pr[1];
2984 memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
2989 GNUNET_CONTAINER_multihashmap_put (query_request_map,
2992 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2993 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2994 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* get on-demand blocks too! */
2995 pr->drq = GNUNET_FS_drq_get (&sm->query,
2997 &process_local_reply,
2999 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
3004 /* **************************** Startup ************************ */
3008 * List of handlers for P2P messages
3009 * that we care about.
3011 static struct GNUNET_CORE_MessageHandler p2p_handlers[] =
3014 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
3016 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
3022 * List of handlers for the messages understood by this
3025 static struct GNUNET_SERVER_MessageHandler handlers[] = {
3026 {&GNUNET_FS_handle_index_start, NULL,
3027 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
3028 {&GNUNET_FS_handle_index_list_get, NULL,
3029 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
3030 {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
3031 sizeof (struct UnindexMessage) },
3032 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
3039 * Process fs requests.
3041 * @param s scheduler to use
3042 * @param server the initialized server
3043 * @param c configuration to use
3046 main_init (struct GNUNET_SCHEDULER_Handle *s,
3047 struct GNUNET_SERVER_Handle *server,
3048 const struct GNUNET_CONFIGURATION_Handle *c)
3052 stats = GNUNET_STATISTICS_create (sched, "fs", cfg);
3053 connected_peers = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3054 query_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3055 peer_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3056 requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
3057 core = GNUNET_CORE_connect (sched,
3059 GNUNET_TIME_UNIT_FOREVER_REL,
3063 &peer_connect_handler,
3064 &peer_disconnect_handler,
3070 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3071 _("Failed to connect to `%s' service.\n"),
3073 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
3074 connected_peers = NULL;
3075 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
3076 query_request_map = NULL;
3077 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
3078 requests_by_expiration_heap = NULL;
3079 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
3080 peer_request_map = NULL;
3082 return GNUNET_SYSERR;
3084 GNUNET_SERVER_disconnect_notify (server,
3085 &handle_client_disconnect,
3087 GNUNET_SERVER_add_handlers (server, handlers);
3088 GNUNET_SCHEDULER_add_delayed (sched,
3089 GNUNET_TIME_UNIT_FOREVER_REL,
3097 * Process fs requests.
3099 * @param cls closure
3100 * @param sched scheduler to use
3101 * @param server the initialized server
3102 * @param cfg configuration to use
3106 struct GNUNET_SCHEDULER_Handle *sched,
3107 struct GNUNET_SERVER_Handle *server,
3108 const struct GNUNET_CONFIGURATION_Handle *cfg)
3110 if ( (GNUNET_OK != GNUNET_FS_drq_init (sched, cfg)) ||
3111 (GNUNET_OK != GNUNET_FS_indexing_init (sched, cfg)) ||
3112 (GNUNET_OK != main_init (sched, server, cfg)) )
3114 GNUNET_SCHEDULER_shutdown (sched);
3121 * The main function for the fs service.
3123 * @param argc number of arguments from the command line
3124 * @param argv command line arguments
3125 * @return 0 ok, 1 on error
3128 main (int argc, char *const *argv)
3130 return (GNUNET_OK ==
3131 GNUNET_SERVICE_run (argc,
3134 GNUNET_SERVICE_OPTION_NONE,
3135 &run, NULL)) ? 0 : 1;
3138 /* end of gnunet-service-fs.c */